Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
af2422c114 |
@@ -1,82 +0,0 @@
|
||||
# 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
@@ -1,143 +0,0 @@
|
||||
# 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_: 校验码
|
||||
@@ -1 +0,0 @@
|
||||
{"code":404,"message":"No static resource files/30/preview.","timestamp":"2026-07-22T18:27:23.0606736"}
|
||||
@@ -1,106 +0,0 @@
|
||||
# 全面端到端测试报告
|
||||
|
||||
## 测试概要
|
||||
|
||||
| 项目 | 值 |
|
||||
|------|-----|
|
||||
| 测试时间 | 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 一致。
|
||||
@@ -1,144 +0,0 @@
|
||||
# 全面端到端测试报告(含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` 字段直接获取(已验证可用)。
|
||||
@@ -1,58 +0,0 @@
|
||||
# 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:自定义日期范围
|
||||
@@ -1,202 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,98 +0,0 @@
|
||||
# ADR-0001: 教练业绩统计功能设计
|
||||
|
||||
**日期**: 2026-07-22
|
||||
**状态**: 已决定
|
||||
**决策者**: 通过 grill-with-docs 追问明确
|
||||
|
||||
---
|
||||
|
||||
## 背景
|
||||
|
||||
需要在后台管理系统中为体育馆新增"教练业绩统计"功能。现有系统已有 `gym-dataCount` 模块提供全局统计(含教练违规统计 `CoachStatistics`),但缺少**按教练维度**的业绩数据(授课量、出勤率、满员率等正向指标)。
|
||||
|
||||
---
|
||||
|
||||
## 决策
|
||||
|
||||
### 1. 架构:扩展现有 gym-dataCount 模块
|
||||
|
||||
**选择**: 在 `gym-dataCount` 模块中新增 CoachPerformance 相关的 Handler + Service + DAO,而非新建独立模块。
|
||||
|
||||
**理由**:
|
||||
- `gym-dataCount` 模块已有成熟的统计架构(DatabaseClient + Reactive + Redis 缓存 + 时间范围推导)
|
||||
- 现有 `DataStatisticsDao` 已有教练相关的 SQL 聚合查询,可直接复用
|
||||
- 避免模块膨胀,将"统计"职责收敛在一个模块中
|
||||
- `manage-app` 已依赖 `gym-dataCount`,路由注册零成本
|
||||
|
||||
**替代方案被拒绝**: 新建 `gym-coach-performance` 独立模块。理由:功能规模不足以支撑独立模块,且会引入额外的模块间依赖管理成本。
|
||||
|
||||
### 2. 数据源:完全基于团课预约数据
|
||||
|
||||
**选择**: 业绩统计的"出席人次"和"出勤率"完全基于 `group_course_booking` 表(status='2'=已出席),而非 `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. 满员率:按出席人数计算
|
||||
|
||||
**选择**: 满员率 = 各课程(出席人数 / max_members)的平均值。
|
||||
|
||||
**拒绝的定义**: 按预约人数(current_members)计算。理由:预约了但没来的学员不能算"满员",出席人数更真实地反映了课程实际到场情况。
|
||||
|
||||
### 5. 综合评分权重:授课量 40% + 出勤率 30% + 满员率 30%
|
||||
|
||||
**选择**: 授课量占比最高,体现工作量;出勤率和满员率体现教学质量。
|
||||
|
||||
**归一化规则**: 授课量按所有教练中最大值归一化到 0-100。这样即使只有少数教练开课多,评分也能合理分布。
|
||||
|
||||
**拒绝的替代方案**:
|
||||
- 三指标等权重(33/33/34):弱化了工作量差异
|
||||
- 授课量 50%:过度强调数量而忽视质量
|
||||
|
||||
### 6. 不包含学员留存率
|
||||
|
||||
**选择**: 首版不计算学员留存率。
|
||||
|
||||
**理由**: 现有系统缺少"学员持续上课"的显式数据模型。要实现留存率需要定义"留存"的判定规则(如:连续两个月以上预约同一教练的课程),这会引入新的领域概念,增加首版复杂度。
|
||||
|
||||
---
|
||||
|
||||
## 影响
|
||||
|
||||
### 后端变更
|
||||
- `gym-dataCount` 模块新增:`CoachPerformance` domain、`CoachPerformanceHandler`、`CoachPerformanceDao`
|
||||
- `manage-app` 的 `SystemRouter` 中新增 2 条路由
|
||||
|
||||
### 前端变更
|
||||
- `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 模块。
|
||||
- 优点:职责隔离清晰
|
||||
- 缺点:模块碎片化,增加编译和依赖管理成本
|
||||
@@ -14,7 +14,6 @@
|
||||
3. [团课管理接口](#团课管理接口)
|
||||
- [获取所有团课](#获取所有团课)
|
||||
- [分页获取团课](#分页获取团课)
|
||||
- [多条件查询团课](#多条件查询团课)
|
||||
- [根据ID获取团课详情](#根据ID获取团课详情)
|
||||
- [创建团课](#创建团课)
|
||||
- [更新团课](#更新团课)
|
||||
@@ -155,149 +154,6 @@
|
||||
|
||||
---
|
||||
|
||||
### 多条件查询团课
|
||||
|
||||
| 属性 | 值 |
|
||||
|------|-----|
|
||||
| **HTTP方法** | POST |
|
||||
| **接口路径** | `/api/groupCourse/search` |
|
||||
| **所属文件** | `GroupCourseHandler.java` |
|
||||
|
||||
**功能说明**: 支持团课名称模糊查询、类型筛选、日期范围、时间段、价格排序、剩余名额排序等多条件组合查询,默认不查询不可预约的团课(已取消或已结束)。
|
||||
|
||||
**请求体**:
|
||||
|
||||
```json
|
||||
{
|
||||
"courseName": "瑜伽",
|
||||
"courseType": 1,
|
||||
"startDate": "2026-06-01T00:00:00",
|
||||
"endDate": "2026-06-30T23:59:59",
|
||||
"timePeriod": "morning",
|
||||
"priceSort": "asc",
|
||||
"remainingMost": true,
|
||||
"page": 0,
|
||||
"size": 10
|
||||
}
|
||||
```
|
||||
|
||||
| 参数名 | 类型 | 必填 | 默认值 | 说明 |
|
||||
|--------|------|------|--------|------|
|
||||
| courseName | String | 否 | - | 课程名称(模糊查询,不区分大小写) |
|
||||
| courseType | Long | 否 | - | 课程类型ID |
|
||||
| startDate | LocalDateTime | 否 | - | 查询开始日期 |
|
||||
| endDate | LocalDateTime | 否 | - | 查询结束日期 |
|
||||
| timePeriod | String | 否 | - | 时间段:`morning`(6:00-12:00)、`afternoon`(12:00-18:00)、`evening`(18:00-24:00) |
|
||||
| priceSort | String | 否 | - | 价格排序:`asc`(从低到高)、`desc`(从高到低) |
|
||||
| remainingMost | Boolean | 否 | false | 是否按剩余名额最多排序 |
|
||||
| page | Integer | 否 | 0 | 页码,从0开始 |
|
||||
| size | Integer | 否 | 10 | 每页数量,最大100 |
|
||||
|
||||
**查询条件优先级说明**:
|
||||
|
||||
| 优先级 | 条件类型 | 说明 |
|
||||
|--------|----------|------|
|
||||
| 1 | 默认过滤 | 自动过滤已删除和不可预约的团课(status != 0) |
|
||||
| 2 | 基础筛选 | courseName、courseType、startDate、endDate、timePeriod |
|
||||
| 3 | 排序规则 | remainingMost优先,其次priceSort,默认按startTime升序 |
|
||||
|
||||
**成功响应** (200 OK):
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"message": "查询成功",
|
||||
"data": {
|
||||
"content": [
|
||||
{
|
||||
"id": 1,
|
||||
"courseName": "瑜伽入门",
|
||||
"coachId": 1,
|
||||
"courseType": 1,
|
||||
"startTime": "2026-06-15T09:00:00",
|
||||
"endTime": "2026-06-15T10:00:00",
|
||||
"maxMembers": 20,
|
||||
"currentMembers": 5,
|
||||
"status": 0,
|
||||
"location": "健身房A区",
|
||||
"coverImage": "https://example.com/yoga.jpg",
|
||||
"description": "适合初学者的瑜伽课程",
|
||||
"pointCardAmount": 1,
|
||||
"storedValueAmount": 50.00,
|
||||
"createdAt": "2026-06-01T10:00:00",
|
||||
"updatedAt": "2026-06-01T10:00:00"
|
||||
}
|
||||
],
|
||||
"totalPages": 3,
|
||||
"totalElements": 25,
|
||||
"currentPage": 0,
|
||||
"pageSize": 10,
|
||||
"first": true,
|
||||
"last": false
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**失败响应** (400 Bad Request):
|
||||
|
||||
```json
|
||||
{
|
||||
"success": false,
|
||||
"message": "查询失败的原因"
|
||||
}
|
||||
```
|
||||
|
||||
**使用示例**:
|
||||
|
||||
1. **查询瑜伽课程**
|
||||
```json
|
||||
{
|
||||
"courseName": "瑜伽"
|
||||
}
|
||||
```
|
||||
|
||||
2. **查询特定类型的早晨课程**
|
||||
```json
|
||||
{
|
||||
"courseType": 1,
|
||||
"timePeriod": "morning"
|
||||
}
|
||||
```
|
||||
|
||||
3. **查询下周的课程,按价格从低到高排序**
|
||||
```json
|
||||
{
|
||||
"startDate": "2026-06-16T00:00:00",
|
||||
"endDate": "2026-06-22T23:59:59",
|
||||
"priceSort": "asc"
|
||||
}
|
||||
```
|
||||
|
||||
4. **查询剩余名额最多的晚间课程**
|
||||
```json
|
||||
{
|
||||
"timePeriod": "evening",
|
||||
"remainingMost": true
|
||||
}
|
||||
```
|
||||
|
||||
5. **多条件组合查询**
|
||||
```json
|
||||
{
|
||||
"courseName": "瑜伽",
|
||||
"courseType": 1,
|
||||
"startDate": "2026-06-01T00:00:00",
|
||||
"endDate": "2026-06-30T23:59:59",
|
||||
"timePeriod": "morning",
|
||||
"priceSort": "asc",
|
||||
"remainingMost": true,
|
||||
"page": 0,
|
||||
"size": 10
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 根据ID获取团课详情
|
||||
|
||||
| 属性 | 值 |
|
||||
@@ -604,26 +460,26 @@
|
||||
| 属性 | 值 |
|
||||
|------|-----|
|
||||
| **HTTP方法** | POST |
|
||||
| **接口路径** | `/api/groupCourse/signin/{memberId}` |
|
||||
| **接口路径** | `/api/groupCourse/{courseId}/signin` |
|
||||
| **所属文件** | `GroupCourseHandler.java` |
|
||||
|
||||
**路径参数**:
|
||||
|
||||
| 参数名 | 类型 | 必填 | 说明 |
|
||||
|--------|------|------|------|
|
||||
| memberId | Long | 是 | 会员ID |
|
||||
| courseId | Long | 是 | 团课ID |
|
||||
|
||||
**请求体**:
|
||||
|
||||
```json
|
||||
{
|
||||
"courseId": 1
|
||||
"memberId": 1001
|
||||
}
|
||||
```
|
||||
|
||||
| 参数名 | 类型 | 必填 | 说明 |
|
||||
|--------|------|------|------|
|
||||
| courseId | Long | **是** | 团课ID |
|
||||
| memberId | Long | **是** | 会员ID |
|
||||
|
||||
**成功响应** (200 OK):
|
||||
|
||||
@@ -638,39 +494,16 @@
|
||||
}
|
||||
```
|
||||
|
||||
**失败响应** (400 Bad Request) —— 校验规则及对应错误信息:
|
||||
|
||||
| 序号 | 校验规则 | 错误信息 |
|
||||
|------|----------|----------|
|
||||
| 1 | 团课不存在或已被删除 | `团课不存在或已删除` |
|
||||
| 2 | 团课状态为"已取消" | `团课已取消,无法签到` |
|
||||
| 3 | 团课状态为"已结束" | `团课已结束,无法签到` |
|
||||
| 4 | 当前时间早于开课前2小时 | `未到签到时间,请在开课前2小时内签到` |
|
||||
| 5 | 当前时间晚于团课结束时间 | `团课已结束,无法签到` |
|
||||
| 6 | 课程当前人数已达上限 | `课程已满员,无法签到` |
|
||||
| 7 | 用户今日无到店签到记录 | `请先完成到店签到` |
|
||||
| 8 | 到店签到状态非SUCCESS | `到店签到未成功,请重新签到` |
|
||||
| 9 | 用户未预约此课程 | `您未预约此课程,无法签到` |
|
||||
| - | 请求体为空 | `请求体不能为空` |
|
||||
| - | 请求体缺少courseId | `courseId不能为空` |
|
||||
|
||||
> **说明**: 校验按上表顺序依次执行,命中第一个失败条件即返回对应错误信息。
|
||||
|
||||
**失败响应示例**:
|
||||
**失败响应** (400 Bad Request):
|
||||
|
||||
```json
|
||||
{
|
||||
"success": false,
|
||||
"message": "未到签到时间,请在开课前2小时内签到"
|
||||
"message": "课程已满员"
|
||||
}
|
||||
```
|
||||
|
||||
```json
|
||||
{
|
||||
"success": false,
|
||||
"message": "您未预约此课程,无法签到"
|
||||
}
|
||||
```
|
||||
---
|
||||
|
||||
### 删除团课
|
||||
|
||||
@@ -1660,14 +1493,7 @@
|
||||
### 团课管理
|
||||
1. **创建团课**:课程名称为必填项
|
||||
2. **取消团课**:需提前24小时通知,否则拒绝操作
|
||||
3. **团课签到**:严格按以下顺序校验,任一不通过即拒绝签到:
|
||||
- 团课是否存在且未被删除
|
||||
- 团课状态不为"已取消"
|
||||
- 团课状态不为"已结束"(含已过结束时间)
|
||||
- 当前时间在开课前2小时内(签到时间窗口)
|
||||
- 课程当前人数未达到最大人数上限
|
||||
- 用户今日已成功到店签到(查询 sign_in_record 表当日 SUCCESS 记录)
|
||||
- 用户已预约该课程(有效预约)
|
||||
3. **团课签到**:验证课程状态必须为正常,且未达最大人数限制
|
||||
4. **删除团课**:采用软删除机制,数据保留可恢复
|
||||
|
||||
### 团课预约
|
||||
|
||||
@@ -1,530 +0,0 @@
|
||||
# 团课推荐模块 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": "错误描述信息"
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
*文档结束*
|
||||
@@ -1,129 +0,0 @@
|
||||
<?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
@@ -1,7 +0,0 @@
|
||||
package cn.novalon.gym.manage.auth.config;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@Configuration
|
||||
public class AuthConfig {
|
||||
}
|
||||
-18
@@ -1,18 +0,0 @@
|
||||
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
@@ -1,47 +0,0 @@
|
||||
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
@@ -1,26 +0,0 @@
|
||||
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
@@ -1,23 +0,0 @@
|
||||
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
@@ -1,22 +0,0 @@
|
||||
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;
|
||||
}
|
||||
@@ -1,25 +0,0 @@
|
||||
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
@@ -1,59 +0,0 @@
|
||||
package cn.novalon.gym.manage.auth.handler;
|
||||
|
||||
import cn.novalon.gym.manage.auth.dto.PhoneCodeLoginDto;
|
||||
import cn.novalon.gym.manage.auth.dto.PhoneLoginDto;
|
||||
import cn.novalon.gym.manage.auth.dto.SendCodeRequest;
|
||||
import cn.novalon.gym.manage.auth.service.PhoneAuthService;
|
||||
import 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
@@ -1,37 +0,0 @@
|
||||
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
@@ -1,37 +0,0 @@
|
||||
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
@@ -1,270 +0,0 @@
|
||||
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
@@ -1,198 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -1,36 +0,0 @@
|
||||
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
@@ -1,5 +0,0 @@
|
||||
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
@@ -1,106 +0,0 @@
|
||||
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");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -118,11 +118,6 @@
|
||||
<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>
|
||||
|
||||
@@ -1,12 +0,0 @@
|
||||
<?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
@@ -1,43 +0,0 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
-4
@@ -2,8 +2,6 @@ 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;
|
||||
@@ -14,7 +12,6 @@ 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;
|
||||
@@ -39,7 +36,6 @@ public class CheckInHandler {
|
||||
public Mono<ServerResponse> checkIn(ServerRequest request) {
|
||||
|
||||
Long memberId = authUtil.getMemberIdOrThrow(request);
|
||||
|
||||
return request.bodyToMono(Map.class)
|
||||
.flatMap(body -> {
|
||||
String qrContent = (String) body.get("qrContent");
|
||||
|
||||
+59
-37
@@ -2,8 +2,6 @@ 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;
|
||||
@@ -15,14 +13,14 @@ 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 cn.hutool.extra.qrcode.QrCodeUtil;
|
||||
import cn.hutool.extra.qrcode.QrConfig;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
@@ -49,19 +47,24 @@ public class CheckServiceImpl implements ICheckInService {
|
||||
private final MemberCardRepository memberCardRepository;
|
||||
private final SignInRecordRepository signInRecordRepository;
|
||||
private final IGroupCourseBookingService groupCourseBookingService;
|
||||
private final IGroupCourseBookingRepository groupCourseBookingRepository;
|
||||
|
||||
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
||||
|
||||
@Override
|
||||
public Mono<QRCodeVo> getQRCode(Long memberId) {
|
||||
log.info("开始生成会员签到二维码, memberId: {}", memberId);
|
||||
log.info("开始查询会员信息, memberId: {}", memberId);
|
||||
|
||||
return findValidMemberCard(memberId)
|
||||
.flatMap(cardRecord -> {
|
||||
log.info("会员信息查询完成, memberCardRecordId: {}", cardRecord.getMemberCardRecordId());
|
||||
|
||||
log.info("开始生成二维码");
|
||||
String qrContent = QRRedisKey.generateQrcodeContent();
|
||||
Map<String, Object> redisMap = new HashMap<>();
|
||||
redisMap.put("qrContent", qrContent);
|
||||
redisMap.put("isUsed", false);
|
||||
redisMap.put("memberId", memberId);
|
||||
redisMap.put("memberCardRecordId", cardRecord.getMemberCardRecordId());
|
||||
|
||||
return redisUtil.setWithExpire(
|
||||
RedisKeyConstants.QRCODE_USER_DAILY + memberId + LocalDate.now(),
|
||||
@@ -73,6 +76,8 @@ public class CheckServiceImpl implements ICheckInService {
|
||||
BeanUtil.copyProperties(qrCodeConfig, QrConfig.class), "png");
|
||||
return new QRCodeVo(qrCodeBase64, false, qrContent, qrCodeConfig.getWidth(), qrCodeConfig.getHeight(), LocalDate.now());
|
||||
}));
|
||||
})
|
||||
.switchIfEmpty(Mono.error(new RuntimeException("该会员没有可用的会员卡")));
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -108,8 +113,7 @@ public class CheckServiceImpl implements ICheckInService {
|
||||
}
|
||||
log.info("二维码匹配成功,memberId: {}", memberId);
|
||||
|
||||
Long memberCardRecordId = map.get("memberCardRecordId") != null
|
||||
? ((Number) map.get("memberCardRecordId")).longValue() : null;
|
||||
Long memberCardRecordId = ((Number) map.get("memberCardRecordId")).longValue();
|
||||
|
||||
return processCheckIn(memberId, memberCardRecordId, map, qrContent);
|
||||
} else {
|
||||
@@ -141,43 +145,60 @@ public class CheckServiceImpl implements ICheckInService {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
|
||||
// 发送实时进度通知
|
||||
MyWebSocketHandler.sendProgress(qrContent, "VALIDATE_BOOKING", "正在检查预约信息...");
|
||||
MyWebSocketHandler.sendProgress(qrContent, "VALIDATE_CARD", "正在验证会员卡...");
|
||||
|
||||
// 检查是否有需要签到的团课预约,有则返回有效预约
|
||||
return memberCardRecordRepository.findById(memberCardRecordId)
|
||||
.switchIfEmpty(Mono.defer(() -> {
|
||||
MyWebSocketHandler.sendFailure(qrContent, "会员卡记录不存在");
|
||||
return Mono.error(new RuntimeException("会员卡记录不存在"));
|
||||
}))
|
||||
.flatMap(cardRecord -> {
|
||||
if (!"ACTIVE".equals(cardRecord.getStatus().name())) {
|
||||
MyWebSocketHandler.sendFailure(qrContent, "会员卡状态不正确");
|
||||
return Mono.error(new RuntimeException("会员卡状态不正确"));
|
||||
}
|
||||
|
||||
if (cardRecord.getExpireTime() != null && cardRecord.getExpireTime().isBefore(now)) {
|
||||
MyWebSocketHandler.sendFailure(qrContent, "会员卡已过期");
|
||||
return Mono.error(new RuntimeException("会员卡已过期"));
|
||||
}
|
||||
|
||||
// 发送实时进度通知
|
||||
MyWebSocketHandler.sendProgress(qrContent, "VALIDATE_BOOKING", "会员卡验证通过,正在检查预约信息...");
|
||||
|
||||
// 检查是否有需要签到的团课预约
|
||||
return validateBooking(memberId, now)
|
||||
.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(() -> {
|
||||
.then(memberCardRepository.findByMemberCardIdAndDeletedAtIsNull(cardRecord.getMemberCardId())
|
||||
.switchIfEmpty(Mono.defer(() -> {
|
||||
MyWebSocketHandler.sendFailure(qrContent, "会员卡类型不存在");
|
||||
return Mono.error(new RuntimeException("会员卡类型不存在"));
|
||||
}))
|
||||
.flatMap(card -> {
|
||||
// 发送实时进度通知
|
||||
MyWebSocketHandler.sendProgress(qrContent, "DEDUCT_USAGE", "正在扣减会员卡次数...");
|
||||
|
||||
return deductCardUsage(cardRecord, card)
|
||||
.flatMap(updatedRecord -> {
|
||||
redisMap.put("isUsed", true);
|
||||
redisMap.put("checkInTime", now.format(DATE_FORMATTER));
|
||||
|
||||
return saveSignInRecord(memberId, null, null)
|
||||
return saveSignInRecord(memberId, cardRecord.getMemberCardRecordId(), card.getMemberCardId())
|
||||
.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);
|
||||
log.info("签到成功, memberId: {}, cardRecordId: {}", memberId, memberCardRecordId);
|
||||
return Mono.just(successMsg);
|
||||
}));
|
||||
});
|
||||
}));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证预约信息,返回时间匹配的有效预约
|
||||
* 验证预约信息
|
||||
*/
|
||||
private Mono<GroupCourseBooking> validateBooking(Long memberId, LocalDateTime now) {
|
||||
private Mono<Void> validateBooking(Long memberId, LocalDateTime now) {
|
||||
return groupCourseBookingService.getBookingsByMemberId(memberId)
|
||||
.filter(booking -> {
|
||||
String status = booking.getStatus();
|
||||
@@ -192,18 +213,19 @@ public class CheckServiceImpl implements ICheckInService {
|
||||
if (bookings.isEmpty()) {
|
||||
return Mono.empty();
|
||||
}
|
||||
// 找到时间范围内第一个有效预约(课程时间内±30分钟)
|
||||
return Flux.fromIterable(bookings)
|
||||
.filter(b -> {
|
||||
boolean hasValidBooking = bookings.stream()
|
||||
.anyMatch(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)));
|
||||
});
|
||||
if (hasValidBooking) {
|
||||
log.info("会员{}有有效的团课预约", memberId);
|
||||
} else {
|
||||
log.warn("会员{}有预约但不在签到时间范围内", memberId);
|
||||
}
|
||||
return Mono.empty();
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+1
-7
@@ -3,7 +3,6 @@ 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;
|
||||
@@ -58,9 +57,6 @@ class CheckInModuleTest {
|
||||
@Mock
|
||||
private IGroupCourseBookingService groupCourseBookingService;
|
||||
|
||||
@Mock
|
||||
private IGroupCourseBookingRepository groupCourseBookingRepository;
|
||||
|
||||
@Mock
|
||||
private MemberCard mockMemberCard;
|
||||
|
||||
@@ -76,8 +72,7 @@ class CheckInModuleTest {
|
||||
void setUp() {
|
||||
MockitoAnnotations.openMocks(this);
|
||||
checkService = new CheckServiceImpl(qrCodeConfig, redisUtil, memberCardRecordRepository,
|
||||
memberCardRepository, signInRecordRepository, groupCourseBookingService,
|
||||
groupCourseBookingRepository);
|
||||
memberCardRepository, signInRecordRepository, groupCourseBookingService);
|
||||
|
||||
when(mockMemberCard.getId()).thenReturn(1L);
|
||||
when(mockMemberCard.getMemberCardType()).thenReturn("TIME_CARD");
|
||||
@@ -131,7 +126,6 @@ class CheckInModuleTest {
|
||||
String key = RedisKeyConstants.QRCODE_USER_DAILY + memberId + LocalDate.now();
|
||||
|
||||
when(redisUtil.get(eq(key))).thenReturn(Mono.just(qrData));
|
||||
when(redisUtil.deleteByPattern(any(String.class))).thenReturn(Mono.empty());
|
||||
when(memberCardRecordRepository.findById(1L)).thenReturn(Mono.just(mockMemberCardRecord));
|
||||
when(memberCardRepository.findByMemberCardIdAndDeletedAtIsNull(1L)).thenReturn(Mono.just(mockMemberCard));
|
||||
when(signInRecordRepository.save(any(SignInRecord.class))).thenReturn(Mono.just(mockSignInRecord));
|
||||
|
||||
@@ -1,62 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<parent>
|
||||
<groupId>cn.novalon.gym.manage</groupId>
|
||||
<artifactId>gym-manage-api</artifactId>
|
||||
<version>1.0.0</version>
|
||||
</parent>
|
||||
|
||||
<artifactId>gym-coach</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>Gym Coach</name>
|
||||
<description>Coach Management Module - Course Start/End, Violation Tracking</description>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>cn.novalon.gym.manage</groupId>
|
||||
<artifactId>manage-common</artifactId>
|
||||
<version>${project.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>cn.novalon.gym.manage</groupId>
|
||||
<artifactId>manage-db</artifactId>
|
||||
<version>${project.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>cn.novalon.gym.manage</groupId>
|
||||
<artifactId>manage-sys</artifactId>
|
||||
<version>${project.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>cn.novalon.gym.manage</groupId>
|
||||
<artifactId>gym-groupCourse</artifactId>
|
||||
<version>${project.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-webflux</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-security</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.data</groupId>
|
||||
<artifactId>spring-data-commons</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springdoc</groupId>
|
||||
<artifactId>springdoc-openapi-starter-webflux-ui</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
-15
@@ -1,15 +0,0 @@
|
||||
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
@@ -1,61 +0,0 @@
|
||||
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
@@ -1,42 +0,0 @@
|
||||
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
@@ -1,30 +0,0 @@
|
||||
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
@@ -1,68 +0,0 @@
|
||||
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
@@ -1,118 +0,0 @@
|
||||
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()));
|
||||
}
|
||||
}
|
||||
-178
@@ -1,178 +0,0 @@
|
||||
package cn.novalon.gym.manage.coach.scheduler;
|
||||
|
||||
import cn.novalon.gym.manage.coach.enums.ViolationReason;
|
||||
import cn.novalon.gym.manage.common.util.RedisUtil;
|
||||
import cn.novalon.gym.manage.groupcourse.dao.GroupCourseBookingDao;
|
||||
import cn.novalon.gym.manage.groupcourse.dao.GroupCourseDao;
|
||||
import cn.novalon.gym.manage.groupcourse.entity.GroupCourseEntity;
|
||||
import cn.novalon.gym.manage.groupcourse.enums.CourseStatus;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.r2dbc.core.DatabaseClient;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 教练课程定时调度器
|
||||
*
|
||||
* 功能:
|
||||
* 1. 检查未手动开课的课程,超时标记为教练缺席(5)并记录违规
|
||||
* 2. 检查未手动结课的课程,超时标记为自动结束(6)并记录违规
|
||||
*
|
||||
* @author 张翔
|
||||
* @date 2026-07-20
|
||||
*/
|
||||
@Component
|
||||
public class CoachCourseScheduler {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(CoachCourseScheduler.class);
|
||||
private static final long ONE_HOUR_MINUTES = 60;
|
||||
private static final long END_GRACE_MINUTES = 10;
|
||||
|
||||
private final GroupCourseDao groupCourseDao;
|
||||
private final GroupCourseBookingDao groupCourseBookingDao;
|
||||
private final DatabaseClient databaseClient;
|
||||
private final RedisUtil redisUtil;
|
||||
|
||||
public CoachCourseScheduler(GroupCourseDao groupCourseDao,
|
||||
GroupCourseBookingDao groupCourseBookingDao,
|
||||
DatabaseClient databaseClient,
|
||||
RedisUtil redisUtil) {
|
||||
this.groupCourseDao = groupCourseDao;
|
||||
this.groupCourseBookingDao = groupCourseBookingDao;
|
||||
this.databaseClient = databaseClient;
|
||||
this.redisUtil = redisUtil;
|
||||
}
|
||||
|
||||
/**
|
||||
* 每分钟检查一次:
|
||||
* - status=0(NORMAL) 的课程是否已过开课缺席阈值
|
||||
* - status=3(IN_PROGRESS) 或 status=7(COACH_LATE) 的课程是否已过结课宽限期
|
||||
*/
|
||||
@Scheduled(fixedRate = 60000)
|
||||
public void checkAndProcessCourses() {
|
||||
logger.debug("教练课程调度器开始检查");
|
||||
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
|
||||
// 1. 检查未开课的课程
|
||||
processAbsentCourses(now)
|
||||
.subscribe(
|
||||
count -> {
|
||||
if (count > 0) {
|
||||
logger.info("教练课程调度器:处理了 {} 门教练缺席课程", count);
|
||||
invalidateCache();
|
||||
}
|
||||
},
|
||||
error -> logger.error("教练课程调度器(缺席检查)执行失败:{}", error.getMessage(), error)
|
||||
);
|
||||
|
||||
// 2. 检查未结课的课程
|
||||
processAutoEndCourses(now)
|
||||
.subscribe(
|
||||
count -> {
|
||||
if (count > 0) {
|
||||
logger.info("教练课程调度器:处理了 {} 门自动结束课程", count);
|
||||
invalidateCache();
|
||||
}
|
||||
},
|
||||
error -> logger.error("教练课程调度器(自动结课)执行失败:{}", error.getMessage(), error)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理缺席课程:status=0 且已过开课缺席阈值
|
||||
*/
|
||||
private Mono<Long> processAbsentCourses(LocalDateTime now) {
|
||||
return groupCourseDao.findByStatusAndStartTimeBefore(databaseClient, "0", now)
|
||||
.filter(course -> isAbsentThresholdExceeded(course, now))
|
||||
.flatMap(course -> markAsCoachAbsent(course, now))
|
||||
.count();
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理自动结课:status IN ('3','7') 且 end_time + 10分钟 已过
|
||||
*/
|
||||
private Mono<Long> processAutoEndCourses(LocalDateTime now) {
|
||||
LocalDateTime endThreshold = now.minusMinutes(END_GRACE_MINUTES);
|
||||
return groupCourseDao.findByStatusInAndEndTimeBefore(databaseClient,
|
||||
new String[]{String.valueOf(CourseStatus.IN_PROGRESS.getValue()),
|
||||
String.valueOf(CourseStatus.COACH_LATE.getValue())},
|
||||
endThreshold)
|
||||
.flatMap(course -> markAsAutoEnded(course, now))
|
||||
.count();
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断课程是否已过缺席阈值
|
||||
*/
|
||||
private boolean isAbsentThresholdExceeded(GroupCourseEntity course, LocalDateTime now) {
|
||||
long courseDurationMinutes = Duration.between(course.getStartTime(), course.getEndTime()).toMinutes();
|
||||
long minutesSinceStart = Duration.between(course.getStartTime(), now).toMinutes();
|
||||
|
||||
if (courseDurationMinutes >= ONE_HOUR_MINUTES) {
|
||||
return minutesSinceStart > 30;
|
||||
} else {
|
||||
long thresholdB = Math.max(1, (long) (courseDurationMinutes * 0.25));
|
||||
return minutesSinceStart > thresholdB;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 标记课程为教练缺席(5),更新预约记录为教练缺席(4),记录违规
|
||||
*/
|
||||
private Mono<GroupCourseEntity> markAsCoachAbsent(GroupCourseEntity course, LocalDateTime now) {
|
||||
logger.info("课程 {} 教练缺席,标记为 COACH_ABSENT", course.getId());
|
||||
|
||||
return insertViolation(course.getCoachId(), course.getId(), now, ViolationReason.COACH_ABSENT)
|
||||
.then(groupCourseDao.updateToCoachAbsent(course.getId(), now, now))
|
||||
.then(groupCourseBookingDao.updateStatusByCourseId(course.getId(), "0", "4"))
|
||||
.thenReturn(course);
|
||||
}
|
||||
|
||||
/**
|
||||
* 标记课程为自动结束(6),记录违规
|
||||
*/
|
||||
private Mono<GroupCourseEntity> markAsAutoEnded(GroupCourseEntity course, LocalDateTime now) {
|
||||
logger.info("课程 {} 未手动结课,标记为 AUTO_ENDED", course.getId());
|
||||
|
||||
return insertViolation(course.getCoachId(), course.getId(), now, ViolationReason.NOT_MANUAL_END)
|
||||
.then(groupCourseDao.updateToAutoEnded(course.getId(), now, now))
|
||||
.thenReturn(course);
|
||||
}
|
||||
|
||||
/**
|
||||
* 插入违规记录(使用 DatabaseClient 直连)
|
||||
*/
|
||||
private Mono<Void> insertViolation(Long coachId, Long courseId, LocalDateTime violationTime,
|
||||
ViolationReason reason) {
|
||||
return databaseClient.sql("""
|
||||
INSERT INTO coach_violation (coach_id, course_id, violation_time, violation_reason, created_at, updated_at)
|
||||
VALUES (:coachId, :courseId, :violationTime, :reason, :now, :now)
|
||||
""")
|
||||
.bind("coachId", coachId)
|
||||
.bind("courseId", courseId)
|
||||
.bind("violationTime", violationTime)
|
||||
.bind("reason", reason.getValue())
|
||||
.bind("now", LocalDateTime.now())
|
||||
.then();
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除统计缓存和团课缓存 —— 调度器触发时,如有课程状态变更则必须及时失效
|
||||
*/
|
||||
private void invalidateCache() {
|
||||
redisUtil.deleteByPattern("datacount:statistics:*").subscribe(
|
||||
deleted -> logger.debug("调度器清除统计缓存,已删除 {} 条", deleted),
|
||||
error -> logger.warn("调度器清除统计缓存失败: {}", error.getMessage())
|
||||
);
|
||||
redisUtil.deleteByPattern("group_course:*").subscribe(
|
||||
deleted -> logger.debug("调度器清除团课缓存,已删除 {} 条", deleted),
|
||||
error -> logger.warn("调度器清除团课缓存失败: {}", error.getMessage())
|
||||
);
|
||||
}
|
||||
}
|
||||
-357
@@ -1,357 +0,0 @@
|
||||
package cn.novalon.gym.manage.coach.service;
|
||||
|
||||
import cn.novalon.gym.manage.coach.dao.CoachViolationDao;
|
||||
import cn.novalon.gym.manage.coach.entity.CoachViolationEntity;
|
||||
import cn.novalon.gym.manage.coach.enums.ViolationReason;
|
||||
import cn.novalon.gym.manage.common.util.RedisUtil;
|
||||
import cn.novalon.gym.manage.common.util.StatusConstants;
|
||||
import cn.novalon.gym.manage.groupcourse.dao.GroupCourseBookingDao;
|
||||
import cn.novalon.gym.manage.groupcourse.dao.GroupCourseDao;
|
||||
import cn.novalon.gym.manage.groupcourse.domain.GroupCourse;
|
||||
import cn.novalon.gym.manage.groupcourse.entity.GroupCourseEntity;
|
||||
import cn.novalon.gym.manage.groupcourse.enums.CourseStatus;
|
||||
import cn.novalon.gym.manage.groupcourse.repository.IGroupCourseBookingRepository;
|
||||
import cn.novalon.gym.manage.groupcourse.repository.IGroupCourseRepository;
|
||||
import cn.novalon.gym.manage.sys.core.domain.SysRole;
|
||||
import cn.novalon.gym.manage.sys.core.domain.SysUser;
|
||||
import cn.novalon.gym.manage.sys.core.domain.UserRole;
|
||||
import cn.novalon.gym.manage.sys.core.repository.ISysRoleRepository;
|
||||
import cn.novalon.gym.manage.sys.core.repository.ISysUserRepository;
|
||||
import cn.novalon.gym.manage.sys.core.repository.IUserRoleRepository;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.r2dbc.core.DatabaseClient;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 教练课程服务(含教练管理 + 开课/结课逻辑 + 违规记录)
|
||||
*
|
||||
* @author 张翔
|
||||
* @date 2026-07-20
|
||||
*/
|
||||
@Service
|
||||
public class CoachCourseService {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(CoachCourseService.class);
|
||||
private static final String COACH_ROLE_NAME = "教练";
|
||||
private static final long ONE_HOUR_MINUTES = 60;
|
||||
|
||||
private final ISysUserRepository userRepository;
|
||||
private final ISysRoleRepository roleRepository;
|
||||
private final IUserRoleRepository userRoleRepository;
|
||||
private final IGroupCourseRepository groupCourseRepository;
|
||||
private final IGroupCourseBookingRepository bookingRepository;
|
||||
private final GroupCourseDao groupCourseDao;
|
||||
private final GroupCourseBookingDao groupCourseBookingDao;
|
||||
private final CoachViolationDao violationDao;
|
||||
private final DatabaseClient databaseClient;
|
||||
private final PasswordEncoder passwordEncoder;
|
||||
private final RedisUtil redisUtil;
|
||||
|
||||
public CoachCourseService(ISysUserRepository userRepository,
|
||||
ISysRoleRepository roleRepository,
|
||||
IUserRoleRepository userRoleRepository,
|
||||
IGroupCourseRepository groupCourseRepository,
|
||||
IGroupCourseBookingRepository bookingRepository,
|
||||
GroupCourseDao groupCourseDao,
|
||||
GroupCourseBookingDao groupCourseBookingDao,
|
||||
CoachViolationDao violationDao,
|
||||
DatabaseClient databaseClient,
|
||||
PasswordEncoder passwordEncoder,
|
||||
RedisUtil redisUtil) {
|
||||
this.userRepository = userRepository;
|
||||
this.roleRepository = roleRepository;
|
||||
this.userRoleRepository = userRoleRepository;
|
||||
this.groupCourseRepository = groupCourseRepository;
|
||||
this.bookingRepository = bookingRepository;
|
||||
this.groupCourseDao = groupCourseDao;
|
||||
this.groupCourseBookingDao = groupCourseBookingDao;
|
||||
this.violationDao = violationDao;
|
||||
this.databaseClient = databaseClient;
|
||||
this.passwordEncoder = passwordEncoder;
|
||||
this.redisUtil = redisUtil;
|
||||
}
|
||||
|
||||
// ==================== 教练管理(从原 CoachService 迁移) ====================
|
||||
|
||||
public Flux<SysUser> getAllCoaches() {
|
||||
return getCoachRoleId()
|
||||
.flatMapMany(roleId -> userRoleRepository.findByRoleId(roleId)
|
||||
.map(UserRole::getUserId)
|
||||
.collectList()
|
||||
.flatMapMany(userIds -> {
|
||||
if (userIds.isEmpty()) {
|
||||
return Flux.empty();
|
||||
}
|
||||
return Flux.fromIterable(userIds)
|
||||
.flatMap(userRepository::findById)
|
||||
.filter(user -> user.getDeletedAt() == null);
|
||||
}));
|
||||
}
|
||||
|
||||
public Mono<SysUser> createCoach(String username, String password, String nickname, String email, String phone) {
|
||||
return getCoachRoleId().flatMap(coachRoleId -> {
|
||||
SysUser user = new SysUser();
|
||||
user.generateId();
|
||||
user.setUsername(username);
|
||||
user.setPassword(passwordEncoder.encode(password));
|
||||
user.setNickname(nickname);
|
||||
user.setEmail(email);
|
||||
user.setPhone(phone);
|
||||
user.setStatus(StatusConstants.ENABLED);
|
||||
|
||||
return userRepository.save(user)
|
||||
.flatMap(saved -> {
|
||||
UserRole userRole = new UserRole();
|
||||
userRole.setUserId(saved.getId());
|
||||
userRole.setRoleId(coachRoleId);
|
||||
return userRoleRepository.save(userRole).thenReturn(saved);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
public Mono<SysUser> updateCoach(Long id, String nickname, String email, String phone) {
|
||||
return userRepository.findById(id)
|
||||
.switchIfEmpty(Mono.error(new RuntimeException("教练不存在")))
|
||||
.flatMap(user -> {
|
||||
if (nickname != null) user.setNickname(nickname);
|
||||
if (email != null) user.setEmail(email);
|
||||
if (phone != null) user.setPhone(phone);
|
||||
user.setUpdatedAt(LocalDateTime.now());
|
||||
return userRepository.update(user);
|
||||
});
|
||||
}
|
||||
|
||||
@Transactional(transactionManager = "connectionFactoryTransactionManager")
|
||||
public Mono<Void> disableCoach(Long id) {
|
||||
return userRepository.findById(id)
|
||||
.switchIfEmpty(Mono.error(new RuntimeException("教练不存在")))
|
||||
.flatMap(user ->
|
||||
groupCourseRepository.countByCoachIdAndStatus(id, 3L)
|
||||
.flatMap(inProgressCount -> {
|
||||
if (inProgressCount > 0) {
|
||||
return Mono.error(new RuntimeException(
|
||||
"该教练有 " + inProgressCount + " 门正在进行中的团课,无法禁用"));
|
||||
}
|
||||
return groupCourseRepository.cancelCoursesByCoachIdExceptStatus(id, 3L)
|
||||
.then();
|
||||
})
|
||||
.then(Mono.defer(() -> {
|
||||
user.setStatus(StatusConstants.DISABLED);
|
||||
user.setUpdatedAt(LocalDateTime.now());
|
||||
return userRepository.update(user).then();
|
||||
}))
|
||||
)
|
||||
.then(invalidateStatisticsCache());
|
||||
}
|
||||
|
||||
public Flux<GroupCourse> getCoachCourses(Long coachId) {
|
||||
return groupCourseRepository.findByCoachId(coachId, Sort.by(Sort.Direction.DESC, "startTime"))
|
||||
.flatMap(course ->
|
||||
bookingRepository.countValidBookings(course.getId())
|
||||
.map(count -> {
|
||||
course.setCurrentMembers(count.intValue());
|
||||
return course;
|
||||
})
|
||||
.defaultIfEmpty(course)
|
||||
);
|
||||
}
|
||||
|
||||
public Mono<Long> getCoachRoleId() {
|
||||
return roleRepository.findByRoleName(COACH_ROLE_NAME)
|
||||
.map(SysRole::getId)
|
||||
.switchIfEmpty(Mono.error(new RuntimeException("教练角色未找到,请先执行数据库迁移")));
|
||||
}
|
||||
|
||||
// ==================== 开课逻辑 ====================
|
||||
|
||||
/**
|
||||
* 教练手动开课
|
||||
* 判定逻辑:
|
||||
* - 长课时(>=1h): 10分钟内正常,10~30分钟迟到,>30分钟拒绝
|
||||
* - 短课时(<1h): 10%时长内正常,10%~25%迟到,>25%拒绝
|
||||
*/
|
||||
public Mono<GroupCourseEntity> startCourse(Long courseId, Long coachId) {
|
||||
return groupCourseDao.findByIdIsAndDeletedAtIsNull(courseId)
|
||||
.switchIfEmpty(Mono.error(new RuntimeException("团课不存在")))
|
||||
.flatMap(course -> {
|
||||
// 验证教练身份
|
||||
if (!course.getCoachId().equals(coachId)) {
|
||||
return Mono.error(new RuntimeException("您不是该课程的教练,无权开课"));
|
||||
}
|
||||
// 验证课程状态:只有 NORMAL(0) 可以开课
|
||||
if (!CourseStatus.NORMAL.getValue().equals(course.getStatus())) {
|
||||
return Mono.error(new RuntimeException("当前课程状态不允许开课,当前状态: " + course.getStatus()));
|
||||
}
|
||||
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
long courseDurationMinutes = Duration.between(course.getStartTime(), course.getEndTime()).toMinutes();
|
||||
|
||||
if (courseDurationMinutes >= ONE_HOUR_MINUTES) {
|
||||
return handleLongCourseStart(course, now);
|
||||
} else {
|
||||
return handleShortCourseStart(course, now, courseDurationMinutes);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private Mono<GroupCourseEntity> handleLongCourseStart(GroupCourseEntity course, LocalDateTime now) {
|
||||
long minutesSinceStart = Duration.between(course.getStartTime(), now).toMinutes();
|
||||
|
||||
if (minutesSinceStart < 0) {
|
||||
return Mono.error(new RuntimeException("课程尚未到开课时间"));
|
||||
}
|
||||
if (minutesSinceStart <= 10) {
|
||||
// 正常开课
|
||||
return doStartCourse(course, now, CourseStatus.IN_PROGRESS, null);
|
||||
}
|
||||
if (minutesSinceStart <= 30) {
|
||||
// 教练迟到
|
||||
return recordViolation(course.getCoachId(), course.getId(), now, ViolationReason.COACH_LATE)
|
||||
.then(doStartCourse(course, now, CourseStatus.COACH_LATE, ViolationReason.COACH_LATE));
|
||||
}
|
||||
// >30分钟,拒绝(调度器应已标记为缺席)
|
||||
return Mono.error(new RuntimeException("已超过开课时间30分钟,无法开课"));
|
||||
}
|
||||
|
||||
private Mono<GroupCourseEntity> handleShortCourseStart(GroupCourseEntity course, LocalDateTime now,
|
||||
long courseDurationMinutes) {
|
||||
long minutesSinceStart = Duration.between(course.getStartTime(), now).toMinutes();
|
||||
long thresholdA = Math.max(1, (long) (courseDurationMinutes * 0.10));
|
||||
long thresholdB = Math.max(1, (long) (courseDurationMinutes * 0.25));
|
||||
|
||||
if (minutesSinceStart < 0) {
|
||||
return Mono.error(new RuntimeException("课程尚未到开课时间"));
|
||||
}
|
||||
if (minutesSinceStart <= thresholdA) {
|
||||
// 正常开课
|
||||
return doStartCourse(course, now, CourseStatus.IN_PROGRESS, null);
|
||||
}
|
||||
if (minutesSinceStart <= thresholdB) {
|
||||
// 教练迟到
|
||||
return recordViolation(course.getCoachId(), course.getId(), now, ViolationReason.COACH_LATE)
|
||||
.then(doStartCourse(course, now, CourseStatus.COACH_LATE, ViolationReason.COACH_LATE));
|
||||
}
|
||||
// >thresholdB,拒绝
|
||||
return Mono.error(new RuntimeException("已超过开课时间,无法开课"));
|
||||
}
|
||||
|
||||
private Mono<GroupCourseEntity> doStartCourse(GroupCourseEntity course, LocalDateTime now,
|
||||
CourseStatus newStatus, ViolationReason violationReason) {
|
||||
course.setStatus(newStatus.getValue());
|
||||
course.setActualStartTime(now);
|
||||
course.setUpdatedAt(now);
|
||||
return groupCourseDao.updateStartInfo(course.getId(), String.valueOf(newStatus.getValue()), now, now)
|
||||
.then(groupCourseDao.findByIdIsAndDeletedAtIsNull(course.getId()))
|
||||
.flatMap(entity -> invalidateStatisticsCache().thenReturn(entity));
|
||||
}
|
||||
|
||||
// ==================== 结课逻辑 ====================
|
||||
|
||||
/**
|
||||
* 教练手动结课
|
||||
* 可在 IN_PROGRESS(3) 或 COACH_LATE(7) 状态下结课
|
||||
* 必须在标注结课时间 + 10分钟内
|
||||
*/
|
||||
public Mono<GroupCourseEntity> endCourse(Long courseId, Long coachId) {
|
||||
return groupCourseDao.findByIdIsAndDeletedAtIsNull(courseId)
|
||||
.switchIfEmpty(Mono.error(new RuntimeException("团课不存在")))
|
||||
.flatMap(course -> {
|
||||
// 验证教练身份
|
||||
if (!course.getCoachId().equals(coachId)) {
|
||||
return Mono.error(new RuntimeException("您不是该课程的教练,无权结课"));
|
||||
}
|
||||
// 验证状态:IN_PROGRESS(3) 或 COACH_LATE(7)
|
||||
Long status = course.getStatus();
|
||||
if (!CourseStatus.IN_PROGRESS.getValue().equals(status)
|
||||
&& !CourseStatus.COACH_LATE.getValue().equals(status)) {
|
||||
return Mono.error(new RuntimeException("当前课程状态不允许结课,当前状态: " + status));
|
||||
}
|
||||
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
long minutesAfterEnd = Duration.between(course.getEndTime(), now).toMinutes();
|
||||
|
||||
if (minutesAfterEnd > 10) {
|
||||
return Mono.error(new RuntimeException("已超过结课时间10分钟,请等待系统自动结课"));
|
||||
}
|
||||
|
||||
course.setStatus(CourseStatus.ENDED.getValue());
|
||||
course.setActualEndTime(now);
|
||||
course.setUpdatedAt(now);
|
||||
return groupCourseDao.updateEndInfo(course.getId(), String.valueOf(CourseStatus.ENDED.getValue()), now, now)
|
||||
.then(groupCourseDao.findByIdIsAndDeletedAtIsNull(course.getId()))
|
||||
.flatMap(entity -> invalidateStatisticsCache().thenReturn(entity));
|
||||
});
|
||||
}
|
||||
|
||||
// ==================== 违规记录 ====================
|
||||
|
||||
/**
|
||||
* 记录教练违规行为(使用 DatabaseClient 直连,避免 R2DBC Entity 映射问题)
|
||||
*/
|
||||
public Mono<Void> recordViolation(Long coachId, Long courseId, LocalDateTime violationTime,
|
||||
ViolationReason reason) {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
return databaseClient.sql("""
|
||||
INSERT INTO coach_violation (coach_id, course_id, violation_time, violation_reason, created_at, updated_at)
|
||||
VALUES (:coachId, :courseId, :violationTime, :reason, :now, :now)
|
||||
""")
|
||||
.bind("coachId", coachId)
|
||||
.bind("courseId", courseId)
|
||||
.bind("violationTime", violationTime)
|
||||
.bind("reason", reason.getValue())
|
||||
.bind("now", now)
|
||||
.then();
|
||||
}
|
||||
|
||||
// ==================== 违规查询 ====================
|
||||
|
||||
/**
|
||||
* 获取所有教练的违规次数统计
|
||||
*/
|
||||
public Flux<Map<String, Object>> getViolationCounts() {
|
||||
return databaseClient.sql("""
|
||||
SELECT coach_id, COUNT(*) AS count
|
||||
FROM coach_violation
|
||||
WHERE deleted_at IS NULL
|
||||
GROUP BY coach_id
|
||||
""")
|
||||
.fetch()
|
||||
.all();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取指定教练的违规记录
|
||||
*/
|
||||
public Flux<Map<String, Object>> getCoachViolations(Long coachId) {
|
||||
return databaseClient.sql("""
|
||||
SELECT v.*, gc.course_name
|
||||
FROM coach_violation v
|
||||
LEFT JOIN group_course gc ON v.course_id = gc.id AND gc.deleted_at IS NULL
|
||||
WHERE v.coach_id = :coachId AND v.deleted_at IS NULL
|
||||
ORDER BY v.violation_time DESC
|
||||
""")
|
||||
.bind("coachId", coachId)
|
||||
.fetch()
|
||||
.all();
|
||||
}
|
||||
|
||||
/**
|
||||
* 清除统计缓存和团课缓存 —— 课程状态变更后调用,返回 Mono 确保链式执行
|
||||
*/
|
||||
private Mono<Void> invalidateStatisticsCache() {
|
||||
return redisUtil.deleteByPattern("datacount:statistics:*")
|
||||
.then(redisUtil.deleteByPattern("group_course:*"))
|
||||
.doOnNext(count -> {})
|
||||
.then();
|
||||
}
|
||||
}
|
||||
-62
@@ -1,62 +0,0 @@
|
||||
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
@@ -1,63 +0,0 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
<?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-coupon</artifactId>
|
||||
<version>1.0.0</version>
|
||||
<name>gym-coupon</name>
|
||||
<description>Coupon Management Module</description>
|
||||
<url/>
|
||||
<licenses>
|
||||
<license/>
|
||||
</licenses>
|
||||
<developers>
|
||||
<developer/>
|
||||
</developers>
|
||||
<scm>
|
||||
<connection/>
|
||||
<developerConnection/>
|
||||
<tag/>
|
||||
<url/>
|
||||
</scm>
|
||||
<properties>
|
||||
<java.version>21</java.version>
|
||||
</properties>
|
||||
<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>cn.novalon.gym.manage</groupId>
|
||||
<artifactId>manage-db</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-data-r2dbc</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-validation</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-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>io.swagger.core.v3</groupId>
|
||||
<artifactId>swagger-annotations-jakarta</artifactId>
|
||||
<version>2.2.43</version>
|
||||
<scope>compile</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>cn.novalon.gym.manage</groupId>
|
||||
<artifactId>gym-member</artifactId>
|
||||
<version>${project.version}</version>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
+75
@@ -0,0 +1,75 @@
|
||||
package cn.novalon.gym.manage.coupon.converter;
|
||||
|
||||
import cn.hutool.core.bean.BeanUtil;
|
||||
import cn.novalon.gym.manage.coupon.domain.CouponTemplate;
|
||||
import cn.novalon.gym.manage.coupon.domain.MemberCoupon;
|
||||
import cn.novalon.gym.manage.coupon.entity.CouponTemplateEntity;
|
||||
import cn.novalon.gym.manage.coupon.entity.MemberCouponEntity;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 优惠券相关转换器
|
||||
*/
|
||||
@Component
|
||||
@Slf4j
|
||||
public class CouponConverter {
|
||||
|
||||
/**
|
||||
* 将优惠券模板实体转换为领域模型
|
||||
*/
|
||||
public CouponTemplate toCouponTemplate(CouponTemplateEntity entity) {
|
||||
if (entity == null) {
|
||||
return null;
|
||||
}
|
||||
CouponTemplate couponTemplate = new CouponTemplate();
|
||||
BeanUtil.copyProperties(entity, couponTemplate);
|
||||
log.debug("转换优惠券模板实体到领域模型:couponId={}", entity.getId());
|
||||
return couponTemplate;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将优惠券模板领域模型转换为实体
|
||||
*/
|
||||
public CouponTemplateEntity toCouponTemplateEntity(CouponTemplate domain) {
|
||||
if (domain == null) {
|
||||
return null;
|
||||
}
|
||||
CouponTemplateEntity entity = new CouponTemplateEntity();
|
||||
BeanUtil.copyProperties(domain, entity);
|
||||
if (domain.getId() != null) {
|
||||
entity.markNotNew();
|
||||
}
|
||||
log.debug("转换优惠券模板领域模型到实体:couponId={}", domain.getId());
|
||||
return entity;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将会员优惠券实体转换为领域模型
|
||||
*/
|
||||
public MemberCoupon toMemberCoupon(MemberCouponEntity entity) {
|
||||
if (entity == null) {
|
||||
return null;
|
||||
}
|
||||
MemberCoupon memberCoupon = new MemberCoupon();
|
||||
BeanUtil.copyProperties(entity, memberCoupon);
|
||||
log.debug("转换会员优惠券实体到领域模型:memberCouponId={}", entity.getId());
|
||||
return memberCoupon;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将会员优惠券领域模型转换为实体
|
||||
*/
|
||||
public MemberCouponEntity toMemberCouponEntity(MemberCoupon domain) {
|
||||
if (domain == null) {
|
||||
return null;
|
||||
}
|
||||
MemberCouponEntity entity = new MemberCouponEntity();
|
||||
BeanUtil.copyProperties(domain, entity);
|
||||
if (domain.getId() != null) {
|
||||
entity.markNotNew();
|
||||
}
|
||||
log.debug("转换会员优惠券领域模型到实体:memberCouponId={}", domain.getId());
|
||||
return entity;
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package cn.novalon.gym.manage.coupon.dao;
|
||||
|
||||
import cn.novalon.gym.manage.coupon.entity.CouponTemplateEntity;
|
||||
import org.springframework.data.r2dbc.repository.Modifying;
|
||||
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
|
||||
public interface CouponTemplateDao extends R2dbcRepository<CouponTemplateEntity, Long> {
|
||||
|
||||
Mono<CouponTemplateEntity> findByIdIsAndDeletedAtIsNull(Long id);
|
||||
|
||||
Flux<CouponTemplateEntity> findAllByDeletedAtIsNull();
|
||||
|
||||
Flux<CouponTemplateEntity> findByNameContainingAndDeletedAtIsNull(String name);
|
||||
|
||||
Flux<CouponTemplateEntity> findByCouponTypeAndDeletedAtIsNull(String couponType);
|
||||
|
||||
Flux<CouponTemplateEntity> findByStatusAndDeletedAtIsNull(String status);
|
||||
|
||||
Mono<CouponTemplateEntity> findByClaimCodeAndDeletedAtIsNull(String claimCode);
|
||||
|
||||
@Modifying
|
||||
@Query("UPDATE coupon_template SET deleted_at = :deletedAt WHERE id = :id")
|
||||
Mono<Integer> softDelete(Long id, LocalDateTime deletedAt);
|
||||
|
||||
@Modifying
|
||||
@Query("UPDATE coupon_template SET status = :status, updated_at = :updatedAt WHERE id = :id")
|
||||
Mono<Integer> updateStatus(Long id, String status, LocalDateTime updatedAt);
|
||||
|
||||
@Modifying
|
||||
@Query("UPDATE coupon_template SET issued_count = issued_count + :count, updated_at = :updatedAt WHERE id = :id")
|
||||
Mono<Integer> incrementIssuedCount(Long id, int count, LocalDateTime updatedAt);
|
||||
|
||||
@Modifying
|
||||
@Query("UPDATE coupon_template SET used_count = used_count + :count, updated_at = :updatedAt WHERE id = :id")
|
||||
Mono<Integer> incrementUsedCount(Long id, int count, LocalDateTime updatedAt);
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package cn.novalon.gym.manage.coupon.dao;
|
||||
|
||||
import cn.novalon.gym.manage.coupon.entity.MemberCouponEntity;
|
||||
import org.springframework.data.r2dbc.repository.Modifying;
|
||||
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;
|
||||
|
||||
@Repository
|
||||
public interface MemberCouponDao extends R2dbcRepository<MemberCouponEntity, Long> {
|
||||
|
||||
Flux<MemberCouponEntity> findByTemplateIdAndDeletedAtIsNull(Long templateId);
|
||||
|
||||
Flux<MemberCouponEntity> findByMemberIdAndDeletedAtIsNull(Long memberId);
|
||||
|
||||
Mono<Long> countByTemplateIdAndMemberIdAndDeletedAtIsNull(Long templateId, Long memberId);
|
||||
|
||||
@Query("SELECT COUNT(*) FROM member_coupon WHERE template_id = :templateId AND status = :status AND deleted_at IS NULL")
|
||||
Mono<Long> countByTemplateIdAndStatus(Long templateId, String status);
|
||||
|
||||
Mono<MemberCouponEntity> findByCouponCodeAndDeletedAtIsNull(String couponCode);
|
||||
|
||||
@Modifying
|
||||
@Query("UPDATE member_coupon SET status = 'EXPIRED', updated_at = :now WHERE status = 'AVAILABLE' AND expire_at < :now AND deleted_at IS NULL")
|
||||
Mono<Integer> expireAvailableCoupons(java.time.LocalDateTime now);
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package cn.novalon.gym.manage.coupon.domain;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
@Schema(description = "领取码兑换优惠券请求")
|
||||
public class ClaimCouponRequest {
|
||||
|
||||
@Schema(description = "会员ID", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
private Long memberId;
|
||||
|
||||
@Schema(description = "领取码", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
private String claimCode;
|
||||
|
||||
public Long getMemberId() {
|
||||
return memberId;
|
||||
}
|
||||
|
||||
public void setMemberId(Long memberId) {
|
||||
this.memberId = memberId;
|
||||
}
|
||||
|
||||
public String getClaimCode() {
|
||||
return claimCode;
|
||||
}
|
||||
|
||||
public void setClaimCode(String claimCode) {
|
||||
this.claimCode = claimCode;
|
||||
}
|
||||
}
|
||||
+86
@@ -0,0 +1,86 @@
|
||||
package cn.novalon.gym.manage.coupon.domain;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
@Schema(description = "优惠券统计数据")
|
||||
public class CouponStatistics {
|
||||
|
||||
@Schema(description = "优惠券模板ID")
|
||||
private Long templateId;
|
||||
|
||||
@Schema(description = "已发放数量")
|
||||
private long issuedCount;
|
||||
|
||||
@Schema(description = "已使用数量")
|
||||
private long usedCount;
|
||||
|
||||
@Schema(description = "可用数量")
|
||||
private long availableCount;
|
||||
|
||||
@Schema(description = "已过期数量")
|
||||
private long expiredCount;
|
||||
|
||||
@Schema(description = "核销率(百分比)")
|
||||
private BigDecimal redemptionRate;
|
||||
|
||||
@Schema(description = "累计优惠金额")
|
||||
private BigDecimal totalDiscountAmount;
|
||||
|
||||
public Long getTemplateId() {
|
||||
return templateId;
|
||||
}
|
||||
|
||||
public void setTemplateId(Long templateId) {
|
||||
this.templateId = templateId;
|
||||
}
|
||||
|
||||
public long getIssuedCount() {
|
||||
return issuedCount;
|
||||
}
|
||||
|
||||
public void setIssuedCount(long issuedCount) {
|
||||
this.issuedCount = issuedCount;
|
||||
}
|
||||
|
||||
public long getUsedCount() {
|
||||
return usedCount;
|
||||
}
|
||||
|
||||
public void setUsedCount(long usedCount) {
|
||||
this.usedCount = usedCount;
|
||||
}
|
||||
|
||||
public long getAvailableCount() {
|
||||
return availableCount;
|
||||
}
|
||||
|
||||
public void setAvailableCount(long availableCount) {
|
||||
this.availableCount = availableCount;
|
||||
}
|
||||
|
||||
public long getExpiredCount() {
|
||||
return expiredCount;
|
||||
}
|
||||
|
||||
public void setExpiredCount(long expiredCount) {
|
||||
this.expiredCount = expiredCount;
|
||||
}
|
||||
|
||||
public BigDecimal getRedemptionRate() {
|
||||
return redemptionRate;
|
||||
}
|
||||
|
||||
public void setRedemptionRate(BigDecimal redemptionRate) {
|
||||
this.redemptionRate = redemptionRate;
|
||||
}
|
||||
|
||||
public BigDecimal getTotalDiscountAmount() {
|
||||
return totalDiscountAmount;
|
||||
}
|
||||
|
||||
public void setTotalDiscountAmount(BigDecimal totalDiscountAmount) {
|
||||
this.totalDiscountAmount = totalDiscountAmount;
|
||||
}
|
||||
}
|
||||
+209
@@ -0,0 +1,209 @@
|
||||
package cn.novalon.gym.manage.coupon.domain;
|
||||
|
||||
import cn.novalon.gym.manage.sys.core.domain.BaseDomain;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Schema(description = "优惠券模板")
|
||||
public class CouponTemplate extends BaseDomain {
|
||||
|
||||
//优惠券名称
|
||||
private String name;
|
||||
|
||||
@Schema(description = "优惠券描述")
|
||||
private String description;
|
||||
|
||||
@Schema(description = "优惠券类型:CASH/DISCOUNT/COURSE/EXPERIENCE", example = "CASH")
|
||||
private String couponType;
|
||||
|
||||
@Schema(description = "优惠值:满减/课程/体验为金额,折扣券为比例(0.9=9折)", example = "20.00")
|
||||
private BigDecimal discountValue;
|
||||
|
||||
@Schema(description = "使用门槛金额", example = "100.00")
|
||||
private BigDecimal thresholdAmount;
|
||||
|
||||
@Schema(description = "有效期类型:FIXED_DATE/DAYS_AFTER_CLAIM", example = "FIXED_DATE")
|
||||
private String validityType;
|
||||
|
||||
@Schema(description = "固定有效期开始时间")
|
||||
private LocalDateTime startTime;
|
||||
|
||||
@Schema(description = "固定有效期结束时间")
|
||||
private LocalDateTime endTime;
|
||||
|
||||
@Schema(description = "领取后有效天数")
|
||||
private Integer validDays;
|
||||
|
||||
@Schema(description = "适用商品范围:ALL/SPECIFIC", example = "ALL")
|
||||
private String applyScope;
|
||||
|
||||
@Schema(description = "指定商品ID列表(JSON数组字符串)")
|
||||
private String applyProductIds;
|
||||
|
||||
@Schema(description = "发放总量,-1表示不限量", example = "1000")
|
||||
private Integer totalQuantity;
|
||||
|
||||
@Schema(description = "每人限领数量", example = "1")
|
||||
private Integer perUserLimit;
|
||||
|
||||
@Schema(description = "是否可叠加使用", example = "false")
|
||||
private Boolean stackable;
|
||||
|
||||
@Schema(description = "领取码")
|
||||
private String claimCode;
|
||||
|
||||
@Schema(description = "状态:DRAFT/ACTIVE/TERMINATED/EXPIRED", example = "DRAFT")
|
||||
private String status;
|
||||
|
||||
@Schema(description = "已发放数量")
|
||||
private Integer issuedCount;
|
||||
|
||||
@Schema(description = "已使用数量")
|
||||
private Integer usedCount;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public String getCouponType() {
|
||||
return couponType;
|
||||
}
|
||||
|
||||
public void setCouponType(String couponType) {
|
||||
this.couponType = couponType;
|
||||
}
|
||||
|
||||
public BigDecimal getDiscountValue() {
|
||||
return discountValue;
|
||||
}
|
||||
|
||||
public void setDiscountValue(BigDecimal discountValue) {
|
||||
this.discountValue = discountValue;
|
||||
}
|
||||
|
||||
public BigDecimal getThresholdAmount() {
|
||||
return thresholdAmount;
|
||||
}
|
||||
|
||||
public void setThresholdAmount(BigDecimal thresholdAmount) {
|
||||
this.thresholdAmount = thresholdAmount;
|
||||
}
|
||||
|
||||
public String getValidityType() {
|
||||
return validityType;
|
||||
}
|
||||
|
||||
public void setValidityType(String validityType) {
|
||||
this.validityType = validityType;
|
||||
}
|
||||
|
||||
public LocalDateTime getStartTime() {
|
||||
return startTime;
|
||||
}
|
||||
|
||||
public void setStartTime(LocalDateTime startTime) {
|
||||
this.startTime = startTime;
|
||||
}
|
||||
|
||||
public LocalDateTime getEndTime() {
|
||||
return endTime;
|
||||
}
|
||||
|
||||
public void setEndTime(LocalDateTime endTime) {
|
||||
this.endTime = endTime;
|
||||
}
|
||||
|
||||
public Integer getValidDays() {
|
||||
return validDays;
|
||||
}
|
||||
|
||||
public void setValidDays(Integer validDays) {
|
||||
this.validDays = validDays;
|
||||
}
|
||||
|
||||
public String getApplyScope() {
|
||||
return applyScope;
|
||||
}
|
||||
|
||||
public void setApplyScope(String applyScope) {
|
||||
this.applyScope = applyScope;
|
||||
}
|
||||
|
||||
public String getApplyProductIds() {
|
||||
return applyProductIds;
|
||||
}
|
||||
|
||||
public void setApplyProductIds(String applyProductIds) {
|
||||
this.applyProductIds = applyProductIds;
|
||||
}
|
||||
|
||||
public Integer getTotalQuantity() {
|
||||
return totalQuantity;
|
||||
}
|
||||
|
||||
public void setTotalQuantity(Integer totalQuantity) {
|
||||
this.totalQuantity = totalQuantity;
|
||||
}
|
||||
|
||||
public Integer getPerUserLimit() {
|
||||
return perUserLimit;
|
||||
}
|
||||
|
||||
public void setPerUserLimit(Integer perUserLimit) {
|
||||
this.perUserLimit = perUserLimit;
|
||||
}
|
||||
|
||||
public Boolean getStackable() {
|
||||
return stackable;
|
||||
}
|
||||
|
||||
public void setStackable(Boolean stackable) {
|
||||
this.stackable = stackable;
|
||||
}
|
||||
|
||||
public String getClaimCode() {
|
||||
return claimCode;
|
||||
}
|
||||
|
||||
public void setClaimCode(String claimCode) {
|
||||
this.claimCode = claimCode;
|
||||
}
|
||||
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(String status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public Integer getIssuedCount() {
|
||||
return issuedCount;
|
||||
}
|
||||
|
||||
public void setIssuedCount(Integer issuedCount) {
|
||||
this.issuedCount = issuedCount;
|
||||
}
|
||||
|
||||
public Integer getUsedCount() {
|
||||
return usedCount;
|
||||
}
|
||||
|
||||
public void setUsedCount(Integer usedCount) {
|
||||
this.usedCount = usedCount;
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package cn.novalon.gym.manage.coupon.domain;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
|
||||
@Schema(description = "优惠券发放请求")
|
||||
public class DistributeCouponRequest {
|
||||
|
||||
@Schema(description = "目标会员ID列表", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
private List<Long> memberIds;
|
||||
|
||||
@Schema(description = "发放方式:MANUAL/BATCH,默认MANUAL", example = "MANUAL")
|
||||
private String distributeType;
|
||||
|
||||
public List<Long> getMemberIds() {
|
||||
return memberIds;
|
||||
}
|
||||
|
||||
public void setMemberIds(List<Long> memberIds) {
|
||||
this.memberIds = memberIds;
|
||||
}
|
||||
|
||||
public String getDistributeType() {
|
||||
return distributeType;
|
||||
}
|
||||
|
||||
public void setDistributeType(String distributeType) {
|
||||
this.distributeType = distributeType;
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package cn.novalon.gym.manage.coupon.domain;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
@Schema(description = "优惠券发放结果")
|
||||
public class DistributeCouponResult {
|
||||
|
||||
@Schema(description = "成功发放数量")
|
||||
private int successCount;
|
||||
|
||||
@Schema(description = "失败数量")
|
||||
private int failCount;
|
||||
|
||||
@Schema(description = "提示信息")
|
||||
private String message;
|
||||
|
||||
public DistributeCouponResult() {
|
||||
}
|
||||
|
||||
public DistributeCouponResult(int successCount, int failCount, String message) {
|
||||
this.successCount = successCount;
|
||||
this.failCount = failCount;
|
||||
this.message = message;
|
||||
}
|
||||
|
||||
public int getSuccessCount() {
|
||||
return successCount;
|
||||
}
|
||||
|
||||
public void setSuccessCount(int successCount) {
|
||||
this.successCount = successCount;
|
||||
}
|
||||
|
||||
public int getFailCount() {
|
||||
return failCount;
|
||||
}
|
||||
|
||||
public void setFailCount(int failCount) {
|
||||
this.failCount = failCount;
|
||||
}
|
||||
|
||||
public String getMessage() {
|
||||
return message;
|
||||
}
|
||||
|
||||
public void setMessage(String message) {
|
||||
this.message = message;
|
||||
}
|
||||
}
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
package cn.novalon.gym.manage.coupon.domain;
|
||||
|
||||
import cn.novalon.gym.manage.sys.core.domain.BaseDomain;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Schema(description = "会员优惠券")
|
||||
public class MemberCoupon extends BaseDomain {
|
||||
|
||||
@Schema(description = "优惠券模板ID")
|
||||
private Long templateId;
|
||||
|
||||
@Schema(description = "会员ID")
|
||||
private Long memberId;
|
||||
|
||||
@Schema(description = "优惠券码")
|
||||
private String couponCode;
|
||||
|
||||
@Schema(description = "状态:AVAILABLE/USED/EXPIRED/INVALID")
|
||||
private String status;
|
||||
|
||||
@Schema(description = "发放方式:MANUAL/BATCH/AUTO/CLAIM")
|
||||
private String distributeType;
|
||||
|
||||
@Schema(description = "领取时间")
|
||||
private LocalDateTime receivedAt;
|
||||
|
||||
@Schema(description = "过期时间")
|
||||
private LocalDateTime expireAt;
|
||||
|
||||
@Schema(description = "使用时间")
|
||||
private LocalDateTime usedAt;
|
||||
|
||||
@Schema(description = "关联订单ID")
|
||||
private Long orderId;
|
||||
|
||||
public Long getTemplateId() {
|
||||
return templateId;
|
||||
}
|
||||
|
||||
public void setTemplateId(Long templateId) {
|
||||
this.templateId = templateId;
|
||||
}
|
||||
|
||||
public Long getMemberId() {
|
||||
return memberId;
|
||||
}
|
||||
|
||||
public void setMemberId(Long memberId) {
|
||||
this.memberId = memberId;
|
||||
}
|
||||
|
||||
public String getCouponCode() {
|
||||
return couponCode;
|
||||
}
|
||||
|
||||
public void setCouponCode(String couponCode) {
|
||||
this.couponCode = couponCode;
|
||||
}
|
||||
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(String status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public String getDistributeType() {
|
||||
return distributeType;
|
||||
}
|
||||
|
||||
public void setDistributeType(String distributeType) {
|
||||
this.distributeType = distributeType;
|
||||
}
|
||||
|
||||
public LocalDateTime getReceivedAt() {
|
||||
return receivedAt;
|
||||
}
|
||||
|
||||
public void setReceivedAt(LocalDateTime receivedAt) {
|
||||
this.receivedAt = receivedAt;
|
||||
}
|
||||
|
||||
public LocalDateTime getExpireAt() {
|
||||
return expireAt;
|
||||
}
|
||||
|
||||
public void setExpireAt(LocalDateTime expireAt) {
|
||||
this.expireAt = expireAt;
|
||||
}
|
||||
|
||||
public LocalDateTime getUsedAt() {
|
||||
return usedAt;
|
||||
}
|
||||
|
||||
public void setUsedAt(LocalDateTime usedAt) {
|
||||
this.usedAt = usedAt;
|
||||
}
|
||||
|
||||
public Long getOrderId() {
|
||||
return orderId;
|
||||
}
|
||||
|
||||
public void setOrderId(Long orderId) {
|
||||
this.orderId = orderId;
|
||||
}
|
||||
}
|
||||
+210
@@ -0,0 +1,210 @@
|
||||
package cn.novalon.gym.manage.coupon.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.math.BigDecimal;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Table("coupon_template")
|
||||
public class CouponTemplateEntity extends BaseEntity {
|
||||
|
||||
@Column("name")
|
||||
private String name;
|
||||
|
||||
@Column("description")
|
||||
private String description;
|
||||
|
||||
@Column("coupon_type")
|
||||
private String couponType;
|
||||
|
||||
@Column("discount_value")
|
||||
private BigDecimal discountValue;
|
||||
|
||||
@Column("threshold_amount")
|
||||
private BigDecimal thresholdAmount;
|
||||
|
||||
@Column("validity_type")
|
||||
private String validityType;
|
||||
|
||||
@Column("start_time")
|
||||
private LocalDateTime startTime;
|
||||
|
||||
@Column("end_time")
|
||||
private LocalDateTime endTime;
|
||||
|
||||
@Column("valid_days")
|
||||
private Integer validDays;
|
||||
|
||||
@Column("apply_scope")
|
||||
private String applyScope;
|
||||
|
||||
@Column("apply_product_ids")
|
||||
private String applyProductIds;
|
||||
|
||||
@Column("total_quantity")
|
||||
private Integer totalQuantity;
|
||||
|
||||
@Column("per_user_limit")
|
||||
private Integer perUserLimit;
|
||||
|
||||
@Column("stackable")
|
||||
private Boolean stackable;
|
||||
|
||||
@Column("claim_code")
|
||||
private String claimCode;
|
||||
|
||||
@Column("status")
|
||||
private String status;
|
||||
|
||||
@Column("issued_count")
|
||||
private Integer issuedCount;
|
||||
|
||||
@Column("used_count")
|
||||
private Integer usedCount;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public String getCouponType() {
|
||||
return couponType;
|
||||
}
|
||||
|
||||
public void setCouponType(String couponType) {
|
||||
this.couponType = couponType;
|
||||
}
|
||||
|
||||
public BigDecimal getDiscountValue() {
|
||||
return discountValue;
|
||||
}
|
||||
|
||||
public void setDiscountValue(BigDecimal discountValue) {
|
||||
this.discountValue = discountValue;
|
||||
}
|
||||
|
||||
public BigDecimal getThresholdAmount() {
|
||||
return thresholdAmount;
|
||||
}
|
||||
|
||||
public void setThresholdAmount(BigDecimal thresholdAmount) {
|
||||
this.thresholdAmount = thresholdAmount;
|
||||
}
|
||||
|
||||
public String getValidityType() {
|
||||
return validityType;
|
||||
}
|
||||
|
||||
public void setValidityType(String validityType) {
|
||||
this.validityType = validityType;
|
||||
}
|
||||
|
||||
public LocalDateTime getStartTime() {
|
||||
return startTime;
|
||||
}
|
||||
|
||||
public void setStartTime(LocalDateTime startTime) {
|
||||
this.startTime = startTime;
|
||||
}
|
||||
|
||||
public LocalDateTime getEndTime() {
|
||||
return endTime;
|
||||
}
|
||||
|
||||
public void setEndTime(LocalDateTime endTime) {
|
||||
this.endTime = endTime;
|
||||
}
|
||||
|
||||
public Integer getValidDays() {
|
||||
return validDays;
|
||||
}
|
||||
|
||||
public void setValidDays(Integer validDays) {
|
||||
this.validDays = validDays;
|
||||
}
|
||||
|
||||
public String getApplyScope() {
|
||||
return applyScope;
|
||||
}
|
||||
|
||||
public void setApplyScope(String applyScope) {
|
||||
this.applyScope = applyScope;
|
||||
}
|
||||
|
||||
public String getApplyProductIds() {
|
||||
return applyProductIds;
|
||||
}
|
||||
|
||||
public void setApplyProductIds(String applyProductIds) {
|
||||
this.applyProductIds = applyProductIds;
|
||||
}
|
||||
|
||||
public Integer getTotalQuantity() {
|
||||
return totalQuantity;
|
||||
}
|
||||
|
||||
public void setTotalQuantity(Integer totalQuantity) {
|
||||
this.totalQuantity = totalQuantity;
|
||||
}
|
||||
|
||||
public Integer getPerUserLimit() {
|
||||
return perUserLimit;
|
||||
}
|
||||
|
||||
public void setPerUserLimit(Integer perUserLimit) {
|
||||
this.perUserLimit = perUserLimit;
|
||||
}
|
||||
|
||||
public Boolean getStackable() {
|
||||
return stackable;
|
||||
}
|
||||
|
||||
public void setStackable(Boolean stackable) {
|
||||
this.stackable = stackable;
|
||||
}
|
||||
|
||||
public String getClaimCode() {
|
||||
return claimCode;
|
||||
}
|
||||
|
||||
public void setClaimCode(String claimCode) {
|
||||
this.claimCode = claimCode;
|
||||
}
|
||||
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(String status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public Integer getIssuedCount() {
|
||||
return issuedCount;
|
||||
}
|
||||
|
||||
public void setIssuedCount(Integer issuedCount) {
|
||||
this.issuedCount = issuedCount;
|
||||
}
|
||||
|
||||
public Integer getUsedCount() {
|
||||
return usedCount;
|
||||
}
|
||||
|
||||
public void setUsedCount(Integer usedCount) {
|
||||
this.usedCount = usedCount;
|
||||
}
|
||||
}
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
package cn.novalon.gym.manage.coupon.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;
|
||||
|
||||
@Table("member_coupon")
|
||||
public class MemberCouponEntity extends BaseEntity {
|
||||
|
||||
@Column("template_id")
|
||||
private Long templateId;
|
||||
|
||||
@Column("member_id")
|
||||
private Long memberId;
|
||||
|
||||
@Column("coupon_code")
|
||||
private String couponCode;
|
||||
|
||||
@Column("status")
|
||||
private String status;
|
||||
|
||||
@Column("distribute_type")
|
||||
private String distributeType;
|
||||
|
||||
@Column("received_at")
|
||||
private LocalDateTime receivedAt;
|
||||
|
||||
@Column("expire_at")
|
||||
private LocalDateTime expireAt;
|
||||
|
||||
@Column("used_at")
|
||||
private LocalDateTime usedAt;
|
||||
|
||||
@Column("order_id")
|
||||
private Long orderId;
|
||||
|
||||
public Long getTemplateId() {
|
||||
return templateId;
|
||||
}
|
||||
|
||||
public void setTemplateId(Long templateId) {
|
||||
this.templateId = templateId;
|
||||
}
|
||||
|
||||
public Long getMemberId() {
|
||||
return memberId;
|
||||
}
|
||||
|
||||
public void setMemberId(Long memberId) {
|
||||
this.memberId = memberId;
|
||||
}
|
||||
|
||||
public String getCouponCode() {
|
||||
return couponCode;
|
||||
}
|
||||
|
||||
public void setCouponCode(String couponCode) {
|
||||
this.couponCode = couponCode;
|
||||
}
|
||||
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(String status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public String getDistributeType() {
|
||||
return distributeType;
|
||||
}
|
||||
|
||||
public void setDistributeType(String distributeType) {
|
||||
this.distributeType = distributeType;
|
||||
}
|
||||
|
||||
public LocalDateTime getReceivedAt() {
|
||||
return receivedAt;
|
||||
}
|
||||
|
||||
public void setReceivedAt(LocalDateTime receivedAt) {
|
||||
this.receivedAt = receivedAt;
|
||||
}
|
||||
|
||||
public LocalDateTime getExpireAt() {
|
||||
return expireAt;
|
||||
}
|
||||
|
||||
public void setExpireAt(LocalDateTime expireAt) {
|
||||
this.expireAt = expireAt;
|
||||
}
|
||||
|
||||
public LocalDateTime getUsedAt() {
|
||||
return usedAt;
|
||||
}
|
||||
|
||||
public void setUsedAt(LocalDateTime usedAt) {
|
||||
this.usedAt = usedAt;
|
||||
}
|
||||
|
||||
public Long getOrderId() {
|
||||
return orderId;
|
||||
}
|
||||
|
||||
public void setOrderId(Long orderId) {
|
||||
this.orderId = orderId;
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package cn.novalon.gym.manage.coupon.enums;
|
||||
|
||||
/**
|
||||
* 优惠券适用商品范围
|
||||
*/
|
||||
public enum ApplyScope {
|
||||
/** 全场通用 */
|
||||
ALL,
|
||||
/** 指定商品 */
|
||||
SPECIFIC
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package cn.novalon.gym.manage.coupon.enums;
|
||||
|
||||
/**
|
||||
* 优惠券模板状态
|
||||
*/
|
||||
public enum CouponTemplateStatus {
|
||||
/** 草稿 */
|
||||
DRAFT,
|
||||
/** 进行中 */
|
||||
ACTIVE,
|
||||
/** 已终止 */
|
||||
TERMINATED,
|
||||
/** 已过期 */
|
||||
EXPIRED
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package cn.novalon.gym.manage.coupon.enums;
|
||||
|
||||
/**
|
||||
* 优惠券类型
|
||||
*/
|
||||
public enum CouponType {
|
||||
/** 满减券 */
|
||||
CASH,
|
||||
/** 折扣券 */
|
||||
DISCOUNT,
|
||||
/** 课程券 */
|
||||
COURSE,
|
||||
/** 体验券(会员体验专用) */
|
||||
EXPERIENCE
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package cn.novalon.gym.manage.coupon.enums;
|
||||
|
||||
/**
|
||||
* 优惠券发放方式
|
||||
*/
|
||||
public enum DistributeType {
|
||||
/** 手动发放(指定会员) */
|
||||
MANUAL,
|
||||
/** 批量发放(按会员分组) */
|
||||
BATCH,
|
||||
/** 自动发放(触发规则) */
|
||||
AUTO,
|
||||
/** 领取码/二维码领取 */
|
||||
CLAIM
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package cn.novalon.gym.manage.coupon.enums;
|
||||
|
||||
/**
|
||||
* 会员优惠券状态
|
||||
*/
|
||||
public enum MemberCouponStatus {
|
||||
/** 可用 */
|
||||
AVAILABLE,
|
||||
/** 已使用 */
|
||||
USED,
|
||||
/** 已过期 */
|
||||
EXPIRED,
|
||||
/** 已作废 */
|
||||
INVALID
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package cn.novalon.gym.manage.coupon.enums;
|
||||
|
||||
/**
|
||||
* 优惠券有效期类型
|
||||
*/
|
||||
public enum ValidityType {
|
||||
/** 固定日期 */
|
||||
FIXED_DATE,
|
||||
/** 领取后X天 */
|
||||
DAYS_AFTER_CLAIM
|
||||
}
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
package cn.novalon.gym.manage.coupon.flashsale.converter;
|
||||
|
||||
import cn.hutool.core.bean.BeanUtil;
|
||||
import cn.novalon.gym.manage.coupon.flashsale.domain.FlashSaleActivity;
|
||||
import cn.novalon.gym.manage.coupon.flashsale.domain.FlashSaleItem;
|
||||
import cn.novalon.gym.manage.coupon.flashsale.domain.FlashSaleOrder;
|
||||
import cn.novalon.gym.manage.coupon.flashsale.entity.FlashSaleActivityEntity;
|
||||
import cn.novalon.gym.manage.coupon.flashsale.entity.FlashSaleItemEntity;
|
||||
import cn.novalon.gym.manage.coupon.flashsale.entity.FlashSaleOrderEntity;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class FlashSaleConverter {
|
||||
|
||||
public FlashSaleActivity toActivity(FlashSaleActivityEntity entity) {
|
||||
if (entity == null) {
|
||||
return null;
|
||||
}
|
||||
FlashSaleActivity domain = new FlashSaleActivity();
|
||||
BeanUtil.copyProperties(entity, domain);
|
||||
return domain;
|
||||
}
|
||||
|
||||
public FlashSaleActivityEntity toActivityEntity(FlashSaleActivity domain) {
|
||||
if (domain == null) {
|
||||
return null;
|
||||
}
|
||||
FlashSaleActivityEntity entity = new FlashSaleActivityEntity();
|
||||
BeanUtil.copyProperties(domain, entity);
|
||||
if (domain.getId() != null) {
|
||||
entity.markNotNew();
|
||||
}
|
||||
return entity;
|
||||
}
|
||||
|
||||
public FlashSaleItem toItem(FlashSaleItemEntity entity) {
|
||||
if (entity == null) {
|
||||
return null;
|
||||
}
|
||||
FlashSaleItem domain = new FlashSaleItem();
|
||||
BeanUtil.copyProperties(entity, domain);
|
||||
return domain;
|
||||
}
|
||||
|
||||
public FlashSaleItemEntity toItemEntity(FlashSaleItem domain) {
|
||||
if (domain == null) {
|
||||
return null;
|
||||
}
|
||||
FlashSaleItemEntity entity = new FlashSaleItemEntity();
|
||||
BeanUtil.copyProperties(domain, entity);
|
||||
if (domain.getId() != null) {
|
||||
entity.markNotNew();
|
||||
}
|
||||
return entity;
|
||||
}
|
||||
|
||||
public FlashSaleOrder toOrder(FlashSaleOrderEntity entity) {
|
||||
if (entity == null) {
|
||||
return null;
|
||||
}
|
||||
FlashSaleOrder domain = new FlashSaleOrder();
|
||||
BeanUtil.copyProperties(entity, domain);
|
||||
return domain;
|
||||
}
|
||||
|
||||
public FlashSaleOrderEntity toOrderEntity(FlashSaleOrder domain) {
|
||||
if (domain == null) {
|
||||
return null;
|
||||
}
|
||||
FlashSaleOrderEntity entity = new FlashSaleOrderEntity();
|
||||
BeanUtil.copyProperties(domain, entity);
|
||||
if (domain.getId() != null) {
|
||||
entity.markNotNew();
|
||||
}
|
||||
return entity;
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package cn.novalon.gym.manage.coupon.flashsale.dao;
|
||||
|
||||
import cn.novalon.gym.manage.coupon.flashsale.entity.FlashSaleActivityEntity;
|
||||
import org.springframework.data.r2dbc.repository.Modifying;
|
||||
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
|
||||
public interface FlashSaleActivityDao extends R2dbcRepository<FlashSaleActivityEntity, Long> {
|
||||
|
||||
Mono<FlashSaleActivityEntity> findByIdIsAndDeletedAtIsNull(Long id);
|
||||
|
||||
Flux<FlashSaleActivityEntity> findAllByDeletedAtIsNull();
|
||||
|
||||
Flux<FlashSaleActivityEntity> findByNameContainingAndDeletedAtIsNull(String name);
|
||||
|
||||
Flux<FlashSaleActivityEntity> findByStatusAndDeletedAtIsNull(String status);
|
||||
|
||||
@Modifying
|
||||
@Query("UPDATE flash_sale_activity SET deleted_at = :deletedAt WHERE id = :id")
|
||||
Mono<Integer> softDelete(Long id, LocalDateTime deletedAt);
|
||||
|
||||
@Modifying
|
||||
@Query("UPDATE flash_sale_activity SET status = :status, updated_at = :updatedAt WHERE id = :id")
|
||||
Mono<Integer> updateStatus(Long id, String status, LocalDateTime updatedAt);
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package cn.novalon.gym.manage.coupon.flashsale.dao;
|
||||
|
||||
import cn.novalon.gym.manage.coupon.flashsale.entity.FlashSaleItemEntity;
|
||||
import org.springframework.data.r2dbc.repository.Modifying;
|
||||
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
|
||||
public interface FlashSaleItemDao extends R2dbcRepository<FlashSaleItemEntity, Long> {
|
||||
|
||||
Mono<FlashSaleItemEntity> findByIdIsAndDeletedAtIsNull(Long id);
|
||||
|
||||
Flux<FlashSaleItemEntity> findByActivityIdAndDeletedAtIsNull(Long activityId);
|
||||
|
||||
@Modifying
|
||||
@Query("UPDATE flash_sale_item SET stock = stock - :quantity, updated_at = :updatedAt WHERE id = :id AND stock >= :quantity")
|
||||
Mono<Integer> deductStock(Long id, int quantity, LocalDateTime updatedAt);
|
||||
|
||||
@Modifying
|
||||
@Query("UPDATE flash_sale_item SET stock = stock + :quantity, updated_at = :updatedAt WHERE id = :id")
|
||||
Mono<Integer> restoreStock(Long id, int quantity, LocalDateTime updatedAt);
|
||||
|
||||
@Modifying
|
||||
@Query("UPDATE flash_sale_item SET sold_count = sold_count + :count, updated_at = :updatedAt WHERE id = :id")
|
||||
Mono<Integer> incrementSoldCount(Long id, int count, LocalDateTime updatedAt);
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package cn.novalon.gym.manage.coupon.flashsale.dao;
|
||||
|
||||
import cn.novalon.gym.manage.coupon.flashsale.entity.FlashSaleOrderEntity;
|
||||
import org.springframework.data.r2dbc.repository.Modifying;
|
||||
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
|
||||
public interface FlashSaleOrderDao extends R2dbcRepository<FlashSaleOrderEntity, Long> {
|
||||
|
||||
Mono<FlashSaleOrderEntity> findByIdIsAndDeletedAtIsNull(Long id);
|
||||
|
||||
Flux<FlashSaleOrderEntity> findByMemberIdAndDeletedAtIsNull(Long memberId);
|
||||
|
||||
Flux<FlashSaleOrderEntity> findByActivityIdAndDeletedAtIsNull(Long activityId);
|
||||
|
||||
Mono<Long> countByActivityIdAndMemberIdAndStatusAndDeletedAtIsNull(
|
||||
Long activityId, Long memberId, String status);
|
||||
|
||||
Mono<Long> countByItemIdAndMemberIdAndStatusInAndDeletedAtIsNull(
|
||||
Long itemId, Long memberId, java.util.Collection<String> statuses);
|
||||
|
||||
@Query("SELECT * FROM flash_sale_order WHERE status = :status AND expire_at < :now AND deleted_at IS NULL")
|
||||
Flux<FlashSaleOrderEntity> findExpiredPendingOrders(String status, LocalDateTime now);
|
||||
|
||||
@Modifying
|
||||
@Query("UPDATE flash_sale_order SET status = :status, updated_at = :updatedAt WHERE id = :id")
|
||||
Mono<Integer> updateStatus(Long id, String status, LocalDateTime updatedAt);
|
||||
|
||||
@Modifying
|
||||
@Query("UPDATE flash_sale_order SET status = :status, pay_at = :payAt, updated_at = :updatedAt WHERE id = :id")
|
||||
Mono<Integer> markPaid(Long id, String status, LocalDateTime payAt, LocalDateTime updatedAt);
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package cn.novalon.gym.manage.coupon.flashsale.domain;
|
||||
|
||||
import cn.novalon.gym.manage.sys.core.domain.BaseDomain;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Schema(description = "秒杀活动")
|
||||
public class FlashSaleActivity extends BaseDomain {
|
||||
|
||||
private String name;
|
||||
private String description;
|
||||
private LocalDateTime startTime;
|
||||
private LocalDateTime endTime;
|
||||
private Integer payTimeoutMinutes;
|
||||
private Integer perUserLimit;
|
||||
private String status;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public LocalDateTime getStartTime() {
|
||||
return startTime;
|
||||
}
|
||||
|
||||
public void setStartTime(LocalDateTime startTime) {
|
||||
this.startTime = startTime;
|
||||
}
|
||||
|
||||
public LocalDateTime getEndTime() {
|
||||
return endTime;
|
||||
}
|
||||
|
||||
public void setEndTime(LocalDateTime endTime) {
|
||||
this.endTime = endTime;
|
||||
}
|
||||
|
||||
public Integer getPayTimeoutMinutes() {
|
||||
return payTimeoutMinutes;
|
||||
}
|
||||
|
||||
public void setPayTimeoutMinutes(Integer payTimeoutMinutes) {
|
||||
this.payTimeoutMinutes = payTimeoutMinutes;
|
||||
}
|
||||
|
||||
public Integer getPerUserLimit() {
|
||||
return perUserLimit;
|
||||
}
|
||||
|
||||
public void setPerUserLimit(Integer perUserLimit) {
|
||||
this.perUserLimit = perUserLimit;
|
||||
}
|
||||
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(String status) {
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
package cn.novalon.gym.manage.coupon.flashsale.domain;
|
||||
|
||||
import cn.novalon.gym.manage.sys.core.domain.BaseDomain;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
@Schema(description = "秒杀商品")
|
||||
public class FlashSaleItem extends BaseDomain {
|
||||
|
||||
private Long activityId;
|
||||
private String productType;
|
||||
private Long productId;
|
||||
private String productName;
|
||||
private BigDecimal originalPrice;
|
||||
private BigDecimal seckillPrice;
|
||||
private Integer stock;
|
||||
private Integer soldCount;
|
||||
private Integer perUserLimit;
|
||||
|
||||
public Long getActivityId() {
|
||||
return activityId;
|
||||
}
|
||||
|
||||
public void setActivityId(Long activityId) {
|
||||
this.activityId = activityId;
|
||||
}
|
||||
|
||||
public String getProductType() {
|
||||
return productType;
|
||||
}
|
||||
|
||||
public void setProductType(String productType) {
|
||||
this.productType = productType;
|
||||
}
|
||||
|
||||
public Long getProductId() {
|
||||
return productId;
|
||||
}
|
||||
|
||||
public void setProductId(Long productId) {
|
||||
this.productId = productId;
|
||||
}
|
||||
|
||||
public String getProductName() {
|
||||
return productName;
|
||||
}
|
||||
|
||||
public void setProductName(String productName) {
|
||||
this.productName = productName;
|
||||
}
|
||||
|
||||
public BigDecimal getOriginalPrice() {
|
||||
return originalPrice;
|
||||
}
|
||||
|
||||
public void setOriginalPrice(BigDecimal originalPrice) {
|
||||
this.originalPrice = originalPrice;
|
||||
}
|
||||
|
||||
public BigDecimal getSeckillPrice() {
|
||||
return seckillPrice;
|
||||
}
|
||||
|
||||
public void setSeckillPrice(BigDecimal seckillPrice) {
|
||||
this.seckillPrice = seckillPrice;
|
||||
}
|
||||
|
||||
public Integer getStock() {
|
||||
return stock;
|
||||
}
|
||||
|
||||
public void setStock(Integer stock) {
|
||||
this.stock = stock;
|
||||
}
|
||||
|
||||
public Integer getSoldCount() {
|
||||
return soldCount;
|
||||
}
|
||||
|
||||
public void setSoldCount(Integer soldCount) {
|
||||
this.soldCount = soldCount;
|
||||
}
|
||||
|
||||
public Integer getPerUserLimit() {
|
||||
return perUserLimit;
|
||||
}
|
||||
|
||||
public void setPerUserLimit(Integer perUserLimit) {
|
||||
this.perUserLimit = perUserLimit;
|
||||
}
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
package cn.novalon.gym.manage.coupon.flashsale.domain;
|
||||
|
||||
import cn.novalon.gym.manage.sys.core.domain.BaseDomain;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Schema(description = "秒杀订单")
|
||||
public class FlashSaleOrder extends BaseDomain {
|
||||
|
||||
private Long activityId;
|
||||
private Long itemId;
|
||||
private Long memberId;
|
||||
private Integer quantity;
|
||||
private BigDecimal payAmount;
|
||||
private String status;
|
||||
private LocalDateTime expireAt;
|
||||
private LocalDateTime payAt;
|
||||
|
||||
public Long getActivityId() {
|
||||
return activityId;
|
||||
}
|
||||
|
||||
public void setActivityId(Long activityId) {
|
||||
this.activityId = activityId;
|
||||
}
|
||||
|
||||
public Long getItemId() {
|
||||
return itemId;
|
||||
}
|
||||
|
||||
public void setItemId(Long itemId) {
|
||||
this.itemId = itemId;
|
||||
}
|
||||
|
||||
public Long getMemberId() {
|
||||
return memberId;
|
||||
}
|
||||
|
||||
public void setMemberId(Long memberId) {
|
||||
this.memberId = memberId;
|
||||
}
|
||||
|
||||
public Integer getQuantity() {
|
||||
return quantity;
|
||||
}
|
||||
|
||||
public void setQuantity(Integer quantity) {
|
||||
this.quantity = quantity;
|
||||
}
|
||||
|
||||
public BigDecimal getPayAmount() {
|
||||
return payAmount;
|
||||
}
|
||||
|
||||
public void setPayAmount(BigDecimal payAmount) {
|
||||
this.payAmount = payAmount;
|
||||
}
|
||||
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(String status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public LocalDateTime getExpireAt() {
|
||||
return expireAt;
|
||||
}
|
||||
|
||||
public void setExpireAt(LocalDateTime expireAt) {
|
||||
this.expireAt = expireAt;
|
||||
}
|
||||
|
||||
public LocalDateTime getPayAt() {
|
||||
return payAt;
|
||||
}
|
||||
|
||||
public void setPayAt(LocalDateTime payAt) {
|
||||
this.payAt = payAt;
|
||||
}
|
||||
}
|
||||
+82
@@ -0,0 +1,82 @@
|
||||
package cn.novalon.gym.manage.coupon.flashsale.domain;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
@Schema(description = "秒杀统计数据")
|
||||
public class FlashSaleStatistics {
|
||||
|
||||
private Long activityId;
|
||||
private long totalOrders;
|
||||
private long pendingOrders;
|
||||
private long paidOrders;
|
||||
private long cancelledOrders;
|
||||
private long expiredOrders;
|
||||
private long totalSoldQuantity;
|
||||
private BigDecimal totalRevenue;
|
||||
|
||||
public Long getActivityId() {
|
||||
return activityId;
|
||||
}
|
||||
|
||||
public void setActivityId(Long activityId) {
|
||||
this.activityId = activityId;
|
||||
}
|
||||
|
||||
public long getTotalOrders() {
|
||||
return totalOrders;
|
||||
}
|
||||
|
||||
public void setTotalOrders(long totalOrders) {
|
||||
this.totalOrders = totalOrders;
|
||||
}
|
||||
|
||||
public long getPendingOrders() {
|
||||
return pendingOrders;
|
||||
}
|
||||
|
||||
public void setPendingOrders(long pendingOrders) {
|
||||
this.pendingOrders = pendingOrders;
|
||||
}
|
||||
|
||||
public long getPaidOrders() {
|
||||
return paidOrders;
|
||||
}
|
||||
|
||||
public void setPaidOrders(long paidOrders) {
|
||||
this.paidOrders = paidOrders;
|
||||
}
|
||||
|
||||
public long getCancelledOrders() {
|
||||
return cancelledOrders;
|
||||
}
|
||||
|
||||
public void setCancelledOrders(long cancelledOrders) {
|
||||
this.cancelledOrders = cancelledOrders;
|
||||
}
|
||||
|
||||
public long getExpiredOrders() {
|
||||
return expiredOrders;
|
||||
}
|
||||
|
||||
public void setExpiredOrders(long expiredOrders) {
|
||||
this.expiredOrders = expiredOrders;
|
||||
}
|
||||
|
||||
public long getTotalSoldQuantity() {
|
||||
return totalSoldQuantity;
|
||||
}
|
||||
|
||||
public void setTotalSoldQuantity(long totalSoldQuantity) {
|
||||
this.totalSoldQuantity = totalSoldQuantity;
|
||||
}
|
||||
|
||||
public BigDecimal getTotalRevenue() {
|
||||
return totalRevenue;
|
||||
}
|
||||
|
||||
public void setTotalRevenue(BigDecimal totalRevenue) {
|
||||
this.totalRevenue = totalRevenue;
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package cn.novalon.gym.manage.coupon.flashsale.domain;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
@Schema(description = "秒杀抢购请求")
|
||||
public class GrabRequest {
|
||||
|
||||
private Long itemId;
|
||||
private Long memberId;
|
||||
private Integer quantity;
|
||||
|
||||
public Long getItemId() {
|
||||
return itemId;
|
||||
}
|
||||
|
||||
public void setItemId(Long itemId) {
|
||||
this.itemId = itemId;
|
||||
}
|
||||
|
||||
public Long getMemberId() {
|
||||
return memberId;
|
||||
}
|
||||
|
||||
public void setMemberId(Long memberId) {
|
||||
this.memberId = memberId;
|
||||
}
|
||||
|
||||
public Integer getQuantity() {
|
||||
return quantity;
|
||||
}
|
||||
|
||||
public void setQuantity(Integer quantity) {
|
||||
this.quantity = quantity;
|
||||
}
|
||||
}
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
package cn.novalon.gym.manage.coupon.flashsale.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;
|
||||
|
||||
@Table("flash_sale_activity")
|
||||
public class FlashSaleActivityEntity extends BaseEntity {
|
||||
|
||||
@Column("name")
|
||||
private String name;
|
||||
|
||||
@Column("description")
|
||||
private String description;
|
||||
|
||||
@Column("start_time")
|
||||
private LocalDateTime startTime;
|
||||
|
||||
@Column("end_time")
|
||||
private LocalDateTime endTime;
|
||||
|
||||
@Column("pay_timeout_minutes")
|
||||
private Integer payTimeoutMinutes;
|
||||
|
||||
@Column("per_user_limit")
|
||||
private Integer perUserLimit;
|
||||
|
||||
@Column("status")
|
||||
private String status;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public LocalDateTime getStartTime() {
|
||||
return startTime;
|
||||
}
|
||||
|
||||
public void setStartTime(LocalDateTime startTime) {
|
||||
this.startTime = startTime;
|
||||
}
|
||||
|
||||
public LocalDateTime getEndTime() {
|
||||
return endTime;
|
||||
}
|
||||
|
||||
public void setEndTime(LocalDateTime endTime) {
|
||||
this.endTime = endTime;
|
||||
}
|
||||
|
||||
public Integer getPayTimeoutMinutes() {
|
||||
return payTimeoutMinutes;
|
||||
}
|
||||
|
||||
public void setPayTimeoutMinutes(Integer payTimeoutMinutes) {
|
||||
this.payTimeoutMinutes = payTimeoutMinutes;
|
||||
}
|
||||
|
||||
public Integer getPerUserLimit() {
|
||||
return perUserLimit;
|
||||
}
|
||||
|
||||
public void setPerUserLimit(Integer perUserLimit) {
|
||||
this.perUserLimit = perUserLimit;
|
||||
}
|
||||
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(String status) {
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
package cn.novalon.gym.manage.coupon.flashsale.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.math.BigDecimal;
|
||||
|
||||
@Table("flash_sale_item")
|
||||
public class FlashSaleItemEntity extends BaseEntity {
|
||||
|
||||
@Column("activity_id")
|
||||
private Long activityId;
|
||||
|
||||
@Column("product_type")
|
||||
private String productType;
|
||||
|
||||
@Column("product_id")
|
||||
private Long productId;
|
||||
|
||||
@Column("product_name")
|
||||
private String productName;
|
||||
|
||||
@Column("original_price")
|
||||
private BigDecimal originalPrice;
|
||||
|
||||
@Column("seckill_price")
|
||||
private BigDecimal seckillPrice;
|
||||
|
||||
@Column("stock")
|
||||
private Integer stock;
|
||||
|
||||
@Column("sold_count")
|
||||
private Integer soldCount;
|
||||
|
||||
@Column("per_user_limit")
|
||||
private Integer perUserLimit;
|
||||
|
||||
public Long getActivityId() {
|
||||
return activityId;
|
||||
}
|
||||
|
||||
public void setActivityId(Long activityId) {
|
||||
this.activityId = activityId;
|
||||
}
|
||||
|
||||
public String getProductType() {
|
||||
return productType;
|
||||
}
|
||||
|
||||
public void setProductType(String productType) {
|
||||
this.productType = productType;
|
||||
}
|
||||
|
||||
public Long getProductId() {
|
||||
return productId;
|
||||
}
|
||||
|
||||
public void setProductId(Long productId) {
|
||||
this.productId = productId;
|
||||
}
|
||||
|
||||
public String getProductName() {
|
||||
return productName;
|
||||
}
|
||||
|
||||
public void setProductName(String productName) {
|
||||
this.productName = productName;
|
||||
}
|
||||
|
||||
public BigDecimal getOriginalPrice() {
|
||||
return originalPrice;
|
||||
}
|
||||
|
||||
public void setOriginalPrice(BigDecimal originalPrice) {
|
||||
this.originalPrice = originalPrice;
|
||||
}
|
||||
|
||||
public BigDecimal getSeckillPrice() {
|
||||
return seckillPrice;
|
||||
}
|
||||
|
||||
public void setSeckillPrice(BigDecimal seckillPrice) {
|
||||
this.seckillPrice = seckillPrice;
|
||||
}
|
||||
|
||||
public Integer getStock() {
|
||||
return stock;
|
||||
}
|
||||
|
||||
public void setStock(Integer stock) {
|
||||
this.stock = stock;
|
||||
}
|
||||
|
||||
public Integer getSoldCount() {
|
||||
return soldCount;
|
||||
}
|
||||
|
||||
public void setSoldCount(Integer soldCount) {
|
||||
this.soldCount = soldCount;
|
||||
}
|
||||
|
||||
public Integer getPerUserLimit() {
|
||||
return perUserLimit;
|
||||
}
|
||||
|
||||
public void setPerUserLimit(Integer perUserLimit) {
|
||||
this.perUserLimit = perUserLimit;
|
||||
}
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
package cn.novalon.gym.manage.coupon.flashsale.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.math.BigDecimal;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Table("flash_sale_order")
|
||||
public class FlashSaleOrderEntity extends BaseEntity {
|
||||
|
||||
@Column("activity_id")
|
||||
private Long activityId;
|
||||
|
||||
@Column("item_id")
|
||||
private Long itemId;
|
||||
|
||||
@Column("member_id")
|
||||
private Long memberId;
|
||||
|
||||
@Column("quantity")
|
||||
private Integer quantity;
|
||||
|
||||
@Column("pay_amount")
|
||||
private BigDecimal payAmount;
|
||||
|
||||
@Column("status")
|
||||
private String status;
|
||||
|
||||
@Column("expire_at")
|
||||
private LocalDateTime expireAt;
|
||||
|
||||
@Column("pay_at")
|
||||
private LocalDateTime payAt;
|
||||
|
||||
public Long getActivityId() {
|
||||
return activityId;
|
||||
}
|
||||
|
||||
public void setActivityId(Long activityId) {
|
||||
this.activityId = activityId;
|
||||
}
|
||||
|
||||
public Long getItemId() {
|
||||
return itemId;
|
||||
}
|
||||
|
||||
public void setItemId(Long itemId) {
|
||||
this.itemId = itemId;
|
||||
}
|
||||
|
||||
public Long getMemberId() {
|
||||
return memberId;
|
||||
}
|
||||
|
||||
public void setMemberId(Long memberId) {
|
||||
this.memberId = memberId;
|
||||
}
|
||||
|
||||
public Integer getQuantity() {
|
||||
return quantity;
|
||||
}
|
||||
|
||||
public void setQuantity(Integer quantity) {
|
||||
this.quantity = quantity;
|
||||
}
|
||||
|
||||
public BigDecimal getPayAmount() {
|
||||
return payAmount;
|
||||
}
|
||||
|
||||
public void setPayAmount(BigDecimal payAmount) {
|
||||
this.payAmount = payAmount;
|
||||
}
|
||||
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(String status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public LocalDateTime getExpireAt() {
|
||||
return expireAt;
|
||||
}
|
||||
|
||||
public void setExpireAt(LocalDateTime expireAt) {
|
||||
this.expireAt = expireAt;
|
||||
}
|
||||
|
||||
public LocalDateTime getPayAt() {
|
||||
return payAt;
|
||||
}
|
||||
|
||||
public void setPayAt(LocalDateTime payAt) {
|
||||
this.payAt = payAt;
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package cn.novalon.gym.manage.coupon.flashsale.enums;
|
||||
|
||||
/**
|
||||
* 秒杀活动状态
|
||||
*/
|
||||
public enum FlashSaleActivityStatus {
|
||||
DRAFT,
|
||||
ACTIVE,
|
||||
TERMINATED,
|
||||
EXPIRED
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package cn.novalon.gym.manage.coupon.flashsale.enums;
|
||||
|
||||
/**
|
||||
* 秒杀订单状态
|
||||
*/
|
||||
public enum FlashSaleOrderStatus {
|
||||
PENDING,
|
||||
PAID,
|
||||
CANCELLED,
|
||||
EXPIRED
|
||||
}
|
||||
+219
@@ -0,0 +1,219 @@
|
||||
package cn.novalon.gym.manage.coupon.flashsale.handler;
|
||||
|
||||
import cn.novalon.gym.manage.common.dto.PageRequest;
|
||||
import cn.novalon.gym.manage.coupon.flashsale.domain.FlashSaleActivity;
|
||||
import cn.novalon.gym.manage.coupon.flashsale.domain.FlashSaleItem;
|
||||
import cn.novalon.gym.manage.coupon.flashsale.domain.FlashSaleOrder;
|
||||
import cn.novalon.gym.manage.coupon.flashsale.domain.GrabRequest;
|
||||
import cn.novalon.gym.manage.coupon.flashsale.service.IFlashSaleActivityService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
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;
|
||||
|
||||
@Component
|
||||
@Tag(name = "秒杀管理", description = "秒杀相关操作")
|
||||
public class FlashSaleHandler {
|
||||
|
||||
private final IFlashSaleActivityService flashSaleService;
|
||||
|
||||
public FlashSaleHandler(IFlashSaleActivityService flashSaleService) {
|
||||
this.flashSaleService = flashSaleService;
|
||||
}
|
||||
|
||||
@Operation(summary = "获取所有秒杀活动")
|
||||
public Mono<ServerResponse> getAllActivities(ServerRequest request) {
|
||||
boolean includeDeleted = Boolean.parseBoolean(request.queryParam("includeDeleted").orElse("false"));
|
||||
return ServerResponse.ok()
|
||||
.body(flashSaleService.findAll(includeDeleted), FlashSaleActivity.class);
|
||||
}
|
||||
|
||||
@Operation(summary = "分页获取秒杀活动")
|
||||
public Mono<ServerResponse> getActivitiesByPage(ServerRequest request) {
|
||||
return request.bodyToMono(PageRequest.class)
|
||||
.flatMap(pageRequest -> {
|
||||
String status = request.queryParam("status").orElse(null);
|
||||
normalizePageRequest(pageRequest);
|
||||
return flashSaleService.findByPage(pageRequest, status)
|
||||
.flatMap(response -> ServerResponse.ok().bodyValue(response));
|
||||
});
|
||||
}
|
||||
|
||||
@Operation(summary = "搜索秒杀活动")
|
||||
public Mono<ServerResponse> searchActivities(ServerRequest request) {
|
||||
String keyword = request.queryParam("keyword").orElse("");
|
||||
String status = request.queryParam("status").orElse(null);
|
||||
return ServerResponse.ok()
|
||||
.body(flashSaleService.findByKeywordAndStatus(keyword, status), FlashSaleActivity.class);
|
||||
}
|
||||
|
||||
@Operation(summary = "根据ID获取秒杀活动")
|
||||
public Mono<ServerResponse> getActivityById(ServerRequest request) {
|
||||
Long id = Long.valueOf(request.pathVariable("id"));
|
||||
return flashSaleService.findById(id)
|
||||
.flatMap(activity -> ServerResponse.ok().bodyValue(activity))
|
||||
.switchIfEmpty(ServerResponse.notFound().build());
|
||||
}
|
||||
|
||||
@Operation(summary = "创建秒杀活动")
|
||||
public Mono<ServerResponse> createActivity(ServerRequest request) {
|
||||
return request.bodyToMono(FlashSaleActivity.class)
|
||||
.flatMap(activity -> {
|
||||
if (activity.getName() == null || activity.getName().isEmpty()) {
|
||||
return badRequest("活动名称不能为空");
|
||||
}
|
||||
return flashSaleService.create(activity)
|
||||
.flatMap(created -> successResponse("秒杀活动创建成功", created))
|
||||
.onErrorResume(this::errorResponse);
|
||||
});
|
||||
}
|
||||
|
||||
@Operation(summary = "更新秒杀活动")
|
||||
public Mono<ServerResponse> updateActivity(ServerRequest request) {
|
||||
Long id = Long.valueOf(request.pathVariable("id"));
|
||||
return request.bodyToMono(FlashSaleActivity.class)
|
||||
.flatMap(activity -> flashSaleService.update(id, activity)
|
||||
.flatMap(updated -> successResponse("秒杀活动更新成功", updated))
|
||||
.onErrorResume(this::errorResponse));
|
||||
}
|
||||
|
||||
@Operation(summary = "删除秒杀活动")
|
||||
public Mono<ServerResponse> deleteActivity(ServerRequest request) {
|
||||
Long id = Long.valueOf(request.pathVariable("id"));
|
||||
return flashSaleService.delete(id)
|
||||
.then(Mono.defer(() -> successResponse("秒杀活动删除成功", null)))
|
||||
.onErrorResume(this::errorResponse);
|
||||
}
|
||||
|
||||
@Operation(summary = "发布秒杀活动")
|
||||
public Mono<ServerResponse> publishActivity(ServerRequest request) {
|
||||
Long id = Long.valueOf(request.pathVariable("id"));
|
||||
return flashSaleService.publish(id)
|
||||
.flatMap(activity -> successResponse("秒杀活动发布成功", activity))
|
||||
.onErrorResume(this::errorResponse);
|
||||
}
|
||||
|
||||
@Operation(summary = "终止秒杀活动")
|
||||
public Mono<ServerResponse> terminateActivity(ServerRequest request) {
|
||||
Long id = Long.valueOf(request.pathVariable("id"));
|
||||
return flashSaleService.terminate(id)
|
||||
.flatMap(activity -> successResponse("秒杀活动已终止", activity))
|
||||
.onErrorResume(this::errorResponse);
|
||||
}
|
||||
|
||||
@Operation(summary = "获取秒杀统计")
|
||||
public Mono<ServerResponse> getStatistics(ServerRequest request) {
|
||||
Long id = Long.valueOf(request.pathVariable("id"));
|
||||
return flashSaleService.getStatistics(id)
|
||||
.flatMap(stats -> ServerResponse.ok().bodyValue(stats))
|
||||
.onErrorResume(this::errorResponse);
|
||||
}
|
||||
|
||||
@Operation(summary = "获取秒杀商品列表")
|
||||
public Mono<ServerResponse> getItems(ServerRequest request) {
|
||||
String activityIdStr = request.queryParam("activityId").orElse(null);
|
||||
if (activityIdStr == null) {
|
||||
return badRequest("activityId不能为空");
|
||||
}
|
||||
Long activityId = Long.valueOf(activityIdStr);
|
||||
return ServerResponse.ok()
|
||||
.body(flashSaleService.findItemsByActivityId(activityId), FlashSaleItem.class);
|
||||
}
|
||||
|
||||
@Operation(summary = "创建秒杀商品")
|
||||
public Mono<ServerResponse> createItem(ServerRequest request) {
|
||||
return request.bodyToMono(FlashSaleItem.class)
|
||||
.flatMap(item -> flashSaleService.createItem(item)
|
||||
.flatMap(created -> successResponse("秒杀商品创建成功", created))
|
||||
.onErrorResume(this::errorResponse));
|
||||
}
|
||||
|
||||
@Operation(summary = "更新秒杀商品")
|
||||
public Mono<ServerResponse> updateItem(ServerRequest request) {
|
||||
Long id = Long.valueOf(request.pathVariable("id"));
|
||||
return request.bodyToMono(FlashSaleItem.class)
|
||||
.flatMap(item -> flashSaleService.updateItem(id, item)
|
||||
.flatMap(updated -> successResponse("秒杀商品更新成功", updated))
|
||||
.onErrorResume(this::errorResponse));
|
||||
}
|
||||
|
||||
@Operation(summary = "秒杀抢购")
|
||||
public Mono<ServerResponse> grab(ServerRequest request) {
|
||||
return request.bodyToMono(GrabRequest.class)
|
||||
.flatMap(body -> {
|
||||
if (body.getItemId() == null || body.getMemberId() == null) {
|
||||
return badRequest("itemId和memberId不能为空");
|
||||
}
|
||||
return flashSaleService.grab(body)
|
||||
.flatMap(order -> successResponse("抢购成功,请尽快支付", order))
|
||||
.onErrorResume(this::errorResponse);
|
||||
});
|
||||
}
|
||||
|
||||
@Operation(summary = "支付秒杀订单")
|
||||
public Mono<ServerResponse> payOrder(ServerRequest request) {
|
||||
Long orderId = Long.valueOf(request.pathVariable("orderId"));
|
||||
return flashSaleService.payOrder(orderId)
|
||||
.flatMap(order -> successResponse("支付成功", order))
|
||||
.onErrorResume(this::errorResponse);
|
||||
}
|
||||
|
||||
@Operation(summary = "取消秒杀订单")
|
||||
public Mono<ServerResponse> cancelOrder(ServerRequest request) {
|
||||
Long orderId = Long.valueOf(request.pathVariable("orderId"));
|
||||
return flashSaleService.cancelOrder(orderId)
|
||||
.flatMap(order -> successResponse("订单已取消", order))
|
||||
.onErrorResume(this::errorResponse);
|
||||
}
|
||||
|
||||
@Operation(summary = "获取会员秒杀订单")
|
||||
public Mono<ServerResponse> getOrdersByMember(ServerRequest request) {
|
||||
Long memberId = Long.valueOf(request.pathVariable("memberId"));
|
||||
return ServerResponse.ok()
|
||||
.body(flashSaleService.findOrdersByMemberId(memberId), FlashSaleOrder.class);
|
||||
}
|
||||
|
||||
private void normalizePageRequest(PageRequest pageRequest) {
|
||||
if (pageRequest.getPage() < 0) {
|
||||
pageRequest.setPage(0);
|
||||
}
|
||||
if (pageRequest.getSize() <= 0 || pageRequest.getSize() > 100) {
|
||||
pageRequest.setSize(10);
|
||||
}
|
||||
if (pageRequest.getSort() == null || pageRequest.getSort().isEmpty()) {
|
||||
pageRequest.setSort("id");
|
||||
}
|
||||
if (pageRequest.getOrder() == null || pageRequest.getOrder().isEmpty()) {
|
||||
pageRequest.setOrder("desc");
|
||||
}
|
||||
}
|
||||
|
||||
private Mono<ServerResponse> successResponse(String message, Object data) {
|
||||
Map<String, Object> response = new HashMap<>();
|
||||
response.put("success", true);
|
||||
response.put("message", message);
|
||||
if (data != null) {
|
||||
response.put("data", data);
|
||||
}
|
||||
return ServerResponse.ok().bodyValue(response);
|
||||
}
|
||||
|
||||
private Mono<ServerResponse> badRequest(String message) {
|
||||
Map<String, Object> error = new HashMap<>();
|
||||
error.put("success", false);
|
||||
error.put("message", message);
|
||||
return ServerResponse.badRequest().bodyValue(error);
|
||||
}
|
||||
|
||||
private Mono<ServerResponse> errorResponse(Throwable error) {
|
||||
Map<String, Object> response = new HashMap<>();
|
||||
response.put("success", false);
|
||||
response.put("message", error.getMessage());
|
||||
return ServerResponse.badRequest().bodyValue(response);
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package cn.novalon.gym.manage.coupon.flashsale.repository;
|
||||
|
||||
import cn.novalon.gym.manage.coupon.flashsale.domain.FlashSaleActivity;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
public interface IFlashSaleActivityRepository {
|
||||
|
||||
Mono<FlashSaleActivity> findById(Long id);
|
||||
|
||||
Flux<FlashSaleActivity> findAll(boolean includeDeleted);
|
||||
|
||||
Flux<FlashSaleActivity> findByKeyword(String keyword);
|
||||
|
||||
Flux<FlashSaleActivity> findByStatus(String status);
|
||||
|
||||
Flux<FlashSaleActivity> findByKeywordAndStatus(String keyword, String status);
|
||||
|
||||
Mono<FlashSaleActivity> save(FlashSaleActivity activity);
|
||||
|
||||
Mono<FlashSaleActivity> update(FlashSaleActivity activity);
|
||||
|
||||
Mono<Void> deleteById(Long id);
|
||||
|
||||
Mono<Void> updateStatus(Long id, String status);
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package cn.novalon.gym.manage.coupon.flashsale.repository;
|
||||
|
||||
import cn.novalon.gym.manage.coupon.flashsale.domain.FlashSaleItem;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
public interface IFlashSaleItemRepository {
|
||||
|
||||
Mono<FlashSaleItem> findById(Long id);
|
||||
|
||||
Flux<FlashSaleItem> findByActivityId(Long activityId);
|
||||
|
||||
Mono<FlashSaleItem> save(FlashSaleItem item);
|
||||
|
||||
Mono<FlashSaleItem> update(FlashSaleItem item);
|
||||
|
||||
Mono<Boolean> deductStock(Long id, int quantity);
|
||||
|
||||
Mono<Void> restoreStock(Long id, int quantity);
|
||||
|
||||
Mono<Void> incrementSoldCount(Long id, int count);
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package cn.novalon.gym.manage.coupon.flashsale.repository;
|
||||
|
||||
import cn.novalon.gym.manage.coupon.flashsale.domain.FlashSaleOrder;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.util.Collection;
|
||||
|
||||
public interface IFlashSaleOrderRepository {
|
||||
|
||||
Mono<FlashSaleOrder> findById(Long id);
|
||||
|
||||
Flux<FlashSaleOrder> findByMemberId(Long memberId);
|
||||
|
||||
Flux<FlashSaleOrder> findByActivityId(Long activityId);
|
||||
|
||||
Flux<FlashSaleOrder> findExpiredPendingOrders();
|
||||
|
||||
Mono<Long> countByItemIdAndMemberIdAndStatusIn(Long itemId, Long memberId, Collection<String> statuses);
|
||||
|
||||
Mono<FlashSaleOrder> save(FlashSaleOrder order);
|
||||
|
||||
Mono<Void> updateStatus(Long id, String status);
|
||||
|
||||
Mono<Void> markPaid(Long id, String status);
|
||||
}
|
||||
+109
@@ -0,0 +1,109 @@
|
||||
package cn.novalon.gym.manage.coupon.flashsale.repository.impl;
|
||||
|
||||
import cn.novalon.gym.manage.coupon.flashsale.converter.FlashSaleConverter;
|
||||
import cn.novalon.gym.manage.coupon.flashsale.dao.FlashSaleActivityDao;
|
||||
import cn.novalon.gym.manage.coupon.flashsale.domain.FlashSaleActivity;
|
||||
import cn.novalon.gym.manage.coupon.flashsale.entity.FlashSaleActivityEntity;
|
||||
import cn.novalon.gym.manage.coupon.flashsale.repository.IFlashSaleActivityRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Repository
|
||||
@Transactional
|
||||
public class FlashSaleActivityRepository implements IFlashSaleActivityRepository {
|
||||
|
||||
private final FlashSaleActivityDao activityDao;
|
||||
private final FlashSaleConverter converter;
|
||||
|
||||
public FlashSaleActivityRepository(FlashSaleActivityDao activityDao, FlashSaleConverter converter) {
|
||||
this.activityDao = activityDao;
|
||||
this.converter = converter;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<FlashSaleActivity> findById(Long id) {
|
||||
return activityDao.findByIdIsAndDeletedAtIsNull(id).map(converter::toActivity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flux<FlashSaleActivity> findAll(boolean includeDeleted) {
|
||||
if (includeDeleted) {
|
||||
return activityDao.findAll().map(converter::toActivity);
|
||||
}
|
||||
return activityDao.findAllByDeletedAtIsNull().map(converter::toActivity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flux<FlashSaleActivity> findByKeyword(String keyword) {
|
||||
if (keyword == null || keyword.isEmpty()) {
|
||||
return findAll(false);
|
||||
}
|
||||
return activityDao.findByNameContainingAndDeletedAtIsNull(keyword).map(converter::toActivity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flux<FlashSaleActivity> findByStatus(String status) {
|
||||
if (status == null || status.isEmpty()) {
|
||||
return findAll(false);
|
||||
}
|
||||
return activityDao.findByStatusAndDeletedAtIsNull(status).map(converter::toActivity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flux<FlashSaleActivity> findByKeywordAndStatus(String keyword, String status) {
|
||||
Flux<FlashSaleActivity> result = findByKeyword(keyword);
|
||||
if (status != null && !status.isEmpty()) {
|
||||
result = result.filter(a -> status.equals(a.getStatus()));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<FlashSaleActivity> save(FlashSaleActivity activity) {
|
||||
return activityDao.save(converter.toActivityEntity(activity)).map(converter::toActivity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<FlashSaleActivity> update(FlashSaleActivity activity) {
|
||||
return activityDao.findByIdIsAndDeletedAtIsNull(activity.getId())
|
||||
.switchIfEmpty(Mono.error(new RuntimeException("秒杀活动不存在")))
|
||||
.flatMap(existing -> {
|
||||
existing.markNotNew();
|
||||
if (activity.getName() != null) {
|
||||
existing.setName(activity.getName());
|
||||
}
|
||||
if (activity.getDescription() != null) {
|
||||
existing.setDescription(activity.getDescription());
|
||||
}
|
||||
if (activity.getStartTime() != null) {
|
||||
existing.setStartTime(activity.getStartTime());
|
||||
}
|
||||
if (activity.getEndTime() != null) {
|
||||
existing.setEndTime(activity.getEndTime());
|
||||
}
|
||||
if (activity.getPayTimeoutMinutes() != null) {
|
||||
existing.setPayTimeoutMinutes(activity.getPayTimeoutMinutes());
|
||||
}
|
||||
if (activity.getPerUserLimit() != null) {
|
||||
existing.setPerUserLimit(activity.getPerUserLimit());
|
||||
}
|
||||
existing.setUpdatedAt(LocalDateTime.now());
|
||||
return activityDao.save(existing);
|
||||
})
|
||||
.map(converter::toActivity);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Void> deleteById(Long id) {
|
||||
return activityDao.softDelete(id, LocalDateTime.now()).then();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Void> updateStatus(Long id, String status) {
|
||||
return activityDao.updateStatus(id, status, LocalDateTime.now()).then();
|
||||
}
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
package cn.novalon.gym.manage.coupon.flashsale.repository.impl;
|
||||
|
||||
import cn.novalon.gym.manage.coupon.flashsale.converter.FlashSaleConverter;
|
||||
import cn.novalon.gym.manage.coupon.flashsale.dao.FlashSaleItemDao;
|
||||
import cn.novalon.gym.manage.coupon.flashsale.domain.FlashSaleItem;
|
||||
import cn.novalon.gym.manage.coupon.flashsale.entity.FlashSaleItemEntity;
|
||||
import cn.novalon.gym.manage.coupon.flashsale.repository.IFlashSaleItemRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Repository
|
||||
@Transactional
|
||||
public class FlashSaleItemRepository implements IFlashSaleItemRepository {
|
||||
|
||||
private final FlashSaleItemDao itemDao;
|
||||
private final FlashSaleConverter converter;
|
||||
|
||||
public FlashSaleItemRepository(FlashSaleItemDao itemDao, FlashSaleConverter converter) {
|
||||
this.itemDao = itemDao;
|
||||
this.converter = converter;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<FlashSaleItem> findById(Long id) {
|
||||
return itemDao.findByIdIsAndDeletedAtIsNull(id).map(converter::toItem);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flux<FlashSaleItem> findByActivityId(Long activityId) {
|
||||
return itemDao.findByActivityIdAndDeletedAtIsNull(activityId).map(converter::toItem);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<FlashSaleItem> save(FlashSaleItem item) {
|
||||
return itemDao.save(converter.toItemEntity(item)).map(converter::toItem);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<FlashSaleItem> update(FlashSaleItem item) {
|
||||
return itemDao.findByIdIsAndDeletedAtIsNull(item.getId())
|
||||
.switchIfEmpty(Mono.error(new RuntimeException("秒杀商品不存在")))
|
||||
.flatMap(existing -> {
|
||||
existing.markNotNew();
|
||||
if (item.getProductType() != null) {
|
||||
existing.setProductType(item.getProductType());
|
||||
}
|
||||
if (item.getProductId() != null) {
|
||||
existing.setProductId(item.getProductId());
|
||||
}
|
||||
if (item.getProductName() != null) {
|
||||
existing.setProductName(item.getProductName());
|
||||
}
|
||||
if (item.getOriginalPrice() != null) {
|
||||
existing.setOriginalPrice(item.getOriginalPrice());
|
||||
}
|
||||
if (item.getSeckillPrice() != null) {
|
||||
existing.setSeckillPrice(item.getSeckillPrice());
|
||||
}
|
||||
if (item.getStock() != null) {
|
||||
existing.setStock(item.getStock());
|
||||
}
|
||||
if (item.getPerUserLimit() != null) {
|
||||
existing.setPerUserLimit(item.getPerUserLimit());
|
||||
}
|
||||
existing.setUpdatedAt(LocalDateTime.now());
|
||||
return itemDao.save(existing);
|
||||
})
|
||||
.map(converter::toItem);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Boolean> deductStock(Long id, int quantity) {
|
||||
return itemDao.deductStock(id, quantity, LocalDateTime.now())
|
||||
.map(rows -> rows != null && rows > 0);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Void> restoreStock(Long id, int quantity) {
|
||||
return itemDao.restoreStock(id, quantity, LocalDateTime.now()).then();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Void> incrementSoldCount(Long id, int count) {
|
||||
return itemDao.incrementSoldCount(id, count, LocalDateTime.now()).then();
|
||||
}
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
package cn.novalon.gym.manage.coupon.flashsale.repository.impl;
|
||||
|
||||
import cn.novalon.gym.manage.coupon.flashsale.converter.FlashSaleConverter;
|
||||
import cn.novalon.gym.manage.coupon.flashsale.dao.FlashSaleOrderDao;
|
||||
import cn.novalon.gym.manage.coupon.flashsale.domain.FlashSaleOrder;
|
||||
import cn.novalon.gym.manage.coupon.flashsale.enums.FlashSaleOrderStatus;
|
||||
import cn.novalon.gym.manage.coupon.flashsale.repository.IFlashSaleOrderRepository;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Collection;
|
||||
|
||||
@Repository
|
||||
@Transactional
|
||||
public class FlashSaleOrderRepository implements IFlashSaleOrderRepository {
|
||||
|
||||
private final FlashSaleOrderDao orderDao;
|
||||
private final FlashSaleConverter converter;
|
||||
|
||||
public FlashSaleOrderRepository(FlashSaleOrderDao orderDao, FlashSaleConverter converter) {
|
||||
this.orderDao = orderDao;
|
||||
this.converter = converter;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<FlashSaleOrder> findById(Long id) {
|
||||
return orderDao.findByIdIsAndDeletedAtIsNull(id).map(converter::toOrder);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flux<FlashSaleOrder> findByMemberId(Long memberId) {
|
||||
return orderDao.findByMemberIdAndDeletedAtIsNull(memberId).map(converter::toOrder);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flux<FlashSaleOrder> findByActivityId(Long activityId) {
|
||||
return orderDao.findByActivityIdAndDeletedAtIsNull(activityId).map(converter::toOrder);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flux<FlashSaleOrder> findExpiredPendingOrders() {
|
||||
return orderDao.findExpiredPendingOrders(
|
||||
FlashSaleOrderStatus.PENDING.name(), LocalDateTime.now()).map(converter::toOrder);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Long> countByItemIdAndMemberIdAndStatusIn(Long itemId, Long memberId, Collection<String> statuses) {
|
||||
return orderDao.countByItemIdAndMemberIdAndStatusInAndDeletedAtIsNull(itemId, memberId, statuses);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<FlashSaleOrder> save(FlashSaleOrder order) {
|
||||
return orderDao.save(converter.toOrderEntity(order)).map(converter::toOrder);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Void> updateStatus(Long id, String status) {
|
||||
return orderDao.updateStatus(id, status, LocalDateTime.now()).then();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Void> markPaid(Long id, String status) {
|
||||
return orderDao.markPaid(id, status, LocalDateTime.now(), LocalDateTime.now()).then();
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package cn.novalon.gym.manage.coupon.flashsale.scheduler;
|
||||
|
||||
import cn.novalon.gym.manage.coupon.flashsale.service.IFlashSaleActivityService;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 秒杀订单过期定时任务
|
||||
*
|
||||
* 功能:定期检查已过期的待支付订单,取消订单并恢复库存
|
||||
*/
|
||||
@Component
|
||||
public class FlashSaleOrderExpireScheduler {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(FlashSaleOrderExpireScheduler.class);
|
||||
|
||||
private final IFlashSaleActivityService flashSaleService;
|
||||
|
||||
public FlashSaleOrderExpireScheduler(IFlashSaleActivityService flashSaleService) {
|
||||
this.flashSaleService = flashSaleService;
|
||||
}
|
||||
|
||||
@Scheduled(fixedRate = 60000)
|
||||
public void processExpiredOrders() {
|
||||
logger.debug("定时任务开始检查过期秒杀订单");
|
||||
|
||||
flashSaleService.processExpiredOrders()
|
||||
.subscribe(
|
||||
count -> logger.debug("定时任务完成,处理了 {} 个过期秒杀订单", count),
|
||||
error -> logger.error("秒杀订单过期定时任务执行失败:{}", error.getMessage(), error)
|
||||
);
|
||||
}
|
||||
}
|
||||
+50
@@ -0,0 +1,50 @@
|
||||
package cn.novalon.gym.manage.coupon.flashsale.service;
|
||||
|
||||
import cn.novalon.gym.manage.common.dto.PageRequest;
|
||||
import cn.novalon.gym.manage.common.dto.PageResponse;
|
||||
import cn.novalon.gym.manage.coupon.flashsale.domain.FlashSaleActivity;
|
||||
import cn.novalon.gym.manage.coupon.flashsale.domain.FlashSaleItem;
|
||||
import cn.novalon.gym.manage.coupon.flashsale.domain.FlashSaleOrder;
|
||||
import cn.novalon.gym.manage.coupon.flashsale.domain.FlashSaleStatistics;
|
||||
import cn.novalon.gym.manage.coupon.flashsale.domain.GrabRequest;
|
||||
import reactor.core.publisher.Flux;
|
||||
import reactor.core.publisher.Mono;
|
||||
|
||||
public interface IFlashSaleActivityService {
|
||||
|
||||
Mono<FlashSaleActivity> findById(Long id);
|
||||
|
||||
Flux<FlashSaleActivity> findAll(boolean includeDeleted);
|
||||
|
||||
Flux<FlashSaleActivity> findByKeywordAndStatus(String keyword, String status);
|
||||
|
||||
Mono<PageResponse<FlashSaleActivity>> findByPage(PageRequest pageRequest, String status);
|
||||
|
||||
Mono<FlashSaleActivity> create(FlashSaleActivity activity);
|
||||
|
||||
Mono<FlashSaleActivity> update(Long id, FlashSaleActivity activity);
|
||||
|
||||
Mono<Void> delete(Long id);
|
||||
|
||||
Mono<FlashSaleActivity> publish(Long id);
|
||||
|
||||
Mono<FlashSaleActivity> terminate(Long id);
|
||||
|
||||
Flux<FlashSaleItem> findItemsByActivityId(Long activityId);
|
||||
|
||||
Mono<FlashSaleItem> createItem(FlashSaleItem item);
|
||||
|
||||
Mono<FlashSaleItem> updateItem(Long id, FlashSaleItem item);
|
||||
|
||||
Mono<FlashSaleOrder> grab(GrabRequest request);
|
||||
|
||||
Mono<FlashSaleOrder> payOrder(Long orderId);
|
||||
|
||||
Mono<FlashSaleOrder> cancelOrder(Long orderId);
|
||||
|
||||
Flux<FlashSaleOrder> findOrdersByMemberId(Long memberId);
|
||||
|
||||
Mono<FlashSaleStatistics> getStatistics(Long id);
|
||||
|
||||
Mono<Long> processExpiredOrders();
|
||||
}
|
||||
+390
@@ -0,0 +1,390 @@
|
||||
package cn.novalon.gym.manage.coupon.flashsale.service.impl;
|
||||
|
||||
import cn.novalon.gym.manage.common.dto.PageRequest;
|
||||
import cn.novalon.gym.manage.common.dto.PageResponse;
|
||||
import cn.novalon.gym.manage.common.util.SnowflakeId;
|
||||
import cn.novalon.gym.manage.coupon.flashsale.domain.FlashSaleActivity;
|
||||
import cn.novalon.gym.manage.coupon.flashsale.domain.FlashSaleItem;
|
||||
import cn.novalon.gym.manage.coupon.flashsale.domain.FlashSaleOrder;
|
||||
import cn.novalon.gym.manage.coupon.flashsale.domain.FlashSaleStatistics;
|
||||
import cn.novalon.gym.manage.coupon.flashsale.domain.GrabRequest;
|
||||
import cn.novalon.gym.manage.coupon.flashsale.enums.FlashSaleActivityStatus;
|
||||
import cn.novalon.gym.manage.coupon.flashsale.enums.FlashSaleOrderStatus;
|
||||
import cn.novalon.gym.manage.coupon.flashsale.repository.IFlashSaleActivityRepository;
|
||||
import cn.novalon.gym.manage.coupon.flashsale.repository.IFlashSaleItemRepository;
|
||||
import cn.novalon.gym.manage.coupon.flashsale.repository.IFlashSaleOrderRepository;
|
||||
import cn.novalon.gym.manage.coupon.flashsale.service.IFlashSaleActivityService;
|
||||
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.math.BigDecimal;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Arrays;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
|
||||
@Service
|
||||
public class FlashSaleActivityService implements IFlashSaleActivityService {
|
||||
|
||||
private static final Logger logger = LoggerFactory.getLogger(FlashSaleActivityService.class);
|
||||
|
||||
private final IFlashSaleActivityRepository activityRepository;
|
||||
private final IFlashSaleItemRepository itemRepository;
|
||||
private final IFlashSaleOrderRepository orderRepository;
|
||||
|
||||
public FlashSaleActivityService(IFlashSaleActivityRepository activityRepository,
|
||||
IFlashSaleItemRepository itemRepository,
|
||||
IFlashSaleOrderRepository orderRepository) {
|
||||
this.activityRepository = activityRepository;
|
||||
this.itemRepository = itemRepository;
|
||||
this.orderRepository = orderRepository;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<FlashSaleActivity> findById(Long id) {
|
||||
return activityRepository.findById(id);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flux<FlashSaleActivity> findAll(boolean includeDeleted) {
|
||||
return activityRepository.findAll(includeDeleted);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flux<FlashSaleActivity> findByKeywordAndStatus(String keyword, String status) {
|
||||
return activityRepository.findByKeywordAndStatus(keyword, status);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<PageResponse<FlashSaleActivity>> findByPage(PageRequest pageRequest, String status) {
|
||||
int page = Math.max(pageRequest.getPage(), 0);
|
||||
int size = pageRequest.getSize() <= 0 || pageRequest.getSize() > 100 ? 10 : pageRequest.getSize();
|
||||
String keyword = pageRequest.getKeyword();
|
||||
|
||||
return activityRepository.findByKeywordAndStatus(keyword, status)
|
||||
.sort(Comparator.comparing(FlashSaleActivity::getCreatedAt,
|
||||
Comparator.nullsLast(Comparator.reverseOrder())))
|
||||
.collectList()
|
||||
.map(list -> {
|
||||
long total = list.size();
|
||||
int fromIndex = Math.min(page * size, list.size());
|
||||
int toIndex = Math.min(fromIndex + size, list.size());
|
||||
List<FlashSaleActivity> content = list.subList(fromIndex, toIndex);
|
||||
int totalPages = size == 0 ? 0 : (int) Math.ceil((double) total / size);
|
||||
return new PageResponse<>(content, totalPages, total, page, size);
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<FlashSaleActivity> create(FlashSaleActivity activity) {
|
||||
return validateActivity(activity)
|
||||
.flatMap(validated -> {
|
||||
validated.generateId();
|
||||
validated.setStatus(FlashSaleActivityStatus.DRAFT.name());
|
||||
applyDefaults(validated);
|
||||
return activityRepository.save(validated);
|
||||
})
|
||||
.doOnSuccess(a -> logger.info("秒杀活动创建成功 - id={}, name={}", a.getId(), a.getName()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<FlashSaleActivity> update(Long id, FlashSaleActivity activity) {
|
||||
return activityRepository.findById(id)
|
||||
.switchIfEmpty(Mono.error(new RuntimeException("秒杀活动不存在")))
|
||||
.flatMap(existing -> {
|
||||
if (!FlashSaleActivityStatus.DRAFT.name().equals(existing.getStatus())) {
|
||||
return Mono.error(new RuntimeException("仅草稿状态的秒杀活动可编辑"));
|
||||
}
|
||||
activity.setId(id);
|
||||
return validateActivity(activity)
|
||||
.flatMap(activityRepository::update);
|
||||
})
|
||||
.doOnSuccess(a -> logger.info("秒杀活动更新成功 - id={}", id));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Void> delete(Long id) {
|
||||
return activityRepository.findById(id)
|
||||
.switchIfEmpty(Mono.error(new RuntimeException("秒杀活动不存在")))
|
||||
.flatMap(existing -> {
|
||||
if (!FlashSaleActivityStatus.DRAFT.name().equals(existing.getStatus())) {
|
||||
return Mono.error(new RuntimeException("仅草稿状态的秒杀活动可删除"));
|
||||
}
|
||||
return activityRepository.deleteById(id);
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<FlashSaleActivity> publish(Long id) {
|
||||
return activityRepository.findById(id)
|
||||
.switchIfEmpty(Mono.error(new RuntimeException("秒杀活动不存在")))
|
||||
.flatMap(existing -> {
|
||||
if (!FlashSaleActivityStatus.DRAFT.name().equals(existing.getStatus())) {
|
||||
return Mono.error(new RuntimeException("仅草稿状态的秒杀活动可发布"));
|
||||
}
|
||||
return validateActivity(existing)
|
||||
.flatMap(validated -> activityRepository.updateStatus(id, FlashSaleActivityStatus.ACTIVE.name())
|
||||
.then(activityRepository.findById(id)));
|
||||
})
|
||||
.doOnSuccess(a -> logger.info("秒杀活动发布成功 - id={}", id));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<FlashSaleActivity> terminate(Long id) {
|
||||
return activityRepository.findById(id)
|
||||
.switchIfEmpty(Mono.error(new RuntimeException("秒杀活动不存在")))
|
||||
.flatMap(existing -> {
|
||||
if (!FlashSaleActivityStatus.ACTIVE.name().equals(existing.getStatus())) {
|
||||
return Mono.error(new RuntimeException("仅进行中的秒杀活动可终止"));
|
||||
}
|
||||
return activityRepository.updateStatus(id, FlashSaleActivityStatus.TERMINATED.name())
|
||||
.then(activityRepository.findById(id));
|
||||
})
|
||||
.doOnSuccess(a -> logger.info("秒杀活动已终止 - id={}", id));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flux<FlashSaleItem> findItemsByActivityId(Long activityId) {
|
||||
return itemRepository.findByActivityId(activityId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<FlashSaleItem> createItem(FlashSaleItem item) {
|
||||
return validateItem(item)
|
||||
.flatMap(validated -> activityRepository.findById(validated.getActivityId())
|
||||
.switchIfEmpty(Mono.error(new RuntimeException("秒杀活动不存在")))
|
||||
.flatMap(activity -> {
|
||||
if (!FlashSaleActivityStatus.DRAFT.name().equals(activity.getStatus())) {
|
||||
return Mono.error(new RuntimeException("仅草稿状态的秒杀活动可添加商品"));
|
||||
}
|
||||
validated.setId(SnowflakeId.nextId());
|
||||
validated.setSoldCount(0);
|
||||
if (validated.getPerUserLimit() == null) {
|
||||
validated.setPerUserLimit(activity.getPerUserLimit() != null ? activity.getPerUserLimit() : 1);
|
||||
}
|
||||
return itemRepository.save(validated);
|
||||
}));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<FlashSaleItem> updateItem(Long id, FlashSaleItem item) {
|
||||
return itemRepository.findById(id)
|
||||
.switchIfEmpty(Mono.error(new RuntimeException("秒杀商品不存在")))
|
||||
.flatMap(existing -> activityRepository.findById(existing.getActivityId())
|
||||
.flatMap(activity -> {
|
||||
if (!FlashSaleActivityStatus.DRAFT.name().equals(activity.getStatus())) {
|
||||
return Mono.error(new RuntimeException("活动已发布,不可修改商品"));
|
||||
}
|
||||
item.setId(id);
|
||||
return validateItem(item)
|
||||
.flatMap(itemRepository::update);
|
||||
}));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<FlashSaleOrder> grab(GrabRequest request) {
|
||||
if (request.getItemId() == null || request.getMemberId() == null) {
|
||||
return Mono.error(new RuntimeException("itemId和memberId不能为空"));
|
||||
}
|
||||
int quantity = request.getQuantity() != null && request.getQuantity() > 0 ? request.getQuantity() : 1;
|
||||
|
||||
return itemRepository.findById(request.getItemId())
|
||||
.switchIfEmpty(Mono.error(new RuntimeException("秒杀商品不存在")))
|
||||
.flatMap(item -> activityRepository.findById(item.getActivityId())
|
||||
.switchIfEmpty(Mono.error(new RuntimeException("秒杀活动不存在")))
|
||||
.flatMap(activity -> validateActivityForGrab(activity)
|
||||
.then(checkUserLimit(item, activity, request.getMemberId(), quantity))
|
||||
.then(itemRepository.deductStock(item.getId(), quantity))
|
||||
.flatMap(success -> {
|
||||
if (!success) {
|
||||
return Mono.error(new RuntimeException("库存不足"));
|
||||
}
|
||||
return createOrder(item, activity, request.getMemberId(), quantity)
|
||||
.onErrorResume(e -> itemRepository.restoreStock(item.getId(), quantity)
|
||||
.then(Mono.error(e)));
|
||||
})));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<FlashSaleOrder> payOrder(Long orderId) {
|
||||
return orderRepository.findById(orderId)
|
||||
.switchIfEmpty(Mono.error(new RuntimeException("秒杀订单不存在")))
|
||||
.flatMap(order -> {
|
||||
if (!FlashSaleOrderStatus.PENDING.name().equals(order.getStatus())) {
|
||||
return Mono.error(new RuntimeException("订单状态不允许支付"));
|
||||
}
|
||||
if (order.getExpireAt() != null && order.getExpireAt().isBefore(LocalDateTime.now())) {
|
||||
return Mono.error(new RuntimeException("订单已过期"));
|
||||
}
|
||||
return orderRepository.markPaid(orderId, FlashSaleOrderStatus.PAID.name())
|
||||
.then(itemRepository.incrementSoldCount(order.getItemId(), order.getQuantity()))
|
||||
.then(orderRepository.findById(orderId));
|
||||
})
|
||||
.doOnSuccess(o -> logger.info("秒杀订单支付成功 - orderId={}", orderId));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<FlashSaleOrder> cancelOrder(Long orderId) {
|
||||
return orderRepository.findById(orderId)
|
||||
.switchIfEmpty(Mono.error(new RuntimeException("秒杀订单不存在")))
|
||||
.flatMap(order -> {
|
||||
if (!FlashSaleOrderStatus.PENDING.name().equals(order.getStatus())) {
|
||||
return Mono.error(new RuntimeException("仅待支付订单可取消"));
|
||||
}
|
||||
return orderRepository.updateStatus(orderId, FlashSaleOrderStatus.CANCELLED.name())
|
||||
.then(itemRepository.restoreStock(order.getItemId(), order.getQuantity()))
|
||||
.then(orderRepository.findById(orderId));
|
||||
})
|
||||
.doOnSuccess(o -> logger.info("秒杀订单已取消 - orderId={}", orderId));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Flux<FlashSaleOrder> findOrdersByMemberId(Long memberId) {
|
||||
return orderRepository.findByMemberId(memberId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<FlashSaleStatistics> getStatistics(Long id) {
|
||||
return activityRepository.findById(id)
|
||||
.switchIfEmpty(Mono.error(new RuntimeException("秒杀活动不存在")))
|
||||
.flatMap(activity -> orderRepository.findByActivityId(id)
|
||||
.collectList()
|
||||
.map(orders -> {
|
||||
FlashSaleStatistics stats = new FlashSaleStatistics();
|
||||
stats.setActivityId(id);
|
||||
stats.setTotalOrders(orders.size());
|
||||
stats.setPendingOrders(countByStatus(orders, FlashSaleOrderStatus.PENDING));
|
||||
stats.setPaidOrders(countByStatus(orders, FlashSaleOrderStatus.PAID));
|
||||
stats.setCancelledOrders(countByStatus(orders, FlashSaleOrderStatus.CANCELLED));
|
||||
stats.setExpiredOrders(countByStatus(orders, FlashSaleOrderStatus.EXPIRED));
|
||||
|
||||
long soldQty = orders.stream()
|
||||
.filter(o -> FlashSaleOrderStatus.PAID.name().equals(o.getStatus()))
|
||||
.mapToLong(o -> o.getQuantity() != null ? o.getQuantity() : 0)
|
||||
.sum();
|
||||
stats.setTotalSoldQuantity(soldQty);
|
||||
|
||||
BigDecimal revenue = orders.stream()
|
||||
.filter(o -> FlashSaleOrderStatus.PAID.name().equals(o.getStatus()))
|
||||
.map(o -> o.getPayAmount() != null ? o.getPayAmount() : BigDecimal.ZERO)
|
||||
.reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
stats.setTotalRevenue(revenue);
|
||||
|
||||
return stats;
|
||||
}));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Mono<Long> processExpiredOrders() {
|
||||
return orderRepository.findExpiredPendingOrders()
|
||||
.flatMap(order -> orderRepository.updateStatus(order.getId(), FlashSaleOrderStatus.EXPIRED.name())
|
||||
.then(itemRepository.restoreStock(order.getItemId(), order.getQuantity()))
|
||||
.thenReturn(1L))
|
||||
.reduce(0L, Long::sum)
|
||||
.doOnSuccess(count -> {
|
||||
if (count > 0) {
|
||||
logger.info("已处理 {} 个过期秒杀订单", count);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private Mono<FlashSaleOrder> createOrder(FlashSaleItem item, FlashSaleActivity activity,
|
||||
Long memberId, int quantity) {
|
||||
int timeoutMinutes = activity.getPayTimeoutMinutes() != null ? activity.getPayTimeoutMinutes() : 5;
|
||||
BigDecimal payAmount = item.getSeckillPrice().multiply(BigDecimal.valueOf(quantity));
|
||||
|
||||
FlashSaleOrder order = new FlashSaleOrder();
|
||||
order.setId(SnowflakeId.nextId());
|
||||
order.setActivityId(activity.getId());
|
||||
order.setItemId(item.getId());
|
||||
order.setMemberId(memberId);
|
||||
order.setQuantity(quantity);
|
||||
order.setPayAmount(payAmount);
|
||||
order.setStatus(FlashSaleOrderStatus.PENDING.name());
|
||||
order.setExpireAt(LocalDateTime.now().plusMinutes(timeoutMinutes));
|
||||
|
||||
return orderRepository.save(order);
|
||||
}
|
||||
|
||||
private Mono<Void> checkUserLimit(FlashSaleItem item, FlashSaleActivity activity,
|
||||
Long memberId, int quantity) {
|
||||
int itemLimit = item.getPerUserLimit() != null ? item.getPerUserLimit() : 1;
|
||||
int activityLimit = activity.getPerUserLimit() != null ? activity.getPerUserLimit() : 1;
|
||||
int effectiveLimit = Math.min(itemLimit, activityLimit);
|
||||
|
||||
return orderRepository.countByItemIdAndMemberIdAndStatusIn(
|
||||
item.getId(), memberId,
|
||||
Arrays.asList(FlashSaleOrderStatus.PENDING.name(), FlashSaleOrderStatus.PAID.name()))
|
||||
.flatMap(count -> {
|
||||
if (count + quantity > effectiveLimit) {
|
||||
return Mono.error(new RuntimeException("超出每人限购数量"));
|
||||
}
|
||||
return Mono.empty();
|
||||
});
|
||||
}
|
||||
|
||||
private Mono<Void> validateActivityForGrab(FlashSaleActivity activity) {
|
||||
if (!FlashSaleActivityStatus.ACTIVE.name().equals(activity.getStatus())) {
|
||||
return Mono.error(new RuntimeException("秒杀活动未开始或已结束"));
|
||||
}
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
if (activity.getStartTime() != null && now.isBefore(activity.getStartTime())) {
|
||||
return Mono.error(new RuntimeException("秒杀活动尚未开始"));
|
||||
}
|
||||
if (activity.getEndTime() != null && now.isAfter(activity.getEndTime())) {
|
||||
return Mono.error(new RuntimeException("秒杀活动已结束"));
|
||||
}
|
||||
return Mono.empty();
|
||||
}
|
||||
|
||||
private Mono<FlashSaleActivity> validateActivity(FlashSaleActivity activity) {
|
||||
if (activity.getName() == null || activity.getName().isBlank()) {
|
||||
return Mono.error(new RuntimeException("活动名称不能为空"));
|
||||
}
|
||||
if (activity.getStartTime() == null || activity.getEndTime() == null) {
|
||||
return Mono.error(new RuntimeException("活动开始和结束时间不能为空"));
|
||||
}
|
||||
if (activity.getEndTime().isBefore(activity.getStartTime())) {
|
||||
return Mono.error(new RuntimeException("结束时间不能早于开始时间"));
|
||||
}
|
||||
return Mono.just(activity);
|
||||
}
|
||||
|
||||
private Mono<FlashSaleItem> validateItem(FlashSaleItem item) {
|
||||
if (item.getActivityId() == null) {
|
||||
return Mono.error(new RuntimeException("活动ID不能为空"));
|
||||
}
|
||||
if (item.getProductType() == null || item.getProductName() == null) {
|
||||
return Mono.error(new RuntimeException("商品类型和名称不能为空"));
|
||||
}
|
||||
if (item.getProductId() == null) {
|
||||
return Mono.error(new RuntimeException("商品ID不能为空"));
|
||||
}
|
||||
if (item.getOriginalPrice() == null || item.getSeckillPrice() == null) {
|
||||
return Mono.error(new RuntimeException("原价和秒杀价不能为空"));
|
||||
}
|
||||
if (item.getSeckillPrice().compareTo(item.getOriginalPrice()) >= 0) {
|
||||
return Mono.error(new RuntimeException("秒杀价必须低于原价"));
|
||||
}
|
||||
if (item.getStock() == null || item.getStock() < 0) {
|
||||
return Mono.error(new RuntimeException("库存不能为空且不能为负数"));
|
||||
}
|
||||
return Mono.just(item);
|
||||
}
|
||||
|
||||
private void applyDefaults(FlashSaleActivity activity) {
|
||||
if (activity.getPayTimeoutMinutes() == null) {
|
||||
activity.setPayTimeoutMinutes(5);
|
||||
}
|
||||
if (activity.getPerUserLimit() == null) {
|
||||
activity.setPerUserLimit(1);
|
||||
}
|
||||
}
|
||||
|
||||
private long countByStatus(List<FlashSaleOrder> orders, FlashSaleOrderStatus status) {
|
||||
return orders.stream().filter(o -> status.name().equals(o.getStatus())).count();
|
||||
}
|
||||
}
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
package cn.novalon.gym.manage.coupon.groupbuy.converter;
|
||||
|
||||
import cn.hutool.core.bean.BeanUtil;
|
||||
import cn.novalon.gym.manage.coupon.groupbuy.domain.GroupBuyActivity;
|
||||
import cn.novalon.gym.manage.coupon.groupbuy.domain.GroupBuyParticipant;
|
||||
import cn.novalon.gym.manage.coupon.groupbuy.domain.GroupBuyTeam;
|
||||
import cn.novalon.gym.manage.coupon.groupbuy.entity.GroupBuyActivityEntity;
|
||||
import cn.novalon.gym.manage.coupon.groupbuy.entity.GroupBuyParticipantEntity;
|
||||
import cn.novalon.gym.manage.coupon.groupbuy.entity.GroupBuyTeamEntity;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Component
|
||||
public class GroupBuyConverter {
|
||||
|
||||
public GroupBuyActivity toActivity(GroupBuyActivityEntity entity) {
|
||||
if (entity == null) {
|
||||
return null;
|
||||
}
|
||||
GroupBuyActivity domain = new GroupBuyActivity();
|
||||
BeanUtil.copyProperties(entity, domain);
|
||||
return domain;
|
||||
}
|
||||
|
||||
public GroupBuyActivityEntity toActivityEntity(GroupBuyActivity domain) {
|
||||
if (domain == null) {
|
||||
return null;
|
||||
}
|
||||
GroupBuyActivityEntity entity = new GroupBuyActivityEntity();
|
||||
BeanUtil.copyProperties(domain, entity);
|
||||
if (domain.getId() != null) {
|
||||
entity.markNotNew();
|
||||
}
|
||||
return entity;
|
||||
}
|
||||
|
||||
public GroupBuyTeam toTeam(GroupBuyTeamEntity entity) {
|
||||
if (entity == null) {
|
||||
return null;
|
||||
}
|
||||
GroupBuyTeam domain = new GroupBuyTeam();
|
||||
BeanUtil.copyProperties(entity, domain);
|
||||
return domain;
|
||||
}
|
||||
|
||||
public GroupBuyTeamEntity toTeamEntity(GroupBuyTeam domain) {
|
||||
if (domain == null) {
|
||||
return null;
|
||||
}
|
||||
GroupBuyTeamEntity entity = new GroupBuyTeamEntity();
|
||||
BeanUtil.copyProperties(domain, entity);
|
||||
if (domain.getId() != null) {
|
||||
entity.markNotNew();
|
||||
}
|
||||
return entity;
|
||||
}
|
||||
|
||||
public GroupBuyParticipant toParticipant(GroupBuyParticipantEntity entity) {
|
||||
if (entity == null) {
|
||||
return null;
|
||||
}
|
||||
GroupBuyParticipant domain = new GroupBuyParticipant();
|
||||
BeanUtil.copyProperties(entity, domain);
|
||||
return domain;
|
||||
}
|
||||
|
||||
public GroupBuyParticipantEntity toParticipantEntity(GroupBuyParticipant domain) {
|
||||
if (domain == null) {
|
||||
return null;
|
||||
}
|
||||
GroupBuyParticipantEntity entity = new GroupBuyParticipantEntity();
|
||||
BeanUtil.copyProperties(domain, entity);
|
||||
if (domain.getId() != null) {
|
||||
entity.markNotNew();
|
||||
}
|
||||
return entity;
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package cn.novalon.gym.manage.coupon.groupbuy.dao;
|
||||
|
||||
import cn.novalon.gym.manage.coupon.groupbuy.entity.GroupBuyActivityEntity;
|
||||
import org.springframework.data.r2dbc.repository.Modifying;
|
||||
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
|
||||
public interface GroupBuyActivityDao extends R2dbcRepository<GroupBuyActivityEntity, Long> {
|
||||
|
||||
Mono<GroupBuyActivityEntity> findByIdIsAndDeletedAtIsNull(Long id);
|
||||
|
||||
Flux<GroupBuyActivityEntity> findAllByDeletedAtIsNull();
|
||||
|
||||
Flux<GroupBuyActivityEntity> findByNameContainingAndDeletedAtIsNull(String name);
|
||||
|
||||
Flux<GroupBuyActivityEntity> findByStatusAndDeletedAtIsNull(String status);
|
||||
|
||||
@Modifying
|
||||
@Query("UPDATE group_buy_activity SET deleted_at = :deletedAt WHERE id = :id")
|
||||
Mono<Integer> softDelete(Long id, LocalDateTime deletedAt);
|
||||
|
||||
@Modifying
|
||||
@Query("UPDATE group_buy_activity SET status = :status, updated_at = :updatedAt WHERE id = :id")
|
||||
Mono<Integer> updateStatus(Long id, String status, LocalDateTime updatedAt);
|
||||
|
||||
@Modifying
|
||||
@Query("UPDATE group_buy_activity SET sold_count = sold_count + :count, updated_at = :updatedAt WHERE id = :id")
|
||||
Mono<Integer> incrementSoldCount(Long id, int count, LocalDateTime updatedAt);
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package cn.novalon.gym.manage.coupon.groupbuy.dao;
|
||||
|
||||
import cn.novalon.gym.manage.coupon.groupbuy.entity.GroupBuyParticipantEntity;
|
||||
import org.springframework.data.r2dbc.repository.Modifying;
|
||||
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
|
||||
public interface GroupBuyParticipantDao extends R2dbcRepository<GroupBuyParticipantEntity, Long> {
|
||||
|
||||
Flux<GroupBuyParticipantEntity> findByTeamIdAndDeletedAtIsNull(Long teamId);
|
||||
|
||||
Flux<GroupBuyParticipantEntity> findByActivityIdAndDeletedAtIsNull(Long activityId);
|
||||
|
||||
@Query("""
|
||||
SELECT p.* FROM group_buy_participant p
|
||||
INNER JOIN group_buy_team t ON p.team_id = t.id
|
||||
WHERE p.activity_id = :activityId AND p.member_id = :memberId
|
||||
AND p.status = :participantStatus AND t.status = :teamStatus
|
||||
AND p.deleted_at IS NULL AND t.deleted_at IS NULL
|
||||
""")
|
||||
Flux<GroupBuyParticipantEntity> findActiveParticipantInFormingTeam(
|
||||
Long activityId, Long memberId, String participantStatus, String teamStatus);
|
||||
|
||||
Mono<Long> countByActivityIdAndDeletedAtIsNull(Long activityId);
|
||||
|
||||
@Modifying
|
||||
@Query("UPDATE group_buy_participant SET status = :status, updated_at = :updatedAt WHERE team_id = :teamId")
|
||||
Mono<Integer> updateStatusByTeamId(Long teamId, String status, LocalDateTime updatedAt);
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package cn.novalon.gym.manage.coupon.groupbuy.dao;
|
||||
|
||||
import cn.novalon.gym.manage.coupon.groupbuy.entity.GroupBuyTeamEntity;
|
||||
import org.springframework.data.r2dbc.repository.Modifying;
|
||||
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
|
||||
public interface GroupBuyTeamDao extends R2dbcRepository<GroupBuyTeamEntity, Long> {
|
||||
|
||||
Mono<GroupBuyTeamEntity> findByIdIsAndDeletedAtIsNull(Long id);
|
||||
|
||||
Flux<GroupBuyTeamEntity> findByActivityIdAndDeletedAtIsNull(Long activityId);
|
||||
|
||||
Flux<GroupBuyTeamEntity> findByActivityIdAndStatusAndDeletedAtIsNull(Long activityId, String status);
|
||||
|
||||
Flux<GroupBuyTeamEntity> findByStatusAndDeletedAtIsNull(String status);
|
||||
|
||||
@Query("SELECT * FROM group_buy_team WHERE status = :status AND expire_at < :now AND deleted_at IS NULL")
|
||||
Flux<GroupBuyTeamEntity> findExpiredFormingTeams(String status, LocalDateTime now);
|
||||
|
||||
@Modifying
|
||||
@Query("UPDATE group_buy_team SET status = :status, updated_at = :updatedAt WHERE id = :id")
|
||||
Mono<Integer> updateStatus(Long id, String status, LocalDateTime updatedAt);
|
||||
|
||||
@Modifying
|
||||
@Query("UPDATE group_buy_team SET current_members = current_members + :count, updated_at = :updatedAt WHERE id = :id")
|
||||
Mono<Integer> incrementCurrentMembers(Long id, int count, LocalDateTime updatedAt);
|
||||
|
||||
@Modifying
|
||||
@Query("UPDATE group_buy_team SET status = :status, success_at = :successAt, updated_at = :updatedAt WHERE id = :id")
|
||||
Mono<Integer> markSuccess(Long id, String status, LocalDateTime successAt, LocalDateTime updatedAt);
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package cn.novalon.gym.manage.coupon.groupbuy.domain;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
@Schema(description = "创建拼团团队请求")
|
||||
public class CreateTeamRequest {
|
||||
|
||||
private Long activityId;
|
||||
private Long memberId;
|
||||
|
||||
public Long getActivityId() {
|
||||
return activityId;
|
||||
}
|
||||
|
||||
public void setActivityId(Long activityId) {
|
||||
this.activityId = activityId;
|
||||
}
|
||||
|
||||
public Long getMemberId() {
|
||||
return memberId;
|
||||
}
|
||||
|
||||
public void setMemberId(Long memberId) {
|
||||
this.memberId = memberId;
|
||||
}
|
||||
}
|
||||
+138
@@ -0,0 +1,138 @@
|
||||
package cn.novalon.gym.manage.coupon.groupbuy.domain;
|
||||
|
||||
import cn.novalon.gym.manage.sys.core.domain.BaseDomain;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Schema(description = "拼团活动")
|
||||
public class GroupBuyActivity extends BaseDomain {
|
||||
|
||||
private String name;
|
||||
private String description;
|
||||
private String productType;
|
||||
private Long productId;
|
||||
private String productName;
|
||||
private BigDecimal originalPrice;
|
||||
private BigDecimal groupPrice;
|
||||
private Integer requiredMembers;
|
||||
private Integer validHours;
|
||||
private LocalDateTime startTime;
|
||||
private LocalDateTime endTime;
|
||||
private Integer stock;
|
||||
private Integer soldCount;
|
||||
private String status;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public String getProductType() {
|
||||
return productType;
|
||||
}
|
||||
|
||||
public void setProductType(String productType) {
|
||||
this.productType = productType;
|
||||
}
|
||||
|
||||
public Long getProductId() {
|
||||
return productId;
|
||||
}
|
||||
|
||||
public void setProductId(Long productId) {
|
||||
this.productId = productId;
|
||||
}
|
||||
|
||||
public String getProductName() {
|
||||
return productName;
|
||||
}
|
||||
|
||||
public void setProductName(String productName) {
|
||||
this.productName = productName;
|
||||
}
|
||||
|
||||
public BigDecimal getOriginalPrice() {
|
||||
return originalPrice;
|
||||
}
|
||||
|
||||
public void setOriginalPrice(BigDecimal originalPrice) {
|
||||
this.originalPrice = originalPrice;
|
||||
}
|
||||
|
||||
public BigDecimal getGroupPrice() {
|
||||
return groupPrice;
|
||||
}
|
||||
|
||||
public void setGroupPrice(BigDecimal groupPrice) {
|
||||
this.groupPrice = groupPrice;
|
||||
}
|
||||
|
||||
public Integer getRequiredMembers() {
|
||||
return requiredMembers;
|
||||
}
|
||||
|
||||
public void setRequiredMembers(Integer requiredMembers) {
|
||||
this.requiredMembers = requiredMembers;
|
||||
}
|
||||
|
||||
public Integer getValidHours() {
|
||||
return validHours;
|
||||
}
|
||||
|
||||
public void setValidHours(Integer validHours) {
|
||||
this.validHours = validHours;
|
||||
}
|
||||
|
||||
public LocalDateTime getStartTime() {
|
||||
return startTime;
|
||||
}
|
||||
|
||||
public void setStartTime(LocalDateTime startTime) {
|
||||
this.startTime = startTime;
|
||||
}
|
||||
|
||||
public LocalDateTime getEndTime() {
|
||||
return endTime;
|
||||
}
|
||||
|
||||
public void setEndTime(LocalDateTime endTime) {
|
||||
this.endTime = endTime;
|
||||
}
|
||||
|
||||
public Integer getStock() {
|
||||
return stock;
|
||||
}
|
||||
|
||||
public void setStock(Integer stock) {
|
||||
this.stock = stock;
|
||||
}
|
||||
|
||||
public Integer getSoldCount() {
|
||||
return soldCount;
|
||||
}
|
||||
|
||||
public void setSoldCount(Integer soldCount) {
|
||||
this.soldCount = soldCount;
|
||||
}
|
||||
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(String status) {
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
package cn.novalon.gym.manage.coupon.groupbuy.domain;
|
||||
|
||||
import cn.novalon.gym.manage.sys.core.domain.BaseDomain;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Schema(description = "拼团参与人")
|
||||
public class GroupBuyParticipant extends BaseDomain {
|
||||
|
||||
private Long teamId;
|
||||
private Long activityId;
|
||||
private Long memberId;
|
||||
private Boolean isLeader;
|
||||
private String status;
|
||||
private LocalDateTime joinAt;
|
||||
|
||||
public Long getTeamId() {
|
||||
return teamId;
|
||||
}
|
||||
|
||||
public void setTeamId(Long teamId) {
|
||||
this.teamId = teamId;
|
||||
}
|
||||
|
||||
public Long getActivityId() {
|
||||
return activityId;
|
||||
}
|
||||
|
||||
public void setActivityId(Long activityId) {
|
||||
this.activityId = activityId;
|
||||
}
|
||||
|
||||
public Long getMemberId() {
|
||||
return memberId;
|
||||
}
|
||||
|
||||
public void setMemberId(Long memberId) {
|
||||
this.memberId = memberId;
|
||||
}
|
||||
|
||||
public Boolean getIsLeader() {
|
||||
return isLeader;
|
||||
}
|
||||
|
||||
public void setIsLeader(Boolean isLeader) {
|
||||
this.isLeader = isLeader;
|
||||
}
|
||||
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(String status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public LocalDateTime getJoinAt() {
|
||||
return joinAt;
|
||||
}
|
||||
|
||||
public void setJoinAt(LocalDateTime joinAt) {
|
||||
this.joinAt = joinAt;
|
||||
}
|
||||
}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
package cn.novalon.gym.manage.coupon.groupbuy.domain;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
@Schema(description = "拼团统计数据")
|
||||
public class GroupBuyStatistics {
|
||||
|
||||
private Long activityId;
|
||||
private long totalTeams;
|
||||
private long formingTeams;
|
||||
private long successTeams;
|
||||
private long failedTeams;
|
||||
private long cancelledTeams;
|
||||
private long totalParticipants;
|
||||
private long soldCount;
|
||||
private BigDecimal totalRevenue;
|
||||
|
||||
public Long getActivityId() {
|
||||
return activityId;
|
||||
}
|
||||
|
||||
public void setActivityId(Long activityId) {
|
||||
this.activityId = activityId;
|
||||
}
|
||||
|
||||
public long getTotalTeams() {
|
||||
return totalTeams;
|
||||
}
|
||||
|
||||
public void setTotalTeams(long totalTeams) {
|
||||
this.totalTeams = totalTeams;
|
||||
}
|
||||
|
||||
public long getFormingTeams() {
|
||||
return formingTeams;
|
||||
}
|
||||
|
||||
public void setFormingTeams(long formingTeams) {
|
||||
this.formingTeams = formingTeams;
|
||||
}
|
||||
|
||||
public long getSuccessTeams() {
|
||||
return successTeams;
|
||||
}
|
||||
|
||||
public void setSuccessTeams(long successTeams) {
|
||||
this.successTeams = successTeams;
|
||||
}
|
||||
|
||||
public long getFailedTeams() {
|
||||
return failedTeams;
|
||||
}
|
||||
|
||||
public void setFailedTeams(long failedTeams) {
|
||||
this.failedTeams = failedTeams;
|
||||
}
|
||||
|
||||
public long getCancelledTeams() {
|
||||
return cancelledTeams;
|
||||
}
|
||||
|
||||
public void setCancelledTeams(long cancelledTeams) {
|
||||
this.cancelledTeams = cancelledTeams;
|
||||
}
|
||||
|
||||
public long getTotalParticipants() {
|
||||
return totalParticipants;
|
||||
}
|
||||
|
||||
public void setTotalParticipants(long totalParticipants) {
|
||||
this.totalParticipants = totalParticipants;
|
||||
}
|
||||
|
||||
public long getSoldCount() {
|
||||
return soldCount;
|
||||
}
|
||||
|
||||
public void setSoldCount(long soldCount) {
|
||||
this.soldCount = soldCount;
|
||||
}
|
||||
|
||||
public BigDecimal getTotalRevenue() {
|
||||
return totalRevenue;
|
||||
}
|
||||
|
||||
public void setTotalRevenue(BigDecimal totalRevenue) {
|
||||
this.totalRevenue = totalRevenue;
|
||||
}
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
package cn.novalon.gym.manage.coupon.groupbuy.domain;
|
||||
|
||||
import cn.novalon.gym.manage.sys.core.domain.BaseDomain;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Schema(description = "拼团团队")
|
||||
public class GroupBuyTeam extends BaseDomain {
|
||||
|
||||
private Long activityId;
|
||||
private Long leaderMemberId;
|
||||
private Integer requiredMembers;
|
||||
private Integer currentMembers;
|
||||
private String status;
|
||||
private LocalDateTime expireAt;
|
||||
private LocalDateTime successAt;
|
||||
|
||||
public Long getActivityId() {
|
||||
return activityId;
|
||||
}
|
||||
|
||||
public void setActivityId(Long activityId) {
|
||||
this.activityId = activityId;
|
||||
}
|
||||
|
||||
public Long getLeaderMemberId() {
|
||||
return leaderMemberId;
|
||||
}
|
||||
|
||||
public void setLeaderMemberId(Long leaderMemberId) {
|
||||
this.leaderMemberId = leaderMemberId;
|
||||
}
|
||||
|
||||
public Integer getRequiredMembers() {
|
||||
return requiredMembers;
|
||||
}
|
||||
|
||||
public void setRequiredMembers(Integer requiredMembers) {
|
||||
this.requiredMembers = requiredMembers;
|
||||
}
|
||||
|
||||
public Integer getCurrentMembers() {
|
||||
return currentMembers;
|
||||
}
|
||||
|
||||
public void setCurrentMembers(Integer currentMembers) {
|
||||
this.currentMembers = currentMembers;
|
||||
}
|
||||
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(String status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public LocalDateTime getExpireAt() {
|
||||
return expireAt;
|
||||
}
|
||||
|
||||
public void setExpireAt(LocalDateTime expireAt) {
|
||||
this.expireAt = expireAt;
|
||||
}
|
||||
|
||||
public LocalDateTime getSuccessAt() {
|
||||
return successAt;
|
||||
}
|
||||
|
||||
public void setSuccessAt(LocalDateTime successAt) {
|
||||
this.successAt = successAt;
|
||||
}
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package cn.novalon.gym.manage.coupon.groupbuy.domain;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
|
||||
@Schema(description = "加入拼团团队请求")
|
||||
public class JoinTeamRequest {
|
||||
|
||||
private Long memberId;
|
||||
|
||||
public Long getMemberId() {
|
||||
return memberId;
|
||||
}
|
||||
|
||||
public void setMemberId(Long memberId) {
|
||||
this.memberId = memberId;
|
||||
}
|
||||
}
|
||||
+166
@@ -0,0 +1,166 @@
|
||||
package cn.novalon.gym.manage.coupon.groupbuy.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.math.BigDecimal;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@Table("group_buy_activity")
|
||||
public class GroupBuyActivityEntity extends BaseEntity {
|
||||
|
||||
@Column("name")
|
||||
private String name;
|
||||
|
||||
@Column("description")
|
||||
private String description;
|
||||
|
||||
@Column("product_type")
|
||||
private String productType;
|
||||
|
||||
@Column("product_id")
|
||||
private Long productId;
|
||||
|
||||
@Column("product_name")
|
||||
private String productName;
|
||||
|
||||
@Column("original_price")
|
||||
private BigDecimal originalPrice;
|
||||
|
||||
@Column("group_price")
|
||||
private BigDecimal groupPrice;
|
||||
|
||||
@Column("required_members")
|
||||
private Integer requiredMembers;
|
||||
|
||||
@Column("valid_hours")
|
||||
private Integer validHours;
|
||||
|
||||
@Column("start_time")
|
||||
private LocalDateTime startTime;
|
||||
|
||||
@Column("end_time")
|
||||
private LocalDateTime endTime;
|
||||
|
||||
@Column("stock")
|
||||
private Integer stock;
|
||||
|
||||
@Column("sold_count")
|
||||
private Integer soldCount;
|
||||
|
||||
@Column("status")
|
||||
private String status;
|
||||
|
||||
public String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
public void setName(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
public String getDescription() {
|
||||
return description;
|
||||
}
|
||||
|
||||
public void setDescription(String description) {
|
||||
this.description = description;
|
||||
}
|
||||
|
||||
public String getProductType() {
|
||||
return productType;
|
||||
}
|
||||
|
||||
public void setProductType(String productType) {
|
||||
this.productType = productType;
|
||||
}
|
||||
|
||||
public Long getProductId() {
|
||||
return productId;
|
||||
}
|
||||
|
||||
public void setProductId(Long productId) {
|
||||
this.productId = productId;
|
||||
}
|
||||
|
||||
public String getProductName() {
|
||||
return productName;
|
||||
}
|
||||
|
||||
public void setProductName(String productName) {
|
||||
this.productName = productName;
|
||||
}
|
||||
|
||||
public BigDecimal getOriginalPrice() {
|
||||
return originalPrice;
|
||||
}
|
||||
|
||||
public void setOriginalPrice(BigDecimal originalPrice) {
|
||||
this.originalPrice = originalPrice;
|
||||
}
|
||||
|
||||
public BigDecimal getGroupPrice() {
|
||||
return groupPrice;
|
||||
}
|
||||
|
||||
public void setGroupPrice(BigDecimal groupPrice) {
|
||||
this.groupPrice = groupPrice;
|
||||
}
|
||||
|
||||
public Integer getRequiredMembers() {
|
||||
return requiredMembers;
|
||||
}
|
||||
|
||||
public void setRequiredMembers(Integer requiredMembers) {
|
||||
this.requiredMembers = requiredMembers;
|
||||
}
|
||||
|
||||
public Integer getValidHours() {
|
||||
return validHours;
|
||||
}
|
||||
|
||||
public void setValidHours(Integer validHours) {
|
||||
this.validHours = validHours;
|
||||
}
|
||||
|
||||
public LocalDateTime getStartTime() {
|
||||
return startTime;
|
||||
}
|
||||
|
||||
public void setStartTime(LocalDateTime startTime) {
|
||||
this.startTime = startTime;
|
||||
}
|
||||
|
||||
public LocalDateTime getEndTime() {
|
||||
return endTime;
|
||||
}
|
||||
|
||||
public void setEndTime(LocalDateTime endTime) {
|
||||
this.endTime = endTime;
|
||||
}
|
||||
|
||||
public Integer getStock() {
|
||||
return stock;
|
||||
}
|
||||
|
||||
public void setStock(Integer stock) {
|
||||
this.stock = stock;
|
||||
}
|
||||
|
||||
public Integer getSoldCount() {
|
||||
return soldCount;
|
||||
}
|
||||
|
||||
public void setSoldCount(Integer soldCount) {
|
||||
this.soldCount = soldCount;
|
||||
}
|
||||
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(String status) {
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
+77
@@ -0,0 +1,77 @@
|
||||
package cn.novalon.gym.manage.coupon.groupbuy.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;
|
||||
|
||||
@Table("group_buy_participant")
|
||||
public class GroupBuyParticipantEntity extends BaseEntity {
|
||||
|
||||
@Column("team_id")
|
||||
private Long teamId;
|
||||
|
||||
@Column("activity_id")
|
||||
private Long activityId;
|
||||
|
||||
@Column("member_id")
|
||||
private Long memberId;
|
||||
|
||||
@Column("is_leader")
|
||||
private Boolean isLeader;
|
||||
|
||||
@Column("status")
|
||||
private String status;
|
||||
|
||||
@Column("join_at")
|
||||
private LocalDateTime joinAt;
|
||||
|
||||
public Long getTeamId() {
|
||||
return teamId;
|
||||
}
|
||||
|
||||
public void setTeamId(Long teamId) {
|
||||
this.teamId = teamId;
|
||||
}
|
||||
|
||||
public Long getActivityId() {
|
||||
return activityId;
|
||||
}
|
||||
|
||||
public void setActivityId(Long activityId) {
|
||||
this.activityId = activityId;
|
||||
}
|
||||
|
||||
public Long getMemberId() {
|
||||
return memberId;
|
||||
}
|
||||
|
||||
public void setMemberId(Long memberId) {
|
||||
this.memberId = memberId;
|
||||
}
|
||||
|
||||
public Boolean getIsLeader() {
|
||||
return isLeader;
|
||||
}
|
||||
|
||||
public void setIsLeader(Boolean isLeader) {
|
||||
this.isLeader = isLeader;
|
||||
}
|
||||
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(String status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public LocalDateTime getJoinAt() {
|
||||
return joinAt;
|
||||
}
|
||||
|
||||
public void setJoinAt(LocalDateTime joinAt) {
|
||||
this.joinAt = joinAt;
|
||||
}
|
||||
}
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
package cn.novalon.gym.manage.coupon.groupbuy.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;
|
||||
|
||||
@Table("group_buy_team")
|
||||
public class GroupBuyTeamEntity extends BaseEntity {
|
||||
|
||||
@Column("activity_id")
|
||||
private Long activityId;
|
||||
|
||||
@Column("leader_member_id")
|
||||
private Long leaderMemberId;
|
||||
|
||||
@Column("required_members")
|
||||
private Integer requiredMembers;
|
||||
|
||||
@Column("current_members")
|
||||
private Integer currentMembers;
|
||||
|
||||
@Column("status")
|
||||
private String status;
|
||||
|
||||
@Column("expire_at")
|
||||
private LocalDateTime expireAt;
|
||||
|
||||
@Column("success_at")
|
||||
private LocalDateTime successAt;
|
||||
|
||||
public Long getActivityId() {
|
||||
return activityId;
|
||||
}
|
||||
|
||||
public void setActivityId(Long activityId) {
|
||||
this.activityId = activityId;
|
||||
}
|
||||
|
||||
public Long getLeaderMemberId() {
|
||||
return leaderMemberId;
|
||||
}
|
||||
|
||||
public void setLeaderMemberId(Long leaderMemberId) {
|
||||
this.leaderMemberId = leaderMemberId;
|
||||
}
|
||||
|
||||
public Integer getRequiredMembers() {
|
||||
return requiredMembers;
|
||||
}
|
||||
|
||||
public void setRequiredMembers(Integer requiredMembers) {
|
||||
this.requiredMembers = requiredMembers;
|
||||
}
|
||||
|
||||
public Integer getCurrentMembers() {
|
||||
return currentMembers;
|
||||
}
|
||||
|
||||
public void setCurrentMembers(Integer currentMembers) {
|
||||
this.currentMembers = currentMembers;
|
||||
}
|
||||
|
||||
public String getStatus() {
|
||||
return status;
|
||||
}
|
||||
|
||||
public void setStatus(String status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public LocalDateTime getExpireAt() {
|
||||
return expireAt;
|
||||
}
|
||||
|
||||
public void setExpireAt(LocalDateTime expireAt) {
|
||||
this.expireAt = expireAt;
|
||||
}
|
||||
|
||||
public LocalDateTime getSuccessAt() {
|
||||
return successAt;
|
||||
}
|
||||
|
||||
public void setSuccessAt(LocalDateTime successAt) {
|
||||
this.successAt = successAt;
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package cn.novalon.gym.manage.coupon.groupbuy.enums;
|
||||
|
||||
/**
|
||||
* 拼团活动状态
|
||||
*/
|
||||
public enum GroupBuyActivityStatus {
|
||||
DRAFT,
|
||||
ACTIVE,
|
||||
TERMINATED,
|
||||
EXPIRED
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user