Compare commits
95
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
47a685f419 | ||
|
|
3cfa7cc82e | ||
|
|
56825ba89f | ||
|
|
63da239524 | ||
|
|
e4ca99ffb2 | ||
|
|
20e9e066bf | ||
|
|
603b5a584a | ||
|
|
fdcf22832a | ||
|
|
b830b201f7 | ||
|
|
3503558ebc | ||
|
|
50e44e24bd | ||
|
|
ea388107f8 | ||
|
|
9141be16d7 | ||
|
|
8d8827fa5c | ||
|
|
5fc45b31bc | ||
|
|
86b0158710 | ||
|
|
537b13e60e | ||
|
|
ecc482ce13 | ||
|
|
3a48b6f34f | ||
|
|
ba869b62a5 | ||
|
|
c79c6c405c | ||
|
|
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. **性能考虑**: 对于大量数据,建议添加适当的查询限制和缓存机制
|
||||
+35
-1
@@ -90,4 +90,38 @@ CREATE INDEX idx_wechat_config_serial_number_2 ON wechat_config(serial_number);
|
||||
-- - serial_number:微信平台证书的序列号,用于验证回调请求的签名
|
||||
-- - 在微信支付回调时,通过此字段可以快速定位对应的配置信息
|
||||
-- - 与回调请求头中的 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. 检查订单状态
|
||||
String orderStatus = orderCenterService.getOrderStatusByOrderNo(orderNo);
|
||||
if (!isValidOrderStatus(orderStatus)) {
|
||||
return Result.succeed("设备已执行");
|
||||
return Result.failed("设备已处理,请关注订单详情");
|
||||
}
|
||||
|
||||
// 3. 构建控制消息
|
||||
JsonObject controlMessage = buildControlMessage(control, orderNo, deviceId);
|
||||
if (controlMessage == null) {
|
||||
return Result.succeed("暂未开放控制权限");
|
||||
return Result.failed("暂未开放控制权限");
|
||||
}
|
||||
|
||||
// 4. 发送设备控制请求
|
||||
@@ -160,7 +160,16 @@ public class ApiDeviceController {
|
||||
if (requestResult.getStatus() == 200 || requestResult.getStatus() == 500) {
|
||||
log.info("设置设备属性返回消息: message={}", requestResult.getMessage());
|
||||
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);
|
||||
if (updateResult.getResp_code() != null && updateResult.getResp_code() == 0) {
|
||||
@@ -171,6 +180,36 @@ public class ApiDeviceController {
|
||||
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")
|
||||
public Result<Map> getWayline(@RequestParam String no){
|
||||
return Result.succeed(orderCenterService.getWaylineByOrderNo(no));
|
||||
|
||||
+73
-5
@@ -13,7 +13,10 @@ import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* Wayline file information
|
||||
@@ -48,8 +51,16 @@ public class LineFileController {
|
||||
@Operation(summary = "查询")
|
||||
@GetMapping("/{id}")
|
||||
public Result findById(@PathVariable String id) {
|
||||
LineFile model = lineFileService.findLineFileByWaylineId(id);
|
||||
return Result.succeed(model, "查询成功");
|
||||
try {
|
||||
LineFile model = lineFileService.findLineFileByWaylineId(id);
|
||||
if (model == null) {
|
||||
return Result.failed("未找到对应的航线文件信息");
|
||||
}
|
||||
return Result.succeed(model, "查询成功");
|
||||
} catch (Exception e) {
|
||||
log.error("查询航线文件失败,id: {}", id, e);
|
||||
return Result.failed("查询航线文件失败:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -57,9 +68,17 @@ public class LineFileController {
|
||||
*/
|
||||
@Operation(summary = "查询")
|
||||
@GetMapping("/sign/{id}")
|
||||
public String findLineSignById(@PathVariable String id) {
|
||||
LineFile model = lineFileService.findLineFileByWaylineId(id);
|
||||
return model.getSign();
|
||||
public Result findLineSignById(@PathVariable String id) {
|
||||
try {
|
||||
LineFile model = lineFileService.findLineFileByWaylineId(id);
|
||||
if (model == null) {
|
||||
return Result.failed("未找到对应的航线文件信息");
|
||||
}
|
||||
return Result.succeed(model.getSign(), "查询成功");
|
||||
} catch (Exception e) {
|
||||
log.error("查询航线文件签名失败,id: {}", id, e);
|
||||
return Result.failed("查询航线文件签名失败:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -82,4 +101,53 @@ public class LineFileController {
|
||||
lineFileService.removeById(id);
|
||||
return Result.succeed("删除成功");
|
||||
}
|
||||
|
||||
/**
|
||||
* 诊断航线文件数据
|
||||
*/
|
||||
@Operation(summary = "诊断航线文件数据")
|
||||
@GetMapping("/diagnose")
|
||||
public Result diagnoseLineFileData() {
|
||||
try {
|
||||
// 查询所有航线文件
|
||||
List<LineFile> allLineFiles = lineFileService.list();
|
||||
|
||||
Map<String, Object> diagnosis = new HashMap<>();
|
||||
diagnosis.put("totalCount", allLineFiles.size());
|
||||
|
||||
// 按waylineId分组统计
|
||||
Map<String, Long> waylineIdStats = allLineFiles.stream()
|
||||
.collect(Collectors.groupingBy(
|
||||
f -> f.getWaylineId() == null ? "NULL_WAYLINE_ID" : f.getWaylineId(),
|
||||
Collectors.counting()
|
||||
));
|
||||
diagnosis.put("waylineIdStats", waylineIdStats);
|
||||
|
||||
// 检查有sign字段的文件
|
||||
List<LineFile> filesWithSign = allLineFiles.stream()
|
||||
.filter(f -> f.getSign() != null && !f.getSign().isEmpty())
|
||||
.collect(Collectors.toList());
|
||||
diagnosis.put("filesWithSign", filesWithSign.size());
|
||||
|
||||
// 最近的文件示例
|
||||
List<Map<String, Object>> recentFiles = allLineFiles.stream()
|
||||
.limit(10)
|
||||
.map(f -> {
|
||||
Map<String, Object> fileInfo = new HashMap<>();
|
||||
fileInfo.put("id", f.getId());
|
||||
fileInfo.put("name", f.getName());
|
||||
fileInfo.put("waylineId", f.getWaylineId());
|
||||
fileInfo.put("sign", f.getSign());
|
||||
fileInfo.put("createTime", f.getCreateTime());
|
||||
return fileInfo;
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
diagnosis.put("recentFiles", recentFiles);
|
||||
|
||||
return Result.succeed(diagnosis, "诊断完成");
|
||||
} catch (Exception e) {
|
||||
log.error("诊断航线文件数据失败", e);
|
||||
return Result.failed("诊断失败:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+9
@@ -30,4 +30,13 @@ public interface OrderCenterService {
|
||||
|
||||
@GetMapping("/qrcode/wayline/{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) {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Result createRefundForOfflineDevice(String orderNo, Map<String, Object> refundBody) {
|
||||
log.error("调用订单中心退款接口失败: orderNo={}, cause={}", orderNo, cause.getMessage());
|
||||
return Result.failed("退款服务调用失败");
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
+73
-5
@@ -13,7 +13,10 @@ import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* Wayline file information
|
||||
@@ -48,8 +51,16 @@ public class LineFileController {
|
||||
@Operation(summary = "查询")
|
||||
@GetMapping("/{id}")
|
||||
public Result findById(@PathVariable String id) {
|
||||
LineFile model = lineFileService.findLineFileByWaylineId(id);
|
||||
return Result.succeed(model, "查询成功");
|
||||
try {
|
||||
LineFile model = lineFileService.findLineFileByWaylineId(id);
|
||||
if (model == null) {
|
||||
return Result.failed("未找到对应的航线文件信息");
|
||||
}
|
||||
return Result.succeed(model, "查询成功");
|
||||
} catch (Exception e) {
|
||||
log.error("查询航线文件失败,id: {}", id, e);
|
||||
return Result.failed("查询航线文件失败:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -57,9 +68,17 @@ public class LineFileController {
|
||||
*/
|
||||
@Operation(summary = "查询")
|
||||
@GetMapping("/sign/{id}")
|
||||
public String findLineSignById(@PathVariable String id) {
|
||||
LineFile model = lineFileService.findLineFileByWaylineId(id);
|
||||
return model.getSign();
|
||||
public Result findLineSignById(@PathVariable String id) {
|
||||
try {
|
||||
LineFile model = lineFileService.findLineFileByWaylineId(id);
|
||||
if (model == null) {
|
||||
return Result.failed("未找到对应的航线文件信息");
|
||||
}
|
||||
return Result.succeed(model.getSign(), "查询成功");
|
||||
} catch (Exception e) {
|
||||
log.error("查询航线文件签名失败,id: {}", id, e);
|
||||
return Result.failed("查询航线文件签名失败:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -82,4 +101,53 @@ public class LineFileController {
|
||||
lineFileService.removeById(id);
|
||||
return Result.succeed("删除成功");
|
||||
}
|
||||
|
||||
/**
|
||||
* 诊断航线文件数据
|
||||
*/
|
||||
@Operation(summary = "诊断航线文件数据")
|
||||
@GetMapping("/diagnose")
|
||||
public Result diagnoseLineFileData() {
|
||||
try {
|
||||
// 查询所有航线文件
|
||||
List<LineFile> allLineFiles = lineFileService.list();
|
||||
|
||||
Map<String, Object> diagnosis = new HashMap<>();
|
||||
diagnosis.put("totalCount", allLineFiles.size());
|
||||
|
||||
// 按waylineId分组统计
|
||||
Map<String, Long> waylineIdStats = allLineFiles.stream()
|
||||
.collect(Collectors.groupingBy(
|
||||
f -> f.getWaylineId() == null ? "NULL_WAYLINE_ID" : f.getWaylineId(),
|
||||
Collectors.counting()
|
||||
));
|
||||
diagnosis.put("waylineIdStats", waylineIdStats);
|
||||
|
||||
// 检查有sign字段的文件
|
||||
List<LineFile> filesWithSign = allLineFiles.stream()
|
||||
.filter(f -> f.getSign() != null && !f.getSign().isEmpty())
|
||||
.collect(Collectors.toList());
|
||||
diagnosis.put("filesWithSign", filesWithSign.size());
|
||||
|
||||
// 最近的文件示例
|
||||
List<Map<String, Object>> recentFiles = allLineFiles.stream()
|
||||
.limit(10)
|
||||
.map(f -> {
|
||||
Map<String, Object> fileInfo = new HashMap<>();
|
||||
fileInfo.put("id", f.getId());
|
||||
fileInfo.put("name", f.getName());
|
||||
fileInfo.put("waylineId", f.getWaylineId());
|
||||
fileInfo.put("sign", f.getSign());
|
||||
fileInfo.put("createTime", f.getCreateTime());
|
||||
return fileInfo;
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
diagnosis.put("recentFiles", recentFiles);
|
||||
|
||||
return Result.succeed(diagnosis, "诊断完成");
|
||||
} catch (Exception e) {
|
||||
log.error("诊断航线文件数据失败", e);
|
||||
return Result.failed("诊断失败:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
</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>
|
||||
|
||||
<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;
|
||||
}
|
||||
+325
@@ -0,0 +1,325 @@
|
||||
package com.central.file.controller;
|
||||
|
||||
import com.central.common.model.FileInfo;
|
||||
import com.central.common.model.Result;
|
||||
import com.central.file.mapper.FileMapper;
|
||||
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.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* CDN管理控制器
|
||||
*
|
||||
* @author system
|
||||
* @date 2024-12-19
|
||||
*/
|
||||
@Slf4j
|
||||
@RestController
|
||||
@Tag(name = "CDN管理")
|
||||
@RequiredArgsConstructor
|
||||
@RequestMapping("/cdn")
|
||||
public class CdnController {
|
||||
|
||||
@Autowired
|
||||
private ICdnService cdnService;
|
||||
|
||||
@Autowired
|
||||
private FileMapper fileMapper;
|
||||
|
||||
@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) {
|
||||
try {
|
||||
log.info("获取订单图片URL,订单号: {}", orderNo);
|
||||
|
||||
// 方案1: 通过文件服务查询订单相关的图片文件
|
||||
List<String> imageUrls = new ArrayList<>();
|
||||
|
||||
// 查询订单相关的图片文件(根据路径模式匹配)
|
||||
// 假设订单图片的路径包含订单号
|
||||
List<FileInfo> orderFiles = fileMapper.selectList(null).stream()
|
||||
.filter(file -> {
|
||||
if (file.getPath() == null || orderNo == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 检查路径是否包含订单号
|
||||
return file.getPath().contains(orderNo);
|
||||
})
|
||||
.filter(file -> {
|
||||
// 只处理图片文件
|
||||
if (file.getContentType() == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return file.getContentType().startsWith("image/");
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
|
||||
log.info("找到订单相关图片文件: {} 个", orderFiles.size());
|
||||
|
||||
// 转换为URL列表
|
||||
for (FileInfo fileInfo : orderFiles) {
|
||||
try {
|
||||
String imageUrl = getImageUrl(fileInfo);
|
||||
if (imageUrl != null && !imageUrl.isEmpty()) {
|
||||
imageUrls.add(imageUrl);
|
||||
log.debug("订单图片URL: {}", imageUrl);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("获取订单图片URL失败,文件ID: {}", fileInfo.getId(), e);
|
||||
}
|
||||
}
|
||||
|
||||
// 方案2: 如果文件服务中没有找到,可以尝试调用订单服务
|
||||
if (imageUrls.isEmpty()) {
|
||||
log.info("文件服务中未找到订单图片,尝试其他方式获取");
|
||||
// 这里可以添加调用订单服务的逻辑
|
||||
// 例如:通过RestTemplate调用订单服务获取图片URL
|
||||
}
|
||||
|
||||
log.info("订单图片URL获取完成,订单号: {}, 图片数量: {}", orderNo, imageUrls.size());
|
||||
return imageUrls;
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("获取订单图片URL失败,订单号: {}", orderNo, e);
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取图片文件的访问URL
|
||||
*/
|
||||
private String getImageUrl(FileInfo fileInfo) {
|
||||
try {
|
||||
if (fileInfo.getPath() == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 根据存储类型获取URL
|
||||
if (fileInfo.getStorageType() != null) {
|
||||
switch (fileInfo.getStorageType().toUpperCase()) {
|
||||
case "OSS":
|
||||
case "ALIYUN":
|
||||
// 使用OSS服务获取URL
|
||||
return getOssImageUrl(fileInfo.getPath());
|
||||
case "S3":
|
||||
case "MINIO":
|
||||
// 使用S3服务获取URL
|
||||
return getS3ImageUrl(fileInfo.getPath());
|
||||
default:
|
||||
// 默认使用OSS
|
||||
return getOssImageUrl(fileInfo.getPath());
|
||||
}
|
||||
} else {
|
||||
// 根据路径特征判断存储类型
|
||||
if (fileInfo.getPath().startsWith("picture/") ||
|
||||
fileInfo.getPath().startsWith("video/") ||
|
||||
fileInfo.getPath().startsWith("file/")) {
|
||||
return getOssImageUrl(fileInfo.getPath());
|
||||
} else if (fileInfo.getPath().contains("s3://") ||
|
||||
fileInfo.getPath().contains("minio")) {
|
||||
return getS3ImageUrl(fileInfo.getPath());
|
||||
} else {
|
||||
return getOssImageUrl(fileInfo.getPath());
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("获取图片URL失败,文件ID: {}", fileInfo.getId(), e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取OSS图片URL
|
||||
*/
|
||||
private String getOssImageUrl(String path) {
|
||||
try {
|
||||
// 这里需要注入OssService,暂时返回模拟URL
|
||||
// 实际实现中应该调用ossService.getViewUrlByPath(path)
|
||||
return "https://" + cdnOssUrl + "/" + path;
|
||||
} catch (Exception e) {
|
||||
log.error("获取OSS图片URL失败: {}", path, e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取S3图片URL
|
||||
*/
|
||||
private String getS3ImageUrl(String path) {
|
||||
try {
|
||||
// 这里需要注入S3Service,暂时返回模拟URL
|
||||
// 实际实现中应该调用s3Service.getViewUrlByPath(path)
|
||||
return "https://s3.amazonaws.com/" + path;
|
||||
} catch (Exception e) {
|
||||
log.error("获取S3图片URL失败: {}", path, e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理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();
|
||||
}
|
||||
}
|
||||
+729
@@ -6,6 +6,9 @@ import com.central.common.model.Result;
|
||||
import com.central.file.service.IFileService;
|
||||
import com.central.file.service.StorageHealthCheckService;
|
||||
import com.central.file.service.TimeWindowStorageService;
|
||||
import com.central.file.service.OssToS3SyncService;
|
||||
import com.central.file.service.OssToMinioSyncScheduler;
|
||||
import com.central.file.mapper.FileMapper;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.collections.MapUtils;
|
||||
@@ -20,10 +23,12 @@ import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.InputStream;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 文件上传
|
||||
@@ -42,6 +47,15 @@ public class FileController {
|
||||
@Autowired
|
||||
private StorageHealthCheckService storageHealthCheckService;
|
||||
|
||||
@Autowired(required = false)
|
||||
private OssToS3SyncService ossToS3SyncService;
|
||||
|
||||
@Autowired(required = false)
|
||||
private OssToMinioSyncScheduler ossToMinioSyncScheduler;
|
||||
|
||||
@Autowired
|
||||
private FileMapper fileMapper;
|
||||
|
||||
@Value("${zlt.security.tencent.accessTokenUrl}")
|
||||
private String accessTokenUrl;
|
||||
|
||||
@@ -243,4 +257,719 @@ public class FileController {
|
||||
public Result<String> getStorageHealth() {
|
||||
return Result.succeed(storageHealthCheckService.getStorageStatus(), "获取成功");
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取智能存储文件URL
|
||||
*/
|
||||
@GetMapping("/storage/smart-url/{id}")
|
||||
public Result<Map<String, Object>> getSmartStorageUrl(@PathVariable String id) {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
try {
|
||||
String smartUrl = timeWindowStorageService.getSmartViewUrl(id);
|
||||
result.put("fileId", id);
|
||||
result.put("smartUrl", smartUrl);
|
||||
result.put("success", !smartUrl.isEmpty());
|
||||
result.put("hasUrl", smartUrl != null && !smartUrl.isEmpty());
|
||||
|
||||
return Result.succeed(result);
|
||||
} catch (Exception e) {
|
||||
log.error("获取智能存储URL失败: {}", id, e);
|
||||
result.put("fileId", id);
|
||||
result.put("error", e.getMessage());
|
||||
result.put("success", false);
|
||||
return Result.failed("获取智能存储URL失败");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据路径获取智能存储文件URL
|
||||
*/
|
||||
@GetMapping("/storage/smart-url-by-path")
|
||||
public Result<Map<String, Object>> getSmartStorageUrlByPath(@RequestParam String path) {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
try {
|
||||
String smartUrl = timeWindowStorageService.getSmartViewUrlByPath(path);
|
||||
result.put("path", path);
|
||||
result.put("smartUrl", smartUrl);
|
||||
result.put("success", !smartUrl.isEmpty());
|
||||
result.put("hasUrl", smartUrl != null && !smartUrl.isEmpty());
|
||||
|
||||
return Result.succeed(result);
|
||||
} catch (Exception e) {
|
||||
log.error("获取智能存储URL失败: path={}", path, e);
|
||||
result.put("path", path);
|
||||
result.put("error", e.getMessage());
|
||||
result.put("success", false);
|
||||
return Result.failed("获取智能存储URL失败");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试S3文件访问
|
||||
*/
|
||||
@GetMapping("/storage/test-s3-access")
|
||||
public Result<Map<String, Object>> testS3Access(@RequestParam String path) {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
try {
|
||||
// 使用TimeWindowStorageService来测试S3访问
|
||||
String smartUrl = timeWindowStorageService.getSmartViewUrlByPath(path);
|
||||
result.put("path", path);
|
||||
result.put("smartUrl", smartUrl);
|
||||
result.put("success", !smartUrl.isEmpty());
|
||||
result.put("hasUrl", smartUrl != null && !smartUrl.isEmpty());
|
||||
|
||||
return Result.succeed(result);
|
||||
} catch (Exception e) {
|
||||
log.error("测试S3访问失败: path={}", path, e);
|
||||
result.put("path", path);
|
||||
result.put("error", e.getMessage());
|
||||
result.put("success", false);
|
||||
return Result.failed("测试S3访问失败");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 手动同步OSS文件到S3
|
||||
*/
|
||||
@PostMapping("/storage/sync-oss-to-s3")
|
||||
public Result<Map<String, Object>> syncOssToS3(@RequestParam String path) {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
try {
|
||||
if (ossToS3SyncService == null) {
|
||||
result.put("path", path);
|
||||
result.put("error", "OSS到S3同步服务未配置");
|
||||
result.put("success", false);
|
||||
return Result.failed("OSS到S3同步服务未配置");
|
||||
}
|
||||
|
||||
boolean syncResult = ossToS3SyncService.syncFileToS3(path);
|
||||
result.put("path", path);
|
||||
result.put("syncResult", syncResult);
|
||||
result.put("success", syncResult);
|
||||
|
||||
if (syncResult) {
|
||||
log.info("手动同步OSS到S3成功: path={}", path);
|
||||
return Result.succeed(result, "同步成功");
|
||||
} else {
|
||||
log.error("手动同步OSS到S3失败: path={}", path);
|
||||
return Result.failed("同步失败");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("手动同步OSS到S3异常: path={}", path, e);
|
||||
result.put("path", path);
|
||||
result.put("error", e.getMessage());
|
||||
result.put("success", false);
|
||||
return Result.failed("同步异常:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试OSS文件访问
|
||||
*/
|
||||
@GetMapping("/storage/test-oss-access")
|
||||
public Result<Map<String, Object>> testOssAccess(@RequestParam String path) {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
try {
|
||||
// 使用现有的fileService来测试OSS访问
|
||||
String ossUrl = fileService.getViewUrlByPath(path);
|
||||
result.put("path", path);
|
||||
result.put("ossUrl", ossUrl);
|
||||
result.put("success", ossUrl != null && !ossUrl.isEmpty());
|
||||
result.put("hasUrl", ossUrl != null && !ossUrl.isEmpty());
|
||||
|
||||
return Result.succeed(result);
|
||||
} catch (Exception e) {
|
||||
log.error("测试OSS访问失败: path={}", path, e);
|
||||
result.put("path", path);
|
||||
result.put("error", e.getMessage());
|
||||
result.put("success", false);
|
||||
return Result.failed("测试OSS访问失败");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量同步OSS文件到MinIO
|
||||
*/
|
||||
@PostMapping("/storage/batch-sync-oss-to-minio")
|
||||
public Result<Map<String, Object>> batchSyncOssToMinio(@RequestParam(required = false) Integer days) {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
try {
|
||||
if (ossToS3SyncService == null) {
|
||||
result.put("error", "OSS到MinIO同步服务未配置");
|
||||
result.put("success", false);
|
||||
return Result.failed("OSS到MinIO同步服务未配置");
|
||||
}
|
||||
|
||||
// 如果没有指定天数,默认同步30天前的文件
|
||||
int syncDays = days != null ? days : 30;
|
||||
|
||||
log.info("开始批量同步OSS文件到MinIO,同步{}天前的文件", syncDays);
|
||||
|
||||
// 实现批量同步逻辑
|
||||
// 1. 查询指定天数前的文件列表
|
||||
LocalDateTime syncThreshold = LocalDateTime.now().minusDays(syncDays);
|
||||
List<FileInfo> filesToSync = fileMapper.selectList(null).stream()
|
||||
.filter(file -> {
|
||||
if (file.getCreateTime() == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
LocalDateTime createTime = file.getCreateTime().toInstant()
|
||||
.atZone(java.time.ZoneId.systemDefault())
|
||||
.toLocalDateTime();
|
||||
|
||||
return createTime.isBefore(syncThreshold);
|
||||
})
|
||||
.filter(file -> {
|
||||
// 过滤掉已经在S3中的文件
|
||||
if (file.getStorageType() != null &&
|
||||
(file.getStorageType().contains("S3") || file.getStorageType().contains("MINIO"))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (file.getPath() != null &&
|
||||
(file.getPath().contains("s3://") || file.getPath().contains("minio") ||
|
||||
file.getPath().contains("s3-storage/") || file.getPath().contains("cold-storage/"))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
})
|
||||
.filter(file -> {
|
||||
// 确保文件在OSS中
|
||||
if (file.getStorageType() != null &&
|
||||
(file.getStorageType().contains("OSS") || file.getStorageType().contains("ALIYUN"))) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (file.getPath() != null) {
|
||||
String path = file.getPath();
|
||||
if (path.contains("oss://") || path.contains("aliyun") ||
|
||||
path.startsWith("picture/") || path.startsWith("video/") || path.startsWith("file/")) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
})
|
||||
.limit(1000) // 限制最大同步数量
|
||||
.collect(Collectors.toList());
|
||||
|
||||
// 2. 批量同步到MinIO
|
||||
int totalFiles = filesToSync.size();
|
||||
int successCount = 0;
|
||||
int failCount = 0;
|
||||
|
||||
log.info("开始批量同步,共找到 {} 个文件需要同步", totalFiles);
|
||||
|
||||
for (FileInfo fileInfo : filesToSync) {
|
||||
try {
|
||||
if (ossToS3SyncService != null) {
|
||||
boolean syncResult = ossToS3SyncService.syncFileToS3(fileInfo);
|
||||
if (syncResult) {
|
||||
successCount++;
|
||||
log.debug("文件同步成功: {}", fileInfo.getPath());
|
||||
} else {
|
||||
failCount++;
|
||||
log.warn("文件同步失败: {}", fileInfo.getPath());
|
||||
}
|
||||
} else {
|
||||
failCount++;
|
||||
log.warn("OSS到S3同步服务未配置,文件同步失败: {}", fileInfo.getPath());
|
||||
}
|
||||
|
||||
// 控制同步速度
|
||||
Thread.sleep(100);
|
||||
|
||||
} catch (Exception e) {
|
||||
failCount++;
|
||||
log.error("文件同步异常: {}, error: {}", fileInfo.getPath(), e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
// 3. 返回同步结果
|
||||
result.put("syncDays", syncDays);
|
||||
result.put("totalFiles", totalFiles);
|
||||
result.put("successCount", successCount);
|
||||
result.put("failCount", failCount);
|
||||
result.put("message", String.format("批量同步完成,总数: %d, 成功: %d, 失败: %d", totalFiles, successCount, failCount));
|
||||
result.put("success", true);
|
||||
|
||||
return Result.succeed(result, "批量同步任务已启动");
|
||||
} catch (Exception e) {
|
||||
log.error("批量同步OSS到MinIO异常", e);
|
||||
result.put("error", e.getMessage());
|
||||
result.put("success", false);
|
||||
return Result.failed("批量同步异常:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取同步状态
|
||||
*/
|
||||
@GetMapping("/storage/sync-status")
|
||||
public Result<Map<String, Object>> getSyncStatus() {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
try {
|
||||
if (ossToMinioSyncScheduler != null) {
|
||||
String syncStatus = ossToMinioSyncScheduler.getSyncStatus();
|
||||
result.put("syncStatus", syncStatus);
|
||||
result.put("success", true);
|
||||
} else {
|
||||
result.put("error", "同步调度器未配置");
|
||||
result.put("success", false);
|
||||
}
|
||||
|
||||
return Result.succeed(result);
|
||||
} catch (Exception e) {
|
||||
log.error("获取同步状态失败", e);
|
||||
result.put("error", e.getMessage());
|
||||
result.put("success", false);
|
||||
return Result.failed("获取同步状态失败");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 手动启动夜间同步
|
||||
*/
|
||||
@PostMapping("/storage/start-night-sync")
|
||||
public Result<Map<String, Object>> startNightSync() {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
try {
|
||||
if (ossToMinioSyncScheduler != null) {
|
||||
ossToMinioSyncScheduler.manualStartNightSync();
|
||||
result.put("message", "夜间同步已启动");
|
||||
result.put("success", true);
|
||||
} else {
|
||||
result.put("error", "同步调度器未配置");
|
||||
result.put("success", false);
|
||||
}
|
||||
|
||||
return Result.succeed(result);
|
||||
} catch (Exception e) {
|
||||
log.error("启动夜间同步失败", e);
|
||||
result.put("error", e.getMessage());
|
||||
result.put("success", false);
|
||||
return Result.failed("启动夜间同步失败");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 手动停止夜间同步
|
||||
*/
|
||||
@PostMapping("/storage/stop-night-sync")
|
||||
public Result<Map<String, Object>> stopNightSync() {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
try {
|
||||
if (ossToMinioSyncScheduler != null) {
|
||||
ossToMinioSyncScheduler.manualStopNightSync();
|
||||
result.put("message", "夜间同步已停止");
|
||||
result.put("success", true);
|
||||
} else {
|
||||
result.put("error", "同步调度器未配置");
|
||||
result.put("success", false);
|
||||
}
|
||||
|
||||
return Result.succeed(result);
|
||||
} catch (Exception e) {
|
||||
log.error("停止夜间同步失败", e);
|
||||
result.put("error", e.getMessage());
|
||||
result.put("success", false);
|
||||
return Result.failed("停止夜间同步失败");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试同步功能
|
||||
*/
|
||||
@PostMapping("/storage/test-sync")
|
||||
public Result<Map<String, Object>> testSync() {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
try {
|
||||
if (ossToMinioSyncScheduler == null) {
|
||||
result.put("error", "同步调度器未配置");
|
||||
result.put("success", false);
|
||||
return Result.failed("同步调度器未配置");
|
||||
}
|
||||
|
||||
// 启动测试同步
|
||||
ossToMinioSyncScheduler.manualStartNightSync();
|
||||
|
||||
result.put("message", "测试同步已启动");
|
||||
result.put("success", true);
|
||||
result.put("testMode", true);
|
||||
|
||||
return Result.succeed(result, "测试同步已启动");
|
||||
} catch (Exception e) {
|
||||
log.error("测试同步失败", e);
|
||||
result.put("error", e.getMessage());
|
||||
result.put("success", false);
|
||||
return Result.failed("测试同步失败");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 立即同步指定文件
|
||||
*/
|
||||
@PostMapping("/storage/sync-file-now")
|
||||
public Result<Map<String, Object>> syncFileNow(@RequestParam String path) {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
try {
|
||||
if (ossToS3SyncService == null) {
|
||||
result.put("error", "同步服务未配置");
|
||||
result.put("success", false);
|
||||
return Result.failed("同步服务未配置");
|
||||
}
|
||||
|
||||
log.info("立即同步文件: {}", path);
|
||||
boolean syncResult = ossToS3SyncService.syncFileToS3(path);
|
||||
|
||||
result.put("path", path);
|
||||
result.put("syncResult", syncResult);
|
||||
result.put("success", syncResult);
|
||||
|
||||
if (syncResult) {
|
||||
return Result.succeed(result, "文件同步成功");
|
||||
} else {
|
||||
return Result.failed("文件同步失败");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("立即同步文件失败: path={}", path, e);
|
||||
result.put("path", path);
|
||||
result.put("error", e.getMessage());
|
||||
result.put("success", false);
|
||||
return Result.failed("立即同步失败:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查数据库文件状态
|
||||
*/
|
||||
@GetMapping("/storage/check-file-status")
|
||||
public Result<Map<String, Object>> checkFileStatus() {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
try {
|
||||
// 查询数据库中的文件统计信息
|
||||
List<FileInfo> allFiles = fileMapper.selectList(null);
|
||||
List<FileInfo> recentFiles = fileMapper.selectHotDataFiles(
|
||||
LocalDateTime.now().minusDays(7), 1000);
|
||||
|
||||
// 统计信息
|
||||
Map<String, Object> stats = new HashMap<>();
|
||||
stats.put("totalFiles", allFiles.size());
|
||||
stats.put("recentFiles", recentFiles.size());
|
||||
|
||||
// 存储类型统计
|
||||
long nullStorageType = allFiles.stream()
|
||||
.filter(f -> f.getStorageType() == null)
|
||||
.count();
|
||||
long ossFiles = allFiles.stream()
|
||||
.filter(f -> f.getStorageType() != null && f.getStorageType().contains("OSS"))
|
||||
.count();
|
||||
long s3Files = allFiles.stream()
|
||||
.filter(f -> f.getStorageType() != null && f.getStorageType().contains("S3"))
|
||||
.count();
|
||||
|
||||
stats.put("nullStorageType", nullStorageType);
|
||||
stats.put("ossFiles", ossFiles);
|
||||
stats.put("s3Files", s3Files);
|
||||
|
||||
// 路径特征统计
|
||||
long ossPathFiles = allFiles.stream()
|
||||
.filter(f -> f.getPath() != null && f.getPath().contains("oss://"))
|
||||
.count();
|
||||
long s3PathFiles = allFiles.stream()
|
||||
.filter(f -> f.getPath() != null && f.getPath().contains("s3://"))
|
||||
.count();
|
||||
|
||||
stats.put("ossPathFiles", ossPathFiles);
|
||||
stats.put("s3PathFiles", s3PathFiles);
|
||||
|
||||
// 最近文件示例
|
||||
List<Map<String, Object>> recentFileExamples = recentFiles.stream()
|
||||
.limit(5)
|
||||
.map(f -> {
|
||||
Map<String, Object> fileInfo = new HashMap<>();
|
||||
fileInfo.put("id", f.getId());
|
||||
fileInfo.put("name", f.getName());
|
||||
fileInfo.put("path", f.getPath());
|
||||
fileInfo.put("storageType", f.getStorageType());
|
||||
fileInfo.put("createTime", f.getCreateTime());
|
||||
return fileInfo;
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
|
||||
stats.put("recentFileExamples", recentFileExamples);
|
||||
|
||||
result.put("stats", stats);
|
||||
result.put("success", true);
|
||||
|
||||
return Result.succeed(result, "文件状态检查完成");
|
||||
} catch (Exception e) {
|
||||
log.error("检查文件状态失败", e);
|
||||
result.put("error", e.getMessage());
|
||||
result.put("success", false);
|
||||
return Result.failed("检查文件状态失败:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 诊断热数据同步问题
|
||||
*/
|
||||
@GetMapping("/storage/diagnose-hot-sync")
|
||||
public Result<Map<String, Object>> diagnoseHotSync() {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
try {
|
||||
Map<String, Object> diagnosis = new HashMap<>();
|
||||
|
||||
// 1. 检查配置
|
||||
diagnosis.put("hotDataDays", 7);
|
||||
diagnosis.put("batchSize", 100);
|
||||
diagnosis.put("accessThreshold", 10);
|
||||
|
||||
// 2. 检查数据库文件
|
||||
List<FileInfo> allFiles = fileMapper.selectList(null);
|
||||
List<FileInfo> recentFiles = fileMapper.selectHotDataFiles(
|
||||
LocalDateTime.now().minusDays(7), 1000);
|
||||
|
||||
diagnosis.put("totalFiles", allFiles.size());
|
||||
diagnosis.put("recentFiles", recentFiles.size());
|
||||
|
||||
// 3. 分析文件存储类型
|
||||
Map<String, Long> storageTypeStats = allFiles.stream()
|
||||
.collect(Collectors.groupingBy(
|
||||
f -> f.getStorageType() == null ? "NULL" : f.getStorageType(),
|
||||
Collectors.counting()
|
||||
));
|
||||
diagnosis.put("storageTypeStats", storageTypeStats);
|
||||
|
||||
// 4. 分析路径特征
|
||||
Map<String, Long> pathStats = allFiles.stream()
|
||||
.collect(Collectors.groupingBy(
|
||||
f -> {
|
||||
if (f.getPath() == null) return "NULL_PATH";
|
||||
if (f.getPath().contains("oss://")) return "OSS_PATH";
|
||||
if (f.getPath().contains("s3://")) return "S3_PATH";
|
||||
if (f.getPath().contains("minio")) return "MINIO_PATH";
|
||||
if (f.getPath().startsWith("picture/")) return "PICTURE_PATH";
|
||||
if (f.getPath().startsWith("video/")) return "VIDEO_PATH";
|
||||
if (f.getPath().startsWith("file/")) return "FILE_PATH";
|
||||
return "OTHER_PATH";
|
||||
},
|
||||
Collectors.counting()
|
||||
));
|
||||
diagnosis.put("pathStats", pathStats);
|
||||
|
||||
// 5. 检查最近文件的详细信息
|
||||
List<Map<String, Object>> recentFileDetails = recentFiles.stream()
|
||||
.limit(10)
|
||||
.map(f -> {
|
||||
Map<String, Object> fileDetail = new HashMap<>();
|
||||
fileDetail.put("id", f.getId());
|
||||
fileDetail.put("name", f.getName());
|
||||
fileDetail.put("path", f.getPath());
|
||||
fileDetail.put("storageType", f.getStorageType());
|
||||
fileDetail.put("size", f.getSize());
|
||||
fileDetail.put("createTime", f.getCreateTime());
|
||||
fileDetail.put("url", f.getUrl());
|
||||
return fileDetail;
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
diagnosis.put("recentFileDetails", recentFileDetails);
|
||||
|
||||
// 6. 模拟热数据过滤逻辑(使用修改后的逻辑)
|
||||
List<FileInfo> filteredFiles = recentFiles.stream()
|
||||
.filter(file -> {
|
||||
// 模拟 isFileInS3 检查(修改后的逻辑)
|
||||
boolean inS3 = false;
|
||||
if (file.getStorageType() != null &&
|
||||
(file.getStorageType().contains("S3") || file.getStorageType().contains("MINIO"))) {
|
||||
inS3 = true;
|
||||
}
|
||||
if (file.getPath() != null) {
|
||||
String path = file.getPath();
|
||||
if (path.contains("s3://") || path.contains("minio") ||
|
||||
path.contains("s3-storage/") || path.contains("cold-storage/")) {
|
||||
inS3 = true;
|
||||
}
|
||||
}
|
||||
|
||||
// 模拟 isFileInOSS 检查(修改后的逻辑)
|
||||
boolean inOSS = false;
|
||||
if (file.getStorageType() != null &&
|
||||
(file.getStorageType().contains("OSS") || file.getStorageType().contains("ALIYUN"))) {
|
||||
inOSS = true;
|
||||
}
|
||||
if (file.getPath() != null) {
|
||||
String path = file.getPath();
|
||||
if (path.contains("oss://") || path.contains("aliyun") ||
|
||||
path.startsWith("picture/") || path.startsWith("video/") || path.startsWith("file/")) {
|
||||
inOSS = true;
|
||||
}
|
||||
}
|
||||
|
||||
return !inS3 && inOSS;
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
|
||||
diagnosis.put("filteredFiles", filteredFiles.size());
|
||||
diagnosis.put("filteredFileDetails", filteredFiles.stream()
|
||||
.limit(5)
|
||||
.map(f -> {
|
||||
Map<String, Object> detail = new HashMap<>();
|
||||
detail.put("id", f.getId());
|
||||
detail.put("name", f.getName());
|
||||
detail.put("path", f.getPath());
|
||||
detail.put("storageType", f.getStorageType());
|
||||
return detail;
|
||||
})
|
||||
.collect(Collectors.toList()));
|
||||
|
||||
// 7. 问题分析
|
||||
Map<String, Object> analysis = new HashMap<>();
|
||||
analysis.put("step1", "查询最近7天内的文件: " + recentFiles.size() + "个");
|
||||
analysis.put("step2", "过滤掉已在S3中的文件");
|
||||
analysis.put("step3", "过滤掉不在OSS中的文件");
|
||||
analysis.put("step4", "剩余需要同步的文件: " + filteredFiles.size() + "个");
|
||||
|
||||
if (filteredFiles.isEmpty()) {
|
||||
if (recentFiles.isEmpty()) {
|
||||
analysis.put("conclusion", "没有最近7天内的文件,需要检查文件上传时间");
|
||||
} else {
|
||||
analysis.put("conclusion", "有最近文件但都被过滤掉了,可能原因:1)文件已在S3中 2)文件不在OSS中 3)存储类型标识问题");
|
||||
}
|
||||
} else {
|
||||
analysis.put("conclusion", "找到需要同步的文件,但同步服务可能有问题");
|
||||
}
|
||||
|
||||
diagnosis.put("analysis", analysis);
|
||||
|
||||
result.put("diagnosis", diagnosis);
|
||||
result.put("success", true);
|
||||
|
||||
return Result.succeed(result, "热数据同步诊断完成");
|
||||
} catch (Exception e) {
|
||||
log.error("诊断热数据同步失败", e);
|
||||
result.put("error", e.getMessage());
|
||||
result.put("success", false);
|
||||
return Result.failed("诊断热数据同步失败:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 诊断夜间同步问题
|
||||
*/
|
||||
@GetMapping("/storage/diagnose-night-sync")
|
||||
public Result<Map<String, Object>> diagnoseNightSync() {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
try {
|
||||
Map<String, Object> diagnosis = new HashMap<>();
|
||||
|
||||
// 1. 检查配置参数
|
||||
diagnosis.put("hotDataDays", 30); // 默认30天
|
||||
diagnosis.put("batchSize", 50);
|
||||
diagnosis.put("syncInterval", 300000); // 5分钟
|
||||
|
||||
// 2. 检查数据库文件
|
||||
List<FileInfo> allFiles = fileMapper.selectList(null);
|
||||
|
||||
// 计算冷数据阈值
|
||||
LocalDateTime coldDataThreshold = LocalDateTime.now().minusDays(30);
|
||||
|
||||
// 过滤出冷数据文件
|
||||
List<FileInfo> coldFiles = allFiles.stream()
|
||||
.filter(file -> {
|
||||
if (file.getCreateTime() == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
LocalDateTime createTime = file.getCreateTime().toInstant()
|
||||
.atZone(java.time.ZoneId.systemDefault())
|
||||
.toLocalDateTime();
|
||||
|
||||
return createTime.isBefore(coldDataThreshold);
|
||||
})
|
||||
.filter(file -> {
|
||||
// 过滤掉已经在S3中的文件
|
||||
if (file.getStorageType() != null &&
|
||||
(file.getStorageType().contains("S3") || file.getStorageType().contains("MINIO"))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (file.getPath() != null &&
|
||||
(file.getPath().contains("s3://") || file.getPath().contains("minio") ||
|
||||
file.getPath().contains("s3-storage/") || file.getPath().contains("cold-storage/"))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
})
|
||||
.filter(file -> {
|
||||
// 确保文件在OSS中
|
||||
if (file.getStorageType() != null &&
|
||||
(file.getStorageType().contains("OSS") || file.getStorageType().contains("ALIYUN"))) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (file.getPath() != null) {
|
||||
String path = file.getPath();
|
||||
if (path.contains("oss://") || path.contains("aliyun") ||
|
||||
path.startsWith("picture/") || path.startsWith("video/") || path.startsWith("file/")) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
})
|
||||
.limit(100)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
diagnosis.put("totalFiles", allFiles.size());
|
||||
diagnosis.put("coldDataThreshold", coldDataThreshold.toString());
|
||||
diagnosis.put("coldFiles", coldFiles.size());
|
||||
|
||||
// 3. 冷数据文件示例
|
||||
List<Map<String, Object>> coldFileExamples = coldFiles.stream()
|
||||
.limit(10)
|
||||
.map(f -> {
|
||||
Map<String, Object> fileInfo = new HashMap<>();
|
||||
fileInfo.put("id", f.getId());
|
||||
fileInfo.put("name", f.getName());
|
||||
fileInfo.put("path", f.getPath());
|
||||
fileInfo.put("storageType", f.getStorageType());
|
||||
fileInfo.put("createTime", f.getCreateTime());
|
||||
fileInfo.put("size", f.getSize());
|
||||
return fileInfo;
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
|
||||
diagnosis.put("coldFileExamples", coldFileExamples);
|
||||
|
||||
// 4. 同步逻辑分析
|
||||
Map<String, Object> analysis = new HashMap<>();
|
||||
analysis.put("step1", "查询所有文件: " + allFiles.size() + "个");
|
||||
analysis.put("step2", "过滤出冷数据文件(创建时间早于" + coldDataThreshold + ")");
|
||||
analysis.put("step3", "过滤掉已在S3中的文件");
|
||||
analysis.put("step4", "确保文件在OSS中");
|
||||
analysis.put("step5", "剩余需要同步的冷数据文件: " + coldFiles.size() + "个");
|
||||
|
||||
if (coldFiles.isEmpty()) {
|
||||
analysis.put("conclusion", "没有找到需要同步的冷数据文件,可能原因:1)所有文件都是热数据 2)所有文件都已同步到S3 3)文件不在OSS中");
|
||||
} else {
|
||||
analysis.put("conclusion", "找到需要同步的冷数据文件,夜间同步应该能正常工作");
|
||||
}
|
||||
|
||||
diagnosis.put("analysis", analysis);
|
||||
|
||||
result.put("diagnosis", diagnosis);
|
||||
result.put("success", true);
|
||||
|
||||
return Result.succeed(result, "夜间同步诊断完成");
|
||||
} catch (Exception e) {
|
||||
log.error("诊断夜间同步失败", e);
|
||||
result.put("error", e.getMessage());
|
||||
result.put("success", false);
|
||||
return Result.failed("诊断夜间同步失败:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+227
@@ -10,6 +10,7 @@ import org.springframework.web.bind.annotation.*;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import com.central.common.model.Result;
|
||||
|
||||
/**
|
||||
* 热数据同步控制器
|
||||
@@ -194,4 +195,230 @@ public class HotDataSyncController {
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 诊断S3配置和URL生成
|
||||
*/
|
||||
@Operation(summary = "诊断S3配置和URL生成")
|
||||
@GetMapping("/diagnose")
|
||||
public Result<Map<String, Object>> diagnoseS3Config() {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
|
||||
try {
|
||||
// 检查S3配置
|
||||
result.put("s3Enabled", hotDataSyncService.isS3Enabled());
|
||||
result.put("enhancedS3ServiceAvailable", hotDataSyncService.isEnhancedS3ServiceAvailable());
|
||||
result.put("s3ServiceAvailable", hotDataSyncService.isS3ServiceAvailable());
|
||||
|
||||
// 检查S3配置信息
|
||||
result.put("s3Config", hotDataSyncService.getS3ConfigInfo());
|
||||
|
||||
// 测试URL生成
|
||||
result.put("urlTest", hotDataSyncService.testUrlGeneration());
|
||||
|
||||
// 检查热同步配置
|
||||
result.put("hotSyncConfig", hotDataSyncService.getHotSyncConfig());
|
||||
|
||||
// 测试新的S3路径生成
|
||||
Map<String, Object> pathTest = new HashMap<>();
|
||||
pathTest.put("oldPath", "hot-sync/test-file.txt");
|
||||
pathTest.put("newPath", "s3://test-file.txt");
|
||||
result.put("pathTest", pathTest);
|
||||
|
||||
return Result.succeed(result);
|
||||
} catch (Exception e) {
|
||||
log.error("诊断S3配置失败", e);
|
||||
result.put("error", e.getMessage());
|
||||
return Result.failed("诊断失败:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 详细诊断热数据同步问题
|
||||
*/
|
||||
@Operation(summary = "详细诊断热数据同步问题")
|
||||
@GetMapping("/diagnose-detailed")
|
||||
public Result<Map<String, Object>> diagnoseHotSyncDetailed() {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
|
||||
try {
|
||||
// 1. 检查配置参数
|
||||
Map<String, Object> config = new HashMap<>();
|
||||
config.put("syncEnabled", hotDataSyncService.isRunning());
|
||||
config.put("hotDataDays", 7); // 默认7天
|
||||
config.put("batchSize", 100);
|
||||
config.put("accessThreshold", 10);
|
||||
result.put("config", config);
|
||||
|
||||
// 2. 检查数据库文件统计
|
||||
Map<String, Object> dbStats = new HashMap<>();
|
||||
|
||||
// 这里需要注入FileMapper,暂时用模拟数据
|
||||
dbStats.put("totalFiles", "需要查询数据库");
|
||||
dbStats.put("recentFiles", "需要查询数据库");
|
||||
dbStats.put("ossFiles", "需要查询数据库");
|
||||
dbStats.put("s3Files", "需要查询数据库");
|
||||
result.put("databaseStats", dbStats);
|
||||
|
||||
// 3. 检查OSS服务状态
|
||||
Map<String, Object> ossStatus = new HashMap<>();
|
||||
try {
|
||||
// 这里可以添加OSS服务检查逻辑
|
||||
ossStatus.put("status", "需要检查OSS服务");
|
||||
ossStatus.put("accessible", "需要测试");
|
||||
} catch (Exception e) {
|
||||
ossStatus.put("status", "OSS服务检查失败");
|
||||
ossStatus.put("error", e.getMessage());
|
||||
}
|
||||
result.put("ossStatus", ossStatus);
|
||||
|
||||
// 4. 检查S3服务状态
|
||||
Map<String, Object> s3Status = new HashMap<>();
|
||||
s3Status.put("s3Enabled", hotDataSyncService.isS3Enabled());
|
||||
s3Status.put("enhancedS3ServiceAvailable", hotDataSyncService.isEnhancedS3ServiceAvailable());
|
||||
s3Status.put("s3ServiceAvailable", hotDataSyncService.isS3ServiceAvailable());
|
||||
result.put("s3Status", s3Status);
|
||||
|
||||
// 5. 同步逻辑分析
|
||||
Map<String, Object> syncLogic = new HashMap<>();
|
||||
syncLogic.put("step1", "查询最近7天内的文件");
|
||||
syncLogic.put("step2", "过滤掉已在S3中的文件");
|
||||
syncLogic.put("step3", "过滤掉不在OSS中的文件");
|
||||
syncLogic.put("step4", "剩余文件即为需要同步的文件");
|
||||
result.put("syncLogic", syncLogic);
|
||||
|
||||
// 6. 可能的问题原因
|
||||
Map<String, Object> possibleIssues = new HashMap<>();
|
||||
possibleIssues.put("issue1", "数据库中没有最近7天内的文件");
|
||||
possibleIssues.put("issue2", "所有文件都已经在S3中");
|
||||
possibleIssues.put("issue3", "文件不在OSS中(OSS服务问题)");
|
||||
possibleIssues.put("issue4", "文件存储类型标识不正确");
|
||||
possibleIssues.put("issue5", "OSS/S3服务配置问题");
|
||||
result.put("possibleIssues", possibleIssues);
|
||||
|
||||
// 7. 建议的排查步骤
|
||||
Map<String, Object> troubleshooting = new HashMap<>();
|
||||
troubleshooting.put("step1", "检查数据库中的文件数据");
|
||||
troubleshooting.put("step2", "检查OSS服务是否正常");
|
||||
troubleshooting.put("step3", "检查S3服务是否正常");
|
||||
troubleshooting.put("step4", "检查文件存储类型标识");
|
||||
troubleshooting.put("step5", "手动测试单个文件同步");
|
||||
result.put("troubleshooting", troubleshooting);
|
||||
|
||||
return Result.succeed(result);
|
||||
} catch (Exception e) {
|
||||
log.error("详细诊断热数据同步失败", e);
|
||||
result.put("error", e.getMessage());
|
||||
return Result.failed("详细诊断失败:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试URL访问
|
||||
*/
|
||||
@Operation(summary = "测试URL访问")
|
||||
@PostMapping("/test-url")
|
||||
public Result<Map<String, Object>> testUrlAccess(@RequestParam String url) {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
|
||||
try {
|
||||
log.info("测试URL访问: {}", url);
|
||||
|
||||
// 创建HTTP连接
|
||||
java.net.URL testUrl = new java.net.URL(url);
|
||||
java.net.HttpURLConnection connection = (java.net.HttpURLConnection) testUrl.openConnection();
|
||||
connection.setRequestMethod("GET");
|
||||
connection.setConnectTimeout(10000); // 10秒连接超时
|
||||
connection.setReadTimeout(30000); // 30秒读取超时
|
||||
|
||||
// 设置User-Agent
|
||||
connection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36");
|
||||
|
||||
int responseCode = connection.getResponseCode();
|
||||
String responseMessage = connection.getResponseMessage();
|
||||
|
||||
result.put("url", url);
|
||||
result.put("responseCode", responseCode);
|
||||
result.put("responseMessage", responseMessage);
|
||||
result.put("contentType", connection.getContentType());
|
||||
result.put("contentLength", connection.getContentLengthLong());
|
||||
result.put("accessible", responseCode == 200);
|
||||
|
||||
// 获取响应头信息
|
||||
Map<String, String> headers = new HashMap<>();
|
||||
connection.getHeaderFields().forEach((key, values) -> {
|
||||
if (key != null && values != null && !values.isEmpty()) {
|
||||
headers.put(key, String.join(", ", values));
|
||||
}
|
||||
});
|
||||
result.put("headers", headers);
|
||||
|
||||
log.info("URL访问测试结果: 状态码={}, 消息={}, 可访问={}", responseCode, responseMessage, responseCode == 200);
|
||||
|
||||
return Result.succeed(result);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("测试URL访问失败: {}", url, e);
|
||||
result.put("url", url);
|
||||
result.put("error", e.getMessage());
|
||||
result.put("accessible", false);
|
||||
return Result.failed("URL访问测试失败:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试文件同步到S3
|
||||
*/
|
||||
@Operation(summary = "测试文件同步到S3")
|
||||
@PostMapping("/test-sync")
|
||||
public Result<Map<String, Object>> testFileSync(@RequestParam String fileId) {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
|
||||
try {
|
||||
log.info("测试文件同步到S3: fileId={}", fileId);
|
||||
|
||||
boolean success = hotDataSyncService.syncSpecificFile(fileId);
|
||||
|
||||
result.put("fileId", fileId);
|
||||
result.put("success", success);
|
||||
result.put("message", success ? "文件同步成功" : "文件同步失败");
|
||||
result.put("timestamp", System.currentTimeMillis());
|
||||
|
||||
return Result.succeed(result);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("测试文件同步失败: fileId={}", fileId, e);
|
||||
result.put("fileId", fileId);
|
||||
result.put("error", e.getMessage());
|
||||
result.put("success", false);
|
||||
return Result.failed("文件同步测试失败:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试URL生成
|
||||
*/
|
||||
@Operation(summary = "测试URL生成")
|
||||
@PostMapping("/test-url-generation")
|
||||
public Result<Map<String, Object>> testUrlGeneration(@RequestParam String path) {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
|
||||
try {
|
||||
log.info("测试URL生成: path={}", path);
|
||||
|
||||
// 通过HotDataSyncService获取URL生成信息
|
||||
Map<String, Object> urlTest = hotDataSyncService.testUrlGeneration();
|
||||
result.put("path", path);
|
||||
result.put("urlTest", urlTest);
|
||||
result.put("timestamp", System.currentTimeMillis());
|
||||
|
||||
return Result.succeed(result);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("测试URL生成失败: path={}", path, e);
|
||||
result.put("path", path);
|
||||
result.put("error", e.getMessage());
|
||||
return Result.failed("URL生成测试失败:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+102
@@ -0,0 +1,102 @@
|
||||
package com.central.file.service;
|
||||
|
||||
import com.central.common.model.FileInfo;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.context.event.EventListener;
|
||||
import org.springframework.scheduling.annotation.Async;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
|
||||
/**
|
||||
* 文件同步事件监听器
|
||||
* 监听文件访问事件,自动触发同步
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class FileSyncEventListener {
|
||||
|
||||
@Autowired
|
||||
private OssToS3SyncService ossToS3SyncService;
|
||||
|
||||
@Value("${zlt.storage.hot-data-days:30}")
|
||||
private int hotDataDays;
|
||||
|
||||
@Value("${zlt.storage.sync.event-driven:true}")
|
||||
private boolean eventDrivenSync; // 是否启用事件驱动同步
|
||||
|
||||
/**
|
||||
* 监听文件访问事件
|
||||
* 当访问冷数据文件时,自动触发同步
|
||||
*/
|
||||
@EventListener
|
||||
@Async
|
||||
public void handleFileAccessEvent(FileAccessEvent event) {
|
||||
if (!eventDrivenSync) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
FileInfo fileInfo = event.getFileInfo();
|
||||
if (fileInfo == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
// 检查是否为冷数据
|
||||
if (isColdData(fileInfo)) {
|
||||
log.info("检测到冷数据文件访问,触发同步: {}", fileInfo.getPath());
|
||||
|
||||
// 异步同步文件
|
||||
boolean syncResult = ossToS3SyncService.syncFileToS3(fileInfo);
|
||||
if (syncResult) {
|
||||
log.info("事件驱动同步成功: {}", fileInfo.getPath());
|
||||
} else {
|
||||
log.warn("事件驱动同步失败: {}", fileInfo.getPath());
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("处理文件访问事件失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查是否为冷数据
|
||||
*/
|
||||
private boolean isColdData(FileInfo fileInfo) {
|
||||
if (fileInfo.getCreateTime() == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
LocalDateTime createTime = fileInfo.getCreateTime().toInstant()
|
||||
.atZone(java.time.ZoneId.systemDefault())
|
||||
.toLocalDateTime();
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
|
||||
long daysDiff = ChronoUnit.DAYS.between(createTime, now);
|
||||
return daysDiff > hotDataDays;
|
||||
}
|
||||
|
||||
/**
|
||||
* 文件访问事件
|
||||
*/
|
||||
public static class FileAccessEvent {
|
||||
private final FileInfo fileInfo;
|
||||
private final String accessType; // "READ", "WRITE", "DELETE"
|
||||
|
||||
public FileAccessEvent(FileInfo fileInfo, String accessType) {
|
||||
this.fileInfo = fileInfo;
|
||||
this.accessType = accessType;
|
||||
}
|
||||
|
||||
public FileInfo getFileInfo() {
|
||||
return fileInfo;
|
||||
}
|
||||
|
||||
public String getAccessType() {
|
||||
return accessType;
|
||||
}
|
||||
}
|
||||
}
|
||||
+234
-29
@@ -19,6 +19,8 @@ import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
import java.util.Map;
|
||||
import java.util.HashMap;
|
||||
|
||||
/**
|
||||
* 热数据自动同步服务
|
||||
@@ -203,10 +205,14 @@ public class HotDataSyncService {
|
||||
log.info("开始同步文件到S3,文件ID: {}, 文件名: {}, 重试次数: {}/{}",
|
||||
fileInfo.getId(), fileInfo.getName(), retryCount + 1, maxRetries);
|
||||
|
||||
// 获取原始OSS路径(不包含hot-sync前缀)
|
||||
String originalPath = getOriginalPath(fileInfo);
|
||||
log.debug("原始OSS路径: {}", originalPath);
|
||||
|
||||
// 从OSS获取文件URL
|
||||
String ossUrl = ossService.getViewUrlByPath(fileInfo.getPath());
|
||||
String ossUrl = ossService.getViewUrlByPath(originalPath);
|
||||
if (ossUrl == null || ossUrl.isEmpty()) {
|
||||
log.error("从OSS获取文件URL失败,文件ID: {}", fileInfo.getId());
|
||||
log.error("从OSS获取文件URL失败,文件ID: {}, 路径: {}", fileInfo.getId(), originalPath);
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -219,27 +225,39 @@ public class HotDataSyncService {
|
||||
// 使用增强的S3服务下载并上传文件
|
||||
boolean uploadSuccess = false;
|
||||
if (enhancedS3Service != null) {
|
||||
log.info("使用增强S3服务同步文件: {} -> {}", ossUrl, s3Path);
|
||||
uploadSuccess = enhancedS3Service.downloadAndUpload(ossUrl, s3Path);
|
||||
} else if (s3Service != null) {
|
||||
// 使用基础S3服务(简化实现)
|
||||
// 使用基础S3服务
|
||||
log.warn("使用基础S3服务,功能可能受限");
|
||||
uploadSuccess = true; // 临时设置为true,实际需要实现具体的上传逻辑
|
||||
// 这里需要实现具体的上传逻辑
|
||||
uploadSuccess = false; // 暂时设置为false,需要实现具体逻辑
|
||||
} else {
|
||||
log.error("S3服务未配置,无法同步文件");
|
||||
return false;
|
||||
}
|
||||
|
||||
if (uploadSuccess) {
|
||||
// 更新文件存储信息
|
||||
updateFileStorageInfo(fileInfo, s3Path);
|
||||
log.info("文件同步成功,文件ID: {}, 新路径: {}", fileInfo.getId(), s3Path);
|
||||
return true;
|
||||
// 验证文件是否真的上传成功
|
||||
if (verifyFileUpload(s3Path)) {
|
||||
// 更新文件存储信息
|
||||
updateFileStorageInfo(fileInfo, s3Path);
|
||||
log.info("文件同步成功,文件ID: {}, 新路径: {}", fileInfo.getId(), s3Path);
|
||||
return true;
|
||||
} else {
|
||||
log.error("文件上传验证失败,文件ID: {}", fileInfo.getId());
|
||||
retryCount++;
|
||||
if (retryCount < maxRetries) {
|
||||
log.info("准备重试,等待2秒后重试...");
|
||||
Thread.sleep(2000);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
log.error("文件上传到S3失败,文件ID: {}", fileInfo.getId());
|
||||
retryCount++;
|
||||
if (retryCount < maxRetries) {
|
||||
log.info("准备重试,等待2秒后重试...");
|
||||
Thread.sleep(2000); // 等待2秒后重试
|
||||
Thread.sleep(2000);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -254,7 +272,7 @@ public class HotDataSyncService {
|
||||
if (retryCount < maxRetries) {
|
||||
try {
|
||||
log.info("准备重试,等待2秒后重试...");
|
||||
Thread.sleep(2000); // 等待2秒后重试
|
||||
Thread.sleep(2000);
|
||||
} catch (InterruptedException ie) {
|
||||
log.error("重试等待被中断", ie);
|
||||
Thread.currentThread().interrupt();
|
||||
@@ -311,20 +329,40 @@ public class HotDataSyncService {
|
||||
// 检查存储类型
|
||||
if (fileInfo.getStorageType() != null &&
|
||||
(fileInfo.getStorageType().contains("S3") || fileInfo.getStorageType().contains("MINIO"))) {
|
||||
log.debug("文件存储类型标识为S3,文件ID: {}", fileInfo.getId());
|
||||
return true;
|
||||
}
|
||||
|
||||
// 检查路径特征
|
||||
if (fileInfo.getPath() != null &&
|
||||
(fileInfo.getPath().contains("s3://") || fileInfo.getPath().contains("minio"))) {
|
||||
return true;
|
||||
if (fileInfo.getPath() != null) {
|
||||
String path = fileInfo.getPath();
|
||||
|
||||
// 标准S3路径格式
|
||||
if (path.contains("s3://") || path.contains("minio")) {
|
||||
log.debug("文件路径包含S3标识,文件ID: {}", fileInfo.getId());
|
||||
return true;
|
||||
}
|
||||
|
||||
// 检查是否包含S3存储标识
|
||||
if (path.contains("s3-storage/") || path.contains("cold-storage/")) {
|
||||
log.debug("文件路径包含S3存储标识,文件ID: {}", fileInfo.getId());
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// 使用增强S3服务检查文件是否存在
|
||||
if (enhancedS3Service != null && fileInfo.getPath() != null) {
|
||||
return enhancedS3Service.fileExists(fileInfo.getPath());
|
||||
try {
|
||||
boolean exists = enhancedS3Service.fileExists(fileInfo.getPath());
|
||||
log.debug("S3服务检查文件存在,文件ID: {}, 存在: {}", fileInfo.getId(), exists);
|
||||
return exists;
|
||||
} catch (Exception e) {
|
||||
log.warn("S3服务检查失败,文件ID: {}, path: {}", fileInfo.getId(), fileInfo.getPath(), e);
|
||||
}
|
||||
}
|
||||
|
||||
log.debug("文件不在S3中,文件ID: {}, path: {}, storageType: {}",
|
||||
fileInfo.getId(), fileInfo.getPath(), fileInfo.getStorageType());
|
||||
return false;
|
||||
} catch (Exception e) {
|
||||
log.warn("检查文件S3状态失败,文件ID: {}", fileInfo.getId(), e);
|
||||
@@ -340,21 +378,49 @@ public class HotDataSyncService {
|
||||
// 检查存储类型
|
||||
if (fileInfo.getStorageType() != null &&
|
||||
(fileInfo.getStorageType().contains("OSS") || fileInfo.getStorageType().contains("ALIYUN"))) {
|
||||
log.debug("文件存储类型标识为OSS,文件ID: {}", fileInfo.getId());
|
||||
return true;
|
||||
}
|
||||
|
||||
// 检查路径特征
|
||||
if (fileInfo.getPath() != null &&
|
||||
(fileInfo.getPath().contains("oss://") || fileInfo.getPath().contains("aliyun"))) {
|
||||
return true;
|
||||
// 检查路径特征 - 支持多种OSS路径格式
|
||||
if (fileInfo.getPath() != null) {
|
||||
String path = fileInfo.getPath();
|
||||
|
||||
// 标准OSS路径格式
|
||||
if (path.contains("oss://") || path.contains("aliyun")) {
|
||||
log.debug("文件路径包含OSS标识,文件ID: {}", fileInfo.getId());
|
||||
return true;
|
||||
}
|
||||
|
||||
// 自定义路径格式(如 picture/xxx/xxx)
|
||||
if (path.startsWith("picture/") || path.startsWith("video/") || path.startsWith("file/")) {
|
||||
log.debug("文件路径为自定义格式,文件ID: {}, path: {}", fileInfo.getId(), path);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
// 尝试从OSS获取URL,如果能获取到说明文件存在
|
||||
if (fileInfo.getPath() != null) {
|
||||
String ossUrl = ossService.getViewUrlByPath(fileInfo.getPath());
|
||||
return ossUrl != null && !ossUrl.isEmpty();
|
||||
try {
|
||||
String ossUrl = ossService.getViewUrlByPath(fileInfo.getPath());
|
||||
boolean exists = ossUrl != null && !ossUrl.isEmpty();
|
||||
log.debug("OSS服务检查文件存在,文件ID: {}, 存在: {}", fileInfo.getId(), exists);
|
||||
return exists;
|
||||
} catch (Exception e) {
|
||||
log.warn("OSS服务检查失败,文件ID: {}, path: {}", fileInfo.getId(), fileInfo.getPath(), e);
|
||||
// 如果OSS服务检查失败,但路径格式正确,仍然认为是OSS文件
|
||||
if (fileInfo.getPath() != null &&
|
||||
(fileInfo.getPath().startsWith("picture/") ||
|
||||
fileInfo.getPath().startsWith("video/") ||
|
||||
fileInfo.getPath().startsWith("file/"))) {
|
||||
log.debug("OSS服务检查失败,但路径格式正确,认为文件在OSS中,文件ID: {}", fileInfo.getId());
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
log.debug("文件不在OSS中,文件ID: {}, path: {}, storageType: {}",
|
||||
fileInfo.getId(), fileInfo.getPath(), fileInfo.getStorageType());
|
||||
return false;
|
||||
} catch (Exception e) {
|
||||
log.warn("检查文件OSS状态失败,文件ID: {}", fileInfo.getId(), e);
|
||||
@@ -368,17 +434,58 @@ public class HotDataSyncService {
|
||||
private String generateS3Path(FileInfo fileInfo) {
|
||||
String originalPath = fileInfo.getPath();
|
||||
if (originalPath == null || originalPath.isEmpty()) {
|
||||
return "hot-sync/" + fileInfo.getId() + "/" + fileInfo.getName();
|
||||
return "s3://" + fileInfo.getId() + "/" + fileInfo.getName();
|
||||
}
|
||||
|
||||
// 如果原路径包含OSS信息,替换为S3路径
|
||||
if (originalPath.contains("oss://") || originalPath.contains("aliyun")) {
|
||||
return originalPath.replace("oss://", "s3://")
|
||||
.replace("aliyun", "minio");
|
||||
// 提取文件名,避免路径过长
|
||||
String fileName = fileInfo.getName();
|
||||
if (fileName == null || fileName.isEmpty()) {
|
||||
// 从路径中提取文件名
|
||||
if (originalPath.contains("/")) {
|
||||
fileName = originalPath.substring(originalPath.lastIndexOf("/") + 1);
|
||||
} else {
|
||||
fileName = originalPath;
|
||||
}
|
||||
}
|
||||
|
||||
// 否则添加热同步前缀
|
||||
return "hot-sync/" + originalPath;
|
||||
// 生成真正的S3路径,直接使用文件名(不带前缀)
|
||||
return fileName;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取原始OSS路径(去除hot-sync前缀)
|
||||
*/
|
||||
private String getOriginalPath(FileInfo fileInfo) {
|
||||
String path = fileInfo.getPath();
|
||||
if (path == null || path.isEmpty()) {
|
||||
return path;
|
||||
}
|
||||
|
||||
// 如果路径包含hot-sync前缀,去除它
|
||||
if (path.startsWith("hot-sync/")) {
|
||||
return path.substring("hot-sync/".length());
|
||||
}
|
||||
|
||||
return path;
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证文件是否上传成功
|
||||
*/
|
||||
private boolean verifyFileUpload(String s3Path) {
|
||||
try {
|
||||
if (enhancedS3Service != null) {
|
||||
return enhancedS3Service.fileExists(s3Path);
|
||||
} else if (s3Service != null) {
|
||||
// 基础S3服务验证
|
||||
String url = s3Service.getViewUrlByPath(s3Path);
|
||||
return url != null && !url.isEmpty();
|
||||
}
|
||||
return false;
|
||||
} catch (Exception e) {
|
||||
log.warn("验证文件上传失败: {}", s3Path, e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -482,7 +589,105 @@ public class HotDataSyncService {
|
||||
* 获取配置信息
|
||||
*/
|
||||
public String getConfigInfo() {
|
||||
return String.format("批次大小: %d, 同步间隔: %d分钟, 访问阈值: %d, 热数据天数: %d, 最大线程: %d",
|
||||
batchSize, syncIntervalMinutes, accessThreshold, hotDataDays, maxThreads);
|
||||
return String.format("热数据同步配置 - 启用: %s, 批次大小: %d, 同步间隔: %d分钟, 访问阈值: %d, 最大线程数: %d, 热数据天数: %d",
|
||||
syncEnabled, batchSize, syncIntervalMinutes, accessThreshold, maxThreads, hotDataDays);
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查S3是否启用
|
||||
*/
|
||||
public boolean isS3Enabled() {
|
||||
return syncEnabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查增强S3服务是否可用
|
||||
*/
|
||||
public boolean isEnhancedS3ServiceAvailable() {
|
||||
return enhancedS3Service != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查基础S3服务是否可用
|
||||
*/
|
||||
public boolean isS3ServiceAvailable() {
|
||||
return s3Service != null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取S3配置信息
|
||||
*/
|
||||
public Map<String, Object> getS3ConfigInfo() {
|
||||
Map<String, Object> config = new HashMap<>();
|
||||
|
||||
if (enhancedS3Service != null) {
|
||||
config.put("enhancedS3Service", "可用");
|
||||
// 尝试获取S3配置信息
|
||||
try {
|
||||
// 这里可以添加更多S3配置信息的获取逻辑
|
||||
config.put("s3Template", enhancedS3Service != null ? "已配置" : "未配置");
|
||||
} catch (Exception e) {
|
||||
config.put("s3Template", "配置错误: " + e.getMessage());
|
||||
}
|
||||
} else {
|
||||
config.put("enhancedS3Service", "不可用");
|
||||
}
|
||||
|
||||
if (s3Service != null) {
|
||||
config.put("s3Service", "可用");
|
||||
} else {
|
||||
config.put("s3Service", "不可用");
|
||||
}
|
||||
|
||||
return config;
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试URL生成
|
||||
*/
|
||||
public Map<String, Object> testUrlGeneration() {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
|
||||
try {
|
||||
// 测试一个示例路径
|
||||
String testPath = "hot-sync/test-file.txt";
|
||||
|
||||
if (enhancedS3Service != null) {
|
||||
String url = enhancedS3Service.getViewUrlByPath(testPath);
|
||||
result.put("enhancedS3Url", url);
|
||||
result.put("enhancedS3UrlValid", url != null && !url.isEmpty());
|
||||
}
|
||||
|
||||
if (s3Service != null) {
|
||||
String url = s3Service.getViewUrlByPath(testPath);
|
||||
result.put("s3ServiceUrl", url);
|
||||
result.put("s3ServiceUrlValid", url != null && !url.isEmpty());
|
||||
}
|
||||
|
||||
result.put("testPath", testPath);
|
||||
|
||||
} catch (Exception e) {
|
||||
result.put("error", e.getMessage());
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取热同步配置
|
||||
*/
|
||||
public Map<String, Object> getHotSyncConfig() {
|
||||
Map<String, Object> config = new HashMap<>();
|
||||
config.put("syncEnabled", syncEnabled);
|
||||
config.put("batchSize", batchSize);
|
||||
config.put("syncIntervalMinutes", syncIntervalMinutes);
|
||||
config.put("accessThreshold", accessThreshold);
|
||||
config.put("maxThreads", maxThreads);
|
||||
config.put("hotDataDays", hotDataDays);
|
||||
config.put("running", running);
|
||||
config.put("lastSyncTime", lastSyncTime);
|
||||
config.put("totalSyncedFiles", totalSyncedFiles.get());
|
||||
config.put("totalFailedFiles", totalFailedFiles.get());
|
||||
return config;
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
+307
@@ -0,0 +1,307 @@
|
||||
package com.central.file.service;
|
||||
|
||||
import com.central.common.model.FileInfo;
|
||||
import com.central.file.mapper.FileMapper;
|
||||
import com.central.file.service.impl.OssService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.LocalTime;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
|
||||
/**
|
||||
* OSS到MinIO定时同步调度器
|
||||
* 在晚上00:00至6:00持续同步OSS数据到MinIO
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class OssToMinioSyncScheduler {
|
||||
|
||||
@Autowired
|
||||
private OssToS3SyncService ossToS3SyncService;
|
||||
|
||||
@Autowired
|
||||
private OssService ossService;
|
||||
|
||||
@Autowired
|
||||
private FileMapper fileMapper;
|
||||
|
||||
@Value("${zlt.storage.hot-data-days:30}")
|
||||
private int hotDataDays; // 热数据保留天数
|
||||
|
||||
@Value("${zlt.storage.sync.enabled:true}")
|
||||
private boolean syncEnabled; // 是否启用同步
|
||||
|
||||
@Value("${zlt.storage.sync.batch-size:50}")
|
||||
private int batchSize; // 批量同步大小
|
||||
|
||||
@Value("${zlt.storage.sync.interval:300000}")
|
||||
private long syncInterval; // 同步间隔(毫秒),默认5分钟
|
||||
|
||||
// 同步状态控制
|
||||
private final AtomicBoolean isNightSyncRunning = new AtomicBoolean(false);
|
||||
private LocalDateTime lastSyncTime = null;
|
||||
|
||||
/**
|
||||
* 每天晚上00:00启动夜间同步任务
|
||||
*/
|
||||
@Scheduled(cron = "${zlt.storage.sync.night-start:0 0 0 * * ?}")
|
||||
public void startNightSync() {
|
||||
if (!syncEnabled) {
|
||||
log.info("OSS到MinIO同步功能已禁用");
|
||||
return;
|
||||
}
|
||||
|
||||
log.info("启动夜间OSS到MinIO同步任务");
|
||||
isNightSyncRunning.set(true);
|
||||
|
||||
// 启动夜间同步循环
|
||||
new Thread(this::nightSyncLoop, "NightSyncThread").start();
|
||||
}
|
||||
|
||||
/**
|
||||
* 每天早上6:00停止夜间同步任务
|
||||
*/
|
||||
@Scheduled(cron = "${zlt.storage.sync.night-stop:0 0 6 * * ?}")
|
||||
public void stopNightSync() {
|
||||
log.info("停止夜间OSS到MinIO同步任务");
|
||||
isNightSyncRunning.set(false);
|
||||
}
|
||||
|
||||
/**
|
||||
* 夜间同步循环
|
||||
* 在00:00-6:00期间持续同步
|
||||
*/
|
||||
private void nightSyncLoop() {
|
||||
log.info("开始夜间同步循环");
|
||||
|
||||
while (isNightSyncRunning.get()) {
|
||||
try {
|
||||
LocalTime currentTime = LocalTime.now();
|
||||
|
||||
// 检查是否在夜间同步时间窗口内(00:00-6:00)
|
||||
if (currentTime.isAfter(LocalTime.of(0, 0)) &&
|
||||
currentTime.isBefore(LocalTime.of(6, 0))) {
|
||||
|
||||
// 执行同步任务
|
||||
performNightSync();
|
||||
|
||||
// 等待下次同步
|
||||
Thread.sleep(syncInterval);
|
||||
} else {
|
||||
// 不在夜间时间窗口,等待1分钟后再次检查
|
||||
Thread.sleep(60000);
|
||||
}
|
||||
|
||||
} catch (InterruptedException e) {
|
||||
log.info("夜间同步循环被中断");
|
||||
Thread.currentThread().interrupt();
|
||||
break;
|
||||
} catch (Exception e) {
|
||||
log.error("夜间同步循环异常", e);
|
||||
try {
|
||||
Thread.sleep(60000); // 异常后等待1分钟再继续
|
||||
} catch (InterruptedException ie) {
|
||||
Thread.currentThread().interrupt();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
log.info("夜间同步循环结束");
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行夜间同步任务
|
||||
*/
|
||||
private void performNightSync() {
|
||||
try {
|
||||
log.info("执行夜间同步任务 - 时间: {}", LocalDateTime.now());
|
||||
|
||||
// 获取需要同步的文件列表
|
||||
List<FileInfo> filesToSync = getFilesToSync();
|
||||
if (filesToSync.isEmpty()) {
|
||||
log.debug("没有需要同步的文件");
|
||||
return;
|
||||
}
|
||||
|
||||
log.info("找到 {} 个文件需要同步", filesToSync.size());
|
||||
|
||||
int successCount = 0;
|
||||
int failCount = 0;
|
||||
int processedCount = 0;
|
||||
|
||||
for (FileInfo fileInfo : filesToSync) {
|
||||
if (!isNightSyncRunning.get()) {
|
||||
log.info("夜间同步被停止,已处理 {} 个文件", processedCount);
|
||||
break;
|
||||
}
|
||||
|
||||
try {
|
||||
boolean syncResult = ossToS3SyncService.syncFileToS3(fileInfo);
|
||||
if (syncResult) {
|
||||
successCount++;
|
||||
log.debug("文件同步成功: {}", fileInfo.getPath());
|
||||
} else {
|
||||
failCount++;
|
||||
log.warn("文件同步失败: {}", fileInfo.getPath());
|
||||
}
|
||||
|
||||
processedCount++;
|
||||
|
||||
// 控制同步速度,避免对系统造成压力
|
||||
Thread.sleep(200);
|
||||
|
||||
} catch (Exception e) {
|
||||
failCount++;
|
||||
processedCount++;
|
||||
log.error("文件同步异常: {}, error: {}", fileInfo.getPath(), e.getMessage());
|
||||
}
|
||||
|
||||
// 每处理一批文件后暂停一下
|
||||
if (processedCount % batchSize == 0) {
|
||||
log.info("已处理 {} 个文件,成功: {}, 失败: {}", processedCount, successCount, failCount);
|
||||
Thread.sleep(1000); // 暂停1秒
|
||||
}
|
||||
}
|
||||
|
||||
lastSyncTime = LocalDateTime.now();
|
||||
log.info("夜间同步任务完成 - 处理: {}, 成功: {}, 失败: {}",
|
||||
processedCount, successCount, failCount);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("夜间同步任务执行失败", e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取需要同步的文件列表
|
||||
*/
|
||||
private List<FileInfo> getFilesToSync() {
|
||||
try {
|
||||
// 获取冷数据文件(超过热数据天数的文件)
|
||||
LocalDateTime coldDataThreshold = LocalDateTime.now().minusDays(hotDataDays);
|
||||
log.info("查询冷数据文件,热数据天数: {}, 冷数据阈值: {}", hotDataDays, coldDataThreshold);
|
||||
|
||||
List<FileInfo> filesToSync = queryColdDataFiles(coldDataThreshold);
|
||||
|
||||
log.info("获取到 {} 个文件需要同步", filesToSync.size());
|
||||
|
||||
return filesToSync;
|
||||
} catch (Exception e) {
|
||||
log.error("获取需要同步的文件列表失败", e);
|
||||
return java.util.Collections.emptyList();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询冷数据文件
|
||||
* 查询创建时间早于threshold且不在S3中的文件
|
||||
*/
|
||||
private List<FileInfo> queryColdDataFiles(LocalDateTime threshold) {
|
||||
try {
|
||||
log.debug("查询冷数据文件,截止时间: {}", threshold);
|
||||
|
||||
// 查询创建时间早于threshold的文件
|
||||
List<FileInfo> allFiles = fileMapper.selectList(null);
|
||||
|
||||
// 过滤出冷数据文件(创建时间早于threshold)
|
||||
List<FileInfo> coldFiles = allFiles.stream()
|
||||
.filter(file -> {
|
||||
if (file.getCreateTime() == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 转换为LocalDateTime进行比较
|
||||
LocalDateTime createTime = file.getCreateTime().toInstant()
|
||||
.atZone(java.time.ZoneId.systemDefault())
|
||||
.toLocalDateTime();
|
||||
|
||||
return createTime.isBefore(threshold);
|
||||
})
|
||||
.filter(file -> {
|
||||
// 过滤掉已经在S3中的文件
|
||||
if (file.getStorageType() != null &&
|
||||
(file.getStorageType().contains("S3") || file.getStorageType().contains("MINIO"))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (file.getPath() != null &&
|
||||
(file.getPath().contains("s3://") || file.getPath().contains("minio") ||
|
||||
file.getPath().contains("s3-storage/") || file.getPath().contains("cold-storage/"))) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
})
|
||||
.filter(file -> {
|
||||
// 确保文件在OSS中(支持多种路径格式)
|
||||
if (file.getStorageType() != null &&
|
||||
(file.getStorageType().contains("OSS") || file.getStorageType().contains("ALIYUN"))) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (file.getPath() != null) {
|
||||
String path = file.getPath();
|
||||
if (path.contains("oss://") || path.contains("aliyun") ||
|
||||
path.startsWith("picture/") || path.startsWith("video/") || path.startsWith("file/")) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
})
|
||||
.limit(batchSize * 2) // 限制查询数量
|
||||
.toList();
|
||||
|
||||
log.info("查询到 {} 个冷数据文件需要同步", coldFiles.size());
|
||||
|
||||
// 记录前几个文件的详细信息用于调试
|
||||
if (!coldFiles.isEmpty()) {
|
||||
log.debug("冷数据文件示例:");
|
||||
coldFiles.stream().limit(3).forEach(file ->
|
||||
log.debug("文件ID: {}, 路径: {}, 创建时间: {}, 存储类型: {}",
|
||||
file.getId(), file.getPath(), file.getCreateTime(), file.getStorageType()));
|
||||
}
|
||||
|
||||
return coldFiles;
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("查询冷数据文件失败", e);
|
||||
return java.util.Collections.emptyList();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取同步状态
|
||||
*/
|
||||
public String getSyncStatus() {
|
||||
return String.format("夜间同步状态 - 运行中: %s, 最后同步时间: %s, 热数据天数: %d",
|
||||
isNightSyncRunning.get(),
|
||||
lastSyncTime != null ? lastSyncTime.toString() : "未执行",
|
||||
hotDataDays);
|
||||
}
|
||||
|
||||
/**
|
||||
* 手动启动夜间同步(用于测试)
|
||||
*/
|
||||
public void manualStartNightSync() {
|
||||
log.info("手动启动夜间同步");
|
||||
isNightSyncRunning.set(true);
|
||||
new Thread(this::nightSyncLoop, "ManualNightSyncThread").start();
|
||||
}
|
||||
|
||||
/**
|
||||
* 手动停止夜间同步
|
||||
*/
|
||||
public void manualStopNightSync() {
|
||||
log.info("手动停止夜间同步");
|
||||
isNightSyncRunning.set(false);
|
||||
}
|
||||
}
|
||||
+144
@@ -0,0 +1,144 @@
|
||||
package com.central.file.service;
|
||||
|
||||
import com.central.common.model.FileInfo;
|
||||
import com.central.file.service.impl.EnhancedS3Service;
|
||||
import com.central.file.service.impl.OssService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.InputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
|
||||
/**
|
||||
* OSS到S3同步服务
|
||||
* 用于将OSS上的文件同步到S3存储
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class OssToS3SyncService {
|
||||
|
||||
@Autowired
|
||||
private EnhancedS3Service enhancedS3Service;
|
||||
|
||||
@Autowired
|
||||
private OssService ossService;
|
||||
|
||||
/**
|
||||
* 同步OSS文件到S3
|
||||
*
|
||||
* @param ossUrl OSS文件URL
|
||||
* @param s3ObjectName S3对象名称
|
||||
* @return 是否同步成功
|
||||
*/
|
||||
public boolean syncOssToS3(String ossUrl, String s3ObjectName) {
|
||||
try {
|
||||
log.info("开始同步OSS文件到S3: {} -> {}", ossUrl, s3ObjectName);
|
||||
|
||||
// 检查S3中是否已存在
|
||||
if (enhancedS3Service.fileExists(s3ObjectName)) {
|
||||
log.info("S3中已存在文件,跳过同步: {}", s3ObjectName);
|
||||
return true;
|
||||
}
|
||||
|
||||
// 从OSS下载文件
|
||||
InputStream inputStream = downloadFromOss(ossUrl);
|
||||
if (inputStream == null) {
|
||||
log.error("从OSS下载文件失败: {}", ossUrl);
|
||||
return false;
|
||||
}
|
||||
|
||||
// 使用现有的downloadAndUpload方法
|
||||
boolean uploadResult = enhancedS3Service.downloadAndUpload(ossUrl, s3ObjectName);
|
||||
if (uploadResult) {
|
||||
log.info("OSS文件同步到S3成功: {} -> {}", ossUrl, s3ObjectName);
|
||||
} else {
|
||||
log.error("OSS文件同步到S3失败: {} -> {}", ossUrl, s3ObjectName);
|
||||
}
|
||||
|
||||
return uploadResult;
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("同步OSS文件到S3异常: {} -> {}", ossUrl, s3ObjectName, e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据文件信息同步到S3
|
||||
*
|
||||
* @param fileInfo 文件信息
|
||||
* @return 是否同步成功
|
||||
*/
|
||||
public boolean syncFileToS3(FileInfo fileInfo) {
|
||||
if (fileInfo == null || fileInfo.getPath() == null) {
|
||||
log.error("文件信息为空,无法同步");
|
||||
return false;
|
||||
}
|
||||
|
||||
// 使用OSS服务获取带签名的URL
|
||||
String ossUrl = ossService.getViewUrlByPath(fileInfo.getPath());
|
||||
if (ossUrl == null || ossUrl.isEmpty()) {
|
||||
log.error("无法获取OSS文件URL: {}", fileInfo.getPath());
|
||||
return false;
|
||||
}
|
||||
|
||||
String s3ObjectName = fileInfo.getPath();
|
||||
return syncOssToS3(ossUrl, s3ObjectName);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据文件路径同步到S3
|
||||
*
|
||||
* @param filePath 文件路径
|
||||
* @return 是否同步成功
|
||||
*/
|
||||
public boolean syncFileToS3(String filePath) {
|
||||
if (filePath == null || filePath.isEmpty()) {
|
||||
log.error("文件路径为空,无法同步");
|
||||
return false;
|
||||
}
|
||||
|
||||
// 使用OSS服务获取带签名的URL
|
||||
String ossUrl = ossService.getViewUrlByPath(filePath);
|
||||
if (ossUrl == null || ossUrl.isEmpty()) {
|
||||
log.error("无法获取OSS文件URL: {}", filePath);
|
||||
return false;
|
||||
}
|
||||
|
||||
String s3ObjectName = filePath;
|
||||
return syncOssToS3(ossUrl, s3ObjectName);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从OSS下载文件
|
||||
*
|
||||
* @param ossUrl OSS文件URL
|
||||
* @return 文件输入流
|
||||
*/
|
||||
private InputStream downloadFromOss(String ossUrl) {
|
||||
try {
|
||||
log.debug("从OSS下载文件: {}", ossUrl);
|
||||
|
||||
URL url = new URL(ossUrl);
|
||||
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
|
||||
connection.setRequestMethod("GET");
|
||||
connection.setConnectTimeout(30000);
|
||||
connection.setReadTimeout(30000);
|
||||
|
||||
int responseCode = connection.getResponseCode();
|
||||
if (responseCode == 200) {
|
||||
log.debug("OSS文件下载成功: {}", ossUrl);
|
||||
return connection.getInputStream();
|
||||
} else {
|
||||
log.error("OSS文件下载失败,响应码: {}, URL: {}", responseCode, ossUrl);
|
||||
return null;
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("从OSS下载文件异常: {}", ossUrl, e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
+53
-9
@@ -3,6 +3,7 @@ package com.central.file.service;
|
||||
import com.central.common.model.FileInfo;
|
||||
import com.central.file.service.impl.OssService;
|
||||
import com.central.file.service.impl.S3Service;
|
||||
import com.central.file.service.impl.EnhancedS3Service;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.beans.factory.annotation.Qualifier;
|
||||
@@ -31,6 +32,13 @@ public class TimeWindowStorageService {
|
||||
@Qualifier("s3FileService")
|
||||
private S3Service s3Service;
|
||||
|
||||
@Autowired(required = false)
|
||||
@Qualifier("enhancedS3FileService")
|
||||
private EnhancedS3Service enhancedS3Service;
|
||||
|
||||
@Autowired(required = false)
|
||||
private OssToS3SyncService ossToS3SyncService;
|
||||
|
||||
// 配置参数
|
||||
@Value("${zlt.storage.hot-data-days:30}")
|
||||
private int hotDataDays; // 热数据保留天数,默认30天
|
||||
@@ -60,7 +68,7 @@ public class TimeWindowStorageService {
|
||||
// 3. 根据存储类型获取URL
|
||||
String viewUrl = getViewUrlByStorageType(fileInfo, storageType);
|
||||
|
||||
log.debug("智能存储查询成功: fileId={}, storageType={}, url={}",
|
||||
log.info("智能存储查询成功: fileId={}, storageType={}, url={}",
|
||||
fileId, storageType, viewUrl);
|
||||
|
||||
return viewUrl;
|
||||
@@ -134,10 +142,15 @@ public class TimeWindowStorageService {
|
||||
* 根据存储类型获取访问URL
|
||||
*/
|
||||
private String getViewUrlByStorageType(FileInfo fileInfo, String storageType) {
|
||||
log.info("根据存储类型获取URL: fileId={}, storageType={}, path={}",
|
||||
fileInfo.getId(), storageType, fileInfo.getPath());
|
||||
|
||||
if ("S3".equals(storageType)) {
|
||||
// 冷数据,优先从S3查询
|
||||
log.info("冷数据,优先从S3查询: fileId={}", fileInfo.getId());
|
||||
String s3Url = queryFromS3(fileInfo);
|
||||
if (s3Url != null && !s3Url.isEmpty()) {
|
||||
log.info("S3查询成功: fileId={}, url={}", fileInfo.getId(), s3Url);
|
||||
return s3Url;
|
||||
}
|
||||
// S3查询失败,降级到OSS
|
||||
@@ -145,8 +158,10 @@ public class TimeWindowStorageService {
|
||||
return queryFromOss(fileInfo);
|
||||
} else {
|
||||
// 热数据,优先从OSS查询
|
||||
log.info("热数据,优先从OSS查询: fileId={}", fileInfo.getId());
|
||||
String ossUrl = queryFromOss(fileInfo);
|
||||
if (ossUrl != null && !ossUrl.isEmpty()) {
|
||||
log.info("OSS查询成功: fileId={}, url={}", fileInfo.getId(), ossUrl);
|
||||
return ossUrl;
|
||||
}
|
||||
// OSS查询失败,降级到S3
|
||||
@@ -172,10 +187,15 @@ public class TimeWindowStorageService {
|
||||
*/
|
||||
private String queryFromS3(FileInfo fileInfo) {
|
||||
try {
|
||||
if (s3Service != null) {
|
||||
// 优先使用EnhancedS3Service
|
||||
if (enhancedS3Service != null) {
|
||||
log.debug("使用EnhancedS3Service查询: fileId={}, path={}", fileInfo.getId(), fileInfo.getPath());
|
||||
return enhancedS3Service.getViewUrlByPath(fileInfo.getPath());
|
||||
} else if (s3Service != null) {
|
||||
log.debug("使用S3Service查询: fileId={}, path={}", fileInfo.getId(), fileInfo.getPath());
|
||||
return s3Service.getViewUrlByPath(fileInfo.getPath());
|
||||
} else {
|
||||
log.warn("S3Service未配置,无法查询S3: fileId={}", fileInfo.getId());
|
||||
log.warn("S3服务未配置,无法查询S3: fileId={}", fileInfo.getId());
|
||||
return "";
|
||||
}
|
||||
} catch (Exception e) {
|
||||
@@ -189,10 +209,29 @@ public class TimeWindowStorageService {
|
||||
*/
|
||||
private String queryFromS3ByPath(String filePath) {
|
||||
try {
|
||||
if (s3Service != null) {
|
||||
// 优先使用EnhancedS3Service
|
||||
if (enhancedS3Service != null) {
|
||||
log.debug("使用EnhancedS3Service查询: path={}", filePath);
|
||||
String s3Url = enhancedS3Service.getViewUrlByPath(filePath);
|
||||
|
||||
// 如果S3中没有找到文件,尝试从OSS同步
|
||||
if ((s3Url == null || s3Url.isEmpty()) && ossToS3SyncService != null) {
|
||||
log.info("S3中未找到文件,尝试从OSS同步: path={}", filePath);
|
||||
boolean syncResult = ossToS3SyncService.syncFileToS3(filePath);
|
||||
if (syncResult) {
|
||||
log.info("OSS同步到S3成功,重新获取URL: path={}", filePath);
|
||||
s3Url = enhancedS3Service.getViewUrlByPath(filePath);
|
||||
} else {
|
||||
log.warn("OSS同步到S3失败: path={}", filePath);
|
||||
}
|
||||
}
|
||||
|
||||
return s3Url;
|
||||
} else if (s3Service != null) {
|
||||
log.debug("使用S3Service查询: path={}", filePath);
|
||||
return s3Service.getViewUrlByPath(filePath);
|
||||
} else {
|
||||
log.warn("S3Service未配置,无法查询S3: path={}", filePath);
|
||||
log.warn("S3服务未配置,无法查询S3: path={}", filePath);
|
||||
return "";
|
||||
}
|
||||
} catch (Exception e) {
|
||||
@@ -236,10 +275,14 @@ public class TimeWindowStorageService {
|
||||
*/
|
||||
private boolean isS3Path(String path) {
|
||||
return path != null && (
|
||||
path.contains("s3://") ||
|
||||
path.startsWith("s3://") ||
|
||||
path.contains("minio") ||
|
||||
path.startsWith("cold-storage") ||
|
||||
path.contains("S3")
|
||||
path.contains("S3") ||
|
||||
path.startsWith("hot-sync/") || // 兼容旧的hot-sync前缀
|
||||
// 只有明确包含S3标识的路径才认为是S3路径
|
||||
path.contains("s3://") ||
|
||||
path.contains("minio://")
|
||||
);
|
||||
}
|
||||
|
||||
@@ -248,10 +291,11 @@ public class TimeWindowStorageService {
|
||||
*/
|
||||
private boolean isOssPath(String path) {
|
||||
return path != null && (
|
||||
path.contains("oss://") ||
|
||||
path.startsWith("oss://") ||
|
||||
path.contains("aliyun") ||
|
||||
path.contains("ali-oss") ||
|
||||
path.contains("OSS")
|
||||
path.contains("OSS") ||
|
||||
path.startsWith("https://goflyapp.oss-cn-beijing.aliyuncs.com/")
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
+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);
|
||||
}
|
||||
}
|
||||
+61
-8
@@ -68,8 +68,21 @@ public class EnhancedS3Service extends AbstractIFileService {
|
||||
public String getViewUrlByPath(String name) {
|
||||
try {
|
||||
S3Object s3Object = parsePath(name);
|
||||
log.info("解析S3路径: {} -> bucket: {}, object: {}", name, s3Object.bucketName, s3Object.objectName);
|
||||
|
||||
// 检查文件是否存在
|
||||
boolean exists = s3Template.doesObjectExist(s3Object.bucketName, s3Object.objectName);
|
||||
log.info("S3文件存在检查: bucket={}, object={}, exists={}", s3Object.bucketName, s3Object.objectName, exists);
|
||||
|
||||
if (!exists) {
|
||||
log.warn("S3文件不存在: bucket={}, object={}", s3Object.bucketName, s3Object.objectName);
|
||||
return "";
|
||||
}
|
||||
|
||||
// 使用getViewUrl方法获取预签名URL
|
||||
return s3Template.getViewUrl(s3Object.bucketName, s3Object.objectName, 60); // 60分钟有效期
|
||||
String url = s3Template.getViewUrl(s3Object.bucketName, s3Object.objectName, 60); // 60分钟有效期
|
||||
log.info("生成S3 URL: {}", url);
|
||||
return url;
|
||||
} catch (Exception e) {
|
||||
log.error("获取S3文件URL失败: {}", name, e);
|
||||
return "";
|
||||
@@ -323,16 +336,56 @@ public class EnhancedS3Service extends AbstractIFileService {
|
||||
private S3Object parsePath(String path) {
|
||||
S3Object s3Object = new S3Object();
|
||||
if (StrUtil.isNotEmpty(path)) {
|
||||
int splitIndex = path.lastIndexOf(CommonConstant.PATH_SPLIT);
|
||||
if (splitIndex != -1) {
|
||||
s3Object.bucketName = path.substring(0, splitIndex);
|
||||
s3Object.objectName = path.substring(splitIndex + 1);
|
||||
// 处理s3://bucket/object格式
|
||||
if (path.startsWith("s3://")) {
|
||||
String[] parts = path.substring(5).split("/", 2);
|
||||
if (parts.length >= 2) {
|
||||
s3Object.bucketName = parts[0];
|
||||
s3Object.objectName = decodeUrl(parts[1]);
|
||||
} else {
|
||||
s3Object.bucketName = fileServerProperties.getS3().getBucketName();
|
||||
s3Object.objectName = decodeUrl(parts[0]);
|
||||
}
|
||||
} else if (path.startsWith("hot-sync/")) {
|
||||
// 处理hot-sync前缀的路径(兼容旧格式)
|
||||
s3Object.bucketName = fileServerProperties.getS3().getBucketName();
|
||||
s3Object.objectName = decodeUrl(path.substring("hot-sync/".length())); // 去掉hot-sync/前缀并解码
|
||||
} else {
|
||||
// 如果没有分隔符,使用默认bucket
|
||||
s3Object.bucketName = "default-bucket";
|
||||
s3Object.objectName = path;
|
||||
// 处理相对路径或无前缀路径
|
||||
int splitIndex = path.lastIndexOf(CommonConstant.PATH_SPLIT);
|
||||
if (splitIndex != -1) {
|
||||
s3Object.bucketName = path.substring(0, splitIndex);
|
||||
s3Object.objectName = decodeUrl(path.substring(splitIndex + 1));
|
||||
} else {
|
||||
// 如果没有分隔符,使用配置的bucket
|
||||
s3Object.bucketName = fileServerProperties.getS3().getBucketName();
|
||||
s3Object.objectName = decodeUrl(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
return s3Object;
|
||||
}
|
||||
|
||||
/**
|
||||
* URL解码,处理特殊字符
|
||||
*/
|
||||
private String decodeUrl(String encodedString) {
|
||||
try {
|
||||
if (encodedString == null || encodedString.isEmpty()) {
|
||||
return encodedString;
|
||||
}
|
||||
|
||||
// 检查是否包含URL编码字符
|
||||
if (encodedString.contains("%")) {
|
||||
String decoded = java.net.URLDecoder.decode(encodedString, "UTF-8");
|
||||
log.debug("URL解码: {} -> {}", encodedString, decoded);
|
||||
return decoded;
|
||||
}
|
||||
|
||||
return encodedString;
|
||||
} catch (Exception e) {
|
||||
log.warn("URL解码失败: {}, 使用原始字符串", encodedString, e);
|
||||
return encodedString;
|
||||
}
|
||||
}
|
||||
}
|
||||
+55
-7
@@ -1,5 +1,6 @@
|
||||
package com.central.file.service.impl;
|
||||
|
||||
import cn.hutool.core.util.IdUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.central.common.constant.CommonConstant;
|
||||
import com.central.common.model.FileInfo;
|
||||
@@ -44,7 +45,11 @@ public class S3Service extends AbstractIFileService {
|
||||
|
||||
@Override
|
||||
protected ObjectInfo uploadFile(String name, InputStream inputStream) {
|
||||
return null;
|
||||
try {
|
||||
return s3Template.upload(name, inputStream);
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -55,12 +60,22 @@ public class S3Service extends AbstractIFileService {
|
||||
|
||||
@Override
|
||||
public String getViewUrlByPath(String name) {
|
||||
return "";
|
||||
try {
|
||||
S3Object s3Object = parsePath(name);
|
||||
return s3Template.getViewUrl(s3Object.bucketName, s3Object.objectName, 60); // 60分钟有效期
|
||||
} catch (Exception e) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getZipViewUrlByPath(String name, String style) {
|
||||
return "";
|
||||
try {
|
||||
S3Object s3Object = parsePath(name);
|
||||
return s3Template.getViewUrl(s3Object.bucketName, s3Object.objectName, 60);
|
||||
} catch (Exception e) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -74,27 +89,60 @@ public class S3Service extends AbstractIFileService {
|
||||
|
||||
@Override
|
||||
public String getViewUrl(String id) {
|
||||
try {
|
||||
FileInfo fileInfo = baseMapper.selectById(id);
|
||||
if (fileInfo != null) {
|
||||
return getViewUrlByPath(fileInfo.getPath());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
// 忽略异常
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
@Override
|
||||
public FileInfo getFileInfo(String id) {
|
||||
return null;
|
||||
try {
|
||||
return baseMapper.selectById(id);
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public FileInfo createFile(String path) {
|
||||
return null;
|
||||
try {
|
||||
S3Object s3Object = parsePath(path);
|
||||
FileInfo fileInfo = new FileInfo();
|
||||
fileInfo.setPath(path);
|
||||
fileInfo.setId(IdUtil.fastSimpleUUID());
|
||||
fileInfo.setName(s3Object.objectName);
|
||||
fileInfo.setSource(fileType());
|
||||
fileInfo.setStorageType(FileServerProperties.TYPE_S3);
|
||||
return fileInfo;
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<String> listFiles(String prefix) {
|
||||
return List.of();
|
||||
try {
|
||||
// 简化实现,直接返回空列表
|
||||
return List.of();
|
||||
} catch (Exception e) {
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getViewUrlByPathAndExpires(String name, int expires) {
|
||||
return "";
|
||||
try {
|
||||
S3Object s3Object = parsePath(name);
|
||||
return s3Template.getViewUrl(s3Object.bucketName, s3Object.objectName, expires);
|
||||
} catch (Exception e) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
@Setter
|
||||
|
||||
@@ -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 # 迁移后是否删除源文件
|
||||
@@ -0,0 +1,36 @@
|
||||
# OSS到MinIO同步配置
|
||||
zlt:
|
||||
storage:
|
||||
# 热数据保留天数
|
||||
hot-data-days: 30
|
||||
|
||||
# 同步功能配置
|
||||
sync:
|
||||
# 是否启用同步
|
||||
enabled: true
|
||||
|
||||
# 夜间同步配置
|
||||
night-start: "0 0 0 * * ?" # 每天晚上00:00启动
|
||||
night-stop: "0 0 6 * * ?" # 每天早上6:00停止
|
||||
|
||||
# 同步间隔(毫秒)
|
||||
interval: 180000 # 3分钟
|
||||
|
||||
# 批量同步大小
|
||||
batch-size: 100
|
||||
|
||||
# 是否启用事件驱动同步
|
||||
event-driven: true
|
||||
|
||||
# 同步线程池配置
|
||||
thread-pool:
|
||||
core-size: 2
|
||||
max-size: 5
|
||||
queue-size: 100
|
||||
keep-alive: 60
|
||||
|
||||
# 日志配置
|
||||
logging:
|
||||
level:
|
||||
com.central.file.service.OssToMinioSyncScheduler: INFO
|
||||
com.central.file.service.OssToS3SyncService: DEBUG
|
||||
@@ -54,12 +54,12 @@ zlt:
|
||||
delete-source: false # 迁移后是否删除源文件
|
||||
batch-size: 100 # 迁移批次大小
|
||||
hot-sync:
|
||||
enabled: true # 启用热数据同步
|
||||
enabled: true # 启用热数据同步
|
||||
batch-size: 100 # 批次大小
|
||||
interval-minutes: 30 # 同步间隔
|
||||
access-threshold: 10 # 访问次数阈值
|
||||
max-threads: 5 # 最大线程数
|
||||
|
||||
|
||||
sync:
|
||||
schedule:
|
||||
enabled: true # 启用定时任务
|
||||
@@ -75,3 +75,27 @@ zlt:
|
||||
# soTimeout: 1500
|
||||
# connectTimeout: 600
|
||||
# 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:
|
||||
application:
|
||||
name: file-center
|
||||
# cloud:
|
||||
# nacos:
|
||||
# discovery:
|
||||
# ip: 119.45.169.13
|
||||
cloud:
|
||||
nacos:
|
||||
discovery:
|
||||
ip: 119.45.169.13
|
||||
servlet:
|
||||
multipart:
|
||||
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>
|
||||
</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>
|
||||
<groupId>javax.servlet</groupId>
|
||||
<artifactId>javax.servlet-api</artifactId>
|
||||
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.central.order.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 租户分配配置
|
||||
*/
|
||||
@Data
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "tenant.allocation")
|
||||
public class TenantAllocationConfig {
|
||||
|
||||
/**
|
||||
* 是否启用租户分配功能
|
||||
*/
|
||||
private boolean enabled = false;
|
||||
|
||||
/**
|
||||
* 分配比例(景区:平台)
|
||||
*/
|
||||
private int allocationRatio = 10;
|
||||
|
||||
/**
|
||||
* 平台默认租户ID
|
||||
*/
|
||||
private String platformTenantId = "webApp";
|
||||
|
||||
/**
|
||||
* 是否启用调试模式
|
||||
*/
|
||||
private boolean debug = false;
|
||||
|
||||
/**
|
||||
* 是否强制使用平台租户(用于测试)
|
||||
*/
|
||||
private boolean forcePlatformTenant = false;
|
||||
}
|
||||
+1895
File diff suppressed because it is too large
Load Diff
+139
-2
@@ -4,13 +4,23 @@ import com.central.common.model.Result;
|
||||
import com.central.order.model.vo.DashboardStatisticsVO;
|
||||
import com.central.order.service.IDashboardService;
|
||||
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.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
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;
|
||||
import com.central.order.model.Order;
|
||||
import com.central.common.model.PageResult;
|
||||
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequestMapping("/dashboard")
|
||||
@@ -19,16 +29,143 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
public class DashboardController {
|
||||
|
||||
private final IDashboardService dashboardService;
|
||||
private final DashboardMapper dashboardMapper;
|
||||
|
||||
@Operation(summary = "获取首页统计数据")
|
||||
@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 {
|
||||
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, "获取首页统计数据成功");
|
||||
} catch (Exception e) {
|
||||
log.error("获取首页统计数据失败", e);
|
||||
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());
|
||||
}
|
||||
}
|
||||
|
||||
@Operation(summary = "测试时间参数传递")
|
||||
@GetMapping("/test-time-params")
|
||||
public Result<Map<String, Object>> testTimeParams(
|
||||
@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 {
|
||||
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);
|
||||
|
||||
// 测试各个统计方法
|
||||
Long totalOrders = dashboardMapper.getTotalOrders(params);
|
||||
Long totalAmount = dashboardMapper.getTotalAmount(params);
|
||||
Long refundAmount = dashboardMapper.getRefundAmount(params);
|
||||
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("params", params);
|
||||
result.put("totalOrders", totalOrders);
|
||||
result.put("totalAmount", totalAmount);
|
||||
result.put("refundAmount", refundAmount);
|
||||
|
||||
return Result.succeed(result, "测试时间参数成功");
|
||||
} catch (Exception e) {
|
||||
log.error("测试时间参数失败", e);
|
||||
return Result.failed("测试失败:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Operation(summary = "调试数据库时间查询")
|
||||
@GetMapping("/debug-time-query")
|
||||
public Result<Map<String, Object>> debugTimeQuery(
|
||||
@Parameter(description = "开始时间") @RequestParam(required = false) String startTime,
|
||||
@Parameter(description = "结束时间") @RequestParam(required = false) String endTime) {
|
||||
try {
|
||||
Map<String, Object> params = new HashMap<>();
|
||||
params.put("startTime", startTime);
|
||||
params.put("endTime", endTime);
|
||||
|
||||
// 直接查询数据库中的时间范围数据
|
||||
List<Map<String, Object>> timeRangeData = dashboardMapper.debugTimeRangeQuery(params);
|
||||
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
result.put("params", params);
|
||||
result.put("timeRangeData", timeRangeData);
|
||||
result.put("dataCount", timeRangeData.size());
|
||||
|
||||
return Result.succeed(result, "调试时间查询成功");
|
||||
} catch (Exception e) {
|
||||
log.error("调试时间查询失败", e);
|
||||
return Result.failed("调试失败:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Operation(summary = "获取首页订单列表")
|
||||
@GetMapping("/orders")
|
||||
public Result<PageResult<Order>> getDashboardOrders(
|
||||
@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,
|
||||
@Parameter(description = "页码") @RequestParam(defaultValue = "1") Integer page,
|
||||
@Parameter(description = "每页数量") @RequestParam(defaultValue = "10") Integer limit) {
|
||||
try {
|
||||
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);
|
||||
params.put("page", page);
|
||||
params.put("limit", limit);
|
||||
|
||||
PageResult<Order> result = dashboardService.getDashboardOrders(params);
|
||||
return Result.succeed(result, "获取订单列表成功");
|
||||
} catch (Exception e) {
|
||||
log.error("获取订单列表失败", e);
|
||||
return Result.failed("获取订单列表失败:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
package com.central.order.controller;
|
||||
|
||||
import com.central.common.model.Result;
|
||||
import com.fasterxml.jackson.core.JsonParseException;
|
||||
import com.fasterxml.jackson.databind.JsonMappingException;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.converter.HttpMessageNotReadableException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
|
||||
/**
|
||||
* 全局异常处理器
|
||||
*/
|
||||
@Slf4j
|
||||
@RestControllerAdvice
|
||||
public class GlobalExceptionHandler {
|
||||
|
||||
/**
|
||||
* 处理JSON反序列化错误
|
||||
*/
|
||||
@ExceptionHandler(HttpMessageNotReadableException.class)
|
||||
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
||||
public Result<String> handleHttpMessageNotReadableException(HttpMessageNotReadableException e) {
|
||||
log.error("JSON反序列化错误", e);
|
||||
|
||||
String errorMessage = "请求格式错误";
|
||||
Throwable cause = e.getCause();
|
||||
|
||||
if (cause instanceof JsonParseException) {
|
||||
errorMessage = "JSON格式错误:" + cause.getMessage();
|
||||
} else if (cause instanceof JsonMappingException) {
|
||||
JsonMappingException mappingException = (JsonMappingException) cause;
|
||||
String path = mappingException.getPathReference();
|
||||
String message = mappingException.getMessage();
|
||||
|
||||
// 检查是否是字符串反序列化问题
|
||||
if (message.contains("no String-argument constructor") && message.contains("deserialize from String value")) {
|
||||
errorMessage = "数据格式错误:期望JSON对象,但收到字符串数据。请检查请求格式或联系技术支持。";
|
||||
log.error("检测到字符串反序列化问题,可能需要使用 /ctrip/create/non-json 接口");
|
||||
} else {
|
||||
errorMessage = "JSON映射错误:" + message + " (路径: " + path + ")";
|
||||
}
|
||||
}
|
||||
|
||||
return Result.failed(errorMessage);
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理通用异常
|
||||
*/
|
||||
@ExceptionHandler(Exception.class)
|
||||
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
public Result<String> handleException(Exception e) {
|
||||
log.error("系统异常", e);
|
||||
return Result.failed("系统异常:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
+438
-59
@@ -19,7 +19,11 @@ import com.central.order.service.*;
|
||||
import com.central.wechat.config.WxPayConfigFactory;
|
||||
import com.central.wechat.entity.WechatConfig;
|
||||
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.Parameter;
|
||||
import io.swagger.v3.oas.annotations.Parameters;
|
||||
@@ -97,6 +101,9 @@ public class OrderController {
|
||||
|
||||
@Autowired
|
||||
private WxPayConfigFactory wxPayConfigFactory;
|
||||
|
||||
@Autowired
|
||||
private OrderTenantAllocationService orderTenantAllocationService;
|
||||
|
||||
/**
|
||||
* 列表
|
||||
@@ -141,6 +148,8 @@ public class OrderController {
|
||||
public PageResult<Map> listInfoByUser(@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); // 查询已完成和素材上传中
|
||||
String fileType = MapUtils.getString(params, "fileType");
|
||||
if (StringUtil.isBlank(fileType)) {
|
||||
fileType = "image/jpeg";
|
||||
@@ -163,7 +172,9 @@ public class OrderController {
|
||||
for (OrderFile orderFile : list){
|
||||
Map<String,String> imgMap = new HashMap<>();
|
||||
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());
|
||||
fileMap.put("path",orderFile.getFilePath());
|
||||
imgMap.put("viewUrl", fileCenterService.getViewUrlByPathStyle(fileMap));
|
||||
@@ -193,7 +204,7 @@ public class OrderController {
|
||||
LoginAppUser user = LoginUserContextHolder.getUser();
|
||||
|
||||
order.setUserId(user.getId());
|
||||
order.setTenantId(TenantContextHolder.getTenant());
|
||||
|
||||
|
||||
List<Order> userOrderList = orderService.getOrderCountByStatusAndUser(user.getId(),OrderStatus.PAID.getId(),OrderStatus.UNPAID.getId());
|
||||
if (!userOrderList.isEmpty()){
|
||||
@@ -205,11 +216,20 @@ public class OrderController {
|
||||
if (qrCode.getStatus().equals(CommonStatus.UNABLE.getId())){
|
||||
return Result.failed("该二维码已过期");
|
||||
}
|
||||
|
||||
// 智能租户分配:根据二维码ID确定租户
|
||||
String determinedTenantId = orderTenantAllocationService.determineTenant(
|
||||
qrCode.getCodeId(), qrCode.getTenantId());
|
||||
order.setTenantId(determinedTenantId);
|
||||
|
||||
//设置订单所属tenantId
|
||||
TenantContextHolder.setTenant(qrCode.getTenantId());
|
||||
order.setTourismId(qrCode.getTourismId());
|
||||
order.setDeviceSn(qrCode.getDeviceSn());
|
||||
order.setOrderAmount(qrCode.getPrice());
|
||||
|
||||
// 记录订单分配日志
|
||||
orderTenantAllocationService.incrementOrderCount(qrCode.getCodeId());
|
||||
|
||||
}else {
|
||||
Assert.notNull(qrCode,"二维码不存在");
|
||||
}
|
||||
@@ -231,7 +251,7 @@ public class OrderController {
|
||||
|
||||
@Operation(summary = "生成预支付订单")
|
||||
@PutMapping("/{orderId}/pay")
|
||||
public Result<PrepayWithRequestPaymentResponse> payOrder(@PathVariable("orderId") Long orderId) {
|
||||
public Result<Object> payOrder(@PathVariable("orderId") Long orderId) {
|
||||
try {
|
||||
// 1. 获取用户和订单信息
|
||||
SysUser user = userCenterService.findUserById(LoginUserContextHolder.getUser().getId());
|
||||
@@ -240,67 +260,96 @@ public class OrderController {
|
||||
return Result.failed("订单数据不存在");
|
||||
}
|
||||
|
||||
// 检查是否需要开启分账
|
||||
// 检查二维码信息
|
||||
QrCode qrCode = qrCodeService.getByCodeId(order.getCodeId());
|
||||
if (qrCode == null) {
|
||||
return Result.failed("二维码不存在");
|
||||
}
|
||||
|
||||
// 3. 创建支付请求
|
||||
PrepayRequest request = new PrepayRequest();
|
||||
WechatConfig wechatConfig = wechatConfigService.getConfig("PAY",qrCode.getTenantId());
|
||||
|
||||
// 设置基本支付信息
|
||||
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());
|
||||
// 4. 根据是否为服务商模式设置不同的支付参数
|
||||
if (Boolean.TRUE.equals(wechatConfig.getIsServiceMode())) {
|
||||
// 服务商模式:使用partnerpayments包下的PrepayRequest
|
||||
com.wechat.pay.java.service.partnerpayments.jsapi.model.PrepayRequest partnerRequest =
|
||||
new com.wechat.pay.java.service.partnerpayments.jsapi.model.PrepayRequest();
|
||||
|
||||
// 设置支付者信息
|
||||
Payer payer = new Payer();
|
||||
payer.setOpenid(user.getOpenId());
|
||||
request.setPayer(payer);
|
||||
// 设置服务商信息
|
||||
partnerRequest.setSpAppid(wechatConfig.getServiceAppId());
|
||||
partnerRequest.setSpMchid(wechatConfig.getServiceMchId());
|
||||
|
||||
// 设置分账信息
|
||||
SettleInfo settleInfo = new SettleInfo();
|
||||
if (isEnableProfit(qrCode)) {
|
||||
settleInfo.setProfitSharing(true);
|
||||
request.setSettleInfo(settleInfo);
|
||||
// 设置子商户信息
|
||||
partnerRequest.setSubAppid(wechatConfig.getSubAppId());
|
||||
partnerRequest.setSubMchid(wechatConfig.getSubMchId());
|
||||
|
||||
// 设置其他支付信息
|
||||
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 {
|
||||
settleInfo.setProfitSharing(false);
|
||||
request.setSettleInfo(settleInfo);
|
||||
// 普通商户模式:使用payments包下的PrepayRequest
|
||||
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) {
|
||||
log.error("创建预支付订单失败", e);
|
||||
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 = "获取排队总览信息")
|
||||
@GetMapping("/queue/info")
|
||||
public Result<Map> getQueueInfo(@RequestParam String codeId) {
|
||||
@@ -443,19 +492,29 @@ public class OrderController {
|
||||
@AuditLog(operation = "'机库更新订单完成状态:' + #payload")
|
||||
@PutMapping("/update")
|
||||
public Result<String> updateOrderStatusCompleted(@RequestBody Map payload) {
|
||||
Order order = orderService.getOrderByNumber(payload.get("orderNo").toString());
|
||||
Assert.notNull(order,"订单数据不能为空");
|
||||
if (order.getOrderStatus().equals(OrderStatus.DOING.getId())
|
||||
|| order.getOrderStatus().equals(OrderStatus.UPLOADED.getId())
|
||||
|| order.getOrderStatus().equals(OrderStatus.UPLOADING.getId())){
|
||||
order.setOrderStatus(OrderStatus.COMPLETE.getId());
|
||||
if (orderService.updateOrder(order)){
|
||||
return Result.succeed("更新成功");
|
||||
try {
|
||||
TenantContextHolder.setTenant("webApp");
|
||||
Order order = orderService.getOrderByNumber(payload.get("orderNo").toString());
|
||||
Assert.notNull(order,"订单数据不能为空");
|
||||
if (order.getOrderStatus().equals(OrderStatus.DOING.getId())
|
||||
|| order.getOrderStatus().equals(OrderStatus.UPLOADED.getId())
|
||||
|| order.getOrderStatus().equals(OrderStatus.UPLOADING.getId())){
|
||||
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 = "取消订单")
|
||||
@@ -470,6 +529,21 @@ public class OrderController {
|
||||
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 = "后台管理更新订单")
|
||||
@PostMapping("/update/order")
|
||||
public Result updateOrder(@RequestBody Order order) {
|
||||
@@ -584,6 +658,8 @@ public class OrderController {
|
||||
for (OrderFile orderFile : orderFiles) {
|
||||
Map<String, String> fileInfo = new HashMap<>();
|
||||
String url = fileCenterService.getViewUrlByPath(orderFile.getFilePath());
|
||||
// 去掉URL中的参数并替换域名
|
||||
// String cleanUrl = removeUrlParams(url.replace(cdnOssUrl, cdnUrl));
|
||||
fileInfo.put("url", url.replace(cdnOssUrl, cdnUrl));
|
||||
fileInfo.put("contentType", orderFile.getFileType());
|
||||
fileMap.put("path", orderFile.getFilePath());
|
||||
@@ -608,6 +684,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,方便前端显示
|
||||
* @param str
|
||||
@@ -662,7 +807,9 @@ public class OrderController {
|
||||
for (String orderFile : list){
|
||||
Map<String,String> imgMap = new HashMap<>();
|
||||
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")){
|
||||
imgMap.put("contentType", "image/jpeg");
|
||||
}
|
||||
@@ -681,4 +828,236 @@ public class OrderController {
|
||||
}
|
||||
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());
|
||||
|
||||
// 视频缩略图使用图片的缩略图
|
||||
if (!imgList.isEmpty()) {
|
||||
// 使用第一张图片的缩略图作为视频缩略图
|
||||
String thumbnailUrl = imgList.get(0).get("viewUrl");
|
||||
videoMap.put("viewUrl", thumbnailUrl);
|
||||
} else {
|
||||
// 如果没有图片,则使用默认缩略图或空值
|
||||
videoMap.put("viewUrl", null);
|
||||
}
|
||||
|
||||
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<>();
|
||||
}
|
||||
|
||||
/**
|
||||
* 新版:查询用户图片订单详情列表
|
||||
*/
|
||||
@Operation(summary = "新版-查询用户图片订单详情列表")
|
||||
@Parameters({
|
||||
@Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY),
|
||||
@Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY),
|
||||
@Parameter(name = "fileType",description = "文件类型筛选",required = false,in=ParameterIn.QUERY),
|
||||
@Parameter(name = "fileTag",description = "文件标签筛选",required = false,in=ParameterIn.QUERY)
|
||||
})
|
||||
@GetMapping("/user/images")
|
||||
public PageResult<Map> listImageOrdersByUser(@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());
|
||||
|
||||
// 图片素材
|
||||
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);
|
||||
|
||||
// 只返回有图片的订单
|
||||
if (!imgList.isEmpty()) {
|
||||
page.add(orderFileMap);
|
||||
}
|
||||
}
|
||||
return PageResult.<Map>builder().data(page).resp_code(0).count((long) page.size()).build();
|
||||
}
|
||||
return new PageResult<>();
|
||||
}
|
||||
|
||||
/**
|
||||
* 新版:查询用户视频订单详情列表
|
||||
*/
|
||||
@Operation(summary = "新版-查询用户视频订单详情列表")
|
||||
@Parameters({
|
||||
@Parameter(name = "page",description = "分页起始位置",required = true,in=ParameterIn.QUERY),
|
||||
@Parameter(name = "limit",description = "分页结束位置",required = true,in=ParameterIn.QUERY),
|
||||
@Parameter(name = "fileType",description = "文件类型筛选",required = false,in=ParameterIn.QUERY),
|
||||
@Parameter(name = "fileTag",description = "文件标签筛选",required = false,in=ParameterIn.QUERY)
|
||||
})
|
||||
@GetMapping("/user/videos")
|
||||
public PageResult<Map> listVideoOrdersByUser(@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()) {
|
||||
aiVideoUrl = fileCenterService.getViewUrlByPath(aiVideoFiles.get(0).getFilePath()).replace(cdnOssUrl, cdnUrl);
|
||||
}
|
||||
orderFileMap.put("aiVideo", aiVideoUrl);
|
||||
|
||||
// 视频素材
|
||||
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);
|
||||
|
||||
// 只返回有视频的订单(包括aiVideo或raw_video)
|
||||
if (aiVideoUrl != null || !videoList.isEmpty()) {
|
||||
page.add(orderFileMap);
|
||||
}
|
||||
}
|
||||
return PageResult.<Map>builder().data(page).resp_code(0).count((long) page.size()).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;
|
||||
|
||||
import com.central.common.context.LoginUserContextHolder;
|
||||
import com.central.common.context.TenantContextHolder;
|
||||
import com.central.common.model.*;
|
||||
import com.central.order.constants.EditTaskStatus;
|
||||
import com.central.order.enums.OrderStatus;
|
||||
import com.central.order.feign.FileCenterService;
|
||||
import com.central.order.feign.UserCenterService;
|
||||
import com.central.order.model.*;
|
||||
import com.central.order.model.EditTask;
|
||||
import com.central.order.service.*;
|
||||
import com.central.order.util.DateUtils;
|
||||
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.web.bind.annotation.*;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -54,6 +55,21 @@ public class OrderFileController {
|
||||
@Value("${file.style}")
|
||||
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
|
||||
private UserCenterService userCenterService;
|
||||
|
||||
@@ -164,6 +180,7 @@ public class OrderFileController {
|
||||
@PostMapping("/path")
|
||||
public Result createOrderFileForPath(@RequestBody OrderFile orderFile) {
|
||||
try {
|
||||
TenantContextHolder.setTenant("webApp");
|
||||
if (orderFile == null || orderFile.getOrderNo() == null) {
|
||||
log.warn("参数为空,orderFile: {}", orderFile);
|
||||
return Result.failed(orderFile,"参数为空");
|
||||
@@ -205,6 +222,10 @@ public class OrderFileController {
|
||||
orderFile.setFilePath(fileInfo.getPath());
|
||||
orderFile.setFileType(fileInfo.getContentType());
|
||||
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);
|
||||
@@ -228,6 +249,8 @@ public class OrderFileController {
|
||||
} catch (Exception e) {
|
||||
log.error("素材记录创建异常", e);
|
||||
return Result.failed(orderFile,"素材记录创建异常: " + e.getMessage());
|
||||
}finally {
|
||||
TenantContextHolder.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -253,16 +276,27 @@ public class OrderFileController {
|
||||
|
||||
// 如果当前文件数量达到或超过二维码要求的数量,则更新订单状态为素材上传完成
|
||||
if (currentFileCount >= qrCode.getMaterialCount()) {
|
||||
|
||||
Tourism tourism = tourismService.getTourismById(qrCode.getTourismId());
|
||||
|
||||
//发送用户素材上传成功通知
|
||||
sendMessageForResouresUploaded(order,tourism);
|
||||
|
||||
// 预热订单相关的文件到CDN
|
||||
prefetchOrderFilesToCdn(order.getOrderNo());
|
||||
|
||||
// 检查是否开启一键成片功能
|
||||
if (isVideoEditEnabled(qrCode)) {
|
||||
log.info("二维码已开启一键成片功能,开始触发一键成片: orderNo={}, codeId={}",
|
||||
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. 创建新任务
|
||||
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 = "删除文件")
|
||||
|
||||
+10
-6
@@ -67,14 +67,16 @@ public class OrderStatisticsController {
|
||||
@Operation(summary = "按景区维度统计", description = "统计时间范围内各景区的订单数据")
|
||||
@Parameters({
|
||||
@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")
|
||||
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 endTime) {
|
||||
@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String endTime,
|
||||
@RequestParam(required = false) String tourismId) {
|
||||
try {
|
||||
List<Map<String, Object>> result = orderStatisticsService.statisticsByTourism(startTime, endTime);
|
||||
List<Map<String, Object>> result = orderStatisticsService.statisticsByTourism(startTime, endTime, tourismId);
|
||||
return Result.succeed(result, "获取景区维度统计数据成功");
|
||||
} catch (Exception e) {
|
||||
log.error("获取景区维度统计数据失败", e);
|
||||
@@ -85,14 +87,16 @@ public class OrderStatisticsController {
|
||||
@Operation(summary = "按设备维度统计", description = "统计时间范围内各设备的订单数据")
|
||||
@Parameters({
|
||||
@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")
|
||||
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 endTime) {
|
||||
@RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss") String endTime,
|
||||
@RequestParam(required = false) String deviceSn) {
|
||||
try {
|
||||
List<Map<String, Object>> result = orderStatisticsService.statisticsByDevice(startTime, endTime);
|
||||
List<Map<String, Object>> result = orderStatisticsService.statisticsByDevice(startTime, endTime, deviceSn);
|
||||
return Result.succeed(result, "获取设备维度统计数据成功");
|
||||
} catch (Exception e) {
|
||||
log.error("获取设备维度统计数据失败", e);
|
||||
|
||||
+169
@@ -0,0 +1,169 @@
|
||||
package com.central.order.controller;
|
||||
|
||||
import com.central.common.model.Result;
|
||||
import com.central.order.service.OrderTenantAllocationService;
|
||||
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.Map;
|
||||
|
||||
/**
|
||||
* 订单租户分配测试控制器
|
||||
*/
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequestMapping("/order/tenant-allocation")
|
||||
@Tag(name = "订单租户分配测试")
|
||||
public class OrderTenantAllocationController {
|
||||
|
||||
@Autowired
|
||||
private OrderTenantAllocationService allocationService;
|
||||
|
||||
@Operation(summary = "测试租户分配逻辑")
|
||||
@GetMapping("/test")
|
||||
public Result<Map<String, Object>> testAllocationLogic(
|
||||
@Parameter(description = "用户ID") @RequestParam String userId,
|
||||
@Parameter(description = "二维码ID") @RequestParam String qrCodeId,
|
||||
@Parameter(description = "期望订单数量") @RequestParam(defaultValue = "100") int expectedCount) {
|
||||
|
||||
try {
|
||||
log.info("测试租户分配逻辑 - userId: {}, qrCodeId: {}, expectedCount: {}", userId, qrCodeId, expectedCount);
|
||||
|
||||
Map<String, Object> result = allocationService.validateAllocationLogic(qrCodeId, expectedCount);
|
||||
|
||||
// 添加分配示例
|
||||
Map<String, Object> allocationExample = allocationService.getAllocationStatistics(qrCodeId);
|
||||
result.put("allocationConfig", allocationExample);
|
||||
|
||||
log.info("租户分配逻辑测试完成");
|
||||
return Result.succeed(result, "分配逻辑验证完成");
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("测试租户分配逻辑失败", e);
|
||||
return Result.failed("测试失败:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Operation(summary = "模拟订单分配")
|
||||
@PostMapping("/simulate")
|
||||
public Result<Map<String, Object>> simulateOrderAllocation(
|
||||
@Parameter(description = "用户ID") @RequestParam String userId,
|
||||
@Parameter(description = "二维码ID") @RequestParam String qrCodeId,
|
||||
@Parameter(description = "模拟订单数量") @RequestParam(defaultValue = "22") int orderCount) {
|
||||
|
||||
try {
|
||||
log.info("模拟订单分配 - userId: {}, qrCodeId: {}, orderCount: {}", userId, qrCodeId, orderCount);
|
||||
|
||||
Map<String, Object> result = new java.util.HashMap<>();
|
||||
Map<String, Object> allocationDetails = new java.util.HashMap<>();
|
||||
|
||||
int scenicCount = 0;
|
||||
int platformCount = 0;
|
||||
|
||||
// 模拟订单分配过程
|
||||
for (int i = 0; i < orderCount; i++) {
|
||||
String tenantId = allocationService.determineTenant(qrCodeId, "scenic_tenant_" + qrCodeId);
|
||||
|
||||
if (tenantId.contains("platform")) {
|
||||
platformCount++;
|
||||
} else {
|
||||
scenicCount++;
|
||||
}
|
||||
|
||||
// 记录分配日志(模拟)
|
||||
allocationService.incrementOrderCount(qrCodeId);
|
||||
|
||||
allocationDetails.put("order_" + (i + 1), Map.of(
|
||||
"orderNumber", i + 1,
|
||||
"tenantId", tenantId,
|
||||
"tenantType", tenantId.contains("platform") ? "平台" : "景区"
|
||||
));
|
||||
}
|
||||
|
||||
result.put("totalOrders", orderCount);
|
||||
result.put("scenicOrders", scenicCount);
|
||||
result.put("platformOrders", platformCount);
|
||||
result.put("scenicPercentage", (double) scenicCount / orderCount * 100);
|
||||
result.put("platformPercentage", (double) platformCount / orderCount * 100);
|
||||
result.put("allocationDetails", allocationDetails);
|
||||
|
||||
log.info("模拟订单分配完成 - 总订单: {}, 景区订单: {}, 平台订单: {}", orderCount, scenicCount, platformCount);
|
||||
return Result.succeed(result, "模拟分配完成");
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("模拟订单分配失败", e);
|
||||
return Result.failed("模拟失败:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Operation(summary = "获取分配统计信息")
|
||||
@GetMapping("/statistics")
|
||||
public Result<Map<String, Object>> getAllocationStatistics(
|
||||
@Parameter(description = "二维码ID") @RequestParam String qrCodeId) {
|
||||
|
||||
try {
|
||||
log.info("获取分配统计信息 - qrCodeId: {}", qrCodeId);
|
||||
|
||||
Map<String, Object> result = allocationService.getAllocationStatistics(qrCodeId);
|
||||
|
||||
return Result.succeed(result, "获取统计信息成功");
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("获取分配统计信息失败", e);
|
||||
return Result.failed("获取失败:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Operation(summary = "获取详细诊断信息")
|
||||
@GetMapping("/diagnostics")
|
||||
public Result<Map<String, Object>> getDetailedDiagnostics(
|
||||
@Parameter(description = "二维码ID") @RequestParam String qrCodeId) {
|
||||
|
||||
try {
|
||||
log.info("获取详细诊断信息 - qrCodeId: {}", qrCodeId);
|
||||
|
||||
Map<String, Object> result = allocationService.getDetailedDiagnostics(qrCodeId);
|
||||
|
||||
return Result.succeed(result, "获取诊断信息成功");
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("获取详细诊断信息失败", e);
|
||||
return Result.failed("获取失败:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Operation(summary = "测试数据库查询")
|
||||
@GetMapping("/test-db")
|
||||
public Result<Map<String, Object>> testDatabaseQuery(
|
||||
@Parameter(description = "二维码ID") @RequestParam String qrCodeId) {
|
||||
|
||||
try {
|
||||
log.info("测试数据库查询 - qrCodeId: {}", qrCodeId);
|
||||
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
|
||||
// 测试各种查询
|
||||
int totalOrders = allocationService.getOrderCountByQrCode(qrCodeId);
|
||||
result.put("totalOrders", totalOrders);
|
||||
|
||||
// 获取统计信息
|
||||
Map<String, Object> statistics = allocationService.getAllocationStatistics(qrCodeId);
|
||||
result.put("statistics", statistics);
|
||||
|
||||
// 获取诊断信息
|
||||
Map<String, Object> diagnostics = allocationService.getDetailedDiagnostics(qrCodeId);
|
||||
result.put("diagnostics", diagnostics);
|
||||
|
||||
return Result.succeed(result, "数据库查询测试完成");
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("测试数据库查询失败", e);
|
||||
return Result.failed("测试失败:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
+3
@@ -79,6 +79,9 @@ public class QrCodeController {
|
||||
String codeId = UUID.randomUUID().toString();
|
||||
Result<Map> result = fileCenterService.uploadQrCodeFile(codeId);
|
||||
if (result.getResp_code() == 0){
|
||||
Tourism tourism = tourismService.getTourismById(qrCode.getTourismId());
|
||||
Assert.notNull(tourism, "请选择景区数据");
|
||||
qrCode.setTenantId(tourism.getTenantId());
|
||||
qrCode.setCodeId(codeId);
|
||||
qrCode.setFilePath(result.getData().get("filePath").toString());
|
||||
qrCode.setFileId(result.getData().get("fileId").toString());
|
||||
|
||||
+53
-6
@@ -1,5 +1,6 @@
|
||||
package com.central.order.controller;
|
||||
|
||||
import com.central.common.context.TenantContextHolder;
|
||||
import com.central.common.model.PageResult;
|
||||
import com.central.common.model.Result;
|
||||
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.feign.UserCenterService;
|
||||
import com.central.order.model.Order;
|
||||
import com.central.order.model.QrCode;
|
||||
import com.central.order.service.IOrderService;
|
||||
import com.central.order.service.IQrCodeService;
|
||||
import com.central.order.service.IRefundService;
|
||||
import com.central.order.service.IWxTemplateMessageService;
|
||||
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.CreateRequest;
|
||||
import com.wechat.pay.java.service.refund.model.Refund;
|
||||
@@ -49,6 +55,12 @@ public class RefundController {
|
||||
@Autowired
|
||||
private UserCenterService userCenterService;
|
||||
|
||||
@Autowired
|
||||
private WechatConfigService wechatConfigService;
|
||||
|
||||
@Autowired
|
||||
private IQrCodeService qrCodeService;
|
||||
|
||||
@Value("${tencent.refund-notify-url}")
|
||||
private String refundNotifyUrl;
|
||||
|
||||
@@ -88,6 +100,7 @@ public class RefundController {
|
||||
refund.setState(RefundState.APPROVING.getId());
|
||||
refund.setRefundReason(refundBody.getRefundReason());
|
||||
refund.setRefundImgs(refundBody.getRefundImgs());
|
||||
refund.setTenantId(order.getTenantId());
|
||||
boolean res = refundService.createRefund(refund);
|
||||
if (res) {
|
||||
order.setOrderStatus(OrderStatus.REFUNDING.getId());
|
||||
@@ -105,6 +118,7 @@ public class RefundController {
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
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());
|
||||
Assert.notNull(order, "ORDER DATA不存在");
|
||||
@@ -134,6 +148,8 @@ public class RefundController {
|
||||
public Result<String> autoRefundProcess(@RequestBody Map payload) {
|
||||
String orderNo = payload.get("orderNo").toString();
|
||||
Assert.notNull(orderNo,"订单数据不能为空");
|
||||
//机库端触发异常后自动创建退款单,没有带请求头信息,因此没有租户ID @TODO
|
||||
TenantContextHolder.setTenant("webApp");
|
||||
log.info("收到自动退款请求,订单号: {}", orderNo);
|
||||
try {
|
||||
|
||||
@@ -174,6 +190,7 @@ public class RefundController {
|
||||
refund.setRefundAmount(order.getOrderAmount());
|
||||
refund.setStatus(OrderStatus.REFUNDING.getId());
|
||||
refund.setState(RefundState.APPROVING.getId());
|
||||
refund.setTenantId(order.getTenantId());
|
||||
refund.setRefundReason("机库执行任务异常自动退款,该退款单由系统自动创建,请高传旭先生仔细核实!");
|
||||
|
||||
boolean refundCreated = refundService.createRefund(refund);
|
||||
@@ -203,6 +220,8 @@ public class RefundController {
|
||||
} catch (Exception e) {
|
||||
log.error("退款流程测试失败,订单号: {},异常: {}", orderNo, e.getMessage(), e);
|
||||
return Result.failed("退款流程测试失败:" + e.getMessage());
|
||||
}finally {
|
||||
TenantContextHolder.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -212,29 +231,57 @@ public class RefundController {
|
||||
*/
|
||||
private void dealRefundRequest(Order order) {
|
||||
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();
|
||||
request.setOutTradeNo(order.getOrderNo());
|
||||
request.setOutRefundNo("RF" + order.getOrderNo());
|
||||
request.setReason("用户申请退款");
|
||||
// 从配置文件中获取退款结果回调通知地址
|
||||
request.setNotifyUrl(refundNotifyUrl);
|
||||
|
||||
// 设置退款金额
|
||||
AmountReq amount = new AmountReq();
|
||||
// 订单总金额,单位为分
|
||||
amount.setTotal(Long.valueOf(order.getOrderAmount()));
|
||||
// 退款金额,单位为分
|
||||
amount.setRefund(Long.valueOf(order.getOrderAmount()));
|
||||
amount.setCurrency("CNY");
|
||||
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, "退款失败");
|
||||
|
||||
log.info("退款请求成功,退款单号: {}, 订单号: {}", response.getRefundId(), order.getOrderNo());
|
||||
} catch (Exception e) {
|
||||
// 记录异常信息
|
||||
e.printStackTrace();
|
||||
log.error("退款请求失败,订单号: {}, 异常: {}", order.getOrderNo(), e.getMessage(), e);
|
||||
throw new RuntimeException("退款失败: " + e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+151
@@ -0,0 +1,151 @@
|
||||
package com.central.order.controller;
|
||||
|
||||
import com.central.common.model.Result;
|
||||
import com.central.order.config.TenantAllocationConfig;
|
||||
import com.central.order.service.OrderTenantAllocationService;
|
||||
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.Map;
|
||||
|
||||
/**
|
||||
* 租户分配配置管理控制器
|
||||
*/
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequestMapping("/tenant-allocation/config")
|
||||
@Tag(name = "租户分配配置管理")
|
||||
public class TenantAllocationConfigController {
|
||||
|
||||
@Autowired
|
||||
private TenantAllocationConfig config;
|
||||
|
||||
@Autowired
|
||||
private OrderTenantAllocationService allocationService;
|
||||
|
||||
@Operation(summary = "获取当前配置")
|
||||
@GetMapping("/current")
|
||||
public Result<Map<String, Object>> getCurrentConfig() {
|
||||
try {
|
||||
Map<String, Object> result = Map.of(
|
||||
"enabled", config.isEnabled(),
|
||||
"allocationRatio", config.getAllocationRatio(),
|
||||
"platformTenantId", config.getPlatformTenantId(),
|
||||
"debug", config.isDebug(),
|
||||
"forcePlatformTenant", config.isForcePlatformTenant()
|
||||
);
|
||||
|
||||
return Result.succeed(result, "获取配置成功");
|
||||
} catch (Exception e) {
|
||||
log.error("获取配置失败", e);
|
||||
return Result.failed("获取配置失败:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Operation(summary = "更新配置")
|
||||
@PostMapping("/update")
|
||||
public Result<String> updateConfig(
|
||||
@Parameter(description = "是否启用") @RequestParam(required = false) Boolean enabled,
|
||||
@Parameter(description = "分配比例") @RequestParam(required = false) Integer allocationRatio,
|
||||
@Parameter(description = "平台租户ID") @RequestParam(required = false) String platformTenantId,
|
||||
@Parameter(description = "是否调试模式") @RequestParam(required = false) Boolean debug,
|
||||
@Parameter(description = "是否强制平台租户") @RequestParam(required = false) Boolean forcePlatformTenant) {
|
||||
|
||||
try {
|
||||
if (enabled != null) {
|
||||
config.setEnabled(enabled);
|
||||
log.info("更新配置 - enabled: {}", enabled);
|
||||
}
|
||||
|
||||
if (allocationRatio != null) {
|
||||
config.setAllocationRatio(allocationRatio);
|
||||
log.info("更新配置 - allocationRatio: {}", allocationRatio);
|
||||
}
|
||||
|
||||
if (platformTenantId != null) {
|
||||
config.setPlatformTenantId(platformTenantId);
|
||||
log.info("更新配置 - platformTenantId: {}", platformTenantId);
|
||||
}
|
||||
|
||||
if (debug != null) {
|
||||
config.setDebug(debug);
|
||||
log.info("更新配置 - debug: {}", debug);
|
||||
}
|
||||
|
||||
if (forcePlatformTenant != null) {
|
||||
config.setForcePlatformTenant(forcePlatformTenant);
|
||||
log.info("更新配置 - forcePlatformTenant: {}", forcePlatformTenant);
|
||||
}
|
||||
|
||||
return Result.succeed("配置更新成功");
|
||||
} catch (Exception e) {
|
||||
log.error("更新配置失败", e);
|
||||
return Result.failed("更新配置失败:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Operation(summary = "启用租户分配功能")
|
||||
@PostMapping("/enable")
|
||||
public Result<String> enableAllocation() {
|
||||
try {
|
||||
config.setEnabled(true);
|
||||
log.info("启用租户分配功能");
|
||||
return Result.succeed("租户分配功能已启用");
|
||||
} catch (Exception e) {
|
||||
log.error("启用租户分配功能失败", e);
|
||||
return Result.failed("启用失败:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Operation(summary = "禁用租户分配功能")
|
||||
@PostMapping("/disable")
|
||||
public Result<String> disableAllocation() {
|
||||
try {
|
||||
config.setEnabled(false);
|
||||
log.info("禁用租户分配功能");
|
||||
return Result.succeed("租户分配功能已禁用");
|
||||
} catch (Exception e) {
|
||||
log.error("禁用租户分配功能失败", e);
|
||||
return Result.failed("禁用失败:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Operation(summary = "测试配置")
|
||||
@PostMapping("/test")
|
||||
public Result<Map<String, Object>> testConfig(
|
||||
@Parameter(description = "用户ID") @RequestParam String userId,
|
||||
@Parameter(description = "二维码ID") @RequestParam String qrCodeId,
|
||||
@Parameter(description = "测试订单数量") @RequestParam(defaultValue = "22") int testCount) {
|
||||
|
||||
try {
|
||||
log.info("测试配置 - userId: {}, qrCodeId: {}, testCount: {}", userId, qrCodeId, testCount);
|
||||
|
||||
// 获取当前配置
|
||||
Map<String, Object> currentConfig = Map.of(
|
||||
"enabled", config.isEnabled(),
|
||||
"allocationRatio", config.getAllocationRatio(),
|
||||
"platformTenantId", config.getPlatformTenantId(),
|
||||
"debug", config.isDebug(),
|
||||
"forcePlatformTenant", config.isForcePlatformTenant()
|
||||
);
|
||||
|
||||
// 测试分配逻辑
|
||||
Map<String, Object> testResult = allocationService.validateAllocationLogic(qrCodeId, testCount);
|
||||
|
||||
// 合并结果
|
||||
Map<String, Object> result = Map.of(
|
||||
"currentConfig", currentConfig,
|
||||
"testResult", testResult
|
||||
);
|
||||
|
||||
return Result.succeed(result, "配置测试完成");
|
||||
} catch (Exception e) {
|
||||
log.error("测试配置失败", e);
|
||||
return Result.failed("测试失败:" + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
+109
-2
@@ -1,8 +1,12 @@
|
||||
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.Result;
|
||||
import com.central.order.model.Tourism;
|
||||
import com.central.order.model.TourismWithDistance;
|
||||
import com.central.order.service.ITourismService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
@@ -12,19 +16,24 @@ 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.security.core.context.SecurityContextHolder;
|
||||
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;
|
||||
|
||||
/**
|
||||
* Tourism information
|
||||
* 景区管理控制器
|
||||
*
|
||||
* @author lsl
|
||||
* @date 2024-12-19 17:51:47
|
||||
*/
|
||||
@Slf4j
|
||||
@RestController
|
||||
@Tag(name = "Tourism管理")
|
||||
@Tag(name = "景区管理")
|
||||
@RequestMapping("/tourism")
|
||||
@RequiredArgsConstructor
|
||||
public class TourismController {
|
||||
@@ -47,6 +56,11 @@ public class TourismController {
|
||||
|
||||
@PostMapping()
|
||||
public Result saveOrUpdate(@RequestBody Tourism tourism) {
|
||||
if (tourism.getTenantId() == null) {
|
||||
String tenantId = TenantContextHolder.getTenant();
|
||||
//新增景区所属租户ID,创建景区的时候在
|
||||
tourism.setTenantId(tenantId);
|
||||
}
|
||||
return tourismService.saveOrUpdateTourism(tourism);
|
||||
}
|
||||
|
||||
@@ -66,4 +80,97 @@ public class TourismController {
|
||||
boolean result = tourismService.removeById(tourism);
|
||||
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());
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
+62
-11
@@ -1,5 +1,6 @@
|
||||
package com.central.order.controller;
|
||||
|
||||
import com.central.common.context.TenantContextHolder;
|
||||
import com.central.order.enums.OrderStatus;
|
||||
import com.central.order.enums.RefundState;
|
||||
import com.central.order.model.Order;
|
||||
@@ -69,6 +70,8 @@ public class WxPayController {
|
||||
WechatConfig config = wechatConfigService.getConfigBySerialNumber(serial);
|
||||
Assert.notNull(config,"支付配置参数为空,请确认参数是否正确配置");
|
||||
String tenantId = config.getTenantId();
|
||||
log.info("订单支付回调租户ID设置,租户ID:{}", tenantId);
|
||||
TenantContextHolder.setTenant(tenantId);
|
||||
|
||||
// 创建通知解析器
|
||||
NotificationParser notificationParser;
|
||||
@@ -120,12 +123,36 @@ public class WxPayController {
|
||||
* 处理服务商模式下的支付结果
|
||||
*/
|
||||
private void handleSubMerchantPaymentResult(Transaction transaction, WechatConfig config) {
|
||||
// TODO: 实现服务商模式下的支付结果处理逻辑
|
||||
|
||||
log.info("处理服务商模式支付结果,子商户号:{}", config.getSubMchId());
|
||||
|
||||
// 1. 更新订单状态
|
||||
// 2. 处理分账逻辑(如果需要)
|
||||
// 3. 发送通知
|
||||
String outTradeNo = transaction.getOutTradeNo();
|
||||
String tradeState = transaction.getTradeState().toString();
|
||||
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -173,6 +200,7 @@ public class WxPayController {
|
||||
@RequestBody String body) {
|
||||
log.info("------收到微信退款回调通知------");
|
||||
try {
|
||||
TenantContextHolder.setTenant(defaultTenantId);
|
||||
// 构建请求参数
|
||||
RequestParam requestParam = new RequestParam
|
||||
.Builder()
|
||||
@@ -185,10 +213,10 @@ public class WxPayController {
|
||||
|
||||
// 根据证书序列号获取配置
|
||||
WechatConfig config = wechatConfigService.getConfigBySerialNumber(serial);
|
||||
String tenantId = defaultTenantId;
|
||||
if (config != null) {
|
||||
tenantId = config.getTenantId();
|
||||
}
|
||||
Assert.notNull(config,"支付配置参数为空,请确认参数是否正确配置");
|
||||
String tenantId = config.getTenantId();
|
||||
log.info("订单退款回调租户ID设置,租户ID:{}", tenantId);
|
||||
TenantContextHolder.setTenant(tenantId);
|
||||
|
||||
// 创建通知解析器
|
||||
NotificationParser notificationParser;
|
||||
@@ -212,6 +240,8 @@ public class WxPayController {
|
||||
// 处理异常,记录日志等
|
||||
log.error("处理退款回调失败", e);
|
||||
return buildErrorResponse();
|
||||
}finally {
|
||||
TenantContextHolder.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -240,11 +270,32 @@ public class WxPayController {
|
||||
* 处理服务商模式下的退款结果
|
||||
*/
|
||||
private void handleSubMerchantRefundResult(RefundNotification notification, WechatConfig config) {
|
||||
// TODO: 实现服务商模式下的退款结果处理逻辑
|
||||
|
||||
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, "活动"),
|
||||
SHOOTING_ANGLE(2,"拍照角度"),
|
||||
GUIDANCE(3,"引导"),
|
||||
BIG_PICTURE(4,"大图");
|
||||
BIG_PICTURE(4,"大图"),
|
||||
VIDEO(5,"景区视频"),
|
||||
ORDER_SHOW(6,"订单展示图");
|
||||
|
||||
private Integer id;
|
||||
private String content;
|
||||
|
||||
+23
@@ -47,4 +47,27 @@ public interface FileCenterService {
|
||||
|
||||
@GetMapping("/list/files")
|
||||
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();
|
||||
}
|
||||
|
||||
@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());
|
||||
}
|
||||
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
-10
@@ -37,18 +37,8 @@ public class OrderStatusChangeListener {
|
||||
@Autowired
|
||||
private IOrderService orderService;
|
||||
@Autowired
|
||||
private IQrCodeService qrCodeService;
|
||||
@Autowired
|
||||
private IVideoEditService videoEditService;
|
||||
@Autowired
|
||||
private IOrderFileService orderFileService;
|
||||
@Autowired
|
||||
private IWxTemplateMessageService wxTemplateMessageService;
|
||||
@Autowired
|
||||
private UserCenterService userCenterService;
|
||||
@Autowired
|
||||
private IEditTaskService editTaskService;
|
||||
@Autowired
|
||||
private WxMiniSubscribeService wxMiniSubscribeService;
|
||||
|
||||
@EventListener
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
+601
-59
@@ -1,91 +1,633 @@
|
||||
package com.central.order.mapper;
|
||||
|
||||
import com.central.order.model.vo.IncomeDataVO;
|
||||
import com.central.order.model.vo.TourismRankingVO;
|
||||
import com.central.order.model.vo.TrendDataVO;
|
||||
import com.central.order.model.vo.*;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Mapper
|
||||
public interface DashboardMapper {
|
||||
|
||||
@Select("SELECT COUNT(*) FROM orders WHERE is_del = 0")
|
||||
Long getTotalOrders();
|
||||
|
||||
@Select("SELECT COUNT(*) FROM orders WHERE is_del = 0 AND DATE(create_time) = CURDATE()")
|
||||
Long getTodayOrders();
|
||||
|
||||
@Select("SELECT COUNT(*) FROM orders WHERE is_del = 0 AND DATE(create_time) = DATE_SUB(CURDATE(), INTERVAL 1 DAY)")
|
||||
Long getYesterdayOrders();
|
||||
|
||||
@Select("SELECT COUNT(*) FROM orders WHERE is_del = 0 AND order_status = #{completeStatus}")
|
||||
Long getCompletedOrders();
|
||||
// 基础订单统计(支持筛选)
|
||||
@Select({
|
||||
"<script>",
|
||||
"SELECT COUNT(*) as count",
|
||||
"FROM orders o",
|
||||
"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>",
|
||||
"AND o.order_status IN (1, 3, 4, 5, 7, 8)",
|
||||
"<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 getTotalOrders(@Param("p") Map<String, Object> params);
|
||||
|
||||
@Select({
|
||||
"<script>",
|
||||
"SELECT COALESCE(SUM(order_amount), 0)",
|
||||
"FROM orders",
|
||||
"WHERE is_del = 0",
|
||||
"AND order_status IN ${@com.central.order.constants.OrderStatusConstants@PAID_STATUS}",
|
||||
"SELECT COUNT(*) as count",
|
||||
"FROM orders o",
|
||||
"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>",
|
||||
"AND DATE(o.create_time) = CURDATE()",
|
||||
"AND o.order_status IN (1, 3, 4, 5, 7, 8)",
|
||||
"<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>"
|
||||
})
|
||||
Long getTotalIncome();
|
||||
Long getTodayOrders(@Param("p") Map<String, Object> params);
|
||||
|
||||
@Select({
|
||||
"<script>",
|
||||
"SELECT COALESCE(SUM(order_amount), 0)",
|
||||
"FROM orders",
|
||||
"WHERE is_del = 0",
|
||||
"AND order_status IN ${@com.central.order.constants.OrderStatusConstants@PAID_STATUS}",
|
||||
"AND DATE(create_time) = CURDATE()",
|
||||
"SELECT COUNT(*) as count",
|
||||
"FROM orders o",
|
||||
"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>",
|
||||
"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>"
|
||||
})
|
||||
Long getTodayIncome();
|
||||
|
||||
|
||||
Long getYesterdayOrders(@Param("p") Map<String, Object> params);
|
||||
|
||||
@Select({
|
||||
"<script>",
|
||||
"SELECT COUNT(*) as count",
|
||||
"FROM orders o",
|
||||
"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>",
|
||||
"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 COUNT(*) as count",
|
||||
"FROM orders o",
|
||||
"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>",
|
||||
"AND o.order_status = 8",
|
||||
"<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 getRefundedOrders(@Param("p") Map<String, Object> params);
|
||||
|
||||
@Select({
|
||||
"<script>",
|
||||
"SELECT COUNT(*) as count",
|
||||
"FROM orders o",
|
||||
"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>",
|
||||
"AND o.order_status = 8",
|
||||
"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>"
|
||||
})
|
||||
Long getTodayRefundedOrders(@Param("p") Map<String, Object> params);
|
||||
|
||||
@Select({
|
||||
"<script>",
|
||||
"SELECT COUNT(*) as count",
|
||||
"FROM orders o",
|
||||
"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>",
|
||||
"AND o.order_status IN (1, 3, 4, 7, 5)",
|
||||
"<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 getTotalPaidOrders(@Param("p") Map<String, Object> params);
|
||||
|
||||
@Select({
|
||||
"<script>",
|
||||
"SELECT COUNT(*) as count",
|
||||
"FROM orders o",
|
||||
"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>",
|
||||
"AND o.order_status IN (1, 3, 4, 7, 5)",
|
||||
"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>"
|
||||
})
|
||||
Long getTodayPaidOrders(@Param("p") Map<String, Object> params);
|
||||
|
||||
// 对账相关统计
|
||||
@Select({
|
||||
"<script>",
|
||||
"SELECT COALESCE(SUM(o.order_amount), 0) as amount",
|
||||
"FROM orders o",
|
||||
"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>",
|
||||
"AND o.order_status IN (3, 8)",
|
||||
"<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 getTotalAmount(@Param("p") Map<String, Object> params);
|
||||
|
||||
@Select({
|
||||
"<script>",
|
||||
"SELECT COALESCE(SUM(os.platform_amount), 0)",
|
||||
"FROM order_statistics os",
|
||||
"WHERE 1=1",
|
||||
"<if test='p.includeTestQrcodes == null or p.includeTestQrcodes == false'>",
|
||||
" AND os.qrcode_id IN (SELECT code_id FROM qrcodes WHERE 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",
|
||||
"WHERE 1=1",
|
||||
"<if test='p.includeTestQrcodes == null or p.includeTestQrcodes == false'>",
|
||||
" AND os.qrcode_id IN (SELECT code_id FROM qrcodes WHERE 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(o.order_amount), 0) as amount",
|
||||
"FROM orders o",
|
||||
"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>",
|
||||
"AND o.order_status = 8",
|
||||
"<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 getRefundAmount(@Param("p") Map<String, Object> params);
|
||||
|
||||
// 图表数据
|
||||
@Select({
|
||||
"<script>",
|
||||
"SELECT",
|
||||
" DATE_FORMAT(create_time, '%Y-%m-%d') as date,",
|
||||
" 'orders' as type,",
|
||||
" DATE_FORMAT(o.create_time, '%Y-%m-%d') as date,",
|
||||
" 'created' as type,",
|
||||
" COUNT(*) as value",
|
||||
"FROM orders",
|
||||
"WHERE is_del = 0",
|
||||
" AND create_time >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)",
|
||||
"GROUP BY DATE_FORMAT(create_time, '%Y-%m-%d')"
|
||||
})
|
||||
List<TrendDataVO> getOrderTrend();
|
||||
|
||||
@Select({
|
||||
"SELECT",
|
||||
" 'platform' as type,",
|
||||
" SUM(platform_amount) as value",
|
||||
"FROM order_statistics",
|
||||
"WHERE DATE(create_time) = CURDATE()",
|
||||
"FROM orders o",
|
||||
"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.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>",
|
||||
"<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')",
|
||||
"UNION ALL",
|
||||
"SELECT",
|
||||
" 'tourism' as type,",
|
||||
" SUM(tourism_amount) as value",
|
||||
"FROM order_statistics",
|
||||
"WHERE DATE(create_time) = CURDATE()"
|
||||
" DATE_FORMAT(o.create_time, '%Y-%m-%d') as date,",
|
||||
" 'completed' as type,",
|
||||
" COUNT(*) as value",
|
||||
"FROM orders o",
|
||||
"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>",
|
||||
" AND o.order_status = 3",
|
||||
"<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>",
|
||||
"<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')",
|
||||
"UNION ALL",
|
||||
"SELECT",
|
||||
" DATE_FORMAT(o.create_time, '%Y-%m-%d') as date,",
|
||||
" 'refunded' as type,",
|
||||
" COUNT(*) as value",
|
||||
"FROM orders o",
|
||||
"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>",
|
||||
" AND o.order_status = 8",
|
||||
"<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>",
|
||||
"<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, type",
|
||||
"</script>"
|
||||
})
|
||||
List<IncomeDataVO> getIncomeData();
|
||||
List<TrendDataVO> getOrderTrend(@Param("p") Map<String, Object> params);
|
||||
|
||||
@Select({
|
||||
"<script>",
|
||||
"SELECT",
|
||||
" t.id,",
|
||||
" t.tourism_name as name,",
|
||||
" COUNT(o.id) as value",
|
||||
"FROM tourisms t",
|
||||
"LEFT JOIN orders o ON t.id = o.tourism_id",
|
||||
"WHERE t.is_del = 0",
|
||||
" AND o.is_del = 0",
|
||||
" AND o.create_time >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)",
|
||||
"GROUP BY t.id, t.tourism_name",
|
||||
"ORDER BY value DESC",
|
||||
"LIMIT 10"
|
||||
" CASE o.order_status",
|
||||
" WHEN 0 THEN '待支付'",
|
||||
" WHEN 1 THEN '已支付排队中'",
|
||||
" 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 1=1",
|
||||
"<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<TourismRankingVO> getTourismRanking();
|
||||
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",
|
||||
"WHERE 1=1",
|
||||
"<if test='p.includeTestQrcodes == null or p.includeTestQrcodes == false'>",
|
||||
" AND os.qrcode_id IN (SELECT code_id FROM qrcodes WHERE 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.tourism_amount), 0) as value",
|
||||
"FROM order_statistics os",
|
||||
"WHERE 1=1",
|
||||
"<if test='p.includeTestQrcodes == null or p.includeTestQrcodes == false'>",
|
||||
" AND os.qrcode_id IN (SELECT code_id FROM qrcodes WHERE 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",
|
||||
"WHERE 1=1",
|
||||
"<if test='p.includeTestQrcodes == null or p.includeTestQrcodes == false'>",
|
||||
" AND os.qrcode_id IN (SELECT code_id FROM qrcodes WHERE 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> getIncomeBreakdown(@Param("p") Map<String, Object> params);
|
||||
|
||||
@Select({
|
||||
"<script>",
|
||||
"SELECT",
|
||||
" q.name as qrcodeName,",
|
||||
" q.code_id as qrcodeId,",
|
||||
" COUNT(o.id) as orderCount",
|
||||
"FROM qrcodes q",
|
||||
"LEFT JOIN orders o ON q.code_id = o.code_id AND o.order_status = 3",
|
||||
"WHERE q.is_del = 0",
|
||||
"<if test='p.includeTestQrcodes == null or p.includeTestQrcodes == false'>",
|
||||
" AND q.is_test = 0",
|
||||
"</if>",
|
||||
"<if test='p.tourismId != null'>",
|
||||
" AND q.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>",
|
||||
"GROUP BY q.code_id, q.name",
|
||||
"HAVING orderCount > 0",
|
||||
"ORDER BY orderCount DESC",
|
||||
"LIMIT 20",
|
||||
"</script>"
|
||||
})
|
||||
List<QrcodeOrderDataVO> getQrcodeOrderCount(@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({
|
||||
"<script>",
|
||||
"SELECT code_id as value, name as label FROM qrcodes",
|
||||
"WHERE is_del = 0",
|
||||
"<if test='p.includeTestQrcodes == null or p.includeTestQrcodes == false'>",
|
||||
" AND is_test = 0",
|
||||
"</if>",
|
||||
"<if test='p.tourismId != null'>",
|
||||
" AND tourism_id = #{p.tourismId}",
|
||||
"</if>",
|
||||
"ORDER BY create_time DESC",
|
||||
"</script>"
|
||||
})
|
||||
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);
|
||||
|
||||
// 调试时间范围查询
|
||||
@Select({
|
||||
"<script>",
|
||||
"SELECT",
|
||||
" o.id,",
|
||||
" o.order_no,",
|
||||
" o.order_amount,",
|
||||
" o.order_status,",
|
||||
" o.create_time,",
|
||||
" o.tourism_id",
|
||||
"FROM orders o",
|
||||
"WHERE 1=1",
|
||||
"<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>",
|
||||
"ORDER BY o.create_time DESC",
|
||||
"LIMIT 20",
|
||||
"</script>"
|
||||
})
|
||||
List<Map<String, Object>> debugTimeRangeQuery(@Param("p") Map<String, Object> params);
|
||||
}
|
||||
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
package com.central.order.mapper;
|
||||
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
import org.apache.ibatis.annotations.Select;
|
||||
import org.apache.ibatis.annotations.Update;
|
||||
|
||||
/**
|
||||
* 租户分配数据库查询Mapper
|
||||
*/
|
||||
@Mapper
|
||||
public interface OrderTenantAllocationMapper {
|
||||
|
||||
/**
|
||||
* 获取指定二维码下的总订单数量
|
||||
* @param qrCodeId 二维码ID
|
||||
* @return 订单数量
|
||||
*/
|
||||
@Select("SELECT COUNT(*) FROM orders WHERE code_id = #{qrCodeId} AND is_del = 0")
|
||||
int getOrderCountByQrCode(@Param("qrCodeId") String qrCodeId);
|
||||
|
||||
/**
|
||||
* 获取指定二维码下指定租户的订单数量
|
||||
* @param qrCodeId 二维码ID
|
||||
* @param tenantId 租户ID
|
||||
* @return 订单数量
|
||||
*/
|
||||
@Select("SELECT COUNT(*) FROM orders WHERE code_id = #{qrCodeId} AND tenant_id = #{tenantId} AND is_del = 0")
|
||||
int getOrderCountByQrCodeAndTenant(@Param("qrCodeId") String qrCodeId, @Param("tenantId") String tenantId);
|
||||
|
||||
/**
|
||||
* 获取指定二维码下景区租户的订单数量
|
||||
* @param qrCodeId 二维码ID
|
||||
* @param scenicTenantId 景区租户ID
|
||||
* @return 订单数量
|
||||
*/
|
||||
@Select("SELECT COUNT(*) FROM orders WHERE code_id = #{qrCodeId} AND tenant_id = #{scenicTenantId} AND is_del = 0")
|
||||
int getScenicOrderCount(@Param("qrCodeId") String qrCodeId, @Param("scenicTenantId") String scenicTenantId);
|
||||
|
||||
/**
|
||||
* 获取指定二维码下平台租户的订单数量
|
||||
* @param qrCodeId 二维码ID
|
||||
* @param platformTenantId 平台租户ID
|
||||
* @return 订单数量
|
||||
*/
|
||||
@Select("SELECT COUNT(*) FROM orders WHERE code_id = #{qrCodeId} AND tenant_id = #{platformTenantId} AND is_del = 0")
|
||||
int getPlatformOrderCount(@Param("qrCodeId") String qrCodeId, @Param("platformTenantId") String platformTenantId);
|
||||
|
||||
/**
|
||||
* 获取指定二维码下的订单统计信息
|
||||
* @param qrCodeId 二维码ID
|
||||
* @return 统计信息Map
|
||||
*/
|
||||
@Select("SELECT " +
|
||||
"COUNT(*) as totalOrders, " +
|
||||
"SUM(CASE WHEN tenant_id = #{scenicTenantId} THEN 1 ELSE 0 END) as scenicOrders, " +
|
||||
"SUM(CASE WHEN tenant_id = #{platformTenantId} THEN 1 ELSE 0 END) as platformOrders " +
|
||||
"FROM orders " +
|
||||
"WHERE code_id = #{qrCodeId} AND is_del = 0")
|
||||
java.util.Map<String, Object> getOrderStatisticsByQrCode(
|
||||
@Param("qrCodeId") String qrCodeId,
|
||||
@Param("scenicTenantId") String scenicTenantId,
|
||||
@Param("platformTenantId") String platformTenantId);
|
||||
|
||||
/**
|
||||
* 获取指定二维码下最近的订单信息
|
||||
* @param qrCodeId 二维码ID
|
||||
* @param limit 限制数量
|
||||
* @return 订单列表
|
||||
*/
|
||||
@Select("SELECT id, order_no, user_id, tenant_id, order_amount, order_status, create_time " +
|
||||
"FROM orders " +
|
||||
"WHERE code_id = #{qrCodeId} AND is_del = 0 " +
|
||||
"ORDER BY create_time DESC " +
|
||||
"LIMIT #{limit}")
|
||||
java.util.List<java.util.Map<String, Object>> getRecentOrdersByQrCode(
|
||||
@Param("qrCodeId") String qrCodeId, @Param("limit") int limit);
|
||||
|
||||
/**
|
||||
* 获取指定二维码下指定时间范围内的订单数量
|
||||
* @param qrCodeId 二维码ID
|
||||
* @param startTime 开始时间
|
||||
* @param endTime 结束时间
|
||||
* @return 订单数量
|
||||
*/
|
||||
@Select("SELECT COUNT(*) FROM orders " +
|
||||
"WHERE code_id = #{qrCodeId} AND is_del = 0 " +
|
||||
"AND create_time >= #{startTime} AND create_time <= #{endTime}")
|
||||
int getOrderCountByQrCodeAndTimeRange(
|
||||
@Param("qrCodeId") String qrCodeId,
|
||||
@Param("startTime") java.util.Date startTime,
|
||||
@Param("endTime") java.util.Date endTime);
|
||||
}
|
||||
@@ -3,9 +3,11 @@ package com.central.order.mapper;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import com.central.db.mapper.SuperMapper;
|
||||
import com.central.order.model.Tourism;
|
||||
import com.central.order.model.TourismWithDistance;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@@ -32,4 +34,42 @@ public interface TourismMapper extends SuperMapper<Tourism> {
|
||||
// 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
|
||||
);
|
||||
|
||||
}
|
||||
|
||||
+88
@@ -0,0 +1,88 @@
|
||||
package com.central.order.model;
|
||||
|
||||
import lombok.Data;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 携程核销通知请求
|
||||
*/
|
||||
@Data
|
||||
public class CtripConsumedNoticeRequest {
|
||||
|
||||
/**
|
||||
* 请求头
|
||||
*/
|
||||
private CtripConsumedNoticeHeader header;
|
||||
|
||||
/**
|
||||
* 请求体
|
||||
*/
|
||||
private CtripConsumedNoticeBody body;
|
||||
|
||||
/**
|
||||
* 携程核销通知请求头
|
||||
*/
|
||||
@Data
|
||||
public static class CtripConsumedNoticeHeader {
|
||||
/**
|
||||
* 请求时间
|
||||
*/
|
||||
private String requestTime;
|
||||
|
||||
/**
|
||||
* 账户ID
|
||||
*/
|
||||
private String accountId;
|
||||
|
||||
/**
|
||||
* 签名
|
||||
*/
|
||||
private String sign;
|
||||
|
||||
/**
|
||||
* 服务名称
|
||||
*/
|
||||
private String serviceName;
|
||||
|
||||
/**
|
||||
* 版本号
|
||||
*/
|
||||
private String version;
|
||||
}
|
||||
|
||||
/**
|
||||
* 携程核销通知请求体
|
||||
*/
|
||||
@Data
|
||||
public static class CtripConsumedNoticeBody {
|
||||
/**
|
||||
* OTA订单ID
|
||||
*/
|
||||
private String otaOrderId;
|
||||
|
||||
/**
|
||||
* 供应商订单ID
|
||||
*/
|
||||
private String supplierOrderId;
|
||||
|
||||
/**
|
||||
* 核销时间
|
||||
*/
|
||||
private String consumedTime;
|
||||
|
||||
/**
|
||||
* 核销地点
|
||||
*/
|
||||
private String consumedLocation;
|
||||
|
||||
/**
|
||||
* 核销人
|
||||
*/
|
||||
private String consumedBy;
|
||||
|
||||
/**
|
||||
* 核销备注
|
||||
*/
|
||||
private String consumedRemark;
|
||||
}
|
||||
}
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
package com.central.order.model;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 携程核销通知响应
|
||||
*/
|
||||
@Data
|
||||
public class CtripConsumedNoticeResponse {
|
||||
|
||||
/**
|
||||
* 响应头
|
||||
*/
|
||||
private CtripConsumedNoticeResponseHeader header;
|
||||
|
||||
/**
|
||||
* 响应码
|
||||
*/
|
||||
private String resultCode;
|
||||
|
||||
/**
|
||||
* 响应消息
|
||||
*/
|
||||
private String resultMessage;
|
||||
|
||||
/**
|
||||
* 响应体
|
||||
*/
|
||||
private CtripConsumedNoticeResponseBody body;
|
||||
|
||||
/**
|
||||
* 携程核销通知响应头
|
||||
*/
|
||||
@Data
|
||||
public static class CtripConsumedNoticeResponseHeader {
|
||||
/**
|
||||
* 请求时间
|
||||
*/
|
||||
private String requestTime;
|
||||
|
||||
/**
|
||||
* 账户ID
|
||||
*/
|
||||
private String accountId;
|
||||
|
||||
/**
|
||||
* 签名
|
||||
*/
|
||||
private String sign;
|
||||
|
||||
/**
|
||||
* 服务名称
|
||||
*/
|
||||
private String serviceName;
|
||||
|
||||
/**
|
||||
* 版本号
|
||||
*/
|
||||
private String version;
|
||||
}
|
||||
|
||||
/**
|
||||
* 携程核销通知响应体
|
||||
*/
|
||||
@Data
|
||||
public static class CtripConsumedNoticeResponseBody {
|
||||
/**
|
||||
* OTA订单ID
|
||||
*/
|
||||
private String otaOrderId;
|
||||
|
||||
/**
|
||||
* 供应商订单ID
|
||||
*/
|
||||
private String supplierOrderId;
|
||||
|
||||
/**
|
||||
* 处理结果
|
||||
*/
|
||||
private String processResult;
|
||||
|
||||
/**
|
||||
* 处理时间
|
||||
*/
|
||||
private String processTime;
|
||||
}
|
||||
}
|
||||
+190
@@ -0,0 +1,190 @@
|
||||
package com.central.order.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.Data;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 携程订单新订请求
|
||||
*/
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class CtripCreateOrderRequest {
|
||||
|
||||
/**
|
||||
* 请求头
|
||||
*/
|
||||
@JsonProperty("header")
|
||||
private CtripHeader header;
|
||||
|
||||
/**
|
||||
* 请求体 - 可能是加密字符串或JSON对象
|
||||
*/
|
||||
@JsonProperty("body")
|
||||
private Object body; // 改为Object类型,支持字符串和对象两种格式
|
||||
|
||||
/**
|
||||
* 携程请求头
|
||||
*/
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class CtripHeader {
|
||||
@JsonProperty("requestTime")
|
||||
private String requestTime;
|
||||
@JsonProperty("accountId")
|
||||
private String accountId;
|
||||
@JsonProperty("sign")
|
||||
private String sign;
|
||||
@JsonProperty("serviceName")
|
||||
private String serviceName;
|
||||
@JsonProperty("version")
|
||||
private String version;
|
||||
}
|
||||
|
||||
/**
|
||||
* 携程订单体
|
||||
*/
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class CtripOrderBody {
|
||||
@JsonProperty("otaOrderId")
|
||||
private String otaOrderId;
|
||||
@JsonProperty("sequenceId")
|
||||
private String sequenceId;
|
||||
@JsonProperty("items")
|
||||
private List<CtripOrderItem> items;
|
||||
@JsonProperty("contacts")
|
||||
private List<CtripContact> contacts;
|
||||
@JsonProperty("confirmType")
|
||||
private Integer confirmType;
|
||||
@JsonProperty("locale")
|
||||
private String locale;
|
||||
}
|
||||
|
||||
/**
|
||||
* 携程订单项
|
||||
*/
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class CtripOrderItem {
|
||||
@JsonProperty("passengers")
|
||||
private List<CtripPassenger> passengers;
|
||||
@JsonProperty("cost")
|
||||
private java.math.BigDecimal cost;
|
||||
@JsonProperty("quantity")
|
||||
private Integer quantity;
|
||||
@JsonProperty("salePrice")
|
||||
private java.math.BigDecimal salePrice;
|
||||
@JsonProperty("remark")
|
||||
private String remark;
|
||||
@JsonProperty("useEndDate")
|
||||
private String useEndDate;
|
||||
@JsonProperty("locale")
|
||||
private String locale;
|
||||
@JsonProperty("useStartDate")
|
||||
private String useStartDate;
|
||||
@JsonProperty("priceCurrency")
|
||||
private String priceCurrency;
|
||||
@JsonProperty("adjunctions")
|
||||
private List<String> adjunctions;
|
||||
@JsonProperty("price")
|
||||
private java.math.BigDecimal price;
|
||||
@JsonProperty("PLU")
|
||||
private String PLU;
|
||||
@JsonProperty("deposit")
|
||||
private Object deposit; // 改回Object类型,因为可能是对象
|
||||
@JsonProperty("distributionChannel")
|
||||
private String distributionChannel;
|
||||
@JsonProperty("costCurrency")
|
||||
private String costCurrency;
|
||||
@JsonProperty("salePriceCurrency")
|
||||
private String salePriceCurrency;
|
||||
@JsonProperty("expressDelivery")
|
||||
private CtripExpressDelivery expressDelivery;
|
||||
}
|
||||
|
||||
/**
|
||||
* 携程乘客信息
|
||||
*/
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class CtripPassenger {
|
||||
@JsonProperty("cardIssuePlace")
|
||||
private String cardIssuePlace;
|
||||
@JsonProperty("lastName")
|
||||
private String lastName;
|
||||
@JsonProperty("cardIssueCountry")
|
||||
private String cardIssueCountry;
|
||||
@JsonProperty("shoeSize")
|
||||
private Integer shoeSize;
|
||||
@JsonProperty("gender")
|
||||
private String gender;
|
||||
@JsonProperty("cardIssueDate")
|
||||
private String cardIssueDate;
|
||||
@JsonProperty("intlCode")
|
||||
private String intlCode;
|
||||
@JsonProperty("nationalityName")
|
||||
private String nationalityName;
|
||||
@JsonProperty("mobile")
|
||||
private String mobile;
|
||||
@JsonProperty("cardType")
|
||||
private String cardType;
|
||||
@JsonProperty("weight")
|
||||
private Integer weight;
|
||||
@JsonProperty("myopiaDegreeL")
|
||||
private Integer myopiaDegreeL;
|
||||
@JsonProperty("birthDate")
|
||||
private String birthDate;
|
||||
@JsonProperty("cardNo")
|
||||
private String cardNo;
|
||||
@JsonProperty("ageType")
|
||||
private String ageType;
|
||||
@JsonProperty("myopiaDegreeR")
|
||||
private Integer myopiaDegreeR;
|
||||
@JsonProperty("firstName")
|
||||
private String firstName;
|
||||
@JsonProperty("birthPlace")
|
||||
private String birthPlace;
|
||||
@JsonProperty("nationalityCode")
|
||||
private String nationalityCode;
|
||||
@JsonProperty("name")
|
||||
private String name;
|
||||
@JsonProperty("passengerId")
|
||||
private String passengerId;
|
||||
@JsonProperty("cardValidDate")
|
||||
private String cardValidDate;
|
||||
@JsonProperty("height")
|
||||
private Integer height;
|
||||
}
|
||||
|
||||
/**
|
||||
* 携程联系人信息
|
||||
*/
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class CtripContact {
|
||||
@JsonProperty("intlCode")
|
||||
private String intlCode;
|
||||
@JsonProperty("name")
|
||||
private String name;
|
||||
@JsonProperty("mobile")
|
||||
private String mobile;
|
||||
@JsonProperty("optionalMobile")
|
||||
private String optionalMobile;
|
||||
@JsonProperty("optionalIntlCode")
|
||||
private String optionalIntlCode;
|
||||
@JsonProperty("email")
|
||||
private String email;
|
||||
}
|
||||
|
||||
/**
|
||||
* 携程快递信息
|
||||
*/
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class CtripExpressDelivery {
|
||||
@JsonProperty("type")
|
||||
private String type;
|
||||
}
|
||||
}
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
package com.central.order.model;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.Data;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 携程订单新订响应
|
||||
*/
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class CtripCreateOrderResponse {
|
||||
|
||||
/**
|
||||
* 返回头
|
||||
*/
|
||||
@JsonProperty("header")
|
||||
private CtripResponseHeader header;
|
||||
|
||||
/**
|
||||
* 处理结果返回码
|
||||
*/
|
||||
@JsonProperty("resultCode")
|
||||
private String resultCode;
|
||||
|
||||
/**
|
||||
* 处理结果返回信息
|
||||
*/
|
||||
@JsonProperty("resultMessage")
|
||||
private String resultMessage;
|
||||
|
||||
/**
|
||||
* 返回体
|
||||
*/
|
||||
@JsonProperty("body")
|
||||
private CtripResponseBody body;
|
||||
|
||||
/**
|
||||
* 携程返回头
|
||||
*/
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class CtripResponseHeader {
|
||||
@JsonProperty("requestTime")
|
||||
private String requestTime;
|
||||
@JsonProperty("accountId")
|
||||
private String accountId;
|
||||
@JsonProperty("sign")
|
||||
private String sign;
|
||||
@JsonProperty("serviceName")
|
||||
private String serviceName;
|
||||
@JsonProperty("version")
|
||||
private String version;
|
||||
}
|
||||
|
||||
/**
|
||||
* 携程返回体
|
||||
*/
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class CtripResponseBody {
|
||||
@JsonProperty("otaOrderId")
|
||||
private String otaOrderId;
|
||||
@JsonProperty("supplierOrderId")
|
||||
private String supplierOrderId;
|
||||
@JsonProperty("supplierConfirmType")
|
||||
private Integer supplierConfirmType;
|
||||
@JsonProperty("voucherSender")
|
||||
private Integer voucherSender;
|
||||
@JsonProperty("vouchers")
|
||||
private List<CtripVoucher> vouchers;
|
||||
@JsonProperty("orderExtendMessage")
|
||||
private String orderExtendMessage;
|
||||
@JsonProperty("items")
|
||||
private List<CtripResponseOrderItem> items;
|
||||
}
|
||||
|
||||
/**
|
||||
* 携程凭证
|
||||
*/
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class CtripVoucher {
|
||||
@JsonProperty("voucherType")
|
||||
private Integer voucherType;
|
||||
@JsonProperty("voucherContent")
|
||||
private String voucherContent;
|
||||
@JsonProperty("voucherUrl")
|
||||
private String voucherUrl;
|
||||
@JsonProperty("locale")
|
||||
private String locale;
|
||||
}
|
||||
|
||||
/**
|
||||
* 携程返回订单项
|
||||
*/
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public static class CtripResponseOrderItem {
|
||||
@JsonProperty("itemId")
|
||||
private String itemId;
|
||||
@JsonProperty("supplierItemId")
|
||||
private String supplierItemId;
|
||||
@JsonProperty("status")
|
||||
private Integer status;
|
||||
@JsonProperty("message")
|
||||
private String message;
|
||||
}
|
||||
}
|
||||
@@ -53,6 +53,7 @@ public class Order extends SuperEntity {
|
||||
|
||||
private transient String waylineLinkUrl;
|
||||
private transient JSONObject streamUrls;
|
||||
private transient String tourismImgUrl;
|
||||
|
||||
|
||||
}
|
||||
|
||||
@@ -46,4 +46,8 @@ public class OrderFile extends SuperEntity {
|
||||
private String tenantId;
|
||||
private Integer isDel;
|
||||
|
||||
/**
|
||||
* 文件标签,如ai_video、raw_video等
|
||||
*/
|
||||
private String fileTag;
|
||||
}
|
||||
|
||||
@@ -99,4 +99,10 @@ public class QrCode extends SuperEntity {
|
||||
@Schema(description = "素材数量")
|
||||
private Integer materialCount;
|
||||
|
||||
/**
|
||||
* 是否为测试二维码(0:否,1:是)
|
||||
*/
|
||||
@Schema(description = "是否为测试二维码")
|
||||
private Integer isTest;
|
||||
|
||||
}
|
||||
|
||||
@@ -8,10 +8,11 @@ import lombok.EqualsAndHashCode;
|
||||
import lombok.Getter;
|
||||
import lombok.Setter;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Date;
|
||||
|
||||
/**
|
||||
* Device information
|
||||
* 景区信息实体类
|
||||
*
|
||||
* @author lsl
|
||||
* @date 2024-12-19 17:51:47
|
||||
@@ -34,6 +35,16 @@ public class Tourism extends SuperEntity {
|
||||
private String tourismPhone;
|
||||
private String tourismEmail;
|
||||
|
||||
/**
|
||||
* 景区经度
|
||||
*/
|
||||
private BigDecimal longitude;
|
||||
|
||||
/**
|
||||
* 景区纬度
|
||||
*/
|
||||
private BigDecimal latitude;
|
||||
|
||||
@TableField(fill = FieldFill.INSERT)
|
||||
private Date createTime;
|
||||
@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;
|
||||
}
|
||||
}
|
||||
+7
-4
@@ -6,14 +6,17 @@ import lombok.Data;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@Schema(description = "图表统计数据")
|
||||
@Schema(description = "图表统计")
|
||||
public class ChartStatistics {
|
||||
@Schema(description = "订单趋势")
|
||||
private List<TrendDataVO> orderTrend;
|
||||
|
||||
@Schema(description = "设备分布")
|
||||
private List<DistributionDataVO> deviceDistribution;
|
||||
@Schema(description = "订单状态分布")
|
||||
private List<DistributionDataVO> orderDistribution;
|
||||
|
||||
@Schema(description = "收入构成")
|
||||
private List<IncomeDataVO> incomeData;
|
||||
private List<IncomeDataVO> incomeBreakdown;
|
||||
|
||||
@Schema(description = "二维码订单数量")
|
||||
private List<QrcodeOrderDataVO> qrcodeOrderCount;
|
||||
}
|
||||
+2
-11
@@ -11,18 +11,9 @@ public class DashboardStatisticsVO {
|
||||
@Schema(description = "订单统计")
|
||||
private OrderStatistics orderStats;
|
||||
|
||||
@Schema(description = "收入统计")
|
||||
private IncomeStatistics incomeStats;
|
||||
|
||||
@Schema(description = "航线统计")
|
||||
private WaylineStatistics waylineStats;
|
||||
|
||||
@Schema(description = "设备统计")
|
||||
private DeviceStatistics deviceStats;
|
||||
|
||||
@Schema(description = "图表统计")
|
||||
private ChartStatistics chartStats;
|
||||
|
||||
@Schema(description = "景区排行")
|
||||
private List<TourismRankingVO> tourismRanking;
|
||||
@Schema(description = "筛选选项")
|
||||
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;
|
||||
}
|
||||
}
|
||||
+27
-3
@@ -6,9 +6,9 @@ import lombok.Data;
|
||||
import java.math.BigDecimal;
|
||||
|
||||
@Data
|
||||
@Schema(description = "订单统计数据")
|
||||
@Schema(description = "订单统计")
|
||||
public class OrderStatistics {
|
||||
@Schema(description = "订单总数")
|
||||
@Schema(description = "总订单数")
|
||||
private Long totalOrders;
|
||||
|
||||
@Schema(description = "今日订单数")
|
||||
@@ -17,6 +17,30 @@ public class OrderStatistics {
|
||||
@Schema(description = "订单增长率")
|
||||
private BigDecimal orderGrowth;
|
||||
|
||||
@Schema(description = "订单完成率")
|
||||
@Schema(description = "完成率")
|
||||
private BigDecimal completionRate;
|
||||
|
||||
@Schema(description = "退款订单数")
|
||||
private Long refundedOrders;
|
||||
|
||||
@Schema(description = "总完成订单数")
|
||||
private Long completedOrders;
|
||||
|
||||
@Schema(description = "总收款订单数")
|
||||
private Long totalPaidOrders;
|
||||
|
||||
@Schema(description = "今日收款订单数")
|
||||
private Long todayPaidOrders;
|
||||
|
||||
@Schema(description = "今日退款订单数")
|
||||
private Long todayRefundedOrders;
|
||||
|
||||
@Schema(description = "订单总金额(分)")
|
||||
private Long totalAmount;
|
||||
|
||||
@Schema(description = "退款金额(分)")
|
||||
private Long refundAmount;
|
||||
|
||||
@Schema(description = "净收入(分)")
|
||||
private Long netIncome;
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package com.central.order.model.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
@Schema(description = "二维码订单数据")
|
||||
public class QrcodeOrderDataVO {
|
||||
@Schema(description = "二维码名称")
|
||||
private String qrcodeName;
|
||||
|
||||
@Schema(description = "二维码ID")
|
||||
private String qrcodeId;
|
||||
|
||||
@Schema(description = "订单数量")
|
||||
private Long orderCount;
|
||||
}
|
||||
+13
-8
@@ -1,12 +1,15 @@
|
||||
package com.central.order.scheduler;
|
||||
|
||||
import com.central.common.context.TenantContextHolder;
|
||||
import com.central.order.service.IOrderService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@Configuration
|
||||
@EnableScheduling
|
||||
@@ -18,14 +21,16 @@ public class OrderScheduler {
|
||||
// 每隔一定时间(这里设置为每分钟检查一次,可根据实际情况调整)检查订单超时情况
|
||||
@Scheduled(fixedRate = 60 * 1000)
|
||||
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,90 @@
|
||||
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);
|
||||
|
||||
/**
|
||||
* 根据携程优惠券ID查询优惠券
|
||||
*/
|
||||
Coupon getByCtripCouponId(String ctripCouponId);
|
||||
|
||||
/**
|
||||
* 更新优惠券为已核销状态
|
||||
*/
|
||||
boolean updateCouponConsumed(Long couponId, String orderNo, String consumedTime);
|
||||
}
|
||||
+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);
|
||||
}
|
||||
+11
-2
@@ -1,10 +1,19 @@
|
||||
package com.central.order.service;
|
||||
package com.central.order.service;
|
||||
|
||||
import com.central.order.model.vo.DashboardStatisticsVO;
|
||||
import com.central.common.model.PageResult;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
public interface IDashboardService {
|
||||
/**
|
||||
* 获取首页统计数据
|
||||
*/
|
||||
DashboardStatisticsVO getDashboardStatistics();
|
||||
DashboardStatisticsVO getDashboardStatistics(Map<String, Object> params);
|
||||
|
||||
/**
|
||||
* 获取首页订单列表
|
||||
*/
|
||||
PageResult<com.central.order.model.Order> getDashboardOrders(Map<String, Object> params);
|
||||
}
|
||||
|
||||
+4
-2
@@ -38,6 +38,7 @@ public interface IOrderStatisticsService extends ISuperService<OrderStatistics>
|
||||
* 按景区维度统计
|
||||
* @param startTime 开始时间
|
||||
* @param endTime 结束时间
|
||||
* @param tourismId 景区ID筛选(可选)
|
||||
* @return 统计数据列表,包含:
|
||||
* - tourismId: 景区ID
|
||||
* - tourismName: 景区名称
|
||||
@@ -48,17 +49,18 @@ public interface IOrderStatisticsService extends ISuperService<OrderStatistics>
|
||||
* - paidAmountYuan: 已支付金额(元)
|
||||
* - refundAmountYuan: 退款金额(元)
|
||||
*/
|
||||
List<Map<String, Object>> statisticsByTourism(String startTime, String endTime);
|
||||
List<Map<String, Object>> statisticsByTourism(String startTime, String endTime, String tourismId);
|
||||
|
||||
/**
|
||||
* 按设备维度统计
|
||||
* @param startTime 开始时间
|
||||
* @param endTime 结束时间
|
||||
* @param deviceSn 设备编号筛选(可选)
|
||||
* @return 统计数据列表,包含:
|
||||
* - deviceSn: 设备编号
|
||||
* - totalOrders: 订单总数
|
||||
* - totalAmountYuan: 总金额(元)
|
||||
* - 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.service.ISuperService;
|
||||
import com.central.order.model.Tourism;
|
||||
import com.central.order.model.TourismWithDistance;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Firmware file information
|
||||
* 景区信息服务接口
|
||||
*
|
||||
* @author lsl
|
||||
* @date 2024-12-19 17:52:54
|
||||
@@ -35,5 +38,43 @@ public interface ITourismService extends ISuperService<Tourism> {
|
||||
* @return
|
||||
*/
|
||||
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);
|
||||
}
|
||||
|
||||
|
||||
+53
@@ -0,0 +1,53 @@
|
||||
package com.central.order.service;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 订单租户分配服务
|
||||
* 实现10:1的分配策略:前10单分配给景区租户,第11单分配给平台租户
|
||||
*/
|
||||
public interface OrderTenantAllocationService {
|
||||
|
||||
/**
|
||||
* 根据二维码ID确定订单归属租户
|
||||
* @param qrCodeId 二维码ID
|
||||
* @param scenicTenantId 景区租户ID(来自二维码)
|
||||
* @return 租户ID
|
||||
*/
|
||||
String determineTenant(String qrCodeId, String scenicTenantId);
|
||||
|
||||
/**
|
||||
* 获取该二维码下的总订单计数
|
||||
* @param qrCodeId 二维码ID
|
||||
* @return 订单计数
|
||||
*/
|
||||
int getOrderCountByQrCode(String qrCodeId);
|
||||
|
||||
/**
|
||||
* 记录订单分配日志
|
||||
* @param qrCodeId 二维码ID
|
||||
*/
|
||||
void incrementOrderCount(String qrCodeId);
|
||||
|
||||
/**
|
||||
* 获取分配统计信息
|
||||
* @param qrCodeId 二维码ID
|
||||
* @return 统计信息
|
||||
*/
|
||||
Map<String, Object> getAllocationStatistics(String qrCodeId);
|
||||
|
||||
/**
|
||||
* 获取详细的分配诊断信息
|
||||
* @param qrCodeId 二维码ID
|
||||
* @return 诊断信息
|
||||
*/
|
||||
Map<String, Object> getDetailedDiagnostics(String qrCodeId);
|
||||
|
||||
/**
|
||||
* 验证分配逻辑
|
||||
* @param qrCodeId 二维码ID
|
||||
* @param expectedCount 期望的订单数量
|
||||
* @return 验证结果
|
||||
*/
|
||||
Map<String, Object> validateAllocationLogic(String qrCodeId, int expectedCount);
|
||||
}
|
||||
+6
-2
@@ -1,3 +1,4 @@
|
||||
/*
|
||||
package com.central.order.service;
|
||||
|
||||
import com.central.common.context.LoginUserContextHolder;
|
||||
@@ -88,7 +89,8 @@ public class PaymentService {
|
||||
request.setPayer(payer);
|
||||
|
||||
// 设置分账信息(暂时注释掉分账逻辑)
|
||||
/*
|
||||
*/
|
||||
/*
|
||||
SettleInfo settleInfo = new SettleInfo();
|
||||
if (isEnableProfit(qrCode)) {
|
||||
settleInfo.setProfitSharing(true);
|
||||
@@ -99,7 +101,8 @@ public class PaymentService {
|
||||
settleInfo.setProfitSharing(false);
|
||||
request.setSettleInfo(settleInfo);
|
||||
}
|
||||
*/
|
||||
*//*
|
||||
|
||||
|
||||
// 6. 创建对应的支付服务
|
||||
JsapiServiceExtension jsapiService;
|
||||
@@ -125,3 +128,4 @@ public class PaymentService {
|
||||
qrCode.getProfitRate() != null;
|
||||
}
|
||||
}
|
||||
*/
|
||||
|
||||
+301
@@ -0,0 +1,301 @@
|
||||
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) {
|
||||
|
||||
log.info("开始创建携程优惠券 - ctripCouponId: {}, userPhone: {}, couponName: {}, amount: {}, minAmount: {}",
|
||||
ctripCouponId, userPhone, couponName, amount, minAmount);
|
||||
|
||||
// 检查是否已存在该携程优惠券
|
||||
Coupon existingCoupon = baseMapper.selectByCtripCouponId(ctripCouponId);
|
||||
if (existingCoupon != null) {
|
||||
log.warn("携程优惠券已存在,ctripCouponId: {}, 优惠券ID: {}", ctripCouponId, existingCoupon.getId());
|
||||
return true; // 已存在也算成功
|
||||
}
|
||||
|
||||
log.info("携程优惠券不存在,开始创建新优惠券");
|
||||
|
||||
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");
|
||||
|
||||
log.info("优惠券对象创建完成,准备保存到数据库 - couponNo: {}", coupon.getCouponNo());
|
||||
|
||||
boolean saveResult = save(coupon);
|
||||
|
||||
if (saveResult) {
|
||||
log.info("携程优惠券保存成功 - 优惠券ID: {}, couponNo: {}, ctripCouponId: {}",
|
||||
coupon.getId(), coupon.getCouponNo(), ctripCouponId);
|
||||
} else {
|
||||
log.error("携程优惠券保存失败 - ctripCouponId: {}, userPhone: {}", ctripCouponId, userPhone);
|
||||
}
|
||||
|
||||
return saveResult;
|
||||
}
|
||||
|
||||
@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();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Coupon getByCtripCouponId(String ctripCouponId) {
|
||||
return baseMapper.selectByCtripCouponId(ctripCouponId);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public boolean updateCouponConsumed(Long couponId, String orderNo, String consumedTime) {
|
||||
try {
|
||||
Coupon coupon = getById(couponId);
|
||||
if (coupon == null) {
|
||||
log.error("优惠券不存在,couponId: {}", couponId);
|
||||
return false;
|
||||
}
|
||||
|
||||
// 更新优惠券状态
|
||||
coupon.setStatus(1); // 已使用
|
||||
coupon.setUsedOrderNo(orderNo);
|
||||
coupon.setUsedTime(parseDate(consumedTime));
|
||||
coupon.setUpdateTime(new Date());
|
||||
coupon.setUpdateBy("ctrip-consumed");
|
||||
|
||||
boolean result = updateById(coupon);
|
||||
if (result) {
|
||||
log.info("优惠券核销成功,couponId: {}, orderNo: {}, consumedTime: {}",
|
||||
couponId, orderNo, consumedTime);
|
||||
} else {
|
||||
log.error("优惠券核销失败,couponId: {}", couponId);
|
||||
}
|
||||
|
||||
return result;
|
||||
} catch (Exception e) {
|
||||
log.error("更新优惠券核销状态失败,couponId: {}", couponId, e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析日期字符串
|
||||
*/
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
package com.central.order.service.impl;
|
||||
|
||||
import com.central.order.service.ICtripApiService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 携程API服务实现类
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class CtripApiServiceImpl implements ICtripApiService {
|
||||
|
||||
@Override
|
||||
public boolean verifyCoupon(String ctripCouponId, String orderNo) {
|
||||
log.info("调用携程核销接口,ctripCouponId: {}, orderNo: {}", ctripCouponId, orderNo);
|
||||
|
||||
try {
|
||||
// 根据携程API文档实现核销接口调用
|
||||
// 这里需要根据实际的携程API接口进行实现
|
||||
|
||||
// 1. 构建请求参数
|
||||
Map<String, Object> requestParams = new HashMap<>();
|
||||
requestParams.put("ctripCouponId", ctripCouponId);
|
||||
requestParams.put("orderNo", orderNo);
|
||||
requestParams.put("verifyTime", new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new java.util.Date()));
|
||||
|
||||
// 2. 添加签名验证(如果需要)
|
||||
// String sign = generateSign(requestParams);
|
||||
// requestParams.put("sign", sign);
|
||||
|
||||
// 3. 调用携程核销API
|
||||
// 这里应该使用HttpClient或其他HTTP客户端调用携程的核销接口
|
||||
// 例如:
|
||||
// String url = "https://api.ctrip.com/coupon/verify";
|
||||
// String response = httpClient.post(url, requestParams);
|
||||
|
||||
// 4. 解析响应结果
|
||||
// JSONObject responseJson = JSON.parseObject(response);
|
||||
// boolean success = responseJson.getBoolean("success");
|
||||
// String message = responseJson.getString("message");
|
||||
|
||||
// 暂时模拟成功响应
|
||||
log.info("携程核销接口调用成功,ctripCouponId: {}, orderNo: {}", ctripCouponId, orderNo);
|
||||
return true;
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("携程核销接口调用失败,ctripCouponId: {}, orderNo: {}", ctripCouponId, orderNo, 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";
|
||||
}
|
||||
}
|
||||
}
|
||||
+119
-41
@@ -10,6 +10,13 @@ import org.springframework.stereotype.Service;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.ArrayList;
|
||||
import com.central.order.service.IOrderService;
|
||||
import com.central.order.model.Order;
|
||||
import com.central.common.model.PageResult;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@@ -17,23 +24,21 @@ import java.util.List;
|
||||
public class DashboardServiceImpl implements IDashboardService {
|
||||
|
||||
private final DashboardMapper dashboardMapper;
|
||||
private final IOrderService orderService;
|
||||
|
||||
@Override
|
||||
public DashboardStatisticsVO getDashboardStatistics() {
|
||||
public DashboardStatisticsVO getDashboardStatistics(Map<String, Object> params) {
|
||||
DashboardStatisticsVO statistics = new DashboardStatisticsVO();
|
||||
|
||||
try {
|
||||
// 1. 获取订单统计
|
||||
statistics.setOrderStats(getOrderStatistics());
|
||||
// 1. 获取订单统计(包含对账数据)
|
||||
statistics.setOrderStats(getOrderStatistics(params));
|
||||
|
||||
// 2. 获取收入统计
|
||||
statistics.setIncomeStats(getIncomeStatistics());
|
||||
// 2. 获取图表统计
|
||||
statistics.setChartStats(getChartStatistics(params));
|
||||
|
||||
// 5. 获取图表统计
|
||||
statistics.setChartStats(getChartStatistics());
|
||||
|
||||
// 6. 获取景区排行
|
||||
statistics.setTourismRanking(getTourismRanking());
|
||||
// 3. 获取筛选选项
|
||||
statistics.setFilterOptions(getFilterOptions(params));
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("获取仪表盘统计数据失败", e);
|
||||
@@ -42,20 +47,70 @@ public class DashboardServiceImpl implements IDashboardService {
|
||||
return statistics;
|
||||
}
|
||||
|
||||
@Override
|
||||
public PageResult<com.central.order.model.Order> getDashboardOrders(Map<String, Object> params) {
|
||||
try {
|
||||
// 获取分页参数
|
||||
Integer page = (Integer) params.getOrDefault("page", 1);
|
||||
Integer limit = (Integer) params.getOrDefault("limit", 10);
|
||||
|
||||
// 构建查询条件
|
||||
LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<Order>()
|
||||
.orderByDesc(Order::getCreateTime);
|
||||
|
||||
// 如果有时间筛选条件,添加时间范围
|
||||
if (params.get("startTime") != null && !params.get("startTime").toString().isEmpty()) {
|
||||
wrapper.ge(Order::getCreateTime, params.get("startTime"));
|
||||
}
|
||||
if (params.get("endTime") != null && !params.get("endTime").toString().isEmpty()) {
|
||||
wrapper.le(Order::getCreateTime, params.get("endTime"));
|
||||
}
|
||||
|
||||
// 添加其他筛选条件
|
||||
if (params.get("tourismId") != null) {
|
||||
wrapper.eq(Order::getTourismId, params.get("tourismId"));
|
||||
}
|
||||
if (params.get("qrcodeId") != null && !params.get("qrcodeId").toString().isEmpty()) {
|
||||
wrapper.eq(Order::getCodeId, params.get("qrcodeId"));
|
||||
}
|
||||
if (params.get("deviceSn") != null && !params.get("deviceSn").toString().isEmpty()) {
|
||||
wrapper.eq(Order::getDeviceSn, params.get("deviceSn"));
|
||||
}
|
||||
|
||||
// 执行分页查询
|
||||
Page<Order> pageParam = new Page<>(page, limit);
|
||||
Page<Order> resultPage = orderService.page(pageParam, wrapper);
|
||||
|
||||
// 转换为PageResult
|
||||
return PageResult.<Order>builder()
|
||||
.data(resultPage.getRecords())
|
||||
.resp_code(0)
|
||||
.count(resultPage.getTotal())
|
||||
.build();
|
||||
} catch (Exception e) {
|
||||
log.error("获取首页订单列表失败", e);
|
||||
return PageResult.<Order>builder()
|
||||
.data(new ArrayList<>())
|
||||
.resp_code(0)
|
||||
.count(0L)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取订单统计
|
||||
* 获取订单统计(包含对账数据)
|
||||
*/
|
||||
private OrderStatistics getOrderStatistics() {
|
||||
private OrderStatistics getOrderStatistics(Map<String, Object> params) {
|
||||
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) {
|
||||
BigDecimal growth = new BigDecimal(stats.getTodayOrders() - yesterdayOrders)
|
||||
.divide(new BigDecimal(yesterdayOrders), 4, RoundingMode.HALF_UP)
|
||||
@@ -64,37 +119,43 @@ public class DashboardServiceImpl implements IDashboardService {
|
||||
}
|
||||
|
||||
// 计算完成率
|
||||
Long completedOrders = dashboardMapper.getCompletedOrders();
|
||||
Long completedOrders = dashboardMapper.getCompletedOrders(params);
|
||||
if (stats.getTotalOrders() > 0) {
|
||||
BigDecimal completionRate = new BigDecimal(completedOrders)
|
||||
.divide(new BigDecimal(stats.getTotalOrders()), 4, RoundingMode.HALF_UP)
|
||||
.multiply(new BigDecimal(100));
|
||||
stats.setCompletionRate(completionRate);
|
||||
}
|
||||
// 设置总完成订单数
|
||||
stats.setCompletedOrders(completedOrders);
|
||||
|
||||
return stats;
|
||||
}
|
||||
// 获取总收款订单数量
|
||||
Long totalPaidOrders = dashboardMapper.getTotalPaidOrders(params);
|
||||
stats.setTotalPaidOrders(totalPaidOrders);
|
||||
|
||||
/**
|
||||
* 获取收入统计
|
||||
*/
|
||||
private IncomeStatistics getIncomeStatistics() {
|
||||
IncomeStatistics stats = new IncomeStatistics();
|
||||
// 获取今日收款订单数量
|
||||
Long todayPaidOrders = dashboardMapper.getTodayPaidOrders(params);
|
||||
stats.setTodayPaidOrders(todayPaidOrders);
|
||||
|
||||
// 获取总收入
|
||||
stats.setTotalAmount(dashboardMapper.getTotalIncome());
|
||||
// 获取退款订单数量
|
||||
Long refundedOrders = dashboardMapper.getRefundedOrders(params);
|
||||
stats.setRefundedOrders(refundedOrders);
|
||||
|
||||
// 获取今日收入
|
||||
stats.setTodayAmount(dashboardMapper.getTodayIncome());
|
||||
// 获取今日退款订单数量
|
||||
Long todayRefundedOrders = dashboardMapper.getTodayRefundedOrders(params);
|
||||
stats.setTodayRefundedOrders(todayRefundedOrders);
|
||||
|
||||
// 计算目标完成率(假设每日目标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);
|
||||
}
|
||||
// 获取对账相关数据 - 使用 orders 表的数据
|
||||
Long totalAmount = dashboardMapper.getTotalAmount(params);
|
||||
Long refundAmount = dashboardMapper.getRefundAmount(params);
|
||||
|
||||
// 设置基础数据
|
||||
stats.setTotalAmount(totalAmount);
|
||||
stats.setRefundAmount(refundAmount);
|
||||
|
||||
// 计算净收入 = 总金额 - 退款金额
|
||||
Long netIncome = (totalAmount != null ? totalAmount : 0) - (refundAmount != null ? refundAmount : 0);
|
||||
stats.setNetIncome(netIncome);
|
||||
|
||||
return stats;
|
||||
}
|
||||
@@ -102,22 +163,39 @@ public class DashboardServiceImpl implements IDashboardService {
|
||||
/**
|
||||
* 获取图表统计
|
||||
*/
|
||||
private ChartStatistics getChartStatistics() {
|
||||
private ChartStatistics getChartStatistics(Map<String, Object> params) {
|
||||
ChartStatistics stats = new ChartStatistics();
|
||||
|
||||
// 获取订单趋势(最近7天)
|
||||
stats.setOrderTrend(dashboardMapper.getOrderTrend());
|
||||
stats.setOrderTrend(dashboardMapper.getOrderTrend(params));
|
||||
|
||||
// 获取订单状态分布
|
||||
stats.setOrderDistribution(dashboardMapper.getOrderDistribution(params));
|
||||
|
||||
// 获取收入构成
|
||||
stats.setIncomeData(dashboardMapper.getIncomeData());
|
||||
stats.setIncomeBreakdown(dashboardMapper.getIncomeBreakdown(params));
|
||||
|
||||
// 获取二维码订单数量
|
||||
stats.setQrcodeOrderCount(dashboardMapper.getQrcodeOrderCount(params));
|
||||
|
||||
return stats;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取景区排行
|
||||
* 获取筛选选项
|
||||
*/
|
||||
private List<TourismRankingVO> getTourismRanking() {
|
||||
return dashboardMapper.getTourismRanking();
|
||||
private FilterOptions getFilterOptions(Map<String, Object> params) {
|
||||
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<>();
|
||||
List<OrderFile> videoFiles = taskData.getVideoFiles();
|
||||
//@TODO 后期需要通过模板参数进行动态设置clips参数
|
||||
|
||||
clips.put("1", fileCenterService.getViewUrlByPath(videoFiles.get(4).getFilePath()));
|
||||
clips.put("2", fileCenterService.getViewUrlByPath(videoFiles.get(5).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("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);
|
||||
} catch (Exception e) {
|
||||
throw new BusinessException("构建剪辑参数失败: " + e.getMessage());
|
||||
|
||||
+57
-6
@@ -1,19 +1,24 @@
|
||||
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.extension.plugins.pagination.Page;
|
||||
import com.central.common.context.TenantContextHolder;
|
||||
import com.central.common.lock.DistributedLock;
|
||||
import com.central.common.model.PageResult;
|
||||
import com.central.common.service.impl.SuperServiceImpl;
|
||||
import com.central.order.enums.OrderStatus;
|
||||
import com.central.order.event.OrderStatusChangeEvent;
|
||||
import com.central.order.feign.FileCenterService;
|
||||
import com.central.order.feign.UserCenterService;
|
||||
import com.central.order.mapper.OrderFileMapper;
|
||||
import com.central.order.mapper.OrderMapper;
|
||||
import com.central.order.mapper.TourismFileMapper;
|
||||
import com.central.order.mapper.TourismMapper;
|
||||
import com.central.order.model.Order;
|
||||
import com.central.order.model.OrderFile;
|
||||
import com.central.order.model.OrderRanking;
|
||||
import com.central.order.model.TourismFile;
|
||||
import com.central.order.service.IOrderService;
|
||||
import com.central.order.util.DateUtils;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -56,6 +61,10 @@ public class OrderServiceImpl extends SuperServiceImpl<OrderMapper, Order> imple
|
||||
|
||||
@Autowired
|
||||
private TourismMapper tourismMapper;
|
||||
|
||||
@Autowired
|
||||
private TourismFileMapper tourismFileMapper;
|
||||
|
||||
@Autowired
|
||||
private OrderFileMapper orderFileMapper;
|
||||
|
||||
@@ -65,6 +74,9 @@ public class OrderServiceImpl extends SuperServiceImpl<OrderMapper, Order> imple
|
||||
@Autowired
|
||||
private UserCenterService userCenterService;
|
||||
|
||||
@Autowired
|
||||
private FileCenterService fileCenterService;
|
||||
|
||||
/**
|
||||
* 列表
|
||||
* @param params
|
||||
@@ -76,6 +88,7 @@ public class OrderServiceImpl extends SuperServiceImpl<OrderMapper, Order> imple
|
||||
List<Order> list = baseMapper.findList(page, params);
|
||||
for (Order order : list){
|
||||
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();
|
||||
}
|
||||
@@ -110,14 +123,33 @@ public class OrderServiceImpl extends SuperServiceImpl<OrderMapper, Order> imple
|
||||
// 检查并处理订单超时逻辑,5分钟超时后自动取消
|
||||
@Override
|
||||
public void checkAndHandleOrderTimeout() {
|
||||
log.debug("开始检查订单超时情况");
|
||||
|
||||
List<Order> orders = baseMapper.getOrdersByStatus(OrderStatus.UNPAID.getId());
|
||||
log.debug("查询到 {} 个待支付订单", orders.size());
|
||||
|
||||
long currentTime = new Date().getTime();
|
||||
int timeoutCount = 0;
|
||||
|
||||
for (Order order : orders) {
|
||||
long elapsedTime = currentTime - order.getCreateTime().getTime();
|
||||
if (TimeUnit.MILLISECONDS.toMinutes(elapsedTime) >= 5) {
|
||||
long elapsedMinutes = TimeUnit.MILLISECONDS.toMinutes(elapsedTime);
|
||||
|
||||
log.debug("订单检查: 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());
|
||||
timeoutCount++;
|
||||
}
|
||||
}
|
||||
|
||||
log.debug("订单超时检查完成: 总订单数={}, 超时取消数={}", orders.size(), timeoutCount);
|
||||
}
|
||||
|
||||
// 获取所有处于排队状态的订单,用于后续按顺序处理
|
||||
@@ -159,12 +191,18 @@ public class OrderServiceImpl extends SuperServiceImpl<OrderMapper, Order> imple
|
||||
@Override
|
||||
public boolean updateOrder(Order order) {
|
||||
try {
|
||||
|
||||
log.info("更新订单状态时租户ID: tenantId={}", TenantContextHolder.getTenant());
|
||||
|
||||
// 获取原订单信息
|
||||
Order oldOrder = getById(order.getId());
|
||||
boolean result = super.saveOrUpdateIdempotency(order, lock,
|
||||
ORDER_LOCK + order.getOrderNo(),
|
||||
new QueryWrapper<Order>().eq("order_no", order.getOrderNo()),
|
||||
"订单已存在");
|
||||
if (oldOrder == null) {
|
||||
log.error("订单不存在,无法更新: orderId={}", order.getId());
|
||||
return false;
|
||||
}
|
||||
|
||||
// 使用updateById进行更新,避免INSERT操作
|
||||
boolean result = updateById(order);
|
||||
|
||||
// 如果更新成功且状态发生变化,发布事件
|
||||
if (result && !order.getOrderStatus().equals(oldOrder.getOrderStatus())) {
|
||||
@@ -189,7 +227,7 @@ public class OrderServiceImpl extends SuperServiceImpl<OrderMapper, Order> imple
|
||||
}
|
||||
return result;
|
||||
} catch (Exception e) {
|
||||
log.error("更新订单失败", e);
|
||||
log.error("更新订单失败: orderId={}, orderNo={}", order.getId(), order.getOrderNo(), e);
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
@@ -224,6 +262,19 @@ public class OrderServiceImpl extends SuperServiceImpl<OrderMapper, Order> imple
|
||||
for (Order order : list) {
|
||||
order.setTourismName(tourismMapper.getTourismById(order.getTourismId()).getTourismName());
|
||||
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();
|
||||
|
||||
+22
-10
@@ -202,15 +202,23 @@ public class OrderStatisticsServiceImpl extends SuperServiceImpl<OrderStatistics
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Map<String, Object>> statisticsByTourism(String startTime, String endTime) {
|
||||
public List<Map<String, Object>> statisticsByTourism(String startTime, String endTime, String tourismId) {
|
||||
try {
|
||||
OrderStatisticsQuery query = OrderStatisticsQuery.builder()
|
||||
OrderStatisticsQuery.OrderStatisticsQueryBuilder queryBuilder = OrderStatisticsQuery.builder()
|
||||
.startTime(startTime)
|
||||
.endTime(endTime)
|
||||
.groupField("o.tourism_id")
|
||||
.build();
|
||||
.groupField("o.tourism_id");
|
||||
|
||||
// 如果指定了景区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(query);
|
||||
List<Map<String, Object>> statistics = baseMapper.getOrderStatisticsByGroup(queryBuilder.build());
|
||||
return processStatisticsResult(statistics);
|
||||
} catch (Exception e) {
|
||||
log.error("按景区维度统计失败", e);
|
||||
@@ -219,15 +227,19 @@ public class OrderStatisticsServiceImpl extends SuperServiceImpl<OrderStatistics
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Map<String, Object>> statisticsByDevice(String startTime, String endTime) {
|
||||
public List<Map<String, Object>> statisticsByDevice(String startTime, String endTime, String deviceSn) {
|
||||
try {
|
||||
OrderStatisticsQuery query = OrderStatisticsQuery.builder()
|
||||
OrderStatisticsQuery.OrderStatisticsQueryBuilder queryBuilder = OrderStatisticsQuery.builder()
|
||||
.startTime(startTime)
|
||||
.endTime(endTime)
|
||||
.groupField("o.device_sn")
|
||||
.build();
|
||||
.groupField("o.device_sn");
|
||||
|
||||
// 如果指定了设备编号,则添加筛选条件
|
||||
if (deviceSn != null && !deviceSn.trim().isEmpty()) {
|
||||
queryBuilder.deviceSn(deviceSn);
|
||||
}
|
||||
|
||||
List<Map<String, Object>> statistics = baseMapper.getOrderStatisticsByGroup(query);
|
||||
List<Map<String, Object>> statistics = baseMapper.getOrderStatisticsByGroup(queryBuilder.build());
|
||||
return processStatisticsResult(statistics);
|
||||
} catch (Exception e) {
|
||||
log.error("按设备维度统计失败", e);
|
||||
|
||||
+307
@@ -0,0 +1,307 @@
|
||||
package com.central.order.service.impl;
|
||||
|
||||
import com.central.order.config.TenantAllocationConfig;
|
||||
import com.central.order.mapper.OrderTenantAllocationMapper;
|
||||
import com.central.order.model.QrCode;
|
||||
import com.central.order.service.IQrCodeService;
|
||||
import com.central.order.service.OrderTenantAllocationService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 订单租户分配服务实现类
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
public class OrderTenantAllocationServiceImpl implements OrderTenantAllocationService {
|
||||
|
||||
@Autowired
|
||||
private TenantAllocationConfig config;
|
||||
|
||||
@Autowired
|
||||
private OrderTenantAllocationMapper orderTenantAllocationMapper;
|
||||
|
||||
@Autowired
|
||||
private IQrCodeService qrCodeService;
|
||||
|
||||
// 分配比例:10单景区 + 1单平台
|
||||
private int allocationRatio = 10;
|
||||
private int cycleSize = 11; // allocationRatio + 1
|
||||
|
||||
@Override
|
||||
public String determineTenant(String qrCodeId, String scenicTenantId) {
|
||||
// 检查是否启用租户分配功能
|
||||
if (!config.isEnabled()) {
|
||||
log.debug("租户分配功能未启用,使用景区租户ID: {}", scenicTenantId);
|
||||
return scenicTenantId;
|
||||
}
|
||||
|
||||
// 检查是否强制使用平台租户(用于测试)
|
||||
if (config.isForcePlatformTenant()) {
|
||||
log.info("强制使用平台租户 - qrCodeId: {}", qrCodeId);
|
||||
return config.getPlatformTenantId();
|
||||
}
|
||||
|
||||
// 更新分配比例
|
||||
allocationRatio = config.getAllocationRatio();
|
||||
cycleSize = allocationRatio + 1;
|
||||
|
||||
int orderCount = getOrderCountByQrCode(qrCodeId);
|
||||
int remainder = orderCount % cycleSize; // 当前周期内的位置
|
||||
|
||||
if (remainder == allocationRatio) { // 第11单(索引10)
|
||||
String platformTenantId = getPlatformTenantId(qrCodeId);
|
||||
log.info("订单分配给平台租户 - qrCodeId: {}, orderCount: {}, tenantId: {}",
|
||||
qrCodeId, orderCount, platformTenantId);
|
||||
return platformTenantId;
|
||||
} else {
|
||||
log.info("订单分配给景区租户 - qrCodeId: {}, orderCount: {}, tenantId: {}",
|
||||
qrCodeId, orderCount, scenicTenantId);
|
||||
return scenicTenantId;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public int getOrderCountByQrCode(String qrCodeId) {
|
||||
try {
|
||||
int count = orderTenantAllocationMapper.getOrderCountByQrCode(qrCodeId);
|
||||
log.debug("获取二维码订单计数 - qrCodeId: {}, count: {}", qrCodeId, count);
|
||||
return count;
|
||||
} catch (Exception e) {
|
||||
log.error("查询二维码订单计数失败 - qrCodeId: {}", qrCodeId, e);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void incrementOrderCount(String qrCodeId) {
|
||||
// 订单计数通过实际创建订单时自动增加
|
||||
// 实际计数通过查询orders表获取,这里主要用于日志记录
|
||||
log.info("订单计数已更新 - qrCodeId: {}, 当前订单总数: {}", qrCodeId, getOrderCountByQrCode(qrCodeId));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> getAllocationStatistics(String qrCodeId) {
|
||||
Map<String, Object> statistics = new HashMap<>();
|
||||
|
||||
try {
|
||||
// 更新分配比例
|
||||
allocationRatio = config.getAllocationRatio();
|
||||
cycleSize = allocationRatio + 1;
|
||||
|
||||
// 获取景区租户ID - 需要查询二维码表
|
||||
String scenicTenantId = getScenicTenantIdFromQrCode(qrCodeId);
|
||||
String platformTenantId = config.getPlatformTenantId();
|
||||
|
||||
// 从数据库查询统计信息
|
||||
Map<String, Object> dbStatistics = orderTenantAllocationMapper.getOrderStatisticsByQrCode(
|
||||
qrCodeId, scenicTenantId, platformTenantId);
|
||||
|
||||
// 获取最近的订单信息
|
||||
java.util.List<java.util.Map<String, Object>> recentOrders =
|
||||
orderTenantAllocationMapper.getRecentOrdersByQrCode(qrCodeId, 10);
|
||||
|
||||
// 组装统计信息
|
||||
statistics.put("qrCodeId", qrCodeId);
|
||||
statistics.put("allocationRatio", allocationRatio);
|
||||
statistics.put("cycleSize", cycleSize);
|
||||
statistics.put("enabled", config.isEnabled());
|
||||
statistics.put("platformTenantId", platformTenantId);
|
||||
statistics.put("scenicTenantId", scenicTenantId);
|
||||
|
||||
// 数据库统计信息
|
||||
if (dbStatistics != null) {
|
||||
statistics.put("totalOrders", dbStatistics.get("totalOrders"));
|
||||
statistics.put("scenicOrders", dbStatistics.get("scenicOrders"));
|
||||
statistics.put("platformOrders", dbStatistics.get("platformOrders"));
|
||||
|
||||
// 计算百分比
|
||||
Long totalOrders = (Long) dbStatistics.get("totalOrders");
|
||||
Long scenicOrders = (Long) dbStatistics.get("scenicOrders");
|
||||
Long platformOrders = (Long) dbStatistics.get("platformOrders");
|
||||
|
||||
if (totalOrders != null && totalOrders > 0) {
|
||||
statistics.put("scenicPercentage", (double) scenicOrders / totalOrders * 100);
|
||||
statistics.put("platformPercentage", (double) platformOrders / totalOrders * 100);
|
||||
} else {
|
||||
statistics.put("scenicPercentage", 0.0);
|
||||
statistics.put("platformPercentage", 0.0);
|
||||
}
|
||||
}
|
||||
|
||||
// 最近订单信息
|
||||
statistics.put("recentOrders", recentOrders);
|
||||
|
||||
log.info("获取分配统计信息成功 - qrCodeId: {}, 总订单: {}, 景区订单: {}, 平台订单: {}",
|
||||
qrCodeId, statistics.get("totalOrders"), statistics.get("scenicOrders"), statistics.get("platformOrders"));
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("获取分配统计信息失败 - qrCodeId: {}", qrCodeId, e);
|
||||
statistics.put("error", "查询失败:" + e.getMessage());
|
||||
}
|
||||
|
||||
return statistics;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> getDetailedDiagnostics(String qrCodeId) {
|
||||
Map<String, Object> diagnostics = new HashMap<>();
|
||||
|
||||
try {
|
||||
// 获取景区租户ID - 从二维码表查询
|
||||
String scenicTenantId = getScenicTenantIdFromQrCode(qrCodeId);
|
||||
String platformTenantId = config.getPlatformTenantId();
|
||||
|
||||
// 查询各种统计数据
|
||||
int totalOrders = orderTenantAllocationMapper.getOrderCountByQrCode(qrCodeId);
|
||||
int scenicOrders = orderTenantAllocationMapper.getScenicOrderCount(qrCodeId, scenicTenantId);
|
||||
int platformOrders = orderTenantAllocationMapper.getPlatformOrderCount(qrCodeId, platformTenantId);
|
||||
|
||||
// 获取最近的订单详情
|
||||
java.util.List<java.util.Map<String, Object>> recentOrders =
|
||||
orderTenantAllocationMapper.getRecentOrdersByQrCode(qrCodeId, 20);
|
||||
|
||||
// 计算理论分配
|
||||
allocationRatio = config.getAllocationRatio();
|
||||
cycleSize = allocationRatio + 1;
|
||||
int expectedScenicOrders = 0;
|
||||
int expectedPlatformOrders = 0;
|
||||
|
||||
for (int i = 0; i < totalOrders; i++) {
|
||||
int remainder = i % cycleSize;
|
||||
if (remainder == allocationRatio) {
|
||||
expectedPlatformOrders++;
|
||||
} else {
|
||||
expectedScenicOrders++;
|
||||
}
|
||||
}
|
||||
|
||||
// 组装诊断信息
|
||||
diagnostics.put("qrCodeId", qrCodeId);
|
||||
diagnostics.put("scenicTenantId", scenicTenantId);
|
||||
diagnostics.put("platformTenantId", platformTenantId);
|
||||
diagnostics.put("allocationRatio", allocationRatio);
|
||||
diagnostics.put("cycleSize", cycleSize);
|
||||
diagnostics.put("enabled", config.isEnabled());
|
||||
|
||||
// 实际统计
|
||||
diagnostics.put("actualTotalOrders", totalOrders);
|
||||
diagnostics.put("actualScenicOrders", scenicOrders);
|
||||
diagnostics.put("actualPlatformOrders", platformOrders);
|
||||
|
||||
// 理论分配
|
||||
diagnostics.put("expectedScenicOrders", expectedScenicOrders);
|
||||
diagnostics.put("expectedPlatformOrders", expectedPlatformOrders);
|
||||
|
||||
// 差异分析
|
||||
diagnostics.put("scenicOrderDiff", scenicOrders - expectedScenicOrders);
|
||||
diagnostics.put("platformOrderDiff", platformOrders - expectedPlatformOrders);
|
||||
|
||||
// 百分比
|
||||
if (totalOrders > 0) {
|
||||
diagnostics.put("actualScenicPercentage", (double) scenicOrders / totalOrders * 100);
|
||||
diagnostics.put("actualPlatformPercentage", (double) platformOrders / totalOrders * 100);
|
||||
diagnostics.put("expectedScenicPercentage", (double) expectedScenicOrders / totalOrders * 100);
|
||||
diagnostics.put("expectedPlatformPercentage", (double) expectedPlatformOrders / totalOrders * 100);
|
||||
}
|
||||
|
||||
// 最近订单详情
|
||||
diagnostics.put("recentOrders", recentOrders);
|
||||
|
||||
// 分配状态
|
||||
int currentCount = getOrderCountByQrCode(qrCodeId);
|
||||
int remainder = currentCount % cycleSize;
|
||||
diagnostics.put("currentOrderCount", currentCount);
|
||||
diagnostics.put("currentRemainder", remainder);
|
||||
diagnostics.put("nextOrderShouldBePlatform", remainder == allocationRatio);
|
||||
|
||||
log.info("获取详细诊断信息成功 - qrCodeId: {}, 实际: 景区{}单/平台{}单, 理论: 景区{}单/平台{}单",
|
||||
qrCodeId, scenicOrders, platformOrders, expectedScenicOrders, expectedPlatformOrders);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("获取详细诊断信息失败 - qrCodeId: {}", qrCodeId, e);
|
||||
diagnostics.put("error", "查询失败:" + e.getMessage());
|
||||
}
|
||||
|
||||
return diagnostics;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Object> validateAllocationLogic(String qrCodeId, int expectedCount) {
|
||||
Map<String, Object> result = new HashMap<>();
|
||||
|
||||
// 更新分配比例
|
||||
allocationRatio = config.getAllocationRatio();
|
||||
cycleSize = allocationRatio + 1;
|
||||
|
||||
int scenicCount = 0;
|
||||
int platformCount = 0;
|
||||
|
||||
// 模拟验证分配逻辑
|
||||
for (int i = 0; i < expectedCount; i++) {
|
||||
int remainder = i % cycleSize;
|
||||
if (remainder == allocationRatio) {
|
||||
platformCount++;
|
||||
} else {
|
||||
scenicCount++;
|
||||
}
|
||||
}
|
||||
|
||||
result.put("expectedCount", expectedCount);
|
||||
result.put("scenicCount", scenicCount);
|
||||
result.put("platformCount", platformCount);
|
||||
result.put("scenicPercentage", (double) scenicCount / expectedCount * 100);
|
||||
result.put("platformPercentage", (double) platformCount / expectedCount * 100);
|
||||
result.put("allocationRatio", allocationRatio + ":1");
|
||||
result.put("enabled", config.isEnabled());
|
||||
result.put("platformTenantId", config.getPlatformTenantId());
|
||||
|
||||
log.info("分配逻辑验证完成 - 二维码: {}, 总订单: {}, 景区订单: {}, 平台订单: {}, 景区占比: {}%, 平台占比: {}%",
|
||||
qrCodeId, expectedCount, scenicCount, platformCount,
|
||||
result.get("scenicPercentage"), result.get("platformPercentage"));
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取景区租户ID
|
||||
*/
|
||||
private String getScenicTenantId(String qrCodeId) {
|
||||
// 这里应该查询二维码表获取租户ID
|
||||
// 但是由于在订单创建时已经获取了二维码信息,所以直接传入景区租户ID
|
||||
// 这个方法主要用于测试和诊断,实际使用时应该传入正确的景区租户ID
|
||||
log.warn("getScenicTenantId方法被调用,但应该直接使用传入的scenicTenantId参数");
|
||||
return qrCodeId;
|
||||
}
|
||||
|
||||
/**
|
||||
* 从二维码表获取景区租户ID
|
||||
*/
|
||||
private String getScenicTenantIdFromQrCode(String qrCodeId) {
|
||||
try {
|
||||
QrCode qrCode = qrCodeService.getByCodeId(qrCodeId);
|
||||
if (qrCode != null && qrCode.getTenantId() != null) {
|
||||
log.debug("从二维码表获取景区租户ID - qrCodeId: {}, tenantId: {}", qrCodeId, qrCode.getTenantId());
|
||||
return qrCode.getTenantId();
|
||||
} else {
|
||||
log.warn("二维码不存在或租户ID为空 - qrCodeId: {}", qrCodeId);
|
||||
return qrCodeId; // 降级处理
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("查询二维码租户ID失败 - qrCodeId: {}", qrCodeId, e);
|
||||
return qrCodeId; // 降级处理
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取平台租户ID
|
||||
*/
|
||||
private String getPlatformTenantId(String qrCodeId) {
|
||||
// 使用配置中的平台租户ID
|
||||
return config.getPlatformTenantId();
|
||||
}
|
||||
}
|
||||
+126
-1
@@ -6,16 +6,22 @@ import com.central.common.model.Result;
|
||||
import com.central.common.service.impl.SuperServiceImpl;
|
||||
import com.central.order.mapper.TourismMapper;
|
||||
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.ITourismFileService;
|
||||
import com.central.order.feign.FileCenterService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.apache.commons.collections4.MapUtils;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Order information
|
||||
* 景区信息服务实现类
|
||||
*
|
||||
* @author lsl
|
||||
* @date 2024-12-19 17:52:54
|
||||
@@ -24,6 +30,12 @@ import java.util.Map;
|
||||
@Service
|
||||
public class TourismServiceImpl extends SuperServiceImpl<TourismMapper, Tourism> implements ITourismService {
|
||||
|
||||
@Autowired
|
||||
private ITourismFileService tourismFileService;
|
||||
|
||||
@Autowired
|
||||
private FileCenterService fileCenterService;
|
||||
|
||||
/**
|
||||
* 列表
|
||||
* @param params
|
||||
@@ -47,4 +59,117 @@ public class TourismServiceImpl extends SuperServiceImpl<TourismMapper, Tourism>
|
||||
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 = 1000.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.setOrderNo(orderNo);
|
||||
orderFile.setFileType("video/mp4");
|
||||
orderFile.setFileTag("ai_video");
|
||||
orderFile.setFilePath(extractFilePath(outputUrl));
|
||||
orderFile.setUserId(order.getUserId());
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,317 @@
|
||||
package com.central.order.util;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.spec.IvParameterSpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
import java.util.Map;
|
||||
import java.util.TreeMap;
|
||||
|
||||
/**
|
||||
* 携程API解密工具类
|
||||
* 实现AES-128-CBC解密和MD5签名验证
|
||||
*
|
||||
* @author system
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class CtripDecryptUtil {
|
||||
|
||||
@Value("${ctrip.aes.key:}")
|
||||
private String aesKey;
|
||||
|
||||
@Value("${ctrip.sign.key:}")
|
||||
private String signKey;
|
||||
|
||||
@Value("${ctrip.aes.iv:}")
|
||||
private String aesIv;
|
||||
|
||||
/**
|
||||
* AES-128-CBC解密(携程标准)
|
||||
*
|
||||
* @param encryptedData 携程自定义编码的加密数据
|
||||
* @return 解密后的原始数据
|
||||
*/
|
||||
public String decryptAES(String encryptedData) {
|
||||
try {
|
||||
if (encryptedData == null || encryptedData.isEmpty()) {
|
||||
log.warn("加密数据为空");
|
||||
return null;
|
||||
}
|
||||
|
||||
log.debug("开始解密携程数据,数据长度: {}", encryptedData.length());
|
||||
|
||||
// 使用携程自定义解码方法
|
||||
byte[] encryptedBytes = decodeBytes(encryptedData);
|
||||
log.debug("自定义解码成功,数据长度: {}", encryptedBytes.length);
|
||||
|
||||
// 检查数据长度
|
||||
if (encryptedBytes.length < 16) {
|
||||
log.error("加密数据长度不足,无法提取IV");
|
||||
return null;
|
||||
}
|
||||
|
||||
// 提取IV(前16字节)
|
||||
byte[] iv = Arrays.copyOfRange(encryptedBytes, 0, 16);
|
||||
byte[] cipherData = Arrays.copyOfRange(encryptedBytes, 16, encryptedBytes.length);
|
||||
|
||||
log.debug("提取IV成功,IV长度: {}, 密文长度: {}", iv.length, cipherData.length);
|
||||
|
||||
// 使用UTF-8字节作为密钥和IV(携程标准)
|
||||
byte[] keyBytes = aesKey.getBytes(StandardCharsets.UTF_8);
|
||||
byte[] ivBytes = aesIv.getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
log.debug("密钥长度: {}, IV长度: {}", keyBytes.length, ivBytes.length);
|
||||
|
||||
// 创建AES密钥
|
||||
SecretKeySpec secretKey = new SecretKeySpec(keyBytes, "AES");
|
||||
IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
|
||||
|
||||
// 创建解密器
|
||||
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
|
||||
cipher.init(Cipher.DECRYPT_MODE, secretKey, ivSpec);
|
||||
|
||||
// 解密
|
||||
byte[] decryptedBytes = cipher.doFinal(cipherData);
|
||||
String decryptedData = new String(decryptedBytes, StandardCharsets.UTF_8);
|
||||
|
||||
log.info("AES解密成功,解密后数据长度: {}", decryptedData.length());
|
||||
|
||||
// 清理解密后的数据,移除可能的头部乱码
|
||||
String cleanedData = cleanDecryptedData(decryptedData);
|
||||
log.debug("清理后数据长度: {}", cleanedData.length());
|
||||
|
||||
return cleanedData;
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("AES解密失败: {}", e.getMessage(), e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理解密后的数据,移除头部乱码
|
||||
*/
|
||||
private String cleanDecryptedData(String decryptedData) {
|
||||
if (decryptedData == null || decryptedData.isEmpty()) {
|
||||
return decryptedData;
|
||||
}
|
||||
|
||||
log.info("原始解密数据前100个字符: {}",
|
||||
decryptedData.length() > 100 ? decryptedData.substring(0, 100) : decryptedData);
|
||||
log.info("原始解密数据后100个字符: {}",
|
||||
decryptedData.length() > 100 ? decryptedData.substring(decryptedData.length() - 100) : decryptedData);
|
||||
|
||||
// 查找第一个 '{' 字符(JSON对象开始)
|
||||
int startIndex = decryptedData.indexOf('{');
|
||||
if (startIndex == -1) {
|
||||
// 如果没有找到 '{',查找第一个 '"' 字符
|
||||
startIndex = decryptedData.indexOf('"');
|
||||
}
|
||||
|
||||
if (startIndex == -1) {
|
||||
// 如果都没有找到,查找第一个字母或数字
|
||||
for (int i = 0; i < decryptedData.length(); i++) {
|
||||
char c = decryptedData.charAt(i);
|
||||
if (Character.isLetterOrDigit(c)) {
|
||||
startIndex = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (startIndex > 0) {
|
||||
String cleanedData = decryptedData.substring(startIndex);
|
||||
log.info("移除头部乱码,从位置 {} 开始,清理后数据前100个字符: {}",
|
||||
startIndex, cleanedData.length() > 100 ? cleanedData.substring(0, 100) : cleanedData);
|
||||
return cleanedData;
|
||||
}
|
||||
|
||||
log.info("无需清理,数据前100个字符: {}",
|
||||
decryptedData.length() > 100 ? decryptedData.substring(0, 100) : decryptedData);
|
||||
return decryptedData;
|
||||
}
|
||||
|
||||
/**
|
||||
* 携程自定义解码方法(转字节数组)
|
||||
*
|
||||
* @param str 编码字符串
|
||||
* @return 字节数组
|
||||
*/
|
||||
private byte[] decodeBytes(String str) {
|
||||
byte[] bytes = new byte[str.length() / 2];
|
||||
for (int i = 0; i < str.length(); i += 2) {
|
||||
char c = str.charAt(i);
|
||||
bytes[i / 2] = (byte) ((c - 'a') << 4);
|
||||
c = str.charAt(i + 1);
|
||||
bytes[i / 2] += (c - 'a');
|
||||
}
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/**
|
||||
* 携程自定义编码方法(转16进制)
|
||||
*
|
||||
* @param bytes 字节数组
|
||||
* @return 编码字符串
|
||||
*/
|
||||
private String encodeBytes(byte[] bytes) {
|
||||
StringBuffer strBuf = new StringBuffer();
|
||||
for (int i = 0; i < bytes.length; i++) {
|
||||
strBuf.append((char) (((bytes[i] >> 4) & 0xF) + ((int) 'a')));
|
||||
strBuf.append((char) (((bytes[i]) & 0xF) + ((int) 'a')));
|
||||
}
|
||||
return strBuf.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证MD5签名(携程标准)
|
||||
*
|
||||
* @param accountId 账号ID
|
||||
* @param serviceName 服务名称
|
||||
* @param requestTime 请求时间
|
||||
* @param body 请求体
|
||||
* @param version 版本
|
||||
* @param sign 签名
|
||||
* @return 验证结果
|
||||
*/
|
||||
public boolean verifySign(String accountId, String serviceName, String requestTime, String body, String version, String sign) {
|
||||
try {
|
||||
// 按携程标准拼接参数:accountId+serviceName+requestTime+body+version+signkey
|
||||
String signContent = accountId + serviceName + requestTime + body + version + signKey;
|
||||
log.debug("签名内容: {}", signContent);
|
||||
|
||||
// 计算MD5并转小写
|
||||
MessageDigest md = MessageDigest.getInstance("MD5");
|
||||
byte[] md5Bytes = md.digest(signContent.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
// 转换为小写十六进制
|
||||
StringBuilder calculatedSign = new StringBuilder();
|
||||
for (byte b : md5Bytes) {
|
||||
calculatedSign.append(String.format("%02x", b & 0xff));
|
||||
}
|
||||
|
||||
String calculatedSignStr = calculatedSign.toString();
|
||||
log.debug("计算签名: {}, 接收签名: {}", calculatedSignStr, sign);
|
||||
|
||||
return calculatedSignStr.equalsIgnoreCase(sign);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("签名验证失败: {}", e.getMessage(), e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证MD5签名(兼容旧版本)
|
||||
*
|
||||
* @param params 请求参数
|
||||
* @param sign 签名
|
||||
* @return 验证结果
|
||||
*/
|
||||
public boolean verifySign(Map<String, String> params, String sign) {
|
||||
try {
|
||||
// 按字典序排序参数
|
||||
TreeMap<String, String> sortedParams = new TreeMap<>(params);
|
||||
|
||||
// 构建签名字符串
|
||||
StringBuilder signStr = new StringBuilder();
|
||||
for (Map.Entry<String, String> entry : sortedParams.entrySet()) {
|
||||
if (entry.getValue() != null && !entry.getValue().isEmpty()) {
|
||||
signStr.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
|
||||
}
|
||||
}
|
||||
|
||||
// 添加签名密钥
|
||||
signStr.append("key=").append(signKey);
|
||||
|
||||
String signContent = signStr.toString();
|
||||
log.debug("签名内容: {}", signContent);
|
||||
|
||||
// 计算MD5
|
||||
MessageDigest md = MessageDigest.getInstance("MD5");
|
||||
byte[] md5Bytes = md.digest(signContent.getBytes(StandardCharsets.UTF_8));
|
||||
|
||||
// 转换为小写十六进制
|
||||
StringBuilder calculatedSign = new StringBuilder();
|
||||
for (byte b : md5Bytes) {
|
||||
calculatedSign.append(String.format("%02x", b & 0xff));
|
||||
}
|
||||
|
||||
String calculatedSignStr = calculatedSign.toString();
|
||||
log.debug("计算签名: {}, 接收签名: {}", calculatedSignStr, sign);
|
||||
|
||||
return calculatedSignStr.equalsIgnoreCase(sign);
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("签名验证失败: {}", e.getMessage(), e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 解密携程请求体
|
||||
*
|
||||
* @param encryptedBody 加密的请求体
|
||||
* @return 解密后的JSON字符串
|
||||
*/
|
||||
public String decryptCtripBody(String encryptedBody) {
|
||||
if (encryptedBody == null || encryptedBody.isEmpty()) {
|
||||
log.warn("请求体为空");
|
||||
return null;
|
||||
}
|
||||
|
||||
log.info("开始解密携程请求体,数据长度: {}", encryptedBody.length());
|
||||
|
||||
// 尝试AES解密
|
||||
String decryptedData = decryptAES(encryptedBody);
|
||||
if (decryptedData != null) {
|
||||
log.info("携程请求体解密成功");
|
||||
return decryptedData;
|
||||
}
|
||||
|
||||
log.error("携程请求体解密失败");
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查配置是否完整
|
||||
*/
|
||||
public boolean isConfigValid() {
|
||||
boolean valid = true;
|
||||
|
||||
if (aesKey == null || aesKey.isEmpty()) {
|
||||
log.error("携程AES密钥未配置");
|
||||
valid = false;
|
||||
}
|
||||
|
||||
if (signKey == null || signKey.isEmpty()) {
|
||||
log.error("携程签名密钥未配置");
|
||||
valid = false;
|
||||
}
|
||||
|
||||
if (aesIv == null || aesIv.isEmpty()) {
|
||||
log.error("携程AES IV未配置");
|
||||
valid = false;
|
||||
}
|
||||
|
||||
return valid;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取配置信息(脱敏)
|
||||
*/
|
||||
public String getConfigInfo() {
|
||||
return String.format("AES密钥长度: %d, 签名密钥长度: %d, IV长度: %d",
|
||||
aesKey != null ? aesKey.length() : 0,
|
||||
signKey != null ? signKey.length() : 0,
|
||||
aesIv != null ? aesIv.length() : 0);
|
||||
}
|
||||
}
|
||||
+363
@@ -0,0 +1,363 @@
|
||||
package com.central.order.util;
|
||||
|
||||
import com.central.order.model.CtripCreateOrderResponse;
|
||||
import com.central.order.model.CtripConsumedNoticeResponse;
|
||||
import com.central.order.model.CtripCreateOrderRequest;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 携程标准响应码工具类
|
||||
* 根据携程API平台标准定义响应码
|
||||
*
|
||||
* @author system
|
||||
* @date 2024-12-19
|
||||
*/
|
||||
@Slf4j
|
||||
public class CtripResponseCodeUtil {
|
||||
|
||||
/**
|
||||
* 携程标准响应码定义
|
||||
*/
|
||||
public static class CtripResponseCodes {
|
||||
// 成功响应码
|
||||
public static final String SUCCESS = "0000";
|
||||
public static final String SUCCESS_MESSAGE = "操作成功";
|
||||
|
||||
// 系统错误码 (1000-1999)
|
||||
public static final String SYSTEM_ERROR = "1000";
|
||||
public static final String SYSTEM_ERROR_MESSAGE = "系统错误";
|
||||
|
||||
public static final String PARAM_ERROR = "1001";
|
||||
public static final String PARAM_ERROR_MESSAGE = "参数错误";
|
||||
|
||||
public static final String SIGN_ERROR = "1002";
|
||||
public static final String SIGN_ERROR_MESSAGE = "签名验证失败";
|
||||
|
||||
public static final String TIMESTAMP_ERROR = "1003";
|
||||
public static final String TIMESTAMP_ERROR_MESSAGE = "时间戳错误";
|
||||
|
||||
public static final String VERSION_ERROR = "1004";
|
||||
public static final String VERSION_ERROR_MESSAGE = "版本号错误";
|
||||
|
||||
// 业务错误码 (2000-2999)
|
||||
public static final String ORDER_NOT_FOUND = "2000";
|
||||
public static final String ORDER_NOT_FOUND_MESSAGE = "订单不存在";
|
||||
|
||||
public static final String ORDER_ALREADY_EXISTS = "2001";
|
||||
public static final String ORDER_ALREADY_EXISTS_MESSAGE = "订单已存在";
|
||||
|
||||
public static final String ORDER_STATUS_ERROR = "2002";
|
||||
public static final String ORDER_STATUS_ERROR_MESSAGE = "订单状态错误";
|
||||
|
||||
public static final String COUPON_NOT_FOUND = "2003";
|
||||
public static final String COUPON_NOT_FOUND_MESSAGE = "优惠券不存在";
|
||||
|
||||
public static final String COUPON_ALREADY_USED = "2004";
|
||||
public static final String COUPON_ALREADY_USED_MESSAGE = "优惠券已使用";
|
||||
|
||||
public static final String COUPON_EXPIRED = "2005";
|
||||
public static final String COUPON_EXPIRED_MESSAGE = "优惠券已过期";
|
||||
|
||||
public static final String COUPON_INSUFFICIENT = "2006";
|
||||
public static final String COUPON_INSUFFICIENT_MESSAGE = "优惠券余额不足";
|
||||
|
||||
public static final String USER_NOT_FOUND = "2007";
|
||||
public static final String USER_NOT_FOUND_MESSAGE = "用户不存在";
|
||||
|
||||
public static final String PRODUCT_NOT_FOUND = "2008";
|
||||
public static final String PRODUCT_NOT_FOUND_MESSAGE = "产品不存在";
|
||||
|
||||
public static final String PRODUCT_UNAVAILABLE = "2009";
|
||||
public static final String PRODUCT_UNAVAILABLE_MESSAGE = "产品不可用";
|
||||
|
||||
// 网络错误码 (3000-3999)
|
||||
public static final String NETWORK_ERROR = "3000";
|
||||
public static final String NETWORK_ERROR_MESSAGE = "网络连接错误";
|
||||
|
||||
public static final String TIMEOUT_ERROR = "3001";
|
||||
public static final String TIMEOUT_ERROR_MESSAGE = "请求超时";
|
||||
|
||||
public static final String SERVICE_UNAVAILABLE = "3002";
|
||||
public static final String SERVICE_UNAVAILABLE_MESSAGE = "服务不可用";
|
||||
|
||||
// 权限错误码 (4000-4999)
|
||||
public static final String UNAUTHORIZED = "4000";
|
||||
public static final String UNAUTHORIZED_MESSAGE = "未授权访问";
|
||||
|
||||
public static final String FORBIDDEN = "4001";
|
||||
public static final String FORBIDDEN_MESSAGE = "访问被拒绝";
|
||||
|
||||
public static final String ACCOUNT_DISABLED = "4002";
|
||||
public static final String ACCOUNT_DISABLED_MESSAGE = "账户已禁用";
|
||||
|
||||
// 数据错误码 (5000-5999)
|
||||
public static final String DATA_NOT_FOUND = "5000";
|
||||
public static final String DATA_NOT_FOUND_MESSAGE = "数据不存在";
|
||||
|
||||
public static final String DATA_INVALID = "5001";
|
||||
public static final String DATA_INVALID_MESSAGE = "数据格式错误";
|
||||
|
||||
public static final String DATA_CONFLICT = "5002";
|
||||
public static final String DATA_CONFLICT_MESSAGE = "数据冲突";
|
||||
|
||||
// 第三方服务错误码 (6000-6999)
|
||||
public static final String THIRD_PARTY_ERROR = "6000";
|
||||
public static final String THIRD_PARTY_ERROR_MESSAGE = "第三方服务错误";
|
||||
|
||||
public static final String PAYMENT_ERROR = "6001";
|
||||
public static final String PAYMENT_ERROR_MESSAGE = "支付服务错误";
|
||||
|
||||
public static final String SMS_ERROR = "6002";
|
||||
public static final String SMS_ERROR_MESSAGE = "短信服务错误";
|
||||
|
||||
public static final String EMAIL_ERROR = "6003";
|
||||
public static final String EMAIL_ERROR_MESSAGE = "邮件服务错误";
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建携程订单创建成功响应
|
||||
*/
|
||||
public static CtripCreateOrderResponse buildCreateOrderSuccessResponse(
|
||||
CtripCreateOrderRequest request,
|
||||
String otaOrderId,
|
||||
String supplierOrderId,
|
||||
String message) {
|
||||
|
||||
CtripCreateOrderResponse response = new CtripCreateOrderResponse();
|
||||
|
||||
// 设置返回头
|
||||
CtripCreateOrderResponse.CtripResponseHeader responseHeader = new CtripCreateOrderResponse.CtripResponseHeader();
|
||||
responseHeader.setRequestTime(request.getHeader().getRequestTime());
|
||||
responseHeader.setAccountId(request.getHeader().getAccountId());
|
||||
responseHeader.setSign(request.getHeader().getSign());
|
||||
responseHeader.setServiceName(request.getHeader().getServiceName());
|
||||
responseHeader.setVersion(request.getHeader().getVersion());
|
||||
response.setHeader(responseHeader);
|
||||
|
||||
// 设置返回码
|
||||
response.setResultCode(CtripResponseCodes.SUCCESS);
|
||||
response.setResultMessage(CtripResponseCodes.SUCCESS_MESSAGE);
|
||||
|
||||
// 设置返回体
|
||||
CtripCreateOrderResponse.CtripResponseBody responseBody = new CtripCreateOrderResponse.CtripResponseBody();
|
||||
responseBody.setOtaOrderId(otaOrderId);
|
||||
responseBody.setSupplierOrderId(supplierOrderId);
|
||||
responseBody.setSupplierConfirmType(1); // 已确认
|
||||
responseBody.setVoucherSender(1); // 携程对客发送凭证
|
||||
responseBody.setOrderExtendMessage(message);
|
||||
|
||||
// 设置订单项
|
||||
List<CtripCreateOrderResponse.CtripResponseOrderItem> responseItems = new ArrayList<>();
|
||||
CtripCreateOrderResponse.CtripResponseOrderItem responseItem = new CtripCreateOrderResponse.CtripResponseOrderItem();
|
||||
responseItem.setItemId("1");
|
||||
responseItem.setSupplierItemId(supplierOrderId + "_ITEM");
|
||||
responseItem.setStatus(1); // 成功
|
||||
responseItem.setMessage(message);
|
||||
responseItems.add(responseItem);
|
||||
responseBody.setItems(responseItems);
|
||||
|
||||
response.setBody(responseBody);
|
||||
|
||||
log.info("构建携程订单创建成功响应: otaOrderId={}, supplierOrderId={}", otaOrderId, supplierOrderId);
|
||||
return response;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建携程订单创建错误响应
|
||||
*/
|
||||
public static CtripCreateOrderResponse buildCreateOrderErrorResponse(
|
||||
CtripCreateOrderRequest request,
|
||||
String resultCode,
|
||||
String resultMessage) {
|
||||
|
||||
CtripCreateOrderResponse response = new CtripCreateOrderResponse();
|
||||
|
||||
// 设置返回头
|
||||
CtripCreateOrderResponse.CtripResponseHeader responseHeader = new CtripCreateOrderResponse.CtripResponseHeader();
|
||||
responseHeader.setRequestTime(request.getHeader().getRequestTime());
|
||||
responseHeader.setAccountId(request.getHeader().getAccountId());
|
||||
responseHeader.setSign(request.getHeader().getSign());
|
||||
responseHeader.setServiceName(request.getHeader().getServiceName());
|
||||
responseHeader.setVersion(request.getHeader().getVersion());
|
||||
response.setHeader(responseHeader);
|
||||
|
||||
// 设置返回码
|
||||
response.setResultCode(resultCode);
|
||||
response.setResultMessage(resultMessage);
|
||||
|
||||
log.warn("构建携程订单创建错误响应: resultCode={}, resultMessage={}", resultCode, resultMessage);
|
||||
return response;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建携程核销通知成功响应
|
||||
*/
|
||||
public static CtripConsumedNoticeResponse buildConsumedNoticeSuccessResponse(
|
||||
String otaOrderId,
|
||||
String supplierOrderId) {
|
||||
|
||||
CtripConsumedNoticeResponse response = new CtripConsumedNoticeResponse();
|
||||
|
||||
// 设置响应头
|
||||
CtripConsumedNoticeResponse.CtripConsumedNoticeResponseHeader header = new CtripConsumedNoticeResponse.CtripConsumedNoticeResponseHeader();
|
||||
header.setRequestTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
|
||||
header.setAccountId("SYSTEM");
|
||||
header.setSign("SUCCESS");
|
||||
header.setServiceName("ConsumedNotice");
|
||||
header.setVersion("1.0");
|
||||
response.setHeader(header);
|
||||
|
||||
// 设置响应码
|
||||
response.setResultCode(CtripResponseCodes.SUCCESS);
|
||||
response.setResultMessage(CtripResponseCodes.SUCCESS_MESSAGE);
|
||||
|
||||
// 设置响应体
|
||||
CtripConsumedNoticeResponse.CtripConsumedNoticeResponseBody body = new CtripConsumedNoticeResponse.CtripConsumedNoticeResponseBody();
|
||||
body.setOtaOrderId(otaOrderId);
|
||||
body.setSupplierOrderId(supplierOrderId);
|
||||
body.setProcessResult("SUCCESS");
|
||||
body.setProcessTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
|
||||
response.setBody(body);
|
||||
|
||||
log.info("构建携程核销通知成功响应: otaOrderId={}, supplierOrderId={}", otaOrderId, supplierOrderId);
|
||||
return response;
|
||||
}
|
||||
|
||||
/**
|
||||
* 构建携程核销通知错误响应
|
||||
*/
|
||||
public static CtripConsumedNoticeResponse buildConsumedNoticeErrorResponse(
|
||||
String otaOrderId,
|
||||
String supplierOrderId,
|
||||
String resultCode,
|
||||
String resultMessage) {
|
||||
|
||||
CtripConsumedNoticeResponse response = new CtripConsumedNoticeResponse();
|
||||
|
||||
// 设置响应头
|
||||
CtripConsumedNoticeResponse.CtripConsumedNoticeResponseHeader header = new CtripConsumedNoticeResponse.CtripConsumedNoticeResponseHeader();
|
||||
header.setRequestTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
|
||||
header.setAccountId("SYSTEM");
|
||||
header.setSign("ERROR");
|
||||
header.setServiceName("ConsumedNotice");
|
||||
header.setVersion("1.0");
|
||||
response.setHeader(header);
|
||||
|
||||
// 设置响应码
|
||||
response.setResultCode(resultCode);
|
||||
response.setResultMessage(resultMessage);
|
||||
|
||||
// 设置响应体
|
||||
CtripConsumedNoticeResponse.CtripConsumedNoticeResponseBody body = new CtripConsumedNoticeResponse.CtripConsumedNoticeResponseBody();
|
||||
body.setOtaOrderId(otaOrderId);
|
||||
body.setSupplierOrderId(supplierOrderId);
|
||||
body.setProcessResult("FAILED");
|
||||
body.setProcessTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
|
||||
response.setBody(body);
|
||||
|
||||
log.warn("构建携程核销通知错误响应: otaOrderId={}, resultCode={}, resultMessage={}", otaOrderId, resultCode, resultMessage);
|
||||
return response;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据异常类型获取标准响应码
|
||||
*/
|
||||
public static String getResultCodeByException(Exception e) {
|
||||
String exceptionName = e.getClass().getSimpleName();
|
||||
|
||||
switch (exceptionName) {
|
||||
case "IllegalArgumentException":
|
||||
case "MissingServletRequestParameterException":
|
||||
return CtripResponseCodes.PARAM_ERROR;
|
||||
case "UnauthorizedException":
|
||||
return CtripResponseCodes.UNAUTHORIZED;
|
||||
case "ForbiddenException":
|
||||
return CtripResponseCodes.FORBIDDEN;
|
||||
case "NotFoundException":
|
||||
return CtripResponseCodes.DATA_NOT_FOUND;
|
||||
case "ConflictException":
|
||||
return CtripResponseCodes.DATA_CONFLICT;
|
||||
case "TimeoutException":
|
||||
return CtripResponseCodes.TIMEOUT_ERROR;
|
||||
default:
|
||||
return CtripResponseCodes.SYSTEM_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据异常类型获取标准响应消息
|
||||
*/
|
||||
public static String getResultMessageByException(Exception e) {
|
||||
String exceptionName = e.getClass().getSimpleName();
|
||||
|
||||
switch (exceptionName) {
|
||||
case "IllegalArgumentException":
|
||||
case "MissingServletRequestParameterException":
|
||||
return CtripResponseCodes.PARAM_ERROR_MESSAGE;
|
||||
case "UnauthorizedException":
|
||||
return CtripResponseCodes.UNAUTHORIZED_MESSAGE;
|
||||
case "ForbiddenException":
|
||||
return CtripResponseCodes.FORBIDDEN_MESSAGE;
|
||||
case "NotFoundException":
|
||||
return CtripResponseCodes.DATA_NOT_FOUND_MESSAGE;
|
||||
case "ConflictException":
|
||||
return CtripResponseCodes.DATA_CONFLICT_MESSAGE;
|
||||
case "TimeoutException":
|
||||
return CtripResponseCodes.TIMEOUT_ERROR_MESSAGE;
|
||||
default:
|
||||
return CtripResponseCodes.SYSTEM_ERROR_MESSAGE;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证响应码是否有效
|
||||
*/
|
||||
public static boolean isValidResponseCode(String resultCode) {
|
||||
if (resultCode == null || resultCode.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 检查是否为4位数字
|
||||
if (!resultCode.matches("\\d{4}")) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 检查是否在有效范围内
|
||||
int code = Integer.parseInt(resultCode);
|
||||
return (code >= 0 && code <= 9999);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取响应码分类
|
||||
*/
|
||||
public static String getResponseCodeCategory(String resultCode) {
|
||||
if (resultCode == null || resultCode.isEmpty()) {
|
||||
return "UNKNOWN";
|
||||
}
|
||||
|
||||
int code = Integer.parseInt(resultCode);
|
||||
|
||||
if (code == 0) {
|
||||
return "SUCCESS";
|
||||
} else if (code >= 1000 && code < 2000) {
|
||||
return "SYSTEM_ERROR";
|
||||
} else if (code >= 2000 && code < 3000) {
|
||||
return "BUSINESS_ERROR";
|
||||
} else if (code >= 3000 && code < 4000) {
|
||||
return "NETWORK_ERROR";
|
||||
} else if (code >= 4000 && code < 5000) {
|
||||
return "AUTHORIZATION_ERROR";
|
||||
} else if (code >= 5000 && code < 6000) {
|
||||
return "DATA_ERROR";
|
||||
} else if (code >= 6000 && code < 7000) {
|
||||
return "THIRD_PARTY_ERROR";
|
||||
} else {
|
||||
return "UNKNOWN";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
# 租户分配配置示例
|
||||
tenant:
|
||||
allocation:
|
||||
# 是否启用租户分配功能
|
||||
enabled: false
|
||||
# 分配比例(景区:平台),默认10:1
|
||||
allocation-ratio: 10
|
||||
# 平台默认租户ID
|
||||
platform-tenant-id: "webApp"
|
||||
# 是否启用调试模式
|
||||
debug: false
|
||||
# 是否强制使用平台租户(用于测试)
|
||||
force-platform-tenant: false
|
||||
|
||||
# 配置说明:
|
||||
# 1. enabled: 控制是否启用智能租户分配功能
|
||||
# - true: 启用,订单会根据10:1比例分配给景区和平台租户
|
||||
# - false: 禁用,所有订单都分配给景区租户(原有逻辑)
|
||||
#
|
||||
# 2. allocation-ratio: 分配比例
|
||||
# - 10: 表示10单景区 + 1单平台
|
||||
# - 可以调整为其他比例,如5表示5单景区 + 1单平台
|
||||
#
|
||||
# 3. platform-tenant-id: 平台租户ID
|
||||
# - 默认值: "webApp"
|
||||
# - 分配给平台的订单会使用这个租户ID
|
||||
#
|
||||
# 4. debug: 调试模式
|
||||
# - true: 启用详细日志
|
||||
# - false: 正常日志级别
|
||||
#
|
||||
# 5. force-platform-tenant: 强制平台租户(测试用)
|
||||
# - true: 所有订单都分配给平台租户
|
||||
# - false: 正常分配逻辑
|
||||
@@ -29,7 +29,7 @@ knife4j:
|
||||
zlt:
|
||||
#多租户配置
|
||||
tenant:
|
||||
enable: false
|
||||
enable: true
|
||||
ignoreTables:
|
||||
- edit_task
|
||||
- home_carousel
|
||||
@@ -39,17 +39,16 @@ zlt:
|
||||
- video_template
|
||||
- profit_sharing
|
||||
- order_statistics
|
||||
- orders_refund
|
||||
ignoreSqls:
|
||||
# 查询全部列表
|
||||
# - com.central.order.mapper.OrderMapper.findList
|
||||
# 获取某个订单
|
||||
# - com.central.order.mapper.OrderMapper.getOrderByNumber
|
||||
noIgnoreSqls:
|
||||
- com.central.order.mapper.OrderMapper.findList
|
||||
- com.central.order.mapper.TourismMapper.findList
|
||||
- com.central.order.mapper.OrderFileMapper.findList
|
||||
- com.central.order.mapper.QrCodeMapper.findList
|
||||
- com.central.order.mapper.QrCodeMapper.save
|
||||
# 移除所有ignoreSqls配置,让所有SQL都经过租户过滤处理
|
||||
# 这样webApp租户的特殊处理逻辑才能生效
|
||||
# 该接口是白名单接口查询中的逻辑,来例如:机库直接创建数据没有携带租户ID
|
||||
- com.central.order.mapper.OrderMapper.getOrderByNumber
|
||||
- com.central.order.mapper.OrderMapper.getOrdersByStatus
|
||||
- com.central.order.mapper.RefundMapper.selectOne
|
||||
# update和delete类型的操作mybatisPlus不支持,原因是数据隔离级别
|
||||
# - com.central.order.mapper.OrderMapper.updateOrderStatus
|
||||
# 微信支付商户号
|
||||
tencent:
|
||||
merchantId: ${zlt.wxpay.merchantId}
|
||||
@@ -88,7 +87,7 @@ tencent:
|
||||
file:
|
||||
oss-url: goflyapp.oss-cn-beijing.aliyuncs.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:
|
||||
# enabled: true
|
||||
@@ -126,3 +125,26 @@ wx:
|
||||
activity-start: lgwkRnbdDc3mEwk3RMob43LpLHnLfglZtTkbFRPsPCA
|
||||
order-complete: ZeIlAA6ImQLxBiLmo-53lM7wkL4KnuKKTGKWBZwYAdM
|
||||
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
|
||||
|
||||
# 携程API配置
|
||||
ctrip:
|
||||
aes:
|
||||
key: 087b36ad0dff7942 # 请替换为实际的AES密钥
|
||||
iv: 750e15a31356a99d # 请替换为实际的AES IV
|
||||
sign:
|
||||
key: ce6033ae31124ec5cdab3d2bc79f2622 # 请替换为实际的签名密钥
|
||||
|
||||
@@ -4,10 +4,10 @@ server:
|
||||
spring:
|
||||
application:
|
||||
name: order-center
|
||||
# cloud:
|
||||
# nacos:
|
||||
# discovery:
|
||||
# ip: 81.70.164.178
|
||||
cloud:
|
||||
nacos:
|
||||
discovery:
|
||||
ip: 81.70.164.178
|
||||
# cloud:
|
||||
# nacos:
|
||||
# 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 != ''">
|
||||
AND t.order_no LIKE CONCAT('%', #{params.orderNo}, '%')
|
||||
</if>
|
||||
<if test="params.createTime != null and params.createTime.length == 2">
|
||||
AND t.create_time BETWEEN #{params.createTime[0]} AND #{params.createTime[1]}
|
||||
<if test="params.startTime != null and params.endTime != null ">
|
||||
AND t.create_time BETWEEN #{params.startTime} AND #{params.endTime}
|
||||
</if>
|
||||
</where>
|
||||
ORDER BY t.id DESC
|
||||
|
||||
@@ -22,7 +22,15 @@
|
||||
|
||||
<!-- 动态获取参数采用备参 -->
|
||||
<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>
|
||||
|
||||
<!-- 根据订单状态查询订单列表 -->
|
||||
|
||||
@@ -17,4 +17,61 @@
|
||||
INSERT INTO tourisms (tourism_no, tourism_name, tourism_address,tourism_phone)
|
||||
VALUES (#{tourismNo}, #{tourismName}, #{tourismAddress},#{tourismPhone})
|
||||
</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>
|
||||
|
||||
+427
@@ -0,0 +1,427 @@
|
||||
package com.central.order.controller;
|
||||
|
||||
import com.central.order.model.CtripCreateOrderRequest;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Arrays;
|
||||
import java.util.Base64;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* 优惠券控制器测试
|
||||
*/
|
||||
@SpringBootTest
|
||||
public class CouponControllerTest {
|
||||
|
||||
@Test
|
||||
public void testCtripCreateOrderRequestDeserialization() throws Exception {
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
// 构建测试JSON
|
||||
String testJson = "{\n" +
|
||||
" \"header\": {\n" +
|
||||
" \"requestTime\": \"2024-12-19 10:00:00\",\n" +
|
||||
" \"accountId\": \"testAccount\",\n" +
|
||||
" \"sign\": \"testSign\",\n" +
|
||||
" \"serviceName\": \"createOrder\",\n" +
|
||||
" \"version\": \"1.0\"\n" +
|
||||
" },\n" +
|
||||
" \"body\": {\n" +
|
||||
" \"otaOrderId\": \"CTRIP123456\",\n" +
|
||||
" \"sequenceId\": \"SEQ123456\",\n" +
|
||||
" \"items\": [\n" +
|
||||
" {\n" +
|
||||
" \"passengers\": [\n" +
|
||||
" {\n" +
|
||||
" \"name\": \"张三\",\n" +
|
||||
" \"mobile\": \"13800138000\",\n" +
|
||||
" \"gender\": \"M\",\n" +
|
||||
" \"cardType\": \"ID\",\n" +
|
||||
" \"cardNo\": \"110101199001011234\"\n" +
|
||||
" }\n" +
|
||||
" ],\n" +
|
||||
" \"cost\": 100.00,\n" +
|
||||
" \"quantity\": 1,\n" +
|
||||
" \"salePrice\": 80.00,\n" +
|
||||
" \"price\": 100.00,\n" +
|
||||
" \"useStartDate\": \"2024-12-20\",\n" +
|
||||
" \"useEndDate\": \"2024-12-25\",\n" +
|
||||
" \"adjunctions\": [\"adj1\", \"adj2\"],\n" +
|
||||
" \"deposit\": {},\n" +
|
||||
" \"distributionChannel\": \"online\",\n" +
|
||||
" \"priceCurrency\": \"CNY\",\n" +
|
||||
" \"costCurrency\": \"CNY\",\n" +
|
||||
" \"salePriceCurrency\": \"CNY\"\n" +
|
||||
" }\n" +
|
||||
" ],\n" +
|
||||
" \"contacts\": [\n" +
|
||||
" {\n" +
|
||||
" \"name\": \"张三\",\n" +
|
||||
" \"mobile\": \"13800138000\",\n" +
|
||||
" \"email\": \"zhangsan@example.com\"\n" +
|
||||
" }\n" +
|
||||
" ]\n" +
|
||||
" }\n" +
|
||||
"}";
|
||||
|
||||
// 测试反序列化
|
||||
CtripCreateOrderRequest request = objectMapper.readValue(testJson, CtripCreateOrderRequest.class);
|
||||
|
||||
// 验证反序列化结果
|
||||
assertNotNull(request);
|
||||
assertNotNull(request.getHeader());
|
||||
assertNotNull(request.getBody());
|
||||
assertEquals("testAccount", request.getHeader().getAccountId());
|
||||
assertEquals("createOrder", request.getHeader().getServiceName());
|
||||
|
||||
// 验证body是对象
|
||||
assertTrue(request.getBody() instanceof CtripCreateOrderRequest.CtripOrderBody);
|
||||
CtripCreateOrderRequest.CtripOrderBody body = (CtripCreateOrderRequest.CtripOrderBody) request.getBody();
|
||||
assertEquals("CTRIP123456", body.getOtaOrderId());
|
||||
|
||||
// 验证订单项
|
||||
assertNotNull(body.getItems());
|
||||
assertFalse(body.getItems().isEmpty());
|
||||
|
||||
CtripCreateOrderRequest.CtripOrderItem item = body.getItems().get(0);
|
||||
assertNotNull(item.getPassengers());
|
||||
assertFalse(item.getPassengers().isEmpty());
|
||||
assertEquals("张三", item.getPassengers().get(0).getName());
|
||||
assertEquals("13800138000", item.getPassengers().get(0).getMobile());
|
||||
|
||||
System.out.println("JSON反序列化测试通过!");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCtripCreateOrderRequestSerialization() throws Exception {
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
// 构建测试对象
|
||||
CtripCreateOrderRequest request = new CtripCreateOrderRequest();
|
||||
|
||||
// 设置header
|
||||
CtripCreateOrderRequest.CtripHeader header = new CtripCreateOrderRequest.CtripHeader();
|
||||
header.setRequestTime("2024-12-19 10:00:00");
|
||||
header.setAccountId("testAccount");
|
||||
header.setSign("testSign");
|
||||
header.setServiceName("createOrder");
|
||||
header.setVersion("1.0");
|
||||
request.setHeader(header);
|
||||
|
||||
// 设置body为对象
|
||||
CtripCreateOrderRequest.CtripOrderBody body = new CtripCreateOrderRequest.CtripOrderBody();
|
||||
body.setOtaOrderId("CTRIP123456");
|
||||
body.setSequenceId("SEQ123456");
|
||||
|
||||
// 设置item
|
||||
CtripCreateOrderRequest.CtripOrderItem item = new CtripCreateOrderRequest.CtripOrderItem();
|
||||
item.setCost(new BigDecimal("100.00"));
|
||||
item.setQuantity(1);
|
||||
item.setSalePrice(new BigDecimal("80.00"));
|
||||
item.setPrice(new BigDecimal("100.00"));
|
||||
item.setUseStartDate("2024-12-20");
|
||||
item.setUseEndDate("2024-12-25");
|
||||
item.setAdjunctions(Arrays.asList("adj1", "adj2"));
|
||||
item.setDeposit(new Object());
|
||||
item.setDistributionChannel("online");
|
||||
item.setPriceCurrency("CNY");
|
||||
item.setCostCurrency("CNY");
|
||||
item.setSalePriceCurrency("CNY");
|
||||
|
||||
// 设置passenger
|
||||
CtripCreateOrderRequest.CtripPassenger passenger = new CtripCreateOrderRequest.CtripPassenger();
|
||||
passenger.setName("张三");
|
||||
passenger.setMobile("13800138000");
|
||||
passenger.setGender("M");
|
||||
passenger.setCardType("ID");
|
||||
passenger.setCardNo("110101199001011234");
|
||||
item.setPassengers(Arrays.asList(passenger));
|
||||
|
||||
body.setItems(Arrays.asList(item));
|
||||
|
||||
// 设置contact
|
||||
CtripCreateOrderRequest.CtripContact contact = new CtripCreateOrderRequest.CtripContact();
|
||||
contact.setName("张三");
|
||||
contact.setMobile("13800138000");
|
||||
contact.setEmail("zhangsan@example.com");
|
||||
body.setContacts(Arrays.asList(contact));
|
||||
|
||||
request.setBody(body);
|
||||
|
||||
// 测试序列化
|
||||
String json = objectMapper.writeValueAsString(request);
|
||||
assertNotNull(json);
|
||||
assertTrue(json.contains("CTRIP123456"));
|
||||
assertTrue(json.contains("testAccount"));
|
||||
|
||||
System.out.println("JSON序列化测试通过!");
|
||||
System.out.println("生成的JSON: " + json);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testErrorHandling() throws Exception {
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
// 测试错误的JSON格式
|
||||
String invalidJson = "{\"invalid\": \"data\"}";
|
||||
|
||||
try {
|
||||
CtripCreateOrderRequest request = objectMapper.readValue(invalidJson, CtripCreateOrderRequest.class);
|
||||
// 如果没有抛出异常,说明@JsonIgnoreProperties生效了
|
||||
assertNotNull(request);
|
||||
System.out.println("错误处理测试通过 - 忽略未知属性");
|
||||
} catch (Exception e) {
|
||||
// 如果抛出异常,也是正常的
|
||||
System.out.println("错误处理测试通过 - 捕获到异常: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEncryptedDataHandling() {
|
||||
// 测试加密数据处理
|
||||
String encryptedData = "anipkokpjcnikijobbdgmeddhnmngkidmfoeamjgmmjenpikgpeafnoonnjppdlhhhoidlopkfbpepchhbikpeiaogpmglhjbcaoomkponmciaphjjajhogmmagkiflikbffgmgkinckainhidjjmmoifodpakdlacfepfphenlflpcpdmjpnpaocckibgoagfcncpjnkhaniibphkmgknjabnfoeiblkfbmpekpkpaolangbbpflclbnbmffcaaemnaceckfmaegfnoclpgkblgpjggkjdmkbnkbffacmlpbnefipiaenjclfppilnedllghnejhdchhkdacadanioehbpbdmghioohnjbaamahjdoebckhhljnohfaddbndlepilbnngdhlmfbajnjchllinafbpeldcaacnddmieipmnikgbbbmjpbnpofceacdecjdifkmipeknimidgpbjpdoclimemkjmjhnneghcknneambllglnahlkenngnakncoijpggpdafipbladoaadbdfdebkcjfkaopaieknmjfopbojgljmlgkehmgoghnhggppbeoflhgfijjoabbmkipehekdpchlagnlbdidbmdmghdhoicoapnneljedkkaiikieneiopokkbidoigjlbmkkpeilapilhcmdkaiokiciaacenikijicllgdkbhlenhhcdapipkjhompefkfeginnmgmkjjooleihjfnjofkdgelojfboejjdopiajgldoppcaepkoceffkfjacfcpcbfcblgkaigddakfagnijfjdombelmfgjgopighebpdgbfcbmbecblhdgfbgkoacoiemfelalemmnkeejnighfgmlbenocgdlmoelbcakjppjlpoecimikkbcjblemhbhcgnapcmjbbflgmlfkllmpgdmhiagpolnlccanjdbajnbieapghplipmemakjkkfgphligccnlpjhgeiglbpdcejaajfhjfkplhocifopajenpmdmpncbpkhbbnpnbckmkahemfddhkgijgagkbmpigmbdedmkonkcchimohghkojhmgfeafpefoefccbjjkfkdcedbcmlgomoicfihhaalamkafkmfefdlihpopbdomkiodfdaiogemkebjmbgnfodmnbfedbaacdlmmangllfjihbhmngeoibobbjjmfmfdmpncdpbnfhcggonmfnpifhbjbjlnmcffdpnjpajkgdhllhdpffbdnioacknijcabmncijgmepdkipfpncchmaiamlmfpbcjamggjdjeokhdepklpflafjolemjednbbfmgoikkmfdhgnfiomkaahccnflpdlholfdkncdimgdgfmjdahadbohhfiamlfggljdeahjaaoopclacaakmpobapkhnbmcfmlbobdhblillhdbmmnoaaaeedaleehgpeofipljnmloicglmdmefpkdiplhlmhgiafhjjijigeapikdcdaoallpjlcmebbcohnmlacnkcbcnjkapdaeemkgcgbodjbneaapdgomhbmoljahdlmffnebohgngnfhkjlhejfebgjcccfpmclbeooaghapbkdcjicgjpjnjcgfnhefcmkknglodcoajnobpakaempkbllghgfcobefnebjnaniocjmdedcbgpbbacelfecgemifkedogbloplckenjopknbpfgabpfnaphcklifibbhgohhkjldaekcedkeimlmegdhbjnffililaamfbfdkakleknjdjahogknimijcdahggheehclghkbkkclebcgopeabkkcceiahldnmnffhkgcdbahaldpgddehbpjieaojnknbedoinappdpjjkinjcgiodfahffppcpkeaelgcabkelblhlbbddbemckhkjldpndoohboioplpdohngjpbdegfcnhloenmncalldemhoigglahmnpcdepjfmfhdekbnombijpcfiggmllpglbghlelijohdegkkmicbcgioccekjbhfhoimhdpcejcjcjlmohpfiijjpmknihlhgjeniknkjlhjdgemjgjbnahdhjgobmgonnlljhpendhke";
|
||||
|
||||
// 验证这是一个长字符串而不是JSON
|
||||
assertFalse(encryptedData.startsWith("{"));
|
||||
assertFalse(encryptedData.endsWith("}"));
|
||||
assertTrue(encryptedData.length() > 1000);
|
||||
|
||||
System.out.println("加密数据处理测试通过 - 识别为非JSON格式的长字符串");
|
||||
}
|
||||
|
||||
|
||||
|
||||
@Test
|
||||
public void testOrderCreation() throws Exception {
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
// 构建测试JSON - 实际的携程订单数据
|
||||
String testJson = "{\n" +
|
||||
" \"header\": {\n" +
|
||||
" \"requestTime\": \"2025-08-01 22:58:01\",\n" +
|
||||
" \"accountId\": \"c50a8f2a4a59c9e7\",\n" +
|
||||
" \"sign\": \"5e8ebe775c7aaa466cd469947d6dee22\",\n" +
|
||||
" \"serviceName\": \"CreatePreOrder\",\n" +
|
||||
" \"version\": \"1.0\"\n" +
|
||||
" },\n" +
|
||||
" \"body\": {\n" +
|
||||
" \"otaOrderId\": \"ctriptest-10816912-454259-145573\",\n" +
|
||||
" \"sequenceId\": \"2025080122580189a0fbcc46364e1ab3b47fc7c20e3767\",\n" +
|
||||
" \"items\": [\n" +
|
||||
" {\n" +
|
||||
" \"passengers\": [\n" +
|
||||
" {\n" +
|
||||
" \"cardIssuePlace\": \"\",\n" +
|
||||
" \"lastName\": \"\",\n" +
|
||||
" \"cardIssueCountry\": \"\",\n" +
|
||||
" \"shoeSize\": 0,\n" +
|
||||
" \"gender\": \"M\",\n" +
|
||||
" \"cardIssueDate\": \"\",\n" +
|
||||
" \"intlCode\": \"+86\",\n" +
|
||||
" \"nationalityName\": \"\",\n" +
|
||||
" \"mobile\": \"18322694510\",\n" +
|
||||
" \"cardType\": \"1\",\n" +
|
||||
" \"weight\": 0,\n" +
|
||||
" \"myopiaDegreeL\": 0,\n" +
|
||||
" \"birthDate\": \"2025-07-10\",\n" +
|
||||
" \"cardNo\": \"620421198909185197\",\n" +
|
||||
" \"ageType\": \"ADU\",\n" +
|
||||
" \"myopiaDegreeR\": 0,\n" +
|
||||
" \"firstName\": \"sl\",\n" +
|
||||
" \"birthPlace\": \"\",\n" +
|
||||
" \"nationalityCode\": \"\",\n" +
|
||||
" \"name\": \"李世琳\",\n" +
|
||||
" \"passengerId\": \"33c0b8013a554c5c8f59e7e0fac6ef32\",\n" +
|
||||
" \"cardValidDate\": \"\",\n" +
|
||||
" \"height\": 0\n" +
|
||||
" }\n" +
|
||||
" ],\n" +
|
||||
" \"cost\": 2.00,\n" +
|
||||
" \"quantity\": 1,\n" +
|
||||
" \"salePrice\": 2.00,\n" +
|
||||
" \"remark\": \"This is remark\",\n" +
|
||||
" \"useEndDate\": \"2025-07-25\",\n" +
|
||||
" \"locale\": \"zh-CN\",\n" +
|
||||
" \"useStartDate\": \"2025-07-25\",\n" +
|
||||
" \"priceCurrency\": \"CNY\",\n" +
|
||||
" \"adjunctions\": [],\n" +
|
||||
" \"price\": 2.00,\n" +
|
||||
" \"PLU\": \"1\",\n" +
|
||||
" \"deposit\": {},\n" +
|
||||
" \"distributionChannel\": \"XCW\",\n" +
|
||||
" \"costCurrency\": \"CNY\",\n" +
|
||||
" \"salePriceCurrency\": \"CNY\",\n" +
|
||||
" \"expressDelivery\": {\n" +
|
||||
" \"type\": \"1\"\n" +
|
||||
" }\n" +
|
||||
" }\n" +
|
||||
" ],\n" +
|
||||
" \"contacts\": [\n" +
|
||||
" {\n" +
|
||||
" \"intlCode\": \"+86\",\n" +
|
||||
" \"name\": \"李世琳\",\n" +
|
||||
" \"mobile\": \"18322694510\",\n" +
|
||||
" \"optionalMobile\": \"13333333333\",\n" +
|
||||
" \"optionalIntlCode\": \"86\",\n" +
|
||||
" \"email\": \"1272745473@qq.com\"\n" +
|
||||
" }\n" +
|
||||
" ]\n" +
|
||||
" }\n" +
|
||||
"}";
|
||||
|
||||
// 测试反序列化
|
||||
CtripCreateOrderRequest request = objectMapper.readValue(testJson, CtripCreateOrderRequest.class);
|
||||
|
||||
// 验证反序列化结果
|
||||
assertNotNull(request);
|
||||
assertNotNull(request.getHeader());
|
||||
assertNotNull(request.getBody());
|
||||
assertEquals("c50a8f2a4a59c9e7", request.getHeader().getAccountId());
|
||||
assertEquals("CreatePreOrder", request.getHeader().getServiceName());
|
||||
|
||||
// 验证body是对象
|
||||
assertTrue(request.getBody() instanceof CtripCreateOrderRequest.CtripOrderBody);
|
||||
CtripCreateOrderRequest.CtripOrderBody body = (CtripCreateOrderRequest.CtripOrderBody) request.getBody();
|
||||
assertEquals("ctriptest-10816912-454259-145573", body.getOtaOrderId());
|
||||
|
||||
// 验证订单项
|
||||
assertNotNull(body.getItems());
|
||||
assertFalse(body.getItems().isEmpty());
|
||||
|
||||
CtripCreateOrderRequest.CtripOrderItem item = body.getItems().get(0);
|
||||
assertNotNull(item.getPassengers());
|
||||
assertFalse(item.getPassengers().isEmpty());
|
||||
assertEquals("李世琳", item.getPassengers().get(0).getName());
|
||||
assertEquals("18322694510", item.getPassengers().get(0).getMobile());
|
||||
assertEquals(new java.math.BigDecimal("2.00"), item.getSalePrice());
|
||||
|
||||
// 验证联系人
|
||||
assertNotNull(body.getContacts());
|
||||
assertFalse(body.getContacts().isEmpty());
|
||||
assertEquals("李世琳", body.getContacts().get(0).getName());
|
||||
assertEquals("18322694510", body.getContacts().get(0).getMobile());
|
||||
|
||||
System.out.println("订单创建测试通过!");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCtripCouponCreation() throws Exception {
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
// 构建测试JSON - 实际的携程优惠券数据
|
||||
String testJson = "{\n" +
|
||||
" \"header\": {\n" +
|
||||
" \"requestTime\": \"2025-08-01 22:58:01\",\n" +
|
||||
" \"accountId\": \"c50a8f2a4a59c9e7\",\n" +
|
||||
" \"sign\": \"5e8ebe775c7aaa466cd469947d6dee22\",\n" +
|
||||
" \"serviceName\": \"CreatePreOrder\",\n" +
|
||||
" \"version\": \"1.0\"\n" +
|
||||
" },\n" +
|
||||
" \"body\": {\n" +
|
||||
" \"otaOrderId\": \"ctriptest-10816912-454259-145573\",\n" +
|
||||
" \"sequenceId\": \"2025080122580189a0fbcc46364e1ab3b47fc7c20e3767\",\n" +
|
||||
" \"items\": [\n" +
|
||||
" {\n" +
|
||||
" \"passengers\": [\n" +
|
||||
" {\n" +
|
||||
" \"cardIssuePlace\": \"\",\n" +
|
||||
" \"lastName\": \"\",\n" +
|
||||
" \"cardIssueCountry\": \"\",\n" +
|
||||
" \"shoeSize\": 0,\n" +
|
||||
" \"gender\": \"M\",\n" +
|
||||
" \"cardIssueDate\": \"\",\n" +
|
||||
" \"intlCode\": \"+86\",\n" +
|
||||
" \"nationalityName\": \"\",\n" +
|
||||
" \"mobile\": \"18322694510\",\n" +
|
||||
" \"cardType\": \"1\",\n" +
|
||||
" \"weight\": 0,\n" +
|
||||
" \"myopiaDegreeL\": 0,\n" +
|
||||
" \"birthDate\": \"2025-07-10\",\n" +
|
||||
" \"cardNo\": \"620421198909185197\",\n" +
|
||||
" \"ageType\": \"ADU\",\n" +
|
||||
" \"myopiaDegreeR\": 0,\n" +
|
||||
" \"firstName\": \"sl\",\n" +
|
||||
" \"birthPlace\": \"\",\n" +
|
||||
" \"nationalityCode\": \"\",\n" +
|
||||
" \"name\": \"李世琳\",\n" +
|
||||
" \"passengerId\": \"33c0b8013a554c5c8f59e7e0fac6ef32\",\n" +
|
||||
" \"cardValidDate\": \"\",\n" +
|
||||
" \"height\": 0\n" +
|
||||
" }\n" +
|
||||
" ],\n" +
|
||||
" \"cost\": 2.00,\n" +
|
||||
" \"quantity\": 1,\n" +
|
||||
" \"salePrice\": 2.00,\n" +
|
||||
" \"remark\": \"This is remark\",\n" +
|
||||
" \"useEndDate\": \"2025-07-25\",\n" +
|
||||
" \"locale\": \"zh-CN\",\n" +
|
||||
" \"useStartDate\": \"2025-07-25\",\n" +
|
||||
" \"priceCurrency\": \"CNY\",\n" +
|
||||
" \"adjunctions\": [],\n" +
|
||||
" \"price\": 2.00,\n" +
|
||||
" \"PLU\": \"1\",\n" +
|
||||
" \"deposit\": {},\n" +
|
||||
" \"distributionChannel\": \"XCW\",\n" +
|
||||
" \"costCurrency\": \"CNY\",\n" +
|
||||
" \"salePriceCurrency\": \"CNY\",\n" +
|
||||
" \"expressDelivery\": {\n" +
|
||||
" \"type\": \"1\"\n" +
|
||||
" }\n" +
|
||||
" }\n" +
|
||||
" ],\n" +
|
||||
" \"contacts\": [\n" +
|
||||
" {\n" +
|
||||
" \"intlCode\": \"+86\",\n" +
|
||||
" \"name\": \"李世琳\",\n" +
|
||||
" \"mobile\": \"18322694510\",\n" +
|
||||
" \"optionalMobile\": \"13333333333\",\n" +
|
||||
" \"optionalIntlCode\": \"86\",\n" +
|
||||
" \"email\": \"1272745473@qq.com\"\n" +
|
||||
" }\n" +
|
||||
" ]\n" +
|
||||
" }\n" +
|
||||
"}";
|
||||
|
||||
// 测试反序列化
|
||||
CtripCreateOrderRequest request = objectMapper.readValue(testJson, CtripCreateOrderRequest.class);
|
||||
|
||||
// 验证反序列化结果
|
||||
assertNotNull(request);
|
||||
assertNotNull(request.getHeader());
|
||||
assertNotNull(request.getBody());
|
||||
assertEquals("c50a8f2a4a59c9e7", request.getHeader().getAccountId());
|
||||
assertEquals("CreatePreOrder", request.getHeader().getServiceName());
|
||||
|
||||
// 验证body是对象
|
||||
assertTrue(request.getBody() instanceof CtripCreateOrderRequest.CtripOrderBody);
|
||||
CtripCreateOrderRequest.CtripOrderBody body = (CtripCreateOrderRequest.CtripOrderBody) request.getBody();
|
||||
assertEquals("ctriptest-10816912-454259-145573", body.getOtaOrderId());
|
||||
|
||||
// 验证订单项
|
||||
assertNotNull(body.getItems());
|
||||
assertFalse(body.getItems().isEmpty());
|
||||
|
||||
CtripCreateOrderRequest.CtripOrderItem item = body.getItems().get(0);
|
||||
assertNotNull(item.getPassengers());
|
||||
assertFalse(item.getPassengers().isEmpty());
|
||||
assertEquals("李世琳", item.getPassengers().get(0).getName());
|
||||
assertEquals("18322694510", item.getPassengers().get(0).getMobile());
|
||||
assertEquals(new java.math.BigDecimal("2.00"), item.getSalePrice());
|
||||
|
||||
// 验证联系人
|
||||
assertNotNull(body.getContacts());
|
||||
assertFalse(body.getContacts().isEmpty());
|
||||
assertEquals("李世琳", body.getContacts().get(0).getName());
|
||||
assertEquals("18322694510", body.getContacts().get(0).getMobile());
|
||||
|
||||
System.out.println("携程优惠券创建测试通过!");
|
||||
System.out.println("接口路径: /coupon/ctrip/create");
|
||||
System.out.println("请求方法: POST");
|
||||
System.out.println("Content-Type: application/json");
|
||||
}
|
||||
|
||||
}
|
||||
+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("未找到配置");
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户注销账户
|
||||
*/
|
||||
@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查询微信配置")
|
||||
@GetMapping("/type/{type}")
|
||||
public WechatConfig getConfig(@PathVariable String type, @RequestParam String tenantId) {
|
||||
WechatConfig config = wechatConfigService.getConfig(type, tenantId);
|
||||
WechatConfig config = wechatConfigService.getConfigByTypeTenantId(type, tenantId);
|
||||
return config;
|
||||
}
|
||||
|
||||
@@ -113,8 +113,8 @@ public class WechatConfigController {
|
||||
|
||||
@Operation(summary = "获取微信配置")
|
||||
@GetMapping("/app/{id}")
|
||||
public WechatConfig getConfigByAppId(@PathVariable("id") String appId) {
|
||||
return wechatConfigService.getConfig(appId);
|
||||
public WechatConfig getConfigByAppId(@PathVariable("id") String appId, @RequestParam String type) {
|
||||
return wechatConfigService.getConfigByAppIdAndType(appId,type);
|
||||
}
|
||||
|
||||
@GetMapping(value = "/serial/{serialNumber}")
|
||||
@@ -128,7 +128,7 @@ public class WechatConfigController {
|
||||
public Result<Boolean> uploadPrivateKey(@RequestParam("file") MultipartFile file) {
|
||||
try {
|
||||
String privateKey = new String(file.getBytes());
|
||||
WechatConfig wechatConfig = wechatConfigService.getConfig("PAY",TenantContextHolder.getTenant());
|
||||
WechatConfig wechatConfig = wechatConfigService.getConfigByTypeTenantId("PAY",TenantContextHolder.getTenant());
|
||||
wechatConfig.setPrivateKey(privateKey);
|
||||
return Result.succeed(wechatConfigService.updateConfig(wechatConfig));
|
||||
} catch (Exception e) {
|
||||
@@ -140,7 +140,7 @@ public class WechatConfigController {
|
||||
@Operation(summary = "获取当前配置")
|
||||
@GetMapping("/current/{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("设备中心服务不可用");
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user