Compare commits
49
Commits
8cf3c9ccee
..
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 | ||
|
|
2ffd1aa7d6 | ||
|
|
581cc995c6 | ||
|
|
2251f31524 | ||
|
|
4481819eba | ||
|
|
79eb07599e | ||
|
|
a7f31083cf | ||
|
|
524182c478 | ||
|
|
3586a7d74b | ||
|
|
8da58a8f51 | ||
|
|
0b2146f237 | ||
|
|
7cc9a68144 | ||
|
|
b5c8a087dd | ||
|
|
7a94145819 | ||
|
|
7e4035e0ae | ||
|
|
e19324d0ef | ||
|
|
e0e707edcb | ||
|
|
8ab528a74b | ||
|
|
de7a359ead | ||
|
|
fbb41911a2 | ||
|
|
223a427614 | ||
|
|
78c80c4b1d |
@@ -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,202 @@
|
|||||||
|
import java.util.Base64;
|
||||||
|
import java.math.BigInteger;
|
||||||
|
import java.io.ByteArrayInputStream;
|
||||||
|
|
||||||
|
public class KeyAnalyzer {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
String privateKeyBase64 = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCcxAwrhZF+izz1gxQKOr4jnC05obIBHbl0DzHOcd4CaaDV7Kv1NRJKi33JhdDsW4JGgu16e5Rtzq1VzU5VWz5EKgGL46maOFwCkngJUTP/LC3JVf/wtJmYCm8xNE8C7GNNIqKzYEvUOEfXqagpVvVrGsQ9FpzFp2rP9hBmHY3yizVyPX/uT9S+af5TRxiaItj3SSJGgloaEMrnKOpb/EH7JwPSS0liAyT/NxPfOyyZHc22AvaAIOE5y+0PMUIKPuIdfpOrej3LVpO1Arc2hSgmdB+YIPSiBVYPXa6AuAmil9mpbtSikQJ7Uu7lX4JyTW4QxQ06rPFKnFWVKkzivAElAgMBAAECggEAJd0AJ37iTlMpDQ90xqe7hvRQxAu256gbQ9nrqLY97g0/KIw6WEZSPakFX6gvdvb/NzKmUyAIEKGLoh6tXdZk6qfOqc/6BeK47nIcBfwT9/zerjNUVvn34w4aHyNINieMMHQ+Id8PUZmqWH+Euz9ilVTosuyEPwUZulLvUQqwXzU5VnwVghURbUhDd+ecBJACWgemRun6d5241PQXNYAdH1k7cETd8GfIi3qclhhJrxi7tu5tq4YGCXQIoz7HCLim7GIvT0M+FRgSw2EOrHnAQNFeQ/vQbP71ttLoTxehL6Se9dfWrV5OI+Y/T7vR2F84Qt0iNbaxyJGir7siKDFIwQKBgQDXDzinx3/TasplM78pR/0CtuuKr1Ch02LOPrTosJ1qf1OohxQThowhOTxMsBlgYSKu9s1QRffUUXEqYXxd2B6lzDKfggwO6U2XxIcxWeNow0xoFfqcXYSg7Ga2sCr9uhdwxIdFQNF7SNBpT8ht4fJrRX6mWY1nHybpyTDQ4xoQNQKBgQC6m+yiOoi5JD3zVSSJq/iq5DJPA5B4aoP+t5u9lp2Q7iVO0QI5ilBlEKGE4VOU0glnXlDTfuqEYooMY85ekl4WGb3AOT0PhLL2i+gO2nlWBzf4HPzB/hibjfyPyniRM03cHkG3HXucL7Sne6FwERcfjEqjUd2cdP1l89PNrq4rMQKBgQCMmjABSWYh8/y1I5rEQ4OAJdVjC3GdC1Xa35ZpVybjvLEWSpHunhW5lvD8dllw8LC7UTI0XDpGPqTM/4VO2YBYB2PFc0Gs8g0/v0ZgFpOeJ6kpl80MM/wFNemFYTIKRoMSv/psZY9PmfBgGcBBTuquBXZjDcNr+yr2yAm5V/DvTQKBgHqRi94KoF8q5N39IKCkqhJlDH5FkxDktYoKw2rFkPzuzuZz9gghRyj6wXxsG9/2DWMt2dzw0czehFoa/CO188KEadPmRKr6uCmkP2nyKhxNZX+8WnB5G2Sg4DD6BjMpBYz8+qDx5ozx8LDJTYI0V4HLPgMD9JGdbgsXGhlREOkhAoGALr6IQOXnviWNAhCdc7rrsaMLMPbLZ1wqzWtQUG1JxDobbpzEP4CW/mvW5pMn58mSBg5qbXhyDI4fFP0CPb98QIz2tGnIzYyFzdKmF5Z1N7X1OF9O+tsSqASoBZzTqB4fr/o4mz0s9JCeriBR2LWjsbsDU13DTLsfQpWbtOnIy70=";
|
||||||
|
|
||||||
|
System.out.println("========== 密钥分析开始 ==========");
|
||||||
|
System.out.println("密钥长度: " + privateKeyBase64.length());
|
||||||
|
|
||||||
|
byte[] keyBytes = Base64.getDecoder().decode(privateKeyBase64);
|
||||||
|
System.out.println("解码后长度: " + keyBytes.length + " bytes");
|
||||||
|
|
||||||
|
// 打印前30字节
|
||||||
|
System.out.print("前30字节(hex): ");
|
||||||
|
for (int i = 0; i < 30 && i < keyBytes.length; i++) {
|
||||||
|
System.out.printf("%02X ", keyBytes[i]);
|
||||||
|
}
|
||||||
|
System.out.println();
|
||||||
|
|
||||||
|
// 解析ASN.1结构
|
||||||
|
try {
|
||||||
|
parseASN1(keyBytes);
|
||||||
|
} catch (Exception e) {
|
||||||
|
System.out.println("解析失败: " + e.getMessage());
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void parseASN1(byte[] keyBytes) throws Exception {
|
||||||
|
ByteArrayInputStream bis = new ByteArrayInputStream(keyBytes);
|
||||||
|
|
||||||
|
// 读取SEQUENCE
|
||||||
|
int tag = bis.read();
|
||||||
|
System.out.println("第一个tag: 0x" + Integer.toHexString(tag));
|
||||||
|
|
||||||
|
if (tag == 0x30) {
|
||||||
|
System.out.println("这是SEQUENCE");
|
||||||
|
|
||||||
|
// 读取长度
|
||||||
|
int len = readASN1Length(bis);
|
||||||
|
System.out.println("SEQUENCE长度: " + len);
|
||||||
|
|
||||||
|
// 检查下一个tag
|
||||||
|
int nextTag = bis.read();
|
||||||
|
System.out.println("下一个tag: 0x" + Integer.toHexString(nextTag));
|
||||||
|
|
||||||
|
if (nextTag == 0x02) {
|
||||||
|
// INTEGER
|
||||||
|
int intLen = readASN1Length(bis);
|
||||||
|
byte[] versionBytes = new byte[intLen];
|
||||||
|
bis.read(versionBytes);
|
||||||
|
int version = new BigInteger(versionBytes).intValue();
|
||||||
|
System.out.println("版本INTEGER值: " + version);
|
||||||
|
|
||||||
|
// 检查这是PKCS#8还是PKCS#1
|
||||||
|
// PKCS#8: version=0后是SEQUENCE(算法标识符)
|
||||||
|
// PKCS#1: version=0后是INTEGER(modulus)
|
||||||
|
int afterVersionTag = bis.read();
|
||||||
|
System.out.println("版本后的tag: 0x" + Integer.toHexString(afterVersionTag));
|
||||||
|
|
||||||
|
if (afterVersionTag == 0x30) {
|
||||||
|
System.out.println(">>> 这是PKCS#8格式 (version后是SEQUENCE)");
|
||||||
|
|
||||||
|
// 解析PKCS#8
|
||||||
|
// AlgorithmIdentifier: SEQUENCE { OID, NULL }
|
||||||
|
int algLen = readASN1Length(bis);
|
||||||
|
System.out.println("AlgorithmIdentifier长度: " + algLen);
|
||||||
|
|
||||||
|
// 跳过AlgorithmIdentifier内容
|
||||||
|
byte[] algBytes = new byte[algLen];
|
||||||
|
bis.read(algBytes);
|
||||||
|
|
||||||
|
// 打印OID
|
||||||
|
System.out.print("OID bytes: ");
|
||||||
|
for (int i = 0; i < algBytes.length; i++) {
|
||||||
|
System.out.printf("%02X ", algBytes[i]);
|
||||||
|
}
|
||||||
|
System.out.println();
|
||||||
|
|
||||||
|
// 下一个应该是OCTET STRING (包含私钥)
|
||||||
|
int octetTag = bis.read();
|
||||||
|
System.out.println("下一个tag: 0x" + Integer.toHexString(octetTag));
|
||||||
|
|
||||||
|
if (octetTag == 0x04) {
|
||||||
|
System.out.println("这是OCTET STRING (包含私钥数据)");
|
||||||
|
int octetLen = readASN1Length(bis);
|
||||||
|
System.out.println("OCTET STRING长度: " + octetLen);
|
||||||
|
|
||||||
|
// OCTET STRING内容是PKCS#1私钥
|
||||||
|
byte[] pkcs1Bytes = new byte[octetLen];
|
||||||
|
bis.read(pkcs1Bytes);
|
||||||
|
|
||||||
|
System.out.print("PKCS#1私钥前20字节: ");
|
||||||
|
for (int i = 0; i < 20; i++) {
|
||||||
|
System.out.printf("%02X ", pkcs1Bytes[i]);
|
||||||
|
}
|
||||||
|
System.out.println();
|
||||||
|
|
||||||
|
// 解析PKCS#1私钥
|
||||||
|
ByteArrayInputStream pkcs1Stream = new ByteArrayInputStream(pkcs1Bytes);
|
||||||
|
int pkcs1Tag = pkcs1Stream.read();
|
||||||
|
System.out.println("PKCS#1第一个tag: 0x" + Integer.toHexString(pkcs1Tag));
|
||||||
|
|
||||||
|
if (pkcs1Tag == 0x30) {
|
||||||
|
int pkcs1Len = readASN1Length(pkcs1Stream);
|
||||||
|
System.out.println("PKCS#1 SEQUENCE长度: " + pkcs1Len);
|
||||||
|
|
||||||
|
// version
|
||||||
|
int vTag = pkcs1Stream.read();
|
||||||
|
int vLen = readASN1Length(pkcs1Stream);
|
||||||
|
byte[] vBytes = new byte[vLen];
|
||||||
|
pkcs1Stream.read(vBytes);
|
||||||
|
System.out.println("PKCS#1版本: " + new BigInteger(vBytes));
|
||||||
|
|
||||||
|
// 解析私钥参数
|
||||||
|
parsePKCS1(pkcs1Stream);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (afterVersionTag == 0x02) {
|
||||||
|
System.out.println(">>> 这是PKCS#1格式 (version后是INTEGER)");
|
||||||
|
|
||||||
|
// 继续解析PKCS#1
|
||||||
|
parsePKCS1(bis);
|
||||||
|
} else {
|
||||||
|
System.out.println(">>> 未知格式 (tag: 0x" + Integer.toHexString(afterVersionTag) + ")");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void parsePKCS1(ByteArrayInputStream bis) throws Exception {
|
||||||
|
System.out.println("\n========== 解析PKCS#1私钥参数 ==========");
|
||||||
|
|
||||||
|
// modulus
|
||||||
|
BigInteger modulus = readASN1Integer(bis);
|
||||||
|
System.out.println("modulus长度: " + modulus.bitLength() + " bits");
|
||||||
|
|
||||||
|
// publicExponent
|
||||||
|
BigInteger publicExponent = readASN1Integer(bis);
|
||||||
|
System.out.println("publicExponent: " + publicExponent);
|
||||||
|
|
||||||
|
// privateExponent
|
||||||
|
BigInteger privateExponent = readASN1Integer(bis);
|
||||||
|
System.out.println("privateExponent长度: " + privateExponent.bitLength() + " bits");
|
||||||
|
|
||||||
|
// prime1
|
||||||
|
BigInteger prime1 = readASN1Integer(bis);
|
||||||
|
System.out.println("prime1长度: " + prime1.bitLength() + " bits");
|
||||||
|
|
||||||
|
// prime2
|
||||||
|
BigInteger prime2 = readASN1Integer(bis);
|
||||||
|
System.out.println("prime2长度: " + prime2.bitLength() + " bits");
|
||||||
|
|
||||||
|
// 验证 prime1 * prime2 == modulus
|
||||||
|
BigInteger calculatedModulus = prime1.multiply(prime2);
|
||||||
|
boolean valid = calculatedModulus.equals(modulus);
|
||||||
|
System.out.println("\n验证 prime1 * prime2 == modulus: " + valid);
|
||||||
|
|
||||||
|
if (!valid) {
|
||||||
|
System.out.println(">>> 密钥数学关系不正确!这是无效的RSA私钥");
|
||||||
|
System.out.println("计算得到的modulus长度: " + calculatedModulus.bitLength() + " bits");
|
||||||
|
}
|
||||||
|
|
||||||
|
// exponent1
|
||||||
|
BigInteger exponent1 = readASN1Integer(bis);
|
||||||
|
System.out.println("exponent1长度: " + exponent1.bitLength() + " bits");
|
||||||
|
|
||||||
|
// exponent2
|
||||||
|
BigInteger exponent2 = readASN1Integer(bis);
|
||||||
|
System.out.println("exponent2长度: " + exponent2.bitLength() + " bits");
|
||||||
|
|
||||||
|
// coefficient
|
||||||
|
BigInteger coefficient = readASN1Integer(bis);
|
||||||
|
System.out.println("coefficient长度: " + coefficient.bitLength() + " bits");
|
||||||
|
|
||||||
|
System.out.println("\n========== 解析完成 ==========");
|
||||||
|
}
|
||||||
|
|
||||||
|
static int readASN1Length(ByteArrayInputStream bis) throws Exception {
|
||||||
|
int firstByte = bis.read();
|
||||||
|
if ((firstByte & 0x80) == 0) {
|
||||||
|
return firstByte;
|
||||||
|
}
|
||||||
|
int numBytes = firstByte & 0x7F;
|
||||||
|
int length = 0;
|
||||||
|
for (int i = 0; i < numBytes; i++) {
|
||||||
|
length = (length << 8) | (bis.read() & 0xFF);
|
||||||
|
}
|
||||||
|
return length;
|
||||||
|
}
|
||||||
|
|
||||||
|
static BigInteger readASN1Integer(ByteArrayInputStream bis) throws Exception {
|
||||||
|
int tag = bis.read();
|
||||||
|
if (tag != 0x02) throw new Exception("期望INTEGER tag: 0x02, 实际: 0x" + Integer.toHexString(tag));
|
||||||
|
int len = readASN1Length(bis);
|
||||||
|
byte[] data = new byte[len];
|
||||||
|
bis.read(data);
|
||||||
|
return new BigInteger(1, data);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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%);满员率防御除零 |
|
||||||
@@ -0,0 +1,452 @@
|
|||||||
|
# 数据统计模块 API 文档
|
||||||
|
|
||||||
|
> **文档版本**: v1.0
|
||||||
|
> **创建日期**: 2026-06-09
|
||||||
|
> **作者**: system
|
||||||
|
> **状态**: 正式发布
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📋 目录
|
||||||
|
|
||||||
|
1. [概述](#概述)
|
||||||
|
2. [基础路径](#基础路径)
|
||||||
|
3. [统计数据接口](#统计数据接口)
|
||||||
|
- [获取综合统计数据](#获取综合统计数据)
|
||||||
|
- [获取会员统计数据](#获取会员统计数据)
|
||||||
|
- [获取预约统计数据](#获取预约统计数据)
|
||||||
|
- [获取签到统计数据](#获取签到统计数据)
|
||||||
|
- [查询历史统计数据](#查询历史统计数据)
|
||||||
|
- [导出统计数据](#导出统计数据)
|
||||||
|
4. [数据模型](#数据模型)
|
||||||
|
- [StatisticsQuery(查询条件)](#StatisticsQuery查询条件)
|
||||||
|
- [StatisticsSummary(统计汇总)](#StatisticsSummary统计汇总)
|
||||||
|
- [MemberStatistics(会员统计)](#MemberStatistics会员统计)
|
||||||
|
- [BookingStatistics(预约统计)](#BookingStatistics预约统计)
|
||||||
|
- [SignInStatistics(签到统计)](#SignInStatistics签到统计)
|
||||||
|
5. [状态码说明](#状态码说明)
|
||||||
|
6. [业务规则](#业务规则)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 概述
|
||||||
|
|
||||||
|
数据统计模块提供健身房会员、预约、签到数据的统计功能,支持按日、周、月周期统计,并提供Excel导出功能。采用 Spring WebFlux 响应式编程,统计结果通过 Redis 缓存提高查询性能。
|
||||||
|
|
||||||
|
## 基础路径
|
||||||
|
|
||||||
|
所有接口的基础路径为: `http://{host}:{port}/api/datacount`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 统计数据接口
|
||||||
|
|
||||||
|
### 获取综合统计数据
|
||||||
|
|
||||||
|
| 属性 | 值 |
|
||||||
|
|------|-----|
|
||||||
|
| **HTTP方法** | GET |
|
||||||
|
| **接口路径** | `/api/datacount/summary` |
|
||||||
|
| **所属文件** | `DataStatisticsHandler.java` |
|
||||||
|
|
||||||
|
**请求参数**:
|
||||||
|
|
||||||
|
| 参数名 | 类型 | 必填 | 默认值 | 说明 |
|
||||||
|
|--------|------|------|--------|------|
|
||||||
|
| statType | string | 否 | 空 | 统计类型筛选 |
|
||||||
|
| periodType | string | 否 | DAY | 统计周期:DAY/WEEK/MONTH |
|
||||||
|
| startTime | string | 否 | 自动计算 | 开始时间(ISO格式) |
|
||||||
|
| endTime | string | 否 | 自动计算 | 结束时间(ISO格式) |
|
||||||
|
|
||||||
|
**请求示例**:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. 使用周期类型查询今日统计
|
||||||
|
GET /api/datacount/summary?periodType=DAY
|
||||||
|
|
||||||
|
# 2. 使用周期类型查询本周统计
|
||||||
|
GET /api/datacount/summary?periodType=WEEK
|
||||||
|
|
||||||
|
# 3. 使用周期类型查询本月统计
|
||||||
|
GET /api/datacount/summary?periodType=MONTH
|
||||||
|
|
||||||
|
# 4. 使用自定义时间范围查询
|
||||||
|
GET /api/datacount/summary?startTime=2026-06-01T00:00:00&endTime=2026-06-07T23:59:59
|
||||||
|
|
||||||
|
# 5. 带统计类型筛选
|
||||||
|
GET /api/datacount/summary?statType=member&periodType=WEEK
|
||||||
|
```
|
||||||
|
|
||||||
|
**成功响应** (200 OK):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"statDate": "2026-06-09",
|
||||||
|
"generatedAt": "2026-06-09T10:30:00",
|
||||||
|
"memberStatistics": {
|
||||||
|
"statDate": "2026-06-09",
|
||||||
|
"newMembers": 5,
|
||||||
|
"activeMembers": 120,
|
||||||
|
"totalMembers": 500,
|
||||||
|
"signInMembers": 85,
|
||||||
|
"bookingMembers": 45,
|
||||||
|
"cancelMembers": 5
|
||||||
|
},
|
||||||
|
"bookingStatistics": {
|
||||||
|
"statDate": "2026-06-09",
|
||||||
|
"totalBookings": 60,
|
||||||
|
"cancelBookings": 10,
|
||||||
|
"attendBookings": 45,
|
||||||
|
"absentBookings": 5,
|
||||||
|
"attendRate": 75.0,
|
||||||
|
"cancelRate": 16.67
|
||||||
|
},
|
||||||
|
"signInStatistics": {
|
||||||
|
"statDate": "2026-06-09",
|
||||||
|
"totalSignIns": 95,
|
||||||
|
"successSignIns": 92,
|
||||||
|
"failSignIns": 3,
|
||||||
|
"successRate": 96.84,
|
||||||
|
"signInTypeDistribution": {
|
||||||
|
"QR_CODE": 60,
|
||||||
|
"MANUAL": 25,
|
||||||
|
"FACE": 10
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 获取会员统计数据
|
||||||
|
|
||||||
|
| 属性 | 值 |
|
||||||
|
|------|-----|
|
||||||
|
| **HTTP方法** | GET |
|
||||||
|
| **接口路径** | `/api/datacount/member` |
|
||||||
|
| **所属文件** | `DataStatisticsHandler.java` |
|
||||||
|
|
||||||
|
**请求参数**:
|
||||||
|
|
||||||
|
| 参数名 | 类型 | 必填 | 默认值 | 说明 |
|
||||||
|
|--------|------|------|--------|------|
|
||||||
|
| periodType | string | 否 | DAY | 统计周期:DAY/WEEK/MONTH |
|
||||||
|
| startTime | string | 否 | 自动计算 | 开始时间 |
|
||||||
|
| endTime | string | 否 | 自动计算 | 结束时间 |
|
||||||
|
|
||||||
|
**请求示例**:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. 查询今日会员统计
|
||||||
|
GET /api/datacount/member
|
||||||
|
|
||||||
|
# 2. 查询本周会员统计
|
||||||
|
GET /api/datacount/member?periodType=WEEK
|
||||||
|
|
||||||
|
# 3. 查询指定时间范围的会员统计
|
||||||
|
GET /api/datacount/member?startTime=2026-06-01T00:00:00&endTime=2026-06-30T23:59:59
|
||||||
|
```
|
||||||
|
|
||||||
|
**成功响应** (200 OK):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"statDate": "2026-06-09",
|
||||||
|
"newMembers": 5,
|
||||||
|
"activeMembers": 120,
|
||||||
|
"totalMembers": 500,
|
||||||
|
"signInMembers": 85,
|
||||||
|
"bookingMembers": 45,
|
||||||
|
"cancelMembers": 5
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 获取预约统计数据
|
||||||
|
|
||||||
|
| 属性 | 值 |
|
||||||
|
|------|-----|
|
||||||
|
| **HTTP方法** | GET |
|
||||||
|
| **接口路径** | `/api/datacount/booking` |
|
||||||
|
| **所属文件** | `DataStatisticsHandler.java` |
|
||||||
|
|
||||||
|
**请求参数**:
|
||||||
|
|
||||||
|
| 参数名 | 类型 | 必填 | 默认值 | 说明 |
|
||||||
|
|--------|------|------|--------|------|
|
||||||
|
| periodType | string | 否 | DAY | 统计周期:DAY/WEEK/MONTH |
|
||||||
|
| startTime | string | 否 | 自动计算 | 开始时间 |
|
||||||
|
| endTime | string | 否 | 自动计算 | 结束时间 |
|
||||||
|
|
||||||
|
**请求示例**:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. 查询今日预约统计
|
||||||
|
GET /api/datacount/booking
|
||||||
|
|
||||||
|
# 2. 查询本月预约统计
|
||||||
|
GET /api/datacount/booking?periodType=MONTH
|
||||||
|
|
||||||
|
# 3. 查询指定日期范围的预约统计
|
||||||
|
GET /api/datacount/booking?startTime=2026-06-01T00:00:00&endTime=2026-06-15T23:59:59
|
||||||
|
```
|
||||||
|
|
||||||
|
**成功响应** (200 OK):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"statDate": "2026-06-09",
|
||||||
|
"totalBookings": 60,
|
||||||
|
"cancelBookings": 10,
|
||||||
|
"attendBookings": 45,
|
||||||
|
"absentBookings": 5,
|
||||||
|
"attendRate": 75.0,
|
||||||
|
"cancelRate": 16.67
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 获取签到统计数据
|
||||||
|
|
||||||
|
| 属性 | 值 |
|
||||||
|
|------|-----|
|
||||||
|
| **HTTP方法** | GET |
|
||||||
|
| **接口路径** | `/api/datacount/signin` |
|
||||||
|
| **所属文件** | `DataStatisticsHandler.java` |
|
||||||
|
|
||||||
|
**请求参数**:
|
||||||
|
|
||||||
|
| 参数名 | 类型 | 必填 | 默认值 | 说明 |
|
||||||
|
|--------|------|------|--------|------|
|
||||||
|
| periodType | string | 否 | DAY | 统计周期:DAY/WEEK/MONTH |
|
||||||
|
| startTime | string | 否 | 自动计算 | 开始时间 |
|
||||||
|
| endTime | string | 否 | 自动计算 | 结束时间 |
|
||||||
|
|
||||||
|
**请求示例**:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. 查询今日签到统计
|
||||||
|
GET /api/datacount/signin
|
||||||
|
|
||||||
|
# 2. 查询本周签到统计
|
||||||
|
GET /api/datacount/signin?periodType=WEEK
|
||||||
|
|
||||||
|
# 3. 查询指定日期范围的签到统计
|
||||||
|
GET /api/datacount/signin?startTime=2026-06-01T00:00:00&endTime=2026-06-30T23:59:59
|
||||||
|
```
|
||||||
|
|
||||||
|
**成功响应** (200 OK):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"statDate": "2026-06-09",
|
||||||
|
"totalSignIns": 95,
|
||||||
|
"successSignIns": 92,
|
||||||
|
"failSignIns": 3,
|
||||||
|
"successRate": 96.84,
|
||||||
|
"signInTypeDistribution": {
|
||||||
|
"QR_CODE": 60,
|
||||||
|
"MANUAL": 25,
|
||||||
|
"FACE": 10
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 查询历史统计数据
|
||||||
|
|
||||||
|
| 属性 | 值 |
|
||||||
|
|------|-----|
|
||||||
|
| **HTTP方法** | GET |
|
||||||
|
| **接口路径** | `/api/datacount/history` |
|
||||||
|
| **所属文件** | `DataStatisticsHandler.java` |
|
||||||
|
|
||||||
|
**请求参数**:
|
||||||
|
|
||||||
|
| 参数名 | 类型 | 必填 | 默认值 | 说明 |
|
||||||
|
|--------|------|------|--------|------|
|
||||||
|
| statType | string | 否 | 空 | 统计类型:member/booking/signin |
|
||||||
|
| startTime | string | 是 | - | 开始日期(格式:yyyy-MM-dd) |
|
||||||
|
| endTime | string | 是 | - | 结束日期(格式:yyyy-MM-dd) |
|
||||||
|
|
||||||
|
**请求示例**:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. 查询指定日期范围的签到历史统计
|
||||||
|
GET /api/datacount/history?statType=signin&startTime=2026-06-01&endTime=2026-06-30
|
||||||
|
|
||||||
|
# 2. 查询指定日期范围的会员历史统计
|
||||||
|
GET /api/datacount/history?statType=member&startTime=2026-06-01&endTime=2026-06-15
|
||||||
|
|
||||||
|
# 3. 查询指定日期范围的预约历史统计
|
||||||
|
GET /api/datacount/history?statType=booking&startTime=2026-06-01&endTime=2026-06-30
|
||||||
|
|
||||||
|
# 4. 查询所有类型的历史统计(不指定statType)
|
||||||
|
GET /api/datacount/history?startTime=2026-06-01&endTime=2026-06-07
|
||||||
|
```
|
||||||
|
|
||||||
|
**成功响应** (200 OK):
|
||||||
|
|
||||||
|
```json
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"statDate": "2026-06-07",
|
||||||
|
"totalSignIns": 88,
|
||||||
|
"successSignIns": 86,
|
||||||
|
"failSignIns": 2,
|
||||||
|
"successRate": 97.73,
|
||||||
|
"signInTypeDistribution": {
|
||||||
|
"QR_CODE": 55,
|
||||||
|
"MANUAL": 23,
|
||||||
|
"FACE": 10
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"statDate": "2026-06-08",
|
||||||
|
"totalSignIns": 92,
|
||||||
|
"successSignIns": 90,
|
||||||
|
"failSignIns": 2,
|
||||||
|
"successRate": 97.83,
|
||||||
|
"signInTypeDistribution": {
|
||||||
|
"QR_CODE": 58,
|
||||||
|
"MANUAL": 24,
|
||||||
|
"FACE": 10
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 导出统计数据
|
||||||
|
|
||||||
|
| 属性 | 值 |
|
||||||
|
|------|-----|
|
||||||
|
| **HTTP方法** | GET |
|
||||||
|
| **接口路径** | `/api/datacount/export` |
|
||||||
|
| **所属文件** | `DataStatisticsHandler.java` |
|
||||||
|
|
||||||
|
**请求参数**:
|
||||||
|
|
||||||
|
| 参数名 | 类型 | 必填 | 默认值 | 说明 |
|
||||||
|
|--------|------|------|--------|------|
|
||||||
|
| periodType | string | 否 | DAY | 统计周期:DAY/WEEK/MONTH |
|
||||||
|
| startTime | string | 否 | 自动计算 | 开始时间 |
|
||||||
|
| endTime | string | 否 | 自动计算 | 结束时间 |
|
||||||
|
|
||||||
|
**请求示例**:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. 导出今日统计数据
|
||||||
|
GET /api/datacount/export
|
||||||
|
|
||||||
|
# 2. 导出本周统计数据
|
||||||
|
GET /api/datacount/export?periodType=WEEK
|
||||||
|
|
||||||
|
# 3. 导出本月统计数据
|
||||||
|
GET /api/datacount/export?periodType=MONTH
|
||||||
|
|
||||||
|
# 4. 导出指定时间范围的统计数据
|
||||||
|
GET /api/datacount/export?startTime=2026-06-01T00:00:00&endTime=2026-06-30T23:59:59
|
||||||
|
```
|
||||||
|
|
||||||
|
**成功响应** (200 OK):
|
||||||
|
|
||||||
|
返回 Excel 文件(.xlsx),包含以下 Sheet:
|
||||||
|
- **会员统计**: 会员相关统计数据
|
||||||
|
- **预约统计**: 预约相关统计数据
|
||||||
|
- **签到统计**: 签到相关统计数据
|
||||||
|
|
||||||
|
**Content-Type**: `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 数据模型
|
||||||
|
|
||||||
|
### StatisticsQuery(查询条件)
|
||||||
|
|
||||||
|
| 字段名 | 类型 | 说明 |
|
||||||
|
|--------|------|------|
|
||||||
|
| statType | String | 统计类型筛选 |
|
||||||
|
| periodType | String | 统计周期:DAY/WEEK/MONTH |
|
||||||
|
| startTime | LocalDateTime | 开始时间 |
|
||||||
|
| endTime | LocalDateTime | 结束时间 |
|
||||||
|
|
||||||
|
### StatisticsSummary(统计汇总)
|
||||||
|
|
||||||
|
| 字段名 | 类型 | 说明 |
|
||||||
|
|--------|------|------|
|
||||||
|
| statDate | String | 统计日期 |
|
||||||
|
| generatedAt | String | 生成时间 |
|
||||||
|
| memberStatistics | MemberStatistics | 会员统计数据 |
|
||||||
|
| bookingStatistics | BookingStatistics | 预约统计数据 |
|
||||||
|
| signInStatistics | SignInStatistics | 签到统计数据 |
|
||||||
|
|
||||||
|
### MemberStatistics(会员统计)
|
||||||
|
|
||||||
|
| 字段名 | 类型 | 说明 |
|
||||||
|
|--------|------|------|
|
||||||
|
| statDate | String | 统计日期 |
|
||||||
|
| newMembers | Long | 新增会员数 |
|
||||||
|
| activeMembers | Long | 活跃会员数 |
|
||||||
|
| totalMembers | Long | 累计会员总数 |
|
||||||
|
| signInMembers | Long | 签到会员数 |
|
||||||
|
| bookingMembers | Long | 预约会员数 |
|
||||||
|
| cancelMembers | Long | 取消预约会员数 |
|
||||||
|
|
||||||
|
### BookingStatistics(预约统计)
|
||||||
|
|
||||||
|
| 字段名 | 类型 | 说明 |
|
||||||
|
|--------|------|------|
|
||||||
|
| statDate | String | 统计日期 |
|
||||||
|
| totalBookings | Long | 预约总数 |
|
||||||
|
| cancelBookings | Long | 取消预约数 |
|
||||||
|
| attendBookings | Long | 出席预约数 |
|
||||||
|
| absentBookings | Long | 缺席预约数 |
|
||||||
|
| attendRate | Double | 出席率(%) |
|
||||||
|
| cancelRate | Double | 取消率(%) |
|
||||||
|
|
||||||
|
### SignInStatistics(签到统计)
|
||||||
|
|
||||||
|
| 字段名 | 类型 | 说明 |
|
||||||
|
|--------|------|------|
|
||||||
|
| statDate | String | 统计日期 |
|
||||||
|
| totalSignIns | Long | 签到总次数 |
|
||||||
|
| successSignIns | Long | 成功签到次数 |
|
||||||
|
| failSignIns | Long | 失败签到次数 |
|
||||||
|
| successRate | Double | 签到成功率(%) |
|
||||||
|
| signInTypeDistribution | Map<String, Long> | 签到类型分布 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 状态码说明
|
||||||
|
|
||||||
|
| 状态码 | 说明 |
|
||||||
|
|--------|------|
|
||||||
|
| 200 | 请求成功 |
|
||||||
|
| 400 | 请求参数错误 |
|
||||||
|
| 500 | 服务器内部错误 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 业务规则
|
||||||
|
|
||||||
|
1. **统计周期**: 支持按日、周、月统计
|
||||||
|
- DAY: 当天 00:00:00 - 当前时间
|
||||||
|
- WEEK: 本周一 00:00:00 - 本周日 23:59:59
|
||||||
|
- MONTH: 本月1日 00:00:00 - 本月最后一天 23:59:59
|
||||||
|
|
||||||
|
2. **数据保留**: 统计数据缓存30天,业务记录永久保存
|
||||||
|
|
||||||
|
3. **缓存策略**: 查询结果缓存1小时,统计数据缓存30天
|
||||||
|
|
||||||
|
4. **定时任务**:
|
||||||
|
- 每日凌晨2点执行前一天的日统计
|
||||||
|
- 每周一凌晨3点执行上周的周统计
|
||||||
|
- 每月1日凌晨3点执行上月的月统计
|
||||||
|
- 每月15日凌晨4点清理30天前的旧数据
|
||||||
|
|
||||||
|
5. **数据导出**: 支持Excel格式导出,包含会员、预约、签到三个Sheet
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,530 @@
|
|||||||
|
# 团课推荐模块 API 文档
|
||||||
|
|
||||||
|
> **文档版本**: v1.0
|
||||||
|
> **创建日期**: 2026-06-15
|
||||||
|
> **作者**: 张翔
|
||||||
|
> **状态**: 正式发布
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📋 目录
|
||||||
|
|
||||||
|
1. [概述](#概述)
|
||||||
|
2. [基础路径](#基础路径)
|
||||||
|
3. [团课推荐管理接口](#团课推荐管理接口)
|
||||||
|
- [获取所有团课推荐](#获取所有团课推荐)
|
||||||
|
- [获取所有启用的团课推荐](#获取所有启用的团课推荐)
|
||||||
|
- [根据ID获取团课推荐](#根据ID获取团课推荐)
|
||||||
|
- [根据团课ID获取推荐](#根据团课ID获取推荐)
|
||||||
|
- [创建团课推荐](#创建团课推荐)
|
||||||
|
- [更新团课推荐](#更新团课推荐)
|
||||||
|
- [删除团课推荐](#删除团课推荐)
|
||||||
|
- [启用团课推荐](#启用团课推荐)
|
||||||
|
- [禁用团课推荐](#禁用团课推荐)
|
||||||
|
4. [数据模型](#数据模型)
|
||||||
|
- [GroupCourseRecommend(团课推荐)](#GroupCourseRecommend团课推荐)
|
||||||
|
5. [状态码说明](#状态码说明)
|
||||||
|
6. [业务规则](#业务规则)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 概述
|
||||||
|
|
||||||
|
团课推荐模块提供团课推荐信息的创建、编辑、查询、删除和状态管理功能。推荐信息包含团课ID、推荐标题、推荐内容、推荐理由、优先级等必要信息,支持按优先级排序展示。
|
||||||
|
|
||||||
|
## 基础路径
|
||||||
|
|
||||||
|
所有接口的基础路径为: `http://{host}:{port}/api/groupCourse/recommend`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 团课推荐管理接口
|
||||||
|
|
||||||
|
### 获取所有团课推荐
|
||||||
|
|
||||||
|
| 属性 | 值 |
|
||||||
|
|------|-----|
|
||||||
|
| **HTTP方法** | GET |
|
||||||
|
| **接口路径** | `/api/groupCourse/recommend/list` |
|
||||||
|
| **所属文件** | `GroupCourseRecommendHandler.java` |
|
||||||
|
|
||||||
|
**请求参数**:
|
||||||
|
|
||||||
|
| 参数名 | 类型 | 必填 | 默认值 | 说明 |
|
||||||
|
|--------|------|------|--------|------|
|
||||||
|
| sortBy | string | 否 | priority | 排序字段(支持:priority、createdAt、updatedAt) |
|
||||||
|
| sortOrder | string | 否 | desc | 排序方式(asc-升序,desc-降序) |
|
||||||
|
|
||||||
|
**成功响应** (200 OK):
|
||||||
|
|
||||||
|
```json
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"id": 1,
|
||||||
|
"courseId": 1,
|
||||||
|
"recommendTitle": "本周热门课程",
|
||||||
|
"recommendContent": "这是一门非常棒的课程,快来参加吧!",
|
||||||
|
"recommendReason": "教练专业,课程内容丰富",
|
||||||
|
"priority": 10,
|
||||||
|
"isActive": true,
|
||||||
|
"groupCourse": {
|
||||||
|
"id": 1,
|
||||||
|
"courseName": "瑜伽入门",
|
||||||
|
"coachId": 1,
|
||||||
|
"courseType": 1,
|
||||||
|
"startTime": "2026-06-15T09:00:00",
|
||||||
|
"endTime": "2026-06-15T10:00:00",
|
||||||
|
"maxMembers": 20,
|
||||||
|
"currentMembers": 15,
|
||||||
|
"status": 0,
|
||||||
|
"location": "健身房A区",
|
||||||
|
"coverImage": "https://example.com/yoga.jpg",
|
||||||
|
"description": "适合初学者的瑜伽课程"
|
||||||
|
},
|
||||||
|
"createdAt": "2026-06-15T10:00:00",
|
||||||
|
"updatedAt": "2026-06-15T10:00:00"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 获取所有启用的团课推荐
|
||||||
|
|
||||||
|
| 属性 | 值 |
|
||||||
|
|------|-----|
|
||||||
|
| **HTTP方法** | GET |
|
||||||
|
| **接口路径** | `/api/groupCourse/recommend/active` |
|
||||||
|
| **所属文件** | `GroupCourseRecommendHandler.java` |
|
||||||
|
|
||||||
|
**功能说明**: 获取系统中所有已启用的团课推荐列表,按优先级从高到低排序。
|
||||||
|
|
||||||
|
**成功响应** (200 OK):
|
||||||
|
|
||||||
|
```json
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"id": 2,
|
||||||
|
"courseId": 3,
|
||||||
|
"recommendTitle": "新学员推荐",
|
||||||
|
"recommendContent": "专为新学员设计的入门课程,轻松上手",
|
||||||
|
"recommendReason": "零基础友好,教练耐心指导",
|
||||||
|
"priority": 20,
|
||||||
|
"isActive": true,
|
||||||
|
"groupCourse": {
|
||||||
|
"id": 3,
|
||||||
|
"courseName": "基础有氧",
|
||||||
|
"coachId": 2,
|
||||||
|
"courseType": 2,
|
||||||
|
"startTime": "2026-06-16T18:00:00",
|
||||||
|
"endTime": "2026-06-16T19:00:00",
|
||||||
|
"maxMembers": 30,
|
||||||
|
"currentMembers": 8,
|
||||||
|
"status": 0,
|
||||||
|
"location": "健身房B区",
|
||||||
|
"coverImage": "https://example.com/aerobic.jpg",
|
||||||
|
"description": "适合所有健身水平的有氧课程"
|
||||||
|
},
|
||||||
|
"createdAt": "2026-06-15T11:00:00",
|
||||||
|
"updatedAt": "2026-06-15T11:00:00"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 根据ID获取团课推荐
|
||||||
|
|
||||||
|
| 属性 | 值 |
|
||||||
|
|------|-----|
|
||||||
|
| **HTTP方法** | GET |
|
||||||
|
| **接口路径** | `/api/groupCourse/recommend/{id}` |
|
||||||
|
| **所属文件** | `GroupCourseRecommendHandler.java` |
|
||||||
|
|
||||||
|
**路径参数**:
|
||||||
|
|
||||||
|
| 参数名 | 类型 | 必填 | 说明 |
|
||||||
|
|--------|------|------|------|
|
||||||
|
| id | Long | 是 | 团课推荐ID |
|
||||||
|
|
||||||
|
**成功响应** (200 OK):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"id": 1,
|
||||||
|
"courseId": 1,
|
||||||
|
"recommendTitle": "本周热门课程",
|
||||||
|
"recommendContent": "这是一门非常棒的课程,快来参加吧!",
|
||||||
|
"recommendReason": "教练专业,课程内容丰富",
|
||||||
|
"priority": 10,
|
||||||
|
"isActive": true,
|
||||||
|
"groupCourse": {
|
||||||
|
"id": 1,
|
||||||
|
"courseName": "瑜伽入门",
|
||||||
|
"coachId": 1,
|
||||||
|
"courseType": 1,
|
||||||
|
"startTime": "2026-06-15T09:00:00",
|
||||||
|
"endTime": "2026-06-15T10:00:00",
|
||||||
|
"maxMembers": 20,
|
||||||
|
"currentMembers": 15,
|
||||||
|
"status": 0,
|
||||||
|
"location": "健身房A区",
|
||||||
|
"coverImage": "https://example.com/yoga.jpg",
|
||||||
|
"description": "适合初学者的瑜伽课程"
|
||||||
|
},
|
||||||
|
"createdAt": "2026-06-15T10:00:00",
|
||||||
|
"updatedAt": "2026-06-15T10:00:00"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**失败响应** (404 Not Found):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 根据团课ID获取推荐
|
||||||
|
|
||||||
|
| 属性 | 值 |
|
||||||
|
|------|-----|
|
||||||
|
| **HTTP方法** | GET |
|
||||||
|
| **接口路径** | `/api/groupCourse/recommend/course/{courseId}` |
|
||||||
|
| **所属文件** | `GroupCourseRecommendHandler.java` |
|
||||||
|
|
||||||
|
**路径参数**:
|
||||||
|
|
||||||
|
| 参数名 | 类型 | 必填 | 说明 |
|
||||||
|
|--------|------|------|------|
|
||||||
|
| courseId | Long | 是 | 团课ID |
|
||||||
|
|
||||||
|
**成功响应** (200 OK):
|
||||||
|
|
||||||
|
```json
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"id": 1,
|
||||||
|
"courseId": 1,
|
||||||
|
"recommendTitle": "本周热门课程",
|
||||||
|
"recommendContent": "这是一门非常棒的课程,快来参加吧!",
|
||||||
|
"recommendReason": "教练专业,课程内容丰富",
|
||||||
|
"priority": 10,
|
||||||
|
"isActive": true,
|
||||||
|
"groupCourse": {
|
||||||
|
"id": 1,
|
||||||
|
"courseName": "瑜伽入门",
|
||||||
|
"coachId": 1,
|
||||||
|
"courseType": 1,
|
||||||
|
"startTime": "2026-06-15T09:00:00",
|
||||||
|
"endTime": "2026-06-15T10:00:00",
|
||||||
|
"maxMembers": 20,
|
||||||
|
"currentMembers": 15,
|
||||||
|
"status": 0,
|
||||||
|
"location": "健身房A区"
|
||||||
|
},
|
||||||
|
"createdAt": "2026-06-15T10:00:00",
|
||||||
|
"updatedAt": "2026-06-15T10:00:00"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 创建团课推荐
|
||||||
|
|
||||||
|
| 属性 | 值 |
|
||||||
|
|------|-----|
|
||||||
|
| **HTTP方法** | POST |
|
||||||
|
| **接口路径** | `/api/groupCourse/recommend` |
|
||||||
|
| **所属文件** | `GroupCourseRecommendHandler.java` |
|
||||||
|
|
||||||
|
**请求体**:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"courseId": 1,
|
||||||
|
"recommendTitle": "本周热门课程",
|
||||||
|
"recommendContent": "这是一门非常棒的课程,快来参加吧!",
|
||||||
|
"recommendReason": "教练专业,课程内容丰富",
|
||||||
|
"priority": 10,
|
||||||
|
"isActive": true
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
| 参数名 | 类型 | 必填 | 默认值 | 说明 |
|
||||||
|
|--------|------|------|--------|------|
|
||||||
|
| courseId | Long | **是** | - | 团课ID(必须是有效的团课) |
|
||||||
|
| recommendTitle | String | 否 | - | 推荐标题 |
|
||||||
|
| recommendContent | String | 否 | - | 推荐内容 |
|
||||||
|
| recommendReason | String | 否 | - | 推荐理由 |
|
||||||
|
| priority | Integer | 否 | 0 | 优先级(数字越大优先级越高) |
|
||||||
|
| isActive | Boolean | 否 | true | 是否启用 |
|
||||||
|
|
||||||
|
**成功响应** (200 OK):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": true,
|
||||||
|
"message": "团课推荐创建成功",
|
||||||
|
"data": {
|
||||||
|
"id": 1,
|
||||||
|
"courseId": 1,
|
||||||
|
"recommendTitle": "本周热门课程",
|
||||||
|
"recommendContent": "这是一门非常棒的课程,快来参加吧!",
|
||||||
|
"recommendReason": "教练专业,课程内容丰富",
|
||||||
|
"priority": 10,
|
||||||
|
"isActive": true,
|
||||||
|
"createdAt": "2026-06-15T10:00:00",
|
||||||
|
"updatedAt": "2026-06-15T10:00:00"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**失败响应** (400 Bad Request):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": false,
|
||||||
|
"message": "团课ID不能为空"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 更新团课推荐
|
||||||
|
|
||||||
|
| 属性 | 值 |
|
||||||
|
|------|-----|
|
||||||
|
| **HTTP方法** | PUT |
|
||||||
|
| **接口路径** | `/api/groupCourse/recommend/{id}` |
|
||||||
|
| **所属文件** | `GroupCourseRecommendHandler.java` |
|
||||||
|
|
||||||
|
**路径参数**:
|
||||||
|
|
||||||
|
| 参数名 | 类型 | 必填 | 说明 |
|
||||||
|
|--------|------|------|------|
|
||||||
|
| id | Long | 是 | 团课推荐ID |
|
||||||
|
|
||||||
|
**请求体**:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"recommendTitle": "本周热门课程(更新)",
|
||||||
|
"recommendContent": "更新后的推荐内容",
|
||||||
|
"recommendReason": "更新后的推荐理由",
|
||||||
|
"priority": 15,
|
||||||
|
"isActive": true
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
| 参数名 | 类型 | 必填 | 说明 |
|
||||||
|
|--------|------|------|------|
|
||||||
|
| courseId | Long | 否 | 团课ID |
|
||||||
|
| recommendTitle | String | 否 | 推荐标题 |
|
||||||
|
| recommendContent | String | 否 | 推荐内容 |
|
||||||
|
| recommendReason | String | 否 | 推荐理由 |
|
||||||
|
| priority | Integer | 否 | 优先级 |
|
||||||
|
| isActive | Boolean | 否 | 是否启用 |
|
||||||
|
|
||||||
|
**成功响应** (200 OK):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": true,
|
||||||
|
"message": "团课推荐更新成功",
|
||||||
|
"data": {
|
||||||
|
"id": 1,
|
||||||
|
"courseId": 1,
|
||||||
|
"recommendTitle": "本周热门课程(更新)",
|
||||||
|
"recommendContent": "更新后的推荐内容",
|
||||||
|
"recommendReason": "更新后的推荐理由",
|
||||||
|
"priority": 15,
|
||||||
|
"isActive": true,
|
||||||
|
"updatedAt": "2026-06-15T12:00:00"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**失败响应** (400 Bad Request):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": false,
|
||||||
|
"message": "团课推荐不存在"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 删除团课推荐
|
||||||
|
|
||||||
|
| 属性 | 值 |
|
||||||
|
|------|-----|
|
||||||
|
| **HTTP方法** | DELETE |
|
||||||
|
| **接口路径** | `/api/groupCourse/recommend/{id}` |
|
||||||
|
| **所属文件** | `GroupCourseRecommendHandler.java` |
|
||||||
|
|
||||||
|
**路径参数**:
|
||||||
|
|
||||||
|
| 参数名 | 类型 | 必填 | 说明 |
|
||||||
|
|--------|------|------|------|
|
||||||
|
| id | Long | 是 | 团课推荐ID |
|
||||||
|
|
||||||
|
**成功响应** (200 OK):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": true,
|
||||||
|
"message": "团课推荐删除成功"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**失败响应** (400 Bad Request):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": false,
|
||||||
|
"message": "团课推荐不存在"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 启用团课推荐
|
||||||
|
|
||||||
|
| 属性 | 值 |
|
||||||
|
|------|-----|
|
||||||
|
| **HTTP方法** | POST |
|
||||||
|
| **接口路径** | `/api/groupCourse/recommend/{id}/enable` |
|
||||||
|
| **所属文件** | `GroupCourseRecommendHandler.java` |
|
||||||
|
|
||||||
|
**路径参数**:
|
||||||
|
|
||||||
|
| 参数名 | 类型 | 必填 | 说明 |
|
||||||
|
|--------|------|------|------|
|
||||||
|
| id | Long | 是 | 团课推荐ID |
|
||||||
|
|
||||||
|
**成功响应** (200 OK):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": true,
|
||||||
|
"message": "团课推荐启用成功",
|
||||||
|
"data": {
|
||||||
|
"id": 1,
|
||||||
|
"courseId": 1,
|
||||||
|
"recommendTitle": "本周热门课程",
|
||||||
|
"isActive": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**失败响应** (400 Bad Request):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": false,
|
||||||
|
"message": "团课推荐不存在"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 禁用团课推荐
|
||||||
|
|
||||||
|
| 属性 | 值 |
|
||||||
|
|------|-----|
|
||||||
|
| **HTTP方法** | POST |
|
||||||
|
| **接口路径** | `/api/groupCourse/recommend/{id}/disable` |
|
||||||
|
| **所属文件** | `GroupCourseRecommendHandler.java` |
|
||||||
|
|
||||||
|
**路径参数**:
|
||||||
|
|
||||||
|
| 参数名 | 类型 | 必填 | 说明 |
|
||||||
|
|--------|------|------|------|
|
||||||
|
| id | Long | 是 | 团课推荐ID |
|
||||||
|
|
||||||
|
**成功响应** (200 OK):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": true,
|
||||||
|
"message": "团课推荐禁用成功",
|
||||||
|
"data": {
|
||||||
|
"id": 1,
|
||||||
|
"courseId": 1,
|
||||||
|
"recommendTitle": "本周热门课程",
|
||||||
|
"isActive": false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**失败响应** (400 Bad Request):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": false,
|
||||||
|
"message": "团课推荐不存在"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 数据模型
|
||||||
|
|
||||||
|
### GroupCourseRecommend(团课推荐)
|
||||||
|
|
||||||
|
| 字段名 | 类型 | 说明 |
|
||||||
|
|--------|------|------|
|
||||||
|
| id | Long | 主键ID |
|
||||||
|
| courseId | Long | 团课ID(关联group_course.id) |
|
||||||
|
| recommendTitle | String | 推荐标题 |
|
||||||
|
| recommendContent | String | 推荐内容 |
|
||||||
|
| recommendReason | String | 推荐理由 |
|
||||||
|
| priority | Integer | 优先级(数字越大优先级越高),默认0 |
|
||||||
|
| isActive | Boolean | 是否启用,默认true |
|
||||||
|
| groupCourse | GroupCourse | 关联的团课信息(查询时自动填充) |
|
||||||
|
| createdBy | String | 创建人 |
|
||||||
|
| updatedBy | String | 更新人 |
|
||||||
|
| createdAt | LocalDateTime | 创建时间 |
|
||||||
|
| updatedAt | LocalDateTime | 更新时间 |
|
||||||
|
| deletedAt | LocalDateTime | 删除时间(软删除) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 状态码说明
|
||||||
|
|
||||||
|
### 推荐状态
|
||||||
|
|
||||||
|
| 状态值 | 含义 |
|
||||||
|
|--------|------|
|
||||||
|
| true | 启用 |
|
||||||
|
| false | 禁用 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 业务规则
|
||||||
|
|
||||||
|
### 团课推荐管理
|
||||||
|
1. **创建推荐**:团课ID为必填项,且必须是有效的团课
|
||||||
|
2. **优先级排序**:获取启用的推荐列表时,按优先级从高到低排序
|
||||||
|
3. **删除推荐**:采用软删除机制,数据保留可恢复
|
||||||
|
4. **状态管理**:支持启用/禁用推荐状态,禁用的推荐不会在推荐列表中显示
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 附录:错误响应格式
|
||||||
|
|
||||||
|
所有接口的错误响应统一格式:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": false,
|
||||||
|
"message": "错误描述信息"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
*文档结束*
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
一、基础有氧与热身(难度 1-3)
|
||||||
|
|
||||||
|
主要是低冲击、低技巧,用于建立运动基础。
|
||||||
|
|
||||||
|
慢走/椭圆机轻松模式:1(几乎无难度,适合所有人)
|
||||||
|
|
||||||
|
固定自行车(低阻力):2(注意座椅高度调节即可)
|
||||||
|
|
||||||
|
跑步机慢跑:3(需要基本协调性,膝盖有压力)
|
||||||
|
|
||||||
|
跳绳(连续基础跳):3(需要手脚配合,心肺要求明显)
|
||||||
|
|
||||||
|
二、固定器械训练(难度 2-5)
|
||||||
|
|
||||||
|
轨迹固定,主要考验力量和耐力,技巧要求低。
|
||||||
|
|
||||||
|
坐姿腿屈伸/腿弯举:2(很容易找到发力感)
|
||||||
|
|
||||||
|
坐姿推胸机:3(需注意肩胛后收,避免耸肩)
|
||||||
|
|
||||||
|
高位下拉(坐姿):3(需控制不要过度后仰)
|
||||||
|
|
||||||
|
史密斯机深蹲:4(轨迹固定,但需保持核心稳定)
|
||||||
|
|
||||||
|
蝴蝶机夹胸:3(易用肘关节代偿,需锁定肩关节)
|
||||||
|
|
||||||
|
三、自重基础动作(难度 3-7)
|
||||||
|
|
||||||
|
需要一定的力量-体重比和身体控制能力。
|
||||||
|
|
||||||
|
平板支撑:3(耐力考验,技巧低)
|
||||||
|
|
||||||
|
跪姿俯卧撑:3(上肢力量较弱者首选)
|
||||||
|
|
||||||
|
标准俯卧撑:5(需核心收紧,身体成直线)
|
||||||
|
|
||||||
|
引体向上(弹力带辅助):6(背部和手臂力量要求高)
|
||||||
|
|
||||||
|
标准引体向上:8(力量-体重比极高,多数男性无法完成1次)
|
||||||
|
|
||||||
|
徒手深蹲:3(注意膝盖方向与背部直立)
|
||||||
|
|
||||||
|
单腿深蹲(手枪蹲):8(需要极高下肢力量、柔韧性和平衡)
|
||||||
|
|
||||||
|
四、自由重量杠铃/哑铃(难度 5-9)
|
||||||
|
|
||||||
|
技巧风险最高,需要神经系统协调和长期动作打磨。
|
||||||
|
|
||||||
|
哑铃二头弯举:4(容易晃动借力,但较安全)
|
||||||
|
|
||||||
|
哑铃侧平举:5(极易用斜方肌代偿,真正练到三角肌中束很难)
|
||||||
|
|
||||||
|
杠铃卧推:7(肩关节压力大,起桥、沉肩、稳定手腕均有技巧,有压伤风险)
|
||||||
|
|
||||||
|
杠铃深蹲(颈后):8(全身协调性、核心抗压、杠位放置、呼吸模式,学习曲线陡峭)
|
||||||
|
|
||||||
|
传统硬拉:9(风险极高,需要精确的脊柱中立、髋铰链、背阔肌收紧,错误时伤腰)
|
||||||
|
|
||||||
|
高翻/抓举(奥运举重):10(需要爆发力、柔韧、精准衔接,非数月训练不能掌握)
|
||||||
|
|
||||||
|
五、高强度与爆发力(难度 6-10)
|
||||||
|
|
||||||
|
对心肺、神经系统和恢复能力要求极高。
|
||||||
|
|
||||||
|
波比跳(标准版):6(连续做时心肺压力极大)
|
||||||
|
|
||||||
|
冲刺跑(短跑):7(对腘绳肌和脚踝爆发力要求高)
|
||||||
|
|
||||||
|
跳箱(合理高度):6(需要落地缓冲技巧)
|
||||||
|
|
||||||
|
负重雪橇推:6(主要考验腿部耐力和意志力)
|
||||||
|
|
||||||
|
双力臂(引体向上后翻腕上杠):9(需要爆发引体 + 极高相对力量)
|
||||||
|
|
||||||
|
六、柔韧与平衡类(难度 3-8)
|
||||||
|
|
||||||
|
考验本体感觉和关节活动度。
|
||||||
|
|
||||||
|
静态拉伸(坐姿体前屈):2(无风险,但需要坚持)
|
||||||
|
|
||||||
|
瑜伽下犬式:3(常见,但需背部与手臂对齐)
|
||||||
|
|
||||||
|
单腿罗马尼亚硬拉(徒手):6(极考验平衡和髋稳定)
|
||||||
|
|
||||||
|
全深蹲(脚跟贴地,亚洲蹲):5(踝关节灵活度限制多数人)
|
||||||
|
|
||||||
|
竖叉/横叉:8(需要数月甚至数年拉伸)
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
<?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-auth</artifactId>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
|
<name>Gym Auth</name>
|
||||||
|
<description>Phone Authentication Module - Phone Number Login Services</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-member</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>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.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>
|
||||||
|
<dependency>
|
||||||
|
<groupId>cn.hutool</groupId>
|
||||||
|
<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>
|
||||||
|
<version>1.2.12</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.aliyun</groupId>
|
||||||
|
<artifactId>aliyun-java-sdk-core</artifactId>
|
||||||
|
<version>4.6.0</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.aliyun</groupId>
|
||||||
|
<artifactId>dysmsapi20170525</artifactId>
|
||||||
|
<version>2.0.0</version>
|
||||||
|
</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>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</project>
|
||||||
+7
@@ -0,0 +1,7 @@
|
|||||||
|
package cn.novalon.gym.manage.auth.config;
|
||||||
|
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
public class AuthConfig {
|
||||||
|
}
|
||||||
+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;
|
||||||
|
}
|
||||||
+47
@@ -0,0 +1,47 @@
|
|||||||
|
package cn.novalon.gym.manage.auth.config;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 阿里云短信配置属性类
|
||||||
|
*
|
||||||
|
* @author auto-generated
|
||||||
|
* @date 2026-06-20
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Configuration
|
||||||
|
@ConfigurationProperties(prefix = "alibaba.cloud.sms")
|
||||||
|
public class SmsProperties {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 访问密钥ID
|
||||||
|
*/
|
||||||
|
private String accessKeyId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 访问密钥密钥
|
||||||
|
*/
|
||||||
|
private String accessKeySecret;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 短信签名名称
|
||||||
|
*/
|
||||||
|
private String signName;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 短信模板CODE
|
||||||
|
*/
|
||||||
|
private String templateCode;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 短信验证码长度(默认6位)
|
||||||
|
*/
|
||||||
|
private int codeLength = 6;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 短信验证码有效期(秒,默认300秒=5分钟)
|
||||||
|
*/
|
||||||
|
private long codeExpireSeconds = 300;
|
||||||
|
}
|
||||||
+26
@@ -0,0 +1,26 @@
|
|||||||
|
package cn.novalon.gym.manage.auth.dto;
|
||||||
|
|
||||||
|
import jakarta.validation.constraints.NotBlank;
|
||||||
|
import jakarta.validation.constraints.Pattern;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 手机号验证码登录请求DTO
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class PhoneCodeLoginDto {
|
||||||
|
|
||||||
|
@NotBlank(message = "手机号不能为空")
|
||||||
|
@Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确")
|
||||||
|
private String phone;
|
||||||
|
|
||||||
|
@NotBlank(message = "验证码不能为空")
|
||||||
|
@Pattern(regexp = "^\\d{4,6}$", message = "验证码格式不正确")
|
||||||
|
private String code;
|
||||||
|
}
|
||||||
+23
@@ -0,0 +1,23 @@
|
|||||||
|
package cn.novalon.gym.manage.auth.dto;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class PhoneLoginDto {
|
||||||
|
|
||||||
|
private String phone;
|
||||||
|
|
||||||
|
private String accessToken;
|
||||||
|
|
||||||
|
private String openid;
|
||||||
|
|
||||||
|
private String nickname;
|
||||||
|
|
||||||
|
private String avatar;
|
||||||
|
}
|
||||||
+22
@@ -0,0 +1,22 @@
|
|||||||
|
package cn.novalon.gym.manage.auth.dto;
|
||||||
|
|
||||||
|
import jakarta.validation.constraints.NotBlank;
|
||||||
|
import jakarta.validation.constraints.Pattern;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 发送短信验证码请求DTO
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class SendCodeRequest {
|
||||||
|
|
||||||
|
@NotBlank(message = "手机号不能为空")
|
||||||
|
@Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确")
|
||||||
|
private String phone;
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package cn.novalon.gym.manage.auth.dto;
|
||||||
|
|
||||||
|
import jakarta.validation.constraints.NotBlank;
|
||||||
|
import jakarta.validation.constraints.Pattern;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 短信验证码登录请求DTO
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class SmsLoginDto {
|
||||||
|
|
||||||
|
@NotBlank(message = "手机号不能为空")
|
||||||
|
@Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确")
|
||||||
|
private String phone;
|
||||||
|
|
||||||
|
@NotBlank(message = "验证码不能为空")
|
||||||
|
private String code;
|
||||||
|
}
|
||||||
+59
@@ -0,0 +1,59 @@
|
|||||||
|
package cn.novalon.gym.manage.auth.handler;
|
||||||
|
|
||||||
|
import cn.novalon.gym.manage.auth.dto.PhoneCodeLoginDto;
|
||||||
|
import cn.novalon.gym.manage.auth.dto.PhoneLoginDto;
|
||||||
|
import cn.novalon.gym.manage.auth.dto.SendCodeRequest;
|
||||||
|
import cn.novalon.gym.manage.auth.service.PhoneAuthService;
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
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;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
@Tag(name = "手机号认证", description = "手机号一键登录与验证码登录")
|
||||||
|
public class PhoneAuthHandler {
|
||||||
|
|
||||||
|
private final PhoneAuthService phoneAuthService;
|
||||||
|
|
||||||
|
@Operation(summary = "手机号一键登录", description = "使用uniapp官方运营商认证,直接手机号登录或注册")
|
||||||
|
public Mono<ServerResponse> oneClickLogin(ServerRequest request) {
|
||||||
|
log.info("收到手机号一键登录请求");
|
||||||
|
|
||||||
|
return request.bodyToMono(PhoneLoginDto.class)
|
||||||
|
.flatMap(phoneAuthService::oneClickLogin)
|
||||||
|
.flatMap(response -> ServerResponse.ok()
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.bodyValue(response));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "发送短信验证码", description = "使用阿里云发送短信验证码")
|
||||||
|
public Mono<ServerResponse> sendSmsCode(ServerRequest request) {
|
||||||
|
log.info("收到发送短信验证码请求");
|
||||||
|
|
||||||
|
return request.bodyToMono(SendCodeRequest.class)
|
||||||
|
.flatMap(req -> phoneAuthService.sendSmsCode(req.getPhone()))
|
||||||
|
.flatMap(success -> ServerResponse.ok()
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.bodyValue(Map.of("success", success, "message", success ? "验证码发送成功" : "验证码发送失败")));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "手机号验证码登录", description = "使用阿里云短信验证码登录或注册")
|
||||||
|
public Mono<ServerResponse> codeLogin(ServerRequest request) {
|
||||||
|
log.info("收到手机号验证码登录请求");
|
||||||
|
|
||||||
|
return request.bodyToMono(PhoneCodeLoginDto.class)
|
||||||
|
.flatMap(phoneAuthService::codeLogin)
|
||||||
|
.flatMap(response -> ServerResponse.ok()
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.bodyValue(response));
|
||||||
|
}
|
||||||
|
}
|
||||||
+37
@@ -0,0 +1,37 @@
|
|||||||
|
package cn.novalon.gym.manage.auth.service;
|
||||||
|
|
||||||
|
import cn.novalon.gym.manage.auth.dto.PhoneLoginDto;
|
||||||
|
import cn.novalon.gym.manage.auth.dto.PhoneCodeLoginDto;
|
||||||
|
import cn.novalon.gym.manage.auth.vo.PhoneLoginVO;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 手机号认证服务接口
|
||||||
|
*/
|
||||||
|
public interface PhoneAuthService {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 手机号一键登录(uniapp官方运营商认证)
|
||||||
|
* 已注册则直接登录,未注册则自动注册后登录
|
||||||
|
*
|
||||||
|
* @param request 登录请求
|
||||||
|
* @return 登录响应
|
||||||
|
*/
|
||||||
|
Mono<PhoneLoginVO> oneClickLogin(PhoneLoginDto request);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 发送短信验证码(阿里云)
|
||||||
|
*
|
||||||
|
* @param phone 手机号
|
||||||
|
* @return 是否发送成功
|
||||||
|
*/
|
||||||
|
Mono<Boolean> sendSmsCode(String phone);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 手机号验证码登录(阿里云)
|
||||||
|
*
|
||||||
|
* @param request 登录请求
|
||||||
|
* @return 登录响应
|
||||||
|
*/
|
||||||
|
Mono<PhoneLoginVO> codeLogin(PhoneCodeLoginDto request);
|
||||||
|
}
|
||||||
+37
@@ -0,0 +1,37 @@
|
|||||||
|
package cn.novalon.gym.manage.auth.service;
|
||||||
|
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 短信服务接口
|
||||||
|
*
|
||||||
|
* @author auto-generated
|
||||||
|
* @date 2026-06-20
|
||||||
|
*/
|
||||||
|
public interface SmsService {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 发送短信验证码
|
||||||
|
*
|
||||||
|
* @param phone 手机号
|
||||||
|
* @return 发送结果
|
||||||
|
*/
|
||||||
|
Mono<Boolean> sendVerificationCode(String phone);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 验证短信验证码
|
||||||
|
*
|
||||||
|
* @param phone 手机号
|
||||||
|
* @param code 验证码
|
||||||
|
* @return 验证结果
|
||||||
|
*/
|
||||||
|
Mono<Boolean> verifyCode(String phone, String code);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取验证码(用于测试或特殊场景)
|
||||||
|
*
|
||||||
|
* @param phone 手机号
|
||||||
|
* @return 验证码
|
||||||
|
*/
|
||||||
|
Mono<String> getVerificationCode(String phone);
|
||||||
|
}
|
||||||
+270
@@ -0,0 +1,270 @@
|
|||||||
|
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;
|
||||||
|
import cn.novalon.gym.manage.auth.service.PhoneAuthService;
|
||||||
|
import cn.novalon.gym.manage.auth.service.SmsService;
|
||||||
|
import cn.novalon.gym.manage.auth.vo.PhoneLoginVO;
|
||||||
|
import cn.novalon.gym.manage.common.exception.ErrorCode;
|
||||||
|
import cn.novalon.gym.manage.common.exception.SystemException;
|
||||||
|
import cn.novalon.gym.manage.member.entity.Member;
|
||||||
|
import cn.novalon.gym.manage.member.es.entity.MemberES;
|
||||||
|
import cn.novalon.gym.manage.member.es.repository.MemberESRepository;
|
||||||
|
import cn.novalon.gym.manage.member.repository.IMemberRepository;
|
||||||
|
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 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
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class PhoneAuthServiceImpl implements PhoneAuthService {
|
||||||
|
|
||||||
|
private final IMemberRepository memberRepository;
|
||||||
|
private final MemberESRepository memberESRepository;
|
||||||
|
private final EsSyncUtils esSyncUtils;
|
||||||
|
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("手机号一键登录请求, phone: {}, accessToken: {}, openid: {}", request.getPhone(), 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 processPhoneLogin(encryptedPhone, request);
|
||||||
|
})
|
||||||
|
.onErrorResume(e -> {
|
||||||
|
log.error("一键登录失败", e);
|
||||||
|
return Mono.error(new SystemException(ErrorCode.AUTH_PHONE_ERROR, "手机号获取失败: " + e.getMessage()));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
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()));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 手机号脱敏显示
|
||||||
|
*/
|
||||||
|
private String maskPhone(String phone) {
|
||||||
|
if (phone == null || phone.length() < 11) {
|
||||||
|
return phone;
|
||||||
|
}
|
||||||
|
return phone.substring(0, 3) + "****" + phone.substring(7);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Mono<Boolean> sendSmsCode(String phone) {
|
||||||
|
log.info("发送短信验证码, phone: {}", phone);
|
||||||
|
return smsService.sendVerificationCode(phone);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Mono<PhoneLoginVO> codeLogin(PhoneCodeLoginDto request) {
|
||||||
|
log.info("手机号验证码登录, phone: {}", request.getPhone());
|
||||||
|
|
||||||
|
return smsService.verifyCode(request.getPhone(), request.getCode())
|
||||||
|
.flatMap(verified -> {
|
||||||
|
if (!verified) {
|
||||||
|
log.warn("验证码验证失败, phone: {}", request.getPhone());
|
||||||
|
return Mono.error(new SystemException(ErrorCode.SYSTEM_INTERNAL_ERROR, "验证码错误或已过期"));
|
||||||
|
}
|
||||||
|
|
||||||
|
String encryptedPhone = encryptPhone(request.getPhone());
|
||||||
|
|
||||||
|
return memberRepository.findByPhone(encryptedPhone)
|
||||||
|
.flatMap(existingMember -> {
|
||||||
|
log.info("手机号已注册,直接登录, memberId: {}", existingMember.getId());
|
||||||
|
return doLogin(existingMember, false, null);
|
||||||
|
})
|
||||||
|
.switchIfEmpty(Mono.defer(() -> {
|
||||||
|
log.info("手机号未注册,创建新会员");
|
||||||
|
PhoneLoginDto registerRequest = new PhoneLoginDto();
|
||||||
|
return createNewMemberAndLogin(registerRequest, encryptedPhone);
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private Mono<PhoneLoginVO> createNewMemberAndLogin(PhoneLoginDto request, String encryptedPhone) {
|
||||||
|
String memberNo = MemberNoGenerator.generate();
|
||||||
|
log.info("生成会员号: {}", memberNo);
|
||||||
|
|
||||||
|
Member member = new Member();
|
||||||
|
member.setMemberNo(memberNo);
|
||||||
|
member.setPhone(encryptedPhone);
|
||||||
|
member.setNickname(request != null ? request.getNickname() : null);
|
||||||
|
member.setAvatar(request != null ? request.getAvatar() : null);
|
||||||
|
member.setLastLoginAt(LocalDateTime.now());
|
||||||
|
member.setIsDeleted(false);
|
||||||
|
|
||||||
|
return memberRepository.save(member)
|
||||||
|
.doOnSuccess(memberSyncer::sync)
|
||||||
|
.flatMap(savedMember -> {
|
||||||
|
log.info("新会员创建成功, memberId: {}, memberNo: {}", savedMember.getId(), savedMember.getMemberNo());
|
||||||
|
return doLogin(savedMember, true, request);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private Mono<PhoneLoginVO> doLogin(Member member, boolean isNewUser, PhoneLoginDto request) {
|
||||||
|
log.info("登录成功, memberId: {}", member.getId());
|
||||||
|
|
||||||
|
member.setLastLoginAt(LocalDateTime.now());
|
||||||
|
|
||||||
|
if (isNewUser && request != null) {
|
||||||
|
if ((member.getNickname() == null || member.getNickname().isEmpty())
|
||||||
|
&& request.getNickname() != null && !request.getNickname().isEmpty()) {
|
||||||
|
member.setNickname(request.getNickname());
|
||||||
|
}
|
||||||
|
if ((member.getAvatar() == null || member.getAvatar().isEmpty())
|
||||||
|
&& request.getAvatar() != null && !request.getAvatar().isEmpty()) {
|
||||||
|
member.setAvatar(request.getAvatar());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return memberRepository.save(member)
|
||||||
|
.doOnSuccess(memberSyncer::sync)
|
||||||
|
.map(this::buildLoginResponse);
|
||||||
|
}
|
||||||
|
|
||||||
|
private PhoneLoginVO buildLoginResponse(Member member) {
|
||||||
|
boolean needCompleteInfo = member.getNickname() == null || member.getNickname().isEmpty();
|
||||||
|
|
||||||
|
List<String> roles = new ArrayList<>();
|
||||||
|
String accessToken = jwtTokenProvider.generateToken(String.valueOf(member.getId()), member.getId(), roles);
|
||||||
|
|
||||||
|
log.info("JWT Token 生成成功, memberId: {}", member.getId());
|
||||||
|
|
||||||
|
PhoneLoginVO vo = new PhoneLoginVO();
|
||||||
|
vo.setMemberId(member.getId());
|
||||||
|
vo.setMemberNo(member.getMemberNo());
|
||||||
|
vo.setAccessToken(accessToken);
|
||||||
|
vo.setRefreshToken(accessToken);
|
||||||
|
vo.setExpiresIn(86400);
|
||||||
|
vo.setIsNewUser(member.getCreatedAt() == null ? false :
|
||||||
|
member.getCreatedAt().isAfter(LocalDateTime.now().minusMinutes(1)));
|
||||||
|
vo.setNeedCompleteInfo(needCompleteInfo);
|
||||||
|
vo.setNickname(member.getNickname());
|
||||||
|
vo.setAvatar(member.getAvatar());
|
||||||
|
vo.setPhone(member.getPhone() != null ? decryptPhone(member.getPhone()) : null);
|
||||||
|
return vo;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String encryptPhone(String phoneNumber) {
|
||||||
|
try {
|
||||||
|
return AesUtil.encrypt(phoneNumber);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("手机号加密失败", e);
|
||||||
|
throw new SystemException(ErrorCode.SYSTEM_INTERNAL_ERROR, "手机号加密失败");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private String decryptPhone(String encryptedPhone) {
|
||||||
|
try {
|
||||||
|
return AesUtil.decrypt(encryptedPhone);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("手机号解密失败", e);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+198
@@ -0,0 +1,198 @@
|
|||||||
|
package cn.novalon.gym.manage.auth.service.impl;
|
||||||
|
|
||||||
|
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.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.LocalDateTime;
|
||||||
|
import java.time.ZoneOffset;
|
||||||
|
|
||||||
|
@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 Mono<Boolean> sendVerificationCode(String phone) {
|
||||||
|
log.info("发送短信验证码, phone: {}", phone);
|
||||||
|
|
||||||
|
String rateLimitKey = RedisKeyConstants.SMS_CODE + phone + ":rate_limit";
|
||||||
|
|
||||||
|
return redisUtil.get(rateLimitKey, Long.class)
|
||||||
|
.defaultIfEmpty(0L)
|
||||||
|
.flatMap(lastSendTime -> {
|
||||||
|
long currentTime = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC);
|
||||||
|
|
||||||
|
if (currentTime - lastSendTime < SEND_INTERVAL_SECONDS) {
|
||||||
|
long remainingSeconds = SEND_INTERVAL_SECONDS - (currentTime - lastSendTime);
|
||||||
|
log.warn("发送频率限制, phone: {}, 剩余时间: {}秒", phone, remainingSeconds);
|
||||||
|
return Mono.just(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Mono.fromCallable(() -> {
|
||||||
|
try {
|
||||||
|
IAcsClient client = createClient();
|
||||||
|
|
||||||
|
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");
|
||||||
|
|
||||||
|
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 Mono<Boolean> verifyCode(String phone, String code) {
|
||||||
|
log.info("验证短信验证码, phone: {}", phone);
|
||||||
|
|
||||||
|
return Mono.fromCallable(() -> {
|
||||||
|
try {
|
||||||
|
IAcsClient client = createClient();
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Mono<String> getVerificationCode(String phone) {
|
||||||
|
try {
|
||||||
|
String cacheKey = RedisKeyConstants.SMS_CODE + phone;
|
||||||
|
return redisUtil.get(cacheKey, String.class);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("获取验证码异常, phone: {}", phone, e);
|
||||||
|
return Mono.empty();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
package cn.novalon.gym.manage.auth.vo;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 手机号一键登录响应VO
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class PhoneLoginVO {
|
||||||
|
|
||||||
|
private Long memberId;
|
||||||
|
|
||||||
|
private String memberNo;
|
||||||
|
|
||||||
|
private String phone;
|
||||||
|
|
||||||
|
private String accessToken;
|
||||||
|
|
||||||
|
private String refreshToken;
|
||||||
|
|
||||||
|
private Integer expiresIn;
|
||||||
|
|
||||||
|
private Boolean isNewUser;
|
||||||
|
|
||||||
|
private Boolean needCompleteInfo;
|
||||||
|
|
||||||
|
private String nickname;
|
||||||
|
|
||||||
|
private String avatar;
|
||||||
|
}
|
||||||
+5
@@ -0,0 +1,5 @@
|
|||||||
|
cn.novalon.gym.manage.auth.handler.PhoneAuthHandler
|
||||||
|
cn.novalon.gym.manage.auth.service.impl.PhoneAuthServiceImpl
|
||||||
|
cn.novalon.gym.manage.auth.service.impl.SmsServiceImpl
|
||||||
|
cn.novalon.gym.manage.auth.config.AuthConfig
|
||||||
|
cn.novalon.gym.manage.auth.config.SmsProperties
|
||||||
+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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
# Compiled class file
|
||||||
|
*.class
|
||||||
|
|
||||||
|
# Log file
|
||||||
|
*.log
|
||||||
|
|
||||||
|
# BlueJ files
|
||||||
|
*.ctxt
|
||||||
|
|
||||||
|
# Mobile Tools for Java (J2ME)
|
||||||
|
.mtj.tmp/
|
||||||
|
|
||||||
|
# Package Files
|
||||||
|
*.jar
|
||||||
|
*.war
|
||||||
|
*.nar
|
||||||
|
*.ear
|
||||||
|
*.zip
|
||||||
|
*.tar.gz
|
||||||
|
*.rar
|
||||||
|
|
||||||
|
# Virtual machine crash logs
|
||||||
|
hs_err_pid*
|
||||||
|
replay_pid*
|
||||||
|
|
||||||
|
# Maven
|
||||||
|
target/
|
||||||
|
pom.xml.tag
|
||||||
|
pom.xml.releaseBackup
|
||||||
|
pom.xml.versionsBackup
|
||||||
|
pom.xml.next
|
||||||
|
release.properties
|
||||||
|
dependency-reduced-pom.xml
|
||||||
|
buildNumber.properties
|
||||||
|
.mvn/timing.properties
|
||||||
|
.mvn/wrapper/maven-wrapper.jar
|
||||||
|
|
||||||
|
# IDE
|
||||||
|
.idea/
|
||||||
|
*.iml
|
||||||
|
.vscode/
|
||||||
|
.settings/
|
||||||
|
.classpath
|
||||||
|
.project
|
||||||
|
|
||||||
|
# OS
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
@@ -0,0 +1,257 @@
|
|||||||
|
<?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-checkIn</artifactId>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
|
<name>Gym CheckIn</name>
|
||||||
|
<description>Check-In Management Module - Member Attendance Services</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>gym-member</artifactId>
|
||||||
|
<version>${project.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>cn.novalon.gym.manage</groupId>
|
||||||
|
<artifactId>gym-groupCourse</artifactId>
|
||||||
|
<version>${project.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-webflux</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-aop</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springdoc</groupId>
|
||||||
|
<artifactId>springdoc-openapi-starter-webflux-ui</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.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-test</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.security</groupId>
|
||||||
|
<artifactId>spring-security-test</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.projectreactor</groupId>
|
||||||
|
<artifactId>reactor-test</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.github.resilience4j</groupId>
|
||||||
|
<artifactId>resilience4j-spring-boot3</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.github.resilience4j</groupId>
|
||||||
|
<artifactId>resilience4j-reactor</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.testcontainers</groupId>
|
||||||
|
<artifactId>testcontainers</artifactId>
|
||||||
|
<version>1.21.4</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.testcontainers</groupId>
|
||||||
|
<artifactId>postgresql</artifactId>
|
||||||
|
<version>1.21.4</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.testcontainers</groupId>
|
||||||
|
<artifactId>junit-jupiter</artifactId>
|
||||||
|
<version>1.21.4</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.h2database</groupId>
|
||||||
|
<artifactId>h2</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.r2dbc</groupId>
|
||||||
|
<artifactId>r2dbc-h2</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.postgresql</groupId>
|
||||||
|
<artifactId>r2dbc-postgresql</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>cn.hutool</groupId>
|
||||||
|
<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>
|
||||||
|
<version>3.5.1</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- 添加 ZXing JavaSE 扩展(用于生成图片) -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.google.zxing</groupId>
|
||||||
|
<artifactId>javase</artifactId>
|
||||||
|
<version>3.5.1</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-websocket</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.mapstruct</groupId>
|
||||||
|
<artifactId>mapstruct-processor</artifactId>
|
||||||
|
<version>1.5.5.Final</version>
|
||||||
|
</path>
|
||||||
|
<path>
|
||||||
|
<groupId>org.projectlombok</groupId>
|
||||||
|
<artifactId>lombok</artifactId>
|
||||||
|
<version>${lombok.version}</version>
|
||||||
|
</path>
|
||||||
|
<path>
|
||||||
|
<groupId>org.projectlombok</groupId>
|
||||||
|
<artifactId>lombok-mapstruct-binding</artifactId>
|
||||||
|
<version>0.2.0</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>
|
||||||
|
<execution>
|
||||||
|
<id>check</id>
|
||||||
|
<phase>verify</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>check</goal>
|
||||||
|
</goals>
|
||||||
|
<configuration>
|
||||||
|
<rules>
|
||||||
|
<rule>
|
||||||
|
<element>BUNDLE</element>
|
||||||
|
<limits>
|
||||||
|
<limit>
|
||||||
|
<counter>INSTRUCTION</counter>
|
||||||
|
<value>COVEREDRATIO</value>
|
||||||
|
<minimum>0.60</minimum>
|
||||||
|
</limit>
|
||||||
|
</limits>
|
||||||
|
</rule>
|
||||||
|
</rules>
|
||||||
|
</configuration>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>com.github.spotbugs</groupId>
|
||||||
|
<artifactId>spotbugs-maven-plugin</artifactId>
|
||||||
|
<version>4.8.6.0</version>
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.github.spotbugs</groupId>
|
||||||
|
<artifactId>spotbugs</artifactId>
|
||||||
|
<version>4.8.6</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<id>spotbugs-check</id>
|
||||||
|
<phase>verify</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>check</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
<configuration>
|
||||||
|
<effort>Max</effort>
|
||||||
|
<threshold>High</threshold>
|
||||||
|
<failOnError>true</failOnError>
|
||||||
|
<excludeFilterFile>spotbugs-exclude.xml</excludeFilterFile>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</project>
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<FindBugsFilter>
|
||||||
|
<Match>
|
||||||
|
<Class name="~.*\.entity\..*" />
|
||||||
|
</Match>
|
||||||
|
<Match>
|
||||||
|
<Class name="~.*\.dto\..*" />
|
||||||
|
</Match>
|
||||||
|
<Match>
|
||||||
|
<Class name="~.*\.converter\..*" />
|
||||||
|
</Match>
|
||||||
|
</FindBugsFilter>
|
||||||
+43
@@ -0,0 +1,43 @@
|
|||||||
|
package cn.novalon.gym.manage.checkIn.config;
|
||||||
|
|
||||||
|
import cn.novalon.gym.manage.checkIn.websocket.MyWebSocketHandler;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
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;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
public class CheckInWebSocketConfig {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private MyWebSocketHandler myWebSocketHandler;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 注册 WebSocket 路由映射
|
||||||
|
* 路径对应前端连接的 ws://xxx/webSocket/checkIn
|
||||||
|
*/
|
||||||
|
@Bean
|
||||||
|
public HandlerMapping webSocketMapping() {
|
||||||
|
Map<String, WebSocketHandler> map = new HashMap<>();
|
||||||
|
map.put("/webSocket/checkIn", myWebSocketHandler);
|
||||||
|
|
||||||
|
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
|
||||||
|
mapping.setUrlMap(map);
|
||||||
|
mapping.setOrder(10); // 设置优先级
|
||||||
|
return mapping;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 注册 WebSocket 处理器适配器(必须)
|
||||||
|
*/
|
||||||
|
@Bean
|
||||||
|
public WebSocketHandlerAdapter handlerAdapter() {
|
||||||
|
return new WebSocketHandlerAdapter();
|
||||||
|
}
|
||||||
|
}
|
||||||
+46
@@ -0,0 +1,46 @@
|
|||||||
|
package cn.novalon.gym.manage.checkIn.config;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Configuration
|
||||||
|
@ConfigurationProperties(prefix = "qr.config")
|
||||||
|
public class QRCodeConfig {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 二维码宽度(像素)
|
||||||
|
*/
|
||||||
|
private Integer width = 300;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 二维码高度(像素)
|
||||||
|
*/
|
||||||
|
private Integer height = 300;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 白边宽度
|
||||||
|
*/
|
||||||
|
private Integer margin = 1;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 容错率:L, M, Q, H
|
||||||
|
*/
|
||||||
|
private String errorCorrection = "M";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 图片格式:png, jpg
|
||||||
|
*/
|
||||||
|
private String format = "png";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 是否启用Logo
|
||||||
|
*/
|
||||||
|
private Boolean logoEnabled = false;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Logo路径
|
||||||
|
*/
|
||||||
|
private String logoPath = "";
|
||||||
|
}
|
||||||
+43
@@ -0,0 +1,43 @@
|
|||||||
|
package cn.novalon.gym.manage.checkIn.config;
|
||||||
|
|
||||||
|
import cn.novalon.gym.manage.checkIn.websocket.MyWebSocketHandler;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
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;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
public class WebSocketConfig {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private MyWebSocketHandler myWebSocketHandler;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 注册 WebSocket 路由映射
|
||||||
|
* 路径对应前端连接的 ws://xxx/webSocket/checkIn
|
||||||
|
*/
|
||||||
|
@Bean
|
||||||
|
public HandlerMapping webSocketMapping() {
|
||||||
|
Map<String, WebSocketHandler> map = new HashMap<>();
|
||||||
|
map.put("/webSocket/checkIn", myWebSocketHandler);
|
||||||
|
|
||||||
|
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
|
||||||
|
mapping.setUrlMap(map);
|
||||||
|
mapping.setOrder(10); // 设置优先级
|
||||||
|
return mapping;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 注册 WebSocket 处理器适配器(必须)
|
||||||
|
*/
|
||||||
|
@Bean
|
||||||
|
public WebSocketHandlerAdapter handlerAdapter() {
|
||||||
|
return new WebSocketHandlerAdapter();
|
||||||
|
}
|
||||||
|
}
|
||||||
+43
@@ -0,0 +1,43 @@
|
|||||||
|
package cn.novalon.gym.manage.checkIn.constant;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 打卡模块 Redis 键常量
|
||||||
|
*
|
||||||
|
* @author 付嘉
|
||||||
|
* @date 2026-05-30
|
||||||
|
*/
|
||||||
|
public final class QRRedisKey {
|
||||||
|
|
||||||
|
private static final String SEPARATOR = ":";
|
||||||
|
private static final String QRCODE_USER_DAILY = "qrcode:user:daily";
|
||||||
|
private static final String QRCODE_CONTENT = "QR_";
|
||||||
|
private QRRedisKey() {
|
||||||
|
// 私有构造,防止实例化
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用户当日二维码
|
||||||
|
* 格式:qrcode:user:daily:{userId}:{date}
|
||||||
|
* 示例:qrcode:user:daily:1001:2026-05-30
|
||||||
|
*/
|
||||||
|
public static String qrcodeUserDaily(Long userId, LocalDate date) {
|
||||||
|
return QRCODE_USER_DAILY + SEPARATOR + userId + SEPARATOR + date;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用户当日二维码(今天)
|
||||||
|
*/
|
||||||
|
public static String qrcodeUserToday(Long userId) {
|
||||||
|
return qrcodeUserDaily(userId, LocalDate.now());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 生成二维码内容(每个用户每次调用都不同)
|
||||||
|
*/
|
||||||
|
public static String generateQrcodeContent() {
|
||||||
|
return QRCODE_CONTENT + UUID.randomUUID().toString().replace("-", "");
|
||||||
|
}
|
||||||
|
}
|
||||||
+13
@@ -0,0 +1,13 @@
|
|||||||
|
package cn.novalon.gym.manage.checkIn.dto;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class QRCodeDto {
|
||||||
|
|
||||||
|
private String qrContent;
|
||||||
|
|
||||||
|
private boolean isUsed;
|
||||||
|
}
|
||||||
+209
@@ -0,0 +1,209 @@
|
|||||||
|
package cn.novalon.gym.manage.checkIn.entity;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
import org.springframework.data.annotation.CreatedDate;
|
||||||
|
import org.springframework.data.annotation.Id;
|
||||||
|
import org.springframework.data.annotation.LastModifiedDate;
|
||||||
|
import org.springframework.data.relational.core.mapping.Column;
|
||||||
|
import org.springframework.data.relational.core.mapping.Table;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 会员到店签到记录实体
|
||||||
|
*
|
||||||
|
* @author 付嘉
|
||||||
|
* @date 2026-06-08
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
@Table("sign_in_record")
|
||||||
|
public class SignInRecord {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 自增主键
|
||||||
|
*/
|
||||||
|
@Id
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 会员ID,关联member表
|
||||||
|
*/
|
||||||
|
@Column("member_id")
|
||||||
|
private Long memberId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签到时使用的会员卡ID
|
||||||
|
*/
|
||||||
|
@Column("member_card_id")
|
||||||
|
private Long memberCardId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签到入场时间
|
||||||
|
*/
|
||||||
|
@Column("sign_in_time")
|
||||||
|
private LocalDateTime signInTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签到方式:QR_CODE-扫码签到,MANUAL-手动签到,FACE-人脸识别
|
||||||
|
*/
|
||||||
|
@Column("sign_in_type")
|
||||||
|
private String signInType;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签到状态:SUCCESS-成功,FAILED-失败
|
||||||
|
*/
|
||||||
|
@Column("sign_in_status")
|
||||||
|
private String signInStatus;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* JSONB格式,存储会员卡验证时的快照数据
|
||||||
|
*/
|
||||||
|
@Column("verification_details")
|
||||||
|
private String verificationDetails;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 失败时的具体原因文案
|
||||||
|
*/
|
||||||
|
@Column("fail_reason")
|
||||||
|
private String failReason;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 操作人ID(前台人员),自助签到时为NULL
|
||||||
|
*/
|
||||||
|
@Column("operator_id")
|
||||||
|
private Long operatorId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 操作人姓名冗余
|
||||||
|
*/
|
||||||
|
@Column("operator_name")
|
||||||
|
private String operatorName;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签到设备标识或型号
|
||||||
|
*/
|
||||||
|
@Column("device_info")
|
||||||
|
private String deviceInfo;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 客户端IP地址
|
||||||
|
*/
|
||||||
|
@Column("ip_address")
|
||||||
|
private String ipAddress;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签到来源:MINI_PROGRAM-小程序扫码,PC_BACKEND-后台管理端
|
||||||
|
*/
|
||||||
|
@Column("source")
|
||||||
|
private String source;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 软删除标识:false-未删除,true-已删除
|
||||||
|
*/
|
||||||
|
@Column("is_delete")
|
||||||
|
private Boolean isDelete;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 记录创建时间
|
||||||
|
*/
|
||||||
|
@CreatedDate
|
||||||
|
@Column("created_at")
|
||||||
|
private LocalDateTime createdAt;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 记录更新时间
|
||||||
|
*/
|
||||||
|
@LastModifiedDate
|
||||||
|
@Column("updated_at")
|
||||||
|
private LocalDateTime updatedAt;
|
||||||
|
|
||||||
|
// ========== 常量定义 ==========
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签到类型常量
|
||||||
|
*/
|
||||||
|
public static final class SignInType {
|
||||||
|
/** 扫码签到 */
|
||||||
|
public static final String QR_CODE = "QR_CODE";
|
||||||
|
/** 手动签到 */
|
||||||
|
public static final String MANUAL = "MANUAL";
|
||||||
|
/** 人脸识别 */
|
||||||
|
public static final String FACE = "FACE";
|
||||||
|
|
||||||
|
private SignInType() {}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签到状态常量
|
||||||
|
*/
|
||||||
|
public static final class SignInStatus {
|
||||||
|
/** 成功 */
|
||||||
|
public static final String SUCCESS = "SUCCESS";
|
||||||
|
/** 失败 */
|
||||||
|
public static final String FAILED = "FAILED";
|
||||||
|
|
||||||
|
private SignInStatus() {}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签到来源常量
|
||||||
|
*/
|
||||||
|
public static final class Source {
|
||||||
|
/** 小程序扫码 */
|
||||||
|
public static final String MINI_PROGRAM = "MINI_PROGRAM";
|
||||||
|
/** 后台管理端手动签到 */
|
||||||
|
public static final String PC_BACKEND = "PC_BACKEND";
|
||||||
|
|
||||||
|
private Source() {}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== 辅助方法 ==========
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断签到是否成功
|
||||||
|
*/
|
||||||
|
public boolean isSuccess() {
|
||||||
|
return SignInStatus.SUCCESS.equals(this.signInStatus);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断签到是否失败
|
||||||
|
*/
|
||||||
|
public boolean isFailed() {
|
||||||
|
return SignInStatus.FAILED.equals(this.signInStatus);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断是否为扫码签到
|
||||||
|
*/
|
||||||
|
public boolean isQrCodeSign() {
|
||||||
|
return SignInType.QR_CODE.equals(this.signInType);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断是否已删除
|
||||||
|
*/
|
||||||
|
public boolean isDeleted() {
|
||||||
|
return Boolean.TRUE.equals(this.isDelete);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 软删除
|
||||||
|
*/
|
||||||
|
public void softDelete() {
|
||||||
|
this.isDelete = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 恢复删除
|
||||||
|
*/
|
||||||
|
public void restore() {
|
||||||
|
this.isDelete = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
+197
@@ -0,0 +1,197 @@
|
|||||||
|
package cn.novalon.gym.manage.checkIn.handler;
|
||||||
|
|
||||||
|
import cn.novalon.gym.manage.checkIn.service.impl.CheckServiceImpl;
|
||||||
|
import cn.novalon.gym.manage.checkIn.websocket.MyWebSocketHandler;
|
||||||
|
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 lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
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 cn.novalon.gym.manage.checkIn.websocket.MyWebSocketHandler;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.format.DateTimeFormatter;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class CheckInHandler {
|
||||||
|
|
||||||
|
private final AuthUtil authUtil;
|
||||||
|
private final CheckServiceImpl checkService;
|
||||||
|
|
||||||
|
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签到
|
||||||
|
*
|
||||||
|
* POST /api/checkIn
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
public Mono<ServerResponse> checkIn(ServerRequest request) {
|
||||||
|
|
||||||
|
Long memberId = authUtil.getMemberIdOrThrow(request);
|
||||||
|
|
||||||
|
return request.bodyToMono(Map.class)
|
||||||
|
.flatMap(body -> {
|
||||||
|
String qrContent = (String) body.get("qrContent");
|
||||||
|
log.info("收到签到请求, memberId: {}, qrContent: {}", memberId, qrContent);
|
||||||
|
boolean messageToClient = MyWebSocketHandler.sendMessageToClient(qrContent, "正在进行签到");
|
||||||
|
log.info("WebSocket 推送结果: {}", messageToClient);
|
||||||
|
return checkService.checkIn(memberId, qrContent)
|
||||||
|
.flatMap(result -> ServerResponse.ok()
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.bodyValue(result));
|
||||||
|
})
|
||||||
|
.onErrorResume(e -> {
|
||||||
|
log.error("签到失败", e);
|
||||||
|
return ServerResponse.status(HttpStatus.BAD_REQUEST)
|
||||||
|
.bodyValue(Map.of("code", 400, "message", e.getMessage()));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取二维码
|
||||||
|
*
|
||||||
|
* GET /api/checkin/qrcode
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
public Mono<ServerResponse> getQRCode(ServerRequest request) {
|
||||||
|
|
||||||
|
Long memberId = authUtil.getMemberIdOrThrow(request);
|
||||||
|
|
||||||
|
log.info("收到用户{}获取二维码请求", memberId);
|
||||||
|
|
||||||
|
return checkService.getQRCode(memberId)
|
||||||
|
.flatMap(qrCodeVo -> ServerResponse.ok()
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.bodyValue(qrCodeVo));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询签到记录列表
|
||||||
|
*
|
||||||
|
* GET /api/checkIn/records
|
||||||
|
*
|
||||||
|
* @param request
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public Mono<ServerResponse> getSignInRecords(ServerRequest request) {
|
||||||
|
Long memberId = authUtil.getMemberIdOrThrow(request);
|
||||||
|
|
||||||
|
String startDateStr = request.queryParam("startDate").orElse(null);
|
||||||
|
String endDateStr = request.queryParam("endDate").orElse(null);
|
||||||
|
|
||||||
|
LocalDate startDate = startDateStr != null ? LocalDate.parse(startDateStr, DATE_FORMATTER) : LocalDate.now().minusDays(30);
|
||||||
|
LocalDate endDate = endDateStr != null ? LocalDate.parse(endDateStr, DATE_FORMATTER) : LocalDate.now();
|
||||||
|
|
||||||
|
log.info("查询签到记录, memberId: {}, startDate: {}, endDate: {}", memberId, startDate, endDate);
|
||||||
|
|
||||||
|
return checkService.getSignInRecords(memberId, startDate, endDate)
|
||||||
|
.collectList()
|
||||||
|
.flatMap(records -> ServerResponse.ok()
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.bodyValue(Map.of("code", 200, "message", "success", "data", records)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询单条签到记录
|
||||||
|
*
|
||||||
|
* GET /api/checkIn/records/{id}
|
||||||
|
*
|
||||||
|
* @param request
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public Mono<ServerResponse> getSignInRecordById(ServerRequest request) {
|
||||||
|
Long id = Long.parseLong(request.pathVariable("id"));
|
||||||
|
|
||||||
|
log.info("查询签到记录详情, id: {}", id);
|
||||||
|
|
||||||
|
return checkService.getSignInRecordById(id)
|
||||||
|
.flatMap(record -> ServerResponse.ok()
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.bodyValue(Map.of("code", 200, "message", "success", "data", record)))
|
||||||
|
.switchIfEmpty(ServerResponse.notFound().build());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取签到统计
|
||||||
|
*
|
||||||
|
* GET /api/checkIn/statistics
|
||||||
|
*
|
||||||
|
* @param request
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public Mono<ServerResponse> getSignInStatistics(ServerRequest request) {
|
||||||
|
Long memberId = authUtil.getMemberIdOrThrow(request);
|
||||||
|
|
||||||
|
String startDateStr = request.queryParam("startDate").orElse(null);
|
||||||
|
String endDateStr = request.queryParam("endDate").orElse(null);
|
||||||
|
|
||||||
|
LocalDate startDate = startDateStr != null ? LocalDate.parse(startDateStr, DATE_FORMATTER) : LocalDate.now().minusDays(30);
|
||||||
|
LocalDate endDate = endDateStr != null ? LocalDate.parse(endDateStr, DATE_FORMATTER) : LocalDate.now();
|
||||||
|
|
||||||
|
log.info("查询签到统计, memberId: {}, startDate: {}, endDate: {}", memberId, startDate, endDate);
|
||||||
|
|
||||||
|
return checkService.getSignInStats(memberId, startDate, endDate)
|
||||||
|
.flatMap(stats -> ServerResponse.ok()
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.bodyValue(Map.of("code", 200, "message", "success", "data", stats)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 导出签到记录
|
||||||
|
*
|
||||||
|
* GET /api/checkIn/records/export
|
||||||
|
*
|
||||||
|
* @param request
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public Mono<ServerResponse> exportSignInRecords(ServerRequest request) {
|
||||||
|
Long memberId = authUtil.getMemberIdOrThrow(request);
|
||||||
|
|
||||||
|
String startDateStr = request.queryParam("startDate").orElse(null);
|
||||||
|
String endDateStr = request.queryParam("endDate").orElse(null);
|
||||||
|
|
||||||
|
LocalDate startDate = startDateStr != null ? LocalDate.parse(startDateStr, DATE_FORMATTER) : LocalDate.now().minusDays(30);
|
||||||
|
LocalDate endDate = endDateStr != null ? LocalDate.parse(endDateStr, DATE_FORMATTER) : LocalDate.now();
|
||||||
|
|
||||||
|
log.info("导出签到记录, memberId: {}, startDate: {}, endDate: {}", memberId, startDate, endDate);
|
||||||
|
|
||||||
|
String filename = "签到记录_" + startDateStr + "_" + endDateStr + ".csv";
|
||||||
|
|
||||||
|
return checkService.exportSignInRecords(memberId, startDate, endDate)
|
||||||
|
.flatMap(bytes -> ServerResponse.ok()
|
||||||
|
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
|
||||||
|
.contentType(MediaType.parseMediaType("text/csv; charset=UTF-8"))
|
||||||
|
.bodyValue(bytes));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取每日签到统计
|
||||||
|
*
|
||||||
|
* GET /api/checkIn/daily-stats
|
||||||
|
*
|
||||||
|
* @param request
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public Mono<ServerResponse> getDailySignInStats(ServerRequest request) {
|
||||||
|
String dateStr = request.queryParam("date").orElse(null);
|
||||||
|
LocalDate date = dateStr != null ? LocalDate.parse(dateStr, DATE_FORMATTER) : LocalDate.now();
|
||||||
|
|
||||||
|
log.info("查询每日签到统计, date: {}", date);
|
||||||
|
|
||||||
|
return checkService.getDailySignInStats(date)
|
||||||
|
.flatMap(stats -> ServerResponse.ok()
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.bodyValue(Map.of("code", 200, "message", "success", "data", stats)));
|
||||||
|
}
|
||||||
|
}
|
||||||
+101
@@ -0,0 +1,101 @@
|
|||||||
|
package cn.novalon.gym.manage.checkIn.repository;
|
||||||
|
|
||||||
|
import cn.novalon.gym.manage.checkIn.entity.SignInRecord;
|
||||||
|
import org.springframework.data.r2dbc.repository.Query;
|
||||||
|
import org.springframework.data.r2dbc.repository.R2dbcRepository;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
import reactor.core.publisher.Flux;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签到记录 Repository
|
||||||
|
*
|
||||||
|
* @author 付嘉
|
||||||
|
* @date 2026-06-08
|
||||||
|
*/
|
||||||
|
@Repository
|
||||||
|
public interface SignInRecordRepository extends R2dbcRepository<SignInRecord, Long> {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询会员某天的签到记录
|
||||||
|
*/
|
||||||
|
@Query("SELECT * FROM sign_in_record WHERE member_id = :memberId AND sign_in_time >= :startTime AND sign_in_time < :endTime AND is_delete = false")
|
||||||
|
Mono<SignInRecord> findByMemberIdAndDate(Long memberId, LocalDateTime startTime, LocalDateTime endTime);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询会员的签到记录列表
|
||||||
|
*/
|
||||||
|
@Query("SELECT * FROM sign_in_record WHERE member_id = :memberId AND is_delete = false ORDER BY sign_in_time DESC")
|
||||||
|
Flux<SignInRecord> findByMemberId(Long memberId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计会员某天的签到次数
|
||||||
|
*/
|
||||||
|
@Query("SELECT COUNT(*) FROM sign_in_record WHERE member_id = :memberId AND sign_in_time >= :startTime AND sign_in_time < :endTime AND is_delete = false")
|
||||||
|
Mono<Long> countByMemberIdAndDate(Long memberId, LocalDateTime startTime, LocalDateTime endTime);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 插入签到记录
|
||||||
|
*/
|
||||||
|
@Query("INSERT INTO sign_in_record (member_id, member_card_id, sign_in_time, sign_in_type, sign_in_status, verification_details, fail_reason, source, created_at, updated_at, is_delete) " +
|
||||||
|
"VALUES (:memberId, :memberCardId, :signInTime, :signInType, :signInStatus, :verificationDetails, :failReason, :source, NOW(), NOW(), false)")
|
||||||
|
Mono<Void> insertRecord(Long memberId, Long memberCardId, LocalDateTime signInTime,
|
||||||
|
String signInType, String signInStatus, String verificationDetails,
|
||||||
|
String failReason, String source);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据会员ID和时间范围查询签到记录
|
||||||
|
*/
|
||||||
|
@Query("SELECT * FROM sign_in_record WHERE member_id = :memberId AND sign_in_time >= :startTime AND sign_in_time <= :endTime AND is_delete = false ORDER BY sign_in_time DESC")
|
||||||
|
Flux<SignInRecord> findByMemberIdAndTimeRange(Long memberId, LocalDateTime startTime, LocalDateTime endTime);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据时间范围查询签到记录
|
||||||
|
*/
|
||||||
|
@Query("SELECT * FROM sign_in_record WHERE sign_in_time >= :startTime AND sign_in_time <= :endTime AND is_delete = false ORDER BY sign_in_time DESC")
|
||||||
|
Flux<SignInRecord> findByTimeRange(LocalDateTime startTime, LocalDateTime endTime);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计会员在时间范围内的签到次数
|
||||||
|
*/
|
||||||
|
@Query("SELECT COUNT(*) FROM sign_in_record WHERE member_id = :memberId AND sign_in_time >= :startTime AND sign_in_time <= :endTime AND is_delete = false")
|
||||||
|
Mono<Long> countByMemberIdAndTimeRange(Long memberId, LocalDateTime startTime, LocalDateTime endTime);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计时间范围内的签到次数
|
||||||
|
*/
|
||||||
|
@Query("SELECT COUNT(*) FROM sign_in_record WHERE sign_in_time >= :startTime AND sign_in_time <= :endTime AND is_delete = false")
|
||||||
|
Mono<Long> countByTimeRange(LocalDateTime startTime, LocalDateTime endTime);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计会员在时间范围内的成功签到次数
|
||||||
|
*/
|
||||||
|
@Query("SELECT COUNT(*) FROM sign_in_record WHERE member_id = :memberId AND sign_in_time >= :startTime AND sign_in_time <= :endTime AND sign_in_status = 'SUCCESS' AND is_delete = false")
|
||||||
|
Mono<Long> countSuccessByMemberIdAndTimeRange(Long memberId, LocalDateTime startTime, LocalDateTime endTime);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计时间范围内的成功签到次数
|
||||||
|
*/
|
||||||
|
@Query("SELECT COUNT(*) FROM sign_in_record WHERE sign_in_time >= :startTime AND sign_in_time <= :endTime AND sign_in_status = 'SUCCESS' AND is_delete = false")
|
||||||
|
Mono<Long> countSuccessByTimeRange(LocalDateTime startTime, LocalDateTime endTime);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计时间范围内签到的独立会员数
|
||||||
|
*/
|
||||||
|
@Query("SELECT COUNT(DISTINCT member_id) FROM sign_in_record WHERE sign_in_time >= :startTime AND sign_in_time <= :endTime AND is_delete = false")
|
||||||
|
Mono<Long> countDistinctMembersByTimeRange(LocalDateTime startTime, LocalDateTime endTime);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取会员在时间范围内的首次签到时间
|
||||||
|
*/
|
||||||
|
@Query("SELECT MIN(sign_in_time) FROM sign_in_record WHERE member_id = :memberId AND sign_in_time >= :startTime AND sign_in_time <= :endTime AND is_delete = false")
|
||||||
|
Mono<LocalDateTime> getFirstSignInTime(Long memberId, LocalDateTime startTime, LocalDateTime endTime);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取会员在时间范围内的最后签到时间
|
||||||
|
*/
|
||||||
|
@Query("SELECT MAX(sign_in_time) FROM sign_in_record WHERE member_id = :memberId AND sign_in_time >= :startTime AND sign_in_time <= :endTime AND is_delete = false")
|
||||||
|
Mono<LocalDateTime> getLastSignInTime(Long memberId, LocalDateTime startTime, LocalDateTime endTime);
|
||||||
|
}
|
||||||
+81
@@ -0,0 +1,81 @@
|
|||||||
|
package cn.novalon.gym.manage.checkIn.service;
|
||||||
|
|
||||||
|
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 reactor.core.publisher.Flux;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签到服务接口
|
||||||
|
*
|
||||||
|
* @author 付嘉
|
||||||
|
* @date 2026-06-08
|
||||||
|
*/
|
||||||
|
public interface ICheckInService {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取签到二维码
|
||||||
|
*
|
||||||
|
* @param memberId 会员ID
|
||||||
|
* @return 二维码VO
|
||||||
|
*/
|
||||||
|
Mono<QRCodeVo> getQRCode(Long memberId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 扫码签到
|
||||||
|
*
|
||||||
|
* @param memberId 会员ID
|
||||||
|
* @param qrContent 二维码内容
|
||||||
|
* @return 签到结果JSON字符串
|
||||||
|
*/
|
||||||
|
Mono<String> checkIn(Long memberId, String qrContent);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询会员签到记录列表
|
||||||
|
*
|
||||||
|
* @param memberId 会员ID
|
||||||
|
* @param startTime 开始时间
|
||||||
|
* @param endTime 结束时间
|
||||||
|
* @return 签到记录列表
|
||||||
|
*/
|
||||||
|
Flux<SignInRecordVO> getSignInRecords(Long memberId, LocalDate startTime, LocalDate endTime);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据ID查询签到记录
|
||||||
|
*
|
||||||
|
* @param id 签到记录ID
|
||||||
|
* @return 签到记录VO
|
||||||
|
*/
|
||||||
|
Mono<SignInRecordVO> getSignInRecordById(Long id);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取会员签到统计
|
||||||
|
*
|
||||||
|
* @param memberId 会员ID
|
||||||
|
* @param startTime 开始时间
|
||||||
|
* @param endTime 结束时间
|
||||||
|
* @return 签到统计VO
|
||||||
|
*/
|
||||||
|
Mono<SignInStatsVO> getSignInStats(Long memberId, LocalDate startTime, LocalDate endTime);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 导出会员签到记录
|
||||||
|
*
|
||||||
|
* @param memberId 会员ID
|
||||||
|
* @param startTime 开始时间
|
||||||
|
* @param endTime 结束时间
|
||||||
|
* @return CSV格式的字节数组
|
||||||
|
*/
|
||||||
|
Mono<byte[]> exportSignInRecords(Long memberId, LocalDate startTime, LocalDate endTime);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取每日签到统计
|
||||||
|
*
|
||||||
|
* @param date 日期
|
||||||
|
* @return 签到统计VO
|
||||||
|
*/
|
||||||
|
Mono<SignInStatsVO> getDailySignInStats(LocalDate date);
|
||||||
|
}
|
||||||
+417
@@ -0,0 +1,417 @@
|
|||||||
|
package cn.novalon.gym.manage.checkIn.service.impl;
|
||||||
|
|
||||||
|
import cn.hutool.core.bean.BeanUtil;
|
||||||
|
import cn.hutool.json.JSONUtil;
|
||||||
|
import cn.hutool.extra.qrcode.QrCodeUtil;
|
||||||
|
import cn.hutool.extra.qrcode.QrConfig;
|
||||||
|
import cn.novalon.gym.manage.checkIn.config.QRCodeConfig;
|
||||||
|
import cn.novalon.gym.manage.checkIn.constant.QRRedisKey;
|
||||||
|
import cn.novalon.gym.manage.checkIn.entity.SignInRecord;
|
||||||
|
import cn.novalon.gym.manage.checkIn.repository.SignInRecordRepository;
|
||||||
|
import cn.novalon.gym.manage.checkIn.service.ICheckInService;
|
||||||
|
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.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;
|
||||||
|
import cn.novalon.gym.manage.member.enums.MemberCardType;
|
||||||
|
import cn.novalon.gym.manage.member.repository.MemberCardRecordRepository;
|
||||||
|
import cn.novalon.gym.manage.member.repository.MemberCardRepository;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import reactor.core.publisher.Flux;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.LocalTime;
|
||||||
|
import java.time.format.DateTimeFormatter;
|
||||||
|
import java.time.temporal.ChronoUnit;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class CheckServiceImpl implements ICheckInService {
|
||||||
|
|
||||||
|
private final QRCodeConfig qrCodeConfig;
|
||||||
|
private final RedisUtil redisUtil;
|
||||||
|
private final MemberCardRecordRepository memberCardRecordRepository;
|
||||||
|
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);
|
||||||
|
|
||||||
|
String qrContent = QRRedisKey.generateQrcodeContent();
|
||||||
|
Map<String, Object> redisMap = new HashMap<>();
|
||||||
|
redisMap.put("qrContent", qrContent);
|
||||||
|
redisMap.put("isUsed", false);
|
||||||
|
redisMap.put("memberId", memberId);
|
||||||
|
|
||||||
|
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
|
||||||
|
public Mono<String> checkIn(Long memberId, String qrContent) {
|
||||||
|
String key = RedisKeyConstants.QRCODE_USER_DAILY + memberId + LocalDate.now();
|
||||||
|
|
||||||
|
// 先检查当天是否已经签到(从数据库查询,作为重复签到的额外保障)
|
||||||
|
return checkTodayAlreadySignedIn(memberId)
|
||||||
|
.flatMap(existingRecord -> {
|
||||||
|
String checkInTime = existingRecord.getSignInTime().format(DATE_FORMATTER);
|
||||||
|
log.error("重复签到, memberId: {}", memberId);
|
||||||
|
MyWebSocketHandler.sendFailure(qrContent, "您已经在" + checkInTime + "完成签到,请勿重复签到");
|
||||||
|
return Mono.error(new RuntimeException("您已经在" + checkInTime + "完成签到,请勿重复签到"));
|
||||||
|
})
|
||||||
|
.then(Mono.defer(() -> redisUtil.get(key)))
|
||||||
|
.flatMap(cachedObj -> {
|
||||||
|
if (cachedObj != null) {
|
||||||
|
Map<String, Object> map;
|
||||||
|
if (cachedObj instanceof Map) {
|
||||||
|
map = (Map<String, Object>) cachedObj;
|
||||||
|
} else if (cachedObj instanceof String) {
|
||||||
|
map = JSONUtil.parseObj((String) cachedObj);
|
||||||
|
} else {
|
||||||
|
MyWebSocketHandler.sendFailure(qrContent, "二维码数据格式错误");
|
||||||
|
return Mono.error(new RuntimeException("二维码数据格式错误"));
|
||||||
|
}
|
||||||
|
if (map.get("qrContent").equals(qrContent)) {
|
||||||
|
if ((boolean) map.get("isUsed")) {
|
||||||
|
String checkInTime = String.valueOf(map.get("checkInTime"));
|
||||||
|
log.error("重复签到(缓存), memberId: {}", memberId);
|
||||||
|
MyWebSocketHandler.sendFailure(qrContent, "您已经在" + checkInTime + "完成签到,请勿重复签到");
|
||||||
|
return Mono.error(new RuntimeException("您已经在" + checkInTime + "完成签到,请勿重复签到"));
|
||||||
|
}
|
||||||
|
log.info("二维码匹配成功,memberId: {}", memberId);
|
||||||
|
|
||||||
|
Long memberCardRecordId = map.get("memberCardRecordId") != null
|
||||||
|
? ((Number) map.get("memberCardRecordId")).longValue() : null;
|
||||||
|
|
||||||
|
return processCheckIn(memberId, memberCardRecordId, map, qrContent);
|
||||||
|
} else {
|
||||||
|
MyWebSocketHandler.sendFailure(qrContent, "二维码无效");
|
||||||
|
return Mono.error(new RuntimeException("二维码无效"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
MyWebSocketHandler.sendFailure(qrContent, "二维码已过期或不存在");
|
||||||
|
return Mono.error(new RuntimeException("二维码已过期或不存在"));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检查会员当天是否已经签到
|
||||||
|
* @param memberId 会员ID
|
||||||
|
* @return 如果已签到返回签到记录,否则返回空
|
||||||
|
*/
|
||||||
|
private Mono<SignInRecord> checkTodayAlreadySignedIn(Long memberId) {
|
||||||
|
LocalDateTime startOfDay = LocalDate.now().atStartOfDay();
|
||||||
|
LocalDateTime endOfDay = LocalDate.now().atTime(LocalTime.MAX);
|
||||||
|
|
||||||
|
return signInRecordRepository.findByMemberIdAndDate(memberId, startOfDay, endOfDay);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 处理签到逻辑
|
||||||
|
*/
|
||||||
|
private Mono<String> processCheckIn(Long memberId, Long memberCardRecordId, Map<String, Object> redisMap, String qrContent) {
|
||||||
|
LocalDateTime now = LocalDateTime.now();
|
||||||
|
|
||||||
|
// 发送实时进度通知
|
||||||
|
MyWebSocketHandler.sendProgress(qrContent, "VALIDATE_BOOKING", "正在检查预约信息...");
|
||||||
|
|
||||||
|
// 检查是否有需要签到的团课预约,有则返回有效预约
|
||||||
|
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));
|
||||||
|
|
||||||
|
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<GroupCourseBooking> validateBooking(Long memberId, LocalDateTime now) {
|
||||||
|
return groupCourseBookingService.getBookingsByMemberId(memberId)
|
||||||
|
.filter(booking -> {
|
||||||
|
String status = booking.getStatus();
|
||||||
|
LocalDateTime startTime = booking.getCourseStartTime();
|
||||||
|
return "0".equals(status) &&
|
||||||
|
startTime != null &&
|
||||||
|
startTime.toLocalDate().equals(now.toLocalDate()) &&
|
||||||
|
!startTime.isBefore(now.minusMinutes(30));
|
||||||
|
})
|
||||||
|
.collectList()
|
||||||
|
.flatMap(bookings -> {
|
||||||
|
if (bookings.isEmpty()) {
|
||||||
|
return Mono.empty();
|
||||||
|
}
|
||||||
|
// 找到时间范围内第一个有效预约(课程时间内±30分钟)
|
||||||
|
return Flux.fromIterable(bookings)
|
||||||
|
.filter(b -> {
|
||||||
|
LocalDateTime startTime = b.getCourseStartTime();
|
||||||
|
return startTime != null &&
|
||||||
|
!startTime.isBefore(now.minusMinutes(30)) &&
|
||||||
|
!startTime.isAfter(now.plusMinutes(30));
|
||||||
|
})
|
||||||
|
.next()
|
||||||
|
.doOnNext(b -> log.info("会员{}有有效的团课预约, bookingId: {}", memberId, b.getId()))
|
||||||
|
.switchIfEmpty(Mono.fromRunnable(() ->
|
||||||
|
log.warn("会员{}有预约但不在签到时间范围内", memberId)));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 扣减会员卡使用次数/金额
|
||||||
|
*/
|
||||||
|
private Mono<MemberCardRecord> deductCardUsage(MemberCardRecord record, MemberCard card) {
|
||||||
|
MemberCardType cardType = MemberCardType.valueOf(card.getMemberCardType());
|
||||||
|
LocalDateTime now = LocalDateTime.now();
|
||||||
|
|
||||||
|
switch (cardType) {
|
||||||
|
case TIME_CARD:
|
||||||
|
if (record.getExpireTime() != null && record.getExpireTime().isBefore(now)) {
|
||||||
|
return Mono.error(new RuntimeException("时长卡已过期"));
|
||||||
|
}
|
||||||
|
return Mono.just(record);
|
||||||
|
case COUNT_CARD:
|
||||||
|
int currentTimes = record.getRemainingTimes() != null ? record.getRemainingTimes() : 0;
|
||||||
|
if (currentTimes < 1) {
|
||||||
|
return Mono.error(new RuntimeException("次卡剩余次数不足"));
|
||||||
|
}
|
||||||
|
record.setRemainingTimes(currentTimes - 1);
|
||||||
|
if (record.getRemainingTimes() == 0) {
|
||||||
|
record.setStatus(cn.novalon.gym.manage.member.enums.MemberCardRecordStatus.USED_UP);
|
||||||
|
}
|
||||||
|
return memberCardRecordRepository.save(record);
|
||||||
|
case STORED_VALUE_CARD:
|
||||||
|
double currentAmount = record.getRemainingAmount() != null ? record.getRemainingAmount() : 0.0;
|
||||||
|
if (currentAmount < 0.01) {
|
||||||
|
return Mono.error(new RuntimeException("储值卡余额不足"));
|
||||||
|
}
|
||||||
|
record.setRemainingAmount(Math.max(0, currentAmount - 1));
|
||||||
|
if (record.getRemainingAmount() <= 0) {
|
||||||
|
record.setStatus(cn.novalon.gym.manage.member.enums.MemberCardRecordStatus.USED_UP);
|
||||||
|
}
|
||||||
|
return memberCardRecordRepository.save(record);
|
||||||
|
default:
|
||||||
|
return Mono.error(new RuntimeException("不支持的会员卡类型"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 保存签到记录
|
||||||
|
*/
|
||||||
|
private Mono<Void> saveSignInRecord(Long memberId, Long memberCardRecordId, Long memberCardId) {
|
||||||
|
SignInRecord record = SignInRecord.builder()
|
||||||
|
.memberId(memberId)
|
||||||
|
.memberCardId(memberCardId)
|
||||||
|
.signInTime(LocalDateTime.now())
|
||||||
|
.signInType(SignInRecord.SignInType.QR_CODE)
|
||||||
|
.signInStatus(SignInRecord.SignInStatus.SUCCESS)
|
||||||
|
.source(SignInRecord.Source.MINI_PROGRAM)
|
||||||
|
.isDelete(false)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
return signInRecordRepository.save(record).then();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构建成功响应
|
||||||
|
*/
|
||||||
|
private String buildSuccessResponse(LocalDateTime dateTime) {
|
||||||
|
Map<String, Object> res = new HashMap<>();
|
||||||
|
res.put("message", "签到成功");
|
||||||
|
res.put("dateTime", dateTime.format(DATE_FORMATTER));
|
||||||
|
return JSONUtil.toJsonStr(res);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查找会员的有效会员卡(优先选择有效期最早到期的)
|
||||||
|
*/
|
||||||
|
private Mono<MemberCardRecord> findValidMemberCard(Long memberId) {
|
||||||
|
return memberCardRecordRepository.findActiveCardsByMemberId(memberId)
|
||||||
|
.filter(record -> {
|
||||||
|
LocalDateTime expireTime = record.getExpireTime();
|
||||||
|
return expireTime == null || expireTime.isAfter(LocalDateTime.now());
|
||||||
|
})
|
||||||
|
.sort((r1, r2) -> {
|
||||||
|
LocalDateTime e1 = r1.getExpireTime();
|
||||||
|
LocalDateTime e2 = r2.getExpireTime();
|
||||||
|
if (e1 == null && e2 == null) return 0;
|
||||||
|
if (e1 == null) return 1;
|
||||||
|
if (e2 == null) return -1;
|
||||||
|
return e1.compareTo(e2);
|
||||||
|
})
|
||||||
|
.next();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== 签到记录管理功能 ====================
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Flux<SignInRecordVO> getSignInRecords(Long memberId, LocalDate startTime, LocalDate endTime) {
|
||||||
|
LocalDateTime start = startTime.atStartOfDay();
|
||||||
|
LocalDateTime end = endTime.atTime(LocalTime.MAX);
|
||||||
|
|
||||||
|
return signInRecordRepository.findByMemberIdAndTimeRange(memberId, start, end)
|
||||||
|
.map(this::convertToVO);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Mono<SignInRecordVO> getSignInRecordById(Long id) {
|
||||||
|
return signInRecordRepository.findById(id)
|
||||||
|
.map(this::convertToVO);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Mono<SignInStatsVO> getSignInStats(Long memberId, LocalDate startTime, LocalDate endTime) {
|
||||||
|
LocalDateTime start = startTime.atStartOfDay();
|
||||||
|
LocalDateTime end = endTime.atTime(LocalTime.MAX);
|
||||||
|
|
||||||
|
return Mono.zip(
|
||||||
|
(Object[] results) -> {
|
||||||
|
Long total = (Long) results[0];
|
||||||
|
Long success = (Long) results[1];
|
||||||
|
LocalDateTime first = (LocalDateTime) results[2];
|
||||||
|
LocalDateTime last = (LocalDateTime) results[3];
|
||||||
|
SignInStatsVO stats = new SignInStatsVO();
|
||||||
|
stats.setTotalCount(total);
|
||||||
|
stats.setSuccessCount(success);
|
||||||
|
stats.setStartDate(startTime);
|
||||||
|
stats.setEndDate(endTime);
|
||||||
|
stats.setFirstSignInTime(first);
|
||||||
|
stats.setLastSignInTime(last);
|
||||||
|
stats.setSuccessRate(total > 0 ? (double) success / total * 100.0 : 0.0);
|
||||||
|
return stats;
|
||||||
|
},
|
||||||
|
signInRecordRepository.countByMemberIdAndTimeRange(memberId, start, end),
|
||||||
|
signInRecordRepository.countSuccessByMemberIdAndTimeRange(memberId, start, end),
|
||||||
|
signInRecordRepository.getFirstSignInTime(memberId, start, end),
|
||||||
|
signInRecordRepository.getLastSignInTime(memberId, start, end)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Mono<byte[]> exportSignInRecords(Long memberId, LocalDate startTime, LocalDate endTime) {
|
||||||
|
LocalDateTime start = startTime.atStartOfDay();
|
||||||
|
LocalDateTime end = endTime.atTime(LocalTime.MAX);
|
||||||
|
|
||||||
|
return signInRecordRepository.findByMemberIdAndTimeRange(memberId, start, end)
|
||||||
|
.map(record -> {
|
||||||
|
String status = "SUCCESS".equals(record.getSignInStatus()) ? "成功" : "失败";
|
||||||
|
String type = "QR_CODE".equals(record.getSignInType()) ? "扫码签到" :
|
||||||
|
"MANUAL".equals(record.getSignInType()) ? "手动签到" : "人脸识别";
|
||||||
|
return String.join(",",
|
||||||
|
record.getId().toString(),
|
||||||
|
record.getMemberId().toString(),
|
||||||
|
record.getMemberCardId() != null ? record.getMemberCardId().toString() : "",
|
||||||
|
record.getSignInTime() != null ? record.getSignInTime().format(DATE_FORMATTER) : "",
|
||||||
|
type,
|
||||||
|
status,
|
||||||
|
record.getFailReason() != null ? record.getFailReason() : ""
|
||||||
|
);
|
||||||
|
})
|
||||||
|
.collectList()
|
||||||
|
.map(rows -> {
|
||||||
|
List<String> csvLines = new java.util.ArrayList<>();
|
||||||
|
csvLines.add("签到记录ID,会员ID,会员卡ID,签到时间,签到方式,签到状态,失败原因");
|
||||||
|
csvLines.addAll(rows);
|
||||||
|
return String.join("\n", csvLines).getBytes(java.nio.charset.StandardCharsets.UTF_8);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Mono<SignInStatsVO> getDailySignInStats(LocalDate date) {
|
||||||
|
LocalDateTime start = date.atStartOfDay();
|
||||||
|
LocalDateTime end = date.atTime(LocalTime.MAX);
|
||||||
|
|
||||||
|
return Mono.zip(
|
||||||
|
(Object[] results) -> {
|
||||||
|
Long total = (Long) results[0];
|
||||||
|
Long success = (Long) results[1];
|
||||||
|
Long members = (Long) results[2];
|
||||||
|
SignInStatsVO stats = new SignInStatsVO();
|
||||||
|
stats.setTotalCount(total);
|
||||||
|
stats.setSuccessCount(success);
|
||||||
|
stats.setStartDate(date);
|
||||||
|
stats.setEndDate(date);
|
||||||
|
stats.setUniqueMemberCount(members);
|
||||||
|
stats.setSuccessRate(total > 0 ? (double) success / total * 100.0 : 0.0);
|
||||||
|
return stats;
|
||||||
|
},
|
||||||
|
signInRecordRepository.countByTimeRange(start, end),
|
||||||
|
signInRecordRepository.countSuccessByTimeRange(start, end),
|
||||||
|
signInRecordRepository.countDistinctMembersByTimeRange(start, end)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 转换实体到VO
|
||||||
|
*/
|
||||||
|
private SignInRecordVO convertToVO(SignInRecord record) {
|
||||||
|
SignInRecordVO vo = new SignInRecordVO();
|
||||||
|
vo.setId(record.getId());
|
||||||
|
vo.setMemberId(record.getMemberId());
|
||||||
|
vo.setMemberCardId(record.getMemberCardId());
|
||||||
|
vo.setSignInTime(record.getSignInTime());
|
||||||
|
vo.setSignInType(record.getSignInType());
|
||||||
|
vo.setSignInStatus(record.getSignInStatus());
|
||||||
|
vo.setFailReason(record.getFailReason());
|
||||||
|
vo.setSource(record.getSource());
|
||||||
|
vo.setCreatedAt(record.getCreatedAt());
|
||||||
|
return vo;
|
||||||
|
}
|
||||||
|
|
||||||
|
private long getSecondsUntilEndOfDay() {
|
||||||
|
LocalDateTime now = LocalDateTime.now();
|
||||||
|
LocalDateTime endOfDay = now.toLocalDate().atTime(23, 59, 59);
|
||||||
|
if (now.isAfter(endOfDay)) return 1;
|
||||||
|
return ChronoUnit.SECONDS.between(now, endOfDay);
|
||||||
|
}
|
||||||
|
}
|
||||||
+23
@@ -0,0 +1,23 @@
|
|||||||
|
package cn.novalon.gym.manage.checkIn.vo;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class QRCodeVo {
|
||||||
|
|
||||||
|
private String qrCodeBase64;
|
||||||
|
|
||||||
|
private boolean isUsed;
|
||||||
|
|
||||||
|
private String qrContent;
|
||||||
|
|
||||||
|
private Integer width;
|
||||||
|
|
||||||
|
private Integer height;
|
||||||
|
|
||||||
|
private LocalDate createTime;
|
||||||
|
}
|
||||||
+66
@@ -0,0 +1,66 @@
|
|||||||
|
package cn.novalon.gym.manage.checkIn.vo;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签到记录VO
|
||||||
|
*
|
||||||
|
* @author 付嘉
|
||||||
|
* @date 2026-06-08
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class SignInRecordVO {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签到记录ID
|
||||||
|
*/
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 会员ID
|
||||||
|
*/
|
||||||
|
private Long memberId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 会员卡ID
|
||||||
|
*/
|
||||||
|
private Long memberCardId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签到时间
|
||||||
|
*/
|
||||||
|
private LocalDateTime signInTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签到类型:QR_CODE-扫码签到,MANUAL-手动签到,FACE-人脸识别
|
||||||
|
*/
|
||||||
|
private String signInType;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签到状态:SUCCESS-成功,FAILED-失败
|
||||||
|
*/
|
||||||
|
private String signInStatus;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 失败原因
|
||||||
|
*/
|
||||||
|
private String failReason;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签到来源:MINI_PROGRAM-小程序扫码,PC_BACKEND-后台管理端
|
||||||
|
*/
|
||||||
|
private String source;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建时间
|
||||||
|
*/
|
||||||
|
private LocalDateTime createdAt;
|
||||||
|
}
|
||||||
+62
@@ -0,0 +1,62 @@
|
|||||||
|
package cn.novalon.gym.manage.checkIn.vo;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签到统计VO
|
||||||
|
*
|
||||||
|
* @author 付嘉
|
||||||
|
* @date 2026-06-08
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class SignInStatsVO {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计开始日期
|
||||||
|
*/
|
||||||
|
private LocalDate startDate;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计结束日期
|
||||||
|
*/
|
||||||
|
private LocalDate endDate;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 总签到次数
|
||||||
|
*/
|
||||||
|
private Long totalCount;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 成功签到次数
|
||||||
|
*/
|
||||||
|
private Long successCount;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 成功率(百分比)
|
||||||
|
*/
|
||||||
|
private Double successRate;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 独立会员数
|
||||||
|
*/
|
||||||
|
private Long uniqueMemberCount;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 首次签到时间
|
||||||
|
*/
|
||||||
|
private LocalDateTime firstSignInTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 最后签到时间
|
||||||
|
*/
|
||||||
|
private LocalDateTime lastSignInTime;
|
||||||
|
}
|
||||||
+202
@@ -0,0 +1,202 @@
|
|||||||
|
package cn.novalon.gym.manage.checkIn.websocket;
|
||||||
|
|
||||||
|
import cn.hutool.json.JSONUtil;
|
||||||
|
import cn.novalon.gym.manage.checkIn.dto.QRCodeDto;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
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 reactor.core.publisher.Sinks;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* WebSocket 处理类,用于实时签到反馈
|
||||||
|
*
|
||||||
|
* 技术要点:
|
||||||
|
* - 使用 Sinks 实现响应式消息推送
|
||||||
|
* - 使用 ConcurrentHashMap 管理 qrContent 与 sink 的映射
|
||||||
|
* - 支持实时推送签到进度和结果
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
public class MyWebSocketHandler implements WebSocketHandler {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* qrContent -> Sink 映射,用于根据二维码内容找到对应的客户端连接
|
||||||
|
*/
|
||||||
|
private static final Map<String, Sinks.Many<String>> qrContentToSink = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 连接创建时间映射,用于超时清理
|
||||||
|
*/
|
||||||
|
private static final Map<String, LocalDateTime> qrContentToCreateTime = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 超时时间(秒),超过此时间未使用的连接将被清理
|
||||||
|
*/
|
||||||
|
private static final long TIMEOUT_SECONDS = 300;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Mono<Void> handle(WebSocketSession session) {
|
||||||
|
String sessionId = session.getId();
|
||||||
|
log.info("WebSocket 连接建立,sessionId: {}", sessionId);
|
||||||
|
|
||||||
|
// 创建 sink,用于向客户端发送消息
|
||||||
|
Sinks.Many<String> sink = Sinks.many().unicast().onBackpressureBuffer();
|
||||||
|
|
||||||
|
// 订阅接收客户端消息(异步处理)
|
||||||
|
session.receive()
|
||||||
|
.doOnNext(message -> {
|
||||||
|
String payload = message.getPayloadAsText();
|
||||||
|
log.debug("收到消息:sessionId={}, payload={}", sessionId, payload);
|
||||||
|
|
||||||
|
try {
|
||||||
|
QRCodeDto qrCodeDto = JSONUtil.toBean(payload, QRCodeDto.class);
|
||||||
|
String qrContent = qrCodeDto.getQrContent();
|
||||||
|
|
||||||
|
if (qrContent != null && !qrContent.isEmpty()) {
|
||||||
|
// 绑定 qrContent 和 sink
|
||||||
|
qrContentToSink.put(qrContent, sink);
|
||||||
|
qrContentToCreateTime.put(qrContent, LocalDateTime.now());
|
||||||
|
log.info("绑定成功: qrContent={}, sessionId={}", qrContent, sessionId);
|
||||||
|
|
||||||
|
// 发送连接成功消息
|
||||||
|
sink.tryEmitNext(buildMessage("CONNECTED", "签到监听已建立,请扫描二维码"));
|
||||||
|
} else {
|
||||||
|
sink.tryEmitNext(buildMessage("ERROR", "二维码内容为空"));
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("解析消息失败,sessionId={}", sessionId, e);
|
||||||
|
sink.tryEmitNext(buildMessage("ERROR", "消息格式错误: " + e.getMessage()));
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.doOnError(e -> {
|
||||||
|
log.error("接收消息出错,sessionId={}", sessionId, e);
|
||||||
|
})
|
||||||
|
.subscribe(); // 必须订阅,否则不会执行
|
||||||
|
|
||||||
|
// 发送流给客户端
|
||||||
|
return session.send(sink.asFlux().map(session::textMessage))
|
||||||
|
.doFinally(signal -> {
|
||||||
|
// 连接关闭时清理映射
|
||||||
|
qrContentToSink.entrySet().removeIf(entry -> entry.getValue() == sink);
|
||||||
|
qrContentToCreateTime.entrySet().removeIf(entry -> {
|
||||||
|
Sinks.Many<String> s = qrContentToSink.get(entry.getKey());
|
||||||
|
return s == null || s == sink;
|
||||||
|
});
|
||||||
|
log.info("WebSocket 连接关闭,sessionId={}", sessionId);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 向客户端发送消息
|
||||||
|
*
|
||||||
|
* @param qrContent 二维码内容
|
||||||
|
* @param message 消息内容
|
||||||
|
* @return 是否发送成功
|
||||||
|
*/
|
||||||
|
public static boolean sendMessageToClient(String qrContent, String message) {
|
||||||
|
// 先清理超时连接
|
||||||
|
cleanupTimeoutConnections();
|
||||||
|
|
||||||
|
Sinks.Many<String> sink = qrContentToSink.get(qrContent);
|
||||||
|
if (sink == null) {
|
||||||
|
log.warn("未找到绑定的连接,qrContent: {}", qrContent);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
Sinks.EmitResult result = sink.tryEmitNext(message);
|
||||||
|
if (result.isSuccess()) {
|
||||||
|
log.info("主动推送成功,qrContent: {}, message: {}", qrContent, message);
|
||||||
|
return true;
|
||||||
|
} else {
|
||||||
|
log.warn("推送失败,qrContent: {}, result: {}", qrContent, result);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 发送签到进度消息
|
||||||
|
*
|
||||||
|
* @param qrContent 二维码内容
|
||||||
|
* @param step 进度步骤
|
||||||
|
* @param message 进度消息
|
||||||
|
*/
|
||||||
|
public static void sendProgress(String qrContent, String step, String message) {
|
||||||
|
String progressMessage = buildMessage("PROGRESS", message);
|
||||||
|
sendMessageToClient(qrContent, progressMessage);
|
||||||
|
log.debug("发送进度消息: qrContent={}, step={}, message={}", qrContent, step, message);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 发送签到成功消息
|
||||||
|
*
|
||||||
|
* @param qrContent 二维码内容
|
||||||
|
* @param memberId 会员ID
|
||||||
|
* @param signInTime 签到时间
|
||||||
|
*/
|
||||||
|
public static void sendSuccess(String qrContent, Long memberId, String signInTime) {
|
||||||
|
String successMessage = buildMessage("SUCCESS", "签到成功!欢迎光临\n会员ID: " + memberId + "\n签到时间: " + signInTime);
|
||||||
|
sendMessageToClient(qrContent, successMessage);
|
||||||
|
log.info("发送成功消息: qrContent={}, memberId={}", qrContent, memberId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 发送签到失败消息
|
||||||
|
*
|
||||||
|
* @param qrContent 二维码内容
|
||||||
|
* @param reason 失败原因
|
||||||
|
*/
|
||||||
|
public static void sendFailure(String qrContent, String reason) {
|
||||||
|
String failureMessage = buildMessage("FAILURE", "签到失败:" + reason);
|
||||||
|
sendMessageToClient(qrContent, failureMessage);
|
||||||
|
log.warn("发送失败消息: qrContent={}, reason={}", qrContent, reason);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构建标准消息格式
|
||||||
|
*
|
||||||
|
* @param type 消息类型
|
||||||
|
* @param content 消息内容
|
||||||
|
* @return 格式化后的消息字符串
|
||||||
|
*/
|
||||||
|
private static String buildMessage(String type, String content) {
|
||||||
|
return JSONUtil.toJsonStr(Map.of(
|
||||||
|
"type", type,
|
||||||
|
"content", content,
|
||||||
|
"timestamp", System.currentTimeMillis()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清理超时连接
|
||||||
|
*/
|
||||||
|
private static void cleanupTimeoutConnections() {
|
||||||
|
LocalDateTime now = LocalDateTime.now();
|
||||||
|
qrContentToCreateTime.entrySet().removeIf(entry -> {
|
||||||
|
LocalDateTime createTime = entry.getValue();
|
||||||
|
long secondsDiff = java.time.Duration.between(createTime, now).getSeconds();
|
||||||
|
if (secondsDiff > TIMEOUT_SECONDS) {
|
||||||
|
String qrContent = entry.getKey();
|
||||||
|
qrContentToSink.remove(qrContent);
|
||||||
|
log.debug("清理超时连接: qrContent={}, 超时时间={}秒", qrContent, secondsDiff);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取当前连接数
|
||||||
|
*
|
||||||
|
* @return 连接数
|
||||||
|
*/
|
||||||
|
public static int getConnectionCount() {
|
||||||
|
cleanupTimeoutConnections();
|
||||||
|
return qrContentToSink.size();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
# 二维码配置
|
||||||
|
qr:
|
||||||
|
config:
|
||||||
|
width: 300 # 二维码宽度(像素)
|
||||||
|
height: 300 # 二维码高度(像素)
|
||||||
|
margin: 1 # 白边宽度(像素)
|
||||||
|
format: png # 图片格式:png / jpg
|
||||||
|
error-correction: L #容错率:L, M, Q, H,如果启用Logo(logo-enabled: true),必须设置为 H
|
||||||
|
logo-enabled: false # 是否启用Logo(启用时error-correction必须为H)
|
||||||
|
# logo-path: static/logo.png # Logo图片路径(支持相对路径或绝对路径)
|
||||||
+287
@@ -0,0 +1,287 @@
|
|||||||
|
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;
|
||||||
|
import cn.novalon.gym.manage.checkIn.vo.SignInRecordVO;
|
||||||
|
import cn.novalon.gym.manage.checkIn.vo.SignInStatsVO;
|
||||||
|
import cn.novalon.gym.manage.common.constant.RedisKeyConstants;
|
||||||
|
import cn.novalon.gym.manage.common.util.RedisUtil;
|
||||||
|
import cn.novalon.gym.manage.member.entity.MemberCard;
|
||||||
|
import cn.novalon.gym.manage.member.entity.MemberCardRecord;
|
||||||
|
import cn.novalon.gym.manage.member.repository.MemberCardRecordRepository;
|
||||||
|
import cn.novalon.gym.manage.member.repository.MemberCardRepository;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.DisplayName;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.MockitoAnnotations;
|
||||||
|
import reactor.core.publisher.Flux;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
import reactor.test.StepVerifier;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.LocalTime;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签到模块接口测试类
|
||||||
|
* 测试模块三(gym-checkIn)的所有接口
|
||||||
|
*/
|
||||||
|
class CheckInModuleTest {
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private QRCodeConfig qrCodeConfig;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private RedisUtil redisUtil;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private MemberCardRecordRepository memberCardRecordRepository;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private MemberCardRepository memberCardRepository;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private SignInRecordRepository signInRecordRepository;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private IGroupCourseBookingService groupCourseBookingService;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private IGroupCourseBookingRepository groupCourseBookingRepository;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private MemberCard mockMemberCard;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private SignInRecord mockSignInRecord;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private MemberCardRecord mockMemberCardRecord;
|
||||||
|
|
||||||
|
private CheckServiceImpl checkService;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
MockitoAnnotations.openMocks(this);
|
||||||
|
checkService = new CheckServiceImpl(qrCodeConfig, redisUtil, memberCardRecordRepository,
|
||||||
|
memberCardRepository, signInRecordRepository, groupCourseBookingService,
|
||||||
|
groupCourseBookingRepository);
|
||||||
|
|
||||||
|
when(mockMemberCard.getId()).thenReturn(1L);
|
||||||
|
when(mockMemberCard.getMemberCardType()).thenReturn("TIME_CARD");
|
||||||
|
|
||||||
|
when(mockSignInRecord.getId()).thenReturn(1L);
|
||||||
|
when(mockSignInRecord.getMemberId()).thenReturn(1L);
|
||||||
|
when(mockSignInRecord.getMemberCardId()).thenReturn(1L);
|
||||||
|
when(mockSignInRecord.getSignInTime()).thenReturn(LocalDateTime.now());
|
||||||
|
when(mockSignInRecord.getSignInType()).thenReturn("QR_CODE");
|
||||||
|
when(mockSignInRecord.getSignInStatus()).thenReturn("SUCCESS");
|
||||||
|
when(mockSignInRecord.getSource()).thenReturn("MINI_PROGRAM");
|
||||||
|
|
||||||
|
when(mockMemberCardRecord.getMemberCardRecordId()).thenReturn(1L);
|
||||||
|
when(mockMemberCardRecord.getMemberCardId()).thenReturn(1L);
|
||||||
|
when(mockMemberCardRecord.getRemainingTimes()).thenReturn(10);
|
||||||
|
when(mockMemberCardRecord.getRemainingAmount()).thenReturn(100.0);
|
||||||
|
when(mockMemberCardRecord.getExpireTime()).thenReturn(LocalDateTime.now().plusDays(30));
|
||||||
|
when(mockMemberCardRecord.getStatus()).thenReturn(cn.novalon.gym.manage.member.enums.MemberCardRecordStatus.ACTIVE);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("测试1: 获取二维码 - getQRCode")
|
||||||
|
void testGetQRCode() {
|
||||||
|
when(memberCardRecordRepository.findActiveCardsByMemberId(1L))
|
||||||
|
.thenReturn(Flux.just(mockMemberCardRecord));
|
||||||
|
when(redisUtil.setWithExpire(any(String.class), any(Map.class), any(Long.class)))
|
||||||
|
.thenReturn(Mono.just(true));
|
||||||
|
|
||||||
|
Mono<QRCodeVo> result = checkService.getQRCode(1L);
|
||||||
|
|
||||||
|
StepVerifier.create(result)
|
||||||
|
.expectNextMatches(qrCodeVo -> {
|
||||||
|
org.junit.jupiter.api.Assertions.assertNotNull(qrCodeVo);
|
||||||
|
org.junit.jupiter.api.Assertions.assertNotNull(qrCodeVo.getQrContent());
|
||||||
|
return true;
|
||||||
|
})
|
||||||
|
.verifyComplete();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("测试2: 签到 - checkIn")
|
||||||
|
void testCheckIn() {
|
||||||
|
Long memberId = 1L;
|
||||||
|
Map<String, Object> qrData = new HashMap<>();
|
||||||
|
qrData.put("qrContent", "test-qr-content");
|
||||||
|
qrData.put("memberId", memberId);
|
||||||
|
qrData.put("memberCardRecordId", 1L);
|
||||||
|
qrData.put("isUsed", false);
|
||||||
|
qrData.put("expireTime", System.currentTimeMillis() + 3600000);
|
||||||
|
|
||||||
|
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));
|
||||||
|
when(redisUtil.set(any(String.class), any(Map.class))).thenReturn(Mono.just(true));
|
||||||
|
when(groupCourseBookingService.getBookingsByMemberId(memberId)).thenReturn(Flux.empty());
|
||||||
|
when(signInRecordRepository.findByMemberIdAndDate(eq(memberId), any(LocalDateTime.class), any(LocalDateTime.class)))
|
||||||
|
.thenReturn(Mono.empty());
|
||||||
|
|
||||||
|
Mono<String> result = checkService.checkIn(memberId, "test-qr-content");
|
||||||
|
|
||||||
|
StepVerifier.create(result)
|
||||||
|
.expectNextMatches(response -> response.contains("签到成功"))
|
||||||
|
.verifyComplete();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("测试3: 查询签到记录列表 - getSignInRecords")
|
||||||
|
void testGetSignInRecords() {
|
||||||
|
when(signInRecordRepository.findByMemberIdAndTimeRange(
|
||||||
|
eq(1L), any(LocalDateTime.class), any(LocalDateTime.class)))
|
||||||
|
.thenReturn(Flux.just(mockSignInRecord));
|
||||||
|
|
||||||
|
Flux<SignInRecordVO> result = checkService.getSignInRecords(1L,
|
||||||
|
LocalDate.now().minusDays(30), LocalDate.now());
|
||||||
|
|
||||||
|
StepVerifier.create(result)
|
||||||
|
.expectNextCount(1)
|
||||||
|
.verifyComplete();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("测试4: 查询单条签到记录 - getSignInRecordById")
|
||||||
|
void testGetSignInRecordById() {
|
||||||
|
when(signInRecordRepository.findById(1L))
|
||||||
|
.thenReturn(Mono.just(mockSignInRecord));
|
||||||
|
|
||||||
|
Mono<SignInRecordVO> result = checkService.getSignInRecordById(1L);
|
||||||
|
|
||||||
|
StepVerifier.create(result)
|
||||||
|
.expectNextMatches(vo -> vo.getId() == 1L)
|
||||||
|
.verifyComplete();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("测试5: 查询签到记录 - 记录不存在")
|
||||||
|
void testGetSignInRecordById_NotFound() {
|
||||||
|
when(signInRecordRepository.findById(999L))
|
||||||
|
.thenReturn(Mono.empty());
|
||||||
|
|
||||||
|
Mono<SignInRecordVO> result = checkService.getSignInRecordById(999L);
|
||||||
|
|
||||||
|
StepVerifier.create(result)
|
||||||
|
.verifyComplete();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("测试6: 获取签到统计 - getSignInStats")
|
||||||
|
void testGetSignInStats() {
|
||||||
|
when(signInRecordRepository.countByMemberIdAndTimeRange(
|
||||||
|
eq(1L), any(LocalDateTime.class), any(LocalDateTime.class)))
|
||||||
|
.thenReturn(Mono.just(10L));
|
||||||
|
when(signInRecordRepository.countSuccessByMemberIdAndTimeRange(
|
||||||
|
eq(1L), any(LocalDateTime.class), any(LocalDateTime.class)))
|
||||||
|
.thenReturn(Mono.just(8L));
|
||||||
|
when(signInRecordRepository.getFirstSignInTime(
|
||||||
|
eq(1L), any(LocalDateTime.class), any(LocalDateTime.class)))
|
||||||
|
.thenReturn(Mono.just(LocalDateTime.now().minusDays(29)));
|
||||||
|
when(signInRecordRepository.getLastSignInTime(
|
||||||
|
eq(1L), any(LocalDateTime.class), any(LocalDateTime.class)))
|
||||||
|
.thenReturn(Mono.just(LocalDateTime.now()));
|
||||||
|
|
||||||
|
Mono<SignInStatsVO> result = checkService.getSignInStats(1L,
|
||||||
|
LocalDate.now().minusDays(30), LocalDate.now());
|
||||||
|
|
||||||
|
StepVerifier.create(result)
|
||||||
|
.expectNextMatches(stats -> {
|
||||||
|
org.junit.jupiter.api.Assertions.assertEquals(10L, stats.getTotalCount());
|
||||||
|
org.junit.jupiter.api.Assertions.assertEquals(8L, stats.getSuccessCount());
|
||||||
|
return true;
|
||||||
|
})
|
||||||
|
.verifyComplete();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("测试7: 获取每日签到统计 - getDailySignInStats")
|
||||||
|
void testGetDailySignInStats() {
|
||||||
|
when(signInRecordRepository.countByTimeRange(any(LocalDateTime.class), any(LocalDateTime.class)))
|
||||||
|
.thenReturn(Mono.just(50L));
|
||||||
|
when(signInRecordRepository.countSuccessByTimeRange(
|
||||||
|
any(LocalDateTime.class), any(LocalDateTime.class)))
|
||||||
|
.thenReturn(Mono.just(45L));
|
||||||
|
when(signInRecordRepository.countDistinctMembersByTimeRange(
|
||||||
|
any(LocalDateTime.class), any(LocalDateTime.class)))
|
||||||
|
.thenReturn(Mono.just(30L));
|
||||||
|
|
||||||
|
Mono<SignInStatsVO> result = checkService.getDailySignInStats(LocalDate.now());
|
||||||
|
|
||||||
|
StepVerifier.create(result)
|
||||||
|
.expectNextMatches(stats -> {
|
||||||
|
org.junit.jupiter.api.Assertions.assertEquals(50L, stats.getTotalCount());
|
||||||
|
org.junit.jupiter.api.Assertions.assertEquals(45L, stats.getSuccessCount());
|
||||||
|
org.junit.jupiter.api.Assertions.assertEquals(30L, stats.getUniqueMemberCount());
|
||||||
|
return true;
|
||||||
|
})
|
||||||
|
.verifyComplete();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("测试8: 导出签到记录 - exportSignInRecords")
|
||||||
|
void testExportSignInRecords() {
|
||||||
|
when(signInRecordRepository.findByMemberIdAndTimeRange(
|
||||||
|
eq(1L), any(LocalDateTime.class), any(LocalDateTime.class)))
|
||||||
|
.thenReturn(Flux.just(mockSignInRecord));
|
||||||
|
|
||||||
|
Mono<byte[]> result = checkService.exportSignInRecords(1L,
|
||||||
|
LocalDate.now().minusDays(7), LocalDate.now());
|
||||||
|
|
||||||
|
StepVerifier.create(result)
|
||||||
|
.expectNextMatches(bytes -> bytes.length > 0)
|
||||||
|
.verifyComplete();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("测试9: 签到失败 - 二维码无效")
|
||||||
|
void testCheckIn_QRCodeInvalid() {
|
||||||
|
Long memberId = 1L;
|
||||||
|
String key = RedisKeyConstants.QRCODE_USER_DAILY + memberId + LocalDate.now();
|
||||||
|
when(redisUtil.get(eq(key))).thenReturn(Mono.just(new HashMap<>()));
|
||||||
|
when(signInRecordRepository.findByMemberIdAndDate(eq(memberId), any(LocalDateTime.class), any(LocalDateTime.class)))
|
||||||
|
.thenReturn(Mono.empty());
|
||||||
|
|
||||||
|
Mono<String> result = checkService.checkIn(memberId, "invalid-qr");
|
||||||
|
|
||||||
|
StepVerifier.create(result)
|
||||||
|
.expectError(RuntimeException.class)
|
||||||
|
.verify();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("测试10: 签到失败 - 二维码不存在")
|
||||||
|
void testCheckIn_QRCodeNotFound() {
|
||||||
|
Long memberId = 1L;
|
||||||
|
String key = RedisKeyConstants.QRCODE_USER_DAILY + memberId + LocalDate.now();
|
||||||
|
when(redisUtil.get(eq(key))).thenReturn(Mono.empty());
|
||||||
|
when(signInRecordRepository.findByMemberIdAndDate(eq(memberId), any(LocalDateTime.class), any(LocalDateTime.class)))
|
||||||
|
.thenReturn(Mono.empty());
|
||||||
|
|
||||||
|
Mono<String> result = checkService.checkIn(memberId, "not-exist");
|
||||||
|
|
||||||
|
StepVerifier.create(result)
|
||||||
|
.verifyComplete();
|
||||||
|
}
|
||||||
|
}
|
||||||
+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 @@
|
|||||||
|
# Test Configuration
|
||||||
@@ -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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
HELP.md
|
||||||
|
target/
|
||||||
|
.mvn/wrapper/maven-wrapper.jar
|
||||||
|
!**/src/main/**/target/
|
||||||
|
!**/src/test/**/target/
|
||||||
|
|
||||||
|
### STS ###
|
||||||
|
.apt_generated
|
||||||
|
.classpath
|
||||||
|
.factorypath
|
||||||
|
.project
|
||||||
|
.settings
|
||||||
|
.springBeans
|
||||||
|
.sts4-cache
|
||||||
|
|
||||||
|
### IntelliJ IDEA ###
|
||||||
|
.idea
|
||||||
|
*.iws
|
||||||
|
*.iml
|
||||||
|
*.ipr
|
||||||
|
|
||||||
|
### NetBeans ###
|
||||||
|
/nbproject/private/
|
||||||
|
/nbbuild/
|
||||||
|
/dist/
|
||||||
|
/nbdist/
|
||||||
|
/.nb-gradle/
|
||||||
|
build/
|
||||||
|
!**/src/main/**/build/
|
||||||
|
!**/src/test/**/build/
|
||||||
|
|
||||||
|
### VS Code ###
|
||||||
|
.vscode/
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
wrapperVersion=3.3.4
|
||||||
|
distributionType=only-script
|
||||||
|
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.16/apache-maven-3.9.16-bin.zip
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
<?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 https://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>
|
||||||
|
<relativePath>../pom.xml</relativePath>
|
||||||
|
</parent>
|
||||||
|
<groupId>cn.novalon.gym.manage</groupId>
|
||||||
|
<artifactId>gym-dataCount</artifactId>
|
||||||
|
<version>1.0.0</version>
|
||||||
|
<name>gym-dataCount</name>
|
||||||
|
<description>Data Statistics Module for Gym Management</description>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<java.version>21</java.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<!-- Common模块 -->
|
||||||
|
<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>
|
||||||
|
|
||||||
|
<!-- WebFlux -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-webflux</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- R2dbc -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-data-r2dbc</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- Redis -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-data-redis</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- Validation -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-validation</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- Swagger -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springdoc</groupId>
|
||||||
|
<artifactId>springdoc-openapi-starter-webflux-ui</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- POI for Excel export -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.poi</groupId>
|
||||||
|
<artifactId>poi-ooxml</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- Fix commons-compress version for POI compatibility -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.commons</groupId>
|
||||||
|
<artifactId>commons-compress</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- Gym Modules -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>cn.novalon.gym.manage</groupId>
|
||||||
|
<artifactId>gym-member</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-checkIn</artifactId>
|
||||||
|
<version>${project.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- Test -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-test</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<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>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</project>
|
||||||
+15
@@ -0,0 +1,15 @@
|
|||||||
|
package cn.novalon.gym.manage.datacount.config;
|
||||||
|
|
||||||
|
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||||
|
import org.springframework.context.annotation.ComponentScan;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 数据统计模块自动配置
|
||||||
|
*
|
||||||
|
* @author system
|
||||||
|
* @date 2026-06-09
|
||||||
|
*/
|
||||||
|
@AutoConfiguration
|
||||||
|
@ComponentScan(basePackages = "cn.novalon.gym.manage.datacount")
|
||||||
|
public class DataCountAutoConfiguration {
|
||||||
|
}
|
||||||
+355
@@ -0,0 +1,355 @@
|
|||||||
|
package cn.novalon.gym.manage.datacount.dao;
|
||||||
|
|
||||||
|
import org.springframework.r2dbc.core.DatabaseClient;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
import reactor.core.publisher.Flux;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 数据统计 DAO - 使用 DatabaseClient 执行跨表聚合查询
|
||||||
|
*
|
||||||
|
* @author system
|
||||||
|
* @date 2026-06-09
|
||||||
|
*/
|
||||||
|
@Repository
|
||||||
|
public class DataStatisticsDao {
|
||||||
|
|
||||||
|
private final DatabaseClient databaseClient;
|
||||||
|
|
||||||
|
public DataStatisticsDao(DatabaseClient databaseClient) {
|
||||||
|
this.databaseClient = databaseClient;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计指定时间范围内新增会员数
|
||||||
|
*/
|
||||||
|
public Mono<Long> countNewMembers(LocalDateTime startTime, LocalDateTime endTime) {
|
||||||
|
return databaseClient.sql("SELECT COUNT(*) FROM member_user WHERE created_at >= :startTime AND created_at < :endTime AND is_deleted = false")
|
||||||
|
.bind("startTime", startTime)
|
||||||
|
.bind("endTime", endTime)
|
||||||
|
.map(row -> row.get(0, Long.class))
|
||||||
|
.one();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计总会员数
|
||||||
|
*/
|
||||||
|
public Mono<Long> countTotalMembers() {
|
||||||
|
return databaseClient.sql("SELECT COUNT(*) FROM member_user WHERE is_deleted = false")
|
||||||
|
.map(row -> row.get(0, Long.class))
|
||||||
|
.one();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计指定时间范围内的签到次数
|
||||||
|
*/
|
||||||
|
public Mono<Long> countSignIns(LocalDateTime startTime, LocalDateTime endTime) {
|
||||||
|
return databaseClient.sql("SELECT COUNT(*) FROM sign_in_record WHERE sign_in_time >= :startTime AND sign_in_time < :endTime AND is_delete = false")
|
||||||
|
.bind("startTime", startTime)
|
||||||
|
.bind("endTime", endTime)
|
||||||
|
.map(row -> row.get(0, Long.class))
|
||||||
|
.one();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计指定时间范围内的成功签到次数
|
||||||
|
*/
|
||||||
|
public Mono<Long> countSuccessSignIns(LocalDateTime startTime, LocalDateTime endTime) {
|
||||||
|
return databaseClient.sql("SELECT COUNT(*) FROM sign_in_record WHERE sign_in_time >= :startTime AND sign_in_time < :endTime AND sign_in_status = 'SUCCESS' AND is_delete = false")
|
||||||
|
.bind("startTime", startTime)
|
||||||
|
.bind("endTime", endTime)
|
||||||
|
.map(row -> row.get(0, Long.class))
|
||||||
|
.one();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计指定时间范围内签到的独立会员数
|
||||||
|
*/
|
||||||
|
public Mono<Long> countDistinctSignInMembers(LocalDateTime startTime, LocalDateTime endTime) {
|
||||||
|
return databaseClient.sql("SELECT COUNT(DISTINCT member_id) FROM sign_in_record WHERE sign_in_time >= :startTime AND sign_in_time < :endTime AND is_delete = false")
|
||||||
|
.bind("startTime", startTime)
|
||||||
|
.bind("endTime", endTime)
|
||||||
|
.map(row -> row.get(0, Long.class))
|
||||||
|
.one();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计指定时间范围内的预约数
|
||||||
|
*/
|
||||||
|
public Mono<Long> countBookings(LocalDateTime startTime, LocalDateTime endTime) {
|
||||||
|
return databaseClient.sql("SELECT COUNT(*) FROM group_course_booking WHERE booking_time >= :startTime AND booking_time < :endTime AND deleted_at IS NULL")
|
||||||
|
.bind("startTime", startTime)
|
||||||
|
.bind("endTime", endTime)
|
||||||
|
.map(row -> row.get(0, Long.class))
|
||||||
|
.one();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计指定时间范围内的取消预约数
|
||||||
|
*/
|
||||||
|
public Mono<Long> countCancelBookings(LocalDateTime startTime, LocalDateTime endTime) {
|
||||||
|
return databaseClient.sql("SELECT COUNT(*) FROM group_course_booking WHERE booking_time >= :startTime AND booking_time < :endTime AND status = '1' AND deleted_at IS NULL")
|
||||||
|
.bind("startTime", startTime)
|
||||||
|
.bind("endTime", endTime)
|
||||||
|
.map(row -> row.get(0, Long.class))
|
||||||
|
.one();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计指定时间范围内的出席预约数
|
||||||
|
*/
|
||||||
|
public Mono<Long> countAttendBookings(LocalDateTime startTime, LocalDateTime endTime) {
|
||||||
|
return databaseClient.sql("SELECT COUNT(*) FROM group_course_booking WHERE booking_time >= :startTime AND booking_time < :endTime AND status = '2' AND deleted_at IS NULL")
|
||||||
|
.bind("startTime", startTime)
|
||||||
|
.bind("endTime", endTime)
|
||||||
|
.map(row -> row.get(0, Long.class))
|
||||||
|
.one();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计指定时间范围内的缺席预约数
|
||||||
|
*/
|
||||||
|
public Mono<Long> countAbsentBookings(LocalDateTime startTime, LocalDateTime endTime) {
|
||||||
|
return databaseClient.sql("SELECT COUNT(*) FROM group_course_booking WHERE booking_time >= :startTime AND booking_time < :endTime AND status = '3' AND deleted_at IS NULL")
|
||||||
|
.bind("startTime", startTime)
|
||||||
|
.bind("endTime", endTime)
|
||||||
|
.map(row -> row.get(0, Long.class))
|
||||||
|
.one();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计指定时间范围内有预约的独立会员数
|
||||||
|
*/
|
||||||
|
public Mono<Long> countDistinctBookingMembers(LocalDateTime startTime, LocalDateTime endTime) {
|
||||||
|
return databaseClient.sql("SELECT COUNT(DISTINCT member_id) FROM group_course_booking WHERE booking_time >= :startTime AND booking_time < :endTime AND deleted_at IS NULL")
|
||||||
|
.bind("startTime", startTime)
|
||||||
|
.bind("endTime", endTime)
|
||||||
|
.map(row -> row.get(0, Long.class))
|
||||||
|
.one();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计指定时间范围内取消预约的独立会员数
|
||||||
|
*/
|
||||||
|
public Mono<Long> countDistinctCancelMembers(LocalDateTime startTime, LocalDateTime endTime) {
|
||||||
|
return databaseClient.sql("SELECT COUNT(DISTINCT member_id) FROM group_course_booking WHERE booking_time >= :startTime AND booking_time < :endTime AND status = '1' AND deleted_at IS NULL")
|
||||||
|
.bind("startTime", startTime)
|
||||||
|
.bind("endTime", endTime)
|
||||||
|
.map(row -> row.get(0, Long.class))
|
||||||
|
.one();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 按签到类型统计次数
|
||||||
|
*/
|
||||||
|
public Flux<SignInTypeCount> countSignInsByType(LocalDateTime startTime, LocalDateTime endTime) {
|
||||||
|
return databaseClient.sql("SELECT sign_in_type as type, COUNT(*) as count FROM sign_in_record WHERE sign_in_time >= :startTime AND sign_in_time < :endTime AND is_delete = false GROUP BY sign_in_type")
|
||||||
|
.bind("startTime", startTime)
|
||||||
|
.bind("endTime", endTime)
|
||||||
|
.map(row -> {
|
||||||
|
SignInTypeCount result = new SignInTypeCount();
|
||||||
|
result.setType(row.get("type", String.class));
|
||||||
|
result.setCount(row.get("count", Long.class));
|
||||||
|
return result;
|
||||||
|
})
|
||||||
|
.all();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签到类型计数结果
|
||||||
|
*/
|
||||||
|
public static class SignInTypeCount {
|
||||||
|
private String type;
|
||||||
|
private Long count;
|
||||||
|
|
||||||
|
public String getType() {
|
||||||
|
return type;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setType(String type) {
|
||||||
|
this.type = type;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getCount() {
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCount(Long count) {
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
+64
@@ -0,0 +1,64 @@
|
|||||||
|
package cn.novalon.gym.manage.datacount.domain;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 预约数据统计结果
|
||||||
|
*
|
||||||
|
* @author system
|
||||||
|
* @date 2026-06-09
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class BookingStatistics {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计日期
|
||||||
|
*/
|
||||||
|
private String statDate;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 新增预约数
|
||||||
|
*/
|
||||||
|
private Long newBookings;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 取消预约数
|
||||||
|
*/
|
||||||
|
private Long cancelBookings;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 出席预约数
|
||||||
|
*/
|
||||||
|
private Long attendBookings;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 缺席预约数
|
||||||
|
*/
|
||||||
|
private Long absentBookings;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 预约出席率
|
||||||
|
*/
|
||||||
|
private Double attendanceRate;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 取消率
|
||||||
|
*/
|
||||||
|
private Double cancelRate;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 预约人数(独立会员数)
|
||||||
|
*/
|
||||||
|
private Long bookingMembers;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 取消人数(独立会员数)
|
||||||
|
*/
|
||||||
|
private Long cancelMembers;
|
||||||
|
}
|
||||||
+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;
|
||||||
|
}
|
||||||
+85
@@ -0,0 +1,85 @@
|
|||||||
|
package cn.novalon.gym.manage.datacount.domain;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 数据统计结果域对象
|
||||||
|
*
|
||||||
|
* @author system
|
||||||
|
* @date 2026-06-09
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class DataStatistics {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计类型:MEMBER-会员统计,BOOKING-预约统计,SIGN_IN-签到统计
|
||||||
|
*/
|
||||||
|
private String statType;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计周期:DAY-日统计,WEEK-周统计,MONTH-月统计
|
||||||
|
*/
|
||||||
|
private String periodType;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计日期(DAY时为具体日期,WEEK时为周开始日期,MONTH时为月份第一天)
|
||||||
|
*/
|
||||||
|
private LocalDateTime statDate;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计数据值
|
||||||
|
*/
|
||||||
|
private Long count;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 关联ID(如会员ID等)
|
||||||
|
*/
|
||||||
|
private Long relatedId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 扩展数据(JSON格式存储额外信息)
|
||||||
|
*/
|
||||||
|
private String extraData;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计周期常量
|
||||||
|
*/
|
||||||
|
public static final class PeriodType {
|
||||||
|
/** 日统计 */
|
||||||
|
public static final String DAY = "DAY";
|
||||||
|
/** 周统计 */
|
||||||
|
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() {}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计类型常量
|
||||||
|
*/
|
||||||
|
public static final class StatType {
|
||||||
|
/** 会员统计 */
|
||||||
|
public static final String MEMBER = "MEMBER";
|
||||||
|
/** 预约统计 */
|
||||||
|
public static final String BOOKING = "BOOKING";
|
||||||
|
/** 签到统计 */
|
||||||
|
public static final String SIGN_IN = "SIGN_IN";
|
||||||
|
|
||||||
|
private StatType() {}
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user