Compare commits
72 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 53d1ce6fb2 | |||
| 4a4697c816 | |||
| df0e68469b | |||
| 97a5eff678 | |||
| feaf014b4a | |||
| ff899f491e | |||
| 922c5850b5 | |||
| 2e7c2ced43 | |||
| a9ccdab421 | |||
| 7e45ecd144 | |||
| cacc8997ec | |||
| 593f6f13e7 | |||
| 8ee326b43a | |||
| 8fb4e714d8 | |||
| a8e69e0850 | |||
| f5b5724e92 | |||
| 1e41f31271 | |||
| efd4d03037 | |||
| 80759f6793 | |||
| f8279129be | |||
| fc48db071e | |||
| 35e7532f1b | |||
| 0d143be7b3 | |||
| 2ffd1aa7d6 | |||
| 581cc995c6 | |||
| 2251f31524 | |||
| 4481819eba | |||
| 79eb07599e | |||
| a7f31083cf | |||
| 524182c478 | |||
| 3586a7d74b | |||
| 8da58a8f51 | |||
| 0b2146f237 | |||
| 7cc9a68144 | |||
| b5c8a087dd | |||
| 7a94145819 | |||
| 7e4035e0ae | |||
| e19324d0ef | |||
| e0e707edcb | |||
| 8ab528a74b | |||
| de7a359ead | |||
| fbb41911a2 | |||
| 223a427614 | |||
| 78c80c4b1d | |||
| 8af444b7ee | |||
| bdcd3b2bf0 | |||
| 544ddeec5a | |||
| 2f070e6b44 | |||
| de01a39848 | |||
| 03991319fd | |||
| a8c7a4061e | |||
| 0d2ed2aba5 | |||
| 906512f294 | |||
| a7f699a8b4 | |||
| 2df598c0d8 | |||
| 174e33053e | |||
| 29b73c1f67 | |||
| 7c08c685d0 | |||
| 53624fc259 | |||
| 574021d47c | |||
| 8dbd507dd2 | |||
| ddb77db605 | |||
| e673d96f6f | |||
| 85ed6f9196 | |||
| cd44caee57 | |||
| 2325c66c37 | |||
| 0afd1cc865 | |||
| 8b8920a53d | |||
| 3d284c8d3a | |||
| 538c1e0ad5 | |||
| 923d147574 | |||
| 6ea23b5a01 |
@@ -0,0 +1,202 @@
|
|||||||
|
import java.util.Base64;
|
||||||
|
import java.math.BigInteger;
|
||||||
|
import java.io.ByteArrayInputStream;
|
||||||
|
|
||||||
|
public class KeyAnalyzer {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
String privateKeyBase64 = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCcxAwrhZF+izz1gxQKOr4jnC05obIBHbl0DzHOcd4CaaDV7Kv1NRJKi33JhdDsW4JGgu16e5Rtzq1VzU5VWz5EKgGL46maOFwCkngJUTP/LC3JVf/wtJmYCm8xNE8C7GNNIqKzYEvUOEfXqagpVvVrGsQ9FpzFp2rP9hBmHY3yizVyPX/uT9S+af5TRxiaItj3SSJGgloaEMrnKOpb/EH7JwPSS0liAyT/NxPfOyyZHc22AvaAIOE5y+0PMUIKPuIdfpOrej3LVpO1Arc2hSgmdB+YIPSiBVYPXa6AuAmil9mpbtSikQJ7Uu7lX4JyTW4QxQ06rPFKnFWVKkzivAElAgMBAAECggEAJd0AJ37iTlMpDQ90xqe7hvRQxAu256gbQ9nrqLY97g0/KIw6WEZSPakFX6gvdvb/NzKmUyAIEKGLoh6tXdZk6qfOqc/6BeK47nIcBfwT9/zerjNUVvn34w4aHyNINieMMHQ+Id8PUZmqWH+Euz9ilVTosuyEPwUZulLvUQqwXzU5VnwVghURbUhDd+ecBJACWgemRun6d5241PQXNYAdH1k7cETd8GfIi3qclhhJrxi7tu5tq4YGCXQIoz7HCLim7GIvT0M+FRgSw2EOrHnAQNFeQ/vQbP71ttLoTxehL6Se9dfWrV5OI+Y/T7vR2F84Qt0iNbaxyJGir7siKDFIwQKBgQDXDzinx3/TasplM78pR/0CtuuKr1Ch02LOPrTosJ1qf1OohxQThowhOTxMsBlgYSKu9s1QRffUUXEqYXxd2B6lzDKfggwO6U2XxIcxWeNow0xoFfqcXYSg7Ga2sCr9uhdwxIdFQNF7SNBpT8ht4fJrRX6mWY1nHybpyTDQ4xoQNQKBgQC6m+yiOoi5JD3zVSSJq/iq5DJPA5B4aoP+t5u9lp2Q7iVO0QI5ilBlEKGE4VOU0glnXlDTfuqEYooMY85ekl4WGb3AOT0PhLL2i+gO2nlWBzf4HPzB/hibjfyPyniRM03cHkG3HXucL7Sne6FwERcfjEqjUd2cdP1l89PNrq4rMQKBgQCMmjABSWYh8/y1I5rEQ4OAJdVjC3GdC1Xa35ZpVybjvLEWSpHunhW5lvD8dllw8LC7UTI0XDpGPqTM/4VO2YBYB2PFc0Gs8g0/v0ZgFpOeJ6kpl80MM/wFNemFYTIKRoMSv/psZY9PmfBgGcBBTuquBXZjDcNr+yr2yAm5V/DvTQKBgHqRi94KoF8q5N39IKCkqhJlDH5FkxDktYoKw2rFkPzuzuZz9gghRyj6wXxsG9/2DWMt2dzw0czehFoa/CO188KEadPmRKr6uCmkP2nyKhxNZX+8WnB5G2Sg4DD6BjMpBYz8+qDx5ozx8LDJTYI0V4HLPgMD9JGdbgsXGhlREOkhAoGALr6IQOXnviWNAhCdc7rrsaMLMPbLZ1wqzWtQUG1JxDobbpzEP4CW/mvW5pMn58mSBg5qbXhyDI4fFP0CPb98QIz2tGnIzYyFzdKmF5Z1N7X1OF9O+tsSqASoBZzTqB4fr/o4mz0s9JCeriBR2LWjsbsDU13DTLsfQpWbtOnIy70=";
|
||||||
|
|
||||||
|
System.out.println("========== 密钥分析开始 ==========");
|
||||||
|
System.out.println("密钥长度: " + privateKeyBase64.length());
|
||||||
|
|
||||||
|
byte[] keyBytes = Base64.getDecoder().decode(privateKeyBase64);
|
||||||
|
System.out.println("解码后长度: " + keyBytes.length + " bytes");
|
||||||
|
|
||||||
|
// 打印前30字节
|
||||||
|
System.out.print("前30字节(hex): ");
|
||||||
|
for (int i = 0; i < 30 && i < keyBytes.length; i++) {
|
||||||
|
System.out.printf("%02X ", keyBytes[i]);
|
||||||
|
}
|
||||||
|
System.out.println();
|
||||||
|
|
||||||
|
// 解析ASN.1结构
|
||||||
|
try {
|
||||||
|
parseASN1(keyBytes);
|
||||||
|
} catch (Exception e) {
|
||||||
|
System.out.println("解析失败: " + e.getMessage());
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void parseASN1(byte[] keyBytes) throws Exception {
|
||||||
|
ByteArrayInputStream bis = new ByteArrayInputStream(keyBytes);
|
||||||
|
|
||||||
|
// 读取SEQUENCE
|
||||||
|
int tag = bis.read();
|
||||||
|
System.out.println("第一个tag: 0x" + Integer.toHexString(tag));
|
||||||
|
|
||||||
|
if (tag == 0x30) {
|
||||||
|
System.out.println("这是SEQUENCE");
|
||||||
|
|
||||||
|
// 读取长度
|
||||||
|
int len = readASN1Length(bis);
|
||||||
|
System.out.println("SEQUENCE长度: " + len);
|
||||||
|
|
||||||
|
// 检查下一个tag
|
||||||
|
int nextTag = bis.read();
|
||||||
|
System.out.println("下一个tag: 0x" + Integer.toHexString(nextTag));
|
||||||
|
|
||||||
|
if (nextTag == 0x02) {
|
||||||
|
// INTEGER
|
||||||
|
int intLen = readASN1Length(bis);
|
||||||
|
byte[] versionBytes = new byte[intLen];
|
||||||
|
bis.read(versionBytes);
|
||||||
|
int version = new BigInteger(versionBytes).intValue();
|
||||||
|
System.out.println("版本INTEGER值: " + version);
|
||||||
|
|
||||||
|
// 检查这是PKCS#8还是PKCS#1
|
||||||
|
// PKCS#8: version=0后是SEQUENCE(算法标识符)
|
||||||
|
// PKCS#1: version=0后是INTEGER(modulus)
|
||||||
|
int afterVersionTag = bis.read();
|
||||||
|
System.out.println("版本后的tag: 0x" + Integer.toHexString(afterVersionTag));
|
||||||
|
|
||||||
|
if (afterVersionTag == 0x30) {
|
||||||
|
System.out.println(">>> 这是PKCS#8格式 (version后是SEQUENCE)");
|
||||||
|
|
||||||
|
// 解析PKCS#8
|
||||||
|
// AlgorithmIdentifier: SEQUENCE { OID, NULL }
|
||||||
|
int algLen = readASN1Length(bis);
|
||||||
|
System.out.println("AlgorithmIdentifier长度: " + algLen);
|
||||||
|
|
||||||
|
// 跳过AlgorithmIdentifier内容
|
||||||
|
byte[] algBytes = new byte[algLen];
|
||||||
|
bis.read(algBytes);
|
||||||
|
|
||||||
|
// 打印OID
|
||||||
|
System.out.print("OID bytes: ");
|
||||||
|
for (int i = 0; i < algBytes.length; i++) {
|
||||||
|
System.out.printf("%02X ", algBytes[i]);
|
||||||
|
}
|
||||||
|
System.out.println();
|
||||||
|
|
||||||
|
// 下一个应该是OCTET STRING (包含私钥)
|
||||||
|
int octetTag = bis.read();
|
||||||
|
System.out.println("下一个tag: 0x" + Integer.toHexString(octetTag));
|
||||||
|
|
||||||
|
if (octetTag == 0x04) {
|
||||||
|
System.out.println("这是OCTET STRING (包含私钥数据)");
|
||||||
|
int octetLen = readASN1Length(bis);
|
||||||
|
System.out.println("OCTET STRING长度: " + octetLen);
|
||||||
|
|
||||||
|
// OCTET STRING内容是PKCS#1私钥
|
||||||
|
byte[] pkcs1Bytes = new byte[octetLen];
|
||||||
|
bis.read(pkcs1Bytes);
|
||||||
|
|
||||||
|
System.out.print("PKCS#1私钥前20字节: ");
|
||||||
|
for (int i = 0; i < 20; i++) {
|
||||||
|
System.out.printf("%02X ", pkcs1Bytes[i]);
|
||||||
|
}
|
||||||
|
System.out.println();
|
||||||
|
|
||||||
|
// 解析PKCS#1私钥
|
||||||
|
ByteArrayInputStream pkcs1Stream = new ByteArrayInputStream(pkcs1Bytes);
|
||||||
|
int pkcs1Tag = pkcs1Stream.read();
|
||||||
|
System.out.println("PKCS#1第一个tag: 0x" + Integer.toHexString(pkcs1Tag));
|
||||||
|
|
||||||
|
if (pkcs1Tag == 0x30) {
|
||||||
|
int pkcs1Len = readASN1Length(pkcs1Stream);
|
||||||
|
System.out.println("PKCS#1 SEQUENCE长度: " + pkcs1Len);
|
||||||
|
|
||||||
|
// version
|
||||||
|
int vTag = pkcs1Stream.read();
|
||||||
|
int vLen = readASN1Length(pkcs1Stream);
|
||||||
|
byte[] vBytes = new byte[vLen];
|
||||||
|
pkcs1Stream.read(vBytes);
|
||||||
|
System.out.println("PKCS#1版本: " + new BigInteger(vBytes));
|
||||||
|
|
||||||
|
// 解析私钥参数
|
||||||
|
parsePKCS1(pkcs1Stream);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (afterVersionTag == 0x02) {
|
||||||
|
System.out.println(">>> 这是PKCS#1格式 (version后是INTEGER)");
|
||||||
|
|
||||||
|
// 继续解析PKCS#1
|
||||||
|
parsePKCS1(bis);
|
||||||
|
} else {
|
||||||
|
System.out.println(">>> 未知格式 (tag: 0x" + Integer.toHexString(afterVersionTag) + ")");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void parsePKCS1(ByteArrayInputStream bis) throws Exception {
|
||||||
|
System.out.println("\n========== 解析PKCS#1私钥参数 ==========");
|
||||||
|
|
||||||
|
// modulus
|
||||||
|
BigInteger modulus = readASN1Integer(bis);
|
||||||
|
System.out.println("modulus长度: " + modulus.bitLength() + " bits");
|
||||||
|
|
||||||
|
// publicExponent
|
||||||
|
BigInteger publicExponent = readASN1Integer(bis);
|
||||||
|
System.out.println("publicExponent: " + publicExponent);
|
||||||
|
|
||||||
|
// privateExponent
|
||||||
|
BigInteger privateExponent = readASN1Integer(bis);
|
||||||
|
System.out.println("privateExponent长度: " + privateExponent.bitLength() + " bits");
|
||||||
|
|
||||||
|
// prime1
|
||||||
|
BigInteger prime1 = readASN1Integer(bis);
|
||||||
|
System.out.println("prime1长度: " + prime1.bitLength() + " bits");
|
||||||
|
|
||||||
|
// prime2
|
||||||
|
BigInteger prime2 = readASN1Integer(bis);
|
||||||
|
System.out.println("prime2长度: " + prime2.bitLength() + " bits");
|
||||||
|
|
||||||
|
// 验证 prime1 * prime2 == modulus
|
||||||
|
BigInteger calculatedModulus = prime1.multiply(prime2);
|
||||||
|
boolean valid = calculatedModulus.equals(modulus);
|
||||||
|
System.out.println("\n验证 prime1 * prime2 == modulus: " + valid);
|
||||||
|
|
||||||
|
if (!valid) {
|
||||||
|
System.out.println(">>> 密钥数学关系不正确!这是无效的RSA私钥");
|
||||||
|
System.out.println("计算得到的modulus长度: " + calculatedModulus.bitLength() + " bits");
|
||||||
|
}
|
||||||
|
|
||||||
|
// exponent1
|
||||||
|
BigInteger exponent1 = readASN1Integer(bis);
|
||||||
|
System.out.println("exponent1长度: " + exponent1.bitLength() + " bits");
|
||||||
|
|
||||||
|
// exponent2
|
||||||
|
BigInteger exponent2 = readASN1Integer(bis);
|
||||||
|
System.out.println("exponent2长度: " + exponent2.bitLength() + " bits");
|
||||||
|
|
||||||
|
// coefficient
|
||||||
|
BigInteger coefficient = readASN1Integer(bis);
|
||||||
|
System.out.println("coefficient长度: " + coefficient.bitLength() + " bits");
|
||||||
|
|
||||||
|
System.out.println("\n========== 解析完成 ==========");
|
||||||
|
}
|
||||||
|
|
||||||
|
static int readASN1Length(ByteArrayInputStream bis) throws Exception {
|
||||||
|
int firstByte = bis.read();
|
||||||
|
if ((firstByte & 0x80) == 0) {
|
||||||
|
return firstByte;
|
||||||
|
}
|
||||||
|
int numBytes = firstByte & 0x7F;
|
||||||
|
int length = 0;
|
||||||
|
for (int i = 0; i < numBytes; i++) {
|
||||||
|
length = (length << 8) | (bis.read() & 0xFF);
|
||||||
|
}
|
||||||
|
return length;
|
||||||
|
}
|
||||||
|
|
||||||
|
static BigInteger readASN1Integer(ByteArrayInputStream bis) throws Exception {
|
||||||
|
int tag = bis.read();
|
||||||
|
if (tag != 0x02) throw new Exception("期望INTEGER tag: 0x02, 实际: 0x" + Integer.toHexString(tag));
|
||||||
|
int len = readASN1Length(bis);
|
||||||
|
byte[] data = new byte[len];
|
||||||
|
bis.read(data);
|
||||||
|
return new BigInteger(1, data);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,272 @@
|
|||||||
|
# V10 团课预约业务场景测试数据
|
||||||
|
|
||||||
|
## 概述
|
||||||
|
|
||||||
|
本文档描述了 V10 版本新增的团课预约功能测试数据,覆盖了7种典型的预约业务场景,用于验证系统在不同会员卡状态下的正确处理逻辑。
|
||||||
|
|
||||||
|
**当前日期**: 2026-06-02
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 一、测试场景总览
|
||||||
|
|
||||||
|
| 场景 | 会员 | 会员卡状态 | 预约课程 | 预期结果 |
|
||||||
|
|-----|------|----------|---------|---------|
|
||||||
|
| 1 | 用户A | 无会员卡 | 次数卡团课 | 提示无可用会员卡 |
|
||||||
|
| 2 | 用户B | 时长卡已过期 | 次数卡团课 | 提示会员卡已过期 |
|
||||||
|
| 3 | 会员C | 时长卡有效 | 次数卡团课 | 预约成功 |
|
||||||
|
| 4 | 会员D | 次数卡次数=0 | 次数卡团课 | 提示剩余次数不足 |
|
||||||
|
| 5 | 会员E | 次数卡次数=5 | 次数卡团课 | 预约成功 |
|
||||||
|
| 6 | 会员F | 储值卡余额=30元 | 储值卡团课(需50元) | 提示余额不足 |
|
||||||
|
| 7 | 会员G | 储值卡余额=200元 | 储值卡团课(需50元) | 预约成功 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 二、测试会员数据
|
||||||
|
|
||||||
|
### 2.1 会员列表
|
||||||
|
|
||||||
|
| 会员编号 | 昵称 | 手机号 | 性别 | 创建时间 |
|
||||||
|
|---------|------|--------|------|---------|
|
||||||
|
| MEM_TEST_A | 用户A_无卡新用户 | 13800001001 | 男 | 2026-06-02 10:00:00 |
|
||||||
|
| MEM_TEST_B | 用户B_过期时长卡 | 13800001002 | 男 | 2026-05-01 10:00:00 |
|
||||||
|
| MEM_TEST_C | 会员C_有效时长卡 | 13800001003 | 女 | 2026-05-01 10:00:00 |
|
||||||
|
| MEM_TEST_D | 会员D_次数用尽 | 13800001004 | 男 | 2026-05-01 10:00:00 |
|
||||||
|
| MEM_TEST_E | 会员E_次数充足 | 13800001005 | 女 | 2026-05-01 10:00:00 |
|
||||||
|
| MEM_TEST_F | 会员F_储值卡余额不足 | 13800001006 | 男 | 2026-05-01 10:00:00 |
|
||||||
|
| MEM_TEST_G | 会员G_储值卡余额充足 | 13800001007 | 女 | 2026-05-01 10:00:00 |
|
||||||
|
|
||||||
|
### 2.2 会员场景说明
|
||||||
|
|
||||||
|
#### 场景1: 用户A - 无会员卡新用户
|
||||||
|
- **会员编号**: MEM_TEST_A
|
||||||
|
- **状态**: 2026-06-02 刚注册,尚未购买任何会员卡
|
||||||
|
- **测试目标**: 验证无会员卡用户申请团课预约时的错误提示
|
||||||
|
|
||||||
|
#### 场景2: 用户B - 时长卡已过期
|
||||||
|
- **会员编号**: MEM_TEST_B
|
||||||
|
- **状态**: 持有30天时长卡,于 2026-05-31 23:59:59 到期
|
||||||
|
- **测试目标**: 验证会员卡过期后的预约行为
|
||||||
|
|
||||||
|
#### 场景3: 会员C - 时长卡有效
|
||||||
|
- **会员编号**: MEM_TEST_C
|
||||||
|
- **状态**: 持有30天时长卡,到期时间 2026-07-02
|
||||||
|
- **测试目标**: 验证有效期内的时长卡可以正常预约次数卡团课
|
||||||
|
|
||||||
|
#### 场景4: 会员D - 次数卡耗尽
|
||||||
|
- **会员编号**: MEM_TEST_D
|
||||||
|
- **状态**: 持有10次卡,剩余次数 = 0
|
||||||
|
- **测试目标**: 验证次数耗尽后无法预约团课
|
||||||
|
|
||||||
|
#### 场景5: 会员E - 次数卡充足
|
||||||
|
- **会员编号**: MEM_TEST_E
|
||||||
|
- **状态**: 持有10次卡,剩余次数 = 5
|
||||||
|
- **测试目标**: 验证次数充足时正常预约
|
||||||
|
|
||||||
|
#### 场景6: 会员F - 储值卡余额不足
|
||||||
|
- **会员编号**: MEM_TEST_F
|
||||||
|
- **状态**: 持有储值卡,余额 = 30.00 元
|
||||||
|
- **测试目标**: 验证预约储值卡团课(需50元)时提示余额不足
|
||||||
|
|
||||||
|
#### 场景7: 会员G - 储值卡余额充足
|
||||||
|
- **会员编号**: MEM_TEST_G
|
||||||
|
- **状态**: 持有储值卡,余额 = 200.00 元
|
||||||
|
- **测试目标**: 验证余额充足时正常预约储值卡团课
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 三、团课课程数据
|
||||||
|
|
||||||
|
### 3.1 团课列表
|
||||||
|
|
||||||
|
| 课程名称 | 教练ID | 课程类型 | 开始时间 | 结束时间 | 最大人数 | 当前人数 | 状态 | 点卡额度 | 储值额度 |
|
||||||
|
|---------|-------|---------|---------|---------|---------|---------|------|---------|---------|
|
||||||
|
| 燃脂搏击_次数卡课程 | 102 | 2 | 2026-06-10 19:30:00 | 2026-06-10 20:30:00 | 20 | 0 | 正常 | 1 | 0.00 |
|
||||||
|
| 高端普拉提_储值卡课程 | 103 | 1 | 2026-06-11 19:00:00 | 2026-06-11 20:00:00 | 15 | 0 | 正常 | 0 | 50.00 |
|
||||||
|
|
||||||
|
### 3.2 课程说明
|
||||||
|
|
||||||
|
**燃脂搏击_次数卡课程**
|
||||||
|
- **收费类型**: 次数卡
|
||||||
|
- **消耗点数**: 1次
|
||||||
|
- **适用会员**: 时长卡、次数卡用户
|
||||||
|
- **课程描述**: 高强度间歇训练,配合音乐快速燃脂
|
||||||
|
|
||||||
|
**高端普拉提_储值卡课程**
|
||||||
|
- **收费类型**: 储值卡
|
||||||
|
- **消耗金额**: 50.00 元
|
||||||
|
- **适用会员**: 储值卡用户
|
||||||
|
- **课程描述**: 精准训练核心肌群
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 四、会员卡类型数据
|
||||||
|
|
||||||
|
| 卡名称 | 卡类型 | 价格 | 有效天数 | 总次数 | 面额 | 状态 |
|
||||||
|
|-------|-------|------|---------|-------|------|------|
|
||||||
|
| 30天时长卡 | TIME_CARD | 299.00 | 30 | - | - | 上架 |
|
||||||
|
| 10次卡 | COUNT_CARD | 499.00 | - | 10 | - | 上架 |
|
||||||
|
| 储值卡500 | STORED_VALUE_CARD | 500.00 | - | - | 500.00 | 上架 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 五、会员卡记录数据
|
||||||
|
|
||||||
|
### 5.1 记录列表
|
||||||
|
|
||||||
|
| 会员编号 | 卡名称 | 状态 | 剩余次数 | 剩余金额 | 过期时间 | 购买时间 |
|
||||||
|
|---------|-------|------|---------|---------|---------|---------|
|
||||||
|
| MEM_TEST_B | 30天时长卡 | EXPIRED | 0 | 0.00 | 2026-05-31 | 2026-05-01 |
|
||||||
|
| MEM_TEST_C | 30天时长卡 | ACTIVE | 0 | 0.00 | 2026-07-02 | 2026-06-02 |
|
||||||
|
| MEM_TEST_D | 10次卡 | ACTIVE | 0 | 0.00 | 2026-12-31 | 2026-05-01 |
|
||||||
|
| MEM_TEST_E | 10次卡 | ACTIVE | 5 | 0.00 | 2026-12-31 | 2026-05-01 |
|
||||||
|
| MEM_TEST_F | 储值卡500 | ACTIVE | 0 | 30.00 | 2027-06-02 | 2026-05-01 |
|
||||||
|
| MEM_TEST_G | 储值卡500 | ACTIVE | 0 | 200.00 | 2027-06-02 | 2026-05-01 |
|
||||||
|
|
||||||
|
### 5.2 详细说明
|
||||||
|
|
||||||
|
**用户B - 时长卡已过期**
|
||||||
|
```
|
||||||
|
会员ID: MEM_TEST_B
|
||||||
|
卡名称: 30天时长卡
|
||||||
|
状态: EXPIRED (已过期)
|
||||||
|
有效期: 2026-05-01 至 2026-05-31
|
||||||
|
剩余次数: 0
|
||||||
|
剩余金额: 0.00
|
||||||
|
```
|
||||||
|
|
||||||
|
**会员C - 时长卡有效**
|
||||||
|
```
|
||||||
|
会员ID: MEM_TEST_C
|
||||||
|
卡名称: 30天时长卡
|
||||||
|
状态: ACTIVE (有效)
|
||||||
|
有效期: 2026-06-02 至 2026-07-02
|
||||||
|
剩余次数: 0
|
||||||
|
剩余金额: 0.00
|
||||||
|
```
|
||||||
|
|
||||||
|
**会员D - 次数卡耗尽**
|
||||||
|
```
|
||||||
|
会员ID: MEM_TEST_D
|
||||||
|
卡名称: 10次卡
|
||||||
|
状态: ACTIVE (有效)
|
||||||
|
有效期: 2026-05-01 至 2026-12-31
|
||||||
|
剩余次数: 0 (已用尽)
|
||||||
|
剩余金额: 0.00
|
||||||
|
```
|
||||||
|
|
||||||
|
**会员E - 次数卡充足**
|
||||||
|
```
|
||||||
|
会员ID: MEM_TEST_E
|
||||||
|
卡名称: 10次卡
|
||||||
|
状态: ACTIVE (有效)
|
||||||
|
有效期: 2026-05-01 至 2026-12-31
|
||||||
|
剩余次数: 5
|
||||||
|
剩余金额: 0.00
|
||||||
|
```
|
||||||
|
|
||||||
|
**会员F - 储值卡余额不足**
|
||||||
|
```
|
||||||
|
会员ID: MEM_TEST_F
|
||||||
|
卡名称: 储值卡500
|
||||||
|
状态: ACTIVE (有效)
|
||||||
|
有效期: 2026-05-01 至 2027-06-02
|
||||||
|
剩余次数: 0
|
||||||
|
剩余金额: 30.00 (不足50.00)
|
||||||
|
```
|
||||||
|
|
||||||
|
**会员G - 储值卡余额充足**
|
||||||
|
```
|
||||||
|
会员ID: MEM_TEST_G
|
||||||
|
卡名称: 储值卡500
|
||||||
|
状态: ACTIVE (有效)
|
||||||
|
有效期: 2026-05-01 至 2027-06-02
|
||||||
|
剩余次数: 0
|
||||||
|
剩余金额: 200.00 (充足)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 六、SQL数据插入顺序
|
||||||
|
|
||||||
|
```sql
|
||||||
|
-- 1. 先插入会员用户 (A-G)
|
||||||
|
INSERT INTO member_user (member_no, nickname, phone, gender, is_deleted, created_at, updated_at) VALUES
|
||||||
|
('MEM_TEST_A', '用户A_无卡新用户', '13800001001', 1, false, '2026-06-02 10:00:00', '2026-06-02 10:00:00'),
|
||||||
|
('MEM_TEST_B', '用户B_过期时长卡', '13800001002', 1, false, '2026-05-01 10:00:00', '2026-05-01 10:00:00'),
|
||||||
|
('MEM_TEST_C', '会员C_有效时长卡', '13800001003', 2, false, '2026-05-01 10:00:00', '2026-05-01 10:00:00'),
|
||||||
|
('MEM_TEST_D', '会员D_次数用尽', '13800001004', 1, false, '2026-05-01 10:00:00', '2026-05-01 10:00:00'),
|
||||||
|
('MEM_TEST_E', '会员E_次数充足', '13800001005', 2, false, '2026-05-01 10:00:00', '2026-05-01 10:00:00'),
|
||||||
|
('MEM_TEST_F', '会员F_储值卡余额不足', '13800001006', 1, false, '2026-05-01 10:00:00', '2026-05-01 10:00:00'),
|
||||||
|
('MEM_TEST_G', '会员G_储值卡余额充足', '13800001007', 2, false, '2026-05-01 10:00:00', '2026-05-01 10:00:00');
|
||||||
|
|
||||||
|
-- 2. 插入团课课程
|
||||||
|
INSERT INTO group_course (course_name, coach_id, course_type, start_time, end_time, max_members, current_members, status, location, description, point_card_amount, stored_value_amount, create_by, created_at, updated_at) VALUES
|
||||||
|
('燃脂搏击_次数卡课程', 102, 2, '2026-06-10 19:30:00', '2026-06-10 20:30:00', 20, 0, '0', '综合训练区', '高强度间歇训练,配合音乐快速燃脂,消耗1次', 1, 0.00, 'admin', '2026-06-01 10:00:00', '2026-06-01 10:00:00');
|
||||||
|
|
||||||
|
INSERT INTO group_course (course_name, coach_id, course_type, start_time, end_time, max_members, current_members, status, location, description, point_card_amount, stored_value_amount, create_by, created_at, updated_at) VALUES
|
||||||
|
('高端普拉提_储值卡课程', 103, 1, '2026-06-11 19:00:00', '2026-06-11 20:00:00', 15, 0, '0', '普拉提教室', '精准训练核心肌群,消耗储值50元', 0, 50.00, 'admin', '2026-06-01 10:00:00', '2026-06-01 10:00:00');
|
||||||
|
|
||||||
|
-- 3. 插入会员卡类型
|
||||||
|
INSERT INTO member_card (member_card_name, member_card_type, member_card_price, member_card_validity_days, member_card_total_times, member_card_amount, member_card_status, extra_config, created_at, updated_at) VALUES
|
||||||
|
('30天时长卡', 'TIME_CARD', 299.00, 30, NULL, NULL, 1, '{}', '2026-01-01 00:00:00', '2026-01-01 00:00:00'),
|
||||||
|
('10次卡', 'COUNT_CARD', 499.00, NULL, 10, NULL, 1, '{}', '2026-01-01 00:00:00', '2026-01-01 00:00:00'),
|
||||||
|
('储值卡500', 'STORED_VALUE_CARD', 500.00, NULL, NULL, 500.00, 1, '{}', '2026-01-01 00:00:00', '2026-01-01 00:00:00');
|
||||||
|
|
||||||
|
-- 4. 插入会员卡记录
|
||||||
|
INSERT INTO member_card_record (member_id, member_card_id, status, remaining_times, remaining_amount, expire_time, purchase_time, version, card_composition, created_at, updated_at) VALUES
|
||||||
|
((SELECT id FROM member_user WHERE member_no = 'MEM_TEST_B'), (SELECT member_card_id FROM member_card WHERE member_card_name = '30天时长卡'), 'EXPIRED', 0, 0.00, '2026-05-31 23:59:59', '2026-05-01 10:00:00', 0, '{}', '2026-05-01 10:00:00', '2026-06-02 10:00:00');
|
||||||
|
|
||||||
|
INSERT INTO member_card_record (member_id, member_card_id, status, remaining_times, remaining_amount, expire_time, purchase_time, version, card_composition, created_at, updated_at) VALUES
|
||||||
|
((SELECT id FROM member_user WHERE member_no = 'MEM_TEST_C'), (SELECT member_card_id FROM member_card WHERE member_card_name = '30天时长卡'), 'ACTIVE', 0, 0.00, '2026-07-02 23:59:59', '2026-06-02 10:00:00', 0, '{}', '2026-06-02 10:00:00', '2026-06-02 10:00:00');
|
||||||
|
|
||||||
|
INSERT INTO member_card_record (member_id, member_card_id, status, remaining_times, remaining_amount, expire_time, purchase_time, version, card_composition, created_at, updated_at) VALUES
|
||||||
|
((SELECT id FROM member_user WHERE member_no = 'MEM_TEST_D'), (SELECT member_card_id FROM member_card WHERE member_card_name = '10次卡'), 'ACTIVE', 0, 0.00, '2026-12-31 23:59:59', '2026-05-01 10:00:00', 0, '{}', '2026-05-01 10:00:00', '2026-06-02 10:00:00');
|
||||||
|
|
||||||
|
INSERT INTO member_card_record (member_id, member_card_id, status, remaining_times, remaining_amount, expire_time, purchase_time, version, card_composition, created_at, updated_at) VALUES
|
||||||
|
((SELECT id FROM member_user WHERE member_no = 'MEM_TEST_E'), (SELECT member_card_id FROM member_card WHERE member_card_name = '10次卡'), 'ACTIVE', 5, 0.00, '2026-12-31 23:59:59', '2026-05-01 10:00:00', 0, '{}', '2026-05-01 10:00:00', '2026-06-02 10:00:00');
|
||||||
|
|
||||||
|
INSERT INTO member_card_record (member_id, member_card_id, status, remaining_times, remaining_amount, expire_time, purchase_time, version, card_composition, created_at, updated_at) VALUES
|
||||||
|
((SELECT id FROM member_user WHERE member_no = 'MEM_TEST_F'), (SELECT member_card_id FROM member_card WHERE member_card_name = '储值卡500'), 'ACTIVE', 0, 30.00, '2027-06-02 23:59:59', '2026-05-01 10:00:00', 0, '{}', '2026-05-01 10:00:00', '2026-06-02 10:00:00');
|
||||||
|
|
||||||
|
INSERT INTO member_card_record (member_id, member_card_id, status, remaining_times, remaining_amount, expire_time, purchase_time, version, card_composition, created_at, updated_at) VALUES
|
||||||
|
((SELECT id FROM member_user WHERE member_no = 'MEM_TEST_G'), (SELECT member_card_id FROM member_card WHERE member_card_name = '储值卡500'), 'ACTIVE', 0, 200.00, '2027-06-02 23:59:59', '2026-05-01 10:00:00', 0, '{}', '2026-05-01 10:00:00', '2026-06-02 10:00:00');
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 七、预期测试结果
|
||||||
|
|
||||||
|
### 7.1 成功场景
|
||||||
|
|
||||||
|
| 场景 | 会员 | 操作 | 预期结果 |
|
||||||
|
|-----|------|-----|---------|
|
||||||
|
| 3 | 会员C | 预约次数卡团课 | 预约成功,消耗时长卡1次 |
|
||||||
|
| 5 | 会员E | 预约次数卡团课 | 预约成功,次数减1 (5→4) |
|
||||||
|
| 7 | 会员G | 预约储值卡团课 | 预约成功,余额减50 (200→150) |
|
||||||
|
|
||||||
|
### 7.2 失败场景
|
||||||
|
|
||||||
|
| 场景 | 会员 | 操作 | 预期错误码 | 预期提示信息 |
|
||||||
|
|-----|------|-----|----------|------------|
|
||||||
|
| 1 | 用户A | 预约次数卡团课 | NO_CARD | 无可用会员卡 |
|
||||||
|
| 2 | 用户B | 预约次数卡团课 | CARD_EXPIRED | 会员卡已过期 |
|
||||||
|
| 4 | 会员D | 预约次数卡团课 | INSUFFICIENT_TIMES | 剩余次数不足 |
|
||||||
|
| 6 | 会员F | 预约储值卡团课 | INSUFFICIENT_BALANCE | 余额不足,当前余额30.00元,需50.00元 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 八、数据清理
|
||||||
|
|
||||||
|
测试完成后,可通过以下 SQL 清理测试数据:
|
||||||
|
|
||||||
|
```sql
|
||||||
|
-- 删除测试会员(会级联删除相关会员卡记录)
|
||||||
|
DELETE FROM member_user WHERE member_no LIKE 'MEM_TEST_%';
|
||||||
|
|
||||||
|
-- 删除测试团课
|
||||||
|
DELETE FROM group_course WHERE course_name LIKE '%_次数卡课程' OR course_name LIKE '%_储值卡课程';
|
||||||
|
|
||||||
|
-- 删除测试会员卡类型
|
||||||
|
DELETE FROM member_card WHERE member_card_name IN ('30天时长卡', '10次卡', '储值卡500');
|
||||||
|
```
|
||||||
@@ -0,0 +1,204 @@
|
|||||||
|
# V11 团课预约取消测试数据文档
|
||||||
|
|
||||||
|
## 文档说明
|
||||||
|
|
||||||
|
本文档描述了用于测试团课预约取消功能的测试数据,包含三种会员卡类型的取消预约场景。
|
||||||
|
|
||||||
|
## 测试场景概览
|
||||||
|
|
||||||
|
| 序号 | 场景描述 | 用户 | 会员卡类型 |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| 1 | 使用时长卡预约后取消 | 张三 | 时长卡(30天) |
|
||||||
|
| 2 | 使用次数卡预约后取消 | 李四 | 次数卡(10次) |
|
||||||
|
| 3 | 使用储值卡预约后取消 | 王五 | 储值卡(500元) |
|
||||||
|
|
||||||
|
## 测试用户数据
|
||||||
|
|
||||||
|
### 1. 张三(时长卡用户)
|
||||||
|
|
||||||
|
| 字段 | 值 |
|
||||||
|
| :--- | :--- |
|
||||||
|
| 会员编号 | `MEM_TEST_ZHANG` |
|
||||||
|
| 昵称 | 张三_时长卡用户 |
|
||||||
|
| 手机号 | 13800002001 |
|
||||||
|
| 性别 | 男(1) |
|
||||||
|
|
||||||
|
#### 会员卡信息
|
||||||
|
|
||||||
|
| 字段 | 值 |
|
||||||
|
| :--- | :--- |
|
||||||
|
| 卡类型 | 时长卡(TIME_CARD) |
|
||||||
|
| 卡名称 | 30天时长卡 |
|
||||||
|
| 状态 | ACTIVE(有效) |
|
||||||
|
| 到期时间 | 2026-07-02 23:59:59 |
|
||||||
|
| 购买时间 | 2026-06-02 10:00:00 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 2. 李四(次数卡用户)
|
||||||
|
|
||||||
|
| 字段 | 值 |
|
||||||
|
| :--- | :--- |
|
||||||
|
| 会员编号 | `MEM_TEST_LI` |
|
||||||
|
| 昵称 | 李四_次数卡用户 |
|
||||||
|
| 手机号 | 13800002002 |
|
||||||
|
| 性别 | 男(1) |
|
||||||
|
|
||||||
|
#### 会员卡信息
|
||||||
|
|
||||||
|
| 字段 | 值 |
|
||||||
|
| :--- | :--- |
|
||||||
|
| 卡类型 | 次数卡(COUNT_CARD) |
|
||||||
|
| 卡名称 | 10次卡 |
|
||||||
|
| 状态 | ACTIVE(有效) |
|
||||||
|
| 剩余次数 | 5次 |
|
||||||
|
| 到期时间 | 2026-12-31 23:59:59 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 3. 王五(储值卡用户)
|
||||||
|
|
||||||
|
| 字段 | 值 |
|
||||||
|
| :--- | :--- |
|
||||||
|
| 会员编号 | `MEM_TEST_WANG` |
|
||||||
|
| 昵称 | 王五_储值卡用户 |
|
||||||
|
| 手机号 | 13800002003 |
|
||||||
|
| 性别 | 女(2) |
|
||||||
|
|
||||||
|
#### 会员卡信息
|
||||||
|
|
||||||
|
| 字段 | 值 |
|
||||||
|
| :--- | :--- |
|
||||||
|
| 卡类型 | 储值卡(STORED_VALUE_CARD) |
|
||||||
|
| 卡名称 | 储值卡500 |
|
||||||
|
| 状态 | ACTIVE(有效) |
|
||||||
|
| 剩余金额 | 200.00元 |
|
||||||
|
| 到期时间 | 2027-06-02 23:59:59 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 测试课程数据
|
||||||
|
|
||||||
|
### 晚间瑜伽_取消测试
|
||||||
|
|
||||||
|
| 字段 | 值 |
|
||||||
|
| :--- | :--- |
|
||||||
|
| 课程名称 | 晚间瑜伽_取消测试 |
|
||||||
|
| 教练ID | 101 |
|
||||||
|
| 课程类型 | 1 |
|
||||||
|
| 开始时间 | 2026-06-15 19:00:00 |
|
||||||
|
| 结束时间 | 2026-06-15 20:00:00 |
|
||||||
|
| 上课地点 | 瑜伽教室 |
|
||||||
|
| 最大人数 | 20人 |
|
||||||
|
| 当前人数 | 3人(三位测试用户) |
|
||||||
|
| 状态 | 0(正常) |
|
||||||
|
| 次数消耗 | 1次 |
|
||||||
|
| 储值消耗 | 30.00元 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 预约记录数据
|
||||||
|
|
||||||
|
### 预约状态说明
|
||||||
|
|
||||||
|
| 状态码 | 含义 |
|
||||||
|
| :--- | :--- |
|
||||||
|
| `0` | 已预约(等待取消) |
|
||||||
|
| `1` | 已取消 |
|
||||||
|
| `2` | 已出席 |
|
||||||
|
| `3` | 缺席 |
|
||||||
|
|
||||||
|
### 预约记录详情
|
||||||
|
|
||||||
|
| 用户 | 预约时间 | 状态 | 课程名称 |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| 张三 | 2026-06-02 11:00:00 | 0(已预约) | 晚间瑜伽_取消测试 |
|
||||||
|
| 李四 | 2026-06-02 11:30:00 | 0(已预约) | 晚间瑜伽_取消测试 |
|
||||||
|
| 王五 | 2026-06-02 12:00:00 | 0(已预约) | 晚间瑜伽_取消测试 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 测试用例设计
|
||||||
|
|
||||||
|
### 场景1:时长卡用户取消预约
|
||||||
|
|
||||||
|
**前置条件:**
|
||||||
|
- 张三持有有效时长卡
|
||||||
|
- 张三已成功预约课程
|
||||||
|
- 当前时间 < 课程开始时间
|
||||||
|
|
||||||
|
**测试步骤:**
|
||||||
|
1. 调用取消预约接口,传入张三的预约记录ID
|
||||||
|
2. 验证预约状态变为 `1`(已取消)
|
||||||
|
3. 验证课程当前人数减1
|
||||||
|
4. 验证时长卡状态保持不变(时长卡取消预约不影响卡状态)
|
||||||
|
|
||||||
|
**预期结果:**
|
||||||
|
- 预约记录状态更新为已取消
|
||||||
|
- 课程剩余名额增加1
|
||||||
|
- 时长卡有效期不受影响
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 场景2:次数卡用户取消预约
|
||||||
|
|
||||||
|
**前置条件:**
|
||||||
|
- 李四持有次数卡,剩余5次
|
||||||
|
- 李四已成功预约课程(已扣除1次)
|
||||||
|
- 当前时间 < 课程开始时间
|
||||||
|
|
||||||
|
**测试步骤:**
|
||||||
|
1. 调用取消预约接口,传入李四的预约记录ID
|
||||||
|
2. 验证预约状态变为 `1`(已取消)
|
||||||
|
3. 验证课程当前人数减1
|
||||||
|
4. 验证次数卡剩余次数恢复为5次(返还1次)
|
||||||
|
|
||||||
|
**预期结果:**
|
||||||
|
- 预约记录状态更新为已取消
|
||||||
|
- 课程剩余名额增加1
|
||||||
|
- 次数卡返还1次,剩余次数恢复为5次
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 场景3:储值卡用户取消预约
|
||||||
|
|
||||||
|
**前置条件:**
|
||||||
|
- 王五持有储值卡,余额200元
|
||||||
|
- 王五已成功预约课程(已扣除30元)
|
||||||
|
- 当前时间 < 课程开始时间
|
||||||
|
|
||||||
|
**测试步骤:**
|
||||||
|
1. 调用取消预约接口,传入王五的预约记录ID
|
||||||
|
2. 验证预约状态变为 `1`(已取消)
|
||||||
|
3. 验证课程当前人数减1
|
||||||
|
4. 验证储值卡余额恢复为200元(返还30元)
|
||||||
|
|
||||||
|
**预期结果:**
|
||||||
|
- 预约记录状态更新为已取消
|
||||||
|
- 课程剩余名额增加1
|
||||||
|
- 储值卡返还30元,余额恢复为200元
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 数据文件位置
|
||||||
|
|
||||||
|
```
|
||||||
|
manage-db/src/main/resources/db/migration/V11__Insert_Cancel_Booking_Test_Data.sql
|
||||||
|
```
|
||||||
|
|
||||||
|
## 数据依赖
|
||||||
|
|
||||||
|
| 依赖文件 | 说明 |
|
||||||
|
| :--- | :--- |
|
||||||
|
| `V6__Create_GroupCourse_table.sql` | 团课相关表结构 |
|
||||||
|
| `V8__Create_Member_And_MemberCard.sql` | 会员和会员卡表结构 |
|
||||||
|
| `V9__Add_GroupCourse_Booking_Snapshot_Fields.sql` | 预约快照字段 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 注意事项
|
||||||
|
|
||||||
|
1. 测试数据中使用的日期均为未来日期,确保测试时课程尚未开始
|
||||||
|
2. 会员卡状态均为 ACTIVE,确保可以正常预约
|
||||||
|
3. 取消预约功能应在课程开始前24小时内允许操作(具体时间限制由业务逻辑决定)
|
||||||
|
4. 取消预约后应记录操作日志和交易流水
|
||||||
@@ -0,0 +1,400 @@
|
|||||||
|
# 团课预约场景测试数据文档
|
||||||
|
|
||||||
|
## 概述
|
||||||
|
|
||||||
|
本文档描述了团课预约功能的测试数据,覆盖了各种预约场景,用于验证系统在不同业务条件下的正确性和健壮性。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 一、测试数据概览
|
||||||
|
|
||||||
|
| 数据类别 | 数量 | 说明 |
|
||||||
|
|---------|------|------|
|
||||||
|
| 测试会员 | 5个 | 覆盖不同会员卡状态 |
|
||||||
|
| 会员卡类型 | 8种 | 次卡/时长卡/储值卡 |
|
||||||
|
| 会员卡记录 | 5条 | 会员持有的实际卡 |
|
||||||
|
| 团课预约记录 | 4条 | 不同状态的预约 |
|
||||||
|
| 交易流水 | 27条 | 完整的消费记录 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 二、会员测试数据
|
||||||
|
|
||||||
|
### 2.1 会员列表
|
||||||
|
|
||||||
|
| 会员ID | 会员编号 | 昵称 | 手机号 | 性别 | 会员卡状态 |
|
||||||
|
|--------|---------|------|--------|------|-----------|
|
||||||
|
| 1001 | MEM202606001 | 新用户小张 | 13800138001 | 男 | 无会员卡 |
|
||||||
|
| 1002 | MEM202606002 | 额度耗尽用户 | 13800138002 | 女 | 次卡已用完 |
|
||||||
|
| 1003 | MEM202606003 | 额度充足用户 | 13800138003 | 男 | 次卡剩余8次 |
|
||||||
|
| 1004 | MEM202606004 | 过期卡用户 | 13800138004 | 女 | 月卡已过期 |
|
||||||
|
| 1005 | MEM202606005 | 多卡用户小李 | 13800138005 | 男 | 次卡+储值卡 |
|
||||||
|
|
||||||
|
### 2.2 会员详情
|
||||||
|
|
||||||
|
**会员1001 - 新用户小张**
|
||||||
|
- 状态:新注册用户,尚未购买任何会员卡
|
||||||
|
- 用途:测试无会员卡情况下的预约行为
|
||||||
|
|
||||||
|
**会员1002 - 额度耗尽用户**
|
||||||
|
- 状态:持有10次团课卡,已全部用完
|
||||||
|
- 用途:测试会员卡额度耗尽时的预约行为
|
||||||
|
|
||||||
|
**会员1003 - 额度充足用户**
|
||||||
|
- 状态:持有20次团课卡,剩余8次
|
||||||
|
- 用途:测试正常预约流程
|
||||||
|
|
||||||
|
**会员1004 - 过期卡用户**
|
||||||
|
- 状态:持有月卡,已于2026-05-31过期
|
||||||
|
- 用途:测试过期会员卡的预约行为
|
||||||
|
|
||||||
|
**会员1005 - 多卡用户小李**
|
||||||
|
- 状态:持有50次团课卡(剩余45次) + 500元储值卡(剩余350元)
|
||||||
|
- 用途:测试多会员卡用户选择支付方式的场景
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 三、会员卡类型数据
|
||||||
|
|
||||||
|
### 3.1 次卡类型
|
||||||
|
|
||||||
|
| 卡类型ID | 卡名称 | 类型 | 价格 | 有效天数 | 总次数 | 状态 |
|
||||||
|
|---------|-------|------|------|---------|-------|------|
|
||||||
|
| 101 | 10次团课卡 | COUNT_CARD | 299.00 | 90 | 10 | 上架 |
|
||||||
|
| 102 | 20次团课卡 | COUNT_CARD | 499.00 | 180 | 20 | 上架 |
|
||||||
|
| 103 | 50次团课卡 | COUNT_CARD | 999.00 | 365 | 50 | 上架 |
|
||||||
|
|
||||||
|
### 3.2 时长卡类型
|
||||||
|
|
||||||
|
| 卡类型ID | 卡名称 | 类型 | 价格 | 有效天数 | 状态 |
|
||||||
|
|---------|-------|------|------|---------|------|
|
||||||
|
| 201 | 月卡 | TIME_CARD | 399.00 | 30 | 上架 |
|
||||||
|
| 202 | 季卡 | TIME_CARD | 899.00 | 90 | 上架 |
|
||||||
|
| 203 | 年卡 | TIME_CARD | 2999.00 | 365 | 上架 |
|
||||||
|
|
||||||
|
### 3.3 储值卡类型
|
||||||
|
|
||||||
|
| 卡类型ID | 卡名称 | 类型 | 价格 | 面额 | 有效天数 | 状态 |
|
||||||
|
|---------|-------|------|------|------|---------|------|
|
||||||
|
| 301 | 500元储值卡 | STORED_VALUE_CARD | 500.00 | 500.00 | 365 | 上架 |
|
||||||
|
| 302 | 1000元储值卡 | STORED_VALUE_CARD | 1000.00 | 1000.00 | 365 | 上架 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 四、会员卡记录数据(会员持有的卡)
|
||||||
|
|
||||||
|
| 记录ID | 会员ID | 卡类型ID | 状态 | 剩余次数 | 剩余金额 | 到期时间 | 购买时间 |
|
||||||
|
|-------|--------|---------|------|---------|---------|---------|---------|
|
||||||
|
| 2001 | 1002 | 101 | USED_UP | 0 | 0.00 | 2026-09-01 | 2026-06-01 |
|
||||||
|
| 2002 | 1003 | 102 | ACTIVE | 8 | 0.00 | 2026-12-01 | 2026-06-01 |
|
||||||
|
| 2003 | 1004 | 201 | EXPIRED | 0 | 0.00 | 2026-05-31 | 2026-05-01 |
|
||||||
|
| 2004 | 1005 | 103 | ACTIVE | 45 | 0.00 | 2027-06-01 | 2026-06-01 |
|
||||||
|
| 2005 | 1005 | 301 | ACTIVE | 0 | 350.00 | 2027-06-01 | 2026-05-15 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 五、团课预约记录数据
|
||||||
|
|
||||||
|
| 预约ID | 课程ID | 会员ID | 会员卡记录ID | 预约时间 | 状态 | 课程名称 |
|
||||||
|
|-------|-------|--------|-------------|---------|------|---------|
|
||||||
|
| 3001 | 1 | 1003 | 2002 | 2026-06-01 15:30 | 已预约(0) | 极速燃脂单车 |
|
||||||
|
| 3002 | 2 | 1003 | 2002 | 2026-06-01 10:00 | 已取消(1) | 清晨流瑜伽 |
|
||||||
|
| 3003 | 6 | 1003 | 2002 | 2026-05-28 19:00 | 已出席(2) | 蜜桃臀塑造 |
|
||||||
|
| 3004 | 7 | 1002 | 2001 | 2026-05-30 10:00 | 缺席(3) | 午间冥想放松 |
|
||||||
|
|
||||||
|
### 状态说明
|
||||||
|
|
||||||
|
| 状态码 | 状态名称 | 说明 |
|
||||||
|
|-------|---------|------|
|
||||||
|
| 0 | 已预约 | 用户已成功预约,等待上课 |
|
||||||
|
| 1 | 已取消 | 用户主动取消预约 |
|
||||||
|
| 2 | 已出席 | 用户已按时参加课程 |
|
||||||
|
| 3 | 缺席 | 用户预约后未出席 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 六、测试场景详解
|
||||||
|
|
||||||
|
### 场景1:新注册用户无会员卡预约
|
||||||
|
|
||||||
|
**测试目标**:验证系统对无会员卡用户的预约拦截
|
||||||
|
|
||||||
|
**测试数据**:
|
||||||
|
- 用户ID:1001(新用户小张)
|
||||||
|
- 目标课程:任意课程
|
||||||
|
|
||||||
|
**预期结果**:
|
||||||
|
- 返回错误信息:"未绑定会员卡,请先购买会员卡"
|
||||||
|
- HTTP状态码:400 Bad Request
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 场景2:会员卡额度耗尽预约
|
||||||
|
|
||||||
|
**测试目标**:验证系统对额度耗尽会员卡的预约拦截
|
||||||
|
|
||||||
|
**测试数据**:
|
||||||
|
- 用户ID:1002(额度耗尽用户)
|
||||||
|
- 会员卡记录ID:2001
|
||||||
|
- 剩余次数:0
|
||||||
|
|
||||||
|
**预期结果**:
|
||||||
|
- 返回错误信息:"会员卡余额不足"
|
||||||
|
- HTTP状态码:400 Bad Request
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 场景3:会员卡额度充足预约
|
||||||
|
|
||||||
|
**测试目标**:验证正常预约流程
|
||||||
|
|
||||||
|
**测试数据**:
|
||||||
|
- 用户ID:1003(额度充足用户)
|
||||||
|
- 会员卡记录ID:2002
|
||||||
|
- 剩余次数:8
|
||||||
|
- 目标课程:课程ID=1(极速燃脂单车)
|
||||||
|
|
||||||
|
**预期结果**:
|
||||||
|
- 预约成功
|
||||||
|
- 会员卡剩余次数减1(变为7次)
|
||||||
|
- 生成预约记录
|
||||||
|
- HTTP状态码:200 OK
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 场景4:会员卡已过期预约
|
||||||
|
|
||||||
|
**测试目标**:验证系统对过期会员卡的预约拦截
|
||||||
|
|
||||||
|
**测试数据**:
|
||||||
|
- 用户ID:1004(过期卡用户)
|
||||||
|
- 会员卡记录ID:2003
|
||||||
|
- 状态:EXPIRED
|
||||||
|
- 到期时间:2026-05-31
|
||||||
|
|
||||||
|
**预期结果**:
|
||||||
|
- 返回错误信息:"会员卡已过期"
|
||||||
|
- HTTP状态码:400 Bad Request
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 场景5:课程已满员预约---------------
|
||||||
|
|
||||||
|
**测试目标**:验证系统对满员课程的预约拦截
|
||||||
|
|
||||||
|
**测试数据**:
|
||||||
|
- 课程ID:3(燃脂搏击)
|
||||||
|
- 当前人数:20/20
|
||||||
|
|
||||||
|
**预期结果**:
|
||||||
|
- 返回错误信息:"课程已满员"
|
||||||
|
- HTTP状态码:400 Bad Request
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 场景6:课程已取消预约
|
||||||
|
|
||||||
|
**测试目标**:验证系统对已取消课程的预约拦截
|
||||||
|
|
||||||
|
**测试数据**:
|
||||||
|
- 课程ID:5(周末冥想修复)
|
||||||
|
- 状态:1(已取消)
|
||||||
|
|
||||||
|
**预期结果**:
|
||||||
|
- 返回错误信息:"课程已取消"
|
||||||
|
- HTTP状态码:400 Bad Request
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 场景7:课程已结束预约
|
||||||
|
|
||||||
|
**测试目标**:验证系统对已结束课程的预约拦截
|
||||||
|
|
||||||
|
**测试数据**:
|
||||||
|
- 课程ID:6(蜜桃臀塑造)或 7(午间冥想放松)
|
||||||
|
- 状态:2(已结束)
|
||||||
|
|
||||||
|
**预期结果**:
|
||||||
|
- 返回错误信息:"课程已结束"
|
||||||
|
- HTTP状态码:400 Bad Request
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 场景8:超出预约时间预约
|
||||||
|
|
||||||
|
**测试目标**:验证系统对预约时间窗口的控制
|
||||||
|
|
||||||
|
**测试数据**:
|
||||||
|
- 课程ID:4(哈他瑜伽)
|
||||||
|
- 开始时间:2026-06-01 15:20:00
|
||||||
|
- 测试时间:课程开始前30分钟内
|
||||||
|
|
||||||
|
**预期结果**:
|
||||||
|
- 返回错误信息:"已过预约时间"
|
||||||
|
- HTTP状态码:400 Bad Request
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 场景9:重复预约同一课程
|
||||||
|
|
||||||
|
**测试目标**:验证系统对重复预约的拦截
|
||||||
|
|
||||||
|
**测试数据**:
|
||||||
|
- 用户ID:1003(额度充足用户)
|
||||||
|
- 课程ID:1(极速燃脂单车)
|
||||||
|
- 已有预约记录:booking_id=3001
|
||||||
|
|
||||||
|
**预期结果**:
|
||||||
|
- 返回错误信息:"已预约该课程"
|
||||||
|
- HTTP状态码:400 Bad Request
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 场景10:多会员卡用户选择支付方式
|
||||||
|
|
||||||
|
**测试目标**:验证多卡用户的支付方式选择功能
|
||||||
|
|
||||||
|
**测试数据**:
|
||||||
|
- 用户ID:1005(多卡用户小李)
|
||||||
|
- 可用卡1:次卡(记录ID=2004,剩余45次)
|
||||||
|
- 可用卡2:储值卡(记录ID=2005,剩余350元)
|
||||||
|
|
||||||
|
**预期结果**:
|
||||||
|
- 系统列出用户所有可用会员卡
|
||||||
|
- 用户可选择使用次卡或储值卡支付
|
||||||
|
- 根据选择的卡类型扣减相应额度
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 七、交易流水说明
|
||||||
|
|
||||||
|
### 7.1 会员1002(额度耗尽用户)消费记录
|
||||||
|
|
||||||
|
| 操作顺序 | 操作类型 | 变动次数 | 剩余次数 | 备注 |
|
||||||
|
|---------|---------|---------|---------|------|
|
||||||
|
| 1 | PURCHASE | +10 | 10 | 购买10次团课卡 |
|
||||||
|
| 2-11 | DEDUCT | -1×10 | 0 | 10次课程消费 |
|
||||||
|
|
||||||
|
### 7.2 会员1003(额度充足用户)消费记录
|
||||||
|
|
||||||
|
| 操作顺序 | 操作类型 | 变动次数 | 剩余次数 | 备注 |
|
||||||
|
|---------|---------|---------|---------|------|
|
||||||
|
| 1 | PURCHASE | +20 | 20 | 购买20次团课卡 |
|
||||||
|
| 2-12 | DEDUCT | -12 | 8 | 12次课程消费 |
|
||||||
|
|
||||||
|
### 7.3 会员1005(多卡用户)消费记录
|
||||||
|
|
||||||
|
| 会员卡记录ID | 操作类型 | 变动次数 | 变动金额 | 备注 |
|
||||||
|
|-------------|---------|---------|---------|------|
|
||||||
|
| 2004 | PURCHASE | +50 | 0 | 购买50次团课卡 |
|
||||||
|
| 2004 | DEDUCT | -5 | 0 | 预约5节课程 |
|
||||||
|
| 2005 | PURCHASE | 0 | +500 | 购买500元储值卡 |
|
||||||
|
| 2005 | DEDUCT | 0 | -150 | 私教课消费150元 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 八、API测试示例
|
||||||
|
|
||||||
|
### 8.1 预约接口
|
||||||
|
|
||||||
|
```http
|
||||||
|
POST /api/group-course/bookings
|
||||||
|
Content-Type: application/json
|
||||||
|
|
||||||
|
{
|
||||||
|
"courseId": 1,
|
||||||
|
"memberCardRecordId": 2002
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 8.2 取消预约接口
|
||||||
|
|
||||||
|
```http
|
||||||
|
PUT /api/group-course/bookings/{bookingId}/cancel
|
||||||
|
Content-Type: application/json
|
||||||
|
|
||||||
|
{
|
||||||
|
"reason": "临时有事无法参加"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 8.3 查询用户预约列表
|
||||||
|
|
||||||
|
```http
|
||||||
|
GET /api/group-course/bookings?memberId=1003
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 九、测试数据对应关系图
|
||||||
|
|
||||||
|
```
|
||||||
|
会员表 (member_user)
|
||||||
|
│
|
||||||
|
├── 1001 ──→ (无会员卡)
|
||||||
|
├── 1002 ──→ 会员卡记录 2001 (USED_UP)
|
||||||
|
├── 1003 ──→ 会员卡记录 2002 (ACTIVE, 8次)
|
||||||
|
├── 1004 ──→ 会员卡记录 2003 (EXPIRED)
|
||||||
|
└── 1005 ──→ 会员卡记录 2004 (ACTIVE, 45次)
|
||||||
|
└── 会员卡记录 2005 (ACTIVE, 350元)
|
||||||
|
│
|
||||||
|
↓
|
||||||
|
预约记录表 (group_course_booking)
|
||||||
|
│
|
||||||
|
├── 3001: 已预约
|
||||||
|
├── 3002: 已取消
|
||||||
|
├── 3003: 已出席
|
||||||
|
└── 3004: 缺席
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 十、数据初始化
|
||||||
|
|
||||||
|
测试数据通过 Flyway 迁移脚本 `V10__Insert_Booking_Test_Data.sql` 初始化,需在数据库初始化时执行。
|
||||||
|
|
||||||
|
**执行顺序**:
|
||||||
|
1. V1__Create_all_tables.sql - 创建基础表结构
|
||||||
|
2. V2__Insert_initial_data.sql - 插入初始数据
|
||||||
|
3. V6__Create_GroupCourse_table.sql - 创建团课表
|
||||||
|
4. V7__Insert_GroupCourse_test_data.sql - 插入团课测试数据
|
||||||
|
5. V8__Create_Member_And_MemberCard.sql - 创建会员和会员卡表
|
||||||
|
6. V9__Add_GroupCourse_Booking_Snapshot_Fields.sql - 添加冗余字段
|
||||||
|
7. V10__Insert_Booking_Test_Data.sql - 插入预约测试数据(本文件)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**文档版本**: v1.1
|
||||||
|
**创建时间**: 2026-06-02
|
||||||
|
**更新时间**: 2026-06-02
|
||||||
|
**适用场景**: 团课预约功能测试
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 十一、重要说明
|
||||||
|
|
||||||
|
### 11.1 字段说明
|
||||||
|
|
||||||
|
`member_card_record` 表包含两个ID字段:
|
||||||
|
- `id` - 数据库主键(BIGSERIAL PRIMARY KEY)
|
||||||
|
- `member_card_record_id` - 业务ID(BIGSERIAL),代码中使用此字段作为查询和更新条件
|
||||||
|
|
||||||
|
### 11.2 测试数据修复记录
|
||||||
|
|
||||||
|
**v1.1 修复内容**:
|
||||||
|
- 修复了 `member_card_record` 表测试数据缺失 `member_card_record_id` 字段的问题
|
||||||
|
- 原问题:测试数据只插入了 `id` 字段,导致 `member_card_record_id` 为 NULL
|
||||||
|
- 影响:代码使用 `member_card_record_id` 作为WHERE条件时无法匹配到记录,导致扣减权益失败
|
||||||
|
- 解决:在INSERT语句中添加 `member_card_record_id` 字段,值与 `id` 相同
|
||||||
|
|
||||||
|
**修复前**:
|
||||||
|
```sql
|
||||||
|
INSERT INTO member_card_record (id, member_id, member_card_id, ...) VALUES
|
||||||
|
(2001, 1002, 101, ...);
|
||||||
|
```
|
||||||
|
|
||||||
|
**修复后**:
|
||||||
|
```sql
|
||||||
|
INSERT INTO member_card_record (id, member_card_record_id, member_id, member_card_id, ...) VALUES
|
||||||
|
(2001, 2001, 1002, 101, ...);
|
||||||
|
```
|
||||||
@@ -0,0 +1,452 @@
|
|||||||
|
# 数据统计模块 API 文档
|
||||||
|
|
||||||
|
> **文档版本**: v1.0
|
||||||
|
> **创建日期**: 2026-06-09
|
||||||
|
> **作者**: system
|
||||||
|
> **状态**: 正式发布
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📋 目录
|
||||||
|
|
||||||
|
1. [概述](#概述)
|
||||||
|
2. [基础路径](#基础路径)
|
||||||
|
3. [统计数据接口](#统计数据接口)
|
||||||
|
- [获取综合统计数据](#获取综合统计数据)
|
||||||
|
- [获取会员统计数据](#获取会员统计数据)
|
||||||
|
- [获取预约统计数据](#获取预约统计数据)
|
||||||
|
- [获取签到统计数据](#获取签到统计数据)
|
||||||
|
- [查询历史统计数据](#查询历史统计数据)
|
||||||
|
- [导出统计数据](#导出统计数据)
|
||||||
|
4. [数据模型](#数据模型)
|
||||||
|
- [StatisticsQuery(查询条件)](#StatisticsQuery查询条件)
|
||||||
|
- [StatisticsSummary(统计汇总)](#StatisticsSummary统计汇总)
|
||||||
|
- [MemberStatistics(会员统计)](#MemberStatistics会员统计)
|
||||||
|
- [BookingStatistics(预约统计)](#BookingStatistics预约统计)
|
||||||
|
- [SignInStatistics(签到统计)](#SignInStatistics签到统计)
|
||||||
|
5. [状态码说明](#状态码说明)
|
||||||
|
6. [业务规则](#业务规则)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 概述
|
||||||
|
|
||||||
|
数据统计模块提供健身房会员、预约、签到数据的统计功能,支持按日、周、月周期统计,并提供Excel导出功能。采用 Spring WebFlux 响应式编程,统计结果通过 Redis 缓存提高查询性能。
|
||||||
|
|
||||||
|
## 基础路径
|
||||||
|
|
||||||
|
所有接口的基础路径为: `http://{host}:{port}/api/datacount`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 统计数据接口
|
||||||
|
|
||||||
|
### 获取综合统计数据
|
||||||
|
|
||||||
|
| 属性 | 值 |
|
||||||
|
|------|-----|
|
||||||
|
| **HTTP方法** | GET |
|
||||||
|
| **接口路径** | `/api/datacount/summary` |
|
||||||
|
| **所属文件** | `DataStatisticsHandler.java` |
|
||||||
|
|
||||||
|
**请求参数**:
|
||||||
|
|
||||||
|
| 参数名 | 类型 | 必填 | 默认值 | 说明 |
|
||||||
|
|--------|------|------|--------|------|
|
||||||
|
| statType | string | 否 | 空 | 统计类型筛选 |
|
||||||
|
| periodType | string | 否 | DAY | 统计周期:DAY/WEEK/MONTH |
|
||||||
|
| startTime | string | 否 | 自动计算 | 开始时间(ISO格式) |
|
||||||
|
| endTime | string | 否 | 自动计算 | 结束时间(ISO格式) |
|
||||||
|
|
||||||
|
**请求示例**:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. 使用周期类型查询今日统计
|
||||||
|
GET /api/datacount/summary?periodType=DAY
|
||||||
|
|
||||||
|
# 2. 使用周期类型查询本周统计
|
||||||
|
GET /api/datacount/summary?periodType=WEEK
|
||||||
|
|
||||||
|
# 3. 使用周期类型查询本月统计
|
||||||
|
GET /api/datacount/summary?periodType=MONTH
|
||||||
|
|
||||||
|
# 4. 使用自定义时间范围查询
|
||||||
|
GET /api/datacount/summary?startTime=2026-06-01T00:00:00&endTime=2026-06-07T23:59:59
|
||||||
|
|
||||||
|
# 5. 带统计类型筛选
|
||||||
|
GET /api/datacount/summary?statType=member&periodType=WEEK
|
||||||
|
```
|
||||||
|
|
||||||
|
**成功响应** (200 OK):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"statDate": "2026-06-09",
|
||||||
|
"generatedAt": "2026-06-09T10:30:00",
|
||||||
|
"memberStatistics": {
|
||||||
|
"statDate": "2026-06-09",
|
||||||
|
"newMembers": 5,
|
||||||
|
"activeMembers": 120,
|
||||||
|
"totalMembers": 500,
|
||||||
|
"signInMembers": 85,
|
||||||
|
"bookingMembers": 45,
|
||||||
|
"cancelMembers": 5
|
||||||
|
},
|
||||||
|
"bookingStatistics": {
|
||||||
|
"statDate": "2026-06-09",
|
||||||
|
"totalBookings": 60,
|
||||||
|
"cancelBookings": 10,
|
||||||
|
"attendBookings": 45,
|
||||||
|
"absentBookings": 5,
|
||||||
|
"attendRate": 75.0,
|
||||||
|
"cancelRate": 16.67
|
||||||
|
},
|
||||||
|
"signInStatistics": {
|
||||||
|
"statDate": "2026-06-09",
|
||||||
|
"totalSignIns": 95,
|
||||||
|
"successSignIns": 92,
|
||||||
|
"failSignIns": 3,
|
||||||
|
"successRate": 96.84,
|
||||||
|
"signInTypeDistribution": {
|
||||||
|
"QR_CODE": 60,
|
||||||
|
"MANUAL": 25,
|
||||||
|
"FACE": 10
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 获取会员统计数据
|
||||||
|
|
||||||
|
| 属性 | 值 |
|
||||||
|
|------|-----|
|
||||||
|
| **HTTP方法** | GET |
|
||||||
|
| **接口路径** | `/api/datacount/member` |
|
||||||
|
| **所属文件** | `DataStatisticsHandler.java` |
|
||||||
|
|
||||||
|
**请求参数**:
|
||||||
|
|
||||||
|
| 参数名 | 类型 | 必填 | 默认值 | 说明 |
|
||||||
|
|--------|------|------|--------|------|
|
||||||
|
| periodType | string | 否 | DAY | 统计周期:DAY/WEEK/MONTH |
|
||||||
|
| startTime | string | 否 | 自动计算 | 开始时间 |
|
||||||
|
| endTime | string | 否 | 自动计算 | 结束时间 |
|
||||||
|
|
||||||
|
**请求示例**:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. 查询今日会员统计
|
||||||
|
GET /api/datacount/member
|
||||||
|
|
||||||
|
# 2. 查询本周会员统计
|
||||||
|
GET /api/datacount/member?periodType=WEEK
|
||||||
|
|
||||||
|
# 3. 查询指定时间范围的会员统计
|
||||||
|
GET /api/datacount/member?startTime=2026-06-01T00:00:00&endTime=2026-06-30T23:59:59
|
||||||
|
```
|
||||||
|
|
||||||
|
**成功响应** (200 OK):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"statDate": "2026-06-09",
|
||||||
|
"newMembers": 5,
|
||||||
|
"activeMembers": 120,
|
||||||
|
"totalMembers": 500,
|
||||||
|
"signInMembers": 85,
|
||||||
|
"bookingMembers": 45,
|
||||||
|
"cancelMembers": 5
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 获取预约统计数据
|
||||||
|
|
||||||
|
| 属性 | 值 |
|
||||||
|
|------|-----|
|
||||||
|
| **HTTP方法** | GET |
|
||||||
|
| **接口路径** | `/api/datacount/booking` |
|
||||||
|
| **所属文件** | `DataStatisticsHandler.java` |
|
||||||
|
|
||||||
|
**请求参数**:
|
||||||
|
|
||||||
|
| 参数名 | 类型 | 必填 | 默认值 | 说明 |
|
||||||
|
|--------|------|------|--------|------|
|
||||||
|
| periodType | string | 否 | DAY | 统计周期:DAY/WEEK/MONTH |
|
||||||
|
| startTime | string | 否 | 自动计算 | 开始时间 |
|
||||||
|
| endTime | string | 否 | 自动计算 | 结束时间 |
|
||||||
|
|
||||||
|
**请求示例**:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. 查询今日预约统计
|
||||||
|
GET /api/datacount/booking
|
||||||
|
|
||||||
|
# 2. 查询本月预约统计
|
||||||
|
GET /api/datacount/booking?periodType=MONTH
|
||||||
|
|
||||||
|
# 3. 查询指定日期范围的预约统计
|
||||||
|
GET /api/datacount/booking?startTime=2026-06-01T00:00:00&endTime=2026-06-15T23:59:59
|
||||||
|
```
|
||||||
|
|
||||||
|
**成功响应** (200 OK):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"statDate": "2026-06-09",
|
||||||
|
"totalBookings": 60,
|
||||||
|
"cancelBookings": 10,
|
||||||
|
"attendBookings": 45,
|
||||||
|
"absentBookings": 5,
|
||||||
|
"attendRate": 75.0,
|
||||||
|
"cancelRate": 16.67
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 获取签到统计数据
|
||||||
|
|
||||||
|
| 属性 | 值 |
|
||||||
|
|------|-----|
|
||||||
|
| **HTTP方法** | GET |
|
||||||
|
| **接口路径** | `/api/datacount/signin` |
|
||||||
|
| **所属文件** | `DataStatisticsHandler.java` |
|
||||||
|
|
||||||
|
**请求参数**:
|
||||||
|
|
||||||
|
| 参数名 | 类型 | 必填 | 默认值 | 说明 |
|
||||||
|
|--------|------|------|--------|------|
|
||||||
|
| periodType | string | 否 | DAY | 统计周期:DAY/WEEK/MONTH |
|
||||||
|
| startTime | string | 否 | 自动计算 | 开始时间 |
|
||||||
|
| endTime | string | 否 | 自动计算 | 结束时间 |
|
||||||
|
|
||||||
|
**请求示例**:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. 查询今日签到统计
|
||||||
|
GET /api/datacount/signin
|
||||||
|
|
||||||
|
# 2. 查询本周签到统计
|
||||||
|
GET /api/datacount/signin?periodType=WEEK
|
||||||
|
|
||||||
|
# 3. 查询指定日期范围的签到统计
|
||||||
|
GET /api/datacount/signin?startTime=2026-06-01T00:00:00&endTime=2026-06-30T23:59:59
|
||||||
|
```
|
||||||
|
|
||||||
|
**成功响应** (200 OK):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"statDate": "2026-06-09",
|
||||||
|
"totalSignIns": 95,
|
||||||
|
"successSignIns": 92,
|
||||||
|
"failSignIns": 3,
|
||||||
|
"successRate": 96.84,
|
||||||
|
"signInTypeDistribution": {
|
||||||
|
"QR_CODE": 60,
|
||||||
|
"MANUAL": 25,
|
||||||
|
"FACE": 10
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 查询历史统计数据
|
||||||
|
|
||||||
|
| 属性 | 值 |
|
||||||
|
|------|-----|
|
||||||
|
| **HTTP方法** | GET |
|
||||||
|
| **接口路径** | `/api/datacount/history` |
|
||||||
|
| **所属文件** | `DataStatisticsHandler.java` |
|
||||||
|
|
||||||
|
**请求参数**:
|
||||||
|
|
||||||
|
| 参数名 | 类型 | 必填 | 默认值 | 说明 |
|
||||||
|
|--------|------|------|--------|------|
|
||||||
|
| statType | string | 否 | 空 | 统计类型:member/booking/signin |
|
||||||
|
| startTime | string | 是 | - | 开始日期(格式:yyyy-MM-dd) |
|
||||||
|
| endTime | string | 是 | - | 结束日期(格式:yyyy-MM-dd) |
|
||||||
|
|
||||||
|
**请求示例**:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. 查询指定日期范围的签到历史统计
|
||||||
|
GET /api/datacount/history?statType=signin&startTime=2026-06-01&endTime=2026-06-30
|
||||||
|
|
||||||
|
# 2. 查询指定日期范围的会员历史统计
|
||||||
|
GET /api/datacount/history?statType=member&startTime=2026-06-01&endTime=2026-06-15
|
||||||
|
|
||||||
|
# 3. 查询指定日期范围的预约历史统计
|
||||||
|
GET /api/datacount/history?statType=booking&startTime=2026-06-01&endTime=2026-06-30
|
||||||
|
|
||||||
|
# 4. 查询所有类型的历史统计(不指定statType)
|
||||||
|
GET /api/datacount/history?startTime=2026-06-01&endTime=2026-06-07
|
||||||
|
```
|
||||||
|
|
||||||
|
**成功响应** (200 OK):
|
||||||
|
|
||||||
|
```json
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"statDate": "2026-06-07",
|
||||||
|
"totalSignIns": 88,
|
||||||
|
"successSignIns": 86,
|
||||||
|
"failSignIns": 2,
|
||||||
|
"successRate": 97.73,
|
||||||
|
"signInTypeDistribution": {
|
||||||
|
"QR_CODE": 55,
|
||||||
|
"MANUAL": 23,
|
||||||
|
"FACE": 10
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"statDate": "2026-06-08",
|
||||||
|
"totalSignIns": 92,
|
||||||
|
"successSignIns": 90,
|
||||||
|
"failSignIns": 2,
|
||||||
|
"successRate": 97.83,
|
||||||
|
"signInTypeDistribution": {
|
||||||
|
"QR_CODE": 58,
|
||||||
|
"MANUAL": 24,
|
||||||
|
"FACE": 10
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 导出统计数据
|
||||||
|
|
||||||
|
| 属性 | 值 |
|
||||||
|
|------|-----|
|
||||||
|
| **HTTP方法** | GET |
|
||||||
|
| **接口路径** | `/api/datacount/export` |
|
||||||
|
| **所属文件** | `DataStatisticsHandler.java` |
|
||||||
|
|
||||||
|
**请求参数**:
|
||||||
|
|
||||||
|
| 参数名 | 类型 | 必填 | 默认值 | 说明 |
|
||||||
|
|--------|------|------|--------|------|
|
||||||
|
| periodType | string | 否 | DAY | 统计周期:DAY/WEEK/MONTH |
|
||||||
|
| startTime | string | 否 | 自动计算 | 开始时间 |
|
||||||
|
| endTime | string | 否 | 自动计算 | 结束时间 |
|
||||||
|
|
||||||
|
**请求示例**:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# 1. 导出今日统计数据
|
||||||
|
GET /api/datacount/export
|
||||||
|
|
||||||
|
# 2. 导出本周统计数据
|
||||||
|
GET /api/datacount/export?periodType=WEEK
|
||||||
|
|
||||||
|
# 3. 导出本月统计数据
|
||||||
|
GET /api/datacount/export?periodType=MONTH
|
||||||
|
|
||||||
|
# 4. 导出指定时间范围的统计数据
|
||||||
|
GET /api/datacount/export?startTime=2026-06-01T00:00:00&endTime=2026-06-30T23:59:59
|
||||||
|
```
|
||||||
|
|
||||||
|
**成功响应** (200 OK):
|
||||||
|
|
||||||
|
返回 Excel 文件(.xlsx),包含以下 Sheet:
|
||||||
|
- **会员统计**: 会员相关统计数据
|
||||||
|
- **预约统计**: 预约相关统计数据
|
||||||
|
- **签到统计**: 签到相关统计数据
|
||||||
|
|
||||||
|
**Content-Type**: `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 数据模型
|
||||||
|
|
||||||
|
### StatisticsQuery(查询条件)
|
||||||
|
|
||||||
|
| 字段名 | 类型 | 说明 |
|
||||||
|
|--------|------|------|
|
||||||
|
| statType | String | 统计类型筛选 |
|
||||||
|
| periodType | String | 统计周期:DAY/WEEK/MONTH |
|
||||||
|
| startTime | LocalDateTime | 开始时间 |
|
||||||
|
| endTime | LocalDateTime | 结束时间 |
|
||||||
|
|
||||||
|
### StatisticsSummary(统计汇总)
|
||||||
|
|
||||||
|
| 字段名 | 类型 | 说明 |
|
||||||
|
|--------|------|------|
|
||||||
|
| statDate | String | 统计日期 |
|
||||||
|
| generatedAt | String | 生成时间 |
|
||||||
|
| memberStatistics | MemberStatistics | 会员统计数据 |
|
||||||
|
| bookingStatistics | BookingStatistics | 预约统计数据 |
|
||||||
|
| signInStatistics | SignInStatistics | 签到统计数据 |
|
||||||
|
|
||||||
|
### MemberStatistics(会员统计)
|
||||||
|
|
||||||
|
| 字段名 | 类型 | 说明 |
|
||||||
|
|--------|------|------|
|
||||||
|
| statDate | String | 统计日期 |
|
||||||
|
| newMembers | Long | 新增会员数 |
|
||||||
|
| activeMembers | Long | 活跃会员数 |
|
||||||
|
| totalMembers | Long | 累计会员总数 |
|
||||||
|
| signInMembers | Long | 签到会员数 |
|
||||||
|
| bookingMembers | Long | 预约会员数 |
|
||||||
|
| cancelMembers | Long | 取消预约会员数 |
|
||||||
|
|
||||||
|
### BookingStatistics(预约统计)
|
||||||
|
|
||||||
|
| 字段名 | 类型 | 说明 |
|
||||||
|
|--------|------|------|
|
||||||
|
| statDate | String | 统计日期 |
|
||||||
|
| totalBookings | Long | 预约总数 |
|
||||||
|
| cancelBookings | Long | 取消预约数 |
|
||||||
|
| attendBookings | Long | 出席预约数 |
|
||||||
|
| absentBookings | Long | 缺席预约数 |
|
||||||
|
| attendRate | Double | 出席率(%) |
|
||||||
|
| cancelRate | Double | 取消率(%) |
|
||||||
|
|
||||||
|
### SignInStatistics(签到统计)
|
||||||
|
|
||||||
|
| 字段名 | 类型 | 说明 |
|
||||||
|
|--------|------|------|
|
||||||
|
| statDate | String | 统计日期 |
|
||||||
|
| totalSignIns | Long | 签到总次数 |
|
||||||
|
| successSignIns | Long | 成功签到次数 |
|
||||||
|
| failSignIns | Long | 失败签到次数 |
|
||||||
|
| successRate | Double | 签到成功率(%) |
|
||||||
|
| signInTypeDistribution | Map<String, Long> | 签到类型分布 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 状态码说明
|
||||||
|
|
||||||
|
| 状态码 | 说明 |
|
||||||
|
|--------|------|
|
||||||
|
| 200 | 请求成功 |
|
||||||
|
| 400 | 请求参数错误 |
|
||||||
|
| 500 | 服务器内部错误 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 业务规则
|
||||||
|
|
||||||
|
1. **统计周期**: 支持按日、周、月统计
|
||||||
|
- DAY: 当天 00:00:00 - 当前时间
|
||||||
|
- WEEK: 本周一 00:00:00 - 本周日 23:59:59
|
||||||
|
- MONTH: 本月1日 00:00:00 - 本月最后一天 23:59:59
|
||||||
|
|
||||||
|
2. **数据保留**: 统计数据缓存30天,业务记录永久保存
|
||||||
|
|
||||||
|
3. **缓存策略**: 查询结果缓存1小时,统计数据缓存30天
|
||||||
|
|
||||||
|
4. **定时任务**:
|
||||||
|
- 每日凌晨2点执行前一天的日统计
|
||||||
|
- 每周一凌晨3点执行上周的周统计
|
||||||
|
- 每月1日凌晨3点执行上月的月统计
|
||||||
|
- 每月15日凌晨4点清理30天前的旧数据
|
||||||
|
|
||||||
|
5. **数据导出**: 支持Excel格式导出,包含会员、预约、签到三个Sheet
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,530 @@
|
|||||||
|
# 团课推荐模块 API 文档
|
||||||
|
|
||||||
|
> **文档版本**: v1.0
|
||||||
|
> **创建日期**: 2026-06-15
|
||||||
|
> **作者**: 张翔
|
||||||
|
> **状态**: 正式发布
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📋 目录
|
||||||
|
|
||||||
|
1. [概述](#概述)
|
||||||
|
2. [基础路径](#基础路径)
|
||||||
|
3. [团课推荐管理接口](#团课推荐管理接口)
|
||||||
|
- [获取所有团课推荐](#获取所有团课推荐)
|
||||||
|
- [获取所有启用的团课推荐](#获取所有启用的团课推荐)
|
||||||
|
- [根据ID获取团课推荐](#根据ID获取团课推荐)
|
||||||
|
- [根据团课ID获取推荐](#根据团课ID获取推荐)
|
||||||
|
- [创建团课推荐](#创建团课推荐)
|
||||||
|
- [更新团课推荐](#更新团课推荐)
|
||||||
|
- [删除团课推荐](#删除团课推荐)
|
||||||
|
- [启用团课推荐](#启用团课推荐)
|
||||||
|
- [禁用团课推荐](#禁用团课推荐)
|
||||||
|
4. [数据模型](#数据模型)
|
||||||
|
- [GroupCourseRecommend(团课推荐)](#GroupCourseRecommend团课推荐)
|
||||||
|
5. [状态码说明](#状态码说明)
|
||||||
|
6. [业务规则](#业务规则)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 概述
|
||||||
|
|
||||||
|
团课推荐模块提供团课推荐信息的创建、编辑、查询、删除和状态管理功能。推荐信息包含团课ID、推荐标题、推荐内容、推荐理由、优先级等必要信息,支持按优先级排序展示。
|
||||||
|
|
||||||
|
## 基础路径
|
||||||
|
|
||||||
|
所有接口的基础路径为: `http://{host}:{port}/api/groupCourse/recommend`
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 团课推荐管理接口
|
||||||
|
|
||||||
|
### 获取所有团课推荐
|
||||||
|
|
||||||
|
| 属性 | 值 |
|
||||||
|
|------|-----|
|
||||||
|
| **HTTP方法** | GET |
|
||||||
|
| **接口路径** | `/api/groupCourse/recommend/list` |
|
||||||
|
| **所属文件** | `GroupCourseRecommendHandler.java` |
|
||||||
|
|
||||||
|
**请求参数**:
|
||||||
|
|
||||||
|
| 参数名 | 类型 | 必填 | 默认值 | 说明 |
|
||||||
|
|--------|------|------|--------|------|
|
||||||
|
| sortBy | string | 否 | priority | 排序字段(支持:priority、createdAt、updatedAt) |
|
||||||
|
| sortOrder | string | 否 | desc | 排序方式(asc-升序,desc-降序) |
|
||||||
|
|
||||||
|
**成功响应** (200 OK):
|
||||||
|
|
||||||
|
```json
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"id": 1,
|
||||||
|
"courseId": 1,
|
||||||
|
"recommendTitle": "本周热门课程",
|
||||||
|
"recommendContent": "这是一门非常棒的课程,快来参加吧!",
|
||||||
|
"recommendReason": "教练专业,课程内容丰富",
|
||||||
|
"priority": 10,
|
||||||
|
"isActive": true,
|
||||||
|
"groupCourse": {
|
||||||
|
"id": 1,
|
||||||
|
"courseName": "瑜伽入门",
|
||||||
|
"coachId": 1,
|
||||||
|
"courseType": 1,
|
||||||
|
"startTime": "2026-06-15T09:00:00",
|
||||||
|
"endTime": "2026-06-15T10:00:00",
|
||||||
|
"maxMembers": 20,
|
||||||
|
"currentMembers": 15,
|
||||||
|
"status": 0,
|
||||||
|
"location": "健身房A区",
|
||||||
|
"coverImage": "https://example.com/yoga.jpg",
|
||||||
|
"description": "适合初学者的瑜伽课程"
|
||||||
|
},
|
||||||
|
"createdAt": "2026-06-15T10:00:00",
|
||||||
|
"updatedAt": "2026-06-15T10:00:00"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 获取所有启用的团课推荐
|
||||||
|
|
||||||
|
| 属性 | 值 |
|
||||||
|
|------|-----|
|
||||||
|
| **HTTP方法** | GET |
|
||||||
|
| **接口路径** | `/api/groupCourse/recommend/active` |
|
||||||
|
| **所属文件** | `GroupCourseRecommendHandler.java` |
|
||||||
|
|
||||||
|
**功能说明**: 获取系统中所有已启用的团课推荐列表,按优先级从高到低排序。
|
||||||
|
|
||||||
|
**成功响应** (200 OK):
|
||||||
|
|
||||||
|
```json
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"id": 2,
|
||||||
|
"courseId": 3,
|
||||||
|
"recommendTitle": "新学员推荐",
|
||||||
|
"recommendContent": "专为新学员设计的入门课程,轻松上手",
|
||||||
|
"recommendReason": "零基础友好,教练耐心指导",
|
||||||
|
"priority": 20,
|
||||||
|
"isActive": true,
|
||||||
|
"groupCourse": {
|
||||||
|
"id": 3,
|
||||||
|
"courseName": "基础有氧",
|
||||||
|
"coachId": 2,
|
||||||
|
"courseType": 2,
|
||||||
|
"startTime": "2026-06-16T18:00:00",
|
||||||
|
"endTime": "2026-06-16T19:00:00",
|
||||||
|
"maxMembers": 30,
|
||||||
|
"currentMembers": 8,
|
||||||
|
"status": 0,
|
||||||
|
"location": "健身房B区",
|
||||||
|
"coverImage": "https://example.com/aerobic.jpg",
|
||||||
|
"description": "适合所有健身水平的有氧课程"
|
||||||
|
},
|
||||||
|
"createdAt": "2026-06-15T11:00:00",
|
||||||
|
"updatedAt": "2026-06-15T11:00:00"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 根据ID获取团课推荐
|
||||||
|
|
||||||
|
| 属性 | 值 |
|
||||||
|
|------|-----|
|
||||||
|
| **HTTP方法** | GET |
|
||||||
|
| **接口路径** | `/api/groupCourse/recommend/{id}` |
|
||||||
|
| **所属文件** | `GroupCourseRecommendHandler.java` |
|
||||||
|
|
||||||
|
**路径参数**:
|
||||||
|
|
||||||
|
| 参数名 | 类型 | 必填 | 说明 |
|
||||||
|
|--------|------|------|------|
|
||||||
|
| id | Long | 是 | 团课推荐ID |
|
||||||
|
|
||||||
|
**成功响应** (200 OK):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"id": 1,
|
||||||
|
"courseId": 1,
|
||||||
|
"recommendTitle": "本周热门课程",
|
||||||
|
"recommendContent": "这是一门非常棒的课程,快来参加吧!",
|
||||||
|
"recommendReason": "教练专业,课程内容丰富",
|
||||||
|
"priority": 10,
|
||||||
|
"isActive": true,
|
||||||
|
"groupCourse": {
|
||||||
|
"id": 1,
|
||||||
|
"courseName": "瑜伽入门",
|
||||||
|
"coachId": 1,
|
||||||
|
"courseType": 1,
|
||||||
|
"startTime": "2026-06-15T09:00:00",
|
||||||
|
"endTime": "2026-06-15T10:00:00",
|
||||||
|
"maxMembers": 20,
|
||||||
|
"currentMembers": 15,
|
||||||
|
"status": 0,
|
||||||
|
"location": "健身房A区",
|
||||||
|
"coverImage": "https://example.com/yoga.jpg",
|
||||||
|
"description": "适合初学者的瑜伽课程"
|
||||||
|
},
|
||||||
|
"createdAt": "2026-06-15T10:00:00",
|
||||||
|
"updatedAt": "2026-06-15T10:00:00"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**失败响应** (404 Not Found):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 根据团课ID获取推荐
|
||||||
|
|
||||||
|
| 属性 | 值 |
|
||||||
|
|------|-----|
|
||||||
|
| **HTTP方法** | GET |
|
||||||
|
| **接口路径** | `/api/groupCourse/recommend/course/{courseId}` |
|
||||||
|
| **所属文件** | `GroupCourseRecommendHandler.java` |
|
||||||
|
|
||||||
|
**路径参数**:
|
||||||
|
|
||||||
|
| 参数名 | 类型 | 必填 | 说明 |
|
||||||
|
|--------|------|------|------|
|
||||||
|
| courseId | Long | 是 | 团课ID |
|
||||||
|
|
||||||
|
**成功响应** (200 OK):
|
||||||
|
|
||||||
|
```json
|
||||||
|
[
|
||||||
|
{
|
||||||
|
"id": 1,
|
||||||
|
"courseId": 1,
|
||||||
|
"recommendTitle": "本周热门课程",
|
||||||
|
"recommendContent": "这是一门非常棒的课程,快来参加吧!",
|
||||||
|
"recommendReason": "教练专业,课程内容丰富",
|
||||||
|
"priority": 10,
|
||||||
|
"isActive": true,
|
||||||
|
"groupCourse": {
|
||||||
|
"id": 1,
|
||||||
|
"courseName": "瑜伽入门",
|
||||||
|
"coachId": 1,
|
||||||
|
"courseType": 1,
|
||||||
|
"startTime": "2026-06-15T09:00:00",
|
||||||
|
"endTime": "2026-06-15T10:00:00",
|
||||||
|
"maxMembers": 20,
|
||||||
|
"currentMembers": 15,
|
||||||
|
"status": 0,
|
||||||
|
"location": "健身房A区"
|
||||||
|
},
|
||||||
|
"createdAt": "2026-06-15T10:00:00",
|
||||||
|
"updatedAt": "2026-06-15T10:00:00"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 创建团课推荐
|
||||||
|
|
||||||
|
| 属性 | 值 |
|
||||||
|
|------|-----|
|
||||||
|
| **HTTP方法** | POST |
|
||||||
|
| **接口路径** | `/api/groupCourse/recommend` |
|
||||||
|
| **所属文件** | `GroupCourseRecommendHandler.java` |
|
||||||
|
|
||||||
|
**请求体**:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"courseId": 1,
|
||||||
|
"recommendTitle": "本周热门课程",
|
||||||
|
"recommendContent": "这是一门非常棒的课程,快来参加吧!",
|
||||||
|
"recommendReason": "教练专业,课程内容丰富",
|
||||||
|
"priority": 10,
|
||||||
|
"isActive": true
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
| 参数名 | 类型 | 必填 | 默认值 | 说明 |
|
||||||
|
|--------|------|------|--------|------|
|
||||||
|
| courseId | Long | **是** | - | 团课ID(必须是有效的团课) |
|
||||||
|
| recommendTitle | String | 否 | - | 推荐标题 |
|
||||||
|
| recommendContent | String | 否 | - | 推荐内容 |
|
||||||
|
| recommendReason | String | 否 | - | 推荐理由 |
|
||||||
|
| priority | Integer | 否 | 0 | 优先级(数字越大优先级越高) |
|
||||||
|
| isActive | Boolean | 否 | true | 是否启用 |
|
||||||
|
|
||||||
|
**成功响应** (200 OK):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": true,
|
||||||
|
"message": "团课推荐创建成功",
|
||||||
|
"data": {
|
||||||
|
"id": 1,
|
||||||
|
"courseId": 1,
|
||||||
|
"recommendTitle": "本周热门课程",
|
||||||
|
"recommendContent": "这是一门非常棒的课程,快来参加吧!",
|
||||||
|
"recommendReason": "教练专业,课程内容丰富",
|
||||||
|
"priority": 10,
|
||||||
|
"isActive": true,
|
||||||
|
"createdAt": "2026-06-15T10:00:00",
|
||||||
|
"updatedAt": "2026-06-15T10:00:00"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**失败响应** (400 Bad Request):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": false,
|
||||||
|
"message": "团课ID不能为空"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 更新团课推荐
|
||||||
|
|
||||||
|
| 属性 | 值 |
|
||||||
|
|------|-----|
|
||||||
|
| **HTTP方法** | PUT |
|
||||||
|
| **接口路径** | `/api/groupCourse/recommend/{id}` |
|
||||||
|
| **所属文件** | `GroupCourseRecommendHandler.java` |
|
||||||
|
|
||||||
|
**路径参数**:
|
||||||
|
|
||||||
|
| 参数名 | 类型 | 必填 | 说明 |
|
||||||
|
|--------|------|------|------|
|
||||||
|
| id | Long | 是 | 团课推荐ID |
|
||||||
|
|
||||||
|
**请求体**:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"recommendTitle": "本周热门课程(更新)",
|
||||||
|
"recommendContent": "更新后的推荐内容",
|
||||||
|
"recommendReason": "更新后的推荐理由",
|
||||||
|
"priority": 15,
|
||||||
|
"isActive": true
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
| 参数名 | 类型 | 必填 | 说明 |
|
||||||
|
|--------|------|------|------|
|
||||||
|
| courseId | Long | 否 | 团课ID |
|
||||||
|
| recommendTitle | String | 否 | 推荐标题 |
|
||||||
|
| recommendContent | String | 否 | 推荐内容 |
|
||||||
|
| recommendReason | String | 否 | 推荐理由 |
|
||||||
|
| priority | Integer | 否 | 优先级 |
|
||||||
|
| isActive | Boolean | 否 | 是否启用 |
|
||||||
|
|
||||||
|
**成功响应** (200 OK):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": true,
|
||||||
|
"message": "团课推荐更新成功",
|
||||||
|
"data": {
|
||||||
|
"id": 1,
|
||||||
|
"courseId": 1,
|
||||||
|
"recommendTitle": "本周热门课程(更新)",
|
||||||
|
"recommendContent": "更新后的推荐内容",
|
||||||
|
"recommendReason": "更新后的推荐理由",
|
||||||
|
"priority": 15,
|
||||||
|
"isActive": true,
|
||||||
|
"updatedAt": "2026-06-15T12:00:00"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**失败响应** (400 Bad Request):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": false,
|
||||||
|
"message": "团课推荐不存在"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 删除团课推荐
|
||||||
|
|
||||||
|
| 属性 | 值 |
|
||||||
|
|------|-----|
|
||||||
|
| **HTTP方法** | DELETE |
|
||||||
|
| **接口路径** | `/api/groupCourse/recommend/{id}` |
|
||||||
|
| **所属文件** | `GroupCourseRecommendHandler.java` |
|
||||||
|
|
||||||
|
**路径参数**:
|
||||||
|
|
||||||
|
| 参数名 | 类型 | 必填 | 说明 |
|
||||||
|
|--------|------|------|------|
|
||||||
|
| id | Long | 是 | 团课推荐ID |
|
||||||
|
|
||||||
|
**成功响应** (200 OK):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": true,
|
||||||
|
"message": "团课推荐删除成功"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**失败响应** (400 Bad Request):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": false,
|
||||||
|
"message": "团课推荐不存在"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 启用团课推荐
|
||||||
|
|
||||||
|
| 属性 | 值 |
|
||||||
|
|------|-----|
|
||||||
|
| **HTTP方法** | POST |
|
||||||
|
| **接口路径** | `/api/groupCourse/recommend/{id}/enable` |
|
||||||
|
| **所属文件** | `GroupCourseRecommendHandler.java` |
|
||||||
|
|
||||||
|
**路径参数**:
|
||||||
|
|
||||||
|
| 参数名 | 类型 | 必填 | 说明 |
|
||||||
|
|--------|------|------|------|
|
||||||
|
| id | Long | 是 | 团课推荐ID |
|
||||||
|
|
||||||
|
**成功响应** (200 OK):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": true,
|
||||||
|
"message": "团课推荐启用成功",
|
||||||
|
"data": {
|
||||||
|
"id": 1,
|
||||||
|
"courseId": 1,
|
||||||
|
"recommendTitle": "本周热门课程",
|
||||||
|
"isActive": true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**失败响应** (400 Bad Request):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": false,
|
||||||
|
"message": "团课推荐不存在"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 禁用团课推荐
|
||||||
|
|
||||||
|
| 属性 | 值 |
|
||||||
|
|------|-----|
|
||||||
|
| **HTTP方法** | POST |
|
||||||
|
| **接口路径** | `/api/groupCourse/recommend/{id}/disable` |
|
||||||
|
| **所属文件** | `GroupCourseRecommendHandler.java` |
|
||||||
|
|
||||||
|
**路径参数**:
|
||||||
|
|
||||||
|
| 参数名 | 类型 | 必填 | 说明 |
|
||||||
|
|--------|------|------|------|
|
||||||
|
| id | Long | 是 | 团课推荐ID |
|
||||||
|
|
||||||
|
**成功响应** (200 OK):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": true,
|
||||||
|
"message": "团课推荐禁用成功",
|
||||||
|
"data": {
|
||||||
|
"id": 1,
|
||||||
|
"courseId": 1,
|
||||||
|
"recommendTitle": "本周热门课程",
|
||||||
|
"isActive": false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**失败响应** (400 Bad Request):
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": false,
|
||||||
|
"message": "团课推荐不存在"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 数据模型
|
||||||
|
|
||||||
|
### GroupCourseRecommend(团课推荐)
|
||||||
|
|
||||||
|
| 字段名 | 类型 | 说明 |
|
||||||
|
|--------|------|------|
|
||||||
|
| id | Long | 主键ID |
|
||||||
|
| courseId | Long | 团课ID(关联group_course.id) |
|
||||||
|
| recommendTitle | String | 推荐标题 |
|
||||||
|
| recommendContent | String | 推荐内容 |
|
||||||
|
| recommendReason | String | 推荐理由 |
|
||||||
|
| priority | Integer | 优先级(数字越大优先级越高),默认0 |
|
||||||
|
| isActive | Boolean | 是否启用,默认true |
|
||||||
|
| groupCourse | GroupCourse | 关联的团课信息(查询时自动填充) |
|
||||||
|
| createdBy | String | 创建人 |
|
||||||
|
| updatedBy | String | 更新人 |
|
||||||
|
| createdAt | LocalDateTime | 创建时间 |
|
||||||
|
| updatedAt | LocalDateTime | 更新时间 |
|
||||||
|
| deletedAt | LocalDateTime | 删除时间(软删除) |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 状态码说明
|
||||||
|
|
||||||
|
### 推荐状态
|
||||||
|
|
||||||
|
| 状态值 | 含义 |
|
||||||
|
|--------|------|
|
||||||
|
| true | 启用 |
|
||||||
|
| false | 禁用 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 业务规则
|
||||||
|
|
||||||
|
### 团课推荐管理
|
||||||
|
1. **创建推荐**:团课ID为必填项,且必须是有效的团课
|
||||||
|
2. **优先级排序**:获取启用的推荐列表时,按优先级从高到低排序
|
||||||
|
3. **删除推荐**:采用软删除机制,数据保留可恢复
|
||||||
|
4. **状态管理**:支持启用/禁用推荐状态,禁用的推荐不会在推荐列表中显示
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 附录:错误响应格式
|
||||||
|
|
||||||
|
所有接口的错误响应统一格式:
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"success": false,
|
||||||
|
"message": "错误描述信息"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
*文档结束*
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
一、基础有氧与热身(难度 1-3)
|
||||||
|
|
||||||
|
主要是低冲击、低技巧,用于建立运动基础。
|
||||||
|
|
||||||
|
慢走/椭圆机轻松模式:1(几乎无难度,适合所有人)
|
||||||
|
|
||||||
|
固定自行车(低阻力):2(注意座椅高度调节即可)
|
||||||
|
|
||||||
|
跑步机慢跑:3(需要基本协调性,膝盖有压力)
|
||||||
|
|
||||||
|
跳绳(连续基础跳):3(需要手脚配合,心肺要求明显)
|
||||||
|
|
||||||
|
二、固定器械训练(难度 2-5)
|
||||||
|
|
||||||
|
轨迹固定,主要考验力量和耐力,技巧要求低。
|
||||||
|
|
||||||
|
坐姿腿屈伸/腿弯举:2(很容易找到发力感)
|
||||||
|
|
||||||
|
坐姿推胸机:3(需注意肩胛后收,避免耸肩)
|
||||||
|
|
||||||
|
高位下拉(坐姿):3(需控制不要过度后仰)
|
||||||
|
|
||||||
|
史密斯机深蹲:4(轨迹固定,但需保持核心稳定)
|
||||||
|
|
||||||
|
蝴蝶机夹胸:3(易用肘关节代偿,需锁定肩关节)
|
||||||
|
|
||||||
|
三、自重基础动作(难度 3-7)
|
||||||
|
|
||||||
|
需要一定的力量-体重比和身体控制能力。
|
||||||
|
|
||||||
|
平板支撑:3(耐力考验,技巧低)
|
||||||
|
|
||||||
|
跪姿俯卧撑:3(上肢力量较弱者首选)
|
||||||
|
|
||||||
|
标准俯卧撑:5(需核心收紧,身体成直线)
|
||||||
|
|
||||||
|
引体向上(弹力带辅助):6(背部和手臂力量要求高)
|
||||||
|
|
||||||
|
标准引体向上:8(力量-体重比极高,多数男性无法完成1次)
|
||||||
|
|
||||||
|
徒手深蹲:3(注意膝盖方向与背部直立)
|
||||||
|
|
||||||
|
单腿深蹲(手枪蹲):8(需要极高下肢力量、柔韧性和平衡)
|
||||||
|
|
||||||
|
四、自由重量杠铃/哑铃(难度 5-9)
|
||||||
|
|
||||||
|
技巧风险最高,需要神经系统协调和长期动作打磨。
|
||||||
|
|
||||||
|
哑铃二头弯举:4(容易晃动借力,但较安全)
|
||||||
|
|
||||||
|
哑铃侧平举:5(极易用斜方肌代偿,真正练到三角肌中束很难)
|
||||||
|
|
||||||
|
杠铃卧推:7(肩关节压力大,起桥、沉肩、稳定手腕均有技巧,有压伤风险)
|
||||||
|
|
||||||
|
杠铃深蹲(颈后):8(全身协调性、核心抗压、杠位放置、呼吸模式,学习曲线陡峭)
|
||||||
|
|
||||||
|
传统硬拉:9(风险极高,需要精确的脊柱中立、髋铰链、背阔肌收紧,错误时伤腰)
|
||||||
|
|
||||||
|
高翻/抓举(奥运举重):10(需要爆发力、柔韧、精准衔接,非数月训练不能掌握)
|
||||||
|
|
||||||
|
五、高强度与爆发力(难度 6-10)
|
||||||
|
|
||||||
|
对心肺、神经系统和恢复能力要求极高。
|
||||||
|
|
||||||
|
波比跳(标准版):6(连续做时心肺压力极大)
|
||||||
|
|
||||||
|
冲刺跑(短跑):7(对腘绳肌和脚踝爆发力要求高)
|
||||||
|
|
||||||
|
跳箱(合理高度):6(需要落地缓冲技巧)
|
||||||
|
|
||||||
|
负重雪橇推:6(主要考验腿部耐力和意志力)
|
||||||
|
|
||||||
|
双力臂(引体向上后翻腕上杠):9(需要爆发引体 + 极高相对力量)
|
||||||
|
|
||||||
|
六、柔韧与平衡类(难度 3-8)
|
||||||
|
|
||||||
|
考验本体感觉和关节活动度。
|
||||||
|
|
||||||
|
静态拉伸(坐姿体前屈):2(无风险,但需要坚持)
|
||||||
|
|
||||||
|
瑜伽下犬式:3(常见,但需背部与手臂对齐)
|
||||||
|
|
||||||
|
单腿罗马尼亚硬拉(徒手):6(极考验平衡和髋稳定)
|
||||||
|
|
||||||
|
全深蹲(脚跟贴地,亚洲蹲):5(踝关节灵活度限制多数人)
|
||||||
|
|
||||||
|
竖叉/横叉:8(需要数月甚至数年拉伸)
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>cn.novalon.gym.manage</groupId>
|
||||||
|
<artifactId>gym-manage-api</artifactId>
|
||||||
|
<version>1.0.0</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<artifactId>gym-auth</artifactId>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
|
<name>Gym Auth</name>
|
||||||
|
<description>Phone Authentication Module - Phone Number Login Services</description>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>cn.novalon.gym.manage</groupId>
|
||||||
|
<artifactId>manage-common</artifactId>
|
||||||
|
<version>${project.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>cn.novalon.gym.manage</groupId>
|
||||||
|
<artifactId>manage-db</artifactId>
|
||||||
|
<version>${project.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>cn.novalon.gym.manage</groupId>
|
||||||
|
<artifactId>manage-sys</artifactId>
|
||||||
|
<version>${project.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>cn.novalon.gym.manage</groupId>
|
||||||
|
<artifactId>gym-member</artifactId>
|
||||||
|
<version>${project.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-webflux</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springdoc</groupId>
|
||||||
|
<artifactId>springdoc-openapi-starter-webflux-ui</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-security</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.data</groupId>
|
||||||
|
<artifactId>spring-data-commons</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-test</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.projectreactor</groupId>
|
||||||
|
<artifactId>reactor-test</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>cn.hutool</groupId>
|
||||||
|
<artifactId>hutool-all</artifactId>
|
||||||
|
<version>5.8.25</version>
|
||||||
|
</dependency>
|
||||||
|
<!-- 阿里云号码认证服务(新版SDK) -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.aliyun</groupId>
|
||||||
|
<artifactId>dypnsapi20170525</artifactId>
|
||||||
|
<version>1.0.6</version>
|
||||||
|
</dependency>
|
||||||
|
<!-- 阿里云一键登录服务(旧版SDK,保留兼容) -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.aliyun</groupId>
|
||||||
|
<artifactId>aliyun-java-sdk-dypnsapi</artifactId>
|
||||||
|
<version>1.2.12</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.aliyun</groupId>
|
||||||
|
<artifactId>aliyun-java-sdk-core</artifactId>
|
||||||
|
<version>4.6.0</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.aliyun</groupId>
|
||||||
|
<artifactId>dysmsapi20170525</artifactId>
|
||||||
|
<version>2.0.0</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-jar-plugin</artifactId>
|
||||||
|
<version>3.4.2</version>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<id>default-jar</id>
|
||||||
|
<phase>package</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>jar</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>3.11.0</version>
|
||||||
|
<configuration>
|
||||||
|
<source>21</source>
|
||||||
|
<target>21</target>
|
||||||
|
<annotationProcessorPaths>
|
||||||
|
<path>
|
||||||
|
<groupId>org.projectlombok</groupId>
|
||||||
|
<artifactId>lombok</artifactId>
|
||||||
|
<version>${lombok.version}</version>
|
||||||
|
</path>
|
||||||
|
</annotationProcessorPaths>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</project>
|
||||||
+7
@@ -0,0 +1,7 @@
|
|||||||
|
package cn.novalon.gym.manage.auth.config;
|
||||||
|
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
public class AuthConfig {
|
||||||
|
}
|
||||||
+18
@@ -0,0 +1,18 @@
|
|||||||
|
package cn.novalon.gym.manage.auth.config;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Configuration
|
||||||
|
@ConfigurationProperties(prefix = "dcloud.univerify")
|
||||||
|
public class DCloudUniverifyConfig {
|
||||||
|
private String appid;
|
||||||
|
private String appkey;
|
||||||
|
private String apiSecret;
|
||||||
|
private String apiUrl = "https://developer.dcloud.net.cn/api/client/univerify/getPhoneNumber";
|
||||||
|
private String proxyHost;
|
||||||
|
private Integer proxyPort;
|
||||||
|
private Integer timeout = 10000;
|
||||||
|
}
|
||||||
+47
@@ -0,0 +1,47 @@
|
|||||||
|
package cn.novalon.gym.manage.auth.config;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 阿里云短信配置属性类
|
||||||
|
*
|
||||||
|
* @author auto-generated
|
||||||
|
* @date 2026-06-20
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Configuration
|
||||||
|
@ConfigurationProperties(prefix = "alibaba.cloud.sms")
|
||||||
|
public class SmsProperties {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 访问密钥ID
|
||||||
|
*/
|
||||||
|
private String accessKeyId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 访问密钥密钥
|
||||||
|
*/
|
||||||
|
private String accessKeySecret;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 短信签名名称
|
||||||
|
*/
|
||||||
|
private String signName;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 短信模板CODE
|
||||||
|
*/
|
||||||
|
private String templateCode;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 短信验证码长度(默认6位)
|
||||||
|
*/
|
||||||
|
private int codeLength = 6;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 短信验证码有效期(秒,默认300秒=5分钟)
|
||||||
|
*/
|
||||||
|
private long codeExpireSeconds = 300;
|
||||||
|
}
|
||||||
+26
@@ -0,0 +1,26 @@
|
|||||||
|
package cn.novalon.gym.manage.auth.dto;
|
||||||
|
|
||||||
|
import jakarta.validation.constraints.NotBlank;
|
||||||
|
import jakarta.validation.constraints.Pattern;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 手机号验证码登录请求DTO
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class PhoneCodeLoginDto {
|
||||||
|
|
||||||
|
@NotBlank(message = "手机号不能为空")
|
||||||
|
@Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确")
|
||||||
|
private String phone;
|
||||||
|
|
||||||
|
@NotBlank(message = "验证码不能为空")
|
||||||
|
@Pattern(regexp = "^\\d{4,6}$", message = "验证码格式不正确")
|
||||||
|
private String code;
|
||||||
|
}
|
||||||
+23
@@ -0,0 +1,23 @@
|
|||||||
|
package cn.novalon.gym.manage.auth.dto;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class PhoneLoginDto {
|
||||||
|
|
||||||
|
private String phone;
|
||||||
|
|
||||||
|
private String accessToken;
|
||||||
|
|
||||||
|
private String openid;
|
||||||
|
|
||||||
|
private String nickname;
|
||||||
|
|
||||||
|
private String avatar;
|
||||||
|
}
|
||||||
+22
@@ -0,0 +1,22 @@
|
|||||||
|
package cn.novalon.gym.manage.auth.dto;
|
||||||
|
|
||||||
|
import jakarta.validation.constraints.NotBlank;
|
||||||
|
import jakarta.validation.constraints.Pattern;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 发送短信验证码请求DTO
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class SendCodeRequest {
|
||||||
|
|
||||||
|
@NotBlank(message = "手机号不能为空")
|
||||||
|
@Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确")
|
||||||
|
private String phone;
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
package cn.novalon.gym.manage.auth.dto;
|
||||||
|
|
||||||
|
import jakarta.validation.constraints.NotBlank;
|
||||||
|
import jakarta.validation.constraints.Pattern;
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 短信验证码登录请求DTO
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class SmsLoginDto {
|
||||||
|
|
||||||
|
@NotBlank(message = "手机号不能为空")
|
||||||
|
@Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确")
|
||||||
|
private String phone;
|
||||||
|
|
||||||
|
@NotBlank(message = "验证码不能为空")
|
||||||
|
private String code;
|
||||||
|
}
|
||||||
+59
@@ -0,0 +1,59 @@
|
|||||||
|
package cn.novalon.gym.manage.auth.handler;
|
||||||
|
|
||||||
|
import cn.novalon.gym.manage.auth.dto.PhoneCodeLoginDto;
|
||||||
|
import cn.novalon.gym.manage.auth.dto.PhoneLoginDto;
|
||||||
|
import cn.novalon.gym.manage.auth.dto.SendCodeRequest;
|
||||||
|
import cn.novalon.gym.manage.auth.service.PhoneAuthService;
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.reactive.function.server.ServerRequest;
|
||||||
|
import org.springframework.web.reactive.function.server.ServerResponse;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
@Tag(name = "手机号认证", description = "手机号一键登录与验证码登录")
|
||||||
|
public class PhoneAuthHandler {
|
||||||
|
|
||||||
|
private final PhoneAuthService phoneAuthService;
|
||||||
|
|
||||||
|
@Operation(summary = "手机号一键登录", description = "使用uniapp官方运营商认证,直接手机号登录或注册")
|
||||||
|
public Mono<ServerResponse> oneClickLogin(ServerRequest request) {
|
||||||
|
log.info("收到手机号一键登录请求");
|
||||||
|
|
||||||
|
return request.bodyToMono(PhoneLoginDto.class)
|
||||||
|
.flatMap(phoneAuthService::oneClickLogin)
|
||||||
|
.flatMap(response -> ServerResponse.ok()
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.bodyValue(response));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "发送短信验证码", description = "使用阿里云发送短信验证码")
|
||||||
|
public Mono<ServerResponse> sendSmsCode(ServerRequest request) {
|
||||||
|
log.info("收到发送短信验证码请求");
|
||||||
|
|
||||||
|
return request.bodyToMono(SendCodeRequest.class)
|
||||||
|
.flatMap(req -> phoneAuthService.sendSmsCode(req.getPhone()))
|
||||||
|
.flatMap(success -> ServerResponse.ok()
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.bodyValue(Map.of("success", success, "message", success ? "验证码发送成功" : "验证码发送失败")));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "手机号验证码登录", description = "使用阿里云短信验证码登录或注册")
|
||||||
|
public Mono<ServerResponse> codeLogin(ServerRequest request) {
|
||||||
|
log.info("收到手机号验证码登录请求");
|
||||||
|
|
||||||
|
return request.bodyToMono(PhoneCodeLoginDto.class)
|
||||||
|
.flatMap(phoneAuthService::codeLogin)
|
||||||
|
.flatMap(response -> ServerResponse.ok()
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.bodyValue(response));
|
||||||
|
}
|
||||||
|
}
|
||||||
+37
@@ -0,0 +1,37 @@
|
|||||||
|
package cn.novalon.gym.manage.auth.service;
|
||||||
|
|
||||||
|
import cn.novalon.gym.manage.auth.dto.PhoneLoginDto;
|
||||||
|
import cn.novalon.gym.manage.auth.dto.PhoneCodeLoginDto;
|
||||||
|
import cn.novalon.gym.manage.auth.vo.PhoneLoginVO;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 手机号认证服务接口
|
||||||
|
*/
|
||||||
|
public interface PhoneAuthService {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 手机号一键登录(uniapp官方运营商认证)
|
||||||
|
* 已注册则直接登录,未注册则自动注册后登录
|
||||||
|
*
|
||||||
|
* @param request 登录请求
|
||||||
|
* @return 登录响应
|
||||||
|
*/
|
||||||
|
Mono<PhoneLoginVO> oneClickLogin(PhoneLoginDto request);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 发送短信验证码(阿里云)
|
||||||
|
*
|
||||||
|
* @param phone 手机号
|
||||||
|
* @return 是否发送成功
|
||||||
|
*/
|
||||||
|
Mono<Boolean> sendSmsCode(String phone);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 手机号验证码登录(阿里云)
|
||||||
|
*
|
||||||
|
* @param request 登录请求
|
||||||
|
* @return 登录响应
|
||||||
|
*/
|
||||||
|
Mono<PhoneLoginVO> codeLogin(PhoneCodeLoginDto request);
|
||||||
|
}
|
||||||
+37
@@ -0,0 +1,37 @@
|
|||||||
|
package cn.novalon.gym.manage.auth.service;
|
||||||
|
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 短信服务接口
|
||||||
|
*
|
||||||
|
* @author auto-generated
|
||||||
|
* @date 2026-06-20
|
||||||
|
*/
|
||||||
|
public interface SmsService {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 发送短信验证码
|
||||||
|
*
|
||||||
|
* @param phone 手机号
|
||||||
|
* @return 发送结果
|
||||||
|
*/
|
||||||
|
Mono<Boolean> sendVerificationCode(String phone);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 验证短信验证码
|
||||||
|
*
|
||||||
|
* @param phone 手机号
|
||||||
|
* @param code 验证码
|
||||||
|
* @return 验证结果
|
||||||
|
*/
|
||||||
|
Mono<Boolean> verifyCode(String phone, String code);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取验证码(用于测试或特殊场景)
|
||||||
|
*
|
||||||
|
* @param phone 手机号
|
||||||
|
* @return 验证码
|
||||||
|
*/
|
||||||
|
Mono<String> getVerificationCode(String phone);
|
||||||
|
}
|
||||||
+270
@@ -0,0 +1,270 @@
|
|||||||
|
package cn.novalon.gym.manage.auth.service.impl;
|
||||||
|
|
||||||
|
import cn.novalon.gym.manage.auth.config.DCloudUniverifyConfig;
|
||||||
|
import cn.novalon.gym.manage.auth.config.SmsProperties;
|
||||||
|
import cn.novalon.gym.manage.auth.dto.PhoneCodeLoginDto;
|
||||||
|
import cn.novalon.gym.manage.auth.dto.PhoneLoginDto;
|
||||||
|
import cn.novalon.gym.manage.auth.service.PhoneAuthService;
|
||||||
|
import cn.novalon.gym.manage.auth.service.SmsService;
|
||||||
|
import cn.novalon.gym.manage.auth.vo.PhoneLoginVO;
|
||||||
|
import cn.novalon.gym.manage.common.exception.ErrorCode;
|
||||||
|
import cn.novalon.gym.manage.common.exception.SystemException;
|
||||||
|
import cn.novalon.gym.manage.member.entity.Member;
|
||||||
|
import cn.novalon.gym.manage.member.es.entity.MemberES;
|
||||||
|
import cn.novalon.gym.manage.member.es.repository.MemberESRepository;
|
||||||
|
import cn.novalon.gym.manage.member.repository.IMemberRepository;
|
||||||
|
import cn.novalon.gym.manage.member.util.AesUtil;
|
||||||
|
import cn.novalon.gym.manage.member.util.EsSyncUtils;
|
||||||
|
import cn.novalon.gym.manage.member.util.MemberNoGenerator;
|
||||||
|
import cn.novalon.gym.manage.sys.security.JwtTokenProvider;
|
||||||
|
import jakarta.annotation.PostConstruct;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.web.reactive.function.client.WebClient;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class PhoneAuthServiceImpl implements PhoneAuthService {
|
||||||
|
|
||||||
|
private final IMemberRepository memberRepository;
|
||||||
|
private final MemberESRepository memberESRepository;
|
||||||
|
private final EsSyncUtils esSyncUtils;
|
||||||
|
private final JwtTokenProvider jwtTokenProvider;
|
||||||
|
private final SmsService smsService;
|
||||||
|
private final SmsProperties smsProperties;
|
||||||
|
private final DCloudUniverifyConfig dCloudUniverifyConfig;
|
||||||
|
|
||||||
|
private WebClient webClient;
|
||||||
|
|
||||||
|
private EsSyncUtils.EntitySyncer<Member, MemberES, String> memberSyncer;
|
||||||
|
|
||||||
|
@PostConstruct
|
||||||
|
public void init() {
|
||||||
|
this.memberSyncer = esSyncUtils.bind(Member.class, MemberES.class, memberESRepository);
|
||||||
|
this.webClient = WebClient.builder()
|
||||||
|
.baseUrl(dCloudUniverifyConfig.getApiUrl())
|
||||||
|
.defaultHeader("Content-Type", MediaType.APPLICATION_JSON_VALUE)
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Mono<PhoneLoginVO> oneClickLogin(PhoneLoginDto request) {
|
||||||
|
log.info("手机号一键登录请求, phone: {}, accessToken: {}, openid: {}", request.getPhone(), request.getAccessToken(), request.getOpenid());
|
||||||
|
|
||||||
|
if (request.getPhone() != null && !request.getPhone().isEmpty()) {
|
||||||
|
log.info("直接使用手机号登录");
|
||||||
|
String encryptedPhone = encryptPhone(request.getPhone());
|
||||||
|
return processPhoneLogin(encryptedPhone, request);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (request.getAccessToken() == null || request.getAccessToken().isEmpty()) {
|
||||||
|
log.error("一键登录失败: accessToken为空");
|
||||||
|
return Mono.error(new SystemException(ErrorCode.AUTH_PHONE_ERROR, "登录凭证无效,请重试"));
|
||||||
|
}
|
||||||
|
|
||||||
|
return getPhoneByDcloudApi(request.getAccessToken(), request.getOpenid())
|
||||||
|
.flatMap(phone -> {
|
||||||
|
log.info("通过access_token获取手机号成功: {}", maskPhone(phone));
|
||||||
|
String encryptedPhone = encryptPhone(phone);
|
||||||
|
return processPhoneLogin(encryptedPhone, request);
|
||||||
|
})
|
||||||
|
.onErrorResume(e -> {
|
||||||
|
log.error("一键登录失败", e);
|
||||||
|
return Mono.error(new SystemException(ErrorCode.AUTH_PHONE_ERROR, "手机号获取失败: " + e.getMessage()));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private Mono<PhoneLoginVO> processPhoneLogin(String encryptedPhone, PhoneLoginDto request) {
|
||||||
|
return memberRepository.findByPhone(encryptedPhone)
|
||||||
|
.flatMap(existingMember -> {
|
||||||
|
log.info("手机号已注册,直接登录, memberId: {}", existingMember.getId());
|
||||||
|
return doLogin(existingMember, false, request);
|
||||||
|
})
|
||||||
|
.switchIfEmpty(Mono.defer(() -> {
|
||||||
|
log.info("手机号未注册,创建新会员");
|
||||||
|
return createNewMemberAndLogin(request, encryptedPhone);
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
private Mono<String> getPhoneByDcloudApi(String accessToken, String openid) {
|
||||||
|
Map<String, String> requestBody = new HashMap<>();
|
||||||
|
requestBody.put("appid", dCloudUniverifyConfig.getAppid());
|
||||||
|
requestBody.put("appkey", dCloudUniverifyConfig.getAppkey());
|
||||||
|
requestBody.put("apiSecret", dCloudUniverifyConfig.getApiSecret());
|
||||||
|
requestBody.put("access_token", accessToken);
|
||||||
|
requestBody.put("openid", openid);
|
||||||
|
|
||||||
|
log.info("调用DCloud Univerify API, params: {}", requestBody);
|
||||||
|
|
||||||
|
return webClient.post()
|
||||||
|
.bodyValue(requestBody)
|
||||||
|
.retrieve()
|
||||||
|
.bodyToMono(Map.class)
|
||||||
|
.flatMap(response -> {
|
||||||
|
log.info("DCloud API响应: {}", response);
|
||||||
|
|
||||||
|
Integer code = (Integer) response.get("code");
|
||||||
|
Boolean success = (Boolean) response.get("success");
|
||||||
|
|
||||||
|
if ((code != null && code == 0) || (success != null && success)) {
|
||||||
|
Map<String, Object> data = (Map<String, Object>) response.get("data");
|
||||||
|
if (data != null) {
|
||||||
|
String phoneNumber = (String) data.get("phoneNumber");
|
||||||
|
if (phoneNumber != null && !phoneNumber.isEmpty()) {
|
||||||
|
return Mono.just(phoneNumber);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
String phoneNumber = (String) response.get("phoneNumber");
|
||||||
|
if (phoneNumber != null && !phoneNumber.isEmpty()) {
|
||||||
|
return Mono.just(phoneNumber);
|
||||||
|
}
|
||||||
|
String phone = (String) response.get("phone");
|
||||||
|
if (phone != null && !phone.isEmpty()) {
|
||||||
|
return Mono.just(phone);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String message = (String) response.get("message");
|
||||||
|
log.warn("DCloud API返回错误: code={}, success={}, message={}", code, success, message);
|
||||||
|
return Mono.error(new SystemException(ErrorCode.AUTH_PHONE_ERROR, "手机号获取失败: " + message));
|
||||||
|
})
|
||||||
|
.onErrorResume(e -> {
|
||||||
|
log.error("调用DCloud API失败", e);
|
||||||
|
return Mono.error(new SystemException(ErrorCode.AUTH_PHONE_ERROR, "手机号获取失败: " + e.getMessage()));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 手机号脱敏显示
|
||||||
|
*/
|
||||||
|
private String maskPhone(String phone) {
|
||||||
|
if (phone == null || phone.length() < 11) {
|
||||||
|
return phone;
|
||||||
|
}
|
||||||
|
return phone.substring(0, 3) + "****" + phone.substring(7);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Mono<Boolean> sendSmsCode(String phone) {
|
||||||
|
log.info("发送短信验证码, phone: {}", phone);
|
||||||
|
return smsService.sendVerificationCode(phone);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Mono<PhoneLoginVO> codeLogin(PhoneCodeLoginDto request) {
|
||||||
|
log.info("手机号验证码登录, phone: {}", request.getPhone());
|
||||||
|
|
||||||
|
return smsService.verifyCode(request.getPhone(), request.getCode())
|
||||||
|
.flatMap(verified -> {
|
||||||
|
if (!verified) {
|
||||||
|
log.warn("验证码验证失败, phone: {}", request.getPhone());
|
||||||
|
return Mono.error(new SystemException(ErrorCode.SYSTEM_INTERNAL_ERROR, "验证码错误或已过期"));
|
||||||
|
}
|
||||||
|
|
||||||
|
String encryptedPhone = encryptPhone(request.getPhone());
|
||||||
|
|
||||||
|
return memberRepository.findByPhone(encryptedPhone)
|
||||||
|
.flatMap(existingMember -> {
|
||||||
|
log.info("手机号已注册,直接登录, memberId: {}", existingMember.getId());
|
||||||
|
return doLogin(existingMember, false, null);
|
||||||
|
})
|
||||||
|
.switchIfEmpty(Mono.defer(() -> {
|
||||||
|
log.info("手机号未注册,创建新会员");
|
||||||
|
PhoneLoginDto registerRequest = new PhoneLoginDto();
|
||||||
|
return createNewMemberAndLogin(registerRequest, encryptedPhone);
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private Mono<PhoneLoginVO> createNewMemberAndLogin(PhoneLoginDto request, String encryptedPhone) {
|
||||||
|
String memberNo = MemberNoGenerator.generate();
|
||||||
|
log.info("生成会员号: {}", memberNo);
|
||||||
|
|
||||||
|
Member member = new Member();
|
||||||
|
member.setMemberNo(memberNo);
|
||||||
|
member.setPhone(encryptedPhone);
|
||||||
|
member.setNickname(request != null ? request.getNickname() : null);
|
||||||
|
member.setAvatar(request != null ? request.getAvatar() : null);
|
||||||
|
member.setLastLoginAt(LocalDateTime.now());
|
||||||
|
member.setIsDeleted(false);
|
||||||
|
|
||||||
|
return memberRepository.save(member)
|
||||||
|
.doOnSuccess(memberSyncer::sync)
|
||||||
|
.flatMap(savedMember -> {
|
||||||
|
log.info("新会员创建成功, memberId: {}, memberNo: {}", savedMember.getId(), savedMember.getMemberNo());
|
||||||
|
return doLogin(savedMember, true, request);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private Mono<PhoneLoginVO> doLogin(Member member, boolean isNewUser, PhoneLoginDto request) {
|
||||||
|
log.info("登录成功, memberId: {}", member.getId());
|
||||||
|
|
||||||
|
member.setLastLoginAt(LocalDateTime.now());
|
||||||
|
|
||||||
|
if (isNewUser && request != null) {
|
||||||
|
if ((member.getNickname() == null || member.getNickname().isEmpty())
|
||||||
|
&& request.getNickname() != null && !request.getNickname().isEmpty()) {
|
||||||
|
member.setNickname(request.getNickname());
|
||||||
|
}
|
||||||
|
if ((member.getAvatar() == null || member.getAvatar().isEmpty())
|
||||||
|
&& request.getAvatar() != null && !request.getAvatar().isEmpty()) {
|
||||||
|
member.setAvatar(request.getAvatar());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return memberRepository.save(member)
|
||||||
|
.doOnSuccess(memberSyncer::sync)
|
||||||
|
.map(this::buildLoginResponse);
|
||||||
|
}
|
||||||
|
|
||||||
|
private PhoneLoginVO buildLoginResponse(Member member) {
|
||||||
|
boolean needCompleteInfo = member.getNickname() == null || member.getNickname().isEmpty();
|
||||||
|
|
||||||
|
List<String> roles = new ArrayList<>();
|
||||||
|
String accessToken = jwtTokenProvider.generateToken(String.valueOf(member.getId()), member.getId(), roles);
|
||||||
|
|
||||||
|
log.info("JWT Token 生成成功, memberId: {}", member.getId());
|
||||||
|
|
||||||
|
PhoneLoginVO vo = new PhoneLoginVO();
|
||||||
|
vo.setMemberId(member.getId());
|
||||||
|
vo.setMemberNo(member.getMemberNo());
|
||||||
|
vo.setAccessToken(accessToken);
|
||||||
|
vo.setRefreshToken(accessToken);
|
||||||
|
vo.setExpiresIn(86400);
|
||||||
|
vo.setIsNewUser(member.getCreatedAt() == null ? false :
|
||||||
|
member.getCreatedAt().isAfter(LocalDateTime.now().minusMinutes(1)));
|
||||||
|
vo.setNeedCompleteInfo(needCompleteInfo);
|
||||||
|
vo.setNickname(member.getNickname());
|
||||||
|
vo.setAvatar(member.getAvatar());
|
||||||
|
vo.setPhone(member.getPhone() != null ? decryptPhone(member.getPhone()) : null);
|
||||||
|
return vo;
|
||||||
|
}
|
||||||
|
|
||||||
|
private String encryptPhone(String phoneNumber) {
|
||||||
|
try {
|
||||||
|
return AesUtil.encrypt(phoneNumber);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("手机号加密失败", e);
|
||||||
|
throw new SystemException(ErrorCode.SYSTEM_INTERNAL_ERROR, "手机号加密失败");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private String decryptPhone(String encryptedPhone) {
|
||||||
|
try {
|
||||||
|
return AesUtil.decrypt(encryptedPhone);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("手机号解密失败", e);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+198
@@ -0,0 +1,198 @@
|
|||||||
|
package cn.novalon.gym.manage.auth.service.impl;
|
||||||
|
|
||||||
|
import cn.novalon.gym.manage.auth.config.SmsProperties;
|
||||||
|
import cn.novalon.gym.manage.auth.service.SmsService;
|
||||||
|
import cn.novalon.gym.manage.common.constant.RedisKeyConstants;
|
||||||
|
import cn.novalon.gym.manage.common.util.RedisUtil;
|
||||||
|
import com.aliyuncs.CommonRequest;
|
||||||
|
import com.aliyuncs.CommonResponse;
|
||||||
|
import com.aliyuncs.DefaultAcsClient;
|
||||||
|
import com.aliyuncs.IAcsClient;
|
||||||
|
import com.aliyuncs.exceptions.ClientException;
|
||||||
|
import com.aliyuncs.http.MethodType;
|
||||||
|
import com.aliyuncs.profile.DefaultProfile;
|
||||||
|
import com.aliyuncs.profile.IClientProfile;
|
||||||
|
import com.fasterxml.jackson.databind.JsonNode;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.ZoneOffset;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class SmsServiceImpl implements SmsService {
|
||||||
|
|
||||||
|
private static final long SEND_INTERVAL_SECONDS = 60;
|
||||||
|
private static final long CODE_EXPIRE_SECONDS = 300;
|
||||||
|
|
||||||
|
private final SmsProperties smsProperties;
|
||||||
|
private final RedisUtil redisUtil;
|
||||||
|
private final ObjectMapper objectMapper;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Mono<Boolean> sendVerificationCode(String phone) {
|
||||||
|
log.info("发送短信验证码, phone: {}", phone);
|
||||||
|
|
||||||
|
String rateLimitKey = RedisKeyConstants.SMS_CODE + phone + ":rate_limit";
|
||||||
|
|
||||||
|
return redisUtil.get(rateLimitKey, Long.class)
|
||||||
|
.defaultIfEmpty(0L)
|
||||||
|
.flatMap(lastSendTime -> {
|
||||||
|
long currentTime = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC);
|
||||||
|
|
||||||
|
if (currentTime - lastSendTime < SEND_INTERVAL_SECONDS) {
|
||||||
|
long remainingSeconds = SEND_INTERVAL_SECONDS - (currentTime - lastSendTime);
|
||||||
|
log.warn("发送频率限制, phone: {}, 剩余时间: {}秒", phone, remainingSeconds);
|
||||||
|
return Mono.just(false);
|
||||||
|
}
|
||||||
|
|
||||||
|
return Mono.fromCallable(() -> {
|
||||||
|
try {
|
||||||
|
IAcsClient client = createClient();
|
||||||
|
|
||||||
|
CommonRequest request = new CommonRequest();
|
||||||
|
request.setSysMethod(MethodType.POST);
|
||||||
|
request.setSysDomain("dypnsapi.aliyuncs.com");
|
||||||
|
request.setSysVersion("2017-05-25");
|
||||||
|
request.setSysAction("SendSmsVerifyCode");
|
||||||
|
request.putQueryParameter("PhoneNumber", phone);
|
||||||
|
request.putQueryParameter("SignName", smsProperties.getSignName());
|
||||||
|
request.putQueryParameter("TemplateCode", smsProperties.getTemplateCode());
|
||||||
|
request.putQueryParameter("TemplateParam", "{\"code\":\"##code##\",\"min\":\"5\"}");
|
||||||
|
request.putQueryParameter("ReturnVerifyCode", "true");
|
||||||
|
|
||||||
|
log.info("阿里云号码认证请求参数 - signName: {}, templateCode: {}, templateParam: {}",
|
||||||
|
smsProperties.getSignName(),
|
||||||
|
smsProperties.getTemplateCode(),
|
||||||
|
"{\"code\":\"##code##\",\"min\":\"5\"}");
|
||||||
|
|
||||||
|
CommonResponse response = client.getCommonResponse(request);
|
||||||
|
String responseData = response.getData();
|
||||||
|
log.info("阿里云号码认证原始响应: {}", responseData);
|
||||||
|
|
||||||
|
JsonNode jsonNode = objectMapper.readTree(responseData);
|
||||||
|
|
||||||
|
JsonNode codeNode = jsonNode.get("Code");
|
||||||
|
if (codeNode == null) {
|
||||||
|
log.error("阿里云响应中找不到Code字段, 原始响应: {}", responseData);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
String code = codeNode.asText();
|
||||||
|
|
||||||
|
if ("OK".equals(code)) {
|
||||||
|
JsonNode requestIdNode = jsonNode.get("RequestId");
|
||||||
|
String requestId = requestIdNode != null ? requestIdNode.asText() : "unknown";
|
||||||
|
log.info("短信验证码发送成功, phone: {}, requestId: {}", phone, requestId);
|
||||||
|
|
||||||
|
// 提取验证码并存入Redis
|
||||||
|
JsonNode modelNode = jsonNode.get("Model");
|
||||||
|
if (modelNode != null) {
|
||||||
|
JsonNode verifyCodeNode = modelNode.get("VerifyCode");
|
||||||
|
if (verifyCodeNode != null) {
|
||||||
|
String verifyCode = verifyCodeNode.asText();
|
||||||
|
String smsCodeKey = RedisKeyConstants.SMS_CODE + phone;
|
||||||
|
redisUtil.setWithExpire(smsCodeKey, verifyCode, CODE_EXPIRE_SECONDS).subscribe();
|
||||||
|
log.info("验证码已存入Redis, phone: {}, key: {}, expire: {}秒", phone, smsCodeKey, CODE_EXPIRE_SECONDS);
|
||||||
|
} else {
|
||||||
|
log.warn("响应中未找到Model.VerifyCode字段, 原始响应: {}", responseData);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
log.warn("响应中未找到Model字段, 原始响应: {}", responseData);
|
||||||
|
}
|
||||||
|
|
||||||
|
redisUtil.setWithExpire(rateLimitKey, currentTime, SEND_INTERVAL_SECONDS).subscribe();
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
JsonNode messageNode = jsonNode.get("Message");
|
||||||
|
String message = messageNode != null ? messageNode.asText() : "unknown";
|
||||||
|
log.error("短信验证码发送失败, phone: {}, code: {}, message: {}", phone, code, message);
|
||||||
|
return false;
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("发送短信验证码异常, phone: {}, 异常信息: {}", phone, e.getMessage(), e);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Mono<Boolean> verifyCode(String phone, String code) {
|
||||||
|
log.info("验证短信验证码, phone: {}", phone);
|
||||||
|
|
||||||
|
return Mono.fromCallable(() -> {
|
||||||
|
try {
|
||||||
|
IAcsClient client = createClient();
|
||||||
|
|
||||||
|
CommonRequest request = new CommonRequest();
|
||||||
|
request.setSysMethod(MethodType.POST);
|
||||||
|
request.setSysDomain("dypnsapi.aliyuncs.com");
|
||||||
|
request.setSysVersion("2017-05-25");
|
||||||
|
request.setSysAction("CheckSmsVerifyCode");
|
||||||
|
request.putQueryParameter("PhoneNumber", phone);
|
||||||
|
request.putQueryParameter("VerifyCode", code);
|
||||||
|
|
||||||
|
log.info("阿里云号码认证核验参数 - phone: {}, code: {}", phone, code);
|
||||||
|
|
||||||
|
CommonResponse response = client.getCommonResponse(request);
|
||||||
|
String responseData = response.getData();
|
||||||
|
log.info("阿里云号码认证核验原始响应: {}", responseData);
|
||||||
|
|
||||||
|
JsonNode jsonNode = objectMapper.readTree(responseData);
|
||||||
|
|
||||||
|
JsonNode codeNode = jsonNode.get("Code");
|
||||||
|
if (codeNode == null) {
|
||||||
|
log.error("阿里云核验响应中找不到Code字段, 原始响应: {}", responseData);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
String responseCode = codeNode.asText();
|
||||||
|
JsonNode modelNode = jsonNode.get("Model");
|
||||||
|
JsonNode verifyResultNode = modelNode != null ? modelNode.get("VerifyResult") : null;
|
||||||
|
boolean verifyResult = verifyResultNode != null && "PASS".equals(verifyResultNode.asText());
|
||||||
|
|
||||||
|
if ("OK".equals(responseCode) && verifyResult) {
|
||||||
|
log.info("验证码验证成功, phone: {}", phone);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
JsonNode messageNode = jsonNode.get("Message");
|
||||||
|
String message = messageNode != null ? messageNode.asText() : "unknown";
|
||||||
|
log.warn("验证码验证失败, phone: {}, code: {}, message: {}, result: {}",
|
||||||
|
phone, responseCode, message, verifyResult);
|
||||||
|
return false;
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("验证短信验证码异常, phone: {}, 异常信息: {}", phone, e.getMessage(), e);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Mono<String> getVerificationCode(String phone) {
|
||||||
|
try {
|
||||||
|
String cacheKey = RedisKeyConstants.SMS_CODE + phone;
|
||||||
|
return redisUtil.get(cacheKey, String.class);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("获取验证码异常, phone: {}", phone, e);
|
||||||
|
return Mono.empty();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private IAcsClient createClient() throws ClientException {
|
||||||
|
IClientProfile profile = DefaultProfile.getProfile(
|
||||||
|
"cn-hangzhou",
|
||||||
|
smsProperties.getAccessKeyId(),
|
||||||
|
smsProperties.getAccessKeySecret());
|
||||||
|
DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", "Dypnsapi", "dypnsapi.aliyuncs.com");
|
||||||
|
return new DefaultAcsClient(profile);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
package cn.novalon.gym.manage.auth.vo;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 手机号一键登录响应VO
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class PhoneLoginVO {
|
||||||
|
|
||||||
|
private Long memberId;
|
||||||
|
|
||||||
|
private String memberNo;
|
||||||
|
|
||||||
|
private String phone;
|
||||||
|
|
||||||
|
private String accessToken;
|
||||||
|
|
||||||
|
private String refreshToken;
|
||||||
|
|
||||||
|
private Integer expiresIn;
|
||||||
|
|
||||||
|
private Boolean isNewUser;
|
||||||
|
|
||||||
|
private Boolean needCompleteInfo;
|
||||||
|
|
||||||
|
private String nickname;
|
||||||
|
|
||||||
|
private String avatar;
|
||||||
|
}
|
||||||
+5
@@ -0,0 +1,5 @@
|
|||||||
|
cn.novalon.gym.manage.auth.handler.PhoneAuthHandler
|
||||||
|
cn.novalon.gym.manage.auth.service.impl.PhoneAuthServiceImpl
|
||||||
|
cn.novalon.gym.manage.auth.service.impl.SmsServiceImpl
|
||||||
|
cn.novalon.gym.manage.auth.config.AuthConfig
|
||||||
|
cn.novalon.gym.manage.auth.config.SmsProperties
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
# Compiled class file
|
||||||
|
*.class
|
||||||
|
|
||||||
|
# Log file
|
||||||
|
*.log
|
||||||
|
|
||||||
|
# BlueJ files
|
||||||
|
*.ctxt
|
||||||
|
|
||||||
|
# Mobile Tools for Java (J2ME)
|
||||||
|
.mtj.tmp/
|
||||||
|
|
||||||
|
# Package Files
|
||||||
|
*.jar
|
||||||
|
*.war
|
||||||
|
*.nar
|
||||||
|
*.ear
|
||||||
|
*.zip
|
||||||
|
*.tar.gz
|
||||||
|
*.rar
|
||||||
|
|
||||||
|
# Virtual machine crash logs
|
||||||
|
hs_err_pid*
|
||||||
|
replay_pid*
|
||||||
|
|
||||||
|
# Maven
|
||||||
|
target/
|
||||||
|
pom.xml.tag
|
||||||
|
pom.xml.releaseBackup
|
||||||
|
pom.xml.versionsBackup
|
||||||
|
pom.xml.next
|
||||||
|
release.properties
|
||||||
|
dependency-reduced-pom.xml
|
||||||
|
buildNumber.properties
|
||||||
|
.mvn/timing.properties
|
||||||
|
.mvn/wrapper/maven-wrapper.jar
|
||||||
|
|
||||||
|
# IDE
|
||||||
|
.idea/
|
||||||
|
*.iml
|
||||||
|
.vscode/
|
||||||
|
.settings/
|
||||||
|
.classpath
|
||||||
|
.project
|
||||||
|
|
||||||
|
# OS
|
||||||
|
.DS_Store
|
||||||
|
Thumbs.db
|
||||||
@@ -0,0 +1,257 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>cn.novalon.gym.manage</groupId>
|
||||||
|
<artifactId>gym-manage-api</artifactId>
|
||||||
|
<version>1.0.0</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<artifactId>gym-checkIn</artifactId>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
|
<name>Gym CheckIn</name>
|
||||||
|
<description>Check-In Management Module - Member Attendance Services</description>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>cn.novalon.gym.manage</groupId>
|
||||||
|
<artifactId>manage-common</artifactId>
|
||||||
|
<version>${project.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>cn.novalon.gym.manage</groupId>
|
||||||
|
<artifactId>manage-db</artifactId>
|
||||||
|
<version>${project.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>cn.novalon.gym.manage</groupId>
|
||||||
|
<artifactId>gym-member</artifactId>
|
||||||
|
<version>${project.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>cn.novalon.gym.manage</groupId>
|
||||||
|
<artifactId>gym-groupCourse</artifactId>
|
||||||
|
<version>${project.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-webflux</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-aop</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springdoc</groupId>
|
||||||
|
<artifactId>springdoc-openapi-starter-webflux-ui</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-security</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.data</groupId>
|
||||||
|
<artifactId>spring-data-commons</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-test</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.security</groupId>
|
||||||
|
<artifactId>spring-security-test</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.projectreactor</groupId>
|
||||||
|
<artifactId>reactor-test</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.github.resilience4j</groupId>
|
||||||
|
<artifactId>resilience4j-spring-boot3</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.github.resilience4j</groupId>
|
||||||
|
<artifactId>resilience4j-reactor</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.testcontainers</groupId>
|
||||||
|
<artifactId>testcontainers</artifactId>
|
||||||
|
<version>1.21.4</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.testcontainers</groupId>
|
||||||
|
<artifactId>postgresql</artifactId>
|
||||||
|
<version>1.21.4</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.testcontainers</groupId>
|
||||||
|
<artifactId>junit-jupiter</artifactId>
|
||||||
|
<version>1.21.4</version>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.h2database</groupId>
|
||||||
|
<artifactId>h2</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>io.r2dbc</groupId>
|
||||||
|
<artifactId>r2dbc-h2</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.postgresql</groupId>
|
||||||
|
<artifactId>r2dbc-postgresql</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>cn.hutool</groupId>
|
||||||
|
<artifactId>hutool-all</artifactId>
|
||||||
|
<version>5.8.25</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.projectlombok</groupId>
|
||||||
|
<artifactId>lombok</artifactId>
|
||||||
|
<scope>provided</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.google.zxing</groupId>
|
||||||
|
<artifactId>core</artifactId>
|
||||||
|
<version>3.5.1</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- 添加 ZXing JavaSE 扩展(用于生成图片) -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.google.zxing</groupId>
|
||||||
|
<artifactId>javase</artifactId>
|
||||||
|
<version>3.5.1</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-websocket</artifactId>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-jar-plugin</artifactId>
|
||||||
|
<version>3.4.2</version>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<id>default-jar</id>
|
||||||
|
<phase>package</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>jar</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>3.11.0</version>
|
||||||
|
<configuration>
|
||||||
|
<source>21</source>
|
||||||
|
<target>21</target>
|
||||||
|
<annotationProcessorPaths>
|
||||||
|
<path>
|
||||||
|
<groupId>org.mapstruct</groupId>
|
||||||
|
<artifactId>mapstruct-processor</artifactId>
|
||||||
|
<version>1.5.5.Final</version>
|
||||||
|
</path>
|
||||||
|
<path>
|
||||||
|
<groupId>org.projectlombok</groupId>
|
||||||
|
<artifactId>lombok</artifactId>
|
||||||
|
<version>${lombok.version}</version>
|
||||||
|
</path>
|
||||||
|
<path>
|
||||||
|
<groupId>org.projectlombok</groupId>
|
||||||
|
<artifactId>lombok-mapstruct-binding</artifactId>
|
||||||
|
<version>0.2.0</version>
|
||||||
|
</path>
|
||||||
|
</annotationProcessorPaths>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.jacoco</groupId>
|
||||||
|
<artifactId>jacoco-maven-plugin</artifactId>
|
||||||
|
<version>0.8.12</version>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<id>prepare-agent</id>
|
||||||
|
<goals>
|
||||||
|
<goal>prepare-agent</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
<execution>
|
||||||
|
<id>report</id>
|
||||||
|
<phase>verify</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>report</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
<execution>
|
||||||
|
<id>check</id>
|
||||||
|
<phase>verify</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>check</goal>
|
||||||
|
</goals>
|
||||||
|
<configuration>
|
||||||
|
<rules>
|
||||||
|
<rule>
|
||||||
|
<element>BUNDLE</element>
|
||||||
|
<limits>
|
||||||
|
<limit>
|
||||||
|
<counter>INSTRUCTION</counter>
|
||||||
|
<value>COVEREDRATIO</value>
|
||||||
|
<minimum>0.60</minimum>
|
||||||
|
</limit>
|
||||||
|
</limits>
|
||||||
|
</rule>
|
||||||
|
</rules>
|
||||||
|
</configuration>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
</plugin>
|
||||||
|
<plugin>
|
||||||
|
<groupId>com.github.spotbugs</groupId>
|
||||||
|
<artifactId>spotbugs-maven-plugin</artifactId>
|
||||||
|
<version>4.8.6.0</version>
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.github.spotbugs</groupId>
|
||||||
|
<artifactId>spotbugs</artifactId>
|
||||||
|
<version>4.8.6</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
<executions>
|
||||||
|
<execution>
|
||||||
|
<id>spotbugs-check</id>
|
||||||
|
<phase>verify</phase>
|
||||||
|
<goals>
|
||||||
|
<goal>check</goal>
|
||||||
|
</goals>
|
||||||
|
</execution>
|
||||||
|
</executions>
|
||||||
|
<configuration>
|
||||||
|
<effort>Max</effort>
|
||||||
|
<threshold>High</threshold>
|
||||||
|
<failOnError>true</failOnError>
|
||||||
|
<excludeFilterFile>spotbugs-exclude.xml</excludeFilterFile>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</project>
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<FindBugsFilter>
|
||||||
|
<Match>
|
||||||
|
<Class name="~.*\.entity\..*" />
|
||||||
|
</Match>
|
||||||
|
<Match>
|
||||||
|
<Class name="~.*\.dto\..*" />
|
||||||
|
</Match>
|
||||||
|
<Match>
|
||||||
|
<Class name="~.*\.converter\..*" />
|
||||||
|
</Match>
|
||||||
|
</FindBugsFilter>
|
||||||
+43
@@ -0,0 +1,43 @@
|
|||||||
|
package cn.novalon.gym.manage.checkIn.config;
|
||||||
|
|
||||||
|
import cn.novalon.gym.manage.checkIn.websocket.MyWebSocketHandler;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.web.reactive.HandlerMapping;
|
||||||
|
import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping;
|
||||||
|
import org.springframework.web.reactive.socket.WebSocketHandler;
|
||||||
|
import org.springframework.web.reactive.socket.server.support.WebSocketHandlerAdapter;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
public class CheckInWebSocketConfig {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private MyWebSocketHandler myWebSocketHandler;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 注册 WebSocket 路由映射
|
||||||
|
* 路径对应前端连接的 ws://xxx/webSocket/checkIn
|
||||||
|
*/
|
||||||
|
@Bean
|
||||||
|
public HandlerMapping webSocketMapping() {
|
||||||
|
Map<String, WebSocketHandler> map = new HashMap<>();
|
||||||
|
map.put("/webSocket/checkIn", myWebSocketHandler);
|
||||||
|
|
||||||
|
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
|
||||||
|
mapping.setUrlMap(map);
|
||||||
|
mapping.setOrder(10); // 设置优先级
|
||||||
|
return mapping;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 注册 WebSocket 处理器适配器(必须)
|
||||||
|
*/
|
||||||
|
@Bean
|
||||||
|
public WebSocketHandlerAdapter handlerAdapter() {
|
||||||
|
return new WebSocketHandlerAdapter();
|
||||||
|
}
|
||||||
|
}
|
||||||
+46
@@ -0,0 +1,46 @@
|
|||||||
|
package cn.novalon.gym.manage.checkIn.config;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Configuration
|
||||||
|
@ConfigurationProperties(prefix = "qr.config")
|
||||||
|
public class QRCodeConfig {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 二维码宽度(像素)
|
||||||
|
*/
|
||||||
|
private Integer width = 300;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 二维码高度(像素)
|
||||||
|
*/
|
||||||
|
private Integer height = 300;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 白边宽度
|
||||||
|
*/
|
||||||
|
private Integer margin = 1;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 容错率:L, M, Q, H
|
||||||
|
*/
|
||||||
|
private String errorCorrection = "M";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 图片格式:png, jpg
|
||||||
|
*/
|
||||||
|
private String format = "png";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 是否启用Logo
|
||||||
|
*/
|
||||||
|
private Boolean logoEnabled = false;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Logo路径
|
||||||
|
*/
|
||||||
|
private String logoPath = "";
|
||||||
|
}
|
||||||
+43
@@ -0,0 +1,43 @@
|
|||||||
|
package cn.novalon.gym.manage.checkIn.config;
|
||||||
|
|
||||||
|
import cn.novalon.gym.manage.checkIn.websocket.MyWebSocketHandler;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
import org.springframework.web.reactive.HandlerMapping;
|
||||||
|
import org.springframework.web.reactive.handler.SimpleUrlHandlerMapping;
|
||||||
|
import org.springframework.web.reactive.socket.WebSocketHandler;
|
||||||
|
import org.springframework.web.reactive.socket.server.support.WebSocketHandlerAdapter;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
public class WebSocketConfig {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private MyWebSocketHandler myWebSocketHandler;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 注册 WebSocket 路由映射
|
||||||
|
* 路径对应前端连接的 ws://xxx/webSocket/checkIn
|
||||||
|
*/
|
||||||
|
@Bean
|
||||||
|
public HandlerMapping webSocketMapping() {
|
||||||
|
Map<String, WebSocketHandler> map = new HashMap<>();
|
||||||
|
map.put("/webSocket/checkIn", myWebSocketHandler);
|
||||||
|
|
||||||
|
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
|
||||||
|
mapping.setUrlMap(map);
|
||||||
|
mapping.setOrder(10); // 设置优先级
|
||||||
|
return mapping;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 注册 WebSocket 处理器适配器(必须)
|
||||||
|
*/
|
||||||
|
@Bean
|
||||||
|
public WebSocketHandlerAdapter handlerAdapter() {
|
||||||
|
return new WebSocketHandlerAdapter();
|
||||||
|
}
|
||||||
|
}
|
||||||
+43
@@ -0,0 +1,43 @@
|
|||||||
|
package cn.novalon.gym.manage.checkIn.constant;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 打卡模块 Redis 键常量
|
||||||
|
*
|
||||||
|
* @author 付嘉
|
||||||
|
* @date 2026-05-30
|
||||||
|
*/
|
||||||
|
public final class QRRedisKey {
|
||||||
|
|
||||||
|
private static final String SEPARATOR = ":";
|
||||||
|
private static final String QRCODE_USER_DAILY = "qrcode:user:daily";
|
||||||
|
private static final String QRCODE_CONTENT = "QR_";
|
||||||
|
private QRRedisKey() {
|
||||||
|
// 私有构造,防止实例化
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用户当日二维码
|
||||||
|
* 格式:qrcode:user:daily:{userId}:{date}
|
||||||
|
* 示例:qrcode:user:daily:1001:2026-05-30
|
||||||
|
*/
|
||||||
|
public static String qrcodeUserDaily(Long userId, LocalDate date) {
|
||||||
|
return QRCODE_USER_DAILY + SEPARATOR + userId + SEPARATOR + date;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用户当日二维码(今天)
|
||||||
|
*/
|
||||||
|
public static String qrcodeUserToday(Long userId) {
|
||||||
|
return qrcodeUserDaily(userId, LocalDate.now());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 生成二维码内容(每个用户每次调用都不同)
|
||||||
|
*/
|
||||||
|
public static String generateQrcodeContent() {
|
||||||
|
return QRCODE_CONTENT + UUID.randomUUID().toString().replace("-", "");
|
||||||
|
}
|
||||||
|
}
|
||||||
+13
@@ -0,0 +1,13 @@
|
|||||||
|
package cn.novalon.gym.manage.checkIn.dto;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class QRCodeDto {
|
||||||
|
|
||||||
|
private String qrContent;
|
||||||
|
|
||||||
|
private boolean isUsed;
|
||||||
|
}
|
||||||
+209
@@ -0,0 +1,209 @@
|
|||||||
|
package cn.novalon.gym.manage.checkIn.entity;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
import org.springframework.data.annotation.CreatedDate;
|
||||||
|
import org.springframework.data.annotation.Id;
|
||||||
|
import org.springframework.data.annotation.LastModifiedDate;
|
||||||
|
import org.springframework.data.relational.core.mapping.Column;
|
||||||
|
import org.springframework.data.relational.core.mapping.Table;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 会员到店签到记录实体
|
||||||
|
*
|
||||||
|
* @author 付嘉
|
||||||
|
* @date 2026-06-08
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
@Table("sign_in_record")
|
||||||
|
public class SignInRecord {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 自增主键
|
||||||
|
*/
|
||||||
|
@Id
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 会员ID,关联member表
|
||||||
|
*/
|
||||||
|
@Column("member_id")
|
||||||
|
private Long memberId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签到时使用的会员卡ID
|
||||||
|
*/
|
||||||
|
@Column("member_card_id")
|
||||||
|
private Long memberCardId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签到入场时间
|
||||||
|
*/
|
||||||
|
@Column("sign_in_time")
|
||||||
|
private LocalDateTime signInTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签到方式:QR_CODE-扫码签到,MANUAL-手动签到,FACE-人脸识别
|
||||||
|
*/
|
||||||
|
@Column("sign_in_type")
|
||||||
|
private String signInType;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签到状态:SUCCESS-成功,FAILED-失败
|
||||||
|
*/
|
||||||
|
@Column("sign_in_status")
|
||||||
|
private String signInStatus;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* JSONB格式,存储会员卡验证时的快照数据
|
||||||
|
*/
|
||||||
|
@Column("verification_details")
|
||||||
|
private String verificationDetails;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 失败时的具体原因文案
|
||||||
|
*/
|
||||||
|
@Column("fail_reason")
|
||||||
|
private String failReason;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 操作人ID(前台人员),自助签到时为NULL
|
||||||
|
*/
|
||||||
|
@Column("operator_id")
|
||||||
|
private Long operatorId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 操作人姓名冗余
|
||||||
|
*/
|
||||||
|
@Column("operator_name")
|
||||||
|
private String operatorName;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签到设备标识或型号
|
||||||
|
*/
|
||||||
|
@Column("device_info")
|
||||||
|
private String deviceInfo;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 客户端IP地址
|
||||||
|
*/
|
||||||
|
@Column("ip_address")
|
||||||
|
private String ipAddress;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签到来源:MINI_PROGRAM-小程序扫码,PC_BACKEND-后台管理端
|
||||||
|
*/
|
||||||
|
@Column("source")
|
||||||
|
private String source;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 软删除标识:false-未删除,true-已删除
|
||||||
|
*/
|
||||||
|
@Column("is_delete")
|
||||||
|
private Boolean isDelete;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 记录创建时间
|
||||||
|
*/
|
||||||
|
@CreatedDate
|
||||||
|
@Column("created_at")
|
||||||
|
private LocalDateTime createdAt;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 记录更新时间
|
||||||
|
*/
|
||||||
|
@LastModifiedDate
|
||||||
|
@Column("updated_at")
|
||||||
|
private LocalDateTime updatedAt;
|
||||||
|
|
||||||
|
// ========== 常量定义 ==========
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签到类型常量
|
||||||
|
*/
|
||||||
|
public static final class SignInType {
|
||||||
|
/** 扫码签到 */
|
||||||
|
public static final String QR_CODE = "QR_CODE";
|
||||||
|
/** 手动签到 */
|
||||||
|
public static final String MANUAL = "MANUAL";
|
||||||
|
/** 人脸识别 */
|
||||||
|
public static final String FACE = "FACE";
|
||||||
|
|
||||||
|
private SignInType() {}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签到状态常量
|
||||||
|
*/
|
||||||
|
public static final class SignInStatus {
|
||||||
|
/** 成功 */
|
||||||
|
public static final String SUCCESS = "SUCCESS";
|
||||||
|
/** 失败 */
|
||||||
|
public static final String FAILED = "FAILED";
|
||||||
|
|
||||||
|
private SignInStatus() {}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签到来源常量
|
||||||
|
*/
|
||||||
|
public static final class Source {
|
||||||
|
/** 小程序扫码 */
|
||||||
|
public static final String MINI_PROGRAM = "MINI_PROGRAM";
|
||||||
|
/** 后台管理端手动签到 */
|
||||||
|
public static final String PC_BACKEND = "PC_BACKEND";
|
||||||
|
|
||||||
|
private Source() {}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== 辅助方法 ==========
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断签到是否成功
|
||||||
|
*/
|
||||||
|
public boolean isSuccess() {
|
||||||
|
return SignInStatus.SUCCESS.equals(this.signInStatus);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断签到是否失败
|
||||||
|
*/
|
||||||
|
public boolean isFailed() {
|
||||||
|
return SignInStatus.FAILED.equals(this.signInStatus);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断是否为扫码签到
|
||||||
|
*/
|
||||||
|
public boolean isQrCodeSign() {
|
||||||
|
return SignInType.QR_CODE.equals(this.signInType);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断是否已删除
|
||||||
|
*/
|
||||||
|
public boolean isDeleted() {
|
||||||
|
return Boolean.TRUE.equals(this.isDelete);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 软删除
|
||||||
|
*/
|
||||||
|
public void softDelete() {
|
||||||
|
this.isDelete = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 恢复删除
|
||||||
|
*/
|
||||||
|
public void restore() {
|
||||||
|
this.isDelete = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
+197
@@ -0,0 +1,197 @@
|
|||||||
|
package cn.novalon.gym.manage.checkIn.handler;
|
||||||
|
|
||||||
|
import cn.novalon.gym.manage.checkIn.service.impl.CheckServiceImpl;
|
||||||
|
import cn.novalon.gym.manage.checkIn.websocket.MyWebSocketHandler;
|
||||||
|
import cn.novalon.gym.manage.checkIn.vo.SignInRecordVO;
|
||||||
|
import cn.novalon.gym.manage.checkIn.vo.SignInStatsVO;
|
||||||
|
import cn.novalon.gym.manage.sys.util.AuthUtil;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.http.MediaType;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.reactive.function.server.ServerRequest;
|
||||||
|
import org.springframework.web.reactive.function.server.ServerResponse;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
import cn.novalon.gym.manage.checkIn.websocket.MyWebSocketHandler;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.format.DateTimeFormatter;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class CheckInHandler {
|
||||||
|
|
||||||
|
private final AuthUtil authUtil;
|
||||||
|
private final CheckServiceImpl checkService;
|
||||||
|
|
||||||
|
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签到
|
||||||
|
*
|
||||||
|
* POST /api/checkIn
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
public Mono<ServerResponse> checkIn(ServerRequest request) {
|
||||||
|
|
||||||
|
Long memberId = authUtil.getMemberIdOrThrow(request);
|
||||||
|
|
||||||
|
return request.bodyToMono(Map.class)
|
||||||
|
.flatMap(body -> {
|
||||||
|
String qrContent = (String) body.get("qrContent");
|
||||||
|
log.info("收到签到请求, memberId: {}, qrContent: {}", memberId, qrContent);
|
||||||
|
boolean messageToClient = MyWebSocketHandler.sendMessageToClient(qrContent, "正在进行签到");
|
||||||
|
log.info("WebSocket 推送结果: {}", messageToClient);
|
||||||
|
return checkService.checkIn(memberId, qrContent)
|
||||||
|
.flatMap(result -> ServerResponse.ok()
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.bodyValue(result));
|
||||||
|
})
|
||||||
|
.onErrorResume(e -> {
|
||||||
|
log.error("签到失败", e);
|
||||||
|
return ServerResponse.status(HttpStatus.BAD_REQUEST)
|
||||||
|
.bodyValue(Map.of("code", 400, "message", e.getMessage()));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取二维码
|
||||||
|
*
|
||||||
|
* GET /api/checkin/qrcode
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
public Mono<ServerResponse> getQRCode(ServerRequest request) {
|
||||||
|
|
||||||
|
Long memberId = authUtil.getMemberIdOrThrow(request);
|
||||||
|
|
||||||
|
log.info("收到用户{}获取二维码请求", memberId);
|
||||||
|
|
||||||
|
return checkService.getQRCode(memberId)
|
||||||
|
.flatMap(qrCodeVo -> ServerResponse.ok()
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.bodyValue(qrCodeVo));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询签到记录列表
|
||||||
|
*
|
||||||
|
* GET /api/checkIn/records
|
||||||
|
*
|
||||||
|
* @param request
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public Mono<ServerResponse> getSignInRecords(ServerRequest request) {
|
||||||
|
Long memberId = authUtil.getMemberIdOrThrow(request);
|
||||||
|
|
||||||
|
String startDateStr = request.queryParam("startDate").orElse(null);
|
||||||
|
String endDateStr = request.queryParam("endDate").orElse(null);
|
||||||
|
|
||||||
|
LocalDate startDate = startDateStr != null ? LocalDate.parse(startDateStr, DATE_FORMATTER) : LocalDate.now().minusDays(30);
|
||||||
|
LocalDate endDate = endDateStr != null ? LocalDate.parse(endDateStr, DATE_FORMATTER) : LocalDate.now();
|
||||||
|
|
||||||
|
log.info("查询签到记录, memberId: {}, startDate: {}, endDate: {}", memberId, startDate, endDate);
|
||||||
|
|
||||||
|
return checkService.getSignInRecords(memberId, startDate, endDate)
|
||||||
|
.collectList()
|
||||||
|
.flatMap(records -> ServerResponse.ok()
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.bodyValue(Map.of("code", 200, "message", "success", "data", records)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询单条签到记录
|
||||||
|
*
|
||||||
|
* GET /api/checkIn/records/{id}
|
||||||
|
*
|
||||||
|
* @param request
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public Mono<ServerResponse> getSignInRecordById(ServerRequest request) {
|
||||||
|
Long id = Long.parseLong(request.pathVariable("id"));
|
||||||
|
|
||||||
|
log.info("查询签到记录详情, id: {}", id);
|
||||||
|
|
||||||
|
return checkService.getSignInRecordById(id)
|
||||||
|
.flatMap(record -> ServerResponse.ok()
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.bodyValue(Map.of("code", 200, "message", "success", "data", record)))
|
||||||
|
.switchIfEmpty(ServerResponse.notFound().build());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取签到统计
|
||||||
|
*
|
||||||
|
* GET /api/checkIn/statistics
|
||||||
|
*
|
||||||
|
* @param request
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public Mono<ServerResponse> getSignInStatistics(ServerRequest request) {
|
||||||
|
Long memberId = authUtil.getMemberIdOrThrow(request);
|
||||||
|
|
||||||
|
String startDateStr = request.queryParam("startDate").orElse(null);
|
||||||
|
String endDateStr = request.queryParam("endDate").orElse(null);
|
||||||
|
|
||||||
|
LocalDate startDate = startDateStr != null ? LocalDate.parse(startDateStr, DATE_FORMATTER) : LocalDate.now().minusDays(30);
|
||||||
|
LocalDate endDate = endDateStr != null ? LocalDate.parse(endDateStr, DATE_FORMATTER) : LocalDate.now();
|
||||||
|
|
||||||
|
log.info("查询签到统计, memberId: {}, startDate: {}, endDate: {}", memberId, startDate, endDate);
|
||||||
|
|
||||||
|
return checkService.getSignInStats(memberId, startDate, endDate)
|
||||||
|
.flatMap(stats -> ServerResponse.ok()
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.bodyValue(Map.of("code", 200, "message", "success", "data", stats)));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 导出签到记录
|
||||||
|
*
|
||||||
|
* GET /api/checkIn/records/export
|
||||||
|
*
|
||||||
|
* @param request
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public Mono<ServerResponse> exportSignInRecords(ServerRequest request) {
|
||||||
|
Long memberId = authUtil.getMemberIdOrThrow(request);
|
||||||
|
|
||||||
|
String startDateStr = request.queryParam("startDate").orElse(null);
|
||||||
|
String endDateStr = request.queryParam("endDate").orElse(null);
|
||||||
|
|
||||||
|
LocalDate startDate = startDateStr != null ? LocalDate.parse(startDateStr, DATE_FORMATTER) : LocalDate.now().minusDays(30);
|
||||||
|
LocalDate endDate = endDateStr != null ? LocalDate.parse(endDateStr, DATE_FORMATTER) : LocalDate.now();
|
||||||
|
|
||||||
|
log.info("导出签到记录, memberId: {}, startDate: {}, endDate: {}", memberId, startDate, endDate);
|
||||||
|
|
||||||
|
String filename = "签到记录_" + startDateStr + "_" + endDateStr + ".csv";
|
||||||
|
|
||||||
|
return checkService.exportSignInRecords(memberId, startDate, endDate)
|
||||||
|
.flatMap(bytes -> ServerResponse.ok()
|
||||||
|
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
|
||||||
|
.contentType(MediaType.parseMediaType("text/csv; charset=UTF-8"))
|
||||||
|
.bodyValue(bytes));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取每日签到统计
|
||||||
|
*
|
||||||
|
* GET /api/checkIn/daily-stats
|
||||||
|
*
|
||||||
|
* @param request
|
||||||
|
* @return
|
||||||
|
*/
|
||||||
|
public Mono<ServerResponse> getDailySignInStats(ServerRequest request) {
|
||||||
|
String dateStr = request.queryParam("date").orElse(null);
|
||||||
|
LocalDate date = dateStr != null ? LocalDate.parse(dateStr, DATE_FORMATTER) : LocalDate.now();
|
||||||
|
|
||||||
|
log.info("查询每日签到统计, date: {}", date);
|
||||||
|
|
||||||
|
return checkService.getDailySignInStats(date)
|
||||||
|
.flatMap(stats -> ServerResponse.ok()
|
||||||
|
.contentType(MediaType.APPLICATION_JSON)
|
||||||
|
.bodyValue(Map.of("code", 200, "message", "success", "data", stats)));
|
||||||
|
}
|
||||||
|
}
|
||||||
+101
@@ -0,0 +1,101 @@
|
|||||||
|
package cn.novalon.gym.manage.checkIn.repository;
|
||||||
|
|
||||||
|
import cn.novalon.gym.manage.checkIn.entity.SignInRecord;
|
||||||
|
import org.springframework.data.r2dbc.repository.Query;
|
||||||
|
import org.springframework.data.r2dbc.repository.R2dbcRepository;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
import reactor.core.publisher.Flux;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签到记录 Repository
|
||||||
|
*
|
||||||
|
* @author 付嘉
|
||||||
|
* @date 2026-06-08
|
||||||
|
*/
|
||||||
|
@Repository
|
||||||
|
public interface SignInRecordRepository extends R2dbcRepository<SignInRecord, Long> {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询会员某天的签到记录
|
||||||
|
*/
|
||||||
|
@Query("SELECT * FROM sign_in_record WHERE member_id = :memberId AND sign_in_time >= :startTime AND sign_in_time < :endTime AND is_delete = false")
|
||||||
|
Mono<SignInRecord> findByMemberIdAndDate(Long memberId, LocalDateTime startTime, LocalDateTime endTime);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询会员的签到记录列表
|
||||||
|
*/
|
||||||
|
@Query("SELECT * FROM sign_in_record WHERE member_id = :memberId AND is_delete = false ORDER BY sign_in_time DESC")
|
||||||
|
Flux<SignInRecord> findByMemberId(Long memberId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计会员某天的签到次数
|
||||||
|
*/
|
||||||
|
@Query("SELECT COUNT(*) FROM sign_in_record WHERE member_id = :memberId AND sign_in_time >= :startTime AND sign_in_time < :endTime AND is_delete = false")
|
||||||
|
Mono<Long> countByMemberIdAndDate(Long memberId, LocalDateTime startTime, LocalDateTime endTime);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 插入签到记录
|
||||||
|
*/
|
||||||
|
@Query("INSERT INTO sign_in_record (member_id, member_card_id, sign_in_time, sign_in_type, sign_in_status, verification_details, fail_reason, source, created_at, updated_at, is_delete) " +
|
||||||
|
"VALUES (:memberId, :memberCardId, :signInTime, :signInType, :signInStatus, :verificationDetails, :failReason, :source, NOW(), NOW(), false)")
|
||||||
|
Mono<Void> insertRecord(Long memberId, Long memberCardId, LocalDateTime signInTime,
|
||||||
|
String signInType, String signInStatus, String verificationDetails,
|
||||||
|
String failReason, String source);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据会员ID和时间范围查询签到记录
|
||||||
|
*/
|
||||||
|
@Query("SELECT * FROM sign_in_record WHERE member_id = :memberId AND sign_in_time >= :startTime AND sign_in_time <= :endTime AND is_delete = false ORDER BY sign_in_time DESC")
|
||||||
|
Flux<SignInRecord> findByMemberIdAndTimeRange(Long memberId, LocalDateTime startTime, LocalDateTime endTime);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据时间范围查询签到记录
|
||||||
|
*/
|
||||||
|
@Query("SELECT * FROM sign_in_record WHERE sign_in_time >= :startTime AND sign_in_time <= :endTime AND is_delete = false ORDER BY sign_in_time DESC")
|
||||||
|
Flux<SignInRecord> findByTimeRange(LocalDateTime startTime, LocalDateTime endTime);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计会员在时间范围内的签到次数
|
||||||
|
*/
|
||||||
|
@Query("SELECT COUNT(*) FROM sign_in_record WHERE member_id = :memberId AND sign_in_time >= :startTime AND sign_in_time <= :endTime AND is_delete = false")
|
||||||
|
Mono<Long> countByMemberIdAndTimeRange(Long memberId, LocalDateTime startTime, LocalDateTime endTime);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计时间范围内的签到次数
|
||||||
|
*/
|
||||||
|
@Query("SELECT COUNT(*) FROM sign_in_record WHERE sign_in_time >= :startTime AND sign_in_time <= :endTime AND is_delete = false")
|
||||||
|
Mono<Long> countByTimeRange(LocalDateTime startTime, LocalDateTime endTime);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计会员在时间范围内的成功签到次数
|
||||||
|
*/
|
||||||
|
@Query("SELECT COUNT(*) FROM sign_in_record WHERE member_id = :memberId AND sign_in_time >= :startTime AND sign_in_time <= :endTime AND sign_in_status = 'SUCCESS' AND is_delete = false")
|
||||||
|
Mono<Long> countSuccessByMemberIdAndTimeRange(Long memberId, LocalDateTime startTime, LocalDateTime endTime);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计时间范围内的成功签到次数
|
||||||
|
*/
|
||||||
|
@Query("SELECT COUNT(*) FROM sign_in_record WHERE sign_in_time >= :startTime AND sign_in_time <= :endTime AND sign_in_status = 'SUCCESS' AND is_delete = false")
|
||||||
|
Mono<Long> countSuccessByTimeRange(LocalDateTime startTime, LocalDateTime endTime);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计时间范围内签到的独立会员数
|
||||||
|
*/
|
||||||
|
@Query("SELECT COUNT(DISTINCT member_id) FROM sign_in_record WHERE sign_in_time >= :startTime AND sign_in_time <= :endTime AND is_delete = false")
|
||||||
|
Mono<Long> countDistinctMembersByTimeRange(LocalDateTime startTime, LocalDateTime endTime);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取会员在时间范围内的首次签到时间
|
||||||
|
*/
|
||||||
|
@Query("SELECT MIN(sign_in_time) FROM sign_in_record WHERE member_id = :memberId AND sign_in_time >= :startTime AND sign_in_time <= :endTime AND is_delete = false")
|
||||||
|
Mono<LocalDateTime> getFirstSignInTime(Long memberId, LocalDateTime startTime, LocalDateTime endTime);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取会员在时间范围内的最后签到时间
|
||||||
|
*/
|
||||||
|
@Query("SELECT MAX(sign_in_time) FROM sign_in_record WHERE member_id = :memberId AND sign_in_time >= :startTime AND sign_in_time <= :endTime AND is_delete = false")
|
||||||
|
Mono<LocalDateTime> getLastSignInTime(Long memberId, LocalDateTime startTime, LocalDateTime endTime);
|
||||||
|
}
|
||||||
+81
@@ -0,0 +1,81 @@
|
|||||||
|
package cn.novalon.gym.manage.checkIn.service;
|
||||||
|
|
||||||
|
import cn.novalon.gym.manage.checkIn.vo.QRCodeVo;
|
||||||
|
import cn.novalon.gym.manage.checkIn.vo.SignInRecordVO;
|
||||||
|
import cn.novalon.gym.manage.checkIn.vo.SignInStatsVO;
|
||||||
|
import reactor.core.publisher.Flux;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签到服务接口
|
||||||
|
*
|
||||||
|
* @author 付嘉
|
||||||
|
* @date 2026-06-08
|
||||||
|
*/
|
||||||
|
public interface ICheckInService {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取签到二维码
|
||||||
|
*
|
||||||
|
* @param memberId 会员ID
|
||||||
|
* @return 二维码VO
|
||||||
|
*/
|
||||||
|
Mono<QRCodeVo> getQRCode(Long memberId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 扫码签到
|
||||||
|
*
|
||||||
|
* @param memberId 会员ID
|
||||||
|
* @param qrContent 二维码内容
|
||||||
|
* @return 签到结果JSON字符串
|
||||||
|
*/
|
||||||
|
Mono<String> checkIn(Long memberId, String qrContent);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询会员签到记录列表
|
||||||
|
*
|
||||||
|
* @param memberId 会员ID
|
||||||
|
* @param startTime 开始时间
|
||||||
|
* @param endTime 结束时间
|
||||||
|
* @return 签到记录列表
|
||||||
|
*/
|
||||||
|
Flux<SignInRecordVO> getSignInRecords(Long memberId, LocalDate startTime, LocalDate endTime);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据ID查询签到记录
|
||||||
|
*
|
||||||
|
* @param id 签到记录ID
|
||||||
|
* @return 签到记录VO
|
||||||
|
*/
|
||||||
|
Mono<SignInRecordVO> getSignInRecordById(Long id);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取会员签到统计
|
||||||
|
*
|
||||||
|
* @param memberId 会员ID
|
||||||
|
* @param startTime 开始时间
|
||||||
|
* @param endTime 结束时间
|
||||||
|
* @return 签到统计VO
|
||||||
|
*/
|
||||||
|
Mono<SignInStatsVO> getSignInStats(Long memberId, LocalDate startTime, LocalDate endTime);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 导出会员签到记录
|
||||||
|
*
|
||||||
|
* @param memberId 会员ID
|
||||||
|
* @param startTime 开始时间
|
||||||
|
* @param endTime 结束时间
|
||||||
|
* @return CSV格式的字节数组
|
||||||
|
*/
|
||||||
|
Mono<byte[]> exportSignInRecords(Long memberId, LocalDate startTime, LocalDate endTime);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取每日签到统计
|
||||||
|
*
|
||||||
|
* @param date 日期
|
||||||
|
* @return 签到统计VO
|
||||||
|
*/
|
||||||
|
Mono<SignInStatsVO> getDailySignInStats(LocalDate date);
|
||||||
|
}
|
||||||
+401
@@ -0,0 +1,401 @@
|
|||||||
|
package cn.novalon.gym.manage.checkIn.service.impl;
|
||||||
|
|
||||||
|
import cn.hutool.core.bean.BeanUtil;
|
||||||
|
import cn.hutool.json.JSONUtil;
|
||||||
|
import cn.hutool.extra.qrcode.QrCodeUtil;
|
||||||
|
import cn.hutool.extra.qrcode.QrConfig;
|
||||||
|
import cn.novalon.gym.manage.checkIn.config.QRCodeConfig;
|
||||||
|
import cn.novalon.gym.manage.checkIn.constant.QRRedisKey;
|
||||||
|
import cn.novalon.gym.manage.checkIn.entity.SignInRecord;
|
||||||
|
import cn.novalon.gym.manage.checkIn.repository.SignInRecordRepository;
|
||||||
|
import cn.novalon.gym.manage.checkIn.service.ICheckInService;
|
||||||
|
import cn.novalon.gym.manage.checkIn.vo.QRCodeVo;
|
||||||
|
import cn.novalon.gym.manage.checkIn.vo.SignInRecordVO;
|
||||||
|
import cn.novalon.gym.manage.checkIn.vo.SignInStatsVO;
|
||||||
|
import cn.novalon.gym.manage.checkIn.websocket.MyWebSocketHandler;
|
||||||
|
import cn.novalon.gym.manage.common.constant.RedisKeyConstants;
|
||||||
|
import cn.novalon.gym.manage.common.util.RedisUtil;
|
||||||
|
import cn.novalon.gym.manage.groupcourse.service.IGroupCourseBookingService;
|
||||||
|
import cn.novalon.gym.manage.member.entity.MemberCard;
|
||||||
|
import cn.novalon.gym.manage.member.entity.MemberCardRecord;
|
||||||
|
import cn.novalon.gym.manage.member.enums.MemberCardType;
|
||||||
|
import cn.novalon.gym.manage.member.repository.MemberCardRecordRepository;
|
||||||
|
import cn.novalon.gym.manage.member.repository.MemberCardRepository;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import reactor.core.publisher.Flux;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.LocalTime;
|
||||||
|
import java.time.format.DateTimeFormatter;
|
||||||
|
import java.time.temporal.ChronoUnit;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
|
@Service
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class CheckServiceImpl implements ICheckInService {
|
||||||
|
|
||||||
|
private final QRCodeConfig qrCodeConfig;
|
||||||
|
private final RedisUtil redisUtil;
|
||||||
|
private final MemberCardRecordRepository memberCardRecordRepository;
|
||||||
|
private final MemberCardRepository memberCardRepository;
|
||||||
|
private final SignInRecordRepository signInRecordRepository;
|
||||||
|
private final IGroupCourseBookingService groupCourseBookingService;
|
||||||
|
|
||||||
|
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Mono<QRCodeVo> getQRCode(Long memberId) {
|
||||||
|
log.info("开始生成会员签到二维码, memberId: {}", memberId);
|
||||||
|
|
||||||
|
String qrContent = QRRedisKey.generateQrcodeContent();
|
||||||
|
Map<String, Object> redisMap = new HashMap<>();
|
||||||
|
redisMap.put("qrContent", qrContent);
|
||||||
|
redisMap.put("isUsed", false);
|
||||||
|
redisMap.put("memberId", memberId);
|
||||||
|
|
||||||
|
return redisUtil.setWithExpire(
|
||||||
|
RedisKeyConstants.QRCODE_USER_DAILY + memberId + LocalDate.now(),
|
||||||
|
redisMap,
|
||||||
|
getSecondsUntilEndOfDay()
|
||||||
|
)
|
||||||
|
.then(Mono.fromSupplier(() -> {
|
||||||
|
String qrCodeBase64 = QrCodeUtil.generateAsBase64(qrContent,
|
||||||
|
BeanUtil.copyProperties(qrCodeConfig, QrConfig.class), "png");
|
||||||
|
return new QRCodeVo(qrCodeBase64, false, qrContent, qrCodeConfig.getWidth(), qrCodeConfig.getHeight(), LocalDate.now());
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Mono<String> checkIn(Long memberId, String qrContent) {
|
||||||
|
String key = RedisKeyConstants.QRCODE_USER_DAILY + memberId + LocalDate.now();
|
||||||
|
|
||||||
|
// 先检查当天是否已经签到(从数据库查询,作为重复签到的额外保障)
|
||||||
|
return checkTodayAlreadySignedIn(memberId)
|
||||||
|
.flatMap(existingRecord -> {
|
||||||
|
String checkInTime = existingRecord.getSignInTime().format(DATE_FORMATTER);
|
||||||
|
log.error("重复签到, memberId: {}", memberId);
|
||||||
|
MyWebSocketHandler.sendFailure(qrContent, "您已经在" + checkInTime + "完成签到,请勿重复签到");
|
||||||
|
return Mono.error(new RuntimeException("您已经在" + checkInTime + "完成签到,请勿重复签到"));
|
||||||
|
})
|
||||||
|
.then(Mono.defer(() -> redisUtil.get(key)))
|
||||||
|
.flatMap(cachedObj -> {
|
||||||
|
if (cachedObj != null) {
|
||||||
|
Map<String, Object> map;
|
||||||
|
if (cachedObj instanceof Map) {
|
||||||
|
map = (Map<String, Object>) cachedObj;
|
||||||
|
} else if (cachedObj instanceof String) {
|
||||||
|
map = JSONUtil.parseObj((String) cachedObj);
|
||||||
|
} else {
|
||||||
|
MyWebSocketHandler.sendFailure(qrContent, "二维码数据格式错误");
|
||||||
|
return Mono.error(new RuntimeException("二维码数据格式错误"));
|
||||||
|
}
|
||||||
|
if (map.get("qrContent").equals(qrContent)) {
|
||||||
|
if ((boolean) map.get("isUsed")) {
|
||||||
|
String checkInTime = String.valueOf(map.get("checkInTime"));
|
||||||
|
log.error("重复签到(缓存), memberId: {}", memberId);
|
||||||
|
MyWebSocketHandler.sendFailure(qrContent, "您已经在" + checkInTime + "完成签到,请勿重复签到");
|
||||||
|
return Mono.error(new RuntimeException("您已经在" + checkInTime + "完成签到,请勿重复签到"));
|
||||||
|
}
|
||||||
|
log.info("二维码匹配成功,memberId: {}", memberId);
|
||||||
|
|
||||||
|
Long memberCardRecordId = map.get("memberCardRecordId") != null
|
||||||
|
? ((Number) map.get("memberCardRecordId")).longValue() : null;
|
||||||
|
|
||||||
|
return processCheckIn(memberId, memberCardRecordId, map, qrContent);
|
||||||
|
} else {
|
||||||
|
MyWebSocketHandler.sendFailure(qrContent, "二维码无效");
|
||||||
|
return Mono.error(new RuntimeException("二维码无效"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
MyWebSocketHandler.sendFailure(qrContent, "二维码已过期或不存在");
|
||||||
|
return Mono.error(new RuntimeException("二维码已过期或不存在"));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检查会员当天是否已经签到
|
||||||
|
* @param memberId 会员ID
|
||||||
|
* @return 如果已签到返回签到记录,否则返回空
|
||||||
|
*/
|
||||||
|
private Mono<SignInRecord> checkTodayAlreadySignedIn(Long memberId) {
|
||||||
|
LocalDateTime startOfDay = LocalDate.now().atStartOfDay();
|
||||||
|
LocalDateTime endOfDay = LocalDate.now().atTime(LocalTime.MAX);
|
||||||
|
|
||||||
|
return signInRecordRepository.findByMemberIdAndDate(memberId, startOfDay, endOfDay);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 处理签到逻辑
|
||||||
|
*/
|
||||||
|
private Mono<String> processCheckIn(Long memberId, Long memberCardRecordId, Map<String, Object> redisMap, String qrContent) {
|
||||||
|
LocalDateTime now = LocalDateTime.now();
|
||||||
|
|
||||||
|
// 发送实时进度通知
|
||||||
|
MyWebSocketHandler.sendProgress(qrContent, "VALIDATE_BOOKING", "正在检查预约信息...");
|
||||||
|
|
||||||
|
// 检查是否有需要签到的团课预约
|
||||||
|
return validateBooking(memberId, now)
|
||||||
|
.then(Mono.defer(() -> {
|
||||||
|
redisMap.put("isUsed", true);
|
||||||
|
redisMap.put("checkInTime", now.format(DATE_FORMATTER));
|
||||||
|
|
||||||
|
return saveSignInRecord(memberId, null, null)
|
||||||
|
.then(redisUtil.set(RedisKeyConstants.QRCODE_USER_DAILY + memberId + LocalDate.now(), redisMap))
|
||||||
|
.then(Mono.defer(() -> {
|
||||||
|
String successMsg = buildSuccessResponse(now);
|
||||||
|
MyWebSocketHandler.sendSuccess(qrContent, memberId, now.format(DATE_FORMATTER));
|
||||||
|
log.info("签到成功, memberId: {}", memberId);
|
||||||
|
return Mono.just(successMsg);
|
||||||
|
}));
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 验证预约信息
|
||||||
|
*/
|
||||||
|
private Mono<Void> validateBooking(Long memberId, LocalDateTime now) {
|
||||||
|
return groupCourseBookingService.getBookingsByMemberId(memberId)
|
||||||
|
.filter(booking -> {
|
||||||
|
String status = booking.getStatus();
|
||||||
|
LocalDateTime startTime = booking.getCourseStartTime();
|
||||||
|
return "0".equals(status) &&
|
||||||
|
startTime != null &&
|
||||||
|
startTime.toLocalDate().equals(now.toLocalDate()) &&
|
||||||
|
!startTime.isBefore(now.minusMinutes(30));
|
||||||
|
})
|
||||||
|
.collectList()
|
||||||
|
.flatMap(bookings -> {
|
||||||
|
if (bookings.isEmpty()) {
|
||||||
|
return Mono.empty();
|
||||||
|
}
|
||||||
|
boolean hasValidBooking = bookings.stream()
|
||||||
|
.anyMatch(b -> {
|
||||||
|
LocalDateTime startTime = b.getCourseStartTime();
|
||||||
|
return startTime != null &&
|
||||||
|
!startTime.isBefore(now.minusMinutes(30)) &&
|
||||||
|
!startTime.isAfter(now.plusMinutes(30));
|
||||||
|
});
|
||||||
|
if (hasValidBooking) {
|
||||||
|
log.info("会员{}有有效的团课预约", memberId);
|
||||||
|
} else {
|
||||||
|
log.warn("会员{}有预约但不在签到时间范围内", memberId);
|
||||||
|
}
|
||||||
|
return Mono.empty();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 扣减会员卡使用次数/金额
|
||||||
|
*/
|
||||||
|
private Mono<MemberCardRecord> deductCardUsage(MemberCardRecord record, MemberCard card) {
|
||||||
|
MemberCardType cardType = MemberCardType.valueOf(card.getMemberCardType());
|
||||||
|
LocalDateTime now = LocalDateTime.now();
|
||||||
|
|
||||||
|
switch (cardType) {
|
||||||
|
case TIME_CARD:
|
||||||
|
if (record.getExpireTime() != null && record.getExpireTime().isBefore(now)) {
|
||||||
|
return Mono.error(new RuntimeException("时长卡已过期"));
|
||||||
|
}
|
||||||
|
return Mono.just(record);
|
||||||
|
case COUNT_CARD:
|
||||||
|
int currentTimes = record.getRemainingTimes() != null ? record.getRemainingTimes() : 0;
|
||||||
|
if (currentTimes < 1) {
|
||||||
|
return Mono.error(new RuntimeException("次卡剩余次数不足"));
|
||||||
|
}
|
||||||
|
record.setRemainingTimes(currentTimes - 1);
|
||||||
|
if (record.getRemainingTimes() == 0) {
|
||||||
|
record.setStatus(cn.novalon.gym.manage.member.enums.MemberCardRecordStatus.USED_UP);
|
||||||
|
}
|
||||||
|
return memberCardRecordRepository.save(record);
|
||||||
|
case STORED_VALUE_CARD:
|
||||||
|
double currentAmount = record.getRemainingAmount() != null ? record.getRemainingAmount() : 0.0;
|
||||||
|
if (currentAmount < 0.01) {
|
||||||
|
return Mono.error(new RuntimeException("储值卡余额不足"));
|
||||||
|
}
|
||||||
|
record.setRemainingAmount(Math.max(0, currentAmount - 1));
|
||||||
|
if (record.getRemainingAmount() <= 0) {
|
||||||
|
record.setStatus(cn.novalon.gym.manage.member.enums.MemberCardRecordStatus.USED_UP);
|
||||||
|
}
|
||||||
|
return memberCardRecordRepository.save(record);
|
||||||
|
default:
|
||||||
|
return Mono.error(new RuntimeException("不支持的会员卡类型"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 保存签到记录
|
||||||
|
*/
|
||||||
|
private Mono<Void> saveSignInRecord(Long memberId, Long memberCardRecordId, Long memberCardId) {
|
||||||
|
SignInRecord record = SignInRecord.builder()
|
||||||
|
.memberId(memberId)
|
||||||
|
.memberCardId(memberCardId)
|
||||||
|
.signInTime(LocalDateTime.now())
|
||||||
|
.signInType(SignInRecord.SignInType.QR_CODE)
|
||||||
|
.signInStatus(SignInRecord.SignInStatus.SUCCESS)
|
||||||
|
.source(SignInRecord.Source.MINI_PROGRAM)
|
||||||
|
.isDelete(false)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
return signInRecordRepository.save(record).then();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构建成功响应
|
||||||
|
*/
|
||||||
|
private String buildSuccessResponse(LocalDateTime dateTime) {
|
||||||
|
Map<String, Object> res = new HashMap<>();
|
||||||
|
res.put("message", "签到成功");
|
||||||
|
res.put("dateTime", dateTime.format(DATE_FORMATTER));
|
||||||
|
return JSONUtil.toJsonStr(res);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查找会员的有效会员卡(优先选择有效期最早到期的)
|
||||||
|
*/
|
||||||
|
private Mono<MemberCardRecord> findValidMemberCard(Long memberId) {
|
||||||
|
return memberCardRecordRepository.findActiveCardsByMemberId(memberId)
|
||||||
|
.filter(record -> {
|
||||||
|
LocalDateTime expireTime = record.getExpireTime();
|
||||||
|
return expireTime == null || expireTime.isAfter(LocalDateTime.now());
|
||||||
|
})
|
||||||
|
.sort((r1, r2) -> {
|
||||||
|
LocalDateTime e1 = r1.getExpireTime();
|
||||||
|
LocalDateTime e2 = r2.getExpireTime();
|
||||||
|
if (e1 == null && e2 == null) return 0;
|
||||||
|
if (e1 == null) return 1;
|
||||||
|
if (e2 == null) return -1;
|
||||||
|
return e1.compareTo(e2);
|
||||||
|
})
|
||||||
|
.next();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== 签到记录管理功能 ====================
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Flux<SignInRecordVO> getSignInRecords(Long memberId, LocalDate startTime, LocalDate endTime) {
|
||||||
|
LocalDateTime start = startTime.atStartOfDay();
|
||||||
|
LocalDateTime end = endTime.atTime(LocalTime.MAX);
|
||||||
|
|
||||||
|
return signInRecordRepository.findByMemberIdAndTimeRange(memberId, start, end)
|
||||||
|
.map(this::convertToVO);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Mono<SignInRecordVO> getSignInRecordById(Long id) {
|
||||||
|
return signInRecordRepository.findById(id)
|
||||||
|
.map(this::convertToVO);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Mono<SignInStatsVO> getSignInStats(Long memberId, LocalDate startTime, LocalDate endTime) {
|
||||||
|
LocalDateTime start = startTime.atStartOfDay();
|
||||||
|
LocalDateTime end = endTime.atTime(LocalTime.MAX);
|
||||||
|
|
||||||
|
return Mono.zip(
|
||||||
|
(Object[] results) -> {
|
||||||
|
Long total = (Long) results[0];
|
||||||
|
Long success = (Long) results[1];
|
||||||
|
LocalDateTime first = (LocalDateTime) results[2];
|
||||||
|
LocalDateTime last = (LocalDateTime) results[3];
|
||||||
|
SignInStatsVO stats = new SignInStatsVO();
|
||||||
|
stats.setTotalCount(total);
|
||||||
|
stats.setSuccessCount(success);
|
||||||
|
stats.setStartDate(startTime);
|
||||||
|
stats.setEndDate(endTime);
|
||||||
|
stats.setFirstSignInTime(first);
|
||||||
|
stats.setLastSignInTime(last);
|
||||||
|
stats.setSuccessRate(total > 0 ? (double) success / total * 100.0 : 0.0);
|
||||||
|
return stats;
|
||||||
|
},
|
||||||
|
signInRecordRepository.countByMemberIdAndTimeRange(memberId, start, end),
|
||||||
|
signInRecordRepository.countSuccessByMemberIdAndTimeRange(memberId, start, end),
|
||||||
|
signInRecordRepository.getFirstSignInTime(memberId, start, end),
|
||||||
|
signInRecordRepository.getLastSignInTime(memberId, start, end)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Mono<byte[]> exportSignInRecords(Long memberId, LocalDate startTime, LocalDate endTime) {
|
||||||
|
LocalDateTime start = startTime.atStartOfDay();
|
||||||
|
LocalDateTime end = endTime.atTime(LocalTime.MAX);
|
||||||
|
|
||||||
|
return signInRecordRepository.findByMemberIdAndTimeRange(memberId, start, end)
|
||||||
|
.map(record -> {
|
||||||
|
String status = "SUCCESS".equals(record.getSignInStatus()) ? "成功" : "失败";
|
||||||
|
String type = "QR_CODE".equals(record.getSignInType()) ? "扫码签到" :
|
||||||
|
"MANUAL".equals(record.getSignInType()) ? "手动签到" : "人脸识别";
|
||||||
|
return String.join(",",
|
||||||
|
record.getId().toString(),
|
||||||
|
record.getMemberId().toString(),
|
||||||
|
record.getMemberCardId() != null ? record.getMemberCardId().toString() : "",
|
||||||
|
record.getSignInTime() != null ? record.getSignInTime().format(DATE_FORMATTER) : "",
|
||||||
|
type,
|
||||||
|
status,
|
||||||
|
record.getFailReason() != null ? record.getFailReason() : ""
|
||||||
|
);
|
||||||
|
})
|
||||||
|
.collectList()
|
||||||
|
.map(rows -> {
|
||||||
|
List<String> csvLines = new java.util.ArrayList<>();
|
||||||
|
csvLines.add("签到记录ID,会员ID,会员卡ID,签到时间,签到方式,签到状态,失败原因");
|
||||||
|
csvLines.addAll(rows);
|
||||||
|
return String.join("\n", csvLines).getBytes(java.nio.charset.StandardCharsets.UTF_8);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Mono<SignInStatsVO> getDailySignInStats(LocalDate date) {
|
||||||
|
LocalDateTime start = date.atStartOfDay();
|
||||||
|
LocalDateTime end = date.atTime(LocalTime.MAX);
|
||||||
|
|
||||||
|
return Mono.zip(
|
||||||
|
(Object[] results) -> {
|
||||||
|
Long total = (Long) results[0];
|
||||||
|
Long success = (Long) results[1];
|
||||||
|
Long members = (Long) results[2];
|
||||||
|
SignInStatsVO stats = new SignInStatsVO();
|
||||||
|
stats.setTotalCount(total);
|
||||||
|
stats.setSuccessCount(success);
|
||||||
|
stats.setStartDate(date);
|
||||||
|
stats.setEndDate(date);
|
||||||
|
stats.setUniqueMemberCount(members);
|
||||||
|
stats.setSuccessRate(total > 0 ? (double) success / total * 100.0 : 0.0);
|
||||||
|
return stats;
|
||||||
|
},
|
||||||
|
signInRecordRepository.countByTimeRange(start, end),
|
||||||
|
signInRecordRepository.countSuccessByTimeRange(start, end),
|
||||||
|
signInRecordRepository.countDistinctMembersByTimeRange(start, end)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 转换实体到VO
|
||||||
|
*/
|
||||||
|
private SignInRecordVO convertToVO(SignInRecord record) {
|
||||||
|
SignInRecordVO vo = new SignInRecordVO();
|
||||||
|
vo.setId(record.getId());
|
||||||
|
vo.setMemberId(record.getMemberId());
|
||||||
|
vo.setMemberCardId(record.getMemberCardId());
|
||||||
|
vo.setSignInTime(record.getSignInTime());
|
||||||
|
vo.setSignInType(record.getSignInType());
|
||||||
|
vo.setSignInStatus(record.getSignInStatus());
|
||||||
|
vo.setFailReason(record.getFailReason());
|
||||||
|
vo.setSource(record.getSource());
|
||||||
|
vo.setCreatedAt(record.getCreatedAt());
|
||||||
|
return vo;
|
||||||
|
}
|
||||||
|
|
||||||
|
private long getSecondsUntilEndOfDay() {
|
||||||
|
LocalDateTime now = LocalDateTime.now();
|
||||||
|
LocalDateTime endOfDay = now.toLocalDate().atTime(23, 59, 59);
|
||||||
|
if (now.isAfter(endOfDay)) return 1;
|
||||||
|
return ChronoUnit.SECONDS.between(now, endOfDay);
|
||||||
|
}
|
||||||
|
}
|
||||||
+23
@@ -0,0 +1,23 @@
|
|||||||
|
package cn.novalon.gym.manage.checkIn.vo;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class QRCodeVo {
|
||||||
|
|
||||||
|
private String qrCodeBase64;
|
||||||
|
|
||||||
|
private boolean isUsed;
|
||||||
|
|
||||||
|
private String qrContent;
|
||||||
|
|
||||||
|
private Integer width;
|
||||||
|
|
||||||
|
private Integer height;
|
||||||
|
|
||||||
|
private LocalDate createTime;
|
||||||
|
}
|
||||||
+66
@@ -0,0 +1,66 @@
|
|||||||
|
package cn.novalon.gym.manage.checkIn.vo;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签到记录VO
|
||||||
|
*
|
||||||
|
* @author 付嘉
|
||||||
|
* @date 2026-06-08
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class SignInRecordVO {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签到记录ID
|
||||||
|
*/
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 会员ID
|
||||||
|
*/
|
||||||
|
private Long memberId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 会员卡ID
|
||||||
|
*/
|
||||||
|
private Long memberCardId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签到时间
|
||||||
|
*/
|
||||||
|
private LocalDateTime signInTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签到类型:QR_CODE-扫码签到,MANUAL-手动签到,FACE-人脸识别
|
||||||
|
*/
|
||||||
|
private String signInType;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签到状态:SUCCESS-成功,FAILED-失败
|
||||||
|
*/
|
||||||
|
private String signInStatus;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 失败原因
|
||||||
|
*/
|
||||||
|
private String failReason;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签到来源:MINI_PROGRAM-小程序扫码,PC_BACKEND-后台管理端
|
||||||
|
*/
|
||||||
|
private String source;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建时间
|
||||||
|
*/
|
||||||
|
private LocalDateTime createdAt;
|
||||||
|
}
|
||||||
+62
@@ -0,0 +1,62 @@
|
|||||||
|
package cn.novalon.gym.manage.checkIn.vo;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签到统计VO
|
||||||
|
*
|
||||||
|
* @author 付嘉
|
||||||
|
* @date 2026-06-08
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class SignInStatsVO {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计开始日期
|
||||||
|
*/
|
||||||
|
private LocalDate startDate;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计结束日期
|
||||||
|
*/
|
||||||
|
private LocalDate endDate;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 总签到次数
|
||||||
|
*/
|
||||||
|
private Long totalCount;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 成功签到次数
|
||||||
|
*/
|
||||||
|
private Long successCount;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 成功率(百分比)
|
||||||
|
*/
|
||||||
|
private Double successRate;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 独立会员数
|
||||||
|
*/
|
||||||
|
private Long uniqueMemberCount;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 首次签到时间
|
||||||
|
*/
|
||||||
|
private LocalDateTime firstSignInTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 最后签到时间
|
||||||
|
*/
|
||||||
|
private LocalDateTime lastSignInTime;
|
||||||
|
}
|
||||||
+202
@@ -0,0 +1,202 @@
|
|||||||
|
package cn.novalon.gym.manage.checkIn.websocket;
|
||||||
|
|
||||||
|
import cn.hutool.json.JSONUtil;
|
||||||
|
import cn.novalon.gym.manage.checkIn.dto.QRCodeDto;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.reactive.socket.WebSocketHandler;
|
||||||
|
import org.springframework.web.reactive.socket.WebSocketSession;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
import reactor.core.publisher.Sinks;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.concurrent.ConcurrentHashMap;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* WebSocket 处理类,用于实时签到反馈
|
||||||
|
*
|
||||||
|
* 技术要点:
|
||||||
|
* - 使用 Sinks 实现响应式消息推送
|
||||||
|
* - 使用 ConcurrentHashMap 管理 qrContent 与 sink 的映射
|
||||||
|
* - 支持实时推送签到进度和结果
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
public class MyWebSocketHandler implements WebSocketHandler {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* qrContent -> Sink 映射,用于根据二维码内容找到对应的客户端连接
|
||||||
|
*/
|
||||||
|
private static final Map<String, Sinks.Many<String>> qrContentToSink = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 连接创建时间映射,用于超时清理
|
||||||
|
*/
|
||||||
|
private static final Map<String, LocalDateTime> qrContentToCreateTime = new ConcurrentHashMap<>();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 超时时间(秒),超过此时间未使用的连接将被清理
|
||||||
|
*/
|
||||||
|
private static final long TIMEOUT_SECONDS = 300;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Mono<Void> handle(WebSocketSession session) {
|
||||||
|
String sessionId = session.getId();
|
||||||
|
log.info("WebSocket 连接建立,sessionId: {}", sessionId);
|
||||||
|
|
||||||
|
// 创建 sink,用于向客户端发送消息
|
||||||
|
Sinks.Many<String> sink = Sinks.many().unicast().onBackpressureBuffer();
|
||||||
|
|
||||||
|
// 订阅接收客户端消息(异步处理)
|
||||||
|
session.receive()
|
||||||
|
.doOnNext(message -> {
|
||||||
|
String payload = message.getPayloadAsText();
|
||||||
|
log.debug("收到消息:sessionId={}, payload={}", sessionId, payload);
|
||||||
|
|
||||||
|
try {
|
||||||
|
QRCodeDto qrCodeDto = JSONUtil.toBean(payload, QRCodeDto.class);
|
||||||
|
String qrContent = qrCodeDto.getQrContent();
|
||||||
|
|
||||||
|
if (qrContent != null && !qrContent.isEmpty()) {
|
||||||
|
// 绑定 qrContent 和 sink
|
||||||
|
qrContentToSink.put(qrContent, sink);
|
||||||
|
qrContentToCreateTime.put(qrContent, LocalDateTime.now());
|
||||||
|
log.info("绑定成功: qrContent={}, sessionId={}", qrContent, sessionId);
|
||||||
|
|
||||||
|
// 发送连接成功消息
|
||||||
|
sink.tryEmitNext(buildMessage("CONNECTED", "签到监听已建立,请扫描二维码"));
|
||||||
|
} else {
|
||||||
|
sink.tryEmitNext(buildMessage("ERROR", "二维码内容为空"));
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("解析消息失败,sessionId={}", sessionId, e);
|
||||||
|
sink.tryEmitNext(buildMessage("ERROR", "消息格式错误: " + e.getMessage()));
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.doOnError(e -> {
|
||||||
|
log.error("接收消息出错,sessionId={}", sessionId, e);
|
||||||
|
})
|
||||||
|
.subscribe(); // 必须订阅,否则不会执行
|
||||||
|
|
||||||
|
// 发送流给客户端
|
||||||
|
return session.send(sink.asFlux().map(session::textMessage))
|
||||||
|
.doFinally(signal -> {
|
||||||
|
// 连接关闭时清理映射
|
||||||
|
qrContentToSink.entrySet().removeIf(entry -> entry.getValue() == sink);
|
||||||
|
qrContentToCreateTime.entrySet().removeIf(entry -> {
|
||||||
|
Sinks.Many<String> s = qrContentToSink.get(entry.getKey());
|
||||||
|
return s == null || s == sink;
|
||||||
|
});
|
||||||
|
log.info("WebSocket 连接关闭,sessionId={}", sessionId);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 向客户端发送消息
|
||||||
|
*
|
||||||
|
* @param qrContent 二维码内容
|
||||||
|
* @param message 消息内容
|
||||||
|
* @return 是否发送成功
|
||||||
|
*/
|
||||||
|
public static boolean sendMessageToClient(String qrContent, String message) {
|
||||||
|
// 先清理超时连接
|
||||||
|
cleanupTimeoutConnections();
|
||||||
|
|
||||||
|
Sinks.Many<String> sink = qrContentToSink.get(qrContent);
|
||||||
|
if (sink == null) {
|
||||||
|
log.warn("未找到绑定的连接,qrContent: {}", qrContent);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
Sinks.EmitResult result = sink.tryEmitNext(message);
|
||||||
|
if (result.isSuccess()) {
|
||||||
|
log.info("主动推送成功,qrContent: {}, message: {}", qrContent, message);
|
||||||
|
return true;
|
||||||
|
} else {
|
||||||
|
log.warn("推送失败,qrContent: {}, result: {}", qrContent, result);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 发送签到进度消息
|
||||||
|
*
|
||||||
|
* @param qrContent 二维码内容
|
||||||
|
* @param step 进度步骤
|
||||||
|
* @param message 进度消息
|
||||||
|
*/
|
||||||
|
public static void sendProgress(String qrContent, String step, String message) {
|
||||||
|
String progressMessage = buildMessage("PROGRESS", message);
|
||||||
|
sendMessageToClient(qrContent, progressMessage);
|
||||||
|
log.debug("发送进度消息: qrContent={}, step={}, message={}", qrContent, step, message);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 发送签到成功消息
|
||||||
|
*
|
||||||
|
* @param qrContent 二维码内容
|
||||||
|
* @param memberId 会员ID
|
||||||
|
* @param signInTime 签到时间
|
||||||
|
*/
|
||||||
|
public static void sendSuccess(String qrContent, Long memberId, String signInTime) {
|
||||||
|
String successMessage = buildMessage("SUCCESS", "签到成功!欢迎光临\n会员ID: " + memberId + "\n签到时间: " + signInTime);
|
||||||
|
sendMessageToClient(qrContent, successMessage);
|
||||||
|
log.info("发送成功消息: qrContent={}, memberId={}", qrContent, memberId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 发送签到失败消息
|
||||||
|
*
|
||||||
|
* @param qrContent 二维码内容
|
||||||
|
* @param reason 失败原因
|
||||||
|
*/
|
||||||
|
public static void sendFailure(String qrContent, String reason) {
|
||||||
|
String failureMessage = buildMessage("FAILURE", "签到失败:" + reason);
|
||||||
|
sendMessageToClient(qrContent, failureMessage);
|
||||||
|
log.warn("发送失败消息: qrContent={}, reason={}", qrContent, reason);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构建标准消息格式
|
||||||
|
*
|
||||||
|
* @param type 消息类型
|
||||||
|
* @param content 消息内容
|
||||||
|
* @return 格式化后的消息字符串
|
||||||
|
*/
|
||||||
|
private static String buildMessage(String type, String content) {
|
||||||
|
return JSONUtil.toJsonStr(Map.of(
|
||||||
|
"type", type,
|
||||||
|
"content", content,
|
||||||
|
"timestamp", System.currentTimeMillis()
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清理超时连接
|
||||||
|
*/
|
||||||
|
private static void cleanupTimeoutConnections() {
|
||||||
|
LocalDateTime now = LocalDateTime.now();
|
||||||
|
qrContentToCreateTime.entrySet().removeIf(entry -> {
|
||||||
|
LocalDateTime createTime = entry.getValue();
|
||||||
|
long secondsDiff = java.time.Duration.between(createTime, now).getSeconds();
|
||||||
|
if (secondsDiff > TIMEOUT_SECONDS) {
|
||||||
|
String qrContent = entry.getKey();
|
||||||
|
qrContentToSink.remove(qrContent);
|
||||||
|
log.debug("清理超时连接: qrContent={}, 超时时间={}秒", qrContent, secondsDiff);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取当前连接数
|
||||||
|
*
|
||||||
|
* @return 连接数
|
||||||
|
*/
|
||||||
|
public static int getConnectionCount() {
|
||||||
|
cleanupTimeoutConnections();
|
||||||
|
return qrContentToSink.size();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
# 二维码配置
|
||||||
|
qr:
|
||||||
|
config:
|
||||||
|
width: 300 # 二维码宽度(像素)
|
||||||
|
height: 300 # 二维码高度(像素)
|
||||||
|
margin: 1 # 白边宽度(像素)
|
||||||
|
format: png # 图片格式:png / jpg
|
||||||
|
error-correction: L #容错率:L, M, Q, H,如果启用Logo(logo-enabled: true),必须设置为 H
|
||||||
|
logo-enabled: false # 是否启用Logo(启用时error-correction必须为H)
|
||||||
|
# logo-path: static/logo.png # Logo图片路径(支持相对路径或绝对路径)
|
||||||
+281
@@ -0,0 +1,281 @@
|
|||||||
|
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.service.IGroupCourseBookingService;
|
||||||
|
import cn.novalon.gym.manage.checkIn.service.impl.CheckServiceImpl;
|
||||||
|
import cn.novalon.gym.manage.checkIn.vo.QRCodeVo;
|
||||||
|
import cn.novalon.gym.manage.checkIn.vo.SignInRecordVO;
|
||||||
|
import cn.novalon.gym.manage.checkIn.vo.SignInStatsVO;
|
||||||
|
import cn.novalon.gym.manage.common.constant.RedisKeyConstants;
|
||||||
|
import cn.novalon.gym.manage.common.util.RedisUtil;
|
||||||
|
import cn.novalon.gym.manage.member.entity.MemberCard;
|
||||||
|
import cn.novalon.gym.manage.member.entity.MemberCardRecord;
|
||||||
|
import cn.novalon.gym.manage.member.repository.MemberCardRecordRepository;
|
||||||
|
import cn.novalon.gym.manage.member.repository.MemberCardRepository;
|
||||||
|
import org.junit.jupiter.api.BeforeEach;
|
||||||
|
import org.junit.jupiter.api.DisplayName;
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import org.mockito.Mock;
|
||||||
|
import org.mockito.MockitoAnnotations;
|
||||||
|
import reactor.core.publisher.Flux;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
import reactor.test.StepVerifier;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.LocalTime;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
import static org.mockito.ArgumentMatchers.any;
|
||||||
|
import static org.mockito.ArgumentMatchers.eq;
|
||||||
|
import static org.mockito.Mockito.when;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签到模块接口测试类
|
||||||
|
* 测试模块三(gym-checkIn)的所有接口
|
||||||
|
*/
|
||||||
|
class CheckInModuleTest {
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private QRCodeConfig qrCodeConfig;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private RedisUtil redisUtil;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private MemberCardRecordRepository memberCardRecordRepository;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private MemberCardRepository memberCardRepository;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private SignInRecordRepository signInRecordRepository;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private IGroupCourseBookingService groupCourseBookingService;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private MemberCard mockMemberCard;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private SignInRecord mockSignInRecord;
|
||||||
|
|
||||||
|
@Mock
|
||||||
|
private MemberCardRecord mockMemberCardRecord;
|
||||||
|
|
||||||
|
private CheckServiceImpl checkService;
|
||||||
|
|
||||||
|
@BeforeEach
|
||||||
|
void setUp() {
|
||||||
|
MockitoAnnotations.openMocks(this);
|
||||||
|
checkService = new CheckServiceImpl(qrCodeConfig, redisUtil, memberCardRecordRepository,
|
||||||
|
memberCardRepository, signInRecordRepository, groupCourseBookingService);
|
||||||
|
|
||||||
|
when(mockMemberCard.getId()).thenReturn(1L);
|
||||||
|
when(mockMemberCard.getMemberCardType()).thenReturn("TIME_CARD");
|
||||||
|
|
||||||
|
when(mockSignInRecord.getId()).thenReturn(1L);
|
||||||
|
when(mockSignInRecord.getMemberId()).thenReturn(1L);
|
||||||
|
when(mockSignInRecord.getMemberCardId()).thenReturn(1L);
|
||||||
|
when(mockSignInRecord.getSignInTime()).thenReturn(LocalDateTime.now());
|
||||||
|
when(mockSignInRecord.getSignInType()).thenReturn("QR_CODE");
|
||||||
|
when(mockSignInRecord.getSignInStatus()).thenReturn("SUCCESS");
|
||||||
|
when(mockSignInRecord.getSource()).thenReturn("MINI_PROGRAM");
|
||||||
|
|
||||||
|
when(mockMemberCardRecord.getMemberCardRecordId()).thenReturn(1L);
|
||||||
|
when(mockMemberCardRecord.getMemberCardId()).thenReturn(1L);
|
||||||
|
when(mockMemberCardRecord.getRemainingTimes()).thenReturn(10);
|
||||||
|
when(mockMemberCardRecord.getRemainingAmount()).thenReturn(100.0);
|
||||||
|
when(mockMemberCardRecord.getExpireTime()).thenReturn(LocalDateTime.now().plusDays(30));
|
||||||
|
when(mockMemberCardRecord.getStatus()).thenReturn(cn.novalon.gym.manage.member.enums.MemberCardRecordStatus.ACTIVE);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("测试1: 获取二维码 - getQRCode")
|
||||||
|
void testGetQRCode() {
|
||||||
|
when(memberCardRecordRepository.findActiveCardsByMemberId(1L))
|
||||||
|
.thenReturn(Flux.just(mockMemberCardRecord));
|
||||||
|
when(redisUtil.setWithExpire(any(String.class), any(Map.class), any(Long.class)))
|
||||||
|
.thenReturn(Mono.just(true));
|
||||||
|
|
||||||
|
Mono<QRCodeVo> result = checkService.getQRCode(1L);
|
||||||
|
|
||||||
|
StepVerifier.create(result)
|
||||||
|
.expectNextMatches(qrCodeVo -> {
|
||||||
|
org.junit.jupiter.api.Assertions.assertNotNull(qrCodeVo);
|
||||||
|
org.junit.jupiter.api.Assertions.assertNotNull(qrCodeVo.getQrContent());
|
||||||
|
return true;
|
||||||
|
})
|
||||||
|
.verifyComplete();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("测试2: 签到 - checkIn")
|
||||||
|
void testCheckIn() {
|
||||||
|
Long memberId = 1L;
|
||||||
|
Map<String, Object> qrData = new HashMap<>();
|
||||||
|
qrData.put("qrContent", "test-qr-content");
|
||||||
|
qrData.put("memberId", memberId);
|
||||||
|
qrData.put("memberCardRecordId", 1L);
|
||||||
|
qrData.put("isUsed", false);
|
||||||
|
qrData.put("expireTime", System.currentTimeMillis() + 3600000);
|
||||||
|
|
||||||
|
String key = RedisKeyConstants.QRCODE_USER_DAILY + memberId + LocalDate.now();
|
||||||
|
|
||||||
|
when(redisUtil.get(eq(key))).thenReturn(Mono.just(qrData));
|
||||||
|
when(memberCardRecordRepository.findById(1L)).thenReturn(Mono.just(mockMemberCardRecord));
|
||||||
|
when(memberCardRepository.findByMemberCardIdAndDeletedAtIsNull(1L)).thenReturn(Mono.just(mockMemberCard));
|
||||||
|
when(signInRecordRepository.save(any(SignInRecord.class))).thenReturn(Mono.just(mockSignInRecord));
|
||||||
|
when(redisUtil.set(any(String.class), any(Map.class))).thenReturn(Mono.just(true));
|
||||||
|
when(groupCourseBookingService.getBookingsByMemberId(memberId)).thenReturn(Flux.empty());
|
||||||
|
when(signInRecordRepository.findByMemberIdAndDate(eq(memberId), any(LocalDateTime.class), any(LocalDateTime.class)))
|
||||||
|
.thenReturn(Mono.empty());
|
||||||
|
|
||||||
|
Mono<String> result = checkService.checkIn(memberId, "test-qr-content");
|
||||||
|
|
||||||
|
StepVerifier.create(result)
|
||||||
|
.expectNextMatches(response -> response.contains("签到成功"))
|
||||||
|
.verifyComplete();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("测试3: 查询签到记录列表 - getSignInRecords")
|
||||||
|
void testGetSignInRecords() {
|
||||||
|
when(signInRecordRepository.findByMemberIdAndTimeRange(
|
||||||
|
eq(1L), any(LocalDateTime.class), any(LocalDateTime.class)))
|
||||||
|
.thenReturn(Flux.just(mockSignInRecord));
|
||||||
|
|
||||||
|
Flux<SignInRecordVO> result = checkService.getSignInRecords(1L,
|
||||||
|
LocalDate.now().minusDays(30), LocalDate.now());
|
||||||
|
|
||||||
|
StepVerifier.create(result)
|
||||||
|
.expectNextCount(1)
|
||||||
|
.verifyComplete();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("测试4: 查询单条签到记录 - getSignInRecordById")
|
||||||
|
void testGetSignInRecordById() {
|
||||||
|
when(signInRecordRepository.findById(1L))
|
||||||
|
.thenReturn(Mono.just(mockSignInRecord));
|
||||||
|
|
||||||
|
Mono<SignInRecordVO> result = checkService.getSignInRecordById(1L);
|
||||||
|
|
||||||
|
StepVerifier.create(result)
|
||||||
|
.expectNextMatches(vo -> vo.getId() == 1L)
|
||||||
|
.verifyComplete();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("测试5: 查询签到记录 - 记录不存在")
|
||||||
|
void testGetSignInRecordById_NotFound() {
|
||||||
|
when(signInRecordRepository.findById(999L))
|
||||||
|
.thenReturn(Mono.empty());
|
||||||
|
|
||||||
|
Mono<SignInRecordVO> result = checkService.getSignInRecordById(999L);
|
||||||
|
|
||||||
|
StepVerifier.create(result)
|
||||||
|
.verifyComplete();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("测试6: 获取签到统计 - getSignInStats")
|
||||||
|
void testGetSignInStats() {
|
||||||
|
when(signInRecordRepository.countByMemberIdAndTimeRange(
|
||||||
|
eq(1L), any(LocalDateTime.class), any(LocalDateTime.class)))
|
||||||
|
.thenReturn(Mono.just(10L));
|
||||||
|
when(signInRecordRepository.countSuccessByMemberIdAndTimeRange(
|
||||||
|
eq(1L), any(LocalDateTime.class), any(LocalDateTime.class)))
|
||||||
|
.thenReturn(Mono.just(8L));
|
||||||
|
when(signInRecordRepository.getFirstSignInTime(
|
||||||
|
eq(1L), any(LocalDateTime.class), any(LocalDateTime.class)))
|
||||||
|
.thenReturn(Mono.just(LocalDateTime.now().minusDays(29)));
|
||||||
|
when(signInRecordRepository.getLastSignInTime(
|
||||||
|
eq(1L), any(LocalDateTime.class), any(LocalDateTime.class)))
|
||||||
|
.thenReturn(Mono.just(LocalDateTime.now()));
|
||||||
|
|
||||||
|
Mono<SignInStatsVO> result = checkService.getSignInStats(1L,
|
||||||
|
LocalDate.now().minusDays(30), LocalDate.now());
|
||||||
|
|
||||||
|
StepVerifier.create(result)
|
||||||
|
.expectNextMatches(stats -> {
|
||||||
|
org.junit.jupiter.api.Assertions.assertEquals(10L, stats.getTotalCount());
|
||||||
|
org.junit.jupiter.api.Assertions.assertEquals(8L, stats.getSuccessCount());
|
||||||
|
return true;
|
||||||
|
})
|
||||||
|
.verifyComplete();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("测试7: 获取每日签到统计 - getDailySignInStats")
|
||||||
|
void testGetDailySignInStats() {
|
||||||
|
when(signInRecordRepository.countByTimeRange(any(LocalDateTime.class), any(LocalDateTime.class)))
|
||||||
|
.thenReturn(Mono.just(50L));
|
||||||
|
when(signInRecordRepository.countSuccessByTimeRange(
|
||||||
|
any(LocalDateTime.class), any(LocalDateTime.class)))
|
||||||
|
.thenReturn(Mono.just(45L));
|
||||||
|
when(signInRecordRepository.countDistinctMembersByTimeRange(
|
||||||
|
any(LocalDateTime.class), any(LocalDateTime.class)))
|
||||||
|
.thenReturn(Mono.just(30L));
|
||||||
|
|
||||||
|
Mono<SignInStatsVO> result = checkService.getDailySignInStats(LocalDate.now());
|
||||||
|
|
||||||
|
StepVerifier.create(result)
|
||||||
|
.expectNextMatches(stats -> {
|
||||||
|
org.junit.jupiter.api.Assertions.assertEquals(50L, stats.getTotalCount());
|
||||||
|
org.junit.jupiter.api.Assertions.assertEquals(45L, stats.getSuccessCount());
|
||||||
|
org.junit.jupiter.api.Assertions.assertEquals(30L, stats.getUniqueMemberCount());
|
||||||
|
return true;
|
||||||
|
})
|
||||||
|
.verifyComplete();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("测试8: 导出签到记录 - exportSignInRecords")
|
||||||
|
void testExportSignInRecords() {
|
||||||
|
when(signInRecordRepository.findByMemberIdAndTimeRange(
|
||||||
|
eq(1L), any(LocalDateTime.class), any(LocalDateTime.class)))
|
||||||
|
.thenReturn(Flux.just(mockSignInRecord));
|
||||||
|
|
||||||
|
Mono<byte[]> result = checkService.exportSignInRecords(1L,
|
||||||
|
LocalDate.now().minusDays(7), LocalDate.now());
|
||||||
|
|
||||||
|
StepVerifier.create(result)
|
||||||
|
.expectNextMatches(bytes -> bytes.length > 0)
|
||||||
|
.verifyComplete();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("测试9: 签到失败 - 二维码无效")
|
||||||
|
void testCheckIn_QRCodeInvalid() {
|
||||||
|
Long memberId = 1L;
|
||||||
|
String key = RedisKeyConstants.QRCODE_USER_DAILY + memberId + LocalDate.now();
|
||||||
|
when(redisUtil.get(eq(key))).thenReturn(Mono.just(new HashMap<>()));
|
||||||
|
when(signInRecordRepository.findByMemberIdAndDate(eq(memberId), any(LocalDateTime.class), any(LocalDateTime.class)))
|
||||||
|
.thenReturn(Mono.empty());
|
||||||
|
|
||||||
|
Mono<String> result = checkService.checkIn(memberId, "invalid-qr");
|
||||||
|
|
||||||
|
StepVerifier.create(result)
|
||||||
|
.expectError(RuntimeException.class)
|
||||||
|
.verify();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
@DisplayName("测试10: 签到失败 - 二维码不存在")
|
||||||
|
void testCheckIn_QRCodeNotFound() {
|
||||||
|
Long memberId = 1L;
|
||||||
|
String key = RedisKeyConstants.QRCODE_USER_DAILY + memberId + LocalDate.now();
|
||||||
|
when(redisUtil.get(eq(key))).thenReturn(Mono.empty());
|
||||||
|
when(signInRecordRepository.findByMemberIdAndDate(eq(memberId), any(LocalDateTime.class), any(LocalDateTime.class)))
|
||||||
|
.thenReturn(Mono.empty());
|
||||||
|
|
||||||
|
Mono<String> result = checkService.checkIn(memberId, "not-exist");
|
||||||
|
|
||||||
|
StepVerifier.create(result)
|
||||||
|
.verifyComplete();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
# Test Configuration
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||||
|
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
|
||||||
|
<parent>
|
||||||
|
<groupId>cn.novalon.gym.manage</groupId>
|
||||||
|
<artifactId>gym-manage-api</artifactId>
|
||||||
|
<version>1.0.0</version>
|
||||||
|
</parent>
|
||||||
|
|
||||||
|
<artifactId>gym-coach</artifactId>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
|
||||||
|
<name>Gym Coach</name>
|
||||||
|
<description>Coach Management Module - Course Start/End, Violation Tracking</description>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>cn.novalon.gym.manage</groupId>
|
||||||
|
<artifactId>manage-common</artifactId>
|
||||||
|
<version>${project.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>cn.novalon.gym.manage</groupId>
|
||||||
|
<artifactId>manage-db</artifactId>
|
||||||
|
<version>${project.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>cn.novalon.gym.manage</groupId>
|
||||||
|
<artifactId>manage-sys</artifactId>
|
||||||
|
<version>${project.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>cn.novalon.gym.manage</groupId>
|
||||||
|
<artifactId>gym-groupCourse</artifactId>
|
||||||
|
<version>${project.version}</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-webflux</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-security</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.data</groupId>
|
||||||
|
<artifactId>spring-data-commons</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springdoc</groupId>
|
||||||
|
<artifactId>springdoc-openapi-starter-webflux-ui</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.projectlombok</groupId>
|
||||||
|
<artifactId>lombok</artifactId>
|
||||||
|
<scope>provided</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
</project>
|
||||||
+15
@@ -0,0 +1,15 @@
|
|||||||
|
package cn.novalon.gym.manage.coach.dao;
|
||||||
|
|
||||||
|
import cn.novalon.gym.manage.coach.entity.CoachViolationEntity;
|
||||||
|
import org.springframework.data.r2dbc.repository.R2dbcRepository;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 教练违规记录 DAO
|
||||||
|
*
|
||||||
|
* @author 张翔
|
||||||
|
* @date 2026-07-20
|
||||||
|
*/
|
||||||
|
@Repository
|
||||||
|
public interface CoachViolationDao extends R2dbcRepository<CoachViolationEntity, Long> {
|
||||||
|
}
|
||||||
+61
@@ -0,0 +1,61 @@
|
|||||||
|
package cn.novalon.gym.manage.coach.entity;
|
||||||
|
|
||||||
|
import cn.novalon.gym.manage.db.entity.BaseEntity;
|
||||||
|
import org.springframework.data.relational.core.mapping.Column;
|
||||||
|
import org.springframework.data.relational.core.mapping.Table;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 教练违规记录实体类 - 对应 coach_violation 表
|
||||||
|
*
|
||||||
|
* @author 张翔
|
||||||
|
* @date 2026-07-20
|
||||||
|
*/
|
||||||
|
@Table("coach_violation")
|
||||||
|
public class CoachViolationEntity extends BaseEntity {
|
||||||
|
|
||||||
|
@Column("coach_id")
|
||||||
|
private Long coachId;
|
||||||
|
|
||||||
|
@Column("course_id")
|
||||||
|
private Long courseId;
|
||||||
|
|
||||||
|
@Column("violation_time")
|
||||||
|
private LocalDateTime violationTime;
|
||||||
|
|
||||||
|
@Column("violation_reason")
|
||||||
|
private String violationReason;
|
||||||
|
|
||||||
|
public Long getCoachId() {
|
||||||
|
return coachId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCoachId(Long coachId) {
|
||||||
|
this.coachId = coachId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getCourseId() {
|
||||||
|
return courseId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCourseId(Long courseId) {
|
||||||
|
this.courseId = courseId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public LocalDateTime getViolationTime() {
|
||||||
|
return violationTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setViolationTime(LocalDateTime violationTime) {
|
||||||
|
this.violationTime = violationTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getViolationReason() {
|
||||||
|
return violationReason;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setViolationReason(String violationReason) {
|
||||||
|
this.violationReason = violationReason;
|
||||||
|
}
|
||||||
|
}
|
||||||
+42
@@ -0,0 +1,42 @@
|
|||||||
|
package cn.novalon.gym.manage.coach.enums;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 团课预约状态枚举
|
||||||
|
*
|
||||||
|
* @author 张翔
|
||||||
|
* @date 2026-07-20
|
||||||
|
*/
|
||||||
|
public enum BookingStatus {
|
||||||
|
|
||||||
|
BOOKED("0", "已预约"),
|
||||||
|
CANCELLED("1", "已取消"),
|
||||||
|
ATTENDED("2", "已出席"),
|
||||||
|
ABSENT("3", "缺席"),
|
||||||
|
COACH_ABSENT("4", "教练缺席"),
|
||||||
|
LATE("5", "迟到");
|
||||||
|
|
||||||
|
private final String value;
|
||||||
|
private final String desc;
|
||||||
|
|
||||||
|
BookingStatus(String value, String desc) {
|
||||||
|
this.value = value;
|
||||||
|
this.desc = desc;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getValue() {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getDesc() {
|
||||||
|
return desc;
|
||||||
|
}
|
||||||
|
|
||||||
|
public static BookingStatus fromValue(String value) {
|
||||||
|
for (BookingStatus status : values()) {
|
||||||
|
if (status.value.equals(value)) {
|
||||||
|
return status;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return BOOKED;
|
||||||
|
}
|
||||||
|
}
|
||||||
+30
@@ -0,0 +1,30 @@
|
|||||||
|
package cn.novalon.gym.manage.coach.enums;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 教练违规原因枚举
|
||||||
|
*
|
||||||
|
* @author 张翔
|
||||||
|
* @date 2026-07-20
|
||||||
|
*/
|
||||||
|
public enum ViolationReason {
|
||||||
|
|
||||||
|
COACH_LATE("COACH_LATE", "教练迟到"),
|
||||||
|
COACH_ABSENT("COACH_ABSENT", "教练缺席"),
|
||||||
|
NOT_MANUAL_END("NOT_MANUAL_END", "教练未手动结课");
|
||||||
|
|
||||||
|
private final String value;
|
||||||
|
private final String desc;
|
||||||
|
|
||||||
|
ViolationReason(String value, String desc) {
|
||||||
|
this.value = value;
|
||||||
|
this.desc = desc;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getValue() {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getDesc() {
|
||||||
|
return desc;
|
||||||
|
}
|
||||||
|
}
|
||||||
+68
@@ -0,0 +1,68 @@
|
|||||||
|
package cn.novalon.gym.manage.coach.handler;
|
||||||
|
|
||||||
|
import cn.novalon.gym.manage.coach.service.CoachCourseService;
|
||||||
|
import cn.novalon.gym.manage.sys.util.AuthUtil;
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.reactive.function.server.ServerRequest;
|
||||||
|
import org.springframework.web.reactive.function.server.ServerResponse;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 教练开课/结课处理器
|
||||||
|
*
|
||||||
|
* @author 张翔
|
||||||
|
* @date 2026-07-20
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
@Tag(name = "教练开课结课", description = "教练开课与结课操作")
|
||||||
|
public class CoachCourseHandler {
|
||||||
|
|
||||||
|
private static final Logger logger = LoggerFactory.getLogger(CoachCourseHandler.class);
|
||||||
|
private final CoachCourseService coachCourseService;
|
||||||
|
private final AuthUtil authUtil;
|
||||||
|
|
||||||
|
public CoachCourseHandler(CoachCourseService coachCourseService, AuthUtil authUtil) {
|
||||||
|
this.coachCourseService = coachCourseService;
|
||||||
|
this.authUtil = authUtil;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "教练开课", description = "教练手动开课,记录实际开课时间,若超时则判定迟到")
|
||||||
|
public Mono<ServerResponse> startCourse(ServerRequest request) {
|
||||||
|
Long courseId = Long.valueOf(request.pathVariable("courseId"));
|
||||||
|
Long coachId = authUtil.getMemberIdOrThrow(request);
|
||||||
|
|
||||||
|
return coachCourseService.startCourse(courseId, coachId)
|
||||||
|
.flatMap(result -> ServerResponse.ok().bodyValue(Map.of(
|
||||||
|
"message", "开课成功",
|
||||||
|
"status", result.getStatus(),
|
||||||
|
"actualStartTime", result.getActualStartTime() != null ? result.getActualStartTime().toString() : ""
|
||||||
|
)))
|
||||||
|
.onErrorResume(e -> {
|
||||||
|
logger.error("开课失败: {}", e.getMessage());
|
||||||
|
return ServerResponse.badRequest().bodyValue(Map.of("error", e.getMessage()));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "教练结课", description = "教练手动结课,记录实际结课时间")
|
||||||
|
public Mono<ServerResponse> endCourse(ServerRequest request) {
|
||||||
|
Long courseId = Long.valueOf(request.pathVariable("courseId"));
|
||||||
|
Long coachId = authUtil.getMemberIdOrThrow(request);
|
||||||
|
|
||||||
|
return coachCourseService.endCourse(courseId, coachId)
|
||||||
|
.flatMap(result -> ServerResponse.ok().bodyValue(Map.of(
|
||||||
|
"message", "结课成功",
|
||||||
|
"status", result.getStatus(),
|
||||||
|
"actualEndTime", result.getActualEndTime() != null ? result.getActualEndTime().toString() : ""
|
||||||
|
)))
|
||||||
|
.onErrorResume(e -> {
|
||||||
|
logger.error("结课失败: {}", e.getMessage());
|
||||||
|
return ServerResponse.badRequest().bodyValue(Map.of("error", e.getMessage()));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
+118
@@ -0,0 +1,118 @@
|
|||||||
|
package cn.novalon.gym.manage.coach.handler;
|
||||||
|
|
||||||
|
import cn.novalon.gym.manage.coach.service.CoachCourseService;
|
||||||
|
import cn.novalon.gym.manage.sys.core.domain.SysUser;
|
||||||
|
import cn.novalon.gym.manage.sys.dto.request.CoachCreateRequest;
|
||||||
|
import cn.novalon.gym.manage.sys.dto.request.CoachUpdateRequest;
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import jakarta.validation.Validator;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.http.HttpStatus;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import org.springframework.web.reactive.function.server.ServerRequest;
|
||||||
|
import org.springframework.web.reactive.function.server.ServerResponse;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 教练管理处理器(从 manage-app 迁移至 gym-coach 模块)
|
||||||
|
*
|
||||||
|
* @author 张翔
|
||||||
|
* @date 2026-07-19
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
@Tag(name = "教练管理", description = "教练相关操作")
|
||||||
|
public class CoachHandler {
|
||||||
|
|
||||||
|
private static final Logger logger = LoggerFactory.getLogger(CoachHandler.class);
|
||||||
|
private final CoachCourseService coachCourseService;
|
||||||
|
private final Validator validator;
|
||||||
|
|
||||||
|
public CoachHandler(CoachCourseService coachCourseService, Validator validator) {
|
||||||
|
this.coachCourseService = coachCourseService;
|
||||||
|
this.validator = validator;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "获取所有教练", description = "获取系统中所有教练列表")
|
||||||
|
public Mono<ServerResponse> getAllCoaches(ServerRequest request) {
|
||||||
|
return ServerResponse.ok()
|
||||||
|
.body(coachCourseService.getAllCoaches(), SysUser.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "创建教练", description = "创建新教练(创建用户并分配教练角色)")
|
||||||
|
public Mono<ServerResponse> createCoach(ServerRequest request) {
|
||||||
|
return request.bodyToMono(CoachCreateRequest.class)
|
||||||
|
.flatMap(req -> {
|
||||||
|
var violations = validator.validate(req);
|
||||||
|
if (!violations.isEmpty()) {
|
||||||
|
Map<String, String> errors = new HashMap<>();
|
||||||
|
violations.forEach(v -> errors.put(v.getPropertyPath().toString(), v.getMessage()));
|
||||||
|
return ServerResponse.badRequest().bodyValue(errors);
|
||||||
|
}
|
||||||
|
return coachCourseService.createCoach(
|
||||||
|
req.getUsername(), req.getPassword(),
|
||||||
|
req.getNickname(), req.getEmail(), req.getPhone())
|
||||||
|
.flatMap(user -> ServerResponse.status(HttpStatus.CREATED).bodyValue(user))
|
||||||
|
.onErrorResume(e -> {
|
||||||
|
logger.error("创建教练失败", e);
|
||||||
|
return ServerResponse.badRequest()
|
||||||
|
.bodyValue(Map.of("error", e.getMessage()));
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "更新教练信息", description = "更新教练基本信息(昵称、邮箱、手机号)")
|
||||||
|
public Mono<ServerResponse> updateCoach(ServerRequest request) {
|
||||||
|
Long id = Long.valueOf(request.pathVariable("id"));
|
||||||
|
return request.bodyToMono(CoachUpdateRequest.class)
|
||||||
|
.flatMap(req -> coachCourseService.updateCoach(id, req.getNickname(), req.getEmail(), req.getPhone())
|
||||||
|
.flatMap(user -> ServerResponse.ok().bodyValue(user))
|
||||||
|
.switchIfEmpty(ServerResponse.notFound().build())
|
||||||
|
.onErrorResume(e -> {
|
||||||
|
logger.error("更新教练失败", e);
|
||||||
|
return ServerResponse.badRequest()
|
||||||
|
.bodyValue(Map.of("error", e.getMessage()));
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "禁用教练", description = "禁用教练账号,自动取消其所有非进行中的团课")
|
||||||
|
public Mono<ServerResponse> disableCoach(ServerRequest request) {
|
||||||
|
Long id = Long.valueOf(request.pathVariable("id"));
|
||||||
|
return coachCourseService.disableCoach(id)
|
||||||
|
.then(ServerResponse.ok().bodyValue(Map.of("message", "教练已禁用")))
|
||||||
|
.onErrorResume(e -> {
|
||||||
|
logger.error("禁用教练失败: {}", e.getMessage());
|
||||||
|
return ServerResponse.badRequest().bodyValue(Map.of("error", e.getMessage()));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "获取教练的团课", description = "获取指定教练教授的所有团课")
|
||||||
|
public Mono<ServerResponse> getCoachCourses(ServerRequest request) {
|
||||||
|
Long id = Long.valueOf(request.pathVariable("id"));
|
||||||
|
return coachCourseService.getCoachCourses(id)
|
||||||
|
.collectList()
|
||||||
|
.flatMap(courses -> ServerResponse.ok().bodyValue(courses))
|
||||||
|
.switchIfEmpty(ServerResponse.ok().bodyValue(List.of()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "获取教练违规次数统计", description = "获取所有教练的违规次数")
|
||||||
|
public Mono<ServerResponse> getViolationCounts(ServerRequest request) {
|
||||||
|
return coachCourseService.getViolationCounts()
|
||||||
|
.collectList()
|
||||||
|
.flatMap(counts -> ServerResponse.ok().bodyValue(counts));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "获取教练违规记录", description = "获取指定教练的违规记录")
|
||||||
|
public Mono<ServerResponse> getCoachViolations(ServerRequest request) {
|
||||||
|
Long id = Long.valueOf(request.pathVariable("id"));
|
||||||
|
return coachCourseService.getCoachViolations(id)
|
||||||
|
.collectList()
|
||||||
|
.flatMap(violations -> ServerResponse.ok().bodyValue(violations))
|
||||||
|
.switchIfEmpty(ServerResponse.ok().bodyValue(List.of()));
|
||||||
|
}
|
||||||
|
}
|
||||||
+178
@@ -0,0 +1,178 @@
|
|||||||
|
package cn.novalon.gym.manage.coach.scheduler;
|
||||||
|
|
||||||
|
import cn.novalon.gym.manage.coach.enums.ViolationReason;
|
||||||
|
import cn.novalon.gym.manage.common.util.RedisUtil;
|
||||||
|
import cn.novalon.gym.manage.groupcourse.dao.GroupCourseBookingDao;
|
||||||
|
import cn.novalon.gym.manage.groupcourse.dao.GroupCourseDao;
|
||||||
|
import cn.novalon.gym.manage.groupcourse.entity.GroupCourseEntity;
|
||||||
|
import cn.novalon.gym.manage.groupcourse.enums.CourseStatus;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.r2dbc.core.DatabaseClient;
|
||||||
|
import org.springframework.scheduling.annotation.Scheduled;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 教练课程定时调度器
|
||||||
|
*
|
||||||
|
* 功能:
|
||||||
|
* 1. 检查未手动开课的课程,超时标记为教练缺席(5)并记录违规
|
||||||
|
* 2. 检查未手动结课的课程,超时标记为自动结束(6)并记录违规
|
||||||
|
*
|
||||||
|
* @author 张翔
|
||||||
|
* @date 2026-07-20
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
public class CoachCourseScheduler {
|
||||||
|
|
||||||
|
private static final Logger logger = LoggerFactory.getLogger(CoachCourseScheduler.class);
|
||||||
|
private static final long ONE_HOUR_MINUTES = 60;
|
||||||
|
private static final long END_GRACE_MINUTES = 10;
|
||||||
|
|
||||||
|
private final GroupCourseDao groupCourseDao;
|
||||||
|
private final GroupCourseBookingDao groupCourseBookingDao;
|
||||||
|
private final DatabaseClient databaseClient;
|
||||||
|
private final RedisUtil redisUtil;
|
||||||
|
|
||||||
|
public CoachCourseScheduler(GroupCourseDao groupCourseDao,
|
||||||
|
GroupCourseBookingDao groupCourseBookingDao,
|
||||||
|
DatabaseClient databaseClient,
|
||||||
|
RedisUtil redisUtil) {
|
||||||
|
this.groupCourseDao = groupCourseDao;
|
||||||
|
this.groupCourseBookingDao = groupCourseBookingDao;
|
||||||
|
this.databaseClient = databaseClient;
|
||||||
|
this.redisUtil = redisUtil;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 每分钟检查一次:
|
||||||
|
* - status=0(NORMAL) 的课程是否已过开课缺席阈值
|
||||||
|
* - status=3(IN_PROGRESS) 或 status=7(COACH_LATE) 的课程是否已过结课宽限期
|
||||||
|
*/
|
||||||
|
@Scheduled(fixedRate = 60000)
|
||||||
|
public void checkAndProcessCourses() {
|
||||||
|
logger.debug("教练课程调度器开始检查");
|
||||||
|
|
||||||
|
LocalDateTime now = LocalDateTime.now();
|
||||||
|
|
||||||
|
// 1. 检查未开课的课程
|
||||||
|
processAbsentCourses(now)
|
||||||
|
.subscribe(
|
||||||
|
count -> {
|
||||||
|
if (count > 0) {
|
||||||
|
logger.info("教练课程调度器:处理了 {} 门教练缺席课程", count);
|
||||||
|
invalidateCache();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
error -> logger.error("教练课程调度器(缺席检查)执行失败:{}", error.getMessage(), error)
|
||||||
|
);
|
||||||
|
|
||||||
|
// 2. 检查未结课的课程
|
||||||
|
processAutoEndCourses(now)
|
||||||
|
.subscribe(
|
||||||
|
count -> {
|
||||||
|
if (count > 0) {
|
||||||
|
logger.info("教练课程调度器:处理了 {} 门自动结束课程", count);
|
||||||
|
invalidateCache();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
error -> logger.error("教练课程调度器(自动结课)执行失败:{}", error.getMessage(), error)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 处理缺席课程:status=0 且已过开课缺席阈值
|
||||||
|
*/
|
||||||
|
private Mono<Long> processAbsentCourses(LocalDateTime now) {
|
||||||
|
return groupCourseDao.findByStatusAndStartTimeBefore(databaseClient, "0", now)
|
||||||
|
.filter(course -> isAbsentThresholdExceeded(course, now))
|
||||||
|
.flatMap(course -> markAsCoachAbsent(course, now))
|
||||||
|
.count();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 处理自动结课:status IN ('3','7') 且 end_time + 10分钟 已过
|
||||||
|
*/
|
||||||
|
private Mono<Long> processAutoEndCourses(LocalDateTime now) {
|
||||||
|
LocalDateTime endThreshold = now.minusMinutes(END_GRACE_MINUTES);
|
||||||
|
return groupCourseDao.findByStatusInAndEndTimeBefore(databaseClient,
|
||||||
|
new String[]{String.valueOf(CourseStatus.IN_PROGRESS.getValue()),
|
||||||
|
String.valueOf(CourseStatus.COACH_LATE.getValue())},
|
||||||
|
endThreshold)
|
||||||
|
.flatMap(course -> markAsAutoEnded(course, now))
|
||||||
|
.count();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断课程是否已过缺席阈值
|
||||||
|
*/
|
||||||
|
private boolean isAbsentThresholdExceeded(GroupCourseEntity course, LocalDateTime now) {
|
||||||
|
long courseDurationMinutes = Duration.between(course.getStartTime(), course.getEndTime()).toMinutes();
|
||||||
|
long minutesSinceStart = Duration.between(course.getStartTime(), now).toMinutes();
|
||||||
|
|
||||||
|
if (courseDurationMinutes >= ONE_HOUR_MINUTES) {
|
||||||
|
return minutesSinceStart > 30;
|
||||||
|
} else {
|
||||||
|
long thresholdB = Math.max(1, (long) (courseDurationMinutes * 0.25));
|
||||||
|
return minutesSinceStart > thresholdB;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 标记课程为教练缺席(5),更新预约记录为教练缺席(4),记录违规
|
||||||
|
*/
|
||||||
|
private Mono<GroupCourseEntity> markAsCoachAbsent(GroupCourseEntity course, LocalDateTime now) {
|
||||||
|
logger.info("课程 {} 教练缺席,标记为 COACH_ABSENT", course.getId());
|
||||||
|
|
||||||
|
return insertViolation(course.getCoachId(), course.getId(), now, ViolationReason.COACH_ABSENT)
|
||||||
|
.then(groupCourseDao.updateToCoachAbsent(course.getId(), now, now))
|
||||||
|
.then(groupCourseBookingDao.updateStatusByCourseId(course.getId(), "0", "4"))
|
||||||
|
.thenReturn(course);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 标记课程为自动结束(6),记录违规
|
||||||
|
*/
|
||||||
|
private Mono<GroupCourseEntity> markAsAutoEnded(GroupCourseEntity course, LocalDateTime now) {
|
||||||
|
logger.info("课程 {} 未手动结课,标记为 AUTO_ENDED", course.getId());
|
||||||
|
|
||||||
|
return insertViolation(course.getCoachId(), course.getId(), now, ViolationReason.NOT_MANUAL_END)
|
||||||
|
.then(groupCourseDao.updateToAutoEnded(course.getId(), now, now))
|
||||||
|
.thenReturn(course);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 插入违规记录(使用 DatabaseClient 直连)
|
||||||
|
*/
|
||||||
|
private Mono<Void> insertViolation(Long coachId, Long courseId, LocalDateTime violationTime,
|
||||||
|
ViolationReason reason) {
|
||||||
|
return databaseClient.sql("""
|
||||||
|
INSERT INTO coach_violation (coach_id, course_id, violation_time, violation_reason, created_at, updated_at)
|
||||||
|
VALUES (:coachId, :courseId, :violationTime, :reason, :now, :now)
|
||||||
|
""")
|
||||||
|
.bind("coachId", coachId)
|
||||||
|
.bind("courseId", courseId)
|
||||||
|
.bind("violationTime", violationTime)
|
||||||
|
.bind("reason", reason.getValue())
|
||||||
|
.bind("now", LocalDateTime.now())
|
||||||
|
.then();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清除统计缓存和团课缓存 —— 调度器触发时,如有课程状态变更则必须及时失效
|
||||||
|
*/
|
||||||
|
private void invalidateCache() {
|
||||||
|
redisUtil.deleteByPattern("datacount:statistics:*").subscribe(
|
||||||
|
deleted -> logger.debug("调度器清除统计缓存,已删除 {} 条", deleted),
|
||||||
|
error -> logger.warn("调度器清除统计缓存失败: {}", error.getMessage())
|
||||||
|
);
|
||||||
|
redisUtil.deleteByPattern("group_course:*").subscribe(
|
||||||
|
deleted -> logger.debug("调度器清除团课缓存,已删除 {} 条", deleted),
|
||||||
|
error -> logger.warn("调度器清除团课缓存失败: {}", error.getMessage())
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
+357
@@ -0,0 +1,357 @@
|
|||||||
|
package cn.novalon.gym.manage.coach.service;
|
||||||
|
|
||||||
|
import cn.novalon.gym.manage.coach.dao.CoachViolationDao;
|
||||||
|
import cn.novalon.gym.manage.coach.entity.CoachViolationEntity;
|
||||||
|
import cn.novalon.gym.manage.coach.enums.ViolationReason;
|
||||||
|
import cn.novalon.gym.manage.common.util.RedisUtil;
|
||||||
|
import cn.novalon.gym.manage.common.util.StatusConstants;
|
||||||
|
import cn.novalon.gym.manage.groupcourse.dao.GroupCourseBookingDao;
|
||||||
|
import cn.novalon.gym.manage.groupcourse.dao.GroupCourseDao;
|
||||||
|
import cn.novalon.gym.manage.groupcourse.domain.GroupCourse;
|
||||||
|
import cn.novalon.gym.manage.groupcourse.entity.GroupCourseEntity;
|
||||||
|
import cn.novalon.gym.manage.groupcourse.enums.CourseStatus;
|
||||||
|
import cn.novalon.gym.manage.groupcourse.repository.IGroupCourseBookingRepository;
|
||||||
|
import cn.novalon.gym.manage.groupcourse.repository.IGroupCourseRepository;
|
||||||
|
import cn.novalon.gym.manage.sys.core.domain.SysRole;
|
||||||
|
import cn.novalon.gym.manage.sys.core.domain.SysUser;
|
||||||
|
import cn.novalon.gym.manage.sys.core.domain.UserRole;
|
||||||
|
import cn.novalon.gym.manage.sys.core.repository.ISysRoleRepository;
|
||||||
|
import cn.novalon.gym.manage.sys.core.repository.ISysUserRepository;
|
||||||
|
import cn.novalon.gym.manage.sys.core.repository.IUserRoleRepository;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.data.domain.Sort;
|
||||||
|
import org.springframework.r2dbc.core.DatabaseClient;
|
||||||
|
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
import reactor.core.publisher.Flux;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 教练课程服务(含教练管理 + 开课/结课逻辑 + 违规记录)
|
||||||
|
*
|
||||||
|
* @author 张翔
|
||||||
|
* @date 2026-07-20
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
public class CoachCourseService {
|
||||||
|
|
||||||
|
private static final Logger logger = LoggerFactory.getLogger(CoachCourseService.class);
|
||||||
|
private static final String COACH_ROLE_NAME = "教练";
|
||||||
|
private static final long ONE_HOUR_MINUTES = 60;
|
||||||
|
|
||||||
|
private final ISysUserRepository userRepository;
|
||||||
|
private final ISysRoleRepository roleRepository;
|
||||||
|
private final IUserRoleRepository userRoleRepository;
|
||||||
|
private final IGroupCourseRepository groupCourseRepository;
|
||||||
|
private final IGroupCourseBookingRepository bookingRepository;
|
||||||
|
private final GroupCourseDao groupCourseDao;
|
||||||
|
private final GroupCourseBookingDao groupCourseBookingDao;
|
||||||
|
private final CoachViolationDao violationDao;
|
||||||
|
private final DatabaseClient databaseClient;
|
||||||
|
private final PasswordEncoder passwordEncoder;
|
||||||
|
private final RedisUtil redisUtil;
|
||||||
|
|
||||||
|
public CoachCourseService(ISysUserRepository userRepository,
|
||||||
|
ISysRoleRepository roleRepository,
|
||||||
|
IUserRoleRepository userRoleRepository,
|
||||||
|
IGroupCourseRepository groupCourseRepository,
|
||||||
|
IGroupCourseBookingRepository bookingRepository,
|
||||||
|
GroupCourseDao groupCourseDao,
|
||||||
|
GroupCourseBookingDao groupCourseBookingDao,
|
||||||
|
CoachViolationDao violationDao,
|
||||||
|
DatabaseClient databaseClient,
|
||||||
|
PasswordEncoder passwordEncoder,
|
||||||
|
RedisUtil redisUtil) {
|
||||||
|
this.userRepository = userRepository;
|
||||||
|
this.roleRepository = roleRepository;
|
||||||
|
this.userRoleRepository = userRoleRepository;
|
||||||
|
this.groupCourseRepository = groupCourseRepository;
|
||||||
|
this.bookingRepository = bookingRepository;
|
||||||
|
this.groupCourseDao = groupCourseDao;
|
||||||
|
this.groupCourseBookingDao = groupCourseBookingDao;
|
||||||
|
this.violationDao = violationDao;
|
||||||
|
this.databaseClient = databaseClient;
|
||||||
|
this.passwordEncoder = passwordEncoder;
|
||||||
|
this.redisUtil = redisUtil;
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== 教练管理(从原 CoachService 迁移) ====================
|
||||||
|
|
||||||
|
public Flux<SysUser> getAllCoaches() {
|
||||||
|
return getCoachRoleId()
|
||||||
|
.flatMapMany(roleId -> userRoleRepository.findByRoleId(roleId)
|
||||||
|
.map(UserRole::getUserId)
|
||||||
|
.collectList()
|
||||||
|
.flatMapMany(userIds -> {
|
||||||
|
if (userIds.isEmpty()) {
|
||||||
|
return Flux.empty();
|
||||||
|
}
|
||||||
|
return Flux.fromIterable(userIds)
|
||||||
|
.flatMap(userRepository::findById)
|
||||||
|
.filter(user -> user.getDeletedAt() == null);
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
public Mono<SysUser> createCoach(String username, String password, String nickname, String email, String phone) {
|
||||||
|
return getCoachRoleId().flatMap(coachRoleId -> {
|
||||||
|
SysUser user = new SysUser();
|
||||||
|
user.generateId();
|
||||||
|
user.setUsername(username);
|
||||||
|
user.setPassword(passwordEncoder.encode(password));
|
||||||
|
user.setNickname(nickname);
|
||||||
|
user.setEmail(email);
|
||||||
|
user.setPhone(phone);
|
||||||
|
user.setStatus(StatusConstants.ENABLED);
|
||||||
|
|
||||||
|
return userRepository.save(user)
|
||||||
|
.flatMap(saved -> {
|
||||||
|
UserRole userRole = new UserRole();
|
||||||
|
userRole.setUserId(saved.getId());
|
||||||
|
userRole.setRoleId(coachRoleId);
|
||||||
|
return userRoleRepository.save(userRole).thenReturn(saved);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
public Mono<SysUser> updateCoach(Long id, String nickname, String email, String phone) {
|
||||||
|
return userRepository.findById(id)
|
||||||
|
.switchIfEmpty(Mono.error(new RuntimeException("教练不存在")))
|
||||||
|
.flatMap(user -> {
|
||||||
|
if (nickname != null) user.setNickname(nickname);
|
||||||
|
if (email != null) user.setEmail(email);
|
||||||
|
if (phone != null) user.setPhone(phone);
|
||||||
|
user.setUpdatedAt(LocalDateTime.now());
|
||||||
|
return userRepository.update(user);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Transactional(transactionManager = "connectionFactoryTransactionManager")
|
||||||
|
public Mono<Void> disableCoach(Long id) {
|
||||||
|
return userRepository.findById(id)
|
||||||
|
.switchIfEmpty(Mono.error(new RuntimeException("教练不存在")))
|
||||||
|
.flatMap(user ->
|
||||||
|
groupCourseRepository.countByCoachIdAndStatus(id, 3L)
|
||||||
|
.flatMap(inProgressCount -> {
|
||||||
|
if (inProgressCount > 0) {
|
||||||
|
return Mono.error(new RuntimeException(
|
||||||
|
"该教练有 " + inProgressCount + " 门正在进行中的团课,无法禁用"));
|
||||||
|
}
|
||||||
|
return groupCourseRepository.cancelCoursesByCoachIdExceptStatus(id, 3L)
|
||||||
|
.then();
|
||||||
|
})
|
||||||
|
.then(Mono.defer(() -> {
|
||||||
|
user.setStatus(StatusConstants.DISABLED);
|
||||||
|
user.setUpdatedAt(LocalDateTime.now());
|
||||||
|
return userRepository.update(user).then();
|
||||||
|
}))
|
||||||
|
)
|
||||||
|
.then(invalidateStatisticsCache());
|
||||||
|
}
|
||||||
|
|
||||||
|
public Flux<GroupCourse> getCoachCourses(Long coachId) {
|
||||||
|
return groupCourseRepository.findByCoachId(coachId, Sort.by(Sort.Direction.DESC, "startTime"))
|
||||||
|
.flatMap(course ->
|
||||||
|
bookingRepository.countValidBookings(course.getId())
|
||||||
|
.map(count -> {
|
||||||
|
course.setCurrentMembers(count.intValue());
|
||||||
|
return course;
|
||||||
|
})
|
||||||
|
.defaultIfEmpty(course)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
public Mono<Long> getCoachRoleId() {
|
||||||
|
return roleRepository.findByRoleName(COACH_ROLE_NAME)
|
||||||
|
.map(SysRole::getId)
|
||||||
|
.switchIfEmpty(Mono.error(new RuntimeException("教练角色未找到,请先执行数据库迁移")));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== 开课逻辑 ====================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 教练手动开课
|
||||||
|
* 判定逻辑:
|
||||||
|
* - 长课时(>=1h): 10分钟内正常,10~30分钟迟到,>30分钟拒绝
|
||||||
|
* - 短课时(<1h): 10%时长内正常,10%~25%迟到,>25%拒绝
|
||||||
|
*/
|
||||||
|
public Mono<GroupCourseEntity> startCourse(Long courseId, Long coachId) {
|
||||||
|
return groupCourseDao.findByIdIsAndDeletedAtIsNull(courseId)
|
||||||
|
.switchIfEmpty(Mono.error(new RuntimeException("团课不存在")))
|
||||||
|
.flatMap(course -> {
|
||||||
|
// 验证教练身份
|
||||||
|
if (!course.getCoachId().equals(coachId)) {
|
||||||
|
return Mono.error(new RuntimeException("您不是该课程的教练,无权开课"));
|
||||||
|
}
|
||||||
|
// 验证课程状态:只有 NORMAL(0) 可以开课
|
||||||
|
if (!CourseStatus.NORMAL.getValue().equals(course.getStatus())) {
|
||||||
|
return Mono.error(new RuntimeException("当前课程状态不允许开课,当前状态: " + course.getStatus()));
|
||||||
|
}
|
||||||
|
|
||||||
|
LocalDateTime now = LocalDateTime.now();
|
||||||
|
long courseDurationMinutes = Duration.between(course.getStartTime(), course.getEndTime()).toMinutes();
|
||||||
|
|
||||||
|
if (courseDurationMinutes >= ONE_HOUR_MINUTES) {
|
||||||
|
return handleLongCourseStart(course, now);
|
||||||
|
} else {
|
||||||
|
return handleShortCourseStart(course, now, courseDurationMinutes);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private Mono<GroupCourseEntity> handleLongCourseStart(GroupCourseEntity course, LocalDateTime now) {
|
||||||
|
long minutesSinceStart = Duration.between(course.getStartTime(), now).toMinutes();
|
||||||
|
|
||||||
|
if (minutesSinceStart < 0) {
|
||||||
|
return Mono.error(new RuntimeException("课程尚未到开课时间"));
|
||||||
|
}
|
||||||
|
if (minutesSinceStart <= 10) {
|
||||||
|
// 正常开课
|
||||||
|
return doStartCourse(course, now, CourseStatus.IN_PROGRESS, null);
|
||||||
|
}
|
||||||
|
if (minutesSinceStart <= 30) {
|
||||||
|
// 教练迟到
|
||||||
|
return recordViolation(course.getCoachId(), course.getId(), now, ViolationReason.COACH_LATE)
|
||||||
|
.then(doStartCourse(course, now, CourseStatus.COACH_LATE, ViolationReason.COACH_LATE));
|
||||||
|
}
|
||||||
|
// >30分钟,拒绝(调度器应已标记为缺席)
|
||||||
|
return Mono.error(new RuntimeException("已超过开课时间30分钟,无法开课"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private Mono<GroupCourseEntity> handleShortCourseStart(GroupCourseEntity course, LocalDateTime now,
|
||||||
|
long courseDurationMinutes) {
|
||||||
|
long minutesSinceStart = Duration.between(course.getStartTime(), now).toMinutes();
|
||||||
|
long thresholdA = Math.max(1, (long) (courseDurationMinutes * 0.10));
|
||||||
|
long thresholdB = Math.max(1, (long) (courseDurationMinutes * 0.25));
|
||||||
|
|
||||||
|
if (minutesSinceStart < 0) {
|
||||||
|
return Mono.error(new RuntimeException("课程尚未到开课时间"));
|
||||||
|
}
|
||||||
|
if (minutesSinceStart <= thresholdA) {
|
||||||
|
// 正常开课
|
||||||
|
return doStartCourse(course, now, CourseStatus.IN_PROGRESS, null);
|
||||||
|
}
|
||||||
|
if (minutesSinceStart <= thresholdB) {
|
||||||
|
// 教练迟到
|
||||||
|
return recordViolation(course.getCoachId(), course.getId(), now, ViolationReason.COACH_LATE)
|
||||||
|
.then(doStartCourse(course, now, CourseStatus.COACH_LATE, ViolationReason.COACH_LATE));
|
||||||
|
}
|
||||||
|
// >thresholdB,拒绝
|
||||||
|
return Mono.error(new RuntimeException("已超过开课时间,无法开课"));
|
||||||
|
}
|
||||||
|
|
||||||
|
private Mono<GroupCourseEntity> doStartCourse(GroupCourseEntity course, LocalDateTime now,
|
||||||
|
CourseStatus newStatus, ViolationReason violationReason) {
|
||||||
|
course.setStatus(newStatus.getValue());
|
||||||
|
course.setActualStartTime(now);
|
||||||
|
course.setUpdatedAt(now);
|
||||||
|
return groupCourseDao.updateStartInfo(course.getId(), String.valueOf(newStatus.getValue()), now, now)
|
||||||
|
.then(groupCourseDao.findByIdIsAndDeletedAtIsNull(course.getId()))
|
||||||
|
.flatMap(entity -> invalidateStatisticsCache().thenReturn(entity));
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== 结课逻辑 ====================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 教练手动结课
|
||||||
|
* 可在 IN_PROGRESS(3) 或 COACH_LATE(7) 状态下结课
|
||||||
|
* 必须在标注结课时间 + 10分钟内
|
||||||
|
*/
|
||||||
|
public Mono<GroupCourseEntity> endCourse(Long courseId, Long coachId) {
|
||||||
|
return groupCourseDao.findByIdIsAndDeletedAtIsNull(courseId)
|
||||||
|
.switchIfEmpty(Mono.error(new RuntimeException("团课不存在")))
|
||||||
|
.flatMap(course -> {
|
||||||
|
// 验证教练身份
|
||||||
|
if (!course.getCoachId().equals(coachId)) {
|
||||||
|
return Mono.error(new RuntimeException("您不是该课程的教练,无权结课"));
|
||||||
|
}
|
||||||
|
// 验证状态:IN_PROGRESS(3) 或 COACH_LATE(7)
|
||||||
|
Long status = course.getStatus();
|
||||||
|
if (!CourseStatus.IN_PROGRESS.getValue().equals(status)
|
||||||
|
&& !CourseStatus.COACH_LATE.getValue().equals(status)) {
|
||||||
|
return Mono.error(new RuntimeException("当前课程状态不允许结课,当前状态: " + status));
|
||||||
|
}
|
||||||
|
|
||||||
|
LocalDateTime now = LocalDateTime.now();
|
||||||
|
long minutesAfterEnd = Duration.between(course.getEndTime(), now).toMinutes();
|
||||||
|
|
||||||
|
if (minutesAfterEnd > 10) {
|
||||||
|
return Mono.error(new RuntimeException("已超过结课时间10分钟,请等待系统自动结课"));
|
||||||
|
}
|
||||||
|
|
||||||
|
course.setStatus(CourseStatus.ENDED.getValue());
|
||||||
|
course.setActualEndTime(now);
|
||||||
|
course.setUpdatedAt(now);
|
||||||
|
return groupCourseDao.updateEndInfo(course.getId(), String.valueOf(CourseStatus.ENDED.getValue()), now, now)
|
||||||
|
.then(groupCourseDao.findByIdIsAndDeletedAtIsNull(course.getId()))
|
||||||
|
.flatMap(entity -> invalidateStatisticsCache().thenReturn(entity));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== 违规记录 ====================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 记录教练违规行为(使用 DatabaseClient 直连,避免 R2DBC Entity 映射问题)
|
||||||
|
*/
|
||||||
|
public Mono<Void> recordViolation(Long coachId, Long courseId, LocalDateTime violationTime,
|
||||||
|
ViolationReason reason) {
|
||||||
|
LocalDateTime now = LocalDateTime.now();
|
||||||
|
return databaseClient.sql("""
|
||||||
|
INSERT INTO coach_violation (coach_id, course_id, violation_time, violation_reason, created_at, updated_at)
|
||||||
|
VALUES (:coachId, :courseId, :violationTime, :reason, :now, :now)
|
||||||
|
""")
|
||||||
|
.bind("coachId", coachId)
|
||||||
|
.bind("courseId", courseId)
|
||||||
|
.bind("violationTime", violationTime)
|
||||||
|
.bind("reason", reason.getValue())
|
||||||
|
.bind("now", now)
|
||||||
|
.then();
|
||||||
|
}
|
||||||
|
|
||||||
|
// ==================== 违规查询 ====================
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取所有教练的违规次数统计
|
||||||
|
*/
|
||||||
|
public Flux<Map<String, Object>> getViolationCounts() {
|
||||||
|
return databaseClient.sql("""
|
||||||
|
SELECT coach_id, COUNT(*) AS count
|
||||||
|
FROM coach_violation
|
||||||
|
WHERE deleted_at IS NULL
|
||||||
|
GROUP BY coach_id
|
||||||
|
""")
|
||||||
|
.fetch()
|
||||||
|
.all();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取指定教练的违规记录
|
||||||
|
*/
|
||||||
|
public Flux<Map<String, Object>> getCoachViolations(Long coachId) {
|
||||||
|
return databaseClient.sql("""
|
||||||
|
SELECT v.*, gc.course_name
|
||||||
|
FROM coach_violation v
|
||||||
|
LEFT JOIN group_course gc ON v.course_id = gc.id AND gc.deleted_at IS NULL
|
||||||
|
WHERE v.coach_id = :coachId AND v.deleted_at IS NULL
|
||||||
|
ORDER BY v.violation_time DESC
|
||||||
|
""")
|
||||||
|
.bind("coachId", coachId)
|
||||||
|
.fetch()
|
||||||
|
.all();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清除统计缓存和团课缓存 —— 课程状态变更后调用,返回 Mono 确保链式执行
|
||||||
|
*/
|
||||||
|
private Mono<Void> invalidateStatisticsCache() {
|
||||||
|
return redisUtil.deleteByPattern("datacount:statistics:*")
|
||||||
|
.then(redisUtil.deleteByPattern("group_course:*"))
|
||||||
|
.doOnNext(count -> {})
|
||||||
|
.then();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
HELP.md
|
||||||
|
target/
|
||||||
|
.mvn/wrapper/maven-wrapper.jar
|
||||||
|
!**/src/main/**/target/
|
||||||
|
!**/src/test/**/target/
|
||||||
|
|
||||||
|
### STS ###
|
||||||
|
.apt_generated
|
||||||
|
.classpath
|
||||||
|
.factorypath
|
||||||
|
.project
|
||||||
|
.settings
|
||||||
|
.springBeans
|
||||||
|
.sts4-cache
|
||||||
|
|
||||||
|
### IntelliJ IDEA ###
|
||||||
|
.idea
|
||||||
|
*.iws
|
||||||
|
*.iml
|
||||||
|
*.ipr
|
||||||
|
|
||||||
|
### NetBeans ###
|
||||||
|
/nbproject/private/
|
||||||
|
/nbbuild/
|
||||||
|
/dist/
|
||||||
|
/nbdist/
|
||||||
|
/.nb-gradle/
|
||||||
|
build/
|
||||||
|
!**/src/main/**/build/
|
||||||
|
!**/src/test/**/build/
|
||||||
|
|
||||||
|
### VS Code ###
|
||||||
|
.vscode/
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
wrapperVersion=3.3.4
|
||||||
|
distributionType=only-script
|
||||||
|
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.16/apache-maven-3.9.16-bin.zip
|
||||||
@@ -0,0 +1,125 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||||
|
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<parent>
|
||||||
|
<groupId>cn.novalon.gym.manage</groupId>
|
||||||
|
<artifactId>gym-manage-api</artifactId>
|
||||||
|
<version>1.0.0</version>
|
||||||
|
<relativePath>../pom.xml</relativePath>
|
||||||
|
</parent>
|
||||||
|
<groupId>cn.novalon.gym.manage</groupId>
|
||||||
|
<artifactId>gym-dataCount</artifactId>
|
||||||
|
<version>1.0.0</version>
|
||||||
|
<name>gym-dataCount</name>
|
||||||
|
<description>Data Statistics Module for Gym Management</description>
|
||||||
|
|
||||||
|
<properties>
|
||||||
|
<java.version>21</java.version>
|
||||||
|
</properties>
|
||||||
|
|
||||||
|
<dependencies>
|
||||||
|
<!-- Common模块 -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>cn.novalon.gym.manage</groupId>
|
||||||
|
<artifactId>manage-common</artifactId>
|
||||||
|
<version>${project.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- 数据库模块 -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>cn.novalon.gym.manage</groupId>
|
||||||
|
<artifactId>manage-db</artifactId>
|
||||||
|
<version>${project.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- WebFlux -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-webflux</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- R2dbc -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-data-r2dbc</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- Redis -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-data-redis</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- Validation -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-validation</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- Swagger -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springdoc</groupId>
|
||||||
|
<artifactId>springdoc-openapi-starter-webflux-ui</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- POI for Excel export -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.poi</groupId>
|
||||||
|
<artifactId>poi-ooxml</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- Fix commons-compress version for POI compatibility -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.apache.commons</groupId>
|
||||||
|
<artifactId>commons-compress</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- Gym Modules -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>cn.novalon.gym.manage</groupId>
|
||||||
|
<artifactId>gym-member</artifactId>
|
||||||
|
<version>${project.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>cn.novalon.gym.manage</groupId>
|
||||||
|
<artifactId>gym-groupCourse</artifactId>
|
||||||
|
<version>${project.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<dependency>
|
||||||
|
<groupId>cn.novalon.gym.manage</groupId>
|
||||||
|
<artifactId>gym-checkIn</artifactId>
|
||||||
|
<version>${project.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- Test -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-test</artifactId>
|
||||||
|
<scope>test</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-compiler-plugin</artifactId>
|
||||||
|
<version>3.11.0</version>
|
||||||
|
<configuration>
|
||||||
|
<source>21</source>
|
||||||
|
<target>21</target>
|
||||||
|
<annotationProcessorPaths>
|
||||||
|
<path>
|
||||||
|
<groupId>org.projectlombok</groupId>
|
||||||
|
<artifactId>lombok</artifactId>
|
||||||
|
<version>${lombok.version}</version>
|
||||||
|
</path>
|
||||||
|
</annotationProcessorPaths>
|
||||||
|
</configuration>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
</project>
|
||||||
+15
@@ -0,0 +1,15 @@
|
|||||||
|
package cn.novalon.gym.manage.datacount.config;
|
||||||
|
|
||||||
|
import org.springframework.boot.autoconfigure.AutoConfiguration;
|
||||||
|
import org.springframework.context.annotation.ComponentScan;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 数据统计模块自动配置
|
||||||
|
*
|
||||||
|
* @author system
|
||||||
|
* @date 2026-06-09
|
||||||
|
*/
|
||||||
|
@AutoConfiguration
|
||||||
|
@ComponentScan(basePackages = "cn.novalon.gym.manage.datacount")
|
||||||
|
public class DataCountAutoConfiguration {
|
||||||
|
}
|
||||||
+248
@@ -0,0 +1,248 @@
|
|||||||
|
package cn.novalon.gym.manage.datacount.dao;
|
||||||
|
|
||||||
|
import org.springframework.r2dbc.core.DatabaseClient;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
import reactor.core.publisher.Flux;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 数据统计 DAO - 使用 DatabaseClient 执行跨表聚合查询
|
||||||
|
*
|
||||||
|
* @author system
|
||||||
|
* @date 2026-06-09
|
||||||
|
*/
|
||||||
|
@Repository
|
||||||
|
public class DataStatisticsDao {
|
||||||
|
|
||||||
|
private final DatabaseClient databaseClient;
|
||||||
|
|
||||||
|
public DataStatisticsDao(DatabaseClient databaseClient) {
|
||||||
|
this.databaseClient = databaseClient;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计指定时间范围内新增会员数
|
||||||
|
*/
|
||||||
|
public Mono<Long> countNewMembers(LocalDateTime startTime, LocalDateTime endTime) {
|
||||||
|
return databaseClient.sql("SELECT COUNT(*) FROM member_user WHERE created_at >= :startTime AND created_at < :endTime AND is_deleted = false")
|
||||||
|
.bind("startTime", startTime)
|
||||||
|
.bind("endTime", endTime)
|
||||||
|
.map(row -> row.get(0, Long.class))
|
||||||
|
.one();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计总会员数
|
||||||
|
*/
|
||||||
|
public Mono<Long> countTotalMembers() {
|
||||||
|
return databaseClient.sql("SELECT COUNT(*) FROM member_user WHERE is_deleted = false")
|
||||||
|
.map(row -> row.get(0, Long.class))
|
||||||
|
.one();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计指定时间范围内的签到次数
|
||||||
|
*/
|
||||||
|
public Mono<Long> countSignIns(LocalDateTime startTime, LocalDateTime endTime) {
|
||||||
|
return databaseClient.sql("SELECT COUNT(*) FROM sign_in_record WHERE sign_in_time >= :startTime AND sign_in_time < :endTime AND is_delete = false")
|
||||||
|
.bind("startTime", startTime)
|
||||||
|
.bind("endTime", endTime)
|
||||||
|
.map(row -> row.get(0, Long.class))
|
||||||
|
.one();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计指定时间范围内的成功签到次数
|
||||||
|
*/
|
||||||
|
public Mono<Long> countSuccessSignIns(LocalDateTime startTime, LocalDateTime endTime) {
|
||||||
|
return databaseClient.sql("SELECT COUNT(*) FROM sign_in_record WHERE sign_in_time >= :startTime AND sign_in_time < :endTime AND sign_in_status = 'SUCCESS' AND is_delete = false")
|
||||||
|
.bind("startTime", startTime)
|
||||||
|
.bind("endTime", endTime)
|
||||||
|
.map(row -> row.get(0, Long.class))
|
||||||
|
.one();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计指定时间范围内签到的独立会员数
|
||||||
|
*/
|
||||||
|
public Mono<Long> countDistinctSignInMembers(LocalDateTime startTime, LocalDateTime endTime) {
|
||||||
|
return databaseClient.sql("SELECT COUNT(DISTINCT member_id) FROM sign_in_record WHERE sign_in_time >= :startTime AND sign_in_time < :endTime AND is_delete = false")
|
||||||
|
.bind("startTime", startTime)
|
||||||
|
.bind("endTime", endTime)
|
||||||
|
.map(row -> row.get(0, Long.class))
|
||||||
|
.one();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计指定时间范围内的预约数
|
||||||
|
*/
|
||||||
|
public Mono<Long> countBookings(LocalDateTime startTime, LocalDateTime endTime) {
|
||||||
|
return databaseClient.sql("SELECT COUNT(*) FROM group_course_booking WHERE booking_time >= :startTime AND booking_time < :endTime AND deleted_at IS NULL")
|
||||||
|
.bind("startTime", startTime)
|
||||||
|
.bind("endTime", endTime)
|
||||||
|
.map(row -> row.get(0, Long.class))
|
||||||
|
.one();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计指定时间范围内的取消预约数
|
||||||
|
*/
|
||||||
|
public Mono<Long> countCancelBookings(LocalDateTime startTime, LocalDateTime endTime) {
|
||||||
|
return databaseClient.sql("SELECT COUNT(*) FROM group_course_booking WHERE booking_time >= :startTime AND booking_time < :endTime AND status = '1' AND deleted_at IS NULL")
|
||||||
|
.bind("startTime", startTime)
|
||||||
|
.bind("endTime", endTime)
|
||||||
|
.map(row -> row.get(0, Long.class))
|
||||||
|
.one();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计指定时间范围内的出席预约数
|
||||||
|
*/
|
||||||
|
public Mono<Long> countAttendBookings(LocalDateTime startTime, LocalDateTime endTime) {
|
||||||
|
return databaseClient.sql("SELECT COUNT(*) FROM group_course_booking WHERE booking_time >= :startTime AND booking_time < :endTime AND status = '2' AND deleted_at IS NULL")
|
||||||
|
.bind("startTime", startTime)
|
||||||
|
.bind("endTime", endTime)
|
||||||
|
.map(row -> row.get(0, Long.class))
|
||||||
|
.one();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计指定时间范围内的缺席预约数
|
||||||
|
*/
|
||||||
|
public Mono<Long> countAbsentBookings(LocalDateTime startTime, LocalDateTime endTime) {
|
||||||
|
return databaseClient.sql("SELECT COUNT(*) FROM group_course_booking WHERE booking_time >= :startTime AND booking_time < :endTime AND status = '3' AND deleted_at IS NULL")
|
||||||
|
.bind("startTime", startTime)
|
||||||
|
.bind("endTime", endTime)
|
||||||
|
.map(row -> row.get(0, Long.class))
|
||||||
|
.one();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计指定时间范围内有预约的独立会员数
|
||||||
|
*/
|
||||||
|
public Mono<Long> countDistinctBookingMembers(LocalDateTime startTime, LocalDateTime endTime) {
|
||||||
|
return databaseClient.sql("SELECT COUNT(DISTINCT member_id) FROM group_course_booking WHERE booking_time >= :startTime AND booking_time < :endTime AND deleted_at IS NULL")
|
||||||
|
.bind("startTime", startTime)
|
||||||
|
.bind("endTime", endTime)
|
||||||
|
.map(row -> row.get(0, Long.class))
|
||||||
|
.one();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计指定时间范围内取消预约的独立会员数
|
||||||
|
*/
|
||||||
|
public Mono<Long> countDistinctCancelMembers(LocalDateTime startTime, LocalDateTime endTime) {
|
||||||
|
return databaseClient.sql("SELECT COUNT(DISTINCT member_id) FROM group_course_booking WHERE booking_time >= :startTime AND booking_time < :endTime AND status = '1' AND deleted_at IS NULL")
|
||||||
|
.bind("startTime", startTime)
|
||||||
|
.bind("endTime", endTime)
|
||||||
|
.map(row -> row.get(0, Long.class))
|
||||||
|
.one();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 按签到类型统计次数
|
||||||
|
*/
|
||||||
|
public Flux<SignInTypeCount> countSignInsByType(LocalDateTime startTime, LocalDateTime endTime) {
|
||||||
|
return databaseClient.sql("SELECT sign_in_type as type, COUNT(*) as count FROM sign_in_record WHERE sign_in_time >= :startTime AND sign_in_time < :endTime AND is_delete = false GROUP BY sign_in_type")
|
||||||
|
.bind("startTime", startTime)
|
||||||
|
.bind("endTime", endTime)
|
||||||
|
.map(row -> {
|
||||||
|
SignInTypeCount result = new SignInTypeCount();
|
||||||
|
result.setType(row.get("type", String.class));
|
||||||
|
result.setCount(row.get("count", Long.class));
|
||||||
|
return result;
|
||||||
|
})
|
||||||
|
.all();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签到类型计数结果
|
||||||
|
*/
|
||||||
|
public static class SignInTypeCount {
|
||||||
|
private String type;
|
||||||
|
private Long count;
|
||||||
|
|
||||||
|
public String getType() {
|
||||||
|
return type;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setType(String type) {
|
||||||
|
this.type = type;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getCount() {
|
||||||
|
return count;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCount(Long count) {
|
||||||
|
this.count = count;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ========== 教练相关统计 ==========
|
||||||
|
|
||||||
|
/** 统计教练总数(角色为"教练"的用户) */
|
||||||
|
public Mono<Long> countTotalCoaches() {
|
||||||
|
return databaseClient.sql("""
|
||||||
|
SELECT COUNT(*) FROM sys_user u
|
||||||
|
INNER JOIN user_role ur ON u.id = ur.user_id
|
||||||
|
INNER JOIN sys_role sr ON ur.role_id = sr.id
|
||||||
|
WHERE sr.role_name = '教练' AND u.deleted_at IS NULL
|
||||||
|
""")
|
||||||
|
.map(row -> row.get(0, Long.class))
|
||||||
|
.one();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 统计违规总数(时间范围) */
|
||||||
|
public Mono<Long> countTotalViolations(LocalDateTime startTime, LocalDateTime endTime) {
|
||||||
|
return databaseClient.sql("""
|
||||||
|
SELECT COUNT(*) FROM coach_violation
|
||||||
|
WHERE violation_time >= :startTime AND violation_time < :endTime AND deleted_at IS NULL
|
||||||
|
""")
|
||||||
|
.bind("startTime", startTime)
|
||||||
|
.bind("endTime", endTime)
|
||||||
|
.map(row -> row.get(0, Long.class))
|
||||||
|
.one();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 按违规类型统计次数 */
|
||||||
|
public Flux<Map<String, Object>> countViolationsByReason(LocalDateTime startTime, LocalDateTime endTime) {
|
||||||
|
return databaseClient.sql("""
|
||||||
|
SELECT violation_reason, COUNT(*) AS count
|
||||||
|
FROM coach_violation
|
||||||
|
WHERE violation_time >= :startTime AND violation_time < :endTime AND deleted_at IS NULL
|
||||||
|
GROUP BY violation_reason
|
||||||
|
""")
|
||||||
|
.bind("startTime", startTime)
|
||||||
|
.bind("endTime", endTime)
|
||||||
|
.fetch()
|
||||||
|
.all();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 统计有违规记录的教练数 */
|
||||||
|
public Mono<Long> countViolatedCoaches(LocalDateTime startTime, LocalDateTime endTime) {
|
||||||
|
return databaseClient.sql("""
|
||||||
|
SELECT COUNT(DISTINCT coach_id) FROM coach_violation
|
||||||
|
WHERE violation_time >= :startTime AND violation_time < :endTime AND deleted_at IS NULL
|
||||||
|
""")
|
||||||
|
.bind("startTime", startTime)
|
||||||
|
.bind("endTime", endTime)
|
||||||
|
.map(row -> row.get(0, Long.class))
|
||||||
|
.one();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 统计区间内开课的团课数 */
|
||||||
|
public Mono<Long> countCourses(LocalDateTime startTime, LocalDateTime endTime) {
|
||||||
|
return databaseClient.sql("""
|
||||||
|
SELECT COUNT(*) FROM group_course
|
||||||
|
WHERE start_time >= :startTime AND start_time < :endTime AND deleted_at IS NULL
|
||||||
|
""")
|
||||||
|
.bind("startTime", startTime)
|
||||||
|
.bind("endTime", endTime)
|
||||||
|
.map(row -> row.get(0, Long.class))
|
||||||
|
.one();
|
||||||
|
}
|
||||||
|
}
|
||||||
+64
@@ -0,0 +1,64 @@
|
|||||||
|
package cn.novalon.gym.manage.datacount.domain;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 预约数据统计结果
|
||||||
|
*
|
||||||
|
* @author system
|
||||||
|
* @date 2026-06-09
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class BookingStatistics {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计日期
|
||||||
|
*/
|
||||||
|
private String statDate;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 新增预约数
|
||||||
|
*/
|
||||||
|
private Long newBookings;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 取消预约数
|
||||||
|
*/
|
||||||
|
private Long cancelBookings;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 出席预约数
|
||||||
|
*/
|
||||||
|
private Long attendBookings;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 缺席预约数
|
||||||
|
*/
|
||||||
|
private Long absentBookings;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 预约出席率
|
||||||
|
*/
|
||||||
|
private Double attendanceRate;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 取消率
|
||||||
|
*/
|
||||||
|
private Double cancelRate;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 预约人数(独立会员数)
|
||||||
|
*/
|
||||||
|
private Long bookingMembers;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 取消人数(独立会员数)
|
||||||
|
*/
|
||||||
|
private Long cancelMembers;
|
||||||
|
}
|
||||||
+40
@@ -0,0 +1,40 @@
|
|||||||
|
package cn.novalon.gym.manage.datacount.domain;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 教练统计数据
|
||||||
|
*
|
||||||
|
* @author 张翔
|
||||||
|
* @date 2026-07-20
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class CoachStatistics {
|
||||||
|
|
||||||
|
/** 教练总数 */
|
||||||
|
private Long totalCoaches;
|
||||||
|
|
||||||
|
/** 违规总数 */
|
||||||
|
private Long totalViolations;
|
||||||
|
|
||||||
|
/** 迟到次数 */
|
||||||
|
private Long lateCount;
|
||||||
|
|
||||||
|
/** 缺席次数 */
|
||||||
|
private Long absentCount;
|
||||||
|
|
||||||
|
/** 未手动结课次数 */
|
||||||
|
private Long notManualEndCount;
|
||||||
|
|
||||||
|
/** 有违规记录的教练数 */
|
||||||
|
private Long violatedCoaches;
|
||||||
|
|
||||||
|
/** 统计区间内开课的团课数 */
|
||||||
|
private Long totalCourses;
|
||||||
|
}
|
||||||
+85
@@ -0,0 +1,85 @@
|
|||||||
|
package cn.novalon.gym.manage.datacount.domain;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 数据统计结果域对象
|
||||||
|
*
|
||||||
|
* @author system
|
||||||
|
* @date 2026-06-09
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class DataStatistics {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计类型:MEMBER-会员统计,BOOKING-预约统计,SIGN_IN-签到统计
|
||||||
|
*/
|
||||||
|
private String statType;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计周期:DAY-日统计,WEEK-周统计,MONTH-月统计
|
||||||
|
*/
|
||||||
|
private String periodType;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计日期(DAY时为具体日期,WEEK时为周开始日期,MONTH时为月份第一天)
|
||||||
|
*/
|
||||||
|
private LocalDateTime statDate;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计数据值
|
||||||
|
*/
|
||||||
|
private Long count;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 关联ID(如会员ID等)
|
||||||
|
*/
|
||||||
|
private Long relatedId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 扩展数据(JSON格式存储额外信息)
|
||||||
|
*/
|
||||||
|
private String extraData;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计周期常量
|
||||||
|
*/
|
||||||
|
public static final class PeriodType {
|
||||||
|
/** 日统计 */
|
||||||
|
public static final String DAY = "DAY";
|
||||||
|
/** 周统计 */
|
||||||
|
public static final String WEEK = "WEEK";
|
||||||
|
/** 月统计 */
|
||||||
|
public static final String MONTH = "MONTH";
|
||||||
|
/** 近30天 */
|
||||||
|
public static final String LAST_30_DAYS = "LAST_30_DAYS";
|
||||||
|
/** 近90天 */
|
||||||
|
public static final String LAST_90_DAYS = "LAST_90_DAYS";
|
||||||
|
/** 今年 */
|
||||||
|
public static final String YEAR = "YEAR";
|
||||||
|
|
||||||
|
private PeriodType() {}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计类型常量
|
||||||
|
*/
|
||||||
|
public static final class StatType {
|
||||||
|
/** 会员统计 */
|
||||||
|
public static final String MEMBER = "MEMBER";
|
||||||
|
/** 预约统计 */
|
||||||
|
public static final String BOOKING = "BOOKING";
|
||||||
|
/** 签到统计 */
|
||||||
|
public static final String SIGN_IN = "SIGN_IN";
|
||||||
|
|
||||||
|
private StatType() {}
|
||||||
|
}
|
||||||
|
}
|
||||||
+54
@@ -0,0 +1,54 @@
|
|||||||
|
package cn.novalon.gym.manage.datacount.domain;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 会员数据统计结果
|
||||||
|
*
|
||||||
|
* @author system
|
||||||
|
* @date 2026-06-09
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class MemberStatistics {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计日期
|
||||||
|
*/
|
||||||
|
private String statDate;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 新增会员数
|
||||||
|
*/
|
||||||
|
private Long newMembers;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 活跃会员数(当天有签到或预约的会员)
|
||||||
|
*/
|
||||||
|
private Long activeMembers;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 累计会员总数
|
||||||
|
*/
|
||||||
|
private Long totalMembers;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 今日签到会员数
|
||||||
|
*/
|
||||||
|
private Long signInMembers;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 今日预约会员数
|
||||||
|
*/
|
||||||
|
private Long bookingMembers;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 今日取消预约会员数
|
||||||
|
*/
|
||||||
|
private Long cancelBookingMembers;
|
||||||
|
}
|
||||||
+64
@@ -0,0 +1,64 @@
|
|||||||
|
package cn.novalon.gym.manage.datacount.domain;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签到数据统计结果
|
||||||
|
*
|
||||||
|
* @author system
|
||||||
|
* @date 2026-06-09
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class SignInStatistics {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计日期
|
||||||
|
*/
|
||||||
|
private String statDate;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签到总次数
|
||||||
|
*/
|
||||||
|
private Long totalSignIns;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 成功签到次数
|
||||||
|
*/
|
||||||
|
private Long successSignIns;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 失败签到次数
|
||||||
|
*/
|
||||||
|
private Long failedSignIns;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签到成功率
|
||||||
|
*/
|
||||||
|
private Double successRate;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签到人数(独立会员数)
|
||||||
|
*/
|
||||||
|
private Long signInMembers;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 扫码签到次数
|
||||||
|
*/
|
||||||
|
private Long qrCodeSignIns;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 手动签到次数
|
||||||
|
*/
|
||||||
|
private Long manualSignIns;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 人脸识别签到次数
|
||||||
|
*/
|
||||||
|
private Long faceSignIns;
|
||||||
|
}
|
||||||
+52
@@ -0,0 +1,52 @@
|
|||||||
|
package cn.novalon.gym.manage.datacount.domain;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计数据查询请求
|
||||||
|
*
|
||||||
|
* @author system
|
||||||
|
* @date 2026-06-09
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class StatisticsQuery {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计类型:MEMBER-会员统计,BOOKING-预约统计,SIGN_IN-签到统计
|
||||||
|
* 空表示所有类型
|
||||||
|
*/
|
||||||
|
private String statType;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计周期:DAY-日统计,WEEK-周统计,MONTH-月统计
|
||||||
|
*/
|
||||||
|
private String periodType;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 开始时间
|
||||||
|
*/
|
||||||
|
private LocalDateTime startTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 结束时间
|
||||||
|
*/
|
||||||
|
private LocalDateTime endTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 分页页码
|
||||||
|
*/
|
||||||
|
private Integer page;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 每页大小
|
||||||
|
*/
|
||||||
|
private Integer size;
|
||||||
|
}
|
||||||
+49
@@ -0,0 +1,49 @@
|
|||||||
|
package cn.novalon.gym.manage.datacount.domain;
|
||||||
|
|
||||||
|
import lombok.AllArgsConstructor;
|
||||||
|
import lombok.Builder;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.NoArgsConstructor;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计数据汇总
|
||||||
|
*
|
||||||
|
* @author system
|
||||||
|
* @date 2026-06-09
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Builder
|
||||||
|
@NoArgsConstructor
|
||||||
|
@AllArgsConstructor
|
||||||
|
public class StatisticsSummary {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计日期
|
||||||
|
*/
|
||||||
|
private String statDate;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 会员统计数据
|
||||||
|
*/
|
||||||
|
private MemberStatistics memberStatistics;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 预约统计数据
|
||||||
|
*/
|
||||||
|
private BookingStatistics bookingStatistics;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 签到统计数据
|
||||||
|
*/
|
||||||
|
private SignInStatistics signInStatistics;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 教练统计数据
|
||||||
|
*/
|
||||||
|
private CoachStatistics coachStatistics;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计数据生成时间
|
||||||
|
*/
|
||||||
|
private String generatedAt;
|
||||||
|
}
|
||||||
+125
@@ -0,0 +1,125 @@
|
|||||||
|
package cn.novalon.gym.manage.datacount.handler;
|
||||||
|
|
||||||
|
import cn.novalon.gym.manage.datacount.domain.*;
|
||||||
|
import cn.novalon.gym.manage.datacount.service.IDataStatisticsService;
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.http.HttpHeaders;
|
||||||
|
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.time.LocalDateTime;
|
||||||
|
import java.time.format.DateTimeFormatter;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 数据统计 Handler
|
||||||
|
*
|
||||||
|
* @author system
|
||||||
|
* @date 2026-06-09
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
@Tag(name = "数据统计", description = "数据统计相关操作")
|
||||||
|
public class DataStatisticsHandler {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private IDataStatisticsService dataStatisticsService;
|
||||||
|
|
||||||
|
@Operation(summary = "获取综合统计数据", description = "获取会员、预约、签到综合统计数据")
|
||||||
|
public Mono<ServerResponse> getStatisticsSummary(ServerRequest request) {
|
||||||
|
StatisticsQuery query = buildQueryFromRequest(request);
|
||||||
|
|
||||||
|
return dataStatisticsService.getStatisticsSummaryWithCache(query)
|
||||||
|
.flatMap(summary -> ServerResponse.ok().bodyValue(summary))
|
||||||
|
.onErrorResume(e -> {
|
||||||
|
StatisticsSummary errorSummary = StatisticsSummary.builder()
|
||||||
|
.statDate(LocalDateTime.now().toLocalDate().toString())
|
||||||
|
.generatedAt(LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME))
|
||||||
|
.build();
|
||||||
|
return ServerResponse.ok().bodyValue(errorSummary);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "获取会员统计数据", description = "获取会员统计数据")
|
||||||
|
public Mono<ServerResponse> getMemberStatistics(ServerRequest request) {
|
||||||
|
StatisticsQuery query = buildQueryFromRequest(request);
|
||||||
|
|
||||||
|
return dataStatisticsService.getMemberStatistics(query)
|
||||||
|
.flatMap(stats -> ServerResponse.ok().bodyValue(stats))
|
||||||
|
.onErrorResume(e -> ServerResponse.ok().bodyValue(MemberStatistics.builder().statDate(query.getStartTime() != null ? query.getStartTime().toLocalDate().toString() : LocalDateTime.now().toLocalDate().toString()).build()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "获取预约统计数据", description = "获取预约统计数据")
|
||||||
|
public Mono<ServerResponse> getBookingStatistics(ServerRequest request) {
|
||||||
|
StatisticsQuery query = buildQueryFromRequest(request);
|
||||||
|
|
||||||
|
return dataStatisticsService.getBookingStatistics(query)
|
||||||
|
.flatMap(stats -> ServerResponse.ok().bodyValue(stats))
|
||||||
|
.onErrorResume(e -> ServerResponse.ok().bodyValue(BookingStatistics.builder().statDate(query.getStartTime() != null ? query.getStartTime().toLocalDate().toString() : LocalDateTime.now().toLocalDate().toString()).build()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "获取签到统计数据", description = "获取签到统计数据")
|
||||||
|
public Mono<ServerResponse> getSignInStatistics(ServerRequest request) {
|
||||||
|
StatisticsQuery query = buildQueryFromRequest(request);
|
||||||
|
|
||||||
|
return dataStatisticsService.getSignInStatistics(query)
|
||||||
|
.flatMap(stats -> ServerResponse.ok().bodyValue(stats))
|
||||||
|
.onErrorResume(e -> ServerResponse.ok().bodyValue(SignInStatistics.builder().statDate(query.getStartTime() != null ? query.getStartTime().toLocalDate().toString() : LocalDateTime.now().toLocalDate().toString()).build()));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "查询历史统计数据", description = "查询历史统计数据")
|
||||||
|
public Mono<ServerResponse> queryHistoricalStatistics(ServerRequest request) {
|
||||||
|
StatisticsQuery query = buildQueryFromRequest(request);
|
||||||
|
|
||||||
|
return dataStatisticsService.queryHistoricalStatistics(query)
|
||||||
|
.collectList()
|
||||||
|
.flatMap(stats -> ServerResponse.ok().bodyValue(stats));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "导出统计数据", description = "导出统计数据为Excel文件")
|
||||||
|
public Mono<ServerResponse> exportStatistics(ServerRequest request) {
|
||||||
|
StatisticsQuery query = buildQueryFromRequest(request);
|
||||||
|
|
||||||
|
return dataStatisticsService.exportStatistics(query)
|
||||||
|
.flatMap(bytes -> {
|
||||||
|
String filename = "statistics_" + LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + ".xlsx";
|
||||||
|
return ServerResponse.ok()
|
||||||
|
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + filename + "\"")
|
||||||
|
.contentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
|
||||||
|
.bodyValue(bytes);
|
||||||
|
})
|
||||||
|
.onErrorResume(e -> ServerResponse.ok().bodyValue("导出失败: " + e.getMessage()));
|
||||||
|
}
|
||||||
|
|
||||||
|
private StatisticsQuery buildQueryFromRequest(ServerRequest request) {
|
||||||
|
StatisticsQuery.StatisticsQueryBuilder builder = StatisticsQuery.builder();
|
||||||
|
|
||||||
|
request.queryParam("statType").ifPresent(builder::statType);
|
||||||
|
request.queryParam("periodType").ifPresent(builder::periodType);
|
||||||
|
request.queryParam("startTime").ifPresent(startTimeStr -> {
|
||||||
|
try {
|
||||||
|
builder.startTime(LocalDateTime.parse(startTimeStr, DateTimeFormatter.ISO_LOCAL_DATE_TIME));
|
||||||
|
} catch (Exception e) {
|
||||||
|
try {
|
||||||
|
builder.startTime(LocalDateTime.parse(startTimeStr));
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
request.queryParam("endTime").ifPresent(endTimeStr -> {
|
||||||
|
try {
|
||||||
|
builder.endTime(LocalDateTime.parse(endTimeStr, DateTimeFormatter.ISO_LOCAL_DATE_TIME));
|
||||||
|
} catch (Exception e) {
|
||||||
|
try {
|
||||||
|
builder.endTime(LocalDateTime.parse(endTimeStr));
|
||||||
|
} catch (Exception ignored) {
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return builder.build();
|
||||||
|
}
|
||||||
|
}
|
||||||
+109
@@ -0,0 +1,109 @@
|
|||||||
|
package cn.novalon.gym.manage.datacount.scheduler;
|
||||||
|
|
||||||
|
import cn.novalon.gym.manage.datacount.domain.DataStatistics;
|
||||||
|
import cn.novalon.gym.manage.datacount.service.IDataStatisticsService;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.scheduling.annotation.Scheduled;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 数据统计定时任务
|
||||||
|
* 每日凌晨执行统计数据更新
|
||||||
|
*
|
||||||
|
* @author system
|
||||||
|
* @date 2026-06-09
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
public class DataStatisticsScheduler {
|
||||||
|
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(DataStatisticsScheduler.class);
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private IDataStatisticsService dataStatisticsService;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 每日凌晨2点执行前一天的日统计数据
|
||||||
|
* 使用cron表达式: 0 0 2 * * ?
|
||||||
|
*/
|
||||||
|
@Scheduled(cron = "0 0 2 * * ?")
|
||||||
|
public void executeDailyStatistics() {
|
||||||
|
LocalDate yesterday = LocalDate.now().minusDays(1);
|
||||||
|
log.info("Starting daily statistics task for date: {}", yesterday);
|
||||||
|
|
||||||
|
dataStatisticsService.executeDailyStatistics(yesterday)
|
||||||
|
.subscribe(
|
||||||
|
null,
|
||||||
|
error -> log.error("Daily statistics task failed for date: {}", yesterday, error),
|
||||||
|
() -> log.info("Daily statistics task completed for date: {}", yesterday)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 每周一凌晨3点执行上周的周统计数据
|
||||||
|
* 使用cron表达式: 0 0 3 ? * MON
|
||||||
|
*/
|
||||||
|
@Scheduled(cron = "0 0 3 ? * MON")
|
||||||
|
public void executeWeeklyStatistics() {
|
||||||
|
LocalDate lastWeek = LocalDate.now().minusWeeks(1);
|
||||||
|
log.info("Starting weekly statistics task for week of: {}", lastWeek);
|
||||||
|
|
||||||
|
// 执行上周每天的统计数据汇总
|
||||||
|
LocalDate weekStart = lastWeek.with(java.time.temporal.TemporalAdjusters.previousOrSame(java.time.DayOfWeek.MONDAY));
|
||||||
|
LocalDate weekEnd = lastWeek.with(java.time.temporal.TemporalAdjusters.nextOrSame(java.time.DayOfWeek.SUNDAY));
|
||||||
|
|
||||||
|
for (LocalDate date = weekStart; !date.isAfter(weekEnd); date = date.plusDays(1)) {
|
||||||
|
final LocalDate statDate = date;
|
||||||
|
dataStatisticsService.executeDailyStatistics(statDate)
|
||||||
|
.block();
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info("Weekly statistics task completed for week: {} - {}", weekStart, weekEnd);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 每月1日凌晨3点执行上个月的月统计数据
|
||||||
|
* 使用cron表达式: 0 0 3 1 * ?
|
||||||
|
*/
|
||||||
|
@Scheduled(cron = "0 0 3 1 * ?")
|
||||||
|
public void executeMonthlyStatistics() {
|
||||||
|
LocalDate lastMonth = LocalDate.now().minusMonths(1);
|
||||||
|
log.info("Starting monthly statistics task for month: {}", lastMonth.getMonth());
|
||||||
|
|
||||||
|
// 执行上个月每天的统计数据补全
|
||||||
|
LocalDate startOfMonth = lastMonth.withDayOfMonth(1);
|
||||||
|
LocalDate endOfMonth = lastMonth.with(java.time.temporal.TemporalAdjusters.lastDayOfMonth());
|
||||||
|
|
||||||
|
for (LocalDate date = startOfMonth; !date.isAfter(endOfMonth); date = date.plusDays(1)) {
|
||||||
|
final LocalDate statDate = date;
|
||||||
|
dataStatisticsService.executeDailyStatistics(statDate)
|
||||||
|
.block();
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info("Monthly statistics task completed for month: {}", lastMonth.getMonth());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 每月15日凌晨4点清理30天前的旧统计数据
|
||||||
|
* 使用cron表达式: 0 0 4 15 * ?
|
||||||
|
*/
|
||||||
|
@Scheduled(cron = "0 0 4 15 * ?")
|
||||||
|
public void cleanupOldStatistics() {
|
||||||
|
LocalDate cutoffDate = LocalDate.now().minusDays(30);
|
||||||
|
log.info("Starting cleanup old statistics task, removing data before: {}", cutoffDate);
|
||||||
|
|
||||||
|
// 清理Redis中的旧统计数据
|
||||||
|
String pattern = "datacount:statistics:*:" + cutoffDate.toString();
|
||||||
|
cn.novalon.gym.manage.common.util.RedisUtil redisUtil = null;
|
||||||
|
try {
|
||||||
|
// 这里可以通过注入的service来清理,但当前实现使用Redis缓存30天自动过期
|
||||||
|
log.info("Old statistics cleanup completed, cutoff date: {}", cutoffDate);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("Failed to cleanup old statistics", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+78
@@ -0,0 +1,78 @@
|
|||||||
|
package cn.novalon.gym.manage.datacount.service;
|
||||||
|
|
||||||
|
import cn.novalon.gym.manage.datacount.domain.*;
|
||||||
|
import reactor.core.publisher.Flux;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 数据统计服务接口
|
||||||
|
*
|
||||||
|
* @author system
|
||||||
|
* @date 2026-06-09
|
||||||
|
*/
|
||||||
|
public interface IDataStatisticsService {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取会员统计数据
|
||||||
|
*
|
||||||
|
* @param query 查询条件
|
||||||
|
* @return 会员统计数据
|
||||||
|
*/
|
||||||
|
Mono<MemberStatistics> getMemberStatistics(StatisticsQuery query);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取预约统计数据
|
||||||
|
*
|
||||||
|
* @param query 查询条件
|
||||||
|
* @return 预约统计数据
|
||||||
|
*/
|
||||||
|
Mono<BookingStatistics> getBookingStatistics(StatisticsQuery query);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取签到统计数据
|
||||||
|
*
|
||||||
|
* @param query 查询条件
|
||||||
|
* @return 签到统计数据
|
||||||
|
*/
|
||||||
|
Mono<SignInStatistics> getSignInStatistics(StatisticsQuery query);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取综合统计数据(包含会员、预约、签到)
|
||||||
|
*
|
||||||
|
* @param query 查询条件
|
||||||
|
* @return 综合统计数据
|
||||||
|
*/
|
||||||
|
Mono<StatisticsSummary> getStatisticsSummary(StatisticsQuery query);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询历史统计数据
|
||||||
|
*
|
||||||
|
* @param query 查询条件
|
||||||
|
* @return 历史统计数据列表
|
||||||
|
*/
|
||||||
|
Flux<DataStatistics> queryHistoricalStatistics(StatisticsQuery query);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 执行每日统计数据更新(定时任务调用)
|
||||||
|
*
|
||||||
|
* @param statDate 统计日期
|
||||||
|
* @return 更新结果
|
||||||
|
*/
|
||||||
|
Mono<Void> executeDailyStatistics(java.time.LocalDate statDate);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 导出统计数据为Excel
|
||||||
|
*
|
||||||
|
* @param query 查询条件
|
||||||
|
* @return Excel文件的字节数组
|
||||||
|
*/
|
||||||
|
Mono<byte[]> exportStatistics(StatisticsQuery query);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取统计数据(带缓存)
|
||||||
|
*
|
||||||
|
* @param query 查询条件
|
||||||
|
* @return 统计数据
|
||||||
|
*/
|
||||||
|
Mono<StatisticsSummary> getStatisticsSummaryWithCache(StatisticsQuery query);
|
||||||
|
}
|
||||||
+555
@@ -0,0 +1,555 @@
|
|||||||
|
package cn.novalon.gym.manage.datacount.service.impl;
|
||||||
|
|
||||||
|
import cn.novalon.gym.manage.checkIn.entity.SignInRecord;
|
||||||
|
import cn.novalon.gym.manage.common.util.RedisUtil;
|
||||||
|
import cn.novalon.gym.manage.datacount.dao.DataStatisticsDao;
|
||||||
|
import cn.novalon.gym.manage.datacount.domain.*;
|
||||||
|
import cn.novalon.gym.manage.datacount.service.IDataStatisticsService;
|
||||||
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||||
|
import org.apache.poi.ss.usermodel.*;
|
||||||
|
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
import java.io.ByteArrayOutputStream;
|
||||||
|
import java.time.DayOfWeek;
|
||||||
|
import java.time.Duration;
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.time.format.DateTimeFormatter;
|
||||||
|
import java.time.temporal.TemporalAdjusters;
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 数据统计服务实现类
|
||||||
|
*
|
||||||
|
* @author system
|
||||||
|
* @date 2026-06-09
|
||||||
|
*/
|
||||||
|
@Service
|
||||||
|
public class DataStatisticsServiceImpl implements IDataStatisticsService {
|
||||||
|
|
||||||
|
private static final Logger log = LoggerFactory.getLogger(DataStatisticsServiceImpl.class);
|
||||||
|
|
||||||
|
private static final String CACHE_KEY_PREFIX = "datacount:statistics:";
|
||||||
|
private static final long CACHE_EXPIRE_SECONDS = 3600; // 1小时
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private DataStatisticsDao dataStatisticsDao;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private RedisUtil redisUtil;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private ObjectMapper objectMapper;
|
||||||
|
|
||||||
|
@Value("${datacount.cache.expire-seconds:3600}")
|
||||||
|
private long cacheExpireSeconds = 3600;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Mono<MemberStatistics> getMemberStatistics(StatisticsQuery query) {
|
||||||
|
LocalDateTime startTime = getStartTime(query);
|
||||||
|
LocalDateTime endTime = getEndTime(query);
|
||||||
|
|
||||||
|
Mono<Long> newMembersMono = dataStatisticsDao.countNewMembers(startTime, endTime);
|
||||||
|
Mono<Long> totalMembersMono = dataStatisticsDao.countTotalMembers();
|
||||||
|
Mono<Long> signInMembersMono = dataStatisticsDao.countDistinctSignInMembers(startTime, endTime);
|
||||||
|
Mono<Long> bookingMembersMono = dataStatisticsDao.countDistinctBookingMembers(startTime, endTime);
|
||||||
|
Mono<Long> cancelMembersMono = dataStatisticsDao.countDistinctCancelMembers(startTime, endTime);
|
||||||
|
|
||||||
|
return Mono.zip(newMembersMono, totalMembersMono, signInMembersMono, bookingMembersMono, cancelMembersMono)
|
||||||
|
.map(tuple -> {
|
||||||
|
long newMembers = tuple.getT1() != null ? tuple.getT1() : 0L;
|
||||||
|
long totalMembers = tuple.getT2() != null ? tuple.getT2() : 0L;
|
||||||
|
long signInMembers = tuple.getT3() != null ? tuple.getT3() : 0L;
|
||||||
|
long bookingMembers = tuple.getT4() != null ? tuple.getT4() : 0L;
|
||||||
|
long cancelMembers = tuple.getT5() != null ? tuple.getT5() : 0L;
|
||||||
|
|
||||||
|
// 活跃会员数 = 有签到的 + 有预约的(去重后大概值)
|
||||||
|
long activeMembers = signInMembers + bookingMembers;
|
||||||
|
|
||||||
|
return MemberStatistics.builder()
|
||||||
|
.statDate(startTime.toLocalDate().toString())
|
||||||
|
.newMembers(newMembers)
|
||||||
|
.activeMembers(activeMembers)
|
||||||
|
.totalMembers(totalMembers)
|
||||||
|
.signInMembers(signInMembers)
|
||||||
|
.bookingMembers(bookingMembers)
|
||||||
|
.cancelBookingMembers(cancelMembers)
|
||||||
|
.build();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Mono<BookingStatistics> getBookingStatistics(StatisticsQuery query) {
|
||||||
|
LocalDateTime startTime = getStartTime(query);
|
||||||
|
LocalDateTime endTime = getEndTime(query);
|
||||||
|
|
||||||
|
Mono<Long> totalMono = dataStatisticsDao.countBookings(startTime, endTime);
|
||||||
|
Mono<Long> cancelMono = dataStatisticsDao.countCancelBookings(startTime, endTime);
|
||||||
|
Mono<Long> attendMono = dataStatisticsDao.countAttendBookings(startTime, endTime);
|
||||||
|
Mono<Long> absentMono = dataStatisticsDao.countAbsentBookings(startTime, endTime);
|
||||||
|
Mono<Long> bookingMembersMono = dataStatisticsDao.countDistinctBookingMembers(startTime, endTime);
|
||||||
|
Mono<Long> cancelMembersMono = dataStatisticsDao.countDistinctCancelMembers(startTime, endTime);
|
||||||
|
|
||||||
|
return Mono.zip(totalMono, cancelMono, attendMono, absentMono, bookingMembersMono, cancelMembersMono)
|
||||||
|
.map(tuple -> {
|
||||||
|
long total = tuple.getT1() != null ? tuple.getT1() : 0L;
|
||||||
|
long cancel = tuple.getT2() != null ? tuple.getT2() : 0L;
|
||||||
|
long attend = tuple.getT3() != null ? tuple.getT3() : 0L;
|
||||||
|
long absent = tuple.getT4() != null ? tuple.getT4() : 0L;
|
||||||
|
long bookingMembers = tuple.getT5() != null ? tuple.getT5() : 0L;
|
||||||
|
long cancelMembers = tuple.getT6() != null ? tuple.getT6() : 0L;
|
||||||
|
|
||||||
|
double attendanceRate = total > 0 ? (double) attend / total * 100 : 0;
|
||||||
|
double cancelRate = total > 0 ? (double) cancel / total * 100 : 0;
|
||||||
|
|
||||||
|
return BookingStatistics.builder()
|
||||||
|
.statDate(startTime.toLocalDate().toString())
|
||||||
|
.newBookings(total)
|
||||||
|
.cancelBookings(cancel)
|
||||||
|
.attendBookings(attend)
|
||||||
|
.absentBookings(absent)
|
||||||
|
.attendanceRate(Math.round(attendanceRate * 100.0) / 100.0)
|
||||||
|
.cancelRate(Math.round(cancelRate * 100.0) / 100.0)
|
||||||
|
.bookingMembers(bookingMembers)
|
||||||
|
.cancelMembers(cancelMembers)
|
||||||
|
.build();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Mono<SignInStatistics> getSignInStatistics(StatisticsQuery query) {
|
||||||
|
LocalDateTime startTime = getStartTime(query);
|
||||||
|
LocalDateTime endTime = getEndTime(query);
|
||||||
|
|
||||||
|
Mono<Long> totalMono = dataStatisticsDao.countSignIns(startTime, endTime);
|
||||||
|
Mono<Long> successMono = dataStatisticsDao.countSuccessSignIns(startTime, endTime);
|
||||||
|
Mono<Long> distinctMembersMono = dataStatisticsDao.countDistinctSignInMembers(startTime, endTime);
|
||||||
|
|
||||||
|
return Mono.zip(totalMono, successMono, distinctMembersMono)
|
||||||
|
.flatMap(tuple -> {
|
||||||
|
long total = tuple.getT1() != null ? tuple.getT1() : 0L;
|
||||||
|
long success = tuple.getT2() != null ? tuple.getT2() : 0L;
|
||||||
|
long distinctMembers = tuple.getT3() != null ? tuple.getT3() : 0L;
|
||||||
|
|
||||||
|
double successRate = total > 0 ? (double) success / total * 100 : 0;
|
||||||
|
|
||||||
|
return dataStatisticsDao.countSignInsByType(startTime, endTime)
|
||||||
|
.collectMap(
|
||||||
|
DataStatisticsDao.SignInTypeCount::getType,
|
||||||
|
DataStatisticsDao.SignInTypeCount::getCount
|
||||||
|
)
|
||||||
|
.defaultIfEmpty(new HashMap<>())
|
||||||
|
.map(typeCountMap -> {
|
||||||
|
long qrCode = getCountByType(typeCountMap, SignInRecord.SignInType.QR_CODE);
|
||||||
|
long manual = getCountByType(typeCountMap, SignInRecord.SignInType.MANUAL);
|
||||||
|
long face = getCountByType(typeCountMap, SignInRecord.SignInType.FACE);
|
||||||
|
|
||||||
|
return SignInStatistics.builder()
|
||||||
|
.statDate(startTime.toLocalDate().toString())
|
||||||
|
.totalSignIns(total)
|
||||||
|
.successSignIns(success)
|
||||||
|
.failedSignIns(total - success)
|
||||||
|
.successRate(Math.round(successRate * 100.0) / 100.0)
|
||||||
|
.signInMembers(distinctMembers)
|
||||||
|
.qrCodeSignIns(qrCode)
|
||||||
|
.manualSignIns(manual)
|
||||||
|
.faceSignIns(face)
|
||||||
|
.build();
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private long getCountByType(Map<String, Long> typeCountMap, String type) {
|
||||||
|
Long count = typeCountMap.get(type);
|
||||||
|
return count != null ? count : 0L;
|
||||||
|
}
|
||||||
|
|
||||||
|
private Mono<CoachStatistics> getCoachStatistics(StatisticsQuery query) {
|
||||||
|
LocalDateTime startTime = getStartTime(query);
|
||||||
|
LocalDateTime endTime = getEndTime(query);
|
||||||
|
|
||||||
|
Mono<Long> totalCoachesMono = dataStatisticsDao.countTotalCoaches();
|
||||||
|
Mono<Long> totalViolationsMono = dataStatisticsDao.countTotalViolations(startTime, endTime);
|
||||||
|
Mono<Long> violatedCoachesMono = dataStatisticsDao.countViolatedCoaches(startTime, endTime);
|
||||||
|
Mono<Long> totalCoursesMono = dataStatisticsDao.countCourses(startTime, endTime);
|
||||||
|
Mono<Map<String, Long>> violationByReasonMono = dataStatisticsDao.countViolationsByReason(startTime, endTime)
|
||||||
|
.collectMap(row -> (String) row.get("violation_reason"),
|
||||||
|
row -> ((Number) row.get("count")).longValue());
|
||||||
|
|
||||||
|
return Mono.zip(totalCoachesMono, totalViolationsMono, violatedCoachesMono, totalCoursesMono, violationByReasonMono)
|
||||||
|
.map(tuple -> {
|
||||||
|
Map<String, Long> reasonMap = tuple.getT5();
|
||||||
|
return CoachStatistics.builder()
|
||||||
|
.totalCoaches(tuple.getT1())
|
||||||
|
.totalViolations(tuple.getT2())
|
||||||
|
.lateCount(reasonMap.getOrDefault("COACH_LATE", 0L))
|
||||||
|
.absentCount(reasonMap.getOrDefault("COACH_ABSENT", 0L))
|
||||||
|
.notManualEndCount(reasonMap.getOrDefault("NOT_MANUAL_END", 0L))
|
||||||
|
.violatedCoaches(tuple.getT3())
|
||||||
|
.totalCourses(tuple.getT4())
|
||||||
|
.build();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Mono<StatisticsSummary> getStatisticsSummary(StatisticsQuery query) {
|
||||||
|
Mono<MemberStatistics> memberStatsMono = getMemberStatistics(query);
|
||||||
|
Mono<BookingStatistics> bookingStatsMono = getBookingStatistics(query);
|
||||||
|
Mono<SignInStatistics> signInStatsMono = getSignInStatistics(query);
|
||||||
|
Mono<CoachStatistics> coachStatsMono = getCoachStatistics(query);
|
||||||
|
|
||||||
|
return Mono.zip(memberStatsMono, bookingStatsMono, signInStatsMono, coachStatsMono)
|
||||||
|
.map(tuple -> StatisticsSummary.builder()
|
||||||
|
.statDate(LocalDateTime.now().toLocalDate().toString())
|
||||||
|
.memberStatistics(tuple.getT1())
|
||||||
|
.bookingStatistics(tuple.getT2())
|
||||||
|
.signInStatistics(tuple.getT3())
|
||||||
|
.coachStatistics(tuple.getT4())
|
||||||
|
.generatedAt(LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME))
|
||||||
|
.build());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public reactor.core.publisher.Flux<DataStatistics> queryHistoricalStatistics(StatisticsQuery query) {
|
||||||
|
// 历史统计数据查询(从Redis缓存中获取)
|
||||||
|
String cacheKey = buildCacheKey(query);
|
||||||
|
return redisUtil.get(cacheKey, String.class)
|
||||||
|
.flatMapMany(json -> {
|
||||||
|
try {
|
||||||
|
java.util.List<DataStatistics> stats = objectMapper.readValue(json,
|
||||||
|
objectMapper.getTypeFactory().constructCollectionType(java.util.List.class, DataStatistics.class));
|
||||||
|
return reactor.core.publisher.Flux.fromIterable(stats);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("Failed to parse historical statistics from cache", e);
|
||||||
|
return reactor.core.publisher.Flux.empty();
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.switchIfEmpty(reactor.core.publisher.Flux.empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Mono<Void> executeDailyStatistics(LocalDate statDate) {
|
||||||
|
log.info("Executing daily statistics for date: {}", statDate);
|
||||||
|
|
||||||
|
LocalDateTime dayStart = statDate.atStartOfDay();
|
||||||
|
LocalDateTime dayEnd = statDate.plusDays(1).atStartOfDay();
|
||||||
|
|
||||||
|
StatisticsQuery query = StatisticsQuery.builder()
|
||||||
|
.startTime(dayStart)
|
||||||
|
.endTime(dayEnd)
|
||||||
|
.build();
|
||||||
|
|
||||||
|
Mono<MemberStatistics> memberStatsMono = getMemberStatistics(query);
|
||||||
|
Mono<BookingStatistics> bookingStatsMono = getBookingStatistics(query);
|
||||||
|
Mono<SignInStatistics> signInStatsMono = getSignInStatistics(query);
|
||||||
|
|
||||||
|
return Mono.zip(memberStatsMono, bookingStatsMono, signInStatsMono)
|
||||||
|
.flatMap(tuple -> {
|
||||||
|
MemberStatistics memberStats = tuple.getT1();
|
||||||
|
BookingStatistics bookingStats = tuple.getT2();
|
||||||
|
SignInStatistics signInStats = tuple.getT3();
|
||||||
|
|
||||||
|
String dateStr = statDate.toString();
|
||||||
|
String memberKey = CACHE_KEY_PREFIX + "member:" + dateStr;
|
||||||
|
String bookingKey = CACHE_KEY_PREFIX + "booking:" + dateStr;
|
||||||
|
String signInKey = CACHE_KEY_PREFIX + "signin:" + dateStr;
|
||||||
|
|
||||||
|
try {
|
||||||
|
String memberJson = objectMapper.writeValueAsString(memberStats);
|
||||||
|
String bookingJson = objectMapper.writeValueAsString(bookingStats);
|
||||||
|
String signInJson = objectMapper.writeValueAsString(signInStats);
|
||||||
|
|
||||||
|
return reactor.core.publisher.Flux.merge(
|
||||||
|
redisUtil.setWithExpire(memberKey, memberJson, Duration.ofDays(30).getSeconds()),
|
||||||
|
redisUtil.setWithExpire(bookingKey, bookingJson, Duration.ofDays(30).getSeconds()),
|
||||||
|
redisUtil.setWithExpire(signInKey, signInJson, Duration.ofDays(30).getSeconds())
|
||||||
|
).then();
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("Failed to serialize statistics data", e);
|
||||||
|
return Mono.empty();
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.then()
|
||||||
|
.doOnSuccess(v -> log.info("Daily statistics completed for date: {}", statDate))
|
||||||
|
.doOnError(e -> log.error("Failed to execute daily statistics for date: {}", statDate, e));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Mono<byte[]> exportStatistics(StatisticsQuery query) {
|
||||||
|
return getStatisticsSummary(query)
|
||||||
|
.flatMap(summary -> {
|
||||||
|
try (Workbook workbook = new XSSFWorkbook()) {
|
||||||
|
Sheet sheet = workbook.createSheet("数据统计报表");
|
||||||
|
|
||||||
|
CellStyle headerStyle = workbook.createCellStyle();
|
||||||
|
Font headerFont = workbook.createFont();
|
||||||
|
headerFont.setBold(true);
|
||||||
|
headerStyle.setFont(headerFont);
|
||||||
|
|
||||||
|
createMainSheet(sheet, summary, headerStyle);
|
||||||
|
|
||||||
|
Sheet memberSheet = workbook.createSheet("会员统计");
|
||||||
|
createMemberStatisticsSheet(memberSheet, summary.getMemberStatistics(), headerStyle);
|
||||||
|
|
||||||
|
Sheet bookingSheet = workbook.createSheet("预约统计");
|
||||||
|
createBookingStatisticsSheet(bookingSheet, summary.getBookingStatistics(), headerStyle);
|
||||||
|
|
||||||
|
Sheet signInSheet = workbook.createSheet("签到统计");
|
||||||
|
createSignInStatisticsSheet(signInSheet, summary.getSignInStatistics(), headerStyle);
|
||||||
|
|
||||||
|
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
|
||||||
|
workbook.write(outputStream);
|
||||||
|
return Mono.just(outputStream.toByteArray());
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("Failed to export statistics", e);
|
||||||
|
return Mono.error(e);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private void createMainSheet(Sheet sheet, StatisticsSummary summary, CellStyle headerStyle) {
|
||||||
|
int rowNum = 0;
|
||||||
|
Row row = sheet.createRow(rowNum++);
|
||||||
|
row.createCell(0).setCellValue("统计项");
|
||||||
|
row.createCell(1).setCellValue("数值");
|
||||||
|
|
||||||
|
row = sheet.createRow(rowNum++);
|
||||||
|
row.createCell(0).setCellValue("统计日期");
|
||||||
|
row.createCell(1).setCellValue(summary.getStatDate());
|
||||||
|
|
||||||
|
row = sheet.createRow(rowNum++);
|
||||||
|
row.createCell(0).setCellValue("新增会员数");
|
||||||
|
row.createCell(1).setCellValue(summary.getMemberStatistics().getNewMembers());
|
||||||
|
|
||||||
|
row = sheet.createRow(rowNum++);
|
||||||
|
row.createCell(0).setCellValue("活跃会员数");
|
||||||
|
row.createCell(1).setCellValue(summary.getMemberStatistics().getActiveMembers());
|
||||||
|
|
||||||
|
row = sheet.createRow(rowNum++);
|
||||||
|
row.createCell(0).setCellValue("累计会员总数");
|
||||||
|
row.createCell(1).setCellValue(summary.getMemberStatistics().getTotalMembers());
|
||||||
|
|
||||||
|
row = sheet.createRow(rowNum++);
|
||||||
|
row.createCell(0).setCellValue("新增预约数");
|
||||||
|
row.createCell(1).setCellValue(summary.getBookingStatistics().getNewBookings());
|
||||||
|
|
||||||
|
row = sheet.createRow(rowNum++);
|
||||||
|
row.createCell(0).setCellValue("预约出席率");
|
||||||
|
row.createCell(1).setCellValue(summary.getBookingStatistics().getAttendanceRate() + "%");
|
||||||
|
|
||||||
|
row = sheet.createRow(rowNum++);
|
||||||
|
row.createCell(0).setCellValue("签到总次数");
|
||||||
|
row.createCell(1).setCellValue(summary.getSignInStatistics().getTotalSignIns());
|
||||||
|
|
||||||
|
row = sheet.createRow(rowNum++);
|
||||||
|
row.createCell(0).setCellValue("签到成功率");
|
||||||
|
row.createCell(1).setCellValue(summary.getSignInStatistics().getSuccessRate() + "%");
|
||||||
|
|
||||||
|
sheet.autoSizeColumn(0);
|
||||||
|
sheet.autoSizeColumn(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void createMemberStatisticsSheet(Sheet sheet, MemberStatistics stats, CellStyle headerStyle) {
|
||||||
|
int rowNum = 0;
|
||||||
|
Row row = sheet.createRow(rowNum++);
|
||||||
|
row.createCell(0).setCellValue("统计项");
|
||||||
|
row.createCell(1).setCellValue("数值");
|
||||||
|
|
||||||
|
String[][] data = {
|
||||||
|
{"统计日期", stats.getStatDate()},
|
||||||
|
{"新增会员数", String.valueOf(stats.getNewMembers())},
|
||||||
|
{"活跃会员数", String.valueOf(stats.getActiveMembers())},
|
||||||
|
{"累计会员总数", String.valueOf(stats.getTotalMembers())},
|
||||||
|
{"今日签到会员数", String.valueOf(stats.getSignInMembers())},
|
||||||
|
{"今日预约会员数", String.valueOf(stats.getBookingMembers())},
|
||||||
|
{"今日取消预约会员数", String.valueOf(stats.getCancelBookingMembers())}
|
||||||
|
};
|
||||||
|
|
||||||
|
for (String[] rowData : data) {
|
||||||
|
row = sheet.createRow(rowNum++);
|
||||||
|
row.createCell(0).setCellValue(rowData[0]);
|
||||||
|
row.createCell(1).setCellValue(rowData[1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
sheet.autoSizeColumn(0);
|
||||||
|
sheet.autoSizeColumn(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void createBookingStatisticsSheet(Sheet sheet, BookingStatistics stats, CellStyle headerStyle) {
|
||||||
|
int rowNum = 0;
|
||||||
|
Row row = sheet.createRow(rowNum++);
|
||||||
|
row.createCell(0).setCellValue("统计项");
|
||||||
|
row.createCell(1).setCellValue("数值");
|
||||||
|
|
||||||
|
String[][] data = {
|
||||||
|
{"统计日期", stats.getStatDate()},
|
||||||
|
{"新增预约数", String.valueOf(stats.getNewBookings())},
|
||||||
|
{"取消预约数", String.valueOf(stats.getCancelBookings())},
|
||||||
|
{"出席预约数", String.valueOf(stats.getAttendBookings())},
|
||||||
|
{"缺席预约数", String.valueOf(stats.getAbsentBookings())},
|
||||||
|
{"预约出席率", stats.getAttendanceRate() + "%"},
|
||||||
|
{"取消率", stats.getCancelRate() + "%"},
|
||||||
|
{"预约人数", String.valueOf(stats.getBookingMembers())},
|
||||||
|
{"取消人数", String.valueOf(stats.getCancelMembers())}
|
||||||
|
};
|
||||||
|
|
||||||
|
for (String[] rowData : data) {
|
||||||
|
row = sheet.createRow(rowNum++);
|
||||||
|
row.createCell(0).setCellValue(rowData[0]);
|
||||||
|
row.createCell(1).setCellValue(rowData[1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
sheet.autoSizeColumn(0);
|
||||||
|
sheet.autoSizeColumn(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
private void createSignInStatisticsSheet(Sheet sheet, SignInStatistics stats, CellStyle headerStyle) {
|
||||||
|
int rowNum = 0;
|
||||||
|
Row row = sheet.createRow(rowNum++);
|
||||||
|
row.createCell(0).setCellValue("统计项");
|
||||||
|
row.createCell(1).setCellValue("数值");
|
||||||
|
|
||||||
|
String[][] data = {
|
||||||
|
{"统计日期", stats.getStatDate()},
|
||||||
|
{"签到总次数", String.valueOf(stats.getTotalSignIns())},
|
||||||
|
{"成功签到次数", String.valueOf(stats.getSuccessSignIns())},
|
||||||
|
{"失败签到次数", String.valueOf(stats.getFailedSignIns())},
|
||||||
|
{"签到成功率", stats.getSuccessRate() + "%"},
|
||||||
|
{"签到人数", String.valueOf(stats.getSignInMembers())},
|
||||||
|
{"扫码签到次数", String.valueOf(stats.getQrCodeSignIns())},
|
||||||
|
{"手动签到次数", String.valueOf(stats.getManualSignIns())},
|
||||||
|
{"人脸识别签到次数", String.valueOf(stats.getFaceSignIns())}
|
||||||
|
};
|
||||||
|
|
||||||
|
for (String[] rowData : data) {
|
||||||
|
row = sheet.createRow(rowNum++);
|
||||||
|
row.createCell(0).setCellValue(rowData[0]);
|
||||||
|
row.createCell(1).setCellValue(rowData[1]);
|
||||||
|
}
|
||||||
|
|
||||||
|
sheet.autoSizeColumn(0);
|
||||||
|
sheet.autoSizeColumn(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Mono<StatisticsSummary> getStatisticsSummaryWithCache(StatisticsQuery query) {
|
||||||
|
String cacheKey = buildCacheKey(query);
|
||||||
|
|
||||||
|
return redisUtil.get(cacheKey, StatisticsSummary.class)
|
||||||
|
.switchIfEmpty(
|
||||||
|
getStatisticsSummary(query)
|
||||||
|
.flatMap(summary -> {
|
||||||
|
try {
|
||||||
|
String json = objectMapper.writeValueAsString(summary);
|
||||||
|
return redisUtil.setWithExpire(cacheKey, json, cacheExpireSeconds)
|
||||||
|
.thenReturn(summary);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("Failed to serialize statistics summary", e);
|
||||||
|
return Mono.just(summary);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
private String buildCacheKey(StatisticsQuery query) {
|
||||||
|
StringBuilder keyBuilder = new StringBuilder(CACHE_KEY_PREFIX);
|
||||||
|
keyBuilder.append("summary:");
|
||||||
|
|
||||||
|
if (query.getStartTime() != null) {
|
||||||
|
keyBuilder.append(query.getStartTime().toLocalDate().toString());
|
||||||
|
}
|
||||||
|
if (query.getEndTime() != null) {
|
||||||
|
keyBuilder.append("_").append(query.getEndTime().toLocalDate().toString());
|
||||||
|
}
|
||||||
|
if (query.getStatType() != null) {
|
||||||
|
keyBuilder.append("_").append(query.getStatType());
|
||||||
|
}
|
||||||
|
if (query.getPeriodType() != null) {
|
||||||
|
keyBuilder.append("_").append(query.getPeriodType());
|
||||||
|
}
|
||||||
|
|
||||||
|
return keyBuilder.toString();
|
||||||
|
}
|
||||||
|
|
||||||
|
private LocalDateTime getStartTime(StatisticsQuery query) {
|
||||||
|
if (query.getStartTime() != null) {
|
||||||
|
return query.getStartTime();
|
||||||
|
}
|
||||||
|
|
||||||
|
LocalDate today = LocalDate.now();
|
||||||
|
String periodType = query.getPeriodType();
|
||||||
|
|
||||||
|
if (DataStatistics.PeriodType.WEEK.equals(periodType)) {
|
||||||
|
return today.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)).atStartOfDay();
|
||||||
|
} else if (DataStatistics.PeriodType.MONTH.equals(periodType)) {
|
||||||
|
return today.withDayOfMonth(1).atStartOfDay();
|
||||||
|
} else if (DataStatistics.PeriodType.LAST_30_DAYS.equals(periodType)) {
|
||||||
|
return today.minusDays(29).atStartOfDay();
|
||||||
|
} else if (DataStatistics.PeriodType.LAST_90_DAYS.equals(periodType)) {
|
||||||
|
return today.minusDays(89).atStartOfDay();
|
||||||
|
} else if (DataStatistics.PeriodType.YEAR.equals(periodType)) {
|
||||||
|
return today.withDayOfYear(1).atStartOfDay();
|
||||||
|
} else {
|
||||||
|
return today.atStartOfDay();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private LocalDateTime getEndTime(StatisticsQuery query) {
|
||||||
|
if (query.getEndTime() != null) {
|
||||||
|
return query.getEndTime();
|
||||||
|
}
|
||||||
|
|
||||||
|
LocalDate today = LocalDate.now();
|
||||||
|
String periodType = query.getPeriodType();
|
||||||
|
|
||||||
|
if (DataStatistics.PeriodType.WEEK.equals(periodType)) {
|
||||||
|
return today.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY)).atTime(23, 59, 59);
|
||||||
|
} else if (DataStatistics.PeriodType.MONTH.equals(periodType)) {
|
||||||
|
return today.with(TemporalAdjusters.lastDayOfMonth()).atTime(23, 59, 59);
|
||||||
|
} else if (DataStatistics.PeriodType.LAST_30_DAYS.equals(periodType)
|
||||||
|
|| DataStatistics.PeriodType.LAST_90_DAYS.equals(periodType)
|
||||||
|
|| DataStatistics.PeriodType.YEAR.equals(periodType)) {
|
||||||
|
return LocalDateTime.now();
|
||||||
|
} else {
|
||||||
|
return LocalDateTime.now();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据周期类型调整时间范围
|
||||||
|
* 用于定时任务中的周期统计
|
||||||
|
*/
|
||||||
|
private LocalDateTime[] adjustTimeRangeByPeriod(LocalDate date, String periodType) {
|
||||||
|
LocalDateTime startTime;
|
||||||
|
LocalDateTime endTime;
|
||||||
|
|
||||||
|
if (DataStatistics.PeriodType.WEEK.equals(periodType)) {
|
||||||
|
startTime = date.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY)).atStartOfDay();
|
||||||
|
endTime = date.with(TemporalAdjusters.nextOrSame(DayOfWeek.SUNDAY)).atTime(23, 59, 59);
|
||||||
|
} else if (DataStatistics.PeriodType.MONTH.equals(periodType)) {
|
||||||
|
startTime = date.withDayOfMonth(1).atStartOfDay();
|
||||||
|
endTime = date.with(TemporalAdjusters.lastDayOfMonth()).atTime(23, 59, 59);
|
||||||
|
} else if (DataStatistics.PeriodType.LAST_30_DAYS.equals(periodType)) {
|
||||||
|
startTime = date.minusDays(29).atStartOfDay();
|
||||||
|
endTime = date.atTime(23, 59, 59);
|
||||||
|
} else if (DataStatistics.PeriodType.LAST_90_DAYS.equals(periodType)) {
|
||||||
|
startTime = date.minusDays(89).atStartOfDay();
|
||||||
|
endTime = date.atTime(23, 59, 59);
|
||||||
|
} else if (DataStatistics.PeriodType.YEAR.equals(periodType)) {
|
||||||
|
startTime = date.withDayOfYear(1).atStartOfDay();
|
||||||
|
endTime = date.atTime(23, 59, 59);
|
||||||
|
} else {
|
||||||
|
startTime = date.atStartOfDay();
|
||||||
|
endTime = date.plusDays(1).atStartOfDay();
|
||||||
|
}
|
||||||
|
|
||||||
|
return new LocalDateTime[]{startTime, endTime};
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
@@ -0,0 +1 @@
|
|||||||
|
cn.novalon.gym.manage.datacount.config.DataCountAutoConfiguration
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
wrapperVersion=3.3.4
|
||||||
|
distributionType=only-script
|
||||||
|
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.15/apache-maven-3.9.15-bin.zip
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
<?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-groupCourse</artifactId>
|
||||||
|
<version>1.0.0</version>
|
||||||
|
<name>gym-groupCourse</name>
|
||||||
|
<description>Group Course 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-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>
|
||||||
|
|
||||||
|
|
||||||
|
<!-- Redis依赖-->
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-starter-data-redis</artifactId>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- 会员模块依赖 -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>cn.novalon.gym.manage</groupId>
|
||||||
|
<artifactId>gym-member</artifactId>
|
||||||
|
<version>${project.version}</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
|
<!-- ZXing QR Code依赖 -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.google.zxing</groupId>
|
||||||
|
<artifactId>core</artifactId>
|
||||||
|
<version>3.5.3</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.google.zxing</groupId>
|
||||||
|
<artifactId>javase</artifactId>
|
||||||
|
<version>3.5.3</version>
|
||||||
|
</dependency>
|
||||||
|
<!-- 阿里云OSS SDK -->
|
||||||
|
<!--
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.aliyun.oss</groupId>
|
||||||
|
<artifactId>aliyun-sdk-oss</artifactId>
|
||||||
|
<version>3.17.4</version>
|
||||||
|
</dependency>
|
||||||
|
-->
|
||||||
|
|
||||||
|
<!-- 文件管理模块(统一文件存储) -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>cn.novalon.gym.manage</groupId>
|
||||||
|
<artifactId>manage-file</artifactId>
|
||||||
|
<version>${project.version}</version>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
|
||||||
|
<build>
|
||||||
|
<plugins>
|
||||||
|
<plugin>
|
||||||
|
<groupId>org.apache.maven.plugins</groupId>
|
||||||
|
<artifactId>maven-jar-plugin</artifactId>
|
||||||
|
<version>3.4.2</version>
|
||||||
|
</plugin>
|
||||||
|
</plugins>
|
||||||
|
</build>
|
||||||
|
|
||||||
|
</project>
|
||||||
+158
@@ -0,0 +1,158 @@
|
|||||||
|
|
||||||
|
package cn.novalon.gym.manage.groupcourse.converter;
|
||||||
|
|
||||||
|
import cn.hutool.core.bean.BeanUtil;
|
||||||
|
import cn.novalon.gym.manage.groupcourse.domain.GroupCourse;
|
||||||
|
import cn.novalon.gym.manage.groupcourse.domain.GroupCourseBooking;
|
||||||
|
import cn.novalon.gym.manage.groupcourse.domain.GroupCourseType;
|
||||||
|
import cn.novalon.gym.manage.groupcourse.entity.GroupCourseBookingEntity;
|
||||||
|
import cn.novalon.gym.manage.groupcourse.entity.GroupCourseEntity;
|
||||||
|
import cn.novalon.gym.manage.groupcourse.entity.GroupCourseTypeEntity;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 团课相关转换器
|
||||||
|
*
|
||||||
|
* @author 张翔
|
||||||
|
* @date 2026-06-01
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
@Slf4j
|
||||||
|
public class GroupCourseConverter {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将团课实体转换为领域模型
|
||||||
|
*/
|
||||||
|
public GroupCourse toDomain(GroupCourseEntity entity){
|
||||||
|
if(entity == null){
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
GroupCourse groupCourse = new GroupCourse();
|
||||||
|
BeanUtil.copyProperties(entity,groupCourse);
|
||||||
|
log.info("转换bean,entity-domain:",groupCourse);
|
||||||
|
return groupCourse;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将团课领域模型转换为实体
|
||||||
|
*/
|
||||||
|
public GroupCourseEntity toEntity(GroupCourse domain){
|
||||||
|
if(domain == null){
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
GroupCourseEntity entity = new GroupCourseEntity();
|
||||||
|
BeanUtil.copyProperties(domain,entity);
|
||||||
|
log.info("转换bean,domain-entity:",entity);
|
||||||
|
return entity;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将团课实体列表转换为领域模型列表
|
||||||
|
*/
|
||||||
|
public List<GroupCourse> toDomainList(List<GroupCourseEntity> entities){
|
||||||
|
if (entities == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return entities.stream()
|
||||||
|
.map(this::toDomain)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将团课领域模型列表转换为实体列表
|
||||||
|
*/
|
||||||
|
public List<GroupCourseEntity> toEntityList(List<GroupCourse> domains){
|
||||||
|
if (domains == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return domains.stream()
|
||||||
|
.map(this::toEntity)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将团课预约实体转换为领域模型
|
||||||
|
*/
|
||||||
|
public GroupCourseBooking toBookingDomain(GroupCourseBookingEntity entity){
|
||||||
|
if(entity == null){
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
GroupCourseBooking booking = new GroupCourseBooking();
|
||||||
|
BeanUtil.copyProperties(entity, booking);
|
||||||
|
log.debug("转换预约记录实体到领域模型:bookingId={}", entity.getId());
|
||||||
|
return booking;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将团课预约领域模型转换为实体
|
||||||
|
*/
|
||||||
|
public GroupCourseBookingEntity toBookingEntity(GroupCourseBooking domain){
|
||||||
|
if(domain == null){
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
GroupCourseBookingEntity entity = new GroupCourseBookingEntity();
|
||||||
|
BeanUtil.copyProperties(domain, entity);
|
||||||
|
if (domain.getId() != null) {
|
||||||
|
entity.markNotNew();
|
||||||
|
}
|
||||||
|
log.debug("转换预约记录领域模型到实体:bookingId={}", domain.getId());
|
||||||
|
return entity;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将团课预约实体列表转换为领域模型列表
|
||||||
|
*/
|
||||||
|
public List<GroupCourseBooking> toBookingDomainList(List<GroupCourseBookingEntity> entities){
|
||||||
|
if (entities == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return entities.stream()
|
||||||
|
.map(this::toBookingDomain)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将团课预约领域模型列表转换为实体列表
|
||||||
|
*/
|
||||||
|
public List<GroupCourseBookingEntity> toBookingEntityList(List<GroupCourseBooking> domains){
|
||||||
|
if (domains == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return domains.stream()
|
||||||
|
.map(this::toBookingEntity)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将团课类型实体转换为领域模型
|
||||||
|
*/
|
||||||
|
public GroupCourseType toGroupCourseType(GroupCourseTypeEntity entity){
|
||||||
|
if(entity == null){
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
GroupCourseType groupCourseType = new GroupCourseType();
|
||||||
|
BeanUtil.copyProperties(entity, groupCourseType);
|
||||||
|
log.debug("转换团课类型实体到领域模型:typeId={}", entity.getId());
|
||||||
|
return groupCourseType;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将团课类型领域模型转换为实体
|
||||||
|
*/
|
||||||
|
public GroupCourseTypeEntity toGroupCourseTypeEntity(GroupCourseType domain){
|
||||||
|
if(domain == null){
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
GroupCourseTypeEntity entity = new GroupCourseTypeEntity();
|
||||||
|
BeanUtil.copyProperties(domain, entity);
|
||||||
|
if (domain.getId() != null) {
|
||||||
|
entity.markNotNew();
|
||||||
|
}
|
||||||
|
log.debug("转换团课类型领域模型到实体:typeId={}", domain.getId());
|
||||||
|
return entity;
|
||||||
|
}
|
||||||
|
}
|
||||||
+27
@@ -0,0 +1,27 @@
|
|||||||
|
package cn.novalon.gym.manage.groupcourse.dao;
|
||||||
|
|
||||||
|
import cn.novalon.gym.manage.groupcourse.entity.CourseLabelEntity;
|
||||||
|
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 CourseLabelDao extends R2dbcRepository<CourseLabelEntity, Long> {
|
||||||
|
|
||||||
|
Mono<CourseLabelEntity> findByIdIsAndDeletedAtIsNull(Long id);
|
||||||
|
|
||||||
|
Flux<CourseLabelEntity> findAllByDeletedAtIsNull();
|
||||||
|
|
||||||
|
Flux<CourseLabelEntity> findByLabelNameContainingAndDeletedAtIsNull(String labelName);
|
||||||
|
|
||||||
|
Mono<CourseLabelEntity> findByLabelNameAndDeletedAtIsNull(String labelName);
|
||||||
|
|
||||||
|
@Modifying
|
||||||
|
@Query("UPDATE course_label SET deleted_at = :deletedAt WHERE id = :id")
|
||||||
|
Mono<Integer> softDelete(Long id, LocalDateTime deletedAt);
|
||||||
|
}
|
||||||
+38
@@ -0,0 +1,38 @@
|
|||||||
|
package cn.novalon.gym.manage.groupcourse.dao;
|
||||||
|
|
||||||
|
import cn.novalon.gym.manage.groupcourse.entity.CourseTypeLabelEntity;
|
||||||
|
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;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Repository
|
||||||
|
public interface CourseTypeLabelDao extends R2dbcRepository<CourseTypeLabelEntity, Long> {
|
||||||
|
|
||||||
|
Flux<CourseTypeLabelEntity> findByTypeIdAndDeletedAtIsNull(Long typeId);
|
||||||
|
|
||||||
|
Flux<CourseTypeLabelEntity> findByLabelIdAndDeletedAtIsNull(Long labelId);
|
||||||
|
|
||||||
|
Mono<CourseTypeLabelEntity> findByTypeIdAndLabelIdAndDeletedAtIsNull(Long typeId, Long labelId);
|
||||||
|
|
||||||
|
@Modifying
|
||||||
|
@Query("UPDATE course_type_label SET deleted_at = :deletedAt WHERE type_id = :typeId AND label_id = :labelId")
|
||||||
|
Mono<Integer> deleteByTypeIdAndLabelId(Long typeId, Long labelId, LocalDateTime deletedAt);
|
||||||
|
|
||||||
|
@Modifying
|
||||||
|
@Query("UPDATE course_type_label SET deleted_at = :deletedAt WHERE type_id = :typeId")
|
||||||
|
Mono<Integer> deleteByTypeId(Long typeId, LocalDateTime deletedAt);
|
||||||
|
|
||||||
|
@Modifying
|
||||||
|
@Query("DELETE FROM course_type_label WHERE type_id = :typeId AND label_id = :labelId")
|
||||||
|
Mono<Integer> physicalDeleteByTypeIdAndLabelId(Long typeId, Long labelId);
|
||||||
|
|
||||||
|
@Modifying
|
||||||
|
@Query("UPDATE course_type_label SET deleted_at = :deletedAt WHERE label_id = :labelId")
|
||||||
|
Mono<Integer> deleteByLabelId(Long labelId, LocalDateTime deletedAt);
|
||||||
|
}
|
||||||
+124
@@ -0,0 +1,124 @@
|
|||||||
|
package cn.novalon.gym.manage.groupcourse.dao;
|
||||||
|
|
||||||
|
import cn.novalon.gym.manage.groupcourse.entity.GroupCourseBookingEntity;
|
||||||
|
import org.springframework.data.domain.Sort;
|
||||||
|
import org.springframework.data.r2dbc.repository.R2dbcRepository;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
import reactor.core.publisher.Flux;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 团课预约记录DAO接口
|
||||||
|
*
|
||||||
|
* @author 张翔
|
||||||
|
* @date 2026-06-01
|
||||||
|
*/
|
||||||
|
@Repository
|
||||||
|
public interface GroupCourseBookingDao extends R2dbcRepository<GroupCourseBookingEntity, Long> {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据ID查询未删除的预约记录
|
||||||
|
*/
|
||||||
|
Mono<GroupCourseBookingEntity> findByIdIsAndDeletedAtIsNull(Long id);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据会员ID查询所有预约记录
|
||||||
|
*/
|
||||||
|
Flux<GroupCourseBookingEntity> findByMemberIdAndDeletedAtIsNull(Long memberId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据会员ID查询所有预约记录(带排序)
|
||||||
|
*/
|
||||||
|
Flux<GroupCourseBookingEntity> findByMemberIdAndDeletedAtIsNull(Long memberId, Sort sort);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据团课ID查询所有预约记录
|
||||||
|
*/
|
||||||
|
Flux<GroupCourseBookingEntity> findByCourseIdAndDeletedAtIsNull(Long courseId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据团课ID和会员ID查询预约记录
|
||||||
|
*/
|
||||||
|
Mono<GroupCourseBookingEntity> findByCourseIdAndMemberIdAndDeletedAtIsNull(Long courseId, Long memberId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据团课ID和状态查询预约记录
|
||||||
|
*/
|
||||||
|
Flux<GroupCourseBookingEntity> findByCourseIdAndStatusAndDeletedAtIsNull(Long courseId, String status);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询会员在指定课程的有效预约(状态为已预约且未取消)
|
||||||
|
*/
|
||||||
|
Mono<GroupCourseBookingEntity> findByCourseIdAndMemberIdAndStatusAndDeletedAtIsNull(Long courseId, Long memberId, String status);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据会员卡记录ID查询预约记录
|
||||||
|
*/
|
||||||
|
Flux<GroupCourseBookingEntity> findByMemberCardRecordIdAndDeletedAtIsNull(Long memberCardRecordId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计团课已预约人数
|
||||||
|
*/
|
||||||
|
Mono<Long> countByCourseIdAndStatusAndDeletedAtIsNull(Long courseId, String status);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计会员取消的预约次数
|
||||||
|
*/
|
||||||
|
@org.springframework.data.r2dbc.repository.Query("SELECT COUNT(*) FROM group_course_booking WHERE member_id = :memberId AND status = '1' AND deleted_at IS NULL")
|
||||||
|
Mono<Long> countCancelledByMemberId(Long memberId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询会员是否有时间冲突的预约(状态为已预约且未取消)
|
||||||
|
* 时间冲突条件:新课程的开始时间 < 已预约课程的结束时间 且 新课程的结束时间 > 已预约课程的开始时间
|
||||||
|
*/
|
||||||
|
@org.springframework.data.r2dbc.repository.Query("SELECT * FROM group_course_booking b " +
|
||||||
|
"JOIN group_course c ON b.course_id = c.id " +
|
||||||
|
"WHERE b.member_id = :memberId " +
|
||||||
|
"AND b.status = '0' " +
|
||||||
|
"AND b.deleted_at IS NULL " +
|
||||||
|
"AND c.deleted_at IS NULL " +
|
||||||
|
"AND :newStartTime < c.end_time " +
|
||||||
|
"AND :newEndTime > c.start_time")
|
||||||
|
Flux<GroupCourseBookingEntity> findConflictingBookings(Long memberId, java.time.LocalDateTime newStartTime, java.time.LocalDateTime newEndTime);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 更新预约状态
|
||||||
|
*/
|
||||||
|
@org.springframework.data.r2dbc.repository.Modifying
|
||||||
|
@org.springframework.data.r2dbc.repository.Query("UPDATE group_course_booking SET status = :status, cancel_time = :cancelTime, updated_at = :updatedAt WHERE id = :id AND deleted_at IS NULL")
|
||||||
|
Mono<Integer> updateStatus(Long id, String status, java.time.LocalDateTime cancelTime, java.time.LocalDateTime updatedAt);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 软删除预约记录
|
||||||
|
*/
|
||||||
|
@org.springframework.data.r2dbc.repository.Modifying
|
||||||
|
@org.springframework.data.r2dbc.repository.Query("UPDATE group_course_booking SET deleted_at = :deletedAt WHERE id = :id")
|
||||||
|
Mono<Integer> softDelete(Long id, java.time.LocalDateTime deletedAt);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询已开始课程但未到场会员的预约记录
|
||||||
|
* 条件:课程开始时间早于当前时间,预约状态为已预约(0)
|
||||||
|
*/
|
||||||
|
@org.springframework.data.r2dbc.repository.Query("SELECT b.* FROM group_course_booking b " +
|
||||||
|
"JOIN group_course c ON b.course_id = c.id " +
|
||||||
|
"WHERE b.status = '0' " +
|
||||||
|
"AND b.deleted_at IS NULL " +
|
||||||
|
"AND c.deleted_at IS NULL " +
|
||||||
|
"AND c.status = '0' " +
|
||||||
|
"AND c.start_time < CURRENT_TIMESTAMP")
|
||||||
|
Flux<GroupCourseBookingEntity> findAbsentMembers();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 批量更新预约状态为缺席
|
||||||
|
*/
|
||||||
|
@org.springframework.data.r2dbc.repository.Modifying
|
||||||
|
@org.springframework.data.r2dbc.repository.Query("UPDATE group_course_booking SET status = '3', updated_at = :updatedAt WHERE id = :id AND deleted_at IS NULL")
|
||||||
|
Mono<Integer> updateToAbsent(Long id, java.time.LocalDateTime updatedAt);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 批量更新某课程的预约状态(教练缺席场景)
|
||||||
|
*/
|
||||||
|
@org.springframework.data.r2dbc.repository.Modifying
|
||||||
|
@org.springframework.data.r2dbc.repository.Query("UPDATE group_course_booking SET status = :newStatus, updated_at = NOW() WHERE course_id = :courseId AND status = :oldStatus AND deleted_at IS NULL")
|
||||||
|
Mono<Integer> updateStatusByCourseId(Long courseId, String oldStatus, String newStatus);
|
||||||
|
}
|
||||||
+377
@@ -0,0 +1,377 @@
|
|||||||
|
package cn.novalon.gym.manage.groupcourse.dao;
|
||||||
|
|
||||||
|
import cn.novalon.gym.manage.common.dto.PageRequest;
|
||||||
|
import cn.novalon.gym.manage.groupcourse.dto.GroupCourseQueryDto;
|
||||||
|
import cn.novalon.gym.manage.groupcourse.entity.GroupCourseEntity;
|
||||||
|
import org.springframework.data.domain.Sort;
|
||||||
|
import org.springframework.data.r2dbc.repository.Modifying;
|
||||||
|
import org.springframework.data.r2dbc.repository.Query;
|
||||||
|
import org.springframework.data.r2dbc.repository.R2dbcRepository;
|
||||||
|
import org.springframework.r2dbc.core.DatabaseClient;
|
||||||
|
import org.springframework.stereotype.Repository;
|
||||||
|
import reactor.core.publisher.Flux;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Repository
|
||||||
|
public interface GroupCourseDao extends R2dbcRepository<GroupCourseEntity, Long> {
|
||||||
|
|
||||||
|
Mono<GroupCourseEntity> findByIdIsAndDeletedAtIsNull(Long id);
|
||||||
|
|
||||||
|
Flux<GroupCourseEntity> findAll();
|
||||||
|
|
||||||
|
Flux<GroupCourseEntity> findAll(Sort sort);
|
||||||
|
|
||||||
|
Flux<GroupCourseEntity> findAllByDeletedAtIsNull();
|
||||||
|
|
||||||
|
Flux<GroupCourseEntity> findAllByDeletedAtIsNull(Sort sort);
|
||||||
|
|
||||||
|
@Modifying
|
||||||
|
@Query("UPDATE group_course SET status = '1', updated_at = :updatedAt WHERE id = :id AND deleted_at IS NULL")
|
||||||
|
Mono<Integer> cancelCourse(Long id, LocalDateTime updatedAt);
|
||||||
|
|
||||||
|
@Modifying
|
||||||
|
@Query("UPDATE group_course SET deleted_at = :deletedAt WHERE id = :id")
|
||||||
|
Mono<Integer> softDelete(Long id, LocalDateTime deletedAt);
|
||||||
|
|
||||||
|
// ---------- 教练相关 SQL 方法 ----------
|
||||||
|
|
||||||
|
@Modifying
|
||||||
|
@Query("UPDATE group_course SET status = :status, actual_start_time = :actualStartTime, updated_at = :updatedAt WHERE id = :id AND deleted_at IS NULL")
|
||||||
|
Mono<Integer> updateStartInfo(Long id, String status, LocalDateTime actualStartTime, LocalDateTime updatedAt);
|
||||||
|
|
||||||
|
@Modifying
|
||||||
|
@Query("UPDATE group_course SET status = :status, actual_end_time = :actualEndTime, updated_at = :updatedAt WHERE id = :id AND deleted_at IS NULL")
|
||||||
|
Mono<Integer> updateEndInfo(Long id, String status, LocalDateTime actualEndTime, LocalDateTime updatedAt);
|
||||||
|
|
||||||
|
@Modifying
|
||||||
|
@Query("UPDATE group_course SET status = '5', actual_end_time = :actualEndTime, updated_at = :updatedAt WHERE id = :id AND deleted_at IS NULL")
|
||||||
|
Mono<Integer> updateToCoachAbsent(Long id, LocalDateTime actualEndTime, LocalDateTime updatedAt);
|
||||||
|
|
||||||
|
@Modifying
|
||||||
|
@Query("UPDATE group_course SET status = '6', actual_end_time = :actualEndTime, updated_at = :updatedAt WHERE id = :id AND deleted_at IS NULL")
|
||||||
|
Mono<Integer> updateToAutoEnded(Long id, LocalDateTime actualEndTime, LocalDateTime updatedAt);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询指定状态且开始时间早于指定时间的课程(用于缺席检查)
|
||||||
|
*/
|
||||||
|
default Flux<GroupCourseEntity> findByStatusAndStartTimeBefore(DatabaseClient databaseClient, String status, LocalDateTime time) {
|
||||||
|
return databaseClient.sql("SELECT * FROM group_course WHERE status = :status AND start_time < :time AND deleted_at IS NULL")
|
||||||
|
.bind("status", status)
|
||||||
|
.bind("time", time)
|
||||||
|
.map((row, meta) -> mapRowToEntity(row))
|
||||||
|
.all();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询指定状态集合且结束时间早于指定时间的课程(用于自动结课检查)
|
||||||
|
*/
|
||||||
|
default Flux<GroupCourseEntity> findByStatusInAndEndTimeBefore(DatabaseClient databaseClient, String[] statuses, LocalDateTime time) {
|
||||||
|
return databaseClient.sql("SELECT * FROM group_course WHERE status = ANY(:statuses::varchar[]) AND end_time < :time AND deleted_at IS NULL")
|
||||||
|
.bind("statuses", statuses)
|
||||||
|
.bind("time", time)
|
||||||
|
.map((row, meta) -> mapRowToEntity(row))
|
||||||
|
.all();
|
||||||
|
}
|
||||||
|
|
||||||
|
Flux<GroupCourseEntity> findByCourseTypeAndDeletedAtIsNull(Long courseType);
|
||||||
|
|
||||||
|
// ==================== 教练相关查询 ====================
|
||||||
|
|
||||||
|
Flux<GroupCourseEntity> findByCoachIdAndDeletedAtIsNull(Long coachId);
|
||||||
|
|
||||||
|
Flux<GroupCourseEntity> findByCoachIdAndDeletedAtIsNull(Long coachId, Sort sort);
|
||||||
|
|
||||||
|
@Query("SELECT COUNT(*) FROM group_course WHERE coach_id = :coachId AND status = :status AND deleted_at IS NULL")
|
||||||
|
Mono<Long> countByCoachIdAndStatus(Long coachId, String status);
|
||||||
|
|
||||||
|
@Modifying
|
||||||
|
@Query("UPDATE group_course SET status = '1', updated_at = :updatedAt WHERE coach_id = :coachId AND status != :excludeStatus AND deleted_at IS NULL")
|
||||||
|
Mono<Integer> cancelCoursesByCoachIdExceptStatus(Long coachId, String excludeStatus, LocalDateTime updatedAt);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 多条件查询团课(使用 DatabaseClient 构建动态 SQL)
|
||||||
|
*/
|
||||||
|
default Flux<GroupCourseEntity> searchGroupCourses(DatabaseClient databaseClient, GroupCourseQueryDto query) {
|
||||||
|
StringBuilder sql = new StringBuilder(
|
||||||
|
"SELECT gc.*, COALESCE(b.cnt, 0) AS current_members " +
|
||||||
|
"FROM group_course gc " +
|
||||||
|
"LEFT JOIN (SELECT course_id, COUNT(*) AS cnt FROM group_course_booking WHERE status = '0' GROUP BY course_id) b " +
|
||||||
|
"ON gc.id = b.course_id " +
|
||||||
|
"WHERE gc.deleted_at IS NULL");
|
||||||
|
List<String> conditions = new ArrayList<>();
|
||||||
|
|
||||||
|
// 默认不查询可预约团课(status = '0' 且未过期)
|
||||||
|
conditions.add("gc.status = '0'");
|
||||||
|
conditions.add("gc.end_time > NOW()");
|
||||||
|
|
||||||
|
// 1. 团课名称模糊查询
|
||||||
|
if (query.getCourseName() != null && !query.getCourseName().isEmpty()) {
|
||||||
|
conditions.add("gc.course_name ILIKE :courseName");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 基于团课类型查询
|
||||||
|
if (query.getCourseType() != null) {
|
||||||
|
conditions.add("gc.course_type = :courseType");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 3. 基于日期时间段查询
|
||||||
|
if (query.getStartDate() != null) {
|
||||||
|
conditions.add("gc.start_time >= :startDate");
|
||||||
|
}
|
||||||
|
if (query.getEndDate() != null) {
|
||||||
|
conditions.add("gc.start_time <= :endDate");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. 基于早晨/下午/夜晚时间段查询
|
||||||
|
if (query.getTimePeriod() != null && !query.getTimePeriod().isEmpty()) {
|
||||||
|
switch (query.getTimePeriod().toLowerCase()) {
|
||||||
|
case "morning":
|
||||||
|
conditions.add("EXTRACT(HOUR FROM gc.start_time) >= 6 AND EXTRACT(HOUR FROM gc.start_time) < 12");
|
||||||
|
break;
|
||||||
|
case "afternoon":
|
||||||
|
conditions.add("EXTRACT(HOUR FROM gc.start_time) >= 12 AND EXTRACT(HOUR FROM gc.start_time) < 18");
|
||||||
|
break;
|
||||||
|
case "evening":
|
||||||
|
conditions.add("EXTRACT(HOUR FROM gc.start_time) >= 18 AND EXTRACT(HOUR FROM gc.start_time) < 24");
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sql.append(" AND ").append(String.join(" AND ", conditions));
|
||||||
|
|
||||||
|
// 5. 价格排序 / 6. 剩余名额最多排序
|
||||||
|
boolean hasPriceSort = query.getPriceSort() != null && !query.getPriceSort().isEmpty();
|
||||||
|
boolean hasRemainingMost = query.getRemainingMost() != null && query.getRemainingMost();
|
||||||
|
|
||||||
|
if (hasPriceSort || hasRemainingMost) {
|
||||||
|
sql.append(" ORDER BY");
|
||||||
|
List<String> orderClauses = new ArrayList<>();
|
||||||
|
|
||||||
|
if (hasRemainingMost) {
|
||||||
|
orderClauses.add(" (gc.max_members - COALESCE(b.cnt, 0)) DESC");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (hasPriceSort) {
|
||||||
|
if ("asc".equalsIgnoreCase(query.getPriceSort())) {
|
||||||
|
orderClauses.add(" gc.stored_value_amount ASC");
|
||||||
|
} else if ("desc".equalsIgnoreCase(query.getPriceSort())) {
|
||||||
|
orderClauses.add(" gc.stored_value_amount DESC");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sql.append(String.join(",", orderClauses));
|
||||||
|
} else {
|
||||||
|
sql.append(" ORDER BY gc.start_time ASC");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 分页
|
||||||
|
int page = query.getPage() != null ? query.getPage() : 0;
|
||||||
|
int size = query.getSize() != null ? query.getSize() : 10;
|
||||||
|
if (size < 1) size = 10;
|
||||||
|
if (size > 100) size = 100;
|
||||||
|
int offset = page * size;
|
||||||
|
sql.append(" LIMIT :limit OFFSET :offset");
|
||||||
|
|
||||||
|
DatabaseClient.GenericExecuteSpec spec = databaseClient.sql(sql.toString());
|
||||||
|
|
||||||
|
if (query.getCourseName() != null && !query.getCourseName().isEmpty()) {
|
||||||
|
spec = spec.bind("courseName", "%" + query.getCourseName() + "%");
|
||||||
|
}
|
||||||
|
if (query.getCourseType() != null) {
|
||||||
|
spec = spec.bind("courseType", query.getCourseType());
|
||||||
|
}
|
||||||
|
if (query.getStartDate() != null) {
|
||||||
|
spec = spec.bind("startDate", query.getStartDate());
|
||||||
|
}
|
||||||
|
if (query.getEndDate() != null) {
|
||||||
|
spec = spec.bind("endDate", query.getEndDate());
|
||||||
|
}
|
||||||
|
spec = spec.bind("limit", size);
|
||||||
|
spec = spec.bind("offset", offset);
|
||||||
|
|
||||||
|
return spec.map((row, meta) -> mapRowToEntity(row)).all();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 多条件查询团课总数
|
||||||
|
*/
|
||||||
|
default Mono<Long> countSearchGroupCourses(DatabaseClient databaseClient, GroupCourseQueryDto query) {
|
||||||
|
StringBuilder sql = new StringBuilder("SELECT COUNT(*) FROM group_course WHERE deleted_at IS NULL");
|
||||||
|
List<String> conditions = new ArrayList<>();
|
||||||
|
|
||||||
|
conditions.add("status = '0'");
|
||||||
|
conditions.add("end_time > NOW()");
|
||||||
|
|
||||||
|
if (query.getCourseName() != null && !query.getCourseName().isEmpty()) {
|
||||||
|
conditions.add("course_name ILIKE :courseName");
|
||||||
|
}
|
||||||
|
if (query.getCourseType() != null) {
|
||||||
|
conditions.add("course_type = :courseType");
|
||||||
|
}
|
||||||
|
if (query.getStartDate() != null) {
|
||||||
|
conditions.add("start_time >= :startDate");
|
||||||
|
}
|
||||||
|
if (query.getEndDate() != null) {
|
||||||
|
conditions.add("start_time <= :endDate");
|
||||||
|
}
|
||||||
|
if (query.getTimePeriod() != null && !query.getTimePeriod().isEmpty()) {
|
||||||
|
switch (query.getTimePeriod().toLowerCase()) {
|
||||||
|
case "morning":
|
||||||
|
conditions.add("EXTRACT(HOUR FROM start_time) >= 6 AND EXTRACT(HOUR FROM start_time) < 12");
|
||||||
|
break;
|
||||||
|
case "afternoon":
|
||||||
|
conditions.add("EXTRACT(HOUR FROM start_time) >= 12 AND EXTRACT(HOUR FROM start_time) < 18");
|
||||||
|
break;
|
||||||
|
case "evening":
|
||||||
|
conditions.add("EXTRACT(HOUR FROM start_time) >= 18 AND EXTRACT(HOUR FROM start_time) < 24");
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
sql.append(" AND ").append(String.join(" AND ", conditions));
|
||||||
|
|
||||||
|
DatabaseClient.GenericExecuteSpec spec = databaseClient.sql(sql.toString());
|
||||||
|
|
||||||
|
if (query.getCourseName() != null && !query.getCourseName().isEmpty()) {
|
||||||
|
spec = spec.bind("courseName", "%" + query.getCourseName() + "%");
|
||||||
|
}
|
||||||
|
if (query.getCourseType() != null) {
|
||||||
|
spec = spec.bind("courseType", query.getCourseType());
|
||||||
|
}
|
||||||
|
if (query.getStartDate() != null) {
|
||||||
|
spec = spec.bind("startDate", query.getStartDate());
|
||||||
|
}
|
||||||
|
if (query.getEndDate() != null) {
|
||||||
|
spec = spec.bind("endDate", query.getEndDate());
|
||||||
|
}
|
||||||
|
|
||||||
|
return spec.map((row, meta) -> row.get(0, Long.class)).one();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 分页查询团课(支持 keyword 和 status 过滤)
|
||||||
|
*/
|
||||||
|
default Flux<GroupCourseEntity> findByPageFiltered(DatabaseClient databaseClient, PageRequest pageRequest) {
|
||||||
|
StringBuilder sql = new StringBuilder(
|
||||||
|
"SELECT gc.*, COALESCE(b.cnt, 0) AS current_members " +
|
||||||
|
"FROM group_course gc " +
|
||||||
|
"LEFT JOIN (SELECT course_id, COUNT(*) AS cnt FROM group_course_booking WHERE status = '0' GROUP BY course_id) b " +
|
||||||
|
"ON gc.id = b.course_id " +
|
||||||
|
"WHERE gc.deleted_at IS NULL");
|
||||||
|
List<String> conditions = new ArrayList<>();
|
||||||
|
|
||||||
|
if (pageRequest.getKeyword() != null && !pageRequest.getKeyword().isEmpty()) {
|
||||||
|
conditions.add("gc.course_name ILIKE :keyword");
|
||||||
|
}
|
||||||
|
if (pageRequest.getStatus() != null && !pageRequest.getStatus().isEmpty()) {
|
||||||
|
conditions.add("gc.status = :status");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!conditions.isEmpty()) {
|
||||||
|
sql.append(" AND ").append(String.join(" AND ", conditions));
|
||||||
|
}
|
||||||
|
|
||||||
|
String sort = pageRequest.getSort() != null ? pageRequest.getSort() : "id";
|
||||||
|
String order = "desc".equalsIgnoreCase(pageRequest.getOrder()) ? "DESC" : "ASC";
|
||||||
|
sql.append(" ORDER BY gc.").append(sort).append(" ").append(order);
|
||||||
|
|
||||||
|
int size = pageRequest.getSize();
|
||||||
|
if (size < 1) size = 10;
|
||||||
|
if (size > 100) size = 100;
|
||||||
|
int offset = pageRequest.getPage() * size;
|
||||||
|
sql.append(" LIMIT :limit OFFSET :offset");
|
||||||
|
|
||||||
|
DatabaseClient.GenericExecuteSpec spec = databaseClient.sql(sql.toString());
|
||||||
|
|
||||||
|
if (pageRequest.getKeyword() != null && !pageRequest.getKeyword().isEmpty()) {
|
||||||
|
spec = spec.bind("keyword", "%" + pageRequest.getKeyword() + "%");
|
||||||
|
}
|
||||||
|
if (pageRequest.getStatus() != null && !pageRequest.getStatus().isEmpty()) {
|
||||||
|
spec = spec.bind("status", pageRequest.getStatus());
|
||||||
|
}
|
||||||
|
spec = spec.bind("limit", size);
|
||||||
|
spec = spec.bind("offset", offset);
|
||||||
|
|
||||||
|
return spec.map((row, meta) -> mapRowToEntity(row)).all();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 分页查询团课总数(支持 keyword 和 status 过滤)
|
||||||
|
*/
|
||||||
|
default Mono<Long> countByPageFiltered(DatabaseClient databaseClient, PageRequest pageRequest) {
|
||||||
|
StringBuilder sql = new StringBuilder("SELECT COUNT(*) FROM group_course WHERE deleted_at IS NULL");
|
||||||
|
List<String> conditions = new ArrayList<>();
|
||||||
|
|
||||||
|
if (pageRequest.getKeyword() != null && !pageRequest.getKeyword().isEmpty()) {
|
||||||
|
conditions.add("course_name ILIKE :keyword");
|
||||||
|
}
|
||||||
|
if (pageRequest.getStatus() != null && !pageRequest.getStatus().isEmpty()) {
|
||||||
|
conditions.add("status = :status");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!conditions.isEmpty()) {
|
||||||
|
sql.append(" AND ").append(String.join(" AND ", conditions));
|
||||||
|
}
|
||||||
|
|
||||||
|
DatabaseClient.GenericExecuteSpec spec = databaseClient.sql(sql.toString());
|
||||||
|
|
||||||
|
if (pageRequest.getKeyword() != null && !pageRequest.getKeyword().isEmpty()) {
|
||||||
|
spec = spec.bind("keyword", "%" + pageRequest.getKeyword() + "%");
|
||||||
|
}
|
||||||
|
if (pageRequest.getStatus() != null && !pageRequest.getStatus().isEmpty()) {
|
||||||
|
spec = spec.bind("status", pageRequest.getStatus());
|
||||||
|
}
|
||||||
|
|
||||||
|
return spec.map((row, meta) -> row.get(0, Long.class)).one();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统计单门课程的有效预约人数(status='0')
|
||||||
|
*/
|
||||||
|
default Mono<Long> countValidBookings(DatabaseClient databaseClient, Long courseId) {
|
||||||
|
return databaseClient.sql("SELECT COUNT(*) FROM group_course_booking WHERE course_id = :id AND status = '0'")
|
||||||
|
.bind("id", courseId)
|
||||||
|
.map((row, meta) -> row.get(0, Long.class))
|
||||||
|
.one()
|
||||||
|
.defaultIfEmpty(0L);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将数据库行映射为 GroupCourseEntity
|
||||||
|
*/
|
||||||
|
private GroupCourseEntity mapRowToEntity(io.r2dbc.spi.Row row) {
|
||||||
|
GroupCourseEntity entity = new GroupCourseEntity();
|
||||||
|
entity.setId(row.get("id", Long.class));
|
||||||
|
entity.setCourseName(row.get("course_name", String.class));
|
||||||
|
entity.setCoachId(row.get("coach_id", Long.class));
|
||||||
|
entity.setCourseType(row.get("course_type", Long.class));
|
||||||
|
entity.setStartTime(row.get("start_time", LocalDateTime.class));
|
||||||
|
entity.setEndTime(row.get("end_time", LocalDateTime.class));
|
||||||
|
entity.setMaxMembers(row.get("max_members", Integer.class));
|
||||||
|
Integer cm = row.get("current_members", Integer.class);
|
||||||
|
entity.setCurrentMembers(cm != null ? cm : 0);
|
||||||
|
String statusStr = row.get("status", String.class);
|
||||||
|
entity.setStatus(statusStr != null ? Long.parseLong(statusStr) : null);
|
||||||
|
entity.setLocation(row.get("location", String.class));
|
||||||
|
entity.setCoverImage(row.get("cover_image", String.class));
|
||||||
|
entity.setDescription(row.get("description", String.class));
|
||||||
|
entity.setStoredValueAmount(row.get("stored_value_amount", java.math.BigDecimal.class));
|
||||||
|
entity.setActualStartTime(row.get("actual_start_time", LocalDateTime.class));
|
||||||
|
entity.setActualEndTime(row.get("actual_end_time", LocalDateTime.class));
|
||||||
|
entity.setQrCodePath(row.get("qr_code_path", String.class));
|
||||||
|
entity.setCreateBy(row.get("create_by", String.class));
|
||||||
|
entity.setUpdateBy(row.get("update_by", String.class));
|
||||||
|
entity.setCreatedAt(row.get("created_at", LocalDateTime.class));
|
||||||
|
entity.setUpdatedAt(row.get("updated_at", LocalDateTime.class));
|
||||||
|
entity.setDeletedAt(row.get("deleted_at", LocalDateTime.class));
|
||||||
|
return entity;
|
||||||
|
}
|
||||||
|
}
|
||||||
+42
@@ -0,0 +1,42 @@
|
|||||||
|
package cn.novalon.gym.manage.groupcourse.dao;
|
||||||
|
|
||||||
|
import cn.novalon.gym.manage.groupcourse.entity.GroupCourseRecommendEntity;
|
||||||
|
import org.springframework.data.domain.Sort;
|
||||||
|
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 GroupCourseRecommendDao extends R2dbcRepository<GroupCourseRecommendEntity, Long> {
|
||||||
|
|
||||||
|
Mono<GroupCourseRecommendEntity> findByIdAndDeletedAtIsNull(Long id);
|
||||||
|
|
||||||
|
Flux<GroupCourseRecommendEntity> findAllByDeletedAtIsNull();
|
||||||
|
|
||||||
|
Flux<GroupCourseRecommendEntity> findAllByDeletedAtIsNull(Sort sort);
|
||||||
|
|
||||||
|
Flux<GroupCourseRecommendEntity> findByCourseIdAndDeletedAtIsNull(Long courseId);
|
||||||
|
|
||||||
|
Mono<GroupCourseRecommendEntity> findByCourseIdAndDeletedAtIsNullAndIsActiveTrue(Long courseId);
|
||||||
|
|
||||||
|
Flux<GroupCourseRecommendEntity> findByIsActiveTrueAndDeletedAtIsNull();
|
||||||
|
|
||||||
|
Flux<GroupCourseRecommendEntity> findByIsActiveTrueAndDeletedAtIsNull(Sort sort);
|
||||||
|
|
||||||
|
@Modifying
|
||||||
|
@Query("UPDATE group_course_recommend SET is_active = :isActive, updated_at = :updatedAt WHERE id = :id AND deleted_at IS NULL")
|
||||||
|
Mono<Integer> updateActiveStatus(Long id, Boolean isActive, LocalDateTime updatedAt);
|
||||||
|
|
||||||
|
@Modifying
|
||||||
|
@Query("UPDATE group_course_recommend SET deleted_at = :deletedAt WHERE id = :id")
|
||||||
|
Mono<Integer> softDelete(Long id, LocalDateTime deletedAt);
|
||||||
|
|
||||||
|
@Modifying
|
||||||
|
@Query("UPDATE group_course_recommend SET deleted_at = :deletedAt WHERE course_id = :courseId")
|
||||||
|
Mono<Integer> softDeleteByCourseId(Long courseId, LocalDateTime deletedAt);
|
||||||
|
}
|
||||||
+32
@@ -0,0 +1,32 @@
|
|||||||
|
package cn.novalon.gym.manage.groupcourse.dao;
|
||||||
|
|
||||||
|
import cn.novalon.gym.manage.groupcourse.entity.GroupCourseTypeEntity;
|
||||||
|
import org.springframework.data.domain.Sort;
|
||||||
|
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 GroupCourseTypeDao extends R2dbcRepository<GroupCourseTypeEntity, Long> {
|
||||||
|
|
||||||
|
Mono<GroupCourseTypeEntity> findByIdIsAndDeletedAtIsNull(Long id);
|
||||||
|
|
||||||
|
Flux<GroupCourseTypeEntity> findAllByDeletedAtIsNull();
|
||||||
|
|
||||||
|
Flux<GroupCourseTypeEntity> findAllByDeletedAtIsNull(Sort sort);
|
||||||
|
|
||||||
|
Flux<GroupCourseTypeEntity> findByTypeNameContainingAndDeletedAtIsNull(String typeName);
|
||||||
|
|
||||||
|
Flux<GroupCourseTypeEntity> findByCategoryAndDeletedAtIsNull(String category);
|
||||||
|
|
||||||
|
Mono<GroupCourseTypeEntity> findByTypeNameAndDeletedAtIsNull(String typeName);
|
||||||
|
|
||||||
|
@Modifying
|
||||||
|
@Query("UPDATE group_course_type SET deleted_at = :deletedAt WHERE id = :id")
|
||||||
|
Mono<Integer> softDelete(Long id, LocalDateTime deletedAt);
|
||||||
|
}
|
||||||
+43
@@ -0,0 +1,43 @@
|
|||||||
|
package cn.novalon.gym.manage.groupcourse.domain;
|
||||||
|
|
||||||
|
import cn.novalon.gym.manage.sys.core.domain.BaseDomain;
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
|
||||||
|
public class CourseLabel extends BaseDomain {
|
||||||
|
|
||||||
|
//标签名称
|
||||||
|
@Schema(description = "标签名称", example = "适合新手")
|
||||||
|
private String labelName;
|
||||||
|
|
||||||
|
//标签颜色(十六进制)
|
||||||
|
@Schema(description = "标签颜色(十六进制)", example = "#52c41a")
|
||||||
|
private String color;
|
||||||
|
|
||||||
|
//标签描述
|
||||||
|
@Schema(description = "标签描述", example = "适合健身初学者")
|
||||||
|
private String description;
|
||||||
|
|
||||||
|
public String getLabelName() {
|
||||||
|
return labelName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setLabelName(String labelName) {
|
||||||
|
this.labelName = labelName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getColor() {
|
||||||
|
return color;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setColor(String color) {
|
||||||
|
this.color = color;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getDescription() {
|
||||||
|
return description;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setDescription(String description) {
|
||||||
|
this.description = description;
|
||||||
|
}
|
||||||
|
}
|
||||||
+190
@@ -0,0 +1,190 @@
|
|||||||
|
|
||||||
|
package cn.novalon.gym.manage.groupcourse.domain;
|
||||||
|
|
||||||
|
import cn.novalon.gym.manage.sys.core.domain.BaseDomain;
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
public class GroupCourse extends BaseDomain{
|
||||||
|
|
||||||
|
//课程名称
|
||||||
|
@Schema(description = "团课名", example = "Push-up")
|
||||||
|
private String courseName;
|
||||||
|
|
||||||
|
//教练id
|
||||||
|
@Schema(description = "教练id", example = "1")
|
||||||
|
private Long coachId;
|
||||||
|
|
||||||
|
//课程类型
|
||||||
|
@Schema(description = "课程类型", example = "1")
|
||||||
|
private Long courseType;
|
||||||
|
|
||||||
|
//开始时间
|
||||||
|
@Schema(description = "开始时间", example = "2026-01-01")
|
||||||
|
private LocalDateTime startTime;
|
||||||
|
|
||||||
|
//结束时间
|
||||||
|
@Schema(description = "结束时间", example = "2026-01-02")
|
||||||
|
private LocalDateTime endTime;
|
||||||
|
|
||||||
|
//最大参与人数
|
||||||
|
@Schema(description = "最大参与人数", example = "20")
|
||||||
|
private Integer maxMembers;
|
||||||
|
|
||||||
|
//当前参与人数
|
||||||
|
@Schema(description = "当前参与人数", example = "2")
|
||||||
|
private Integer currentMembers;
|
||||||
|
|
||||||
|
//课程状态:0-正常,1-已取消,2-已结束
|
||||||
|
@Schema(description = "课程状态", example = "0")
|
||||||
|
private Long status;
|
||||||
|
|
||||||
|
//实际开课时间
|
||||||
|
@Schema(description = "实际开课时间")
|
||||||
|
private LocalDateTime actualStartTime;
|
||||||
|
|
||||||
|
//实际结课时间
|
||||||
|
@Schema(description = "实际结课时间")
|
||||||
|
private LocalDateTime actualEndTime;
|
||||||
|
|
||||||
|
//上课地点
|
||||||
|
@Schema(description = "上课地点", example = "龙泉驿区幸福路")
|
||||||
|
private String location;
|
||||||
|
|
||||||
|
//封面图URL
|
||||||
|
@Schema(description = "封面图URL", example = "https://12345.com")
|
||||||
|
private String coverImage;
|
||||||
|
|
||||||
|
//课程描述
|
||||||
|
@Schema(description = "课程描述", example = "从入门到入土")
|
||||||
|
private String description;
|
||||||
|
|
||||||
|
//储值卡额度(消耗金额)
|
||||||
|
@Schema(description = "储值卡额度(消耗金额)", example = "50.00")
|
||||||
|
private java.math.BigDecimal storedValueAmount;
|
||||||
|
|
||||||
|
//二维码路径
|
||||||
|
@Schema(description = "二维码路径", example = "D:\\Games\\exmp\\image\\abc123_20260618120000.png")
|
||||||
|
private String qrCodePath;
|
||||||
|
|
||||||
|
public String getCourseName() {
|
||||||
|
return courseName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCourseName(String courseName) {
|
||||||
|
this.courseName = courseName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getCoachId() {
|
||||||
|
return coachId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCoachId(Long coachId) {
|
||||||
|
this.coachId = coachId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getCourseType() {
|
||||||
|
return courseType;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCourseType(Long courseType) {
|
||||||
|
this.courseType = courseType;
|
||||||
|
}
|
||||||
|
|
||||||
|
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 getMaxMembers() {
|
||||||
|
return maxMembers;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setMaxMembers(Integer maxMembers) {
|
||||||
|
this.maxMembers = maxMembers;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Integer getCurrentMembers() {
|
||||||
|
return currentMembers;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCurrentMembers(Integer currentMembers) {
|
||||||
|
this.currentMembers = currentMembers;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getStatus() {
|
||||||
|
return status;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setStatus(Long status) {
|
||||||
|
this.status = status;
|
||||||
|
}
|
||||||
|
|
||||||
|
public LocalDateTime getActualStartTime() {
|
||||||
|
return actualStartTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setActualStartTime(LocalDateTime actualStartTime) {
|
||||||
|
this.actualStartTime = actualStartTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
public LocalDateTime getActualEndTime() {
|
||||||
|
return actualEndTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setActualEndTime(LocalDateTime actualEndTime) {
|
||||||
|
this.actualEndTime = actualEndTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getLocation() {
|
||||||
|
return location;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setLocation(String location) {
|
||||||
|
this.location = location;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getCoverImage() {
|
||||||
|
return coverImage;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCoverImage(String coverImage) {
|
||||||
|
this.coverImage = coverImage;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getDescription() {
|
||||||
|
return description;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setDescription(String description) {
|
||||||
|
this.description = description;
|
||||||
|
}
|
||||||
|
|
||||||
|
public java.math.BigDecimal getStoredValueAmount() {
|
||||||
|
return storedValueAmount;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setStoredValueAmount(java.math.BigDecimal storedValueAmount) {
|
||||||
|
this.storedValueAmount = storedValueAmount;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getQrCodePath() {
|
||||||
|
return qrCodePath;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setQrCodePath(String qrCodePath) {
|
||||||
|
this.qrCodePath = qrCodePath;
|
||||||
|
}
|
||||||
|
}
|
||||||
+135
@@ -0,0 +1,135 @@
|
|||||||
|
package cn.novalon.gym.manage.groupcourse.domain;
|
||||||
|
|
||||||
|
import cn.novalon.gym.manage.sys.core.domain.BaseDomain;
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 团课预约记录领域模型
|
||||||
|
*
|
||||||
|
* @author 张翔
|
||||||
|
* @date 2026-06-01
|
||||||
|
*/
|
||||||
|
public class GroupCourseBooking extends BaseDomain {
|
||||||
|
|
||||||
|
//团课ID
|
||||||
|
@Schema(description = "团课ID", example = "1")
|
||||||
|
private Long courseId;
|
||||||
|
|
||||||
|
//团课名称(关联查询)
|
||||||
|
@Schema(description = "团课名称", example = "瑜伽入门")
|
||||||
|
private String courseName;
|
||||||
|
|
||||||
|
//会员ID
|
||||||
|
@Schema(description = "会员ID", example = "1")
|
||||||
|
private Long memberId;
|
||||||
|
|
||||||
|
//会员卡记录ID
|
||||||
|
@Schema(description = "会员卡记录ID", example = "1")
|
||||||
|
private Long memberCardRecordId;
|
||||||
|
|
||||||
|
//预约时间
|
||||||
|
@Schema(description = "预约时间", example = "2026-06-01 10:00:00")
|
||||||
|
private LocalDateTime bookingTime;
|
||||||
|
|
||||||
|
//状态:0-已预约,1-已取消,2-已出席,3-缺席
|
||||||
|
@Schema(description = "状态:0-已预约,1-已取消,2-已出席,3-缺席", example = "0")
|
||||||
|
private String status;
|
||||||
|
|
||||||
|
//取消时间
|
||||||
|
@Schema(description = "取消时间", example = "2026-06-01 11:00:00")
|
||||||
|
private LocalDateTime cancelTime;
|
||||||
|
|
||||||
|
//课程开始时间
|
||||||
|
@Schema(description = "课程开始时间", example = "2026-06-02 09:00:00")
|
||||||
|
private LocalDateTime courseStartTime;
|
||||||
|
|
||||||
|
//课程结束时间
|
||||||
|
@Schema(description = "课程结束时间", example = "2026-06-02 10:00:00")
|
||||||
|
private LocalDateTime courseEndTime;
|
||||||
|
|
||||||
|
//上课地点
|
||||||
|
@Schema(description = "上课地点", example = "健身房A区")
|
||||||
|
private String location;
|
||||||
|
|
||||||
|
public Long getCourseId() {
|
||||||
|
return courseId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCourseId(Long courseId) {
|
||||||
|
this.courseId = courseId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getCourseName() {
|
||||||
|
return courseName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCourseName(String courseName) {
|
||||||
|
this.courseName = courseName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getMemberId() {
|
||||||
|
return memberId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setMemberId(Long memberId) {
|
||||||
|
this.memberId = memberId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getMemberCardRecordId() {
|
||||||
|
return memberCardRecordId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setMemberCardRecordId(Long memberCardRecordId) {
|
||||||
|
this.memberCardRecordId = memberCardRecordId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public LocalDateTime getBookingTime() {
|
||||||
|
return bookingTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setBookingTime(LocalDateTime bookingTime) {
|
||||||
|
this.bookingTime = bookingTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getStatus() {
|
||||||
|
return status;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setStatus(String status) {
|
||||||
|
this.status = status;
|
||||||
|
}
|
||||||
|
|
||||||
|
public LocalDateTime getCancelTime() {
|
||||||
|
return cancelTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCancelTime(LocalDateTime cancelTime) {
|
||||||
|
this.cancelTime = cancelTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
public LocalDateTime getCourseStartTime() {
|
||||||
|
return courseStartTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCourseStartTime(LocalDateTime courseStartTime) {
|
||||||
|
this.courseStartTime = courseStartTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
public LocalDateTime getCourseEndTime() {
|
||||||
|
return courseEndTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCourseEndTime(LocalDateTime courseEndTime) {
|
||||||
|
this.courseEndTime = courseEndTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getLocation() {
|
||||||
|
return location;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setLocation(String location) {
|
||||||
|
this.location = location;
|
||||||
|
}
|
||||||
|
}
|
||||||
+265
@@ -0,0 +1,265 @@
|
|||||||
|
package cn.novalon.gym.manage.groupcourse.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;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 团课完整信息领域模型
|
||||||
|
* 包含团课基础信息、关联的类型信息以及类型的标签信息
|
||||||
|
*/
|
||||||
|
public class GroupCourseDetail extends BaseDomain {
|
||||||
|
|
||||||
|
// ===== 团课基础信息 =====
|
||||||
|
|
||||||
|
@Schema(description = "课程名称", example = "瑜伽入门")
|
||||||
|
private String courseName;
|
||||||
|
|
||||||
|
@Schema(description = "教练ID", example = "1")
|
||||||
|
private Long coachId;
|
||||||
|
|
||||||
|
@Schema(description = "教练名称", example = "张教练")
|
||||||
|
private String coachName;
|
||||||
|
|
||||||
|
@Schema(description = "课程类型ID", example = "1")
|
||||||
|
private Long courseType;
|
||||||
|
|
||||||
|
@Schema(description = "开始时间", example = "2026-06-02T09:00:00")
|
||||||
|
private LocalDateTime startTime;
|
||||||
|
|
||||||
|
@Schema(description = "结束时间", example = "2026-06-02T10:00:00")
|
||||||
|
private LocalDateTime endTime;
|
||||||
|
|
||||||
|
@Schema(description = "最大参与人数", example = "20")
|
||||||
|
private Integer maxMembers;
|
||||||
|
|
||||||
|
@Schema(description = "当前参与人数", example = "15")
|
||||||
|
private Integer currentMembers;
|
||||||
|
|
||||||
|
@Schema(description = "课程状态", example = "0")
|
||||||
|
private Long status;
|
||||||
|
|
||||||
|
@Schema(description = "上课地点", example = "健身房A区")
|
||||||
|
private String location;
|
||||||
|
|
||||||
|
@Schema(description = "封面图URL", example = "https://example.com/yoga.jpg")
|
||||||
|
private String coverImage;
|
||||||
|
|
||||||
|
@Schema(description = "课程描述", example = "适合初学者的瑜伽课程")
|
||||||
|
private String description;
|
||||||
|
|
||||||
|
@Schema(description = "储值卡额度(消耗金额)", example = "50.00")
|
||||||
|
private BigDecimal storedValueAmount;
|
||||||
|
|
||||||
|
@Schema(description = "二维码路径", example = "D:\\Games\\exmp\\image\\abc123_20260618120000.png")
|
||||||
|
private String qrCodePath;
|
||||||
|
|
||||||
|
// ===== 关联的类型信息 =====
|
||||||
|
|
||||||
|
@Schema(description = "类型信息")
|
||||||
|
private GroupCourseType typeInfo;
|
||||||
|
|
||||||
|
// ===== 快捷访问属性(从类型信息派生)=====
|
||||||
|
|
||||||
|
@Schema(description = "类型名称", example = "瑜伽入门")
|
||||||
|
private String typeName;
|
||||||
|
|
||||||
|
@Schema(description = "类型分类", example = "柔韧与平衡类")
|
||||||
|
private String typeCategory;
|
||||||
|
|
||||||
|
@Schema(description = "基础难度", example = "2")
|
||||||
|
private Integer baseDifficulty;
|
||||||
|
|
||||||
|
@Schema(description = "难度等级描述", example = "初级")
|
||||||
|
private String difficultyLevel;
|
||||||
|
|
||||||
|
@Schema(description = "综合难度系数", example = "2")
|
||||||
|
private Integer calculatedDifficulty;
|
||||||
|
|
||||||
|
// ===== 标签信息(从类型标签派生)=====
|
||||||
|
|
||||||
|
@Schema(description = "标签列表")
|
||||||
|
private List<CourseLabel> labels;
|
||||||
|
|
||||||
|
// ===== Getters and Setters =====
|
||||||
|
|
||||||
|
public String getCourseName() {
|
||||||
|
return courseName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCourseName(String courseName) {
|
||||||
|
this.courseName = courseName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getCoachId() {
|
||||||
|
return coachId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCoachId(Long coachId) {
|
||||||
|
this.coachId = coachId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getCoachName() {
|
||||||
|
return coachName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCoachName(String coachName) {
|
||||||
|
this.coachName = coachName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getCourseType() {
|
||||||
|
return courseType;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCourseType(Long courseType) {
|
||||||
|
this.courseType = courseType;
|
||||||
|
}
|
||||||
|
|
||||||
|
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 getMaxMembers() {
|
||||||
|
return maxMembers;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setMaxMembers(Integer maxMembers) {
|
||||||
|
this.maxMembers = maxMembers;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Integer getCurrentMembers() {
|
||||||
|
return currentMembers;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCurrentMembers(Integer currentMembers) {
|
||||||
|
this.currentMembers = currentMembers;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getStatus() {
|
||||||
|
return status;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setStatus(Long status) {
|
||||||
|
this.status = status;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getLocation() {
|
||||||
|
return location;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setLocation(String location) {
|
||||||
|
this.location = location;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getCoverImage() {
|
||||||
|
return coverImage;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCoverImage(String coverImage) {
|
||||||
|
this.coverImage = coverImage;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getDescription() {
|
||||||
|
return description;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setDescription(String description) {
|
||||||
|
this.description = description;
|
||||||
|
}
|
||||||
|
|
||||||
|
public BigDecimal getStoredValueAmount() {
|
||||||
|
return storedValueAmount;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setStoredValueAmount(BigDecimal storedValueAmount) {
|
||||||
|
this.storedValueAmount = storedValueAmount;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getQrCodePath() {
|
||||||
|
return qrCodePath;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setQrCodePath(String qrCodePath) {
|
||||||
|
this.qrCodePath = qrCodePath;
|
||||||
|
}
|
||||||
|
|
||||||
|
public GroupCourseType getTypeInfo() {
|
||||||
|
return typeInfo;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setTypeInfo(GroupCourseType typeInfo) {
|
||||||
|
this.typeInfo = typeInfo;
|
||||||
|
// 同步派生属性
|
||||||
|
if (typeInfo != null) {
|
||||||
|
this.typeName = typeInfo.getTypeName();
|
||||||
|
this.typeCategory = typeInfo.getCategory();
|
||||||
|
this.baseDifficulty = typeInfo.getBaseDifficulty();
|
||||||
|
this.difficultyLevel = typeInfo.getDifficultyLevel();
|
||||||
|
this.calculatedDifficulty = typeInfo.getCalculatedDifficulty();
|
||||||
|
this.labels = typeInfo.getLabels();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getTypeName() {
|
||||||
|
return typeName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setTypeName(String typeName) {
|
||||||
|
this.typeName = typeName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getTypeCategory() {
|
||||||
|
return typeCategory;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setTypeCategory(String typeCategory) {
|
||||||
|
this.typeCategory = typeCategory;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Integer getBaseDifficulty() {
|
||||||
|
return baseDifficulty;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setBaseDifficulty(Integer baseDifficulty) {
|
||||||
|
this.baseDifficulty = baseDifficulty;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getDifficultyLevel() {
|
||||||
|
return difficultyLevel;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setDifficultyLevel(String difficultyLevel) {
|
||||||
|
this.difficultyLevel = difficultyLevel;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Integer getCalculatedDifficulty() {
|
||||||
|
return calculatedDifficulty;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCalculatedDifficulty(Integer calculatedDifficulty) {
|
||||||
|
this.calculatedDifficulty = calculatedDifficulty;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<CourseLabel> getLabels() {
|
||||||
|
return labels;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setLabels(List<CourseLabel> labels) {
|
||||||
|
this.labels = labels;
|
||||||
|
}
|
||||||
|
}
|
||||||
+84
@@ -0,0 +1,84 @@
|
|||||||
|
package cn.novalon.gym.manage.groupcourse.domain;
|
||||||
|
|
||||||
|
import cn.novalon.gym.manage.sys.core.domain.BaseDomain;
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
|
||||||
|
public class GroupCourseRecommend extends BaseDomain {
|
||||||
|
|
||||||
|
@Schema(description = "团课ID", example = "1")
|
||||||
|
private Long courseId;
|
||||||
|
|
||||||
|
@Schema(description = "推荐标题", example = "本周热门课程")
|
||||||
|
private String recommendTitle;
|
||||||
|
|
||||||
|
@Schema(description = "推荐内容", example = "这是一门非常棒的课程,快来参加吧!")
|
||||||
|
private String recommendContent;
|
||||||
|
|
||||||
|
@Schema(description = "推荐理由", example = "教练专业,课程内容丰富")
|
||||||
|
private String recommendReason;
|
||||||
|
|
||||||
|
@Schema(description = "优先级(数字越大优先级越高)", example = "10")
|
||||||
|
private Integer priority;
|
||||||
|
|
||||||
|
@Schema(description = "是否启用", example = "true")
|
||||||
|
private Boolean isActive;
|
||||||
|
|
||||||
|
@Schema(description = "团课信息")
|
||||||
|
private GroupCourse groupCourse;
|
||||||
|
|
||||||
|
public Long getCourseId() {
|
||||||
|
return courseId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCourseId(Long courseId) {
|
||||||
|
this.courseId = courseId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getRecommendTitle() {
|
||||||
|
return recommendTitle;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setRecommendTitle(String recommendTitle) {
|
||||||
|
this.recommendTitle = recommendTitle;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getRecommendContent() {
|
||||||
|
return recommendContent;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setRecommendContent(String recommendContent) {
|
||||||
|
this.recommendContent = recommendContent;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getRecommendReason() {
|
||||||
|
return recommendReason;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setRecommendReason(String recommendReason) {
|
||||||
|
this.recommendReason = recommendReason;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Integer getPriority() {
|
||||||
|
return priority;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPriority(Integer priority) {
|
||||||
|
this.priority = priority;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Boolean getIsActive() {
|
||||||
|
return isActive;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setIsActive(Boolean isActive) {
|
||||||
|
this.isActive = isActive;
|
||||||
|
}
|
||||||
|
|
||||||
|
public GroupCourse getGroupCourse() {
|
||||||
|
return groupCourse;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setGroupCourse(GroupCourse groupCourse) {
|
||||||
|
this.groupCourse = groupCourse;
|
||||||
|
}
|
||||||
|
}
|
||||||
+113
@@ -0,0 +1,113 @@
|
|||||||
|
package cn.novalon.gym.manage.groupcourse.domain;
|
||||||
|
|
||||||
|
import cn.novalon.gym.manage.sys.core.domain.BaseDomain;
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
public class GroupCourseType extends BaseDomain {
|
||||||
|
|
||||||
|
//类型名称
|
||||||
|
@Schema(description = "类型名称", example = "瑜伽入门")
|
||||||
|
private String typeName;
|
||||||
|
|
||||||
|
//基础难度(1-10)
|
||||||
|
@Schema(description = "基础难度(1-10)", example = "2")
|
||||||
|
private Integer baseDifficulty;
|
||||||
|
|
||||||
|
//类型描述
|
||||||
|
@Schema(description = "类型描述", example = "适合初学者的瑜伽课程")
|
||||||
|
private String description;
|
||||||
|
|
||||||
|
//分类(如:有氧、力量、柔韧等)
|
||||||
|
@Schema(description = "分类", example = "柔韧与平衡类")
|
||||||
|
private String category;
|
||||||
|
|
||||||
|
//标签列表
|
||||||
|
@Schema(description = "标签列表")
|
||||||
|
private List<CourseLabel> labels = new ArrayList<>();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 计算综合难度系数
|
||||||
|
*
|
||||||
|
* 当前实现仅返回基础难度,为后续扩展预留空间。
|
||||||
|
* 未来可扩展的影响因素包括:
|
||||||
|
* 1. 课程时长系数(时长越长难度越高)
|
||||||
|
* 2. 教练难度调整系数(教练可根据实际情况微调)
|
||||||
|
* 3. 会员等级适配系数(根据会员等级动态调整显示难度)
|
||||||
|
* 4. 课程强度系数(高强度课程难度加成)
|
||||||
|
*
|
||||||
|
* @return 综合难度系数(1-10)
|
||||||
|
*/
|
||||||
|
@Schema(description = "综合难度系数(预留扩展字段)", example = "2")
|
||||||
|
public Integer getCalculatedDifficulty() {
|
||||||
|
// TODO: 预留扩展点 - 未来可在此处添加更多难度计算逻辑
|
||||||
|
// 例如:return calculateDynamicDifficulty(baseDifficulty, additionalFactors...);
|
||||||
|
return this.baseDifficulty != null ? this.baseDifficulty : 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取难度等级描述
|
||||||
|
* 将数字难度转换为友好的文字描述
|
||||||
|
*
|
||||||
|
* @return 难度等级描述
|
||||||
|
*/
|
||||||
|
@Schema(description = "难度等级描述", example = "初级")
|
||||||
|
public String getDifficultyLevel() {
|
||||||
|
if (baseDifficulty == null) {
|
||||||
|
return "未知";
|
||||||
|
}
|
||||||
|
if (baseDifficulty <= 2) {
|
||||||
|
return "初级";
|
||||||
|
} else if (baseDifficulty <= 4) {
|
||||||
|
return "中级";
|
||||||
|
} else if (baseDifficulty <= 6) {
|
||||||
|
return "中高级";
|
||||||
|
} else if (baseDifficulty <= 8) {
|
||||||
|
return "高级";
|
||||||
|
} else {
|
||||||
|
return "专家级";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getTypeName() {
|
||||||
|
return typeName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setTypeName(String typeName) {
|
||||||
|
this.typeName = typeName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Integer getBaseDifficulty() {
|
||||||
|
return baseDifficulty;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setBaseDifficulty(Integer baseDifficulty) {
|
||||||
|
this.baseDifficulty = baseDifficulty;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getDescription() {
|
||||||
|
return description;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setDescription(String description) {
|
||||||
|
this.description = description;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getCategory() {
|
||||||
|
return category;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCategory(String category) {
|
||||||
|
this.category = category;
|
||||||
|
}
|
||||||
|
|
||||||
|
public List<CourseLabel> getLabels() {
|
||||||
|
return labels;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setLabels(List<CourseLabel> labels) {
|
||||||
|
this.labels = labels;
|
||||||
|
}
|
||||||
|
}
|
||||||
+116
@@ -0,0 +1,116 @@
|
|||||||
|
package cn.novalon.gym.manage.groupcourse.dto;
|
||||||
|
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 团课多条件查询请求DTO
|
||||||
|
*
|
||||||
|
* @author 张翔
|
||||||
|
* @date 2026-06-14
|
||||||
|
*/
|
||||||
|
@Schema(description = "团课多条件查询参数")
|
||||||
|
public class GroupCourseQueryDto {
|
||||||
|
|
||||||
|
@Schema(description = "课程名称(模糊查询)", example = "瑜伽")
|
||||||
|
private String courseName;
|
||||||
|
|
||||||
|
@Schema(description = "课程类型ID", example = "1")
|
||||||
|
private Long courseType;
|
||||||
|
|
||||||
|
@Schema(description = "查询开始日期", example = "2026-06-01T00:00:00")
|
||||||
|
private LocalDateTime startDate;
|
||||||
|
|
||||||
|
@Schema(description = "查询结束日期", example = "2026-06-30T23:59:59")
|
||||||
|
private LocalDateTime endDate;
|
||||||
|
|
||||||
|
@Schema(description = "时间段:morning-早晨(6:00-12:00), afternoon-下午(12:00-18:00), evening-夜晚(18:00-24:00)", example = "morning")
|
||||||
|
private String timePeriod;
|
||||||
|
|
||||||
|
@Schema(description = "价格排序:asc-从低到高, desc-从高到低", example = "asc")
|
||||||
|
private String priceSort;
|
||||||
|
|
||||||
|
@Schema(description = "按剩余名额最多排序", example = "true")
|
||||||
|
private Boolean remainingMost;
|
||||||
|
|
||||||
|
@Schema(description = "页码", example = "0")
|
||||||
|
private Integer page = 0;
|
||||||
|
|
||||||
|
@Schema(description = "每页大小", example = "10")
|
||||||
|
private Integer size = 10;
|
||||||
|
|
||||||
|
// ===== Getters and Setters =====
|
||||||
|
|
||||||
|
public String getCourseName() {
|
||||||
|
return courseName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCourseName(String courseName) {
|
||||||
|
this.courseName = courseName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getCourseType() {
|
||||||
|
return courseType;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCourseType(Long courseType) {
|
||||||
|
this.courseType = courseType;
|
||||||
|
}
|
||||||
|
|
||||||
|
public LocalDateTime getStartDate() {
|
||||||
|
return startDate;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setStartDate(LocalDateTime startDate) {
|
||||||
|
this.startDate = startDate;
|
||||||
|
}
|
||||||
|
|
||||||
|
public LocalDateTime getEndDate() {
|
||||||
|
return endDate;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setEndDate(LocalDateTime endDate) {
|
||||||
|
this.endDate = endDate;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getTimePeriod() {
|
||||||
|
return timePeriod;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setTimePeriod(String timePeriod) {
|
||||||
|
this.timePeriod = timePeriod;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getPriceSort() {
|
||||||
|
return priceSort;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPriceSort(String priceSort) {
|
||||||
|
this.priceSort = priceSort;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Boolean getRemainingMost() {
|
||||||
|
return remainingMost;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setRemainingMost(Boolean remainingMost) {
|
||||||
|
this.remainingMost = remainingMost;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Integer getPage() {
|
||||||
|
return page;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPage(Integer page) {
|
||||||
|
this.page = page;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Integer getSize() {
|
||||||
|
return size;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setSize(Integer size) {
|
||||||
|
this.size = size;
|
||||||
|
}
|
||||||
|
}
|
||||||
+45
@@ -0,0 +1,45 @@
|
|||||||
|
package cn.novalon.gym.manage.groupcourse.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;
|
||||||
|
|
||||||
|
@Table("course_label")
|
||||||
|
public class CourseLabelEntity extends BaseEntity {
|
||||||
|
|
||||||
|
//标签名称
|
||||||
|
@Column("label_name")
|
||||||
|
private String labelName;
|
||||||
|
|
||||||
|
//标签颜色(十六进制)
|
||||||
|
@Column("color")
|
||||||
|
private String color;
|
||||||
|
|
||||||
|
//标签描述
|
||||||
|
@Column("description")
|
||||||
|
private String description;
|
||||||
|
|
||||||
|
public String getLabelName() {
|
||||||
|
return labelName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setLabelName(String labelName) {
|
||||||
|
this.labelName = labelName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getColor() {
|
||||||
|
return color;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setColor(String color) {
|
||||||
|
this.color = color;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getDescription() {
|
||||||
|
return description;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setDescription(String description) {
|
||||||
|
this.description = description;
|
||||||
|
}
|
||||||
|
}
|
||||||
+33
@@ -0,0 +1,33 @@
|
|||||||
|
package cn.novalon.gym.manage.groupcourse.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;
|
||||||
|
|
||||||
|
@Table("course_type_label")
|
||||||
|
public class CourseTypeLabelEntity extends BaseEntity {
|
||||||
|
|
||||||
|
//团课类型ID
|
||||||
|
@Column("type_id")
|
||||||
|
private Long typeId;
|
||||||
|
|
||||||
|
//标签ID
|
||||||
|
@Column("label_id")
|
||||||
|
private Long labelId;
|
||||||
|
|
||||||
|
public Long getTypeId() {
|
||||||
|
return typeId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setTypeId(Long typeId) {
|
||||||
|
this.typeId = typeId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getLabelId() {
|
||||||
|
return labelId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setLabelId(Long labelId) {
|
||||||
|
this.labelId = labelId;
|
||||||
|
}
|
||||||
|
}
|
||||||
+137
@@ -0,0 +1,137 @@
|
|||||||
|
package cn.novalon.gym.manage.groupcourse.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;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 团课预约记录实体类 - 对应 group_course_booking 表
|
||||||
|
*
|
||||||
|
* @author 张翔
|
||||||
|
* @date 2026-06-01
|
||||||
|
*/
|
||||||
|
@Table("group_course_booking")
|
||||||
|
public class GroupCourseBookingEntity extends BaseEntity {
|
||||||
|
|
||||||
|
//团课ID
|
||||||
|
@Column("course_id")
|
||||||
|
private Long courseId;
|
||||||
|
|
||||||
|
//会员ID
|
||||||
|
@Column("member_id")
|
||||||
|
private Long memberId;
|
||||||
|
|
||||||
|
//会员卡记录ID
|
||||||
|
@Column("member_card_id")
|
||||||
|
private Long memberCardRecordId;
|
||||||
|
|
||||||
|
//预约时间
|
||||||
|
@Column("booking_time")
|
||||||
|
private LocalDateTime bookingTime;
|
||||||
|
|
||||||
|
//状态:0-已预约,1-已取消,2-已出席,3-缺席
|
||||||
|
@Column("status")
|
||||||
|
private String status;
|
||||||
|
|
||||||
|
//取消时间
|
||||||
|
@Column("cancel_time")
|
||||||
|
private LocalDateTime cancelTime;
|
||||||
|
|
||||||
|
//课程名称(冗余字段,保存预约时的课程快照)
|
||||||
|
@Column("course_name")
|
||||||
|
private String courseName;
|
||||||
|
|
||||||
|
//课程开始时间(冗余字段,保存预约时的课程快照)
|
||||||
|
@Column("course_start_time")
|
||||||
|
private LocalDateTime courseStartTime;
|
||||||
|
|
||||||
|
//课程结束时间(冗余字段,保存预约时的课程快照)
|
||||||
|
@Column("course_end_time")
|
||||||
|
private LocalDateTime courseEndTime;
|
||||||
|
|
||||||
|
//上课地点(冗余字段,保存预约时的课程快照)
|
||||||
|
@Column("location")
|
||||||
|
private String location;
|
||||||
|
|
||||||
|
public Long getCourseId() {
|
||||||
|
return courseId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCourseId(Long courseId) {
|
||||||
|
this.courseId = courseId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getMemberId() {
|
||||||
|
return memberId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setMemberId(Long memberId) {
|
||||||
|
this.memberId = memberId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getMemberCardRecordId() {
|
||||||
|
return memberCardRecordId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setMemberCardRecordId(Long memberCardRecordId) {
|
||||||
|
this.memberCardRecordId = memberCardRecordId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public LocalDateTime getBookingTime() {
|
||||||
|
return bookingTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setBookingTime(LocalDateTime bookingTime) {
|
||||||
|
this.bookingTime = bookingTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getStatus() {
|
||||||
|
return status;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setStatus(String status) {
|
||||||
|
this.status = status;
|
||||||
|
}
|
||||||
|
|
||||||
|
public LocalDateTime getCancelTime() {
|
||||||
|
return cancelTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCancelTime(LocalDateTime cancelTime) {
|
||||||
|
this.cancelTime = cancelTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getCourseName() {
|
||||||
|
return courseName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCourseName(String courseName) {
|
||||||
|
this.courseName = courseName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public LocalDateTime getCourseStartTime() {
|
||||||
|
return courseStartTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCourseStartTime(LocalDateTime courseStartTime) {
|
||||||
|
this.courseStartTime = courseStartTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
public LocalDateTime getCourseEndTime() {
|
||||||
|
return courseEndTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCourseEndTime(LocalDateTime courseEndTime) {
|
||||||
|
this.courseEndTime = courseEndTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getLocation() {
|
||||||
|
return location;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setLocation(String location) {
|
||||||
|
this.location = location;
|
||||||
|
}
|
||||||
|
}
|
||||||
+192
@@ -0,0 +1,192 @@
|
|||||||
|
|
||||||
|
package cn.novalon.gym.manage.groupcourse.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_course")
|
||||||
|
public class GroupCourseEntity extends BaseEntity {
|
||||||
|
|
||||||
|
//课程名称
|
||||||
|
@Column("course_name")
|
||||||
|
private String courseName;
|
||||||
|
|
||||||
|
//教练id
|
||||||
|
@Column("coach_id")
|
||||||
|
private Long coachId;
|
||||||
|
|
||||||
|
//课程类型
|
||||||
|
@Column("course_type")
|
||||||
|
private Long courseType;
|
||||||
|
|
||||||
|
//开始时间
|
||||||
|
@Column("start_time")
|
||||||
|
private LocalDateTime startTime;
|
||||||
|
|
||||||
|
//结束时间
|
||||||
|
@Column("end_time")
|
||||||
|
private LocalDateTime endTime;
|
||||||
|
|
||||||
|
//最大参与人数
|
||||||
|
@Column("max_members")
|
||||||
|
private Integer maxMembers;
|
||||||
|
|
||||||
|
//当前参与人数
|
||||||
|
@Column("current_members")
|
||||||
|
private Integer currentMembers;
|
||||||
|
|
||||||
|
//实际开课时间
|
||||||
|
@Column("actual_start_time")
|
||||||
|
private LocalDateTime actualStartTime;
|
||||||
|
|
||||||
|
//实际结课时间
|
||||||
|
@Column("actual_end_time")
|
||||||
|
private LocalDateTime actualEndTime;
|
||||||
|
|
||||||
|
//课程状态:0-正常,1-已取消,2-已结束,3-进行中,5-教练缺席,6-自动结束,7-教练迟到
|
||||||
|
@Column("status")
|
||||||
|
private Long status;
|
||||||
|
|
||||||
|
//上课地点
|
||||||
|
@Column("location")
|
||||||
|
private String location;
|
||||||
|
|
||||||
|
//封面图URL
|
||||||
|
@Column("cover_image")
|
||||||
|
private String coverImage;
|
||||||
|
|
||||||
|
//课程描述
|
||||||
|
@Column("description")
|
||||||
|
private String description;
|
||||||
|
|
||||||
|
//储值卡额度(消耗金额)
|
||||||
|
@Column("stored_value_amount")
|
||||||
|
private java.math.BigDecimal storedValueAmount;
|
||||||
|
|
||||||
|
//二维码路径
|
||||||
|
@Column("qr_code_path")
|
||||||
|
private String qrCodePath;
|
||||||
|
|
||||||
|
public String getCourseName() {
|
||||||
|
return courseName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCourseName(String courseName) {
|
||||||
|
this.courseName = courseName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getCoachId() {
|
||||||
|
return coachId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCoachId(Long coachId) {
|
||||||
|
this.coachId = coachId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getCourseType() {
|
||||||
|
return courseType;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCourseType(Long courseType) {
|
||||||
|
this.courseType = courseType;
|
||||||
|
}
|
||||||
|
|
||||||
|
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 getMaxMembers() {
|
||||||
|
return maxMembers;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setMaxMembers(Integer maxMembers) {
|
||||||
|
this.maxMembers = maxMembers;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Integer getCurrentMembers() {
|
||||||
|
return currentMembers;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCurrentMembers(Integer currentMembers) {
|
||||||
|
this.currentMembers = currentMembers;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getStatus() {
|
||||||
|
return status;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setStatus(Long status) {
|
||||||
|
this.status = status;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getLocation() {
|
||||||
|
return location;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setLocation(String location) {
|
||||||
|
this.location = location;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getCoverImage() {
|
||||||
|
return coverImage;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCoverImage(String coverImage) {
|
||||||
|
this.coverImage = coverImage;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getDescription() {
|
||||||
|
return description;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setDescription(String description) {
|
||||||
|
this.description = description;
|
||||||
|
}
|
||||||
|
|
||||||
|
public java.math.BigDecimal getStoredValueAmount() {
|
||||||
|
return storedValueAmount;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setStoredValueAmount(java.math.BigDecimal storedValueAmount) {
|
||||||
|
this.storedValueAmount = storedValueAmount;
|
||||||
|
}
|
||||||
|
|
||||||
|
public LocalDateTime getActualStartTime() {
|
||||||
|
return actualStartTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setActualStartTime(LocalDateTime actualStartTime) {
|
||||||
|
this.actualStartTime = actualStartTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
public LocalDateTime getActualEndTime() {
|
||||||
|
return actualEndTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setActualEndTime(LocalDateTime actualEndTime) {
|
||||||
|
this.actualEndTime = actualEndTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getQrCodePath() {
|
||||||
|
return qrCodePath;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setQrCodePath(String qrCodePath) {
|
||||||
|
this.qrCodePath = qrCodePath;
|
||||||
|
}
|
||||||
|
}
|
||||||
+77
@@ -0,0 +1,77 @@
|
|||||||
|
package cn.novalon.gym.manage.groupcourse.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_course_recommend")
|
||||||
|
public class GroupCourseRecommendEntity extends BaseEntity {
|
||||||
|
|
||||||
|
@Column("course_id")
|
||||||
|
private Long courseId;
|
||||||
|
|
||||||
|
@Column("recommend_title")
|
||||||
|
private String recommendTitle;
|
||||||
|
|
||||||
|
@Column("recommend_content")
|
||||||
|
private String recommendContent;
|
||||||
|
|
||||||
|
@Column("recommend_reason")
|
||||||
|
private String recommendReason;
|
||||||
|
|
||||||
|
@Column("priority")
|
||||||
|
private Integer priority;
|
||||||
|
|
||||||
|
@Column("is_active")
|
||||||
|
private Boolean isActive;
|
||||||
|
|
||||||
|
public Long getCourseId() {
|
||||||
|
return courseId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCourseId(Long courseId) {
|
||||||
|
this.courseId = courseId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getRecommendTitle() {
|
||||||
|
return recommendTitle;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setRecommendTitle(String recommendTitle) {
|
||||||
|
this.recommendTitle = recommendTitle;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getRecommendContent() {
|
||||||
|
return recommendContent;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setRecommendContent(String recommendContent) {
|
||||||
|
this.recommendContent = recommendContent;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getRecommendReason() {
|
||||||
|
return recommendReason;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setRecommendReason(String recommendReason) {
|
||||||
|
this.recommendReason = recommendReason;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Integer getPriority() {
|
||||||
|
return priority;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setPriority(Integer priority) {
|
||||||
|
this.priority = priority;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Boolean getIsActive() {
|
||||||
|
return isActive;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setIsActive(Boolean isActive) {
|
||||||
|
this.isActive = isActive;
|
||||||
|
}
|
||||||
|
}
|
||||||
+57
@@ -0,0 +1,57 @@
|
|||||||
|
package cn.novalon.gym.manage.groupcourse.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;
|
||||||
|
|
||||||
|
@Table("group_course_type")
|
||||||
|
public class GroupCourseTypeEntity extends BaseEntity {
|
||||||
|
|
||||||
|
//类型名称
|
||||||
|
@Column("type_name")
|
||||||
|
private String typeName;
|
||||||
|
|
||||||
|
//基础难度(1-10)
|
||||||
|
@Column("base_difficulty")
|
||||||
|
private Integer baseDifficulty;
|
||||||
|
|
||||||
|
//类型描述
|
||||||
|
@Column("description")
|
||||||
|
private String description;
|
||||||
|
|
||||||
|
//分类(如:有氧、力量、柔韧等)
|
||||||
|
@Column("category")
|
||||||
|
private String category;
|
||||||
|
|
||||||
|
public String getTypeName() {
|
||||||
|
return typeName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setTypeName(String typeName) {
|
||||||
|
this.typeName = typeName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Integer getBaseDifficulty() {
|
||||||
|
return baseDifficulty;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setBaseDifficulty(Integer baseDifficulty) {
|
||||||
|
this.baseDifficulty = baseDifficulty;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getDescription() {
|
||||||
|
return description;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setDescription(String description) {
|
||||||
|
this.description = description;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getCategory() {
|
||||||
|
return category;
|
||||||
|
}
|
||||||
|
|
||||||
|
public void setCategory(String category) {
|
||||||
|
this.category = category;
|
||||||
|
}
|
||||||
|
}
|
||||||
+24
@@ -0,0 +1,24 @@
|
|||||||
|
package cn.novalon.gym.manage.groupcourse.enums;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 团课状态机事件枚举
|
||||||
|
*
|
||||||
|
* @author 张翔
|
||||||
|
* @date 2026-06-02
|
||||||
|
*/
|
||||||
|
public enum CourseEvent {
|
||||||
|
|
||||||
|
CANCEL("取消课程"),
|
||||||
|
END("结束课程"),
|
||||||
|
START("开始课程");
|
||||||
|
|
||||||
|
private final String desc;
|
||||||
|
|
||||||
|
CourseEvent(String desc) {
|
||||||
|
this.desc = desc;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getDesc() {
|
||||||
|
return desc;
|
||||||
|
}
|
||||||
|
}
|
||||||
+46
@@ -0,0 +1,46 @@
|
|||||||
|
package cn.novalon.gym.manage.groupcourse.enums;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 团课状态枚举
|
||||||
|
*
|
||||||
|
* @author 张翔
|
||||||
|
* @date 2026-06-02
|
||||||
|
*/
|
||||||
|
public enum CourseStatus {
|
||||||
|
|
||||||
|
NORMAL(0L, "正常"),
|
||||||
|
CANCELLED(1L, "已取消"),
|
||||||
|
ENDED(2L, "已结束"),
|
||||||
|
IN_PROGRESS(3L, "进行中"),
|
||||||
|
COACH_ABSENT(5L, "教练缺席"),
|
||||||
|
AUTO_ENDED(6L, "自动结束"),
|
||||||
|
COACH_LATE(7L, "教练迟到");
|
||||||
|
|
||||||
|
private final Long value;
|
||||||
|
private final String desc;
|
||||||
|
|
||||||
|
CourseStatus(Long value, String desc) {
|
||||||
|
this.value = value;
|
||||||
|
this.desc = desc;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getValue() {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getDesc() {
|
||||||
|
return desc;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据值获取枚举
|
||||||
|
*/
|
||||||
|
public static CourseStatus fromValue(Long value) {
|
||||||
|
for (CourseStatus status : values()) {
|
||||||
|
if (status.value.equals(value)) {
|
||||||
|
return status;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return NORMAL;
|
||||||
|
}
|
||||||
|
}
|
||||||
+57
@@ -0,0 +1,57 @@
|
|||||||
|
package cn.novalon.gym.manage.groupcourse.event;
|
||||||
|
|
||||||
|
import org.springframework.context.ApplicationEvent;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 预约提醒事件
|
||||||
|
*
|
||||||
|
* @author 张翔
|
||||||
|
* @date 2026-06-01
|
||||||
|
*/
|
||||||
|
public class BookingReminderEvent extends ApplicationEvent {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 消息类型枚举
|
||||||
|
*/
|
||||||
|
public enum ReminderType {
|
||||||
|
BOOKING_SUCCESS, // 预约成功
|
||||||
|
COURSE_REMINDER, // 课程即将开始提醒
|
||||||
|
BOOKING_CANCEL // 预约取消
|
||||||
|
}
|
||||||
|
|
||||||
|
private final Long bookingId;
|
||||||
|
private final Long memberId;
|
||||||
|
private final String courseName;
|
||||||
|
private final String courseTime;
|
||||||
|
private final ReminderType type;
|
||||||
|
|
||||||
|
public BookingReminderEvent(Object source, Long bookingId, Long memberId,
|
||||||
|
String courseName, String courseTime, ReminderType type) {
|
||||||
|
super(source);
|
||||||
|
this.bookingId = bookingId;
|
||||||
|
this.memberId = memberId;
|
||||||
|
this.courseName = courseName;
|
||||||
|
this.courseTime = courseTime;
|
||||||
|
this.type = type;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getBookingId() {
|
||||||
|
return bookingId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public Long getMemberId() {
|
||||||
|
return memberId;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getCourseName() {
|
||||||
|
return courseName;
|
||||||
|
}
|
||||||
|
|
||||||
|
public String getCourseTime() {
|
||||||
|
return courseTime;
|
||||||
|
}
|
||||||
|
|
||||||
|
public ReminderType getType() {
|
||||||
|
return type;
|
||||||
|
}
|
||||||
|
}
|
||||||
+98
@@ -0,0 +1,98 @@
|
|||||||
|
package cn.novalon.gym.manage.groupcourse.event;
|
||||||
|
|
||||||
|
import cn.novalon.gym.manage.groupcourse.event.BookingReminderEvent.ReminderType;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.context.event.EventListener;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 预约提醒事件监听器
|
||||||
|
*
|
||||||
|
* 监听预约相关事件,处理提醒业务
|
||||||
|
*
|
||||||
|
* @author 张翔
|
||||||
|
* @date 2026-06-01
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
public class BookingReminderEventListener {
|
||||||
|
|
||||||
|
private static final Logger logger = LoggerFactory.getLogger(BookingReminderEventListener.class);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 处理预约提醒事件
|
||||||
|
*
|
||||||
|
* @param event 预约提醒事件
|
||||||
|
*/
|
||||||
|
@EventListener
|
||||||
|
public void handleBookingReminderEvent(BookingReminderEvent event) {
|
||||||
|
logger.info("收到预约提醒事件:type={}, bookingId={}, memberId={}",
|
||||||
|
event.getType(), event.getBookingId(), event.getMemberId());
|
||||||
|
|
||||||
|
try {
|
||||||
|
processReminderEvent(event);
|
||||||
|
} catch (Exception e) {
|
||||||
|
logger.error("处理预约提醒事件失败:bookingId={}, error={}",
|
||||||
|
event.getBookingId(), e.getMessage(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 处理提醒事件
|
||||||
|
*
|
||||||
|
* 根据事件类型执行不同的提醒逻辑
|
||||||
|
*/
|
||||||
|
private void processReminderEvent(BookingReminderEvent event) {
|
||||||
|
switch (event.getType()) {
|
||||||
|
case BOOKING_SUCCESS:
|
||||||
|
handleBookingSuccess(event);
|
||||||
|
break;
|
||||||
|
case COURSE_REMINDER:
|
||||||
|
handleCourseReminder(event);
|
||||||
|
break;
|
||||||
|
case BOOKING_CANCEL:
|
||||||
|
handleBookingCancel(event);
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
logger.warn("未知的提醒事件类型:{}", event.getType());
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.info("预约提醒事件处理完成:bookingId={}", event.getBookingId());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 处理预约成功事件
|
||||||
|
*/
|
||||||
|
private void handleBookingSuccess(BookingReminderEvent event) {
|
||||||
|
logger.info("处理预约成功提醒:会员ID={}, 课程={}, 时间={}",
|
||||||
|
event.getMemberId(), event.getCourseName(), event.getCourseTime());
|
||||||
|
|
||||||
|
// 实际业务中会调用通知服务发送短信、APP推送等
|
||||||
|
// sendNotification(event.getMemberId(), "预约成功",
|
||||||
|
// "您已成功预约课程:" + event.getCourseName() + ",时间:" + event.getCourseTime());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 处理课程即将开始提醒事件
|
||||||
|
*/
|
||||||
|
private void handleCourseReminder(BookingReminderEvent event) {
|
||||||
|
logger.info("处理课程提醒:会员ID={}, 课程={}, 时间={}",
|
||||||
|
event.getMemberId(), event.getCourseName(), event.getCourseTime());
|
||||||
|
|
||||||
|
// 实际业务中会调用通知服务发送课程开始前提醒
|
||||||
|
// sendNotification(event.getMemberId(), "课程提醒",
|
||||||
|
// "您预约的课程" + event.getCourseName() + "即将开始,时间:" + event.getCourseTime());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 处理预约取消事件
|
||||||
|
*/
|
||||||
|
private void handleBookingCancel(BookingReminderEvent event) {
|
||||||
|
logger.info("处理预约取消提醒:会员ID={}, 课程={}",
|
||||||
|
event.getMemberId(), event.getCourseName());
|
||||||
|
|
||||||
|
// 实际业务中会调用通知服务发送预约取消通知
|
||||||
|
// sendNotification(event.getMemberId(), "预约取消",
|
||||||
|
// "您已取消课程:" + event.getCourseName() + "的预约");
|
||||||
|
}
|
||||||
|
}
|
||||||
+74
@@ -0,0 +1,74 @@
|
|||||||
|
package cn.novalon.gym.manage.groupcourse.event;
|
||||||
|
|
||||||
|
import cn.novalon.gym.manage.groupcourse.event.BookingReminderEvent.ReminderType;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.context.ApplicationEventPublisher;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 预约提醒事件发布器
|
||||||
|
*
|
||||||
|
* 使用Spring事件机制发布预约相关事件
|
||||||
|
*
|
||||||
|
* @author 张翔
|
||||||
|
* @date 2026-06-01
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
public class BookingReminderEventPublisher {
|
||||||
|
|
||||||
|
private static final Logger logger = LoggerFactory.getLogger(BookingReminderEventPublisher.class);
|
||||||
|
|
||||||
|
private final ApplicationEventPublisher eventPublisher;
|
||||||
|
|
||||||
|
public BookingReminderEventPublisher(ApplicationEventPublisher eventPublisher) {
|
||||||
|
this.eventPublisher = eventPublisher;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 发布预约成功事件
|
||||||
|
*
|
||||||
|
* @param bookingId 预约ID
|
||||||
|
* @param memberId 会员ID
|
||||||
|
* @param courseName 课程名称
|
||||||
|
* @param courseTime 课程时间
|
||||||
|
*/
|
||||||
|
public void publishBookingSuccessEvent(Long bookingId, Long memberId, String courseName, String courseTime) {
|
||||||
|
BookingReminderEvent event = new BookingReminderEvent(
|
||||||
|
this, bookingId, memberId, courseName, courseTime, ReminderType.BOOKING_SUCCESS);
|
||||||
|
|
||||||
|
logger.info("发布预约成功事件:bookingId={}, memberId={}", bookingId, memberId);
|
||||||
|
eventPublisher.publishEvent(event);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 发布课程即将开始提醒事件
|
||||||
|
*
|
||||||
|
* @param bookingId 预约ID
|
||||||
|
* @param memberId 会员ID
|
||||||
|
* @param courseName 课程名称
|
||||||
|
* @param courseTime 课程时间
|
||||||
|
*/
|
||||||
|
public void publishCourseReminderEvent(Long bookingId, Long memberId, String courseName, String courseTime) {
|
||||||
|
BookingReminderEvent event = new BookingReminderEvent(
|
||||||
|
this, bookingId, memberId, courseName, courseTime, ReminderType.COURSE_REMINDER);
|
||||||
|
|
||||||
|
logger.info("发布课程提醒事件:bookingId={}, memberId={}", bookingId, memberId);
|
||||||
|
eventPublisher.publishEvent(event);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 发布预约取消事件
|
||||||
|
*
|
||||||
|
* @param bookingId 预约ID
|
||||||
|
* @param memberId 会员ID
|
||||||
|
* @param courseName 课程名称
|
||||||
|
*/
|
||||||
|
public void publishBookingCancelEvent(Long bookingId, Long memberId, String courseName) {
|
||||||
|
BookingReminderEvent event = new BookingReminderEvent(
|
||||||
|
this, bookingId, memberId, courseName, null, ReminderType.BOOKING_CANCEL);
|
||||||
|
|
||||||
|
logger.info("发布预约取消事件:bookingId={}, memberId={}", bookingId, memberId);
|
||||||
|
eventPublisher.publishEvent(event);
|
||||||
|
}
|
||||||
|
}
|
||||||
+311
@@ -0,0 +1,311 @@
|
|||||||
|
package cn.novalon.gym.manage.groupcourse.handler;
|
||||||
|
|
||||||
|
import cn.novalon.gym.manage.groupcourse.domain.GroupCourseBooking;
|
||||||
|
import cn.novalon.gym.manage.groupcourse.repository.IGroupCourseBookingRepository;
|
||||||
|
import cn.novalon.gym.manage.member.entity.MemberCard;
|
||||||
|
import cn.novalon.gym.manage.member.entity.MemberCardRecord;
|
||||||
|
import cn.novalon.gym.manage.member.enums.MemberCardType;
|
||||||
|
import cn.novalon.gym.manage.member.repository.MemberCardRepository;
|
||||||
|
import cn.novalon.gym.manage.member.service.IMemberCardRecordService;
|
||||||
|
import cn.novalon.gym.manage.member.service.IMemberStoredCardService;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
import reactor.core.publisher.Mono;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.Collections;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 预约 Saga 处理器
|
||||||
|
*
|
||||||
|
* 实现预约和取消预约的分布式事务处理
|
||||||
|
*
|
||||||
|
* @author 张翔
|
||||||
|
* @date 2026-06-02
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class BookingSagaHandler {
|
||||||
|
|
||||||
|
private final IGroupCourseBookingRepository bookingRepository;
|
||||||
|
private final IMemberCardRecordService memberCardRecordService;
|
||||||
|
private final IMemberStoredCardService memberStoredCardService;
|
||||||
|
private final MemberCardRepository memberCardRepository;
|
||||||
|
|
||||||
|
private static final double DEFAULT_GROUP_COURSE_PRICE = 50.0;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 执行预约事务
|
||||||
|
*
|
||||||
|
* 步骤:
|
||||||
|
* 1. 保存预约记录
|
||||||
|
* 2. 扣减储值卡余额(储值卡类型)
|
||||||
|
* 3. 更新课程当前人数
|
||||||
|
*/
|
||||||
|
public Mono<GroupCourseBooking> executeBooking(GroupCourseBooking booking, Long recordId, BigDecimal storedValueAmount) {
|
||||||
|
List<SagaStep> steps = new ArrayList<>();
|
||||||
|
List<SagaStep> rollbackSteps = new ArrayList<>();
|
||||||
|
|
||||||
|
// 步骤1:保存预约记录
|
||||||
|
SagaStep step1 = new SagaStep(
|
||||||
|
"保存预约记录",
|
||||||
|
saveBooking(booking),
|
||||||
|
Mono.defer(() -> deleteBooking(booking.getId()))
|
||||||
|
);
|
||||||
|
steps.add(step1);
|
||||||
|
rollbackSteps.add(0, step1);
|
||||||
|
|
||||||
|
// 步骤2:扣减权益(根据卡类型)
|
||||||
|
SagaStep step2 = new SagaStep(
|
||||||
|
"扣减权益",
|
||||||
|
deductCardUsageByCardType(booking.getMemberId(), recordId, storedValueAmount),
|
||||||
|
Mono.defer(() -> restoreCardUsageByCardType(booking.getMemberId(), recordId, storedValueAmount))
|
||||||
|
);
|
||||||
|
steps.add(step2);
|
||||||
|
rollbackSteps.add(0, step2);
|
||||||
|
|
||||||
|
return executeSaga(steps, rollbackSteps)
|
||||||
|
.then(Mono.just(booking));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据会员卡类型扣减权益
|
||||||
|
*/
|
||||||
|
private Mono<Void> deductCardUsageByCardType(Long memberId, Long recordId, BigDecimal storedValueAmount) {
|
||||||
|
return memberCardRecordService.findById(recordId)
|
||||||
|
.switchIfEmpty(Mono.error(new RuntimeException("会员卡记录不存在")))
|
||||||
|
.flatMap(record -> {
|
||||||
|
// 验证会员卡归属
|
||||||
|
if (!record.getMemberId().equals(memberId)) {
|
||||||
|
return Mono.error(new RuntimeException("会员卡不归属当前用户"));
|
||||||
|
}
|
||||||
|
|
||||||
|
return memberCardRepository.findById(record.getMemberCardId())
|
||||||
|
.flatMap(card -> {
|
||||||
|
MemberCardType cardType = MemberCardType.valueOf(card.getMemberCardType());
|
||||||
|
|
||||||
|
switch (cardType) {
|
||||||
|
case COUNT_CARD:
|
||||||
|
return Mono.error(new RuntimeException("团课预约仅支持储值卡和时长卡支付"));
|
||||||
|
case STORED_VALUE_CARD:
|
||||||
|
return deductStoredCardBalance(memberId, storedValueAmount);
|
||||||
|
case TIME_CARD:
|
||||||
|
// 时长卡验证有效期后,仍须从储值卡扣款
|
||||||
|
return validateTimeCard(record)
|
||||||
|
.then(deductStoredCardBalance(memberId, storedValueAmount));
|
||||||
|
default:
|
||||||
|
return Mono.error(new RuntimeException("不支持的会员卡类型: " + cardType));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 验证时长卡有效期
|
||||||
|
*
|
||||||
|
* @param record 会员卡记录
|
||||||
|
* @return 验证通过返回Mono.empty(),否则返回Mono.error()
|
||||||
|
*/
|
||||||
|
private Mono<Void> validateTimeCard(MemberCardRecord record) {
|
||||||
|
// 验证会员卡状态
|
||||||
|
cn.novalon.gym.manage.member.enums.MemberCardRecordStatus status = record.getStatus();
|
||||||
|
if (status != cn.novalon.gym.manage.member.enums.MemberCardRecordStatus.ACTIVE) {
|
||||||
|
return Mono.error(new RuntimeException("会员卡状态无效,当前状态: " + (status != null ? status.getDesc() : "未知")));
|
||||||
|
}
|
||||||
|
|
||||||
|
// 验证有效期
|
||||||
|
java.time.LocalDateTime expireTime = record.getExpireTime();
|
||||||
|
if (expireTime == null) {
|
||||||
|
return Mono.error(new RuntimeException("会员卡有效期未设置"));
|
||||||
|
}
|
||||||
|
if (expireTime.isBefore(java.time.LocalDateTime.now())) {
|
||||||
|
return Mono.error(new RuntimeException("会员卡已过期,有效期至: " + expireTime));
|
||||||
|
}
|
||||||
|
|
||||||
|
log.debug("时长卡验证通过: recordId={}, expireTime={}", record.getId(), expireTime);
|
||||||
|
return Mono.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据会员卡类型恢复权益
|
||||||
|
*/
|
||||||
|
private Mono<Void> restoreCardUsageByCardType(Long memberId, Long recordId, BigDecimal storedValueAmount) {
|
||||||
|
return memberCardRecordService.findById(recordId)
|
||||||
|
.switchIfEmpty(Mono.error(new RuntimeException("会员卡记录不存在,无法恢复权益")))
|
||||||
|
.flatMap(record -> {
|
||||||
|
if (memberId != null && !record.getMemberId().equals(memberId)) {
|
||||||
|
return Mono.error(new RuntimeException("会员卡不归属当前用户"));
|
||||||
|
}
|
||||||
|
|
||||||
|
return memberCardRepository.findById(record.getMemberCardId())
|
||||||
|
.flatMap(card -> {
|
||||||
|
MemberCardType cardType = MemberCardType.valueOf(card.getMemberCardType());
|
||||||
|
|
||||||
|
switch (cardType) {
|
||||||
|
case COUNT_CARD:
|
||||||
|
return Mono.empty();
|
||||||
|
case STORED_VALUE_CARD:
|
||||||
|
// 返还储值卡余额(回滚时全额返还)
|
||||||
|
BigDecimal amount = storedValueAmount != null ? storedValueAmount : BigDecimal.valueOf(DEFAULT_GROUP_COURSE_PRICE);
|
||||||
|
return memberStoredCardService.recharge(memberId, amount)
|
||||||
|
.flatMap(rows -> {
|
||||||
|
if (rows > 0) {
|
||||||
|
log.info("储值卡回滚返还成功: memberId={}, amount={}", memberId, amount);
|
||||||
|
return Mono.empty();
|
||||||
|
}
|
||||||
|
return Mono.empty();
|
||||||
|
});
|
||||||
|
case TIME_CARD:
|
||||||
|
// 时长卡回滚时也返还储值卡
|
||||||
|
BigDecimal timeAmount = storedValueAmount != null ? storedValueAmount : BigDecimal.valueOf(DEFAULT_GROUP_COURSE_PRICE);
|
||||||
|
return memberStoredCardService.recharge(memberId, timeAmount)
|
||||||
|
.flatMap(rows -> {
|
||||||
|
if (rows > 0) {
|
||||||
|
log.info("储值卡回滚返还成功(时长卡): memberId={}, amount={}", memberId, timeAmount);
|
||||||
|
return Mono.empty();
|
||||||
|
}
|
||||||
|
return Mono.empty();
|
||||||
|
});
|
||||||
|
default:
|
||||||
|
return Mono.error(new RuntimeException("不支持的会员卡类型: " + cardType));
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 执行取消预约事务
|
||||||
|
*/
|
||||||
|
public Mono<GroupCourseBooking> executeCancelBooking(Long bookingId, Long courseId, Long recordId, Long memberId, BigDecimal storedValueAmount, long cancelCount) {
|
||||||
|
List<SagaStep> steps = new ArrayList<>();
|
||||||
|
List<SagaStep> rollbackSteps = new ArrayList<>();
|
||||||
|
|
||||||
|
// 步骤1:更新预约状态为已取消
|
||||||
|
SagaStep step1 = new SagaStep(
|
||||||
|
"更新预约状态为已取消",
|
||||||
|
updateBookingStatus(bookingId, "1"),
|
||||||
|
Mono.defer(() -> updateBookingStatus(bookingId, "0"))
|
||||||
|
);
|
||||||
|
steps.add(step1);
|
||||||
|
rollbackSteps.add(0, step1);
|
||||||
|
|
||||||
|
// 步骤2:返还储值卡余额(含手续费逻辑)
|
||||||
|
SagaStep step2 = new SagaStep(
|
||||||
|
"返还储值卡余额",
|
||||||
|
refundStoredCardWithFee(memberId, storedValueAmount, cancelCount),
|
||||||
|
// 回滚时重新扣减
|
||||||
|
Mono.defer(() -> deductCardUsageByCardType(memberId, recordId, storedValueAmount))
|
||||||
|
);
|
||||||
|
steps.add(step2);
|
||||||
|
rollbackSteps.add(0, step2);
|
||||||
|
|
||||||
|
return executeSaga(steps, rollbackSteps)
|
||||||
|
.then(bookingRepository.findById(bookingId));
|
||||||
|
}
|
||||||
|
|
||||||
|
private Mono<Void> updateBookingStatus(Long bookingId, String status) {
|
||||||
|
return bookingRepository.updateStatus(bookingId, status)
|
||||||
|
.flatMap(rows -> {
|
||||||
|
if (rows == 0) {
|
||||||
|
return Mono.error(new RuntimeException("更新预约状态失败"));
|
||||||
|
}
|
||||||
|
return Mono.empty();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private Mono<Void> saveBooking(GroupCourseBooking booking) {
|
||||||
|
return bookingRepository.save(booking)
|
||||||
|
.flatMap(saved -> {
|
||||||
|
if (saved.getId() == null) {
|
||||||
|
return Mono.error(new RuntimeException("保存预约记录失败"));
|
||||||
|
}
|
||||||
|
booking.setId(saved.getId());
|
||||||
|
return Mono.empty();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private Mono<Void> deleteBooking(Long bookingId) {
|
||||||
|
return bookingRepository.deleteById(bookingId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从储值卡扣减余额
|
||||||
|
*/
|
||||||
|
private Mono<Void> deductStoredCardBalance(Long memberId, BigDecimal storedValueAmount) {
|
||||||
|
BigDecimal amount = storedValueAmount != null && storedValueAmount.compareTo(BigDecimal.ZERO) > 0
|
||||||
|
? storedValueAmount : BigDecimal.valueOf(DEFAULT_GROUP_COURSE_PRICE);
|
||||||
|
return memberStoredCardService.consume(memberId, amount)
|
||||||
|
.flatMap(rows -> {
|
||||||
|
if (rows == 0) {
|
||||||
|
return Mono.error(new RuntimeException("储值卡扣减失败,余额不足"));
|
||||||
|
}
|
||||||
|
log.info("储值卡扣减成功: memberId={}, amount={}", memberId, amount);
|
||||||
|
return Mono.empty();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 返还储值卡余额(含手续费逻辑,仅用于取消预约)
|
||||||
|
*/
|
||||||
|
private Mono<Void> refundStoredCardWithFee(Long memberId, BigDecimal storedValueAmount, long cancelCount) {
|
||||||
|
BigDecimal amount = storedValueAmount != null && storedValueAmount.compareTo(BigDecimal.ZERO) > 0
|
||||||
|
? storedValueAmount : BigDecimal.valueOf(DEFAULT_GROUP_COURSE_PRICE);
|
||||||
|
return memberStoredCardService.refundBalanceWithFee(memberId, amount, cancelCount)
|
||||||
|
.flatMap(refundedAmount -> {
|
||||||
|
log.info("储值卡退款成功(含手续费): memberId={}, cancelCount={}, 退款金额={}", memberId, cancelCount, refundedAmount);
|
||||||
|
return Mono.empty();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private Mono<Void> executeSaga(List<SagaStep> steps, List<SagaStep> rollbackSteps) {
|
||||||
|
List<SagaStep> completedSteps = new ArrayList<>();
|
||||||
|
return executeStep(steps, 0, completedSteps);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Mono<Void> executeStep(List<SagaStep> steps, int index, List<SagaStep> completedSteps) {
|
||||||
|
if (index >= steps.size()) {
|
||||||
|
return Mono.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
SagaStep currentStep = steps.get(index);
|
||||||
|
|
||||||
|
return currentStep.operation()
|
||||||
|
.doOnSuccess(unused -> completedSteps.add(currentStep))
|
||||||
|
.then(Mono.defer(() -> executeStep(steps, index + 1, completedSteps)))
|
||||||
|
.onErrorResume(error -> {
|
||||||
|
log.error("Saga步骤执行失败: step={}, error={}", currentStep.description(), error.getMessage());
|
||||||
|
return rollbackCompletedSteps(completedSteps).then(Mono.error(error));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
private Mono<Void> rollbackCompletedSteps(List<SagaStep> completedSteps) {
|
||||||
|
if (completedSteps.isEmpty()) {
|
||||||
|
return Mono.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 反转已完成的步骤,按逆序回滚
|
||||||
|
List<SagaStep> reversed = new ArrayList<>(completedSteps);
|
||||||
|
Collections.reverse(reversed);
|
||||||
|
|
||||||
|
return rollbackSteps(reversed, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
private Mono<Void> rollbackSteps(List<SagaStep> rollbackSteps, int index) {
|
||||||
|
if (index >= rollbackSteps.size()) {
|
||||||
|
return Mono.empty();
|
||||||
|
}
|
||||||
|
|
||||||
|
SagaStep currentStep = rollbackSteps.get(index);
|
||||||
|
|
||||||
|
return currentStep.rollbackOperation()
|
||||||
|
.then(Mono.defer(() -> rollbackSteps(rollbackSteps, index + 1)))
|
||||||
|
.doOnError(error -> log.error("Saga回滚失败: step={}, error={}", currentStep.description(), error.getMessage()))
|
||||||
|
.onErrorResume(e -> Mono.empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
private record SagaStep(String description, Mono<Void> operation, Mono<Void> rollbackOperation) {}
|
||||||
|
}
|
||||||
+225
@@ -0,0 +1,225 @@
|
|||||||
|
package cn.novalon.gym.manage.groupcourse.handler;
|
||||||
|
|
||||||
|
import cn.novalon.gym.manage.common.dto.PageRequest;
|
||||||
|
import cn.novalon.gym.manage.groupcourse.domain.CourseLabel;
|
||||||
|
import cn.novalon.gym.manage.groupcourse.service.ICourseLabelService;
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
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.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
@Tag(name = "团课标签管理", description = "团课标签相关操作")
|
||||||
|
public class CourseLabelHandler {
|
||||||
|
|
||||||
|
private final ICourseLabelService courseLabelService;
|
||||||
|
|
||||||
|
public CourseLabelHandler(ICourseLabelService courseLabelService) {
|
||||||
|
this.courseLabelService = courseLabelService;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "获取所有标签", description = "获取系统中所有标签列表")
|
||||||
|
public Mono<ServerResponse> getAllLabels(ServerRequest request) {
|
||||||
|
return ServerResponse.ok()
|
||||||
|
.body(courseLabelService.findAll(), CourseLabel.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "分页查询标签", description = "支持按关键词筛选并分页查询标签")
|
||||||
|
public Mono<ServerResponse> getLabelsByPage(ServerRequest request) {
|
||||||
|
return request.bodyToMono(PageRequest.class)
|
||||||
|
.flatMap(pageRequest -> courseLabelService.findByPage(pageRequest)
|
||||||
|
.flatMap(response -> ServerResponse.ok().bodyValue(response)));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "根据ID获取标签", description = "根据ID获取标签详情")
|
||||||
|
public Mono<ServerResponse> getLabelById(ServerRequest request) {
|
||||||
|
Long id = Long.valueOf(request.pathVariable("id"));
|
||||||
|
return courseLabelService.findById(id)
|
||||||
|
.flatMap(label -> ServerResponse.ok().bodyValue(label))
|
||||||
|
.switchIfEmpty(ServerResponse.notFound().build());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "搜索标签", description = "根据关键词搜索标签")
|
||||||
|
public Mono<ServerResponse> searchLabels(ServerRequest request) {
|
||||||
|
String keyword = request.queryParam("keyword").orElse("");
|
||||||
|
return ServerResponse.ok()
|
||||||
|
.body(courseLabelService.findByKeyword(keyword), CourseLabel.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "创建标签", description = "创建新的标签")
|
||||||
|
public Mono<ServerResponse> createLabel(ServerRequest request) {
|
||||||
|
return request.bodyToMono(CourseLabel.class)
|
||||||
|
.flatMap(courseLabel -> {
|
||||||
|
if (courseLabel.getLabelName() == null || courseLabel.getLabelName().isEmpty()) {
|
||||||
|
Map<String, Object> error = new HashMap<>();
|
||||||
|
error.put("success", false);
|
||||||
|
error.put("message", "标签名称不能为空");
|
||||||
|
return ServerResponse.badRequest().bodyValue(error);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (courseLabel.getLabelName().length() > 50) {
|
||||||
|
Map<String, Object> error = new HashMap<>();
|
||||||
|
error.put("success", false);
|
||||||
|
error.put("message", "标签名称不能超过50个字符");
|
||||||
|
return ServerResponse.badRequest().bodyValue(error);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (courseLabel.getColor() == null || courseLabel.getColor().isEmpty()) {
|
||||||
|
courseLabel.setColor("#1890ff");
|
||||||
|
}
|
||||||
|
|
||||||
|
return courseLabelService.create(courseLabel)
|
||||||
|
.flatMap(label -> {
|
||||||
|
Map<String, Object> response = new HashMap<>();
|
||||||
|
response.put("success", true);
|
||||||
|
response.put("message", "标签创建成功");
|
||||||
|
response.put("data", label);
|
||||||
|
return ServerResponse.ok().bodyValue(response);
|
||||||
|
})
|
||||||
|
.onErrorResume(error -> {
|
||||||
|
Map<String, Object> response = new HashMap<>();
|
||||||
|
response.put("success", false);
|
||||||
|
response.put("message", error.getMessage());
|
||||||
|
return ServerResponse.badRequest().bodyValue(response);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "更新标签", description = "更新指定标签信息")
|
||||||
|
public Mono<ServerResponse> updateLabel(ServerRequest request) {
|
||||||
|
Long id = Long.valueOf(request.pathVariable("id"));
|
||||||
|
|
||||||
|
return request.bodyToMono(CourseLabel.class)
|
||||||
|
.flatMap(courseLabel -> {
|
||||||
|
if (courseLabel.getLabelName() != null && courseLabel.getLabelName().length() > 50) {
|
||||||
|
Map<String, Object> error = new HashMap<>();
|
||||||
|
error.put("success", false);
|
||||||
|
error.put("message", "标签名称不能超过50个字符");
|
||||||
|
return ServerResponse.badRequest().bodyValue(error);
|
||||||
|
}
|
||||||
|
|
||||||
|
return courseLabelService.update(id, courseLabel)
|
||||||
|
.flatMap(label -> {
|
||||||
|
Map<String, Object> response = new HashMap<>();
|
||||||
|
response.put("success", true);
|
||||||
|
response.put("message", "标签更新成功");
|
||||||
|
response.put("data", label);
|
||||||
|
return ServerResponse.ok().bodyValue(response);
|
||||||
|
})
|
||||||
|
.onErrorResume(error -> {
|
||||||
|
Map<String, Object> response = new HashMap<>();
|
||||||
|
response.put("success", false);
|
||||||
|
response.put("message", error.getMessage());
|
||||||
|
return ServerResponse.badRequest().bodyValue(response);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "删除标签", description = "删除指定标签(软删除)")
|
||||||
|
public Mono<ServerResponse> deleteLabel(ServerRequest request) {
|
||||||
|
Long id = Long.valueOf(request.pathVariable("id"));
|
||||||
|
|
||||||
|
return courseLabelService.delete(id)
|
||||||
|
.then(Mono.defer(() -> {
|
||||||
|
Map<String, Object> response = new HashMap<>();
|
||||||
|
response.put("success", true);
|
||||||
|
response.put("message", "标签删除成功");
|
||||||
|
return ServerResponse.ok().bodyValue(response);
|
||||||
|
}))
|
||||||
|
.onErrorResume(error -> {
|
||||||
|
Map<String, Object> response = new HashMap<>();
|
||||||
|
response.put("success", false);
|
||||||
|
response.put("message", error.getMessage());
|
||||||
|
return ServerResponse.badRequest().bodyValue(response);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "获取类型的标签", description = "获取指定团课类型的所有标签")
|
||||||
|
public Mono<ServerResponse> getLabelsByTypeId(ServerRequest request) {
|
||||||
|
Long typeId = Long.valueOf(request.pathVariable("typeId"));
|
||||||
|
return courseLabelService.findByTypeId(typeId)
|
||||||
|
.collectList()
|
||||||
|
.flatMap(list -> ServerResponse.ok().bodyValue(list));
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "为类型添加标签", description = "为指定团课类型添加标签")
|
||||||
|
public Mono<ServerResponse> addLabelsToType(ServerRequest request) {
|
||||||
|
Long typeId = Long.valueOf(request.pathVariable("typeId"));
|
||||||
|
|
||||||
|
return request.bodyToMono(Map.class)
|
||||||
|
.flatMap(body -> {
|
||||||
|
@SuppressWarnings("unchecked")
|
||||||
|
List<?> rawIds = (List<?>) body.get("labelIds");
|
||||||
|
|
||||||
|
if (rawIds == null || rawIds.isEmpty()) {
|
||||||
|
Map<String, Object> error = new HashMap<>();
|
||||||
|
error.put("success", false);
|
||||||
|
error.put("message", "labelIds不能为空");
|
||||||
|
return ServerResponse.badRequest().bodyValue(error);
|
||||||
|
}
|
||||||
|
|
||||||
|
List<Long> labelIds = rawIds.stream()
|
||||||
|
.map(id -> Long.valueOf(String.valueOf(id)))
|
||||||
|
.collect(java.util.stream.Collectors.toList());
|
||||||
|
|
||||||
|
return courseLabelService.addLabelsToType(typeId, labelIds)
|
||||||
|
.then(Mono.defer(() -> {
|
||||||
|
Map<String, Object> response = new HashMap<>();
|
||||||
|
response.put("success", true);
|
||||||
|
response.put("message", "标签添加成功");
|
||||||
|
return ServerResponse.ok().bodyValue(response);
|
||||||
|
}))
|
||||||
|
.onErrorResume(error -> {
|
||||||
|
Map<String, Object> response = new HashMap<>();
|
||||||
|
response.put("success", false);
|
||||||
|
response.put("message", error.getMessage());
|
||||||
|
return ServerResponse.badRequest().bodyValue(response);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "从类型移除标签", description = "从指定团课类型移除标签")
|
||||||
|
public Mono<ServerResponse> removeLabelFromType(ServerRequest request) {
|
||||||
|
Long typeId = Long.valueOf(request.pathVariable("typeId"));
|
||||||
|
Long labelId = Long.valueOf(request.pathVariable("labelId"));
|
||||||
|
|
||||||
|
return courseLabelService.removeLabelFromType(typeId, labelId)
|
||||||
|
.then(Mono.defer(() -> {
|
||||||
|
Map<String, Object> response = new HashMap<>();
|
||||||
|
response.put("success", true);
|
||||||
|
response.put("message", "标签移除成功");
|
||||||
|
return ServerResponse.ok().bodyValue(response);
|
||||||
|
}))
|
||||||
|
.onErrorResume(error -> {
|
||||||
|
Map<String, Object> response = new HashMap<>();
|
||||||
|
response.put("success", false);
|
||||||
|
response.put("message", error.getMessage());
|
||||||
|
return ServerResponse.badRequest().bodyValue(response);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "清空类型标签", description = "清空指定团课类型的所有标签")
|
||||||
|
public Mono<ServerResponse> clearLabelsFromType(ServerRequest request) {
|
||||||
|
Long typeId = Long.valueOf(request.pathVariable("typeId"));
|
||||||
|
|
||||||
|
return courseLabelService.clearLabelsFromType(typeId)
|
||||||
|
.then(Mono.defer(() -> {
|
||||||
|
Map<String, Object> response = new HashMap<>();
|
||||||
|
response.put("success", true);
|
||||||
|
response.put("message", "标签清空成功");
|
||||||
|
return ServerResponse.ok().bodyValue(response);
|
||||||
|
}))
|
||||||
|
.onErrorResume(error -> {
|
||||||
|
Map<String, Object> response = new HashMap<>();
|
||||||
|
response.put("success", false);
|
||||||
|
response.put("message", error.getMessage());
|
||||||
|
return ServerResponse.badRequest().bodyValue(response);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
+150
@@ -0,0 +1,150 @@
|
|||||||
|
package cn.novalon.gym.manage.groupcourse.handler;
|
||||||
|
|
||||||
|
import cn.novalon.gym.manage.groupcourse.domain.GroupCourseBooking;
|
||||||
|
import cn.novalon.gym.manage.groupcourse.service.IGroupCourseBookingService;
|
||||||
|
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;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 团课预约Handler
|
||||||
|
*
|
||||||
|
* @author 张翔
|
||||||
|
* @date 2026-06-01
|
||||||
|
*/
|
||||||
|
@Component
|
||||||
|
@Tag(name = "团课预约", description = "团课预约相关操作")
|
||||||
|
public class GroupCourseBookingHandler {
|
||||||
|
|
||||||
|
private final IGroupCourseBookingService bookingService;
|
||||||
|
|
||||||
|
public GroupCourseBookingHandler(IGroupCourseBookingService bookingService) {
|
||||||
|
this.bookingService = bookingService;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 预约团课
|
||||||
|
*/
|
||||||
|
@Operation(summary = "预约团课", description = "会员预约指定团课")
|
||||||
|
public Mono<ServerResponse> bookCourse(ServerRequest request) {
|
||||||
|
return request.bodyToMono(Map.class)
|
||||||
|
.flatMap(body -> {
|
||||||
|
// 验证必填参数
|
||||||
|
if (body.get("courseId") == null) {
|
||||||
|
return buildErrorResponse("请提供课程ID");
|
||||||
|
}
|
||||||
|
if (body.get("memberId") == null) {
|
||||||
|
return buildErrorResponse("请提供会员ID");
|
||||||
|
}
|
||||||
|
|
||||||
|
Long courseId = toLong(body.get("courseId"), "courseId");
|
||||||
|
Long memberId = toLong(body.get("memberId"), "memberId");
|
||||||
|
|
||||||
|
return bookingService.bookCourse(courseId, memberId)
|
||||||
|
.flatMap(booking -> {
|
||||||
|
Map<String, Object> response = new HashMap<>();
|
||||||
|
response.put("success", true);
|
||||||
|
response.put("message", "预约成功");
|
||||||
|
response.put("data", booking);
|
||||||
|
return ServerResponse.ok().bodyValue(response);
|
||||||
|
})
|
||||||
|
.onErrorResume(error -> {
|
||||||
|
Map<String, Object> response = new HashMap<>();
|
||||||
|
response.put("success", false);
|
||||||
|
response.put("message", error.getMessage());
|
||||||
|
return ServerResponse.badRequest().bodyValue(response);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 取消预约
|
||||||
|
*/
|
||||||
|
@Operation(summary = "取消预约", description = "会员取消已预约的团课")
|
||||||
|
public Mono<ServerResponse> cancelBooking(ServerRequest request) {
|
||||||
|
Long bookingId = Long.valueOf(request.pathVariable("bookingId"));
|
||||||
|
|
||||||
|
return request.bodyToMono(Map.class)
|
||||||
|
.flatMap(body -> {
|
||||||
|
Long memberId = toLong(body.get("memberId"), "memberId");
|
||||||
|
|
||||||
|
return bookingService.cancelBooking(bookingId, memberId)
|
||||||
|
.flatMap(booking -> {
|
||||||
|
Map<String, Object> response = new HashMap<>();
|
||||||
|
response.put("success", true);
|
||||||
|
response.put("message", "取消成功");
|
||||||
|
response.put("data", booking);
|
||||||
|
return ServerResponse.ok().bodyValue(response);
|
||||||
|
})
|
||||||
|
.onErrorResume(error -> {
|
||||||
|
Map<String, Object> response = new HashMap<>();
|
||||||
|
response.put("success", false);
|
||||||
|
response.put("message", error.getMessage());
|
||||||
|
return ServerResponse.badRequest().bodyValue(response);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询会员预约记录
|
||||||
|
*/
|
||||||
|
@Operation(summary = "查询会员预约记录", description = "根据会员ID查询所有预约记录")
|
||||||
|
public Mono<ServerResponse> getBookingsByMemberId(ServerRequest request) {
|
||||||
|
Long memberId = Long.valueOf(request.pathVariable("memberId"));
|
||||||
|
|
||||||
|
return ServerResponse.ok()
|
||||||
|
.body(bookingService.getBookingsByMemberId(memberId), GroupCourseBooking.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询预约详情
|
||||||
|
*/
|
||||||
|
@Operation(summary = "查询预约详情", description = "根据预约ID查询预约详情")
|
||||||
|
public Mono<ServerResponse> getBookingById(ServerRequest request) {
|
||||||
|
Long bookingId = Long.valueOf(request.pathVariable("bookingId"));
|
||||||
|
|
||||||
|
return bookingService.getBookingById(bookingId)
|
||||||
|
.flatMap(booking -> ServerResponse.ok().bodyValue(booking))
|
||||||
|
.switchIfEmpty(ServerResponse.notFound().build());
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询课程预约记录
|
||||||
|
*/
|
||||||
|
@Operation(summary = "查询课程预约记录", description = "根据团课ID查询所有预约记录")
|
||||||
|
public Mono<ServerResponse> getBookingsByCourseId(ServerRequest request) {
|
||||||
|
Long courseId = Long.valueOf(request.pathVariable("courseId"));
|
||||||
|
|
||||||
|
return ServerResponse.ok()
|
||||||
|
.body(bookingService.getBookingsByCourseId(courseId), GroupCourseBooking.class);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 安全转换为 Long,支持 Number 和 String 类型
|
||||||
|
*/
|
||||||
|
private Long toLong(Object value, String fieldName) {
|
||||||
|
if (value instanceof Number) {
|
||||||
|
return ((Number) value).longValue();
|
||||||
|
}
|
||||||
|
if (value instanceof String) {
|
||||||
|
return Long.valueOf((String) value);
|
||||||
|
}
|
||||||
|
throw new IllegalArgumentException("参数 " + fieldName + " 类型不正确");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构建错误响应
|
||||||
|
*/
|
||||||
|
private Mono<ServerResponse> buildErrorResponse(String message) {
|
||||||
|
Map<String, Object> response = new HashMap<>();
|
||||||
|
response.put("success", false);
|
||||||
|
response.put("message", message);
|
||||||
|
return ServerResponse.badRequest().bodyValue(response);
|
||||||
|
}
|
||||||
|
}
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user