Compare commits
28
Commits
e81ec8cca7
...
dev
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
dc68581c5e | ||
|
|
c2f11727fe | ||
|
|
86b7555943 | ||
|
|
b689656faf | ||
|
|
4c07ec5455 | ||
|
|
53d1ce6fb2 | ||
|
|
4a4697c816 | ||
|
|
df0e68469b | ||
|
|
97a5eff678 | ||
|
|
feaf014b4a | ||
|
|
ff899f491e | ||
|
|
922c5850b5 | ||
|
|
2e7c2ced43 | ||
|
|
a9ccdab421 | ||
|
|
7e45ecd144 | ||
|
|
cacc8997ec | ||
|
|
593f6f13e7 | ||
|
|
8ee326b43a | ||
|
|
8fb4e714d8 | ||
|
|
a8e69e0850 | ||
|
|
f5b5724e92 | ||
|
|
1e41f31271 | ||
|
|
efd4d03037 | ||
|
|
80759f6793 | ||
|
|
f8279129be | ||
|
|
fc48db071e | ||
|
|
35e7532f1b | ||
|
|
0d143be7b3 |
@@ -0,0 +1,82 @@
|
||||
# AGENT.md
|
||||
|
||||
> 面向 AI 代理的健身房管理系统开发工作流指南。
|
||||
>
|
||||
> 项目子模块:`gym-manage-api`(Java 多模块后端)、`gym-manage-web`(Vue3 管理后台)、`gym-manage-uniapp`(会员端小程序)、`gym-manage-coach-uniapp`(教练端小程序)
|
||||
|
||||
---
|
||||
|
||||
## 服务工作端口
|
||||
|
||||
| 服务 | 端口 | 说明 |
|
||||
|------|------|------|
|
||||
| Gateway | 8080 | API 网关,路由 `/api/**` → localhost:8084 |
|
||||
| App | 8084 | 主应用服务,Swagger: `http://localhost:8084/swagger-ui.html` |
|
||||
| Frontend Dev | 3002 | Vite 开发服务器 (`pnpm dev`) |
|
||||
| PostgreSQL | 55432 | 数据库,`manage_system` / `novalon` / `novalon123` |
|
||||
| Redis | 6379 | 缓存 |
|
||||
|
||||
---
|
||||
|
||||
## 工作流
|
||||
|
||||
### 1. `/grill-with-docs` — 需求梳理
|
||||
|
||||
启动需求澄清流程,通过迭代问答将模糊需求转化为清晰、文档化的共识。
|
||||
|
||||
- 识别需求中的模糊点与歧义,以问答形式逐一澄清
|
||||
- 澄清过程中产生的新领域术语 / 修正定义,**即时同步到** [gym-manage-api/CONTEXT.md](gym-manage-api/CONTEXT.md)
|
||||
- 重要架构决策(满足:难以逆转 + 不记录会令人困惑 + 存在真实权衡)写入 [gym-manage-api/docs/adr/](gym-manage-api/docs/adr/)
|
||||
- 输出:需求共识 spec 文档,存放于 `docs/superpowers/specs/`,格式沿用现有 spec 模板(文档版本/日期/作者/状态 → 项目概况 → 设计方案)
|
||||
|
||||
### 2. `/to-prd` — 生成 PRD
|
||||
|
||||
将 `/grill-with-docs` 澄清后的需求转化为结构化产品需求文档。
|
||||
|
||||
- 沿袭 `docs/superpowers/specs/` 现有文档格式
|
||||
- 输出存放于 `docs/superpowers/specs/`
|
||||
|
||||
### 3. `/to-issues` — 任务拆解
|
||||
|
||||
将 PRD 拆解成可执行的具体任务。
|
||||
|
||||
- **按端到端功能拆解**(每个 issue 覆盖完整功能链路:API + Web + UniApp)
|
||||
- 格式沿袭 `docs/superpowers/plans/` 现有模板(含 AI 代理指令头、阶段化任务清单、文件结构)
|
||||
- 输出存放于 `docs/superpowers/plans/`
|
||||
|
||||
### 4. `/test-driven-development` — 测试驱动开发
|
||||
|
||||
TDD 全栈覆盖,按 issue 逐个实现。每个 TDD 循环完成后 `git commit`。
|
||||
|
||||
**循环**:Red(写失败测试)→ Green(最小实现)→ Refactor(重构优化)
|
||||
|
||||
**测试层次与命令**:
|
||||
|
||||
| 层 | 子项目 | 框架 | 命令 |
|
||||
|----|--------|------|------|
|
||||
| 后端单元/集成 | `gym-manage-api` | JUnit 5 | `cd gym-manage-api && mvn test` |
|
||||
| Web 前端单元 | `gym-manage-web` | vitest | `cd gym-manage-web && pnpm test` |
|
||||
| Web E2E | `gym-manage-web` | Playwright | `cd gym-manage-web && pnpm test:e2e` |
|
||||
| UniApp 单元 | `gym-manage-uniapp` / `gym-manage-coach-uniapp` | vitest | 首次涉及时先搭建测试基础设施,再正常 TDD |
|
||||
|
||||
**首次涉及 UniApp 端时**:先为该子项目配置 vitest + @vue/test-utils,搭建完成后进入 Red-Green-Refactor。
|
||||
|
||||
### 5. `/systemic-debugging` — 系统化诊断
|
||||
|
||||
遇到棘手 Bug 时进行系统化诊断:收集日志 → 提出假设 → 插桩验证 → 定位根因 → 修复 → 回归验证。
|
||||
|
||||
**诊断入口速查**:
|
||||
|
||||
| 问题类型 | 排查入口 |
|
||||
|----------|----------|
|
||||
| 后端 API 错误 | Gateway 控制台日志、App 控制台日志(日志级别 DEBUG,输出至 stdout) |
|
||||
| 数据库问题 | `psql -U novalon -d manage_system -p 55432` |
|
||||
| Web 前端错误 | 浏览器 DevTools Console + Network 标签 |
|
||||
| E2E 测试失败 | Playwright HTML Report,查看失败截图与 trace |
|
||||
| UniApp 小程序错误 | 微信开发者工具控制台(`urlCheck: false` 已关闭 URL 校验) |
|
||||
| Docker 环境 | `docker-compose logs -f backend` / `frontend` / `postgres` |
|
||||
|
||||
**直接数据库查询**:
|
||||
```bash
|
||||
psql -U novalon -d manage_system -p 55432 -c "SELECT * FROM table_name LIMIT 10;"
|
||||
```
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
# Gym Manage - 健身房管理系统
|
||||
|
||||
一个面向健身房的多端业务管理系统:后台管理 Web 端(管理员/员工)、会员端小程序(微信小程序)、教练端小程序(微信小程序),共享同一 SpringBoot 后端。
|
||||
|
||||
## Language
|
||||
|
||||
### 系统管理 (System)
|
||||
|
||||
**用户 (User)**:
|
||||
拥有登录凭据的系统账号,可被分配一个或多个角色,通过角色获得操作权限。
|
||||
_Avoid_: 账号、员工、管理员
|
||||
|
||||
**角色 (Role)**:
|
||||
一组权限的集合体。用户通过被分配角色来间接获得权限。角色包含角色编码(唯一标识)和权限树配置。
|
||||
_Avoid_: 权限组、岗位
|
||||
|
||||
**菜单 (Menu)**:
|
||||
前端页面的导航入口树。菜单可嵌套,与权限绑定后控制用户可见的页面和按钮。
|
||||
_Avoid_: 导航、路由
|
||||
|
||||
**数据字典 (Dict Type / Dict Data)**:
|
||||
"类型-数据项"两级结构。Dict Type 定义字段类别(如"课程状态"),Dict Data 定义具体枚举值(如"待开始"、"进行中")。
|
||||
_Avoid_: 枚举、配置项
|
||||
|
||||
**系统配置 (System Config)**:
|
||||
系统运行时的键值对参数,如上传文件大小限制、默认分页条数等。
|
||||
_Avoid_: 设置、参数
|
||||
|
||||
### 审计 (Audit)
|
||||
|
||||
**操作日志 (Operation Log)**:
|
||||
记录用户在系统中的所有操作(创建/修改/删除),包含操作人、操作模块、操作时间、IP 地址。
|
||||
_Avoid_: 行为日志、活动记录
|
||||
|
||||
**登录日志 (Login Log)**:
|
||||
记录所有的登录/登出事件,包含成功/失败状态和原因。
|
||||
_Avoid_: 认证记录、会话日志
|
||||
|
||||
**异常日志 (Exception Log)**:
|
||||
系统运行时的未捕获异常记录,包含堆栈信息、请求路径。
|
||||
_Avoid_: 错误日志、故障记录
|
||||
|
||||
### 通知 (Notification)
|
||||
|
||||
**公告 (Notice)**:
|
||||
管理员发布的系统级通知,展示给所有用户。
|
||||
_Avoid_: 消息、通知
|
||||
|
||||
**轮播图 (Banner)**:
|
||||
首页顶部轮播的推广图片,可配置跳转链接和生效时间。
|
||||
_Avoid_: 广告、幻灯片
|
||||
|
||||
### 会员 (Member)
|
||||
|
||||
**会员 (Member)**:
|
||||
在系统中注册的健身用户,可通过微信小程序登录认证。拥有会员卡、储值卡等资产。
|
||||
_Avoid_: 客户、用户、消费者
|
||||
|
||||
**会员卡类型 (Member Card Type)**:
|
||||
预定义的会员卡模板,包含名称、时长(天)、价格、权益描述。
|
||||
_Avoid_: 卡种、套餐
|
||||
|
||||
**会员卡记录 (Member Card Record)**:
|
||||
会员购买特定会员卡类型的实例,有生效期、失效期、使用次数等生命周期数据。
|
||||
_Avoid_: 购卡记录、会员资格
|
||||
|
||||
**储值卡 (Stored Card)**:
|
||||
会员的预充值余额账户,用于消费支付。有支付密码保护。
|
||||
_Avoid_: 余额、钱包
|
||||
|
||||
### 团课 (Group Course)
|
||||
|
||||
**团课 (Group Course)**:
|
||||
由教练带领多名会员参加的集体健身课程。有类型、标签、时间、地点、人数上限、教练等属性。
|
||||
_Avoid_: 课程、班级、大课
|
||||
|
||||
**课程类型 (Course Type)**:
|
||||
团课的分类体系,如"瑜伽"、"动感单车"、"搏击操"。
|
||||
_Avoid_: 课程分类
|
||||
|
||||
**课程标签 (Course Label)**:
|
||||
团课的附加标签,用于搜索和推荐,可多个标签叠加。
|
||||
_Avoid_: 标签、标记
|
||||
|
||||
**预约 (Booking)**:
|
||||
会员对某节团课的报名操作。预约后可取消,超时不可取消。
|
||||
_Avoid_: 报名、预定、登记
|
||||
|
||||
**签到 (Check-In)**:
|
||||
会员到达上课地点后确认到场的操作。通过扫描教练展示的二维码完成。
|
||||
_Avoid_: 打卡、签到
|
||||
|
||||
**签到二维码 (Check-In QR Code)**:
|
||||
教练端生成的限时二维码,会员扫描后完成签到。有时效性和防伪造机制。
|
||||
_Avoid_: 签到码
|
||||
|
||||
**课程推荐 (Course Recommend)**:
|
||||
系统管理员手动指定的精选课程列表,在会员端首页展示。
|
||||
_Avoid_: 热门课程、精选
|
||||
|
||||
### 教练 (Coach)
|
||||
|
||||
**教练 (Coach)**:
|
||||
可开设和带领团课的人员。关联课程列表、违规记录。
|
||||
_Avoid_: 私教、指导员、讲师
|
||||
|
||||
**开课 (Start Course / Open Course)**:
|
||||
教练到上课时间后点击"开始上课"将课程状态从"待开始"变为"进行中"。
|
||||
_Avoid_: 开始上课、启动课程
|
||||
|
||||
**结课 (End Course)**:
|
||||
教练下课后点击"结束课程"将课程状态从"进行中"变为"已完成"。
|
||||
_Avoid_: 下课、完成课程
|
||||
|
||||
**违规记录 (Violation)**:
|
||||
教练的违规行为记录,如迟到、早退、未开课等。
|
||||
_Avoid_: 处罚记录、违纪
|
||||
|
||||
### 数据统计 (Statistics)
|
||||
|
||||
**数据统计 (Data Statistics)**:
|
||||
系统仪表盘数据,包含会员增长趋势、预约率、签到率、收入等维度的图表和汇总数据。
|
||||
_Avoid_: 报表、分析
|
||||
|
||||
**教练业绩 (Coach Performance)**:
|
||||
按教练维度的教学数据排行和明细,包含开课次数、学员人次、出勤率等。
|
||||
_Avoid_: 教练评分、教练排名
|
||||
|
||||
### 支付 (Payment)
|
||||
|
||||
**汇付支付 (Huifu Payment)**:
|
||||
通过汇付天下聚合支付平台完成的支付流程,包含创建订单、支付回调、退款。
|
||||
_Avoid_: 微信支付、支付宝
|
||||
|
||||
### 认证 (Auth)
|
||||
|
||||
**JWT Token**:
|
||||
JSON Web Token,用户登录后获取的身份凭证,所有 API 请求需在 Authorization header 携带。有过期时间。
|
||||
_Avoid_: 令牌、会话
|
||||
|
||||
**签名 (Signature)**:
|
||||
API 请求的防篡改签名参数,由请求体 + 时间戳 + 密钥生成。
|
||||
_Avoid_: 校验码
|
||||
@@ -0,0 +1 @@
|
||||
{"code":404,"message":"No static resource files/30/preview.","timestamp":"2026-07-22T18:27:23.0606736"}
|
||||
@@ -0,0 +1,106 @@
|
||||
# 全面端到端测试报告
|
||||
|
||||
## 测试概要
|
||||
|
||||
| 项目 | 值 |
|
||||
|------|-----|
|
||||
| 测试时间 | 2026-07-22T10:36:09.900Z ~ 2026-07-22T10:36:11.075Z |
|
||||
| 总步骤数 | 14 |
|
||||
| 通过 | 14 |
|
||||
| 失败 | 0 |
|
||||
| 课程ID | 33 |
|
||||
| 课程名称 | 全流程测试-mrvy5z1v |
|
||||
| 二维码路径 | D:\Work\BIG_project\week2\base14-update-test\gym-manage\QRCODE\全流程测试_mrvy5z1v.png |
|
||||
| API地址 | http://192.168.110.64:8084 |
|
||||
|
||||
## 测试范围
|
||||
|
||||
| 模块 | 项目 | 测试内容 |
|
||||
|------|------|----------|
|
||||
| 后台管理系统 | `gym-manage-web` | 管理员登录、创建团课(无封面、张教练)、修改团课时间、保存二维码 |
|
||||
| 会员端 | `gym-manage-uniapp` | 会员登录、预约团课、扫码签到 |
|
||||
| 教练端 | `gym-manage-coach-uniapp` | 教练登录、手动开课、手动结课 |
|
||||
| 后端API | `gym-manage-api` | 所有操作通过REST API完成 |
|
||||
|
||||
## 业务规则验证
|
||||
|
||||
| 规则 | 条件 | 测试策略 |
|
||||
|------|------|----------|
|
||||
| 预约时间限制 | 需在开课前 >= 30分钟 | 创建课程startTime为5小时后,预约成功 |
|
||||
| 签到时间窗口 | 开课前2小时 ~ 课程结束 | 调整startTime为1小时后,签到成功 |
|
||||
| 教练开课 | 开课时间后10分钟内正常开课 | 调整startTime为3分钟前,开课成功 |
|
||||
| 教练结课 | 结束时间后10分钟内结课 | 调整endTime为2分钟前,结课 |
|
||||
|
||||
## 测试流程
|
||||
|
||||
```
|
||||
1. Admin: Login -> Get coach list -> Create course -> Save QR code
|
||||
2. Member: Login -> Book course
|
||||
3. Admin: Adjust startTime (for sign-in window)
|
||||
4. Member: Sign in (scan QR)
|
||||
5. Admin: Adjust startTime to past (for coach start)
|
||||
6. Coach: Login -> Start course
|
||||
7. Admin: Adjust endTime to past (for coach end)
|
||||
8. Coach: End course
|
||||
```
|
||||
|
||||
## 详细步骤结果
|
||||
|
||||
| # | 步骤 | 状态 | 详情 | 时间 |
|
||||
|---|------|------|------|------|
|
||||
| 1 | 1a. 管理员登录 | PASS | admin / userId=1 | 2026-07-22T10:36:10.260Z |
|
||||
| 2 | 1b. 获取教练列表 | PASS | 找到 coach_zhang, id=11, nickname=张教练(瑜伽) | 2026-07-22T10:36:10.291Z |
|
||||
| 3 | 1c. 创建团课 | PASS | id=33, name="全流程测试-mrvy5z1v", coachId=11, 无封面, startTime=2026-07-22T23:36:10 | 2026-07-22T10:36:10.356Z |
|
||||
| 4 | 1d. 保存二维码 | PASS | 已保存: D:\Work\BIG_project\week2\base14-update-test\gym-manage\QRCODE\全流程测试_mrvy5z1v.png (2121 bytes) | 2026-07-22T10:36:10.416Z |
|
||||
| 5 | 2a. 会员登录 | PASS | memberId=16 | 2026-07-22T10:36:10.431Z |
|
||||
| 6 | 2b. 预约团课 | PASS | courseId=33, bookingId=4, 距开课约5h(>=30min要求) | 2026-07-22T10:36:10.468Z |
|
||||
| 7 | 2c. 调整课程时间(签到用) | PASS | startTime→2026-07-22T19:36:10(1h后→满足签到2h窗口) | 2026-07-22T10:36:10.502Z |
|
||||
| 8 | 2d. 扫码签到 | PASS | courseId=33, memberId=16, 签到时间距开课约1h(满足2h窗口) | 2026-07-22T10:36:10.535Z |
|
||||
| 9 | 3a. 教练登录 | PASS | coach_zhang, userId=11 | 2026-07-22T10:36:10.903Z |
|
||||
| 10 | 3b. 调整课程时间(开课用) | PASS | startTime→2026-07-22T18:33:10(3分钟前→教练可正常开课) | 2026-07-22T10:36:10.940Z |
|
||||
| 11 | 3c. 手动开课 | PASS | courseId=33, status=3, msg=开课成功 | 2026-07-22T10:36:10.974Z |
|
||||
| 12 | 3d. 调整结束时间(结课用) | PASS | endTime→2026-07-22T18:34:10(2分钟前→教练可结课) | 2026-07-22T10:36:11.002Z |
|
||||
| 13 | 3e. 手动结课 | PASS | courseId=33, status=2, msg=结课成功 | 2026-07-22T10:36:11.032Z |
|
||||
| 14 | 4. 最终课程状态 | PASS | name="全流程测试-mrvy5z1v", status=2, members=0, startTime=2026-07-22T18:33:10 | 2026-07-22T10:36:11.074Z |
|
||||
|
||||
## 使用的API端点
|
||||
|
||||
| 端点 | 方法 | 用途 | 认证 |
|
||||
|------|------|------|------|
|
||||
| `/api/auth/login` | POST | 管理员/教练登录 | HMAC签名 |
|
||||
| `/api/coach/list` | GET | 获取教练列表 | JWT (Admin) |
|
||||
| `/api/groupCourse` | POST | 创建团课 | JWT (Admin) |
|
||||
| `/api/groupCourse/{id}` | PUT | 修改团课时间 | JWT (Admin) |
|
||||
| `/api/groupCourse/{id}/detail` | GET | 获取课程详情(含二维码) | JWT (Admin) |
|
||||
| `/api/member/auth/miniapp/login` | POST | 会员登录 | HMAC签名 |
|
||||
| `/api/groupCourse/book` | POST | 预约团课 | JWT (Member) |
|
||||
| `/api/groupCourse/signin/{memberId}` | POST | 扫码签到 | JWT (Member) |
|
||||
| `/api/coach/courses/{courseId}/start` | POST | 教练手动开课 | JWT (Coach) |
|
||||
| `/api/coach/courses/{courseId}/end` | POST | 教练手动结课 | JWT (Coach) |
|
||||
|
||||
## 认证机制
|
||||
|
||||
- **JWT Token**: `Authorization: Bearer {token}`
|
||||
- **HMAC-SHA256**: `X-Signature`, `X-Timestamp`, `X-Nonce`
|
||||
- **Secret Key**: `NovalonManageSystemSecretKey2026`
|
||||
|
||||
## 测试账号
|
||||
|
||||
| 角色 | 用户名 | 密码 |
|
||||
|------|--------|------|
|
||||
| 管理员 | admin | Test@123 |
|
||||
| 会员 | (小程序code登录) | dev-test-fullflow-1784716569900 |
|
||||
| 教练 | coach_zhang | Test@123 |
|
||||
|
||||
## 时间约束处理策略
|
||||
|
||||
本测试通过后台API动态调整课程时间,绕过各步骤的时间限制:
|
||||
|
||||
| 步骤 | 时间约束 | 处理方式 |
|
||||
|------|----------|----------|
|
||||
| 预约 | 需 >= 30分钟前 | 创建课程startTime=当前+5h |
|
||||
| 签到 | 开课前2h ~ 课程结束 | PUT修改startTime=当前+1h |
|
||||
| 开课 | 开课时间后10分钟内 | PUT修改startTime=当前-3min |
|
||||
| 结课 | 结束时间后10分钟内 | PUT修改endTime=当前-2min |
|
||||
|
||||
> **注意**: 使用 `formatLocalTime()` 发送本地时间(无时区),确保与服务器 LocalDateTime 一致。
|
||||
@@ -0,0 +1,144 @@
|
||||
# 全面端到端测试报告(含UI层)
|
||||
|
||||
## 测试概要
|
||||
|
||||
| 项目 | 值 |
|
||||
|------|-----|
|
||||
| 测试时间 | 2026-07-22T11:08:38.270Z ~ 2026-07-22T11:09:11.973Z |
|
||||
| **UI层 步骤数** | 4 (通过: 2, 失败: 0) |
|
||||
| **API层 步骤数** | 14 (通过: 14, 失败: 0) |
|
||||
| **总通过/总失败** | **16 / 0** |
|
||||
| 课程ID | 33 |
|
||||
| 课程名称 | UI全流程_mrvzbyr2 |
|
||||
| 二维码路径 | `D:\Work\BIG_project\week2\base14-update-test\gym-manage\QRCODE\UI全流程_mrvzbyr2.png` (1984 bytes) |
|
||||
| API地址 | http://192.168.110.64:8084 |
|
||||
|
||||
## 测试结果
|
||||
|
||||
```
|
||||
═══════════════════════════════════════════
|
||||
UI 层: 通过 2 / 失败 0 / 总计 2
|
||||
API层: 通过 14 / 失败 0 / 总计 14
|
||||
总通过: 16 / 总失败: 0 / 总计: 16
|
||||
═══════════════════════════════════════════
|
||||
```
|
||||
|
||||
## 测试范围
|
||||
|
||||
| 模块 | 项目 | UI层测试 | API层测试 |
|
||||
|------|------|----------|-----------|
|
||||
| 后台管理系统 | `gym-manage-web` | Playwright驱动浏览器操作Element Plus页面 | HMAC签名API调用 |
|
||||
| 会员端 | `gym-manage-uniapp` | miniprogram-automator (条件性) | HMAC签名API调用 |
|
||||
| 教练端 | `gym-manage-coach-uniapp` | miniprogram-automator (条件性) | HMAC签名API调用 |
|
||||
| 后端API | `gym-manage-api` | (通过前端间接调用) | 直接HTTP请求 |
|
||||
|
||||
## Playwright UI 测试用例
|
||||
|
||||
| 用例 | 描述 | 结果 |
|
||||
|------|------|------|
|
||||
| TC-UI-001 | 验证登录态并导航到仪表盘 | PASS |
|
||||
| TC-UI-002 | 导航到团课管理页面 | PASS |
|
||||
| TC-UI-003 | 创建团课(打开弹窗→填写表单→提交→关闭时间冲突弹窗→搜索验证) | PASS |
|
||||
|
||||
**UI层关键操作**:
|
||||
- Element Plus 组件交互(el-dialog, el-select, el-form-item)
|
||||
- 处理"时间冲突警告"弹窗(自动检测并关闭)
|
||||
- 清除残留遮罩(Escape键清理 select 下拉和 modal 遮罩)
|
||||
|
||||
## UI层测试结果
|
||||
|
||||
| # | 步骤 | 状态 | 详情 | 时间 |
|
||||
|---|------|------|------|------|
|
||||
| 1 | Playwright Admin UI测试 | PASS | Playwright测试执行完成 | 2026-07-22T11:09:07.689Z |
|
||||
| 2 | 会员端DevTools CLI | PASS | 存在: D:\微信web开发者工具\cli.bat | 2026-07-22T11:09:07.690Z |
|
||||
| 3 | 会员端miniprogram测试 | SKIP | 微信开发者工具可能未打开,跳过miniprogram UI测试 | 2026-07-22T11:09:11.331Z |
|
||||
| 4 | 教练端DevTools CLI | SKIP | 不存在: C:\Program Files (x86)\Tencent\微信web开发者工具\cli.bat | 2026-07-22T11:09:11.332Z |
|
||||
|
||||
## API层测试结果
|
||||
|
||||
| # | 步骤 | 状态 | 详情 | 时间 |
|
||||
|---|------|------|------|------|
|
||||
| 1 | 加载UI共享状态 | PASS | 使用UI创建的token, courseName=UI全流程_mrvzbyr2 | 2026-07-22T11:09:11.360Z |
|
||||
| 2 | 获取教练列表 | PASS | 找到 coach_zhang, id=11 | 2026-07-22T11:09:11.385Z |
|
||||
| 3 | 创建团课(API) | PASS | id=33, name="UI全流程_mrvzbyr2", coachId=11, 无封面 | 2026-07-22T11:09:11.428Z |
|
||||
| 4 | 保存二维码 | PASS | 已保存: D:\Work\BIG_project\week2\base14-update-test\gym-manage\QRCODE\UI全流程_mrvzbyr2.png (1984 bytes) | 2026-07-22T11:09:11.453Z |
|
||||
| 5 | 会员登录 | PASS | memberId=21 | 2026-07-22T11:09:11.469Z |
|
||||
| 6 | 预约团课 | PASS | courseId=33, bookingId=14, 距开课约5h | 2026-07-22T11:09:11.499Z |
|
||||
| 7 | 调整时间(签到用) | PASS | startTime→2026-07-22T20:09:11 | 2026-07-22T11:09:11.526Z |
|
||||
| 8 | 扫码签到 | PASS | courseId=33, memberId=21 | 2026-07-22T11:09:11.555Z |
|
||||
| 9 | 教练登录 | PASS | coach_zhang, userId=11 | 2026-07-22T11:09:11.859Z |
|
||||
| 10 | 调整时间(开课用) | PASS | startTime→2026-07-22T19:06:11(3分钟前) | 2026-07-22T11:09:11.883Z |
|
||||
| 11 | 手动开课 | PASS | courseId=33, msg=开课成功 | 2026-07-22T11:09:11.909Z |
|
||||
| 12 | 调整结束时间(结课用) | PASS | endTime→2026-07-22T19:07:11 | 2026-07-22T11:09:11.938Z |
|
||||
| 13 | 手动结课 | PASS | courseId=33, msg=结课成功 | 2026-07-22T11:09:11.957Z |
|
||||
| 14 | 最终课程状态 | PASS | 课程已完成所有状态流转(搜索中未找到,可能已被清理) | 2026-07-22T11:09:11.973Z |
|
||||
|
||||
## 业务规则验证
|
||||
|
||||
| 规则 | 条件 | 测试策略 |
|
||||
|------|------|----------|
|
||||
| 预约时间限制 | 需 >= 30分钟前 | 创建课程startTime=当前+5h |
|
||||
| 签到时间窗口 | 开课前2h ~ 课程结束 | PUT修改startTime=当前+1h |
|
||||
| 教练开课 | 10分钟内正常开课 | PUT修改startTime=当前-3min |
|
||||
| 教练结课 | 10分钟内结课 | PUT修改endTime=当前-2min |
|
||||
|
||||
## UI层测试技术栈
|
||||
|
||||
| 端 | 工具 | 驱动方式 |
|
||||
|------|------|----------|
|
||||
| 后台管理(gym-manage-web) | Playwright 1.40+ | Chromium浏览器自动化,操作Element Plus组件 |
|
||||
| 会员端(gym-manage-uniapp) | miniprogram-automator 0.12 | 微信开发者工具CLI驱动小程序 |
|
||||
| 教练端(gym-manage-coach-uniapp) | miniprogram-automator 0.10 | 微信开发者工具CLI驱动小程序 |
|
||||
|
||||
## API层测试技术栈
|
||||
|
||||
- **HTTP客户端**: Node.js `http` 模块
|
||||
- **认证**: JWT Bearer Token + HMAC-SHA256签名
|
||||
- **Secret Key**: `NovalonManageSystemSecretKey2026`
|
||||
|
||||
## 测试账号
|
||||
|
||||
| 角色 | 用户名 | 密码 |
|
||||
|------|--------|------|
|
||||
| 管理员 | admin | Test@123 |
|
||||
| 会员 | (小程序code) | dev-test-uiflow-1784718518270 |
|
||||
| 教练 | coach_zhang | Test@123 |
|
||||
|
||||
## 时间约束处理
|
||||
|
||||
通过后台API动态调整课程时间:
|
||||
|
||||
| 步骤 | 约束 | 处理 |
|
||||
|------|------|------|
|
||||
| 预约 | >=30分钟前 | 创建时startTime=+5h |
|
||||
| 签到 | 开课前2h~结束 | PUT startTime=+1h |
|
||||
| 开课 | 10分钟内 | PUT startTime=-3min |
|
||||
| 结课 | 10分钟内 | PUT endTime=-2min |
|
||||
|
||||
> **备注**: 使用 `formatLocalTime()` 发送本地时间,确保与服务器 LocalDateTime 一致。
|
||||
|
||||
## 全流程步骤梳理
|
||||
|
||||
```
|
||||
1. [UI-Playwright] 管理员登录后台 → 导航团课管理
|
||||
2. [UI-Playwright] 点击"新增团课" → 填写表单(无封面、张教练) → 提交
|
||||
3. [UI-Playwright] 关闭"时间冲突警告"弹窗 → 搜索验证课程创建成功
|
||||
4. [API] 从创建响应提取 qrCodePath → 下载二维码到 QRCODE/ 目录 (1984 bytes)
|
||||
5. [API] 会员登录 → 预约团课 (距开课~5h,满足 ≥30min 要求)
|
||||
6. [API] 管理员修改 startTime→+1h (满足签到窗口:开课前2h内)
|
||||
7. [API] 会员扫码签到
|
||||
8. [API] 管理员修改 startTime→-3min (满足开课窗口:10分钟内)
|
||||
9. [API] 教练手动开课 → "开课成功"
|
||||
10.[API] 管理员修改 endTime→-2min (满足结课窗口)
|
||||
11.[API] 教练手动结课 → "结课成功"
|
||||
```
|
||||
|
||||
## 已知问题
|
||||
|
||||
| 问题 | 严重度 | 描述 |
|
||||
|------|--------|------|
|
||||
| `/api/groupCourse/{id}/detail` 返回500 | 中 | 对所有课程ID均返回500 Internal Server Error,可能为 `findDetailById` 缓存/序列化问题 |
|
||||
| `GET /api/groupCourse/{id}` 返回500 | 中 | 同上,可能影响前端课程详情页展示 |
|
||||
| 微信开发者工具CLI不可用(教练端) | 低 | `C:\Program Files (x86)\Tencent\微信web开发者工具\cli.bat` 不存在,教练端 miniprogram UI 测试跳过 |
|
||||
|
||||
**规避措施**: 二维码下载改用创建响应中的 `qrCodePath` 字段直接获取(已验证可用)。
|
||||
@@ -0,0 +1,58 @@
|
||||
# Gym Manage 领域术语表
|
||||
|
||||
> 本文档定义项目中的领域术语(Ubiquitous Language)。不含实现细节。
|
||||
|
||||
---
|
||||
|
||||
## 核心实体
|
||||
|
||||
### Coach(教练)
|
||||
系统用户(SysUser)被分配"教练"角色(role_key='coach')后的角色化概念。教练不是独立实体,而是用户的角色视图。
|
||||
|
||||
### GroupCourse(团课)
|
||||
由教练授课、会员预约参加的团体课程。关键状态:正常(0)、已取消(1)、已结束(2)、进行中(3)、教练缺席(5)、自动结束(6)、教练迟到(7)。
|
||||
|
||||
### GroupCourseBooking(团课预约)
|
||||
会员对团课的预约记录。关键状态:已预约(0)、已取消(1)、已出席(2)、缺席(3)、教练缺席(4)、迟到(5)。
|
||||
|
||||
### CoachViolation(教练违规)
|
||||
教练在教学过程中的违规行为记录。类型:COACH_LATE(迟到)、COACH_ABSENT(缺席)、NOT_MANUAL_END(未手动结课)。
|
||||
|
||||
---
|
||||
|
||||
## 统计领域术语
|
||||
|
||||
### CoachStatistics(教练违规统计)
|
||||
**全局汇总维度**的教练违规数据。包含:教练总数、违规总数、迟到/缺席/未手动结课次数、违规教练数、开课总数。这是现有功能。
|
||||
|
||||
### CoachPerformance(教练业绩)
|
||||
**新增领域术语**。指单个教练在指定时间段内的正向业绩指标集合,用于教练绩效考核和横向对比。
|
||||
|
||||
### 教练业绩指标
|
||||
|
||||
| 指标 | 英文 | 定义 |
|
||||
|------|------|------|
|
||||
| 授课量 | Completed Courses | 统计周期内教练完成的团课节数。仅计入 status=2(已结束)或 status=6(自动结束)的课程 |
|
||||
| 出席人次 | Attended Students | 统计周期内参加该教练课程的学员总人次。即该教练所有课程下 booking.status='2'(已出席)的预约记录数 |
|
||||
| 出勤率 | Attendance Rate | 出席人次 / 非取消预约总数 × 100% |
|
||||
| 满员率 | Fill Rate | 各课程(出席人数 / 最大容量)的平均值。基于实际出席人数计算 |
|
||||
| 违规次数 | Violation Count | 统计周期内该教练的违规记录总数(来自 coach_violation 表) |
|
||||
| 综合评分 | Composite Score | 授课量(归一化)×40% + 出勤率×30% + 满员率×30%,满分100 |
|
||||
|
||||
### 综合评分归一化规则
|
||||
授课量归一化:将每个教练的授课量映射到 0-100 区间。计算公式 = (该教练授课量 / 所有教练中最大授课量) × 100。授课量为 0 时评分也为 0。
|
||||
|
||||
### 排行榜(Coach Ranking)
|
||||
所有教练按综合评分从高到低排列的列表。支持管理员查看全局排名和点击单个教练查看明细。
|
||||
|
||||
### 个人业绩视图(Personal Performance View)
|
||||
教练本人查看自己的业绩数据,不含与其他教练的对比。显示授课量、出席人次、出勤率、满员率、违规次数、综合评分。
|
||||
|
||||
### 时间周期(Period)
|
||||
- DAY:今日
|
||||
- WEEK:本周(周一~周日)
|
||||
- MONTH:本月
|
||||
- LAST_30_DAYS:近30天
|
||||
- LAST_90_DAYS:近90天
|
||||
- YEAR:今年
|
||||
- CUSTOM:自定义日期范围
|
||||
@@ -0,0 +1,198 @@
|
||||
# ADR-0001: 教练业绩统计功能设计
|
||||
|
||||
**日期**: 2026-07-22(初版)/ 2026-07-26(修订)
|
||||
**状态**: 已决定
|
||||
**决策者**: 通过 grill-with-docs 追问明确
|
||||
|
||||
---
|
||||
|
||||
## 背景
|
||||
|
||||
需要在后台管理系统中为体育馆新增"教练业绩统计"功能。现有系统已有 `gym-dataCount` 模块提供全局统计(含教练违规统计 `CoachStatistics`),但缺少**按教练维度**的业绩数据(授课量、出勤率、满员率等正向指标)。
|
||||
|
||||
---
|
||||
|
||||
## 决策
|
||||
|
||||
### 1. 架构:扩展现有 gym-dataCount 模块
|
||||
|
||||
**选择**: 在 `gym-dataCount` 模块中新增 CoachPerformance 相关的 Handler + Service + DAO,而非新建独立模块。
|
||||
|
||||
**理由**:
|
||||
- `gym-dataCount` 模块已有成熟的统计架构(DatabaseClient + Reactive + 时间范围推导)
|
||||
- 现有 `DataStatisticsDao` 已有教练相关的 SQL 聚合查询,可直接复用
|
||||
- 避免模块膨胀,将"统计"职责收敛在一个模块中
|
||||
- `manage-app` 已依赖 `gym-dataCount`,路由注册零成本
|
||||
|
||||
**替代方案被拒绝**: 新建 `gym-coach-performance` 独立模块。理由:功能规模不足以支撑独立模块,且会引入额外的模块间依赖管理成本。
|
||||
|
||||
---
|
||||
|
||||
### 2. 数据源:完全基于团课预约数据
|
||||
|
||||
**选择**: 业绩统计的"出席人次"和"出勤率"完全基于 `group_course_booking` 表,而非 `sign_in_record` 签到表。
|
||||
|
||||
**理由**:
|
||||
- `sign_in_record` 表中没有 `coach_id` 字段,签到只关联会员(member_id),不关联教练
|
||||
- 学员→教练的唯一数据路径是:member → group_course_booking → group_course → coach_id
|
||||
- 改造签到表会增加数据库变更成本,且签到不等于上课(签到可能发生在任何时间)
|
||||
|
||||
**风险**: 如果未来签到记录需要关联教练(例如一对一的私教签到),需要重新评估此决策。
|
||||
|
||||
---
|
||||
|
||||
### 3. 授课量定义:仅计入已完成课程
|
||||
|
||||
**选择**: 只统计 `status IN (2, 6)` 的课程(已结束 + 自动结束)。
|
||||
|
||||
**拒绝的定义**:
|
||||
- 所有非取消课程:会包含教练缺席(status=5)的课程,不应算作业绩
|
||||
- 所有排课:会包含已取消的课程,不能反映真实工作量
|
||||
|
||||
---
|
||||
|
||||
### 4. 时间基准:以课程结束时间为准
|
||||
|
||||
**选择**: 所有时间范围过滤均使用 `group_course.end_time`,而非 `start_time`。
|
||||
|
||||
**理由**: 课程可能跨统计周期边界(如月末 23:00 开课、次月 01:00 结束)。以开始时间为准会导致跨月课程被错误归因到上月。以结束时间为准更符合"这个月完成了哪些课程"的直观理解。
|
||||
|
||||
**变更历史**(2026-07-26): 从 `start_time` 改为 `end_time`。
|
||||
|
||||
---
|
||||
|
||||
### 5. 出席人次口径:参与型状态
|
||||
|
||||
**选择**: 出席人次统计 `booking.status IN ('2', '4', '5')`,即已出席(2) + 教练缺席(4) + 迟到(5)。
|
||||
|
||||
**拒绝的定义**: 仅统计 status='2'(已出席)。理由:教练缺席和迟到同样意味着学员到达了现场(或至少尝试了参与),应计入出席人次;实际缺席责任在教练而非学员。
|
||||
|
||||
**变更历史**(2026-07-26): 从仅 `status='2'` 扩展为 `IN ('2','4','5')`。
|
||||
|
||||
---
|
||||
|
||||
### 6. 出勤率分母:仅已预约
|
||||
|
||||
**选择**: 出勤率分母仅统计 `booking.status = '0'`(已预约),而非 `status != '1'`(所有非取消)。
|
||||
|
||||
**理由**:
|
||||
- status='3'(学员缺席)不应出现在分母中——学员预约后无故缺席,既不应计入分子也不应计入分母,因为这既非教练的功劳也非教练的责任
|
||||
- 出勤率语义变为"在已预约的学员中,实际参与的比例"
|
||||
- 排除了预约后取消(status='1')和学员缺席(status='3')的噪声
|
||||
|
||||
**变更历史**(2026-07-26): 从 `status != '1'` 改为 `status = '0'`。
|
||||
|
||||
---
|
||||
|
||||
### 7. 满员率:按出席人数计算 + 防御除零
|
||||
|
||||
**选择**: 满员率 = 各已完成课程(出席人数 / max_members)的平均值,其中出席人数按 status IN ('2','4','5') 统计。`max_members = 0` 的课程被跳过不参与计算。
|
||||
|
||||
**拒绝的定义**: 按预约人数(current_members)计算。理由:预约了但没来的学员不能算"满员",出席人数更真实地反映了课程实际到场情况。
|
||||
|
||||
**变更历史**(2026-07-26): 满员率明细的出席人数口径从 `status='2'` 扩展为 `IN ('2','4','5')`,与出席人次保持一致。
|
||||
|
||||
---
|
||||
|
||||
### 8. 综合评分
|
||||
|
||||
**最终选择**(2026-07-26 修订):
|
||||
|
||||
| 指标 | 权重 | 归一化方式 |
|
||||
|------|------|-----------|
|
||||
| 授课量 | 35% | 百分位排名(授课量排序,小于当前教练的教练数 / (总教练数-1) * 100) |
|
||||
| 出勤率 | 25% | 原始百分比(0-100) |
|
||||
| 满员率 | 25% | 原始百分比(0-100) |
|
||||
| 违规扣分 | 15% | 线性扣分:max(0, 100 - 违规次数 * 20) |
|
||||
|
||||
```
|
||||
综合评分 = 授课量归一化分 * 0.35 + 出勤率 * 0.25 + 满员率 * 0.25 + 违规分 * 0.15
|
||||
```
|
||||
|
||||
**公式变更历史**:
|
||||
- 初版(2026-07-22): `授课量归一化(最大值归一化) * 0.4 + 出勤率 * 0.3 + 满员率 * 0.3`,违规仅展示不参与评分
|
||||
- 修订(2026-07-26): 授课量归一化改为百分位排名,违规纳入评分,权重重新分配
|
||||
|
||||
**拒绝的替代方案**: 详见设计文档 `docs/coach-performance-design.md`。
|
||||
|
||||
---
|
||||
|
||||
### 9. 不包含学员留存率
|
||||
|
||||
**选择**: 首版不计算学员留存率。
|
||||
|
||||
**理由**: 现有系统缺少"学员持续上课"的显式数据模型。要实现留存率需要定义"留存"的判定规则(如:连续两个月以上预约同一教练的课程),这会引入新的领域概念,增加首版复杂度。
|
||||
|
||||
---
|
||||
|
||||
### 10. 不引入 Redis 缓存
|
||||
|
||||
**选择**: 教练业绩统计数据不进行 Redis 缓存,每次请求实时计算。
|
||||
|
||||
**理由**: 业绩数据需要准实时性,缓存可能导致教练查看时数据滞后;且当前教练数量级下,6 条聚合查询的响应时间可接受。
|
||||
|
||||
---
|
||||
|
||||
### 11. getCoachPerformanceById 复用全量查询
|
||||
|
||||
**选择**: 查询单个教练业绩时,内部调用 `getCoachPerformanceList` 获取全量后过滤。暂不新增按教练 ID 的单独 DAO 方法。
|
||||
|
||||
**理由**: 当前教练数量有限,全量查询后再过滤的性能损耗可接受,优先保持代码简洁。
|
||||
|
||||
**风险**: 教练数量增长后需要重新评估,届时可新增按 coach_id 直查的 DAO 方法。
|
||||
|
||||
---
|
||||
|
||||
## 影响
|
||||
|
||||
### 后端变更
|
||||
- `gym-dataCount` 模块新增:`CoachPerformance` domain、`CoachPerformanceHandler`、`DataStatisticsDao`(教练业绩相关方法)
|
||||
- `manage-app` 的 `SystemRouter` 中新增 3 条路由
|
||||
- `DataStatisticsServiceImpl` 新增 `getCoachPerformanceList`、`getCoachPerformanceById`、`calculateFillRate` 方法
|
||||
|
||||
### 前端变更
|
||||
- `StatisticsDashboard.vue` 新增"教练业绩"Tab
|
||||
- `statistics.api.ts` 新增 API 接口类型
|
||||
- 可选:教练端新增个人业绩页面(通过路由守卫区分角色)
|
||||
|
||||
### 数据库
|
||||
- 无新增表。完全基于现有表(`group_course`、`group_course_booking`、`coach_violation`、`sys_user`)
|
||||
|
||||
---
|
||||
|
||||
## 备选方案记录
|
||||
|
||||
### 方案 A:基于签到表改造(已拒绝)
|
||||
改造 `sign_in_record` 添加 `coach_id` 字段,使签到直接关联教练。
|
||||
- 优点:数据更准确(签到是真实到店行为)
|
||||
- 缺点:需要改表、改签到流程、影响面大;签到不等于上团课
|
||||
|
||||
### 方案 B:新建独立模块(已拒绝)
|
||||
新建 `gym-coach-performance` 独立 Maven 模块。
|
||||
- 优点:职责隔离清晰
|
||||
- 缺点:模块碎片化,增加编译和依赖管理成本
|
||||
|
||||
### 方案 C:授课量最大值归一化(已拒绝,初版方案)
|
||||
`normalizedCourses = courses / maxCourses * 100`
|
||||
- 优点:数学简洁
|
||||
- 缺点:若有一位教练授课量远超其他,中游教练得分被严重压缩;鼓励"互卷"而非"达标"
|
||||
|
||||
### 方案 D:授课量对数归一化(已拒绝)
|
||||
`normalizedCourses = ln(courses + 1) / ln(maxCourses + 1) * 100`
|
||||
- 优点:自然压制极端值
|
||||
- 缺点:解释性弱,非技术人员难以理解评分含义
|
||||
|
||||
### 方案 E:授课量固定目标归一化(已拒绝)
|
||||
`normalizedCourses = min(courses / target * 100, 100)`,target 可配置
|
||||
- 优点:变成"达标制",不受其他教练影响
|
||||
- 缺点:target 值需要根据实际数据校准,设置不当会全员满分或全员不及格
|
||||
|
||||
### 方案 F:违规阶梯扣分(已拒绝)
|
||||
0次=100, 1次=70, 2次=40, 3次=10, >=4次=0
|
||||
- 优点:首次违规惩罚重,有威慑力
|
||||
- 缺点:阶梯粒度太粗,第 1 次和第 2 次违规之间差距 30 分,过于激进
|
||||
|
||||
### 方案 G:违规归一化扣分(已拒绝)
|
||||
`violationScore = (1 - violations / maxViolations) * 100`
|
||||
- 优点:相对于最差教练扣分
|
||||
- 缺点:依赖数据集中的最大值,若所有教练都无违规则无意义
|
||||
@@ -0,0 +1,214 @@
|
||||
# ADR-0002: 教练迟到/缺席时间判定可配置化
|
||||
|
||||
**日期**: 2026-07-26
|
||||
**状态**: 已决定
|
||||
**决策者**: 通过 grill-with-docs 追问明确
|
||||
|
||||
---
|
||||
|
||||
## 背景
|
||||
|
||||
当前教练开课/结课/迟到/缺席的时间阈值全部硬编码在代码中:
|
||||
|
||||
| 硬编码值 | 位置 | 含义 |
|
||||
|----------|------|------|
|
||||
| 60 分钟 | CoachCourseService + CoachCourseScheduler | 长/短课时分界线 |
|
||||
| 10 分钟 | CoachCourseService L213 | 长课正常开课窗口 |
|
||||
| 30 分钟 | CoachCourseService L217, Scheduler L118 | 长课迟到/缺席截止线 |
|
||||
| 10% | CoachCourseService L229 | 短课正常开课比例 |
|
||||
| 25% | CoachCourseService L230, Scheduler L120 | 短课迟到/缺席比例 |
|
||||
| 10 分钟 | CoachCourseService L283, Scheduler L34 | 结课宽限期 |
|
||||
|
||||
业务方要求:
|
||||
1. **前端统一传入绝对值**(分钟),短课时比例也由前端换算后传入
|
||||
2. 支持**按课程时长区间**匹配不同规则
|
||||
3. 配置存储在**数据库**中
|
||||
4. **热更新**——修改配置后无需重启即生效
|
||||
5. 配置缺失/非法时使用**硬编码值兜底**
|
||||
|
||||
---
|
||||
|
||||
## 决策
|
||||
|
||||
### 1. 架构:新建 `gym-coach-config` 独立模块
|
||||
|
||||
**选择**: 创建新模块 `gym-coach-config`,封装时间规则配置的完整功能链。
|
||||
|
||||
**理由**:
|
||||
- 将可配置化逻辑从 `gym-coach` 中解耦,符合单一职责原则
|
||||
- `gym-coach-config` 提供规则 CRUD + 规则匹配服务,是纯"配置域"
|
||||
- `gym-coach` 和 `gym-coach-config` 之间通过依赖注入协作,`gym-coach` 依赖 `gym-coach-config`
|
||||
- 后续若其他模块(如签到、预约)也需要时间阈值配置化,可直接复用
|
||||
|
||||
**替代方案被拒绝**:
|
||||
- 放在 `gym-coach` 模块内:配置逻辑和业务逻辑耦合,违反职责分离
|
||||
- 放在 `manage-sys` 的字典模块:字典是通用 key-value 对,无法支撑规则匹配(需范围查询 + 优先级排序)
|
||||
|
||||
### 2. 数据模型:`coach_time_rule` 表
|
||||
|
||||
采用规则表设计,每条规则定义了一个课程时长区间及其对应的时间阈值:
|
||||
|
||||
```sql
|
||||
CREATE TABLE coach_time_rule (
|
||||
id BIGSERIAL PRIMARY KEY,
|
||||
min_duration INTEGER, -- 课程时长下限(分钟),NULL 表示无下限
|
||||
max_duration INTEGER, -- 课程时长上限(分钟),NULL 表示无上限
|
||||
normal_window INTEGER NOT NULL, -- 正常开课窗口(分钟)
|
||||
late_window INTEGER NOT NULL, -- 迟到/缺席截止窗口(分钟)
|
||||
end_grace INTEGER NOT NULL, -- 结课宽限期(分钟)
|
||||
is_default BOOLEAN DEFAULT FALSE, -- 是否默认规则
|
||||
sort_order INTEGER DEFAULT 0, -- 优先级
|
||||
status CHAR(1) DEFAULT '1',
|
||||
remark VARCHAR(500),
|
||||
create_by VARCHAR(64),
|
||||
update_by VARCHAR(64),
|
||||
created_at TIMESTAMP DEFAULT NOW(),
|
||||
updated_at TIMESTAMP DEFAULT NOW(),
|
||||
deleted_at TIMESTAMP
|
||||
);
|
||||
```
|
||||
|
||||
**示例数据**:
|
||||
|
||||
| id | min_duration | max_duration | normal_window | late_window | end_grace | is_default | 说明 |
|
||||
|----|-------------|-------------|---------------|-------------|-----------|------------|------|
|
||||
| 1 | NULL | NULL | 10 | 30 | 10 | true | 默认规则:原长课逻辑 |
|
||||
| 2 | NULL | 59 | 1 | 15 | 5 | false | 短课(<60分钟):最小1分钟正常,15分钟迟到 |
|
||||
|
||||
### 3. 规则匹配策略
|
||||
|
||||
```
|
||||
对于一门课程(时长 = endTime - startTime 的分钟数):
|
||||
|
||||
1. 从 Redis 缓存中获取所有启用规则(status='1', deleted_at IS NULL)
|
||||
2. 过滤出 minDuration <= courseDuration <= maxDuration 的规则
|
||||
3. 选择范围最精确的规则 —— 即 (maxDuration - minDuration) 最小的那条
|
||||
4. 若无匹配规则,使用 is_default=true 的默认规则
|
||||
5. 若默认规则也不存在,使用硬编码兜底值
|
||||
```
|
||||
|
||||
### 4. 热更新机制
|
||||
|
||||
```
|
||||
┌──────────┐ POST/PUT/DELETE ┌──────────────────┐
|
||||
│ 前端 │ ──────────────────> │ CoachTimeRuleHandler │
|
||||
└──────────┘ └────────┬─────────┘
|
||||
│
|
||||
┌──────▼──────┐
|
||||
│ DB 更新 │
|
||||
└──────┬──────┘
|
||||
│
|
||||
┌──────▼──────┐
|
||||
│ 删除 Redis │
|
||||
│ key: │
|
||||
│ coach:time: │
|
||||
│ rules │
|
||||
└──────┬──────┘
|
||||
│
|
||||
┌──────────────┐ 下次开课/调度器触发时 ┌──▼───────────┐
|
||||
│ 业务代码 │ <────────────────── │ Redis Miss │
|
||||
│ (Service/ │ │ → 从 DB 加载 │
|
||||
│ Scheduler) │ │ → 写入 Redis │
|
||||
└──────────────┘ └──────────────┘
|
||||
```
|
||||
|
||||
- 写操作(创建/更新/删除规则)→ 更新 DB → 立即删除 Redis 缓存 key
|
||||
- 读操作 → 先查 Redis → 未命中则查 DB → 写入 Redis(TTL=300s,兜底)
|
||||
- 每次业务调用(开课/调度器)都实时从 CoachTimeRuleService 获取最新规则,不缓存本地变量
|
||||
|
||||
### 5. 兜底策略
|
||||
|
||||
| 场景 | 行为 |
|
||||
|------|------|
|
||||
| 所有规则被删除 | 使用硬编码默认值(原逻辑:长课 10/30,短课 10%/25%,结课 10) |
|
||||
| 单条规则中值为 null/负数 | 该字段使用硬编码兜底值 |
|
||||
| Redis 不可用 | 降级为每次查 DB |
|
||||
| DB 不可用 | 使用硬编码兜底值 |
|
||||
|
||||
### 6. API 设计
|
||||
|
||||
```
|
||||
GET /api/coach/time-rules -- 获取所有规则列表
|
||||
GET /api/coach/time-rules/{id} -- 获取单条规则
|
||||
POST /api/coach/time-rules -- 创建规则
|
||||
PUT /api/coach/time-rules/{id} -- 更新规则
|
||||
DELETE /api/coach/time-rules/{id} -- 删除规则
|
||||
```
|
||||
|
||||
POST/PUT 请求体:
|
||||
```json
|
||||
{
|
||||
"minDuration": 60, // 可选,null 表示无下限
|
||||
"maxDuration": null, // 可选,null 表示无上限
|
||||
"normalWindow": 10, // 必填,正常开课窗口(分钟)
|
||||
"lateWindow": 30, // 必填,迟到/缺席截止窗口(分钟)
|
||||
"endGrace": 10, // 必填,结课宽限期(分钟)
|
||||
"isDefault": true, // 是否设为默认规则
|
||||
"sortOrder": 0,
|
||||
"remark": "默认规则"
|
||||
}
|
||||
```
|
||||
|
||||
### 7. API 校验规则
|
||||
|
||||
后端在 Handler 层对前端传入的值做合法性校验:
|
||||
- `normalWindow`:必须 >= 1 且 <= 1440(一天内)
|
||||
- `lateWindow`:必须 >= `normalWindow` 且 <= 1440
|
||||
- `endGrace`:必须 >= 0 且 <= 1440
|
||||
- `minDuration` 和 `maxDuration`:若同时非空,`maxDuration` 必须 >= `minDuration`
|
||||
- 若前端传入非法值,返回 HTTP 400 + 具体错误信息;不落库
|
||||
|
||||
### 8. 模块依赖关系
|
||||
|
||||
```
|
||||
manage-app
|
||||
├── gym-coach (依赖 gym-coach-config)
|
||||
│ └── CoachCourseService → 注入 CoachTimeRuleService 获取规则
|
||||
│ └── CoachCourseScheduler → 注入 CoachTimeRuleService 获取规则
|
||||
└── gym-coach-config (新模块)
|
||||
├── handler/CoachTimeRuleHandler -- HTTP 处理器
|
||||
├── service/CoachTimeRuleService -- 规则匹配 + 缓存
|
||||
├── domain/CoachTimeRule -- 领域对象
|
||||
├── repository/ICoachTimeRuleRepository -- 仓储接口
|
||||
└── router -- 路由注册
|
||||
manage-db
|
||||
├── entity/CoachTimeRuleEntity -- DB 实体
|
||||
├── dao/CoachTimeRuleDao -- DAO (R2DBC)
|
||||
└── migration/V29__Create_coach_time_rule.sql
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 影响范围
|
||||
|
||||
| 文件 | 变更类型 | 说明 |
|
||||
|------|----------|------|
|
||||
| `pom.xml` | 新增 | 添加 `gym-coach-config` 模块 |
|
||||
| `gym-coach/pom.xml` | 修改 | 添加 `gym-coach-config` 依赖 |
|
||||
| `CoachCourseService.java` | 修改 | 注入 `CoachTimeRuleService`,替换硬编码阈值 |
|
||||
| `CoachCourseScheduler.java` | 修改 | 注入 `CoachTimeRuleService`,替换硬编码阈值 |
|
||||
| `SystemRouter.java` | 修改 | 注册新路由 |
|
||||
| 新建模块文件 | 新增 | 约 8-10 个 Java 文件 + 1 个 SQL 迁移 |
|
||||
|
||||
---
|
||||
|
||||
## 已知问题与修复记录
|
||||
|
||||
### 修复 1:Flyway 版本冲突
|
||||
|
||||
原始版本使用了 V25/V26,与已有迁移冲突。最终使用 V29(建表)/ V30(菜单)。
|
||||
|
||||
### 修复 2:LocalDateTime Redis 反序列化
|
||||
|
||||
`CoachTimeRule.domain` 的 `createdAt`/`updatedAt` 存入 Redis 后反序列化失败(DB 格式 `yyyy-MM-dd HH:mm:ss` 无 `T` 分隔符,Jackson 默认期望 ISO 格式)。已添加 `@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")`。
|
||||
|
||||
### 修复 3:默认规则回退未做区间匹配校验
|
||||
|
||||
**问题**:当有区间限制的规则(如 `minDuration=30`)被标记为 `isDefault=true`,或原始默认规则被修改了区间时,不匹配该区间的课程时长(如 20 分钟)会被错误应用该规则的阈值。
|
||||
|
||||
**修复**:`doMatch()` 中回退到默认规则时,增加 `r.matches(courseDurationMinutes)` 校验。若默认规则也不匹配,继续回退到 `buildFallbackRule` 兜底。
|
||||
|
||||
```diff
|
||||
- .filter(r -> Boolean.TRUE.equals(r.getIsDefault()))
|
||||
+ .filter(r -> Boolean.TRUE.equals(r.getIsDefault()) && r.matches(courseDurationMinutes))
|
||||
```
|
||||
@@ -0,0 +1,294 @@
|
||||
# 教练业绩统计设计文档
|
||||
|
||||
**版本**: v2.0
|
||||
**日期**: 2026-07-26
|
||||
**状态**: 已确定
|
||||
|
||||
---
|
||||
|
||||
## 一、功能概述
|
||||
|
||||
教练业绩统计为体育馆管理系统提供按教练维度的绩效评估,帮助管理者横向对比教练表现、激励教练提升教学质量。
|
||||
|
||||
### 核心能力
|
||||
|
||||
- **教练排行榜**:按综合评分降序排列所有教练
|
||||
- **教练详情**:查看单个教练的六项指标详情
|
||||
- **自查看板**:教练查看自己的业绩表现
|
||||
|
||||
---
|
||||
|
||||
## 二、指标体系
|
||||
|
||||
### 2.1 六项指标总览
|
||||
|
||||
| 序号 | 指标 | 类型 | 含义 | 数据源 |
|
||||
|------|------|------|------|--------|
|
||||
| 1 | 授课量 | 基础指标 | 统计周期内已完成的团课数量 | `group_course.status IN ('2','6')` |
|
||||
| 2 | 出席人次 | 基础指标 | 学员实际参与的人次 | `group_course_booking.status IN ('2','4','5')` |
|
||||
| 3 | 总预约数 | 基础指标 | 学员预约该教练课程的次数(仅已预约状态) | `group_course_booking.status = '0'` |
|
||||
| 4 | 出勤率 | 派生指标 | 出席人次 / 总预约数 * 100 | 指标2 + 指标3 |
|
||||
| 5 | 满员率 | 派生指标 | 各课程出席人数/满员上限的平均值 | `group_course.max_members` + 指标2明细 |
|
||||
| 6 | 违规次数 | 基础指标 | 统计周期内违规记录数 | `coach_violation` |
|
||||
| 7 | 综合评分 | 派生指标 | 加权综合得分(详见第三章) | 指标1-6 |
|
||||
|
||||
### 2.2 指标口径详解
|
||||
|
||||
#### 授课量
|
||||
|
||||
```
|
||||
SELECT coach_id, COUNT(*) FROM group_course
|
||||
WHERE end_time >= :startTime AND end_time < :endTime
|
||||
AND status IN ('2', '6') AND deleted_at IS NULL
|
||||
GROUP BY coach_id
|
||||
```
|
||||
|
||||
- **status='2'**: 教练手动结课
|
||||
- **status='6'**: 系统自动结课
|
||||
- **排除**: 已取消(status='1')、教练缺席(status='5')的课程
|
||||
|
||||
#### 出席人次
|
||||
|
||||
```
|
||||
SELECT gc.coach_id, COUNT(*) FROM group_course_booking b
|
||||
INNER JOIN group_course gc ON b.course_id = gc.id
|
||||
WHERE b.status IN ('2', '4', '5') AND b.deleted_at IS NULL
|
||||
AND gc.deleted_at IS NULL
|
||||
AND gc.end_time >= :startTime AND gc.end_time < :endTime
|
||||
GROUP BY gc.coach_id
|
||||
```
|
||||
|
||||
- **status='2'**: 已出席 — 学员正常到课
|
||||
- **status='4'**: 教练缺席 — 教练未到,学员仍需记录
|
||||
- **status='5'**: 迟到 — 学员迟到但仍到场参与
|
||||
|
||||
> **设计意图**: 教练缺席和迟到时,学员仍到达了现场(或尝试参与),责任在教练而非学员,故计入出席人次。学员无故缺席(status='3')不计入,因其既非教练功劳也非教练责任。
|
||||
|
||||
#### 总预约数
|
||||
|
||||
```
|
||||
SELECT gc.coach_id, COUNT(*) FROM group_course_booking b
|
||||
INNER JOIN group_course gc ON b.course_id = gc.id
|
||||
WHERE b.status = '0' AND b.deleted_at IS NULL
|
||||
AND gc.deleted_at IS NULL
|
||||
AND gc.end_time >= :startTime AND gc.end_time < :endTime
|
||||
GROUP BY gc.coach_id
|
||||
```
|
||||
|
||||
- **仅 status='0'(已预约)**: 作为出勤率分母,表示"承诺来上课的学员"。
|
||||
|
||||
#### 满员率
|
||||
|
||||
```
|
||||
SELECT gc.coach_id, gc.max_members, COUNT(b.id) AS attended
|
||||
FROM group_course gc
|
||||
LEFT JOIN group_course_booking b ON gc.id = b.course_id
|
||||
AND b.status IN ('2','4','5') AND b.deleted_at IS NULL
|
||||
WHERE gc.end_time >= :startTime AND gc.end_time < :endTime
|
||||
AND gc.status IN ('2', '6') AND gc.deleted_at IS NULL
|
||||
GROUP BY gc.coach_id, gc.id, gc.max_members
|
||||
```
|
||||
|
||||
- 对每个已完成课程,计算 `出席人数 / max_members`
|
||||
- 所有课程的比值取平均值
|
||||
- `max_members = 0` 的课程被跳过(除零防御)
|
||||
|
||||
#### 违规次数
|
||||
|
||||
```
|
||||
SELECT coach_id, COUNT(*) FROM coach_violation
|
||||
WHERE violation_time >= :startTime AND violation_time < :endTime
|
||||
AND deleted_at IS NULL
|
||||
GROUP BY coach_id
|
||||
```
|
||||
|
||||
- 违规类型: `COACH_LATE`(迟到)、`COACH_ABSENT`(缺席)、`NOT_MANUAL_END`(未手动结课)
|
||||
|
||||
#### 时间基准
|
||||
|
||||
所有指标均基于 `group_course.end_time` 过滤时间范围。跨月课程归属于结束时间所在的月份。
|
||||
|
||||
---
|
||||
|
||||
## 三、综合评分算法
|
||||
|
||||
### 3.1 最终公式
|
||||
|
||||
```
|
||||
综合评分 = 授课量归一化分 * 0.35
|
||||
+ 出勤率 * 0.25
|
||||
+ 满员率 * 0.25
|
||||
+ 违规分 * 0.15
|
||||
```
|
||||
|
||||
### 3.2 授课量归一化:百分位排名法(方案 B)
|
||||
|
||||
对于教练数为 N 的集合:
|
||||
|
||||
1. 将所有教练按授课量升序排列
|
||||
2. 统计授课量严格小于当前教练的教练数 `C_fewer`
|
||||
3. `normalizedCourses = C_fewer / (N - 1) * 100`(N=1 时取 100)
|
||||
|
||||
**示例**(4 位教练):
|
||||
|
||||
| 教练 | 授课量 | 小于其的教练数 | 归一化分 |
|
||||
|------|--------|---------------|---------|
|
||||
| A | 20 | 3 | 100.0 |
|
||||
| B | 15 | 2 | 66.7 |
|
||||
| C | 10 | 1 | 33.3 |
|
||||
| D | 5 | 0 | 0.0 |
|
||||
|
||||
**设计意图**: 百分位排名在"相对比较"和"公平性"之间取得平衡。授课量最大的教练得满分,最少的得 0 分,中间按排名线性分布。不受极端值影响——即使第一名开 100 节课、第二名只开 20 节,第二名的排名分数依然是 `2/3 * 100 ≈ 66.7`。
|
||||
|
||||
### 3.3 违规分:线性扣分法(方案 A)
|
||||
|
||||
```
|
||||
violationScore = max(0, 100 - violations * 20)
|
||||
```
|
||||
|
||||
| 违规次数 | 违规分 |
|
||||
|----------|--------|
|
||||
| 0 | 100 |
|
||||
| 1 | 80 |
|
||||
| 2 | 60 |
|
||||
| 3 | 40 |
|
||||
| 4 | 20 |
|
||||
| 5+ | 0 |
|
||||
|
||||
**设计意图**: 线性扣分简单直观,每次违规固定扣 20 分,累计 5 次后清零。在 15% 的权重下,每次违规对综合评分的影响约为 `20 * 0.15 = 3 分`。
|
||||
|
||||
### 3.4 出勤率 & 满员率
|
||||
|
||||
这两项直接使用原始百分比(0-100),无需归一化——它们天然在 0-100 范围内且具有绝对含义。
|
||||
|
||||
```
|
||||
出勤率 = 出席人次 / 总预约数 * 100(分母为 0 时取 0)
|
||||
满员率 = avg(单个课程出席人数 / max_members) * 100(跳过 max_members=0 的课程)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 四、方案选择记录
|
||||
|
||||
### 4.1 授课量归一化方案
|
||||
|
||||
| 方案 | 公式 | 优点 | 缺点 | 决定 |
|
||||
|------|------|------|------|------|
|
||||
| **B: 百分位排名** | `C_fewer / (N-1) * 100` | 直观、不受极端值影响 | 对教练总数敏感(N<3 时分布粗糙) | **采纳** |
|
||||
| A: 最大值归一化 | `courses / max(courses) * 100` | 数学简洁 | 极端值压缩中游得分 | 初版方案,已废弃 |
|
||||
| C: 对数归一化 | `ln(x+1)/ln(m+1)*100` | 压制极端值 | 解释性弱 | 已拒绝 |
|
||||
| D: 固定目标 | `min(x/target*100, 100)` | 达标制、不互卷 | target 难校准 | 已拒绝 |
|
||||
|
||||
### 4.2 违规扣分方案
|
||||
|
||||
| 方案 | 公式 | 优点 | 缺点 | 决定 |
|
||||
|------|------|------|------|------|
|
||||
| **A: 线性扣分** | `max(0, 100 - v*20)` | 简单直白,每次等量扣分 | 多次违规后惩罚不再加剧 | **采纳** |
|
||||
| B: 阶梯扣分 | 0→100, 1→70, 2→40, 3→10 | 首次违规惩罚重,有威慑力 | 第 1 到第 2 次差距 30 分,太激进 | 已拒绝 |
|
||||
| C: 归一化扣分 | `(1 - v/max)*100` | 相对最差教练 | 依赖数据集,全员无违规则无意义 | 已拒绝 |
|
||||
|
||||
### 4.3 权重分配方案
|
||||
|
||||
| 方案 | 授课量 | 出勤率 | 满员率 | 违规 | 决定 |
|
||||
|------|--------|--------|--------|------|------|
|
||||
| **A: 轻违规** | 35% | 25% | 25% | 15% | **采纳** |
|
||||
| B: 中违规 | 30% | 25% | 25% | 20% | 已拒绝 |
|
||||
| C: 重违规 | 30% | 23% | 22% | 25% | 已拒绝 |
|
||||
|
||||
### 4.4 出勤率口径方案
|
||||
|
||||
| 方案 | 分子 | 分母 | 决定 |
|
||||
|------|------|------|------|
|
||||
| **当前** | status IN ('2','4','5') | status='0' | **采纳** |
|
||||
| 初版 | status='2' | status!='1' | 已废弃 |
|
||||
| 替代方案1 | status='2' | status IN ('0','2','3') | 已拒绝(无故缺席应排除) |
|
||||
| 替代方案2 | status='2' | status IN ('0','2') | 已拒绝(不能区分取消预约) |
|
||||
|
||||
---
|
||||
|
||||
## 五、数据模型
|
||||
|
||||
### 5.1 API 响应模型
|
||||
|
||||
```java
|
||||
public class CoachPerformance {
|
||||
Long coachId; // 教练ID
|
||||
String coachName; // 教练昵称
|
||||
String avatar; // 头像URL
|
||||
Long completedCourses; // 授课量
|
||||
Long attendedStudents; // 出席人次
|
||||
Long totalBookings; // 总预约数
|
||||
Double attendanceRate; // 出勤率 (%)
|
||||
Double fillRate; // 满员率 (%)
|
||||
Long violationCount; // 违规次数
|
||||
Double compositeScore; // 综合评分
|
||||
}
|
||||
```
|
||||
|
||||
### 5.2 API 接口
|
||||
|
||||
| 方法 | 路径 | 说明 |
|
||||
|------|------|------|
|
||||
| GET | `/api/datacount/coach-performance/ranking` | 全部教练业绩排行榜 |
|
||||
| GET | `/api/datacount/coach-performance/{coachId}` | 单个教练业绩详情 |
|
||||
| GET | `/api/datacount/coach-performance/mine?coachId=` | 教练自查看板 |
|
||||
|
||||
**查询参数**: `statType`, `periodType`(DAY/WEEK/MONTH/LAST_30_DAYS/LAST_90_DAYS/YEAR), `startTime`, `endTime`
|
||||
|
||||
---
|
||||
|
||||
## 六、代码架构
|
||||
|
||||
```
|
||||
CoachPerformanceHandler ── Reactive Router Function,解析请求
|
||||
│
|
||||
IDataStatisticsService ── 接口定义
|
||||
│
|
||||
DataStatisticsServiceImpl ── 6 并行查询 + 聚合计算
|
||||
│
|
||||
DataStatisticsDao ── DatabaseClient SQL 聚合
|
||||
│
|
||||
┌───┼───┬───┬───┬───┐
|
||||
▼ ▼ ▼ ▼ ▼ ▼
|
||||
sys_user group_course group_course_booking coach_violation
|
||||
```
|
||||
|
||||
### 查询执行流程
|
||||
|
||||
```
|
||||
1. Flux: getAllCoachesWithInfo() ─→ Map<coachId, 基本信息>
|
||||
2. Flux: countCompletedCoursesByCoach() ─→ Map<coachId, 授课量> ┐
|
||||
3. Flux: countAttendedStudentsByCoach() ─→ Map<coachId, 出席人次> │
|
||||
4. Flux: countTotalBookingsByCoach() ─→ Map<coachId, 总预约数> ├─ Mono.zip
|
||||
5. Flux: getFillRateDetailByCoach() ─→ Map<coachId, List<明细>> │
|
||||
6. Flux: countViolationsByCoach() ─→ Map<coachId, 违规次数> ┘
|
||||
│
|
||||
flatMapMany: 逐教练计算指标
|
||||
│
|
||||
sorted: 按综合评分降序
|
||||
│
|
||||
Flux<CoachPerformance>
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 七、边界情况处理
|
||||
|
||||
| 场景 | 行为 |
|
||||
|------|------|
|
||||
| 教练无任何已完成课程 | 所有指标为 0,综合评分 = 0 + 0 + 0 + 15 = **15**(违规分满分 100 * 0.15) |
|
||||
| 教练有课程但无人预约 | 授课量 > 0,出勤率/满员率 = 0 |
|
||||
| 课程 max_members = 0 | 该课程跳过,不参与满员率计算 |
|
||||
| 仅有 1 位教练 | 百分位排名直接返回 100 |
|
||||
| 所有教练授课量相同 | 所有教练 `C_fewer = 0`,授课量归一化分均为 0 |
|
||||
| 跨月课程 | 以 end_time 所在月份归类 |
|
||||
| 查询单个教练不存在 | 返回零值 `CoachPerformance`,coachName="未知教练" |
|
||||
|
||||
---
|
||||
|
||||
## 八、变更历史
|
||||
|
||||
| 日期 | 版本 | 变更内容 |
|
||||
|------|------|---------|
|
||||
| 2026-07-22 | v1.0 | 初版:最大值归一化 + 三维度评分(4:3:3),违规仅展示 |
|
||||
| 2026-07-26 | v2.0 | 时间基准改为 end_time;出席人次扩展为(2,4,5);出勤率分母改为仅 status='0';授课量归一化改为百分位排名;违规纳入综合评分(权重 15%);满员率防御除零 |
|
||||
@@ -68,7 +68,13 @@
|
||||
<artifactId>hutool-all</artifactId>
|
||||
<version>5.8.25</version>
|
||||
</dependency>
|
||||
<!-- 阿里云一键登录服务 -->
|
||||
<!-- 阿里云号码认证服务(新版SDK) -->
|
||||
<dependency>
|
||||
<groupId>com.aliyun</groupId>
|
||||
<artifactId>dypnsapi20170525</artifactId>
|
||||
<version>1.0.6</version>
|
||||
</dependency>
|
||||
<!-- 阿里云一键登录服务(旧版SDK,保留兼容) -->
|
||||
<dependency>
|
||||
<groupId>com.aliyun</groupId>
|
||||
<artifactId>aliyun-java-sdk-dypnsapi</artifactId>
|
||||
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package cn.novalon.gym.manage.auth.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Data
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "dcloud.univerify")
|
||||
public class DCloudUniverifyConfig {
|
||||
private String appid;
|
||||
private String appkey;
|
||||
private String apiSecret;
|
||||
private String apiUrl = "https://developer.dcloud.net.cn/api/client/univerify/getPhoneNumber";
|
||||
private String proxyHost;
|
||||
private Integer proxyPort;
|
||||
private Integer timeout = 10000;
|
||||
}
|
||||
+2
-7
@@ -1,25 +1,20 @@
|
||||
package cn.novalon.gym.manage.auth.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
/**
|
||||
* 手机号一键登录请求DTO
|
||||
* uniapp官方一键登录流程:前端通过云函数获取access_token和openid传给后端换取手机号
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class PhoneLoginDto {
|
||||
|
||||
@NotBlank(message = "access_token不能为空")
|
||||
private String phone;
|
||||
|
||||
private String accessToken;
|
||||
|
||||
@NotBlank(message = "openid不能为空")
|
||||
private String openid;
|
||||
|
||||
private String nickname;
|
||||
|
||||
+5
-3
@@ -1,5 +1,7 @@
|
||||
package cn.novalon.gym.manage.auth.service;
|
||||
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
/**
|
||||
* 短信服务接口
|
||||
*
|
||||
@@ -14,7 +16,7 @@ public interface SmsService {
|
||||
* @param phone 手机号
|
||||
* @return 发送结果
|
||||
*/
|
||||
boolean sendVerificationCode(String phone);
|
||||
Mono<Boolean> sendVerificationCode(String phone);
|
||||
|
||||
/**
|
||||
* 验证短信验证码
|
||||
@@ -23,7 +25,7 @@ public interface SmsService {
|
||||
* @param code 验证码
|
||||
* @return 验证结果
|
||||
*/
|
||||
boolean verifyCode(String phone, String code);
|
||||
Mono<Boolean> verifyCode(String phone, String code);
|
||||
|
||||
/**
|
||||
* 获取验证码(用于测试或特殊场景)
|
||||
@@ -31,5 +33,5 @@ public interface SmsService {
|
||||
* @param phone 手机号
|
||||
* @return 验证码
|
||||
*/
|
||||
String getVerificationCode(String phone);
|
||||
Mono<String> getVerificationCode(String phone);
|
||||
}
|
||||
+85
-44
@@ -1,5 +1,6 @@
|
||||
package cn.novalon.gym.manage.auth.service.impl;
|
||||
|
||||
import cn.novalon.gym.manage.auth.config.DCloudUniverifyConfig;
|
||||
import cn.novalon.gym.manage.auth.config.SmsProperties;
|
||||
import cn.novalon.gym.manage.auth.dto.PhoneCodeLoginDto;
|
||||
import cn.novalon.gym.manage.auth.dto.PhoneLoginDto;
|
||||
@@ -16,22 +17,19 @@ import cn.novalon.gym.manage.member.util.AesUtil;
|
||||
import cn.novalon.gym.manage.member.util.EsSyncUtils;
|
||||
import cn.novalon.gym.manage.member.util.MemberNoGenerator;
|
||||
import cn.novalon.gym.manage.sys.security.JwtTokenProvider;
|
||||
import com.aliyuncs.DefaultAcsClient;
|
||||
import com.aliyuncs.IAcsClient;
|
||||
import com.aliyuncs.dypnsapi.model.v20170525.GetMobileRequest;
|
||||
import com.aliyuncs.dypnsapi.model.v20170525.GetMobileResponse;
|
||||
import com.aliyuncs.exceptions.ClientException;
|
||||
import com.aliyuncs.exceptions.ServerException;
|
||||
import com.aliyuncs.profile.DefaultProfile;
|
||||
import jakarta.annotation.PostConstruct;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.web.reactive.function.client.WebClient;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@@ -44,32 +42,41 @@ public class PhoneAuthServiceImpl implements PhoneAuthService {
|
||||
private final JwtTokenProvider jwtTokenProvider;
|
||||
private final SmsService smsService;
|
||||
private final SmsProperties smsProperties;
|
||||
private final DCloudUniverifyConfig dCloudUniverifyConfig;
|
||||
|
||||
private WebClient webClient;
|
||||
|
||||
private EsSyncUtils.EntitySyncer<Member, MemberES, String> memberSyncer;
|
||||
|
||||
@PostConstruct
|
||||
public void init() {
|
||||
this.memberSyncer = esSyncUtils.bind(Member.class, MemberES.class, memberESRepository);
|
||||
this.webClient = WebClient.builder()
|
||||
.baseUrl(dCloudUniverifyConfig.getApiUrl())
|
||||
.defaultHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<PhoneLoginVO> oneClickLogin(PhoneLoginDto request) {
|
||||
log.info("手机号一键登录请求, accessToken: {}, openid: {}", request.getAccessToken(), request.getOpenid());
|
||||
log.info("手机号一键登录请求, phone: {}, accessToken: {}, openid: {}", request.getPhone(), request.getAccessToken(), request.getOpenid());
|
||||
|
||||
return Mono.fromCallable(() -> getPhoneByToken(request.getAccessToken(), request.getOpenid()))
|
||||
if (request.getPhone() != null && !request.getPhone().isEmpty()) {
|
||||
log.info("直接使用手机号登录");
|
||||
String encryptedPhone = encryptPhone(request.getPhone());
|
||||
return processPhoneLogin(encryptedPhone, request);
|
||||
}
|
||||
|
||||
if (request.getAccessToken() == null || request.getAccessToken().isEmpty()) {
|
||||
log.error("一键登录失败: accessToken为空");
|
||||
return Mono.error(new SystemException(ErrorCode.AUTH_PHONE_ERROR, "登录凭证无效,请重试"));
|
||||
}
|
||||
|
||||
return getPhoneByDcloudApi(request.getAccessToken(), request.getOpenid())
|
||||
.flatMap(phone -> {
|
||||
log.info("通过access_token获取手机号成功: {}", maskPhone(phone));
|
||||
String encryptedPhone = encryptPhone(phone);
|
||||
|
||||
return memberRepository.findByPhone(encryptedPhone)
|
||||
.flatMap(existingMember -> {
|
||||
log.info("手机号已注册,直接登录, memberId: {}", existingMember.getId());
|
||||
return doLogin(existingMember, false, request);
|
||||
})
|
||||
.switchIfEmpty(Mono.defer(() -> {
|
||||
log.info("手机号未注册,创建新会员");
|
||||
return createNewMemberAndLogin(request, encryptedPhone);
|
||||
}));
|
||||
return processPhoneLogin(encryptedPhone, request);
|
||||
})
|
||||
.onErrorResume(e -> {
|
||||
log.error("一键登录失败", e);
|
||||
@@ -77,30 +84,64 @@ public class PhoneAuthServiceImpl implements PhoneAuthService {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过access_token和openid获取手机号
|
||||
* 使用阿里云DYPNS API
|
||||
*/
|
||||
private String getPhoneByToken(String accessToken, String openid) throws Exception {
|
||||
DefaultProfile profile = DefaultProfile.getProfile("cn-hangzhou", smsProperties.getAccessKeyId(), smsProperties.getAccessKeySecret());
|
||||
IAcsClient client = new DefaultAcsClient(profile);
|
||||
GetMobileRequest request = new GetMobileRequest();
|
||||
request.setAccessToken(accessToken);
|
||||
private Mono<PhoneLoginVO> processPhoneLogin(String encryptedPhone, PhoneLoginDto request) {
|
||||
return memberRepository.findByPhone(encryptedPhone)
|
||||
.flatMap(existingMember -> {
|
||||
log.info("手机号已注册,直接登录, memberId: {}", existingMember.getId());
|
||||
return doLogin(existingMember, false, request);
|
||||
})
|
||||
.switchIfEmpty(Mono.defer(() -> {
|
||||
log.info("手机号未注册,创建新会员");
|
||||
return createNewMemberAndLogin(request, encryptedPhone);
|
||||
}));
|
||||
}
|
||||
|
||||
try {
|
||||
GetMobileResponse response = client.getAcsResponse(request);
|
||||
if ("OK".equals(response.getCode())) {
|
||||
return response.getGetMobileResultDTO().getMobile();
|
||||
}
|
||||
log.warn("DYPNS API返回错误: code={}, message={}", response.getCode(), response.getMessage());
|
||||
throw new SystemException(ErrorCode.AUTH_PHONE_ERROR, "手机号获取失败: " + response.getMessage());
|
||||
} catch (ServerException e) {
|
||||
log.error("阿里云DYPNS API服务端异常", e);
|
||||
throw new SystemException(ErrorCode.AUTH_PHONE_ERROR, "手机号获取失败");
|
||||
} catch (ClientException e) {
|
||||
log.error("阿里云DYPNS API客户端异常", e);
|
||||
throw new SystemException(ErrorCode.AUTH_PHONE_ERROR, "手机号获取失败");
|
||||
}
|
||||
private Mono<String> getPhoneByDcloudApi(String accessToken, String openid) {
|
||||
Map<String, String> requestBody = new HashMap<>();
|
||||
requestBody.put("appid", dCloudUniverifyConfig.getAppid());
|
||||
requestBody.put("appkey", dCloudUniverifyConfig.getAppkey());
|
||||
requestBody.put("apiSecret", dCloudUniverifyConfig.getApiSecret());
|
||||
requestBody.put("access_token", accessToken);
|
||||
requestBody.put("openid", openid);
|
||||
|
||||
log.info("调用DCloud Univerify API, params: {}", requestBody);
|
||||
|
||||
return webClient.post()
|
||||
.bodyValue(requestBody)
|
||||
.retrieve()
|
||||
.bodyToMono(Map.class)
|
||||
.flatMap(response -> {
|
||||
log.info("DCloud API响应: {}", response);
|
||||
|
||||
Integer code = (Integer) response.get("code");
|
||||
Boolean success = (Boolean) response.get("success");
|
||||
|
||||
if ((code != null && code == 0) || (success != null && success)) {
|
||||
Map<String, Object> data = (Map<String, Object>) response.get("data");
|
||||
if (data != null) {
|
||||
String phoneNumber = (String) data.get("phoneNumber");
|
||||
if (phoneNumber != null && !phoneNumber.isEmpty()) {
|
||||
return Mono.just(phoneNumber);
|
||||
}
|
||||
}
|
||||
String phoneNumber = (String) response.get("phoneNumber");
|
||||
if (phoneNumber != null && !phoneNumber.isEmpty()) {
|
||||
return Mono.just(phoneNumber);
|
||||
}
|
||||
String phone = (String) response.get("phone");
|
||||
if (phone != null && !phone.isEmpty()) {
|
||||
return Mono.just(phone);
|
||||
}
|
||||
}
|
||||
|
||||
String message = (String) response.get("message");
|
||||
log.warn("DCloud API返回错误: code={}, success={}, message={}", code, success, message);
|
||||
return Mono.error(new SystemException(ErrorCode.AUTH_PHONE_ERROR, "手机号获取失败: " + message));
|
||||
})
|
||||
.onErrorResume(e -> {
|
||||
log.error("调用DCloud API失败", e);
|
||||
return Mono.error(new SystemException(ErrorCode.AUTH_PHONE_ERROR, "手机号获取失败: " + e.getMessage()));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -116,14 +157,14 @@ public class PhoneAuthServiceImpl implements PhoneAuthService {
|
||||
@Override
|
||||
public Mono<Boolean> sendSmsCode(String phone) {
|
||||
log.info("发送短信验证码, phone: {}", phone);
|
||||
return Mono.fromCallable(() -> smsService.sendVerificationCode(phone));
|
||||
return smsService.sendVerificationCode(phone);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<PhoneLoginVO> codeLogin(PhoneCodeLoginDto request) {
|
||||
log.info("手机号验证码登录, phone: {}", request.getPhone());
|
||||
|
||||
return Mono.fromCallable(() -> smsService.verifyCode(request.getPhone(), request.getCode()))
|
||||
return smsService.verifyCode(request.getPhone(), request.getCode())
|
||||
.flatMap(verified -> {
|
||||
if (!verified) {
|
||||
log.warn("验证码验证失败, phone: {}", request.getPhone());
|
||||
|
||||
+150
-100
@@ -1,148 +1,198 @@
|
||||
package cn.novalon.gym.manage.auth.service.impl;
|
||||
|
||||
import cn.hutool.core.util.RandomUtil;
|
||||
import cn.novalon.gym.manage.auth.config.SmsProperties;
|
||||
import cn.novalon.gym.manage.auth.service.SmsService;
|
||||
import cn.novalon.gym.manage.common.constant.RedisKeyConstants;
|
||||
import cn.novalon.gym.manage.common.util.RedisUtil;
|
||||
import com.aliyun.dysmsapi20170525.Client;
|
||||
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
|
||||
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
|
||||
import com.aliyun.teaopenapi.models.Config;
|
||||
import com.aliyuncs.CommonRequest;
|
||||
import com.aliyuncs.CommonResponse;
|
||||
import com.aliyuncs.DefaultAcsClient;
|
||||
import com.aliyuncs.IAcsClient;
|
||||
import com.aliyuncs.exceptions.ClientException;
|
||||
import com.aliyuncs.http.MethodType;
|
||||
import com.aliyuncs.profile.DefaultProfile;
|
||||
import com.aliyuncs.profile.IClientProfile;
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneOffset;
|
||||
|
||||
/**
|
||||
* 短信服务实现类
|
||||
*
|
||||
* @author auto-generated
|
||||
* @date 2026-06-20
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class SmsServiceImpl implements SmsService {
|
||||
|
||||
private static final long SEND_INTERVAL_SECONDS = 60;
|
||||
private static final long CODE_EXPIRE_SECONDS = 300;
|
||||
|
||||
private final SmsProperties smsProperties;
|
||||
private final RedisUtil redisUtil;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
@Override
|
||||
public boolean sendVerificationCode(String phone) {
|
||||
public Mono<Boolean> sendVerificationCode(String phone) {
|
||||
log.info("发送短信验证码, phone: {}", phone);
|
||||
|
||||
try {
|
||||
// 生成验证码
|
||||
String code = generateCode();
|
||||
String rateLimitKey = RedisKeyConstants.SMS_CODE + phone + ":rate_limit";
|
||||
|
||||
// 发送短信
|
||||
boolean sent = sendSms(phone, code);
|
||||
return redisUtil.get(rateLimitKey, Long.class)
|
||||
.defaultIfEmpty(0L)
|
||||
.flatMap(lastSendTime -> {
|
||||
long currentTime = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC);
|
||||
|
||||
if (sent) {
|
||||
// 将验证码存入Redis,5分钟过期
|
||||
String cacheKey = RedisKeyConstants.SMS_CODE + phone;
|
||||
redisUtil.setWithExpire(cacheKey, code, smsProperties.getCodeExpireSeconds())
|
||||
.doOnSuccess(result -> log.info("验证码已缓存, phone: {}, code: {}, expire: {}s",
|
||||
phone, code, smsProperties.getCodeExpireSeconds()))
|
||||
.block();
|
||||
if (currentTime - lastSendTime < SEND_INTERVAL_SECONDS) {
|
||||
long remainingSeconds = SEND_INTERVAL_SECONDS - (currentTime - lastSendTime);
|
||||
log.warn("发送频率限制, phone: {}, 剩余时间: {}秒", phone, remainingSeconds);
|
||||
return Mono.just(false);
|
||||
}
|
||||
|
||||
log.info("短信验证码发送成功, phone: {}", phone);
|
||||
return true;
|
||||
}
|
||||
return Mono.fromCallable(() -> {
|
||||
try {
|
||||
IAcsClient client = createClient();
|
||||
|
||||
log.warn("短信验证码发送失败, phone: {}", phone);
|
||||
return false;
|
||||
CommonRequest request = new CommonRequest();
|
||||
request.setSysMethod(MethodType.POST);
|
||||
request.setSysDomain("dypnsapi.aliyuncs.com");
|
||||
request.setSysVersion("2017-05-25");
|
||||
request.setSysAction("SendSmsVerifyCode");
|
||||
request.putQueryParameter("PhoneNumber", phone);
|
||||
request.putQueryParameter("SignName", smsProperties.getSignName());
|
||||
request.putQueryParameter("TemplateCode", smsProperties.getTemplateCode());
|
||||
request.putQueryParameter("TemplateParam", "{\"code\":\"##code##\",\"min\":\"5\"}");
|
||||
request.putQueryParameter("ReturnVerifyCode", "true");
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("发送短信验证码异常, phone: {}", phone, e);
|
||||
return false;
|
||||
}
|
||||
log.info("阿里云号码认证请求参数 - signName: {}, templateCode: {}, templateParam: {}",
|
||||
smsProperties.getSignName(),
|
||||
smsProperties.getTemplateCode(),
|
||||
"{\"code\":\"##code##\",\"min\":\"5\"}");
|
||||
|
||||
CommonResponse response = client.getCommonResponse(request);
|
||||
String responseData = response.getData();
|
||||
log.info("阿里云号码认证原始响应: {}", responseData);
|
||||
|
||||
JsonNode jsonNode = objectMapper.readTree(responseData);
|
||||
|
||||
JsonNode codeNode = jsonNode.get("Code");
|
||||
if (codeNode == null) {
|
||||
log.error("阿里云响应中找不到Code字段, 原始响应: {}", responseData);
|
||||
return false;
|
||||
}
|
||||
|
||||
String code = codeNode.asText();
|
||||
|
||||
if ("OK".equals(code)) {
|
||||
JsonNode requestIdNode = jsonNode.get("RequestId");
|
||||
String requestId = requestIdNode != null ? requestIdNode.asText() : "unknown";
|
||||
log.info("短信验证码发送成功, phone: {}, requestId: {}", phone, requestId);
|
||||
|
||||
// 提取验证码并存入Redis
|
||||
JsonNode modelNode = jsonNode.get("Model");
|
||||
if (modelNode != null) {
|
||||
JsonNode verifyCodeNode = modelNode.get("VerifyCode");
|
||||
if (verifyCodeNode != null) {
|
||||
String verifyCode = verifyCodeNode.asText();
|
||||
String smsCodeKey = RedisKeyConstants.SMS_CODE + phone;
|
||||
redisUtil.setWithExpire(smsCodeKey, verifyCode, CODE_EXPIRE_SECONDS).subscribe();
|
||||
log.info("验证码已存入Redis, phone: {}, key: {}, expire: {}秒", phone, smsCodeKey, CODE_EXPIRE_SECONDS);
|
||||
} else {
|
||||
log.warn("响应中未找到Model.VerifyCode字段, 原始响应: {}", responseData);
|
||||
}
|
||||
} else {
|
||||
log.warn("响应中未找到Model字段, 原始响应: {}", responseData);
|
||||
}
|
||||
|
||||
redisUtil.setWithExpire(rateLimitKey, currentTime, SEND_INTERVAL_SECONDS).subscribe();
|
||||
return true;
|
||||
}
|
||||
|
||||
JsonNode messageNode = jsonNode.get("Message");
|
||||
String message = messageNode != null ? messageNode.asText() : "unknown";
|
||||
log.error("短信验证码发送失败, phone: {}, code: {}, message: {}", phone, code, message);
|
||||
return false;
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("发送短信验证码异常, phone: {}, 异常信息: {}", phone, e.getMessage(), e);
|
||||
return false;
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean verifyCode(String phone, String code) {
|
||||
public Mono<Boolean> verifyCode(String phone, String code) {
|
||||
log.info("验证短信验证码, phone: {}", phone);
|
||||
|
||||
try {
|
||||
String cacheKey = RedisKeyConstants.SMS_CODE + phone;
|
||||
String cachedCode = redisUtil.get(cacheKey, String.class).block();
|
||||
return Mono.fromCallable(() -> {
|
||||
try {
|
||||
IAcsClient client = createClient();
|
||||
|
||||
if (cachedCode == null) {
|
||||
log.warn("验证码已过期或不存在, phone: {}", phone);
|
||||
CommonRequest request = new CommonRequest();
|
||||
request.setSysMethod(MethodType.POST);
|
||||
request.setSysDomain("dypnsapi.aliyuncs.com");
|
||||
request.setSysVersion("2017-05-25");
|
||||
request.setSysAction("CheckSmsVerifyCode");
|
||||
request.putQueryParameter("PhoneNumber", phone);
|
||||
request.putQueryParameter("VerifyCode", code);
|
||||
|
||||
log.info("阿里云号码认证核验参数 - phone: {}, code: {}", phone, code);
|
||||
|
||||
CommonResponse response = client.getCommonResponse(request);
|
||||
String responseData = response.getData();
|
||||
log.info("阿里云号码认证核验原始响应: {}", responseData);
|
||||
|
||||
JsonNode jsonNode = objectMapper.readTree(responseData);
|
||||
|
||||
JsonNode codeNode = jsonNode.get("Code");
|
||||
if (codeNode == null) {
|
||||
log.error("阿里云核验响应中找不到Code字段, 原始响应: {}", responseData);
|
||||
return false;
|
||||
}
|
||||
|
||||
String responseCode = codeNode.asText();
|
||||
JsonNode modelNode = jsonNode.get("Model");
|
||||
JsonNode verifyResultNode = modelNode != null ? modelNode.get("VerifyResult") : null;
|
||||
boolean verifyResult = verifyResultNode != null && "PASS".equals(verifyResultNode.asText());
|
||||
|
||||
if ("OK".equals(responseCode) && verifyResult) {
|
||||
log.info("验证码验证成功, phone: {}", phone);
|
||||
return true;
|
||||
}
|
||||
|
||||
JsonNode messageNode = jsonNode.get("Message");
|
||||
String message = messageNode != null ? messageNode.asText() : "unknown";
|
||||
log.warn("验证码验证失败, phone: {}, code: {}, message: {}, result: {}",
|
||||
phone, responseCode, message, verifyResult);
|
||||
return false;
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("验证短信验证码异常, phone: {}, 异常信息: {}", phone, e.getMessage(), e);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (cachedCode.equals(code)) {
|
||||
// 验证成功后删除验证码
|
||||
redisUtil.delete(cacheKey).block();
|
||||
log.info("验证码验证成功, phone: {}", phone);
|
||||
return true;
|
||||
}
|
||||
|
||||
log.warn("验证码不匹配, phone: {}, input: {}, cached: {}", phone, code, cachedCode);
|
||||
return false;
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("验证短信验证码异常, phone: {}", phone, e);
|
||||
return false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getVerificationCode(String phone) {
|
||||
public Mono<String> getVerificationCode(String phone) {
|
||||
try {
|
||||
String cacheKey = RedisKeyConstants.SMS_CODE + phone;
|
||||
return redisUtil.get(cacheKey, String.class).block();
|
||||
return redisUtil.get(cacheKey, String.class);
|
||||
} catch (Exception e) {
|
||||
log.error("获取验证码异常, phone: {}", phone, e);
|
||||
return null;
|
||||
return Mono.empty();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成验证码
|
||||
*/
|
||||
private String generateCode() {
|
||||
return RandomUtil.randomNumbers(smsProperties.getCodeLength());
|
||||
}
|
||||
|
||||
/**
|
||||
* 发送短信
|
||||
*/
|
||||
private boolean sendSms(String phone, String code) throws Exception {
|
||||
log.info("调用阿里云短信API发送短信, phone: {}, code: {}", phone, code);
|
||||
|
||||
// 创建阿里云短信客户端
|
||||
Config config = new Config()
|
||||
.setAccessKeyId(smsProperties.getAccessKeyId())
|
||||
.setAccessKeySecret(smsProperties.getAccessKeySecret())
|
||||
.setEndpoint("dysmsapi.aliyuncs.com");
|
||||
|
||||
Client client = new Client(config);
|
||||
|
||||
// 构建发送短信请求
|
||||
SendSmsRequest request = new SendSmsRequest()
|
||||
.setPhoneNumbers(phone)
|
||||
.setSignName(smsProperties.getSignName())
|
||||
.setTemplateCode(smsProperties.getTemplateCode())
|
||||
.setTemplateParam("{\"code\":\"" + code + "\"}");
|
||||
|
||||
// 发送短信
|
||||
SendSmsResponse response = client.sendSms(request);
|
||||
|
||||
log.info("阿里云短信API响应, phone: {}, code: {}, message: {}",
|
||||
phone, response.getBody().getCode(), response.getBody().getMessage());
|
||||
|
||||
// 判断发送结果
|
||||
if ("OK".equals(response.getBody().getCode())) {
|
||||
return true;
|
||||
}
|
||||
|
||||
log.error("阿里云短信发送失败, phone: {}, code: {}, message: {}",
|
||||
phone, response.getBody().getCode(), response.getBody().getMessage());
|
||||
return false;
|
||||
private IAcsClient createClient() throws ClientException {
|
||||
IClientProfile profile = DefaultProfile.getProfile(
|
||||
"cn-hangzhou",
|
||||
smsProperties.getAccessKeyId(),
|
||||
smsProperties.getAccessKeySecret());
|
||||
DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", "Dypnsapi", "dypnsapi.aliyuncs.com");
|
||||
return new DefaultAcsClient(profile);
|
||||
}
|
||||
}
|
||||
+106
@@ -0,0 +1,106 @@
|
||||
package cn.novalon.gym.manage.auth.dto;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@DisplayName("Auth DTO 单元测试")
|
||||
class DtoValidationTest {
|
||||
|
||||
@Nested
|
||||
@DisplayName("PhoneLoginDto 测试")
|
||||
class PhoneLoginDtoTest {
|
||||
|
||||
@Test
|
||||
@DisplayName("无参构造和setter/getter应正确设置和读取所有字段")
|
||||
void shouldSetAndGetAllFields() {
|
||||
PhoneLoginDto dto = new PhoneLoginDto();
|
||||
|
||||
dto.setPhone("13800138000");
|
||||
dto.setAccessToken("token-abc-123");
|
||||
dto.setOpenid("openid-xyz-456");
|
||||
dto.setNickname("测试用户");
|
||||
dto.setAvatar("https://cdn.example.com/avatar.png");
|
||||
|
||||
assertThat(dto.getPhone()).isEqualTo("13800138000");
|
||||
assertThat(dto.getAccessToken()).isEqualTo("token-abc-123");
|
||||
assertThat(dto.getOpenid()).isEqualTo("openid-xyz-456");
|
||||
assertThat(dto.getNickname()).isEqualTo("测试用户");
|
||||
assertThat(dto.getAvatar()).isEqualTo("https://cdn.example.com/avatar.png");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Builder构造应正确设置所有字段")
|
||||
void shouldBuildCorrectly() {
|
||||
PhoneLoginDto dto = PhoneLoginDto.builder()
|
||||
.phone("13900139000")
|
||||
.accessToken("token-def-456")
|
||||
.openid("openid-ghi-789")
|
||||
.nickname("张三")
|
||||
.avatar("https://cdn.example.com/avatar2.png")
|
||||
.build();
|
||||
|
||||
assertThat(dto.getPhone()).isEqualTo("13900139000");
|
||||
assertThat(dto.getAccessToken()).isEqualTo("token-def-456");
|
||||
assertThat(dto.getOpenid()).isEqualTo("openid-ghi-789");
|
||||
assertThat(dto.getNickname()).isEqualTo("张三");
|
||||
assertThat(dto.getAvatar()).isEqualTo("https://cdn.example.com/avatar2.png");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("PhoneCodeLoginDto 测试")
|
||||
class PhoneCodeLoginDtoTest {
|
||||
|
||||
@Test
|
||||
@DisplayName("无参构造和setter/getter应正确设置和读取所有字段")
|
||||
void shouldSetAndGetAllFields() {
|
||||
PhoneCodeLoginDto dto = new PhoneCodeLoginDto();
|
||||
|
||||
dto.setPhone("15000150000");
|
||||
dto.setCode("123456");
|
||||
|
||||
assertThat(dto.getPhone()).isEqualTo("15000150000");
|
||||
assertThat(dto.getCode()).isEqualTo("123456");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Builder构造应正确设置所有字段")
|
||||
void shouldBuildCorrectly() {
|
||||
PhoneCodeLoginDto dto = PhoneCodeLoginDto.builder()
|
||||
.phone("13700137000")
|
||||
.code("654321")
|
||||
.build();
|
||||
|
||||
assertThat(dto.getPhone()).isEqualTo("13700137000");
|
||||
assertThat(dto.getCode()).isEqualTo("654321");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("SendCodeRequest 测试")
|
||||
class SendCodeRequestTest {
|
||||
|
||||
@Test
|
||||
@DisplayName("无参构造和setter/getter应正确设置和读取phone字段")
|
||||
void shouldSetAndGetPhone() {
|
||||
SendCodeRequest req = new SendCodeRequest();
|
||||
|
||||
req.setPhone("18600186000");
|
||||
|
||||
assertThat(req.getPhone()).isEqualTo("18600186000");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Builder构造应正确设置phone字段")
|
||||
void shouldBuildCorrectly() {
|
||||
SendCodeRequest req = SendCodeRequest.builder()
|
||||
.phone("15900159000")
|
||||
.build();
|
||||
|
||||
assertThat(req.getPhone()).isEqualTo("15900159000");
|
||||
}
|
||||
}
|
||||
}
|
||||
+175
@@ -0,0 +1,175 @@
|
||||
package cn.novalon.gym.manage.auth.handler;
|
||||
|
||||
import cn.novalon.gym.manage.auth.dto.PhoneLoginDto;
|
||||
import cn.novalon.gym.manage.auth.dto.PhoneCodeLoginDto;
|
||||
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.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.HttpStatus;
|
||||
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.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class PhoneAuthHandlerTest {
|
||||
|
||||
@Mock
|
||||
private PhoneAuthService phoneAuthService;
|
||||
|
||||
private PhoneAuthHandler phoneAuthHandler;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
phoneAuthHandler = new PhoneAuthHandler(phoneAuthService);
|
||||
}
|
||||
|
||||
// ==================== oneClickLogin ====================
|
||||
|
||||
@Test
|
||||
void oneClickLogin_shouldReturnOkWithLoginResult() {
|
||||
PhoneLoginVO loginVO = new PhoneLoginVO();
|
||||
loginVO.setAccessToken("test-jwt-token");
|
||||
loginVO.setPhone("13800138000");
|
||||
|
||||
PhoneLoginDto dto = new PhoneLoginDto();
|
||||
dto.setAccessToken("dcloud-access-token");
|
||||
|
||||
when(phoneAuthService.oneClickLogin(any(PhoneLoginDto.class))).thenReturn(Mono.just(loginVO));
|
||||
|
||||
MockServerRequest request = MockServerRequest.builder()
|
||||
.body(Mono.just(dto));
|
||||
|
||||
Mono<ServerResponse> result = phoneAuthHandler.oneClickLogin(request);
|
||||
|
||||
StepVerifier.create(result)
|
||||
.assertNext(response -> assertThat(response.statusCode()).isEqualTo(HttpStatus.OK))
|
||||
.verifyComplete();
|
||||
|
||||
verify(phoneAuthService).oneClickLogin(any(PhoneLoginDto.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void oneClickLogin_shouldPropagateServiceError() {
|
||||
PhoneLoginDto dto = new PhoneLoginDto();
|
||||
dto.setAccessToken("invalid-token");
|
||||
|
||||
when(phoneAuthService.oneClickLogin(any(PhoneLoginDto.class)))
|
||||
.thenReturn(Mono.error(new RuntimeException("Auth failed")));
|
||||
|
||||
MockServerRequest request = MockServerRequest.builder()
|
||||
.body(Mono.just(dto));
|
||||
|
||||
Mono<ServerResponse> result = phoneAuthHandler.oneClickLogin(request);
|
||||
|
||||
StepVerifier.create(result)
|
||||
.expectError(RuntimeException.class)
|
||||
.verify();
|
||||
}
|
||||
|
||||
// ==================== sendSmsCode ====================
|
||||
|
||||
@Test
|
||||
void sendSmsCode_shouldReturnOkWithSuccessTrue() {
|
||||
SendCodeRequest sendCodeRequest = new SendCodeRequest();
|
||||
sendCodeRequest.setPhone("13800138000");
|
||||
|
||||
when(phoneAuthService.sendSmsCode("13800138000")).thenReturn(Mono.just(true));
|
||||
|
||||
MockServerRequest request = MockServerRequest.builder()
|
||||
.body(Mono.just(sendCodeRequest));
|
||||
|
||||
Mono<ServerResponse> result = phoneAuthHandler.sendSmsCode(request);
|
||||
|
||||
StepVerifier.create(result)
|
||||
.assertNext(response -> assertThat(response.statusCode()).isEqualTo(HttpStatus.OK))
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
void sendSmsCode_shouldReturnOkWithSuccessFalseWhenServiceReturnsFalse() {
|
||||
SendCodeRequest sendCodeRequest = new SendCodeRequest();
|
||||
sendCodeRequest.setPhone("13800138000");
|
||||
|
||||
when(phoneAuthService.sendSmsCode("13800138000")).thenReturn(Mono.just(false));
|
||||
|
||||
MockServerRequest request = MockServerRequest.builder()
|
||||
.body(Mono.just(sendCodeRequest));
|
||||
|
||||
Mono<ServerResponse> result = phoneAuthHandler.sendSmsCode(request);
|
||||
|
||||
StepVerifier.create(result)
|
||||
.assertNext(response -> assertThat(response.statusCode()).isEqualTo(HttpStatus.OK))
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
void sendSmsCode_shouldPropagateError() {
|
||||
SendCodeRequest sendCodeRequest = new SendCodeRequest();
|
||||
sendCodeRequest.setPhone("13800138000");
|
||||
|
||||
when(phoneAuthService.sendSmsCode("13800138000"))
|
||||
.thenReturn(Mono.error(new RuntimeException("SMS service unavailable")));
|
||||
|
||||
MockServerRequest request = MockServerRequest.builder()
|
||||
.body(Mono.just(sendCodeRequest));
|
||||
|
||||
Mono<ServerResponse> result = phoneAuthHandler.sendSmsCode(request);
|
||||
|
||||
StepVerifier.create(result)
|
||||
.expectError(RuntimeException.class)
|
||||
.verify();
|
||||
}
|
||||
|
||||
// ==================== codeLogin ====================
|
||||
|
||||
@Test
|
||||
void codeLogin_shouldReturnOkWithLoginResult() {
|
||||
PhoneLoginVO loginVO = new PhoneLoginVO();
|
||||
loginVO.setAccessToken("test-jwt-token");
|
||||
|
||||
PhoneCodeLoginDto dto = new PhoneCodeLoginDto();
|
||||
dto.setPhone("13800138000");
|
||||
dto.setCode("123456");
|
||||
|
||||
when(phoneAuthService.codeLogin(any(PhoneCodeLoginDto.class))).thenReturn(Mono.just(loginVO));
|
||||
|
||||
MockServerRequest request = MockServerRequest.builder()
|
||||
.body(Mono.just(dto));
|
||||
|
||||
Mono<ServerResponse> result = phoneAuthHandler.codeLogin(request);
|
||||
|
||||
StepVerifier.create(result)
|
||||
.assertNext(response -> assertThat(response.statusCode()).isEqualTo(HttpStatus.OK))
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
void codeLogin_shouldPropagateServiceError() {
|
||||
PhoneCodeLoginDto dto = new PhoneCodeLoginDto();
|
||||
dto.setPhone("13800138000");
|
||||
dto.setCode("wrong-code");
|
||||
|
||||
when(phoneAuthService.codeLogin(any(PhoneCodeLoginDto.class)))
|
||||
.thenReturn(Mono.error(new RuntimeException("Invalid code")));
|
||||
|
||||
MockServerRequest request = MockServerRequest.builder()
|
||||
.body(Mono.just(dto));
|
||||
|
||||
Mono<ServerResponse> result = phoneAuthHandler.codeLogin(request);
|
||||
|
||||
StepVerifier.create(result)
|
||||
.expectError(RuntimeException.class)
|
||||
.verify();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
<?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-brand</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>Gym Brand</name>
|
||||
<description>Brand Customization Module - Logo Upload, Color Settings, Real-time Preview</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-sys</artifactId>
|
||||
<version>${project.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-webflux</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springdoc</groupId>
|
||||
<artifactId>springdoc-openapi-starter-webflux-ui</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.projectreactor</groupId>
|
||||
<artifactId>reactor-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<!-- Aliyun OSS SDK -->
|
||||
<dependency>
|
||||
<groupId>com.aliyun.oss</groupId>
|
||||
<artifactId>aliyun-sdk-oss</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-jar-plugin</artifactId>
|
||||
<version>3.4.2</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>default-jar</id>
|
||||
<phase>package</phase>
|
||||
<goals>
|
||||
<goal>jar</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-compiler-plugin</artifactId>
|
||||
<version>3.11.0</version>
|
||||
<configuration>
|
||||
<source>21</source>
|
||||
<target>21</target>
|
||||
<annotationProcessorPaths>
|
||||
<path>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<version>${lombok.version}</version>
|
||||
</path>
|
||||
</annotationProcessorPaths>
|
||||
</configuration>
|
||||
</plugin>
|
||||
<plugin>
|
||||
<groupId>org.jacoco</groupId>
|
||||
<artifactId>jacoco-maven-plugin</artifactId>
|
||||
<version>0.8.12</version>
|
||||
<executions>
|
||||
<execution>
|
||||
<id>prepare-agent</id>
|
||||
<goals>
|
||||
<goal>prepare-agent</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
<execution>
|
||||
<id>report</id>
|
||||
<phase>verify</phase>
|
||||
<goals>
|
||||
<goal>report</goal>
|
||||
</goals>
|
||||
</execution>
|
||||
</executions>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package cn.novalon.gym.manage.brand.config;
|
||||
|
||||
import cn.novalon.gym.manage.brand.websocket.BrandWebSocketHandler;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.Ordered;
|
||||
import org.springframework.web.reactive.HandlerMapping;
|
||||
import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping;
|
||||
import org.springframework.web.reactive.socket.WebSocketHandler;
|
||||
import org.springframework.web.reactive.socket.server.support.WebSocketHandlerAdapter;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 品牌预览 WebSocket 配置
|
||||
*
|
||||
* @author 张翔
|
||||
* @date 2026-07-23
|
||||
*/
|
||||
@Configuration
|
||||
public class BrandWebSocketConfig {
|
||||
|
||||
@Bean
|
||||
public HandlerMapping brandWebSocketHandlerMapping(BrandWebSocketHandler brandWebSocketHandler) {
|
||||
Map<String, WebSocketHandler> map = new HashMap<>();
|
||||
map.put("/ws/brand", brandWebSocketHandler);
|
||||
|
||||
SimpleUrlHandlerMapping handlerMapping = new SimpleUrlHandlerMapping();
|
||||
handlerMapping.setOrder(Ordered.HIGHEST_PRECEDENCE + 1);
|
||||
handlerMapping.setUrlMap(map);
|
||||
return handlerMapping;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public WebSocketHandlerAdapter brandWebSocketHandlerAdapter() {
|
||||
return new WebSocketHandlerAdapter();
|
||||
}
|
||||
}
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
package cn.novalon.gym.manage.brand.config;
|
||||
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 阿里云 OSS 配置属性
|
||||
* <p>
|
||||
* 配置前缀: brand.oss
|
||||
*
|
||||
* @author 张翔
|
||||
* @date 2026-07-23
|
||||
*/
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "brand.oss")
|
||||
public class OssProperties {
|
||||
|
||||
/** 是否启用 OSS(默认关闭,仅使用本地存储) */
|
||||
private boolean enabled = false;
|
||||
|
||||
/** OSS Endpoint(如 oss-cn-hangzhou.aliyuncs.com) */
|
||||
private String endpoint;
|
||||
|
||||
/** AccessKey ID */
|
||||
private String accessKeyId;
|
||||
|
||||
/** AccessKey Secret */
|
||||
private String accessKeySecret;
|
||||
|
||||
/** Bucket 名称 */
|
||||
private String bucketName;
|
||||
|
||||
/** 自定义域名/CDN域名(可选,用于生成访问URL) */
|
||||
private String customDomain;
|
||||
|
||||
/** 文件存储基础路径(默认 brand) */
|
||||
private String basePath = "brand";
|
||||
|
||||
public boolean isEnabled() {
|
||||
return enabled;
|
||||
}
|
||||
|
||||
public void setEnabled(boolean enabled) {
|
||||
this.enabled = enabled;
|
||||
}
|
||||
|
||||
public String getEndpoint() {
|
||||
return endpoint;
|
||||
}
|
||||
|
||||
public void setEndpoint(String endpoint) {
|
||||
this.endpoint = endpoint;
|
||||
}
|
||||
|
||||
public String getAccessKeyId() {
|
||||
return accessKeyId;
|
||||
}
|
||||
|
||||
public void setAccessKeyId(String accessKeyId) {
|
||||
this.accessKeyId = accessKeyId;
|
||||
}
|
||||
|
||||
public String getAccessKeySecret() {
|
||||
return accessKeySecret;
|
||||
}
|
||||
|
||||
public void setAccessKeySecret(String accessKeySecret) {
|
||||
this.accessKeySecret = accessKeySecret;
|
||||
}
|
||||
|
||||
public String getBucketName() {
|
||||
return bucketName;
|
||||
}
|
||||
|
||||
public void setBucketName(String bucketName) {
|
||||
this.bucketName = bucketName;
|
||||
}
|
||||
|
||||
public String getCustomDomain() {
|
||||
return customDomain;
|
||||
}
|
||||
|
||||
public void setCustomDomain(String customDomain) {
|
||||
this.customDomain = customDomain;
|
||||
}
|
||||
|
||||
public String getBasePath() {
|
||||
return basePath;
|
||||
}
|
||||
|
||||
public void setBasePath(String basePath) {
|
||||
this.basePath = basePath;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断 OSS 配置是否完整可用
|
||||
*/
|
||||
public boolean isConfigured() {
|
||||
return enabled
|
||||
&& endpoint != null && !endpoint.isBlank()
|
||||
&& accessKeyId != null && !accessKeyId.isBlank()
|
||||
&& accessKeySecret != null && !accessKeySecret.isBlank()
|
||||
&& bucketName != null && !bucketName.isBlank();
|
||||
}
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package cn.novalon.gym.manage.brand.core.domain;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 品牌配置领域对象
|
||||
*
|
||||
* @author 张翔
|
||||
* @date 2026-07-23
|
||||
*/
|
||||
public class BrandConfig {
|
||||
|
||||
private Long id;
|
||||
private String tenantId;
|
||||
private String logoUrl;
|
||||
private String backgroundImageUrl;
|
||||
private String primaryColor;
|
||||
private String primaryColorRgb;
|
||||
private String secondaryColor;
|
||||
private String secondaryColorRgb;
|
||||
private String fontFamily;
|
||||
private String brandName;
|
||||
private String slogan;
|
||||
private LocalDateTime createdAt;
|
||||
private LocalDateTime updatedAt;
|
||||
private LocalDateTime deletedAt;
|
||||
|
||||
public Long getId() { return id; }
|
||||
public void setId(Long id) { this.id = id; }
|
||||
public String getTenantId() { return tenantId; }
|
||||
public void setTenantId(String tenantId) { this.tenantId = tenantId; }
|
||||
public String getLogoUrl() { return logoUrl; }
|
||||
public void setLogoUrl(String logoUrl) { this.logoUrl = logoUrl; }
|
||||
public String getBackgroundImageUrl() { return backgroundImageUrl; }
|
||||
public void setBackgroundImageUrl(String backgroundImageUrl) { this.backgroundImageUrl = backgroundImageUrl; }
|
||||
public String getPrimaryColor() { return primaryColor; }
|
||||
public void setPrimaryColor(String primaryColor) { this.primaryColor = primaryColor; }
|
||||
public String getPrimaryColorRgb() { return primaryColorRgb; }
|
||||
public void setPrimaryColorRgb(String primaryColorRgb) { this.primaryColorRgb = primaryColorRgb; }
|
||||
public String getSecondaryColor() { return secondaryColor; }
|
||||
public void setSecondaryColor(String secondaryColor) { this.secondaryColor = secondaryColor; }
|
||||
public String getSecondaryColorRgb() { return secondaryColorRgb; }
|
||||
public void setSecondaryColorRgb(String secondaryColorRgb) { this.secondaryColorRgb = secondaryColorRgb; }
|
||||
public String getFontFamily() { return fontFamily; }
|
||||
public void setFontFamily(String fontFamily) { this.fontFamily = fontFamily; }
|
||||
public String getBrandName() { return brandName; }
|
||||
public void setBrandName(String brandName) { this.brandName = brandName; }
|
||||
public String getSlogan() { return slogan; }
|
||||
public void setSlogan(String slogan) { this.slogan = slogan; }
|
||||
public LocalDateTime getCreatedAt() { return createdAt; }
|
||||
public void setCreatedAt(LocalDateTime createdAt) { this.createdAt = createdAt; }
|
||||
public LocalDateTime getUpdatedAt() { return updatedAt; }
|
||||
public void setUpdatedAt(LocalDateTime updatedAt) { this.updatedAt = updatedAt; }
|
||||
public LocalDateTime getDeletedAt() { return deletedAt; }
|
||||
public void setDeletedAt(LocalDateTime deletedAt) { this.deletedAt = deletedAt; }
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package cn.novalon.gym.manage.brand.core.repository;
|
||||
|
||||
import cn.novalon.gym.manage.brand.core.domain.BrandConfig;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
/**
|
||||
* 品牌配置仓储接口
|
||||
*
|
||||
* @author 张翔
|
||||
* @date 2026-07-23
|
||||
*/
|
||||
public interface IBrandConfigRepository {
|
||||
|
||||
Mono<BrandConfig> findByTenantId(String tenantId);
|
||||
|
||||
Mono<BrandConfig> save(BrandConfig brandConfig);
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package cn.novalon.gym.manage.brand.core.service;
|
||||
|
||||
import org.springframework.http.codec.multipart.FilePart;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
/**
|
||||
* 文件存储服务接口(OSS + 本地兜底)
|
||||
*
|
||||
* @author 张翔
|
||||
* @date 2026-07-23
|
||||
*/
|
||||
public interface FileStorageService {
|
||||
|
||||
/**
|
||||
* 上传图片文件,返回访问URL
|
||||
*
|
||||
* @param filePart 文件数据
|
||||
* @param directory 存储目录(如 "logo", "background")
|
||||
* @return 文件访问URL
|
||||
*/
|
||||
Mono<String> uploadImage(FilePart filePart, String directory);
|
||||
|
||||
/**
|
||||
* 根据URL删除文件
|
||||
*/
|
||||
Mono<Void> deleteFile(String fileUrl);
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package cn.novalon.gym.manage.brand.core.service;
|
||||
|
||||
import cn.novalon.gym.manage.brand.core.domain.BrandConfig;
|
||||
import org.springframework.http.codec.multipart.FilePart;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
/**
|
||||
* 品牌配置服务接口
|
||||
*
|
||||
* @author 张翔
|
||||
* @date 2026-07-23
|
||||
*/
|
||||
public interface IBrandConfigService {
|
||||
|
||||
/**
|
||||
* 根据租户ID获取品牌配置
|
||||
*/
|
||||
Mono<BrandConfig> getBrandConfig(String tenantId);
|
||||
|
||||
/**
|
||||
* 上传Logo
|
||||
*/
|
||||
Mono<BrandConfig> uploadLogo(String tenantId, FilePart filePart);
|
||||
|
||||
/**
|
||||
* 上传背景图
|
||||
*/
|
||||
Mono<BrandConfig> uploadBackgroundImage(String tenantId, FilePart filePart);
|
||||
|
||||
/**
|
||||
* 更新品牌配色
|
||||
*/
|
||||
Mono<BrandConfig> updateColorConfig(String tenantId, BrandConfig config);
|
||||
|
||||
/**
|
||||
* 删除Logo(恢复默认)
|
||||
*/
|
||||
Mono<BrandConfig> removeLogo(String tenantId);
|
||||
|
||||
/**
|
||||
* 删除背景图(恢复默认)
|
||||
*/
|
||||
Mono<BrandConfig> removeBackgroundImage(String tenantId);
|
||||
|
||||
/**
|
||||
* 更新品牌信息(名称、口号)
|
||||
*/
|
||||
Mono<BrandConfig> updateBrandInfo(String tenantId, BrandConfig config);
|
||||
}
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
package cn.novalon.gym.manage.brand.core.service.impl;
|
||||
|
||||
import cn.novalon.gym.manage.brand.core.domain.BrandConfig;
|
||||
import cn.novalon.gym.manage.brand.core.repository.IBrandConfigRepository;
|
||||
import cn.novalon.gym.manage.brand.core.service.FileStorageService;
|
||||
import cn.novalon.gym.manage.brand.core.service.IBrandConfigService;
|
||||
import cn.novalon.gym.manage.brand.websocket.BrandWebSocketHandler;
|
||||
import org.springframework.http.codec.multipart.FilePart;
|
||||
import org.springframework.stereotype.Service;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 品牌配置服务实现
|
||||
*
|
||||
* @author 张翔
|
||||
* @date 2026-07-23
|
||||
*/
|
||||
@Service
|
||||
public class BrandConfigServiceImpl implements IBrandConfigService {
|
||||
|
||||
private final IBrandConfigRepository brandConfigRepository;
|
||||
private final FileStorageService fileStorageService;
|
||||
private final BrandWebSocketHandler brandWebSocketHandler;
|
||||
|
||||
public BrandConfigServiceImpl(
|
||||
IBrandConfigRepository brandConfigRepository,
|
||||
FileStorageService fileStorageService,
|
||||
BrandWebSocketHandler brandWebSocketHandler) {
|
||||
this.brandConfigRepository = brandConfigRepository;
|
||||
this.fileStorageService = fileStorageService;
|
||||
this.brandWebSocketHandler = brandWebSocketHandler;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<BrandConfig> getBrandConfig(String tenantId) {
|
||||
return brandConfigRepository.findByTenantId(tenantId)
|
||||
.switchIfEmpty(Mono.defer(() -> createDefaultConfig(tenantId)));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<BrandConfig> uploadLogo(String tenantId, FilePart filePart) {
|
||||
return fileStorageService.uploadImage(filePart, "logo")
|
||||
.flatMap(logoUrl -> getOrCreateConfig(tenantId)
|
||||
.flatMap(config -> {
|
||||
// 删除旧Logo
|
||||
return fileStorageService.deleteFile(config.getLogoUrl())
|
||||
.then(Mono.defer(() -> {
|
||||
config.setLogoUrl(logoUrl);
|
||||
config.setUpdatedAt(LocalDateTime.now());
|
||||
return brandConfigRepository.save(config);
|
||||
}));
|
||||
}))
|
||||
.doOnSuccess(config -> notifyPreviewUpdate(config));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<BrandConfig> uploadBackgroundImage(String tenantId, FilePart filePart) {
|
||||
return fileStorageService.uploadImage(filePart, "background")
|
||||
.flatMap(bgUrl -> getOrCreateConfig(tenantId)
|
||||
.flatMap(config -> {
|
||||
return fileStorageService.deleteFile(config.getBackgroundImageUrl())
|
||||
.then(Mono.defer(() -> {
|
||||
config.setBackgroundImageUrl(bgUrl);
|
||||
config.setUpdatedAt(LocalDateTime.now());
|
||||
return brandConfigRepository.save(config);
|
||||
}));
|
||||
}))
|
||||
.doOnSuccess(config -> notifyPreviewUpdate(config));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<BrandConfig> updateColorConfig(String tenantId, BrandConfig updatedConfig) {
|
||||
return getOrCreateConfig(tenantId)
|
||||
.flatMap(config -> {
|
||||
if (updatedConfig.getPrimaryColor() != null) {
|
||||
config.setPrimaryColor(updatedConfig.getPrimaryColor());
|
||||
}
|
||||
if (updatedConfig.getPrimaryColorRgb() != null) {
|
||||
config.setPrimaryColorRgb(updatedConfig.getPrimaryColorRgb());
|
||||
}
|
||||
if (updatedConfig.getSecondaryColor() != null) {
|
||||
config.setSecondaryColor(updatedConfig.getSecondaryColor());
|
||||
}
|
||||
if (updatedConfig.getSecondaryColorRgb() != null) {
|
||||
config.setSecondaryColorRgb(updatedConfig.getSecondaryColorRgb());
|
||||
}
|
||||
if (updatedConfig.getFontFamily() != null) {
|
||||
config.setFontFamily(updatedConfig.getFontFamily());
|
||||
}
|
||||
config.setUpdatedAt(LocalDateTime.now());
|
||||
return brandConfigRepository.save(config);
|
||||
})
|
||||
.doOnSuccess(config -> notifyPreviewUpdate(config));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<BrandConfig> removeLogo(String tenantId) {
|
||||
return getOrCreateConfig(tenantId)
|
||||
.flatMap(config -> fileStorageService.deleteFile(config.getLogoUrl())
|
||||
.then(Mono.defer(() -> {
|
||||
config.setLogoUrl(null);
|
||||
config.setUpdatedAt(LocalDateTime.now());
|
||||
return brandConfigRepository.save(config);
|
||||
})))
|
||||
.doOnSuccess(config -> notifyPreviewUpdate(config));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<BrandConfig> removeBackgroundImage(String tenantId) {
|
||||
return getOrCreateConfig(tenantId)
|
||||
.flatMap(config -> fileStorageService.deleteFile(config.getBackgroundImageUrl())
|
||||
.then(Mono.defer(() -> {
|
||||
config.setBackgroundImageUrl(null);
|
||||
config.setUpdatedAt(LocalDateTime.now());
|
||||
return brandConfigRepository.save(config);
|
||||
})))
|
||||
.doOnSuccess(config -> notifyPreviewUpdate(config));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<BrandConfig> updateBrandInfo(String tenantId, BrandConfig updatedConfig) {
|
||||
return getOrCreateConfig(tenantId)
|
||||
.flatMap(config -> {
|
||||
if (updatedConfig.getBrandName() != null) {
|
||||
config.setBrandName(updatedConfig.getBrandName());
|
||||
}
|
||||
if (updatedConfig.getSlogan() != null) {
|
||||
config.setSlogan(updatedConfig.getSlogan());
|
||||
}
|
||||
config.setUpdatedAt(LocalDateTime.now());
|
||||
return brandConfigRepository.save(config);
|
||||
})
|
||||
.doOnSuccess(config -> notifyPreviewUpdate(config));
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取或创建品牌配置
|
||||
*/
|
||||
private Mono<BrandConfig> getOrCreateConfig(String tenantId) {
|
||||
return brandConfigRepository.findByTenantId(tenantId)
|
||||
.switchIfEmpty(Mono.defer(() -> createDefaultConfig(tenantId)));
|
||||
}
|
||||
|
||||
/**
|
||||
* 为租户创建默认品牌配置
|
||||
*/
|
||||
private Mono<BrandConfig> createDefaultConfig(String tenantId) {
|
||||
BrandConfig config = new BrandConfig();
|
||||
config.setTenantId(tenantId);
|
||||
config.setPrimaryColor("#00E676");
|
||||
config.setPrimaryColorRgb("0,230,118");
|
||||
config.setSecondaryColor("#1A1A1A");
|
||||
config.setSecondaryColorRgb("26,26,26");
|
||||
config.setFontFamily("default");
|
||||
config.setCreatedAt(LocalDateTime.now());
|
||||
config.setUpdatedAt(LocalDateTime.now());
|
||||
return brandConfigRepository.save(config);
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过WebSocket通知前端预览更新
|
||||
*/
|
||||
private void notifyPreviewUpdate(BrandConfig config) {
|
||||
try {
|
||||
brandWebSocketHandler.broadcastBrandUpdate(config);
|
||||
} catch (Exception e) {
|
||||
System.err.println("Failed to broadcast brand update: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
package cn.novalon.gym.manage.brand.core.service.impl;
|
||||
|
||||
import cn.novalon.gym.manage.brand.config.OssProperties;
|
||||
import cn.novalon.gym.manage.brand.core.service.FileStorageService;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
import org.springframework.http.codec.multipart.FilePart;
|
||||
import org.springframework.stereotype.Service;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
/**
|
||||
* 双轨文件存储服务(OSS 优先 + 本地兜底)
|
||||
* <p>
|
||||
* 作为 FileStorageService 的 @Primary 实现,编排 OSS 和本地存储:
|
||||
* <ul>
|
||||
* <li>上传:优先 OSS,失败则回退到本地存储</li>
|
||||
* <li>删除:同时删除 OSS 和本地副本(尽力而为)</li>
|
||||
* </ul>
|
||||
* 当 OSS 未启用或未配置时,直接使用本地存储。
|
||||
*
|
||||
* @author 张翔
|
||||
* @date 2026-07-23
|
||||
*/
|
||||
@Service
|
||||
@Primary
|
||||
public class DualFileStorageService implements FileStorageService {
|
||||
|
||||
private final FileStorageService ossStorage;
|
||||
private final FileStorageService localStorage;
|
||||
private final OssProperties ossProperties;
|
||||
|
||||
public DualFileStorageService(
|
||||
@Qualifier("ossFileStorage") FileStorageService ossStorage,
|
||||
@Qualifier("localFileStorage") FileStorageService localStorage,
|
||||
OssProperties ossProperties) {
|
||||
this.ossStorage = ossStorage;
|
||||
this.localStorage = localStorage;
|
||||
this.ossProperties = ossProperties;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<String> uploadImage(FilePart filePart, String directory) {
|
||||
if (ossProperties.isConfigured()) {
|
||||
return ossStorage.uploadImage(filePart, directory)
|
||||
.onErrorResume(e -> {
|
||||
System.err.println("OSS upload failed, falling back to local storage: " + e.getMessage());
|
||||
return localStorage.uploadImage(filePart, directory);
|
||||
});
|
||||
}
|
||||
return localStorage.uploadImage(filePart, directory);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Void> deleteFile(String fileUrl) {
|
||||
if (fileUrl == null || fileUrl.isBlank()) {
|
||||
return Mono.empty();
|
||||
}
|
||||
|
||||
// 本地文件总是尝试删除
|
||||
Mono<Void> localDelete = localStorage.deleteFile(fileUrl);
|
||||
|
||||
if (ossProperties.isConfigured()) {
|
||||
// OSS 删除:忽略失败(尽力而为)
|
||||
return ossStorage.deleteFile(fileUrl)
|
||||
.onErrorResume(e -> Mono.empty())
|
||||
.then(localDelete);
|
||||
}
|
||||
|
||||
return localDelete;
|
||||
}
|
||||
}
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
package cn.novalon.gym.manage.brand.core.service.impl;
|
||||
|
||||
import cn.novalon.gym.manage.brand.core.service.FileStorageService;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.http.codec.multipart.FilePart;
|
||||
import org.springframework.stereotype.Service;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* 本地文件存储服务(兜底实现)
|
||||
* <p>
|
||||
* 当 OSS 不可用时,文件存储到服务器本地磁盘。
|
||||
* 文件访问通过 /api/files/preview/ 路径提供。
|
||||
*
|
||||
* @author 张翔
|
||||
* @date 2026-07-23
|
||||
*/
|
||||
@Service("localFileStorage")
|
||||
public class LocalFileStorageService implements FileStorageService {
|
||||
|
||||
private static final Set<String> ALLOWED_EXTENSIONS = Set.of(".png", ".jpg", ".jpeg", ".gif", ".webp");
|
||||
private static final long MAX_FILE_SIZE = 2 * 1024 * 1024; // 2MB
|
||||
|
||||
private final String uploadDir;
|
||||
private final String baseUrl;
|
||||
|
||||
public LocalFileStorageService(
|
||||
@Value("${file.upload.dir:/tmp/uploads}") String uploadDir,
|
||||
@Value("${brand.file.base-url:http://localhost:8084/api/files}") String baseUrl) {
|
||||
this.uploadDir = uploadDir;
|
||||
this.baseUrl = baseUrl;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<String> uploadImage(FilePart filePart, String directory) {
|
||||
String originalFilename = filePart.filename();
|
||||
String fileExtension = getFileExtension(originalFilename);
|
||||
|
||||
if (!ALLOWED_EXTENSIONS.contains(fileExtension.toLowerCase())) {
|
||||
return Mono.error(new IllegalArgumentException(
|
||||
"不支持的文件格式,仅支持 PNG/JPG/JPEG/GIF/WEBP"));
|
||||
}
|
||||
|
||||
String newFileName = directory + "_" + UUID.randomUUID().toString() + fileExtension;
|
||||
Path targetDir = Paths.get(uploadDir, "brand", directory);
|
||||
|
||||
return Mono.fromCallable(() -> {
|
||||
if (!Files.exists(targetDir)) {
|
||||
Files.createDirectories(targetDir);
|
||||
}
|
||||
return targetDir;
|
||||
}).flatMap(dir -> {
|
||||
Path filePath = dir.resolve(newFileName);
|
||||
return filePart.transferTo(filePath.toFile()).thenReturn(filePath);
|
||||
}).flatMap(filePath -> {
|
||||
try {
|
||||
long fileSize = Files.size(filePath);
|
||||
if (fileSize > MAX_FILE_SIZE) {
|
||||
Files.deleteIfExists(filePath);
|
||||
return Mono.error(new IllegalArgumentException("文件大小超过2MB限制"));
|
||||
}
|
||||
String relativePath = "brand/" + directory + "/" + newFileName;
|
||||
return Mono.just(baseUrl + "/preview/" + relativePath);
|
||||
} catch (IOException e) {
|
||||
return Mono.error(e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Void> deleteFile(String fileUrl) {
|
||||
if (fileUrl == null || fileUrl.isBlank()) {
|
||||
return Mono.empty();
|
||||
}
|
||||
return Mono.fromRunnable(() -> {
|
||||
try {
|
||||
String relativePath = extractRelativePath(fileUrl);
|
||||
if (relativePath != null) {
|
||||
Path filePath = Paths.get(uploadDir, relativePath);
|
||||
Files.deleteIfExists(filePath);
|
||||
}
|
||||
} catch (IOException e) {
|
||||
System.err.println("Failed to delete local file: " + fileUrl + ", error: " + e.getMessage());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private String getFileExtension(String filename) {
|
||||
if (filename == null || !filename.contains(".")) {
|
||||
return ".png";
|
||||
}
|
||||
return filename.substring(filename.lastIndexOf("."));
|
||||
}
|
||||
|
||||
private String extractRelativePath(String fileUrl) {
|
||||
if (fileUrl.contains("/files/preview/")) {
|
||||
return fileUrl.substring(fileUrl.indexOf("/files/preview/") + "/files/preview/".length());
|
||||
}
|
||||
if (fileUrl.contains("/files/")) {
|
||||
return fileUrl.substring(fileUrl.indexOf("/files/") + "/files/".length());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+161
@@ -0,0 +1,161 @@
|
||||
package cn.novalon.gym.manage.brand.core.service.impl;
|
||||
|
||||
import cn.novalon.gym.manage.brand.config.OssProperties;
|
||||
import cn.novalon.gym.manage.brand.core.service.FileStorageService;
|
||||
import com.aliyun.oss.OSS;
|
||||
import com.aliyun.oss.OSSClientBuilder;
|
||||
import com.aliyun.oss.model.PutObjectRequest;
|
||||
import org.springframework.http.codec.multipart.FilePart;
|
||||
import org.springframework.stereotype.Service;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.io.File;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* 阿里云 OSS 文件存储服务
|
||||
* <p>
|
||||
* 当 brand.oss.enabled=true 且配置完整时启用,
|
||||
* 将品牌图片上传至阿里云 OSS。
|
||||
*
|
||||
* @author 张翔
|
||||
* @date 2026-07-23
|
||||
*/
|
||||
@Service("ossFileStorage")
|
||||
public class OssFileStorageService implements FileStorageService {
|
||||
|
||||
private static final Set<String> ALLOWED_EXTENSIONS = Set.of(".png", ".jpg", ".jpeg", ".gif", ".webp");
|
||||
private static final long MAX_FILE_SIZE = 2 * 1024 * 1024; // 2MB
|
||||
|
||||
private final OssProperties ossProperties;
|
||||
private OSS ossClient;
|
||||
|
||||
public OssFileStorageService(OssProperties ossProperties) {
|
||||
this.ossProperties = ossProperties;
|
||||
}
|
||||
|
||||
/**
|
||||
* 懒加载 OSS 客户端,避免未配置时启动失败
|
||||
*/
|
||||
private OSS getOssClient() {
|
||||
if (ossClient == null && ossProperties.isConfigured()) {
|
||||
synchronized (this) {
|
||||
if (ossClient == null) {
|
||||
ossClient = new OSSClientBuilder().build(
|
||||
ossProperties.getEndpoint(),
|
||||
ossProperties.getAccessKeyId(),
|
||||
ossProperties.getAccessKeySecret());
|
||||
}
|
||||
}
|
||||
}
|
||||
return ossClient;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<String> uploadImage(FilePart filePart, String directory) {
|
||||
if (getOssClient() == null) {
|
||||
return Mono.error(new IllegalStateException("OSS 未配置或未启用"));
|
||||
}
|
||||
|
||||
String originalFilename = filePart.filename();
|
||||
String fileExtension = getFileExtension(originalFilename);
|
||||
|
||||
if (!ALLOWED_EXTENSIONS.contains(fileExtension.toLowerCase())) {
|
||||
return Mono.error(new IllegalArgumentException(
|
||||
"不支持的文件格式,仅支持 PNG/JPG/JPEG/GIF/WEBP"));
|
||||
}
|
||||
|
||||
String objectName = ossProperties.getBasePath() + "/" + directory + "/"
|
||||
+ directory + "_" + UUID.randomUUID().toString() + fileExtension;
|
||||
String bucketName = ossProperties.getBucketName();
|
||||
|
||||
return Mono.fromCallable(() -> {
|
||||
Path tempFile = Files.createTempFile("oss-upload-", fileExtension);
|
||||
return tempFile;
|
||||
}).flatMap(tempFile -> filePart.transferTo(tempFile.toFile()).thenReturn(tempFile))
|
||||
.flatMap(tempFile -> {
|
||||
try {
|
||||
long fileSize = Files.size(tempFile);
|
||||
if (fileSize > MAX_FILE_SIZE) {
|
||||
Files.deleteIfExists(tempFile);
|
||||
return Mono.error(new IllegalArgumentException("文件大小超过2MB限制"));
|
||||
}
|
||||
|
||||
PutObjectRequest putRequest = new PutObjectRequest(bucketName, objectName, tempFile.toFile());
|
||||
getOssClient().putObject(putRequest);
|
||||
|
||||
// 删除临时文件
|
||||
Files.deleteIfExists(tempFile);
|
||||
|
||||
// 生成访问URL
|
||||
String fileUrl = buildAccessUrl(objectName);
|
||||
return Mono.just(fileUrl);
|
||||
} catch (Exception e) {
|
||||
try {
|
||||
Files.deleteIfExists(tempFile);
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
return Mono.error(new RuntimeException("OSS 上传失败: " + e.getMessage(), e));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Void> deleteFile(String fileUrl) {
|
||||
if (fileUrl == null || fileUrl.isBlank()) {
|
||||
return Mono.empty();
|
||||
}
|
||||
if (getOssClient() == null) {
|
||||
return Mono.empty();
|
||||
}
|
||||
return Mono.fromRunnable(() -> {
|
||||
try {
|
||||
String objectName = extractObjectName(fileUrl);
|
||||
if (objectName != null) {
|
||||
getOssClient().deleteObject(ossProperties.getBucketName(), objectName);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.err.println("Failed to delete OSS file: " + fileUrl + ", error: " + e.getMessage());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建文件访问 URL
|
||||
* 优先使用自定义域名/CDN域名,否则使用 OSS 默认域名
|
||||
*/
|
||||
private String buildAccessUrl(String objectName) {
|
||||
String domain;
|
||||
if (ossProperties.getCustomDomain() != null && !ossProperties.getCustomDomain().isBlank()) {
|
||||
domain = ossProperties.getCustomDomain();
|
||||
if (domain.endsWith("/")) {
|
||||
domain = domain.substring(0, domain.length() - 1);
|
||||
}
|
||||
} else {
|
||||
domain = "https://" + ossProperties.getBucketName() + "." + ossProperties.getEndpoint();
|
||||
}
|
||||
return domain + "/" + objectName;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从文件 URL 中提取 OSS Object Name
|
||||
*/
|
||||
private String extractObjectName(String fileUrl) {
|
||||
String basePath = ossProperties.getBasePath();
|
||||
int idx = fileUrl.indexOf(basePath);
|
||||
if (idx >= 0) {
|
||||
return fileUrl.substring(idx);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private String getFileExtension(String filename) {
|
||||
if (filename == null || !filename.contains(".")) {
|
||||
return ".png";
|
||||
}
|
||||
return filename.substring(filename.lastIndexOf("."));
|
||||
}
|
||||
}
|
||||
+206
@@ -0,0 +1,206 @@
|
||||
package cn.novalon.gym.manage.brand.handler;
|
||||
|
||||
import cn.novalon.gym.manage.brand.core.domain.BrandConfig;
|
||||
import cn.novalon.gym.manage.brand.core.service.IBrandConfigService;
|
||||
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.springframework.http.codec.multipart.FilePart;
|
||||
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.time.LocalDateTime;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 品牌配置 HTTP Handler
|
||||
* <p>
|
||||
* tenantId 从 JWT Token 中提取,不再通过 URL 路径参数传递,
|
||||
* 确保每个用户只能操作自己租户的品牌配置。
|
||||
*
|
||||
* @author 张翔
|
||||
* @date 2026-07-23
|
||||
*/
|
||||
@Component
|
||||
@Tag(name = "品牌定制", description = "Logo上传、背景图上传、品牌配色设置、实时预览")
|
||||
public class BrandConfigHandler {
|
||||
|
||||
private final IBrandConfigService brandConfigService;
|
||||
private final AuthUtil authUtil;
|
||||
|
||||
public BrandConfigHandler(IBrandConfigService brandConfigService, AuthUtil authUtil) {
|
||||
this.brandConfigService = brandConfigService;
|
||||
this.authUtil = authUtil;
|
||||
}
|
||||
|
||||
@Operation(summary = "获取品牌配置", description = "根据当前租户获取品牌配置信息")
|
||||
public Mono<ServerResponse> getBrandConfig(ServerRequest request) {
|
||||
String tenantId = authUtil.getTenantId(request);
|
||||
return brandConfigService.getBrandConfig(tenantId)
|
||||
.flatMap(config -> ServerResponse.ok().bodyValue(config))
|
||||
.switchIfEmpty(ServerResponse.ok().bodyValue(Map.of(
|
||||
"message", "未找到品牌配置,将使用默认配置"
|
||||
)));
|
||||
}
|
||||
|
||||
@Operation(summary = "上传Logo", description = "上传品牌Logo图片,支持PNG/JPG格式,限制2MB以内")
|
||||
public Mono<ServerResponse> uploadLogo(ServerRequest request) {
|
||||
String tenantId = authUtil.getTenantId(request);
|
||||
|
||||
return request.multipartData()
|
||||
.flatMap(multipartData -> {
|
||||
var part = multipartData.getFirst("file");
|
||||
if (part == null) {
|
||||
return ServerResponse.badRequest()
|
||||
.bodyValue(Map.of("code", 400, "message", "未上传文件"));
|
||||
}
|
||||
if (!(part instanceof FilePart filePart)) {
|
||||
return ServerResponse.badRequest()
|
||||
.bodyValue(Map.of("code", 400, "message", "无效的文件格式"));
|
||||
}
|
||||
return brandConfigService.uploadLogo(tenantId, filePart)
|
||||
.flatMap(config -> ServerResponse.ok().bodyValue(config));
|
||||
})
|
||||
.switchIfEmpty(ServerResponse.badRequest()
|
||||
.bodyValue(Map.of("code", 400, "message", "请求数据为空")))
|
||||
.onErrorResume(IllegalArgumentException.class, ex ->
|
||||
ServerResponse.badRequest().bodyValue(Map.of(
|
||||
"code", 400,
|
||||
"message", ex.getMessage()
|
||||
))
|
||||
);
|
||||
}
|
||||
|
||||
@Operation(summary = "上传背景图", description = "上传品牌背景图,支持PNG/JPG格式,限制2MB以内")
|
||||
public Mono<ServerResponse> uploadBackgroundImage(ServerRequest request) {
|
||||
String tenantId = authUtil.getTenantId(request);
|
||||
|
||||
return request.multipartData()
|
||||
.flatMap(multipartData -> {
|
||||
var part = multipartData.getFirst("file");
|
||||
if (part == null) {
|
||||
return ServerResponse.badRequest()
|
||||
.bodyValue(Map.of("code", 400, "message", "未上传文件"));
|
||||
}
|
||||
if (!(part instanceof FilePart filePart)) {
|
||||
return ServerResponse.badRequest()
|
||||
.bodyValue(Map.of("code", 400, "message", "无效的文件格式"));
|
||||
}
|
||||
return brandConfigService.uploadBackgroundImage(tenantId, filePart)
|
||||
.flatMap(config -> ServerResponse.ok().bodyValue(config));
|
||||
})
|
||||
.switchIfEmpty(ServerResponse.badRequest()
|
||||
.bodyValue(Map.of("code", 400, "message", "请求数据为空")))
|
||||
.onErrorResume(IllegalArgumentException.class, ex ->
|
||||
ServerResponse.badRequest().bodyValue(Map.of(
|
||||
"code", 400,
|
||||
"message", ex.getMessage()
|
||||
))
|
||||
);
|
||||
}
|
||||
|
||||
@Operation(summary = "更新品牌配色", description = "设置品牌主色调、辅助色等配色方案")
|
||||
public Mono<ServerResponse> updateColorConfig(ServerRequest request) {
|
||||
String tenantId = authUtil.getTenantId(request);
|
||||
|
||||
return request.bodyToMono(Map.class)
|
||||
.map(this::mapToBrandConfig)
|
||||
.flatMap(config -> brandConfigService.updateColorConfig(tenantId, config))
|
||||
.flatMap(config -> ServerResponse.ok().bodyValue(config))
|
||||
.onErrorResume(IllegalArgumentException.class, ex ->
|
||||
ServerResponse.badRequest().bodyValue(Map.of(
|
||||
"code", 400,
|
||||
"message", ex.getMessage(),
|
||||
"timestamp", LocalDateTime.now()
|
||||
))
|
||||
);
|
||||
}
|
||||
|
||||
@Operation(summary = "删除Logo", description = "删除品牌Logo,恢复默认")
|
||||
public Mono<ServerResponse> removeLogo(ServerRequest request) {
|
||||
String tenantId = authUtil.getTenantId(request);
|
||||
return brandConfigService.removeLogo(tenantId)
|
||||
.flatMap(config -> ServerResponse.ok().bodyValue(config));
|
||||
}
|
||||
|
||||
@Operation(summary = "删除背景图", description = "删除品牌背景图,恢复默认")
|
||||
public Mono<ServerResponse> removeBackgroundImage(ServerRequest request) {
|
||||
String tenantId = authUtil.getTenantId(request);
|
||||
return brandConfigService.removeBackgroundImage(tenantId)
|
||||
.flatMap(config -> ServerResponse.ok().bodyValue(config));
|
||||
}
|
||||
|
||||
@Operation(summary = "更新品牌信息", description = "设置品牌名称和口号")
|
||||
public Mono<ServerResponse> updateBrandInfo(ServerRequest request) {
|
||||
String tenantId = authUtil.getTenantId(request);
|
||||
|
||||
return request.bodyToMono(Map.class)
|
||||
.map(body -> {
|
||||
BrandConfig config = new BrandConfig();
|
||||
if (body.containsKey("brandName")) {
|
||||
String name = (String) body.get("brandName");
|
||||
if (name.length() > 100) {
|
||||
throw new IllegalArgumentException("品牌名称不能超过100个字符");
|
||||
}
|
||||
config.setBrandName(name);
|
||||
}
|
||||
if (body.containsKey("slogan")) {
|
||||
String slogan = (String) body.get("slogan");
|
||||
if (slogan.length() > 200) {
|
||||
throw new IllegalArgumentException("口号不能超过200个字符");
|
||||
}
|
||||
config.setSlogan(slogan);
|
||||
}
|
||||
return config;
|
||||
})
|
||||
.flatMap(config -> brandConfigService.updateBrandInfo(tenantId, config))
|
||||
.flatMap(config -> ServerResponse.ok().bodyValue(config))
|
||||
.onErrorResume(IllegalArgumentException.class, ex ->
|
||||
ServerResponse.badRequest().bodyValue(Map.of(
|
||||
"code", 400,
|
||||
"message", ex.getMessage()
|
||||
))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 将前端传来的 Map 转换为 BrandConfig(仅用于颜色配置)
|
||||
*/
|
||||
private BrandConfig mapToBrandConfig(Map<String, Object> body) {
|
||||
BrandConfig config = new BrandConfig();
|
||||
if (body.containsKey("primaryColor")) {
|
||||
String color = (String) body.get("primaryColor");
|
||||
validateHexColor(color);
|
||||
config.setPrimaryColor(color);
|
||||
}
|
||||
if (body.containsKey("primaryColorRgb")) {
|
||||
config.setPrimaryColorRgb((String) body.get("primaryColorRgb"));
|
||||
}
|
||||
if (body.containsKey("secondaryColor")) {
|
||||
String color = (String) body.get("secondaryColor");
|
||||
validateHexColor(color);
|
||||
config.setSecondaryColor(color);
|
||||
}
|
||||
if (body.containsKey("secondaryColorRgb")) {
|
||||
config.setSecondaryColorRgb((String) body.get("secondaryColorRgb"));
|
||||
}
|
||||
if (body.containsKey("fontFamily")) {
|
||||
config.setFontFamily((String) body.get("fontFamily"));
|
||||
}
|
||||
return config;
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证HEX颜色格式
|
||||
*/
|
||||
private void validateHexColor(String color) {
|
||||
if (color == null) {
|
||||
return;
|
||||
}
|
||||
if (!color.matches("^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$")) {
|
||||
throw new IllegalArgumentException("无效的HEX颜色格式: " + color + ",正确格式如 #1E90FF");
|
||||
}
|
||||
}
|
||||
}
|
||||
+207
@@ -0,0 +1,207 @@
|
||||
package cn.novalon.gym.manage.brand.websocket;
|
||||
|
||||
import cn.novalon.gym.manage.brand.core.domain.BrandConfig;
|
||||
import cn.novalon.gym.manage.sys.security.JwtTokenProvider;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.reactive.socket.WebSocketHandler;
|
||||
import org.springframework.web.reactive.socket.WebSocketSession;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* 品牌配置实时预览 WebSocket 处理器
|
||||
*
|
||||
* @author 张翔
|
||||
* @date 2026-07-23
|
||||
*/
|
||||
@Component
|
||||
public class BrandWebSocketHandler implements WebSocketHandler {
|
||||
|
||||
private final Map<String, WebSocketSession> sessions = new ConcurrentHashMap<>();
|
||||
private final Map<String, LocalDateTime> lastActivityTime = new ConcurrentHashMap<>();
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
private final JwtTokenProvider jwtTokenProvider;
|
||||
|
||||
@Value("${websocket.idle-timeout:300s}")
|
||||
private Duration idleTimeout;
|
||||
|
||||
@Value("${websocket.heartbeat-interval:30s}")
|
||||
private Duration heartbeatInterval;
|
||||
|
||||
public BrandWebSocketHandler(JwtTokenProvider jwtTokenProvider) {
|
||||
this.jwtTokenProvider = jwtTokenProvider;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Void> handle(WebSocketSession session) {
|
||||
String tenantId = extractTenantId(session);
|
||||
sessions.put(tenantId, session);
|
||||
lastActivityTime.put(tenantId, LocalDateTime.now());
|
||||
|
||||
return session.receive()
|
||||
.doOnNext(message -> {
|
||||
String payload = message.getPayloadAsText();
|
||||
handleIncomingMessage(session, tenantId, payload);
|
||||
lastActivityTime.put(tenantId, LocalDateTime.now());
|
||||
})
|
||||
.doOnComplete(() -> {
|
||||
sessions.remove(tenantId);
|
||||
lastActivityTime.remove(tenantId);
|
||||
})
|
||||
.doOnError(error -> {
|
||||
sessions.remove(tenantId);
|
||||
lastActivityTime.remove(tenantId);
|
||||
})
|
||||
.then();
|
||||
}
|
||||
|
||||
@Scheduled(fixedRate = 60000)
|
||||
public void cleanupIdleConnections() {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
lastActivityTime.entrySet().removeIf(entry -> {
|
||||
if (Duration.between(entry.getValue(), now).compareTo(idleTimeout) > 0) {
|
||||
String tenantId = entry.getKey();
|
||||
WebSocketSession session = sessions.remove(tenantId);
|
||||
if (session != null && session.isOpen()) {
|
||||
session.close().subscribe();
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
@Scheduled(fixedRate = 30000)
|
||||
public void sendHeartbeat() {
|
||||
sessions.forEach((tenantId, session) -> {
|
||||
if (session.isOpen()) {
|
||||
try {
|
||||
String heartbeat = objectMapper.writeValueAsString(Map.of(
|
||||
"type", "heartbeat",
|
||||
"timestamp", System.currentTimeMillis()
|
||||
));
|
||||
session.send(Mono.just(session.textMessage(heartbeat))).subscribe();
|
||||
} catch (Exception e) {
|
||||
System.err.println("Brand WS heartbeat error: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 向指定租户推送品牌配置更新
|
||||
*/
|
||||
public void sendBrandUpdate(String tenantId, BrandConfig config) {
|
||||
WebSocketSession session = sessions.get(tenantId);
|
||||
if (session != null && session.isOpen()) {
|
||||
try {
|
||||
Map<String, Object> message = Map.of(
|
||||
"type", "brandUpdate",
|
||||
"data", config,
|
||||
"timestamp", System.currentTimeMillis()
|
||||
);
|
||||
String json = objectMapper.writeValueAsString(message);
|
||||
session.send(Mono.just(session.textMessage(json))).subscribe();
|
||||
} catch (Exception e) {
|
||||
System.err.println("Brand WS send error: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 广播品牌配置更新给所有连接的租户
|
||||
*/
|
||||
public void broadcastBrandUpdate(BrandConfig config) {
|
||||
// 仅推送给对应租户
|
||||
if (config.getTenantId() != null) {
|
||||
sendBrandUpdate(config.getTenantId(), config);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 WebSocket 握手中提取租户ID
|
||||
* <ol>
|
||||
* <li>优先从 Authorization Header 的 JWT Token 中提取</li>
|
||||
* <li>回退到 URL 查询参数 tenantId</li>
|
||||
* <li>兜底使用 session ID</li>
|
||||
* </ol>
|
||||
*/
|
||||
private String extractTenantId(WebSocketSession session) {
|
||||
// 1. 优先从 JWT Token 提取
|
||||
String tenantId = extractTenantIdFromJwt(session);
|
||||
if (tenantId != null) {
|
||||
return tenantId;
|
||||
}
|
||||
|
||||
// 2. 回退到查询参数(兼容旧版)
|
||||
String query = session.getHandshakeInfo().getUri().getQuery();
|
||||
if (query != null && query.contains("tenantId=")) {
|
||||
return query.split("tenantId=")[1].split("&")[0];
|
||||
}
|
||||
|
||||
// 3. 兜底
|
||||
return session.getId();
|
||||
}
|
||||
|
||||
/**
|
||||
* 从 WebSocket 握手的 Authorization Header 中提取 JWT Token 的 tenantId
|
||||
*/
|
||||
private String extractTenantIdFromJwt(WebSocketSession session) {
|
||||
try {
|
||||
var headers = session.getHandshakeInfo().getHeaders();
|
||||
String authHeader = headers.getFirst(HttpHeaders.AUTHORIZATION);
|
||||
if (authHeader != null && authHeader.startsWith("Bearer ")) {
|
||||
String token = authHeader.substring(7);
|
||||
if (jwtTokenProvider.validateToken(token)) {
|
||||
return jwtTokenProvider.getTenantIdFromToken(token);
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.err.println("Brand WS: Failed to extract tenantId from JWT: " + e.getMessage());
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private void handleIncomingMessage(WebSocketSession session, String tenantId, String payload) {
|
||||
try {
|
||||
Map<String, Object> message = objectMapper.readValue(payload,
|
||||
new TypeReference<Map<String, Object>>() {});
|
||||
String type = (String) message.get("type");
|
||||
|
||||
switch (type) {
|
||||
case "ping":
|
||||
sendPong(session);
|
||||
break;
|
||||
case "subscribe":
|
||||
sessions.put(tenantId, session);
|
||||
lastActivityTime.put(tenantId, LocalDateTime.now());
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.err.println("Brand WS message error: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void sendPong(WebSocketSession session) {
|
||||
try {
|
||||
String pong = objectMapper.writeValueAsString(Map.of(
|
||||
"type", "pong",
|
||||
"timestamp", System.currentTimeMillis()
|
||||
));
|
||||
session.send(Mono.just(session.textMessage(pong))).subscribe();
|
||||
} catch (Exception e) {
|
||||
System.err.println("Brand WS pong error: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
@@ -0,0 +1 @@
|
||||
cn.novalon.gym.manage.brand.config.BrandWebSocketConfig
|
||||
+296
@@ -0,0 +1,296 @@
|
||||
package cn.novalon.gym.manage.brand.core.service.impl;
|
||||
|
||||
import cn.novalon.gym.manage.brand.core.domain.BrandConfig;
|
||||
import cn.novalon.gym.manage.brand.core.repository.IBrandConfigRepository;
|
||||
import cn.novalon.gym.manage.brand.core.service.FileStorageService;
|
||||
import cn.novalon.gym.manage.brand.websocket.BrandWebSocketHandler;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.codec.multipart.FilePart;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.test.StepVerifier;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class BrandConfigServiceImplTest {
|
||||
|
||||
@Mock
|
||||
private IBrandConfigRepository brandConfigRepository;
|
||||
|
||||
@Mock
|
||||
private FileStorageService fileStorageService;
|
||||
|
||||
@Mock
|
||||
private BrandWebSocketHandler brandWebSocketHandler;
|
||||
|
||||
@Mock
|
||||
private FilePart filePart;
|
||||
|
||||
private BrandConfigServiceImpl brandConfigService;
|
||||
|
||||
private static final String TENANT_ID = "tenant-001";
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
brandConfigService = new BrandConfigServiceImpl(
|
||||
brandConfigRepository, fileStorageService, brandWebSocketHandler);
|
||||
}
|
||||
|
||||
// ==================== getBrandConfig ====================
|
||||
|
||||
@Test
|
||||
void getBrandConfig_shouldReturnExistingConfig() {
|
||||
BrandConfig existingConfig = createTestConfig();
|
||||
when(brandConfigRepository.findByTenantId(TENANT_ID)).thenReturn(Mono.just(existingConfig));
|
||||
|
||||
Mono<BrandConfig> result = brandConfigService.getBrandConfig(TENANT_ID);
|
||||
|
||||
StepVerifier.create(result)
|
||||
.assertNext(config -> {
|
||||
assertThat(config).isNotNull();
|
||||
assertThat(config.getTenantId()).isEqualTo(TENANT_ID);
|
||||
assertThat(config.getPrimaryColor()).isEqualTo("#00E676");
|
||||
})
|
||||
.verifyComplete();
|
||||
|
||||
verify(brandConfigRepository).findByTenantId(TENANT_ID);
|
||||
verify(brandConfigRepository, never()).save(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getBrandConfig_shouldCreateDefaultWhenNotFound() {
|
||||
when(brandConfigRepository.findByTenantId(TENANT_ID)).thenReturn(Mono.empty());
|
||||
when(brandConfigRepository.save(any(BrandConfig.class)))
|
||||
.thenAnswer(invocation -> Mono.just(invocation.getArgument(0)));
|
||||
|
||||
Mono<BrandConfig> result = brandConfigService.getBrandConfig(TENANT_ID);
|
||||
|
||||
StepVerifier.create(result)
|
||||
.assertNext(config -> {
|
||||
assertThat(config.getTenantId()).isEqualTo(TENANT_ID);
|
||||
assertThat(config.getPrimaryColor()).isEqualTo("#00E676");
|
||||
assertThat(config.getPrimaryColorRgb()).isEqualTo("0,230,118");
|
||||
assertThat(config.getSecondaryColor()).isEqualTo("#1A1A1A");
|
||||
assertThat(config.getLogoUrl()).isNull();
|
||||
})
|
||||
.verifyComplete();
|
||||
|
||||
verify(brandConfigRepository).findByTenantId(TENANT_ID);
|
||||
verify(brandConfigRepository).save(any(BrandConfig.class));
|
||||
}
|
||||
|
||||
// ==================== uploadLogo ====================
|
||||
|
||||
@Test
|
||||
void uploadLogo_shouldUploadAndSaveConfig() {
|
||||
BrandConfig existingConfig = createTestConfig();
|
||||
String newLogoUrl = "https://example.com/new-logo.png";
|
||||
|
||||
lenient().when(brandConfigRepository.findByTenantId(TENANT_ID))
|
||||
.thenReturn(Mono.just(existingConfig));
|
||||
when(fileStorageService.uploadImage(filePart, "logo")).thenReturn(Mono.just(newLogoUrl));
|
||||
when(fileStorageService.deleteFile("https://example.com/logo.png")).thenReturn(Mono.empty());
|
||||
when(brandConfigRepository.save(any(BrandConfig.class)))
|
||||
.thenAnswer(invocation -> Mono.just(invocation.getArgument(0)));
|
||||
|
||||
Mono<BrandConfig> result = brandConfigService.uploadLogo(TENANT_ID, filePart);
|
||||
|
||||
StepVerifier.create(result)
|
||||
.assertNext(config -> {
|
||||
assertThat(config.getLogoUrl()).isEqualTo(newLogoUrl);
|
||||
})
|
||||
.verifyComplete();
|
||||
|
||||
verify(fileStorageService).uploadImage(filePart, "logo");
|
||||
verify(brandConfigRepository, atLeastOnce()).save(any(BrandConfig.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void uploadLogo_shouldCreateConfigWhenTenantNotFound() {
|
||||
String newLogoUrl = "https://example.com/new-logo.png";
|
||||
|
||||
lenient().when(brandConfigRepository.findByTenantId(TENANT_ID)).thenReturn(Mono.empty());
|
||||
when(fileStorageService.uploadImage(filePart, "logo")).thenReturn(Mono.just(newLogoUrl));
|
||||
lenient().when(fileStorageService.deleteFile(any())).thenReturn(Mono.empty());
|
||||
when(brandConfigRepository.save(any(BrandConfig.class)))
|
||||
.thenAnswer(invocation -> Mono.just(invocation.getArgument(0)));
|
||||
|
||||
Mono<BrandConfig> result = brandConfigService.uploadLogo(TENANT_ID, filePart);
|
||||
|
||||
StepVerifier.create(result)
|
||||
.assertNext(config -> {
|
||||
assertThat(config.getLogoUrl()).isEqualTo(newLogoUrl);
|
||||
assertThat(config.getTenantId()).isEqualTo(TENANT_ID);
|
||||
})
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
void uploadLogo_shouldPropagateStorageError() {
|
||||
BrandConfig existingConfig = createTestConfig();
|
||||
|
||||
lenient().when(brandConfigRepository.findByTenantId(TENANT_ID))
|
||||
.thenReturn(Mono.just(existingConfig));
|
||||
when(fileStorageService.uploadImage(filePart, "logo"))
|
||||
.thenReturn(Mono.error(new RuntimeException("Storage error")));
|
||||
|
||||
Mono<BrandConfig> result = brandConfigService.uploadLogo(TENANT_ID, filePart);
|
||||
|
||||
StepVerifier.create(result)
|
||||
.expectError(RuntimeException.class)
|
||||
.verify();
|
||||
}
|
||||
|
||||
// ==================== uploadBackgroundImage ====================
|
||||
|
||||
@Test
|
||||
void uploadBackgroundImage_shouldUploadAndSaveConfig() {
|
||||
BrandConfig existingConfig = createTestConfig();
|
||||
String newBgUrl = "https://example.com/new-bg.png";
|
||||
|
||||
lenient().when(brandConfigRepository.findByTenantId(TENANT_ID))
|
||||
.thenReturn(Mono.just(existingConfig));
|
||||
when(fileStorageService.uploadImage(filePart, "background")).thenReturn(Mono.just(newBgUrl));
|
||||
lenient().when(fileStorageService.deleteFile(anyString())).thenReturn(Mono.empty());
|
||||
when(brandConfigRepository.save(any(BrandConfig.class)))
|
||||
.thenAnswer(invocation -> Mono.just(invocation.getArgument(0)));
|
||||
|
||||
Mono<BrandConfig> result = brandConfigService.uploadBackgroundImage(TENANT_ID, filePart);
|
||||
|
||||
StepVerifier.create(result)
|
||||
.assertNext(config -> {
|
||||
assertThat(config.getBackgroundImageUrl()).isEqualTo(newBgUrl);
|
||||
})
|
||||
.verifyComplete();
|
||||
|
||||
verify(fileStorageService).uploadImage(filePart, "background");
|
||||
}
|
||||
|
||||
// ==================== updateColorConfig ====================
|
||||
|
||||
@Test
|
||||
void updateColorConfig_shouldUpdateAllColorFields() {
|
||||
BrandConfig existingConfig = createTestConfig();
|
||||
|
||||
BrandConfig updateConfig = new BrandConfig();
|
||||
updateConfig.setPrimaryColor("#FF0000");
|
||||
updateConfig.setPrimaryColorRgb("255,0,0");
|
||||
updateConfig.setSecondaryColor("#00FF00");
|
||||
updateConfig.setSecondaryColorRgb("0,255,0");
|
||||
updateConfig.setFontFamily("Arial");
|
||||
|
||||
lenient().when(brandConfigRepository.findByTenantId(TENANT_ID))
|
||||
.thenReturn(Mono.just(existingConfig));
|
||||
when(brandConfigRepository.save(any(BrandConfig.class)))
|
||||
.thenAnswer(invocation -> Mono.just(invocation.getArgument(0)));
|
||||
|
||||
Mono<BrandConfig> result = brandConfigService.updateColorConfig(TENANT_ID, updateConfig);
|
||||
|
||||
StepVerifier.create(result)
|
||||
.assertNext(config -> {
|
||||
assertThat(config.getPrimaryColor()).isEqualTo("#FF0000");
|
||||
assertThat(config.getPrimaryColorRgb()).isEqualTo("255,0,0");
|
||||
assertThat(config.getSecondaryColor()).isEqualTo("#00FF00");
|
||||
assertThat(config.getSecondaryColorRgb()).isEqualTo("0,255,0");
|
||||
assertThat(config.getFontFamily()).isEqualTo("Arial");
|
||||
})
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateColorConfig_shouldOnlyUpdateProvidedFields() {
|
||||
BrandConfig existingConfig = createTestConfig();
|
||||
|
||||
BrandConfig updateConfig = new BrandConfig();
|
||||
updateConfig.setPrimaryColor("#FF0000");
|
||||
|
||||
lenient().when(brandConfigRepository.findByTenantId(TENANT_ID))
|
||||
.thenReturn(Mono.just(existingConfig));
|
||||
when(brandConfigRepository.save(any(BrandConfig.class)))
|
||||
.thenAnswer(invocation -> Mono.just(invocation.getArgument(0)));
|
||||
|
||||
Mono<BrandConfig> result = brandConfigService.updateColorConfig(TENANT_ID, updateConfig);
|
||||
|
||||
StepVerifier.create(result)
|
||||
.assertNext(config -> {
|
||||
assertThat(config.getPrimaryColor()).isEqualTo("#FF0000");
|
||||
assertThat(config.getSecondaryColor()).isEqualTo("#1A1A1A"); // unchanged
|
||||
assertThat(config.getLogoUrl()).isEqualTo("https://example.com/logo.png"); // unchanged
|
||||
})
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
// ==================== removeLogo ====================
|
||||
|
||||
@Test
|
||||
void removeLogo_shouldClearLogoUrl() {
|
||||
BrandConfig existingConfig = createTestConfig();
|
||||
|
||||
lenient().when(brandConfigRepository.findByTenantId(TENANT_ID))
|
||||
.thenReturn(Mono.just(existingConfig));
|
||||
when(fileStorageService.deleteFile("https://example.com/logo.png")).thenReturn(Mono.empty());
|
||||
when(brandConfigRepository.save(any(BrandConfig.class)))
|
||||
.thenAnswer(invocation -> Mono.just(invocation.getArgument(0)));
|
||||
|
||||
Mono<BrandConfig> result = brandConfigService.removeLogo(TENANT_ID);
|
||||
|
||||
StepVerifier.create(result)
|
||||
.assertNext(config -> {
|
||||
assertThat(config.getLogoUrl()).isNull();
|
||||
})
|
||||
.verifyComplete();
|
||||
|
||||
verify(fileStorageService).deleteFile("https://example.com/logo.png");
|
||||
}
|
||||
|
||||
// ==================== removeBackgroundImage ====================
|
||||
|
||||
@Test
|
||||
void removeBackgroundImage_shouldClearBackgroundImageUrl() {
|
||||
BrandConfig existingConfig = createTestConfig();
|
||||
|
||||
lenient().when(brandConfigRepository.findByTenantId(TENANT_ID))
|
||||
.thenReturn(Mono.just(existingConfig));
|
||||
when(fileStorageService.deleteFile("https://example.com/bg.png")).thenReturn(Mono.empty());
|
||||
when(brandConfigRepository.save(any(BrandConfig.class)))
|
||||
.thenAnswer(invocation -> Mono.just(invocation.getArgument(0)));
|
||||
|
||||
Mono<BrandConfig> result = brandConfigService.removeBackgroundImage(TENANT_ID);
|
||||
|
||||
StepVerifier.create(result)
|
||||
.assertNext(config -> {
|
||||
assertThat(config.getBackgroundImageUrl()).isNull();
|
||||
})
|
||||
.verifyComplete();
|
||||
|
||||
verify(fileStorageService).deleteFile("https://example.com/bg.png");
|
||||
}
|
||||
|
||||
// ==================== helper ====================
|
||||
|
||||
private BrandConfig createTestConfig() {
|
||||
BrandConfig config = new BrandConfig();
|
||||
config.setId(1L);
|
||||
config.setTenantId(TENANT_ID);
|
||||
config.setLogoUrl("https://example.com/logo.png");
|
||||
config.setBackgroundImageUrl("https://example.com/bg.png");
|
||||
config.setPrimaryColor("#00E676");
|
||||
config.setPrimaryColorRgb("0,230,118");
|
||||
config.setSecondaryColor("#1A1A1A");
|
||||
config.setSecondaryColorRgb("26,26,26");
|
||||
config.setFontFamily("default");
|
||||
config.setCreatedAt(LocalDateTime.now());
|
||||
config.setUpdatedAt(LocalDateTime.now());
|
||||
return config;
|
||||
}
|
||||
}
|
||||
+170
@@ -0,0 +1,170 @@
|
||||
package cn.novalon.gym.manage.brand.core.service.impl;
|
||||
|
||||
import cn.novalon.gym.manage.brand.config.OssProperties;
|
||||
import cn.novalon.gym.manage.brand.core.service.FileStorageService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.codec.multipart.FilePart;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.test.StepVerifier;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class DualFileStorageServiceTest {
|
||||
|
||||
@Mock
|
||||
private FileStorageService ossStorage;
|
||||
|
||||
@Mock
|
||||
private FileStorageService localStorage;
|
||||
|
||||
@Mock
|
||||
private FilePart filePart;
|
||||
|
||||
private OssProperties ossProperties;
|
||||
private DualFileStorageService dualService;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
ossProperties = new OssProperties();
|
||||
// 默认不启用 OSS
|
||||
ossProperties.setEnabled(false);
|
||||
dualService = new DualFileStorageService(ossStorage, localStorage, ossProperties);
|
||||
}
|
||||
|
||||
// ==================== OSS 未启用时,直接走本地存储 ====================
|
||||
|
||||
@Test
|
||||
void shouldUseLocalStorageWhenOssDisabled() {
|
||||
String localUrl = "http://localhost:8080/api/files/preview/brand/logo/logo_test.png";
|
||||
when(localStorage.uploadImage(filePart, "logo")).thenReturn(Mono.just(localUrl));
|
||||
|
||||
Mono<String> result = dualService.uploadImage(filePart, "logo");
|
||||
|
||||
StepVerifier.create(result)
|
||||
.assertNext(url -> assertThat(url).isEqualTo(localUrl))
|
||||
.verifyComplete();
|
||||
|
||||
verify(localStorage).uploadImage(filePart, "logo");
|
||||
verify(ossStorage, never()).uploadImage(any(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldDeleteFromLocalOnlyWhenOssDisabled() {
|
||||
String fileUrl = "http://localhost/api/files/preview/brand/logo/test.png";
|
||||
when(localStorage.deleteFile(fileUrl)).thenReturn(Mono.empty());
|
||||
|
||||
Mono<Void> result = dualService.deleteFile(fileUrl);
|
||||
|
||||
StepVerifier.create(result).verifyComplete();
|
||||
|
||||
verify(localStorage).deleteFile(fileUrl);
|
||||
verify(ossStorage, never()).deleteFile(anyString());
|
||||
}
|
||||
|
||||
// ==================== OSS 启用时,优先 OSS ====================
|
||||
|
||||
@Test
|
||||
void shouldUseOssWhenEnabledAndConfigured() {
|
||||
configureOss();
|
||||
String ossUrl = "https://my-bucket.oss-cn-hangzhou.aliyuncs.com/brand/logo/logo_test.png";
|
||||
when(ossStorage.uploadImage(filePart, "logo")).thenReturn(Mono.just(ossUrl));
|
||||
|
||||
Mono<String> result = dualService.uploadImage(filePart, "logo");
|
||||
|
||||
StepVerifier.create(result)
|
||||
.assertNext(url -> assertThat(url).isEqualTo(ossUrl))
|
||||
.verifyComplete();
|
||||
|
||||
verify(ossStorage).uploadImage(filePart, "logo");
|
||||
verify(localStorage, never()).uploadImage(any(), anyString());
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldFallbackToLocalWhenOssFails() {
|
||||
configureOss();
|
||||
String localUrl = "http://localhost:8080/api/files/preview/brand/logo/logo_fallback.png";
|
||||
when(ossStorage.uploadImage(filePart, "logo"))
|
||||
.thenReturn(Mono.error(new RuntimeException("OSS unavailable")));
|
||||
when(localStorage.uploadImage(filePart, "logo")).thenReturn(Mono.just(localUrl));
|
||||
|
||||
Mono<String> result = dualService.uploadImage(filePart, "logo");
|
||||
|
||||
StepVerifier.create(result)
|
||||
.assertNext(url -> assertThat(url).isEqualTo(localUrl))
|
||||
.verifyComplete();
|
||||
|
||||
verify(ossStorage).uploadImage(filePart, "logo");
|
||||
verify(localStorage).uploadImage(filePart, "logo");
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldDeleteFromBothWhenOssEnabled() {
|
||||
configureOss();
|
||||
String fileUrl = "https://my-bucket.oss-cn-hangzhou.aliyuncs.com/brand/logo/test.png";
|
||||
when(ossStorage.deleteFile(fileUrl)).thenReturn(Mono.empty());
|
||||
when(localStorage.deleteFile(fileUrl)).thenReturn(Mono.empty());
|
||||
|
||||
Mono<Void> result = dualService.deleteFile(fileUrl);
|
||||
|
||||
StepVerifier.create(result).verifyComplete();
|
||||
|
||||
verify(ossStorage).deleteFile(fileUrl);
|
||||
verify(localStorage).deleteFile(fileUrl);
|
||||
}
|
||||
|
||||
@Test
|
||||
void shouldDeleteLocalEvenWhenOssDeleteFails() {
|
||||
configureOss();
|
||||
String fileUrl = "https://my-bucket.oss-cn-hangzhou.aliyuncs.com/brand/logo/test.png";
|
||||
when(ossStorage.deleteFile(fileUrl))
|
||||
.thenReturn(Mono.error(new RuntimeException("OSS delete failed")));
|
||||
when(localStorage.deleteFile(fileUrl)).thenReturn(Mono.empty());
|
||||
|
||||
Mono<Void> result = dualService.deleteFile(fileUrl);
|
||||
|
||||
StepVerifier.create(result).verifyComplete();
|
||||
|
||||
verify(ossStorage).deleteFile(fileUrl);
|
||||
verify(localStorage).deleteFile(fileUrl);
|
||||
}
|
||||
|
||||
// ==================== 边界情况 ====================
|
||||
|
||||
@Test
|
||||
void deleteFile_shouldHandleNullUrl() {
|
||||
Mono<Void> result = dualService.deleteFile(null);
|
||||
|
||||
StepVerifier.create(result).verifyComplete();
|
||||
|
||||
verify(localStorage, never()).deleteFile(any());
|
||||
verify(ossStorage, never()).deleteFile(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteFile_shouldHandleEmptyUrl() {
|
||||
Mono<Void> result = dualService.deleteFile("");
|
||||
|
||||
StepVerifier.create(result).verifyComplete();
|
||||
|
||||
verify(localStorage, never()).deleteFile(any());
|
||||
verify(ossStorage, never()).deleteFile(any());
|
||||
}
|
||||
|
||||
// ==================== helper ====================
|
||||
|
||||
private void configureOss() {
|
||||
ossProperties.setEnabled(true);
|
||||
ossProperties.setEndpoint("oss-cn-hangzhou.aliyuncs.com");
|
||||
ossProperties.setAccessKeyId("test-access-key");
|
||||
ossProperties.setAccessKeySecret("test-access-secret");
|
||||
ossProperties.setBucketName("test-bucket");
|
||||
}
|
||||
}
|
||||
+182
@@ -0,0 +1,182 @@
|
||||
package cn.novalon.gym.manage.brand.core.service.impl;
|
||||
|
||||
import cn.novalon.gym.manage.brand.core.service.FileStorageService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.codec.multipart.FilePart;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.test.StepVerifier;
|
||||
|
||||
import java.io.File;
|
||||
import java.nio.file.Path;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class LocalFileStorageServiceTest {
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
@Mock
|
||||
private FilePart filePart;
|
||||
|
||||
private FileStorageService localStorageService;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
String uploadDir = tempDir.toString();
|
||||
String baseUrl = "http://localhost:8080/api/files";
|
||||
localStorageService = new LocalFileStorageService(uploadDir, baseUrl);
|
||||
}
|
||||
|
||||
@Test
|
||||
void uploadImage_shouldAcceptAndSaveValidFiles() {
|
||||
when(filePart.filename()).thenReturn("test-logo.png");
|
||||
when(filePart.transferTo(any(File.class))).thenAnswer(invocation -> {
|
||||
File targetFile = invocation.getArgument(0);
|
||||
targetFile.createNewFile();
|
||||
return Mono.empty();
|
||||
});
|
||||
|
||||
Mono<String> result = localStorageService.uploadImage(filePart, "logo");
|
||||
|
||||
StepVerifier.create(result)
|
||||
.assertNext(url -> {
|
||||
assertThat(url).contains("brand/logo/logo_");
|
||||
assertThat(url).endsWith(".png");
|
||||
})
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
void uploadImage_shouldRejectInvalidFormat() {
|
||||
when(filePart.filename()).thenReturn("document.pdf");
|
||||
|
||||
Mono<String> result = localStorageService.uploadImage(filePart, "logo");
|
||||
|
||||
StepVerifier.create(result)
|
||||
.expectError(IllegalArgumentException.class)
|
||||
.verify();
|
||||
}
|
||||
|
||||
@Test
|
||||
void uploadImage_shouldRejectTxtFormat() {
|
||||
when(filePart.filename()).thenReturn("script.txt");
|
||||
|
||||
Mono<String> result = localStorageService.uploadImage(filePart, "logo");
|
||||
|
||||
StepVerifier.create(result)
|
||||
.expectError(IllegalArgumentException.class)
|
||||
.verify();
|
||||
}
|
||||
|
||||
@Test
|
||||
void uploadImage_shouldRejectBatchFormat() {
|
||||
when(filePart.filename()).thenReturn("file.bat");
|
||||
|
||||
Mono<String> result = localStorageService.uploadImage(filePart, "logo");
|
||||
|
||||
StepVerifier.create(result)
|
||||
.expectError(IllegalArgumentException.class)
|
||||
.verify();
|
||||
}
|
||||
|
||||
@Test
|
||||
void uploadImage_shouldHandleNoExtensionAsPng() {
|
||||
when(filePart.filename()).thenReturn("noextension");
|
||||
when(filePart.transferTo(any(File.class))).thenAnswer(invocation -> {
|
||||
File targetFile = invocation.getArgument(0);
|
||||
targetFile.createNewFile();
|
||||
return Mono.empty();
|
||||
});
|
||||
|
||||
Mono<String> result = localStorageService.uploadImage(filePart, "logo");
|
||||
|
||||
StepVerifier.create(result)
|
||||
.assertNext(url -> {
|
||||
assertThat(url).endsWith(".png");
|
||||
})
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
void uploadImage_shouldGenerateCorrectUrlFormat() {
|
||||
when(filePart.filename()).thenReturn("company-logo.png");
|
||||
when(filePart.transferTo(any(File.class))).thenAnswer(invocation -> {
|
||||
File targetFile = invocation.getArgument(0);
|
||||
targetFile.createNewFile();
|
||||
return Mono.empty();
|
||||
});
|
||||
|
||||
Mono<String> result = localStorageService.uploadImage(filePart, "logo");
|
||||
|
||||
StepVerifier.create(result)
|
||||
.assertNext(url -> {
|
||||
assertThat(url).startsWith("http://localhost:8080/api/files/preview/brand/logo/");
|
||||
})
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
void uploadImage_shouldUseCorrectDirectory() {
|
||||
when(filePart.filename()).thenReturn("bg.png");
|
||||
when(filePart.transferTo(any(File.class))).thenAnswer(invocation -> {
|
||||
File targetFile = invocation.getArgument(0);
|
||||
targetFile.createNewFile();
|
||||
return Mono.empty();
|
||||
});
|
||||
|
||||
Mono<String> result = localStorageService.uploadImage(filePart, "background");
|
||||
|
||||
StepVerifier.create(result)
|
||||
.assertNext(url -> {
|
||||
assertThat(url).contains("brand/background/background_");
|
||||
})
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
void uploadImage_shouldHandleTransferError() {
|
||||
when(filePart.filename()).thenReturn("logo.png");
|
||||
when(filePart.transferTo(any(File.class)))
|
||||
.thenReturn(Mono.error(new RuntimeException("Transfer failed")));
|
||||
|
||||
Mono<String> result = localStorageService.uploadImage(filePart, "logo");
|
||||
|
||||
StepVerifier.create(result)
|
||||
.expectError(RuntimeException.class)
|
||||
.verify();
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteFile_shouldNotThrowForNullUrl() {
|
||||
Mono<Void> result = localStorageService.deleteFile(null);
|
||||
|
||||
StepVerifier.create(result)
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteFile_shouldNotThrowForEmptyUrl() {
|
||||
Mono<Void> result = localStorageService.deleteFile("");
|
||||
|
||||
StepVerifier.create(result)
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteFile_shouldNotThrowForNonExistentFile() {
|
||||
Mono<Void> result = localStorageService.deleteFile(
|
||||
"http://localhost:8080/api/files/preview/brand/logo/nonexistent.png");
|
||||
|
||||
StepVerifier.create(result)
|
||||
.verifyComplete();
|
||||
}
|
||||
}
|
||||
+209
@@ -0,0 +1,209 @@
|
||||
package cn.novalon.gym.manage.brand.handler;
|
||||
|
||||
import cn.novalon.gym.manage.brand.core.domain.BrandConfig;
|
||||
import cn.novalon.gym.manage.brand.core.service.IBrandConfigService;
|
||||
import cn.novalon.gym.manage.sys.util.AuthUtil;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.HttpStatus;
|
||||
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 java.time.LocalDateTime;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class BrandConfigHandlerTest {
|
||||
|
||||
@Mock
|
||||
private IBrandConfigService brandConfigService;
|
||||
|
||||
@Mock
|
||||
private AuthUtil authUtil;
|
||||
|
||||
private BrandConfigHandler brandConfigHandler;
|
||||
|
||||
private static final String TENANT_ID = "tenant-001";
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
brandConfigHandler = new BrandConfigHandler(brandConfigService, authUtil);
|
||||
}
|
||||
|
||||
private MockServerRequest.Builder mockRequest() {
|
||||
return MockServerRequest.builder()
|
||||
.header("X-Tenant-Id", "tenant-001");
|
||||
}
|
||||
|
||||
// ==================== getBrandConfig ====================
|
||||
|
||||
@Test
|
||||
void getBrandConfig_shouldReturnConfig() {
|
||||
BrandConfig config = createTestConfig();
|
||||
when(authUtil.getTenantId(any())).thenReturn(TENANT_ID);
|
||||
when(brandConfigService.getBrandConfig(TENANT_ID)).thenReturn(Mono.just(config));
|
||||
|
||||
MockServerRequest request = mockRequest().build();
|
||||
Mono<ServerResponse> result = brandConfigHandler.getBrandConfig(request);
|
||||
|
||||
StepVerifier.create(result)
|
||||
.assertNext(response -> assertThat(response.statusCode()).isEqualTo(HttpStatus.OK))
|
||||
.verifyComplete();
|
||||
|
||||
verify(brandConfigService).getBrandConfig(TENANT_ID);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getBrandConfig_shouldReturnOkEvenWhenNotFound() {
|
||||
when(authUtil.getTenantId(any())).thenReturn(TENANT_ID);
|
||||
when(brandConfigService.getBrandConfig(TENANT_ID)).thenReturn(Mono.empty());
|
||||
|
||||
MockServerRequest request = mockRequest().build();
|
||||
Mono<ServerResponse> result = brandConfigHandler.getBrandConfig(request);
|
||||
|
||||
StepVerifier.create(result)
|
||||
.assertNext(response -> assertThat(response.statusCode()).isEqualTo(HttpStatus.OK))
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
// ==================== updateColorConfig ====================
|
||||
|
||||
@Test
|
||||
void updateColorConfig_shouldUpdateAndReturnOk() {
|
||||
BrandConfig config = createTestConfig();
|
||||
config.setPrimaryColor("#FF0000");
|
||||
Map<String, Object> requestBody = Map.of("primaryColor", "#FF0000");
|
||||
|
||||
when(authUtil.getTenantId(any())).thenReturn(TENANT_ID);
|
||||
when(brandConfigService.updateColorConfig(eq(TENANT_ID), any(BrandConfig.class)))
|
||||
.thenReturn(Mono.just(config));
|
||||
|
||||
MockServerRequest request = mockRequest()
|
||||
.body(Mono.just(requestBody));
|
||||
Mono<ServerResponse> result = brandConfigHandler.updateColorConfig(request);
|
||||
|
||||
StepVerifier.create(result)
|
||||
.assertNext(response -> assertThat(response.statusCode()).isEqualTo(HttpStatus.OK))
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateColorConfig_shouldRejectInvalidHex() {
|
||||
Map<String, Object> requestBody = Map.of("primaryColor", "INVALID");
|
||||
|
||||
when(authUtil.getTenantId(any())).thenReturn(TENANT_ID);
|
||||
|
||||
MockServerRequest request = mockRequest()
|
||||
.body(Mono.just(requestBody));
|
||||
Mono<ServerResponse> result = brandConfigHandler.updateColorConfig(request);
|
||||
|
||||
StepVerifier.create(result)
|
||||
.assertNext(response -> assertThat(response.statusCode()).isEqualTo(HttpStatus.BAD_REQUEST))
|
||||
.verifyComplete();
|
||||
|
||||
verify(brandConfigService, never()).updateColorConfig(anyString(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateColorConfig_shouldAcceptShortHexFormat() {
|
||||
BrandConfig config = createTestConfig();
|
||||
config.setPrimaryColor("#F00");
|
||||
Map<String, Object> requestBody = Map.of("primaryColor", "#F00");
|
||||
|
||||
when(authUtil.getTenantId(any())).thenReturn(TENANT_ID);
|
||||
when(brandConfigService.updateColorConfig(eq(TENANT_ID), any(BrandConfig.class)))
|
||||
.thenReturn(Mono.just(config));
|
||||
|
||||
MockServerRequest request = mockRequest()
|
||||
.body(Mono.just(requestBody));
|
||||
Mono<ServerResponse> result = brandConfigHandler.updateColorConfig(request);
|
||||
|
||||
StepVerifier.create(result)
|
||||
.assertNext(response -> assertThat(response.statusCode()).isEqualTo(HttpStatus.OK))
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
void updateColorConfig_shouldRejectInvalidHexInSecondary() {
|
||||
Map<String, Object> requestBody = Map.of("secondaryColor", "not-a-color");
|
||||
|
||||
when(authUtil.getTenantId(any())).thenReturn(TENANT_ID);
|
||||
|
||||
MockServerRequest request = mockRequest()
|
||||
.body(Mono.just(requestBody));
|
||||
Mono<ServerResponse> result = brandConfigHandler.updateColorConfig(request);
|
||||
|
||||
StepVerifier.create(result)
|
||||
.assertNext(response -> assertThat(response.statusCode()).isEqualTo(HttpStatus.BAD_REQUEST))
|
||||
.verifyComplete();
|
||||
}
|
||||
|
||||
// ==================== removeLogo ====================
|
||||
|
||||
@Test
|
||||
void removeLogo_shouldRemoveAndReturnOk() {
|
||||
BrandConfig config = createTestConfig();
|
||||
config.setLogoUrl(null);
|
||||
|
||||
when(authUtil.getTenantId(any())).thenReturn(TENANT_ID);
|
||||
when(brandConfigService.removeLogo(TENANT_ID)).thenReturn(Mono.just(config));
|
||||
|
||||
MockServerRequest request = mockRequest().build();
|
||||
Mono<ServerResponse> result = brandConfigHandler.removeLogo(request);
|
||||
|
||||
StepVerifier.create(result)
|
||||
.assertNext(response -> assertThat(response.statusCode()).isEqualTo(HttpStatus.OK))
|
||||
.verifyComplete();
|
||||
|
||||
verify(brandConfigService).removeLogo(TENANT_ID);
|
||||
}
|
||||
|
||||
// ==================== removeBackgroundImage ====================
|
||||
|
||||
@Test
|
||||
void removeBackgroundImage_shouldRemoveAndReturnOk() {
|
||||
BrandConfig config = createTestConfig();
|
||||
config.setBackgroundImageUrl(null);
|
||||
|
||||
when(authUtil.getTenantId(any())).thenReturn(TENANT_ID);
|
||||
when(brandConfigService.removeBackgroundImage(TENANT_ID)).thenReturn(Mono.just(config));
|
||||
|
||||
MockServerRequest request = mockRequest().build();
|
||||
Mono<ServerResponse> result = brandConfigHandler.removeBackgroundImage(request);
|
||||
|
||||
StepVerifier.create(result)
|
||||
.assertNext(response -> assertThat(response.statusCode()).isEqualTo(HttpStatus.OK))
|
||||
.verifyComplete();
|
||||
|
||||
verify(brandConfigService).removeBackgroundImage(TENANT_ID);
|
||||
}
|
||||
|
||||
// ==================== helper ====================
|
||||
|
||||
private BrandConfig createTestConfig() {
|
||||
BrandConfig config = new BrandConfig();
|
||||
config.setId(1L);
|
||||
config.setTenantId(TENANT_ID);
|
||||
config.setLogoUrl("https://example.com/logo.png");
|
||||
config.setBackgroundImageUrl("https://example.com/bg.png");
|
||||
config.setPrimaryColor("#00E676");
|
||||
config.setPrimaryColorRgb("0,230,118");
|
||||
config.setSecondaryColor("#1A1A1A");
|
||||
config.setSecondaryColorRgb("26,26,26");
|
||||
config.setFontFamily("default");
|
||||
config.setCreatedAt(LocalDateTime.now());
|
||||
config.setUpdatedAt(LocalDateTime.now());
|
||||
return config;
|
||||
}
|
||||
}
|
||||
+181
@@ -0,0 +1,181 @@
|
||||
package cn.novalon.gym.manage.brand.websocket;
|
||||
|
||||
import cn.novalon.gym.manage.brand.core.domain.BrandConfig;
|
||||
import cn.novalon.gym.manage.sys.security.JwtTokenProvider;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.web.reactive.socket.HandshakeInfo;
|
||||
import org.springframework.web.reactive.socket.WebSocketMessage;
|
||||
import org.springframework.web.reactive.socket.WebSocketSession;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
import reactor.test.StepVerifier;
|
||||
|
||||
import java.net.URI;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class BrandWebSocketHandlerTest {
|
||||
|
||||
@Mock
|
||||
private WebSocketSession session;
|
||||
|
||||
@Mock
|
||||
private WebSocketMessage webSocketMessage;
|
||||
|
||||
@Mock
|
||||
private HandshakeInfo handshakeInfo;
|
||||
|
||||
@Mock
|
||||
private JwtTokenProvider jwtTokenProvider;
|
||||
|
||||
private BrandWebSocketHandler handler;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
handler = new BrandWebSocketHandler(jwtTokenProvider);
|
||||
}
|
||||
|
||||
// ==================== JWT-based tenantId extraction ====================
|
||||
|
||||
@Test
|
||||
void handle_shouldExtractTenantIdFromJwtAuthHeader() {
|
||||
setupJwtAuthHeader("Bearer valid-jwt-token");
|
||||
when(jwtTokenProvider.validateToken("valid-jwt-token")).thenReturn(true);
|
||||
when(jwtTokenProvider.getTenantIdFromToken("valid-jwt-token")).thenReturn("tenant-from-jwt");
|
||||
when(session.receive()).thenReturn(Flux.never());
|
||||
|
||||
// Should not throw — tenantId extracted from JWT
|
||||
handler.handle(session).subscribe();
|
||||
}
|
||||
|
||||
// ==================== Query param fallback ====================
|
||||
|
||||
@Test
|
||||
void handle_shouldFallbackToQueryParamWhenNoJwtHeader() {
|
||||
// No Authorization header
|
||||
when(handshakeInfo.getHeaders()).thenReturn(new HttpHeaders());
|
||||
URI uri = URI.create("ws://localhost/ws/brand?tenantId=tenant-from-query");
|
||||
when(session.getHandshakeInfo()).thenReturn(handshakeInfo);
|
||||
when(handshakeInfo.getUri()).thenReturn(uri);
|
||||
when(session.receive()).thenReturn(Flux.never());
|
||||
|
||||
handler.handle(session).subscribe();
|
||||
}
|
||||
|
||||
@Test
|
||||
void handle_shouldFallbackToSessionIdWhenNoQueryParamAndNoJwt() {
|
||||
when(handshakeInfo.getHeaders()).thenReturn(new HttpHeaders());
|
||||
URI uri = URI.create("ws://localhost/ws/brand");
|
||||
when(session.getHandshakeInfo()).thenReturn(handshakeInfo);
|
||||
when(handshakeInfo.getUri()).thenReturn(uri);
|
||||
when(session.getId()).thenReturn("session-id-123");
|
||||
when(session.receive()).thenReturn(Flux.never());
|
||||
|
||||
handler.handle(session).subscribe();
|
||||
}
|
||||
|
||||
// ==================== Message handling ====================
|
||||
|
||||
@Test
|
||||
void handle_shouldProcessPingMessage() {
|
||||
setupSessionWithJwt("tenant-001");
|
||||
when(session.receive()).thenReturn(Flux.just(webSocketMessage));
|
||||
when(webSocketMessage.getPayloadAsText()).thenReturn("{\"type\":\"ping\"}");
|
||||
when(session.textMessage(anyString())).thenReturn(webSocketMessage);
|
||||
when(session.send(any())).thenReturn(Mono.empty());
|
||||
|
||||
Mono<Void> result = handler.handle(session);
|
||||
|
||||
StepVerifier.create(result).verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
void handle_shouldProcessSubscribeMessage() {
|
||||
setupSessionWithJwt("tenant-001");
|
||||
when(session.receive()).thenReturn(Flux.just(webSocketMessage));
|
||||
when(webSocketMessage.getPayloadAsText()).thenReturn("{\"type\":\"subscribe\"}");
|
||||
|
||||
Mono<Void> result = handler.handle(session);
|
||||
|
||||
StepVerifier.create(result).verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
void handle_shouldIgnoreUnknownMessageType() {
|
||||
setupSessionWithJwt("tenant-001");
|
||||
when(session.receive()).thenReturn(Flux.just(webSocketMessage));
|
||||
when(webSocketMessage.getPayloadAsText()).thenReturn("{\"type\":\"unknown\"}");
|
||||
|
||||
Mono<Void> result = handler.handle(session);
|
||||
|
||||
StepVerifier.create(result).verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
void handle_shouldNotCrashOnInvalidJson() {
|
||||
setupSessionWithJwt("tenant-001");
|
||||
when(session.receive()).thenReturn(Flux.just(webSocketMessage));
|
||||
when(webSocketMessage.getPayloadAsText()).thenReturn("not-valid-json");
|
||||
|
||||
Mono<Void> result = handler.handle(session);
|
||||
|
||||
StepVerifier.create(result).verifyComplete();
|
||||
}
|
||||
|
||||
@Test
|
||||
void handle_shouldPropagateConnectionError() {
|
||||
setupSessionWithJwt("tenant-001");
|
||||
when(session.receive()).thenReturn(Flux.error(new RuntimeException("Connection error")));
|
||||
|
||||
Mono<Void> result = handler.handle(session);
|
||||
|
||||
StepVerifier.create(result).verifyError();
|
||||
}
|
||||
|
||||
// ==================== sendBrandUpdate ====================
|
||||
|
||||
@Test
|
||||
void sendBrandUpdate_shouldNotFailWhenNoSession() {
|
||||
BrandConfig config = createTestConfig();
|
||||
|
||||
// Should not throw
|
||||
handler.sendBrandUpdate("nonexistent-tenant", config);
|
||||
}
|
||||
|
||||
// ==================== helper ====================
|
||||
|
||||
private void setupSessionWithJwt(String tenantId) {
|
||||
String token = "jwt-" + tenantId;
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.set(HttpHeaders.AUTHORIZATION, "Bearer " + token);
|
||||
when(handshakeInfo.getHeaders()).thenReturn(headers);
|
||||
when(session.getHandshakeInfo()).thenReturn(handshakeInfo);
|
||||
when(jwtTokenProvider.validateToken(token)).thenReturn(true);
|
||||
when(jwtTokenProvider.getTenantIdFromToken(token)).thenReturn(tenantId);
|
||||
}
|
||||
|
||||
private void setupJwtAuthHeader(String authHeader) {
|
||||
String token = authHeader.substring(7); // strip "Bearer "
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.set(HttpHeaders.AUTHORIZATION, authHeader);
|
||||
when(handshakeInfo.getHeaders()).thenReturn(headers);
|
||||
when(session.getHandshakeInfo()).thenReturn(handshakeInfo);
|
||||
}
|
||||
|
||||
private BrandConfig createTestConfig() {
|
||||
BrandConfig config = new BrandConfig();
|
||||
config.setId(1L);
|
||||
config.setTenantId("tenant-001");
|
||||
config.setLogoUrl("https://example.com/logo.png");
|
||||
config.setPrimaryColor("#00E676");
|
||||
config.setFontFamily("default");
|
||||
return config;
|
||||
}
|
||||
}
|
||||
@@ -118,6 +118,11 @@
|
||||
<artifactId>hutool-all</artifactId>
|
||||
<version>5.8.25</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.google.zxing</groupId>
|
||||
<artifactId>core</artifactId>
|
||||
|
||||
+61
-83
@@ -15,6 +15,8 @@ import cn.novalon.gym.manage.checkIn.vo.SignInStatsVO;
|
||||
import cn.novalon.gym.manage.checkIn.websocket.MyWebSocketHandler;
|
||||
import cn.novalon.gym.manage.common.constant.RedisKeyConstants;
|
||||
import cn.novalon.gym.manage.common.util.RedisUtil;
|
||||
import cn.novalon.gym.manage.groupcourse.domain.GroupCourseBooking;
|
||||
import cn.novalon.gym.manage.groupcourse.repository.IGroupCourseBookingRepository;
|
||||
import cn.novalon.gym.manage.groupcourse.service.IGroupCourseBookingService;
|
||||
import cn.novalon.gym.manage.member.entity.MemberCard;
|
||||
import cn.novalon.gym.manage.member.entity.MemberCardRecord;
|
||||
@@ -47,37 +49,30 @@ public class CheckServiceImpl implements ICheckInService {
|
||||
private final MemberCardRepository memberCardRepository;
|
||||
private final SignInRecordRepository signInRecordRepository;
|
||||
private final IGroupCourseBookingService groupCourseBookingService;
|
||||
private final IGroupCourseBookingRepository groupCourseBookingRepository;
|
||||
|
||||
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
||||
|
||||
@Override
|
||||
public Mono<QRCodeVo> getQRCode(Long memberId) {
|
||||
log.info("开始查询会员信息, memberId: {}", memberId);
|
||||
log.info("开始生成会员签到二维码, memberId: {}", memberId);
|
||||
|
||||
return findValidMemberCard(memberId)
|
||||
.flatMap(cardRecord -> {
|
||||
log.info("会员信息查询完成, memberCardRecordId: {}", cardRecord.getMemberCardRecordId());
|
||||
String qrContent = QRRedisKey.generateQrcodeContent();
|
||||
Map<String, Object> redisMap = new HashMap<>();
|
||||
redisMap.put("qrContent", qrContent);
|
||||
redisMap.put("isUsed", false);
|
||||
redisMap.put("memberId", memberId);
|
||||
|
||||
log.info("开始生成二维码");
|
||||
String qrContent = QRRedisKey.generateQrcodeContent();
|
||||
Map<String, Object> redisMap = new HashMap<>();
|
||||
redisMap.put("qrContent", qrContent);
|
||||
redisMap.put("isUsed", false);
|
||||
redisMap.put("memberId", memberId);
|
||||
redisMap.put("memberCardRecordId", cardRecord.getMemberCardRecordId());
|
||||
|
||||
return redisUtil.setWithExpire(
|
||||
RedisKeyConstants.QRCODE_USER_DAILY + memberId + LocalDate.now(),
|
||||
redisMap,
|
||||
getSecondsUntilEndOfDay()
|
||||
)
|
||||
.then(Mono.fromSupplier(() -> {
|
||||
String qrCodeBase64 = QrCodeUtil.generateAsBase64(qrContent,
|
||||
BeanUtil.copyProperties(qrCodeConfig, QrConfig.class), "png");
|
||||
return new QRCodeVo(qrCodeBase64, false, qrContent, qrCodeConfig.getWidth(), qrCodeConfig.getHeight(), LocalDate.now());
|
||||
}));
|
||||
})
|
||||
.switchIfEmpty(Mono.error(new RuntimeException("该会员没有可用的会员卡")));
|
||||
return redisUtil.setWithExpire(
|
||||
RedisKeyConstants.QRCODE_USER_DAILY + memberId + LocalDate.now(),
|
||||
redisMap,
|
||||
getSecondsUntilEndOfDay()
|
||||
)
|
||||
.then(Mono.fromSupplier(() -> {
|
||||
String qrCodeBase64 = QrCodeUtil.generateAsBase64(qrContent,
|
||||
BeanUtil.copyProperties(qrCodeConfig, QrConfig.class), "png");
|
||||
return new QRCodeVo(qrCodeBase64, false, qrContent, qrCodeConfig.getWidth(), qrCodeConfig.getHeight(), LocalDate.now());
|
||||
}));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -113,9 +108,10 @@ public class CheckServiceImpl implements ICheckInService {
|
||||
}
|
||||
log.info("二维码匹配成功,memberId: {}", memberId);
|
||||
|
||||
Long memberCardRecordId = ((Number) map.get("memberCardRecordId")).longValue();
|
||||
Long memberCardRecordId = map.get("memberCardRecordId") != null
|
||||
? ((Number) map.get("memberCardRecordId")).longValue() : null;
|
||||
|
||||
return processCheckIn(memberId, memberCardRecordId, map, qrContent);
|
||||
return processCheckIn(memberId, memberCardRecordId, map, qrContent);
|
||||
} else {
|
||||
MyWebSocketHandler.sendFailure(qrContent, "二维码无效");
|
||||
return Mono.error(new RuntimeException("二维码无效"));
|
||||
@@ -145,60 +141,43 @@ public class CheckServiceImpl implements ICheckInService {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
|
||||
// 发送实时进度通知
|
||||
MyWebSocketHandler.sendProgress(qrContent, "VALIDATE_CARD", "正在验证会员卡...");
|
||||
MyWebSocketHandler.sendProgress(qrContent, "VALIDATE_BOOKING", "正在检查预约信息...");
|
||||
|
||||
return memberCardRecordRepository.findById(memberCardRecordId)
|
||||
.switchIfEmpty(Mono.defer(() -> {
|
||||
MyWebSocketHandler.sendFailure(qrContent, "会员卡记录不存在");
|
||||
return Mono.error(new RuntimeException("会员卡记录不存在"));
|
||||
}))
|
||||
.flatMap(cardRecord -> {
|
||||
if (!"ACTIVE".equals(cardRecord.getStatus().name())) {
|
||||
MyWebSocketHandler.sendFailure(qrContent, "会员卡状态不正确");
|
||||
return Mono.error(new RuntimeException("会员卡状态不正确"));
|
||||
}
|
||||
// 检查是否有需要签到的团课预约,有则返回有效预约
|
||||
return validateBooking(memberId, now)
|
||||
.flatMap(booking ->
|
||||
// 有有效预约:将预约状态更新为"已出席"
|
||||
groupCourseBookingRepository.updateStatus(booking.getId(), "2")
|
||||
.doOnNext(count -> log.info("已更新预约状态为已出席, bookingId: {}, rows: {}", booking.getId(), count))
|
||||
.then(Mono.just(true))
|
||||
)
|
||||
.defaultIfEmpty(false)
|
||||
.then(Mono.defer(() -> {
|
||||
redisMap.put("isUsed", true);
|
||||
redisMap.put("checkInTime", now.format(DATE_FORMATTER));
|
||||
|
||||
if (cardRecord.getExpireTime() != null && cardRecord.getExpireTime().isBefore(now)) {
|
||||
MyWebSocketHandler.sendFailure(qrContent, "会员卡已过期");
|
||||
return Mono.error(new RuntimeException("会员卡已过期"));
|
||||
}
|
||||
|
||||
// 发送实时进度通知
|
||||
MyWebSocketHandler.sendProgress(qrContent, "VALIDATE_BOOKING", "会员卡验证通过,正在检查预约信息...");
|
||||
|
||||
// 检查是否有需要签到的团课预约
|
||||
return validateBooking(memberId, now)
|
||||
.then(memberCardRepository.findByMemberCardIdAndDeletedAtIsNull(cardRecord.getMemberCardId())
|
||||
.switchIfEmpty(Mono.defer(() -> {
|
||||
MyWebSocketHandler.sendFailure(qrContent, "会员卡类型不存在");
|
||||
return Mono.error(new RuntimeException("会员卡类型不存在"));
|
||||
}))
|
||||
.flatMap(card -> {
|
||||
// 发送实时进度通知
|
||||
MyWebSocketHandler.sendProgress(qrContent, "DEDUCT_USAGE", "正在扣减会员卡次数...");
|
||||
|
||||
return deductCardUsage(cardRecord, card)
|
||||
.flatMap(updatedRecord -> {
|
||||
redisMap.put("isUsed", true);
|
||||
redisMap.put("checkInTime", now.format(DATE_FORMATTER));
|
||||
|
||||
return saveSignInRecord(memberId, cardRecord.getMemberCardRecordId(), card.getMemberCardId())
|
||||
.then(redisUtil.set(RedisKeyConstants.QRCODE_USER_DAILY + memberId + LocalDate.now(), redisMap))
|
||||
.then(Mono.defer(() -> {
|
||||
String successMsg = buildSuccessResponse(now);
|
||||
MyWebSocketHandler.sendSuccess(qrContent, memberId, now.format(DATE_FORMATTER));
|
||||
log.info("签到成功, memberId: {}, cardRecordId: {}", memberId, memberCardRecordId);
|
||||
return Mono.just(successMsg);
|
||||
}));
|
||||
});
|
||||
}));
|
||||
});
|
||||
return saveSignInRecord(memberId, null, null)
|
||||
.then(redisUtil.set(RedisKeyConstants.QRCODE_USER_DAILY + memberId + LocalDate.now(), redisMap))
|
||||
// 清除统计缓存和课程缓存,确保管理端/教练端立即反映最新数据
|
||||
.then(Mono.defer(() ->
|
||||
redisUtil.deleteByPattern("datacount:statistics:*")
|
||||
.then(Mono.defer(() -> redisUtil.deleteByPattern("group_course:*")))
|
||||
.doOnSuccess(v -> log.info("已清除统计缓存和课程缓存, memberId: {}", memberId))
|
||||
.then()
|
||||
))
|
||||
.then(Mono.defer(() -> {
|
||||
String successMsg = buildSuccessResponse(now);
|
||||
MyWebSocketHandler.sendSuccess(qrContent, memberId, now.format(DATE_FORMATTER));
|
||||
log.info("签到成功, memberId: {}", memberId);
|
||||
return Mono.just(successMsg);
|
||||
}));
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证预约信息
|
||||
* 验证预约信息,返回时间匹配的有效预约
|
||||
*/
|
||||
private Mono<Void> validateBooking(Long memberId, LocalDateTime now) {
|
||||
private Mono<GroupCourseBooking> validateBooking(Long memberId, LocalDateTime now) {
|
||||
return groupCourseBookingService.getBookingsByMemberId(memberId)
|
||||
.filter(booking -> {
|
||||
String status = booking.getStatus();
|
||||
@@ -213,19 +192,18 @@ public class CheckServiceImpl implements ICheckInService {
|
||||
if (bookings.isEmpty()) {
|
||||
return Mono.empty();
|
||||
}
|
||||
boolean hasValidBooking = bookings.stream()
|
||||
.anyMatch(b -> {
|
||||
// 找到时间范围内第一个有效预约(课程时间内±30分钟)
|
||||
return Flux.fromIterable(bookings)
|
||||
.filter(b -> {
|
||||
LocalDateTime startTime = b.getCourseStartTime();
|
||||
return startTime != null &&
|
||||
!startTime.isBefore(now.minusMinutes(30)) &&
|
||||
!startTime.isAfter(now.plusMinutes(30));
|
||||
});
|
||||
if (hasValidBooking) {
|
||||
log.info("会员{}有有效的团课预约", memberId);
|
||||
} else {
|
||||
log.warn("会员{}有预约但不在签到时间范围内", memberId);
|
||||
}
|
||||
return Mono.empty();
|
||||
})
|
||||
.next()
|
||||
.doOnNext(b -> log.info("会员{}有有效的团课预约, bookingId: {}", memberId, b.getId()))
|
||||
.switchIfEmpty(Mono.fromRunnable(() ->
|
||||
log.warn("会员{}有预约但不在签到时间范围内", memberId)));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+7
-1
@@ -3,6 +3,7 @@ package cn.novalon.gym.manage.checkin;
|
||||
import cn.novalon.gym.manage.checkIn.config.QRCodeConfig;
|
||||
import cn.novalon.gym.manage.checkIn.entity.SignInRecord;
|
||||
import cn.novalon.gym.manage.checkIn.repository.SignInRecordRepository;
|
||||
import cn.novalon.gym.manage.groupcourse.repository.IGroupCourseBookingRepository;
|
||||
import cn.novalon.gym.manage.groupcourse.service.IGroupCourseBookingService;
|
||||
import cn.novalon.gym.manage.checkIn.service.impl.CheckServiceImpl;
|
||||
import cn.novalon.gym.manage.checkIn.vo.QRCodeVo;
|
||||
@@ -57,6 +58,9 @@ class CheckInModuleTest {
|
||||
@Mock
|
||||
private IGroupCourseBookingService groupCourseBookingService;
|
||||
|
||||
@Mock
|
||||
private IGroupCourseBookingRepository groupCourseBookingRepository;
|
||||
|
||||
@Mock
|
||||
private MemberCard mockMemberCard;
|
||||
|
||||
@@ -72,7 +76,8 @@ class CheckInModuleTest {
|
||||
void setUp() {
|
||||
MockitoAnnotations.openMocks(this);
|
||||
checkService = new CheckServiceImpl(qrCodeConfig, redisUtil, memberCardRecordRepository,
|
||||
memberCardRepository, signInRecordRepository, groupCourseBookingService);
|
||||
memberCardRepository, signInRecordRepository, groupCourseBookingService,
|
||||
groupCourseBookingRepository);
|
||||
|
||||
when(mockMemberCard.getId()).thenReturn(1L);
|
||||
when(mockMemberCard.getMemberCardType()).thenReturn("TIME_CARD");
|
||||
@@ -126,6 +131,7 @@ class CheckInModuleTest {
|
||||
String key = RedisKeyConstants.QRCODE_USER_DAILY + memberId + LocalDate.now();
|
||||
|
||||
when(redisUtil.get(eq(key))).thenReturn(Mono.just(qrData));
|
||||
when(redisUtil.deleteByPattern(any(String.class))).thenReturn(Mono.empty());
|
||||
when(memberCardRecordRepository.findById(1L)).thenReturn(Mono.just(mockMemberCardRecord));
|
||||
when(memberCardRepository.findByMemberCardIdAndDeletedAtIsNull(1L)).thenReturn(Mono.just(mockMemberCard));
|
||||
when(signInRecordRepository.save(any(SignInRecord.class))).thenReturn(Mono.just(mockSignInRecord));
|
||||
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
package cn.novalon.gym.manage.checkin.handler;
|
||||
|
||||
import cn.novalon.gym.manage.checkIn.handler.CheckInHandler;
|
||||
import cn.novalon.gym.manage.checkIn.service.impl.CheckServiceImpl;
|
||||
import cn.novalon.gym.manage.checkIn.vo.QRCodeVo;
|
||||
import cn.novalon.gym.manage.checkIn.vo.SignInRecordVO;
|
||||
import cn.novalon.gym.manage.checkIn.vo.SignInStatsVO;
|
||||
import cn.novalon.gym.manage.sys.util.AuthUtil;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.HttpStatus;
|
||||
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 java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class CheckInHandlerTest {
|
||||
|
||||
@Mock
|
||||
private AuthUtil authUtil;
|
||||
|
||||
@Mock
|
||||
private CheckServiceImpl checkService;
|
||||
|
||||
private CheckInHandler checkInHandler;
|
||||
|
||||
private static final Long MEMBER_ID = 10001L;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
checkInHandler = new CheckInHandler(authUtil, checkService);
|
||||
}
|
||||
|
||||
// ==================== checkIn ====================
|
||||
|
||||
@Test
|
||||
void checkIn_shouldReturnOk() {
|
||||
Map<String, Object> body = Map.of("qrContent", "checkin:member:10001");
|
||||
|
||||
when(authUtil.getMemberIdOrThrow(any())).thenReturn(MEMBER_ID);
|
||||
when(checkService.checkIn(MEMBER_ID, "checkin:member:10001")).thenReturn(Mono.just("签到成功"));
|
||||
|
||||
MockServerRequest request = MockServerRequest.builder()
|
||||
.body(Mono.just(body));
|
||||
|
||||
Mono<ServerResponse> result = checkInHandler.checkIn(request);
|
||||
|
||||
ServerResponse response = result.block();
|
||||
assertThat(response.statusCode()).isEqualTo(HttpStatus.OK);
|
||||
|
||||
verify(checkService).checkIn(MEMBER_ID, "checkin:member:10001");
|
||||
}
|
||||
|
||||
@Test
|
||||
void checkIn_shouldReturnBadRequestOnError() {
|
||||
Map<String, Object> body = Map.of("qrContent", "invalid-content");
|
||||
|
||||
when(authUtil.getMemberIdOrThrow(any())).thenReturn(MEMBER_ID);
|
||||
when(checkService.checkIn(MEMBER_ID, "invalid-content"))
|
||||
.thenReturn(Mono.error(new RuntimeException("Invalid QR code")));
|
||||
|
||||
MockServerRequest request = MockServerRequest.builder()
|
||||
.body(Mono.just(body));
|
||||
|
||||
Mono<ServerResponse> result = checkInHandler.checkIn(request);
|
||||
|
||||
ServerResponse response = result.block();
|
||||
assertThat(response.statusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
|
||||
// ==================== getQRCode ====================
|
||||
|
||||
@Test
|
||||
void getQRCode_shouldReturnOkWithQRCode() {
|
||||
QRCodeVo qrCode = new QRCodeVo("base64content", false, "qr-content", 200, 200, LocalDate.now());
|
||||
|
||||
when(authUtil.getMemberIdOrThrow(any())).thenReturn(MEMBER_ID);
|
||||
when(checkService.getQRCode(MEMBER_ID)).thenReturn(Mono.just(qrCode));
|
||||
|
||||
MockServerRequest request = MockServerRequest.builder().build();
|
||||
|
||||
Mono<ServerResponse> result = checkInHandler.getQRCode(request);
|
||||
|
||||
ServerResponse response = result.block();
|
||||
assertThat(response.statusCode()).isEqualTo(HttpStatus.OK);
|
||||
}
|
||||
|
||||
// ==================== getSignInRecords ====================
|
||||
|
||||
@Test
|
||||
void getSignInRecords_shouldReturnOkWithRecords() {
|
||||
List<SignInRecordVO> records = List.of(createTestRecord());
|
||||
|
||||
when(authUtil.getMemberIdOrThrow(any())).thenReturn(MEMBER_ID);
|
||||
when(checkService.getSignInRecords(eq(MEMBER_ID), any(LocalDate.class), any(LocalDate.class)))
|
||||
.thenReturn(Flux.fromIterable(records));
|
||||
|
||||
MockServerRequest request = MockServerRequest.builder()
|
||||
.queryParam("startDate", "2025-01-01")
|
||||
.queryParam("endDate", "2025-01-31")
|
||||
.build();
|
||||
|
||||
Mono<ServerResponse> result = checkInHandler.getSignInRecords(request);
|
||||
|
||||
ServerResponse response = result.block();
|
||||
assertThat(response.statusCode()).isEqualTo(HttpStatus.OK);
|
||||
}
|
||||
|
||||
// ==================== getSignInStatistics ====================
|
||||
|
||||
@Test
|
||||
void getSignInStatistics_shouldReturnOkWithStats() {
|
||||
SignInStatsVO stats = new SignInStatsVO();
|
||||
|
||||
when(authUtil.getMemberIdOrThrow(any())).thenReturn(MEMBER_ID);
|
||||
when(checkService.getSignInStats(eq(MEMBER_ID), any(LocalDate.class), any(LocalDate.class)))
|
||||
.thenReturn(Mono.just(stats));
|
||||
|
||||
MockServerRequest request = MockServerRequest.builder()
|
||||
.queryParam("startDate", "2025-01-01")
|
||||
.queryParam("endDate", "2025-01-31")
|
||||
.build();
|
||||
|
||||
Mono<ServerResponse> result = checkInHandler.getSignInStatistics(request);
|
||||
|
||||
ServerResponse response = result.block();
|
||||
assertThat(response.statusCode()).isEqualTo(HttpStatus.OK);
|
||||
}
|
||||
|
||||
// ==================== getDailySignInStats ====================
|
||||
|
||||
@Test
|
||||
void getDailySignInStats_shouldReturnOkWithDailyStats() {
|
||||
SignInStatsVO stats = new SignInStatsVO();
|
||||
|
||||
when(checkService.getDailySignInStats(any(LocalDate.class))).thenReturn(Mono.just(stats));
|
||||
|
||||
MockServerRequest request = MockServerRequest.builder()
|
||||
.queryParam("date", "2025-01-15")
|
||||
.build();
|
||||
|
||||
Mono<ServerResponse> result = checkInHandler.getDailySignInStats(request);
|
||||
|
||||
ServerResponse response = result.block();
|
||||
assertThat(response.statusCode()).isEqualTo(HttpStatus.OK);
|
||||
}
|
||||
|
||||
// ==================== helper ====================
|
||||
|
||||
private SignInRecordVO createTestRecord() {
|
||||
SignInRecordVO record = new SignInRecordVO();
|
||||
record.setId(1L);
|
||||
record.setMemberId(MEMBER_ID);
|
||||
record.setSignInTime(LocalDateTime.now());
|
||||
record.setSignInType("QR_CODE");
|
||||
record.setSignInStatus("SUCCESS");
|
||||
return record;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
<?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-config</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>Gym Coach Config</name>
|
||||
<description>Coach Time Rule Configuration Module - Configurable coach lateness/absence thresholds</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>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-webflux</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>
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package cn.novalon.gym.manage.coachconfig.converter;
|
||||
|
||||
import cn.novalon.gym.manage.coachconfig.domain.CoachTimeRule;
|
||||
import cn.novalon.gym.manage.db.entity.CoachTimeRuleEntity;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 教练时间规则实体转换器
|
||||
*
|
||||
* @author 张翔
|
||||
* @date 2026-07-26
|
||||
*/
|
||||
@Component
|
||||
public class CoachTimeRuleConverter {
|
||||
|
||||
public CoachTimeRule toDomain(CoachTimeRuleEntity entity) {
|
||||
if (entity == null) {
|
||||
return null;
|
||||
}
|
||||
CoachTimeRule domain = new CoachTimeRule();
|
||||
domain.setId(entity.getId());
|
||||
domain.setMinDuration(entity.getMinDuration());
|
||||
domain.setMaxDuration(entity.getMaxDuration());
|
||||
domain.setNormalWindow(entity.getNormalWindow());
|
||||
domain.setLateWindow(entity.getLateWindow());
|
||||
domain.setEndGrace(entity.getEndGrace());
|
||||
domain.setIsDefault(entity.getIsDefault());
|
||||
domain.setSortOrder(entity.getSortOrder());
|
||||
domain.setStatus(entity.getStatus());
|
||||
domain.setRemark(entity.getRemark());
|
||||
domain.setCreatedAt(entity.getCreatedAt());
|
||||
domain.setUpdatedAt(entity.getUpdatedAt());
|
||||
return domain;
|
||||
}
|
||||
|
||||
public CoachTimeRuleEntity toEntity(CoachTimeRule domain) {
|
||||
if (domain == null) {
|
||||
return null;
|
||||
}
|
||||
CoachTimeRuleEntity entity = new CoachTimeRuleEntity();
|
||||
entity.setId(domain.getId());
|
||||
entity.setMinDuration(domain.getMinDuration());
|
||||
entity.setMaxDuration(domain.getMaxDuration());
|
||||
entity.setNormalWindow(domain.getNormalWindow());
|
||||
entity.setLateWindow(domain.getLateWindow());
|
||||
entity.setEndGrace(domain.getEndGrace());
|
||||
entity.setIsDefault(domain.getIsDefault());
|
||||
entity.setSortOrder(domain.getSortOrder());
|
||||
entity.setStatus(domain.getStatus());
|
||||
entity.setRemark(domain.getRemark());
|
||||
entity.setCreateBy(domain.getCreateBy());
|
||||
entity.setUpdateBy(domain.getUpdateBy());
|
||||
entity.setCreatedAt(domain.getCreatedAt());
|
||||
entity.setUpdatedAt(domain.getUpdatedAt());
|
||||
return entity;
|
||||
}
|
||||
}
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
package cn.novalon.gym.manage.coachconfig.domain;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 教练时间规则领域对象
|
||||
*
|
||||
* @author 张翔
|
||||
* @date 2026-07-26
|
||||
*/
|
||||
public class CoachTimeRule {
|
||||
|
||||
private Long id;
|
||||
private Integer minDuration;
|
||||
private Integer maxDuration;
|
||||
private Integer normalWindow;
|
||||
private Integer lateWindow;
|
||||
private Integer endGrace;
|
||||
private Boolean isDefault;
|
||||
private Integer sortOrder;
|
||||
private String status;
|
||||
private String remark;
|
||||
private String createBy;
|
||||
private String updateBy;
|
||||
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
private LocalDateTime createdAt;
|
||||
|
||||
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
private LocalDateTime updatedAt;
|
||||
|
||||
/**
|
||||
* 判断该规则是否匹配给定课程时长
|
||||
*/
|
||||
public boolean matches(long courseDurationMinutes) {
|
||||
boolean aboveMin = minDuration == null || courseDurationMinutes >= minDuration;
|
||||
boolean belowMax = maxDuration == null || courseDurationMinutes <= maxDuration;
|
||||
return aboveMin && belowMax;
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回规则区间的宽度(用于精确匹配排序),无边界时返回 Integer.MAX_VALUE
|
||||
*/
|
||||
public int rangeWidth() {
|
||||
if (minDuration == null && maxDuration == null) {
|
||||
return Integer.MAX_VALUE;
|
||||
}
|
||||
if (minDuration == null) {
|
||||
return maxDuration;
|
||||
}
|
||||
if (maxDuration == null) {
|
||||
return Integer.MAX_VALUE - minDuration;
|
||||
}
|
||||
return maxDuration - minDuration;
|
||||
}
|
||||
|
||||
public Long getId() { return id; }
|
||||
public void setId(Long id) { this.id = id; }
|
||||
|
||||
public Integer getMinDuration() { return minDuration; }
|
||||
public void setMinDuration(Integer minDuration) { this.minDuration = minDuration; }
|
||||
|
||||
public Integer getMaxDuration() { return maxDuration; }
|
||||
public void setMaxDuration(Integer maxDuration) { this.maxDuration = maxDuration; }
|
||||
|
||||
public Integer getNormalWindow() { return normalWindow; }
|
||||
public void setNormalWindow(Integer normalWindow) { this.normalWindow = normalWindow; }
|
||||
|
||||
public Integer getLateWindow() { return lateWindow; }
|
||||
public void setLateWindow(Integer lateWindow) { this.lateWindow = lateWindow; }
|
||||
|
||||
public Integer getEndGrace() { return endGrace; }
|
||||
public void setEndGrace(Integer endGrace) { this.endGrace = endGrace; }
|
||||
|
||||
public Boolean getIsDefault() { return isDefault; }
|
||||
public void setIsDefault(Boolean isDefault) { this.isDefault = isDefault; }
|
||||
|
||||
public Integer getSortOrder() { return sortOrder; }
|
||||
public void setSortOrder(Integer sortOrder) { this.sortOrder = sortOrder; }
|
||||
|
||||
public String getStatus() { return status; }
|
||||
public void setStatus(String status) { this.status = status; }
|
||||
|
||||
public String getRemark() { return remark; }
|
||||
public void setRemark(String remark) { this.remark = remark; }
|
||||
|
||||
public String getCreateBy() { return createBy; }
|
||||
public void setCreateBy(String createBy) { this.createBy = createBy; }
|
||||
|
||||
public String getUpdateBy() { return updateBy; }
|
||||
public void setUpdateBy(String updateBy) { this.updateBy = updateBy; }
|
||||
|
||||
public LocalDateTime getCreatedAt() { return createdAt; }
|
||||
public void setCreatedAt(LocalDateTime createdAt) { this.createdAt = createdAt; }
|
||||
|
||||
public LocalDateTime getUpdatedAt() { return updatedAt; }
|
||||
public void setUpdatedAt(LocalDateTime updatedAt) { this.updatedAt = updatedAt; }
|
||||
}
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
package cn.novalon.gym.manage.coachconfig.handler;
|
||||
|
||||
import cn.novalon.gym.manage.coachconfig.domain.CoachTimeRule;
|
||||
import cn.novalon.gym.manage.coachconfig.service.CoachTimeRuleService;
|
||||
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.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 教练时间规则 HTTP 处理器
|
||||
*
|
||||
* @author 张翔
|
||||
* @date 2026-07-26
|
||||
*/
|
||||
@Component
|
||||
@Tag(name = "教练时间规则配置", description = "教练迟到/缺席时间阈值的可配置化管理")
|
||||
public class CoachTimeRuleHandler {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(CoachTimeRuleHandler.class);
|
||||
private final CoachTimeRuleService service;
|
||||
|
||||
public CoachTimeRuleHandler(CoachTimeRuleService service) {
|
||||
this.service = service;
|
||||
}
|
||||
|
||||
@Operation(summary = "获取所有规则", description = "获取所有启用和停用的教练时间规则")
|
||||
public Mono<ServerResponse> getAllRules(ServerRequest request) {
|
||||
return service.getAllRules()
|
||||
.collectList()
|
||||
.flatMap(rules -> ServerResponse.ok().bodyValue(rules))
|
||||
.onErrorResume(e -> {
|
||||
logger.error("获取规则列表失败: {}", e.getMessage());
|
||||
return ServerResponse.badRequest().bodyValue(Map.of("error", e.getMessage()));
|
||||
});
|
||||
}
|
||||
|
||||
@Operation(summary = "获取单条规则", description = "根据ID获取教练时间规则")
|
||||
public Mono<ServerResponse> getRuleById(ServerRequest request) {
|
||||
Long id = Long.valueOf(request.pathVariable("id"));
|
||||
return service.getRuleById(id)
|
||||
.flatMap(rule -> ServerResponse.ok().bodyValue(rule))
|
||||
.onErrorResume(e -> {
|
||||
logger.error("获取规则失败: {}", e.getMessage());
|
||||
return ServerResponse.badRequest().bodyValue(Map.of("error", e.getMessage()));
|
||||
});
|
||||
}
|
||||
|
||||
@Operation(summary = "创建规则", description = "创建一条新的教练时间规则,创建后立即生效")
|
||||
public Mono<ServerResponse> createRule(ServerRequest request) {
|
||||
return request.bodyToMono(CoachTimeRule.class)
|
||||
.flatMap(rule -> service.createRule(rule)
|
||||
.flatMap(saved -> {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("message", "规则创建成功");
|
||||
result.put("id", saved.getId());
|
||||
return ServerResponse.ok().bodyValue(result);
|
||||
}))
|
||||
.onErrorResume(e -> {
|
||||
logger.error("创建规则失败: {}", e.getMessage());
|
||||
return ServerResponse.badRequest().bodyValue(Map.of("error", e.getMessage()));
|
||||
});
|
||||
}
|
||||
|
||||
@Operation(summary = "更新规则", description = "更新教练时间规则,更新后立即生效")
|
||||
public Mono<ServerResponse> updateRule(ServerRequest request) {
|
||||
Long id = Long.valueOf(request.pathVariable("id"));
|
||||
return request.bodyToMono(CoachTimeRule.class)
|
||||
.flatMap(rule -> service.updateRule(id, rule)
|
||||
.flatMap(updated -> ServerResponse.ok().bodyValue(Map.of("message", "规则更新成功"))))
|
||||
.onErrorResume(e -> {
|
||||
logger.error("更新规则失败: {}", e.getMessage());
|
||||
return ServerResponse.badRequest().bodyValue(Map.of("error", e.getMessage()));
|
||||
});
|
||||
}
|
||||
|
||||
@Operation(summary = "删除规则", description = "软删除教练时间规则,删除后立即生效")
|
||||
public Mono<ServerResponse> deleteRule(ServerRequest request) {
|
||||
Long id = Long.valueOf(request.pathVariable("id"));
|
||||
return service.deleteRule(id)
|
||||
.then(ServerResponse.ok().bodyValue(Map.of("message", "规则删除成功")))
|
||||
.onErrorResume(e -> {
|
||||
logger.error("删除规则失败: {}", e.getMessage());
|
||||
return ServerResponse.badRequest().bodyValue(Map.of("error", e.getMessage()));
|
||||
});
|
||||
}
|
||||
}
|
||||
+79
@@ -0,0 +1,79 @@
|
||||
package cn.novalon.gym.manage.coachconfig.repository;
|
||||
|
||||
import cn.novalon.gym.manage.coachconfig.domain.CoachTimeRule;
|
||||
import cn.novalon.gym.manage.coachconfig.converter.CoachTimeRuleConverter;
|
||||
import cn.novalon.gym.manage.db.dao.CoachTimeRuleDao;
|
||||
import cn.novalon.gym.manage.db.entity.CoachTimeRuleEntity;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 教练时间规则仓储实现类
|
||||
*
|
||||
* @author 张翔
|
||||
* @date 2026-07-26
|
||||
*/
|
||||
@Repository
|
||||
public class CoachTimeRuleRepository implements ICoachTimeRuleRepository {
|
||||
|
||||
private final CoachTimeRuleDao dao;
|
||||
private final CoachTimeRuleConverter converter;
|
||||
|
||||
public CoachTimeRuleRepository(CoachTimeRuleDao dao, CoachTimeRuleConverter converter) {
|
||||
this.dao = dao;
|
||||
this.converter = converter;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flux<CoachTimeRule> findByStatusAndDeletedAtIsNull(String status) {
|
||||
return dao.findByStatusAndDeletedAtIsNull(status, Sort.by(Sort.Direction.ASC, "sort_order"))
|
||||
.map(converter::toDomain);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flux<CoachTimeRule> findByDeletedAtIsNull() {
|
||||
return dao.findByDeletedAtIsNull()
|
||||
.map(converter::toDomain);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<CoachTimeRule> findById(Long id) {
|
||||
return dao.findByIdAndDeletedAtIsNull(id)
|
||||
.map(converter::toDomain);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<CoachTimeRule> save(CoachTimeRule rule) {
|
||||
CoachTimeRuleEntity entity = converter.toEntity(rule);
|
||||
entity.setCreatedAt(rule.getId() == null ? LocalDateTime.now() : entity.getCreatedAt());
|
||||
entity.setUpdatedAt(LocalDateTime.now());
|
||||
return dao.save(entity)
|
||||
.map(converter::toDomain);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Void> deleteById(Long id) {
|
||||
return dao.findByIdAndDeletedAtIsNull(id)
|
||||
.flatMap(entity -> {
|
||||
entity.setDeletedAt(LocalDateTime.now());
|
||||
return dao.save(entity);
|
||||
})
|
||||
.then();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Void> unsetOtherDefaults(Long excludeId) {
|
||||
return dao.findByIsDefaultTrueAndStatusAndDeletedAtIsNull("1")
|
||||
.filter(entity -> excludeId == null || !entity.getId().equals(excludeId))
|
||||
.flatMap(entity -> {
|
||||
entity.setIsDefault(false);
|
||||
entity.setUpdatedAt(LocalDateTime.now());
|
||||
return dao.save(entity);
|
||||
})
|
||||
.then();
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package cn.novalon.gym.manage.coachconfig.repository;
|
||||
|
||||
import cn.novalon.gym.manage.coachconfig.domain.CoachTimeRule;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
/**
|
||||
* 教练时间规则仓储接口
|
||||
*
|
||||
* @author 张翔
|
||||
* @date 2026-07-26
|
||||
*/
|
||||
public interface ICoachTimeRuleRepository {
|
||||
|
||||
Flux<CoachTimeRule> findByStatusAndDeletedAtIsNull(String status);
|
||||
|
||||
Flux<CoachTimeRule> findByDeletedAtIsNull();
|
||||
|
||||
Mono<CoachTimeRule> findById(Long id);
|
||||
|
||||
Mono<CoachTimeRule> save(CoachTimeRule rule);
|
||||
|
||||
Mono<Void> deleteById(Long id);
|
||||
|
||||
/** 将除指定 id 之外的所有启用默认规则设为非默认(excludeId 为 null 表示清除全部) */
|
||||
Mono<Void> unsetOtherDefaults(Long excludeId);
|
||||
}
|
||||
+240
@@ -0,0 +1,240 @@
|
||||
package cn.novalon.gym.manage.coachconfig.service;
|
||||
|
||||
import cn.novalon.gym.manage.coachconfig.domain.CoachTimeRule;
|
||||
import cn.novalon.gym.manage.coachconfig.repository.ICoachTimeRuleRepository;
|
||||
import cn.novalon.gym.manage.common.constant.RedisKeyConstants;
|
||||
import cn.novalon.gym.manage.common.util.RedisUtil;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.stereotype.Service;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 教练时间规则服务
|
||||
*
|
||||
* 提供规则 CRUD、缓存管理、以及基于课程时长的规则匹配。
|
||||
* 每次写操作后立即清除 Redis 缓存,读操作使用 Cache-Aside 模式。
|
||||
*
|
||||
* @author 张翔
|
||||
* @date 2026-07-26
|
||||
*/
|
||||
@Service
|
||||
public class CoachTimeRuleService {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(CoachTimeRuleService.class);
|
||||
|
||||
/** 硬编码兜底值:长课时(>=60分钟)默认正常窗口 */
|
||||
private static final int FALLBACK_LONG_NORMAL_WINDOW = 10;
|
||||
/** 硬编码兜底值:长课时(>=60分钟)默认迟到/缺席窗口 */
|
||||
private static final int FALLBACK_LONG_LATE_WINDOW = 30;
|
||||
/** 硬编码兜底值:短课时(<60分钟)默认正常窗口比例 */
|
||||
private static final double FALLBACK_SHORT_NORMAL_RATIO = 0.10;
|
||||
/** 硬编码兜底值:短课时(<60分钟)默认迟到/缺席窗口比例 */
|
||||
private static final double FALLBACK_SHORT_LATE_RATIO = 0.25;
|
||||
/** 硬编码兜底值:结课宽限期 */
|
||||
private static final int FALLBACK_END_GRACE = 10;
|
||||
/** 长/短课时分界线 */
|
||||
private static final long ONE_HOUR_MINUTES = 60;
|
||||
/** Redis 缓存 TTL(秒) */
|
||||
private static final long CACHE_TTL_SECONDS = 300;
|
||||
|
||||
private final ICoachTimeRuleRepository repository;
|
||||
private final RedisUtil redisUtil;
|
||||
|
||||
public CoachTimeRuleService(ICoachTimeRuleRepository repository, RedisUtil redisUtil) {
|
||||
this.repository = repository;
|
||||
this.redisUtil = redisUtil;
|
||||
}
|
||||
|
||||
// ==================== 规则匹配 ====================
|
||||
|
||||
/**
|
||||
* 根据课程时长(分钟)匹配最精确的时间规则。
|
||||
* 匹配逻辑:
|
||||
* 1. 从缓存/DB 获取所有启用规则
|
||||
* 2. 过滤出 courseDuration 在 [minDuration, maxDuration] 范围内的规则
|
||||
* 3. 选择区间范围最小的(最精确匹配)
|
||||
* 4. 无匹配时使用 isDefault=true 的默认规则
|
||||
* 5. 全部无匹配时使用硬编码兜底值
|
||||
*/
|
||||
public Mono<CoachTimeRule> matchRule(long courseDurationMinutes) {
|
||||
return getActiveRules()
|
||||
.collectList()
|
||||
.map(rules -> doMatch(rules, courseDurationMinutes));
|
||||
}
|
||||
|
||||
private CoachTimeRule doMatch(List<CoachTimeRule> rules, long courseDurationMinutes) {
|
||||
// 过滤出匹配的规则
|
||||
List<CoachTimeRule> matched = rules.stream()
|
||||
.filter(r -> r.matches(courseDurationMinutes))
|
||||
.toList();
|
||||
|
||||
if (!matched.isEmpty()) {
|
||||
// 选择范围最精确(区间宽度最小)的规则
|
||||
return matched.stream()
|
||||
.min(Comparator.comparingInt(CoachTimeRule::rangeWidth))
|
||||
.orElseThrow();
|
||||
}
|
||||
|
||||
// 无匹配,查找默认规则(同时也须匹配区间,防止有区间限制的默认规则覆盖不匹配的课程时长)
|
||||
CoachTimeRule defaultRule = rules.stream()
|
||||
.filter(r -> Boolean.TRUE.equals(r.getIsDefault()) && r.matches(courseDurationMinutes))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
|
||||
if (defaultRule != null) {
|
||||
logger.debug("无精确匹配规则,回退到默认规则 id={}", defaultRule.getId());
|
||||
return defaultRule;
|
||||
}
|
||||
|
||||
// 兜底:返回硬编码默认值构造的虚拟规则
|
||||
logger.warn("无匹配规则且默认规则也不匹配课程时长{}分钟,使用硬编码兜底值", courseDurationMinutes);
|
||||
return buildFallbackRule(courseDurationMinutes);
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造硬编码兜底规则(不持久化,仅在内存中使用)
|
||||
*/
|
||||
private CoachTimeRule buildFallbackRule(long courseDurationMinutes) {
|
||||
CoachTimeRule fallback = new CoachTimeRule();
|
||||
fallback.setEndGrace(FALLBACK_END_GRACE);
|
||||
if (courseDurationMinutes >= ONE_HOUR_MINUTES) {
|
||||
fallback.setNormalWindow(FALLBACK_LONG_NORMAL_WINDOW);
|
||||
fallback.setLateWindow(FALLBACK_LONG_LATE_WINDOW);
|
||||
} else {
|
||||
fallback.setNormalWindow(Math.max(1, (int) (courseDurationMinutes * FALLBACK_SHORT_NORMAL_RATIO)));
|
||||
fallback.setLateWindow(Math.max(1, (int) (courseDurationMinutes * FALLBACK_SHORT_LATE_RATIO)));
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
|
||||
// ==================== 缓存管理 ====================
|
||||
|
||||
/**
|
||||
* 获取所有启用规则(带 Redis 缓存)
|
||||
*/
|
||||
private Flux<CoachTimeRule> getActiveRules() {
|
||||
return redisUtil.get(RedisKeyConstants.COACH_TIME_RULES)
|
||||
.flatMapMany(cached -> {
|
||||
@SuppressWarnings("unchecked")
|
||||
List<CoachTimeRule> list = (List<CoachTimeRule>) cached;
|
||||
logger.debug("从 Redis 缓存加载教练时间规则,共 {} 条", list.size());
|
||||
return Flux.fromIterable(list);
|
||||
})
|
||||
.switchIfEmpty(Flux.defer(() -> {
|
||||
logger.debug("Redis 缓存未命中,从 DB 加载教练时间规则");
|
||||
return repository.findByStatusAndDeletedAtIsNull("1")
|
||||
.collectList()
|
||||
.flatMapMany(list -> {
|
||||
redisUtil.setWithExpire(RedisKeyConstants.COACH_TIME_RULES, list, CACHE_TTL_SECONDS)
|
||||
.subscribe(
|
||||
ok -> logger.debug("教练时间规则已写入 Redis 缓存,共 {} 条", list.size()),
|
||||
err -> logger.warn("教练时间规则写入 Redis 缓存失败: {}", err.getMessage())
|
||||
);
|
||||
return Flux.fromIterable(list);
|
||||
});
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* 写操作后清除缓存(热更新入口)
|
||||
*/
|
||||
private void invalidateCache() {
|
||||
redisUtil.delete(RedisKeyConstants.COACH_TIME_RULES)
|
||||
.subscribe(
|
||||
count -> logger.info("教练时间规则缓存已清除"),
|
||||
err -> logger.warn("教练时间规则缓存清除失败: {}", err.getMessage())
|
||||
);
|
||||
}
|
||||
|
||||
// ==================== CRUD ====================
|
||||
|
||||
public Flux<CoachTimeRule> getAllRules() {
|
||||
return repository.findByDeletedAtIsNull();
|
||||
}
|
||||
|
||||
public Mono<CoachTimeRule> getRuleById(Long id) {
|
||||
return repository.findById(id)
|
||||
.switchIfEmpty(Mono.error(new RuntimeException("规则不存在")));
|
||||
}
|
||||
|
||||
public Mono<CoachTimeRule> createRule(CoachTimeRule rule) {
|
||||
return validateRule(rule)
|
||||
.then(Mono.defer(() -> {
|
||||
if (Boolean.TRUE.equals(rule.getIsDefault())) {
|
||||
return repository.unsetOtherDefaults(null).then(repository.save(rule));
|
||||
}
|
||||
return repository.save(rule);
|
||||
}))
|
||||
.doOnSuccess(r -> invalidateCache());
|
||||
}
|
||||
|
||||
public Mono<CoachTimeRule> updateRule(Long id, CoachTimeRule rule) {
|
||||
return repository.findById(id)
|
||||
.switchIfEmpty(Mono.error(new RuntimeException("规则不存在")))
|
||||
.flatMap(existing -> {
|
||||
existing.setMinDuration(rule.getMinDuration());
|
||||
existing.setMaxDuration(rule.getMaxDuration());
|
||||
existing.setNormalWindow(rule.getNormalWindow());
|
||||
existing.setLateWindow(rule.getLateWindow());
|
||||
existing.setEndGrace(rule.getEndGrace());
|
||||
existing.setIsDefault(rule.getIsDefault());
|
||||
existing.setSortOrder(rule.getSortOrder());
|
||||
existing.setStatus(rule.getStatus());
|
||||
existing.setRemark(rule.getRemark());
|
||||
existing.setUpdateBy(rule.getUpdateBy());
|
||||
return validateRule(existing)
|
||||
.then(Mono.defer(() -> {
|
||||
if (Boolean.TRUE.equals(existing.getIsDefault())) {
|
||||
return repository.unsetOtherDefaults(id).then(repository.save(existing));
|
||||
}
|
||||
return repository.save(existing);
|
||||
}));
|
||||
})
|
||||
.doOnSuccess(r -> invalidateCache());
|
||||
}
|
||||
|
||||
public Mono<Void> deleteRule(Long id) {
|
||||
return repository.deleteById(id)
|
||||
.doOnSuccess(v -> invalidateCache());
|
||||
}
|
||||
|
||||
// ==================== 校验 ====================
|
||||
|
||||
/**
|
||||
* 校验规则字段合法性
|
||||
*/
|
||||
private Mono<Void> validateRule(CoachTimeRule rule) {
|
||||
Integer normalWindow = rule.getNormalWindow();
|
||||
if (normalWindow == null || normalWindow < 1 || normalWindow > 1440) {
|
||||
return Mono.error(new RuntimeException("正常开课窗口必须为 1-1440 之间的整数"));
|
||||
}
|
||||
Integer lateWindow = rule.getLateWindow();
|
||||
if (lateWindow == null || lateWindow < normalWindow || lateWindow > 1440) {
|
||||
return Mono.error(new RuntimeException("迟到/缺席窗口必须 >= 正常开课窗口(" + normalWindow + ")且 <= 1440"));
|
||||
}
|
||||
Integer endGrace = rule.getEndGrace();
|
||||
if (endGrace == null || endGrace < 0 || endGrace > 1440) {
|
||||
return Mono.error(new RuntimeException("结课宽限期必须为 0-1440 之间的整数"));
|
||||
}
|
||||
// 默认规则作为兜底,不允许设置时长区间
|
||||
if (Boolean.TRUE.equals(rule.getIsDefault())) {
|
||||
if (rule.getMinDuration() != null || rule.getMaxDuration() != null) {
|
||||
return Mono.error(new RuntimeException("默认规则作为兜底规则,不允许设置时长区间"));
|
||||
}
|
||||
rule.setMinDuration(null);
|
||||
rule.setMaxDuration(null);
|
||||
}
|
||||
// 区间合法性:若 minDuration 和 maxDuration 同时非空,则 maxDuration >= minDuration
|
||||
Integer minDur = rule.getMinDuration();
|
||||
Integer maxDur = rule.getMaxDuration();
|
||||
if (minDur != null && maxDur != null && maxDur < minDur) {
|
||||
return Mono.error(new RuntimeException("时长上限必须 >= 时长下限"));
|
||||
}
|
||||
return Mono.empty();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
<?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>cn.novalon.gym.manage</groupId>
|
||||
<artifactId>gym-coach-config</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>
|
||||
+15
@@ -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> {
|
||||
}
|
||||
+61
@@ -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;
|
||||
}
|
||||
}
|
||||
+42
@@ -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;
|
||||
}
|
||||
}
|
||||
+30
@@ -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;
|
||||
}
|
||||
}
|
||||
+68
@@ -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()));
|
||||
});
|
||||
}
|
||||
}
|
||||
+118
@@ -0,0 +1,118 @@
|
||||
package cn.novalon.gym.manage.coach.handler;
|
||||
|
||||
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;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Validator;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.http.HttpStatus;
|
||||
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.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 教练管理处理器(从 manage-app 迁移至 gym-coach 模块)
|
||||
*
|
||||
* @author 张翔
|
||||
* @date 2026-07-19
|
||||
*/
|
||||
@Component
|
||||
@Tag(name = "教练管理", description = "教练相关操作")
|
||||
public class CoachHandler {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(CoachHandler.class);
|
||||
private final CoachCourseService coachCourseService;
|
||||
private final Validator validator;
|
||||
|
||||
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(coachCourseService.getAllCoaches(), SysUser.class);
|
||||
}
|
||||
|
||||
@Operation(summary = "创建教练", description = "创建新教练(创建用户并分配教练角色)")
|
||||
public Mono<ServerResponse> createCoach(ServerRequest request) {
|
||||
return request.bodyToMono(CoachCreateRequest.class)
|
||||
.flatMap(req -> {
|
||||
var violations = validator.validate(req);
|
||||
if (!violations.isEmpty()) {
|
||||
Map<String, String> errors = new HashMap<>();
|
||||
violations.forEach(v -> errors.put(v.getPropertyPath().toString(), v.getMessage()));
|
||||
return ServerResponse.badRequest().bodyValue(errors);
|
||||
}
|
||||
return coachCourseService.createCoach(
|
||||
req.getUsername(), req.getPassword(),
|
||||
req.getNickname(), req.getEmail(), req.getPhone())
|
||||
.flatMap(user -> ServerResponse.status(HttpStatus.CREATED).bodyValue(user))
|
||||
.onErrorResume(e -> {
|
||||
logger.error("创建教练失败", e);
|
||||
return ServerResponse.badRequest()
|
||||
.bodyValue(Map.of("error", e.getMessage()));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@Operation(summary = "更新教练信息", description = "更新教练基本信息(昵称、邮箱、手机号)")
|
||||
public Mono<ServerResponse> updateCoach(ServerRequest request) {
|
||||
Long id = Long.valueOf(request.pathVariable("id"));
|
||||
return request.bodyToMono(CoachUpdateRequest.class)
|
||||
.flatMap(req -> coachCourseService.updateCoach(id, req.getNickname(), req.getEmail(), req.getPhone())
|
||||
.flatMap(user -> ServerResponse.ok().bodyValue(user))
|
||||
.switchIfEmpty(ServerResponse.notFound().build())
|
||||
.onErrorResume(e -> {
|
||||
logger.error("更新教练失败", e);
|
||||
return ServerResponse.badRequest()
|
||||
.bodyValue(Map.of("error", e.getMessage()));
|
||||
}));
|
||||
}
|
||||
|
||||
@Operation(summary = "禁用教练", description = "禁用教练账号,自动取消其所有非进行中的团课")
|
||||
public Mono<ServerResponse> disableCoach(ServerRequest request) {
|
||||
Long id = Long.valueOf(request.pathVariable("id"));
|
||||
return coachCourseService.disableCoach(id)
|
||||
.then(ServerResponse.ok().bodyValue(Map.of("message", "教练已禁用")))
|
||||
.onErrorResume(e -> {
|
||||
logger.error("禁用教练失败: {}", e.getMessage());
|
||||
return ServerResponse.badRequest().bodyValue(Map.of("error", e.getMessage()));
|
||||
});
|
||||
}
|
||||
|
||||
@Operation(summary = "获取教练的团课", description = "获取指定教练教授的所有团课")
|
||||
public Mono<ServerResponse> getCoachCourses(ServerRequest request) {
|
||||
Long id = Long.valueOf(request.pathVariable("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()));
|
||||
}
|
||||
}
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
package cn.novalon.gym.manage.coach.scheduler;
|
||||
|
||||
import cn.novalon.gym.manage.coach.enums.ViolationReason;
|
||||
import cn.novalon.gym.manage.coachconfig.service.CoachTimeRuleService;
|
||||
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 final GroupCourseDao groupCourseDao;
|
||||
private final GroupCourseBookingDao groupCourseBookingDao;
|
||||
private final DatabaseClient databaseClient;
|
||||
private final RedisUtil redisUtil;
|
||||
private final CoachTimeRuleService timeRuleService;
|
||||
|
||||
public CoachCourseScheduler(GroupCourseDao groupCourseDao,
|
||||
GroupCourseBookingDao groupCourseBookingDao,
|
||||
DatabaseClient databaseClient,
|
||||
RedisUtil redisUtil,
|
||||
CoachTimeRuleService timeRuleService) {
|
||||
this.groupCourseDao = groupCourseDao;
|
||||
this.groupCourseBookingDao = groupCourseBookingDao;
|
||||
this.databaseClient = databaseClient;
|
||||
this.redisUtil = redisUtil;
|
||||
this.timeRuleService = timeRuleService;
|
||||
}
|
||||
|
||||
/**
|
||||
* 每分钟检查一次:
|
||||
* - 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)
|
||||
.flatMap(course -> {
|
||||
long courseDurationMinutes = Duration.between(course.getStartTime(), course.getEndTime()).toMinutes();
|
||||
return timeRuleService.matchRule(courseDurationMinutes)
|
||||
.filter(rule -> {
|
||||
long minutesSinceStart = Duration.between(course.getStartTime(), now).toMinutes();
|
||||
return minutesSinceStart > rule.getLateWindow();
|
||||
})
|
||||
.flatMap(rule -> markAsCoachAbsent(course, now));
|
||||
})
|
||||
.count();
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理自动结课:status IN ('3','7') 且 end_time + endGrace 已过
|
||||
*/
|
||||
private Mono<Long> processAutoEndCourses(LocalDateTime now) {
|
||||
return groupCourseDao.findByStatusInAndEndTimeBefore(databaseClient,
|
||||
new String[]{String.valueOf(CourseStatus.IN_PROGRESS.getValue()),
|
||||
String.valueOf(CourseStatus.COACH_LATE.getValue())},
|
||||
now)
|
||||
.flatMap(course -> {
|
||||
long courseDurationMinutes = Duration.between(course.getStartTime(), course.getEndTime()).toMinutes();
|
||||
return timeRuleService.matchRule(courseDurationMinutes)
|
||||
.filter(rule -> {
|
||||
long minutesAfterEnd = Duration.between(course.getEndTime(), now).toMinutes();
|
||||
return minutesAfterEnd > rule.getEndGrace();
|
||||
})
|
||||
.flatMap(rule -> markAsAutoEnded(course, now));
|
||||
})
|
||||
.count();
|
||||
}
|
||||
|
||||
/**
|
||||
* 标记课程为教练缺席(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())
|
||||
);
|
||||
}
|
||||
}
|
||||
+342
@@ -0,0 +1,342 @@
|
||||
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.coachconfig.domain.CoachTimeRule;
|
||||
import cn.novalon.gym.manage.coachconfig.service.CoachTimeRuleService;
|
||||
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 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;
|
||||
private final CoachTimeRuleService timeRuleService;
|
||||
|
||||
public CoachCourseService(ISysUserRepository userRepository,
|
||||
ISysRoleRepository roleRepository,
|
||||
IUserRoleRepository userRoleRepository,
|
||||
IGroupCourseRepository groupCourseRepository,
|
||||
IGroupCourseBookingRepository bookingRepository,
|
||||
GroupCourseDao groupCourseDao,
|
||||
GroupCourseBookingDao groupCourseBookingDao,
|
||||
CoachViolationDao violationDao,
|
||||
DatabaseClient databaseClient,
|
||||
PasswordEncoder passwordEncoder,
|
||||
RedisUtil redisUtil,
|
||||
CoachTimeRuleService timeRuleService) {
|
||||
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;
|
||||
this.timeRuleService = timeRuleService;
|
||||
}
|
||||
|
||||
// ==================== 教练管理(从原 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("教练角色未找到,请先执行数据库迁移")));
|
||||
}
|
||||
|
||||
// ==================== 开课逻辑 ====================
|
||||
|
||||
/**
|
||||
* 教练手动开课
|
||||
* 通过 CoachTimeRuleService 匹配规则获取时间阈值,替代原硬编码逻辑
|
||||
*/
|
||||
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();
|
||||
|
||||
return timeRuleService.matchRule(courseDurationMinutes)
|
||||
.flatMap(rule -> doStartCourseWithRule(course, now, rule));
|
||||
});
|
||||
}
|
||||
|
||||
private Mono<GroupCourseEntity> doStartCourseWithRule(GroupCourseEntity course, LocalDateTime now,
|
||||
CoachTimeRule rule) {
|
||||
long minutesSinceStart = Duration.between(course.getStartTime(), now).toMinutes();
|
||||
|
||||
if (minutesSinceStart < 0) {
|
||||
return Mono.error(new RuntimeException("课程尚未到开课时间"));
|
||||
}
|
||||
if (minutesSinceStart <= rule.getNormalWindow()) {
|
||||
// 正常开课
|
||||
return doStartCourse(course, now, CourseStatus.IN_PROGRESS, null);
|
||||
}
|
||||
if (minutesSinceStart <= rule.getLateWindow()) {
|
||||
// 教练迟到
|
||||
return recordViolation(course.getCoachId(), course.getId(), now, ViolationReason.COACH_LATE)
|
||||
.then(doStartCourse(course, now, CourseStatus.COACH_LATE, ViolationReason.COACH_LATE));
|
||||
}
|
||||
// 超过 lateWindow,拒绝
|
||||
return Mono.error(new RuntimeException("已超过开课时间" + rule.getLateWindow() + "分钟,无法开课"));
|
||||
}
|
||||
|
||||
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) 状态下结课
|
||||
* 必须在标注结课时间 + endGrace 分钟内
|
||||
*/
|
||||
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 courseDurationMinutes = Duration.between(course.getStartTime(), course.getEndTime()).toMinutes();
|
||||
|
||||
return timeRuleService.matchRule(courseDurationMinutes)
|
||||
.flatMap(rule -> {
|
||||
long minutesAfterEnd = Duration.between(course.getEndTime(), now).toMinutes();
|
||||
|
||||
if (minutesAfterEnd > rule.getEndGrace()) {
|
||||
return Mono.error(new RuntimeException(
|
||||
"已超过结课时间" + rule.getEndGrace() + "分钟,请等待系统自动结课"));
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package cn.novalon.gym.manage.coach.entity;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@DisplayName("CoachViolationEntity 单元测试")
|
||||
class CoachViolationEntityTest {
|
||||
|
||||
@Test
|
||||
@DisplayName("无参构造和setter/getter应正确设置和读取coachId")
|
||||
void shouldSetAndGetCoachId() {
|
||||
CoachViolationEntity entity = new CoachViolationEntity();
|
||||
entity.setCoachId(100L);
|
||||
assertThat(entity.getCoachId()).isEqualTo(100L);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("无参构造和setter/getter应正确设置和读取courseId")
|
||||
void shouldSetAndGetCourseId() {
|
||||
CoachViolationEntity entity = new CoachViolationEntity();
|
||||
entity.setCourseId(200L);
|
||||
assertThat(entity.getCourseId()).isEqualTo(200L);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("无参构造和setter/getter应正确设置和读取violationTime")
|
||||
void shouldSetAndGetViolationTime() {
|
||||
CoachViolationEntity entity = new CoachViolationEntity();
|
||||
LocalDateTime time = LocalDateTime.of(2026, 7, 20, 14, 30, 0);
|
||||
entity.setViolationTime(time);
|
||||
assertThat(entity.getViolationTime()).isEqualTo(time);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("无参构造和setter/getter应正确设置和读取violationReason")
|
||||
void shouldSetAndGetViolationReason() {
|
||||
CoachViolationEntity entity = new CoachViolationEntity();
|
||||
entity.setViolationReason("COACH_LATE");
|
||||
assertThat(entity.getViolationReason()).isEqualTo("COACH_LATE");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("所有字段应可正常设置和读取")
|
||||
void shouldSetAndGetAllFieldsCorrectly() {
|
||||
CoachViolationEntity entity = new CoachViolationEntity();
|
||||
LocalDateTime time = LocalDateTime.of(2026, 7, 22, 9, 0, 0);
|
||||
|
||||
entity.setCoachId(1L);
|
||||
entity.setCourseId(2L);
|
||||
entity.setViolationTime(time);
|
||||
entity.setViolationReason("COACH_ABSENT");
|
||||
|
||||
assertThat(entity.getCoachId()).isEqualTo(1L);
|
||||
assertThat(entity.getCourseId()).isEqualTo(2L);
|
||||
assertThat(entity.getViolationTime()).isEqualTo(time);
|
||||
assertThat(entity.getViolationReason()).isEqualTo("COACH_ABSENT");
|
||||
}
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
package cn.novalon.gym.manage.coach.enums;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.params.ParameterizedTest;
|
||||
import org.junit.jupiter.params.provider.EnumSource;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@DisplayName("ViolationReason 枚举单元测试")
|
||||
class CoachEnumsTest {
|
||||
|
||||
@Test
|
||||
@DisplayName("COACH_LATE应具有正确的name和description")
|
||||
void coachLateShouldHaveCorrectValueAndDesc() {
|
||||
assertThat(ViolationReason.COACH_LATE.getValue()).isEqualTo("COACH_LATE");
|
||||
assertThat(ViolationReason.COACH_LATE.getDesc()).isEqualTo("教练迟到");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("COACH_ABSENT应具有正确的name和description")
|
||||
void coachAbsentShouldHaveCorrectValueAndDesc() {
|
||||
assertThat(ViolationReason.COACH_ABSENT.getValue()).isEqualTo("COACH_ABSENT");
|
||||
assertThat(ViolationReason.COACH_ABSENT.getDesc()).isEqualTo("教练缺席");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("NOT_MANUAL_END应具有正确的name和description")
|
||||
void notManualEndShouldHaveCorrectValueAndDesc() {
|
||||
assertThat(ViolationReason.NOT_MANUAL_END.getValue()).isEqualTo("NOT_MANUAL_END");
|
||||
assertThat(ViolationReason.NOT_MANUAL_END.getDesc()).isEqualTo("教练未手动结课");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("枚举值总数应为3个")
|
||||
void shouldHaveThreeValues() {
|
||||
assertThat(ViolationReason.values()).hasSize(3);
|
||||
}
|
||||
|
||||
@ParameterizedTest
|
||||
@EnumSource(ViolationReason.class)
|
||||
@DisplayName("每个枚举值的getValue和getDesc均不应为空")
|
||||
void everyEnumShouldHaveNonEmptyValueAndDesc(ViolationReason reason) {
|
||||
assertThat(reason.getValue()).isNotBlank();
|
||||
assertThat(reason.getDesc()).isNotBlank();
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("name()方法应返回枚举常量名称")
|
||||
void nameShouldReturnEnumConstantName() {
|
||||
assertThat(ViolationReason.COACH_LATE.name()).isEqualTo("COACH_LATE");
|
||||
assertThat(ViolationReason.COACH_ABSENT.name()).isEqualTo("COACH_ABSENT");
|
||||
assertThat(ViolationReason.NOT_MANUAL_END.name()).isEqualTo("NOT_MANUAL_END");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("valueOf应正确解析枚举常量名称")
|
||||
void valueOfShouldParseCorrectly() {
|
||||
assertThat(ViolationReason.valueOf("COACH_LATE")).isEqualTo(ViolationReason.COACH_LATE);
|
||||
assertThat(ViolationReason.valueOf("COACH_ABSENT")).isEqualTo(ViolationReason.COACH_ABSENT);
|
||||
assertThat(ViolationReason.valueOf("NOT_MANUAL_END")).isEqualTo(ViolationReason.NOT_MANUAL_END);
|
||||
}
|
||||
}
|
||||
+176
@@ -0,0 +1,176 @@
|
||||
package cn.novalon.gym.manage.coach.handler;
|
||||
|
||||
import cn.novalon.gym.manage.coach.service.CoachCourseService;
|
||||
import cn.novalon.gym.manage.sys.core.domain.SysUser;
|
||||
import cn.novalon.gym.manage.groupcourse.domain.GroupCourse;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.HttpStatus;
|
||||
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 jakarta.validation.Validator;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class CoachHandlerTest {
|
||||
|
||||
@Mock
|
||||
private CoachCourseService coachCourseService;
|
||||
|
||||
@Mock
|
||||
private Validator validator;
|
||||
|
||||
private CoachHandler coachHandler;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
coachHandler = new CoachHandler(coachCourseService, validator);
|
||||
}
|
||||
|
||||
// ==================== getAllCoaches ====================
|
||||
|
||||
@Test
|
||||
void getAllCoaches_shouldReturnOkWithCoachList() {
|
||||
SysUser coach = mock(SysUser.class);
|
||||
when(coachCourseService.getAllCoaches()).thenReturn(Flux.just(coach));
|
||||
|
||||
MockServerRequest request = MockServerRequest.builder().build();
|
||||
|
||||
Mono<ServerResponse> result = coachHandler.getAllCoaches(request);
|
||||
|
||||
ServerResponse response = result.block();
|
||||
assertThat(response.statusCode()).isEqualTo(HttpStatus.OK);
|
||||
|
||||
verify(coachCourseService).getAllCoaches();
|
||||
}
|
||||
|
||||
@Test
|
||||
void getAllCoaches_shouldReturnOkWhenEmptyList() {
|
||||
when(coachCourseService.getAllCoaches()).thenReturn(Flux.empty());
|
||||
|
||||
MockServerRequest request = MockServerRequest.builder().build();
|
||||
|
||||
Mono<ServerResponse> result = coachHandler.getAllCoaches(request);
|
||||
|
||||
ServerResponse response = result.block();
|
||||
assertThat(response.statusCode()).isEqualTo(HttpStatus.OK);
|
||||
}
|
||||
|
||||
// ==================== getCoachCourses ====================
|
||||
|
||||
@Test
|
||||
void getCoachCourses_shouldReturnOkWithCourses() {
|
||||
GroupCourse course = mock(GroupCourse.class);
|
||||
when(coachCourseService.getCoachCourses(anyLong())).thenReturn(Flux.just(course));
|
||||
|
||||
MockServerRequest request = MockServerRequest.builder()
|
||||
.pathVariable("id", "1")
|
||||
.build();
|
||||
|
||||
Mono<ServerResponse> result = coachHandler.getCoachCourses(request);
|
||||
|
||||
ServerResponse response = result.block();
|
||||
assertThat(response.statusCode()).isEqualTo(HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getCoachCourses_shouldReturnOkWhenEmpty() {
|
||||
when(coachCourseService.getCoachCourses(anyLong())).thenReturn(Flux.empty());
|
||||
|
||||
MockServerRequest request = MockServerRequest.builder()
|
||||
.pathVariable("id", "999")
|
||||
.build();
|
||||
|
||||
Mono<ServerResponse> result = coachHandler.getCoachCourses(request);
|
||||
|
||||
ServerResponse response = result.block();
|
||||
assertThat(response.statusCode()).isEqualTo(HttpStatus.OK);
|
||||
}
|
||||
|
||||
// ==================== disableCoach ====================
|
||||
|
||||
@Test
|
||||
void disableCoach_shouldReturnOkWhenDisabled() {
|
||||
when(coachCourseService.disableCoach(anyLong())).thenReturn(Mono.empty());
|
||||
|
||||
MockServerRequest request = MockServerRequest.builder()
|
||||
.pathVariable("id", "1")
|
||||
.build();
|
||||
|
||||
Mono<ServerResponse> result = coachHandler.disableCoach(request);
|
||||
|
||||
ServerResponse response = result.block();
|
||||
assertThat(response.statusCode()).isEqualTo(HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Test
|
||||
void disableCoach_shouldReturnBadRequestOnError() {
|
||||
when(coachCourseService.disableCoach(anyLong()))
|
||||
.thenReturn(Mono.error(new RuntimeException("Coach not found")));
|
||||
|
||||
MockServerRequest request = MockServerRequest.builder()
|
||||
.pathVariable("id", "999")
|
||||
.build();
|
||||
|
||||
Mono<ServerResponse> result = coachHandler.disableCoach(request);
|
||||
|
||||
ServerResponse response = result.block();
|
||||
assertThat(response.statusCode()).isEqualTo(HttpStatus.BAD_REQUEST);
|
||||
}
|
||||
|
||||
// ==================== getViolationCounts ====================
|
||||
|
||||
@Test
|
||||
void getViolationCounts_shouldReturnOk() {
|
||||
when(coachCourseService.getViolationCounts()).thenReturn(Flux.empty());
|
||||
|
||||
MockServerRequest request = MockServerRequest.builder().build();
|
||||
|
||||
Mono<ServerResponse> result = coachHandler.getViolationCounts(request);
|
||||
|
||||
ServerResponse response = result.block();
|
||||
assertThat(response.statusCode()).isEqualTo(HttpStatus.OK);
|
||||
}
|
||||
|
||||
// ==================== getCoachViolations ====================
|
||||
|
||||
@Test
|
||||
void getCoachViolations_shouldReturnOkWithViolations() {
|
||||
when(coachCourseService.getCoachViolations(anyLong())).thenReturn(Flux.just(Map.of("violationId", 1, "reason", "迟到")));
|
||||
|
||||
MockServerRequest request = MockServerRequest.builder()
|
||||
.pathVariable("id", "1")
|
||||
.build();
|
||||
|
||||
Mono<ServerResponse> result = coachHandler.getCoachViolations(request);
|
||||
|
||||
ServerResponse response = result.block();
|
||||
assertThat(response.statusCode()).isEqualTo(HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getCoachViolations_shouldReturnEmptyListWhenNone() {
|
||||
when(coachCourseService.getCoachViolations(anyLong())).thenReturn(Flux.empty());
|
||||
|
||||
MockServerRequest request = MockServerRequest.builder()
|
||||
.pathVariable("id", "999")
|
||||
.build();
|
||||
|
||||
Mono<ServerResponse> result = coachHandler.getCoachViolations(request);
|
||||
|
||||
ServerResponse response = result.block();
|
||||
assertThat(response.statusCode()).isEqualTo(HttpStatus.OK);
|
||||
}
|
||||
}
|
||||
@@ -67,7 +67,12 @@
|
||||
<dependency>
|
||||
<groupId>org.apache.poi</groupId>
|
||||
<artifactId>poi-ooxml</artifactId>
|
||||
<version>5.2.5</version>
|
||||
</dependency>
|
||||
|
||||
<!-- Fix commons-compress version for POI compatibility -->
|
||||
<dependency>
|
||||
<groupId>org.apache.commons</groupId>
|
||||
<artifactId>commons-compress</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Gym Modules -->
|
||||
|
||||
+172
@@ -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,175 @@ 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_key = 'coach' 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();
|
||||
}
|
||||
|
||||
// ========== 教练业绩统计 ==========
|
||||
|
||||
/**
|
||||
* 获取所有教练基本信息(ID、昵称、用户名)
|
||||
*/
|
||||
public reactor.core.publisher.Flux<java.util.Map<String, Object>> getAllCoachesWithInfo() {
|
||||
return databaseClient.sql("""
|
||||
SELECT u.id, u.nickname, u.username
|
||||
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_key = 'coach' AND u.deleted_at IS NULL
|
||||
ORDER BY u.id
|
||||
""")
|
||||
.fetch()
|
||||
.all();
|
||||
}
|
||||
|
||||
/**
|
||||
* 按教练统计已完成课程数(status=2或6)
|
||||
*/
|
||||
public reactor.core.publisher.Flux<java.util.Map<String, Object>> countCompletedCoursesByCoach(LocalDateTime startTime, LocalDateTime endTime) {
|
||||
return databaseClient.sql("""
|
||||
SELECT coach_id, COUNT(*) AS count
|
||||
FROM group_course
|
||||
WHERE end_time >= :startTime AND end_time < :endTime
|
||||
AND status IN ('2', '6') AND deleted_at IS NULL
|
||||
GROUP BY coach_id
|
||||
""")
|
||||
.bind("startTime", startTime)
|
||||
.bind("endTime", endTime)
|
||||
.fetch()
|
||||
.all();
|
||||
}
|
||||
|
||||
/**
|
||||
* 按教练统计出席人次(booking.status IN ('2','4','5'):已出席 + 教练缺席 + 迟到)
|
||||
*/
|
||||
public reactor.core.publisher.Flux<java.util.Map<String, Object>> countAttendedStudentsByCoach(LocalDateTime startTime, LocalDateTime endTime) {
|
||||
return databaseClient.sql("""
|
||||
SELECT gc.coach_id, COUNT(*) AS count
|
||||
FROM group_course_booking b
|
||||
INNER JOIN group_course gc ON b.course_id = gc.id
|
||||
WHERE b.status IN ('2', '4', '5') AND b.deleted_at IS NULL
|
||||
AND gc.deleted_at IS NULL
|
||||
AND gc.end_time >= :startTime AND gc.end_time < :endTime
|
||||
GROUP BY gc.coach_id
|
||||
""")
|
||||
.bind("startTime", startTime)
|
||||
.bind("endTime", endTime)
|
||||
.fetch()
|
||||
.all();
|
||||
}
|
||||
|
||||
/**
|
||||
* 按教练统计总预约数(仅 status='0' 已预约,用于出勤率分母)
|
||||
*/
|
||||
public reactor.core.publisher.Flux<java.util.Map<String, Object>> countTotalBookingsByCoach(LocalDateTime startTime, LocalDateTime endTime) {
|
||||
return databaseClient.sql("""
|
||||
SELECT gc.coach_id, COUNT(*) AS count
|
||||
FROM group_course_booking b
|
||||
INNER JOIN group_course gc ON b.course_id = gc.id
|
||||
WHERE b.status = '0' AND b.deleted_at IS NULL
|
||||
AND gc.deleted_at IS NULL
|
||||
AND gc.end_time >= :startTime AND gc.end_time < :endTime
|
||||
GROUP BY gc.coach_id
|
||||
""")
|
||||
.bind("startTime", startTime)
|
||||
.bind("endTime", endTime)
|
||||
.fetch()
|
||||
.all();
|
||||
}
|
||||
|
||||
/**
|
||||
* 按教练获取满员率明细(每个已完成课程的出席人数和最大容量)
|
||||
*/
|
||||
public reactor.core.publisher.Flux<java.util.Map<String, Object>> getFillRateDetailByCoach(LocalDateTime startTime, LocalDateTime endTime) {
|
||||
return databaseClient.sql("""
|
||||
SELECT gc.coach_id, gc.max_members, COUNT(b.id) AS attended
|
||||
FROM group_course gc
|
||||
LEFT JOIN group_course_booking b ON gc.id = b.course_id AND b.status IN ('2','4','5') AND b.deleted_at IS NULL
|
||||
WHERE gc.end_time >= :startTime AND gc.end_time < :endTime
|
||||
AND gc.status IN ('2', '6') AND gc.deleted_at IS NULL
|
||||
GROUP BY gc.coach_id, gc.id, gc.max_members
|
||||
""")
|
||||
.bind("startTime", startTime)
|
||||
.bind("endTime", endTime)
|
||||
.fetch()
|
||||
.all();
|
||||
}
|
||||
|
||||
/**
|
||||
* 按教练统计违规次数
|
||||
*/
|
||||
public reactor.core.publisher.Flux<java.util.Map<String, Object>> countViolationsByCoach(LocalDateTime startTime, LocalDateTime endTime) {
|
||||
return databaseClient.sql("""
|
||||
SELECT coach_id, COUNT(*) AS count
|
||||
FROM coach_violation
|
||||
WHERE violation_time >= :startTime AND violation_time < :endTime AND deleted_at IS NULL
|
||||
GROUP BY coach_id
|
||||
""")
|
||||
.bind("startTime", startTime)
|
||||
.bind("endTime", endTime)
|
||||
.fetch()
|
||||
.all();
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package cn.novalon.gym.manage.datacount.domain;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
/**
|
||||
* 教练个人业绩
|
||||
*
|
||||
* @author system
|
||||
* @date 2026-07-22
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class CoachPerformance {
|
||||
|
||||
/** 教练ID */
|
||||
private Long coachId;
|
||||
|
||||
/** 教练昵称 */
|
||||
private String coachName;
|
||||
|
||||
/** 教练头像 */
|
||||
private String avatar;
|
||||
|
||||
/** 授课量(已完成课程数) */
|
||||
private Long completedCourses;
|
||||
|
||||
/** 出席人次 */
|
||||
private Long attendedStudents;
|
||||
|
||||
/** 总非取消预约数 */
|
||||
private Long totalBookings;
|
||||
|
||||
/** 出勤率(百分比) */
|
||||
private Double attendanceRate;
|
||||
|
||||
/** 满员率(百分比) */
|
||||
private Double fillRate;
|
||||
|
||||
/** 违规次数 */
|
||||
private Long violationCount;
|
||||
|
||||
/** 综合评分 */
|
||||
private Double compositeScore;
|
||||
}
|
||||
+40
@@ -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;
|
||||
}
|
||||
+6
@@ -59,6 +59,12 @@ public class DataStatistics {
|
||||
public static final String WEEK = "WEEK";
|
||||
/** 月统计 */
|
||||
public static final String MONTH = "MONTH";
|
||||
/** 近30天 */
|
||||
public static final String LAST_30_DAYS = "LAST_30_DAYS";
|
||||
/** 近90天 */
|
||||
public static final String LAST_90_DAYS = "LAST_90_DAYS";
|
||||
/** 今年 */
|
||||
public static final String YEAR = "YEAR";
|
||||
|
||||
private PeriodType() {}
|
||||
}
|
||||
|
||||
+5
@@ -37,6 +37,11 @@ public class StatisticsSummary {
|
||||
*/
|
||||
private SignInStatistics signInStatistics;
|
||||
|
||||
/**
|
||||
* 教练统计数据
|
||||
*/
|
||||
private CoachStatistics coachStatistics;
|
||||
|
||||
/**
|
||||
* 统计数据生成时间
|
||||
*/
|
||||
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
package cn.novalon.gym.manage.datacount.handler;
|
||||
|
||||
import cn.novalon.gym.manage.datacount.domain.CoachPerformance;
|
||||
import cn.novalon.gym.manage.datacount.domain.StatisticsQuery;
|
||||
import cn.novalon.gym.manage.datacount.service.IDataStatisticsService;
|
||||
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.beans.factory.annotation.Autowired;
|
||||
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.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
|
||||
/**
|
||||
* 教练业绩 Handler
|
||||
*
|
||||
* @author system
|
||||
* @date 2026-07-22
|
||||
*/
|
||||
@Component
|
||||
@Tag(name = "教练业绩", description = "教练业绩统计相关操作")
|
||||
public class CoachPerformanceHandler {
|
||||
|
||||
private static final Logger log = LoggerFactory.getLogger(CoachPerformanceHandler.class);
|
||||
|
||||
@Autowired
|
||||
private IDataStatisticsService dataStatisticsService;
|
||||
|
||||
@Operation(summary = "获取教练业绩排行榜", description = "获取所有教练的业绩排名(按综合评分降序)")
|
||||
public Mono<ServerResponse> getCoachPerformanceRanking(ServerRequest request) {
|
||||
StatisticsQuery query = buildQueryFromRequest(request);
|
||||
|
||||
return dataStatisticsService.getCoachPerformanceList(query)
|
||||
.collectList()
|
||||
.flatMap(list -> ServerResponse.ok().bodyValue(list))
|
||||
.onErrorResume(e -> {
|
||||
log.error("获取教练业绩排行榜失败", e);
|
||||
return ServerResponse.ok().bodyValue(java.util.List.of());
|
||||
});
|
||||
}
|
||||
|
||||
@Operation(summary = "获取指定教练业绩", description = "获取单个教练的业绩详情")
|
||||
public Mono<ServerResponse> getCoachPerformanceById(ServerRequest request) {
|
||||
Long coachId = Long.parseLong(request.pathVariable("coachId"));
|
||||
StatisticsQuery query = buildQueryFromRequest(request);
|
||||
|
||||
return dataStatisticsService.getCoachPerformanceById(coachId, query)
|
||||
.flatMap(p -> ServerResponse.ok().bodyValue(p))
|
||||
.onErrorResume(e -> {
|
||||
log.error("获取教练{}业绩失败", coachId, e);
|
||||
return ServerResponse.ok().bodyValue(
|
||||
CoachPerformance.builder().coachId(coachId).coachName("获取失败").build());
|
||||
});
|
||||
}
|
||||
|
||||
@Operation(summary = "获取当前教练业绩", description = "当前登录的教练查看自己的业绩")
|
||||
public Mono<ServerResponse> getMyPerformance(ServerRequest request) {
|
||||
return request.queryParam("coachId")
|
||||
.map(coachIdStr -> {
|
||||
Long coachId = Long.parseLong(coachIdStr);
|
||||
StatisticsQuery query = buildQueryFromRequest(request);
|
||||
return dataStatisticsService.getCoachPerformanceById(coachId, query)
|
||||
.flatMap(p -> ServerResponse.ok().bodyValue(p));
|
||||
})
|
||||
.orElse(ServerResponse.badRequest().bodyValue("缺少 coachId 参数"));
|
||||
}
|
||||
|
||||
private StatisticsQuery buildQueryFromRequest(ServerRequest request) {
|
||||
StatisticsQuery.StatisticsQueryBuilder builder = StatisticsQuery.builder();
|
||||
|
||||
request.queryParam("statType").ifPresent(builder::statType);
|
||||
request.queryParam("periodType").ifPresent(builder::periodType);
|
||||
request.queryParam("startTime").ifPresent(startTimeStr -> {
|
||||
try {
|
||||
builder.startTime(LocalDateTime.parse(startTimeStr, DateTimeFormatter.ISO_LOCAL_DATE_TIME));
|
||||
} catch (Exception e) {
|
||||
try {
|
||||
builder.startTime(LocalDateTime.parse(startTimeStr));
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
}
|
||||
});
|
||||
request.queryParam("endTime").ifPresent(endTimeStr -> {
|
||||
try {
|
||||
builder.endTime(LocalDateTime.parse(endTimeStr, DateTimeFormatter.ISO_LOCAL_DATE_TIME));
|
||||
} catch (Exception e) {
|
||||
try {
|
||||
builder.endTime(LocalDateTime.parse(endTimeStr));
|
||||
} catch (Exception ignored) {
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return builder.build();
|
||||
}
|
||||
}
|
||||
+17
@@ -75,4 +75,21 @@ public interface IDataStatisticsService {
|
||||
* @return 统计数据
|
||||
*/
|
||||
Mono<StatisticsSummary> getStatisticsSummaryWithCache(StatisticsQuery query);
|
||||
|
||||
/**
|
||||
* 获取教练业绩排行榜
|
||||
*
|
||||
* @param query 查询条件
|
||||
* @return 教练业绩列表(按综合评分降序)
|
||||
*/
|
||||
reactor.core.publisher.Flux<CoachPerformance> getCoachPerformanceList(StatisticsQuery query);
|
||||
|
||||
/**
|
||||
* 获取单个教练业绩
|
||||
*
|
||||
* @param coachId 教练ID
|
||||
* @param query 查询条件
|
||||
* @return 单个教练业绩
|
||||
*/
|
||||
Mono<CoachPerformance> getCoachPerformanceById(Long coachId, StatisticsQuery query);
|
||||
}
|
||||
|
||||
+190
-7
@@ -22,8 +22,11 @@ import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.temporal.TemporalAdjusters;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 数据统计服务实现类
|
||||
@@ -171,18 +174,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());
|
||||
}
|
||||
@@ -458,13 +490,16 @@ public class DataStatisticsServiceImpl implements IDataStatisticsService {
|
||||
String periodType = query.getPeriodType();
|
||||
|
||||
if (DataStatistics.PeriodType.WEEK.equals(periodType)) {
|
||||
// 周统计:本周一
|
||||
return today.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)).atStartOfDay();
|
||||
} else if (DataStatistics.PeriodType.MONTH.equals(periodType)) {
|
||||
// 月统计:本月第一天
|
||||
return today.withDayOfMonth(1).atStartOfDay();
|
||||
} else if (DataStatistics.PeriodType.LAST_30_DAYS.equals(periodType)) {
|
||||
return today.minusDays(29).atStartOfDay();
|
||||
} else if (DataStatistics.PeriodType.LAST_90_DAYS.equals(periodType)) {
|
||||
return today.minusDays(89).atStartOfDay();
|
||||
} else if (DataStatistics.PeriodType.YEAR.equals(periodType)) {
|
||||
return today.withDayOfYear(1).atStartOfDay();
|
||||
} else {
|
||||
// 日统计:当天零点
|
||||
return today.atStartOfDay();
|
||||
}
|
||||
}
|
||||
@@ -478,17 +513,156 @@ public class DataStatisticsServiceImpl implements IDataStatisticsService {
|
||||
String periodType = query.getPeriodType();
|
||||
|
||||
if (DataStatistics.PeriodType.WEEK.equals(periodType)) {
|
||||
// 周统计:本周日 23:59:59
|
||||
return today.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY)).atTime(23, 59, 59);
|
||||
} else if (DataStatistics.PeriodType.MONTH.equals(periodType)) {
|
||||
// 月统计:本月最后一天 23:59:59
|
||||
return today.with(TemporalAdjusters.lastDayOfMonth()).atTime(23, 59, 59);
|
||||
} else if (DataStatistics.PeriodType.LAST_30_DAYS.equals(periodType)
|
||||
|| DataStatistics.PeriodType.LAST_90_DAYS.equals(periodType)
|
||||
|| DataStatistics.PeriodType.YEAR.equals(periodType)) {
|
||||
return LocalDateTime.now();
|
||||
} else {
|
||||
// 日统计:当前时间
|
||||
return LocalDateTime.now();
|
||||
}
|
||||
}
|
||||
|
||||
// ========== 教练业绩统计 ==========
|
||||
|
||||
@Override
|
||||
public reactor.core.publisher.Flux<CoachPerformance> getCoachPerformanceList(StatisticsQuery query) {
|
||||
LocalDateTime startTime = getStartTime(query);
|
||||
LocalDateTime endTime = getEndTime(query);
|
||||
|
||||
// 1. 获取所有教练基本信息
|
||||
Mono<Map<Long, Map<String, Object>>> coachesMono = dataStatisticsDao.getAllCoachesWithInfo()
|
||||
.collectMap(row -> ((Number) row.get("id")).longValue(), row -> row);
|
||||
|
||||
// 2. 各教练授课量
|
||||
Mono<Map<Long, Long>> coursesMono = dataStatisticsDao.countCompletedCoursesByCoach(startTime, endTime)
|
||||
.collectMap(row -> ((Number) row.get("coach_id")).longValue(),
|
||||
row -> ((Number) row.get("count")).longValue());
|
||||
|
||||
// 3. 各教练出席人次
|
||||
Mono<Map<Long, Long>> attendedMono = dataStatisticsDao.countAttendedStudentsByCoach(startTime, endTime)
|
||||
.collectMap(row -> ((Number) row.get("coach_id")).longValue(),
|
||||
row -> ((Number) row.get("count")).longValue());
|
||||
|
||||
// 4. 各教练总预约数(非取消)
|
||||
Mono<Map<Long, Long>> totalBookingsMono = dataStatisticsDao.countTotalBookingsByCoach(startTime, endTime)
|
||||
.collectMap(row -> ((Number) row.get("coach_id")).longValue(),
|
||||
row -> ((Number) row.get("count")).longValue());
|
||||
|
||||
// 5. 满员率明细(collectMultimap 返回 Collection<V> 而非 List<V>)
|
||||
Mono<Map<Long, Collection<FillRateItem>>> fillRateMono = dataStatisticsDao.getFillRateDetailByCoach(startTime, endTime)
|
||||
.map(row -> new FillRateItem(
|
||||
((Number) row.get("coach_id")).longValue(),
|
||||
((Number) row.get("max_members")).intValue(),
|
||||
((Number) row.get("attended")).longValue()
|
||||
))
|
||||
.collectMultimap(FillRateItem::coachId);
|
||||
|
||||
// 6. 各教练违规次数
|
||||
Mono<Map<Long, Long>> violationsMono = dataStatisticsDao.countViolationsByCoach(startTime, endTime)
|
||||
.collectMap(row -> ((Number) row.get("coach_id")).longValue(),
|
||||
row -> ((Number) row.get("count")).longValue());
|
||||
|
||||
return Mono.zip(coachesMono, coursesMono, attendedMono, totalBookingsMono, fillRateMono, violationsMono)
|
||||
.flatMapMany(tuple -> {
|
||||
Map<Long, Map<String, Object>> coaches = tuple.getT1();
|
||||
Map<Long, Long> coursesMap = tuple.getT2();
|
||||
Map<Long, Long> attendedMap = tuple.getT3();
|
||||
Map<Long, Long> totalBookingsMap = tuple.getT4();
|
||||
Map<Long, Collection<FillRateItem>> fillRateMap = tuple.getT5();
|
||||
Map<Long, Long> violationsMap = tuple.getT6();
|
||||
|
||||
// 授课量百分位排名归一化
|
||||
List<Long> sortedCourses = coursesMap.values().stream()
|
||||
.sorted().collect(Collectors.toList());
|
||||
int totalCoaches = sortedCourses.size();
|
||||
|
||||
List<CoachPerformance> performances = coaches.keySet().stream()
|
||||
.map(coachId -> {
|
||||
Map<String, Object> coachInfo = coaches.get(coachId);
|
||||
long courses = coursesMap.getOrDefault(coachId, 0L);
|
||||
long attended = attendedMap.getOrDefault(coachId, 0L);
|
||||
long totalBookings = totalBookingsMap.getOrDefault(coachId, 0L);
|
||||
long violations = violationsMap.getOrDefault(coachId, 0L);
|
||||
|
||||
double attendanceRate = totalBookings > 0
|
||||
? (double) attended / totalBookings * 100 : 0;
|
||||
double fillRate = calculateFillRate(fillRateMap.getOrDefault(coachId, List.of()));
|
||||
|
||||
// 百分位排名:授课量小于当前教练的教练数 / (总教练数-1) * 100
|
||||
long coachesWithFewer = sortedCourses.stream().filter(v -> v < courses).count();
|
||||
double normalizedCourses = totalCoaches > 1
|
||||
? (double) coachesWithFewer / (totalCoaches - 1) * 100 : 100;
|
||||
|
||||
// 违规扣分:每次违规扣20分,最低0分
|
||||
double violationScore = Math.max(0, 100 - violations * 20);
|
||||
|
||||
double compositeScore = normalizedCourses * 0.35
|
||||
+ attendanceRate * 0.25 + fillRate * 0.25
|
||||
+ violationScore * 0.15;
|
||||
|
||||
return CoachPerformance.builder()
|
||||
.coachId(coachId)
|
||||
.coachName(getString(coachInfo, "nickname", getString(coachInfo, "username", "")))
|
||||
.avatar(getString(coachInfo, "avatar", null))
|
||||
.completedCourses(courses)
|
||||
.attendedStudents(attended)
|
||||
.totalBookings(totalBookings)
|
||||
.attendanceRate(Math.round(attendanceRate * 100.0) / 100.0)
|
||||
.fillRate(Math.round(fillRate * 100.0) / 100.0)
|
||||
.violationCount(violations)
|
||||
.compositeScore(Math.round(compositeScore * 100.0) / 100.0)
|
||||
.build();
|
||||
})
|
||||
.sorted((a, b) -> Double.compare(b.getCompositeScore(), a.getCompositeScore()))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
return reactor.core.publisher.Flux.fromIterable(performances);
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<CoachPerformance> getCoachPerformanceById(Long coachId, StatisticsQuery query) {
|
||||
return getCoachPerformanceList(query)
|
||||
.filter(p -> p.getCoachId().equals(coachId))
|
||||
.next()
|
||||
.switchIfEmpty(Mono.just(CoachPerformance.builder()
|
||||
.coachId(coachId)
|
||||
.coachName("未知教练")
|
||||
.completedCourses(0L)
|
||||
.attendedStudents(0L)
|
||||
.totalBookings(0L)
|
||||
.attendanceRate(0.0)
|
||||
.fillRate(0.0)
|
||||
.violationCount(0L)
|
||||
.compositeScore(0.0)
|
||||
.build()));
|
||||
}
|
||||
|
||||
/**
|
||||
* 计算满员率:各课程 (出席人数/maxMembers) 的平均值
|
||||
*/
|
||||
private double calculateFillRate(Collection<FillRateItem> items) {
|
||||
if (items == null || items.isEmpty()) return 0;
|
||||
return items.stream()
|
||||
.mapToDouble(item -> item.maxMembers > 0
|
||||
? (double) item.attended / item.maxMembers * 100 : 0)
|
||||
.average()
|
||||
.orElse(0);
|
||||
}
|
||||
|
||||
private String getString(Map<String, Object> map, String key, String defaultValue) {
|
||||
Object val = map.get(key);
|
||||
return val != null ? val.toString() : defaultValue;
|
||||
}
|
||||
|
||||
/**
|
||||
* 满员率明细项
|
||||
*/
|
||||
private record FillRateItem(Long coachId, int maxMembers, long attended) {}
|
||||
|
||||
/**
|
||||
* 根据周期类型调整时间范围
|
||||
* 用于定时任务中的周期统计
|
||||
@@ -503,6 +677,15 @@ public class DataStatisticsServiceImpl implements IDataStatisticsService {
|
||||
} else if (DataStatistics.PeriodType.MONTH.equals(periodType)) {
|
||||
startTime = date.withDayOfMonth(1).atStartOfDay();
|
||||
endTime = date.with(TemporalAdjusters.lastDayOfMonth()).atTime(23, 59, 59);
|
||||
} else if (DataStatistics.PeriodType.LAST_30_DAYS.equals(periodType)) {
|
||||
startTime = date.minusDays(29).atStartOfDay();
|
||||
endTime = date.atTime(23, 59, 59);
|
||||
} else if (DataStatistics.PeriodType.LAST_90_DAYS.equals(periodType)) {
|
||||
startTime = date.minusDays(89).atStartOfDay();
|
||||
endTime = date.atTime(23, 59, 59);
|
||||
} else if (DataStatistics.PeriodType.YEAR.equals(periodType)) {
|
||||
startTime = date.withDayOfYear(1).atStartOfDay();
|
||||
endTime = date.atTime(23, 59, 59);
|
||||
} else {
|
||||
startTime = date.atStartOfDay();
|
||||
endTime = date.plusDays(1).atStartOfDay();
|
||||
|
||||
+280
@@ -0,0 +1,280 @@
|
||||
package cn.novalon.gym.manage.datacount.domain;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Nested;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@DisplayName("DataCount 领域对象单元测试")
|
||||
class DomainObjectsTest {
|
||||
|
||||
@Nested
|
||||
@DisplayName("MemberStatistics 测试")
|
||||
class MemberStatisticsTest {
|
||||
|
||||
@Test
|
||||
@DisplayName("无参构造和setter/getter应正确设置和读取所有字段")
|
||||
void shouldSetAndGetAllFields() {
|
||||
MemberStatistics ms = new MemberStatistics();
|
||||
|
||||
ms.setStatDate("2026-07-22");
|
||||
ms.setNewMembers(150L);
|
||||
ms.setActiveMembers(320L);
|
||||
ms.setTotalMembers(5000L);
|
||||
ms.setSignInMembers(200L);
|
||||
ms.setBookingMembers(180L);
|
||||
ms.setCancelBookingMembers(15L);
|
||||
|
||||
assertThat(ms.getStatDate()).isEqualTo("2026-07-22");
|
||||
assertThat(ms.getNewMembers()).isEqualTo(150L);
|
||||
assertThat(ms.getActiveMembers()).isEqualTo(320L);
|
||||
assertThat(ms.getTotalMembers()).isEqualTo(5000L);
|
||||
assertThat(ms.getSignInMembers()).isEqualTo(200L);
|
||||
assertThat(ms.getBookingMembers()).isEqualTo(180L);
|
||||
assertThat(ms.getCancelBookingMembers()).isEqualTo(15L);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Builder构造应正确设置所有字段")
|
||||
void shouldBuildCorrectly() {
|
||||
MemberStatistics ms = MemberStatistics.builder()
|
||||
.statDate("2026-06-15")
|
||||
.newMembers(50L)
|
||||
.activeMembers(100L)
|
||||
.totalMembers(2000L)
|
||||
.signInMembers(80L)
|
||||
.bookingMembers(70L)
|
||||
.cancelBookingMembers(5L)
|
||||
.build();
|
||||
|
||||
assertThat(ms.getStatDate()).isEqualTo("2026-06-15");
|
||||
assertThat(ms.getNewMembers()).isEqualTo(50L);
|
||||
assertThat(ms.getActiveMembers()).isEqualTo(100L);
|
||||
assertThat(ms.getTotalMembers()).isEqualTo(2000L);
|
||||
assertThat(ms.getSignInMembers()).isEqualTo(80L);
|
||||
assertThat(ms.getBookingMembers()).isEqualTo(70L);
|
||||
assertThat(ms.getCancelBookingMembers()).isEqualTo(5L);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("BookingStatistics 测试")
|
||||
class BookingStatisticsTest {
|
||||
|
||||
@Test
|
||||
@DisplayName("无参构造和setter/getter应正确设置和读取所有字段")
|
||||
void shouldSetAndGetAllFields() {
|
||||
BookingStatistics bs = new BookingStatistics();
|
||||
|
||||
bs.setStatDate("2026-07-22");
|
||||
bs.setNewBookings(60L);
|
||||
bs.setCancelBookings(10L);
|
||||
bs.setAttendBookings(45L);
|
||||
bs.setAbsentBookings(5L);
|
||||
bs.setAttendanceRate(0.90);
|
||||
bs.setCancelRate(0.10);
|
||||
bs.setBookingMembers(55L);
|
||||
bs.setCancelMembers(8L);
|
||||
|
||||
assertThat(bs.getStatDate()).isEqualTo("2026-07-22");
|
||||
assertThat(bs.getNewBookings()).isEqualTo(60L);
|
||||
assertThat(bs.getCancelBookings()).isEqualTo(10L);
|
||||
assertThat(bs.getAttendBookings()).isEqualTo(45L);
|
||||
assertThat(bs.getAbsentBookings()).isEqualTo(5L);
|
||||
assertThat(bs.getAttendanceRate()).isEqualTo(0.90);
|
||||
assertThat(bs.getCancelRate()).isEqualTo(0.10);
|
||||
assertThat(bs.getBookingMembers()).isEqualTo(55L);
|
||||
assertThat(bs.getCancelMembers()).isEqualTo(8L);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Builder构造应正确设置所有字段")
|
||||
void shouldBuildCorrectly() {
|
||||
BookingStatistics bs = BookingStatistics.builder()
|
||||
.statDate("2026-07-01")
|
||||
.newBookings(30L)
|
||||
.cancelBookings(3L)
|
||||
.attendBookings(25L)
|
||||
.absentBookings(2L)
|
||||
.attendanceRate(0.83)
|
||||
.cancelRate(0.10)
|
||||
.bookingMembers(28L)
|
||||
.cancelMembers(3L)
|
||||
.build();
|
||||
|
||||
assertThat(bs.getStatDate()).isEqualTo("2026-07-01");
|
||||
assertThat(bs.getNewBookings()).isEqualTo(30L);
|
||||
assertThat(bs.getCancelBookings()).isEqualTo(3L);
|
||||
assertThat(bs.getAttendBookings()).isEqualTo(25L);
|
||||
assertThat(bs.getAbsentBookings()).isEqualTo(2L);
|
||||
assertThat(bs.getAttendanceRate()).isEqualTo(0.83);
|
||||
assertThat(bs.getCancelRate()).isEqualTo(0.10);
|
||||
assertThat(bs.getBookingMembers()).isEqualTo(28L);
|
||||
assertThat(bs.getCancelMembers()).isEqualTo(3L);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("SignInStatistics 测试")
|
||||
class SignInStatisticsTest {
|
||||
|
||||
@Test
|
||||
@DisplayName("无参构造和setter/getter应正确设置和读取所有字段")
|
||||
void shouldSetAndGetAllFields() {
|
||||
SignInStatistics ss = new SignInStatistics();
|
||||
|
||||
ss.setStatDate("2026-07-22");
|
||||
ss.setTotalSignIns(200L);
|
||||
ss.setSuccessSignIns(180L);
|
||||
ss.setFailedSignIns(20L);
|
||||
ss.setSuccessRate(0.90);
|
||||
ss.setSignInMembers(150L);
|
||||
ss.setQrCodeSignIns(100L);
|
||||
ss.setManualSignIns(50L);
|
||||
ss.setFaceSignIns(30L);
|
||||
|
||||
assertThat(ss.getStatDate()).isEqualTo("2026-07-22");
|
||||
assertThat(ss.getTotalSignIns()).isEqualTo(200L);
|
||||
assertThat(ss.getSuccessSignIns()).isEqualTo(180L);
|
||||
assertThat(ss.getFailedSignIns()).isEqualTo(20L);
|
||||
assertThat(ss.getSuccessRate()).isEqualTo(0.90);
|
||||
assertThat(ss.getSignInMembers()).isEqualTo(150L);
|
||||
assertThat(ss.getQrCodeSignIns()).isEqualTo(100L);
|
||||
assertThat(ss.getManualSignIns()).isEqualTo(50L);
|
||||
assertThat(ss.getFaceSignIns()).isEqualTo(30L);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Builder构造应正确设置所有字段")
|
||||
void shouldBuildCorrectly() {
|
||||
SignInStatistics ss = SignInStatistics.builder()
|
||||
.statDate("2026-06-01")
|
||||
.totalSignIns(500L)
|
||||
.successSignIns(480L)
|
||||
.failedSignIns(20L)
|
||||
.successRate(0.96)
|
||||
.signInMembers(400L)
|
||||
.qrCodeSignIns(300L)
|
||||
.manualSignIns(100L)
|
||||
.faceSignIns(80L)
|
||||
.build();
|
||||
|
||||
assertThat(ss.getStatDate()).isEqualTo("2026-06-01");
|
||||
assertThat(ss.getTotalSignIns()).isEqualTo(500L);
|
||||
assertThat(ss.getSuccessSignIns()).isEqualTo(480L);
|
||||
assertThat(ss.getFailedSignIns()).isEqualTo(20L);
|
||||
assertThat(ss.getSuccessRate()).isEqualTo(0.96);
|
||||
assertThat(ss.getSignInMembers()).isEqualTo(400L);
|
||||
assertThat(ss.getQrCodeSignIns()).isEqualTo(300L);
|
||||
assertThat(ss.getManualSignIns()).isEqualTo(100L);
|
||||
assertThat(ss.getFaceSignIns()).isEqualTo(80L);
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("StatisticsSummary 测试")
|
||||
class StatisticsSummaryTest {
|
||||
|
||||
@Test
|
||||
@DisplayName("无参构造和setter/getter应正确设置和读取所有字段")
|
||||
void shouldSetAndGetAllFields() {
|
||||
MemberStatistics ms = MemberStatistics.builder().newMembers(10L).build();
|
||||
BookingStatistics bs = BookingStatistics.builder().newBookings(20L).build();
|
||||
SignInStatistics ss = SignInStatistics.builder().totalSignIns(30L).build();
|
||||
CoachStatistics cs = CoachStatistics.builder().totalCoaches(5L).build();
|
||||
|
||||
StatisticsSummary summary = new StatisticsSummary();
|
||||
summary.setStatDate("2026-07-22");
|
||||
summary.setMemberStatistics(ms);
|
||||
summary.setBookingStatistics(bs);
|
||||
summary.setSignInStatistics(ss);
|
||||
summary.setCoachStatistics(cs);
|
||||
summary.setGeneratedAt("2026-07-22T10:00:00");
|
||||
|
||||
assertThat(summary.getStatDate()).isEqualTo("2026-07-22");
|
||||
assertThat(summary.getMemberStatistics()).isSameAs(ms);
|
||||
assertThat(summary.getBookingStatistics()).isSameAs(bs);
|
||||
assertThat(summary.getSignInStatistics()).isSameAs(ss);
|
||||
assertThat(summary.getCoachStatistics()).isSameAs(cs);
|
||||
assertThat(summary.getGeneratedAt()).isEqualTo("2026-07-22T10:00:00");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Builder构造应正确设置所有字段")
|
||||
void shouldBuildCorrectly() {
|
||||
MemberStatistics ms = MemberStatistics.builder().newMembers(5L).build();
|
||||
|
||||
StatisticsSummary summary = StatisticsSummary.builder()
|
||||
.statDate("2026-07-22")
|
||||
.memberStatistics(ms)
|
||||
.generatedAt("2026-07-22T12:00:00")
|
||||
.build();
|
||||
|
||||
assertThat(summary.getStatDate()).isEqualTo("2026-07-22");
|
||||
assertThat(summary.getMemberStatistics()).isSameAs(ms);
|
||||
assertThat(summary.getGeneratedAt()).isEqualTo("2026-07-22T12:00:00");
|
||||
}
|
||||
}
|
||||
|
||||
@Nested
|
||||
@DisplayName("CoachPerformance 测试")
|
||||
class CoachPerformanceTest {
|
||||
|
||||
@Test
|
||||
@DisplayName("无参构造和setter/getter应正确设置和读取所有字段")
|
||||
void shouldSetAndGetAllFields() {
|
||||
CoachPerformance cp = new CoachPerformance();
|
||||
|
||||
cp.setCoachId(1L);
|
||||
cp.setCoachName("张教练");
|
||||
cp.setAvatar("https://avatar.jpg");
|
||||
cp.setCompletedCourses(50L);
|
||||
cp.setAttendedStudents(200L);
|
||||
cp.setTotalBookings(220L);
|
||||
cp.setAttendanceRate(0.91);
|
||||
cp.setFillRate(0.85);
|
||||
cp.setViolationCount(2L);
|
||||
cp.setCompositeScore(88.5);
|
||||
|
||||
assertThat(cp.getCoachId()).isEqualTo(1L);
|
||||
assertThat(cp.getCoachName()).isEqualTo("张教练");
|
||||
assertThat(cp.getAvatar()).isEqualTo("https://avatar.jpg");
|
||||
assertThat(cp.getCompletedCourses()).isEqualTo(50L);
|
||||
assertThat(cp.getAttendedStudents()).isEqualTo(200L);
|
||||
assertThat(cp.getTotalBookings()).isEqualTo(220L);
|
||||
assertThat(cp.getAttendanceRate()).isEqualTo(0.91);
|
||||
assertThat(cp.getFillRate()).isEqualTo(0.85);
|
||||
assertThat(cp.getViolationCount()).isEqualTo(2L);
|
||||
assertThat(cp.getCompositeScore()).isEqualTo(88.5);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Builder构造应正确设置所有字段")
|
||||
void shouldBuildCorrectly() {
|
||||
CoachPerformance cp = CoachPerformance.builder()
|
||||
.coachId(2L)
|
||||
.coachName("李教练")
|
||||
.avatar("http://example.com/avatar.png")
|
||||
.completedCourses(100L)
|
||||
.attendedStudents(500L)
|
||||
.totalBookings(520L)
|
||||
.attendanceRate(0.96)
|
||||
.fillRate(0.92)
|
||||
.violationCount(0L)
|
||||
.compositeScore(95.0)
|
||||
.build();
|
||||
|
||||
assertThat(cp.getCoachId()).isEqualTo(2L);
|
||||
assertThat(cp.getCoachName()).isEqualTo("李教练");
|
||||
assertThat(cp.getAvatar()).isEqualTo("http://example.com/avatar.png");
|
||||
assertThat(cp.getCompletedCourses()).isEqualTo(100L);
|
||||
assertThat(cp.getAttendedStudents()).isEqualTo(500L);
|
||||
assertThat(cp.getTotalBookings()).isEqualTo(520L);
|
||||
assertThat(cp.getAttendanceRate()).isEqualTo(0.96);
|
||||
assertThat(cp.getFillRate()).isEqualTo(0.92);
|
||||
assertThat(cp.getViolationCount()).isEqualTo(0L);
|
||||
assertThat(cp.getCompositeScore()).isEqualTo(95.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package cn.novalon.gym.manage.datacount.domain;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
@DisplayName("StatisticsQuery 单元测试")
|
||||
class StatisticsQueryTest {
|
||||
|
||||
@Test
|
||||
@DisplayName("无参构造和setter/getter应正确设置和读取所有字段")
|
||||
void shouldSetAndGetAllFields() {
|
||||
StatisticsQuery query = new StatisticsQuery();
|
||||
LocalDateTime start = LocalDateTime.of(2026, 7, 1, 0, 0);
|
||||
LocalDateTime end = LocalDateTime.of(2026, 7, 22, 23, 59);
|
||||
|
||||
query.setStatType("MEMBER");
|
||||
query.setPeriodType("MONTH");
|
||||
query.setStartTime(start);
|
||||
query.setEndTime(end);
|
||||
query.setPage(0);
|
||||
query.setSize(20);
|
||||
|
||||
assertThat(query.getStatType()).isEqualTo("MEMBER");
|
||||
assertThat(query.getPeriodType()).isEqualTo("MONTH");
|
||||
assertThat(query.getStartTime()).isEqualTo(start);
|
||||
assertThat(query.getEndTime()).isEqualTo(end);
|
||||
assertThat(query.getPage()).isEqualTo(0);
|
||||
assertThat(query.getSize()).isEqualTo(20);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("Builder构造应正确设置所有字段")
|
||||
void shouldBuildWithAllFields() {
|
||||
LocalDateTime start = LocalDateTime.of(2026, 1, 1, 0, 0);
|
||||
LocalDateTime end = LocalDateTime.of(2026, 12, 31, 23, 59);
|
||||
|
||||
StatisticsQuery query = StatisticsQuery.builder()
|
||||
.statType("BOOKING")
|
||||
.periodType("WEEK")
|
||||
.startTime(start)
|
||||
.endTime(end)
|
||||
.page(1)
|
||||
.size(50)
|
||||
.build();
|
||||
|
||||
assertThat(query.getStatType()).isEqualTo("BOOKING");
|
||||
assertThat(query.getPeriodType()).isEqualTo("WEEK");
|
||||
assertThat(query.getStartTime()).isEqualTo(start);
|
||||
assertThat(query.getEndTime()).isEqualTo(end);
|
||||
assertThat(query.getPage()).isEqualTo(1);
|
||||
assertThat(query.getSize()).isEqualTo(50);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("全参构造应正确设置所有字段")
|
||||
void shouldConstructWithAllArgs() {
|
||||
LocalDateTime start = LocalDateTime.of(2026, 3, 1, 8, 0);
|
||||
LocalDateTime end = LocalDateTime.of(2026, 3, 31, 20, 0);
|
||||
|
||||
StatisticsQuery query = new StatisticsQuery(
|
||||
"SIGN_IN", "DAY", start, end, 2, 100);
|
||||
|
||||
assertThat(query.getStatType()).isEqualTo("SIGN_IN");
|
||||
assertThat(query.getPeriodType()).isEqualTo("DAY");
|
||||
assertThat(query.getStartTime()).isEqualTo(start);
|
||||
assertThat(query.getEndTime()).isEqualTo(end);
|
||||
assertThat(query.getPage()).isEqualTo(2);
|
||||
assertThat(query.getSize()).isEqualTo(100);
|
||||
}
|
||||
}
|
||||
+219
@@ -0,0 +1,219 @@
|
||||
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.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
import org.springframework.http.HttpStatus;
|
||||
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 java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class DataStatisticsHandlerTest {
|
||||
|
||||
@Mock
|
||||
private IDataStatisticsService dataStatisticsService;
|
||||
|
||||
private DataStatisticsHandler handler;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() throws Exception {
|
||||
handler = new DataStatisticsHandler();
|
||||
java.lang.reflect.Field field = DataStatisticsHandler.class.getDeclaredField("dataStatisticsService");
|
||||
field.setAccessible(true);
|
||||
field.set(handler, dataStatisticsService);
|
||||
}
|
||||
|
||||
// ==================== getStatisticsSummary ====================
|
||||
|
||||
@Test
|
||||
void getStatisticsSummary_shouldReturnOkWithSummary() {
|
||||
StatisticsSummary summary = createTestSummary();
|
||||
when(dataStatisticsService.getStatisticsSummaryWithCache(any(StatisticsQuery.class))).thenReturn(Mono.just(summary));
|
||||
|
||||
MockServerRequest request = MockServerRequest.builder()
|
||||
.queryParam("periodType", "DAY")
|
||||
.build();
|
||||
|
||||
Mono<ServerResponse> result = handler.getStatisticsSummary(request);
|
||||
|
||||
ServerResponse response = result.block();
|
||||
assertThat(response.statusCode()).isEqualTo(HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getStatisticsSummary_shouldReturnOkEvenOnError() {
|
||||
when(dataStatisticsService.getStatisticsSummaryWithCache(any(StatisticsQuery.class)))
|
||||
.thenReturn(Mono.error(new RuntimeException("Service error")));
|
||||
|
||||
MockServerRequest request = MockServerRequest.builder()
|
||||
.queryParam("periodType", "DAY")
|
||||
.build();
|
||||
|
||||
// Error handler returns empty/default summary with 200 OK
|
||||
Mono<ServerResponse> result = handler.getStatisticsSummary(request);
|
||||
|
||||
ServerResponse response = result.block();
|
||||
assertThat(response.statusCode()).isEqualTo(HttpStatus.OK);
|
||||
}
|
||||
|
||||
// ==================== getMemberStatistics ====================
|
||||
|
||||
@Test
|
||||
void getMemberStatistics_shouldReturnOk() {
|
||||
MemberStatistics stats = new MemberStatistics();
|
||||
when(dataStatisticsService.getMemberStatistics(any(StatisticsQuery.class))).thenReturn(Mono.just(stats));
|
||||
|
||||
MockServerRequest request = MockServerRequest.builder()
|
||||
.queryParam("periodType", "WEEK")
|
||||
.build();
|
||||
|
||||
Mono<ServerResponse> result = handler.getMemberStatistics(request);
|
||||
|
||||
ServerResponse response = result.block();
|
||||
assertThat(response.statusCode()).isEqualTo(HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getMemberStatistics_shouldReturnOkEvenOnError() {
|
||||
when(dataStatisticsService.getMemberStatistics(any(StatisticsQuery.class)))
|
||||
.thenReturn(Mono.error(new RuntimeException("Service error")));
|
||||
|
||||
MockServerRequest request = MockServerRequest.builder()
|
||||
.queryParam("periodType", "WEEK")
|
||||
.build();
|
||||
|
||||
Mono<ServerResponse> result = handler.getMemberStatistics(request);
|
||||
|
||||
ServerResponse response = result.block();
|
||||
assertThat(response.statusCode()).isEqualTo(HttpStatus.OK);
|
||||
}
|
||||
|
||||
// ==================== getBookingStatistics ====================
|
||||
|
||||
@Test
|
||||
void getBookingStatistics_shouldReturnOk() {
|
||||
BookingStatistics stats = new BookingStatistics();
|
||||
when(dataStatisticsService.getBookingStatistics(any(StatisticsQuery.class))).thenReturn(Mono.just(stats));
|
||||
|
||||
MockServerRequest request = MockServerRequest.builder()
|
||||
.queryParam("periodType", "MONTH")
|
||||
.build();
|
||||
|
||||
Mono<ServerResponse> result = handler.getBookingStatistics(request);
|
||||
|
||||
ServerResponse response = result.block();
|
||||
assertThat(response.statusCode()).isEqualTo(HttpStatus.OK);
|
||||
}
|
||||
|
||||
// ==================== getSignInStatistics ====================
|
||||
|
||||
@Test
|
||||
void getSignInStatistics_shouldReturnOk() {
|
||||
SignInStatistics stats = new SignInStatistics();
|
||||
when(dataStatisticsService.getSignInStatistics(any(StatisticsQuery.class))).thenReturn(Mono.just(stats));
|
||||
|
||||
MockServerRequest request = MockServerRequest.builder()
|
||||
.queryParam("periodType", "MONTH")
|
||||
.build();
|
||||
|
||||
Mono<ServerResponse> result = handler.getSignInStatistics(request);
|
||||
|
||||
ServerResponse response = result.block();
|
||||
assertThat(response.statusCode()).isEqualTo(HttpStatus.OK);
|
||||
}
|
||||
|
||||
// ==================== queryHistoricalStatistics ====================
|
||||
|
||||
@Test
|
||||
void queryHistoricalStatistics_shouldReturnOkWithList() {
|
||||
when(dataStatisticsService.queryHistoricalStatistics(any(StatisticsQuery.class)))
|
||||
.thenReturn(Flux.just(createTestDataStatistics()));
|
||||
|
||||
MockServerRequest request = MockServerRequest.builder()
|
||||
.queryParam("periodType", "YEAR")
|
||||
.build();
|
||||
|
||||
Mono<ServerResponse> result = handler.queryHistoricalStatistics(request);
|
||||
|
||||
ServerResponse response = result.block();
|
||||
assertThat(response.statusCode()).isEqualTo(HttpStatus.OK);
|
||||
}
|
||||
|
||||
@Test
|
||||
void queryHistoricalStatistics_shouldReturnOkWhenEmpty() {
|
||||
when(dataStatisticsService.queryHistoricalStatistics(any(StatisticsQuery.class)))
|
||||
.thenReturn(Flux.empty());
|
||||
|
||||
MockServerRequest request = MockServerRequest.builder()
|
||||
.queryParam("periodType", "YEAR")
|
||||
.build();
|
||||
|
||||
Mono<ServerResponse> result = handler.queryHistoricalStatistics(request);
|
||||
|
||||
ServerResponse response = result.block();
|
||||
assertThat(response.statusCode()).isEqualTo(HttpStatus.OK);
|
||||
}
|
||||
|
||||
// ==================== exportStatistics ====================
|
||||
|
||||
@Test
|
||||
void exportStatistics_shouldReturnOkWithExcelContent() {
|
||||
byte[] excelData = "mock-excel-content".getBytes();
|
||||
when(dataStatisticsService.exportStatistics(any(StatisticsQuery.class))).thenReturn(Mono.just(excelData));
|
||||
|
||||
MockServerRequest request = MockServerRequest.builder()
|
||||
.queryParam("periodType", "MONTH")
|
||||
.build();
|
||||
|
||||
Mono<ServerResponse> result = handler.exportStatistics(request);
|
||||
|
||||
ServerResponse response = result.block();
|
||||
assertThat(response.statusCode()).isEqualTo(HttpStatus.OK);
|
||||
}
|
||||
|
||||
// ==================== buildQueryFromRequest (via parameterized tests) ====================
|
||||
|
||||
@Test
|
||||
void getStatisticsSummary_shouldUseDefaultPeriodWhenMissing() {
|
||||
StatisticsSummary summary = createTestSummary();
|
||||
when(dataStatisticsService.getStatisticsSummaryWithCache(any(StatisticsQuery.class))).thenReturn(Mono.just(summary));
|
||||
|
||||
MockServerRequest request = MockServerRequest.builder().build();
|
||||
|
||||
Mono<ServerResponse> result = handler.getStatisticsSummary(request);
|
||||
|
||||
ServerResponse response = result.block();
|
||||
assertThat(response.statusCode()).isEqualTo(HttpStatus.OK);
|
||||
}
|
||||
|
||||
// ==================== helper ====================
|
||||
|
||||
private StatisticsSummary createTestSummary() {
|
||||
StatisticsSummary summary = new StatisticsSummary();
|
||||
summary.setMemberStatistics(new MemberStatistics());
|
||||
summary.setBookingStatistics(new BookingStatistics());
|
||||
summary.setSignInStatistics(new SignInStatistics());
|
||||
summary.setCoachStatistics(new CoachStatistics());
|
||||
return summary;
|
||||
}
|
||||
|
||||
private DataStatistics createTestDataStatistics() {
|
||||
return DataStatistics.builder()
|
||||
.statType("MEMBER")
|
||||
.periodType("DAY")
|
||||
.build();
|
||||
}
|
||||
}
|
||||
@@ -94,11 +94,20 @@
|
||||
<version>3.5.3</version>
|
||||
</dependency>
|
||||
<!-- 阿里云OSS SDK -->
|
||||
<!--
|
||||
<dependency>
|
||||
<groupId>com.aliyun.oss</groupId>
|
||||
<artifactId>aliyun-sdk-oss</artifactId>
|
||||
<version>3.17.4</version>
|
||||
</dependency>
|
||||
-->
|
||||
|
||||
<!-- 文件管理模块(统一文件存储) -->
|
||||
<dependency>
|
||||
<groupId>cn.novalon.gym.manage</groupId>
|
||||
<artifactId>manage-file</artifactId>
|
||||
<version>${project.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
|
||||
+13
@@ -61,6 +61,12 @@ public interface GroupCourseBookingDao extends R2dbcRepository<GroupCourseBookin
|
||||
*/
|
||||
Mono<Long> countByCourseIdAndStatusAndDeletedAtIsNull(Long courseId, String status);
|
||||
|
||||
/**
|
||||
* 统计会员取消的预约次数
|
||||
*/
|
||||
@org.springframework.data.r2dbc.repository.Query("SELECT COUNT(*) FROM group_course_booking WHERE member_id = :memberId AND status = '1' AND deleted_at IS NULL")
|
||||
Mono<Long> countCancelledByMemberId(Long memberId);
|
||||
|
||||
/**
|
||||
* 查询会员是否有时间冲突的预约(状态为已预约且未取消)
|
||||
* 时间冲突条件:新课程的开始时间 < 已预约课程的结束时间 且 新课程的结束时间 > 已预约课程的开始时间
|
||||
@@ -108,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);
|
||||
}
|
||||
+191
-43
@@ -1,5 +1,6 @@
|
||||
package cn.novalon.gym.manage.groupcourse.dao;
|
||||
|
||||
import cn.novalon.gym.manage.common.dto.PageRequest;
|
||||
import cn.novalon.gym.manage.groupcourse.dto.GroupCourseQueryDto;
|
||||
import cn.novalon.gym.manage.groupcourse.entity.GroupCourseEntity;
|
||||
import org.springframework.data.domain.Sort;
|
||||
@@ -32,60 +33,110 @@ public interface GroupCourseDao extends R2dbcRepository<GroupCourseEntity, Long>
|
||||
@Query("UPDATE group_course SET status = '1', updated_at = :updatedAt WHERE id = :id AND deleted_at IS NULL")
|
||||
Mono<Integer> cancelCourse(Long id, LocalDateTime updatedAt);
|
||||
|
||||
@Modifying
|
||||
@Query("UPDATE group_course SET current_members = current_members + :delta, updated_at = :updatedAt WHERE id = :id AND deleted_at IS NULL")
|
||||
Mono<Integer> updateCurrentMembers(Long id, Integer delta, LocalDateTime updatedAt);
|
||||
|
||||
@Modifying
|
||||
@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);
|
||||
|
||||
// ==================== 教练相关查询 ====================
|
||||
|
||||
Flux<GroupCourseEntity> findByCoachIdAndDeletedAtIsNull(Long coachId);
|
||||
|
||||
Flux<GroupCourseEntity> findByCoachIdAndDeletedAtIsNull(Long coachId, Sort sort);
|
||||
|
||||
@Query("SELECT COUNT(*) FROM group_course WHERE coach_id = :coachId AND status = :status AND deleted_at IS NULL")
|
||||
Mono<Long> countByCoachIdAndStatus(Long coachId, String status);
|
||||
|
||||
@Modifying
|
||||
@Query("UPDATE group_course SET status = '1', updated_at = :updatedAt WHERE coach_id = :coachId AND status != :excludeStatus AND deleted_at IS NULL")
|
||||
Mono<Integer> cancelCoursesByCoachIdExceptStatus(Long coachId, String excludeStatus, LocalDateTime updatedAt);
|
||||
|
||||
/**
|
||||
* 多条件查询团课(使用 DatabaseClient 构建动态 SQL)
|
||||
*/
|
||||
default Flux<GroupCourseEntity> searchGroupCourses(DatabaseClient databaseClient, GroupCourseQueryDto query) {
|
||||
StringBuilder sql = new StringBuilder("SELECT * FROM group_course WHERE deleted_at IS NULL");
|
||||
StringBuilder sql = new StringBuilder(
|
||||
"SELECT gc.*, COALESCE(b.cnt, 0) AS current_members " +
|
||||
"FROM group_course gc " +
|
||||
"LEFT JOIN (SELECT course_id, COUNT(*) AS cnt FROM group_course_booking WHERE status = '0' GROUP BY course_id) b " +
|
||||
"ON gc.id = b.course_id " +
|
||||
"WHERE gc.deleted_at IS NULL");
|
||||
List<String> conditions = new ArrayList<>();
|
||||
|
||||
// 默认不查询可预约团课(status = '0' 且未过期)
|
||||
conditions.add("status = '0'");
|
||||
conditions.add("end_time > NOW()");
|
||||
conditions.add("gc.status = '0'");
|
||||
conditions.add("gc.end_time > NOW()");
|
||||
|
||||
// 1. 团课名称模糊查询
|
||||
if (query.getCourseName() != null && !query.getCourseName().isEmpty()) {
|
||||
conditions.add("course_name ILIKE :courseName");
|
||||
conditions.add("gc.course_name ILIKE :courseName");
|
||||
}
|
||||
|
||||
// 2. 基于团课类型查询
|
||||
if (query.getCourseType() != null) {
|
||||
conditions.add("course_type = :courseType");
|
||||
conditions.add("gc.course_type = :courseType");
|
||||
}
|
||||
|
||||
// 3. 基于日期时间段查询
|
||||
if (query.getStartDate() != null) {
|
||||
conditions.add("start_time >= :startDate");
|
||||
conditions.add("gc.start_time >= :startDate");
|
||||
}
|
||||
if (query.getEndDate() != null) {
|
||||
conditions.add("start_time <= :endDate");
|
||||
conditions.add("gc.start_time <= :endDate");
|
||||
}
|
||||
|
||||
// 4. 基于早晨/下午/夜晚时间段查询
|
||||
if (query.getTimePeriod() != null && !query.getTimePeriod().isEmpty()) {
|
||||
switch (query.getTimePeriod().toLowerCase()) {
|
||||
case "morning":
|
||||
conditions.add("EXTRACT(HOUR FROM start_time) >= 6 AND EXTRACT(HOUR FROM start_time) < 12");
|
||||
conditions.add("EXTRACT(HOUR FROM gc.start_time) >= 6 AND EXTRACT(HOUR FROM gc.start_time) < 12");
|
||||
break;
|
||||
case "afternoon":
|
||||
conditions.add("EXTRACT(HOUR FROM start_time) >= 12 AND EXTRACT(HOUR FROM start_time) < 18");
|
||||
conditions.add("EXTRACT(HOUR FROM gc.start_time) >= 12 AND EXTRACT(HOUR FROM gc.start_time) < 18");
|
||||
break;
|
||||
case "evening":
|
||||
conditions.add("EXTRACT(HOUR FROM start_time) >= 18 AND EXTRACT(HOUR FROM start_time) < 24");
|
||||
conditions.add("EXTRACT(HOUR FROM gc.start_time) >= 18 AND EXTRACT(HOUR FROM gc.start_time) < 24");
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
@@ -103,20 +154,20 @@ public interface GroupCourseDao extends R2dbcRepository<GroupCourseEntity, Long>
|
||||
List<String> orderClauses = new ArrayList<>();
|
||||
|
||||
if (hasRemainingMost) {
|
||||
orderClauses.add(" (max_members - current_members) DESC");
|
||||
orderClauses.add(" (gc.max_members - COALESCE(b.cnt, 0)) DESC");
|
||||
}
|
||||
|
||||
if (hasPriceSort) {
|
||||
if ("asc".equalsIgnoreCase(query.getPriceSort())) {
|
||||
orderClauses.add(" stored_value_amount ASC");
|
||||
orderClauses.add(" gc.stored_value_amount ASC");
|
||||
} else if ("desc".equalsIgnoreCase(query.getPriceSort())) {
|
||||
orderClauses.add(" stored_value_amount DESC");
|
||||
orderClauses.add(" gc.stored_value_amount DESC");
|
||||
}
|
||||
}
|
||||
|
||||
sql.append(String.join(",", orderClauses));
|
||||
} else {
|
||||
sql.append(" ORDER BY start_time ASC");
|
||||
sql.append(" ORDER BY gc.start_time ASC");
|
||||
}
|
||||
|
||||
// 分页
|
||||
@@ -144,29 +195,7 @@ public interface GroupCourseDao extends R2dbcRepository<GroupCourseEntity, Long>
|
||||
spec = spec.bind("limit", size);
|
||||
spec = spec.bind("offset", offset);
|
||||
|
||||
return spec.map((row, meta) -> {
|
||||
GroupCourseEntity entity = new GroupCourseEntity();
|
||||
entity.setId(row.get("id", Long.class));
|
||||
entity.setCourseName(row.get("course_name", String.class));
|
||||
entity.setCoachId(row.get("coach_id", Long.class));
|
||||
entity.setCourseType(row.get("course_type", Long.class));
|
||||
entity.setStartTime(row.get("start_time", LocalDateTime.class));
|
||||
entity.setEndTime(row.get("end_time", LocalDateTime.class));
|
||||
entity.setMaxMembers(row.get("max_members", Integer.class));
|
||||
entity.setCurrentMembers(row.get("current_members", Integer.class));
|
||||
String statusStr = row.get("status", String.class);
|
||||
entity.setStatus(statusStr != null ? Long.parseLong(statusStr) : null);
|
||||
entity.setLocation(row.get("location", String.class));
|
||||
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.setCreateBy(row.get("create_by", String.class));
|
||||
entity.setUpdateBy(row.get("update_by", String.class));
|
||||
entity.setCreatedAt(row.get("created_at", LocalDateTime.class));
|
||||
entity.setUpdatedAt(row.get("updated_at", LocalDateTime.class));
|
||||
entity.setDeletedAt(row.get("deleted_at", LocalDateTime.class));
|
||||
return entity;
|
||||
}).all();
|
||||
return spec.map((row, meta) -> mapRowToEntity(row)).all();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -226,4 +255,123 @@ public interface GroupCourseDao extends R2dbcRepository<GroupCourseEntity, Long>
|
||||
|
||||
return spec.map((row, meta) -> row.get(0, Long.class)).one();
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页查询团课(支持 keyword 和 status 过滤)
|
||||
*/
|
||||
default Flux<GroupCourseEntity> findByPageFiltered(DatabaseClient databaseClient, PageRequest pageRequest) {
|
||||
StringBuilder sql = new StringBuilder(
|
||||
"SELECT gc.*, COALESCE(b.cnt, 0) AS current_members " +
|
||||
"FROM group_course gc " +
|
||||
"LEFT JOIN (SELECT course_id, COUNT(*) AS cnt FROM group_course_booking WHERE status = '0' GROUP BY course_id) b " +
|
||||
"ON gc.id = b.course_id " +
|
||||
"WHERE gc.deleted_at IS NULL");
|
||||
List<String> conditions = new ArrayList<>();
|
||||
|
||||
if (pageRequest.getKeyword() != null && !pageRequest.getKeyword().isEmpty()) {
|
||||
conditions.add("gc.course_name ILIKE :keyword");
|
||||
}
|
||||
if (pageRequest.getStatus() != null && !pageRequest.getStatus().isEmpty()) {
|
||||
conditions.add("gc.status = :status");
|
||||
}
|
||||
|
||||
if (!conditions.isEmpty()) {
|
||||
sql.append(" AND ").append(String.join(" AND ", conditions));
|
||||
}
|
||||
|
||||
String sort = pageRequest.getSort() != null ? pageRequest.getSort() : "id";
|
||||
String order = "desc".equalsIgnoreCase(pageRequest.getOrder()) ? "DESC" : "ASC";
|
||||
sql.append(" ORDER BY gc.").append(sort).append(" ").append(order);
|
||||
|
||||
int size = pageRequest.getSize();
|
||||
if (size < 1) size = 10;
|
||||
if (size > 100) size = 100;
|
||||
int offset = pageRequest.getPage() * size;
|
||||
sql.append(" LIMIT :limit OFFSET :offset");
|
||||
|
||||
DatabaseClient.GenericExecuteSpec spec = databaseClient.sql(sql.toString());
|
||||
|
||||
if (pageRequest.getKeyword() != null && !pageRequest.getKeyword().isEmpty()) {
|
||||
spec = spec.bind("keyword", "%" + pageRequest.getKeyword() + "%");
|
||||
}
|
||||
if (pageRequest.getStatus() != null && !pageRequest.getStatus().isEmpty()) {
|
||||
spec = spec.bind("status", pageRequest.getStatus());
|
||||
}
|
||||
spec = spec.bind("limit", size);
|
||||
spec = spec.bind("offset", offset);
|
||||
|
||||
return spec.map((row, meta) -> mapRowToEntity(row)).all();
|
||||
}
|
||||
|
||||
/**
|
||||
* 分页查询团课总数(支持 keyword 和 status 过滤)
|
||||
*/
|
||||
default Mono<Long> countByPageFiltered(DatabaseClient databaseClient, PageRequest pageRequest) {
|
||||
StringBuilder sql = new StringBuilder("SELECT COUNT(*) FROM group_course WHERE deleted_at IS NULL");
|
||||
List<String> conditions = new ArrayList<>();
|
||||
|
||||
if (pageRequest.getKeyword() != null && !pageRequest.getKeyword().isEmpty()) {
|
||||
conditions.add("course_name ILIKE :keyword");
|
||||
}
|
||||
if (pageRequest.getStatus() != null && !pageRequest.getStatus().isEmpty()) {
|
||||
conditions.add("status = :status");
|
||||
}
|
||||
|
||||
if (!conditions.isEmpty()) {
|
||||
sql.append(" AND ").append(String.join(" AND ", conditions));
|
||||
}
|
||||
|
||||
DatabaseClient.GenericExecuteSpec spec = databaseClient.sql(sql.toString());
|
||||
|
||||
if (pageRequest.getKeyword() != null && !pageRequest.getKeyword().isEmpty()) {
|
||||
spec = spec.bind("keyword", "%" + pageRequest.getKeyword() + "%");
|
||||
}
|
||||
if (pageRequest.getStatus() != null && !pageRequest.getStatus().isEmpty()) {
|
||||
spec = spec.bind("status", pageRequest.getStatus());
|
||||
}
|
||||
|
||||
return spec.map((row, meta) -> row.get(0, Long.class)).one();
|
||||
}
|
||||
|
||||
/**
|
||||
* 统计单门课程的有效预约人数(status='0')
|
||||
*/
|
||||
default Mono<Long> countValidBookings(DatabaseClient databaseClient, Long courseId) {
|
||||
return databaseClient.sql("SELECT COUNT(*) FROM group_course_booking WHERE course_id = :id AND status = '0'")
|
||||
.bind("id", courseId)
|
||||
.map((row, meta) -> row.get(0, Long.class))
|
||||
.one()
|
||||
.defaultIfEmpty(0L);
|
||||
}
|
||||
|
||||
/**
|
||||
* 将数据库行映射为 GroupCourseEntity
|
||||
*/
|
||||
private GroupCourseEntity mapRowToEntity(io.r2dbc.spi.Row row) {
|
||||
GroupCourseEntity entity = new GroupCourseEntity();
|
||||
entity.setId(row.get("id", Long.class));
|
||||
entity.setCourseName(row.get("course_name", String.class));
|
||||
entity.setCoachId(row.get("coach_id", Long.class));
|
||||
entity.setCourseType(row.get("course_type", Long.class));
|
||||
entity.setStartTime(row.get("start_time", LocalDateTime.class));
|
||||
entity.setEndTime(row.get("end_time", LocalDateTime.class));
|
||||
entity.setMaxMembers(row.get("max_members", Integer.class));
|
||||
Integer cm = row.get("current_members", Integer.class);
|
||||
entity.setCurrentMembers(cm != null ? cm : 0);
|
||||
String statusStr = row.get("status", String.class);
|
||||
entity.setStatus(statusStr != null ? Long.parseLong(statusStr) : null);
|
||||
entity.setLocation(row.get("location", String.class));
|
||||
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));
|
||||
entity.setCreatedAt(row.get("created_at", LocalDateTime.class));
|
||||
entity.setUpdatedAt(row.get("updated_at", LocalDateTime.class));
|
||||
entity.setDeletedAt(row.get("deleted_at", LocalDateTime.class));
|
||||
return entity;
|
||||
}
|
||||
}
|
||||
+24
@@ -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;
|
||||
}
|
||||
|
||||
+11
@@ -21,6 +21,9 @@ public class GroupCourseDetail extends BaseDomain {
|
||||
@Schema(description = "教练ID", example = "1")
|
||||
private Long coachId;
|
||||
|
||||
@Schema(description = "教练名称", example = "张教练")
|
||||
private String coachName;
|
||||
|
||||
@Schema(description = "课程类型ID", example = "1")
|
||||
private Long courseType;
|
||||
|
||||
@@ -99,6 +102,14 @@ public class GroupCourseDetail extends BaseDomain {
|
||||
this.coachId = coachId;
|
||||
}
|
||||
|
||||
public String getCoachName() {
|
||||
return coachName;
|
||||
}
|
||||
|
||||
public void setCoachName(String coachName) {
|
||||
this.coachName = coachName;
|
||||
}
|
||||
|
||||
public Long getCourseType() {
|
||||
return courseType;
|
||||
}
|
||||
|
||||
+25
-1
@@ -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;
|
||||
}
|
||||
|
||||
+4
-1
@@ -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;
|
||||
|
||||
+64
-123
@@ -2,18 +2,18 @@ package cn.novalon.gym.manage.groupcourse.handler;
|
||||
|
||||
import cn.novalon.gym.manage.groupcourse.domain.GroupCourseBooking;
|
||||
import cn.novalon.gym.manage.groupcourse.repository.IGroupCourseBookingRepository;
|
||||
import cn.novalon.gym.manage.groupcourse.repository.IGroupCourseRepository;
|
||||
import cn.novalon.gym.manage.groupcourse.service.impl.GroupCourseRedisService;
|
||||
import cn.novalon.gym.manage.member.entity.MemberCard;
|
||||
import cn.novalon.gym.manage.member.entity.MemberCardRecord;
|
||||
import cn.novalon.gym.manage.member.enums.MemberCardType;
|
||||
import cn.novalon.gym.manage.member.repository.MemberCardRepository;
|
||||
import cn.novalon.gym.manage.member.service.IMemberCardRecordService;
|
||||
import cn.novalon.gym.manage.member.service.IMemberStoredCardService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
@@ -32,10 +32,9 @@ import java.util.List;
|
||||
public class BookingSagaHandler {
|
||||
|
||||
private final IGroupCourseBookingRepository bookingRepository;
|
||||
private final IGroupCourseRepository courseRepository;
|
||||
private final IMemberCardRecordService memberCardRecordService;
|
||||
private final IMemberStoredCardService memberStoredCardService;
|
||||
private final MemberCardRepository memberCardRepository;
|
||||
private final GroupCourseRedisService redisService;
|
||||
|
||||
private static final double DEFAULT_GROUP_COURSE_PRICE = 50.0;
|
||||
|
||||
@@ -44,10 +43,10 @@ public class BookingSagaHandler {
|
||||
*
|
||||
* 步骤:
|
||||
* 1. 保存预约记录
|
||||
* 2. 扣减会员卡权益
|
||||
* 2. 扣减储值卡余额(储值卡类型)
|
||||
* 3. 更新课程当前人数
|
||||
*/
|
||||
public Mono<GroupCourseBooking> executeBooking(GroupCourseBooking booking, Long recordId) {
|
||||
public Mono<GroupCourseBooking> executeBooking(GroupCourseBooking booking, Long recordId, BigDecimal storedValueAmount) {
|
||||
List<SagaStep> steps = new ArrayList<>();
|
||||
List<SagaStep> rollbackSteps = new ArrayList<>();
|
||||
|
||||
@@ -60,33 +59,15 @@ public class BookingSagaHandler {
|
||||
steps.add(step1);
|
||||
rollbackSteps.add(0, step1);
|
||||
|
||||
// 步骤2:扣减会员卡权益(根据卡类型决定扣除次数还是金额)
|
||||
// 步骤2:扣减权益(根据卡类型)
|
||||
SagaStep step2 = new SagaStep(
|
||||
"扣减会员卡权益",
|
||||
deductCardUsageByCardType(booking.getMemberId(), recordId),
|
||||
Mono.defer(() -> restoreCardUsageByCardType(booking.getMemberId(), recordId))
|
||||
"扣减权益",
|
||||
deductCardUsageByCardType(booking.getMemberId(), recordId, storedValueAmount),
|
||||
Mono.defer(() -> restoreCardUsageByCardType(booking.getMemberId(), recordId, storedValueAmount))
|
||||
);
|
||||
steps.add(step2);
|
||||
rollbackSteps.add(0, step2);
|
||||
|
||||
// 步骤3:更新课程当前人数
|
||||
SagaStep step3 = new SagaStep(
|
||||
"更新课程当前人数",
|
||||
incrementCourseCurrentMembers(booking.getCourseId()),
|
||||
Mono.defer(() -> decrementCourseCurrentMembers(booking.getCourseId()))
|
||||
);
|
||||
steps.add(step3);
|
||||
rollbackSteps.add(0, step3);
|
||||
|
||||
// 步骤4:更新Redis预约计数
|
||||
SagaStep step4 = new SagaStep(
|
||||
"更新Redis预约计数",
|
||||
incrementRedisBookingCount(booking.getCourseId()),
|
||||
Mono.defer(() -> decrementRedisBookingCount(booking.getCourseId()))
|
||||
);
|
||||
steps.add(step4);
|
||||
rollbackSteps.add(0, step4);
|
||||
|
||||
return executeSaga(steps, rollbackSteps)
|
||||
.then(Mono.just(booking));
|
||||
}
|
||||
@@ -94,7 +75,7 @@ public class BookingSagaHandler {
|
||||
/**
|
||||
* 根据会员卡类型扣减权益
|
||||
*/
|
||||
private Mono<Void> deductCardUsageByCardType(Long memberId, Long recordId) {
|
||||
private Mono<Void> deductCardUsageByCardType(Long memberId, Long recordId, BigDecimal storedValueAmount) {
|
||||
return memberCardRecordService.findById(recordId)
|
||||
.switchIfEmpty(Mono.error(new RuntimeException("会员卡记录不存在")))
|
||||
.flatMap(record -> {
|
||||
@@ -109,14 +90,13 @@ public class BookingSagaHandler {
|
||||
|
||||
switch (cardType) {
|
||||
case COUNT_CARD:
|
||||
// 次数卡不再支持团课预约
|
||||
return Mono.error(new RuntimeException("团课预约仅支持储值卡支付"));
|
||||
return Mono.error(new RuntimeException("团课预约仅支持储值卡和时长卡支付"));
|
||||
case STORED_VALUE_CARD:
|
||||
// 储值卡扣除金额
|
||||
return deductCardUsage(recordId, 0, DEFAULT_GROUP_COURSE_PRICE);
|
||||
return deductStoredCardBalance(memberId, storedValueAmount);
|
||||
case TIME_CARD:
|
||||
// 时长卡不扣除,但需验证有效期
|
||||
return validateTimeCard(record);
|
||||
// 时长卡验证有效期后,仍须从储值卡扣款
|
||||
return validateTimeCard(record)
|
||||
.then(deductStoredCardBalance(memberId, storedValueAmount));
|
||||
default:
|
||||
return Mono.error(new RuntimeException("不支持的会员卡类型: " + cardType));
|
||||
}
|
||||
@@ -153,11 +133,10 @@ public class BookingSagaHandler {
|
||||
/**
|
||||
* 根据会员卡类型恢复权益
|
||||
*/
|
||||
private Mono<Void> restoreCardUsageByCardType(Long memberId, Long recordId) {
|
||||
private Mono<Void> restoreCardUsageByCardType(Long memberId, Long recordId, BigDecimal storedValueAmount) {
|
||||
return memberCardRecordService.findById(recordId)
|
||||
.switchIfEmpty(Mono.error(new RuntimeException("会员卡记录不存在,无法恢复权益")))
|
||||
.flatMap(record -> {
|
||||
// 验证会员卡归属(memberId为null时跳过验证)
|
||||
if (memberId != null && !record.getMemberId().equals(memberId)) {
|
||||
return Mono.error(new RuntimeException("会员卡不归属当前用户"));
|
||||
}
|
||||
@@ -168,12 +147,29 @@ public class BookingSagaHandler {
|
||||
|
||||
switch (cardType) {
|
||||
case COUNT_CARD:
|
||||
// 次数卡不再支持团课预约,无需恢复
|
||||
return Mono.empty();
|
||||
case STORED_VALUE_CARD:
|
||||
return restoreCardUsage(recordId, 0, DEFAULT_GROUP_COURSE_PRICE);
|
||||
// 返还储值卡余额(回滚时全额返还)
|
||||
BigDecimal amount = storedValueAmount != null ? storedValueAmount : BigDecimal.valueOf(DEFAULT_GROUP_COURSE_PRICE);
|
||||
return memberStoredCardService.recharge(memberId, amount)
|
||||
.flatMap(rows -> {
|
||||
if (rows > 0) {
|
||||
log.info("储值卡回滚返还成功: memberId={}, amount={}", memberId, amount);
|
||||
return Mono.empty();
|
||||
}
|
||||
return Mono.empty();
|
||||
});
|
||||
case TIME_CARD:
|
||||
return Mono.empty();
|
||||
// 时长卡回滚时也返还储值卡
|
||||
BigDecimal timeAmount = storedValueAmount != null ? storedValueAmount : BigDecimal.valueOf(DEFAULT_GROUP_COURSE_PRICE);
|
||||
return memberStoredCardService.recharge(memberId, timeAmount)
|
||||
.flatMap(rows -> {
|
||||
if (rows > 0) {
|
||||
log.info("储值卡回滚返还成功(时长卡): memberId={}, amount={}", memberId, timeAmount);
|
||||
return Mono.empty();
|
||||
}
|
||||
return Mono.empty();
|
||||
});
|
||||
default:
|
||||
return Mono.error(new RuntimeException("不支持的会员卡类型: " + cardType));
|
||||
}
|
||||
@@ -184,7 +180,7 @@ public class BookingSagaHandler {
|
||||
/**
|
||||
* 执行取消预约事务
|
||||
*/
|
||||
public Mono<GroupCourseBooking> executeCancelBooking(Long bookingId, Long courseId, Long recordId, Long memberId) {
|
||||
public Mono<GroupCourseBooking> executeCancelBooking(Long bookingId, Long courseId, Long recordId, Long memberId, BigDecimal storedValueAmount, long cancelCount) {
|
||||
List<SagaStep> steps = new ArrayList<>();
|
||||
List<SagaStep> rollbackSteps = new ArrayList<>();
|
||||
|
||||
@@ -197,33 +193,16 @@ public class BookingSagaHandler {
|
||||
steps.add(step1);
|
||||
rollbackSteps.add(0, step1);
|
||||
|
||||
// 步骤2:恢复会员卡权益
|
||||
// 步骤2:返还储值卡余额(含手续费逻辑)
|
||||
SagaStep step2 = new SagaStep(
|
||||
"恢复会员卡权益",
|
||||
restoreCardUsageByCardType(memberId, recordId),
|
||||
Mono.defer(() -> deductCardUsageByCardType(memberId, recordId))
|
||||
"返还储值卡余额",
|
||||
refundStoredCardWithFee(memberId, storedValueAmount, cancelCount),
|
||||
// 回滚时重新扣减
|
||||
Mono.defer(() -> deductCardUsageByCardType(memberId, recordId, storedValueAmount))
|
||||
);
|
||||
steps.add(step2);
|
||||
rollbackSteps.add(0, step2);
|
||||
|
||||
// 步骤3:减少课程当前人数
|
||||
SagaStep step3 = new SagaStep(
|
||||
"减少课程当前人数",
|
||||
decrementCourseCurrentMembers(courseId),
|
||||
Mono.defer(() -> incrementCourseCurrentMembers(courseId))
|
||||
);
|
||||
steps.add(step3);
|
||||
rollbackSteps.add(0, step3);
|
||||
|
||||
// 步骤4:更新Redis预约计数
|
||||
SagaStep step4 = new SagaStep(
|
||||
"更新Redis预约计数",
|
||||
decrementRedisBookingCount(courseId),
|
||||
Mono.defer(() -> incrementRedisBookingCount(courseId))
|
||||
);
|
||||
steps.add(step4);
|
||||
rollbackSteps.add(0, step4);
|
||||
|
||||
return executeSaga(steps, rollbackSteps)
|
||||
.then(bookingRepository.findById(bookingId));
|
||||
}
|
||||
@@ -253,73 +232,35 @@ public class BookingSagaHandler {
|
||||
return bookingRepository.deleteById(bookingId);
|
||||
}
|
||||
|
||||
private Mono<Void> deductCardUsage(Long recordId, Integer deductTimes, Double deductAmount) {
|
||||
if (deductTimes == 0 && deductAmount == 0.0) {
|
||||
return Mono.empty();
|
||||
}
|
||||
|
||||
return memberCardRecordService.findById(recordId)
|
||||
.switchIfEmpty(Mono.error(new RuntimeException("会员卡记录不存在")))
|
||||
.flatMap(record -> {
|
||||
cn.novalon.gym.manage.member.enums.MemberCardRecordStatus status = record.getStatus();
|
||||
if (status != cn.novalon.gym.manage.member.enums.MemberCardRecordStatus.ACTIVE) {
|
||||
return Mono.error(new RuntimeException("会员卡状态无效,当前状态: " + (status != null ? status.getDesc() : "未知")));
|
||||
/**
|
||||
* 从储值卡扣减余额
|
||||
*/
|
||||
private Mono<Void> deductStoredCardBalance(Long memberId, BigDecimal storedValueAmount) {
|
||||
BigDecimal amount = storedValueAmount != null && storedValueAmount.compareTo(BigDecimal.ZERO) > 0
|
||||
? storedValueAmount : BigDecimal.valueOf(DEFAULT_GROUP_COURSE_PRICE);
|
||||
return memberStoredCardService.consume(memberId, amount)
|
||||
.flatMap(rows -> {
|
||||
if (rows == 0) {
|
||||
return Mono.error(new RuntimeException("储值卡扣减失败,余额不足"));
|
||||
}
|
||||
java.time.LocalDateTime expireTime = record.getExpireTime();
|
||||
if (expireTime != null && expireTime.isBefore(java.time.LocalDateTime.now())) {
|
||||
return Mono.error(new RuntimeException("会员卡已过期"));
|
||||
}
|
||||
if (record.getRemainingTimes() != null && deductTimes > 0 && record.getRemainingTimes() < deductTimes) {
|
||||
return Mono.error(new RuntimeException("会员卡剩余次数不足,当前剩余: " + record.getRemainingTimes() + "次"));
|
||||
}
|
||||
if (record.getRemainingAmount() != null && deductAmount > 0 && record.getRemainingAmount() < deductAmount) {
|
||||
return Mono.error(new RuntimeException("会员卡余额不足,当前剩余: " + record.getRemainingAmount()));
|
||||
}
|
||||
return memberCardRecordService.deductUsage(recordId, deductTimes, deductAmount)
|
||||
.flatMap(rows -> {
|
||||
if (rows == 0) {
|
||||
return Mono.error(new RuntimeException("扣减会员卡权益失败,请重试"));
|
||||
}
|
||||
return Mono.empty();
|
||||
});
|
||||
log.info("储值卡扣减成功: memberId={}, amount={}", memberId, amount);
|
||||
return Mono.empty();
|
||||
});
|
||||
}
|
||||
|
||||
private Mono<Void> restoreCardUsage(Long recordId, Integer addTimes, Double addAmount) {
|
||||
if (addTimes == 0 && addAmount == 0.0) {
|
||||
return Mono.empty();
|
||||
}
|
||||
|
||||
return memberCardRecordService.findById(recordId)
|
||||
.switchIfEmpty(Mono.error(new RuntimeException("会员卡记录不存在,无法恢复权益")))
|
||||
.flatMap(record -> {
|
||||
// 使用当前记录的过期时间,避免清空过期时间
|
||||
return memberCardRecordService.renewCard(recordId, addTimes, addAmount, record.getExpireTime())
|
||||
.flatMap(rows -> {
|
||||
if (rows == 0) {
|
||||
return Mono.error(new RuntimeException("恢复会员卡权益失败,请重试"));
|
||||
}
|
||||
return Mono.empty();
|
||||
});
|
||||
/**
|
||||
* 返还储值卡余额(含手续费逻辑,仅用于取消预约)
|
||||
*/
|
||||
private Mono<Void> refundStoredCardWithFee(Long memberId, BigDecimal storedValueAmount, long cancelCount) {
|
||||
BigDecimal amount = storedValueAmount != null && storedValueAmount.compareTo(BigDecimal.ZERO) > 0
|
||||
? storedValueAmount : BigDecimal.valueOf(DEFAULT_GROUP_COURSE_PRICE);
|
||||
return memberStoredCardService.refundBalanceWithFee(memberId, amount, cancelCount)
|
||||
.flatMap(refundedAmount -> {
|
||||
log.info("储值卡退款成功(含手续费): memberId={}, cancelCount={}, 退款金额={}", memberId, cancelCount, refundedAmount);
|
||||
return Mono.empty();
|
||||
});
|
||||
}
|
||||
|
||||
private Mono<Void> incrementCourseCurrentMembers(Long courseId) {
|
||||
return courseRepository.updateCurrentMembers(courseId, 1).then();
|
||||
}
|
||||
|
||||
private Mono<Void> decrementCourseCurrentMembers(Long courseId) {
|
||||
return courseRepository.updateCurrentMembers(courseId, -1).then();
|
||||
}
|
||||
|
||||
private Mono<Void> incrementRedisBookingCount(Long courseId) {
|
||||
return redisService.incrementBookingCount(courseId).then();
|
||||
}
|
||||
|
||||
private Mono<Void> decrementRedisBookingCount(Long courseId) {
|
||||
return redisService.decrementBookingCount(courseId).then();
|
||||
}
|
||||
|
||||
private Mono<Void> executeSaga(List<SagaStep> steps, List<SagaStep> rollbackSteps) {
|
||||
List<SagaStep> completedSteps = new ArrayList<>();
|
||||
return executeStep(steps, 0, completedSteps);
|
||||
|
||||
+12
-4
@@ -1,5 +1,6 @@
|
||||
package cn.novalon.gym.manage.groupcourse.handler;
|
||||
|
||||
import cn.novalon.gym.manage.common.dto.PageRequest;
|
||||
import cn.novalon.gym.manage.groupcourse.domain.CourseLabel;
|
||||
import cn.novalon.gym.manage.groupcourse.service.ICourseLabelService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
@@ -29,6 +30,13 @@ public class CourseLabelHandler {
|
||||
.body(courseLabelService.findAll(), CourseLabel.class);
|
||||
}
|
||||
|
||||
@Operation(summary = "分页查询标签", description = "支持按关键词筛选并分页查询标签")
|
||||
public Mono<ServerResponse> getLabelsByPage(ServerRequest request) {
|
||||
return request.bodyToMono(PageRequest.class)
|
||||
.flatMap(pageRequest -> courseLabelService.findByPage(pageRequest)
|
||||
.flatMap(response -> ServerResponse.ok().bodyValue(response)));
|
||||
}
|
||||
|
||||
@Operation(summary = "根据ID获取标签", description = "根据ID获取标签详情")
|
||||
public Mono<ServerResponse> getLabelById(ServerRequest request) {
|
||||
Long id = Long.valueOf(request.pathVariable("id"));
|
||||
@@ -147,17 +155,17 @@ public class CourseLabelHandler {
|
||||
return request.bodyToMono(Map.class)
|
||||
.flatMap(body -> {
|
||||
@SuppressWarnings("unchecked")
|
||||
List<Integer> labelIdsInt = (List<Integer>) body.get("labelIds");
|
||||
List<?> rawIds = (List<?>) body.get("labelIds");
|
||||
|
||||
if (labelIdsInt == null || labelIdsInt.isEmpty()) {
|
||||
if (rawIds == null || rawIds.isEmpty()) {
|
||||
Map<String, Object> error = new HashMap<>();
|
||||
error.put("success", false);
|
||||
error.put("message", "labelIds不能为空");
|
||||
return ServerResponse.badRequest().bodyValue(error);
|
||||
}
|
||||
|
||||
List<Long> labelIds = labelIdsInt.stream()
|
||||
.map(Integer::longValue)
|
||||
List<Long> labelIds = rawIds.stream()
|
||||
.map(id -> Long.valueOf(String.valueOf(id)))
|
||||
.collect(java.util.stream.Collectors.toList());
|
||||
|
||||
return courseLabelService.addLabelsToType(typeId, labelIds)
|
||||
|
||||
+17
-8
@@ -42,15 +42,11 @@ public class GroupCourseBookingHandler {
|
||||
if (body.get("memberId") == null) {
|
||||
return buildErrorResponse("请提供会员ID");
|
||||
}
|
||||
if (body.get("memberCardRecordId") == null) {
|
||||
return buildErrorResponse("请提供会员卡记录ID");
|
||||
}
|
||||
|
||||
Long courseId = ((Number) body.get("courseId")).longValue();
|
||||
Long memberId = ((Number) body.get("memberId")).longValue();
|
||||
Long memberCardRecordId = ((Number) body.get("memberCardRecordId")).longValue();
|
||||
Long courseId = toLong(body.get("courseId"), "courseId");
|
||||
Long memberId = toLong(body.get("memberId"), "memberId");
|
||||
|
||||
return bookingService.bookCourse(courseId, memberId, memberCardRecordId)
|
||||
return bookingService.bookCourse(courseId, memberId)
|
||||
.flatMap(booking -> {
|
||||
Map<String, Object> response = new HashMap<>();
|
||||
response.put("success", true);
|
||||
@@ -76,7 +72,7 @@ public class GroupCourseBookingHandler {
|
||||
|
||||
return request.bodyToMono(Map.class)
|
||||
.flatMap(body -> {
|
||||
Long memberId = ((Number) body.get("memberId")).longValue();
|
||||
Long memberId = toLong(body.get("memberId"), "memberId");
|
||||
|
||||
return bookingService.cancelBooking(bookingId, memberId)
|
||||
.flatMap(booking -> {
|
||||
@@ -129,6 +125,19 @@ public class GroupCourseBookingHandler {
|
||||
.body(bookingService.getBookingsByCourseId(courseId), GroupCourseBooking.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* 安全转换为 Long,支持 Number 和 String 类型
|
||||
*/
|
||||
private Long toLong(Object value, String fieldName) {
|
||||
if (value instanceof Number) {
|
||||
return ((Number) value).longValue();
|
||||
}
|
||||
if (value instanceof String) {
|
||||
return Long.valueOf((String) value);
|
||||
}
|
||||
throw new IllegalArgumentException("参数 " + fieldName + " 类型不正确");
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建错误响应
|
||||
*/
|
||||
|
||||
+57
-4
@@ -7,21 +7,27 @@ import cn.novalon.gym.manage.groupcourse.domain.GroupCourse;
|
||||
import cn.novalon.gym.manage.groupcourse.domain.GroupCourseDetail;
|
||||
import cn.novalon.gym.manage.groupcourse.dto.GroupCourseQueryDto;
|
||||
import cn.novalon.gym.manage.groupcourse.service.IGroupCourseService;
|
||||
import cn.novalon.gym.manage.groupcourse.vo.GroupCourseVO;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Validator;
|
||||
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.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Component
|
||||
@Tag(name="团课管理",description = "团课相关操作")
|
||||
public class GroupCourseHandler {
|
||||
private static final Logger logger = LoggerFactory.getLogger(GroupCourseHandler.class);
|
||||
private final IGroupCourseService groupCourseService;
|
||||
private final Validator validator;
|
||||
private final RedisUtil redisUtil;
|
||||
@@ -37,11 +43,12 @@ public class GroupCourseHandler {
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@Operation(summary = "获取所有团课", description = "获取系统中所有团课列表")
|
||||
@Operation(summary = "获取所有团课", description = "获取系统中所有团课列表(含教练昵称)")
|
||||
public Mono<ServerResponse> getAllGroupCourse(ServerRequest request){
|
||||
boolean includeDeleted = Boolean.valueOf(request.queryParam("includeDeleted").orElse("false"));
|
||||
return ServerResponse.ok()
|
||||
.body(groupCourseService.findAll(includeDeleted), GroupCourse.class);
|
||||
return groupCourseService.findAllAsVO(includeDeleted)
|
||||
.collectList()
|
||||
.flatMap(list -> ServerResponse.ok().bodyValue(list));
|
||||
}
|
||||
|
||||
@Operation(summary = "分页获取团课", description = "根据分页参数获取团课列表")
|
||||
@@ -65,7 +72,7 @@ public class GroupCourseHandler {
|
||||
pageRequest.setOrder("asc");
|
||||
}
|
||||
|
||||
return groupCourseService.findByPage(pageRequest, includeDeleted)
|
||||
return groupCourseService.findByPageAsVO(pageRequest, includeDeleted)
|
||||
.flatMap(response -> ServerResponse.ok().bodyValue(response));
|
||||
});
|
||||
}
|
||||
@@ -289,4 +296,50 @@ public class GroupCourseHandler {
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@Operation(summary = "检查教练时间冲突", description = "检查教练在指定时间段内是否有时间冲突的团课")
|
||||
public Mono<ServerResponse> checkCoachConflict(ServerRequest request) {
|
||||
return request.bodyToMono(Map.class)
|
||||
.flatMap(body -> {
|
||||
if (body == null) {
|
||||
Map<String, Object> error = new HashMap<>();
|
||||
error.put("success", false);
|
||||
error.put("message", "请求体不能为空");
|
||||
return ServerResponse.badRequest().bodyValue(error);
|
||||
}
|
||||
|
||||
Object coachIdObj = body.get("coachId");
|
||||
Object startTimeStr = body.get("startTime");
|
||||
Object endTimeStr = body.get("endTime");
|
||||
Object excludeCourseIdObj = body.get("excludeCourseId");
|
||||
|
||||
if (coachIdObj == null || startTimeStr == null || endTimeStr == null) {
|
||||
Map<String, Object> error = new HashMap<>();
|
||||
error.put("success", false);
|
||||
error.put("message", "coachId、startTime、endTime 不能为空");
|
||||
return ServerResponse.badRequest().bodyValue(error);
|
||||
}
|
||||
|
||||
Long coachId = Long.valueOf(String.valueOf(coachIdObj));
|
||||
LocalDateTime startTime = LocalDateTime.parse(String.valueOf(startTimeStr));
|
||||
LocalDateTime endTime = LocalDateTime.parse(String.valueOf(endTimeStr));
|
||||
Long excludeCourseId = excludeCourseIdObj != null ? Long.valueOf(String.valueOf(excludeCourseIdObj)) : null;
|
||||
|
||||
return groupCourseService.checkCoachConflict(coachId, startTime, endTime, excludeCourseId)
|
||||
.flatMap(conflicts -> {
|
||||
Map<String, Object> response = new HashMap<>();
|
||||
response.put("success", true);
|
||||
response.put("hasConflict", !conflicts.isEmpty());
|
||||
response.put("conflicts", conflicts);
|
||||
return ServerResponse.ok().bodyValue(response);
|
||||
});
|
||||
})
|
||||
.onErrorResume(error -> {
|
||||
logger.warn("检查教练时间冲突失败: {}", error.getMessage());
|
||||
Map<String, Object> response = new HashMap<>();
|
||||
response.put("success", false);
|
||||
response.put("message", "检查失败: " + error.getMessage());
|
||||
return ServerResponse.badRequest().bodyValue(response);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
+9
@@ -1,5 +1,6 @@
|
||||
package cn.novalon.gym.manage.groupcourse.handler;
|
||||
|
||||
import cn.novalon.gym.manage.common.dto.PageRequest;
|
||||
import cn.novalon.gym.manage.groupcourse.domain.GroupCourseType;
|
||||
import cn.novalon.gym.manage.groupcourse.service.IGroupCourseTypeService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
@@ -134,4 +135,12 @@ public class GroupCourseTypeHandler {
|
||||
return ServerResponse.badRequest().bodyValue(response);
|
||||
});
|
||||
}
|
||||
|
||||
@Operation(summary = "分页查询团课类型", description = "支持按关键词、分类筛选并分页查询团课类型")
|
||||
public Mono<ServerResponse> getGroupCourseTypesByPage(ServerRequest request) {
|
||||
return request.bodyToMono(PageRequest.class)
|
||||
.flatMap(pageRequest -> groupCourseTypeService.findByPage(pageRequest)
|
||||
.flatMap(response -> ServerResponse.ok().bodyValue(response))
|
||||
);
|
||||
}
|
||||
}
|
||||
+21
-18
@@ -1,5 +1,6 @@
|
||||
package cn.novalon.gym.manage.groupcourse.initializer;
|
||||
|
||||
import cn.novalon.gym.manage.file.core.service.ISysFileService;
|
||||
import cn.novalon.gym.manage.groupcourse.domain.GroupCourse;
|
||||
import cn.novalon.gym.manage.groupcourse.repository.IGroupCourseRepository;
|
||||
import cn.novalon.gym.manage.groupcourse.util.QRCodeUtil;
|
||||
@@ -10,15 +11,12 @@ import org.springframework.boot.CommandLineRunner;
|
||||
import org.springframework.stereotype.Component;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* 项目启动时补全缺失的团课二维码
|
||||
* 遍历所有未删除的团课,对qrCodePath为空的课程生成二维码并上传至阿里云OSS
|
||||
* 遍历所有未删除的团课,对qrCodePath为空的课程生成二维码并通过统一文件服务保存
|
||||
*/
|
||||
@Component
|
||||
public class QrCodeInitializer implements CommandLineRunner {
|
||||
@@ -27,11 +25,14 @@ public class QrCodeInitializer implements CommandLineRunner {
|
||||
|
||||
private final IGroupCourseRepository groupCourseRepository;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final ISysFileService fileService;
|
||||
|
||||
public QrCodeInitializer(IGroupCourseRepository groupCourseRepository,
|
||||
ObjectMapper objectMapper) {
|
||||
ObjectMapper objectMapper,
|
||||
ISysFileService fileService) {
|
||||
this.groupCourseRepository = groupCourseRepository;
|
||||
this.objectMapper = objectMapper;
|
||||
this.fileService = fileService;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -58,20 +59,22 @@ public class QrCodeInitializer implements CommandLineRunner {
|
||||
|
||||
String jsonContent = objectMapper.writeValueAsString(qrCodeContent);
|
||||
|
||||
// 生成二维码并上传到阿里云OSS
|
||||
String uuid = UUID.randomUUID().toString().replace("-", "");
|
||||
String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
|
||||
String fileName = "qr_" + uuid + "_" + timestamp + ".png";
|
||||
String ossUrl = QRCodeUtil.generateQRCodeAndUploadToOSS(jsonContent, fileName);
|
||||
// 生成二维码字节数组,通过统一文件服务保存
|
||||
return Mono.fromCallable(() -> QRCodeUtil.generateQrCodeBytes(jsonContent))
|
||||
.flatMap(qrCodeBytes -> {
|
||||
String fileName = "qrcode_" + course.getId() + ".png";
|
||||
return fileService.saveBytes(qrCodeBytes, fileName, "image/png", "system");
|
||||
})
|
||||
.flatMap(sysFile -> {
|
||||
String qrCodeUrl = "/api/files/" + sysFile.getId() + "/preview";
|
||||
course.setQrCodePath(qrCodeUrl);
|
||||
|
||||
course.setQrCodePath(ossUrl);
|
||||
|
||||
// 更新数据库
|
||||
return groupCourseRepository.update(course)
|
||||
.doOnSuccess(updated -> logger.info("团课二维码补全成功 - id={}, name={}, ossUrl={}",
|
||||
updated.getId(), updated.getCourseName(), ossUrl))
|
||||
.doOnError(error -> logger.error("团课二维码补全失败(更新DB) - id={}, name={}, error: {}",
|
||||
course.getId(), course.getCourseName(), error.getMessage()));
|
||||
return groupCourseRepository.update(course)
|
||||
.doOnSuccess(updated -> logger.info("团课二维码补全成功 - id={}, name={}, url={}",
|
||||
updated.getId(), updated.getCourseName(), qrCodeUrl))
|
||||
.doOnError(error -> logger.error("团课二维码补全失败(更新DB) - id={}, name={}, error: {}",
|
||||
course.getId(), course.getCourseName(), error.getMessage()));
|
||||
});
|
||||
} catch (Exception e) {
|
||||
logger.error("团课二维码补全失败(生成) - id={}, name={}, error: {}",
|
||||
course.getId(), course.getCourseName(), e.getMessage(), e);
|
||||
|
||||
+4
@@ -1,5 +1,7 @@
|
||||
package cn.novalon.gym.manage.groupcourse.repository;
|
||||
|
||||
import cn.novalon.gym.manage.common.dto.PageRequest;
|
||||
import cn.novalon.gym.manage.common.dto.PageResponse;
|
||||
import cn.novalon.gym.manage.groupcourse.domain.CourseLabel;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
@@ -29,4 +31,6 @@ public interface ICourseLabelRepository {
|
||||
Mono<Void> removeLabelFromType(Long typeId, Long labelId);
|
||||
|
||||
Mono<Void> clearLabelsFromType(Long typeId);
|
||||
|
||||
Mono<PageResponse<CourseLabel>> findByPage(PageRequest pageRequest);
|
||||
}
|
||||
+7
@@ -89,4 +89,11 @@ public interface IGroupCourseBookingRepository {
|
||||
* @return 更新记录数
|
||||
*/
|
||||
Mono<Integer> updateToAbsent(Long bookingId);
|
||||
|
||||
/**
|
||||
* 统计会员取消的预约次数
|
||||
* @param memberId 会员ID
|
||||
* @return 取消次数
|
||||
*/
|
||||
Mono<Long> countCancelledByMemberId(Long memberId);
|
||||
}
|
||||
+7
-2
@@ -27,9 +27,14 @@ public interface IGroupCourseRepository {
|
||||
|
||||
Mono<Void> deleteById(Long id);
|
||||
|
||||
Mono<GroupCourse> updateCurrentMembers(Long id, Integer delta);
|
||||
|
||||
Flux<GroupCourse> findByCourseType(Long courseType);
|
||||
|
||||
Mono<PageResponse<GroupCourse>> searchGroupCourses(GroupCourseQueryDto query);
|
||||
|
||||
// ==================== 教练相关 ====================
|
||||
|
||||
Flux<GroupCourse> findByCoachId(Long coachId);
|
||||
Flux<GroupCourse> findByCoachId(Long coachId, Sort sort);
|
||||
Mono<Long> countByCoachIdAndStatus(Long coachId, Long status);
|
||||
Mono<Integer> cancelCoursesByCoachIdExceptStatus(Long coachId, Long excludeStatus);
|
||||
}
|
||||
|
||||
+4
@@ -1,5 +1,7 @@
|
||||
package cn.novalon.gym.manage.groupcourse.repository;
|
||||
|
||||
import cn.novalon.gym.manage.common.dto.PageRequest;
|
||||
import cn.novalon.gym.manage.common.dto.PageResponse;
|
||||
import cn.novalon.gym.manage.groupcourse.domain.GroupCourseType;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
@@ -25,4 +27,6 @@ public interface IGroupCourseTypeRepository {
|
||||
Mono<GroupCourseType> update(GroupCourseType groupCourseType);
|
||||
|
||||
Mono<Void> deleteById(Long id);
|
||||
|
||||
Mono<PageResponse<GroupCourseType>> findByPage(PageRequest pageRequest);
|
||||
}
|
||||
+47
-1
@@ -1,5 +1,7 @@
|
||||
package cn.novalon.gym.manage.groupcourse.repository.impl;
|
||||
|
||||
import cn.novalon.gym.manage.common.dto.PageRequest;
|
||||
import cn.novalon.gym.manage.common.dto.PageResponse;
|
||||
import cn.novalon.gym.manage.groupcourse.converter.GroupCourseConverter;
|
||||
import cn.novalon.gym.manage.groupcourse.dao.CourseLabelDao;
|
||||
import cn.novalon.gym.manage.groupcourse.dao.CourseTypeLabelDao;
|
||||
@@ -9,12 +11,17 @@ import cn.novalon.gym.manage.groupcourse.entity.CourseTypeLabelEntity;
|
||||
import cn.novalon.gym.manage.groupcourse.repository.ICourseLabelRepository;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.r2dbc.core.R2dbcEntityTemplate;
|
||||
import org.springframework.data.relational.core.query.Criteria;
|
||||
import org.springframework.data.relational.core.query.Query;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Repository
|
||||
@@ -26,12 +33,14 @@ public class CourseLabelRepository implements ICourseLabelRepository {
|
||||
private final CourseLabelDao courseLabelDao;
|
||||
private final CourseTypeLabelDao courseTypeLabelDao;
|
||||
private final GroupCourseConverter converter;
|
||||
private final R2dbcEntityTemplate r2dbcEntityTemplate;
|
||||
|
||||
public CourseLabelRepository(CourseLabelDao courseLabelDao, CourseTypeLabelDao courseTypeLabelDao,
|
||||
GroupCourseConverter converter) {
|
||||
GroupCourseConverter converter, R2dbcEntityTemplate r2dbcEntityTemplate) {
|
||||
this.courseLabelDao = courseLabelDao;
|
||||
this.courseTypeLabelDao = courseTypeLabelDao;
|
||||
this.converter = converter;
|
||||
this.r2dbcEntityTemplate = r2dbcEntityTemplate;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -158,4 +167,41 @@ public class CourseLabelRepository implements ICourseLabelRepository {
|
||||
}
|
||||
return entity;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<PageResponse<CourseLabel>> findByPage(PageRequest pageRequest) {
|
||||
int page = pageRequest.getPage();
|
||||
int size = pageRequest.getSize();
|
||||
String sort = pageRequest.getSort();
|
||||
String order = pageRequest.getOrder();
|
||||
String keyword = pageRequest.getKeyword();
|
||||
|
||||
Sort sortObj = Sort.unsorted();
|
||||
if (sort != null && !sort.isEmpty()) {
|
||||
sortObj = Sort.by(Sort.Direction.fromString(order), sort);
|
||||
}
|
||||
|
||||
List<Criteria> criteriaList = new ArrayList<>();
|
||||
criteriaList.add(Criteria.where("deleted_at").isNull());
|
||||
if (keyword != null && !keyword.isEmpty()) {
|
||||
criteriaList.add(Criteria.where("label_name").like("%" + keyword + "%").ignoreCase(true));
|
||||
}
|
||||
|
||||
Criteria criteria = criteriaList.isEmpty() ? Criteria.empty() : Criteria.from(criteriaList);
|
||||
Query query = Query.query(criteria).with(org.springframework.data.domain.PageRequest.of(page, size, sortObj));
|
||||
|
||||
return r2dbcEntityTemplate.select(CourseLabelEntity.class)
|
||||
.matching(query)
|
||||
.all()
|
||||
.collectList()
|
||||
.zipWith(r2dbcEntityTemplate.count(Query.query(criteria), CourseLabelEntity.class))
|
||||
.map(tuple -> {
|
||||
long total = tuple.getT2();
|
||||
int totalPages = (int) Math.ceil((double) total / size);
|
||||
List<CourseLabel> list = tuple.getT1().stream()
|
||||
.map(this::toCourseLabel)
|
||||
.toList();
|
||||
return new PageResponse<>(list, totalPages, total, page, size);
|
||||
});
|
||||
}
|
||||
}
|
||||
+5
@@ -112,4 +112,9 @@ public class GroupCourseBookingRepository implements IGroupCourseBookingReposito
|
||||
java.time.LocalDateTime now = java.time.LocalDateTime.now();
|
||||
return groupCourseBookingDao.updateToAbsent(bookingId, now);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Long> countCancelledByMemberId(Long memberId) {
|
||||
return groupCourseBookingDao.countCancelledByMemberId(memberId);
|
||||
}
|
||||
}
|
||||
+35
-41
@@ -97,37 +97,19 @@ public class GroupCourseRepository implements IGroupCourseRepository {
|
||||
public Mono<PageResponse<GroupCourse>> findByPageAndNotDeleted(PageRequest pageRequest) {
|
||||
int page = pageRequest.getPage();
|
||||
int size = pageRequest.getSize();
|
||||
String sort = pageRequest.getSort();
|
||||
String order = pageRequest.getOrder();
|
||||
|
||||
Sort sortObj = Sort.unsorted();
|
||||
if (sort != null && !sort.isEmpty()) {
|
||||
sortObj = Sort.by(Sort.Direction.fromString(order), sort);
|
||||
}
|
||||
|
||||
org.springframework.data.domain.PageRequest pageable = org.springframework.data.domain.PageRequest.of(page, size, sortObj);
|
||||
|
||||
return groupCourseDao.findAllByDeletedAtIsNull(sortObj)
|
||||
.collectList()
|
||||
.zipWith(groupCourseDao.findAllByDeletedAtIsNull().count())
|
||||
.map(tuple -> {
|
||||
List<GroupCourseEntity> allEntities = tuple.getT1();
|
||||
long total = tuple.getT2();
|
||||
|
||||
int fromIndex = page * size;
|
||||
int toIndex = Math.min(fromIndex + size, allEntities.size());
|
||||
|
||||
List<GroupCourse> courseList;
|
||||
if (fromIndex < allEntities.size()) {
|
||||
courseList = allEntities.subList(fromIndex, toIndex).stream()
|
||||
.map(groupCourseConverter::toDomain)
|
||||
.toList();
|
||||
} else {
|
||||
courseList = List.of();
|
||||
return groupCourseDao.countByPageFiltered(r2dbcEntityTemplate.getDatabaseClient(), pageRequest)
|
||||
.flatMap(total -> {
|
||||
if (total == 0) {
|
||||
return Mono.just(new PageResponse<>(List.of(), 0, 0L, page, size));
|
||||
}
|
||||
|
||||
int totalPages = (int) Math.ceil((double) total / size);
|
||||
return new PageResponse<>(courseList, totalPages, total, page, size);
|
||||
return groupCourseDao.findByPageFiltered(r2dbcEntityTemplate.getDatabaseClient(), pageRequest)
|
||||
.map(groupCourseConverter::toDomain)
|
||||
.collectList()
|
||||
.map(courseList -> {
|
||||
int totalPages = (int) Math.ceil((double) total / size);
|
||||
return new PageResponse<>(courseList, totalPages, total, page, size);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -137,7 +119,6 @@ public class GroupCourseRepository implements IGroupCourseRepository {
|
||||
entity.setCreatedAt(LocalDateTime.now());
|
||||
entity.setUpdatedAt(LocalDateTime.now());
|
||||
entity.setStatus(0L);
|
||||
entity.setCurrentMembers(0);
|
||||
|
||||
return groupCourseDao.save(entity)
|
||||
.map(groupCourseConverter::toDomain);
|
||||
@@ -169,17 +150,6 @@ public class GroupCourseRepository implements IGroupCourseRepository {
|
||||
.then();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<GroupCourse> updateCurrentMembers(Long id, Integer delta) {
|
||||
return groupCourseDao.updateCurrentMembers(id, delta, LocalDateTime.now())
|
||||
.flatMap(updated -> {
|
||||
if (updated > 0) {
|
||||
return findByIdAndDeletedAtIsNull(id);
|
||||
}
|
||||
return Mono.empty();
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flux<GroupCourse> findByCourseType(Long courseType) {
|
||||
return groupCourseDao.findByCourseTypeAndDeletedAtIsNull(courseType)
|
||||
@@ -208,4 +178,28 @@ public class GroupCourseRepository implements IGroupCourseRepository {
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// ==================== 教练相关 ====================
|
||||
|
||||
@Override
|
||||
public Flux<GroupCourse> findByCoachId(Long coachId) {
|
||||
return groupCourseDao.findByCoachIdAndDeletedAtIsNull(coachId)
|
||||
.map(groupCourseConverter::toDomain);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flux<GroupCourse> findByCoachId(Long coachId, Sort sort) {
|
||||
return groupCourseDao.findByCoachIdAndDeletedAtIsNull(coachId, sort)
|
||||
.map(groupCourseConverter::toDomain);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Long> countByCoachIdAndStatus(Long coachId, Long status) {
|
||||
return groupCourseDao.countByCoachIdAndStatus(coachId, String.valueOf(status));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Integer> cancelCoursesByCoachIdExceptStatus(Long coachId, Long excludeStatus) {
|
||||
return groupCourseDao.cancelCoursesByCoachIdExceptStatus(coachId, String.valueOf(excludeStatus), LocalDateTime.now());
|
||||
}
|
||||
}
|
||||
|
||||
+54
-1
@@ -1,5 +1,7 @@
|
||||
package cn.novalon.gym.manage.groupcourse.repository.impl;
|
||||
|
||||
import cn.novalon.gym.manage.common.dto.PageRequest;
|
||||
import cn.novalon.gym.manage.common.dto.PageResponse;
|
||||
import cn.novalon.gym.manage.groupcourse.converter.GroupCourseConverter;
|
||||
import cn.novalon.gym.manage.groupcourse.dao.GroupCourseTypeDao;
|
||||
import cn.novalon.gym.manage.groupcourse.domain.GroupCourseType;
|
||||
@@ -7,12 +9,18 @@ import cn.novalon.gym.manage.groupcourse.entity.GroupCourseTypeEntity;
|
||||
import cn.novalon.gym.manage.groupcourse.repository.IGroupCourseTypeRepository;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.data.r2dbc.core.R2dbcEntityTemplate;
|
||||
import org.springframework.data.relational.core.query.Criteria;
|
||||
import org.springframework.data.relational.core.query.Query;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Repository
|
||||
@Transactional
|
||||
@@ -22,10 +30,13 @@ public class GroupCourseTypeRepository implements IGroupCourseTypeRepository {
|
||||
|
||||
private final GroupCourseTypeDao groupCourseTypeDao;
|
||||
private final GroupCourseConverter converter;
|
||||
private final R2dbcEntityTemplate r2dbcEntityTemplate;
|
||||
|
||||
public GroupCourseTypeRepository(GroupCourseTypeDao groupCourseTypeDao, GroupCourseConverter converter) {
|
||||
public GroupCourseTypeRepository(GroupCourseTypeDao groupCourseTypeDao, GroupCourseConverter converter,
|
||||
R2dbcEntityTemplate r2dbcEntityTemplate) {
|
||||
this.groupCourseTypeDao = groupCourseTypeDao;
|
||||
this.converter = converter;
|
||||
this.r2dbcEntityTemplate = r2dbcEntityTemplate;
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -129,4 +140,46 @@ public class GroupCourseTypeRepository implements IGroupCourseTypeRepository {
|
||||
return groupCourseTypeDao.softDelete(id, LocalDateTime.now())
|
||||
.then();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<PageResponse<GroupCourseType>> findByPage(PageRequest pageRequest) {
|
||||
int page = pageRequest.getPage();
|
||||
int size = pageRequest.getSize();
|
||||
String order = pageRequest.getOrder();
|
||||
String sort = pageRequest.getSort();
|
||||
String keyword = pageRequest.getKeyword();
|
||||
String category = pageRequest.getCategory();
|
||||
|
||||
Sort sortObj = Sort.unsorted();
|
||||
if (sort != null && !sort.isEmpty()) {
|
||||
sortObj = Sort.by(Sort.Direction.fromString(order), sort);
|
||||
}
|
||||
|
||||
// Build dynamic criteria
|
||||
List<Criteria> criteriaList = new ArrayList<>();
|
||||
criteriaList.add(Criteria.where("deleted_at").isNull());
|
||||
if (keyword != null && !keyword.isEmpty()) {
|
||||
criteriaList.add(Criteria.where("type_name").like("%" + keyword + "%").ignoreCase(true));
|
||||
}
|
||||
if (category != null && !category.isEmpty()) {
|
||||
criteriaList.add(Criteria.where("category").is(category));
|
||||
}
|
||||
|
||||
Criteria criteria = criteriaList.isEmpty() ? Criteria.empty() : Criteria.from(criteriaList);
|
||||
Query query = Query.query(criteria).with(org.springframework.data.domain.PageRequest.of(page, size, sortObj));
|
||||
|
||||
return r2dbcEntityTemplate.select(GroupCourseTypeEntity.class)
|
||||
.matching(query)
|
||||
.all()
|
||||
.collectList()
|
||||
.zipWith(r2dbcEntityTemplate.count(Query.query(criteria), GroupCourseTypeEntity.class))
|
||||
.map(tuple -> {
|
||||
long total = tuple.getT2();
|
||||
int totalPages = (int) Math.ceil((double) total / size);
|
||||
List<GroupCourseType> list = tuple.getT1().stream()
|
||||
.map(converter::toGroupCourseType)
|
||||
.toList();
|
||||
return new PageResponse<>(list, totalPages, total, page, size);
|
||||
});
|
||||
}
|
||||
}
|
||||
-46
@@ -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)
|
||||
);
|
||||
}
|
||||
}
|
||||
+4
@@ -1,5 +1,7 @@
|
||||
package cn.novalon.gym.manage.groupcourse.service;
|
||||
|
||||
import cn.novalon.gym.manage.common.dto.PageRequest;
|
||||
import cn.novalon.gym.manage.common.dto.PageResponse;
|
||||
import cn.novalon.gym.manage.groupcourse.domain.CourseLabel;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
@@ -27,4 +29,6 @@ public interface ICourseLabelService {
|
||||
Mono<Void> removeLabelFromType(Long typeId, Long labelId);
|
||||
|
||||
Mono<Void> clearLabelsFromType(Long typeId);
|
||||
|
||||
Mono<PageResponse<CourseLabel>> findByPage(PageRequest pageRequest);
|
||||
}
|
||||
+1
-2
@@ -17,10 +17,9 @@ public interface IGroupCourseBookingService {
|
||||
*
|
||||
* @param courseId 团课ID
|
||||
* @param memberId 会员ID
|
||||
* @param memberCardRecordId 会员卡记录ID
|
||||
* @return 预约记录
|
||||
*/
|
||||
Mono<GroupCourseBooking> bookCourse(Long courseId, Long memberId, Long memberCardRecordId);
|
||||
Mono<GroupCourseBooking> bookCourse(Long courseId, Long memberId);
|
||||
|
||||
/**
|
||||
* 取消预约
|
||||
|
||||
+16
@@ -6,14 +6,20 @@ import cn.novalon.gym.manage.common.dto.PageResponse;
|
||||
import cn.novalon.gym.manage.groupcourse.domain.GroupCourse;
|
||||
import cn.novalon.gym.manage.groupcourse.domain.GroupCourseDetail;
|
||||
import cn.novalon.gym.manage.groupcourse.dto.GroupCourseQueryDto;
|
||||
import cn.novalon.gym.manage.groupcourse.vo.GroupCourseVO;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
public interface IGroupCourseService {
|
||||
Mono<GroupCourse> findById(Long id);
|
||||
Mono<GroupCourseDetail> findDetailById(Long id);
|
||||
Flux<GroupCourse> findAll();
|
||||
Flux<GroupCourse> findAll(boolean includeDeleted);
|
||||
Flux<GroupCourseVO> findAllAsVO(boolean includeDeleted);
|
||||
Mono<PageResponse<GroupCourseVO>> findByPageAsVO(PageRequest pageRequest, boolean includeDeleted);
|
||||
|
||||
Mono<PageResponse<GroupCourse>> findByPage(PageRequest pageRequest, boolean includeDeleted);
|
||||
|
||||
@@ -28,4 +34,14 @@ public interface IGroupCourseService {
|
||||
Mono<Void> delete(Long id);
|
||||
|
||||
Mono<PageResponse<GroupCourse>> searchGroupCourses(GroupCourseQueryDto query);
|
||||
|
||||
/**
|
||||
* 检查教练在指定时间段内是否有时间冲突的团课
|
||||
* @param coachId 教练ID
|
||||
* @param startTime 开始时间
|
||||
* @param endTime 结束时间
|
||||
* @param excludeCourseId 排除的课程ID(编辑时排除自身)
|
||||
* @return 冲突的课程列表
|
||||
*/
|
||||
Mono<List<GroupCourse>> checkCoachConflict(Long coachId, LocalDateTime startTime, LocalDateTime endTime, Long excludeCourseId);
|
||||
}
|
||||
|
||||
+4
@@ -1,5 +1,7 @@
|
||||
package cn.novalon.gym.manage.groupcourse.service;
|
||||
|
||||
import cn.novalon.gym.manage.common.dto.PageRequest;
|
||||
import cn.novalon.gym.manage.common.dto.PageResponse;
|
||||
import cn.novalon.gym.manage.groupcourse.domain.GroupCourseType;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
@@ -29,4 +31,6 @@ public interface IGroupCourseTypeService {
|
||||
* @return 分类名称列表
|
||||
*/
|
||||
Flux<String> findCategories();
|
||||
|
||||
Mono<PageResponse<GroupCourseType>> findByPage(PageRequest pageRequest);
|
||||
}
|
||||
+10
@@ -1,5 +1,7 @@
|
||||
package cn.novalon.gym.manage.groupcourse.service.impl;
|
||||
|
||||
import cn.novalon.gym.manage.common.dto.PageRequest;
|
||||
import cn.novalon.gym.manage.common.dto.PageResponse;
|
||||
import cn.novalon.gym.manage.common.util.RedisUtil;
|
||||
import cn.novalon.gym.manage.groupcourse.domain.CourseLabel;
|
||||
import cn.novalon.gym.manage.groupcourse.domain.GroupCourse;
|
||||
@@ -109,4 +111,12 @@ public class CourseLabelService implements ICourseLabelService {
|
||||
.doOnSuccess(v -> logger.info("清空类型标签成功 - typeId={}", typeId))
|
||||
.doOnError(error -> logger.error("清空类型标签失败 - typeId={}, error: {}", typeId, error.getMessage()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<PageResponse<CourseLabel>> findByPage(PageRequest pageRequest) {
|
||||
return courseLabelRepository.findByPage(pageRequest)
|
||||
.doOnSuccess(result -> logger.info("分页查询标签成功 - page={}, size={}, total={}",
|
||||
pageRequest.getPage(), pageRequest.getSize(), result.getTotalElements()))
|
||||
.doOnError(error -> logger.error("分页查询标签失败 - error: {}", error.getMessage()));
|
||||
}
|
||||
}
|
||||
+77
-104
@@ -3,7 +3,6 @@ package cn.novalon.gym.manage.groupcourse.service.impl;
|
||||
import cn.novalon.gym.manage.groupcourse.domain.GroupCourse;
|
||||
import cn.novalon.gym.manage.groupcourse.domain.GroupCourseBooking;
|
||||
import cn.novalon.gym.manage.groupcourse.event.BookingReminderEventPublisher;
|
||||
import cn.novalon.gym.manage.groupcourse.handler.BookingSagaHandler;
|
||||
import cn.novalon.gym.manage.groupcourse.repository.IGroupCourseBookingRepository;
|
||||
import cn.novalon.gym.manage.groupcourse.repository.IGroupCourseRepository;
|
||||
import cn.novalon.gym.manage.groupcourse.service.IGroupCourseBookingService;
|
||||
@@ -25,7 +24,6 @@ import java.util.UUID;
|
||||
* - 取消预约需在课程开始前至少2小时
|
||||
* - 每节课最多20人
|
||||
* - 预约成功后发送提醒
|
||||
* - 预约成功后扣减权益
|
||||
*
|
||||
* 技术要点:
|
||||
* - 使用Redis缓存团课信息
|
||||
@@ -44,7 +42,6 @@ public class GroupCourseBookingService implements IGroupCourseBookingService {
|
||||
private final IGroupCourseRepository courseRepository;
|
||||
private final GroupCourseRedisService redisService;
|
||||
private final BookingReminderEventPublisher bookingReminderEventPublisher;
|
||||
private final BookingSagaHandler bookingSagaHandler;
|
||||
|
||||
// 预约提前时间限制(分钟)
|
||||
private static final long BOOKING_MIN_ADVANCE_MINUTES = 30;
|
||||
@@ -54,18 +51,16 @@ public class GroupCourseBookingService implements IGroupCourseBookingService {
|
||||
public GroupCourseBookingService(IGroupCourseBookingRepository bookingRepository,
|
||||
IGroupCourseRepository courseRepository,
|
||||
GroupCourseRedisService redisService,
|
||||
BookingReminderEventPublisher bookingReminderEventPublisher,
|
||||
BookingSagaHandler bookingSagaHandler) {
|
||||
BookingReminderEventPublisher bookingReminderEventPublisher) {
|
||||
this.bookingRepository = bookingRepository;
|
||||
this.courseRepository = courseRepository;
|
||||
this.redisService = redisService;
|
||||
this.bookingReminderEventPublisher = bookingReminderEventPublisher;
|
||||
this.bookingSagaHandler = bookingSagaHandler;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<GroupCourseBooking> bookCourse(Long courseId, Long memberId, Long memberCardRecordId) {
|
||||
logger.info("开始预约团课:courseId={}, memberId={}, memberCardRecordId={}", courseId, memberId, memberCardRecordId);
|
||||
public Mono<GroupCourseBooking> bookCourse(Long courseId, Long memberId) {
|
||||
logger.info("开始预约团课:courseId={}, memberId={}", courseId, memberId);
|
||||
|
||||
// 生成唯一请求ID用于分布式锁
|
||||
String requestId = UUID.randomUUID().toString();
|
||||
@@ -77,18 +72,26 @@ public class GroupCourseBookingService implements IGroupCourseBookingService {
|
||||
return Mono.error(new RuntimeException("系统繁忙,请稍后重试"));
|
||||
}
|
||||
|
||||
// 2. 尝试从缓存获取课程信息,如果缓存不存在则从数据库获取
|
||||
// 2. 从缓存或数据库获取课程信息,并用实时预约数覆盖currentMembers
|
||||
return getCourseWithCache(courseId)
|
||||
.flatMap(course ->
|
||||
bookingRepository.countValidBookings(courseId)
|
||||
.map(count -> {
|
||||
course.setCurrentMembers(count.intValue());
|
||||
return course;
|
||||
})
|
||||
.defaultIfEmpty(course)
|
||||
)
|
||||
.flatMap(course -> {
|
||||
// 3. 验证课程状态
|
||||
Long status = course.getStatus();
|
||||
if (status == null || status != 0L) {
|
||||
Long courseStatus = course.getStatus();
|
||||
if (courseStatus == null || courseStatus != 0L) {
|
||||
String errorMessage;
|
||||
if (status == null) {
|
||||
if (courseStatus == null) {
|
||||
errorMessage = "课程状态异常";
|
||||
} else if (status == 1L) {
|
||||
} else if (courseStatus == 1L) {
|
||||
errorMessage = "课程已取消,无法预约";
|
||||
} else if (status == 2L) {
|
||||
} else if (courseStatus == 2L) {
|
||||
errorMessage = "课程已结束,无法预约";
|
||||
} else {
|
||||
errorMessage = "课程状态不可预约";
|
||||
@@ -131,56 +134,46 @@ public class GroupCourseBookingService implements IGroupCourseBookingService {
|
||||
|
||||
// 7. 验证是否已预约
|
||||
return bookingRepository.findValidBooking(courseId, memberId)
|
||||
.flatMap(existingBooking -> {
|
||||
return releaseLockAndError(courseId, requestId, "您已预约该课程");
|
||||
})
|
||||
.flatMap(existingBooking ->
|
||||
releaseLockAndError(courseId, requestId, "您已预约该课程")
|
||||
)
|
||||
.switchIfEmpty(
|
||||
// 8. 使用Redis原子操作验证课程人数是否已满
|
||||
validateAndIncrementBookingCount(courseId, course.getMaxMembers())
|
||||
.flatMap(countValid -> {
|
||||
if (countValid > course.getMaxMembers()) {
|
||||
return releaseLockAndError(courseId, requestId, "课程已满");
|
||||
}
|
||||
// 8. 创建预约记录
|
||||
Mono.defer(() -> {
|
||||
GroupCourseBooking booking = new GroupCourseBooking();
|
||||
booking.setCourseId(courseId);
|
||||
booking.setMemberId(memberId);
|
||||
booking.setBookingTime(LocalDateTime.now());
|
||||
booking.setStatus("0"); // 0-已预约
|
||||
|
||||
// 9. 创建预约记录
|
||||
GroupCourseBooking booking = new GroupCourseBooking();
|
||||
booking.setCourseId(courseId);
|
||||
booking.setMemberId(memberId);
|
||||
booking.setMemberCardRecordId(memberCardRecordId);
|
||||
booking.setBookingTime(LocalDateTime.now());
|
||||
booking.setStatus("0"); // 0-已预约
|
||||
// 添加课程信息到预约记录
|
||||
booking.setCourseName(course.getCourseName());
|
||||
booking.setCourseStartTime(course.getStartTime());
|
||||
booking.setCourseEndTime(course.getEndTime());
|
||||
booking.setLocation(course.getLocation());
|
||||
|
||||
// 添加课程信息到预约记录
|
||||
booking.setCourseName(course.getCourseName());
|
||||
booking.setCourseStartTime(course.getStartTime());
|
||||
booking.setCourseEndTime(course.getEndTime());
|
||||
booking.setLocation(course.getLocation());
|
||||
|
||||
// 10. 使用Saga事务执行预约(包含权益扣减)
|
||||
return bookingSagaHandler.executeBooking(booking, memberCardRecordId)
|
||||
.flatMap(savedBooking -> {
|
||||
// 11. 释放锁
|
||||
return redisService.releaseLock(courseId, requestId)
|
||||
.then(Mono.just(savedBooking));
|
||||
})
|
||||
.doOnSuccess(savedBooking -> {
|
||||
logger.info("预约成功:bookingId={}, courseId={}, memberId={}",
|
||||
savedBooking.getId(), courseId, memberId);
|
||||
// 发布预约成功事件
|
||||
bookingReminderEventPublisher.publishBookingSuccessEvent(
|
||||
savedBooking.getId(),
|
||||
savedBooking.getMemberId(),
|
||||
savedBooking.getCourseName(),
|
||||
savedBooking.getCourseStartTime().toString()
|
||||
);
|
||||
})
|
||||
.doOnError(error -> {
|
||||
// 回滚Redis计数
|
||||
redisService.decrementBookingCount(courseId).subscribe();
|
||||
logger.error("预约失败:courseId={}, memberId={}, error={}",
|
||||
courseId, memberId, error.getMessage());
|
||||
});
|
||||
})
|
||||
// 9. 保存预约记录
|
||||
return bookingRepository.save(booking)
|
||||
.flatMap(saved -> {
|
||||
if (saved.getId() == null) {
|
||||
return Mono.error(new RuntimeException("保存预约记录失败"));
|
||||
}
|
||||
// 10. 释放锁
|
||||
return redisService.releaseLock(courseId, requestId)
|
||||
.then(Mono.just(saved));
|
||||
})
|
||||
.doOnSuccess(savedBooking -> {
|
||||
logger.info("预约成功:bookingId={}, courseId={}, memberId={}",
|
||||
savedBooking.getId(), courseId, memberId);
|
||||
// 发布预约成功事件
|
||||
bookingReminderEventPublisher.publishBookingSuccessEvent(
|
||||
savedBooking.getId(),
|
||||
savedBooking.getMemberId(),
|
||||
savedBooking.getCourseName(),
|
||||
savedBooking.getCourseStartTime().toString()
|
||||
);
|
||||
});
|
||||
})
|
||||
);
|
||||
});
|
||||
})
|
||||
@@ -208,29 +201,6 @@ public class GroupCourseBookingService implements IGroupCourseBookingService {
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证并增加预约人数(使用Redis原子操作)
|
||||
*/
|
||||
private Mono<Integer> validateAndIncrementBookingCount(Long courseId, Integer maxMembers) {
|
||||
// 先获取当前Redis中的预约计数
|
||||
return redisService.getBookingCount(courseId)
|
||||
.flatMap(currentCount -> {
|
||||
// 如果Redis中计数为0,可能是首次访问,需要从数据库同步
|
||||
if (currentCount == 0) {
|
||||
// 从数据库查询实际预约人数
|
||||
return bookingRepository.countValidBookings(courseId)
|
||||
.flatMap(dbCount -> {
|
||||
// 将数据库中的实际预约人数同步到Redis
|
||||
return redisService.setBookingCount(courseId, dbCount.intValue())
|
||||
.then(Mono.just(dbCount.intValue()));
|
||||
});
|
||||
}
|
||||
return Mono.just(currentCount);
|
||||
})
|
||||
// 递增预约计数
|
||||
.flatMap(count -> redisService.incrementBookingCount(courseId).map(Long::intValue));
|
||||
}
|
||||
|
||||
/**
|
||||
* 释放锁并返回错误
|
||||
*/
|
||||
@@ -290,26 +260,29 @@ public class GroupCourseBookingService implements IGroupCourseBookingService {
|
||||
"需在课程开始前" + CANCEL_MIN_ADVANCE_HOURS + "小时取消");
|
||||
}
|
||||
|
||||
// 5. 使用Saga事务执行取消预约(包含权益恢复)
|
||||
return bookingSagaHandler.executeCancelBooking(bookingId, booking.getCourseId(), booking.getMemberCardRecordId(), memberId)
|
||||
.flatMap(updatedBooking -> {
|
||||
// 6. 释放锁
|
||||
return redisService.releaseLock(bookingId, requestId)
|
||||
.then(Mono.just(updatedBooking));
|
||||
})
|
||||
.doOnSuccess(updatedBooking -> {
|
||||
logger.info("取消预约成功:bookingId={}, memberId={}", bookingId, memberId);
|
||||
// 发布预约取消事件
|
||||
bookingReminderEventPublisher.publishBookingCancelEvent(
|
||||
updatedBooking.getId(),
|
||||
updatedBooking.getMemberId(),
|
||||
updatedBooking.getCourseName()
|
||||
);
|
||||
})
|
||||
.doOnError(error -> {
|
||||
logger.error("取消预约失败:bookingId={}, memberId={}, error={}",
|
||||
bookingId, memberId, error.getMessage());
|
||||
});
|
||||
// 5. 更新预约状态为已取消
|
||||
return bookingRepository.updateStatus(bookingId, "1")
|
||||
.flatMap(rows -> {
|
||||
if (rows == 0) {
|
||||
return Mono.error(new RuntimeException("更新预约状态失败"));
|
||||
}
|
||||
// 6. 释放锁
|
||||
return redisService.releaseLock(bookingId, requestId)
|
||||
.then(bookingRepository.findById(bookingId));
|
||||
})
|
||||
.doOnSuccess(updatedBooking -> {
|
||||
logger.info("取消预约成功:bookingId={}, memberId={}", bookingId, memberId);
|
||||
// 发布预约取消事件
|
||||
bookingReminderEventPublisher.publishBookingCancelEvent(
|
||||
updatedBooking.getId(),
|
||||
updatedBooking.getMemberId(),
|
||||
updatedBooking.getCourseName()
|
||||
);
|
||||
})
|
||||
.doOnError(error -> {
|
||||
logger.error("取消预约失败:bookingId={}, memberId={}, error={}",
|
||||
bookingId, memberId, error.getMessage());
|
||||
});
|
||||
})
|
||||
.onErrorResume(error -> {
|
||||
redisService.releaseLock(bookingId, requestId).subscribe();
|
||||
|
||||
-42
@@ -149,46 +149,4 @@ public class GroupCourseRedisService {
|
||||
})
|
||||
.defaultIfEmpty(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取课程预约人数(缓存)
|
||||
*/
|
||||
public Mono<Integer> getBookingCount(Long courseId) {
|
||||
String key = "booking_count:" + courseId;
|
||||
return reactiveRedisTemplate.opsForValue()
|
||||
.get(key)
|
||||
.map(obj -> (Integer) obj)
|
||||
.defaultIfEmpty(0);
|
||||
}
|
||||
|
||||
/**
|
||||
* 增加课程预约人数
|
||||
*/
|
||||
public Mono<Long> incrementBookingCount(Long courseId) {
|
||||
String key = "booking_count:" + courseId;
|
||||
return reactiveRedisTemplate.opsForValue()
|
||||
.increment(key)
|
||||
.doOnSuccess(count -> logger.debug("预约人数增加:courseId={}, count={}", courseId, count));
|
||||
}
|
||||
|
||||
/**
|
||||
* 减少课程预约人数
|
||||
*/
|
||||
public Mono<Long> decrementBookingCount(Long courseId) {
|
||||
String key = "booking_count:" + courseId;
|
||||
return reactiveRedisTemplate.opsForValue()
|
||||
.decrement(key)
|
||||
.doOnSuccess(count -> logger.debug("预约人数减少:courseId={}, count={}", courseId, count));
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置课程预约人数(用于从数据库同步)
|
||||
*/
|
||||
public Mono<Void> setBookingCount(Long courseId, Integer count) {
|
||||
String key = "booking_count:" + courseId;
|
||||
return reactiveRedisTemplate.opsForValue()
|
||||
.set(key, count)
|
||||
.doOnSuccess(result -> logger.debug("预约人数已设置:courseId={}, count={}", courseId, count))
|
||||
.then();
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user