Compare commits
74
Commits
product
...
feature_temp
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
38e1168176 | ||
|
|
954f0c582e | ||
|
|
a6ff56291d | ||
|
|
7792b46e51 | ||
|
|
224573763d | ||
|
|
458cbebcec | ||
|
|
7f70542bde | ||
|
|
bdc1ffdfd3 | ||
|
|
9eb250d0f0 | ||
|
|
2cd7c5a1d3 | ||
|
|
98811e86f8 | ||
|
|
9cbada69d3 | ||
|
|
beabf92496 | ||
|
|
f8025b7d15 | ||
|
|
00ec9a4bbf | ||
|
|
e18150ddb2 | ||
|
|
0ef35db0f3 | ||
|
|
b3589ff75d | ||
|
|
50941cd1c1 | ||
|
|
613888d2ef | ||
|
|
8709a0ff1a | ||
|
|
6eac7120c7 | ||
|
|
4979063004 | ||
|
|
e12dc23156 | ||
|
|
ce59cab15b | ||
|
|
662518384b | ||
|
|
ba5cbc21b9 | ||
|
|
a05efb2894 | ||
|
|
cbe119ac64 | ||
|
|
33a8bd276e | ||
|
|
7572aea6b7 | ||
|
|
2d1484897d | ||
|
|
c5edeb7c8b | ||
|
|
57ddaff1ab | ||
|
|
8d0023b171 | ||
|
|
fa3696c8dc | ||
|
|
b0bde7a15c | ||
|
|
9ab661bab3 | ||
|
|
81c825d54a | ||
|
|
3eb2233a0b | ||
|
|
8386f51b0e | ||
|
|
61e218c94d | ||
|
|
68925a4ee4 | ||
|
|
65f0df47bc | ||
|
|
0415cd3a79 | ||
|
|
21889d9584 | ||
|
|
dc8f87b888 | ||
|
|
2b7a1bd850 | ||
|
|
46a15b25bd | ||
|
|
d61ca0e074 | ||
|
|
b7bfeb4c2a | ||
|
|
e876037f11 | ||
|
|
eb98560a01 | ||
|
|
2cc7e6dc80 | ||
|
|
92cfbbffc9 | ||
|
|
b8b580c366 | ||
|
|
111659449f | ||
|
|
d49a90bed6 | ||
|
|
79ba7dfeec | ||
|
|
94dc7ba1cc | ||
|
|
e0f1a3c5b2 | ||
|
|
b418f0c135 | ||
|
|
31399e26dc | ||
|
|
d51e482c4d | ||
|
|
c097ab0dfb | ||
|
|
94ea1656a6 | ||
|
|
cdc437b191 | ||
|
|
42fd011ce2 | ||
|
|
1ac365eeae | ||
|
|
6f49139d34 | ||
|
|
04df758543 | ||
|
|
d8c3239a63 | ||
|
|
44d62744ae | ||
|
|
8ac542dd0a |
@@ -0,0 +1,193 @@
|
|||||||
|
# TourismWithDistance 类修复
|
||||||
|
|
||||||
|
## 问题描述
|
||||||
|
|
||||||
|
`TourismWithDistance` 类被误删,导致以下功能无法正常工作:
|
||||||
|
- 查询附近景区列表接口 `/tourism/nearby`
|
||||||
|
- 景区距离计算和显示
|
||||||
|
- 景区订单展示图片URL设置
|
||||||
|
|
||||||
|
## 解决方案
|
||||||
|
|
||||||
|
### 1. 重新创建 TourismWithDistance 类
|
||||||
|
|
||||||
|
在 `zlt-business/order-center/src/main/java/com/central/order/model/TourismWithDistance.java` 中重新创建了该类:
|
||||||
|
|
||||||
|
```java
|
||||||
|
@Data
|
||||||
|
@EqualsAndHashCode(callSuper = true)
|
||||||
|
public class TourismWithDistance extends Tourism {
|
||||||
|
|
||||||
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 距离(公里)
|
||||||
|
*/
|
||||||
|
private BigDecimal distance;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 距离描述(如:1.2km)
|
||||||
|
*/
|
||||||
|
@TableField(exist = false)
|
||||||
|
private String distanceDesc;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 景区订单展示图片URL
|
||||||
|
*/
|
||||||
|
@TableField(exist = false)
|
||||||
|
private String orderShowImageUrl;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取距离描述
|
||||||
|
* @return 距离描述字符串
|
||||||
|
*/
|
||||||
|
public String getDistanceDesc() {
|
||||||
|
if (distance == null) {
|
||||||
|
return "未知距离";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (distance.compareTo(BigDecimal.ONE) < 0) {
|
||||||
|
// 小于1公里,显示为米
|
||||||
|
int meters = distance.multiply(new BigDecimal("1000")).intValue();
|
||||||
|
return meters + "m";
|
||||||
|
} else {
|
||||||
|
// 大于等于1公里,显示为公里
|
||||||
|
return distance.setScale(1, BigDecimal.ROUND_HALF_UP) + "km";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 类特性
|
||||||
|
|
||||||
|
#### 2.1 继承关系
|
||||||
|
- 继承自 `Tourism` 类,拥有所有景区基本信息
|
||||||
|
- 使用 `@EqualsAndHashCode(callSuper = true)` 确保正确的继承行为
|
||||||
|
|
||||||
|
#### 2.2 新增字段
|
||||||
|
- `distance`: 距离(公里),BigDecimal 类型,精确计算
|
||||||
|
- `distanceDesc`: 距离描述,如 "1.2km" 或 "500m"
|
||||||
|
- `orderShowImageUrl`: 景区订单展示图片URL
|
||||||
|
|
||||||
|
#### 2.3 智能距离描述
|
||||||
|
- 自动根据距离大小选择合适的单位(米/公里)
|
||||||
|
- 小于1公里显示为米,如 "500m"
|
||||||
|
- 大于等于1公里显示为公里,如 "1.2km"
|
||||||
|
- 支持自定义距离描述
|
||||||
|
|
||||||
|
### 3. 使用场景
|
||||||
|
|
||||||
|
#### 3.1 查询附近景区
|
||||||
|
```java
|
||||||
|
@GetMapping("/nearby")
|
||||||
|
public Result<List<TourismWithDistance>> findNearbyTourisms(
|
||||||
|
@RequestParam BigDecimal longitude,
|
||||||
|
@RequestParam BigDecimal latitude,
|
||||||
|
@RequestParam(required = false) Double radius,
|
||||||
|
@RequestParam(required = false) Integer limit) {
|
||||||
|
// 返回包含距离信息的景区列表
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
#### 3.2 数据库查询
|
||||||
|
在 `TourismMapper.xml` 中,SQL 查询会自动计算距离:
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<select id="findNearbyTourisms" resultType="com.central.order.model.TourismWithDistance">
|
||||||
|
<![CDATA[
|
||||||
|
SELECT
|
||||||
|
*,
|
||||||
|
(
|
||||||
|
6371 * acos(
|
||||||
|
cos(radians(#{latitude})) *
|
||||||
|
cos(radians(latitude)) *
|
||||||
|
cos(radians(longitude) - radians(#{longitude})) +
|
||||||
|
sin(radians(#{latitude})) *
|
||||||
|
sin(radians(latitude))
|
||||||
|
)
|
||||||
|
) AS distance
|
||||||
|
FROM tourisms
|
||||||
|
WHERE is_del = 0
|
||||||
|
AND status = 1
|
||||||
|
AND longitude IS NOT NULL
|
||||||
|
AND latitude IS NOT NULL
|
||||||
|
HAVING distance <= #{radius}
|
||||||
|
ORDER BY distance ASC
|
||||||
|
]]>
|
||||||
|
</select>
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. 前端类型定义
|
||||||
|
|
||||||
|
在 `zlt-web/react-web/src/main/frontend/src/services/orders/typings.d.ts` 中:
|
||||||
|
|
||||||
|
```typescript
|
||||||
|
type TourismWithDistance = Tourism & {
|
||||||
|
distance?: number; // 距离(公里)
|
||||||
|
distanceDesc?: string; // 距离描述
|
||||||
|
orderShowImageUrl?: string; // 景区订单展示图片URL
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5. 单元测试
|
||||||
|
|
||||||
|
创建了完整的单元测试 `TourismWithDistanceTest.java`,测试:
|
||||||
|
- 距离描述计算
|
||||||
|
- 继承关系
|
||||||
|
- 订单展示图片URL
|
||||||
|
- 自定义距离描述
|
||||||
|
|
||||||
|
## 修复效果
|
||||||
|
|
||||||
|
### ✅ 已修复的功能
|
||||||
|
1. **查询附近景区接口** - 正常返回包含距离信息的景区列表
|
||||||
|
2. **距离计算** - 自动计算并格式化距离显示
|
||||||
|
3. **景区图片** - 支持设置和获取订单展示图片
|
||||||
|
4. **类型安全** - 完整的类型定义和继承关系
|
||||||
|
|
||||||
|
### 🔧 技术特点
|
||||||
|
- **精确计算**: 使用 BigDecimal 进行距离计算,避免浮点数精度问题
|
||||||
|
- **智能显示**: 根据距离大小自动选择合适的单位
|
||||||
|
- **类型安全**: 完整的 Lombok 注解和继承关系
|
||||||
|
- **测试覆盖**: 完整的单元测试确保功能正确性
|
||||||
|
|
||||||
|
## 使用示例
|
||||||
|
|
||||||
|
### 后端使用
|
||||||
|
```java
|
||||||
|
// 查询附近景区
|
||||||
|
List<TourismWithDistance> nearbyTourisms = tourismService.findNearbyTourisms(
|
||||||
|
new BigDecimal("116.397128"),
|
||||||
|
new BigDecimal("39.916527"),
|
||||||
|
10.0, // 10公里半径
|
||||||
|
20 // 最多返回20个
|
||||||
|
);
|
||||||
|
|
||||||
|
// 获取距离描述
|
||||||
|
for (TourismWithDistance tourism : nearbyTourisms) {
|
||||||
|
System.out.println(tourism.getTourismName() + ": " + tourism.getDistanceDesc());
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 前端使用
|
||||||
|
```typescript
|
||||||
|
// 调用附近景区接口
|
||||||
|
const response = await findNearbyTourisms({
|
||||||
|
longitude: 116.397128,
|
||||||
|
latitude: 39.916527,
|
||||||
|
radius: 10,
|
||||||
|
limit: 20
|
||||||
|
});
|
||||||
|
|
||||||
|
// 显示景区信息
|
||||||
|
response.data.forEach(tourism => {
|
||||||
|
console.log(`${tourism.tourismName}: ${tourism.distanceDesc}`);
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
## 注意事项
|
||||||
|
|
||||||
|
1. **数据库字段**: 确保 `tourisms` 表中有 `longitude` 和 `latitude` 字段
|
||||||
|
2. **索引优化**: 建议为经纬度字段添加索引以提高查询性能
|
||||||
|
3. **距离计算**: 使用球面距离公式,适用于地球表面的距离计算
|
||||||
|
4. **性能考虑**: 对于大量数据,建议添加适当的查询限制和缓存机制
|
||||||
@@ -91,3 +91,37 @@ CREATE INDEX idx_wechat_config_serial_number_2 ON wechat_config(serial_number);
|
|||||||
-- - 在微信支付回调时,通过此字段可以快速定位对应的配置信息
|
-- - 在微信支付回调时,通过此字段可以快速定位对应的配置信息
|
||||||
-- - 与回调请求头中的 Wechatpay-Serial 字段对应
|
-- - 与回调请求头中的 Wechatpay-Serial 字段对应
|
||||||
-- - 支持一个商户配置多个平台证书,通过序列号区分
|
-- - 支持一个商户配置多个平台证书,通过序列号区分
|
||||||
|
|
||||||
|
-- 创建优惠券表
|
||||||
|
CREATE TABLE IF NOT EXISTS `t_coupon` (
|
||||||
|
`id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
|
||||||
|
`coupon_no` varchar(64) NOT NULL COMMENT '优惠券编号',
|
||||||
|
`coupon_name` varchar(128) NOT NULL COMMENT '优惠券名称',
|
||||||
|
`coupon_type` int(11) NOT NULL COMMENT '优惠券类型:1-满减券,2-折扣券,3-免费券',
|
||||||
|
`amount` decimal(10,2) DEFAULT NULL COMMENT '优惠券面额',
|
||||||
|
`min_amount` decimal(10,2) DEFAULT NULL COMMENT '使用门槛金额',
|
||||||
|
`discount_rate` int(11) DEFAULT NULL COMMENT '折扣率(0-100,折扣券时使用)',
|
||||||
|
`status` int(11) NOT NULL DEFAULT '0' COMMENT '优惠券状态:0-未使用,1-已使用,2-已过期,3-已作废',
|
||||||
|
`user_phone` varchar(20) NOT NULL COMMENT '用户手机号',
|
||||||
|
`user_id` bigint(20) DEFAULT NULL COMMENT '用户ID',
|
||||||
|
`source` int(11) NOT NULL DEFAULT '2' COMMENT '来源:1-携程,2-高飞自建',
|
||||||
|
`ctrip_coupon_id` varchar(64) DEFAULT NULL COMMENT '携程优惠券ID(来源为携程时使用)',
|
||||||
|
`valid_start_time` datetime NOT NULL COMMENT '有效期开始时间',
|
||||||
|
`valid_end_time` datetime NOT NULL COMMENT '有效期结束时间',
|
||||||
|
`used_time` datetime DEFAULT NULL COMMENT '使用时间',
|
||||||
|
`used_order_no` varchar(64) DEFAULT NULL COMMENT '使用订单号',
|
||||||
|
`cancel_time` datetime DEFAULT NULL COMMENT '退券时间',
|
||||||
|
`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
|
||||||
|
`update_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
|
||||||
|
`create_by` varchar(64) DEFAULT NULL COMMENT '创建人',
|
||||||
|
`update_by` varchar(64) DEFAULT NULL COMMENT '更新人',
|
||||||
|
`remark` varchar(255) DEFAULT NULL COMMENT '备注',
|
||||||
|
`tenant_id` varchar(64) DEFAULT NULL COMMENT '租户ID',
|
||||||
|
PRIMARY KEY (`id`),
|
||||||
|
UNIQUE KEY `uk_coupon_no` (`coupon_no`),
|
||||||
|
UNIQUE KEY `uk_ctrip_coupon_id` (`ctrip_coupon_id`),
|
||||||
|
KEY `idx_user_phone` (`user_phone`),
|
||||||
|
KEY `idx_status` (`status`),
|
||||||
|
KEY `idx_valid_end_time` (`valid_end_time`),
|
||||||
|
KEY `idx_create_time` (`create_time`)
|
||||||
|
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='优惠券表';
|
||||||
+42
-3
@@ -89,13 +89,13 @@ public class ApiDeviceController {
|
|||||||
// 2. 检查订单状态
|
// 2. 检查订单状态
|
||||||
String orderStatus = orderCenterService.getOrderStatusByOrderNo(orderNo);
|
String orderStatus = orderCenterService.getOrderStatusByOrderNo(orderNo);
|
||||||
if (!isValidOrderStatus(orderStatus)) {
|
if (!isValidOrderStatus(orderStatus)) {
|
||||||
return Result.succeed("设备已执行");
|
return Result.failed("设备已处理,请关注订单详情");
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. 构建控制消息
|
// 3. 构建控制消息
|
||||||
JsonObject controlMessage = buildControlMessage(control, orderNo, deviceId);
|
JsonObject controlMessage = buildControlMessage(control, orderNo, deviceId);
|
||||||
if (controlMessage == null) {
|
if (controlMessage == null) {
|
||||||
return Result.succeed("暂未开放控制权限");
|
return Result.failed("暂未开放控制权限");
|
||||||
}
|
}
|
||||||
|
|
||||||
// 4. 发送设备控制请求
|
// 4. 发送设备控制请求
|
||||||
@@ -160,7 +160,16 @@ public class ApiDeviceController {
|
|||||||
if (requestResult.getStatus() == 200 || requestResult.getStatus() == 500) {
|
if (requestResult.getStatus() == 200 || requestResult.getStatus() == 500) {
|
||||||
log.info("设置设备属性返回消息: message={}", requestResult.getMessage());
|
log.info("设置设备属性返回消息: message={}", requestResult.getMessage());
|
||||||
if (requestResult.getMessage().equals("Device is offline")){
|
if (requestResult.getMessage().equals("Device is offline")){
|
||||||
return Result.failed("Device is offline","设备已离线请稍后重试");
|
// 设备离线时自动创建退款订单
|
||||||
|
log.info("设备离线,开始自动创建退款订单: orderNo={}", orderNo);
|
||||||
|
|
||||||
|
Result refundResult = createRefundForOfflineDevice(orderNo);
|
||||||
|
if (refundResult.getResp_code() != null && refundResult.getResp_code() == 0) {
|
||||||
|
return Result.failed("设备已离线,已自动创建退款订单");
|
||||||
|
} else {
|
||||||
|
log.error("自动创建退款订单失败: orderNo={}, error={}", orderNo, refundResult.getResp_msg());
|
||||||
|
return Result.failed("设备已离线,退款处理失败,请联系客服");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Result updateResult = orderCenterService.updateOrderStatusDoing(orderNo);
|
Result updateResult = orderCenterService.updateOrderStatusDoing(orderNo);
|
||||||
if (updateResult.getResp_code() != null && updateResult.getResp_code() == 0) {
|
if (updateResult.getResp_code() != null && updateResult.getResp_code() == 0) {
|
||||||
@@ -171,6 +180,36 @@ public class ApiDeviceController {
|
|||||||
return Result.failed("请重试");
|
return Result.failed("请重试");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 设备离线时自动创建退款订单
|
||||||
|
* @param orderNo 订单号
|
||||||
|
* @return 退款结果
|
||||||
|
*/
|
||||||
|
private Result createRefundForOfflineDevice(String orderNo) {
|
||||||
|
try {
|
||||||
|
// 构建退款请求体
|
||||||
|
Map<String, Object> refundBody = new HashMap<>();
|
||||||
|
refundBody.put("refundReason", "设备离线,无法提供服务");
|
||||||
|
refundBody.put("refundImgs", ""); // 可以设置为空或者添加默认图片
|
||||||
|
|
||||||
|
// 通过 OrderCenterService 调用退款接口
|
||||||
|
Result refundResult = orderCenterService.createRefundForOfflineDevice(orderNo, refundBody);
|
||||||
|
|
||||||
|
if (refundResult != null && refundResult.getResp_code() != null && refundResult.getResp_code() == 0) {
|
||||||
|
log.info("自动创建退款订单成功: orderNo={}", orderNo);
|
||||||
|
return Result.succeed("退款订单创建成功");
|
||||||
|
} else {
|
||||||
|
log.error("自动创建退款订单失败: orderNo={}, error={}", orderNo,
|
||||||
|
refundResult != null ? refundResult.getResp_msg() : "null");
|
||||||
|
return Result.failed("退款订单创建失败");
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("自动创建退款订单异常: orderNo={}, error={}", orderNo, e.getMessage(), e);
|
||||||
|
return Result.failed("退款订单创建异常: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@GetMapping("/device/wayline")
|
@GetMapping("/device/wayline")
|
||||||
public Result<Map> getWayline(@RequestParam String no){
|
public Result<Map> getWayline(@RequestParam String no){
|
||||||
return Result.succeed(orderCenterService.getWaylineByOrderNo(no));
|
return Result.succeed(orderCenterService.getWaylineByOrderNo(no));
|
||||||
|
|||||||
+9
@@ -30,4 +30,13 @@ public interface OrderCenterService {
|
|||||||
|
|
||||||
@GetMapping("/qrcode/wayline/{orderNo}")
|
@GetMapping("/qrcode/wayline/{orderNo}")
|
||||||
Map<String,Object> getWaylineByOrderNo(@PathVariable("orderNo") String orderNo);
|
Map<String,Object> getWaylineByOrderNo(@PathVariable("orderNo") String orderNo);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 设备离线时自动创建退款订单
|
||||||
|
* @param orderNo 订单号
|
||||||
|
* @param refundBody 退款请求体
|
||||||
|
* @return 退款结果
|
||||||
|
*/
|
||||||
|
@PostMapping("/refund/{orderNo}")
|
||||||
|
Result createRefundForOfflineDevice(@PathVariable("orderNo") String orderNo, @RequestBody Map<String, Object> refundBody);
|
||||||
}
|
}
|
||||||
|
|||||||
+6
@@ -38,6 +38,12 @@ public class OrderCenterServiceFallbackFactory implements FallbackFactory<OrderC
|
|||||||
public Map<String,Object> getWaylineByOrderNo(String orderNo) {
|
public Map<String,Object> getWaylineByOrderNo(String orderNo) {
|
||||||
return null;
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Result createRefundForOfflineDevice(String orderNo, Map<String, Object> refundBody) {
|
||||||
|
log.error("调用订单中心退款接口失败: orderNo={}, cause={}", orderNo, cause.getMessage());
|
||||||
|
return Result.failed("退款服务调用失败");
|
||||||
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,288 @@
|
|||||||
|
# CDN集成说明文档
|
||||||
|
|
||||||
|
## 概述
|
||||||
|
|
||||||
|
本项目已集成阿里云CDN刷新预热功能,支持批量刷新和预热文件,提升静态资源访问性能。
|
||||||
|
|
||||||
|
## 功能特性
|
||||||
|
|
||||||
|
- ✅ 文件缓存刷新
|
||||||
|
- ✅ 目录缓存刷新
|
||||||
|
- ✅ 文件预热
|
||||||
|
- ✅ 批量处理(分批执行)
|
||||||
|
- ✅ 任务状态监控
|
||||||
|
- ✅ 定时任务
|
||||||
|
- ✅ 配额查询
|
||||||
|
- ✅ URL工具类
|
||||||
|
|
||||||
|
## 配置说明
|
||||||
|
|
||||||
|
### 1. 添加依赖
|
||||||
|
|
||||||
|
已在 `pom.xml` 中添加阿里云CDN SDK依赖:
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.aliyun</groupId>
|
||||||
|
<artifactId>aliyun-java-sdk-cdn</artifactId>
|
||||||
|
<version>3.0.2</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.aliyun</groupId>
|
||||||
|
<artifactId>aliyun-java-sdk-core</artifactId>
|
||||||
|
<version>4.6.4</version>
|
||||||
|
</dependency>
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 配置文件
|
||||||
|
|
||||||
|
在 `application.yml` 中添加CDN配置:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
aliyun:
|
||||||
|
cdn:
|
||||||
|
enabled: true
|
||||||
|
access-key-id: ${ALIYUN_ACCESS_KEY_ID:your-access-key-id}
|
||||||
|
access-key-secret: ${ALIYUN_ACCESS_KEY_SECRET:your-access-key-secret}
|
||||||
|
region-id: cn-zhangzhou
|
||||||
|
domain: your-cdn-domain.com
|
||||||
|
default-batch-size: 100
|
||||||
|
task-timeout: 300
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 环境变量配置
|
||||||
|
|
||||||
|
建议使用环境变量配置敏感信息:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
# Linux/macOS
|
||||||
|
export ALIYUN_ACCESS_KEY_ID=your-access-key-id
|
||||||
|
export ALIYUN_ACCESS_KEY_SECRET=your-access-key-secret
|
||||||
|
|
||||||
|
# Windows
|
||||||
|
set ALIYUN_ACCESS_KEY_ID=your-access-key-id
|
||||||
|
set ALIYUN_ACCESS_KEY_SECRET=your-access-key-secret
|
||||||
|
```
|
||||||
|
|
||||||
|
## API接口
|
||||||
|
|
||||||
|
### 1. 刷新文件缓存
|
||||||
|
|
||||||
|
```http
|
||||||
|
POST /api-file/cdn/refresh/files
|
||||||
|
Content-Type: application/json
|
||||||
|
|
||||||
|
[
|
||||||
|
"https://example.com/image1.jpg",
|
||||||
|
"https://example.com/image2.jpg"
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 刷新目录缓存
|
||||||
|
|
||||||
|
```http
|
||||||
|
POST /api-file/cdn/refresh/directories
|
||||||
|
Content-Type: application/json
|
||||||
|
|
||||||
|
[
|
||||||
|
"https://example.com/static/css/",
|
||||||
|
"https://example.com/static/js/"
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 预热文件
|
||||||
|
|
||||||
|
```http
|
||||||
|
POST /api-file/cdn/prefetch?area=domestic
|
||||||
|
Content-Type: application/json
|
||||||
|
|
||||||
|
[
|
||||||
|
"https://example.com/important-file.css",
|
||||||
|
"https://example.com/important-file.js"
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. 批量刷新文件
|
||||||
|
|
||||||
|
```http
|
||||||
|
POST /api-file/cdn/batch/refresh?batchSize=50
|
||||||
|
Content-Type: application/json
|
||||||
|
|
||||||
|
[
|
||||||
|
"https://example.com/file1.jpg",
|
||||||
|
"https://example.com/file2.jpg",
|
||||||
|
// ... 更多文件
|
||||||
|
]
|
||||||
|
```
|
||||||
|
|
||||||
|
### 5. 查询任务状态
|
||||||
|
|
||||||
|
```http
|
||||||
|
GET /api-file/cdn/task/status/{taskId}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 6. 查询刷新配额
|
||||||
|
|
||||||
|
```http
|
||||||
|
GET /api-file/cdn/quota
|
||||||
|
```
|
||||||
|
|
||||||
|
## 代码使用示例
|
||||||
|
|
||||||
|
### 1. 注入CDN服务
|
||||||
|
|
||||||
|
```java
|
||||||
|
@Autowired
|
||||||
|
private ICdnService cdnService;
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 刷新文件缓存
|
||||||
|
|
||||||
|
```java
|
||||||
|
List<String> urls = Arrays.asList(
|
||||||
|
"https://example.com/image1.jpg",
|
||||||
|
"https://example.com/image2.jpg"
|
||||||
|
);
|
||||||
|
|
||||||
|
String taskId = cdnService.refreshFiles(urls);
|
||||||
|
log.info("刷新任务已提交,任务ID: {}", taskId);
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 批量处理
|
||||||
|
|
||||||
|
```java
|
||||||
|
List<String> urls = getLargeUrlList(); // 大量URL
|
||||||
|
boolean success = cdnService.batchRefreshFiles(urls, 100);
|
||||||
|
if (success) {
|
||||||
|
log.info("批量刷新完成");
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. 使用工具类
|
||||||
|
|
||||||
|
```java
|
||||||
|
// 清理URL参数
|
||||||
|
String cleanUrl = CdnUtils.removeUrlParams("https://example.com/image.jpg?param=value");
|
||||||
|
|
||||||
|
// 验证URL格式
|
||||||
|
boolean isValid = CdnUtils.isValidUrl("https://example.com/image.jpg");
|
||||||
|
|
||||||
|
// 批量处理URL
|
||||||
|
List<String> urls = Arrays.asList("url1", "url2", "url3");
|
||||||
|
List<String> validUrls = CdnUtils.filterValidUrls(urls);
|
||||||
|
```
|
||||||
|
|
||||||
|
## 定时任务
|
||||||
|
|
||||||
|
系统已配置以下定时任务:
|
||||||
|
|
||||||
|
- **每日凌晨2点**:清理过期缓存
|
||||||
|
- **每日上午8点**:预热重要文件
|
||||||
|
- **每小时**:检查刷新配额
|
||||||
|
|
||||||
|
## 与订单系统的集成
|
||||||
|
|
||||||
|
### 1. 订单完成后刷新图片缓存
|
||||||
|
|
||||||
|
在订单完成时,可以调用CDN服务刷新相关图片:
|
||||||
|
|
||||||
|
```java
|
||||||
|
@EventListener
|
||||||
|
public void handleOrderCompleted(OrderCompletedEvent event) {
|
||||||
|
String orderNo = event.getOrderNo();
|
||||||
|
|
||||||
|
// 获取订单相关的图片URL
|
||||||
|
List<String> imageUrls = getOrderImageUrls(orderNo);
|
||||||
|
|
||||||
|
// 刷新CDN缓存
|
||||||
|
if (!imageUrls.isEmpty()) {
|
||||||
|
cdnService.refreshFiles(imageUrls);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 批量刷新订单图片
|
||||||
|
|
||||||
|
```java
|
||||||
|
@PostMapping("/refresh/order/{orderNo}")
|
||||||
|
public Result<String> refreshOrderImages(@PathVariable String orderNo) {
|
||||||
|
List<String> imageUrls = getOrderImageUrls(orderNo);
|
||||||
|
if (imageUrls.isEmpty()) {
|
||||||
|
return Result.failed("订单无相关图片");
|
||||||
|
}
|
||||||
|
|
||||||
|
String taskId = cdnService.refreshFiles(imageUrls);
|
||||||
|
return Result.succeed(taskId, "订单图片刷新任务已提交");
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 监控和日志
|
||||||
|
|
||||||
|
### 1. 日志配置
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
logging:
|
||||||
|
level:
|
||||||
|
com.central.file.service.impl.CdnServiceImpl: DEBUG
|
||||||
|
com.central.file.schedule.CdnScheduleTask: INFO
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 关键日志信息
|
||||||
|
|
||||||
|
- 任务提交:`文件刷新成功,任务ID: xxx`
|
||||||
|
- 任务完成:`任务 xxx 已完成`
|
||||||
|
- 任务失败:`任务 xxx 执行失败`
|
||||||
|
- 批量处理:`开始批量刷新文件,总URL数: xxx,批次大小: xxx`
|
||||||
|
|
||||||
|
## 注意事项
|
||||||
|
|
||||||
|
1. **权限配置**:确保RAM用户有CDN操作权限
|
||||||
|
2. **频率限制**:避免过于频繁的刷新请求
|
||||||
|
3. **URL格式**:确保URL格式正确且可访问
|
||||||
|
4. **批次大小**:根据实际情况调整批次大小
|
||||||
|
5. **超时设置**:合理设置任务等待超时时间
|
||||||
|
|
||||||
|
## 故障排查
|
||||||
|
|
||||||
|
### 1. 常见错误
|
||||||
|
|
||||||
|
- **AccessKey错误**:检查AccessKey配置
|
||||||
|
- **权限不足**:确认RAM用户权限
|
||||||
|
- **URL格式错误**:验证URL格式
|
||||||
|
- **网络问题**:检查网络连接
|
||||||
|
|
||||||
|
### 2. 调试方法
|
||||||
|
|
||||||
|
1. 开启DEBUG日志
|
||||||
|
2. 检查任务状态
|
||||||
|
3. 查看配额信息
|
||||||
|
4. 验证URL可访问性
|
||||||
|
|
||||||
|
## 扩展功能
|
||||||
|
|
||||||
|
### 1. 自定义URL处理器
|
||||||
|
|
||||||
|
```java
|
||||||
|
List<String> processedUrls = CdnUtils.processUrls(urls, url -> {
|
||||||
|
// 自定义处理逻辑
|
||||||
|
return url.replace("old-domain.com", "new-domain.com");
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 文件类型过滤
|
||||||
|
|
||||||
|
```java
|
||||||
|
List<String> imageUrls = urls.stream()
|
||||||
|
.filter(CdnUtils::isImageFile)
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 异步处理
|
||||||
|
|
||||||
|
```java
|
||||||
|
@Async
|
||||||
|
public CompletableFuture<String> refreshFilesAsync(List<String> urls) {
|
||||||
|
String taskId = cdnService.refreshFiles(urls);
|
||||||
|
return CompletableFuture.completedFuture(taskId);
|
||||||
|
}
|
||||||
|
```
|
||||||
@@ -107,6 +107,18 @@
|
|||||||
<artifactId>hibernate-validator</artifactId>
|
<artifactId>hibernate-validator</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
|
<!-- 阿里云CDN SDK -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.aliyun</groupId>
|
||||||
|
<artifactId>aliyun-java-sdk-cdn</artifactId>
|
||||||
|
<version>3.0.2</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.aliyun</groupId>
|
||||||
|
<artifactId>aliyun-java-sdk-core</artifactId>
|
||||||
|
<version>4.6.4</version>
|
||||||
|
</dependency>
|
||||||
|
|
||||||
</dependencies>
|
</dependencies>
|
||||||
|
|
||||||
<build>
|
<build>
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
package com.central.file.config;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* CDN配置类
|
||||||
|
*
|
||||||
|
* @author system
|
||||||
|
* @date 2024-12-19
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@Component
|
||||||
|
@ConfigurationProperties(prefix = "aliyun.cdn")
|
||||||
|
public class CdnConfig {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 阿里云AccessKey ID
|
||||||
|
*/
|
||||||
|
private String accessKeyId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 阿里云AccessKey Secret
|
||||||
|
*/
|
||||||
|
private String accessKeySecret;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 地域ID
|
||||||
|
*/
|
||||||
|
private String regionId = "cn-zhangzhou";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 默认域名
|
||||||
|
*/
|
||||||
|
private String domain;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 默认批次大小
|
||||||
|
*/
|
||||||
|
private int defaultBatchSize = 100;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 任务等待超时时间(秒)
|
||||||
|
*/
|
||||||
|
private int taskTimeout = 300;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 是否启用CDN功能
|
||||||
|
*/
|
||||||
|
private boolean enabled = true;
|
||||||
|
}
|
||||||
+194
@@ -0,0 +1,194 @@
|
|||||||
|
package com.central.file.controller;
|
||||||
|
|
||||||
|
import com.central.common.model.Result;
|
||||||
|
import com.central.file.service.ICdnService;
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.Parameter;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* CDN管理控制器
|
||||||
|
*
|
||||||
|
* @author system
|
||||||
|
* @date 2024-12-19
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@RestController
|
||||||
|
@Tag(name = "CDN管理")
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
@RequestMapping("/cdn")
|
||||||
|
public class CdnController {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private ICdnService cdnService;
|
||||||
|
|
||||||
|
@Value("${file.oss-url:goflyapp.oss-cn-beijing.aliyuncs.com}")
|
||||||
|
private String cdnOssUrl;
|
||||||
|
|
||||||
|
@Value("${file.cdn-url:cdn.goflytec.com}")
|
||||||
|
private String cdnUrl;
|
||||||
|
|
||||||
|
@Operation(summary = "刷新文件缓存")
|
||||||
|
@PostMapping("/refresh/files")
|
||||||
|
public Result<String> refreshFiles(@RequestBody List<String> urls) {
|
||||||
|
try {
|
||||||
|
String taskId = cdnService.refreshFiles(urls);
|
||||||
|
return Result.succeed(taskId, "文件刷新任务已提交");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("刷新文件缓存失败", e);
|
||||||
|
return Result.failed("刷新文件缓存失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "刷新目录缓存")
|
||||||
|
@PostMapping("/refresh/directories")
|
||||||
|
public Result<String> refreshDirectories(@RequestBody List<String> urls) {
|
||||||
|
try {
|
||||||
|
String taskId = cdnService.refreshDirectories(urls);
|
||||||
|
return Result.succeed(taskId, "目录刷新任务已提交");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("刷新目录缓存失败", e);
|
||||||
|
return Result.failed("刷新目录缓存失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "预热文件")
|
||||||
|
@PostMapping("/prefetch")
|
||||||
|
public Result<String> prefetchFiles(
|
||||||
|
@RequestBody List<String> urls,
|
||||||
|
@Parameter(description = "预热范围:domestic-仅中国内地,overseas-全球(不包含中国内地),不传-全球")
|
||||||
|
@RequestParam(required = false) String area) {
|
||||||
|
try {
|
||||||
|
// 处理URL,替换OSS域名为CDN域名
|
||||||
|
List<String> processedUrls = processUrls(urls);
|
||||||
|
String taskId = cdnService.prefetchFiles(processedUrls, area);
|
||||||
|
return Result.succeed(taskId, "文件预热任务已提交");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("预热文件失败", e);
|
||||||
|
return Result.failed("预热文件失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "批量刷新文件")
|
||||||
|
@PostMapping("/batch/refresh")
|
||||||
|
public Result<Boolean> batchRefreshFiles(
|
||||||
|
@RequestBody List<String> urls,
|
||||||
|
@Parameter(description = "每批次处理的URL数量,默认100")
|
||||||
|
@RequestParam(defaultValue = "100") int batchSize) {
|
||||||
|
try {
|
||||||
|
boolean result = cdnService.batchRefreshFiles(urls, batchSize);
|
||||||
|
return Result.succeed(result, "批量刷新文件完成");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("批量刷新文件失败", e);
|
||||||
|
return Result.failed("批量刷新文件失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "批量预热文件")
|
||||||
|
@PostMapping("/batch/prefetch")
|
||||||
|
public Result<Boolean> batchPrefetchFiles(
|
||||||
|
@RequestBody List<String> urls,
|
||||||
|
@Parameter(description = "每批次处理的URL数量,默认100")
|
||||||
|
@RequestParam(defaultValue = "100") int batchSize,
|
||||||
|
@Parameter(description = "预热范围:domestic-仅中国内地,overseas-全球(不包含中国内地),不传-全球")
|
||||||
|
@RequestParam(required = false) String area) {
|
||||||
|
try {
|
||||||
|
// 处理URL,替换OSS域名为CDN域名
|
||||||
|
List<String> processedUrls = processUrls(urls);
|
||||||
|
boolean result = cdnService.batchPrefetchFiles(processedUrls, batchSize, area);
|
||||||
|
return Result.succeed(result, "批量预热文件完成");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("批量预热文件失败", e);
|
||||||
|
return Result.failed("批量预热文件失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "查询刷新任务状态")
|
||||||
|
@GetMapping("/task/status/{taskId}")
|
||||||
|
public Result<String> getRefreshTaskStatus(@PathVariable String taskId) {
|
||||||
|
try {
|
||||||
|
String status = cdnService.getRefreshTaskStatus(taskId);
|
||||||
|
return Result.succeed(status, "查询成功");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("查询刷新任务状态失败", e);
|
||||||
|
return Result.failed("查询刷新任务状态失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "查询刷新配额")
|
||||||
|
@GetMapping("/quota")
|
||||||
|
public Result<Object> getRefreshQuota() {
|
||||||
|
try {
|
||||||
|
Object quota = cdnService.getRefreshQuota();
|
||||||
|
return Result.succeed(quota, "查询成功");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("查询刷新配额失败", e);
|
||||||
|
return Result.failed("查询刷新配额失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "刷新指定订单的图片缓存")
|
||||||
|
@PostMapping("/refresh/order/{orderNo}")
|
||||||
|
public Result<String> refreshOrderImages(@PathVariable String orderNo) {
|
||||||
|
try {
|
||||||
|
// 这里可以调用订单服务获取订单相关的图片URL
|
||||||
|
// 然后进行CDN刷新
|
||||||
|
// 示例:根据订单号获取图片URL列表
|
||||||
|
List<String> imageUrls = getOrderImageUrls(orderNo);
|
||||||
|
if (imageUrls.isEmpty()) {
|
||||||
|
return Result.failed("订单无相关图片");
|
||||||
|
}
|
||||||
|
|
||||||
|
String taskId = cdnService.refreshFiles(imageUrls);
|
||||||
|
return Result.succeed(taskId, "订单图片刷新任务已提交");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("刷新订单图片失败,订单号: {}", orderNo, e);
|
||||||
|
return Result.failed("刷新订单图片失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取订单相关的图片URL列表
|
||||||
|
* 这里需要根据实际业务逻辑实现
|
||||||
|
*/
|
||||||
|
private List<String> getOrderImageUrls(String orderNo) {
|
||||||
|
// TODO: 实现获取订单图片URL的逻辑
|
||||||
|
// 可以通过调用订单服务或文件服务来获取
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 处理URL列表,替换OSS域名为CDN域名
|
||||||
|
* @param urls 原始URL列表
|
||||||
|
* @return 处理后的URL列表
|
||||||
|
*/
|
||||||
|
private List<String> processUrls(List<String> urls) {
|
||||||
|
if (urls == null || urls.isEmpty()) {
|
||||||
|
return urls;
|
||||||
|
}
|
||||||
|
|
||||||
|
return urls.stream()
|
||||||
|
.map(url -> {
|
||||||
|
if (url != null && url.contains(cdnOssUrl)) {
|
||||||
|
String processedUrl = url.replace(cdnOssUrl, cdnUrl);
|
||||||
|
// 移除URL参数
|
||||||
|
int questionMarkIndex = processedUrl.indexOf('?');
|
||||||
|
if (questionMarkIndex != -1) {
|
||||||
|
processedUrl = processedUrl.substring(0, questionMarkIndex);
|
||||||
|
}
|
||||||
|
log.debug("URL域名替换: {} -> {}", url, processedUrl);
|
||||||
|
return processedUrl;
|
||||||
|
}
|
||||||
|
return url;
|
||||||
|
})
|
||||||
|
.toList();
|
||||||
|
}
|
||||||
|
}
|
||||||
+104
@@ -0,0 +1,104 @@
|
|||||||
|
package com.central.file.schedule;
|
||||||
|
|
||||||
|
import com.central.file.service.ICdnService;
|
||||||
|
import lombok.RequiredArgsConstructor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.beans.factory.annotation.Value;
|
||||||
|
import org.springframework.scheduling.annotation.Scheduled;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* CDN定时任务
|
||||||
|
*
|
||||||
|
* @author system
|
||||||
|
* @date 2024-12-19
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class CdnScheduleTask {
|
||||||
|
|
||||||
|
private final ICdnService cdnService;
|
||||||
|
|
||||||
|
@Value("${aliyun.cdn.enabled:false}")
|
||||||
|
private boolean cdnEnabled;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 每天凌晨2点清理过期缓存
|
||||||
|
* 清理一些可能过期的静态资源缓存
|
||||||
|
*/
|
||||||
|
@Scheduled(cron = "0 0 2 * * ?")
|
||||||
|
public void cleanExpiredCache() {
|
||||||
|
if (!cdnEnabled) {
|
||||||
|
log.info("CDN功能未启用,跳过缓存清理任务");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info("开始执行CDN缓存清理任务");
|
||||||
|
try {
|
||||||
|
// 清理一些常见的静态资源目录
|
||||||
|
List<String> directories = List.of(
|
||||||
|
"/static/css/",
|
||||||
|
"/static/js/",
|
||||||
|
"/static/images/"
|
||||||
|
);
|
||||||
|
|
||||||
|
for (String directory : directories) {
|
||||||
|
try {
|
||||||
|
String taskId = cdnService.refreshDirectories(List.of(directory));
|
||||||
|
log.info("目录 {} 缓存清理任务已提交,任务ID: {}", directory, taskId);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("目录 {} 缓存清理失败", directory, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("CDN缓存清理任务执行失败", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 每天上午8点预热重要文件
|
||||||
|
* 预热一些常用的静态资源文件
|
||||||
|
*/
|
||||||
|
@Scheduled(cron = "0 0 8 * * ?")
|
||||||
|
public void prefetchImportantFiles() {
|
||||||
|
if (!cdnEnabled) {
|
||||||
|
log.info("CDN功能未启用,跳过文件预热任务");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info("开始执行CDN文件预热任务");
|
||||||
|
try {
|
||||||
|
// 预热一些重要的静态资源文件
|
||||||
|
List<String> importantFiles = List.of(
|
||||||
|
"/static/css/main.css",
|
||||||
|
"/static/js/app.js",
|
||||||
|
"/static/images/logo.png"
|
||||||
|
);
|
||||||
|
|
||||||
|
String taskId = cdnService.prefetchFiles(importantFiles, "domestic");
|
||||||
|
log.info("重要文件预热任务已提交,任务ID: {}", taskId);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("CDN文件预热任务执行失败", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 每小时检查一次刷新配额
|
||||||
|
*/
|
||||||
|
@Scheduled(cron = "0 0 * * * ?")
|
||||||
|
public void checkRefreshQuota() {
|
||||||
|
if (!cdnEnabled) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
Object quota = cdnService.getRefreshQuota();
|
||||||
|
log.info("CDN刷新配额信息: {}", quota);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("查询CDN刷新配额失败", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,71 @@
|
|||||||
|
package com.central.file.service;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* CDN服务接口
|
||||||
|
*
|
||||||
|
* @author system
|
||||||
|
* @date 2024-12-19
|
||||||
|
*/
|
||||||
|
public interface ICdnService {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 刷新文件缓存
|
||||||
|
*
|
||||||
|
* @param urls 需要刷新的URL列表
|
||||||
|
* @return 刷新任务ID
|
||||||
|
*/
|
||||||
|
String refreshFiles(List<String> urls);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 刷新目录缓存
|
||||||
|
*
|
||||||
|
* @param urls 需要刷新的目录URL列表
|
||||||
|
* @return 刷新任务ID
|
||||||
|
*/
|
||||||
|
String refreshDirectories(List<String> urls);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 预热文件
|
||||||
|
*
|
||||||
|
* @param urls 需要预热的URL列表
|
||||||
|
* @param area 预热范围:domestic-仅中国内地,overseas-全球(不包含中国内地),不传-全球
|
||||||
|
* @return 预热任务ID
|
||||||
|
*/
|
||||||
|
String prefetchFiles(List<String> urls, String area);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 批量刷新文件(分批处理)
|
||||||
|
*
|
||||||
|
* @param urls 需要刷新的URL列表
|
||||||
|
* @param batchSize 每批次处理的URL数量
|
||||||
|
* @return 任务执行结果
|
||||||
|
*/
|
||||||
|
boolean batchRefreshFiles(List<String> urls, int batchSize);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 批量预热文件(分批处理)
|
||||||
|
*
|
||||||
|
* @param urls 需要预热的URL列表
|
||||||
|
* @param batchSize 每批次处理的URL数量
|
||||||
|
* @param area 预热范围
|
||||||
|
* @return 任务执行结果
|
||||||
|
*/
|
||||||
|
boolean batchPrefetchFiles(List<String> urls, int batchSize, String area);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询刷新任务状态
|
||||||
|
*
|
||||||
|
* @param taskId 任务ID
|
||||||
|
* @return 任务状态
|
||||||
|
*/
|
||||||
|
String getRefreshTaskStatus(String taskId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询刷新配额
|
||||||
|
*
|
||||||
|
* @return 配额信息
|
||||||
|
*/
|
||||||
|
Object getRefreshQuota();
|
||||||
|
}
|
||||||
+268
@@ -0,0 +1,268 @@
|
|||||||
|
package com.central.file.service.impl;
|
||||||
|
|
||||||
|
import com.aliyuncs.DefaultAcsClient;
|
||||||
|
import com.aliyuncs.IAcsClient;
|
||||||
|
import com.aliyuncs.cdn.model.v20180510.*;
|
||||||
|
import com.aliyuncs.profile.DefaultProfile;
|
||||||
|
import com.central.file.config.CdnConfig;
|
||||||
|
import com.central.file.service.ICdnService;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.util.CollectionUtils;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.concurrent.TimeUnit;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* CDN服务实现类
|
||||||
|
*
|
||||||
|
* @author system
|
||||||
|
* @date 2024-12-19
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Service
|
||||||
|
public class CdnServiceImpl implements ICdnService {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private CdnConfig cdnConfig;
|
||||||
|
|
||||||
|
private IAcsClient acsClient;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 初始化ACS客户端
|
||||||
|
*/
|
||||||
|
private IAcsClient getAcsClient() {
|
||||||
|
if (acsClient == null) {
|
||||||
|
DefaultProfile profile = DefaultProfile.getProfile(
|
||||||
|
cdnConfig.getRegionId(),
|
||||||
|
cdnConfig.getAccessKeyId(),
|
||||||
|
cdnConfig.getAccessKeySecret()
|
||||||
|
);
|
||||||
|
acsClient = new DefaultAcsClient(profile);
|
||||||
|
}
|
||||||
|
return acsClient;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String refreshFiles(List<String> urls) {
|
||||||
|
if (!cdnConfig.isEnabled() || CollectionUtils.isEmpty(urls)) {
|
||||||
|
log.warn("CDN功能未启用或URL列表为空");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
RefreshObjectCachesRequest request = new RefreshObjectCachesRequest();
|
||||||
|
request.setObjectPath(String.join("\n", urls));
|
||||||
|
request.setObjectType("File");
|
||||||
|
|
||||||
|
RefreshObjectCachesResponse response = getAcsClient().getAcsResponse(request);
|
||||||
|
log.info("文件刷新成功,任务ID: {}", response.getRefreshTaskId());
|
||||||
|
return response.getRefreshTaskId();
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("文件刷新失败", e);
|
||||||
|
throw new RuntimeException("文件刷新失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String refreshDirectories(List<String> urls) {
|
||||||
|
if (!cdnConfig.isEnabled() || CollectionUtils.isEmpty(urls)) {
|
||||||
|
log.warn("CDN功能未启用或URL列表为空");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
RefreshObjectCachesRequest request = new RefreshObjectCachesRequest();
|
||||||
|
request.setObjectPath(String.join("\n", urls));
|
||||||
|
request.setObjectType("Directory");
|
||||||
|
|
||||||
|
RefreshObjectCachesResponse response = getAcsClient().getAcsResponse(request);
|
||||||
|
log.info("目录刷新成功,任务ID: {}", response.getRefreshTaskId());
|
||||||
|
return response.getRefreshTaskId();
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("目录刷新失败", e);
|
||||||
|
throw new RuntimeException("目录刷新失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String prefetchFiles(List<String> urls, String area) {
|
||||||
|
if (!cdnConfig.isEnabled() || CollectionUtils.isEmpty(urls)) {
|
||||||
|
log.warn("CDN功能未启用或URL列表为空");
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
PushObjectCacheRequest request = new PushObjectCacheRequest();
|
||||||
|
request.setObjectPath(String.join("\n", urls));
|
||||||
|
if (area != null && !area.isEmpty()) {
|
||||||
|
request.setArea(area);
|
||||||
|
}
|
||||||
|
|
||||||
|
PushObjectCacheResponse response = getAcsClient().getAcsResponse(request);
|
||||||
|
log.info("文件预热成功,任务ID: {}", response.getPreloadTaskId());
|
||||||
|
return response.getPreloadTaskId();
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("文件预热失败", e);
|
||||||
|
throw new RuntimeException("文件预热失败: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean batchRefreshFiles(List<String> urls, int batchSize) {
|
||||||
|
if (!cdnConfig.isEnabled() || CollectionUtils.isEmpty(urls)) {
|
||||||
|
log.warn("CDN功能未启用或URL列表为空");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
int actualBatchSize = batchSize > 0 ? batchSize : cdnConfig.getDefaultBatchSize();
|
||||||
|
List<List<String>> batches = splitIntoBatches(urls, actualBatchSize);
|
||||||
|
|
||||||
|
log.info("开始批量刷新文件,总URL数: {}, 批次大小: {}, 总批次数: {}",
|
||||||
|
urls.size(), actualBatchSize, batches.size());
|
||||||
|
|
||||||
|
for (int i = 0; i < batches.size(); i++) {
|
||||||
|
List<String> batch = batches.get(i);
|
||||||
|
log.info("处理第 {} 批次,URL数量: {}", i + 1, batch.size());
|
||||||
|
|
||||||
|
try {
|
||||||
|
String taskId = refreshFiles(batch);
|
||||||
|
if (taskId != null) {
|
||||||
|
// 等待任务完成
|
||||||
|
waitForTaskCompletion(taskId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 批次间延迟,避免频率限制
|
||||||
|
if (i < batches.size() - 1) {
|
||||||
|
TimeUnit.SECONDS.sleep(1);
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("批次 {} 处理失败", i + 1, e);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info("批量刷新文件完成");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean batchPrefetchFiles(List<String> urls, int batchSize, String area) {
|
||||||
|
if (!cdnConfig.isEnabled() || CollectionUtils.isEmpty(urls)) {
|
||||||
|
log.warn("CDN功能未启用或URL列表为空");
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
int actualBatchSize = batchSize > 0 ? batchSize : cdnConfig.getDefaultBatchSize();
|
||||||
|
List<List<String>> batches = splitIntoBatches(urls, actualBatchSize);
|
||||||
|
|
||||||
|
log.info("开始批量预热文件,总URL数: {}, 批次大小: {}, 总批次数: {}",
|
||||||
|
urls.size(), actualBatchSize, batches.size());
|
||||||
|
|
||||||
|
for (int i = 0; i < batches.size(); i++) {
|
||||||
|
List<String> batch = batches.get(i);
|
||||||
|
log.info("处理第 {} 批次,URL数量: {}", i + 1, batch.size());
|
||||||
|
|
||||||
|
try {
|
||||||
|
String taskId = prefetchFiles(batch, area);
|
||||||
|
if (taskId != null) {
|
||||||
|
// 等待任务完成
|
||||||
|
waitForTaskCompletion(taskId);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 批次间延迟,避免频率限制
|
||||||
|
if (i < batches.size() - 1) {
|
||||||
|
TimeUnit.SECONDS.sleep(1);
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("批次 {} 处理失败", i + 1, e);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info("批量预热文件完成");
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getRefreshTaskStatus(String taskId) {
|
||||||
|
if (!cdnConfig.isEnabled() || taskId == null) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
DescribeRefreshTasksRequest request = new DescribeRefreshTasksRequest();
|
||||||
|
request.setTaskId(taskId);
|
||||||
|
|
||||||
|
DescribeRefreshTasksResponse response = getAcsClient().getAcsResponse(request);
|
||||||
|
if (response.getTasks() != null && !response.getTasks().isEmpty()) {
|
||||||
|
return response.getTasks().get(0).getStatus();
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("查询任务状态失败,任务ID: {}", taskId, e);
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Object getRefreshQuota() {
|
||||||
|
if (!cdnConfig.isEnabled()) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
DescribeRefreshQuotaRequest request = new DescribeRefreshQuotaRequest();
|
||||||
|
DescribeRefreshQuotaResponse response = getAcsClient().getAcsResponse(request);
|
||||||
|
return response;
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("查询刷新配额失败", e);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 将URL列表分割成批次
|
||||||
|
*/
|
||||||
|
private List<List<String>> splitIntoBatches(List<String> urls, int batchSize) {
|
||||||
|
List<List<String>> batches = new ArrayList<>();
|
||||||
|
for (int i = 0; i < urls.size(); i += batchSize) {
|
||||||
|
int end = Math.min(i + batchSize, urls.size());
|
||||||
|
batches.add(urls.subList(i, end));
|
||||||
|
}
|
||||||
|
return batches;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 等待任务完成
|
||||||
|
*/
|
||||||
|
private void waitForTaskCompletion(String taskId) {
|
||||||
|
int timeout = cdnConfig.getTaskTimeout();
|
||||||
|
int waitTime = 0;
|
||||||
|
int checkInterval = 5; // 每5秒检查一次
|
||||||
|
|
||||||
|
while (waitTime < timeout) {
|
||||||
|
try {
|
||||||
|
String status = getRefreshTaskStatus(taskId);
|
||||||
|
if ("Complete".equals(status)) {
|
||||||
|
log.info("任务 {} 已完成", taskId);
|
||||||
|
return;
|
||||||
|
} else if ("Failed".equals(status)) {
|
||||||
|
log.error("任务 {} 执行失败", taskId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
TimeUnit.SECONDS.sleep(checkInterval);
|
||||||
|
waitTime += checkInterval;
|
||||||
|
} catch (InterruptedException e) {
|
||||||
|
Thread.currentThread().interrupt();
|
||||||
|
log.warn("等待任务完成被中断");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
log.warn("任务 {} 等待超时", taskId);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,213 @@
|
|||||||
|
package com.central.file.utils;
|
||||||
|
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
|
import java.net.URL;
|
||||||
|
import java.util.ArrayList;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.regex.Pattern;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* CDN工具类
|
||||||
|
*
|
||||||
|
* @author system
|
||||||
|
* @date 2024-12-19
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
public class CdnUtils {
|
||||||
|
|
||||||
|
// URL验证正则表达式
|
||||||
|
private static final Pattern URL_PATTERN = Pattern.compile(
|
||||||
|
"^https?://[\\w\\-]+(\\.[\\w\\-]+)+([\\w\\-\\.,@?^=%&:/~\\+#]*[\\w\\-\\@?^=%&/~\\+#])?$"
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 验证URL格式是否有效
|
||||||
|
*
|
||||||
|
* @param url URL字符串
|
||||||
|
* @return 是否有效
|
||||||
|
*/
|
||||||
|
public static boolean isValidUrl(String url) {
|
||||||
|
if (!StringUtils.hasText(url)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
return URL_PATTERN.matcher(url).matches();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 移除URL中的查询参数
|
||||||
|
*
|
||||||
|
* @param url 原始URL
|
||||||
|
* @return 移除参数后的URL
|
||||||
|
*/
|
||||||
|
public static String removeUrlParams(String url) {
|
||||||
|
if (!StringUtils.hasText(url)) {
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
|
||||||
|
int questionMarkIndex = url.indexOf('?');
|
||||||
|
if (questionMarkIndex != -1) {
|
||||||
|
return url.substring(0, questionMarkIndex);
|
||||||
|
}
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 替换URL域名
|
||||||
|
*
|
||||||
|
* @param url 原始URL
|
||||||
|
* @param oldDomain 旧域名
|
||||||
|
* @param newDomain 新域名
|
||||||
|
* @return 替换后的URL
|
||||||
|
*/
|
||||||
|
public static String replaceDomain(String url, String oldDomain, String newDomain) {
|
||||||
|
if (!StringUtils.hasText(url) || !StringUtils.hasText(oldDomain) || !StringUtils.hasText(newDomain)) {
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
|
||||||
|
return url.replace(oldDomain, newDomain);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 批量处理URL列表
|
||||||
|
*
|
||||||
|
* @param urls URL列表
|
||||||
|
* @param processor URL处理器
|
||||||
|
* @return 处理后的URL列表
|
||||||
|
*/
|
||||||
|
public static List<String> processUrls(List<String> urls, UrlProcessor processor) {
|
||||||
|
List<String> processedUrls = new ArrayList<>();
|
||||||
|
|
||||||
|
if (urls == null || urls.isEmpty()) {
|
||||||
|
return processedUrls;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (String url : urls) {
|
||||||
|
try {
|
||||||
|
String processedUrl = processor.process(url);
|
||||||
|
if (StringUtils.hasText(processedUrl)) {
|
||||||
|
processedUrls.add(processedUrl);
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("处理URL失败: {}", url, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return processedUrls;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 过滤有效的URL
|
||||||
|
*
|
||||||
|
* @param urls URL列表
|
||||||
|
* @return 有效的URL列表
|
||||||
|
*/
|
||||||
|
public static List<String> filterValidUrls(List<String> urls) {
|
||||||
|
return processUrls(urls, url -> isValidUrl(url) ? url : null);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清理URL列表(移除参数并验证格式)
|
||||||
|
*
|
||||||
|
* @param urls URL列表
|
||||||
|
* @return 清理后的URL列表
|
||||||
|
*/
|
||||||
|
public static List<String> cleanUrls(List<String> urls) {
|
||||||
|
return processUrls(urls, url -> {
|
||||||
|
String cleanedUrl = removeUrlParams(url);
|
||||||
|
return isValidUrl(cleanedUrl) ? cleanedUrl : null;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 从文件路径生成CDN URL
|
||||||
|
*
|
||||||
|
* @param filePath 文件路径
|
||||||
|
* @param cdnDomain CDN域名
|
||||||
|
* @return CDN URL
|
||||||
|
*/
|
||||||
|
public static String generateCdnUrl(String filePath, String cdnDomain) {
|
||||||
|
if (!StringUtils.hasText(filePath) || !StringUtils.hasText(cdnDomain)) {
|
||||||
|
return filePath;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 确保文件路径以/开头
|
||||||
|
if (!filePath.startsWith("/")) {
|
||||||
|
filePath = "/" + filePath;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 确保CDN域名不以/结尾
|
||||||
|
if (cdnDomain.endsWith("/")) {
|
||||||
|
cdnDomain = cdnDomain.substring(0, cdnDomain.length() - 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
return cdnDomain + filePath;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取URL的文件扩展名
|
||||||
|
*
|
||||||
|
* @param url URL字符串
|
||||||
|
* @return 文件扩展名(不包含点)
|
||||||
|
*/
|
||||||
|
public static String getFileExtension(String url) {
|
||||||
|
if (!StringUtils.hasText(url)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
String cleanUrl = removeUrlParams(url);
|
||||||
|
int lastDotIndex = cleanUrl.lastIndexOf('.');
|
||||||
|
int lastSlashIndex = cleanUrl.lastIndexOf('/');
|
||||||
|
|
||||||
|
if (lastDotIndex > lastSlashIndex && lastDotIndex < cleanUrl.length() - 1) {
|
||||||
|
return cleanUrl.substring(lastDotIndex + 1).toLowerCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断是否为图片文件
|
||||||
|
*
|
||||||
|
* @param url URL字符串
|
||||||
|
* @return 是否为图片
|
||||||
|
*/
|
||||||
|
public static boolean isImageFile(String url) {
|
||||||
|
String extension = getFileExtension(url);
|
||||||
|
if (extension == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return List.of("jpg", "jpeg", "png", "gif", "bmp", "webp").contains(extension);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 判断是否为视频文件
|
||||||
|
*
|
||||||
|
* @param url URL字符串
|
||||||
|
* @return 是否为视频
|
||||||
|
*/
|
||||||
|
public static boolean isVideoFile(String url) {
|
||||||
|
String extension = getFileExtension(url);
|
||||||
|
if (extension == null) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return List.of("mp4", "avi", "mov", "wmv", "flv", "webm").contains(extension);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* URL处理器接口
|
||||||
|
*/
|
||||||
|
@FunctionalInterface
|
||||||
|
public interface UrlProcessor {
|
||||||
|
/**
|
||||||
|
* 处理URL
|
||||||
|
*
|
||||||
|
* @param url 原始URL
|
||||||
|
* @return 处理后的URL,返回null表示过滤掉该URL
|
||||||
|
*/
|
||||||
|
String process(String url);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
# 热数据同步配置
|
|
||||||
zlt:
|
|
||||||
storage:
|
|
||||||
# 热数据同步配置
|
|
||||||
hot-sync:
|
|
||||||
enabled: true # 是否启用热数据同步
|
|
||||||
batch-size: 100 # 批次大小
|
|
||||||
interval-minutes: 30 # 同步间隔(分钟)
|
|
||||||
access-threshold: 10 # 访问次数阈值
|
|
||||||
max-threads: 5 # 最大线程数
|
|
||||||
|
|
||||||
# 同步定时任务配置
|
|
||||||
sync:
|
|
||||||
schedule:
|
|
||||||
enabled: true # 是否启用定时任务
|
|
||||||
cron: "0 0 2 * * ?" # 每日同步时间(默认凌晨2点)
|
|
||||||
status-check:
|
|
||||||
cron: "0 0 * * * ?" # 状态检查时间(每小时)
|
|
||||||
|
|
||||||
# 迁移配置
|
|
||||||
migration:
|
|
||||||
enable-verification: true # 是否启用迁移验证
|
|
||||||
delete-source: false # 迁移后是否删除源文件
|
|
||||||
@@ -54,7 +54,7 @@ zlt:
|
|||||||
delete-source: false # 迁移后是否删除源文件
|
delete-source: false # 迁移后是否删除源文件
|
||||||
batch-size: 100 # 迁移批次大小
|
batch-size: 100 # 迁移批次大小
|
||||||
hot-sync:
|
hot-sync:
|
||||||
enabled: true # 启用热数据同步
|
enabled: false # 启用热数据同步
|
||||||
batch-size: 100 # 批次大小
|
batch-size: 100 # 批次大小
|
||||||
interval-minutes: 30 # 同步间隔
|
interval-minutes: 30 # 同步间隔
|
||||||
access-threshold: 10 # 访问次数阈值
|
access-threshold: 10 # 访问次数阈值
|
||||||
@@ -75,3 +75,27 @@ zlt:
|
|||||||
# soTimeout: 1500
|
# soTimeout: 1500
|
||||||
# connectTimeout: 600
|
# connectTimeout: 600
|
||||||
# trackerList: ${zlt.fdfs.trackerList}
|
# trackerList: ${zlt.fdfs.trackerList}
|
||||||
|
|
||||||
|
# CDN配置示例
|
||||||
|
aliyun:
|
||||||
|
cdn:
|
||||||
|
# 是否启用CDN功能
|
||||||
|
enabled: true
|
||||||
|
# 阿里云AccessKey ID(建议使用环境变量配置)
|
||||||
|
access-key-id: ${zlt.oss.secretId:LTAI5tSNV1RvexXpMMCZhxSe}
|
||||||
|
# 阿里云AccessKey Secret(建议使用环境变量配置)
|
||||||
|
access-key-secret: ${zlt.oss.secretKey:XocJRWU8emwjjvYLTrc04l91VZMkQK}
|
||||||
|
# 地域ID
|
||||||
|
region-id: cn-beijing
|
||||||
|
# 默认域名
|
||||||
|
domain: cdn.goflytec.com
|
||||||
|
# 默认批次大小
|
||||||
|
default-batch-size: 100
|
||||||
|
# 任务等待超时时间(秒)
|
||||||
|
task-timeout: 300
|
||||||
|
|
||||||
|
# 日志配置
|
||||||
|
logging:
|
||||||
|
level:
|
||||||
|
com.central.file.service.impl.CdnServiceImpl: DEBUG
|
||||||
|
com.central.file.schedule.CdnScheduleTask: INFO
|
||||||
|
|||||||
@@ -4,10 +4,10 @@ server:
|
|||||||
spring:
|
spring:
|
||||||
application:
|
application:
|
||||||
name: file-center
|
name: file-center
|
||||||
# cloud:
|
cloud:
|
||||||
# nacos:
|
nacos:
|
||||||
# discovery:
|
discovery:
|
||||||
# ip: 119.45.169.13
|
ip: 119.45.169.13
|
||||||
servlet:
|
servlet:
|
||||||
multipart:
|
multipart:
|
||||||
max-file-size: 20MB
|
max-file-size: 20MB
|
||||||
|
|||||||
@@ -0,0 +1,230 @@
|
|||||||
|
# 订单中心CDN预热集成说明
|
||||||
|
|
||||||
|
## 概述
|
||||||
|
|
||||||
|
在订单中心的设备上传文件完成逻辑中集成了CDN预热功能,当订单的素材数量达到二维码要求时,自动预热相关文件到CDN,提升用户访问体验。
|
||||||
|
|
||||||
|
## 集成位置
|
||||||
|
|
||||||
|
### 触发时机
|
||||||
|
- **位置**:`OrderFileController.checkAndUpdateOrderStatus()` 方法
|
||||||
|
- **触发条件**:当订单的文件数量达到或超过二维码要求的素材数量时
|
||||||
|
- **执行时机**:在发送用户通知和触发一键成片之前
|
||||||
|
|
||||||
|
### 代码位置
|
||||||
|
```java
|
||||||
|
// 如果当前文件数量达到或超过二维码要求的数量,则更新订单状态为素材上传完成
|
||||||
|
if (currentFileCount >= qrCode.getMaterialCount()) {
|
||||||
|
Tourism tourism = tourismService.getTourismById(qrCode.getTourismId());
|
||||||
|
|
||||||
|
//发送用户素材上传成功通知
|
||||||
|
sendMessageForResouresUploaded(order,tourism);
|
||||||
|
|
||||||
|
// 预热订单相关的文件到CDN
|
||||||
|
prefetchOrderFilesToCdn(order.getOrderNo());
|
||||||
|
|
||||||
|
// 检查是否开启一键成片功能
|
||||||
|
if (isVideoEditEnabled(qrCode)) {
|
||||||
|
// ... 一键成片逻辑
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 功能特性
|
||||||
|
|
||||||
|
- ✅ **自动触发**:素材上传完成时自动预热
|
||||||
|
- ✅ **批量处理**:支持批量预热多个文件
|
||||||
|
- ✅ **配置化**:可通过配置文件控制功能开关和参数
|
||||||
|
- ✅ **错误处理**:完善的异常处理和日志记录
|
||||||
|
- ✅ **性能优化**:分批处理,避免单次处理过多文件
|
||||||
|
|
||||||
|
## 配置说明
|
||||||
|
|
||||||
|
### 1. 配置文件
|
||||||
|
|
||||||
|
在 `application.yml` 中添加CDN预热配置:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
cdn:
|
||||||
|
prefetch:
|
||||||
|
# 是否启用CDN预热功能
|
||||||
|
enabled: true
|
||||||
|
# 每批次预热的文件数量
|
||||||
|
batch-size: 50
|
||||||
|
# 预热区域:domestic-仅中国内地,overseas-全球(不包含中国内地),不传-全球
|
||||||
|
area: domestic
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 配置项说明
|
||||||
|
|
||||||
|
| 配置项 | 默认值 | 说明 |
|
||||||
|
|--------|--------|------|
|
||||||
|
| `cdn.prefetch.enabled` | `true` | 是否启用CDN预热功能 |
|
||||||
|
| `cdn.prefetch.batch-size` | `50` | 每批次预热的文件数量 |
|
||||||
|
| `cdn.prefetch.area` | `domestic` | 预热区域 |
|
||||||
|
|
||||||
|
## 工作流程
|
||||||
|
|
||||||
|
### 1. 触发流程
|
||||||
|
```
|
||||||
|
设备上传文件 → 创建订单文件记录 → 检查素材数量 → 达到要求数量 → 触发CDN预热
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 预热流程
|
||||||
|
```
|
||||||
|
获取订单文件列表 → 收集文件URL → 调用CDN批量预热接口 → 记录预热结果
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 详细步骤
|
||||||
|
|
||||||
|
1. **检查功能开关**:验证CDN预热功能是否启用
|
||||||
|
2. **获取文件列表**:查询订单的所有文件记录
|
||||||
|
3. **收集URL**:为每个文件生成访问URL
|
||||||
|
4. **批量预热**:调用文件中心的CDN预热接口
|
||||||
|
5. **结果处理**:记录预热成功或失败的结果
|
||||||
|
|
||||||
|
## 接口调用
|
||||||
|
|
||||||
|
### 1. Feign接口
|
||||||
|
|
||||||
|
在 `FileCenterService` 中添加了CDN预热相关接口:
|
||||||
|
|
||||||
|
```java
|
||||||
|
/**
|
||||||
|
* 批量预热文件到CDN
|
||||||
|
*/
|
||||||
|
@PostMapping("/cdn/batch/prefetch")
|
||||||
|
Result<Boolean> batchPrefetchFiles(@RequestBody List<String> urls,
|
||||||
|
@RequestParam(value = "batchSize", defaultValue = "100") int batchSize,
|
||||||
|
@RequestParam(value = "area", required = false) String area);
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 调用示例
|
||||||
|
|
||||||
|
```java
|
||||||
|
// 调用CDN批量预热接口
|
||||||
|
Result<Boolean> result = fileCenterService.batchPrefetchFiles(fileUrls, cdnPrefetchBatchSize, cdnPrefetchArea);
|
||||||
|
|
||||||
|
if (result != null && result.getResp_code() == 0) {
|
||||||
|
log.info("订单文件CDN预热成功,订单号: {}, 文件数量: {}", orderNo, fileUrls.size());
|
||||||
|
} else {
|
||||||
|
log.warn("订单文件CDN预热失败,订单号: {}, 错误信息: {}",
|
||||||
|
orderNo, result != null ? result.getResp_msg() : "未知错误");
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 日志记录
|
||||||
|
|
||||||
|
### 1. 关键日志信息
|
||||||
|
|
||||||
|
- **开始预热**:`开始预热订单文件到CDN,订单号: xxx`
|
||||||
|
- **文件收集**:`准备预热 x 个文件到CDN,订单号: xxx, 批次大小: xxx, 预热区域: xxx`
|
||||||
|
- **预热成功**:`订单文件CDN预热成功,订单号: xxx, 文件数量: xxx`
|
||||||
|
- **预热失败**:`订单文件CDN预热失败,订单号: xxx, 错误信息: xxx`
|
||||||
|
|
||||||
|
### 2. 日志级别
|
||||||
|
|
||||||
|
- **INFO**:预热开始、成功、失败等关键信息
|
||||||
|
- **DEBUG**:详细的文件URL收集过程
|
||||||
|
- **WARN**:单个文件URL获取失败
|
||||||
|
- **ERROR**:整体预热过程异常
|
||||||
|
|
||||||
|
## 错误处理
|
||||||
|
|
||||||
|
### 1. 异常处理策略
|
||||||
|
|
||||||
|
- **功能开关**:如果CDN预热功能未启用,直接跳过
|
||||||
|
- **文件为空**:如果订单无文件,记录日志并返回
|
||||||
|
- **URL获取失败**:单个文件URL获取失败不影响其他文件
|
||||||
|
- **预热失败**:记录错误信息但不影响业务流程
|
||||||
|
|
||||||
|
### 2. 容错机制
|
||||||
|
|
||||||
|
```java
|
||||||
|
try {
|
||||||
|
// CDN预热逻辑
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("预热订单文件到CDN异常,订单号: {}", orderNo, e);
|
||||||
|
// 不影响主业务流程
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 性能考虑
|
||||||
|
|
||||||
|
### 1. 批量处理
|
||||||
|
|
||||||
|
- 使用配置的批次大小进行批量预热
|
||||||
|
- 避免单次处理过多文件导致超时
|
||||||
|
|
||||||
|
### 2. 异步处理
|
||||||
|
|
||||||
|
- CDN预热是异步操作,不阻塞主业务流程
|
||||||
|
- 用户通知和一键成片功能不受影响
|
||||||
|
|
||||||
|
### 3. 资源控制
|
||||||
|
|
||||||
|
- 通过配置控制预热区域和批次大小
|
||||||
|
- 避免对CDN服务造成过大压力
|
||||||
|
|
||||||
|
## 监控和运维
|
||||||
|
|
||||||
|
### 1. 监控指标
|
||||||
|
|
||||||
|
- 预热成功率
|
||||||
|
- 预热文件数量
|
||||||
|
- 预热耗时
|
||||||
|
- 错误率
|
||||||
|
|
||||||
|
### 2. 运维建议
|
||||||
|
|
||||||
|
- 定期检查CDN预热日志
|
||||||
|
- 监控CDN服务配额使用情况
|
||||||
|
- 根据业务量调整批次大小
|
||||||
|
|
||||||
|
## 扩展功能
|
||||||
|
|
||||||
|
### 1. 预热策略优化
|
||||||
|
|
||||||
|
可以根据文件类型采用不同的预热策略:
|
||||||
|
|
||||||
|
```java
|
||||||
|
// 只预热图片和视频文件
|
||||||
|
List<String> mediaUrls = fileUrls.stream()
|
||||||
|
.filter(url -> CdnUtils.isImageFile(url) || CdnUtils.isVideoFile(url))
|
||||||
|
.collect(Collectors.toList());
|
||||||
|
```
|
||||||
|
|
||||||
|
### 2. 优先级控制
|
||||||
|
|
||||||
|
可以为不同类型的文件设置不同的预热优先级:
|
||||||
|
|
||||||
|
```java
|
||||||
|
// 优先预热重要文件
|
||||||
|
if (isImportantFile(orderFile)) {
|
||||||
|
// 立即预热
|
||||||
|
fileCenterService.prefetchFiles(List.of(viewUrl), "domestic");
|
||||||
|
} else {
|
||||||
|
// 批量预热
|
||||||
|
fileUrls.add(viewUrl);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 预热结果通知
|
||||||
|
|
||||||
|
可以将预热结果通知给相关系统:
|
||||||
|
|
||||||
|
```java
|
||||||
|
// 预热完成后发送通知
|
||||||
|
if (result != null && result.getResp_code() == 0) {
|
||||||
|
// 发送预热成功通知
|
||||||
|
notifyCdnPrefetchSuccess(orderNo, fileUrls.size());
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 注意事项
|
||||||
|
|
||||||
|
1. **功能开关**:确保在生产环境中正确配置功能开关
|
||||||
|
2. **批次大小**:根据CDN服务能力调整批次大小
|
||||||
|
3. **预热区域**:根据用户分布选择合适的预热区域
|
||||||
|
4. **错误处理**:预热失败不应影响主业务流程
|
||||||
|
5. **监控告警**:设置适当的监控和告警机制
|
||||||
@@ -90,35 +90,6 @@
|
|||||||
<artifactId>hibernate-validator</artifactId>
|
<artifactId>hibernate-validator</artifactId>
|
||||||
</dependency>
|
</dependency>
|
||||||
|
|
||||||
<!--<dependency>
|
|
||||||
<groupId>com.github.wechatpay-apiv3</groupId>
|
|
||||||
<artifactId>wechatpay-java</artifactId>
|
|
||||||
<version>0.2.15</version>
|
|
||||||
</dependency>-->
|
|
||||||
|
|
||||||
<!-- 微信公众号 SDK -->
|
|
||||||
<!--<dependency>
|
|
||||||
<groupId>com.github.binarywang</groupId>
|
|
||||||
<artifactId>weixin-java-mp</artifactId>
|
|
||||||
<version>4.5.0</version>
|
|
||||||
</dependency>
|
|
||||||
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.squareup.okhttp3</groupId>
|
|
||||||
<artifactId>okhttp</artifactId>
|
|
||||||
<version>4.9.1</version>
|
|
||||||
</dependency>
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.github.binarywang</groupId>
|
|
||||||
<artifactId>weixin-java-miniapp</artifactId>
|
|
||||||
<version>4.5.0</version>
|
|
||||||
</dependency>
|
|
||||||
|
|
||||||
<dependency>
|
|
||||||
<groupId>com.github.binarywang</groupId>
|
|
||||||
<artifactId>weixin-java-common</artifactId>
|
|
||||||
<version>4.6.0</version>
|
|
||||||
</dependency>-->
|
|
||||||
<dependency>
|
<dependency>
|
||||||
<groupId>javax.servlet</groupId>
|
<groupId>javax.servlet</groupId>
|
||||||
<artifactId>javax.servlet-api</artifactId>
|
<artifactId>javax.servlet-api</artifactId>
|
||||||
|
|||||||
+277
@@ -0,0 +1,277 @@
|
|||||||
|
package com.central.order.controller;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||||
|
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||||
|
import com.central.common.model.Result;
|
||||||
|
import com.central.common.model.PageResult;
|
||||||
|
import com.central.order.entity.Coupon;
|
||||||
|
import com.central.order.service.ICouponService;
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.Parameter;
|
||||||
|
import io.swagger.v3.oas.annotations.Parameters;
|
||||||
|
import io.swagger.v3.oas.annotations.enums.ParameterIn;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import com.central.order.model.CtripCreateOrderRequest;
|
||||||
|
import com.central.order.model.CtripCreateOrderRequest.CtripOrderBody;
|
||||||
|
import com.central.order.model.CtripCreateOrderRequest.CtripOrderItem;
|
||||||
|
import com.central.order.model.CtripCreateOrderRequest.CtripPassenger;
|
||||||
|
import com.central.order.model.CtripCreateOrderRequest.CtripContact;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 优惠券管理控制器
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/coupon")
|
||||||
|
@Tag(name = "优惠券管理")
|
||||||
|
public class CouponController {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private ICouponService couponService;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 列表
|
||||||
|
*/
|
||||||
|
@Operation(summary = "查询列表")
|
||||||
|
@Parameters({
|
||||||
|
@Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY),
|
||||||
|
@Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY)
|
||||||
|
})
|
||||||
|
@GetMapping
|
||||||
|
public PageResult<Coupon> list(@RequestParam Map<String, Object> params) {
|
||||||
|
return couponService.findList(params);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据ID查询优惠券
|
||||||
|
*/
|
||||||
|
@Operation(summary = "根据ID查询优惠券")
|
||||||
|
@GetMapping("/{id}")
|
||||||
|
public Result<Coupon> getCouponById(@PathVariable Long id) {
|
||||||
|
Coupon coupon = couponService.getById(id);
|
||||||
|
return Result.succeed(coupon);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建优惠券
|
||||||
|
*/
|
||||||
|
@Operation(summary = "创建优惠券")
|
||||||
|
@PostMapping
|
||||||
|
public Result<Boolean> createCoupon(@RequestBody Coupon coupon) {
|
||||||
|
boolean result = couponService.createCoupon(coupon);
|
||||||
|
return Result.succeed(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 更新优惠券
|
||||||
|
*/
|
||||||
|
@Operation(summary = "更新优惠券")
|
||||||
|
@PutMapping("/{id}")
|
||||||
|
public Result<Boolean> updateCoupon(@PathVariable Long id, @RequestBody Coupon coupon) {
|
||||||
|
coupon.setId(id);
|
||||||
|
boolean result = couponService.updateCoupon(coupon);
|
||||||
|
return Result.succeed(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 删除优惠券
|
||||||
|
*/
|
||||||
|
@Operation(summary = "删除优惠券")
|
||||||
|
@DeleteMapping("/{id}")
|
||||||
|
public Result<Boolean> deleteCoupon(@PathVariable Long id) {
|
||||||
|
boolean result = couponService.deleteCoupon(id);
|
||||||
|
return Result.succeed(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据手机号查询用户优惠券
|
||||||
|
*/
|
||||||
|
@Operation(summary = "根据手机号查询用户优惠券")
|
||||||
|
@GetMapping("/user/{userPhone}")
|
||||||
|
public Result<List<Coupon>> getCouponsByUserPhone(@PathVariable String userPhone) {
|
||||||
|
List<Coupon> coupons = couponService.getCouponsByUserPhone(userPhone);
|
||||||
|
return Result.succeed(coupons);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据手机号查询可用优惠券
|
||||||
|
*/
|
||||||
|
@Operation(summary = "根据手机号查询可用优惠券")
|
||||||
|
@GetMapping("/user/{userPhone}/available")
|
||||||
|
public Result<List<Coupon>> getAvailableCouponsByUserPhone(@PathVariable String userPhone) {
|
||||||
|
List<Coupon> coupons = couponService.getAvailableCouponsByUserPhone(userPhone);
|
||||||
|
return Result.succeed(coupons);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 使用优惠券
|
||||||
|
*/
|
||||||
|
@Operation(summary = "使用优惠券")
|
||||||
|
@PostMapping("/{id}/use")
|
||||||
|
public Result<Boolean> useCoupon(@PathVariable Long id, @RequestParam String orderNo) {
|
||||||
|
boolean result = couponService.useCoupon(id, orderNo);
|
||||||
|
return Result.succeed(result);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 携程创建优惠券接口
|
||||||
|
*/
|
||||||
|
@Operation(summary = "携程创建优惠券接口")
|
||||||
|
@PostMapping("/ctrip/create")
|
||||||
|
public Result<Boolean> createCouponFromCtripJson(@RequestBody CtripCreateOrderRequest request) {
|
||||||
|
log.info("携程创建券请求:{}", request);
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 验证请求头
|
||||||
|
if (request.getHeader() == null || request.getBody() == null) {
|
||||||
|
return Result.failed("请求格式错误");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 从body中提取订单信息
|
||||||
|
CtripOrderBody body = request.getBody();
|
||||||
|
if (body.getItems() == null || body.getItems().isEmpty()) {
|
||||||
|
return Result.failed("订单项不能为空");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取第一个订单项
|
||||||
|
CtripOrderItem item = body.getItems().get(0);
|
||||||
|
|
||||||
|
// 获取乘客信息
|
||||||
|
String userPhone = null;
|
||||||
|
String userName = null;
|
||||||
|
if (item.getPassengers() != null && !item.getPassengers().isEmpty()) {
|
||||||
|
CtripPassenger passenger = item.getPassengers().get(0);
|
||||||
|
userPhone = passenger.getMobile();
|
||||||
|
userName = passenger.getName();
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取联系人信息作为备选
|
||||||
|
if (userPhone == null && body.getContacts() != null && !body.getContacts().isEmpty()) {
|
||||||
|
CtripContact contact = body.getContacts().get(0);
|
||||||
|
userPhone = contact.getMobile();
|
||||||
|
userName = contact.getName();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (userPhone == null) {
|
||||||
|
return Result.failed("无法获取用户手机号");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 构建优惠券信息
|
||||||
|
String ctripCouponId = body.getOtaOrderId(); // 使用otaOrderId作为携程券ID
|
||||||
|
String couponName = userName != null ? userName + "的携程优惠券" : "携程订单优惠券"; // 个性化名称
|
||||||
|
Integer couponType = 1; // 默认类型:满减券
|
||||||
|
BigDecimal amount = item.getSalePrice(); // 使用销售价格作为券面额
|
||||||
|
BigDecimal minAmount = item.getPrice(); // 使用原价作为最低消费
|
||||||
|
String validStartTime = item.getUseStartDate();
|
||||||
|
String validEndTime = item.getUseEndDate();
|
||||||
|
|
||||||
|
// 幂等校验
|
||||||
|
if (couponService.existsByUserPhoneAndCtripCouponId(userPhone, ctripCouponId)) {
|
||||||
|
log.info("携程优惠券已存在,userPhone: {}, ctripCouponId: {}", userPhone, ctripCouponId);
|
||||||
|
return Result.succeed(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 时间解析
|
||||||
|
Date startTime = parseDate(validStartTime);
|
||||||
|
Date endTime = parseDate(validEndTime);
|
||||||
|
|
||||||
|
// 验证时间
|
||||||
|
if (startTime == null || endTime == null) {
|
||||||
|
return Result.failed("时间格式错误");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (endTime.before(startTime)) {
|
||||||
|
return Result.failed("结束时间不能早于开始时间");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 创建优惠券
|
||||||
|
boolean result = couponService.createCouponFromCtrip(ctripCouponId, userPhone, couponName,
|
||||||
|
couponType, amount, minAmount, null,
|
||||||
|
startTime, endTime);
|
||||||
|
|
||||||
|
if (result) {
|
||||||
|
log.info("携程优惠券创建成功,userPhone: {}, ctripCouponId: {}, amount: {}", userPhone, ctripCouponId, amount);
|
||||||
|
return Result.succeed(true);
|
||||||
|
} else {
|
||||||
|
log.error("携程优惠券创建失败,userPhone: {}, ctripCouponId: {}", userPhone, ctripCouponId);
|
||||||
|
return Result.failed("优惠券创建失败");
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("处理携程创建券请求失败", e);
|
||||||
|
return Result.failed("处理请求失败:" + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 携程取消优惠券接口
|
||||||
|
*/
|
||||||
|
@Operation(summary = "携程取消优惠券接口")
|
||||||
|
@PostMapping("/ctrip/cancel")
|
||||||
|
public Result<Boolean> cancelCouponFromCtrip(@RequestParam String userPhone) {
|
||||||
|
List<Coupon> coupons = couponService.getAvailableCouponsByUserPhone(userPhone);
|
||||||
|
if (coupons.isEmpty()) {
|
||||||
|
return Result.failed("无可退优惠券");
|
||||||
|
}
|
||||||
|
Coupon coupon = coupons.get(0); // 默认退第一个
|
||||||
|
coupon.setStatus(3); // 作废/退
|
||||||
|
coupon.setCancelTime(new Date());
|
||||||
|
couponService.updateCoupon(coupon);
|
||||||
|
return Result.succeed(true);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 优化核销携程优惠券接口,先查本地券再核销
|
||||||
|
*/
|
||||||
|
@Operation(summary = "核销携程优惠券")
|
||||||
|
@PostMapping("/ctrip/verify")
|
||||||
|
public Result<Boolean> verifyCtripCoupon(@RequestParam String userPhone, @RequestParam String orderNo) {
|
||||||
|
List<Coupon> coupons = couponService.getAvailableCouponsByUserPhone(userPhone);
|
||||||
|
if (coupons.isEmpty()) {
|
||||||
|
return Result.failed("无可用优惠券");
|
||||||
|
}
|
||||||
|
Coupon coupon = coupons.get(0);
|
||||||
|
boolean result = couponService.verifyCtripCoupon(coupon.getCtripCouponId(), orderNo);
|
||||||
|
if (result) {
|
||||||
|
coupon.setStatus(1); // 已用
|
||||||
|
coupon.setUsedTime(new Date());
|
||||||
|
couponService.updateCoupon(coupon);
|
||||||
|
return Result.succeed(true);
|
||||||
|
} else {
|
||||||
|
return Result.failed("携程核销失败");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 批量更新过期优惠券
|
||||||
|
*/
|
||||||
|
@Operation(summary = "批量更新过期优惠券")
|
||||||
|
@PostMapping("/update-expired")
|
||||||
|
public Result<Void> updateExpiredCoupons() {
|
||||||
|
couponService.updateExpiredCoupons();
|
||||||
|
return Result.succeed("批量更新过期优惠券成功");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 时间解析工具
|
||||||
|
private Date parseDate(String dateStr) {
|
||||||
|
try {
|
||||||
|
return new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateStr);
|
||||||
|
} catch (Exception e) {
|
||||||
|
try {
|
||||||
|
return new java.text.SimpleDateFormat("yyyy-MM-dd").parse(dateStr);
|
||||||
|
} catch (Exception ex) {
|
||||||
|
return new Date();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+46
-2
@@ -4,13 +4,21 @@ import com.central.common.model.Result;
|
|||||||
import com.central.order.model.vo.DashboardStatisticsVO;
|
import com.central.order.model.vo.DashboardStatisticsVO;
|
||||||
import com.central.order.service.IDashboardService;
|
import com.central.order.service.IDashboardService;
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.Parameter;
|
||||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.web.bind.annotation.GetMapping;
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
import org.springframework.web.bind.annotation.RequestMapping;
|
import org.springframework.web.bind.annotation.RequestMapping;
|
||||||
|
import org.springframework.web.bind.annotation.RequestParam;
|
||||||
import org.springframework.web.bind.annotation.RestController;
|
import org.springframework.web.bind.annotation.RestController;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.List;
|
||||||
|
import com.central.order.model.vo.FilterOptions;
|
||||||
|
import com.central.order.mapper.DashboardMapper;
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@RestController
|
@RestController
|
||||||
@RequestMapping("/dashboard")
|
@RequestMapping("/dashboard")
|
||||||
@@ -19,16 +27,52 @@ import org.springframework.web.bind.annotation.RestController;
|
|||||||
public class DashboardController {
|
public class DashboardController {
|
||||||
|
|
||||||
private final IDashboardService dashboardService;
|
private final IDashboardService dashboardService;
|
||||||
|
private final DashboardMapper dashboardMapper;
|
||||||
|
|
||||||
@Operation(summary = "获取首页统计数据")
|
@Operation(summary = "获取首页统计数据")
|
||||||
@GetMapping("/statistics")
|
@GetMapping("/statistics")
|
||||||
public Result<DashboardStatisticsVO> getStatistics() {
|
public Result<DashboardStatisticsVO> getStatistics(
|
||||||
|
@Parameter(description = "景区ID") @RequestParam(required = false) Long tourismId,
|
||||||
|
@Parameter(description = "二维码ID") @RequestParam(required = false) String qrcodeId,
|
||||||
|
@Parameter(description = "设备编号") @RequestParam(required = false) String deviceSn,
|
||||||
|
@Parameter(description = "开始时间") @RequestParam(required = false) String startTime,
|
||||||
|
@Parameter(description = "结束时间") @RequestParam(required = false) String endTime,
|
||||||
|
@Parameter(description = "是否包含测试二维码") @RequestParam(required = false, defaultValue = "false") Boolean includeTestQrcodes) {
|
||||||
try {
|
try {
|
||||||
DashboardStatisticsVO statistics = dashboardService.getDashboardStatistics();
|
Map<String, Object> params = new HashMap<>();
|
||||||
|
params.put("tourismId", tourismId);
|
||||||
|
params.put("qrcodeId", qrcodeId);
|
||||||
|
params.put("deviceSn", deviceSn);
|
||||||
|
params.put("startTime", startTime);
|
||||||
|
params.put("endTime", endTime);
|
||||||
|
params.put("includeTestQrcodes", includeTestQrcodes);
|
||||||
|
|
||||||
|
DashboardStatisticsVO statistics = dashboardService.getDashboardStatistics(params);
|
||||||
return Result.succeed(statistics, "获取首页统计数据成功");
|
return Result.succeed(statistics, "获取首页统计数据成功");
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("获取首页统计数据失败", e);
|
log.error("获取首页统计数据失败", e);
|
||||||
return Result.failed("获取统计数据失败:" + e.getMessage());
|
return Result.failed("获取统计数据失败:" + e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "获取二维码选项")
|
||||||
|
@GetMapping("/qrcode/options")
|
||||||
|
public Result<Map<String, Object>> getQrcodeOptions(
|
||||||
|
@Parameter(description = "景区ID") @RequestParam(required = false) Long tourismId,
|
||||||
|
@Parameter(description = "是否包含测试二维码") @RequestParam(required = false, defaultValue = "false") Boolean includeTestQrcodes) {
|
||||||
|
try {
|
||||||
|
Map<String, Object> params = new HashMap<>();
|
||||||
|
params.put("tourismId", tourismId);
|
||||||
|
params.put("includeTestQrcodes", includeTestQrcodes);
|
||||||
|
|
||||||
|
List<FilterOptions.OptionItem> qrcodeList = dashboardMapper.getQrcodeOptions(params);
|
||||||
|
Map<String, Object> result = new HashMap<>();
|
||||||
|
result.put("qrcodeList", qrcodeList);
|
||||||
|
|
||||||
|
return Result.succeed(result, "获取二维码选项成功");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("获取二维码选项失败", e);
|
||||||
|
return Result.failed("获取二维码选项失败:" + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+291
-59
@@ -19,7 +19,11 @@ import com.central.order.service.*;
|
|||||||
import com.central.wechat.config.WxPayConfigFactory;
|
import com.central.wechat.config.WxPayConfigFactory;
|
||||||
import com.central.wechat.entity.WechatConfig;
|
import com.central.wechat.entity.WechatConfig;
|
||||||
import com.central.wechat.feign.WechatConfigService;
|
import com.central.wechat.feign.WechatConfigService;
|
||||||
import com.wechat.pay.java.service.payments.jsapi.model.*;
|
import com.wechat.pay.java.service.payments.jsapi.JsapiServiceExtension;
|
||||||
|
import com.wechat.pay.java.service.payments.jsapi.model.Amount;
|
||||||
|
import com.wechat.pay.java.service.payments.jsapi.model.Payer;
|
||||||
|
import com.wechat.pay.java.service.payments.jsapi.model.PrepayRequest;
|
||||||
|
import com.wechat.pay.java.service.payments.jsapi.model.PrepayWithRequestPaymentResponse;
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
import io.swagger.v3.oas.annotations.Parameter;
|
import io.swagger.v3.oas.annotations.Parameter;
|
||||||
import io.swagger.v3.oas.annotations.Parameters;
|
import io.swagger.v3.oas.annotations.Parameters;
|
||||||
@@ -141,6 +145,8 @@ public class OrderController {
|
|||||||
public PageResult<Map> listInfoByUser(@RequestParam Map<String, Object> params) {
|
public PageResult<Map> listInfoByUser(@RequestParam Map<String, Object> params) {
|
||||||
LoginAppUser user = LoginUserContextHolder.getUser();
|
LoginAppUser user = LoginUserContextHolder.getUser();
|
||||||
params.put("userId", user.getId());
|
params.put("userId", user.getId());
|
||||||
|
List<Integer> orderStatusList = List.of(OrderStatus.COMPLETE.getId(), OrderStatus.UPLOADING.getId(), OrderStatus.UPLOADED.getId());
|
||||||
|
params.put("orderStatusList", orderStatusList); // 查询已完成和素材上传中
|
||||||
String fileType = MapUtils.getString(params, "fileType");
|
String fileType = MapUtils.getString(params, "fileType");
|
||||||
if (StringUtil.isBlank(fileType)) {
|
if (StringUtil.isBlank(fileType)) {
|
||||||
fileType = "image/jpeg";
|
fileType = "image/jpeg";
|
||||||
@@ -163,7 +169,9 @@ public class OrderController {
|
|||||||
for (OrderFile orderFile : list){
|
for (OrderFile orderFile : list){
|
||||||
Map<String,String> imgMap = new HashMap<>();
|
Map<String,String> imgMap = new HashMap<>();
|
||||||
String url = fileCenterService.getViewUrlByPath(orderFile.getFilePath());
|
String url = fileCenterService.getViewUrlByPath(orderFile.getFilePath());
|
||||||
imgMap.put("url", url.replace(cdnOssUrl,cdnUrl));
|
// 去掉URL中的参数并替换域名
|
||||||
|
// String cleanUrl = removeUrlParams(url.replace(cdnOssUrl, cdnUrl));
|
||||||
|
imgMap.put("url", url.replace(cdnOssUrl, cdnUrl));
|
||||||
imgMap.put("contentType", orderFile.getFileType());
|
imgMap.put("contentType", orderFile.getFileType());
|
||||||
fileMap.put("path",orderFile.getFilePath());
|
fileMap.put("path",orderFile.getFilePath());
|
||||||
imgMap.put("viewUrl", fileCenterService.getViewUrlByPathStyle(fileMap));
|
imgMap.put("viewUrl", fileCenterService.getViewUrlByPathStyle(fileMap));
|
||||||
@@ -193,7 +201,7 @@ public class OrderController {
|
|||||||
LoginAppUser user = LoginUserContextHolder.getUser();
|
LoginAppUser user = LoginUserContextHolder.getUser();
|
||||||
|
|
||||||
order.setUserId(user.getId());
|
order.setUserId(user.getId());
|
||||||
order.setTenantId(TenantContextHolder.getTenant());
|
|
||||||
|
|
||||||
List<Order> userOrderList = orderService.getOrderCountByStatusAndUser(user.getId(),OrderStatus.PAID.getId(),OrderStatus.UNPAID.getId());
|
List<Order> userOrderList = orderService.getOrderCountByStatusAndUser(user.getId(),OrderStatus.PAID.getId(),OrderStatus.UNPAID.getId());
|
||||||
if (!userOrderList.isEmpty()){
|
if (!userOrderList.isEmpty()){
|
||||||
@@ -205,8 +213,8 @@ public class OrderController {
|
|||||||
if (qrCode.getStatus().equals(CommonStatus.UNABLE.getId())){
|
if (qrCode.getStatus().equals(CommonStatus.UNABLE.getId())){
|
||||||
return Result.failed("该二维码已过期");
|
return Result.failed("该二维码已过期");
|
||||||
}
|
}
|
||||||
|
order.setTenantId(qrCode.getTenantId());
|
||||||
//设置订单所属tenantId
|
//设置订单所属tenantId
|
||||||
TenantContextHolder.setTenant(qrCode.getTenantId());
|
|
||||||
order.setTourismId(qrCode.getTourismId());
|
order.setTourismId(qrCode.getTourismId());
|
||||||
order.setDeviceSn(qrCode.getDeviceSn());
|
order.setDeviceSn(qrCode.getDeviceSn());
|
||||||
order.setOrderAmount(qrCode.getPrice());
|
order.setOrderAmount(qrCode.getPrice());
|
||||||
@@ -231,7 +239,7 @@ public class OrderController {
|
|||||||
|
|
||||||
@Operation(summary = "生成预支付订单")
|
@Operation(summary = "生成预支付订单")
|
||||||
@PutMapping("/{orderId}/pay")
|
@PutMapping("/{orderId}/pay")
|
||||||
public Result<PrepayWithRequestPaymentResponse> payOrder(@PathVariable("orderId") Long orderId) {
|
public Result<Object> payOrder(@PathVariable("orderId") Long orderId) {
|
||||||
try {
|
try {
|
||||||
// 1. 获取用户和订单信息
|
// 1. 获取用户和订单信息
|
||||||
SysUser user = userCenterService.findUserById(LoginUserContextHolder.getUser().getId());
|
SysUser user = userCenterService.findUserById(LoginUserContextHolder.getUser().getId());
|
||||||
@@ -240,67 +248,96 @@ public class OrderController {
|
|||||||
return Result.failed("订单数据不存在");
|
return Result.failed("订单数据不存在");
|
||||||
}
|
}
|
||||||
|
|
||||||
// 检查是否需要开启分账
|
// 检查二维码信息
|
||||||
QrCode qrCode = qrCodeService.getByCodeId(order.getCodeId());
|
QrCode qrCode = qrCodeService.getByCodeId(order.getCodeId());
|
||||||
if (qrCode == null) {
|
if (qrCode == null) {
|
||||||
return Result.failed("二维码不存在");
|
return Result.failed("二维码不存在");
|
||||||
}
|
}
|
||||||
|
|
||||||
// 3. 创建支付请求
|
// 3. 创建支付请求
|
||||||
PrepayRequest request = new PrepayRequest();
|
|
||||||
WechatConfig wechatConfig = wechatConfigService.getConfig("PAY",qrCode.getTenantId());
|
WechatConfig wechatConfig = wechatConfigService.getConfig("PAY",qrCode.getTenantId());
|
||||||
|
|
||||||
// 设置基本支付信息
|
// 4. 根据是否为服务商模式设置不同的支付参数
|
||||||
Amount amount = new Amount();
|
if (Boolean.TRUE.equals(wechatConfig.getIsServiceMode())) {
|
||||||
amount.setTotal(Integer.parseInt(order.getOrderAmount()));
|
// 服务商模式:使用partnerpayments包下的PrepayRequest
|
||||||
request.setAmount(amount);
|
com.wechat.pay.java.service.partnerpayments.jsapi.model.PrepayRequest partnerRequest =
|
||||||
request.setAppid(wechatConfig.getAppId());
|
new com.wechat.pay.java.service.partnerpayments.jsapi.model.PrepayRequest();
|
||||||
request.setMchid(wechatConfig.getMerchantId());
|
|
||||||
request.setDescription(qrCode.getName());
|
|
||||||
request.setNotifyUrl(wechatConfig.getNotifyUrl());
|
|
||||||
request.setOutTradeNo(order.getOrderNo());
|
|
||||||
|
|
||||||
// 设置支付者信息
|
// 设置服务商信息
|
||||||
Payer payer = new Payer();
|
partnerRequest.setSpAppid(wechatConfig.getServiceAppId());
|
||||||
payer.setOpenid(user.getOpenId());
|
partnerRequest.setSpMchid(wechatConfig.getServiceMchId());
|
||||||
request.setPayer(payer);
|
|
||||||
|
|
||||||
// 设置分账信息
|
// 设置子商户信息
|
||||||
SettleInfo settleInfo = new SettleInfo();
|
partnerRequest.setSubAppid(wechatConfig.getSubAppId());
|
||||||
if (isEnableProfit(qrCode)) {
|
partnerRequest.setSubMchid(wechatConfig.getSubMchId());
|
||||||
settleInfo.setProfitSharing(true);
|
|
||||||
request.setSettleInfo(settleInfo);
|
// 设置其他支付信息
|
||||||
|
partnerRequest.setDescription(qrCode.getName());
|
||||||
|
partnerRequest.setNotifyUrl(wechatConfig.getNotifyUrl());
|
||||||
|
partnerRequest.setOutTradeNo(order.getOrderNo());
|
||||||
|
|
||||||
|
// 设置金额
|
||||||
|
com.wechat.pay.java.service.partnerpayments.jsapi.model.Amount partnerAmount = new com.wechat.pay.java.service.partnerpayments.jsapi.model.Amount();
|
||||||
|
partnerAmount.setTotal(Integer.parseInt(order.getOrderAmount()));
|
||||||
|
partnerRequest.setAmount(partnerAmount);
|
||||||
|
|
||||||
|
// 设置支付者信息
|
||||||
|
com.wechat.pay.java.service.partnerpayments.jsapi.model.Payer partnerPayer = new com.wechat.pay.java.service.partnerpayments.jsapi.model.Payer();
|
||||||
|
partnerPayer.setSubOpenid(user.getOpenId());
|
||||||
|
partnerRequest.setPayer(partnerPayer);
|
||||||
|
|
||||||
|
log.info("服务商模式支付请求:spAppid={}, spMchid={}, subAppid={}, subMchid={}",
|
||||||
|
wechatConfig.getServiceAppId(), wechatConfig.getServiceMchId(),
|
||||||
|
wechatConfig.getSubAppId(), wechatConfig.getSubMchId());
|
||||||
|
|
||||||
|
// 创建服务商模式的支付服务
|
||||||
|
com.wechat.pay.java.service.partnerpayments.jsapi.JsapiServiceExtension partnerJsapiService =
|
||||||
|
new com.wechat.pay.java.service.partnerpayments.jsapi.JsapiServiceExtension.Builder()
|
||||||
|
.config(wxPayConfigFactory.createConfigBySubMchId(wechatConfig.getSubMchId()))
|
||||||
|
.build();
|
||||||
|
|
||||||
|
// 调用支付接口
|
||||||
|
com.wechat.pay.java.service.partnerpayments.jsapi.model.PrepayWithRequestPaymentResponse partnerResponse =
|
||||||
|
partnerJsapiService.prepayWithRequestPayment(partnerRequest,wechatConfig.getSubAppId());
|
||||||
|
|
||||||
|
// 返回结果
|
||||||
|
return Result.succeed(partnerResponse, order.getOrderNo());
|
||||||
|
|
||||||
// 创建分账记录
|
|
||||||
ProfitSharing profitSharing = profitSharingService.createProfitSharing(order,qrCode);
|
|
||||||
} else {
|
} else {
|
||||||
settleInfo.setProfitSharing(false);
|
// 普通商户模式:使用payments包下的PrepayRequest
|
||||||
request.setSettleInfo(settleInfo);
|
PrepayRequest request = new PrepayRequest();
|
||||||
|
|
||||||
|
// 设置基本支付信息
|
||||||
|
Amount amount = new Amount();
|
||||||
|
amount.setTotal(Integer.parseInt(order.getOrderAmount()));
|
||||||
|
request.setAmount(amount);
|
||||||
|
|
||||||
|
request.setAppid(wechatConfig.getAppId());
|
||||||
|
request.setMchid(wechatConfig.getMerchantId());
|
||||||
|
request.setDescription(qrCode.getName());
|
||||||
|
request.setNotifyUrl(wechatConfig.getNotifyUrl());
|
||||||
|
request.setOutTradeNo(order.getOrderNo());
|
||||||
|
|
||||||
|
// 设置支付者信息
|
||||||
|
Payer payer = new Payer();
|
||||||
|
payer.setOpenid(user.getOpenId());
|
||||||
|
request.setPayer(payer);
|
||||||
|
|
||||||
|
// 创建普通商户模式的支付服务
|
||||||
|
JsapiServiceExtension jsapiService = wxPayConfigFactory.createJsapiService(qrCode.getTenantId());
|
||||||
|
|
||||||
|
// 调用支付接口
|
||||||
|
PrepayWithRequestPaymentResponse response = jsapiService.prepayWithRequestPayment(request);
|
||||||
|
|
||||||
|
// 返回结果
|
||||||
|
return Result.succeed(response, order.getOrderNo());
|
||||||
}
|
}
|
||||||
|
|
||||||
// 5. 调用支付接口
|
|
||||||
PrepayWithRequestPaymentResponse response = wxPayConfigFactory.createJsapiService(qrCode.getTenantId()).prepayWithRequestPayment(request);
|
|
||||||
|
|
||||||
// 6. 返回结果
|
|
||||||
return Result.succeed(response, order.getOrderNo());
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("创建预支付订单失败", e);
|
log.error("创建预支付订单失败", e);
|
||||||
return Result.failed("创建预支付订单失败:" + e.getMessage());
|
return Result.failed("创建预支付订单失败:" + e.getMessage());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 检查是否开启分润
|
|
||||||
*/
|
|
||||||
private boolean isEnableProfit(QrCode qrCode) {
|
|
||||||
return qrCode != null &&
|
|
||||||
Integer.valueOf(1).equals(qrCode.getEnableProfit()) &&
|
|
||||||
qrCode.getPayeeStatus() != null &&
|
|
||||||
qrCode.getPayeeStatus() == 1 && // 确保分账账号已验证
|
|
||||||
qrCode.getPayeeAccount() != null && // 确保有收款账号
|
|
||||||
qrCode.getProfitRate() != null; // 确保有分润比例
|
|
||||||
}
|
|
||||||
|
|
||||||
@Operation(summary = "获取排队总览信息")
|
@Operation(summary = "获取排队总览信息")
|
||||||
@GetMapping("/queue/info")
|
@GetMapping("/queue/info")
|
||||||
public Result<Map> getQueueInfo(@RequestParam String codeId) {
|
public Result<Map> getQueueInfo(@RequestParam String codeId) {
|
||||||
@@ -443,19 +480,29 @@ public class OrderController {
|
|||||||
@AuditLog(operation = "'机库更新订单完成状态:' + #payload")
|
@AuditLog(operation = "'机库更新订单完成状态:' + #payload")
|
||||||
@PutMapping("/update")
|
@PutMapping("/update")
|
||||||
public Result<String> updateOrderStatusCompleted(@RequestBody Map payload) {
|
public Result<String> updateOrderStatusCompleted(@RequestBody Map payload) {
|
||||||
Order order = orderService.getOrderByNumber(payload.get("orderNo").toString());
|
try {
|
||||||
Assert.notNull(order,"订单数据不能为空");
|
TenantContextHolder.setTenant("webApp");
|
||||||
if (order.getOrderStatus().equals(OrderStatus.DOING.getId())
|
Order order = orderService.getOrderByNumber(payload.get("orderNo").toString());
|
||||||
|| order.getOrderStatus().equals(OrderStatus.UPLOADED.getId())
|
Assert.notNull(order,"订单数据不能为空");
|
||||||
|| order.getOrderStatus().equals(OrderStatus.UPLOADING.getId())){
|
if (order.getOrderStatus().equals(OrderStatus.DOING.getId())
|
||||||
order.setOrderStatus(OrderStatus.COMPLETE.getId());
|
|| order.getOrderStatus().equals(OrderStatus.UPLOADED.getId())
|
||||||
if (orderService.updateOrder(order)){
|
|| order.getOrderStatus().equals(OrderStatus.UPLOADING.getId())){
|
||||||
return Result.succeed("更新成功");
|
order.setOrderStatus(OrderStatus.COMPLETE.getId());
|
||||||
|
log.info("更新订单时,租户ID:{}", TenantContextHolder.getTenant());
|
||||||
|
if (orderService.updateOrder(order)){
|
||||||
|
return Result.succeed("更新成功");
|
||||||
|
}
|
||||||
|
}else {
|
||||||
|
return Result.failed("已更新");
|
||||||
}
|
}
|
||||||
}else {
|
return Result.failed("未查询到订单数据");
|
||||||
return Result.failed("已更新");
|
}catch (Exception e){
|
||||||
|
e.printStackTrace();
|
||||||
|
}finally {
|
||||||
|
TenantContextHolder.clear();
|
||||||
}
|
}
|
||||||
return Result.failed("未查询到订单数据");
|
|
||||||
|
return null;
|
||||||
}
|
}
|
||||||
|
|
||||||
@Operation(summary = "取消订单")
|
@Operation(summary = "取消订单")
|
||||||
@@ -470,6 +517,21 @@ public class OrderController {
|
|||||||
return Result.failed("请重试");
|
return Result.failed("请重试");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Operation(summary = "删除订单(逻辑删除)")
|
||||||
|
@DeleteMapping("/{orderNo}")
|
||||||
|
public Result<String> deleteOrder(@PathVariable("orderNo") String orderNo) {
|
||||||
|
Order order = orderService.getOrderByNumber(orderNo);
|
||||||
|
if (order == null) {
|
||||||
|
return Result.failed("订单不存在");
|
||||||
|
}
|
||||||
|
order.setIsDel(1);
|
||||||
|
boolean res = orderService.updateOrder(order);
|
||||||
|
if (res) {
|
||||||
|
return Result.succeed("删除成功");
|
||||||
|
}
|
||||||
|
return Result.failed("删除失败,请重试");
|
||||||
|
}
|
||||||
|
|
||||||
@Operation(summary = "后台管理更新订单")
|
@Operation(summary = "后台管理更新订单")
|
||||||
@PostMapping("/update/order")
|
@PostMapping("/update/order")
|
||||||
public Result updateOrder(@RequestBody Order order) {
|
public Result updateOrder(@RequestBody Order order) {
|
||||||
@@ -584,6 +646,8 @@ public class OrderController {
|
|||||||
for (OrderFile orderFile : orderFiles) {
|
for (OrderFile orderFile : orderFiles) {
|
||||||
Map<String, String> fileInfo = new HashMap<>();
|
Map<String, String> fileInfo = new HashMap<>();
|
||||||
String url = fileCenterService.getViewUrlByPath(orderFile.getFilePath());
|
String url = fileCenterService.getViewUrlByPath(orderFile.getFilePath());
|
||||||
|
// 去掉URL中的参数并替换域名
|
||||||
|
// String cleanUrl = removeUrlParams(url.replace(cdnOssUrl, cdnUrl));
|
||||||
fileInfo.put("url", url.replace(cdnOssUrl, cdnUrl));
|
fileInfo.put("url", url.replace(cdnOssUrl, cdnUrl));
|
||||||
fileInfo.put("contentType", orderFile.getFileType());
|
fileInfo.put("contentType", orderFile.getFileType());
|
||||||
fileMap.put("path", orderFile.getFilePath());
|
fileMap.put("path", orderFile.getFilePath());
|
||||||
@@ -608,6 +672,75 @@ public class OrderController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据订单号查询订单素材
|
||||||
|
*/
|
||||||
|
@Operation(summary = "根据订单号查询订单素材")
|
||||||
|
@GetMapping("/user/files/{orderNo}")
|
||||||
|
public Result<Map<String, Object>> getOrderFilesByOrderNo(@PathVariable("orderNo") String orderNo) {
|
||||||
|
// 校验订单是否存在
|
||||||
|
Order order = orderService.getOrderByNumber(orderNo);
|
||||||
|
if (order == null) {
|
||||||
|
return Result.failed("订单不存在");
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, Object> orderFileMap = new HashMap<>();
|
||||||
|
orderFileMap.put("time", sdf.format(order.getCreateTime()));
|
||||||
|
orderFileMap.put("addr", tourismService.getTourismById(order.getTourismId()).getTourismAddress());
|
||||||
|
orderFileMap.put("orderNo", order.getOrderNo());
|
||||||
|
|
||||||
|
// 只查一次所有文件
|
||||||
|
List<OrderFile> allFiles = orderFileService.getOrderFileByOrderNo(orderNo);
|
||||||
|
|
||||||
|
// aiVideo
|
||||||
|
List<OrderFile> aiVideoFiles = allFiles.stream()
|
||||||
|
.filter(f -> "ai_video".equals(f.getFileTag()))
|
||||||
|
.toList();
|
||||||
|
String aiVideoUrl = null;
|
||||||
|
if (!aiVideoFiles.isEmpty()) {
|
||||||
|
aiVideoUrl = fileCenterService.getViewUrlByPath(aiVideoFiles.get(0).getFilePath()).replace(cdnOssUrl, cdnUrl);
|
||||||
|
}
|
||||||
|
orderFileMap.put("aiVideo", aiVideoUrl);
|
||||||
|
|
||||||
|
// 图片素材
|
||||||
|
List<OrderFile> imgFiles = allFiles.stream()
|
||||||
|
.filter(f -> "image/jpeg".equals(f.getFileType()))
|
||||||
|
.toList();
|
||||||
|
List<Map<String,String>> imgList = new ArrayList<>();
|
||||||
|
Map<String, String> fileMap = new HashMap<>();
|
||||||
|
fileMap.put("style", fileStyle);
|
||||||
|
for (OrderFile orderFile : imgFiles){
|
||||||
|
Map<String,String> imgMap = new HashMap<>();
|
||||||
|
String url = fileCenterService.getViewUrlByPath(orderFile.getFilePath());
|
||||||
|
imgMap.put("url", url.replace(cdnOssUrl, cdnUrl));
|
||||||
|
imgMap.put("contentType", orderFile.getFileType());
|
||||||
|
imgMap.put("path", orderFile.getFilePath());
|
||||||
|
fileMap.put("path",orderFile.getFilePath());
|
||||||
|
imgMap.put("viewUrl", fileCenterService.getViewUrlByPathStyle(fileMap));
|
||||||
|
imgList.add(imgMap);
|
||||||
|
}
|
||||||
|
orderFileMap.put("imgList", imgList);
|
||||||
|
|
||||||
|
// 视频素材
|
||||||
|
List<OrderFile> videoFiles = allFiles.stream()
|
||||||
|
.filter(f -> "raw_video".equals(f.getFileTag()))
|
||||||
|
.toList();
|
||||||
|
List<Map<String,String>> videoList = new ArrayList<>();
|
||||||
|
for (OrderFile orderFile : videoFiles){
|
||||||
|
Map<String,String> videoMap = new HashMap<>();
|
||||||
|
String url = fileCenterService.getViewUrlByPath(orderFile.getFilePath());
|
||||||
|
videoMap.put("url", url.replace(cdnOssUrl, cdnUrl));
|
||||||
|
videoMap.put("contentType", orderFile.getFileType());
|
||||||
|
videoMap.put("path", orderFile.getFilePath());
|
||||||
|
fileMap.put("path",orderFile.getFilePath());
|
||||||
|
videoMap.put("viewUrl", fileCenterService.getViewUrlByPathStyle(fileMap));
|
||||||
|
videoList.add(videoMap);
|
||||||
|
}
|
||||||
|
orderFileMap.put("videoList", videoList);
|
||||||
|
|
||||||
|
return Result.succeed(orderFileMap, "查询成功");
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 将分的价格转换为元的str,方便前端显示
|
* 将分的价格转换为元的str,方便前端显示
|
||||||
* @param str
|
* @param str
|
||||||
@@ -662,7 +795,9 @@ public class OrderController {
|
|||||||
for (String orderFile : list){
|
for (String orderFile : list){
|
||||||
Map<String,String> imgMap = new HashMap<>();
|
Map<String,String> imgMap = new HashMap<>();
|
||||||
String url = fileCenterService.getViewUrlByPath(orderFile);
|
String url = fileCenterService.getViewUrlByPath(orderFile);
|
||||||
imgMap.put("url", url.replace(cdnOssUrl,cdnUrl));
|
// 去掉URL中的参数并替换域名
|
||||||
|
String cleanUrl = removeUrlParams(url.replace(cdnOssUrl, cdnUrl));
|
||||||
|
imgMap.put("url", cleanUrl);
|
||||||
if (orderFile.endsWith(".jpeg") || orderFile.endsWith(".png")){
|
if (orderFile.endsWith(".jpeg") || orderFile.endsWith(".png")){
|
||||||
imgMap.put("contentType", "image/jpeg");
|
imgMap.put("contentType", "image/jpeg");
|
||||||
}
|
}
|
||||||
@@ -681,4 +816,101 @@ public class OrderController {
|
|||||||
}
|
}
|
||||||
return new PageResult<>();
|
return new PageResult<>();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 新版:查询用户订单详情列表(含视频/图片/一键成片)
|
||||||
|
*/
|
||||||
|
@Operation(summary = "新版-查询用户订单详情列表(含视频/图片/一键成片)")
|
||||||
|
@Parameters({
|
||||||
|
@Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY),
|
||||||
|
@Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY)
|
||||||
|
})
|
||||||
|
@GetMapping("/user/v2")
|
||||||
|
public PageResult<Map> listInfoByUserV2(@RequestParam Map<String, Object> params) {
|
||||||
|
LoginAppUser user = LoginUserContextHolder.getUser();
|
||||||
|
params.put("userId", user.getId());
|
||||||
|
List<Integer> orderStatusList = List.of(OrderStatus.COMPLETE.getId(), OrderStatus.UPLOADING.getId(), OrderStatus.UPLOADED.getId());
|
||||||
|
params.put("orderStatusList", orderStatusList);
|
||||||
|
|
||||||
|
PageResult<Order> result = orderService.findListByUser(params);
|
||||||
|
if (result.getCount() > 0){
|
||||||
|
List<Map> page = new ArrayList<>();
|
||||||
|
Map<String, String> fileMap = new HashMap<>();
|
||||||
|
fileMap.put("style", fileStyle);
|
||||||
|
for(Order order : result.getData()){
|
||||||
|
Map<String,Object> orderFileMap = new HashMap<>();
|
||||||
|
orderFileMap.put("time", sdf.format(order.getCreateTime()));
|
||||||
|
orderFileMap.put("addr", tourismService.getTourismById(order.getTourismId()).getTourismAddress());
|
||||||
|
orderFileMap.put("orderNo", order.getOrderNo());
|
||||||
|
|
||||||
|
// 只查一次所有文件
|
||||||
|
List<OrderFile> allFiles = orderFileService.getOrderFileByOrderNo(order.getOrderNo());
|
||||||
|
|
||||||
|
// aiVideo
|
||||||
|
List<OrderFile> aiVideoFiles = allFiles.stream()
|
||||||
|
.filter(f -> "ai_video".equals(f.getFileTag()))
|
||||||
|
.toList();
|
||||||
|
String aiVideoUrl = null;
|
||||||
|
if (!aiVideoFiles.isEmpty()) {
|
||||||
|
// fileMap.put("path", aiVideoFiles.get(0).getFilePath());
|
||||||
|
aiVideoUrl = fileCenterService.getViewUrlByPath(aiVideoFiles.get(0).getFilePath()).replace(cdnOssUrl, cdnUrl);
|
||||||
|
}
|
||||||
|
orderFileMap.put("aiVideo", aiVideoUrl);
|
||||||
|
|
||||||
|
// 图片素材
|
||||||
|
List<OrderFile> imgFiles = allFiles.stream()
|
||||||
|
.filter(f -> "image/jpeg".equals(f.getFileType()))
|
||||||
|
.toList();
|
||||||
|
List<Map<String,String>> imgList = new ArrayList<>();
|
||||||
|
for (OrderFile orderFile : imgFiles){
|
||||||
|
Map<String,String> imgMap = new HashMap<>();
|
||||||
|
String url = fileCenterService.getViewUrlByPath(orderFile.getFilePath());
|
||||||
|
imgMap.put("url", url.replace(cdnOssUrl, cdnUrl));
|
||||||
|
imgMap.put("contentType", orderFile.getFileType());
|
||||||
|
imgMap.put("path", orderFile.getFilePath());
|
||||||
|
fileMap.put("path",orderFile.getFilePath());
|
||||||
|
imgMap.put("viewUrl", fileCenterService.getViewUrlByPathStyle(fileMap));
|
||||||
|
imgList.add(imgMap);
|
||||||
|
}
|
||||||
|
orderFileMap.put("imgList", imgList);
|
||||||
|
|
||||||
|
// 视频素材
|
||||||
|
List<OrderFile> videoFiles = allFiles.stream()
|
||||||
|
.filter(f -> "raw_video".equals(f.getFileTag()))
|
||||||
|
.toList();
|
||||||
|
List<Map<String,String>> videoList = new ArrayList<>();
|
||||||
|
for (OrderFile orderFile : videoFiles){
|
||||||
|
Map<String,String> videoMap = new HashMap<>();
|
||||||
|
String url = fileCenterService.getViewUrlByPath(orderFile.getFilePath());
|
||||||
|
videoMap.put("url", url.replace(cdnOssUrl, cdnUrl));
|
||||||
|
videoMap.put("contentType", orderFile.getFileType());
|
||||||
|
videoMap.put("path", orderFile.getFilePath());
|
||||||
|
fileMap.put("path",orderFile.getFilePath());
|
||||||
|
videoMap.put("viewUrl", fileCenterService.getViewUrlByPathStyle(fileMap));
|
||||||
|
videoList.add(videoMap);
|
||||||
|
}
|
||||||
|
orderFileMap.put("videoList", videoList);
|
||||||
|
|
||||||
|
page.add(orderFileMap);
|
||||||
|
}
|
||||||
|
return PageResult.<Map>builder().data(page).resp_code(0).count(result.getCount()).build();
|
||||||
|
}
|
||||||
|
return new PageResult<>();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 移除URL中的参数
|
||||||
|
* @param url 原始URL
|
||||||
|
* @return 移除参数后的URL
|
||||||
|
*/
|
||||||
|
private String removeUrlParams(String url) {
|
||||||
|
if (url == null || url.isEmpty()) {
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
int questionMarkIndex = url.indexOf('?');
|
||||||
|
if (questionMarkIndex != -1) {
|
||||||
|
return url.substring(0, questionMarkIndex);
|
||||||
|
}
|
||||||
|
return url;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+110
-1
@@ -1,13 +1,13 @@
|
|||||||
package com.central.order.controller;
|
package com.central.order.controller;
|
||||||
|
|
||||||
import com.central.common.context.LoginUserContextHolder;
|
import com.central.common.context.LoginUserContextHolder;
|
||||||
|
import com.central.common.context.TenantContextHolder;
|
||||||
import com.central.common.model.*;
|
import com.central.common.model.*;
|
||||||
import com.central.order.constants.EditTaskStatus;
|
import com.central.order.constants.EditTaskStatus;
|
||||||
import com.central.order.enums.OrderStatus;
|
import com.central.order.enums.OrderStatus;
|
||||||
import com.central.order.feign.FileCenterService;
|
import com.central.order.feign.FileCenterService;
|
||||||
import com.central.order.feign.UserCenterService;
|
import com.central.order.feign.UserCenterService;
|
||||||
import com.central.order.model.*;
|
import com.central.order.model.*;
|
||||||
import com.central.order.model.EditTask;
|
|
||||||
import com.central.order.service.*;
|
import com.central.order.service.*;
|
||||||
import com.central.order.util.DateUtils;
|
import com.central.order.util.DateUtils;
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
@@ -22,6 +22,7 @@ import org.springframework.beans.factory.annotation.Value;
|
|||||||
import org.springframework.util.CollectionUtils;
|
import org.springframework.util.CollectionUtils;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.util.ArrayList;
|
||||||
import java.util.HashMap;
|
import java.util.HashMap;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
@@ -54,6 +55,21 @@ public class OrderFileController {
|
|||||||
@Value("${file.style}")
|
@Value("${file.style}")
|
||||||
private String fileStyle;
|
private String fileStyle;
|
||||||
|
|
||||||
|
@Value("${cdn.prefetch.enabled:true}")
|
||||||
|
private boolean cdnPrefetchEnabled;
|
||||||
|
|
||||||
|
@Value("${cdn.prefetch.batch-size:50}")
|
||||||
|
private int cdnPrefetchBatchSize;
|
||||||
|
|
||||||
|
@Value("${cdn.prefetch.area:domestic}")
|
||||||
|
private String cdnPrefetchArea;
|
||||||
|
|
||||||
|
@Value("${file.oss-url}")
|
||||||
|
private String cdnOssUrl;
|
||||||
|
|
||||||
|
@Value("${file.cdn-url}")
|
||||||
|
private String cdnUrl;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private UserCenterService userCenterService;
|
private UserCenterService userCenterService;
|
||||||
|
|
||||||
@@ -164,6 +180,7 @@ public class OrderFileController {
|
|||||||
@PostMapping("/path")
|
@PostMapping("/path")
|
||||||
public Result createOrderFileForPath(@RequestBody OrderFile orderFile) {
|
public Result createOrderFileForPath(@RequestBody OrderFile orderFile) {
|
||||||
try {
|
try {
|
||||||
|
TenantContextHolder.setTenant("webApp");
|
||||||
if (orderFile == null || orderFile.getOrderNo() == null) {
|
if (orderFile == null || orderFile.getOrderNo() == null) {
|
||||||
log.warn("参数为空,orderFile: {}", orderFile);
|
log.warn("参数为空,orderFile: {}", orderFile);
|
||||||
return Result.failed(orderFile,"参数为空");
|
return Result.failed(orderFile,"参数为空");
|
||||||
@@ -205,6 +222,10 @@ public class OrderFileController {
|
|||||||
orderFile.setFilePath(fileInfo.getPath());
|
orderFile.setFilePath(fileInfo.getPath());
|
||||||
orderFile.setFileType(fileInfo.getContentType());
|
orderFile.setFileType(fileInfo.getContentType());
|
||||||
orderFile.setTourismId(order.getTourismId());
|
orderFile.setTourismId(order.getTourismId());
|
||||||
|
// 新增:如果是视频素材且未指定fileTag,默认标记为raw_video
|
||||||
|
if ("video/mp4".equals(orderFile.getFileType()) && (orderFile.getFileTag() == null || orderFile.getFileTag().isEmpty())) {
|
||||||
|
orderFile.setFileTag("raw_video");
|
||||||
|
}
|
||||||
|
|
||||||
// 保存记录
|
// 保存记录
|
||||||
boolean saved = orderFileService.save(orderFile);
|
boolean saved = orderFileService.save(orderFile);
|
||||||
@@ -228,6 +249,8 @@ public class OrderFileController {
|
|||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("素材记录创建异常", e);
|
log.error("素材记录创建异常", e);
|
||||||
return Result.failed(orderFile,"素材记录创建异常: " + e.getMessage());
|
return Result.failed(orderFile,"素材记录创建异常: " + e.getMessage());
|
||||||
|
}finally {
|
||||||
|
TenantContextHolder.clear();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -253,16 +276,27 @@ public class OrderFileController {
|
|||||||
|
|
||||||
// 如果当前文件数量达到或超过二维码要求的数量,则更新订单状态为素材上传完成
|
// 如果当前文件数量达到或超过二维码要求的数量,则更新订单状态为素材上传完成
|
||||||
if (currentFileCount >= qrCode.getMaterialCount()) {
|
if (currentFileCount >= qrCode.getMaterialCount()) {
|
||||||
|
|
||||||
Tourism tourism = tourismService.getTourismById(qrCode.getTourismId());
|
Tourism tourism = tourismService.getTourismById(qrCode.getTourismId());
|
||||||
|
|
||||||
//发送用户素材上传成功通知
|
//发送用户素材上传成功通知
|
||||||
sendMessageForResouresUploaded(order,tourism);
|
sendMessageForResouresUploaded(order,tourism);
|
||||||
|
|
||||||
|
// 预热订单相关的文件到CDN
|
||||||
|
prefetchOrderFilesToCdn(order.getOrderNo());
|
||||||
|
|
||||||
// 检查是否开启一键成片功能
|
// 检查是否开启一键成片功能
|
||||||
if (isVideoEditEnabled(qrCode)) {
|
if (isVideoEditEnabled(qrCode)) {
|
||||||
log.info("二维码已开启一键成片功能,开始触发一键成片: orderNo={}, codeId={}",
|
log.info("二维码已开启一键成片功能,开始触发一键成片: orderNo={}, codeId={}",
|
||||||
order.getOrderNo(), order.getCodeId());
|
order.getOrderNo(), order.getCodeId());
|
||||||
|
|
||||||
|
// 检查是否存在进行中的编辑任务
|
||||||
|
EditTask existingTask = editTaskService.getTaskByOrderSn(order.getOrderNo());
|
||||||
|
if (existingTask != null && EditTaskStatus.isProcessing(existingTask.getStatus())) {
|
||||||
|
log.info("已存在进行中的编辑任务: orderNo={}, taskId={}", order.getOrderNo(), existingTask.getId());
|
||||||
|
return ;
|
||||||
|
}
|
||||||
|
|
||||||
//触发一键成片
|
//触发一键成片
|
||||||
// 1. 创建新任务
|
// 1. 创建新任务
|
||||||
EditTask task = editTaskService.createTask(order.getOrderNo(), order.getUserId());
|
EditTask task = editTaskService.createTask(order.getOrderNo(), order.getUserId());
|
||||||
@@ -324,6 +358,81 @@ public class OrderFileController {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 预热订单相关的文件到CDN
|
||||||
|
* @param orderNo 订单号
|
||||||
|
*/
|
||||||
|
private void prefetchOrderFilesToCdn(String orderNo) {
|
||||||
|
// 检查CDN预热功能是否启用
|
||||||
|
if (!cdnPrefetchEnabled) {
|
||||||
|
log.debug("CDN预热功能未启用,跳过预热,订单号: {}", orderNo);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
log.info("开始预热订单文件到CDN,订单号: {}", orderNo);
|
||||||
|
|
||||||
|
// 获取订单的所有文件
|
||||||
|
List<OrderFile> orderFiles = orderFileService.getOrderFileByOrderNo(orderNo);
|
||||||
|
if (CollectionUtils.isEmpty(orderFiles)) {
|
||||||
|
log.info("订单无文件需要预热,订单号: {}", orderNo);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 收集所有文件的URL
|
||||||
|
List<String> fileUrls = new ArrayList<>();
|
||||||
|
for (OrderFile orderFile : orderFiles) {
|
||||||
|
try {
|
||||||
|
String viewUrl = fileCenterService.getViewUrlByPath(orderFile.getFilePath());
|
||||||
|
if (viewUrl != null && !viewUrl.trim().isEmpty()) {
|
||||||
|
// 替换OSS域名为CDN域名,并移除URL参数
|
||||||
|
String cleanUrl = viewUrl.replace(cdnOssUrl, cdnUrl);
|
||||||
|
fileUrls.add(cleanUrl);
|
||||||
|
log.debug("添加文件URL到预热列表: {}", cleanUrl);
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("获取文件URL失败,文件路径: {}", orderFile.getFilePath(), e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (fileUrls.isEmpty()) {
|
||||||
|
log.info("没有有效的文件URL需要预热,订单号: {}", orderNo);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info("准备预热 {} 个文件到CDN,订单号: {}, 批次大小: {}, 预热区域: {}",
|
||||||
|
fileUrls.size(), orderNo, cdnPrefetchBatchSize, cdnPrefetchArea);
|
||||||
|
|
||||||
|
// 调用CDN批量预热接口
|
||||||
|
Result<Boolean> result = fileCenterService.batchPrefetchFiles(fileUrls, cdnPrefetchBatchSize, cdnPrefetchArea);
|
||||||
|
|
||||||
|
if (result != null && result.getResp_code() == 0) {
|
||||||
|
log.info("订单文件CDN预热成功,订单号: {}, 文件数量: {}", orderNo, fileUrls.size());
|
||||||
|
} else {
|
||||||
|
log.warn("订单文件CDN预热失败,订单号: {}, 错误信息: {}",
|
||||||
|
orderNo, result != null ? result.getResp_msg() : "未知错误");
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("预热订单文件到CDN异常,订单号: {}", orderNo, e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 移除URL中的参数
|
||||||
|
* @param url 原始URL
|
||||||
|
* @return 移除参数后的URL
|
||||||
|
*/
|
||||||
|
private String removeUrlParams(String url) {
|
||||||
|
if (url == null || url.isEmpty()) {
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
int questionMarkIndex = url.indexOf('?');
|
||||||
|
if (questionMarkIndex != -1) {
|
||||||
|
return url.substring(0, questionMarkIndex);
|
||||||
|
}
|
||||||
|
return url;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
@Operation(summary = "删除文件")
|
@Operation(summary = "删除文件")
|
||||||
|
|||||||
+10
-6
@@ -67,14 +67,16 @@ public class OrderStatisticsController {
|
|||||||
@Operation(summary = "按景区维度统计", description = "统计时间范围内各景区的订单数据")
|
@Operation(summary = "按景区维度统计", description = "统计时间范围内各景区的订单数据")
|
||||||
@Parameters({
|
@Parameters({
|
||||||
@Parameter(name = "startTime", description = "开始时间 (格式:yyyy-MM-dd HH:mm:ss)", required = true),
|
@Parameter(name = "startTime", description = "开始时间 (格式:yyyy-MM-dd HH:mm:ss)", required = true),
|
||||||
@Parameter(name = "endTime", description = "结束时间 (格式:yyyy-MM-dd HH:mm:ss)", required = true)
|
@Parameter(name = "endTime", description = "结束时间 (格式:yyyy-MM-dd HH:mm:ss)", required = true),
|
||||||
|
@Parameter(name = "tourismId", description = "景区ID筛选", required = false)
|
||||||
})
|
})
|
||||||
@GetMapping("/tourism")
|
@GetMapping("/tourism")
|
||||||
public Result<List<Map<String, Object>>> statisticsByTourism(
|
public Result<List<Map<String, Object>>> statisticsByTourism(
|
||||||
@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String startTime,
|
@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String startTime,
|
||||||
@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String endTime) {
|
@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String endTime,
|
||||||
|
@RequestParam(required = false) String tourismId) {
|
||||||
try {
|
try {
|
||||||
List<Map<String, Object>> result = orderStatisticsService.statisticsByTourism(startTime, endTime);
|
List<Map<String, Object>> result = orderStatisticsService.statisticsByTourism(startTime, endTime, tourismId);
|
||||||
return Result.succeed(result, "获取景区维度统计数据成功");
|
return Result.succeed(result, "获取景区维度统计数据成功");
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("获取景区维度统计数据失败", e);
|
log.error("获取景区维度统计数据失败", e);
|
||||||
@@ -85,14 +87,16 @@ public class OrderStatisticsController {
|
|||||||
@Operation(summary = "按设备维度统计", description = "统计时间范围内各设备的订单数据")
|
@Operation(summary = "按设备维度统计", description = "统计时间范围内各设备的订单数据")
|
||||||
@Parameters({
|
@Parameters({
|
||||||
@Parameter(name = "startTime", description = "开始时间 (格式:yyyy-MM-dd HH:mm:ss)", required = true),
|
@Parameter(name = "startTime", description = "开始时间 (格式:yyyy-MM-dd HH:mm:ss)", required = true),
|
||||||
@Parameter(name = "endTime", description = "结束时间 (格式:yyyy-MM-dd HH:mm:ss)", required = true)
|
@Parameter(name = "endTime", description = "结束时间 (格式:yyyy-MM-dd HH:mm:ss)", required = true),
|
||||||
|
@Parameter(name = "deviceSn", description = "设备编号筛选", required = false)
|
||||||
})
|
})
|
||||||
@GetMapping("/device")
|
@GetMapping("/device")
|
||||||
public Result<List<Map<String, Object>>> statisticsByDevice(
|
public Result<List<Map<String, Object>>> statisticsByDevice(
|
||||||
@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String startTime,
|
@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String startTime,
|
||||||
@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String endTime) {
|
@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String endTime,
|
||||||
|
@RequestParam(required = false) String deviceSn) {
|
||||||
try {
|
try {
|
||||||
List<Map<String, Object>> result = orderStatisticsService.statisticsByDevice(startTime, endTime);
|
List<Map<String, Object>> result = orderStatisticsService.statisticsByDevice(startTime, endTime, deviceSn);
|
||||||
return Result.succeed(result, "获取设备维度统计数据成功");
|
return Result.succeed(result, "获取设备维度统计数据成功");
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("获取设备维度统计数据失败", e);
|
log.error("获取设备维度统计数据失败", e);
|
||||||
|
|||||||
+3
@@ -79,6 +79,9 @@ public class QrCodeController {
|
|||||||
String codeId = UUID.randomUUID().toString();
|
String codeId = UUID.randomUUID().toString();
|
||||||
Result<Map> result = fileCenterService.uploadQrCodeFile(codeId);
|
Result<Map> result = fileCenterService.uploadQrCodeFile(codeId);
|
||||||
if (result.getResp_code() == 0){
|
if (result.getResp_code() == 0){
|
||||||
|
Tourism tourism = tourismService.getTourismById(qrCode.getTourismId());
|
||||||
|
Assert.notNull(tourism, "请选择景区数据");
|
||||||
|
qrCode.setTenantId(tourism.getTenantId());
|
||||||
qrCode.setCodeId(codeId);
|
qrCode.setCodeId(codeId);
|
||||||
qrCode.setFilePath(result.getData().get("filePath").toString());
|
qrCode.setFilePath(result.getData().get("filePath").toString());
|
||||||
qrCode.setFileId(result.getData().get("fileId").toString());
|
qrCode.setFileId(result.getData().get("fileId").toString());
|
||||||
|
|||||||
+51
-6
@@ -1,5 +1,6 @@
|
|||||||
package com.central.order.controller;
|
package com.central.order.controller;
|
||||||
|
|
||||||
|
import com.central.common.context.TenantContextHolder;
|
||||||
import com.central.common.model.PageResult;
|
import com.central.common.model.PageResult;
|
||||||
import com.central.common.model.Result;
|
import com.central.common.model.Result;
|
||||||
import com.central.common.model.SysUser;
|
import com.central.common.model.SysUser;
|
||||||
@@ -7,10 +8,15 @@ import com.central.order.enums.OrderStatus;
|
|||||||
import com.central.order.enums.RefundState;
|
import com.central.order.enums.RefundState;
|
||||||
import com.central.order.feign.UserCenterService;
|
import com.central.order.feign.UserCenterService;
|
||||||
import com.central.order.model.Order;
|
import com.central.order.model.Order;
|
||||||
|
import com.central.order.model.QrCode;
|
||||||
import com.central.order.service.IOrderService;
|
import com.central.order.service.IOrderService;
|
||||||
|
import com.central.order.service.IQrCodeService;
|
||||||
import com.central.order.service.IRefundService;
|
import com.central.order.service.IRefundService;
|
||||||
import com.central.order.service.IWxTemplateMessageService;
|
import com.central.order.service.IWxTemplateMessageService;
|
||||||
import com.central.wechat.config.WxPayConfigFactory;
|
import com.central.wechat.config.WxPayConfigFactory;
|
||||||
|
import com.central.wechat.entity.WechatConfig;
|
||||||
|
import com.central.wechat.feign.WechatConfigService;
|
||||||
|
import com.wechat.pay.java.service.refund.RefundService;
|
||||||
import com.wechat.pay.java.service.refund.model.AmountReq;
|
import com.wechat.pay.java.service.refund.model.AmountReq;
|
||||||
import com.wechat.pay.java.service.refund.model.CreateRequest;
|
import com.wechat.pay.java.service.refund.model.CreateRequest;
|
||||||
import com.wechat.pay.java.service.refund.model.Refund;
|
import com.wechat.pay.java.service.refund.model.Refund;
|
||||||
@@ -49,6 +55,12 @@ public class RefundController {
|
|||||||
@Autowired
|
@Autowired
|
||||||
private UserCenterService userCenterService;
|
private UserCenterService userCenterService;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private WechatConfigService wechatConfigService;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private IQrCodeService qrCodeService;
|
||||||
|
|
||||||
@Value("${tencent.refund-notify-url}")
|
@Value("${tencent.refund-notify-url}")
|
||||||
private String refundNotifyUrl;
|
private String refundNotifyUrl;
|
||||||
|
|
||||||
@@ -105,6 +117,7 @@ public class RefundController {
|
|||||||
@Transactional(rollbackFor = Exception.class)
|
@Transactional(rollbackFor = Exception.class)
|
||||||
public Result<com.central.order.model.Refund> approveOrder(@RequestBody com.central.order.model.Refund refund) {
|
public Result<com.central.order.model.Refund> approveOrder(@RequestBody com.central.order.model.Refund refund) {
|
||||||
|
|
||||||
|
log.info("审批退款单,订单号: {}, 退款单号: {}", refund.getOrderNo(), refund.getRefundNo());
|
||||||
// 检查订单是否存在
|
// 检查订单是否存在
|
||||||
Order order = orderService.getOrderByNumber(refund.getOrderNo());
|
Order order = orderService.getOrderByNumber(refund.getOrderNo());
|
||||||
Assert.notNull(order, "ORDER DATA不存在");
|
Assert.notNull(order, "ORDER DATA不存在");
|
||||||
@@ -134,6 +147,8 @@ public class RefundController {
|
|||||||
public Result<String> autoRefundProcess(@RequestBody Map payload) {
|
public Result<String> autoRefundProcess(@RequestBody Map payload) {
|
||||||
String orderNo = payload.get("orderNo").toString();
|
String orderNo = payload.get("orderNo").toString();
|
||||||
Assert.notNull(orderNo,"订单数据不能为空");
|
Assert.notNull(orderNo,"订单数据不能为空");
|
||||||
|
//机库端触发异常后自动创建退款单,没有带请求头信息,因此没有租户ID @TODO
|
||||||
|
TenantContextHolder.setTenant("webApp");
|
||||||
log.info("收到自动退款请求,订单号: {}", orderNo);
|
log.info("收到自动退款请求,订单号: {}", orderNo);
|
||||||
try {
|
try {
|
||||||
|
|
||||||
@@ -203,6 +218,8 @@ public class RefundController {
|
|||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("退款流程测试失败,订单号: {},异常: {}", orderNo, e.getMessage(), e);
|
log.error("退款流程测试失败,订单号: {},异常: {}", orderNo, e.getMessage(), e);
|
||||||
return Result.failed("退款流程测试失败:" + e.getMessage());
|
return Result.failed("退款流程测试失败:" + e.getMessage());
|
||||||
|
}finally {
|
||||||
|
TenantContextHolder.clear();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -212,29 +229,57 @@ public class RefundController {
|
|||||||
*/
|
*/
|
||||||
private void dealRefundRequest(Order order) {
|
private void dealRefundRequest(Order order) {
|
||||||
try {
|
try {
|
||||||
|
// 获取二维码信息
|
||||||
|
QrCode qrCode = qrCodeService.getByCodeId(order.getCodeId());
|
||||||
|
if (qrCode == null) {
|
||||||
|
log.error("二维码不存在,订单号: {}", order.getOrderNo());
|
||||||
|
throw new RuntimeException("二维码不存在");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 获取微信支付配置
|
||||||
|
WechatConfig wechatConfig = wechatConfigService.getConfig("PAY", qrCode.getTenantId());
|
||||||
|
if (wechatConfig == null) {
|
||||||
|
log.error("微信支付配置不存在,租户ID: {}", qrCode.getTenantId());
|
||||||
|
throw new RuntimeException("微信支付配置不存在");
|
||||||
|
}
|
||||||
|
|
||||||
// 创建微信退款请求
|
// 创建微信退款请求
|
||||||
CreateRequest request = new CreateRequest();
|
CreateRequest request = new CreateRequest();
|
||||||
request.setOutTradeNo(order.getOrderNo());
|
request.setOutTradeNo(order.getOrderNo());
|
||||||
request.setOutRefundNo("RF" + order.getOrderNo());
|
request.setOutRefundNo("RF" + order.getOrderNo());
|
||||||
request.setReason("用户申请退款");
|
request.setReason("用户申请退款");
|
||||||
// 从配置文件中获取退款结果回调通知地址
|
|
||||||
request.setNotifyUrl(refundNotifyUrl);
|
request.setNotifyUrl(refundNotifyUrl);
|
||||||
|
|
||||||
// 设置退款金额
|
// 设置退款金额
|
||||||
AmountReq amount = new AmountReq();
|
AmountReq amount = new AmountReq();
|
||||||
// 订单总金额,单位为分
|
|
||||||
amount.setTotal(Long.valueOf(order.getOrderAmount()));
|
amount.setTotal(Long.valueOf(order.getOrderAmount()));
|
||||||
// 退款金额,单位为分
|
|
||||||
amount.setRefund(Long.valueOf(order.getOrderAmount()));
|
amount.setRefund(Long.valueOf(order.getOrderAmount()));
|
||||||
amount.setCurrency("CNY");
|
amount.setCurrency("CNY");
|
||||||
request.setAmount(amount);
|
request.setAmount(amount);
|
||||||
|
|
||||||
|
// 根据是否为服务商模式设置不同的参数
|
||||||
|
RefundService refundService;
|
||||||
|
if (Boolean.TRUE.equals(wechatConfig.getIsServiceMode())) {
|
||||||
|
// 服务商模式:需要设置子商户号
|
||||||
|
request.setSubMchid(wechatConfig.getSubMchId());
|
||||||
|
log.info("服务商模式退款,子商户号: {}, 订单号: {}", wechatConfig.getSubMchId(), order.getOrderNo());
|
||||||
|
|
||||||
|
// 创建服务商模式的退款服务
|
||||||
|
refundService = wxPayConfigFactory.createRefundServiceBySubMchId(wechatConfig.getSubMchId());
|
||||||
|
} else {
|
||||||
|
// 普通商户模式
|
||||||
|
log.info("普通商户模式退款,商户号: {}, 订单号: {}", wechatConfig.getMerchantId(), order.getOrderNo());
|
||||||
|
refundService = wxPayConfigFactory.createRefundService(qrCode.getTenantId());
|
||||||
|
}
|
||||||
|
|
||||||
// 发起退款请求
|
// 发起退款请求
|
||||||
Refund response = wxPayConfigFactory.createRefundService(order.getTenantId()).create(request);
|
Refund response = refundService.create(request);
|
||||||
Assert.notNull(response, "退款失败");
|
Assert.notNull(response, "退款失败");
|
||||||
|
|
||||||
|
log.info("退款请求成功,退款单号: {}, 订单号: {}", response.getRefundId(), order.getOrderNo());
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
// 记录异常信息
|
log.error("退款请求失败,订单号: {}, 异常: {}", order.getOrderNo(), e.getMessage(), e);
|
||||||
e.printStackTrace();
|
throw new RuntimeException("退款失败: " + e.getMessage(), e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+109
-2
@@ -1,8 +1,12 @@
|
|||||||
package com.central.order.controller;
|
package com.central.order.controller;
|
||||||
|
|
||||||
|
import com.central.common.context.LoginUserContextHolder;
|
||||||
|
import com.central.common.context.TenantContextHolder;
|
||||||
|
import com.central.common.model.LoginAppUser;
|
||||||
import com.central.common.model.PageResult;
|
import com.central.common.model.PageResult;
|
||||||
import com.central.common.model.Result;
|
import com.central.common.model.Result;
|
||||||
import com.central.order.model.Tourism;
|
import com.central.order.model.Tourism;
|
||||||
|
import com.central.order.model.TourismWithDistance;
|
||||||
import com.central.order.service.ITourismService;
|
import com.central.order.service.ITourismService;
|
||||||
import io.swagger.v3.oas.annotations.Operation;
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
import io.swagger.v3.oas.annotations.Parameter;
|
import io.swagger.v3.oas.annotations.Parameter;
|
||||||
@@ -12,19 +16,24 @@ import io.swagger.v3.oas.annotations.tags.Tag;
|
|||||||
import lombok.RequiredArgsConstructor;
|
import lombok.RequiredArgsConstructor;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.security.core.context.SecurityContextHolder;
|
||||||
import org.springframework.web.bind.annotation.*;
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.util.List;
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Tourism information
|
* 景区管理控制器
|
||||||
*
|
*
|
||||||
* @author lsl
|
* @author lsl
|
||||||
* @date 2024-12-19 17:51:47
|
* @date 2024-12-19 17:51:47
|
||||||
*/
|
*/
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@RestController
|
@RestController
|
||||||
@Tag(name = "Tourism管理")
|
@Tag(name = "景区管理")
|
||||||
@RequestMapping("/tourism")
|
@RequestMapping("/tourism")
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class TourismController {
|
public class TourismController {
|
||||||
@@ -47,6 +56,11 @@ public class TourismController {
|
|||||||
|
|
||||||
@PostMapping()
|
@PostMapping()
|
||||||
public Result saveOrUpdate(@RequestBody Tourism tourism) {
|
public Result saveOrUpdate(@RequestBody Tourism tourism) {
|
||||||
|
if (tourism.getTenantId() == null) {
|
||||||
|
String tenantId = TenantContextHolder.getTenant();
|
||||||
|
//新增景区所属租户ID,创建景区的时候在
|
||||||
|
tourism.setTenantId(tenantId);
|
||||||
|
}
|
||||||
return tourismService.saveOrUpdateTourism(tourism);
|
return tourismService.saveOrUpdateTourism(tourism);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -66,4 +80,97 @@ public class TourismController {
|
|||||||
boolean result = tourismService.removeById(tourism);
|
boolean result = tourismService.removeById(tourism);
|
||||||
return result ? Result.succeed(tourism, "操作成功") : Result.failed("操作失败");
|
return result ? Result.succeed(tourism, "操作成功") : Result.failed("操作失败");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取景区设备列表
|
||||||
|
* 通过景区下的二维码信息查询二维码绑定的设备
|
||||||
|
*/
|
||||||
|
@Operation(summary = "获取景区设备列表")
|
||||||
|
@GetMapping("/{tourismId}/devices")
|
||||||
|
public Result getTourismDevices(@PathVariable("tourismId") Long tourismId) {
|
||||||
|
try {
|
||||||
|
var devices = tourismService.getDevicesByTourismId(tourismId);
|
||||||
|
return Result.succeed(devices, "获取景区设备列表成功");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("获取景区设备列表失败", e);
|
||||||
|
return Result.failed("获取景区设备列表失败:" + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询附近景区列表
|
||||||
|
*/
|
||||||
|
@Operation(summary = "查询附近景区列表")
|
||||||
|
@Parameters({
|
||||||
|
@Parameter(name = "longitude", description = "经度", required = true, in = ParameterIn.QUERY),
|
||||||
|
@Parameter(name = "latitude", description = "纬度", required = true, in = ParameterIn.QUERY),
|
||||||
|
@Parameter(name = "radius", description = "搜索半径(公里),默认10km", required = false, in = ParameterIn.QUERY),
|
||||||
|
@Parameter(name = "limit", description = "返回数量限制,默认20个", required = false, in = ParameterIn.QUERY)
|
||||||
|
})
|
||||||
|
@GetMapping("/nearby")
|
||||||
|
public Result<List<TourismWithDistance>> findNearbyTourisms(
|
||||||
|
@RequestParam BigDecimal longitude,
|
||||||
|
@RequestParam BigDecimal latitude,
|
||||||
|
@RequestParam(required = false) Double radius,
|
||||||
|
@RequestParam(required = false) Integer limit) {
|
||||||
|
try {
|
||||||
|
log.info("查询附近景区,经度: {}, 纬度: {}, 半径: {}km, 限制数量: {}", longitude, latitude, radius, limit);
|
||||||
|
List<TourismWithDistance> tourisms = tourismService.findNearbyTourisms(longitude, latitude, radius, limit);
|
||||||
|
return Result.succeed(tourisms, "查询附近景区成功");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("查询附近景区失败", e);
|
||||||
|
return Result.failed("查询附近景区失败:" + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据经纬度范围查询景区
|
||||||
|
*/
|
||||||
|
@Operation(summary = "根据经纬度范围查询景区")
|
||||||
|
@Parameters({
|
||||||
|
@Parameter(name = "minLongitude", description = "最小经度", required = true, in = ParameterIn.QUERY),
|
||||||
|
@Parameter(name = "maxLongitude", description = "最大经度", required = true, in = ParameterIn.QUERY),
|
||||||
|
@Parameter(name = "minLatitude", description = "最小纬度", required = true, in = ParameterIn.QUERY),
|
||||||
|
@Parameter(name = "maxLatitude", description = "最大纬度", required = true, in = ParameterIn.QUERY)
|
||||||
|
})
|
||||||
|
@GetMapping("/bounds")
|
||||||
|
public Result<List<Tourism>> findTourismsByBounds(
|
||||||
|
@RequestParam BigDecimal minLongitude,
|
||||||
|
@RequestParam BigDecimal maxLongitude,
|
||||||
|
@RequestParam BigDecimal minLatitude,
|
||||||
|
@RequestParam BigDecimal maxLatitude) {
|
||||||
|
try {
|
||||||
|
log.info("根据经纬度范围查询景区,经度范围: [{}, {}], 纬度范围: [{}, {}]",
|
||||||
|
minLongitude, maxLongitude, minLatitude, maxLatitude);
|
||||||
|
List<Tourism> tourisms = tourismService.findTourismsByBounds(minLongitude, maxLongitude, minLatitude, maxLatitude);
|
||||||
|
return Result.succeed(tourisms, "查询景区成功");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("根据经纬度范围查询景区失败", e);
|
||||||
|
return Result.failed("查询景区失败:" + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 更新景区经纬度信息
|
||||||
|
*/
|
||||||
|
@Operation(summary = "更新景区经纬度信息")
|
||||||
|
@Parameters({
|
||||||
|
@Parameter(name = "id", description = "景区ID", required = true, in = ParameterIn.PATH),
|
||||||
|
@Parameter(name = "longitude", description = "经度", required = true, in = ParameterIn.QUERY),
|
||||||
|
@Parameter(name = "latitude", description = "纬度", required = true, in = ParameterIn.QUERY)
|
||||||
|
})
|
||||||
|
@PutMapping("/{id}/location")
|
||||||
|
public Result updateTourismLocation(
|
||||||
|
@PathVariable Long id,
|
||||||
|
@RequestParam BigDecimal longitude,
|
||||||
|
@RequestParam BigDecimal latitude) {
|
||||||
|
try {
|
||||||
|
log.info("更新景区经纬度信息,景区ID: {}, 经度: {}, 纬度: {}", id, longitude, latitude);
|
||||||
|
return tourismService.updateTourismLocation(id, longitude, latitude);
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("更新景区经纬度信息失败", e);
|
||||||
|
return Result.failed("更新景区经纬度信息失败:" + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
+59
-11
@@ -1,5 +1,6 @@
|
|||||||
package com.central.order.controller;
|
package com.central.order.controller;
|
||||||
|
|
||||||
|
import com.central.common.context.TenantContextHolder;
|
||||||
import com.central.order.enums.OrderStatus;
|
import com.central.order.enums.OrderStatus;
|
||||||
import com.central.order.enums.RefundState;
|
import com.central.order.enums.RefundState;
|
||||||
import com.central.order.model.Order;
|
import com.central.order.model.Order;
|
||||||
@@ -69,6 +70,8 @@ public class WxPayController {
|
|||||||
WechatConfig config = wechatConfigService.getConfigBySerialNumber(serial);
|
WechatConfig config = wechatConfigService.getConfigBySerialNumber(serial);
|
||||||
Assert.notNull(config,"支付配置参数为空,请确认参数是否正确配置");
|
Assert.notNull(config,"支付配置参数为空,请确认参数是否正确配置");
|
||||||
String tenantId = config.getTenantId();
|
String tenantId = config.getTenantId();
|
||||||
|
log.info("订单支付回调租户ID设置,租户ID:{}", tenantId);
|
||||||
|
TenantContextHolder.setTenant(tenantId);
|
||||||
|
|
||||||
// 创建通知解析器
|
// 创建通知解析器
|
||||||
NotificationParser notificationParser;
|
NotificationParser notificationParser;
|
||||||
@@ -120,12 +123,36 @@ public class WxPayController {
|
|||||||
* 处理服务商模式下的支付结果
|
* 处理服务商模式下的支付结果
|
||||||
*/
|
*/
|
||||||
private void handleSubMerchantPaymentResult(Transaction transaction, WechatConfig config) {
|
private void handleSubMerchantPaymentResult(Transaction transaction, WechatConfig config) {
|
||||||
// TODO: 实现服务商模式下的支付结果处理逻辑
|
|
||||||
log.info("处理服务商模式支付结果,子商户号:{}", config.getSubMchId());
|
log.info("处理服务商模式支付结果,子商户号:{}", config.getSubMchId());
|
||||||
|
|
||||||
// 1. 更新订单状态
|
String outTradeNo = transaction.getOutTradeNo();
|
||||||
// 2. 处理分账逻辑(如果需要)
|
String tradeState = transaction.getTradeState().toString();
|
||||||
// 3. 发送通知
|
|
||||||
|
try {
|
||||||
|
if ("SUCCESS".equals(tradeState)) {
|
||||||
|
// 1. 获取订单和二维码信息
|
||||||
|
Order order = orderService.getOrderByNumber(outTradeNo);
|
||||||
|
if (order == null) {
|
||||||
|
log.error("订单不存在: {}", outTradeNo);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
QrCode qrCode = qrCodeService.getByCodeId(order.getCodeId());
|
||||||
|
if (qrCode == null) {
|
||||||
|
log.error("二维码不存在: {}", order.getCodeId());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. 更新订单状态
|
||||||
|
order.setOrderStatus(OrderStatus.PAID.getId());
|
||||||
|
order.setPayTime(new Date());
|
||||||
|
orderService.updateOrder(order);
|
||||||
|
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
throw new RuntimeException(e);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -185,10 +212,10 @@ public class WxPayController {
|
|||||||
|
|
||||||
// 根据证书序列号获取配置
|
// 根据证书序列号获取配置
|
||||||
WechatConfig config = wechatConfigService.getConfigBySerialNumber(serial);
|
WechatConfig config = wechatConfigService.getConfigBySerialNumber(serial);
|
||||||
String tenantId = defaultTenantId;
|
Assert.notNull(config,"支付配置参数为空,请确认参数是否正确配置");
|
||||||
if (config != null) {
|
String tenantId = config.getTenantId();
|
||||||
tenantId = config.getTenantId();
|
log.info("订单退款回调租户ID设置,租户ID:{}", tenantId);
|
||||||
}
|
TenantContextHolder.setTenant(tenantId);
|
||||||
|
|
||||||
// 创建通知解析器
|
// 创建通知解析器
|
||||||
NotificationParser notificationParser;
|
NotificationParser notificationParser;
|
||||||
@@ -240,11 +267,32 @@ public class WxPayController {
|
|||||||
* 处理服务商模式下的退款结果
|
* 处理服务商模式下的退款结果
|
||||||
*/
|
*/
|
||||||
private void handleSubMerchantRefundResult(RefundNotification notification, WechatConfig config) {
|
private void handleSubMerchantRefundResult(RefundNotification notification, WechatConfig config) {
|
||||||
// TODO: 实现服务商模式下的退款结果处理逻辑
|
|
||||||
log.info("处理服务商模式退款结果,子商户号:{}", config.getSubMchId());
|
log.info("处理服务商模式退款结果,子商户号:{}", config.getSubMchId());
|
||||||
|
|
||||||
// 1. 更新退款状态
|
// 获取退款通知中的关键信息
|
||||||
// 2. 处理相关业务逻辑
|
String outRefundNo = notification.getOutRefundNo();
|
||||||
|
|
||||||
|
log.info("回调返回结果"+notification);
|
||||||
|
// 根据退款状态进行相应处理
|
||||||
|
if (Status.SUCCESS.equals(notification.getRefundStatus())) {
|
||||||
|
// 退款成功,更新订单状态等操作
|
||||||
|
com.central.order.model.Refund refund = refundService.getRefundByNo(outRefundNo);
|
||||||
|
Assert.notNull(refund,"退款订单数据不存在");
|
||||||
|
refund.setStatus(OrderStatus.REFUNDED.getId());
|
||||||
|
refund.setState(RefundState.APPROVED.getId());
|
||||||
|
refund.setRefundTime(new Date());
|
||||||
|
refundService.updateById(refund);
|
||||||
|
|
||||||
|
Order order = orderService.getOrderByNumber(refund.getOrderNo());
|
||||||
|
Assert.notNull(order,"订单数据不存在");
|
||||||
|
order.setOrderStatus(OrderStatus.REFUNDED.getId());
|
||||||
|
orderService.updateOrder(order);
|
||||||
|
} else if ("CLOSED".equals(notification.getRefundStatus())) {
|
||||||
|
// 退款关闭,处理退款关闭逻辑
|
||||||
|
} else {
|
||||||
|
// 其他退款状态,如退款中、失败等
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -0,0 +1,143 @@
|
|||||||
|
package com.central.order.entity;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.annotation.IdType;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableId;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableName;
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableField;
|
||||||
|
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.EqualsAndHashCode;
|
||||||
|
|
||||||
|
import java.io.Serializable;
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.time.LocalDateTime;
|
||||||
|
import java.util.Date;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 优惠券实体类
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@EqualsAndHashCode(callSuper = false)
|
||||||
|
@TableName("t_coupon")
|
||||||
|
public class Coupon implements Serializable {
|
||||||
|
|
||||||
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 主键ID
|
||||||
|
*/
|
||||||
|
@TableId(value = "id", type = IdType.AUTO)
|
||||||
|
private Long id;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 优惠券编号
|
||||||
|
*/
|
||||||
|
private String couponNo;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 优惠券名称
|
||||||
|
*/
|
||||||
|
private String couponName;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 优惠券类型:1-满减券,2-折扣券,3-免费券
|
||||||
|
*/
|
||||||
|
private Integer couponType;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 优惠券面额
|
||||||
|
*/
|
||||||
|
private BigDecimal amount;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 使用门槛金额
|
||||||
|
*/
|
||||||
|
private BigDecimal minAmount;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 折扣率(0-100,折扣券时使用)
|
||||||
|
*/
|
||||||
|
private Integer discountRate;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 优惠券状态:0-未使用,1-已使用,2-已过期,3-已作废
|
||||||
|
*/
|
||||||
|
private Integer status;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用户手机号
|
||||||
|
*/
|
||||||
|
private String userPhone;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用户ID
|
||||||
|
*/
|
||||||
|
private Long userId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 来源:1-携程,2-高飞自建
|
||||||
|
*/
|
||||||
|
private Integer source;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 携程优惠券ID(来源为携程时使用)
|
||||||
|
*/
|
||||||
|
private String ctripCouponId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 有效期开始时间
|
||||||
|
*/
|
||||||
|
private Date validStartTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 有效期结束时间
|
||||||
|
*/
|
||||||
|
private Date validEndTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 使用时间
|
||||||
|
*/
|
||||||
|
private Date usedTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 使用订单号
|
||||||
|
*/
|
||||||
|
private String usedOrderNo;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 退券时间
|
||||||
|
*/
|
||||||
|
private Date cancelTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建时间
|
||||||
|
*/
|
||||||
|
@TableField(fill = FieldFill.INSERT)
|
||||||
|
private Date createTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 更新时间
|
||||||
|
*/
|
||||||
|
@TableField(fill = FieldFill.INSERT_UPDATE)
|
||||||
|
private Date updateTime;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 租户ID
|
||||||
|
*/
|
||||||
|
private String tenantId;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建人
|
||||||
|
*/
|
||||||
|
private String createBy;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 更新人
|
||||||
|
*/
|
||||||
|
private String updateBy;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 备注
|
||||||
|
*/
|
||||||
|
private String remark;
|
||||||
|
}
|
||||||
+3
-1
@@ -14,7 +14,9 @@ public enum HomeCarouselType implements ZltEnum {
|
|||||||
ACTIVITY(1, "活动"),
|
ACTIVITY(1, "活动"),
|
||||||
SHOOTING_ANGLE(2,"拍照角度"),
|
SHOOTING_ANGLE(2,"拍照角度"),
|
||||||
GUIDANCE(3,"引导"),
|
GUIDANCE(3,"引导"),
|
||||||
BIG_PICTURE(4,"大图");
|
BIG_PICTURE(4,"大图"),
|
||||||
|
VIDEO(5,"景区视频"),
|
||||||
|
ORDER_SHOW(6,"订单展示图");
|
||||||
|
|
||||||
private Integer id;
|
private Integer id;
|
||||||
private String content;
|
private String content;
|
||||||
|
|||||||
+23
@@ -47,4 +47,27 @@ public interface FileCenterService {
|
|||||||
|
|
||||||
@GetMapping("/list/files")
|
@GetMapping("/list/files")
|
||||||
List<String> getListFiles(@RequestParam("prefix") String prefix) ;
|
List<String> getListFiles(@RequestParam("prefix") String prefix) ;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 预热文件到CDN
|
||||||
|
*
|
||||||
|
* @param urls 需要预热的URL列表
|
||||||
|
* @param area 预热范围:domestic-仅中国内地,overseas-全球(不包含中国内地),不传-全球
|
||||||
|
* @return 预热任务ID
|
||||||
|
*/
|
||||||
|
@PostMapping("/cdn/prefetch")
|
||||||
|
Result<String> prefetchFiles(@RequestBody List<String> urls, @RequestParam(value = "area", required = false) String area);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 批量预热文件到CDN
|
||||||
|
*
|
||||||
|
* @param urls 需要预热的URL列表
|
||||||
|
* @param batchSize 每批次处理的URL数量
|
||||||
|
* @param area 预热范围
|
||||||
|
* @return 预热任务执行结果
|
||||||
|
*/
|
||||||
|
@PostMapping("/cdn/batch/prefetch")
|
||||||
|
Result<Boolean> batchPrefetchFiles(@RequestBody List<String> urls,
|
||||||
|
@RequestParam(value = "batchSize", defaultValue = "100") int batchSize,
|
||||||
|
@RequestParam(value = "area", required = false) String area);
|
||||||
}
|
}
|
||||||
|
|||||||
+12
@@ -61,6 +61,18 @@ public class FileCenterServiceFallbackFactory implements FallbackFactory<FileCen
|
|||||||
return List.of();
|
return List.of();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Result<String> prefetchFiles(List<String> urls, String area) {
|
||||||
|
log.warn("CDN预热文件失败,URLs: {}, area: {}", urls, area, cause);
|
||||||
|
return Result.failed("CDN预热文件失败: " + cause.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Result<Boolean> batchPrefetchFiles(List<String> urls, int batchSize, String area) {
|
||||||
|
log.warn("CDN批量预热文件失败,URLs: {}, batchSize: {}, area: {}", urls, batchSize, area, cause);
|
||||||
|
return Result.failed("CDN批量预热文件失败: " + cause.getMessage());
|
||||||
|
}
|
||||||
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,52 @@
|
|||||||
|
package com.central.order.mapper;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||||
|
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||||
|
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||||
|
import com.central.order.entity.Coupon;
|
||||||
|
import org.apache.ibatis.annotations.Mapper;
|
||||||
|
import org.apache.ibatis.annotations.Param;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 优惠券Mapper接口
|
||||||
|
*/
|
||||||
|
@Mapper
|
||||||
|
public interface CouponMapper extends BaseMapper<Coupon> {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 分页查询优惠券列表
|
||||||
|
*/
|
||||||
|
IPage<Coupon> selectCouponPage(Page<Coupon> page, @Param("coupon") Coupon coupon);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据手机号查询用户优惠券
|
||||||
|
*/
|
||||||
|
List<Coupon> selectByUserPhone(@Param("userPhone") String userPhone);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据手机号查询可用优惠券
|
||||||
|
*/
|
||||||
|
List<Coupon> selectAvailableByUserPhone(@Param("userPhone") String userPhone);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据携程优惠券ID查询
|
||||||
|
*/
|
||||||
|
Coupon selectByCtripCouponId(@Param("ctripCouponId") String ctripCouponId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据订单号查询使用的优惠券
|
||||||
|
*/
|
||||||
|
Coupon selectByUsedOrderNo(@Param("usedOrderNo") String usedOrderNo);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 更新优惠券状态为已使用
|
||||||
|
*/
|
||||||
|
int updateCouponUsed(@Param("id") Long id, @Param("usedOrderNo") String usedOrderNo);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 批量更新过期优惠券状态
|
||||||
|
*/
|
||||||
|
int updateExpiredCoupons();
|
||||||
|
}
|
||||||
+369
-55
@@ -1,91 +1,405 @@
|
|||||||
package com.central.order.mapper;
|
package com.central.order.mapper;
|
||||||
|
|
||||||
import com.central.order.model.vo.IncomeDataVO;
|
import com.central.order.model.vo.*;
|
||||||
import com.central.order.model.vo.TourismRankingVO;
|
|
||||||
import com.central.order.model.vo.TrendDataVO;
|
|
||||||
import org.apache.ibatis.annotations.Mapper;
|
import org.apache.ibatis.annotations.Mapper;
|
||||||
|
import org.apache.ibatis.annotations.Param;
|
||||||
import org.apache.ibatis.annotations.Select;
|
import org.apache.ibatis.annotations.Select;
|
||||||
|
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
@Mapper
|
@Mapper
|
||||||
public interface DashboardMapper {
|
public interface DashboardMapper {
|
||||||
|
|
||||||
@Select("SELECT COUNT(*) FROM orders WHERE is_del = 0")
|
// 基础订单统计(支持筛选)
|
||||||
Long getTotalOrders();
|
@Select({
|
||||||
|
"<script>",
|
||||||
@Select("SELECT COUNT(*) FROM orders WHERE is_del = 0 AND DATE(create_time) = CURDATE()")
|
"SELECT COUNT(*) FROM orders o",
|
||||||
Long getTodayOrders();
|
"JOIN qrcodes q ON o.code_id = q.code_id",
|
||||||
|
"WHERE o.is_del = 0",
|
||||||
@Select("SELECT COUNT(*) FROM orders WHERE is_del = 0 AND DATE(create_time) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)")
|
"<if test='p.includeTestQrcodes == null or p.includeTestQrcodes == false'>",
|
||||||
Long getYesterdayOrders();
|
" AND q.is_test = 0",
|
||||||
|
"</if>",
|
||||||
@Select("SELECT COUNT(*) FROM orders WHERE is_del = 0 AND order_status = #{completeStatus}")
|
"<if test='p.tourismId != null'>",
|
||||||
Long getCompletedOrders();
|
" AND o.tourism_id = #{p.tourismId}",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.qrcodeId != null and p.qrcodeId != \"\"'>",
|
||||||
|
" AND o.code_id = #{p.qrcodeId}",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
|
||||||
|
" AND o.device_sn = #{p.deviceSn}",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.startTime != null and p.startTime != \"\"'>",
|
||||||
|
" AND o.create_time >= #{p.startTime}",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.endTime != null and p.endTime != \"\"'>",
|
||||||
|
" AND o.create_time <= #{p.endTime}",
|
||||||
|
"</if>",
|
||||||
|
"</script>"
|
||||||
|
})
|
||||||
|
Long getTotalOrders(@Param("p") Map<String, Object> params);
|
||||||
|
|
||||||
@Select({
|
@Select({
|
||||||
"<script>",
|
"<script>",
|
||||||
"SELECT COALESCE(SUM(order_amount), 0)",
|
"SELECT COUNT(*) FROM orders o",
|
||||||
"FROM orders",
|
"JOIN qrcodes q ON o.code_id = q.code_id",
|
||||||
"WHERE is_del = 0",
|
"WHERE o.is_del = 0",
|
||||||
"AND order_status IN ${@com.central.order.constants.OrderStatusConstants@PAID_STATUS}",
|
"<if test='p.includeTestQrcodes == null or p.includeTestQrcodes == false'>",
|
||||||
|
" AND q.is_test = 0",
|
||||||
|
"</if>",
|
||||||
|
"AND DATE(o.create_time) = CURDATE()",
|
||||||
|
"<if test='p.tourismId != null'>",
|
||||||
|
" AND o.tourism_id = #{p.tourismId}",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.qrcodeId != null and p.qrcodeId != \"\"'>",
|
||||||
|
" AND o.code_id = #{p.qrcodeId}",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
|
||||||
|
" AND o.device_sn = #{p.deviceSn}",
|
||||||
|
"</if>",
|
||||||
"</script>"
|
"</script>"
|
||||||
})
|
})
|
||||||
Long getTotalIncome();
|
Long getTodayOrders(@Param("p") Map<String, Object> params);
|
||||||
|
|
||||||
@Select({
|
@Select({
|
||||||
"<script>",
|
"<script>",
|
||||||
"SELECT COALESCE(SUM(order_amount), 0)",
|
"SELECT COUNT(*) FROM orders o",
|
||||||
"FROM orders",
|
"JOIN qrcodes q ON o.code_id = q.code_id",
|
||||||
"WHERE is_del = 0",
|
"WHERE o.is_del = 0",
|
||||||
"AND order_status IN ${@com.central.order.constants.OrderStatusConstants@PAID_STATUS}",
|
"<if test='p.includeTestQrcodes == null or p.includeTestQrcodes == false'>",
|
||||||
"AND DATE(create_time) = CURDATE()",
|
" AND q.is_test = 0",
|
||||||
|
"</if>",
|
||||||
|
"AND DATE(o.create_time) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)",
|
||||||
|
"<if test='p.tourismId != null'>",
|
||||||
|
" AND o.tourism_id = #{p.tourismId}",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.qrcodeId != null and p.qrcodeId != \"\"'>",
|
||||||
|
" AND o.code_id = #{p.qrcodeId}",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
|
||||||
|
" AND o.device_sn = #{p.deviceSn}",
|
||||||
|
"</if>",
|
||||||
"</script>"
|
"</script>"
|
||||||
})
|
})
|
||||||
Long getTodayIncome();
|
Long getYesterdayOrders(@Param("p") Map<String, Object> params);
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
@Select({
|
@Select({
|
||||||
|
"<script>",
|
||||||
|
"SELECT COUNT(*) FROM orders o",
|
||||||
|
"JOIN qrcodes q ON o.code_id = q.code_id",
|
||||||
|
"WHERE o.is_del = 0",
|
||||||
|
"<if test='p.includeTestQrcodes == null or p.includeTestQrcodes == false'>",
|
||||||
|
" AND q.is_test = 0",
|
||||||
|
"</if>",
|
||||||
|
"AND o.order_status = 3",
|
||||||
|
"<if test='p.tourismId != null'>",
|
||||||
|
" AND o.tourism_id = #{p.tourismId}",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.qrcodeId != null and p.qrcodeId != \"\"'>",
|
||||||
|
" AND o.code_id = #{p.qrcodeId}",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
|
||||||
|
" AND o.device_sn = #{p.deviceSn}",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.startTime != null and p.startTime != \"\"'>",
|
||||||
|
" AND o.create_time >= #{p.startTime}",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.endTime != null and p.endTime != \"\"'>",
|
||||||
|
" AND o.create_time <= #{p.endTime}",
|
||||||
|
"</if>",
|
||||||
|
"</script>"
|
||||||
|
})
|
||||||
|
Long getCompletedOrders(@Param("p") Map<String, Object> params);
|
||||||
|
|
||||||
|
// 对账相关统计
|
||||||
|
@Select({
|
||||||
|
"<script>",
|
||||||
|
"SELECT COALESCE(SUM(o.order_amount), 0)",
|
||||||
|
"FROM orders o",
|
||||||
|
"JOIN qrcodes q ON o.code_id = q.code_id",
|
||||||
|
"WHERE o.is_del = 0",
|
||||||
|
"<if test='p.includeTestQrcodes == null or p.includeTestQrcodes == false'>",
|
||||||
|
" AND q.is_test = 0",
|
||||||
|
"</if>",
|
||||||
|
"AND (o.order_status = 3 OR o.order_status = 8)",
|
||||||
|
"<if test='p.tourismId != null'>",
|
||||||
|
" AND o.tourism_id = #{p.tourismId}",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.startTime != null and p.startTime != \"\"'>",
|
||||||
|
" AND o.create_time >= #{p.startTime}",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.endTime != null and p.endTime != \"\"'>",
|
||||||
|
" AND o.create_time <= #{p.endTime}",
|
||||||
|
"</if>",
|
||||||
|
"</script>"
|
||||||
|
})
|
||||||
|
Long getTotalAmount(@Param("p") Map<String, Object> params);
|
||||||
|
|
||||||
|
@Select({
|
||||||
|
"<script>",
|
||||||
|
"SELECT COALESCE(SUM(os.platform_amount), 0)",
|
||||||
|
"FROM order_statistics os",
|
||||||
|
"JOIN orders o ON os.order_id = o.id",
|
||||||
|
"JOIN qrcodes q ON o.code_id = q.code_id",
|
||||||
|
"WHERE 1=1",
|
||||||
|
"<if test='p.includeTestQrcodes == null or p.includeTestQrcodes == false'>",
|
||||||
|
" AND q.is_test = 0",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.tourismId != null'>",
|
||||||
|
" AND os.tourism_id = #{p.tourismId}",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.qrcodeId != null and p.qrcodeId != \"\"'>",
|
||||||
|
" AND os.qrcode_id = #{p.qrcodeId}",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
|
||||||
|
" AND os.device_sn = #{p.deviceSn}",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.startTime != null and p.startTime != \"\"'>",
|
||||||
|
" AND os.create_time >= #{p.startTime}",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.endTime != null and p.endTime != \"\"'>",
|
||||||
|
" AND os.create_time <= #{p.endTime}",
|
||||||
|
"</if>",
|
||||||
|
"</script>"
|
||||||
|
})
|
||||||
|
Long getPlatformAmount(@Param("p") Map<String, Object> params);
|
||||||
|
|
||||||
|
@Select({
|
||||||
|
"<script>",
|
||||||
|
"SELECT COALESCE(SUM(os.tourism_amount), 0)",
|
||||||
|
"FROM order_statistics os",
|
||||||
|
"JOIN orders o ON os.order_id = o.id",
|
||||||
|
"JOIN qrcodes q ON o.code_id = q.code_id",
|
||||||
|
"WHERE 1=1",
|
||||||
|
"<if test='p.includeTestQrcodes == null or p.includeTestQrcodes == false'>",
|
||||||
|
" AND q.is_test = 0",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.tourismId != null'>",
|
||||||
|
" AND os.tourism_id = #{p.tourismId}",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.qrcodeId != null and p.qrcodeId != \"\"'>",
|
||||||
|
" AND os.qrcode_id = #{p.qrcodeId}",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
|
||||||
|
" AND os.device_sn = #{p.deviceSn}",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.startTime != null and p.startTime != \"\"'>",
|
||||||
|
" AND os.create_time >= #{p.startTime}",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.endTime != null and p.endTime != \"\"'>",
|
||||||
|
" AND os.create_time <= #{p.endTime}",
|
||||||
|
"</if>",
|
||||||
|
"</script>"
|
||||||
|
})
|
||||||
|
Long getTourismAmount(@Param("p") Map<String, Object> params);
|
||||||
|
|
||||||
|
@Select({
|
||||||
|
"<script>",
|
||||||
|
"SELECT COALESCE(SUM(CAST(r.refund_amount AS SIGNED)), 0)",
|
||||||
|
"FROM orders_refund r",
|
||||||
|
"JOIN orders o ON r.order_no = o.order_no",
|
||||||
|
"JOIN qrcodes q ON o.code_id = q.code_id",
|
||||||
|
"WHERE r.status = 8",
|
||||||
|
"<if test='p.includeTestQrcodes == null or p.includeTestQrcodes == false'>",
|
||||||
|
" AND q.is_test = 0",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.tourismId != null'>",
|
||||||
|
" AND o.tourism_id = #{p.tourismId}",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.startTime != null and p.startTime != \"\"'>",
|
||||||
|
" AND r.create_time >= #{p.startTime}",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.endTime != null and p.endTime != \"\"'>",
|
||||||
|
" AND r.create_time <= #{p.endTime}",
|
||||||
|
"</if>",
|
||||||
|
"</script>"
|
||||||
|
})
|
||||||
|
Long getRefundAmount(@Param("p") Map<String, Object> params);
|
||||||
|
|
||||||
|
// 图表数据
|
||||||
|
@Select({
|
||||||
|
"<script>",
|
||||||
"SELECT",
|
"SELECT",
|
||||||
" DATE_FORMAT(create_time, '%Y-%m-%d') as date,",
|
" DATE_FORMAT(o.create_time, '%Y-%m-%d') as date,",
|
||||||
" 'orders' as type,",
|
" 'orders' as type,",
|
||||||
" COUNT(*) as value",
|
" COUNT(*) as value",
|
||||||
"FROM orders",
|
"FROM orders o",
|
||||||
"WHERE is_del = 0",
|
"JOIN qrcodes q ON o.code_id = q.code_id",
|
||||||
" AND create_time >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)",
|
"WHERE o.is_del = 0",
|
||||||
"GROUP BY DATE_FORMAT(create_time, '%Y-%m-%d')"
|
"<if test='p.includeTestQrcodes == null or p.includeTestQrcodes == false'>",
|
||||||
|
" AND q.is_test = 0",
|
||||||
|
"</if>",
|
||||||
|
" AND o.create_time >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)",
|
||||||
|
"<if test='p.tourismId != null'>",
|
||||||
|
" AND o.tourism_id = #{p.tourismId}",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.qrcodeId != null and p.qrcodeId != \"\"'>",
|
||||||
|
" AND o.code_id = #{p.qrcodeId}",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
|
||||||
|
" AND o.device_sn = #{p.deviceSn}",
|
||||||
|
"</if>",
|
||||||
|
"GROUP BY DATE_FORMAT(o.create_time, '%Y-%m-%d')",
|
||||||
|
"ORDER BY date",
|
||||||
|
"</script>"
|
||||||
})
|
})
|
||||||
List<TrendDataVO> getOrderTrend();
|
List<TrendDataVO> getOrderTrend(@Param("p") Map<String, Object> params);
|
||||||
|
|
||||||
@Select({
|
@Select({
|
||||||
|
"<script>",
|
||||||
"SELECT",
|
"SELECT",
|
||||||
" 'platform' as type,",
|
" CASE o.order_status",
|
||||||
" SUM(platform_amount) as value",
|
" WHEN 0 THEN '待支付'",
|
||||||
"FROM order_statistics",
|
" WHEN 1 THEN '已支付排队中'",
|
||||||
"WHERE DATE(create_time) = CURDATE()",
|
" WHEN 2 THEN '已取消'",
|
||||||
|
" WHEN 3 THEN '设备执行完成'",
|
||||||
|
" WHEN 4 THEN '正在服务中'",
|
||||||
|
" WHEN 5 THEN '素材上传中'",
|
||||||
|
" WHEN 6 THEN '素材上传完成'",
|
||||||
|
" WHEN 7 THEN '退款中'",
|
||||||
|
" WHEN 8 THEN '已退款'",
|
||||||
|
" WHEN 9 THEN '退款失败'",
|
||||||
|
" ELSE '其他'",
|
||||||
|
" END as type,",
|
||||||
|
" COUNT(*) as value",
|
||||||
|
"FROM orders o",
|
||||||
|
"JOIN qrcodes q ON o.code_id = q.code_id",
|
||||||
|
"WHERE o.is_del = 0",
|
||||||
|
"<if test='p.includeTestQrcodes == null or p.includeTestQrcodes == false'>",
|
||||||
|
" AND q.is_test = 0",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.tourismId != null'>",
|
||||||
|
" AND o.tourism_id = #{p.tourismId}",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.qrcodeId != null and p.qrcodeId != \"\"'>",
|
||||||
|
" AND o.code_id = #{p.qrcodeId}",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
|
||||||
|
" AND o.device_sn = #{p.deviceSn}",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.startTime != null and p.startTime != \"\"'>",
|
||||||
|
" AND o.create_time >= #{p.startTime}",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.endTime != null and p.endTime != \"\"'>",
|
||||||
|
" AND o.create_time <= #{p.endTime}",
|
||||||
|
"</if>",
|
||||||
|
"GROUP BY o.order_status",
|
||||||
|
"</script>"
|
||||||
|
})
|
||||||
|
List<DistributionDataVO> getOrderDistribution(@Param("p") Map<String, Object> params);
|
||||||
|
|
||||||
|
@Select({
|
||||||
|
"<script>",
|
||||||
|
"SELECT",
|
||||||
|
" '平台分账' as type,",
|
||||||
|
" COALESCE(SUM(os.platform_amount), 0) as value",
|
||||||
|
"FROM order_statistics os",
|
||||||
|
"JOIN orders o ON os.order_id = o.id",
|
||||||
|
"JOIN qrcodes q ON o.code_id = q.code_id",
|
||||||
|
"WHERE 1=1",
|
||||||
|
"<if test='p.includeTestQrcodes == null or p.includeTestQrcodes == false'>",
|
||||||
|
" AND q.is_test = 0",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.tourismId != null'>",
|
||||||
|
" AND os.tourism_id = #{p.tourismId}",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.qrcodeId != null and p.qrcodeId != \"\"'>",
|
||||||
|
" AND os.qrcode_id = #{p.qrcodeId}",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
|
||||||
|
" AND os.device_sn = #{p.deviceSn}",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.startTime != null and p.startTime != \"\"'>",
|
||||||
|
" AND os.create_time >= #{p.startTime}",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.endTime != null and p.endTime != \"\"'>",
|
||||||
|
" AND os.create_time <= #{p.endTime}",
|
||||||
|
"</if>",
|
||||||
"UNION ALL",
|
"UNION ALL",
|
||||||
"SELECT",
|
"SELECT",
|
||||||
" 'tourism' as type,",
|
" '景区分账' as type,",
|
||||||
" SUM(tourism_amount) as value",
|
" COALESCE(SUM(os.tourism_amount), 0) as value",
|
||||||
"FROM order_statistics",
|
"FROM order_statistics os",
|
||||||
"WHERE DATE(create_time) = CURDATE()"
|
"JOIN orders o ON os.order_id = o.id",
|
||||||
|
"JOIN qrcodes q ON o.code_id = q.code_id",
|
||||||
|
"WHERE 1=1",
|
||||||
|
"<if test='p.includeTestQrcodes == null or p.includeTestQrcodes == false'>",
|
||||||
|
" AND q.is_test = 0",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.tourismId != null'>",
|
||||||
|
" AND os.tourism_id = #{p.tourismId}",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.qrcodeId != null and p.qrcodeId != \"\"'>",
|
||||||
|
" AND os.qrcode_id = #{p.qrcodeId}",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
|
||||||
|
" AND os.device_sn = #{p.deviceSn}",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.startTime != null and p.startTime != \"\"'>",
|
||||||
|
" AND os.create_time >= #{p.startTime}",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.endTime != null and p.endTime != \"\"'>",
|
||||||
|
" AND os.create_time <= #{p.endTime}",
|
||||||
|
"</if>",
|
||||||
|
"UNION ALL",
|
||||||
|
"SELECT",
|
||||||
|
" '退款金额' as type,",
|
||||||
|
" COALESCE(SUM(os.refund_amount), 0) as value",
|
||||||
|
"FROM order_statistics os",
|
||||||
|
"JOIN orders o ON os.order_id = o.id",
|
||||||
|
"JOIN qrcodes q ON o.code_id = q.code_id",
|
||||||
|
"WHERE 1=1",
|
||||||
|
"<if test='p.includeTestQrcodes == null or p.includeTestQrcodes == false'>",
|
||||||
|
" AND q.is_test = 0",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.tourismId != null'>",
|
||||||
|
" AND os.tourism_id = #{p.tourismId}",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.qrcodeId != null and p.qrcodeId != \"\"'>",
|
||||||
|
" AND os.qrcode_id = #{p.qrcodeId}",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.deviceSn != null and p.deviceSn != \"\"'>",
|
||||||
|
" AND os.device_sn = #{p.deviceSn}",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.startTime != null and p.startTime != \"\"'>",
|
||||||
|
" AND os.create_time >= #{p.startTime}",
|
||||||
|
"</if>",
|
||||||
|
"<if test='p.endTime != null and p.endTime != \"\"'>",
|
||||||
|
" AND os.create_time <= #{p.endTime}",
|
||||||
|
"</if>",
|
||||||
|
"</script>"
|
||||||
})
|
})
|
||||||
List<IncomeDataVO> getIncomeData();
|
List<IncomeDataVO> getIncomeBreakdown(@Param("p") Map<String, Object> params);
|
||||||
|
|
||||||
|
// 筛选选项
|
||||||
|
@Select("SELECT id as value, tourism_name as label FROM tourisms WHERE is_del = 0 ORDER BY create_time DESC")
|
||||||
|
List<FilterOptions.OptionItem> getTourismOptions();
|
||||||
|
|
||||||
@Select({
|
@Select({
|
||||||
"SELECT",
|
"<script>",
|
||||||
" t.id,",
|
"SELECT code_id as value, name as label FROM qrcodes",
|
||||||
" t.tourism_name as name,",
|
"WHERE is_del = 0",
|
||||||
" COUNT(o.id) as value",
|
"<if test='p.includeTestQrcodes == null or p.includeTestQrcodes == false'>",
|
||||||
"FROM tourisms t",
|
" AND is_test = 0",
|
||||||
"LEFT JOIN orders o ON t.id = o.tourism_id",
|
"</if>",
|
||||||
"WHERE t.is_del = 0",
|
"<if test='p.tourismId != null'>",
|
||||||
" AND o.is_del = 0",
|
" AND tourism_id = #{p.tourismId}",
|
||||||
" AND o.create_time >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)",
|
"</if>",
|
||||||
"GROUP BY t.id, t.tourism_name",
|
"ORDER BY create_time DESC",
|
||||||
"ORDER BY value DESC",
|
"</script>"
|
||||||
"LIMIT 10"
|
|
||||||
})
|
})
|
||||||
List<TourismRankingVO> getTourismRanking();
|
List<FilterOptions.OptionItem> getQrcodeOptions(@Param("p") Map<String, Object> params);
|
||||||
|
|
||||||
|
@Select({
|
||||||
|
"<script>",
|
||||||
|
"SELECT DISTINCT device_sn as value, device_sn as label FROM qrcodes",
|
||||||
|
"WHERE is_del = 0",
|
||||||
|
"<if test='p.includeTestQrcodes == null or p.includeTestQrcodes == false'>",
|
||||||
|
" AND is_test = 0",
|
||||||
|
"</if>",
|
||||||
|
"AND device_sn IS NOT NULL",
|
||||||
|
"ORDER BY device_sn",
|
||||||
|
"</script>"
|
||||||
|
})
|
||||||
|
List<FilterOptions.OptionItem> getDeviceOptions(@Param("p") Map<String, Object> params);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -3,9 +3,11 @@ package com.central.order.mapper;
|
|||||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||||
import com.central.db.mapper.SuperMapper;
|
import com.central.db.mapper.SuperMapper;
|
||||||
import com.central.order.model.Tourism;
|
import com.central.order.model.Tourism;
|
||||||
|
import com.central.order.model.TourismWithDistance;
|
||||||
import org.apache.ibatis.annotations.Mapper;
|
import org.apache.ibatis.annotations.Mapper;
|
||||||
import org.apache.ibatis.annotations.Param;
|
import org.apache.ibatis.annotations.Param;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
@@ -32,4 +34,42 @@ public interface TourismMapper extends SuperMapper<Tourism> {
|
|||||||
// ID查询
|
// ID查询
|
||||||
Tourism getTourismById(@Param("id") Long id);
|
Tourism getTourismById(@Param("id") Long id);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取景区设备列表
|
||||||
|
* 通过景区下的二维码信息查询二维码绑定的设备
|
||||||
|
* @param tourismId 景区ID
|
||||||
|
* @return 设备列表
|
||||||
|
*/
|
||||||
|
List<Map<String, Object>> getDevicesByTourismId(@Param("tourismId") Long tourismId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询附近景区列表
|
||||||
|
* @param longitude 经度
|
||||||
|
* @param latitude 纬度
|
||||||
|
* @param radius 搜索半径(公里)
|
||||||
|
* @param limit 返回数量限制
|
||||||
|
* @return 附近景区列表(包含距离信息)
|
||||||
|
*/
|
||||||
|
List<TourismWithDistance> findNearbyTourisms(
|
||||||
|
@Param("longitude") BigDecimal longitude,
|
||||||
|
@Param("latitude") BigDecimal latitude,
|
||||||
|
@Param("radius") Double radius,
|
||||||
|
@Param("limit") Integer limit
|
||||||
|
);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据经纬度范围查询景区
|
||||||
|
* @param minLongitude 最小经度
|
||||||
|
* @param maxLongitude 最大经度
|
||||||
|
* @param minLatitude 最小纬度
|
||||||
|
* @param maxLatitude 最大纬度
|
||||||
|
* @return 景区列表
|
||||||
|
*/
|
||||||
|
List<Tourism> findTourismsByBounds(
|
||||||
|
@Param("minLongitude") BigDecimal minLongitude,
|
||||||
|
@Param("maxLongitude") BigDecimal maxLongitude,
|
||||||
|
@Param("minLatitude") BigDecimal minLatitude,
|
||||||
|
@Param("maxLatitude") BigDecimal maxLatitude
|
||||||
|
);
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
+119
@@ -0,0 +1,119 @@
|
|||||||
|
package com.central.order.model;
|
||||||
|
|
||||||
|
import lombok.Data;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 携程创建订单请求
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public class CtripCreateOrderRequest {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 请求头
|
||||||
|
*/
|
||||||
|
private CtripHeader header;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 请求体
|
||||||
|
*/
|
||||||
|
private CtripOrderBody body;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 携程请求头
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public static class CtripHeader {
|
||||||
|
private String requestTime;
|
||||||
|
private String accountId;
|
||||||
|
private String sign;
|
||||||
|
private String serviceName;
|
||||||
|
private String version;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 携程订单体
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public static class CtripOrderBody {
|
||||||
|
private String otaOrderId;
|
||||||
|
private String sequenceId;
|
||||||
|
private List<CtripOrderItem> items;
|
||||||
|
private List<CtripContact> contacts;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 携程订单项
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public static class CtripOrderItem {
|
||||||
|
private List<CtripPassenger> passengers;
|
||||||
|
private java.math.BigDecimal cost;
|
||||||
|
private Integer quantity;
|
||||||
|
private java.math.BigDecimal salePrice;
|
||||||
|
private String remark;
|
||||||
|
private String useEndDate;
|
||||||
|
private String locale;
|
||||||
|
private String useStartDate;
|
||||||
|
private String priceCurrency;
|
||||||
|
private List<Object> adjunctions;
|
||||||
|
private java.math.BigDecimal price;
|
||||||
|
private String PLU;
|
||||||
|
private Object deposit;
|
||||||
|
private String distributionChannel;
|
||||||
|
private String costCurrency;
|
||||||
|
private String salePriceCurrency;
|
||||||
|
private CtripExpressDelivery expressDelivery;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 携程乘客信息
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public static class CtripPassenger {
|
||||||
|
private String cardIssuePlace;
|
||||||
|
private String lastName;
|
||||||
|
private String cardIssueCountry;
|
||||||
|
private Integer shoeSize;
|
||||||
|
private String gender;
|
||||||
|
private String cardIssueDate;
|
||||||
|
private String intlCode;
|
||||||
|
private String nationalityName;
|
||||||
|
private String mobile;
|
||||||
|
private String cardType;
|
||||||
|
private Integer weight;
|
||||||
|
private Integer myopiaDegreeL;
|
||||||
|
private String birthDate;
|
||||||
|
private String cardNo;
|
||||||
|
private String ageType;
|
||||||
|
private Integer myopiaDegreeR;
|
||||||
|
private String firstName;
|
||||||
|
private String birthPlace;
|
||||||
|
private String nationalityCode;
|
||||||
|
private String name;
|
||||||
|
private String passengerId;
|
||||||
|
private String cardValidDate;
|
||||||
|
private Integer height;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 携程联系人信息
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public static class CtripContact {
|
||||||
|
private String intlCode;
|
||||||
|
private String name;
|
||||||
|
private String mobile;
|
||||||
|
private String optionalMobile;
|
||||||
|
private String optionalIntlCode;
|
||||||
|
private String email;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 携程快递信息
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
public static class CtripExpressDelivery {
|
||||||
|
private String type;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -53,6 +53,7 @@ public class Order extends SuperEntity {
|
|||||||
|
|
||||||
private transient String waylineLinkUrl;
|
private transient String waylineLinkUrl;
|
||||||
private transient JSONObject streamUrls;
|
private transient JSONObject streamUrls;
|
||||||
|
private transient String tourismImgUrl;
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -46,4 +46,8 @@ public class OrderFile extends SuperEntity {
|
|||||||
private String tenantId;
|
private String tenantId;
|
||||||
private Integer isDel;
|
private Integer isDel;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 文件标签,如ai_video、raw_video等
|
||||||
|
*/
|
||||||
|
private String fileTag;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -99,4 +99,10 @@ public class QrCode extends SuperEntity {
|
|||||||
@Schema(description = "素材数量")
|
@Schema(description = "素材数量")
|
||||||
private Integer materialCount;
|
private Integer materialCount;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 是否为测试二维码(0:否,1:是)
|
||||||
|
*/
|
||||||
|
@Schema(description = "是否为测试二维码")
|
||||||
|
private Integer isTest;
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -8,10 +8,11 @@ import lombok.EqualsAndHashCode;
|
|||||||
import lombok.Getter;
|
import lombok.Getter;
|
||||||
import lombok.Setter;
|
import lombok.Setter;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
import java.util.Date;
|
import java.util.Date;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Device information
|
* 景区信息实体类
|
||||||
*
|
*
|
||||||
* @author lsl
|
* @author lsl
|
||||||
* @date 2024-12-19 17:51:47
|
* @date 2024-12-19 17:51:47
|
||||||
@@ -34,6 +35,16 @@ public class Tourism extends SuperEntity {
|
|||||||
private String tourismPhone;
|
private String tourismPhone;
|
||||||
private String tourismEmail;
|
private String tourismEmail;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 景区经度
|
||||||
|
*/
|
||||||
|
private BigDecimal longitude;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 景区纬度
|
||||||
|
*/
|
||||||
|
private BigDecimal latitude;
|
||||||
|
|
||||||
@TableField(fill = FieldFill.INSERT)
|
@TableField(fill = FieldFill.INSERT)
|
||||||
private Date createTime;
|
private Date createTime;
|
||||||
@TableField(fill = FieldFill.INSERT_UPDATE)
|
@TableField(fill = FieldFill.INSERT_UPDATE)
|
||||||
|
|||||||
+65
@@ -0,0 +1,65 @@
|
|||||||
|
package com.central.order.model;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.annotation.TableField;
|
||||||
|
import lombok.Data;
|
||||||
|
import lombok.EqualsAndHashCode;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 景区信息实体类(包含距离信息)
|
||||||
|
* 用于查询附近景区时返回距离信息
|
||||||
|
*
|
||||||
|
* @author lsl
|
||||||
|
* @date 2024-12-19 17:51:47
|
||||||
|
*/
|
||||||
|
@Data
|
||||||
|
@EqualsAndHashCode(callSuper = true)
|
||||||
|
public class TourismWithDistance extends Tourism {
|
||||||
|
|
||||||
|
private static final long serialVersionUID = 1L;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 距离(公里)
|
||||||
|
*/
|
||||||
|
private BigDecimal distance;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 距离描述(如:1.2km)
|
||||||
|
*/
|
||||||
|
@TableField(exist = false)
|
||||||
|
private String distanceDesc;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 景区订单展示图片URL
|
||||||
|
*/
|
||||||
|
@TableField(exist = false)
|
||||||
|
private String orderShowImageUrl;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取距离描述
|
||||||
|
* @return 距离描述字符串
|
||||||
|
*/
|
||||||
|
public String getDistanceDesc() {
|
||||||
|
if (distance == null) {
|
||||||
|
return "未知距离";
|
||||||
|
}
|
||||||
|
|
||||||
|
if (distance.compareTo(BigDecimal.ONE) < 0) {
|
||||||
|
// 小于1公里,显示为米
|
||||||
|
int meters = distance.multiply(new BigDecimal("1000")).intValue();
|
||||||
|
return meters + "m";
|
||||||
|
} else {
|
||||||
|
// 大于等于1公里,显示为公里
|
||||||
|
return distance.setScale(1, BigDecimal.ROUND_HALF_UP) + "km";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 设置距离描述
|
||||||
|
* @param distanceDesc 距离描述
|
||||||
|
*/
|
||||||
|
public void setDistanceDesc(String distanceDesc) {
|
||||||
|
this.distanceDesc = distanceDesc;
|
||||||
|
}
|
||||||
|
}
|
||||||
+4
-4
@@ -6,14 +6,14 @@ import lombok.Data;
|
|||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
|
||||||
@Data
|
@Data
|
||||||
@Schema(description = "图表统计数据")
|
@Schema(description = "图表统计")
|
||||||
public class ChartStatistics {
|
public class ChartStatistics {
|
||||||
@Schema(description = "订单趋势")
|
@Schema(description = "订单趋势")
|
||||||
private List<TrendDataVO> orderTrend;
|
private List<TrendDataVO> orderTrend;
|
||||||
|
|
||||||
@Schema(description = "设备分布")
|
@Schema(description = "订单状态分布")
|
||||||
private List<DistributionDataVO> deviceDistribution;
|
private List<DistributionDataVO> orderDistribution;
|
||||||
|
|
||||||
@Schema(description = "收入构成")
|
@Schema(description = "收入构成")
|
||||||
private List<IncomeDataVO> incomeData;
|
private List<IncomeDataVO> incomeBreakdown;
|
||||||
}
|
}
|
||||||
+2
-11
@@ -11,18 +11,9 @@ public class DashboardStatisticsVO {
|
|||||||
@Schema(description = "订单统计")
|
@Schema(description = "订单统计")
|
||||||
private OrderStatistics orderStats;
|
private OrderStatistics orderStats;
|
||||||
|
|
||||||
@Schema(description = "收入统计")
|
|
||||||
private IncomeStatistics incomeStats;
|
|
||||||
|
|
||||||
@Schema(description = "航线统计")
|
|
||||||
private WaylineStatistics waylineStats;
|
|
||||||
|
|
||||||
@Schema(description = "设备统计")
|
|
||||||
private DeviceStatistics deviceStats;
|
|
||||||
|
|
||||||
@Schema(description = "图表统计")
|
@Schema(description = "图表统计")
|
||||||
private ChartStatistics chartStats;
|
private ChartStatistics chartStats;
|
||||||
|
|
||||||
@Schema(description = "景区排行")
|
@Schema(description = "筛选选项")
|
||||||
private List<TourismRankingVO> tourismRanking;
|
private FilterOptions filterOptions;
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
package com.central.order.model.vo;
|
||||||
|
|
||||||
|
import io.swagger.v3.oas.annotations.media.Schema;
|
||||||
|
import lombok.Data;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Schema(description = "筛选选项")
|
||||||
|
public class FilterOptions {
|
||||||
|
@Schema(description = "景区列表")
|
||||||
|
private List<OptionItem> tourismList;
|
||||||
|
|
||||||
|
@Schema(description = "二维码列表")
|
||||||
|
private List<OptionItem> qrcodeList;
|
||||||
|
|
||||||
|
@Schema(description = "设备列表")
|
||||||
|
private List<OptionItem> deviceList;
|
||||||
|
|
||||||
|
@Data
|
||||||
|
@Schema(description = "选项项")
|
||||||
|
public static class OptionItem {
|
||||||
|
@Schema(description = "标签")
|
||||||
|
private String label;
|
||||||
|
|
||||||
|
@Schema(description = "值")
|
||||||
|
private Object value;
|
||||||
|
}
|
||||||
|
}
|
||||||
+18
-3
@@ -6,9 +6,9 @@ import lombok.Data;
|
|||||||
import java.math.BigDecimal;
|
import java.math.BigDecimal;
|
||||||
|
|
||||||
@Data
|
@Data
|
||||||
@Schema(description = "订单统计数据")
|
@Schema(description = "订单统计")
|
||||||
public class OrderStatistics {
|
public class OrderStatistics {
|
||||||
@Schema(description = "订单总数")
|
@Schema(description = "总订单数")
|
||||||
private Long totalOrders;
|
private Long totalOrders;
|
||||||
|
|
||||||
@Schema(description = "今日订单数")
|
@Schema(description = "今日订单数")
|
||||||
@@ -17,6 +17,21 @@ public class OrderStatistics {
|
|||||||
@Schema(description = "订单增长率")
|
@Schema(description = "订单增长率")
|
||||||
private BigDecimal orderGrowth;
|
private BigDecimal orderGrowth;
|
||||||
|
|
||||||
@Schema(description = "订单完成率")
|
@Schema(description = "完成率")
|
||||||
private BigDecimal completionRate;
|
private BigDecimal completionRate;
|
||||||
|
|
||||||
|
@Schema(description = "订单总金额(分)")
|
||||||
|
private Long totalAmount;
|
||||||
|
|
||||||
|
@Schema(description = "平台分账金额(分)")
|
||||||
|
private Long platformAmount;
|
||||||
|
|
||||||
|
@Schema(description = "景区分账金额(分)")
|
||||||
|
private Long tourismAmount;
|
||||||
|
|
||||||
|
@Schema(description = "退款金额(分)")
|
||||||
|
private Long refundAmount;
|
||||||
|
|
||||||
|
@Schema(description = "净收入(分)")
|
||||||
|
private Long netIncome;
|
||||||
}
|
}
|
||||||
+13
-8
@@ -1,12 +1,15 @@
|
|||||||
package com.central.order.scheduler;
|
package com.central.order.scheduler;
|
||||||
|
|
||||||
|
import com.central.common.context.TenantContextHolder;
|
||||||
import com.central.order.service.IOrderService;
|
import com.central.order.service.IOrderService;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.context.annotation.Configuration;
|
import org.springframework.context.annotation.Configuration;
|
||||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||||
import org.springframework.scheduling.annotation.Scheduled;
|
import org.springframework.scheduling.annotation.Scheduled;
|
||||||
import org.springframework.stereotype.Component;
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
@Slf4j
|
||||||
@Component
|
@Component
|
||||||
@Configuration
|
@Configuration
|
||||||
@EnableScheduling
|
@EnableScheduling
|
||||||
@@ -18,14 +21,16 @@ public class OrderScheduler {
|
|||||||
// 每隔一定时间(这里设置为每分钟检查一次,可根据实际情况调整)检查订单超时情况
|
// 每隔一定时间(这里设置为每分钟检查一次,可根据实际情况调整)检查订单超时情况
|
||||||
@Scheduled(fixedRate = 60 * 1000)
|
@Scheduled(fixedRate = 60 * 1000)
|
||||||
public void checkOrderTimeout() {
|
public void checkOrderTimeout() {
|
||||||
orderService.checkAndHandleOrderTimeout();
|
log.debug("开始执行订单超时检查任务");
|
||||||
|
try {
|
||||||
|
TenantContextHolder.setTenant("webApp");
|
||||||
|
orderService.checkAndHandleOrderTimeout();
|
||||||
|
log.debug("订单超时检查任务执行完成");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("订单超时检查任务执行失败", e);
|
||||||
|
} finally {
|
||||||
|
TenantContextHolder.clear();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 每隔一定时间(这里设置为每分钟检查一次,可根据实际情况调整)检查是否存在未服务完成的订单
|
|
||||||
// @Scheduled(fixedRate = 60 * 1000)
|
|
||||||
public void processOrdersInQueue() {
|
|
||||||
orderService.processOrdersInQueue();
|
|
||||||
}
|
|
||||||
@Scheduled(fixedRate = 2 * 60 * 1000)
|
|
||||||
public void processOrdersCompleted() {}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,80 @@
|
|||||||
|
package com.central.order.service;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||||
|
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||||
|
import com.baomidou.mybatisplus.extension.service.IService;
|
||||||
|
import com.central.order.entity.Coupon;
|
||||||
|
import com.central.common.model.PageResult;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 优惠券服务接口
|
||||||
|
*/
|
||||||
|
public interface ICouponService extends IService<Coupon> {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 分页查询优惠券列表
|
||||||
|
*/
|
||||||
|
IPage<Coupon> getCouponPage(Page<Coupon> page, Coupon coupon);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询优惠券列表(统一风格)
|
||||||
|
*/
|
||||||
|
PageResult<Coupon> findList(Map<String, Object> params);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建优惠券
|
||||||
|
*/
|
||||||
|
boolean createCoupon(Coupon coupon);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 更新优惠券
|
||||||
|
*/
|
||||||
|
boolean updateCoupon(Coupon coupon);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 删除优惠券
|
||||||
|
*/
|
||||||
|
boolean deleteCoupon(Long id);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据手机号查询用户优惠券
|
||||||
|
*/
|
||||||
|
List<Coupon> getCouponsByUserPhone(String userPhone);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据手机号查询可用优惠券
|
||||||
|
*/
|
||||||
|
List<Coupon> getAvailableCouponsByUserPhone(String userPhone);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 使用优惠券
|
||||||
|
*/
|
||||||
|
boolean useCoupon(Long couponId, String orderNo);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据携程优惠券ID创建优惠券(携程接口调用)
|
||||||
|
*/
|
||||||
|
boolean createCouponFromCtrip(String ctripCouponId, String userPhone, String couponName,
|
||||||
|
Integer couponType, java.math.BigDecimal amount,
|
||||||
|
java.math.BigDecimal minAmount, Integer discountRate,
|
||||||
|
java.util.Date validStartTime,
|
||||||
|
java.util.Date validEndTime);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 批量更新过期优惠券状态
|
||||||
|
*/
|
||||||
|
void updateExpiredCoupons();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 核销携程优惠券
|
||||||
|
*/
|
||||||
|
boolean verifyCtripCoupon(String ctripCouponId, String orderNo);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 校验手机号+携程券ID是否已存在
|
||||||
|
*/
|
||||||
|
boolean existsByUserPhoneAndCtripCouponId(String userPhone, String ctripCouponId);
|
||||||
|
}
|
||||||
+22
@@ -0,0 +1,22 @@
|
|||||||
|
package com.central.order.service;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 携程API服务接口
|
||||||
|
*/
|
||||||
|
public interface ICtripApiService {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 核销携程优惠券
|
||||||
|
* @param ctripCouponId 携程优惠券ID
|
||||||
|
* @param orderNo 订单号
|
||||||
|
* @return 是否核销成功
|
||||||
|
*/
|
||||||
|
boolean verifyCoupon(String ctripCouponId, String orderNo);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询携程优惠券状态
|
||||||
|
* @param ctripCouponId 携程优惠券ID
|
||||||
|
* @return 优惠券状态
|
||||||
|
*/
|
||||||
|
String getCouponStatus(String ctripCouponId);
|
||||||
|
}
|
||||||
+4
-1
@@ -2,9 +2,12 @@ package com.central.order.service;
|
|||||||
|
|
||||||
import com.central.order.model.vo.DashboardStatisticsVO;
|
import com.central.order.model.vo.DashboardStatisticsVO;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
public interface IDashboardService {
|
public interface IDashboardService {
|
||||||
/**
|
/**
|
||||||
* 获取首页统计数据
|
* 获取首页统计数据
|
||||||
|
* @param params 筛选参数
|
||||||
*/
|
*/
|
||||||
DashboardStatisticsVO getDashboardStatistics();
|
DashboardStatisticsVO getDashboardStatistics(Map<String, Object> params);
|
||||||
}
|
}
|
||||||
|
|||||||
+4
-2
@@ -38,6 +38,7 @@ public interface IOrderStatisticsService extends ISuperService<OrderStatistics>
|
|||||||
* 按景区维度统计
|
* 按景区维度统计
|
||||||
* @param startTime 开始时间
|
* @param startTime 开始时间
|
||||||
* @param endTime 结束时间
|
* @param endTime 结束时间
|
||||||
|
* @param tourismId 景区ID筛选(可选)
|
||||||
* @return 统计数据列表,包含:
|
* @return 统计数据列表,包含:
|
||||||
* - tourismId: 景区ID
|
* - tourismId: 景区ID
|
||||||
* - tourismName: 景区名称
|
* - tourismName: 景区名称
|
||||||
@@ -48,17 +49,18 @@ public interface IOrderStatisticsService extends ISuperService<OrderStatistics>
|
|||||||
* - paidAmountYuan: 已支付金额(元)
|
* - paidAmountYuan: 已支付金额(元)
|
||||||
* - refundAmountYuan: 退款金额(元)
|
* - refundAmountYuan: 退款金额(元)
|
||||||
*/
|
*/
|
||||||
List<Map<String, Object>> statisticsByTourism(String startTime, String endTime);
|
List<Map<String, Object>> statisticsByTourism(String startTime, String endTime, String tourismId);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 按设备维度统计
|
* 按设备维度统计
|
||||||
* @param startTime 开始时间
|
* @param startTime 开始时间
|
||||||
* @param endTime 结束时间
|
* @param endTime 结束时间
|
||||||
|
* @param deviceSn 设备编号筛选(可选)
|
||||||
* @return 统计数据列表,包含:
|
* @return 统计数据列表,包含:
|
||||||
* - deviceSn: 设备编号
|
* - deviceSn: 设备编号
|
||||||
* - totalOrders: 订单总数
|
* - totalOrders: 订单总数
|
||||||
* - totalAmountYuan: 总金额(元)
|
* - totalAmountYuan: 总金额(元)
|
||||||
* - usageRate: 设备使用率
|
* - usageRate: 设备使用率
|
||||||
*/
|
*/
|
||||||
List<Map<String, Object>> statisticsByDevice(String startTime, String endTime);
|
List<Map<String, Object>> statisticsByDevice(String startTime, String endTime, String deviceSn);
|
||||||
}
|
}
|
||||||
|
|||||||
+42
-1
@@ -4,11 +4,14 @@ import com.central.common.model.PageResult;
|
|||||||
import com.central.common.model.Result;
|
import com.central.common.model.Result;
|
||||||
import com.central.common.service.ISuperService;
|
import com.central.common.service.ISuperService;
|
||||||
import com.central.order.model.Tourism;
|
import com.central.order.model.Tourism;
|
||||||
|
import com.central.order.model.TourismWithDistance;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Firmware file information
|
* 景区信息服务接口
|
||||||
*
|
*
|
||||||
* @author lsl
|
* @author lsl
|
||||||
* @date 2024-12-19 17:52:54
|
* @date 2024-12-19 17:52:54
|
||||||
@@ -35,5 +38,43 @@ public interface ITourismService extends ISuperService<Tourism> {
|
|||||||
* @return
|
* @return
|
||||||
*/
|
*/
|
||||||
Tourism getTourismById(Long id);
|
Tourism getTourismById(Long id);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取景区设备列表
|
||||||
|
* 通过景区下的二维码信息查询二维码绑定的设备
|
||||||
|
* @param tourismId 景区ID
|
||||||
|
* @return 设备列表
|
||||||
|
*/
|
||||||
|
java.util.List<java.util.Map<String, Object>> getDevicesByTourismId(Long tourismId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 查询附近景区列表
|
||||||
|
* @param longitude 经度
|
||||||
|
* @param latitude 纬度
|
||||||
|
* @param radius 搜索半径(公里)
|
||||||
|
* @param limit 返回数量限制
|
||||||
|
* @return 附近景区列表(包含距离信息)
|
||||||
|
*/
|
||||||
|
List<TourismWithDistance> findNearbyTourisms(BigDecimal longitude, BigDecimal latitude, Double radius, Integer limit);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 根据经纬度范围查询景区
|
||||||
|
* @param minLongitude 最小经度
|
||||||
|
* @param maxLongitude 最大经度
|
||||||
|
* @param minLatitude 最小纬度
|
||||||
|
* @param maxLatitude 最大纬度
|
||||||
|
* @return 景区列表
|
||||||
|
*/
|
||||||
|
List<Tourism> findTourismsByBounds(BigDecimal minLongitude, BigDecimal maxLongitude,
|
||||||
|
BigDecimal minLatitude, BigDecimal maxLatitude);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 更新景区经纬度信息
|
||||||
|
* @param id 景区ID
|
||||||
|
* @param longitude 经度
|
||||||
|
* @param latitude 纬度
|
||||||
|
* @return 更新结果
|
||||||
|
*/
|
||||||
|
Result updateTourismLocation(Long id, BigDecimal longitude, BigDecimal latitude);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+6
-2
@@ -1,3 +1,4 @@
|
|||||||
|
/*
|
||||||
package com.central.order.service;
|
package com.central.order.service;
|
||||||
|
|
||||||
import com.central.common.context.LoginUserContextHolder;
|
import com.central.common.context.LoginUserContextHolder;
|
||||||
@@ -88,7 +89,8 @@ public class PaymentService {
|
|||||||
request.setPayer(payer);
|
request.setPayer(payer);
|
||||||
|
|
||||||
// 设置分账信息(暂时注释掉分账逻辑)
|
// 设置分账信息(暂时注释掉分账逻辑)
|
||||||
/*
|
*/
|
||||||
|
/*
|
||||||
SettleInfo settleInfo = new SettleInfo();
|
SettleInfo settleInfo = new SettleInfo();
|
||||||
if (isEnableProfit(qrCode)) {
|
if (isEnableProfit(qrCode)) {
|
||||||
settleInfo.setProfitSharing(true);
|
settleInfo.setProfitSharing(true);
|
||||||
@@ -99,7 +101,8 @@ public class PaymentService {
|
|||||||
settleInfo.setProfitSharing(false);
|
settleInfo.setProfitSharing(false);
|
||||||
request.setSettleInfo(settleInfo);
|
request.setSettleInfo(settleInfo);
|
||||||
}
|
}
|
||||||
*/
|
*//*
|
||||||
|
|
||||||
|
|
||||||
// 6. 创建对应的支付服务
|
// 6. 创建对应的支付服务
|
||||||
JsapiServiceExtension jsapiService;
|
JsapiServiceExtension jsapiService;
|
||||||
@@ -125,3 +128,4 @@ public class PaymentService {
|
|||||||
qrCode.getProfitRate() != null;
|
qrCode.getProfitRate() != null;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
*/
|
||||||
|
|||||||
+233
@@ -0,0 +1,233 @@
|
|||||||
|
package com.central.order.service.impl;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||||
|
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||||
|
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||||
|
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||||
|
import com.central.order.entity.Coupon;
|
||||||
|
import com.central.order.mapper.CouponMapper;
|
||||||
|
import com.central.order.service.ICouponService;
|
||||||
|
import com.central.order.service.ICtripApiService;
|
||||||
|
import com.central.common.model.PageResult;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
|
import org.springframework.util.StringUtils;
|
||||||
|
|
||||||
|
import java.util.Date;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
import java.util.UUID;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 优惠券服务实现类
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Service
|
||||||
|
public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> implements ICouponService {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private ICtripApiService ctripApiService;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public IPage<Coupon> getCouponPage(Page<Coupon> page, Coupon coupon) {
|
||||||
|
return baseMapper.selectCouponPage(page, coupon);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public PageResult<Coupon> findList(Map<String, Object> params) {
|
||||||
|
// 获取分页参数
|
||||||
|
Integer page = Integer.parseInt(params.getOrDefault("page", "1").toString());
|
||||||
|
Integer limit = Integer.parseInt(params.getOrDefault("limit", "10").toString());
|
||||||
|
|
||||||
|
// 构建查询条件
|
||||||
|
Coupon queryCoupon = new Coupon();
|
||||||
|
if (params.get("couponName") != null) {
|
||||||
|
queryCoupon.setCouponName(params.get("couponName").toString());
|
||||||
|
}
|
||||||
|
if (params.get("couponType") != null) {
|
||||||
|
queryCoupon.setCouponType(Integer.parseInt(params.get("couponType").toString()));
|
||||||
|
}
|
||||||
|
if (params.get("status") != null) {
|
||||||
|
queryCoupon.setStatus(Integer.parseInt(params.get("status").toString()));
|
||||||
|
}
|
||||||
|
if (params.get("userPhone") != null) {
|
||||||
|
queryCoupon.setUserPhone(params.get("userPhone").toString());
|
||||||
|
}
|
||||||
|
if (params.get("source") != null) {
|
||||||
|
queryCoupon.setSource(Integer.parseInt(params.get("source").toString()));
|
||||||
|
}
|
||||||
|
if (params.get("ctripCouponId") != null) {
|
||||||
|
queryCoupon.setCtripCouponId(params.get("ctripCouponId").toString());
|
||||||
|
}
|
||||||
|
|
||||||
|
// 执行分页查询
|
||||||
|
Page<Coupon> pageParam = new Page<>(page, limit);
|
||||||
|
IPage<Coupon> pageResult = baseMapper.selectCouponPage(pageParam, queryCoupon);
|
||||||
|
|
||||||
|
// 构建返回结果
|
||||||
|
return PageResult.<Coupon>builder()
|
||||||
|
.count(pageResult.getTotal())
|
||||||
|
.resp_code(0)
|
||||||
|
.data(pageResult.getRecords())
|
||||||
|
.build();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public boolean createCoupon(Coupon coupon) {
|
||||||
|
// 生成优惠券编号
|
||||||
|
if (!StringUtils.hasText(coupon.getCouponNo())) {
|
||||||
|
coupon.setCouponNo(generateCouponNo());
|
||||||
|
}
|
||||||
|
|
||||||
|
// 设置默认值
|
||||||
|
if (coupon.getStatus() == null) {
|
||||||
|
coupon.setStatus(0); // 未使用
|
||||||
|
}
|
||||||
|
if (coupon.getCreateTime() == null) {
|
||||||
|
coupon.setCreateTime(new Date());
|
||||||
|
}
|
||||||
|
if (coupon.getUpdateTime() == null) {
|
||||||
|
coupon.setUpdateTime(new Date());
|
||||||
|
}
|
||||||
|
|
||||||
|
return save(coupon);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public boolean updateCoupon(Coupon coupon) {
|
||||||
|
coupon.setUpdateTime(new Date());
|
||||||
|
return updateById(coupon);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public boolean deleteCoupon(Long id) {
|
||||||
|
return removeById(id);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<Coupon> getCouponsByUserPhone(String userPhone) {
|
||||||
|
return baseMapper.selectByUserPhone(userPhone);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<Coupon> getAvailableCouponsByUserPhone(String userPhone) {
|
||||||
|
return baseMapper.selectAvailableByUserPhone(userPhone);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public boolean useCoupon(Long couponId, String orderNo) {
|
||||||
|
Coupon coupon = getById(couponId);
|
||||||
|
if (coupon == null) {
|
||||||
|
log.error("优惠券不存在,couponId: {}", couponId);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (coupon.getStatus() != 0) {
|
||||||
|
log.error("优惠券状态不正确,couponId: {}, status: {}", couponId, coupon.getStatus());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (coupon.getValidEndTime().before(new Date())) {
|
||||||
|
log.error("优惠券已过期,couponId: {}", couponId);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return baseMapper.updateCouponUsed(couponId, orderNo) > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public boolean createCouponFromCtrip(String ctripCouponId, String userPhone, String couponName,
|
||||||
|
Integer couponType, java.math.BigDecimal amount,
|
||||||
|
java.math.BigDecimal minAmount, Integer discountRate,
|
||||||
|
java.util.Date validStartTime,
|
||||||
|
java.util.Date validEndTime) {
|
||||||
|
|
||||||
|
// 检查是否已存在该携程优惠券
|
||||||
|
Coupon existingCoupon = baseMapper.selectByCtripCouponId(ctripCouponId);
|
||||||
|
if (existingCoupon != null) {
|
||||||
|
log.warn("携程优惠券已存在,ctripCouponId: {}", ctripCouponId);
|
||||||
|
return true; // 已存在也算成功
|
||||||
|
}
|
||||||
|
|
||||||
|
Coupon coupon = new Coupon();
|
||||||
|
coupon.setCouponNo(generateCouponNo());
|
||||||
|
coupon.setCouponName(couponName);
|
||||||
|
coupon.setCouponType(couponType);
|
||||||
|
coupon.setAmount(amount);
|
||||||
|
coupon.setMinAmount(minAmount);
|
||||||
|
coupon.setDiscountRate(discountRate);
|
||||||
|
coupon.setStatus(0); // 未使用
|
||||||
|
coupon.setUserPhone(userPhone);
|
||||||
|
coupon.setSource(1); // 来源:携程
|
||||||
|
coupon.setCtripCouponId(ctripCouponId);
|
||||||
|
coupon.setValidStartTime(validStartTime);
|
||||||
|
coupon.setValidEndTime(validEndTime);
|
||||||
|
coupon.setCreateTime(new Date());
|
||||||
|
coupon.setUpdateTime(new Date());
|
||||||
|
coupon.setCreateBy("ctrip");
|
||||||
|
coupon.setUpdateBy("ctrip");
|
||||||
|
|
||||||
|
return save(coupon);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public void updateExpiredCoupons() {
|
||||||
|
int count = baseMapper.updateExpiredCoupons();
|
||||||
|
log.info("批量更新过期优惠券完成,更新数量: {}", count);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
public boolean verifyCtripCoupon(String ctripCouponId, String orderNo) {
|
||||||
|
Coupon coupon = baseMapper.selectByCtripCouponId(ctripCouponId);
|
||||||
|
if (coupon == null) {
|
||||||
|
log.error("携程优惠券不存在,ctripCouponId: {}", ctripCouponId);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (coupon.getStatus() != 0) {
|
||||||
|
log.error("携程优惠券状态不正确,ctripCouponId: {}, status: {}", ctripCouponId, coupon.getStatus());
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (coupon.getValidEndTime().before(new Date())) {
|
||||||
|
log.error("携程优惠券已过期,ctripCouponId: {}", ctripCouponId);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 调用携程核销接口
|
||||||
|
boolean ctripVerifyResult = ctripApiService.verifyCoupon(ctripCouponId, orderNo);
|
||||||
|
if (!ctripVerifyResult) {
|
||||||
|
log.error("携程核销失败,ctripCouponId: {}, orderNo: {}", ctripCouponId, orderNo);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 更新本地优惠券状态
|
||||||
|
return baseMapper.updateCouponUsed(coupon.getId(), orderNo) > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean existsByUserPhoneAndCtripCouponId(String userPhone, String ctripCouponId) {
|
||||||
|
return lambdaQuery()
|
||||||
|
.eq(Coupon::getUserPhone, userPhone)
|
||||||
|
.eq(Coupon::getCtripCouponId, ctripCouponId)
|
||||||
|
.count() > 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 生成优惠券编号
|
||||||
|
*/
|
||||||
|
private String generateCouponNo() {
|
||||||
|
return "CP" + System.currentTimeMillis() + UUID.randomUUID().toString().substring(0, 8).toUpperCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
}
|
||||||
+51
@@ -0,0 +1,51 @@
|
|||||||
|
package com.central.order.service.impl;
|
||||||
|
|
||||||
|
import com.central.order.service.ICtripApiService;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 携程API服务实现类
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Service
|
||||||
|
public class CtripApiServiceImpl implements ICtripApiService {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean verifyCoupon(String ctripCouponId, String orderNo) {
|
||||||
|
// TODO: 实现具体的携程API调用逻辑
|
||||||
|
// 这里需要根据携程的API文档实现具体的调用
|
||||||
|
log.info("调用携程核销接口,ctripCouponId: {}, orderNo: {}", ctripCouponId, orderNo);
|
||||||
|
|
||||||
|
// 模拟API调用
|
||||||
|
try {
|
||||||
|
// 这里应该调用携程的核销API
|
||||||
|
// 例如:HttpClient调用携程的核销接口
|
||||||
|
|
||||||
|
// 暂时返回true,实际需要根据API调用结果返回
|
||||||
|
return true;
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("携程核销接口调用失败", e);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getCouponStatus(String ctripCouponId) {
|
||||||
|
// TODO: 实现具体的携程API调用逻辑
|
||||||
|
// 这里需要根据携程的API文档实现具体的调用
|
||||||
|
log.info("调用携程查询优惠券状态接口,ctripCouponId: {}", ctripCouponId);
|
||||||
|
|
||||||
|
// 模拟API调用
|
||||||
|
try {
|
||||||
|
// 这里应该调用携程的查询API
|
||||||
|
// 例如:HttpClient调用携程的查询接口
|
||||||
|
|
||||||
|
// 暂时返回"VALID",实际需要根据API调用结果返回
|
||||||
|
return "VALID";
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("携程查询优惠券状态接口调用失败", e);
|
||||||
|
return "UNKNOWN";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+41
-45
@@ -10,6 +10,7 @@ import org.springframework.stereotype.Service;
|
|||||||
import java.math.BigDecimal;
|
import java.math.BigDecimal;
|
||||||
import java.math.RoundingMode;
|
import java.math.RoundingMode;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@Service
|
@Service
|
||||||
@@ -19,21 +20,18 @@ public class DashboardServiceImpl implements IDashboardService {
|
|||||||
private final DashboardMapper dashboardMapper;
|
private final DashboardMapper dashboardMapper;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public DashboardStatisticsVO getDashboardStatistics() {
|
public DashboardStatisticsVO getDashboardStatistics(Map<String, Object> params) {
|
||||||
DashboardStatisticsVO statistics = new DashboardStatisticsVO();
|
DashboardStatisticsVO statistics = new DashboardStatisticsVO();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// 1. 获取订单统计
|
// 1. 获取订单统计(包含对账数据)
|
||||||
statistics.setOrderStats(getOrderStatistics());
|
statistics.setOrderStats(getOrderStatistics(params));
|
||||||
|
|
||||||
// 2. 获取收入统计
|
// 2. 获取图表统计
|
||||||
statistics.setIncomeStats(getIncomeStatistics());
|
statistics.setChartStats(getChartStatistics(params));
|
||||||
|
|
||||||
// 5. 获取图表统计
|
// 3. 获取筛选选项
|
||||||
statistics.setChartStats(getChartStatistics());
|
statistics.setFilterOptions(getFilterOptions(params));
|
||||||
|
|
||||||
// 6. 获取景区排行
|
|
||||||
statistics.setTourismRanking(getTourismRanking());
|
|
||||||
|
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("获取仪表盘统计数据失败", e);
|
log.error("获取仪表盘统计数据失败", e);
|
||||||
@@ -43,19 +41,19 @@ public class DashboardServiceImpl implements IDashboardService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取订单统计
|
* 获取订单统计(包含对账数据)
|
||||||
*/
|
*/
|
||||||
private OrderStatistics getOrderStatistics() {
|
private OrderStatistics getOrderStatistics(Map<String, Object> params) {
|
||||||
OrderStatistics stats = new OrderStatistics();
|
OrderStatistics stats = new OrderStatistics();
|
||||||
|
|
||||||
// 获取订单总数
|
// 获取订单总数
|
||||||
stats.setTotalOrders(dashboardMapper.getTotalOrders());
|
stats.setTotalOrders(dashboardMapper.getTotalOrders(params));
|
||||||
|
|
||||||
// 获取今日订单数
|
// 获取今日订单数
|
||||||
stats.setTodayOrders(dashboardMapper.getTodayOrders());
|
stats.setTodayOrders(dashboardMapper.getTodayOrders(params));
|
||||||
|
|
||||||
// 计算订单增长率
|
// 计算订单增长率
|
||||||
Long yesterdayOrders = dashboardMapper.getYesterdayOrders();
|
Long yesterdayOrders = dashboardMapper.getYesterdayOrders(params);
|
||||||
if (yesterdayOrders > 0) {
|
if (yesterdayOrders > 0) {
|
||||||
BigDecimal growth = new BigDecimal(stats.getTodayOrders() - yesterdayOrders)
|
BigDecimal growth = new BigDecimal(stats.getTodayOrders() - yesterdayOrders)
|
||||||
.divide(new BigDecimal(yesterdayOrders), 4, RoundingMode.HALF_UP)
|
.divide(new BigDecimal(yesterdayOrders), 4, RoundingMode.HALF_UP)
|
||||||
@@ -64,7 +62,7 @@ public class DashboardServiceImpl implements IDashboardService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 计算完成率
|
// 计算完成率
|
||||||
Long completedOrders = dashboardMapper.getCompletedOrders();
|
Long completedOrders = dashboardMapper.getCompletedOrders(params);
|
||||||
if (stats.getTotalOrders() > 0) {
|
if (stats.getTotalOrders() > 0) {
|
||||||
BigDecimal completionRate = new BigDecimal(completedOrders)
|
BigDecimal completionRate = new BigDecimal(completedOrders)
|
||||||
.divide(new BigDecimal(stats.getTotalOrders()), 4, RoundingMode.HALF_UP)
|
.divide(new BigDecimal(stats.getTotalOrders()), 4, RoundingMode.HALF_UP)
|
||||||
@@ -72,29 +70,13 @@ public class DashboardServiceImpl implements IDashboardService {
|
|||||||
stats.setCompletionRate(completionRate);
|
stats.setCompletionRate(completionRate);
|
||||||
}
|
}
|
||||||
|
|
||||||
return stats;
|
// 获取对账相关数据
|
||||||
}
|
stats.setTotalAmount(dashboardMapper.getTotalAmount(params));
|
||||||
|
stats.setRefundAmount(dashboardMapper.getRefundAmount(params));
|
||||||
/**
|
// 景区收入 = 总订单金额 - 退款金额
|
||||||
* 获取收入统计
|
Long netIncome = (stats.getTotalAmount() != null ? stats.getTotalAmount() : 0)
|
||||||
*/
|
- (stats.getRefundAmount() != null ? stats.getRefundAmount() : 0);
|
||||||
private IncomeStatistics getIncomeStatistics() {
|
stats.setNetIncome(netIncome);
|
||||||
IncomeStatistics stats = new IncomeStatistics();
|
|
||||||
|
|
||||||
// 获取总收入
|
|
||||||
stats.setTotalAmount(dashboardMapper.getTotalIncome());
|
|
||||||
|
|
||||||
// 获取今日收入
|
|
||||||
stats.setTodayAmount(dashboardMapper.getTodayIncome());
|
|
||||||
|
|
||||||
// 计算目标完成率(假设每日目标10000元)
|
|
||||||
BigDecimal targetAmount = new BigDecimal(1000000); // 100元 * 100(分)
|
|
||||||
if (stats.getTodayAmount() > 0) {
|
|
||||||
BigDecimal completion = new BigDecimal(stats.getTodayAmount())
|
|
||||||
.divide(targetAmount, 4, RoundingMode.HALF_UP)
|
|
||||||
.multiply(new BigDecimal(100));
|
|
||||||
stats.setTargetCompletion(completion);
|
|
||||||
}
|
|
||||||
|
|
||||||
return stats;
|
return stats;
|
||||||
}
|
}
|
||||||
@@ -102,22 +84,36 @@ public class DashboardServiceImpl implements IDashboardService {
|
|||||||
/**
|
/**
|
||||||
* 获取图表统计
|
* 获取图表统计
|
||||||
*/
|
*/
|
||||||
private ChartStatistics getChartStatistics() {
|
private ChartStatistics getChartStatistics(Map<String, Object> params) {
|
||||||
ChartStatistics stats = new ChartStatistics();
|
ChartStatistics stats = new ChartStatistics();
|
||||||
|
|
||||||
// 获取订单趋势(最近7天)
|
// 获取订单趋势(最近7天)
|
||||||
stats.setOrderTrend(dashboardMapper.getOrderTrend());
|
stats.setOrderTrend(dashboardMapper.getOrderTrend(params));
|
||||||
|
|
||||||
|
// 获取订单状态分布
|
||||||
|
stats.setOrderDistribution(dashboardMapper.getOrderDistribution(params));
|
||||||
|
|
||||||
// 获取收入构成
|
// 获取收入构成
|
||||||
stats.setIncomeData(dashboardMapper.getIncomeData());
|
stats.setIncomeBreakdown(dashboardMapper.getIncomeBreakdown(params));
|
||||||
|
|
||||||
return stats;
|
return stats;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取景区排行
|
* 获取筛选选项
|
||||||
*/
|
*/
|
||||||
private List<TourismRankingVO> getTourismRanking() {
|
private FilterOptions getFilterOptions(Map<String, Object> params) {
|
||||||
return dashboardMapper.getTourismRanking();
|
FilterOptions options = new FilterOptions();
|
||||||
|
|
||||||
|
// 获取景区列表
|
||||||
|
options.setTourismList(dashboardMapper.getTourismOptions());
|
||||||
|
|
||||||
|
// 获取二维码列表
|
||||||
|
options.setQrcodeList(dashboardMapper.getQrcodeOptions(params));
|
||||||
|
|
||||||
|
// 获取设备列表
|
||||||
|
options.setDeviceList(dashboardMapper.getDeviceOptions(params));
|
||||||
|
|
||||||
|
return options;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+5
@@ -187,6 +187,7 @@ public class MediaServiceImpl implements IMediaService {
|
|||||||
Map<String, String> clips = new HashMap<>();
|
Map<String, String> clips = new HashMap<>();
|
||||||
List<OrderFile> videoFiles = taskData.getVideoFiles();
|
List<OrderFile> videoFiles = taskData.getVideoFiles();
|
||||||
//@TODO 后期需要通过模板参数进行动态设置clips参数
|
//@TODO 后期需要通过模板参数进行动态设置clips参数
|
||||||
|
|
||||||
clips.put("1", fileCenterService.getViewUrlByPath(videoFiles.get(4).getFilePath()));
|
clips.put("1", fileCenterService.getViewUrlByPath(videoFiles.get(4).getFilePath()));
|
||||||
clips.put("2", fileCenterService.getViewUrlByPath(videoFiles.get(5).getFilePath()));
|
clips.put("2", fileCenterService.getViewUrlByPath(videoFiles.get(5).getFilePath()));
|
||||||
clips.put("3", fileCenterService.getViewUrlByPath(videoFiles.get(6).getFilePath()));
|
clips.put("3", fileCenterService.getViewUrlByPath(videoFiles.get(6).getFilePath()));
|
||||||
@@ -195,6 +196,10 @@ public class MediaServiceImpl implements IMediaService {
|
|||||||
clips.put("6", fileCenterService.getViewUrlByPath(videoFiles.get(2).getFilePath()));
|
clips.put("6", fileCenterService.getViewUrlByPath(videoFiles.get(2).getFilePath()));
|
||||||
clips.put("7", fileCenterService.getViewUrlByPath(videoFiles.get(3).getFilePath()));
|
clips.put("7", fileCenterService.getViewUrlByPath(videoFiles.get(3).getFilePath()));
|
||||||
|
|
||||||
|
if (taskData.getVideoFiles().size() > 7) {
|
||||||
|
clips.put("8", fileCenterService.getViewUrlByPath(videoFiles.get(7).getFilePath()));
|
||||||
|
}
|
||||||
|
|
||||||
return JSON.toJSONString(clips);
|
return JSON.toJSONString(clips);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
throw new BusinessException("构建剪辑参数失败: " + e.getMessage());
|
throw new BusinessException("构建剪辑参数失败: " + e.getMessage());
|
||||||
|
|||||||
+57
-6
@@ -1,19 +1,24 @@
|
|||||||
package com.central.order.service.impl;
|
package com.central.order.service.impl;
|
||||||
|
|
||||||
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||||
|
import com.central.common.context.TenantContextHolder;
|
||||||
import com.central.common.lock.DistributedLock;
|
import com.central.common.lock.DistributedLock;
|
||||||
import com.central.common.model.PageResult;
|
import com.central.common.model.PageResult;
|
||||||
import com.central.common.service.impl.SuperServiceImpl;
|
import com.central.common.service.impl.SuperServiceImpl;
|
||||||
import com.central.order.enums.OrderStatus;
|
import com.central.order.enums.OrderStatus;
|
||||||
import com.central.order.event.OrderStatusChangeEvent;
|
import com.central.order.event.OrderStatusChangeEvent;
|
||||||
|
import com.central.order.feign.FileCenterService;
|
||||||
import com.central.order.feign.UserCenterService;
|
import com.central.order.feign.UserCenterService;
|
||||||
import com.central.order.mapper.OrderFileMapper;
|
import com.central.order.mapper.OrderFileMapper;
|
||||||
import com.central.order.mapper.OrderMapper;
|
import com.central.order.mapper.OrderMapper;
|
||||||
|
import com.central.order.mapper.TourismFileMapper;
|
||||||
import com.central.order.mapper.TourismMapper;
|
import com.central.order.mapper.TourismMapper;
|
||||||
import com.central.order.model.Order;
|
import com.central.order.model.Order;
|
||||||
import com.central.order.model.OrderFile;
|
import com.central.order.model.OrderFile;
|
||||||
import com.central.order.model.OrderRanking;
|
import com.central.order.model.OrderRanking;
|
||||||
|
import com.central.order.model.TourismFile;
|
||||||
import com.central.order.service.IOrderService;
|
import com.central.order.service.IOrderService;
|
||||||
import com.central.order.util.DateUtils;
|
import com.central.order.util.DateUtils;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
@@ -56,6 +61,10 @@ public class OrderServiceImpl extends SuperServiceImpl<OrderMapper, Order> imple
|
|||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private TourismMapper tourismMapper;
|
private TourismMapper tourismMapper;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private TourismFileMapper tourismFileMapper;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private OrderFileMapper orderFileMapper;
|
private OrderFileMapper orderFileMapper;
|
||||||
|
|
||||||
@@ -65,6 +74,9 @@ public class OrderServiceImpl extends SuperServiceImpl<OrderMapper, Order> imple
|
|||||||
@Autowired
|
@Autowired
|
||||||
private UserCenterService userCenterService;
|
private UserCenterService userCenterService;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private FileCenterService fileCenterService;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 列表
|
* 列表
|
||||||
* @param params
|
* @param params
|
||||||
@@ -76,6 +88,7 @@ public class OrderServiceImpl extends SuperServiceImpl<OrderMapper, Order> imple
|
|||||||
List<Order> list = baseMapper.findList(page, params);
|
List<Order> list = baseMapper.findList(page, params);
|
||||||
for (Order order : list){
|
for (Order order : list){
|
||||||
order.setMobile(userCenterService.findUserById(order.getUserId()).getMobile());
|
order.setMobile(userCenterService.findUserById(order.getUserId()).getMobile());
|
||||||
|
order.setTourismName(tourismMapper.selectById(order.getTourismId()).getTourismName());
|
||||||
}
|
}
|
||||||
return PageResult.<Order>builder().data(list).resp_code(0).count(page.getTotal()).build();
|
return PageResult.<Order>builder().data(list).resp_code(0).count(page.getTotal()).build();
|
||||||
}
|
}
|
||||||
@@ -110,14 +123,33 @@ public class OrderServiceImpl extends SuperServiceImpl<OrderMapper, Order> imple
|
|||||||
// 检查并处理订单超时逻辑,5分钟超时后自动取消
|
// 检查并处理订单超时逻辑,5分钟超时后自动取消
|
||||||
@Override
|
@Override
|
||||||
public void checkAndHandleOrderTimeout() {
|
public void checkAndHandleOrderTimeout() {
|
||||||
|
log.info("开始检查订单超时情况");
|
||||||
|
|
||||||
List<Order> orders = baseMapper.getOrdersByStatus(OrderStatus.UNPAID.getId());
|
List<Order> orders = baseMapper.getOrdersByStatus(OrderStatus.UNPAID.getId());
|
||||||
|
log.info("查询到 {} 个待支付订单", orders.size());
|
||||||
|
|
||||||
long currentTime = new Date().getTime();
|
long currentTime = new Date().getTime();
|
||||||
|
int timeoutCount = 0;
|
||||||
|
|
||||||
for (Order order : orders) {
|
for (Order order : orders) {
|
||||||
long elapsedTime = currentTime - order.getCreateTime().getTime();
|
long elapsedTime = currentTime - order.getCreateTime().getTime();
|
||||||
if (TimeUnit.MILLISECONDS.toMinutes(elapsedTime) >= 5) {
|
long elapsedMinutes = TimeUnit.MILLISECONDS.toMinutes(elapsedTime);
|
||||||
|
|
||||||
|
log.info("订单检查: orderNo={}, createTime={}, elapsedMinutes={}, userId={}, tourismId={}",
|
||||||
|
order.getOrderNo(),
|
||||||
|
order.getCreateTime(),
|
||||||
|
elapsedMinutes,
|
||||||
|
order.getUserId(),
|
||||||
|
order.getTourismId());
|
||||||
|
|
||||||
|
if (elapsedMinutes >= 5) {
|
||||||
|
log.info("订单超时,准备取消: orderNo={}, elapsedMinutes={}", order.getOrderNo(), elapsedMinutes);
|
||||||
baseMapper.updateOrderStatus(order.getId(), OrderStatus.CANCELED.getId());
|
baseMapper.updateOrderStatus(order.getId(), OrderStatus.CANCELED.getId());
|
||||||
|
timeoutCount++;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
log.info("订单超时检查完成: 总订单数={}, 超时取消数={}", orders.size(), timeoutCount);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 获取所有处于排队状态的订单,用于后续按顺序处理
|
// 获取所有处于排队状态的订单,用于后续按顺序处理
|
||||||
@@ -159,12 +191,18 @@ public class OrderServiceImpl extends SuperServiceImpl<OrderMapper, Order> imple
|
|||||||
@Override
|
@Override
|
||||||
public boolean updateOrder(Order order) {
|
public boolean updateOrder(Order order) {
|
||||||
try {
|
try {
|
||||||
|
|
||||||
|
log.info("更新订单状态时租户ID: tenantId={}", TenantContextHolder.getTenant());
|
||||||
|
|
||||||
// 获取原订单信息
|
// 获取原订单信息
|
||||||
Order oldOrder = getById(order.getId());
|
Order oldOrder = getById(order.getId());
|
||||||
boolean result = super.saveOrUpdateIdempotency(order, lock,
|
if (oldOrder == null) {
|
||||||
ORDER_LOCK + order.getOrderNo(),
|
log.error("订单不存在,无法更新: orderId={}", order.getId());
|
||||||
new QueryWrapper<Order>().eq("order_no", order.getOrderNo()),
|
return false;
|
||||||
"订单已存在");
|
}
|
||||||
|
|
||||||
|
// 使用updateById进行更新,避免INSERT操作
|
||||||
|
boolean result = updateById(order);
|
||||||
|
|
||||||
// 如果更新成功且状态发生变化,发布事件
|
// 如果更新成功且状态发生变化,发布事件
|
||||||
if (result && !order.getOrderStatus().equals(oldOrder.getOrderStatus())) {
|
if (result && !order.getOrderStatus().equals(oldOrder.getOrderStatus())) {
|
||||||
@@ -189,7 +227,7 @@ public class OrderServiceImpl extends SuperServiceImpl<OrderMapper, Order> imple
|
|||||||
}
|
}
|
||||||
return result;
|
return result;
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("更新订单失败", e);
|
log.error("更新订单失败: orderId={}, orderNo={}", order.getId(), order.getOrderNo(), e);
|
||||||
throw new RuntimeException(e);
|
throw new RuntimeException(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -224,6 +262,19 @@ public class OrderServiceImpl extends SuperServiceImpl<OrderMapper, Order> imple
|
|||||||
for (Order order : list) {
|
for (Order order : list) {
|
||||||
order.setTourismName(tourismMapper.getTourismById(order.getTourismId()).getTourismName());
|
order.setTourismName(tourismMapper.getTourismById(order.getTourismId()).getTourismName());
|
||||||
order.setCreatedTime(sdf.format(order.getCreateTime()));
|
order.setCreatedTime(sdf.format(order.getCreateTime()));
|
||||||
|
// 设置景区订单展示图(type=6)的imageUrl
|
||||||
|
List<TourismFile> tourismFiles = tourismFileMapper.selectList(
|
||||||
|
new LambdaQueryWrapper<TourismFile>()
|
||||||
|
.eq(TourismFile::getTourismId, order.getTourismId())
|
||||||
|
.eq(TourismFile::getType, 6)
|
||||||
|
.last("limit 1")
|
||||||
|
);
|
||||||
|
if (tourismFiles != null && !tourismFiles.isEmpty()) {
|
||||||
|
String imgUrl = tourismFiles.get(0).getImageUrl();
|
||||||
|
order.setTourismImgUrl(fileCenterService.getViewUrlByPath(imgUrl));
|
||||||
|
} else {
|
||||||
|
order.setTourismImgUrl(null);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return PageResult.<Order>builder().data(list).resp_code(0).count(page.getTotal()).build();
|
return PageResult.<Order>builder().data(list).resp_code(0).count(page.getTotal()).build();
|
||||||
|
|||||||
+22
-10
@@ -202,15 +202,23 @@ public class OrderStatisticsServiceImpl extends SuperServiceImpl<OrderStatistics
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public List<Map<String, Object>> statisticsByTourism(String startTime, String endTime) {
|
public List<Map<String, Object>> statisticsByTourism(String startTime, String endTime, String tourismId) {
|
||||||
try {
|
try {
|
||||||
OrderStatisticsQuery query = OrderStatisticsQuery.builder()
|
OrderStatisticsQuery.OrderStatisticsQueryBuilder queryBuilder = OrderStatisticsQuery.builder()
|
||||||
.startTime(startTime)
|
.startTime(startTime)
|
||||||
.endTime(endTime)
|
.endTime(endTime)
|
||||||
.groupField("o.tourism_id")
|
.groupField("o.tourism_id");
|
||||||
.build();
|
|
||||||
|
|
||||||
List<Map<String, Object>> statistics = baseMapper.getOrderStatisticsByGroup(query);
|
// 如果指定了景区ID,则添加筛选条件
|
||||||
|
if (tourismId != null && !tourismId.trim().isEmpty()) {
|
||||||
|
try {
|
||||||
|
queryBuilder.tourismId(Long.parseLong(tourismId));
|
||||||
|
} catch (NumberFormatException e) {
|
||||||
|
log.warn("景区ID格式错误: {}", tourismId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
List<Map<String, Object>> statistics = baseMapper.getOrderStatisticsByGroup(queryBuilder.build());
|
||||||
return processStatisticsResult(statistics);
|
return processStatisticsResult(statistics);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("按景区维度统计失败", e);
|
log.error("按景区维度统计失败", e);
|
||||||
@@ -219,15 +227,19 @@ public class OrderStatisticsServiceImpl extends SuperServiceImpl<OrderStatistics
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public List<Map<String, Object>> statisticsByDevice(String startTime, String endTime) {
|
public List<Map<String, Object>> statisticsByDevice(String startTime, String endTime, String deviceSn) {
|
||||||
try {
|
try {
|
||||||
OrderStatisticsQuery query = OrderStatisticsQuery.builder()
|
OrderStatisticsQuery.OrderStatisticsQueryBuilder queryBuilder = OrderStatisticsQuery.builder()
|
||||||
.startTime(startTime)
|
.startTime(startTime)
|
||||||
.endTime(endTime)
|
.endTime(endTime)
|
||||||
.groupField("o.device_sn")
|
.groupField("o.device_sn");
|
||||||
.build();
|
|
||||||
|
|
||||||
List<Map<String, Object>> statistics = baseMapper.getOrderStatisticsByGroup(query);
|
// 如果指定了设备编号,则添加筛选条件
|
||||||
|
if (deviceSn != null && !deviceSn.trim().isEmpty()) {
|
||||||
|
queryBuilder.deviceSn(deviceSn);
|
||||||
|
}
|
||||||
|
|
||||||
|
List<Map<String, Object>> statistics = baseMapper.getOrderStatisticsByGroup(queryBuilder.build());
|
||||||
return processStatisticsResult(statistics);
|
return processStatisticsResult(statistics);
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
log.error("按设备维度统计失败", e);
|
log.error("按设备维度统计失败", e);
|
||||||
|
|||||||
+126
-1
@@ -6,16 +6,22 @@ import com.central.common.model.Result;
|
|||||||
import com.central.common.service.impl.SuperServiceImpl;
|
import com.central.common.service.impl.SuperServiceImpl;
|
||||||
import com.central.order.mapper.TourismMapper;
|
import com.central.order.mapper.TourismMapper;
|
||||||
import com.central.order.model.Tourism;
|
import com.central.order.model.Tourism;
|
||||||
|
import com.central.order.model.TourismWithDistance;
|
||||||
|
import com.central.order.model.TourismFile;
|
||||||
import com.central.order.service.ITourismService;
|
import com.central.order.service.ITourismService;
|
||||||
|
import com.central.order.service.ITourismFileService;
|
||||||
|
import com.central.order.feign.FileCenterService;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.apache.commons.collections4.MapUtils;
|
import org.apache.commons.collections4.MapUtils;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
import java.util.List;
|
import java.util.List;
|
||||||
import java.util.Map;
|
import java.util.Map;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Order information
|
* 景区信息服务实现类
|
||||||
*
|
*
|
||||||
* @author lsl
|
* @author lsl
|
||||||
* @date 2024-12-19 17:52:54
|
* @date 2024-12-19 17:52:54
|
||||||
@@ -24,6 +30,12 @@ import java.util.Map;
|
|||||||
@Service
|
@Service
|
||||||
public class TourismServiceImpl extends SuperServiceImpl<TourismMapper, Tourism> implements ITourismService {
|
public class TourismServiceImpl extends SuperServiceImpl<TourismMapper, Tourism> implements ITourismService {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private ITourismFileService tourismFileService;
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private FileCenterService fileCenterService;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 列表
|
* 列表
|
||||||
* @param params
|
* @param params
|
||||||
@@ -47,4 +59,117 @@ public class TourismServiceImpl extends SuperServiceImpl<TourismMapper, Tourism>
|
|||||||
return baseMapper.getTourismById(id);
|
return baseMapper.getTourismById(id);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<Map<String, Object>> getDevicesByTourismId(Long tourismId) {
|
||||||
|
return baseMapper.getDevicesByTourismId(tourismId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<TourismWithDistance> findNearbyTourisms(BigDecimal longitude, BigDecimal latitude, Double radius, Integer limit) {
|
||||||
|
log.info("查询附近景区,经度: {}, 纬度: {}, 半径: {}km, 限制数量: {}", longitude, latitude, radius, limit);
|
||||||
|
|
||||||
|
// 参数验证
|
||||||
|
if (longitude == null || latitude == null) {
|
||||||
|
log.warn("经纬度参数不能为空");
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (radius == null || radius <= 0) {
|
||||||
|
radius = 10.0; // 默认10公里
|
||||||
|
}
|
||||||
|
|
||||||
|
if (limit == null || limit <= 0) {
|
||||||
|
limit = 20; // 默认返回20个
|
||||||
|
}
|
||||||
|
|
||||||
|
List<TourismWithDistance> tourisms = baseMapper.findNearbyTourisms(longitude, latitude, radius, limit);
|
||||||
|
log.info("查询到附近景区数量: {}", tourisms.size());
|
||||||
|
|
||||||
|
// 为每个景区添加订单展示图片
|
||||||
|
for (TourismWithDistance tourism : tourisms) {
|
||||||
|
try {
|
||||||
|
// 查询景区的订单展示图片(type=6)
|
||||||
|
List<TourismFile> tourismFiles = tourismFileService.getByTourismId(tourism.getId());
|
||||||
|
if (tourismFiles != null && !tourismFiles.isEmpty()) {
|
||||||
|
// 查找订单展示图(type=6)
|
||||||
|
TourismFile orderShowFile = tourismFiles.stream()
|
||||||
|
.filter(file -> file.getType() == 6)
|
||||||
|
.findFirst()
|
||||||
|
.orElse(null);
|
||||||
|
|
||||||
|
if (orderShowFile != null && orderShowFile.getImageUrl() != null) {
|
||||||
|
// 获取图片的完整URL
|
||||||
|
String imageUrl = fileCenterService.getViewUrlByPath(orderShowFile.getImageUrl());
|
||||||
|
tourism.setOrderShowImageUrl(imageUrl);
|
||||||
|
log.debug("景区 {} 设置订单展示图片: {}", tourism.getTourismName(), imageUrl);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.warn("获取景区 {} 订单展示图片失败: {}", tourism.getTourismName(), e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return tourisms;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public List<Tourism> findTourismsByBounds(BigDecimal minLongitude, BigDecimal maxLongitude,
|
||||||
|
BigDecimal minLatitude, BigDecimal maxLatitude) {
|
||||||
|
log.info("根据经纬度范围查询景区,经度范围: [{}, {}], 纬度范围: [{}, {}]",
|
||||||
|
minLongitude, maxLongitude, minLatitude, maxLatitude);
|
||||||
|
|
||||||
|
// 参数验证
|
||||||
|
if (minLongitude == null || maxLongitude == null || minLatitude == null || maxLatitude == null) {
|
||||||
|
log.warn("经纬度范围参数不能为空");
|
||||||
|
return List.of();
|
||||||
|
}
|
||||||
|
|
||||||
|
List<Tourism> tourisms = baseMapper.findTourismsByBounds(minLongitude, maxLongitude, minLatitude, maxLatitude);
|
||||||
|
log.info("查询到景区数量: {}", tourisms.size());
|
||||||
|
|
||||||
|
return tourisms;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Result updateTourismLocation(Long id, BigDecimal longitude, BigDecimal latitude) {
|
||||||
|
log.info("更新景区经纬度信息,景区ID: {}, 经度: {}, 纬度: {}", id, longitude, latitude);
|
||||||
|
|
||||||
|
// 参数验证
|
||||||
|
if (id == null) {
|
||||||
|
return Result.failed("景区ID不能为空");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (longitude == null || latitude == null) {
|
||||||
|
return Result.failed("经纬度不能为空");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 验证经纬度范围
|
||||||
|
if (longitude.compareTo(BigDecimal.valueOf(-180)) < 0 || longitude.compareTo(BigDecimal.valueOf(180)) > 0) {
|
||||||
|
return Result.failed("经度范围应在-180到180之间");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (latitude.compareTo(BigDecimal.valueOf(-90)) < 0 || latitude.compareTo(BigDecimal.valueOf(90)) > 0) {
|
||||||
|
return Result.failed("纬度范围应在-90到90之间");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 查询景区是否存在
|
||||||
|
Tourism tourism = getById(id);
|
||||||
|
if (tourism == null) {
|
||||||
|
return Result.failed("景区不存在");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 更新经纬度
|
||||||
|
tourism.setLongitude(longitude);
|
||||||
|
tourism.setLatitude(latitude);
|
||||||
|
|
||||||
|
boolean result = updateById(tourism);
|
||||||
|
if (result) {
|
||||||
|
log.info("景区经纬度更新成功,景区ID: {}", id);
|
||||||
|
return Result.succeed(tourism, "经纬度更新成功");
|
||||||
|
} else {
|
||||||
|
log.error("景区经纬度更新失败,景区ID: {}", id);
|
||||||
|
return Result.failed("经纬度更新失败");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
+1
@@ -153,6 +153,7 @@ public class VideoEditServiceImpl implements IVideoEditService {
|
|||||||
orderFile.setFileId(fileInfo.getId());
|
orderFile.setFileId(fileInfo.getId());
|
||||||
orderFile.setOrderNo(orderNo);
|
orderFile.setOrderNo(orderNo);
|
||||||
orderFile.setFileType("video/mp4");
|
orderFile.setFileType("video/mp4");
|
||||||
|
orderFile.setFileTag("ai_video");
|
||||||
orderFile.setFilePath(extractFilePath(outputUrl));
|
orderFile.setFilePath(extractFilePath(outputUrl));
|
||||||
orderFile.setUserId(order.getUserId());
|
orderFile.setUserId(order.getUserId());
|
||||||
orderFile.setTourismId(order.getTourismId());
|
orderFile.setTourismId(order.getTourismId());
|
||||||
|
|||||||
+32
@@ -0,0 +1,32 @@
|
|||||||
|
package com.central.order.task;
|
||||||
|
|
||||||
|
import com.central.order.service.ICouponService;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.scheduling.annotation.Scheduled;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 优惠券过期定时任务
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
public class CouponExpirationTask {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private ICouponService couponService;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 每天凌晨2点执行,批量更新过期优惠券状态
|
||||||
|
*/
|
||||||
|
@Scheduled(cron = "0 0 2 * * ?")
|
||||||
|
public void updateExpiredCoupons() {
|
||||||
|
log.info("开始执行优惠券过期状态更新任务");
|
||||||
|
try {
|
||||||
|
couponService.updateExpiredCoupons();
|
||||||
|
log.info("优惠券过期状态更新任务执行完成");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("优惠券过期状态更新任务执行失败", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -29,7 +29,7 @@ knife4j:
|
|||||||
zlt:
|
zlt:
|
||||||
#多租户配置
|
#多租户配置
|
||||||
tenant:
|
tenant:
|
||||||
enable: false
|
enable: true
|
||||||
ignoreTables:
|
ignoreTables:
|
||||||
- edit_task
|
- edit_task
|
||||||
- home_carousel
|
- home_carousel
|
||||||
@@ -40,16 +40,13 @@ zlt:
|
|||||||
- profit_sharing
|
- profit_sharing
|
||||||
- order_statistics
|
- order_statistics
|
||||||
ignoreSqls:
|
ignoreSqls:
|
||||||
# 查询全部列表
|
# 移除所有ignoreSqls配置,让所有SQL都经过租户过滤处理
|
||||||
# - com.central.order.mapper.OrderMapper.findList
|
# 这样webApp租户的特殊处理逻辑才能生效
|
||||||
# 获取某个订单
|
# 该接口是白名单接口查询中的逻辑,来例如:机库直接创建数据没有携带租户ID
|
||||||
# - com.central.order.mapper.OrderMapper.getOrderByNumber
|
- com.central.order.mapper.OrderMapper.getOrderByNumber
|
||||||
noIgnoreSqls:
|
- com.central.order.mapper.OrderMapper.getOrdersByStatus
|
||||||
- com.central.order.mapper.OrderMapper.findList
|
# update和delete类型的操作mybatisPlus不支持,原因是数据隔离级别
|
||||||
- com.central.order.mapper.TourismMapper.findList
|
# - com.central.order.mapper.OrderMapper.updateOrderStatus
|
||||||
- com.central.order.mapper.OrderFileMapper.findList
|
|
||||||
- com.central.order.mapper.QrCodeMapper.findList
|
|
||||||
- com.central.order.mapper.QrCodeMapper.save
|
|
||||||
# 微信支付商户号
|
# 微信支付商户号
|
||||||
tencent:
|
tencent:
|
||||||
merchantId: ${zlt.wxpay.merchantId}
|
merchantId: ${zlt.wxpay.merchantId}
|
||||||
@@ -88,7 +85,7 @@ tencent:
|
|||||||
file:
|
file:
|
||||||
oss-url: goflyapp.oss-cn-beijing.aliyuncs.com
|
oss-url: goflyapp.oss-cn-beijing.aliyuncs.com
|
||||||
cdn-url: cdn.goflytec.com
|
cdn-url: cdn.goflytec.com
|
||||||
style: image/resize,m_mfit,w_300,h_250
|
style: image/resize,m_mfit,w_218,h_160
|
||||||
#审计日志
|
#审计日志
|
||||||
# audit-log:
|
# audit-log:
|
||||||
# enabled: true
|
# enabled: true
|
||||||
@@ -126,3 +123,18 @@ wx:
|
|||||||
activity-start: lgwkRnbdDc3mEwk3RMob43LpLHnLfglZtTkbFRPsPCA
|
activity-start: lgwkRnbdDc3mEwk3RMob43LpLHnLfglZtTkbFRPsPCA
|
||||||
order-complete: ZeIlAA6ImQLxBiLmo-53lM7wkL4KnuKKTGKWBZwYAdM
|
order-complete: ZeIlAA6ImQLxBiLmo-53lM7wkL4KnuKKTGKWBZwYAdM
|
||||||
video-edit-complete: IXpL-Voztm3GM-zFj3sxA39qy8oRtAcxTiT7_Qsyz9Q
|
video-edit-complete: IXpL-Voztm3GM-zFj3sxA39qy8oRtAcxTiT7_Qsyz9Q
|
||||||
|
|
||||||
|
# 订单中心CDN预热配置
|
||||||
|
cdn:
|
||||||
|
prefetch:
|
||||||
|
# 是否启用CDN预热功能
|
||||||
|
enabled: true
|
||||||
|
# 每批次预热的文件数量
|
||||||
|
batch-size: 50
|
||||||
|
# 预热区域:domestic-仅中国内地,overseas-全球(不包含中国内地),不传-全球
|
||||||
|
area: domestic
|
||||||
|
|
||||||
|
# 日志配置
|
||||||
|
logging:
|
||||||
|
level:
|
||||||
|
com.central.order.controller.OrderFileController: DEBUG
|
||||||
|
|||||||
@@ -4,10 +4,10 @@ server:
|
|||||||
spring:
|
spring:
|
||||||
application:
|
application:
|
||||||
name: order-center
|
name: order-center
|
||||||
# cloud:
|
cloud:
|
||||||
# nacos:
|
nacos:
|
||||||
# discovery:
|
discovery:
|
||||||
# ip: 81.70.164.178
|
ip: 81.70.164.178
|
||||||
# cloud:
|
# cloud:
|
||||||
# nacos:
|
# nacos:
|
||||||
# discovery:
|
# discovery:
|
||||||
|
|||||||
@@ -0,0 +1,124 @@
|
|||||||
|
<?xml version="1.0" encoding="UTF-8"?>
|
||||||
|
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||||
|
<mapper namespace="com.central.order.mapper.CouponMapper">
|
||||||
|
|
||||||
|
<!-- 基础结果映射 -->
|
||||||
|
<resultMap id="BaseResultMap" type="com.central.order.entity.Coupon">
|
||||||
|
<id column="id" property="id" jdbcType="BIGINT"/>
|
||||||
|
<result column="coupon_no" property="couponNo" jdbcType="VARCHAR"/>
|
||||||
|
<result column="coupon_name" property="couponName" jdbcType="VARCHAR"/>
|
||||||
|
<result column="coupon_type" property="couponType" jdbcType="INTEGER"/>
|
||||||
|
<result column="amount" property="amount" jdbcType="DECIMAL"/>
|
||||||
|
<result column="min_amount" property="minAmount" jdbcType="DECIMAL"/>
|
||||||
|
<result column="discount_rate" property="discountRate" jdbcType="INTEGER"/>
|
||||||
|
<result column="status" property="status" jdbcType="INTEGER"/>
|
||||||
|
<result column="user_phone" property="userPhone" jdbcType="VARCHAR"/>
|
||||||
|
<result column="user_id" property="userId" jdbcType="BIGINT"/>
|
||||||
|
<result column="source" property="source" jdbcType="INTEGER"/>
|
||||||
|
<result column="ctrip_coupon_id" property="ctripCouponId" jdbcType="VARCHAR"/>
|
||||||
|
<result column="valid_start_time" property="validStartTime" jdbcType="TIMESTAMP"/>
|
||||||
|
<result column="valid_end_time" property="validEndTime" jdbcType="TIMESTAMP"/>
|
||||||
|
<result column="used_time" property="usedTime" jdbcType="TIMESTAMP"/>
|
||||||
|
<result column="used_order_no" property="usedOrderNo" jdbcType="VARCHAR"/>
|
||||||
|
<result column="create_time" property="createTime" jdbcType="TIMESTAMP"/>
|
||||||
|
<result column="update_time" property="updateTime" jdbcType="TIMESTAMP"/>
|
||||||
|
<result column="create_by" property="createBy" jdbcType="VARCHAR"/>
|
||||||
|
<result column="update_by" property="updateBy" jdbcType="VARCHAR"/>
|
||||||
|
<result column="remark" property="remark" jdbcType="VARCHAR"/>
|
||||||
|
<result column="tenant_id" property="tenantId" jdbcType="VARCHAR"/>
|
||||||
|
</resultMap>
|
||||||
|
|
||||||
|
<!-- 基础字段 -->
|
||||||
|
<sql id="Base_Column_List">
|
||||||
|
id, coupon_no, coupon_name, coupon_type, amount, min_amount, discount_rate, status,
|
||||||
|
user_phone, user_id, source, ctrip_coupon_id, valid_start_time, valid_end_time,
|
||||||
|
used_time, used_order_no, create_time, update_time, create_by, update_by, remark, tenant_id
|
||||||
|
</sql>
|
||||||
|
|
||||||
|
<!-- 分页查询优惠券列表 -->
|
||||||
|
<select id="selectCouponPage" resultMap="BaseResultMap">
|
||||||
|
SELECT
|
||||||
|
<include refid="Base_Column_List"/>
|
||||||
|
FROM t_coupon
|
||||||
|
<where>
|
||||||
|
<if test="coupon.couponName != null and coupon.couponName != ''">
|
||||||
|
AND coupon_name LIKE CONCAT('%', #{coupon.couponName}, '%')
|
||||||
|
</if>
|
||||||
|
<if test="coupon.couponType != null">
|
||||||
|
AND coupon_type = #{coupon.couponType}
|
||||||
|
</if>
|
||||||
|
<if test="coupon.status != null">
|
||||||
|
AND status = #{coupon.status}
|
||||||
|
</if>
|
||||||
|
<if test="coupon.userPhone != null and coupon.userPhone != ''">
|
||||||
|
AND user_phone = #{coupon.userPhone}
|
||||||
|
</if>
|
||||||
|
<if test="coupon.source != null">
|
||||||
|
AND source = #{coupon.source}
|
||||||
|
</if>
|
||||||
|
<if test="coupon.ctripCouponId != null and coupon.ctripCouponId != ''">
|
||||||
|
AND ctrip_coupon_id = #{coupon.ctripCouponId}
|
||||||
|
</if>
|
||||||
|
</where>
|
||||||
|
ORDER BY create_time DESC
|
||||||
|
</select>
|
||||||
|
|
||||||
|
<!-- 根据手机号查询用户优惠券 -->
|
||||||
|
<select id="selectByUserPhone" resultMap="BaseResultMap">
|
||||||
|
SELECT
|
||||||
|
<include refid="Base_Column_List"/>
|
||||||
|
FROM t_coupon
|
||||||
|
WHERE user_phone = #{userPhone}
|
||||||
|
ORDER BY create_time DESC
|
||||||
|
</select>
|
||||||
|
|
||||||
|
<!-- 根据手机号查询可用优惠券 -->
|
||||||
|
<select id="selectAvailableByUserPhone" resultMap="BaseResultMap">
|
||||||
|
SELECT
|
||||||
|
<include refid="Base_Column_List"/>
|
||||||
|
FROM t_coupon
|
||||||
|
WHERE user_phone = #{userPhone}
|
||||||
|
AND status = 0
|
||||||
|
AND valid_start_time <= NOW()
|
||||||
|
AND valid_end_time >= NOW()
|
||||||
|
ORDER BY create_time DESC
|
||||||
|
</select>
|
||||||
|
|
||||||
|
<!-- 根据携程优惠券ID查询 -->
|
||||||
|
<select id="selectByCtripCouponId" resultMap="BaseResultMap">
|
||||||
|
SELECT
|
||||||
|
<include refid="Base_Column_List"/>
|
||||||
|
FROM t_coupon
|
||||||
|
WHERE ctrip_coupon_id = #{ctripCouponId}
|
||||||
|
LIMIT 1
|
||||||
|
</select>
|
||||||
|
|
||||||
|
<!-- 根据订单号查询使用的优惠券 -->
|
||||||
|
<select id="selectByUsedOrderNo" resultMap="BaseResultMap">
|
||||||
|
SELECT
|
||||||
|
<include refid="Base_Column_List"/>
|
||||||
|
FROM t_coupon
|
||||||
|
WHERE used_order_no = #{usedOrderNo}
|
||||||
|
LIMIT 1
|
||||||
|
</select>
|
||||||
|
|
||||||
|
<!-- 更新优惠券状态为已使用 -->
|
||||||
|
<update id="updateCouponUsed">
|
||||||
|
UPDATE t_coupon
|
||||||
|
SET status = 1,
|
||||||
|
used_time = NOW(),
|
||||||
|
used_order_no = #{usedOrderNo},
|
||||||
|
update_time = NOW()
|
||||||
|
WHERE id = #{id}
|
||||||
|
</update>
|
||||||
|
|
||||||
|
<!-- 批量更新过期优惠券状态 -->
|
||||||
|
<update id="updateExpiredCoupons">
|
||||||
|
UPDATE t_coupon
|
||||||
|
SET status = 2,
|
||||||
|
update_time = NOW()
|
||||||
|
WHERE status = 0
|
||||||
|
AND valid_end_time < NOW()
|
||||||
|
</update>
|
||||||
|
|
||||||
|
</mapper>
|
||||||
@@ -8,8 +8,8 @@
|
|||||||
<if test="params.orderNo != null and params.orderNo != ''">
|
<if test="params.orderNo != null and params.orderNo != ''">
|
||||||
AND t.order_no LIKE CONCAT('%', #{params.orderNo}, '%')
|
AND t.order_no LIKE CONCAT('%', #{params.orderNo}, '%')
|
||||||
</if>
|
</if>
|
||||||
<if test="params.createTime != null and params.createTime.length == 2">
|
<if test="params.startTime != null and params.endTime != null ">
|
||||||
AND t.create_time BETWEEN #{params.createTime[0]} AND #{params.createTime[1]}
|
AND t.create_time BETWEEN #{params.startTime} AND #{params.endTime}
|
||||||
</if>
|
</if>
|
||||||
</where>
|
</where>
|
||||||
ORDER BY t.id DESC
|
ORDER BY t.id DESC
|
||||||
|
|||||||
@@ -22,7 +22,15 @@
|
|||||||
|
|
||||||
<!-- 动态获取参数采用备参 -->
|
<!-- 动态获取参数采用备参 -->
|
||||||
<select id="findListByUser" resultType="com.central.order.model.Order">
|
<select id="findListByUser" resultType="com.central.order.model.Order">
|
||||||
select id,order_no,tourism_id,device_sn,workspace_id,code_id,user_id,order_amount,order_status,create_time,update_time from orders t WHERE t.user_id = #{param2.userId} ORDER BY id DESC
|
select id,order_no,tourism_id,device_sn,workspace_id,code_id,user_id,order_amount,order_status,create_time,update_time from orders t WHERE t.user_id = #{param2.userId}
|
||||||
|
and t.is_del = 0
|
||||||
|
<if test="param2.orderStatusList != null and param2.orderStatusList.size() > 0">
|
||||||
|
and t.order_status in
|
||||||
|
<foreach collection="param2.orderStatusList" item="status" open="(" separator="," close=")">
|
||||||
|
#{status}
|
||||||
|
</foreach>
|
||||||
|
</if>
|
||||||
|
ORDER BY id DESC
|
||||||
</select>
|
</select>
|
||||||
|
|
||||||
<!-- 根据订单状态查询订单列表 -->
|
<!-- 根据订单状态查询订单列表 -->
|
||||||
|
|||||||
@@ -17,4 +17,61 @@
|
|||||||
INSERT INTO tourisms (tourism_no, tourism_name, tourism_address,tourism_phone)
|
INSERT INTO tourisms (tourism_no, tourism_name, tourism_address,tourism_phone)
|
||||||
VALUES (#{tourismNo}, #{tourismName}, #{tourismAddress},#{tourismPhone})
|
VALUES (#{tourismNo}, #{tourismName}, #{tourismAddress},#{tourismPhone})
|
||||||
</insert>
|
</insert>
|
||||||
|
|
||||||
|
<!-- 获取景区设备列表 -->
|
||||||
|
<select id="getDevicesByTourismId" resultType="java.util.Map">
|
||||||
|
SELECT DISTINCT
|
||||||
|
q.device_sn as deviceSn,
|
||||||
|
q.name as qrcodeName,
|
||||||
|
q.code_id as qrcodeId,
|
||||||
|
q.price as qrcodePrice,
|
||||||
|
q.status as qrcodeStatus,
|
||||||
|
q.create_time as qrcodeCreateTime,
|
||||||
|
t.tourism_name as tourismName,
|
||||||
|
t.tourism_address as tourismAddress
|
||||||
|
FROM qrcodes q
|
||||||
|
LEFT JOIN tourisms t ON q.tourism_id = t.id
|
||||||
|
WHERE q.tourism_id = #{tourismId}
|
||||||
|
AND q.is_del = 0
|
||||||
|
AND t.is_del = 0
|
||||||
|
ORDER BY q.create_time DESC
|
||||||
|
</select>
|
||||||
|
|
||||||
|
<!-- 查询附近景区列表 -->
|
||||||
|
<select id="findNearbyTourisms" resultType="com.central.order.model.TourismWithDistance">
|
||||||
|
<![CDATA[
|
||||||
|
SELECT
|
||||||
|
*,
|
||||||
|
(
|
||||||
|
6371 * acos(
|
||||||
|
cos(radians(#{latitude})) *
|
||||||
|
cos(radians(latitude)) *
|
||||||
|
cos(radians(longitude) - radians(#{longitude})) +
|
||||||
|
sin(radians(#{latitude})) *
|
||||||
|
sin(radians(latitude))
|
||||||
|
)
|
||||||
|
) AS distance
|
||||||
|
FROM tourisms
|
||||||
|
WHERE is_del = 0
|
||||||
|
AND status = 1
|
||||||
|
AND longitude IS NOT NULL
|
||||||
|
AND latitude IS NOT NULL
|
||||||
|
HAVING distance <= #{radius}
|
||||||
|
ORDER BY distance ASC
|
||||||
|
]]>
|
||||||
|
<if test="limit != null and limit > 0">
|
||||||
|
LIMIT #{limit}
|
||||||
|
</if>
|
||||||
|
</select>
|
||||||
|
|
||||||
|
<!-- 根据经纬度范围查询景区 -->
|
||||||
|
<select id="findTourismsByBounds" resultType="com.central.order.model.Tourism">
|
||||||
|
SELECT * FROM tourisms
|
||||||
|
WHERE is_del = 0
|
||||||
|
AND status = 1
|
||||||
|
AND longitude BETWEEN #{minLongitude} AND #{maxLongitude}
|
||||||
|
AND latitude BETWEEN #{minLatitude} AND #{maxLatitude}
|
||||||
|
ORDER BY create_time DESC
|
||||||
|
</select>
|
||||||
|
|
||||||
</mapper>
|
</mapper>
|
||||||
|
|||||||
+78
@@ -0,0 +1,78 @@
|
|||||||
|
package com.central.order.model;
|
||||||
|
|
||||||
|
import org.junit.jupiter.api.Test;
|
||||||
|
import static org.junit.jupiter.api.Assertions.*;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* TourismWithDistance 类单元测试
|
||||||
|
*
|
||||||
|
* @author lsl
|
||||||
|
* @date 2024-12-19 17:51:47
|
||||||
|
*/
|
||||||
|
public class TourismWithDistanceTest {
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testDistanceDesc() {
|
||||||
|
TourismWithDistance tourism = new TourismWithDistance();
|
||||||
|
|
||||||
|
// 测试小于1公里的距离
|
||||||
|
tourism.setDistance(new BigDecimal("0.5"));
|
||||||
|
assertEquals("500m", tourism.getDistanceDesc());
|
||||||
|
|
||||||
|
// 测试等于1公里的距离
|
||||||
|
tourism.setDistance(BigDecimal.ONE);
|
||||||
|
assertEquals("1.0km", tourism.getDistanceDesc());
|
||||||
|
|
||||||
|
// 测试大于1公里的距离
|
||||||
|
tourism.setDistance(new BigDecimal("2.5"));
|
||||||
|
assertEquals("2.5km", tourism.getDistanceDesc());
|
||||||
|
|
||||||
|
// 测试null距离
|
||||||
|
tourism.setDistance(null);
|
||||||
|
assertEquals("未知距离", tourism.getDistanceDesc());
|
||||||
|
|
||||||
|
// 测试0距离
|
||||||
|
tourism.setDistance(BigDecimal.ZERO);
|
||||||
|
assertEquals("0m", tourism.getDistanceDesc());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testInheritance() {
|
||||||
|
TourismWithDistance tourism = new TourismWithDistance();
|
||||||
|
|
||||||
|
// 测试继承自Tourism的属性
|
||||||
|
tourism.setTourismName("测试景区");
|
||||||
|
tourism.setTourismAddress("测试地址");
|
||||||
|
tourism.setLongitude(new BigDecimal("116.397128"));
|
||||||
|
tourism.setLatitude(new BigDecimal("39.916527"));
|
||||||
|
|
||||||
|
assertEquals("测试景区", tourism.getTourismName());
|
||||||
|
assertEquals("测试地址", tourism.getTourismAddress());
|
||||||
|
assertEquals(new BigDecimal("116.397128"), tourism.getLongitude());
|
||||||
|
assertEquals(new BigDecimal("39.916527"), tourism.getLatitude());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testOrderShowImageUrl() {
|
||||||
|
TourismWithDistance tourism = new TourismWithDistance();
|
||||||
|
|
||||||
|
// 测试设置和获取订单展示图片URL
|
||||||
|
String imageUrl = "https://example.com/image.jpg";
|
||||||
|
tourism.setOrderShowImageUrl(imageUrl);
|
||||||
|
|
||||||
|
assertEquals(imageUrl, tourism.getOrderShowImageUrl());
|
||||||
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testDistanceDescCustom() {
|
||||||
|
TourismWithDistance tourism = new TourismWithDistance();
|
||||||
|
|
||||||
|
// 测试自定义距离描述
|
||||||
|
String customDesc = "约1.2公里";
|
||||||
|
tourism.setDistanceDesc(customDesc);
|
||||||
|
|
||||||
|
assertEquals(customDesc, tourism.getDistanceDesc());
|
||||||
|
}
|
||||||
|
}
|
||||||
+65
@@ -467,4 +467,69 @@ public class SysUserController {
|
|||||||
return config != null ? Result.succeed(config) : Result.failed("未找到配置");
|
return config != null ? Result.succeed(config) : Result.failed("未找到配置");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 用户注销账户
|
||||||
|
*/
|
||||||
|
@PostMapping("/users/account/logout")
|
||||||
|
@Operation(summary = "用户注销账户")
|
||||||
|
public Result<String> logout() {
|
||||||
|
try {
|
||||||
|
SysUser currentUser = LoginUserUtils.getCurrentSysUser();
|
||||||
|
if (currentUser != null) {
|
||||||
|
// 检查是否为超级管理员
|
||||||
|
if (checkAdmin(currentUser.getId())) {
|
||||||
|
return Result.failed("超级管理员账户不能注销");
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info("用户 {} 执行账户注销操作", currentUser.getUsername());
|
||||||
|
|
||||||
|
// 执行用户账户彻底注销(删除所有相关数据)
|
||||||
|
boolean success = appUserService.completelyDeleteUser(currentUser.getId());
|
||||||
|
|
||||||
|
if (success) {
|
||||||
|
log.info("用户 {} 账户彻底注销成功", currentUser.getUsername());
|
||||||
|
return Result.succeed("账户彻底注销成功");
|
||||||
|
} else {
|
||||||
|
log.error("用户 {} 账户彻底注销失败", currentUser.getUsername());
|
||||||
|
return Result.failed("账户彻底注销失败,请重试");
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return Result.failed("用户未登录");
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("用户账户彻底注销失败", e);
|
||||||
|
return Result.failed("账户彻底注销失败,请重试");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 测试彻底删除用户(仅用于测试)
|
||||||
|
*/
|
||||||
|
@PostMapping("/users/test/delete/{userId}")
|
||||||
|
@Operation(summary = "测试彻底删除用户")
|
||||||
|
public Result<String> testCompletelyDeleteUser(@PathVariable Long userId) {
|
||||||
|
try {
|
||||||
|
log.info("开始测试彻底删除用户,用户ID: {}", userId);
|
||||||
|
|
||||||
|
// 检查是否为超级管理员
|
||||||
|
if (checkAdmin(userId)) {
|
||||||
|
return Result.failed("超级管理员账户不能删除");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 执行用户彻底删除
|
||||||
|
boolean success = appUserService.completelyDeleteUser(userId);
|
||||||
|
|
||||||
|
if (success) {
|
||||||
|
log.info("用户彻底删除测试成功,用户ID: {}", userId);
|
||||||
|
return Result.succeed("用户彻底删除测试成功");
|
||||||
|
} else {
|
||||||
|
log.error("用户彻底删除测试失败,用户ID: {}", userId);
|
||||||
|
return Result.failed("用户彻底删除测试失败");
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("用户彻底删除测试异常,用户ID: {}", userId, e);
|
||||||
|
return Result.failed("用户彻底删除测试异常: " + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
+189
@@ -0,0 +1,189 @@
|
|||||||
|
package com.central.user.controller;
|
||||||
|
|
||||||
|
import com.central.common.model.Result;
|
||||||
|
import com.central.user.service.ITenantService;
|
||||||
|
import io.swagger.v3.oas.annotations.Operation;
|
||||||
|
import io.swagger.v3.oas.annotations.Parameter;
|
||||||
|
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统一租户管理控制器
|
||||||
|
* 负责系统级租户管理,其他微服务通过Feign调用
|
||||||
|
*
|
||||||
|
* @author lsl
|
||||||
|
* @date 2024-12-19
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@RestController
|
||||||
|
@RequestMapping("/tenant")
|
||||||
|
@Tag(name = "租户管理", description = "系统级租户管理")
|
||||||
|
public class TenantController {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private ITenantService tenantService;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 设置当前租户
|
||||||
|
*/
|
||||||
|
@PostMapping("/set")
|
||||||
|
@Operation(summary = "设置当前租户")
|
||||||
|
public Result<String> setCurrentTenant(
|
||||||
|
@Parameter(description = "租户ID", required = true)
|
||||||
|
@RequestParam String tenantId) {
|
||||||
|
return tenantService.setCurrentTenant(tenantId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取当前租户
|
||||||
|
*/
|
||||||
|
@GetMapping("/current")
|
||||||
|
@Operation(summary = "获取当前租户")
|
||||||
|
public Result<String> getCurrentTenant() {
|
||||||
|
try {
|
||||||
|
String tenantId = tenantService.getCurrentTenant();
|
||||||
|
log.debug("获取当前租户: {}", tenantId);
|
||||||
|
return Result.succeed(tenantId, "获取租户成功");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("获取租户失败", e);
|
||||||
|
return Result.failed("获取租户失败:" + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清除当前租户
|
||||||
|
*/
|
||||||
|
@PostMapping("/clear")
|
||||||
|
@Operation(summary = "清除当前租户")
|
||||||
|
public Result<String> clearCurrentTenant() {
|
||||||
|
return tenantService.clearCurrentTenant();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检查是否为 webApp 租户
|
||||||
|
*/
|
||||||
|
@GetMapping("/check-webapp")
|
||||||
|
@Operation(summary = "检查是否为 webApp 租户")
|
||||||
|
public Result<Boolean> isWebAppTenant() {
|
||||||
|
try {
|
||||||
|
boolean isWebApp = tenantService.isWebAppTenant();
|
||||||
|
log.debug("检查是否为 webApp 租户: {}", isWebApp);
|
||||||
|
return Result.succeed(isWebApp, "检查成功");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("检查租户类型失败", e);
|
||||||
|
return Result.failed("检查租户类型失败:" + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取租户信息
|
||||||
|
*/
|
||||||
|
@GetMapping("/info")
|
||||||
|
@Operation(summary = "获取租户信息")
|
||||||
|
public Result<Object> getTenantInfo() {
|
||||||
|
try {
|
||||||
|
Map<String, Object> tenantInfo = tenantService.getTenantInfo();
|
||||||
|
log.debug("获取租户信息: {}", tenantInfo);
|
||||||
|
return Result.succeed(tenantInfo, "获取租户信息成功");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("获取租户信息失败", e);
|
||||||
|
return Result.failed("获取租户信息失败:" + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 验证租户权限
|
||||||
|
*/
|
||||||
|
@PostMapping("/validate")
|
||||||
|
@Operation(summary = "验证租户权限")
|
||||||
|
public Result<Object> validateTenantPermission(
|
||||||
|
@Parameter(description = "租户ID", required = true)
|
||||||
|
@RequestParam String tenantId,
|
||||||
|
@Parameter(description = "操作类型", required = true)
|
||||||
|
@RequestParam String operation) {
|
||||||
|
return tenantService.validateTenantPermission(tenantId, operation);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取所有租户列表
|
||||||
|
*/
|
||||||
|
@GetMapping("/list")
|
||||||
|
@Operation(summary = "获取所有租户列表")
|
||||||
|
public Result<List<Map<String, Object>>> getAllTenants() {
|
||||||
|
return tenantService.getAllTenants();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 切换租户
|
||||||
|
*/
|
||||||
|
@PostMapping("/switch")
|
||||||
|
@Operation(summary = "切换租户")
|
||||||
|
public Result<Object> switchTenant(
|
||||||
|
@Parameter(description = "目标租户ID", required = true)
|
||||||
|
@RequestParam String targetTenantId) {
|
||||||
|
return tenantService.switchTenant(targetTenantId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取租户状态
|
||||||
|
*/
|
||||||
|
@GetMapping("/status")
|
||||||
|
@Operation(summary = "获取租户状态")
|
||||||
|
public Result<Object> getTenantStatus() {
|
||||||
|
try {
|
||||||
|
Map<String, Object> status = tenantService.getTenantStatus();
|
||||||
|
log.debug("获取租户状态: {}", status);
|
||||||
|
return Result.succeed(status, "获取租户状态成功");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("获取租户状态失败", e);
|
||||||
|
return Result.failed("获取租户状态失败:" + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取租户统计信息
|
||||||
|
*/
|
||||||
|
@GetMapping("/statistics")
|
||||||
|
@Operation(summary = "获取租户统计信息")
|
||||||
|
public Result<Map<String, Object>> getTenantStatistics() {
|
||||||
|
return tenantService.getTenantStatistics();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建新租户
|
||||||
|
*/
|
||||||
|
@PostMapping("/create")
|
||||||
|
@Operation(summary = "创建新租户")
|
||||||
|
public Result<String> createTenant(@RequestBody Map<String, Object> tenantInfo) {
|
||||||
|
return tenantService.createTenant(tenantInfo);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 删除租户
|
||||||
|
*/
|
||||||
|
@DeleteMapping("/{tenantId}")
|
||||||
|
@Operation(summary = "删除租户")
|
||||||
|
public Result<String> deleteTenant(
|
||||||
|
@Parameter(description = "租户ID", required = true)
|
||||||
|
@PathVariable String tenantId) {
|
||||||
|
return tenantService.deleteTenant(tenantId);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 更新租户信息
|
||||||
|
*/
|
||||||
|
@PutMapping("/{tenantId}")
|
||||||
|
@Operation(summary = "更新租户信息")
|
||||||
|
public Result<String> updateTenant(
|
||||||
|
@Parameter(description = "租户ID", required = true)
|
||||||
|
@PathVariable String tenantId,
|
||||||
|
@RequestBody Map<String, Object> tenantInfo) {
|
||||||
|
return tenantService.updateTenant(tenantId, tenantInfo);
|
||||||
|
}
|
||||||
|
}
|
||||||
+5
-5
@@ -42,7 +42,7 @@ public class WechatConfigController {
|
|||||||
@Operation(summary = "根据类型和租户ID查询微信配置")
|
@Operation(summary = "根据类型和租户ID查询微信配置")
|
||||||
@GetMapping("/type/{type}")
|
@GetMapping("/type/{type}")
|
||||||
public WechatConfig getConfig(@PathVariable String type, @RequestParam String tenantId) {
|
public WechatConfig getConfig(@PathVariable String type, @RequestParam String tenantId) {
|
||||||
WechatConfig config = wechatConfigService.getConfig(type, tenantId);
|
WechatConfig config = wechatConfigService.getConfigByTypeTenantId(type, tenantId);
|
||||||
return config;
|
return config;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -113,8 +113,8 @@ public class WechatConfigController {
|
|||||||
|
|
||||||
@Operation(summary = "获取微信配置")
|
@Operation(summary = "获取微信配置")
|
||||||
@GetMapping("/app/{id}")
|
@GetMapping("/app/{id}")
|
||||||
public WechatConfig getConfigByAppId(@PathVariable("id") String appId) {
|
public WechatConfig getConfigByAppId(@PathVariable("id") String appId, @RequestParam String type) {
|
||||||
return wechatConfigService.getConfig(appId);
|
return wechatConfigService.getConfigByAppIdAndType(appId,type);
|
||||||
}
|
}
|
||||||
|
|
||||||
@GetMapping(value = "/serial/{serialNumber}")
|
@GetMapping(value = "/serial/{serialNumber}")
|
||||||
@@ -128,7 +128,7 @@ public class WechatConfigController {
|
|||||||
public Result<Boolean> uploadPrivateKey(@RequestParam("file") MultipartFile file) {
|
public Result<Boolean> uploadPrivateKey(@RequestParam("file") MultipartFile file) {
|
||||||
try {
|
try {
|
||||||
String privateKey = new String(file.getBytes());
|
String privateKey = new String(file.getBytes());
|
||||||
WechatConfig wechatConfig = wechatConfigService.getConfig("PAY",TenantContextHolder.getTenant());
|
WechatConfig wechatConfig = wechatConfigService.getConfigByTypeTenantId("PAY",TenantContextHolder.getTenant());
|
||||||
wechatConfig.setPrivateKey(privateKey);
|
wechatConfig.setPrivateKey(privateKey);
|
||||||
return Result.succeed(wechatConfigService.updateConfig(wechatConfig));
|
return Result.succeed(wechatConfigService.updateConfig(wechatConfig));
|
||||||
} catch (Exception e) {
|
} catch (Exception e) {
|
||||||
@@ -140,7 +140,7 @@ public class WechatConfigController {
|
|||||||
@Operation(summary = "获取当前配置")
|
@Operation(summary = "获取当前配置")
|
||||||
@GetMapping("/current/{type}")
|
@GetMapping("/current/{type}")
|
||||||
public Result<WechatConfig> getCurrentConfig(@PathVariable String type) {
|
public Result<WechatConfig> getCurrentConfig(@PathVariable String type) {
|
||||||
return Result.succeed(wechatConfigService.getConfig(type, TenantContextHolder.getTenant()));
|
return Result.succeed(wechatConfigService.getConfigByTypeTenantId(type, TenantContextHolder.getTenant()));
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
+38
@@ -0,0 +1,38 @@
|
|||||||
|
package com.central.user.feign;
|
||||||
|
|
||||||
|
import com.central.common.model.Result;
|
||||||
|
import org.springframework.cloud.openfeign.FeignClient;
|
||||||
|
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 设备中心服务Feign客户端
|
||||||
|
* 用于清理用户相关的设备数据
|
||||||
|
*/
|
||||||
|
@FeignClient(name = "device-center", fallback = DeviceCenterServiceFallback.class)
|
||||||
|
public interface DeviceCenterService {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 删除用户相关的所有设备数据
|
||||||
|
* @param userId 用户ID
|
||||||
|
* @return 删除结果
|
||||||
|
*/
|
||||||
|
@DeleteMapping("/devices/user/{userId}")
|
||||||
|
Result<String> deleteUserDevices(@PathVariable("userId") String userId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 删除用户相关的所有航线文件
|
||||||
|
* @param userId 用户ID
|
||||||
|
* @return 删除结果
|
||||||
|
*/
|
||||||
|
@DeleteMapping("/wayline-files/user/{userId}")
|
||||||
|
Result<String> deleteUserWaylineFiles(@PathVariable("userId") String userId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 删除用户相关的所有任务记录
|
||||||
|
* @param userId 用户ID
|
||||||
|
* @return 删除结果
|
||||||
|
*/
|
||||||
|
@DeleteMapping("/wayline-jobs/user/{userId}")
|
||||||
|
Result<String> deleteUserWaylineJobs(@PathVariable("userId") String userId);
|
||||||
|
}
|
||||||
+31
@@ -0,0 +1,31 @@
|
|||||||
|
package com.central.user.feign;
|
||||||
|
|
||||||
|
import com.central.common.model.Result;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 设备中心服务降级处理
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
public class DeviceCenterServiceFallback implements DeviceCenterService {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Result<String> deleteUserDevices(String userId) {
|
||||||
|
log.error("设备中心服务不可用,无法删除用户设备数据,用户ID: {}", userId);
|
||||||
|
return Result.failed("设备中心服务不可用");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Result<String> deleteUserWaylineFiles(String userId) {
|
||||||
|
log.error("设备中心服务不可用,无法删除用户航线文件,用户ID: {}", userId);
|
||||||
|
return Result.failed("设备中心服务不可用");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Result<String> deleteUserWaylineJobs(String userId) {
|
||||||
|
log.error("设备中心服务不可用,无法删除用户任务记录,用户ID: {}", userId);
|
||||||
|
return Result.failed("设备中心服务不可用");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
package com.central.user.feign;
|
||||||
|
|
||||||
|
import com.central.common.model.Result;
|
||||||
|
import org.springframework.cloud.openfeign.FeignClient;
|
||||||
|
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||||
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 订单中心服务Feign客户端
|
||||||
|
* 用于清理用户相关的订单数据
|
||||||
|
*/
|
||||||
|
@FeignClient(name = "order-center", fallback = OrderCenterServiceFallback.class)
|
||||||
|
public interface OrderCenterService {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 删除用户相关的所有订单数据
|
||||||
|
* @param userId 用户ID
|
||||||
|
* @return 删除结果
|
||||||
|
*/
|
||||||
|
@DeleteMapping("/orders/user/{userId}")
|
||||||
|
Result<String> deleteUserOrders(@PathVariable("userId") Long userId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 删除用户相关的所有订单文件
|
||||||
|
* @param userId 用户ID
|
||||||
|
* @return 删除结果
|
||||||
|
*/
|
||||||
|
@DeleteMapping("/order-files/user/{userId}")
|
||||||
|
Result<String> deleteUserOrderFiles(@PathVariable("userId") Long userId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 删除用户相关的所有消息
|
||||||
|
* @param userId 用户ID
|
||||||
|
* @return 删除结果
|
||||||
|
*/
|
||||||
|
@DeleteMapping("/messages/user/{userId}")
|
||||||
|
Result<String> deleteUserMessages(@PathVariable("userId") Long userId);
|
||||||
|
}
|
||||||
+31
@@ -0,0 +1,31 @@
|
|||||||
|
package com.central.user.feign;
|
||||||
|
|
||||||
|
import com.central.common.model.Result;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 订单中心服务降级处理
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
public class OrderCenterServiceFallback implements OrderCenterService {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Result<String> deleteUserOrders(Long userId) {
|
||||||
|
log.error("订单中心服务不可用,无法删除用户订单数据,用户ID: {}", userId);
|
||||||
|
return Result.failed("订单中心服务不可用");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Result<String> deleteUserOrderFiles(Long userId) {
|
||||||
|
log.error("订单中心服务不可用,无法删除用户订单文件,用户ID: {}", userId);
|
||||||
|
return Result.failed("订单中心服务不可用");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Result<String> deleteUserMessages(Long userId) {
|
||||||
|
log.error("订单中心服务不可用,无法删除用户消息,用户ID: {}", userId);
|
||||||
|
return Result.failed("订单中心服务不可用");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,119 @@
|
|||||||
|
package com.central.user.feign;
|
||||||
|
|
||||||
|
import com.central.common.model.Result;
|
||||||
|
import org.springframework.cloud.openfeign.FeignClient;
|
||||||
|
import org.springframework.web.bind.annotation.*;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 租户服务Feign客户端
|
||||||
|
* 供其他微服务调用租户管理功能
|
||||||
|
*
|
||||||
|
* @author lsl
|
||||||
|
* @date 2024-12-19
|
||||||
|
*/
|
||||||
|
@FeignClient(name = "user-center", fallback = TenantServiceFallback.class)
|
||||||
|
public interface TenantService {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 设置当前租户
|
||||||
|
* @param tenantId 租户ID
|
||||||
|
* @return 设置结果
|
||||||
|
*/
|
||||||
|
@PostMapping("/tenant/set")
|
||||||
|
Result<String> setCurrentTenant(@RequestParam("tenantId") String tenantId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取当前租户
|
||||||
|
* @return 租户ID
|
||||||
|
*/
|
||||||
|
@GetMapping("/tenant/current")
|
||||||
|
Result<String> getCurrentTenant();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清除当前租户
|
||||||
|
* @return 清除结果
|
||||||
|
*/
|
||||||
|
@PostMapping("/tenant/clear")
|
||||||
|
Result<String> clearCurrentTenant();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检查是否为 webApp 租户
|
||||||
|
* @return 是否为 webApp 租户
|
||||||
|
*/
|
||||||
|
@GetMapping("/tenant/check-webapp")
|
||||||
|
Result<Boolean> isWebAppTenant();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取租户信息
|
||||||
|
* @return 租户信息
|
||||||
|
*/
|
||||||
|
@GetMapping("/tenant/info")
|
||||||
|
Result<Object> getTenantInfo();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 验证租户权限
|
||||||
|
* @param tenantId 租户ID
|
||||||
|
* @param operation 操作类型
|
||||||
|
* @return 权限验证结果
|
||||||
|
*/
|
||||||
|
@PostMapping("/tenant/validate")
|
||||||
|
Result<Object> validateTenantPermission(
|
||||||
|
@RequestParam("tenantId") String tenantId,
|
||||||
|
@RequestParam("operation") String operation);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取所有租户列表
|
||||||
|
* @return 租户列表
|
||||||
|
*/
|
||||||
|
@GetMapping("/tenant/list")
|
||||||
|
Result<Object> getAllTenants();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 切换租户
|
||||||
|
* @param targetTenantId 目标租户ID
|
||||||
|
* @return 切换结果
|
||||||
|
*/
|
||||||
|
@PostMapping("/tenant/switch")
|
||||||
|
Result<Object> switchTenant(@RequestParam("targetTenantId") String targetTenantId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取租户状态
|
||||||
|
* @return 租户状态
|
||||||
|
*/
|
||||||
|
@GetMapping("/tenant/status")
|
||||||
|
Result<Object> getTenantStatus();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取租户统计信息
|
||||||
|
* @return 统计信息
|
||||||
|
*/
|
||||||
|
@GetMapping("/tenant/statistics")
|
||||||
|
Result<Map<String, Object>> getTenantStatistics();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建新租户
|
||||||
|
* @param tenantInfo 租户信息
|
||||||
|
* @return 创建结果
|
||||||
|
*/
|
||||||
|
@PostMapping("/tenant/create")
|
||||||
|
Result<String> createTenant(@RequestBody Map<String, Object> tenantInfo);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 删除租户
|
||||||
|
* @param tenantId 租户ID
|
||||||
|
* @return 删除结果
|
||||||
|
*/
|
||||||
|
@DeleteMapping("/tenant/{tenantId}")
|
||||||
|
Result<String> deleteTenant(@PathVariable("tenantId") String tenantId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 更新租户信息
|
||||||
|
* @param tenantId 租户ID
|
||||||
|
* @param tenantInfo 租户信息
|
||||||
|
* @return 更新结果
|
||||||
|
*/
|
||||||
|
@PutMapping("/tenant/{tenantId}")
|
||||||
|
Result<String> updateTenant(@PathVariable("tenantId") String tenantId, @RequestBody Map<String, Object> tenantInfo);
|
||||||
|
}
|
||||||
+97
@@ -0,0 +1,97 @@
|
|||||||
|
package com.central.user.feign;
|
||||||
|
|
||||||
|
import com.central.common.model.Result;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.util.HashMap;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 租户服务降级处理
|
||||||
|
*
|
||||||
|
* @author lsl
|
||||||
|
* @date 2024-12-19
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
public class TenantServiceFallback implements TenantService {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Result<String> setCurrentTenant(String tenantId) {
|
||||||
|
log.error("租户服务不可用,无法设置租户: {}", tenantId);
|
||||||
|
return Result.failed("租户服务不可用");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Result<String> getCurrentTenant() {
|
||||||
|
log.error("租户服务不可用,无法获取当前租户");
|
||||||
|
return Result.failed("租户服务不可用");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Result<String> clearCurrentTenant() {
|
||||||
|
log.error("租户服务不可用,无法清除当前租户");
|
||||||
|
return Result.failed("租户服务不可用");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Result<Boolean> isWebAppTenant() {
|
||||||
|
log.error("租户服务不可用,无法检查租户类型");
|
||||||
|
return Result.failed("租户服务不可用");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Result<Object> getTenantInfo() {
|
||||||
|
log.error("租户服务不可用,无法获取租户信息");
|
||||||
|
return Result.failed("租户服务不可用");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Result<Object> validateTenantPermission(String tenantId, String operation) {
|
||||||
|
log.error("租户服务不可用,无法验证租户权限,租户: {}, 操作: {}", tenantId, operation);
|
||||||
|
return Result.failed("租户服务不可用");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Result<Object> getAllTenants() {
|
||||||
|
log.error("租户服务不可用,无法获取租户列表");
|
||||||
|
return Result.failed("租户服务不可用");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Result<Object> switchTenant(String targetTenantId) {
|
||||||
|
log.error("租户服务不可用,无法切换租户: {}", targetTenantId);
|
||||||
|
return Result.failed("租户服务不可用");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Result<Object> getTenantStatus() {
|
||||||
|
log.error("租户服务不可用,无法获取租户状态");
|
||||||
|
return Result.failed("租户服务不可用");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Result<Map<String, Object>> getTenantStatistics() {
|
||||||
|
log.error("租户服务不可用,无法获取租户统计信息");
|
||||||
|
return Result.failed("租户服务不可用");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Result<String> createTenant(Map<String, Object> tenantInfo) {
|
||||||
|
log.error("租户服务不可用,无法创建租户");
|
||||||
|
return Result.failed("租户服务不可用");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Result<String> deleteTenant(String tenantId) {
|
||||||
|
log.error("租户服务不可用,无法删除租户: {}", tenantId);
|
||||||
|
return Result.failed("租户服务不可用");
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Result<String> updateTenant(String tenantId, Map<String, Object> tenantInfo) {
|
||||||
|
log.error("租户服务不可用,无法更新租户信息: {}", tenantId);
|
||||||
|
return Result.failed("租户服务不可用");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -109,4 +109,11 @@ public interface ISysUserService extends ISuperService<SysUser> {
|
|||||||
* 删除用户
|
* 删除用户
|
||||||
*/
|
*/
|
||||||
boolean delUser(Long id);
|
boolean delUser(Long id);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 彻底删除用户及其所有相关数据
|
||||||
|
* @param userId 用户ID
|
||||||
|
* @return 删除结果
|
||||||
|
*/
|
||||||
|
boolean completelyDeleteUser(Long userId);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,109 @@
|
|||||||
|
package com.central.user.service;
|
||||||
|
|
||||||
|
import com.central.common.model.Result;
|
||||||
|
|
||||||
|
import java.util.List;
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 租户服务接口
|
||||||
|
* 统一管理系统中所有租户相关功能
|
||||||
|
*
|
||||||
|
* @author lsl
|
||||||
|
* @date 2024-12-19
|
||||||
|
*/
|
||||||
|
public interface ITenantService {
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 设置当前租户
|
||||||
|
* @param tenantId 租户ID
|
||||||
|
* @return 设置结果
|
||||||
|
*/
|
||||||
|
Result<String> setCurrentTenant(String tenantId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取当前租户
|
||||||
|
* @return 租户ID
|
||||||
|
*/
|
||||||
|
String getCurrentTenant();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 清除当前租户
|
||||||
|
* @return 清除结果
|
||||||
|
*/
|
||||||
|
Result<String> clearCurrentTenant();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检查是否为 webApp 租户
|
||||||
|
* @return 是否为 webApp 租户
|
||||||
|
*/
|
||||||
|
boolean isWebAppTenant();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取租户信息
|
||||||
|
* @return 租户信息
|
||||||
|
*/
|
||||||
|
Map<String, Object> getTenantInfo();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 验证租户权限
|
||||||
|
* @param tenantId 租户ID
|
||||||
|
* @param operation 操作类型
|
||||||
|
* @return 权限验证结果
|
||||||
|
*/
|
||||||
|
Result<Object> validateTenantPermission(String tenantId, String operation);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 切换租户
|
||||||
|
* @param targetTenantId 目标租户ID
|
||||||
|
* @return 切换结果
|
||||||
|
*/
|
||||||
|
Result<Object> switchTenant(String targetTenantId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取租户状态
|
||||||
|
* @return 租户状态
|
||||||
|
*/
|
||||||
|
Map<String, Object> getTenantStatus();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取所有租户列表
|
||||||
|
* @return 租户列表
|
||||||
|
*/
|
||||||
|
Result<List<Map<String, Object>>> getAllTenants();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取租户统计信息
|
||||||
|
* @return 统计信息
|
||||||
|
*/
|
||||||
|
Result<Map<String, Object>> getTenantStatistics();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 检查租户是否存在
|
||||||
|
* @param tenantId 租户ID
|
||||||
|
* @return 是否存在
|
||||||
|
*/
|
||||||
|
boolean isTenantExists(String tenantId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 创建新租户
|
||||||
|
* @param tenantInfo 租户信息
|
||||||
|
* @return 创建结果
|
||||||
|
*/
|
||||||
|
Result<String> createTenant(Map<String, Object> tenantInfo);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 删除租户
|
||||||
|
* @param tenantId 租户ID
|
||||||
|
* @return 删除结果
|
||||||
|
*/
|
||||||
|
Result<String> deleteTenant(String tenantId);
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 更新租户信息
|
||||||
|
* @param tenantId 租户ID
|
||||||
|
* @param tenantInfo 租户信息
|
||||||
|
* @return 更新结果
|
||||||
|
*/
|
||||||
|
Result<String> updateTenant(String tenantId, Map<String, Object> tenantInfo);
|
||||||
|
}
|
||||||
+2
-2
@@ -23,7 +23,7 @@ public interface WechatConfigService extends IService<WechatConfig> {
|
|||||||
* @param tenantId 商户ID
|
* @param tenantId 商户ID
|
||||||
* @return 微信配置
|
* @return 微信配置
|
||||||
*/
|
*/
|
||||||
WechatConfig getConfig(String type, String tenantId);
|
WechatConfig getConfigByTypeTenantId(String type, String tenantId);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取微信配置
|
* 获取微信配置
|
||||||
@@ -31,7 +31,7 @@ public interface WechatConfigService extends IService<WechatConfig> {
|
|||||||
* @param appId 商户ID
|
* @param appId 商户ID
|
||||||
* @return 微信配置
|
* @return 微信配置
|
||||||
*/
|
*/
|
||||||
WechatConfig getConfig(String appId);
|
WechatConfig getConfigByAppIdAndType(String appId, String type);
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 获取微信配置
|
* 获取微信配置
|
||||||
|
|||||||
+122
-8
@@ -1,13 +1,22 @@
|
|||||||
package com.central.user.service.impl;
|
package com.central.user.service.impl;
|
||||||
|
|
||||||
import cn.hutool.core.util.StrUtil;
|
import cn.hutool.core.util.StrUtil;
|
||||||
|
import cn.hutool.core.util.ObjectUtil;
|
||||||
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
|
||||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||||
import com.central.common.constant.CommonConstant;
|
import com.central.common.constant.CommonConstant;
|
||||||
import com.central.common.context.LoginUserContextHolder;
|
import com.central.common.context.LoginUserContextHolder;
|
||||||
import com.central.common.lock.DistributedLock;
|
import com.central.common.lock.DistributedLock;
|
||||||
import com.central.common.model.*;
|
import com.central.common.model.PageResult;
|
||||||
|
import com.central.common.model.Result;
|
||||||
|
import com.central.common.model.SysRole;
|
||||||
|
import com.central.common.model.SysUser;
|
||||||
|
import com.central.common.model.UserType;
|
||||||
|
import com.central.common.model.SuperEntity;
|
||||||
|
import com.central.common.model.SysMenu;
|
||||||
import com.central.common.service.impl.SuperServiceImpl;
|
import com.central.common.service.impl.SuperServiceImpl;
|
||||||
|
import com.central.user.feign.DeviceCenterService;
|
||||||
|
import com.central.user.feign.OrderCenterService;
|
||||||
import com.central.user.mapper.SysRoleMenuMapper;
|
import com.central.user.mapper.SysRoleMenuMapper;
|
||||||
import com.central.user.mapper.SysUserMapper;
|
import com.central.user.mapper.SysUserMapper;
|
||||||
import com.central.user.model.SysRoleUser;
|
import com.central.user.model.SysRoleUser;
|
||||||
@@ -16,7 +25,6 @@ import com.central.user.service.ISysRoleUserService;
|
|||||||
import com.central.user.service.ISysUserService;
|
import com.central.user.service.ISysUserService;
|
||||||
import lombok.extern.slf4j.Slf4j;
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.apache.commons.collections4.MapUtils;
|
import org.apache.commons.collections4.MapUtils;
|
||||||
import org.apache.commons.lang3.ObjectUtils;
|
|
||||||
import org.apache.commons.lang3.StringUtils;
|
import org.apache.commons.lang3.StringUtils;
|
||||||
import org.springframework.beans.BeanUtils;
|
import org.springframework.beans.BeanUtils;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
@@ -24,13 +32,14 @@ import org.springframework.security.crypto.password.PasswordEncoder;
|
|||||||
import org.springframework.stereotype.Service;
|
import org.springframework.stereotype.Service;
|
||||||
import org.springframework.transaction.annotation.Transactional;
|
import org.springframework.transaction.annotation.Transactional;
|
||||||
import org.springframework.util.CollectionUtils;
|
import org.springframework.util.CollectionUtils;
|
||||||
|
import org.springframework.util.ObjectUtils;
|
||||||
|
|
||||||
import javax.annotation.Resource;
|
import javax.annotation.Resource;
|
||||||
import java.util.*;
|
import java.util.*;
|
||||||
import java.util.stream.Collectors;
|
import java.util.stream.Collectors;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @author 作者 owen E-mail: 624191343@qq.com
|
* @author zlt
|
||||||
*/
|
*/
|
||||||
@Slf4j
|
@Slf4j
|
||||||
@Service
|
@Service
|
||||||
@@ -49,6 +58,12 @@ public class SysUserServiceImpl extends SuperServiceImpl<SysUserMapper, SysUser>
|
|||||||
@Autowired
|
@Autowired
|
||||||
private DistributedLock lock;
|
private DistributedLock lock;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private OrderCenterService orderCenterService;
|
||||||
|
|
||||||
|
@Resource
|
||||||
|
private DeviceCenterService deviceCenterService;
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public SysUser findByUsername(String username) {
|
public SysUser findByUsername(String username) {
|
||||||
SysUser sysUser = this.selectByUsername(username);
|
SysUser sysUser = this.selectByUsername(username);
|
||||||
@@ -76,7 +91,7 @@ public class SysUserServiceImpl extends SuperServiceImpl<SysUserMapper, SysUser>
|
|||||||
SysUser sysUser = this.selectByOpenId(wxOpenid);
|
SysUser sysUser = this.selectByOpenId(wxOpenid);
|
||||||
|
|
||||||
// 如果用户存在,更新 unionId(无论是否为空都更新)
|
// 如果用户存在,更新 unionId(无论是否为空都更新)
|
||||||
if (ObjectUtils.isNotEmpty(sysUser)) {
|
if (ObjectUtil.isNotEmpty(sysUser)) {
|
||||||
if (StringUtils.isNotEmpty(unionId)) {
|
if (StringUtils.isNotEmpty(unionId)) {
|
||||||
sysUser.setUnionId(unionId);
|
sysUser.setUnionId(unionId);
|
||||||
log.info("更新用户unionId: {}", unionId);
|
log.info("更新用户unionId: {}", unionId);
|
||||||
@@ -132,7 +147,7 @@ public class SysUserServiceImpl extends SuperServiceImpl<SysUserMapper, SysUser>
|
|||||||
@Override
|
@Override
|
||||||
public SysUser selectByUsername(String username) {
|
public SysUser selectByUsername(String username) {
|
||||||
List<SysUser> users = baseMapper.selectList(
|
List<SysUser> users = baseMapper.selectList(
|
||||||
new QueryWrapper<SysUser>().eq("username", username)
|
new QueryWrapper<SysUser>().eq("username", username).eq("is_del", 0)
|
||||||
);
|
);
|
||||||
return getUser(users);
|
return getUser(users);
|
||||||
}
|
}
|
||||||
@@ -145,7 +160,7 @@ public class SysUserServiceImpl extends SuperServiceImpl<SysUserMapper, SysUser>
|
|||||||
@Override
|
@Override
|
||||||
public SysUser selectByMobile(String mobile) {
|
public SysUser selectByMobile(String mobile) {
|
||||||
List<SysUser> users = baseMapper.selectList(
|
List<SysUser> users = baseMapper.selectList(
|
||||||
new QueryWrapper<SysUser>().eq("mobile", mobile)
|
new QueryWrapper<SysUser>().eq("mobile", mobile).eq("is_del", 0)
|
||||||
);
|
);
|
||||||
return getUser(users);
|
return getUser(users);
|
||||||
}
|
}
|
||||||
@@ -158,7 +173,7 @@ public class SysUserServiceImpl extends SuperServiceImpl<SysUserMapper, SysUser>
|
|||||||
@Override
|
@Override
|
||||||
public SysUser selectByOpenId(String openId) {
|
public SysUser selectByOpenId(String openId) {
|
||||||
List<SysUser> users = baseMapper.selectList(
|
List<SysUser> users = baseMapper.selectList(
|
||||||
new QueryWrapper<SysUser>().eq("open_id", openId)
|
new QueryWrapper<SysUser>().eq("open_id", openId).eq("is_del", 0)
|
||||||
);
|
);
|
||||||
return getUser(users);
|
return getUser(users);
|
||||||
}
|
}
|
||||||
@@ -218,7 +233,7 @@ public class SysUserServiceImpl extends SuperServiceImpl<SysUserMapper, SysUser>
|
|||||||
List<Long> userIds = list.stream().map(SysUser::getId).collect(Collectors.toList());
|
List<Long> userIds = list.stream().map(SysUser::getId).collect(Collectors.toList());
|
||||||
|
|
||||||
List<SysRole> sysRoles = roleUserService.findRolesByUserIds(userIds);
|
List<SysRole> sysRoles = roleUserService.findRolesByUserIds(userIds);
|
||||||
list.forEach(u -> u.setRoles(sysRoles.stream().filter(r -> !ObjectUtils.notEqual(u.getId(), r.getUserId()))
|
list.forEach(u -> u.setRoles(sysRoles.stream().filter(r -> !Objects.equals(u.getId(), r.getUserId()))
|
||||||
.collect(Collectors.toList())));
|
.collect(Collectors.toList())));
|
||||||
}
|
}
|
||||||
return PageResult.<SysUser>builder().data(list).resp_code(0).count(total).build();
|
return PageResult.<SysUser>builder().data(list).resp_code(0).count(total).build();
|
||||||
@@ -282,6 +297,105 @@ public class SysUserServiceImpl extends SuperServiceImpl<SysUserMapper, SysUser>
|
|||||||
return baseMapper.deleteById(id) > 0;
|
return baseMapper.deleteById(id) > 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Transactional(rollbackFor = Exception.class)
|
||||||
|
@Override
|
||||||
|
public boolean completelyDeleteUser(Long userId) {
|
||||||
|
try {
|
||||||
|
log.info("开始彻底删除用户及其相关数据,用户ID: {}", userId);
|
||||||
|
|
||||||
|
// 1. 删除用户角色关联
|
||||||
|
roleUserService.deleteUserRole(userId, null);
|
||||||
|
log.info("已删除用户角色关联,用户ID: {}", userId);
|
||||||
|
|
||||||
|
// 2. 删除用户基本信息(物理删除,不使用逻辑删除)
|
||||||
|
int userDeleteResult = baseMapper.deleteById(userId);
|
||||||
|
log.info("已删除用户基本信息,用户ID: {}, 删除结果: {}", userId, userDeleteResult);
|
||||||
|
|
||||||
|
// 3. 清理订单中心相关数据 @TODO
|
||||||
|
/*try {
|
||||||
|
log.info("开始清理订单中心用户相关数据,用户ID: {}", userId);
|
||||||
|
|
||||||
|
// 删除用户订单
|
||||||
|
Result<String> orderResult = orderCenterService.deleteUserOrders(userId);
|
||||||
|
if (orderResult.getResp_code() == 0) {
|
||||||
|
log.info("已删除用户订单数据,用户ID: {}", userId);
|
||||||
|
} else {
|
||||||
|
log.warn("删除用户订单数据失败,用户ID: {}, 错误: {}", userId, orderResult.getResp_msg());
|
||||||
|
}
|
||||||
|
|
||||||
|
// 删除用户订单文件
|
||||||
|
Result<String> orderFileResult = orderCenterService.deleteUserOrderFiles(userId);
|
||||||
|
if (orderFileResult.getResp_code() == 0) {
|
||||||
|
log.info("已删除用户订单文件,用户ID: {}", userId);
|
||||||
|
} else {
|
||||||
|
log.warn("删除用户订单文件失败,用户ID: {}, 错误: {}", userId, orderFileResult.getResp_msg());
|
||||||
|
}
|
||||||
|
|
||||||
|
// 删除用户消息
|
||||||
|
Result<String> messageResult = orderCenterService.deleteUserMessages(userId);
|
||||||
|
if (messageResult.getResp_code() == 0) {
|
||||||
|
log.info("已删除用户消息,用户ID: {}", userId);
|
||||||
|
} else {
|
||||||
|
log.warn("删除用户消息失败,用户ID: {}, 错误: {}", userId, messageResult.getResp_msg());
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("清理订单中心数据失败,用户ID: {}", userId, e);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 4. 清理设备中心相关数据
|
||||||
|
try {
|
||||||
|
log.info("开始清理设备中心用户相关数据,用户ID: {}", userId);
|
||||||
|
|
||||||
|
String userIdStr = String.valueOf(userId);
|
||||||
|
|
||||||
|
// 删除用户设备
|
||||||
|
Result<String> deviceResult = deviceCenterService.deleteUserDevices(userIdStr);
|
||||||
|
if (deviceResult.getResp_code() == 0) {
|
||||||
|
log.info("已删除用户设备数据,用户ID: {}", userId);
|
||||||
|
} else {
|
||||||
|
log.warn("删除用户设备数据失败,用户ID: {}, 错误: {}", userId, deviceResult.getResp_msg());
|
||||||
|
}
|
||||||
|
|
||||||
|
// 删除用户航线文件
|
||||||
|
Result<String> waylineFileResult = deviceCenterService.deleteUserWaylineFiles(userIdStr);
|
||||||
|
if (waylineFileResult.getResp_code() == 0) {
|
||||||
|
log.info("已删除用户航线文件,用户ID: {}", userId);
|
||||||
|
} else {
|
||||||
|
log.warn("删除用户航线文件失败,用户ID: {}, 错误: {}", userId, waylineFileResult.getResp_msg());
|
||||||
|
}
|
||||||
|
|
||||||
|
// 删除用户任务记录
|
||||||
|
Result<String> waylineJobResult = deviceCenterService.deleteUserWaylineJobs(userIdStr);
|
||||||
|
if (waylineJobResult.getResp_code() == 0) {
|
||||||
|
log.info("已删除用户任务记录,用户ID: {}", userId);
|
||||||
|
} else {
|
||||||
|
log.warn("删除用户任务记录失败,用户ID: {}, 错误: {}", userId, waylineJobResult.getResp_msg());
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("清理设备中心数据失败,用户ID: {}", userId, e);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 5. 清理日志中心相关数据(通过数据库直接清理)
|
||||||
|
try {
|
||||||
|
log.info("开始清理日志中心用户相关数据,用户ID: {}", userId);
|
||||||
|
// 这里可以通过JdbcTemplate直接清理日志数据
|
||||||
|
// 由于日志中心可能没有提供清理接口,我们可以通过数据库直接清理
|
||||||
|
// TODO: 添加日志中心数据清理逻辑
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("清理日志中心数据失败,用户ID: {}", userId, e);
|
||||||
|
}*/
|
||||||
|
|
||||||
|
log.info("用户彻底删除完成,用户ID: {}", userId);
|
||||||
|
return userDeleteResult > 0;
|
||||||
|
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("彻底删除用户失败,用户ID: {}", userId, e);
|
||||||
|
throw new RuntimeException("彻底删除用户失败", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public List<SysUserExcel> findAllUsers(Map<String, Object> params) {
|
public List<SysUserExcel> findAllUsers(Map<String, Object> params) {
|
||||||
List<SysUserExcel> sysUserExcels = new ArrayList<>();
|
List<SysUserExcel> sysUserExcels = new ArrayList<>();
|
||||||
|
|||||||
+255
@@ -0,0 +1,255 @@
|
|||||||
|
package com.central.user.service.impl;
|
||||||
|
|
||||||
|
import com.central.common.context.TenantContextHolder;
|
||||||
|
import com.central.common.model.Result;
|
||||||
|
import com.central.user.service.ITenantService;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.util.*;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 租户服务实现类
|
||||||
|
* 统一管理系统中所有租户相关功能
|
||||||
|
*
|
||||||
|
* @author lsl
|
||||||
|
* @date 2024-12-19
|
||||||
|
*/
|
||||||
|
@Slf4j
|
||||||
|
@Service
|
||||||
|
public class TenantServiceImpl implements ITenantService {
|
||||||
|
|
||||||
|
// 模拟租户数据存储(实际项目中应该使用数据库)
|
||||||
|
private static final Map<String, Map<String, Object>> TENANT_STORE = new HashMap<>();
|
||||||
|
|
||||||
|
static {
|
||||||
|
// 初始化默认租户
|
||||||
|
Map<String, Object> webAppTenant = new HashMap<>();
|
||||||
|
webAppTenant.put("tenantId", "webApp");
|
||||||
|
webAppTenant.put("name", "系统管理租户");
|
||||||
|
webAppTenant.put("description", "系统管理租户,可查询所有数据");
|
||||||
|
webAppTenant.put("level", "admin");
|
||||||
|
webAppTenant.put("canQueryAllData", true);
|
||||||
|
webAppTenant.put("createTime", System.currentTimeMillis());
|
||||||
|
TENANT_STORE.put("webApp", webAppTenant);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Result<String> setCurrentTenant(String tenantId) {
|
||||||
|
try {
|
||||||
|
TenantContextHolder.setTenant(tenantId);
|
||||||
|
log.info("设置当前租户: {}", tenantId);
|
||||||
|
return Result.succeed(tenantId, "租户设置成功");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("设置租户失败", e);
|
||||||
|
return Result.failed("设置租户失败:" + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public String getCurrentTenant() {
|
||||||
|
return TenantContextHolder.getTenant();
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Result<String> clearCurrentTenant() {
|
||||||
|
try {
|
||||||
|
TenantContextHolder.clear();
|
||||||
|
log.info("清除当前租户");
|
||||||
|
return Result.succeed("", "租户清除成功");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("清除租户失败", e);
|
||||||
|
return Result.failed("清除租户失败:" + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isWebAppTenant() {
|
||||||
|
String tenant = TenantContextHolder.getTenant();
|
||||||
|
return "webApp".equals(tenant);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Map<String, Object> getTenantInfo() {
|
||||||
|
String currentTenant = TenantContextHolder.getTenant();
|
||||||
|
boolean isWebApp = "webApp".equals(currentTenant);
|
||||||
|
|
||||||
|
Map<String, Object> tenantInfo = new HashMap<>();
|
||||||
|
tenantInfo.put("tenantId", currentTenant);
|
||||||
|
tenantInfo.put("webAppTenant", isWebApp);
|
||||||
|
tenantInfo.put("canQueryAllData", isWebApp);
|
||||||
|
tenantInfo.put("description", isWebApp ? "系统管理租户,可查询所有数据" : "普通租户,只能查询自己的数据");
|
||||||
|
tenantInfo.put("level", isWebApp ? "admin" : "user");
|
||||||
|
|
||||||
|
// 如果租户存在于存储中,添加额外信息
|
||||||
|
if (TENANT_STORE.containsKey(currentTenant)) {
|
||||||
|
tenantInfo.putAll(TENANT_STORE.get(currentTenant));
|
||||||
|
}
|
||||||
|
|
||||||
|
return tenantInfo;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Result<Object> validateTenantPermission(String tenantId, String operation) {
|
||||||
|
try {
|
||||||
|
Map<String, Object> result = new HashMap<>();
|
||||||
|
result.put("tenantId", tenantId);
|
||||||
|
result.put("operation", operation);
|
||||||
|
|
||||||
|
// webApp 租户拥有所有权限
|
||||||
|
if ("webApp".equals(tenantId)) {
|
||||||
|
result.put("hasPermission", true);
|
||||||
|
result.put("message", "webApp 租户拥有所有权限");
|
||||||
|
result.put("level", "admin");
|
||||||
|
} else {
|
||||||
|
// 其他租户只能操作自己的数据
|
||||||
|
result.put("hasPermission", true);
|
||||||
|
result.put("message", "租户只能操作自己的数据");
|
||||||
|
result.put("level", "user");
|
||||||
|
}
|
||||||
|
|
||||||
|
log.info("验证租户权限: {}", result);
|
||||||
|
return Result.succeed(result, "权限验证成功");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("验证租户权限失败", e);
|
||||||
|
return Result.failed("权限验证失败:" + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Result<Object> switchTenant(String targetTenantId) {
|
||||||
|
try {
|
||||||
|
String oldTenant = TenantContextHolder.getTenant();
|
||||||
|
|
||||||
|
// 设置新租户
|
||||||
|
TenantContextHolder.setTenant(targetTenantId);
|
||||||
|
|
||||||
|
Map<String, Object> result = new HashMap<>();
|
||||||
|
result.put("oldTenant", oldTenant);
|
||||||
|
result.put("newTenant", targetTenantId);
|
||||||
|
result.put("switchTime", System.currentTimeMillis());
|
||||||
|
|
||||||
|
log.info("租户切换成功: {} -> {}", oldTenant, targetTenantId);
|
||||||
|
return Result.succeed(result, "租户切换成功");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("租户切换失败", e);
|
||||||
|
return Result.failed("租户切换失败:" + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Map<String, Object> getTenantStatus() {
|
||||||
|
String currentTenant = TenantContextHolder.getTenant();
|
||||||
|
boolean isWebApp = "webApp".equals(currentTenant);
|
||||||
|
|
||||||
|
Map<String, Object> status = new HashMap<>();
|
||||||
|
status.put("currentTenant", currentTenant);
|
||||||
|
status.put("isWebApp", isWebApp);
|
||||||
|
status.put("canQueryAllData", isWebApp);
|
||||||
|
status.put("timestamp", System.currentTimeMillis());
|
||||||
|
status.put("status", "active");
|
||||||
|
|
||||||
|
return status;
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Result<List<Map<String, Object>>> getAllTenants() {
|
||||||
|
try {
|
||||||
|
List<Map<String, Object>> tenants = new ArrayList<>(TENANT_STORE.values());
|
||||||
|
log.info("获取所有租户,数量: {}", tenants.size());
|
||||||
|
return Result.succeed(tenants, "获取租户列表成功");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("获取租户列表失败", e);
|
||||||
|
return Result.failed("获取租户列表失败:" + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Result<Map<String, Object>> getTenantStatistics() {
|
||||||
|
try {
|
||||||
|
Map<String, Object> statistics = new HashMap<>();
|
||||||
|
statistics.put("totalTenants", TENANT_STORE.size());
|
||||||
|
statistics.put("webAppTenants", TENANT_STORE.containsKey("webApp") ? 1 : 0);
|
||||||
|
statistics.put("regularTenants", TENANT_STORE.size() - (TENANT_STORE.containsKey("webApp") ? 1 : 0));
|
||||||
|
statistics.put("lastUpdateTime", System.currentTimeMillis());
|
||||||
|
|
||||||
|
log.info("获取租户统计信息: {}", statistics);
|
||||||
|
return Result.succeed(statistics, "获取统计信息成功");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("获取租户统计信息失败", e);
|
||||||
|
return Result.failed("获取统计信息失败:" + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean isTenantExists(String tenantId) {
|
||||||
|
return TENANT_STORE.containsKey(tenantId);
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Result<String> createTenant(Map<String, Object> tenantInfo) {
|
||||||
|
try {
|
||||||
|
String tenantId = (String) tenantInfo.get("tenantId");
|
||||||
|
if (tenantId == null || tenantId.trim().isEmpty()) {
|
||||||
|
return Result.failed("租户ID不能为空");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isTenantExists(tenantId)) {
|
||||||
|
return Result.failed("租户已存在");
|
||||||
|
}
|
||||||
|
|
||||||
|
// 设置默认值
|
||||||
|
tenantInfo.put("createTime", System.currentTimeMillis());
|
||||||
|
tenantInfo.put("level", "user");
|
||||||
|
tenantInfo.put("canQueryAllData", false);
|
||||||
|
|
||||||
|
TENANT_STORE.put(tenantId, new HashMap<>(tenantInfo));
|
||||||
|
|
||||||
|
log.info("创建新租户成功: {}", tenantId);
|
||||||
|
return Result.succeed(tenantId, "租户创建成功");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("创建租户失败", e);
|
||||||
|
return Result.failed("创建租户失败:" + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Result<String> deleteTenant(String tenantId) {
|
||||||
|
try {
|
||||||
|
if ("webApp".equals(tenantId)) {
|
||||||
|
return Result.failed("不能删除系统管理租户");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isTenantExists(tenantId)) {
|
||||||
|
return Result.failed("租户不存在");
|
||||||
|
}
|
||||||
|
|
||||||
|
TENANT_STORE.remove(tenantId);
|
||||||
|
|
||||||
|
log.info("删除租户成功: {}", tenantId);
|
||||||
|
return Result.succeed(tenantId, "租户删除成功");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("删除租户失败", e);
|
||||||
|
return Result.failed("删除租户失败:" + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Result<String> updateTenant(String tenantId, Map<String, Object> tenantInfo) {
|
||||||
|
try {
|
||||||
|
if (!isTenantExists(tenantId)) {
|
||||||
|
return Result.failed("租户不存在");
|
||||||
|
}
|
||||||
|
|
||||||
|
Map<String, Object> existingTenant = TENANT_STORE.get(tenantId);
|
||||||
|
existingTenant.putAll(tenantInfo);
|
||||||
|
existingTenant.put("updateTime", System.currentTimeMillis());
|
||||||
|
|
||||||
|
log.info("更新租户信息成功: {}", tenantId);
|
||||||
|
return Result.succeed(tenantId, "租户信息更新成功");
|
||||||
|
} catch (Exception e) {
|
||||||
|
log.error("更新租户信息失败", e);
|
||||||
|
return Result.failed("更新租户信息失败:" + e.getMessage());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+6
-3
@@ -31,7 +31,7 @@ public class WechatConfigServiceImpl extends ServiceImpl<WechatConfigMapper, Wec
|
|||||||
|
|
||||||
@Override
|
@Override
|
||||||
// @Cacheable(value = CACHE_NAME, key = CACHE_KEY_PATTERN, unless = "#result == null")
|
// @Cacheable(value = CACHE_NAME, key = CACHE_KEY_PATTERN, unless = "#result == null")
|
||||||
public WechatConfig getConfig(String type, String tenantId) {
|
public WechatConfig getConfigByTypeTenantId(String type, String tenantId) {
|
||||||
return getOne(new LambdaQueryWrapper<WechatConfig>()
|
return getOne(new LambdaQueryWrapper<WechatConfig>()
|
||||||
.eq(WechatConfig::getType, type)
|
.eq(WechatConfig::getType, type)
|
||||||
.eq(WechatConfig::getTenantId, tenantId)
|
.eq(WechatConfig::getTenantId, tenantId)
|
||||||
@@ -39,9 +39,10 @@ public class WechatConfigServiceImpl extends ServiceImpl<WechatConfigMapper, Wec
|
|||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
public WechatConfig getConfig(String appId) {
|
public WechatConfig getConfigByAppIdAndType(String appId, String type) {
|
||||||
return getOne(new LambdaQueryWrapper<WechatConfig>()
|
return getOne(new LambdaQueryWrapper<WechatConfig>()
|
||||||
.eq(WechatConfig::getAppId, appId)
|
.eq(WechatConfig::getAppId, appId)
|
||||||
|
.eq(WechatConfig::getType,type)
|
||||||
.eq(WechatConfig::getStatus, 1));
|
.eq(WechatConfig::getStatus, 1));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -93,7 +94,9 @@ public class WechatConfigServiceImpl extends ServiceImpl<WechatConfigMapper, Wec
|
|||||||
return getOne(new LambdaQueryWrapper<WechatConfig>()
|
return getOne(new LambdaQueryWrapper<WechatConfig>()
|
||||||
.eq(WechatConfig::getSubMchId, subMchId)
|
.eq(WechatConfig::getSubMchId, subMchId)
|
||||||
.eq(WechatConfig::getIsServiceMode, true)
|
.eq(WechatConfig::getIsServiceMode, true)
|
||||||
.eq(WechatConfig::getStatus, 1));
|
.eq(WechatConfig::getStatus, 1)
|
||||||
|
.orderByDesc(WechatConfig::getId) // 按ID倒序,取最新的
|
||||||
|
.last("LIMIT 1")); // 明确限制只取第一条
|
||||||
}
|
}
|
||||||
|
|
||||||
@Override
|
@Override
|
||||||
|
|||||||
@@ -39,7 +39,7 @@ zlt:
|
|||||||
- sys_user
|
- sys_user
|
||||||
- sys_role_user
|
- sys_role_user
|
||||||
- sys_role_menu
|
- sys_role_menu
|
||||||
- mini_app_config
|
- wechat_config
|
||||||
ignoreSqls:
|
ignoreSqls:
|
||||||
# 用户关联角色时,显示所有角色
|
# 用户关联角色时,显示所有角色
|
||||||
- com.central.user.mapper.SysRoleMapper.findAll
|
- com.central.user.mapper.SysRoleMapper.findAll
|
||||||
|
|||||||
@@ -4,10 +4,10 @@ server:
|
|||||||
spring:
|
spring:
|
||||||
application:
|
application:
|
||||||
name: user-center
|
name: user-center
|
||||||
# cloud:
|
cloud:
|
||||||
# nacos:
|
nacos:
|
||||||
# discovery:
|
discovery:
|
||||||
# ip: 124.222.128.40
|
ip: 124.222.128.40
|
||||||
# cloud:
|
# cloud:
|
||||||
# nacos:
|
# nacos:
|
||||||
# discovery:
|
# discovery:
|
||||||
|
|||||||
@@ -21,6 +21,7 @@
|
|||||||
<module>zlt-common-core</module>
|
<module>zlt-common-core</module>
|
||||||
<module>zlt-elasticsearch-spring-boot-starter</module>
|
<module>zlt-elasticsearch-spring-boot-starter</module>
|
||||||
<module>zlt-oss-spring-boot-starter</module>
|
<module>zlt-oss-spring-boot-starter</module>
|
||||||
|
<module>zlt-sms-spring-boot-starter</module>
|
||||||
<module>zlt-zookeeper-spring-boot-starter</module>
|
<module>zlt-zookeeper-spring-boot-starter</module>
|
||||||
<module>zlt-wechat-common-core</module>
|
<module>zlt-wechat-common-core</module>
|
||||||
<module>zlt-wechat-spring-boot-starter</module>
|
<module>zlt-wechat-spring-boot-starter</module>
|
||||||
|
|||||||
+12
-1
@@ -9,6 +9,7 @@ import jakarta.servlet.FilterChain;
|
|||||||
import jakarta.servlet.ServletException;
|
import jakarta.servlet.ServletException;
|
||||||
import jakarta.servlet.http.HttpServletRequest;
|
import jakarta.servlet.http.HttpServletRequest;
|
||||||
import jakarta.servlet.http.HttpServletResponse;
|
import jakarta.servlet.http.HttpServletResponse;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
|
||||||
import org.springframework.web.filter.OncePerRequestFilter;
|
import org.springframework.web.filter.OncePerRequestFilter;
|
||||||
|
|
||||||
@@ -20,6 +21,7 @@ import java.io.IOException;
|
|||||||
* @author zlt
|
* @author zlt
|
||||||
* @date 2019/9/15
|
* @date 2019/9/15
|
||||||
*/
|
*/
|
||||||
|
@Slf4j
|
||||||
@ConditionalOnClass(Filter.class)
|
@ConditionalOnClass(Filter.class)
|
||||||
public class TenantFilter extends OncePerRequestFilter {
|
public class TenantFilter extends OncePerRequestFilter {
|
||||||
@Override
|
@Override
|
||||||
@@ -31,13 +33,22 @@ public class TenantFilter extends OncePerRequestFilter {
|
|||||||
if (StrUtil.isEmpty(tenantId)) {
|
if (StrUtil.isEmpty(tenantId)) {
|
||||||
tenantId = request.getHeader(SecurityConstants.TENANT_HEADER);
|
tenantId = request.getHeader(SecurityConstants.TENANT_HEADER);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
log.debug("请求URL: {}, 租户ID: {}", request.getRequestURI(), tenantId);
|
||||||
|
|
||||||
//保存租户id
|
//保存租户id
|
||||||
if (StrUtil.isNotEmpty(tenantId)) {
|
if (StrUtil.isNotEmpty(tenantId) && null != tenantId) {
|
||||||
TenantContextHolder.setTenant(tenantId);
|
TenantContextHolder.setTenant(tenantId);
|
||||||
|
log.debug("设置租户上下文: {}", tenantId);
|
||||||
|
} else {
|
||||||
|
TenantContextHolder.setTenant("webApp");
|
||||||
|
log.debug("未找到租户ID,使用默认租户");
|
||||||
}
|
}
|
||||||
|
|
||||||
filterChain.doFilter(request, response);
|
filterChain.doFilter(request, response);
|
||||||
} finally {
|
} finally {
|
||||||
|
String currentTenant = TenantContextHolder.getTenant();
|
||||||
|
log.debug("清理租户上下文: {}", currentTenant);
|
||||||
TenantContextHolder.clear();
|
TenantContextHolder.clear();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+36
-5
@@ -5,8 +5,8 @@ import com.central.common.context.LoginUserContextHolder;
|
|||||||
import com.central.common.context.TenantContextHolder;
|
import com.central.common.context.TenantContextHolder;
|
||||||
import com.central.common.model.LoginAppUser;
|
import com.central.common.model.LoginAppUser;
|
||||||
import com.central.common.properties.TenantProperties;
|
import com.central.common.properties.TenantProperties;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import net.sf.jsqlparser.expression.Expression;
|
import net.sf.jsqlparser.expression.Expression;
|
||||||
import net.sf.jsqlparser.expression.NullValue;
|
|
||||||
import net.sf.jsqlparser.expression.StringValue;
|
import net.sf.jsqlparser.expression.StringValue;
|
||||||
import org.springframework.beans.factory.annotation.Autowired;
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||||
@@ -18,6 +18,7 @@ import org.springframework.context.annotation.Bean;
|
|||||||
* @author zlt
|
* @author zlt
|
||||||
* @date 2019/8/5
|
* @date 2019/8/5
|
||||||
*/
|
*/
|
||||||
|
@Slf4j
|
||||||
@EnableConfigurationProperties(TenantProperties.class)
|
@EnableConfigurationProperties(TenantProperties.class)
|
||||||
public class TenantAutoConfigure {
|
public class TenantAutoConfigure {
|
||||||
@Autowired
|
@Autowired
|
||||||
@@ -31,17 +32,29 @@ public class TenantAutoConfigure {
|
|||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public Expression getTenantId() {
|
public Expression getTenantId() {
|
||||||
|
log.debug("=== 开始处理租户过滤 ===");
|
||||||
|
|
||||||
// 判断当前用户是否为超级管理员
|
// 判断当前用户是否为超级管理员
|
||||||
if (isSuperAdmin()) {
|
if (isSuperAdmin()) {
|
||||||
// 超级管理员返回Null,不加租户条件
|
// 超级管理员返回Null,不加租户条件
|
||||||
return new NullValue();
|
log.debug("超级管理员用户,跳过租户过滤");
|
||||||
|
return new StringValue(""); // 返回空字符串,避免NULL条件
|
||||||
}
|
}
|
||||||
|
|
||||||
String tenant = TenantContextHolder.getTenant();
|
String tenant = TenantContextHolder.getTenant();
|
||||||
|
log.debug("当前租户: {}", tenant);
|
||||||
|
|
||||||
if (tenant != null) {
|
if (tenant != null) {
|
||||||
|
// webApp 租户可以查询所有数据,返回空字符串
|
||||||
|
if ("webApp".equals(tenant)) {
|
||||||
|
log.debug("webApp租户,跳过租户过滤,可以查询所有数据");
|
||||||
|
return new StringValue(""); // 返回空字符串,避免NULL条件
|
||||||
|
}
|
||||||
|
log.debug("普通租户: {},添加租户过滤条件", tenant);
|
||||||
return new StringValue(TenantContextHolder.getTenant());
|
return new StringValue(TenantContextHolder.getTenant());
|
||||||
}
|
}
|
||||||
return new NullValue();
|
log.debug("无租户信息,跳过租户过滤");
|
||||||
|
return new StringValue(""); // 返回空字符串,避免NULL条件
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -50,9 +63,23 @@ public class TenantAutoConfigure {
|
|||||||
*/
|
*/
|
||||||
@Override
|
@Override
|
||||||
public boolean ignoreTable(String tableName) {
|
public boolean ignoreTable(String tableName) {
|
||||||
return tenantProperties.getIgnoreTables().stream().anyMatch(
|
// 获取当前租户
|
||||||
|
String tenant = TenantContextHolder.getTenant();
|
||||||
|
|
||||||
|
// webApp 租户或超级管理员跳过所有表的租户过滤
|
||||||
|
if ("webApp".equals(tenant) || isSuperAdmin()) {
|
||||||
|
log.debug("webApp租户或超级管理员,表 {} 被忽略租户过滤", tableName);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 检查配置的忽略表
|
||||||
|
boolean ignore = tenantProperties.getIgnoreTables().stream().anyMatch(
|
||||||
(e) -> e.equalsIgnoreCase(tableName)
|
(e) -> e.equalsIgnoreCase(tableName)
|
||||||
);
|
);
|
||||||
|
if (ignore) {
|
||||||
|
log.debug("表 {} 被忽略租户过滤", tableName);
|
||||||
|
}
|
||||||
|
return ignore;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -62,6 +89,10 @@ public class TenantAutoConfigure {
|
|||||||
// 例如:
|
// 例如:
|
||||||
LoginAppUser user = LoginUserContextHolder.getUser();
|
LoginAppUser user = LoginUserContextHolder.getUser();
|
||||||
//@TODO 暂定admin和mgnt为系统管理员
|
//@TODO 暂定admin和mgnt为系统管理员
|
||||||
return user != null && (user.getUsername().equals("admin") || user.getUsername().equals("mgnt"));
|
boolean isAdmin = user != null && (user.getUsername().equals("admin") || user.getUsername().equals("mgnt"));
|
||||||
|
if (isAdmin) {
|
||||||
|
log.debug("当前用户为超级管理员: {}", user.getUsername());
|
||||||
|
}
|
||||||
|
return isAdmin;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+31
-3
@@ -2,6 +2,7 @@ package com.central.db.interceptor;
|
|||||||
|
|
||||||
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
|
import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
|
||||||
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
|
import com.baomidou.mybatisplus.extension.plugins.inner.TenantLineInnerInterceptor;
|
||||||
|
import lombok.extern.slf4j.Slf4j;
|
||||||
import org.apache.ibatis.executor.Executor;
|
import org.apache.ibatis.executor.Executor;
|
||||||
import org.apache.ibatis.mapping.BoundSql;
|
import org.apache.ibatis.mapping.BoundSql;
|
||||||
import org.apache.ibatis.mapping.MappedStatement;
|
import org.apache.ibatis.mapping.MappedStatement;
|
||||||
@@ -21,6 +22,7 @@ import java.util.List;
|
|||||||
* Blog: http://zlt2000.gitee.io
|
* Blog: http://zlt2000.gitee.io
|
||||||
* Github: https://github.com/zlt2000
|
* Github: https://github.com/zlt2000
|
||||||
*/
|
*/
|
||||||
|
@Slf4j
|
||||||
public class CustomTenantInterceptor extends TenantLineInnerInterceptor {
|
public class CustomTenantInterceptor extends TenantLineInnerInterceptor {
|
||||||
private List<String> ignoreSqls;
|
private List<String> ignoreSqls;
|
||||||
private List<String> noIgnoreSqls;
|
private List<String> noIgnoreSqls;
|
||||||
@@ -34,13 +36,34 @@ public class CustomTenantInterceptor extends TenantLineInnerInterceptor {
|
|||||||
@Override
|
@Override
|
||||||
public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds
|
public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds
|
||||||
, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
|
, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
|
||||||
if (isIgnoreMappedStatement(ms.getId())) {
|
String msId = ms.getId();
|
||||||
|
log.debug("租户拦截器处理SQL: {}", msId);
|
||||||
|
|
||||||
|
// 获取当前租户
|
||||||
|
String tenant = com.central.common.context.TenantContextHolder.getTenant();
|
||||||
|
|
||||||
|
// webApp 租户或超级管理员直接跳过租户过滤
|
||||||
|
if ("webApp".equals(tenant) || isSuperAdmin()) {
|
||||||
|
log.debug("webApp租户或超级管理员,SQL {} 跳过租户过滤", msId);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (isNoIgnoreMappedStatement(ms.getId())) {
|
|
||||||
super.beforeQuery(executor, ms, parameter, rowBounds, resultHandler, boundSql);
|
// 租户为null时跳过租户过滤
|
||||||
|
log.debug("租户ID: {}", tenant);
|
||||||
|
if (null == tenant ) {
|
||||||
|
log.debug("租户为null,SQL {} 跳过租户过滤", msId);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 如果在忽略列表中,直接返回,不执行租户过滤
|
||||||
|
if (isIgnoreMappedStatement(msId)) {
|
||||||
|
log.debug("SQL {} 在忽略列表中,跳过租户过滤", msId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 所有其他SQL都执行租户过滤处理
|
||||||
|
log.debug("SQL {} 执行租户过滤", msId);
|
||||||
|
super.beforeQuery(executor, ms, parameter, rowBounds, resultHandler, boundSql);
|
||||||
}
|
}
|
||||||
|
|
||||||
private boolean isIgnoreMappedStatement(String msId) {
|
private boolean isIgnoreMappedStatement(String msId) {
|
||||||
@@ -50,4 +73,9 @@ public class CustomTenantInterceptor extends TenantLineInnerInterceptor {
|
|||||||
private boolean isNoIgnoreMappedStatement(String msId) {
|
private boolean isNoIgnoreMappedStatement(String msId) {
|
||||||
return noIgnoreSqls.stream().anyMatch((e) -> e.equalsIgnoreCase(msId));
|
return noIgnoreSqls.stream().anyMatch((e) -> e.equalsIgnoreCase(msId));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
private boolean isSuperAdmin() {
|
||||||
|
com.central.common.model.LoginAppUser user = com.central.common.context.LoginUserContextHolder.getUser();
|
||||||
|
return user != null && (user.getUsername().equals("admin") || user.getUsername().equals("mgnt"));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-7
@@ -3,12 +3,7 @@ package com.central.oss.template;
|
|||||||
import com.aliyun.oss.HttpMethod;
|
import com.aliyun.oss.HttpMethod;
|
||||||
import com.aliyun.oss.OSS;
|
import com.aliyun.oss.OSS;
|
||||||
import com.aliyun.oss.OSSClientBuilder;
|
import com.aliyun.oss.OSSClientBuilder;
|
||||||
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
|
import com.aliyun.oss.model.*;
|
||||||
import com.aliyun.oss.model.OSSObject;
|
|
||||||
import com.aliyun.oss.model.ObjectMetadata;
|
|
||||||
import com.aliyun.oss.model.ObjectListing;
|
|
||||||
import com.aliyun.oss.model.OSSObjectSummary;
|
|
||||||
import com.aliyun.oss.model.PutObjectRequest;
|
|
||||||
import com.central.oss.model.ObjectInfo;
|
import com.central.oss.model.ObjectInfo;
|
||||||
import com.central.oss.properties.FileServerProperties;
|
import com.central.oss.properties.FileServerProperties;
|
||||||
import lombok.SneakyThrows;
|
import lombok.SneakyThrows;
|
||||||
@@ -38,7 +33,7 @@ public class OssTemplate implements InitializingBean {
|
|||||||
|
|
||||||
private static final String DEF_CONTEXT_TYPE = "application/octet-stream";
|
private static final String DEF_CONTEXT_TYPE = "application/octet-stream";
|
||||||
private static final String PATH_SPLIT = "/";
|
private static final String PATH_SPLIT = "/";
|
||||||
private static final int DEFAULT_EXPIRE_TYPE = 60;
|
private static final int DEFAULT_EXPIRE_TYPE = 60 * 24;
|
||||||
|
|
||||||
@Autowired
|
@Autowired
|
||||||
private FileServerProperties fileProperties;
|
private FileServerProperties fileProperties;
|
||||||
|
|||||||
@@ -0,0 +1,58 @@
|
|||||||
|
<?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">
|
||||||
|
<parent>
|
||||||
|
<groupId>com.zlt</groupId>
|
||||||
|
<artifactId>zlt-commons</artifactId>
|
||||||
|
<version>6.0.0</version>
|
||||||
|
</parent>
|
||||||
|
<modelVersion>4.0.0</modelVersion>
|
||||||
|
<packaging>jar</packaging>
|
||||||
|
<artifactId>zlt-sms-spring-boot-starter</artifactId>
|
||||||
|
<description>短信服务通用组件</description>
|
||||||
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework</groupId>
|
||||||
|
<artifactId>spring-web</artifactId>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>org.springframework.boot</groupId>
|
||||||
|
<artifactId>spring-boot-configuration-processor</artifactId>
|
||||||
|
<optional>true</optional>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.tencentcloudapi</groupId>
|
||||||
|
<artifactId>tencentcloud-sdk-java</artifactId>
|
||||||
|
<version>3.1.825</version>
|
||||||
|
</dependency>
|
||||||
|
<!-- 腾讯云短信SDK依赖可后续补充 -->
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.aliyun</groupId>
|
||||||
|
<artifactId>aliyun-java-sdk-dysmsapi</artifactId>
|
||||||
|
<version>2.1.0</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.aliyun</groupId>
|
||||||
|
<artifactId>aliyun-java-sdk-core</artifactId>
|
||||||
|
<version>4.5.20</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.alibaba</groupId>
|
||||||
|
<artifactId>fastjson</artifactId>
|
||||||
|
<version>1.2.83</version>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.aliyun</groupId>
|
||||||
|
<artifactId>aliyun-java-sdk-core</artifactId>
|
||||||
|
<version>4.6.4</version>
|
||||||
|
<scope>compile</scope>
|
||||||
|
</dependency>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.tencentcloudapi</groupId>
|
||||||
|
<artifactId>tencentcloud-sdk-java-common</artifactId>
|
||||||
|
<version>3.1.1040</version>
|
||||||
|
<scope>compile</scope>
|
||||||
|
</dependency>
|
||||||
|
</dependencies>
|
||||||
|
</project>
|
||||||
+19
@@ -0,0 +1,19 @@
|
|||||||
|
package com.central.sms.config;
|
||||||
|
|
||||||
|
import com.central.sms.service.ISmsService;
|
||||||
|
import com.central.sms.service.SmsServiceFactory;
|
||||||
|
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
|
||||||
|
import org.springframework.boot.context.properties.EnableConfigurationProperties;
|
||||||
|
import org.springframework.context.annotation.Bean;
|
||||||
|
import org.springframework.context.annotation.Configuration;
|
||||||
|
|
||||||
|
@Configuration
|
||||||
|
@EnableConfigurationProperties(SmsProperties.class)
|
||||||
|
public class SmsAutoConfigure {
|
||||||
|
|
||||||
|
@Bean
|
||||||
|
@ConditionalOnMissingBean(ISmsService.class)
|
||||||
|
public ISmsService smsService(SmsServiceFactory factory) {
|
||||||
|
return factory.getSmsService();
|
||||||
|
}
|
||||||
|
}
|
||||||
+45
@@ -0,0 +1,45 @@
|
|||||||
|
package com.central.sms.config;
|
||||||
|
|
||||||
|
import com.central.sms.enums.SmsProviderType;
|
||||||
|
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||||
|
|
||||||
|
@ConfigurationProperties(prefix = "sms")
|
||||||
|
public class SmsProperties {
|
||||||
|
private SmsProviderType provider = SmsProviderType.TENCENT;
|
||||||
|
private TencentConfig tencent = new TencentConfig();
|
||||||
|
private AliyunConfig aliyun = new AliyunConfig();
|
||||||
|
|
||||||
|
public SmsProviderType getProvider() { return provider; }
|
||||||
|
public void setProvider(SmsProviderType provider) { this.provider = provider; }
|
||||||
|
public TencentConfig getTencent() { return tencent; }
|
||||||
|
public void setTencent(TencentConfig tencent) { this.tencent = tencent; }
|
||||||
|
public AliyunConfig getAliyun() { return aliyun; }
|
||||||
|
public void setAliyun(AliyunConfig aliyun) { this.aliyun = aliyun; }
|
||||||
|
|
||||||
|
public static class TencentConfig {
|
||||||
|
private String appId;
|
||||||
|
private String secretId;
|
||||||
|
private String secretKey;
|
||||||
|
private String signName;
|
||||||
|
public String getAppId() { return appId; }
|
||||||
|
public void setAppId(String appId) { this.appId = appId; }
|
||||||
|
public String getSecretId() { return secretId; }
|
||||||
|
public void setSecretId(String secretId) { this.secretId = secretId; }
|
||||||
|
public String getSecretKey() { return secretKey; }
|
||||||
|
public void setSecretKey(String secretKey) { this.secretKey = secretKey; }
|
||||||
|
public String getSignName() { return signName; }
|
||||||
|
public void setSignName(String signName) { this.signName = signName; }
|
||||||
|
}
|
||||||
|
|
||||||
|
public static class AliyunConfig {
|
||||||
|
private String accessKeyId;
|
||||||
|
private String accessKeySecret;
|
||||||
|
private String signName;
|
||||||
|
public String getAccessKeyId() { return accessKeyId; }
|
||||||
|
public void setAccessKeyId(String accessKeyId) { this.accessKeyId = accessKeyId; }
|
||||||
|
public String getAccessKeySecret() { return accessKeySecret; }
|
||||||
|
public void setAccessKeySecret(String accessKeySecret) { this.accessKeySecret = accessKeySecret; }
|
||||||
|
public String getSignName() { return signName; }
|
||||||
|
public void setSignName(String signName) { this.signName = signName; }
|
||||||
|
}
|
||||||
|
}
|
||||||
+6
@@ -0,0 +1,6 @@
|
|||||||
|
package com.central.sms.enums;
|
||||||
|
|
||||||
|
public enum SmsProviderType {
|
||||||
|
TENCENT,
|
||||||
|
ALIYUN
|
||||||
|
}
|
||||||
+7
@@ -0,0 +1,7 @@
|
|||||||
|
package com.central.sms.exception;
|
||||||
|
|
||||||
|
public class SmsSendException extends RuntimeException {
|
||||||
|
public SmsSendException(String message, Throwable cause) {
|
||||||
|
super(message, cause);
|
||||||
|
}
|
||||||
|
}
|
||||||
+14
@@ -0,0 +1,14 @@
|
|||||||
|
package com.central.sms.service;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
public interface ISmsService {
|
||||||
|
/**
|
||||||
|
* 发送短信
|
||||||
|
* @param phone 手机号
|
||||||
|
* @param templateId 短信模板ID
|
||||||
|
* @param params 模板参数
|
||||||
|
* @return 是否发送成功
|
||||||
|
*/
|
||||||
|
boolean sendSms(String phone, String templateId, Map<String, String> params);
|
||||||
|
}
|
||||||
+30
@@ -0,0 +1,30 @@
|
|||||||
|
package com.central.sms.service;
|
||||||
|
|
||||||
|
import com.central.sms.config.SmsProperties;
|
||||||
|
import com.central.sms.enums.SmsProviderType;
|
||||||
|
import com.central.sms.service.impl.AliyunSmsService;
|
||||||
|
import com.central.sms.service.impl.TencentSmsService;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class SmsServiceFactory {
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private TencentSmsService tencentSmsService;
|
||||||
|
@Autowired
|
||||||
|
private AliyunSmsService aliyunSmsService;
|
||||||
|
@Autowired
|
||||||
|
private SmsProperties smsProperties;
|
||||||
|
|
||||||
|
public ISmsService getSmsService() {
|
||||||
|
SmsProviderType type = smsProperties.getProvider();
|
||||||
|
switch (type) {
|
||||||
|
case ALIYUN:
|
||||||
|
return aliyunSmsService;
|
||||||
|
case TENCENT:
|
||||||
|
default:
|
||||||
|
return tencentSmsService;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+56
@@ -0,0 +1,56 @@
|
|||||||
|
package com.central.sms.service.impl;
|
||||||
|
|
||||||
|
import com.aliyuncs.DefaultAcsClient;
|
||||||
|
import com.aliyuncs.IAcsClient;
|
||||||
|
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
|
||||||
|
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
|
||||||
|
import com.aliyuncs.exceptions.ClientException;
|
||||||
|
import com.aliyuncs.profile.DefaultProfile;
|
||||||
|
import com.central.sms.config.SmsProperties;
|
||||||
|
import com.central.sms.exception.SmsSendException;
|
||||||
|
import com.central.sms.service.ISmsService;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class AliyunSmsService implements ISmsService {
|
||||||
|
|
||||||
|
private static final Logger logger = LoggerFactory.getLogger(AliyunSmsService.class);
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private SmsProperties smsProperties;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean sendSms(String phone, String templateId, Map<String, String> params) {
|
||||||
|
SmsProperties.AliyunConfig config = smsProperties.getAliyun();
|
||||||
|
DefaultProfile profile = DefaultProfile.getProfile(
|
||||||
|
"cn-hangzhou", // 地域ID
|
||||||
|
config.getAccessKeyId(),
|
||||||
|
config.getAccessKeySecret()
|
||||||
|
);
|
||||||
|
IAcsClient client = new DefaultAcsClient(profile);
|
||||||
|
|
||||||
|
SendSmsRequest request = new SendSmsRequest();
|
||||||
|
request.setPhoneNumbers(phone);
|
||||||
|
request.setSignName(config.getSignName());
|
||||||
|
request.setTemplateCode(templateId);
|
||||||
|
// 阿里云短信模板参数为JSON字符串
|
||||||
|
if (params != null && !params.isEmpty()) {
|
||||||
|
request.setTemplateParam(com.alibaba.fastjson.JSON.toJSONString(params));
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
logger.info("[阿里云短信] 发送请求: 手机号={}, 模板={}, 参数={}", phone, templateId, params);
|
||||||
|
SendSmsResponse response = client.getAcsResponse(request);
|
||||||
|
logger.info("[阿里云短信] 发送结果: {}", response.getMessage());
|
||||||
|
return "OK".equalsIgnoreCase(response.getCode());
|
||||||
|
} catch (ClientException e) {
|
||||||
|
logger.error("[阿里云短信] 发送失败,手机号:{},模板:{},参数:{},异常:{}", phone, templateId, params, e.getMessage(), e);
|
||||||
|
throw new SmsSendException("阿里云短信发送失败", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+52
@@ -0,0 +1,52 @@
|
|||||||
|
package com.central.sms.service.impl;
|
||||||
|
|
||||||
|
import com.central.sms.config.SmsProperties;
|
||||||
|
import com.central.sms.exception.SmsSendException;
|
||||||
|
import com.central.sms.service.ISmsService;
|
||||||
|
import com.tencentcloudapi.common.Credential;
|
||||||
|
import com.tencentcloudapi.common.profile.ClientProfile;
|
||||||
|
import com.tencentcloudapi.common.profile.HttpProfile;
|
||||||
|
import org.slf4j.Logger;
|
||||||
|
import org.slf4j.LoggerFactory;
|
||||||
|
import org.springframework.beans.factory.annotation.Autowired;
|
||||||
|
import org.springframework.stereotype.Service;
|
||||||
|
|
||||||
|
import java.util.Map;
|
||||||
|
|
||||||
|
@Service
|
||||||
|
public class TencentSmsService implements ISmsService {
|
||||||
|
|
||||||
|
private static final Logger logger = LoggerFactory.getLogger(TencentSmsService.class);
|
||||||
|
|
||||||
|
@Autowired
|
||||||
|
private SmsProperties smsProperties;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public boolean sendSms(String phone, String templateId, Map<String, String> params) {
|
||||||
|
try {
|
||||||
|
SmsProperties.TencentConfig config = smsProperties.getTencent();
|
||||||
|
logger.info("[短信发送][服务商:TENCENT] 手机号={}, 模板ID={}, 参数={}", phone, templateId, params);
|
||||||
|
Credential cred = new Credential(config.getSecretId(), config.getSecretKey());
|
||||||
|
HttpProfile httpProfile = new HttpProfile();
|
||||||
|
httpProfile.setEndpoint("sms.tencentcloudapi.com");
|
||||||
|
ClientProfile clientProfile = new ClientProfile();
|
||||||
|
clientProfile.setHttpProfile(httpProfile);
|
||||||
|
/*SmsClient client = new SmsClient(cred, "ap-guangzhou", clientProfile);
|
||||||
|
|
||||||
|
SendSmsRequest req = new SendSmsRequest();
|
||||||
|
req.setSmsSdkAppId(config.getAppId());
|
||||||
|
req.setSignName(config.getSignName());
|
||||||
|
req.setTemplateId(templateId);
|
||||||
|
req.setPhoneNumberSet(new String[]{phone});
|
||||||
|
req.setTemplateParamSet(params.values().toArray(new String[0]));
|
||||||
|
|
||||||
|
SendSmsResponse resp = client.SendSms(req);
|
||||||
|
logger.info("[短信发送][服务商:TENCENT] 响应: code={}, message={}", resp.getSendStatusSet()[0].getCode(), resp.getSendStatusSet()[0].getMessage());
|
||||||
|
return "Ok".equalsIgnoreCase(resp.getSendStatusSet()[0].getCode());*/
|
||||||
|
return true;
|
||||||
|
} catch (Exception e) {
|
||||||
|
logger.error("[短信发送][服务商:TENCENT] 失败,手机号:{},模板ID:{},参数:{},异常:{}", phone, templateId, params, e.getMessage(), e);
|
||||||
|
throw new SmsSendException("腾讯云短信发送失败", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+1
@@ -0,0 +1 @@
|
|||||||
|
com.central.sms.config.SmsAutoConfigure
|
||||||
+1
-1
@@ -20,7 +20,7 @@ public class WechatConfig {
|
|||||||
private String tenantId;
|
private String tenantId;
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 配置类型:MP-公众号,MINI-小程序,PAY-支付
|
* 配置类型:MP-公众号,MINI-小程序,PAY-支付,MA-小程序消息
|
||||||
*/
|
*/
|
||||||
private String type;
|
private String type;
|
||||||
|
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user