21 Commits
Author SHA1 Message Date
lishilin 47a685f419 fix(订单中心):首页统计优化,优惠券创建逻辑完善 2025-08-05 23:11:16 +08:00
lishilin 3cfa7cc82e fix(订单中心):用户相册接口查询逻辑更新V3版本 2025-08-05 15:43:21 +08:00
lishilin 56825ba89f fix(订单中心):首页订单状总览优化总收款订单数和今日收款订单数 2025-08-05 15:30:05 +08:00
lishilin 63da239524 fix(订单中心):首页订单状总览新增总已完成订单 2025-08-05 13:32:43 +08:00
lishilin e4ca99ffb2 fix(订单中心):首页订单状态分布图删除,新增二维码订单数量横向柱状图 2025-08-05 12:56:51 +08:00
lishilin 20e9e066bf fix(订单中心):订单管理这里新增景区筛选和分页默认20条 2025-08-05 12:50:22 +08:00
lishilin 603b5a584a fix(订单中心):首页统计数据规则修改,时间筛选无效bug修复,退款订单显示问题修复 2025-08-05 05:31:22 +08:00
lishilin fdcf22832a fix(订单中心):首页统计数据规则修改,时间筛选无效bug修复 2025-08-04 20:29:06 +08:00
lishilin b830b201f7 fix(订单中心):首页统计数据规则修改 2025-08-04 20:01:45 +08:00
lishilin 3503558ebc fix(文件中心):优化日志记录 2025-08-04 19:41:58 +08:00
lishilin 50e44e24bd fix(文件中心):实现平台租户自动分配订单,实现抽成订单金额的功能 2025-08-04 19:39:24 +08:00
lishilin ea388107f8 fix(文件中心):实现平台租户自动分配订单,实现抽成订单金额的功能 2025-08-04 19:14:34 +08:00
lishilin 9141be16d7 fix(文件中心):实现平台租户自动分配订单,实现抽成订单金额的功能 2025-08-04 19:14:30 +08:00
lishilin 8d8827fa5c fix(文件中心):携程优惠券核销逻辑完善 2025-08-04 15:09:56 +08:00
lishilin 5fc45b31bc fix(文件中心):修复冷数据访问问题彻底修复,设备中心查询航线文件空指针异常问题修复 2025-08-04 08:21:33 +08:00
lishilin 86b0158710 fix(文件中心):修复冷数据访问问题彻底修复,携程回调流程数据解析完成 2025-08-04 00:38:16 +08:00
lishilin 537b13e60e fix(文件中心):修复冷数据访问路径bug 2025-08-03 14:58:06 +08:00
lishilin ecc482ce13 fix(订单中心):首页统计临时演示修复,二维码租户Id修改 2025-08-03 12:12:58 +08:00
lishilin 3a48b6f34f fix(订单中心):首页统计优化,智创商户支付调试,景区商户模式调试,文件冷热数据切换逻辑,携程优惠券调试 2025-08-02 02:19:02 +08:00
lishilin ba869b62a5 fix(订单中心):首页统计优化 2025-07-30 19:49:13 +08:00
lishilin c79c6c405c !22 fix(后台管理): 首页统计功能新增二维码维度统计,灵活设置分账比例,过滤测试二维码订单的数据等
Merge pull request !22 from Iamasoldier/feature_temp
2025-07-30 07:53:10 +00:00
60 changed files with 8031 additions and 266 deletions
@@ -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) {
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) {
public Result findLineSignById(@PathVariable String id) {
try {
LineFile model = lineFileService.findLineFileByWaylineId(id);
return model.getSign();
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());
}
}
}
@@ -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) {
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) {
public Result findLineSignById(@PathVariable String id) {
try {
LineFile model = lineFileService.findLineFileByWaylineId(id);
return model.getSign();
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());
}
}
}
@@ -1,6 +1,8 @@
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;
@@ -11,8 +13,10 @@ 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管理控制器
@@ -30,6 +34,9 @@ public class CdnController {
@Autowired
private ICdnService cdnService;
@Autowired
private FileMapper fileMapper;
@Value("${file.oss-url:goflyapp.oss-cn-beijing.aliyuncs.com}")
private String cdnOssUrl;
@@ -160,10 +167,134 @@ public class CdnController {
* 这里需要根据实际业务逻辑实现
*/
private List<String> getOrderImageUrls(String orderNo) {
// TODO: 实现获取订单图片URL的逻辑
// 可以通过调用订单服务或文件服务来获取
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域名
@@ -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());
}
}
}
@@ -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());
}
}
}
@@ -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;
}
}
}
@@ -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) {
// 验证文件是否真的上传成功
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"))) {
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"))) {
// 检查路径特征 - 支持多种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) {
try {
String ossUrl = ossService.getViewUrlByPath(fileInfo.getPath());
return ossUrl != null && !ossUrl.isEmpty();
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,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);
}
}
@@ -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;
}
}
}
@@ -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/")
);
}
@@ -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)) {
// 处理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 {
// 处理相对路径或无前缀路径
int splitIndex = path.lastIndexOf(CommonConstant.PATH_SPLIT);
if (splitIndex != -1) {
s3Object.bucketName = path.substring(0, splitIndex);
s3Object.objectName = path.substring(splitIndex + 1);
s3Object.objectName = decodeUrl(path.substring(splitIndex + 1));
} else {
// 如果没有分隔符,使用默认bucket
s3Object.bucketName = "default-bucket";
s3Object.objectName = path;
// 如果没有分隔符,使用配置的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;
}
}
}
@@ -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,8 +45,12 @@ public class S3Service extends AbstractIFileService {
@Override
protected ObjectInfo uploadFile(String name, InputStream inputStream) {
try {
return s3Template.upload(name, inputStream);
} catch (Exception e) {
return null;
}
}
@Override
protected void deleteFile(String objectPath) {
@@ -55,13 +60,23 @@ public class S3Service extends AbstractIFileService {
@Override
public String getViewUrlByPath(String name) {
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) {
try {
S3Object s3Object = parsePath(name);
return s3Template.getViewUrl(s3Object.bucketName, s3Object.objectName, 60);
} catch (Exception e) {
return "";
}
}
@Override
public void out(String id, OutputStream os) {
@@ -74,28 +89,61 @@ 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) {
try {
return baseMapper.selectById(id);
} catch (Exception e) {
return null;
}
}
@Override
public FileInfo createFile(String path) {
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) {
try {
// 简化实现,直接返回空列表
return List.of();
} catch (Exception e) {
return List.of();
}
}
@Override
public String getViewUrlByPathAndExpires(String name, int expires) {
try {
S3Object s3Object = parsePath(name);
return s3Template.getViewUrl(s3Object.bucketName, s3Object.objectName, expires);
} catch (Exception e) {
return "";
}
}
@Setter
@Getter
@@ -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,7 +54,7 @@ zlt:
delete-source: false # 迁移后是否删除源文件
batch-size: 100 # 迁移批次大小
hot-sync:
enabled: false # 启用热数据同步
enabled: true # 启用热数据同步
batch-size: 100 # 批次大小
interval-minutes: 30 # 同步间隔
access-threshold: 10 # 访问次数阈值
@@ -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;
}
@@ -18,6 +18,8 @@ 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
@@ -75,4 +77,95 @@ public class DashboardController {
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());
}
}
}
@@ -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());
}
}
@@ -102,6 +102,9 @@ public class OrderController {
@Autowired
private WxPayConfigFactory wxPayConfigFactory;
@Autowired
private OrderTenantAllocationService orderTenantAllocationService;
/**
* 列表
*/
@@ -213,11 +216,20 @@ public class OrderController {
if (qrCode.getStatus().equals(CommonStatus.UNABLE.getId())){
return Result.failed("该二维码已过期");
}
order.setTenantId(qrCode.getTenantId());
// 智能租户分配:根据二维码ID确定租户
String determinedTenantId = orderTenantAllocationService.determineTenant(
qrCode.getCodeId(), qrCode.getTenantId());
order.setTenantId(determinedTenantId);
//设置订单所属tenantId
order.setTourismId(qrCode.getTourismId());
order.setDeviceSn(qrCode.getDeviceSn());
order.setOrderAmount(qrCode.getPrice());
// 记录订单分配日志
orderTenantAllocationService.incrementOrderCount(qrCode.getCodeId());
}else {
Assert.notNull(qrCode,"二维码不存在");
}
@@ -885,8 +897,17 @@ public class OrderController {
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));
// 视频缩略图使用图片的缩略图
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);
@@ -898,6 +919,132 @@ 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),
@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
@@ -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());
}
}
}
@@ -100,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());
@@ -189,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);
@@ -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());
}
}
}
@@ -200,6 +200,7 @@ public class WxPayController {
@RequestBody String body) {
log.info("------收到微信退款回调通知------");
try {
TenantContextHolder.setTenant(defaultTenantId);
// 构建请求参数
RequestParam requestParam = new RequestParam
.Builder()
@@ -239,6 +240,8 @@ public class WxPayController {
// 处理异常,记录日志等
log.error("处理退款回调失败", e);
return buildErrorResponse();
}finally {
TenantContextHolder.clear();
}
}
@@ -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
@@ -14,12 +14,14 @@ public interface DashboardMapper {
// 基础订单统计(支持筛选)
@Select({
"<script>",
"SELECT COUNT(*) FROM orders o",
"SELECT COUNT(*) as count",
"FROM orders o",
"JOIN qrcodes q ON o.code_id = q.code_id",
"WHERE o.is_del = 0",
"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>",
@@ -41,13 +43,15 @@ public interface DashboardMapper {
@Select({
"<script>",
"SELECT COUNT(*) FROM orders o",
"SELECT COUNT(*) as count",
"FROM orders o",
"JOIN qrcodes q ON o.code_id = q.code_id",
"WHERE o.is_del = 0",
"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>",
@@ -63,9 +67,10 @@ public interface DashboardMapper {
@Select({
"<script>",
"SELECT COUNT(*) FROM orders o",
"SELECT COUNT(*) as count",
"FROM orders o",
"JOIN qrcodes q ON o.code_id = q.code_id",
"WHERE o.is_del = 0",
"WHERE 1=1",
"<if test='p.includeTestQrcodes == null or p.includeTestQrcodes == false'>",
" AND q.is_test = 0",
"</if>",
@@ -85,9 +90,10 @@ public interface DashboardMapper {
@Select({
"<script>",
"SELECT COUNT(*) FROM orders o",
"SELECT COUNT(*) as count",
"FROM orders o",
"JOIN qrcodes q ON o.code_id = q.code_id",
"WHERE o.is_del = 0",
"WHERE 1=1",
"<if test='p.includeTestQrcodes == null or p.includeTestQrcodes == false'>",
" AND q.is_test = 0",
"</if>",
@@ -111,20 +117,132 @@ public interface DashboardMapper {
})
Long getCompletedOrders(@Param("p") Map<String, Object> params);
// 对账相关统计
@Select({
"<script>",
"SELECT COALESCE(SUM(o.order_amount), 0)",
"SELECT COUNT(*) as count",
"FROM orders o",
"JOIN qrcodes q ON o.code_id = q.code_id",
"WHERE o.is_del = 0",
"WHERE 1=1",
"<if test='p.includeTestQrcodes == null or p.includeTestQrcodes == false'>",
" AND q.is_test = 0",
"</if>",
"AND (o.order_status = 3 OR o.order_status = 8)",
"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 &lt;= #{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 &lt;= #{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>",
@@ -139,11 +257,9 @@ public interface DashboardMapper {
"<script>",
"SELECT COALESCE(SUM(os.platform_amount), 0)",
"FROM order_statistics os",
"JOIN orders o ON os.order_id = o.id",
"JOIN qrcodes q ON o.code_id = q.code_id",
"WHERE 1=1",
"<if test='p.includeTestQrcodes == null or p.includeTestQrcodes == false'>",
" AND q.is_test = 0",
" 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}",
@@ -168,11 +284,9 @@ public interface DashboardMapper {
"<script>",
"SELECT COALESCE(SUM(os.tourism_amount), 0)",
"FROM order_statistics os",
"JOIN orders o ON os.order_id = o.id",
"JOIN qrcodes q ON o.code_id = q.code_id",
"WHERE 1=1",
"<if test='p.includeTestQrcodes == null or p.includeTestQrcodes == false'>",
" AND q.is_test = 0",
" 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}",
@@ -195,22 +309,28 @@ public interface DashboardMapper {
@Select({
"<script>",
"SELECT COALESCE(SUM(CAST(r.refund_amount AS SIGNED)), 0)",
"FROM orders_refund r",
"JOIN orders o ON r.order_no = o.order_no",
"SELECT COALESCE(SUM(o.order_amount), 0) as amount",
"FROM orders o",
"JOIN qrcodes q ON o.code_id = q.code_id",
"WHERE r.status = 8",
"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 r.create_time >= #{p.startTime}",
" AND o.create_time >= #{p.startTime}",
"</if>",
"<if test='p.endTime != null and p.endTime != \"\"'>",
" AND r.create_time &lt;= #{p.endTime}",
" AND o.create_time &lt;= #{p.endTime}",
"</if>",
"</script>"
})
@@ -221,15 +341,20 @@ public interface DashboardMapper {
"<script>",
"SELECT",
" DATE_FORMAT(o.create_time, '%Y-%m-%d') as date,",
" 'orders' as type,",
" 'created' as type,",
" COUNT(*) as value",
"FROM orders o",
"JOIN qrcodes q ON o.code_id = q.code_id",
"WHERE o.is_del = 0",
"WHERE 1=1",
"<if test='p.includeTestQrcodes == null or p.includeTestQrcodes == false'>",
" AND q.is_test = 0",
"</if>",
" AND o.create_time >= DATE_SUB(CURDATE(), INTERVAL 7 DAY)",
"<if test='p.startTime != null and p.startTime != \"\"'>",
" AND o.create_time >= #{p.startTime}",
"</if>",
"<if test='p.endTime != null and p.endTime != \"\"'>",
" AND o.create_time &lt;= #{p.endTime}",
"</if>",
"<if test='p.tourismId != null'>",
" AND o.tourism_id = #{p.tourismId}",
"</if>",
@@ -240,7 +365,63 @@ public interface DashboardMapper {
" AND o.device_sn = #{p.deviceSn}",
"</if>",
"GROUP BY DATE_FORMAT(o.create_time, '%Y-%m-%d')",
"ORDER BY date",
"UNION ALL",
"SELECT",
" 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 &lt;= #{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 &lt;= #{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<TrendDataVO> getOrderTrend(@Param("p") Map<String, Object> params);
@@ -264,7 +445,7 @@ public interface DashboardMapper {
" COUNT(*) as value",
"FROM orders o",
"JOIN qrcodes q ON o.code_id = q.code_id",
"WHERE o.is_del = 0",
"WHERE 1=1",
"<if test='p.includeTestQrcodes == null or p.includeTestQrcodes == false'>",
" AND q.is_test = 0",
"</if>",
@@ -294,11 +475,9 @@ public interface DashboardMapper {
" '平台分账' as type,",
" COALESCE(SUM(os.platform_amount), 0) as value",
"FROM order_statistics os",
"JOIN orders o ON os.order_id = o.id",
"JOIN qrcodes q ON o.code_id = q.code_id",
"WHERE 1=1",
"<if test='p.includeTestQrcodes == null or p.includeTestQrcodes == false'>",
" AND q.is_test = 0",
" 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}",
@@ -320,11 +499,9 @@ public interface DashboardMapper {
" '景区分账' as type,",
" COALESCE(SUM(os.tourism_amount), 0) as value",
"FROM order_statistics os",
"JOIN orders o ON os.order_id = o.id",
"JOIN qrcodes q ON o.code_id = q.code_id",
"WHERE 1=1",
"<if test='p.includeTestQrcodes == null or p.includeTestQrcodes == false'>",
" AND q.is_test = 0",
" 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}",
@@ -346,11 +523,9 @@ public interface DashboardMapper {
" '退款金额' as type,",
" COALESCE(SUM(os.refund_amount), 0) as value",
"FROM order_statistics os",
"JOIN orders o ON os.order_id = o.id",
"JOIN qrcodes q ON o.code_id = q.code_id",
"WHERE 1=1",
"<if test='p.includeTestQrcodes == null or p.includeTestQrcodes == false'>",
" AND q.is_test = 0",
" 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}",
@@ -371,6 +546,35 @@ public interface DashboardMapper {
})
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 &lt;= #{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();
@@ -402,4 +606,28 @@ public interface DashboardMapper {
"</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 &lt;= #{p.endTime}",
"</if>",
"ORDER BY o.create_time DESC",
"LIMIT 20",
"</script>"
})
List<Map<String, Object>> debugTimeRangeQuery(@Param("p") Map<String, Object> params);
}
@@ -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);
}
@@ -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;
}
}
@@ -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;
}
}
@@ -1,33 +1,44 @@
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对象
*/
private CtripOrderBody body;
@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;
}
@@ -35,34 +46,61 @@ public class CtripCreateOrderRequest {
* 携程订单体
*/
@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;
private List<Object> adjunctions;
@JsonProperty("adjunctions")
private List<String> adjunctions;
@JsonProperty("price")
private java.math.BigDecimal price;
@JsonProperty("PLU")
private String PLU;
private Object deposit;
@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;
}
@@ -70,29 +108,53 @@ public class CtripCreateOrderRequest {
* 携程乘客信息
*/
@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;
}
@@ -100,12 +162,19 @@ public class CtripCreateOrderRequest {
* 携程联系人信息
*/
@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;
}
@@ -113,7 +182,9 @@ public class CtripCreateOrderRequest {
* 携程快递信息
*/
@Data
@JsonIgnoreProperties(ignoreUnknown = true)
public static class CtripExpressDelivery {
@JsonProperty("type")
private String type;
}
}
@@ -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;
}
}
@@ -16,4 +16,7 @@ public class ChartStatistics {
@Schema(description = "收入构成")
private List<IncomeDataVO> incomeBreakdown;
@Schema(description = "二维码订单数量")
private List<QrcodeOrderDataVO> qrcodeOrderCount;
}
@@ -20,15 +20,24 @@ public class OrderStatistics {
@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 platformAmount;
@Schema(description = "景区分账金额(分)")
private Long tourismAmount;
@Schema(description = "退款金额(分)")
private Long refundAmount;
@@ -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;
}
@@ -77,4 +77,14 @@ public interface ICouponService extends IService<Coupon> {
* 校验手机号+携程券ID是否已存在
*/
boolean existsByUserPhoneAndCtripCouponId(String userPhone, String ctripCouponId);
/**
* 根据携程优惠券ID查询优惠券
*/
Coupon getByCtripCouponId(String ctripCouponId);
/**
* 更新优惠券为已核销状态
*/
boolean updateCouponConsumed(Long couponId, String orderNo, String consumedTime);
}
@@ -1,13 +1,19 @@
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 {
/**
* 获取首页统计数据
* @param params 筛选参数
*/
DashboardStatisticsVO getDashboardStatistics(Map<String, Object> params);
/**
* 获取首页订单列表
*/
PageResult<com.central.order.model.Order> getDashboardOrders(Map<String, Object> params);
}
@@ -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);
}
@@ -149,13 +149,18 @@ public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> impleme
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: {}", ctripCouponId);
log.warn("携程优惠券已存在,ctripCouponId: {}, 优惠券ID: {}", ctripCouponId, existingCoupon.getId());
return true; // 已存在也算成功
}
log.info("携程优惠券不存在,开始创建新优惠券");
Coupon coupon = new Coupon();
coupon.setCouponNo(generateCouponNo());
coupon.setCouponName(couponName);
@@ -174,7 +179,18 @@ public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> impleme
coupon.setCreateBy("ctrip");
coupon.setUpdateBy("ctrip");
return save(coupon);
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
@@ -229,5 +245,57 @@ public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> impleme
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();
}
}
}
}
@@ -3,6 +3,8 @@ 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服务实现类
@@ -13,19 +15,39 @@ public class CtripApiServiceImpl implements ICtripApiService {
@Override
public boolean verifyCoupon(String ctripCouponId, String orderNo) {
// TODO: 实现具体的携程API调用逻辑
// 这里需要根据携程的API文档实现具体的调用
log.info("调用携程核销接口,ctripCouponId: {}, orderNo: {}", ctripCouponId, orderNo);
// 模拟API调用
try {
// 这里应该调用携程的核销API
// 例如:HttpClient调用携程的核销接口
// 根据携程API文档实现核销接口调用
// 这里需要根据实际的携程API接口进行实现
// 暂时返回true,实际需要根据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("携程核销接口调用失败", e);
log.error("携程核销接口调用失败,ctripCouponId: {}, orderNo: {}", ctripCouponId, orderNo, e);
return false;
}
}
@@ -11,6 +11,12 @@ 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
@@ -18,6 +24,7 @@ import java.util.Map;
public class DashboardServiceImpl implements IDashboardService {
private final DashboardMapper dashboardMapper;
private final IOrderService orderService;
@Override
public DashboardStatisticsVO getDashboardStatistics(Map<String, Object> params) {
@@ -40,6 +47,56 @@ 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();
}
}
/**
* 获取订单统计(包含对账数据)
*/
@@ -69,13 +126,35 @@ public class DashboardServiceImpl implements IDashboardService {
.multiply(new BigDecimal(100));
stats.setCompletionRate(completionRate);
}
// 设置总完成订单数
stats.setCompletedOrders(completedOrders);
// 获取对账相关数据
stats.setTotalAmount(dashboardMapper.getTotalAmount(params));
stats.setRefundAmount(dashboardMapper.getRefundAmount(params));
// 景区收入 = 总订单金额 - 退款金额
Long netIncome = (stats.getTotalAmount() != null ? stats.getTotalAmount() : 0)
- (stats.getRefundAmount() != null ? stats.getRefundAmount() : 0);
// 获取总收款订单数量
Long totalPaidOrders = dashboardMapper.getTotalPaidOrders(params);
stats.setTotalPaidOrders(totalPaidOrders);
// 获取今日收款订单数量
Long todayPaidOrders = dashboardMapper.getTodayPaidOrders(params);
stats.setTodayPaidOrders(todayPaidOrders);
// 获取退款订单数量
Long refundedOrders = dashboardMapper.getRefundedOrders(params);
stats.setRefundedOrders(refundedOrders);
// 获取今日退款订单数量
Long todayRefundedOrders = dashboardMapper.getTodayRefundedOrders(params);
stats.setTodayRefundedOrders(todayRefundedOrders);
// 获取对账相关数据 - 使用 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;
@@ -96,6 +175,9 @@ public class DashboardServiceImpl implements IDashboardService {
// 获取收入构成
stats.setIncomeBreakdown(dashboardMapper.getIncomeBreakdown(params));
// 获取二维码订单数量
stats.setQrcodeOrderCount(dashboardMapper.getQrcodeOrderCount(params));
return stats;
}
@@ -123,10 +123,10 @@ public class OrderServiceImpl extends SuperServiceImpl<OrderMapper, Order> imple
// 检查并处理订单超时逻辑,5分钟超时后自动取消
@Override
public void checkAndHandleOrderTimeout() {
log.info("开始检查订单超时情况");
log.debug("开始检查订单超时情况");
List<Order> orders = baseMapper.getOrdersByStatus(OrderStatus.UNPAID.getId());
log.info("查询到 {} 个待支付订单", orders.size());
log.debug("查询到 {} 个待支付订单", orders.size());
long currentTime = new Date().getTime();
int timeoutCount = 0;
@@ -135,7 +135,7 @@ public class OrderServiceImpl extends SuperServiceImpl<OrderMapper, Order> imple
long elapsedTime = currentTime - order.getCreateTime().getTime();
long elapsedMinutes = TimeUnit.MILLISECONDS.toMinutes(elapsedTime);
log.info("订单检查: orderNo={}, createTime={}, elapsedMinutes={}, userId={}, tourismId={}",
log.debug("订单检查: orderNo={}, createTime={}, elapsedMinutes={}, userId={}, tourismId={}",
order.getOrderNo(),
order.getCreateTime(),
elapsedMinutes,
@@ -149,7 +149,7 @@ public class OrderServiceImpl extends SuperServiceImpl<OrderMapper, Order> imple
}
}
log.info("订单超时检查完成: 总订单数={}, 超时取消数={}", orders.size(), timeoutCount);
log.debug("订单超时检查完成: 总订单数={}, 超时取消数={}", orders.size(), timeoutCount);
}
// 获取所有处于排队状态的订单,用于后续按顺序处理
@@ -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();
}
}
@@ -75,7 +75,7 @@ public class TourismServiceImpl extends SuperServiceImpl<TourismMapper, Tourism>
}
if (radius == null || radius <= 0) {
radius = 10.0; // 默认10公里
radius = 1000.0; // 默认10公里
}
if (limit == null || limit <= 0) {
@@ -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);
}
}
@@ -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: 正常分配逻辑
@@ -39,12 +39,14 @@ zlt:
- video_template
- profit_sharing
- order_statistics
- orders_refund
ignoreSqls:
# 移除所有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
# 微信支付商户号
@@ -138,3 +140,11 @@ cdn:
logging:
level:
com.central.order.controller.OrderFileController: DEBUG
# 携程API配置
ctrip:
aes:
key: 087b36ad0dff7942 # 请替换为实际的AES密钥
iv: 750e15a31356a99d # 请替换为实际的AES IV
sign:
key: ce6033ae31124ec5cdab3d2bc79f2622 # 请替换为实际的签名密钥
@@ -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");
}
}
@@ -26,10 +26,11 @@ zlt.fdfs.web-url=192.168.28.130
zlt.fdfs.trackerList=${zlt.fdfs.web-url}:22122
##### s3配置
zlt.s3.access-key=33RdDbIlEFK0z9IJHSqx
zlt.s3.accessKeySecret=mmfSh4gjJm8dck0KaG6fKItpIM3tenWVHS4Ygjlm
zlt.s3.endpoint=http://81.70.164.178:9000
zlt.s3.bucketName=gofly
zlt.s3.access-key=Hq78CaYg2BI6ZfxCRMKI
zlt.s3.accessKeySecret=DJCt5q9K7GQ2zcBEfr3twb1vQ6BgUW1LKFlI5NSw
zlt.s3.endpoint=http://220.205.16.27:9000
zlt.s3.bucketName=goflyapp
zlt.s3.region=us-east-1
zlt.oss.secretId=LTAI5tSNV1RvexXpMMCZhxSe
zlt.oss.secretKey=XocJRWU8emwjjvYLTrc04l91VZMkQK
@@ -55,6 +55,8 @@
"@umijs/route-utils": "^2.0.0",
"antd": "^4.20.0",
"classnames": "^2.3.0",
"echarts": "^5.6.0",
"echarts-for-react": "^3.0.2",
"file-saver": "^2.0.5",
"lodash": "^4.17.21",
"moment": "^2.29.0",
@@ -1,8 +1,9 @@
import { PageContainer } from '@ant-design/pro-components';
import { Card, Row, Col, Statistic, Progress, Typography, Select, DatePicker, Space, Button, Switch } from 'antd';
import { Card, Row, Col, Statistic, Progress, Typography, Select, DatePicker, Space, Button, Switch, Pagination } from 'antd';
import React, { useState, useEffect } from 'react';
import { dashboard, getQrcodeOptions } from '@/services/orders/api';
import { Area, Column, Pie } from '@ant-design/plots';
import { dashboard, getQrcodeOptions, getDashboardOrders } from '@/services/orders/api';
import { Line, Column, Pie } from '@ant-design/plots';
import ReactECharts from 'echarts-for-react';
import {
ShoppingCartOutlined,
PayCircleOutlined,
@@ -43,10 +44,12 @@ interface Statistics {
todayOrders: number;
orderGrowth: number;
completionRate: number;
// 新增对账维度
refundedOrders: number; // 退款订单数
completedOrders: number; // 总完成订单数
totalPaidOrders: number; // 总收款订单数
todayPaidOrders: number; // 今日收款订单数
// 对账相关字段
totalAmount: number; // 订单总金额(分)
platformAmount: number; // 平台分账金额(分)
tourismAmount: number; // 景区分账金额(分)
refundAmount: number; // 退款金额(分)
netIncome: number; // 净收入(分)
};
@@ -65,6 +68,11 @@ interface Statistics {
type: string;
value: number;
}[];
qrcodeOrderCount: {
qrcodeName: string;
qrcodeId: string;
orderCount: number;
}[];
};
// 新增筛选维度数据
filterOptions: {
@@ -87,6 +95,13 @@ const Welcome: React.FC = () => {
const [timeRange, setTimeRange] = useState<[string, string]>(['', '']);
// 新增是否包含测试二维码筛选,默认不包含
const [includeTestQrcodes, setIncludeTestQrcodes] = useState<boolean>(false);
// 订单列表数据
const [orderList, setOrderList] = useState<any[]>([]);
const [orderPagination, setOrderPagination] = useState({
current: 1,
pageSize: 10,
total: 0,
});
const fetchData = async () => {
try {
@@ -109,8 +124,34 @@ const Welcome: React.FC = () => {
}
};
const fetchOrderList = async (page = 1) => {
try {
const params = {
tourismId: selectedTourism,
qrcodeId: selectedQrcode,
startTime: timeRange[0],
endTime: timeRange[1],
includeTestQrcodes: includeTestQrcodes,
page: page,
limit: orderPagination.pageSize,
};
const result = await getDashboardOrders(params);
if (result.resp_code === 0) {
setOrderList(result.data?.data || []);
setOrderPagination(prev => ({
...prev,
current: page,
total: result.data?.count || 0,
}));
}
} catch (error) {
console.error('获取订单列表失败:', error);
}
};
useEffect(() => {
fetchData();
fetchOrderList(1); // 重置到第一页
}, [selectedTourism, selectedQrcode, timeRange, includeTestQrcodes]);
// 处理景区选择变化
@@ -158,12 +199,106 @@ const Welcome: React.FC = () => {
const chartStats = statistics.chartStats || {};
const filterOptions = statistics.filterOptions || {};
// 动态分账金额计算
// 使用后端返回的基础数据
// 订单总金额:orderStatus=3+orderStatus=8的总金额(包含逻辑删除记录)
// 退款金额:orderStatus=8的总金额(包含逻辑删除记录)
// 净收入:总金额 - 退款金额
const totalAmount = orderStats.totalAmount || 0;
const refundAmount = orderStats.refundAmount || 0;
const netIncome = orderStats.netIncome || 0;
// 判断是否选择了时间区间
const hasTimeRange = timeRange[0] && timeRange[1];
// 根据时间筛选状态动态显示标题
const getOrderTitle = () => {
if (hasTimeRange) {
return `订单总数 (${timeRange[0].split(' ')[0]} ~ ${timeRange[1].split(' ')[0]})`;
}
return '总订单数';
};
const getTodayTitle = () => {
if (hasTimeRange) {
return `区间订单数`;
}
return '今日订单';
};
const getTodayValue = () => {
if (hasTimeRange) {
return orderStats.totalOrders || 0; // 时间筛选时显示区间总订单数
}
return orderStats.todayOrders || 0; // 无时间筛选时显示今日订单数
};
const getTodayRefundTitle = () => {
if (hasTimeRange) {
return `区间退款订单`;
}
return '今日退款订单';
};
const getTodayRefundValue = () => {
if (hasTimeRange) {
return orderStats.refundedOrders || 0; // 时间筛选时显示区间退款订单数
}
return orderStats.todayRefundedOrders || 0; // 无时间筛选时显示今日退款订单数
};
// 获取订单状态文本
const getOrderStatusText = (status: number) => {
const statusMap: { [key: number]: string } = {
0: '待支付',
1: '已支付排队中',
2: '已取消',
3: '设备执行完成',
4: '正在服务中',
5: '素材上传中',
6: '素材上传完成',
7: '退款中',
8: '已退款',
9: '退款失败',
};
return statusMap[status] || '未知状态';
};
// 时间快捷选择处理函数
const handleQuickTimeSelect = (type: 'today' | 'week' | 'month') => {
const now = new Date();
let startDate: Date;
let endDate: Date;
switch (type) {
case 'today':
startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate());
endDate = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59, 59);
break;
case 'week':
const dayOfWeek = now.getDay();
const daysToSubtract = dayOfWeek === 0 ? 6 : dayOfWeek - 1; // 周一到周日
startDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() - daysToSubtract);
endDate = new Date(now.getFullYear(), now.getMonth(), now.getDate() + (6 - dayOfWeek), 23, 59, 59);
break;
case 'month':
startDate = new Date(now.getFullYear(), now.getMonth(), 1);
endDate = new Date(now.getFullYear(), now.getMonth() + 1, 0, 23, 59, 59);
break;
default:
return;
}
setTimeRange([
startDate.toISOString().slice(0, 19).replace('T', ' '),
endDate.toISOString().slice(0, 19).replace('T', ' ')
]);
};
// 动态分账金额计算(基于净收入和分账比例)
const platformAmount = Math.round(netIncome * platformRate);
const tourismAmount = netIncome - platformAmount;
// 订单趋势配置
// 订单趋势配置 - 改为折线图
const orderTrendConfig = {
data: chartStats.orderTrend || [],
xField: 'date',
@@ -174,47 +309,131 @@ const Welcome: React.FC = () => {
legend: {
position: 'top' as const,
},
areaStyle: {
fillOpacity: 0.6,
// 移除面积图样式,改为折线图
line: {
size: 2,
},
point: {
size: 4,
shape: 'circle',
},
color: ['#1890ff', '#52c41a', '#faad14'],
xAxis: {
type: 'time',
tickCount: 7,
},
yAxis: {
label: {
formatter: (v: any) => `${v}单`,
},
},
tooltip: {
shared: true,
showCrosshairs: true,
crosshairs: {
type: 'xy' as const,
},
},
};
// 订单分布配置
const orderDistConfig = {
data: chartStats.orderDistribution || [],
angleField: 'value',
colorField: 'type',
radius: 0.8,
label: {
type: 'outer',
content: '{name} {percentage}',
// 二维码订单数量配置 - ECharts 横向柱状图(按数量降序排列)
const qrcodeOrderData = (chartStats.qrcodeOrderCount || []).sort((a: any, b: any) => b.orderCount - a.orderCount);
// 确保数据按订单数量从多到少排列,最多的显示在最上面
const sortedData = [...qrcodeOrderData].sort((a: any, b: any) => b.orderCount - a.orderCount);
const qrcodeOrderConfig = {
tooltip: {
trigger: 'axis',
axisPointer: {
type: 'shadow'
},
formatter: function(params: any) {
const data = params[0];
const total = sortedData.reduce((sum: number, item: any) => sum + item.orderCount, 0);
const percentage = ((data.value / total) * 100).toFixed(2);
return `${data.name}<br/>订单数量: ${data.value}单<br/>占比: ${percentage}%`;
}
},
grid: {
left: '15%',
right: '15%',
bottom: '3%',
top: '3%',
containLabel: true
},
xAxis: {
type: 'value',
name: '订单数量',
axisLabel: {
formatter: '{value}单',
fontSize: 12
},
nameTextStyle: {
fontSize: 12
}
},
yAxis: {
type: 'category',
name: '二维码',
data: sortedData.map((item: any) => item.qrcodeName),
axisLabel: {
width: 120,
overflow: 'truncate',
fontSize: 12
},
nameTextStyle: {
fontSize: 12
}
},
series: [
{
name: '订单数量',
type: 'bar',
data: sortedData.map((item: any) => {
const total = sortedData.reduce((sum: number, dataItem: any) => sum + dataItem.orderCount, 0);
const percentage = ((item.orderCount / total) * 100).toFixed(2);
return {
value: item.orderCount,
itemStyle: {
color: '#52c41a' // 绿色,与图片中的颜色一致
}
};
}),
itemStyle: {
color: '#52c41a'
},
label: {
show: true,
position: 'right',
formatter: function(params: any) {
const total = sortedData.reduce((sum: number, item: any) => sum + item.orderCount, 0);
const percentage = ((params.value / total) * 100).toFixed(2);
return `${params.value}单 (${percentage}%)`;
},
fontSize: 11,
color: '#666'
},
barWidth: '60%'
}
]
};
// 收入构成图表数据
const incomeConfig = {
data: [
{ type: '平台分账', value: platformAmount / 100 },
{ type: '景区分账', value: tourismAmount / 100 },
{ type: '退款金额', value: (orderStats.refundAmount || 0) / 100 },
],
xField: 'type',
yField: 'value',
label: {
position: 'middle' as const,
style: {
fill: '#FFFFFF',
opacity: 0.6,
},
},
};
return (
<PageContainer className={styles.container}>
{/* 筛选条件 */}
<Card style={{ marginBottom: 16 }}>
<Space size="large">
<span>筛选条件:</span>
{hasTimeRange && (
<span style={{ color: '#1890ff', fontSize: '12px' }}>
⚠️ 已选择时间区间,统计数据将基于选定时间范围计算
</span>
)}
<Select
placeholder="选择景区"
style={{ width: 200 }}
@@ -250,18 +469,23 @@ const Welcome: React.FC = () => {
<span style={{ color: '#666', fontSize: '12px' }}>
(当前:平台{Math.round(platformRate * 100)}% | 景区{Math.round((1 - platformRate) * 100)}%)
</span>
{/* 快速选择常用分账比例 */}
{/* 时间快捷选择 */}
<Space size="small">
<span style={{ color: '#666', fontSize: '12px' }}>快速选择:</span>
{[0.7, 0.6, 0.5, 0.4, 0.3].map(rate => (
<span style={{ color: '#666', fontSize: '12px' }}>时间快捷选择:</span>
{[
{ key: 'today', label: '今日' },
{ key: 'week', label: '本周' },
{ key: 'month', label: '本月' }
].map(item => (
<Button
key={rate}
key={item.key}
size="small"
type={platformRate === rate ? 'primary' : 'default'}
onClick={() => setPlatformRate(rate)}
type={timeRange[0] && timeRange[1] ? 'primary' : 'default'}
onClick={() => handleQuickTimeSelect(item.key as 'today' | 'week' | 'month')}
style={{ fontSize: '11px', padding: '0 6px' }}
>
{Math.round(rate * 100)}%
{item.label}
</Button>
))}
</Space>
@@ -307,21 +531,29 @@ const Welcome: React.FC = () => {
<ShoppingCartOutlined className={styles.iconOrders} />
<span>订单总览</span>
</div>
<div className="subStats___2WPW1">
<Statistic
title="总订单数"
title={getOrderTitle()}
value={orderStats.totalOrders || 0}
suffix={
<span className={styles.trend}>
<RiseOutlined /> {orderStats.orderGrowth || 0}%
</span>
}
/>
<div className={styles.subStats}>
<Statistic title="今日订单" value={orderStats.todayOrders || 0} />
<Statistic
title="完成率"
value={orderStats.completionRate || 0}
suffix="%"
title="总收款数量"
value={orderStats.totalPaidOrders || 0}
/>
<Statistic
title="总退款订单数"
value={orderStats.refundedOrders || 0}
/>
</div>
<div className={styles.subStats}>
<Statistic title={getTodayTitle()} value={getTodayValue()} />
<Statistic
title="今日收款数量"
value={orderStats.todayPaidOrders || 0}
/>
<Statistic
title={getTodayRefundTitle()}
value={getTodayRefundValue()}
/>
</div>
</Card>
@@ -334,14 +566,14 @@ const Welcome: React.FC = () => {
<span>收入统计</span>
</div>
<Statistic
title="订单总金额"
title="订单总金额 (完成+退款)"
value={(orderStats.totalAmount || 0) / 100}
precision={2}
prefix="¥"
/>
<div className={styles.subStats}>
<Statistic
title="景区净收入"
title="净收入"
value={netIncome / 100}
precision={2}
prefix="¥"
@@ -381,6 +613,7 @@ const Welcome: React.FC = () => {
status="active"
format={(percent) => `分账率 ${percent?.toFixed(1)}%`}
/>
</div>
</Card>
</Col>
@@ -389,22 +622,85 @@ const Welcome: React.FC = () => {
{/* 图表展示 */}
<Row gutter={[16, 16]} className={styles.chartsRow}>
<Col xs={24} lg={16}>
<Card title="订单趋势" loading={loading}>
<Area {...orderTrendConfig} height={300} />
<Card title="订单趋势折线图(创建/完成/退款)" loading={loading}>
<Line {...orderTrendConfig} height={300} />
</Card>
</Col>
<Col xs={24} lg={8}>
<Card title="订单状态分布" loading={loading}>
<Pie {...orderDistConfig} height={300} />
<Card title="二维码订单数量" loading={loading}>
<ReactECharts
option={qrcodeOrderConfig}
style={{ height: '300px' }}
notMerge={true}
/>
</Card>
</Col>
</Row>
{/* 收入构成 */}
<Row gutter={[16, 16]}>
{/* 订单列表 */}
<Row gutter={[16, 16]} style={{ marginTop: 24 }}>
<Col xs={24}>
<Card title="收入构成分析" loading={loading}>
<Column {...incomeConfig} height={300} />
<Card title="最新订单列表" loading={loading}>
<div style={{ maxHeight: '400px', overflowY: 'auto' }}>
{orderList.length > 0 ? (
<div>
{orderList.map((order, index) => (
<div
key={order.id || index}
style={{
padding: '12px',
borderBottom: '1px solid #f0f0f0',
display: 'flex',
justifyContent: 'space-between',
alignItems: 'center',
}}
>
<div style={{ flex: 1 }}>
<div style={{ fontWeight: 'bold', marginBottom: '4px' }}>
订单号: {order.orderNo}
</div>
<div style={{ fontSize: '12px', color: '#666' }}>
创建时间: {order.createTime}
</div>
<div style={{ fontSize: '12px', color: '#666' }}>
状态: {getOrderStatusText(order.orderStatus)}
</div>
</div>
<div style={{ textAlign: 'right' }}>
<div style={{ fontWeight: 'bold', color: '#1890ff' }}>
¥{(order.orderAmount / 100).toFixed(2)}
</div>
<div style={{ fontSize: '12px', color: '#666' }}>
用户ID: {order.userId}
</div>
</div>
</div>
))}
</div>
) : (
<div style={{ textAlign: 'center', padding: '40px', color: '#999' }}>
暂无订单数据
</div>
)}
</div>
{/* 分页组件 */}
{orderPagination.total > 0 && (
<div style={{ textAlign: 'center', marginTop: '16px' }}>
<Pagination
current={orderPagination.current}
pageSize={orderPagination.pageSize}
total={orderPagination.total}
showSizeChanger={false}
showQuickJumper
showTotal={(total, range) =>
`第 ${range[0]}-${range[1]} 条,共 ${total} 条`
}
onChange={(page) => {
fetchOrderList(page);
}}
/>
</div>
)}
</Card>
</Col>
</Row>
@@ -1,4 +1,4 @@
import { order, updateOrder, getOrderDetail } from '@/services/orders/api';
import { order, updateOrder, getOrderDetail, tourism } from '@/services/orders/api';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import {
PageContainer,
@@ -8,7 +8,7 @@ import {
ProFormSelect,
} from '@ant-design/pro-components';
import { Typography, Space, Tag, message } from 'antd';
import React, { useRef, useState, useCallback } from 'react';
import React, { useRef, useState, useCallback, useEffect } from 'react';
import { STATUS_CONFIG, STATUS_OPTIONS } from './constants';
import UpdateForm from './components/UpdateForm';
import DetailModal from './components/DetailModal';
@@ -23,6 +23,7 @@ const TableList: React.FC = () => {
const [detailModalVisible, setDetailModalVisible] = useState<boolean>(false);
const [detailData, setDetailData] = useState<API.OrderDetail>();
const [detailLoading, setDetailLoading] = useState<boolean>(false);
const [tourismOptions, setTourismOptions] = useState<{ label: string; value: number; }[]>([]);
// 渲染状态标签
const renderStatus = useCallback((status: number) => {
@@ -55,6 +56,32 @@ const TableList: React.FC = () => {
}
}, [currentRow]);
// 获取景区选项
const fetchTourismOptions = async () => {
try {
// 调用真实的景区列表API
const result = await tourism({
current: 1,
pageSize: 1000, // 获取所有景区
});
if (result.data && result.data.length > 0) {
// 将景区数据转换为选项格式
const options = result.data.map((item: any) => ({
label: item.tourismName || item.name || `景区${item.id}`,
value: item.id,
}));
setTourismOptions(options);
} else {
setTourismOptions([]);
}
} catch (error) {
console.error('获取景区选项失败:', error);
message.error('获取景区列表失败');
setTourismOptions([]);
}
};
// 获取订单详情
const handleViewDetail = async (orderNo: string) => {
setDetailModalVisible(true);
@@ -76,6 +103,11 @@ const TableList: React.FC = () => {
}
};
// 组件加载时获取景区选项
useEffect(() => {
fetchTourismOptions();
}, []);
const columns: ProColumns<ORDERS.Order>[] = [
{
dataIndex: 'index',
@@ -187,6 +219,7 @@ const TableList: React.FC = () => {
const params = {
orderNo: values.orderNo?.trim(), // 去除空格
orderStatus: values.orderStatus, // 状态
tourismId: values.tourismId, // 景区ID
};
// 过滤掉空值
const validParams = Object.fromEntries(
@@ -207,6 +240,13 @@ const TableList: React.FC = () => {
options={STATUS_OPTIONS}
allowClear
/>
<ProFormSelect
name="tourismId"
label="景区"
placeholder="请选择景区"
options={tourismOptions}
allowClear
/>
</QueryFilter>
<ProTable<ORDERS.Order>
@@ -214,12 +254,13 @@ const TableList: React.FC = () => {
headerTitle="订单列表"
request={async (params) => {
// 处理表格请求参数
const { current, pageSize, orderNo, orderStatus } = params;
const { current, pageSize, orderNo, orderStatus, tourismId } = params;
const result = await order({
current,
pageSize,
orderNo,
orderStatus: orderStatus ? Number(orderStatus) : undefined,
tourismId: tourismId ? Number(tourismId) : undefined,
});
return result;
}}
@@ -230,8 +271,8 @@ const TableList: React.FC = () => {
pagination={{
showSizeChanger: true,
showQuickJumper: true,
defaultPageSize: 10,
pageSizeOptions: ['10', '20', '50'],
defaultPageSize: 20,
pageSizeOptions: ['10', '20', '50', '100'],
}}
dateFormatter="string"
toolbar={{
@@ -23,6 +23,7 @@ interface CreateFormProps {
tourismOptions: any[];
waylineOptions: any[];
deviceOptions: any[];
tenantOptions: any[];
}
const CreateForm: React.FC<CreateFormProps> = ({
@@ -33,6 +34,7 @@ const CreateForm: React.FC<CreateFormProps> = ({
tourismOptions,
waylineOptions,
deviceOptions,
tenantOptions,
}) => {
// 使用 Form.useWatch 监听 enableProfit 的值
const [form] = Form.useForm();
@@ -200,6 +202,24 @@ const CreateForm: React.FC<CreateFormProps> = ({
tooltip="测试二维码的数据不会计入正式统计"
/>
</ProForm.Group>
<ProForm.Group>
<ProFormSelect
width="md"
name="tenantId"
label="应用ID"
options={tenantOptions}
rules={[{ required: true, message: '请选择应用' }]}
placeholder="请选择应用"
showSearch
fieldProps={{
loading: !tenantOptions.length,
filterOption: (input, option) =>
(option?.label ?? '').toLowerCase().includes(input.toLowerCase()),
notFoundContent: tenantOptions.length === 0 ? '暂无应用数据' : undefined,
}}
/>
</ProForm.Group>
</ModalForm>
);
};
@@ -25,6 +25,7 @@ interface UpdateFormProps {
tourismOptions: any[];
waylineOptions: any[];
deviceOptions: any[];
tenantOptions: any[];
}
const UpdateForm: React.FC<UpdateFormProps> = ({
@@ -36,6 +37,7 @@ const UpdateForm: React.FC<UpdateFormProps> = ({
tourismOptions,
waylineOptions,
deviceOptions,
tenantOptions,
}) => {
const [form] = Form.useForm();
const enableProfit = Form.useWatch('enableProfit', form);
@@ -199,6 +201,24 @@ const UpdateForm: React.FC<UpdateFormProps> = ({
tooltip="测试二维码的数据不会计入正式统计"
/>
</ProForm.Group>
<ProForm.Group>
<ProFormSelect
width="md"
name="tenantId"
label="应用ID"
options={tenantOptions}
rules={[{ required: true, message: '请选择应用' }]}
placeholder="请选择应用"
showSearch
fieldProps={{
loading: !tenantOptions.length,
filterOption: (input, option) =>
(option?.label ?? '').toLowerCase().includes(input.toLowerCase()),
notFoundContent: tenantOptions.length === 0 ? '暂无应用数据' : undefined,
}}
/>
</ProForm.Group>
</ModalForm>
);
};
@@ -1,4 +1,4 @@
import { deleteQrcode, qrcode, saveOrUpdateQrcode, getTourismList, getVideoTemplateList } from '@/services/orders/api';
import { deleteQrcode, qrcode, saveOrUpdateQrcode, getTourismList, getVideoTemplateList, getTenantList } from '@/services/orders/api';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import {
@@ -93,6 +93,7 @@ const TableList: React.FC = () => {
const [tourismOptions, setTourismOptions] = useState<any[]>([]);
const [deviceOptions, setDeviceOptions] = useState<any[]>([]);
const [templateOptions, setTemplateOptions] = useState<any[]>([]);
const [tenantOptions, setTenantOptions] = useState<any[]>([]);
const formRef = useRef();
// 将 renderStatus 函数移到组件内部
@@ -243,12 +244,32 @@ const TableList: React.FC = () => {
}
}, []);
const fetchTenantOptions = useCallback(async () => {
try {
const result = await getTenantList({
page: 1,
limit: 100,
});
if (result?.data) {
const options = result.data.map((item: any) => ({
label: item.clientName || item.clientId,
value: item.clientId,
info: item,
}));
setTenantOptions(options);
}
} catch (error) {
message.error('获取应用列表失败');
}
}, []);
useEffect(() => {
fetchTourismList();
fetchWaylineOptions();
fetchDeviceList();
fetchTemplateOptions();
}, [fetchTourismList, fetchWaylineOptions, fetchDeviceList, fetchTemplateOptions]);
fetchTenantOptions();
}, [fetchTourismList, fetchWaylineOptions, fetchDeviceList, fetchTemplateOptions, fetchTenantOptions]);
const columns: ProColumns<ORDERS.Qrcode>[] = [
{
@@ -438,6 +459,16 @@ const TableList: React.FC = () => {
1: { text: '是' },
},
},
{
title: '应用ID',
dataIndex: 'tenantId',
width: 120,
ellipsis: true,
render: (_, record) => {
const tenant = tenantOptions.find(item => item.value === record.tenantId);
return tenant?.label || record.tenantId || '-';
},
},
{
title: '操作',
key: 'action',
@@ -506,6 +537,19 @@ const TableList: React.FC = () => {
placeholder="请选择是否为测试二维码"
options={IS_TEST_OPTIONS}
/>
<ProFormSelect
name="tenantId"
label="应用ID"
placeholder="请选择应用"
options={tenantOptions}
fieldProps={{
loading: !tenantOptions.length,
showSearch: true,
filterOption: (input, option) =>
(option?.label ?? '').toLowerCase().includes(input.toLowerCase()),
notFoundContent: tenantOptions.length === 0 ? '暂无应用数据' : undefined,
}}
/>
</QueryFilter>
<ProTable<ORDERS.Qrcode>
rowKey="id"
@@ -543,6 +587,7 @@ const TableList: React.FC = () => {
fetchDeviceList();
fetchTourismList();
fetchTemplateOptions();
fetchTenantOptions();
}
}}
visible={createModalVisible}
@@ -550,6 +595,7 @@ const TableList: React.FC = () => {
tourismOptions={tourismOptions}
waylineOptions={waylineOptions}
deviceOptions={deviceOptions}
tenantOptions={tenantOptions}
/>
<UpdateForm
onSubmit={async (values) => {
@@ -561,6 +607,7 @@ const TableList: React.FC = () => {
fetchDeviceList();
fetchTourismList();
fetchTemplateOptions();
fetchTenantOptions();
}
if (!visible) {
setCurrentRow(undefined);
@@ -572,6 +619,7 @@ const TableList: React.FC = () => {
tourismOptions={tourismOptions}
deviceOptions={deviceOptions}
templateOptions={templateOptions}
tenantOptions={tenantOptions}
/>
</PageContainer>
);
@@ -19,6 +19,7 @@ interface UpdateFormProps {
onVisibleChange: (visible: boolean) => void;
updateModalVisible: boolean;
values?: ORDERS.Tourism;
tenantOptions?: any[];
}
const UpdateForm: React.FC<UpdateFormProps> = ({
@@ -26,6 +27,7 @@ const UpdateForm: React.FC<UpdateFormProps> = ({
onVisibleChange,
updateModalVisible,
values,
tenantOptions = [],
}) => {
// 表单字段验证规则
const formRules = {
@@ -118,11 +120,19 @@ const UpdateForm: React.FC<UpdateFormProps> = ({
</ProForm.Group>
<ProForm.Group>
<ProFormText
<ProFormSelect
name="tenantId"
label="租户ID"
label="应用ID"
width="md"
placeholder="请输入租户ID"
options={tenantOptions}
placeholder="请选择应用"
showSearch
fieldProps={{
loading: !tenantOptions.length,
filterOption: (input, option) =>
(option?.label ?? '').toLowerCase().includes(input.toLowerCase()),
notFoundContent: tenantOptions.length === 0 ? '暂无应用数据' : undefined,
}}
/>
</ProForm.Group>
@@ -1,5 +1,5 @@
import UpdateForm from '@/pages/orders/Tourism/components/UpdateForm';
import { tourism, saveOrUpdateTourism, deleteTourism } from '@/services/orders/api';
import { tourism, saveOrUpdateTourism, deleteTourism, getTenantList } from '@/services/orders/api';
import { PlusOutlined } from '@ant-design/icons';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import {
@@ -13,7 +13,7 @@ import {
ProFormDigit,
} from '@ant-design/pro-components';
import { Typography, message, Popconfirm, Button, Space, Tag } from 'antd';
import React, { useRef, useState, useCallback } from 'react';
import React, { useRef, useState, useCallback, useEffect } from 'react';
const { Link } = Typography;
@@ -59,6 +59,7 @@ const TableList: React.FC = () => {
const [createModalVisible, setCreateModalVisible] = useState<boolean>(false);
const [updateModalVisible, setUpdateModalVisible] = useState<boolean>(false);
const [currentRow, setCurrentRow] = useState<ORDERS.Tourism>();
const [tenantOptions, setTenantOptions] = useState<any[]>([]);
// 表格操作处理
const handleTableAction = useCallback(async (
@@ -105,6 +106,31 @@ const TableList: React.FC = () => {
}
}, []);
// 获取应用列表
const fetchTenantOptions = useCallback(async () => {
try {
const result = await getTenantList({
page: 1,
limit: 100,
});
if (result?.data) {
const options = result.data.map((item: any) => ({
label: item.clientName || item.clientId,
value: item.clientId,
info: item,
}));
setTenantOptions(options);
}
} catch (error) {
message.error('获取应用列表失败');
}
}, []);
// 组件加载时获取应用列表
useEffect(() => {
fetchTenantOptions();
}, [fetchTenantOptions]);
// 表格列定义
const columns: ProColumns<ORDERS.Tourism>[] = [
{
@@ -160,10 +186,14 @@ const TableList: React.FC = () => {
},
},
{
title: '租户ID',
title: '应用ID',
dataIndex: 'tenantId',
copyable: true,
hideInSearch: true,
render: (_, record) => {
const tenant = tenantOptions.find(item => item.value === record.tenantId);
return tenant?.label || record.tenantId || '-';
},
},
{
title: '状态',
@@ -320,11 +350,19 @@ const TableList: React.FC = () => {
</ProForm.Group>
<ProForm.Group>
<ProFormText
<ProFormSelect
name="tenantId"
label="租户ID"
label="应用ID"
width="md"
placeholder="请输入租户ID(可选,不填将自动获取当前租户)"
options={tenantOptions}
placeholder="请选择应用(可选,不填将自动获取当前应用)"
showSearch
fieldProps={{
loading: !tenantOptions.length,
filterOption: (input, option) =>
(option?.label ?? '').toLowerCase().includes(input.toLowerCase()),
notFoundContent: tenantOptions.length === 0 ? '暂无应用数据' : undefined,
}}
/>
</ProForm.Group>
@@ -349,6 +387,7 @@ const TableList: React.FC = () => {
onVisibleChange={setUpdateModalVisible}
updateModalVisible={updateModalVisible}
values={currentRow}
tenantOptions={tenantOptions}
/>
</PageContainer>
);
@@ -198,6 +198,23 @@ export async function dashboard(params?: {
});
}
/** 获取首页订单列表 GET /api-order/dashboard/orders */
export async function getDashboardOrders(params?: {
tourismId?: number;
qrcodeId?: string;
deviceSn?: string;
startTime?: string;
endTime?: string;
includeTestQrcodes?: boolean;
page?: number;
limit?: number;
}) {
return request('/api-order/dashboard/orders', {
method: 'GET',
params,
});
}
/** 获取二维码列表 GET /api-order/qrcode/options */
export async function getQrcodeOptions(params?: {
tourismId?: number;
@@ -453,3 +470,14 @@ export async function generateEditTask(orderNo: string) {
params: { orderNo },
});
}
// 获取应用列表(作为租户列表)
export async function getTenantList(params: {
page: number;
limit: number;
[key: string]: any;
}) {
return request('/api-uaa/clients/all', {
method: 'GET',
});
}
@@ -148,8 +148,6 @@ declare namespace ORDERS {
completionRate: number;
// 对账相关字段
totalAmount: number; // 订单总金额(分)
platformAmount: number; // 平台分账金额(分)
tourismAmount: number; // 景区分账金额(分)
refundAmount: number; // 退款金额(分)
netIncome: number; // 净收入(分)
};
+255
View File
@@ -0,0 +1,255 @@
# 携程标准响应码说明
## 概述
根据[携程API平台标准](https://open.trip.com/apiplatform/order.jsp#tag/%E8%BF%94%E5%9B%9E%E7%A0%81),我方接口需要返回标准的响应码,只有返回正确的响应码,携程方才能做对应的逻辑处理。
## 响应码分类
### 1. 成功响应码
- **0000** - 操作成功
- 说明:请求处理成功,业务逻辑正常执行
- 使用场景:订单创建成功、优惠券创建成功、核销成功等
### 2. 系统错误码 (1000-1999)
#### 1000 - 系统错误
- 说明:系统内部错误,无法处理的异常
- 使用场景:数据库连接失败、系统崩溃等
#### 1001 - 参数错误
- 说明:请求参数格式错误或缺少必要参数
- 使用场景:缺少手机号、订单号格式错误等
#### 1002 - 签名验证失败
- 说明:请求签名验证失败
- 使用场景:签名算法错误、密钥不匹配等
#### 1003 - 时间戳错误
- 说明:请求时间戳无效或过期
- 使用场景:请求时间超出允许范围
#### 1004 - 版本号错误
- 说明:API版本号不支持
- 使用场景:携程使用旧版本API调用新版本接口
### 3. 业务错误码 (2000-2999)
#### 2000 - 订单不存在
- 说明:请求的订单在系统中不存在
- 使用场景:查询不存在的订单
#### 2001 - 订单已存在
- 说明:订单已存在,重复创建
- 使用场景:幂等性校验失败
#### 2002 - 订单状态错误
- 说明:订单状态不允许当前操作
- 使用场景:已取消订单无法核销
#### 2003 - 优惠券不存在
- 说明:请求的优惠券不存在
- 使用场景:查询不存在的优惠券
#### 2004 - 优惠券已使用
- 说明:优惠券已被使用,无法重复使用
- 使用场景:核销已使用的优惠券
#### 2005 - 优惠券已过期
- 说明:优惠券已超过有效期
- 使用场景:使用过期优惠券
#### 2006 - 优惠券余额不足
- 说明:优惠券余额不足以支付订单
- 使用场景:部分支付场景
#### 2007 - 用户不存在
- 说明:请求的用户在系统中不存在
- 使用场景:查询不存在的用户
#### 2008 - 产品不存在
- 说明:请求的产品不存在
- 使用场景:查询不存在的产品
#### 2009 - 产品不可用
- 说明:产品当前不可用
- 使用场景:产品已下架或库存不足
### 4. 网络错误码 (3000-3999)
#### 3000 - 网络连接错误
- 说明:网络连接异常
- 使用场景:网络超时、连接中断等
#### 3001 - 请求超时
- 说明:请求处理超时
- 使用场景:长时间未响应的请求
#### 3002 - 服务不可用
- 说明:服务暂时不可用
- 使用场景:服务维护、负载过高
### 5. 权限错误码 (4000-4999)
#### 4000 - 未授权访问
- 说明:请求未通过身份验证
- 使用场景:缺少认证信息
#### 4001 - 访问被拒绝
- 说明:请求被拒绝访问
- 使用场景:权限不足
#### 4002 - 账户已禁用
- 说明:账户已被禁用
- 使用场景:违规账户
### 6. 数据错误码 (5000-5999)
#### 5000 - 数据不存在
- 说明:请求的数据不存在
- 使用场景:查询不存在的数据
#### 5001 - 数据格式错误
- 说明:数据格式不符合要求
- 使用场景:JSON格式错误、编码问题
#### 5002 - 数据冲突
- 说明:数据存在冲突
- 使用场景:并发操作冲突
### 7. 第三方服务错误码 (6000-6999)
#### 6000 - 第三方服务错误
- 说明:第三方服务调用失败
- 使用场景:支付服务、短信服务等
#### 6001 - 支付服务错误
- 说明:支付服务异常
- 使用场景:支付失败、退款失败
#### 6002 - 短信服务错误
- 说明:短信服务异常
- 使用场景:验证码发送失败
#### 6003 - 邮件服务错误
- 说明:邮件服务异常
- 使用场景:邮件发送失败
## 响应格式
### 成功响应格式
```json
{
"header": {
"requestTime": "2024-12-19 10:30:00",
"accountId": "ctrip_account",
"sign": "signature",
"serviceName": "CreateOrder",
"version": "1.0"
},
"resultCode": "0000",
"resultMessage": "操作成功",
"body": {
"otaOrderId": "CT123456",
"supplierOrderId": "COUPON_1734567890123",
"supplierConfirmType": 1,
"voucherSender": 1,
"orderExtendMessage": "优惠券创建成功",
"items": [
{
"itemId": "1",
"supplierItemId": "COUPON_ITEM_1734567890123",
"status": 1,
"message": "优惠券创建成功"
}
]
}
}
```
### 错误响应格式
```json
{
"header": {
"requestTime": "2024-12-19 10:30:00",
"accountId": "ctrip_account",
"sign": "signature",
"serviceName": "CreateOrder",
"version": "1.0"
},
"resultCode": "1001",
"resultMessage": "参数错误"
}
```
## 使用示例
### 1. 优惠券创建成功
```java
// 使用标准工具类构建响应
CtripCreateOrderResponse response = CtripResponseCodeUtil.buildCreateOrderSuccessResponse(
request,
"CT123456",
"COUPON_1734567890123",
"优惠券创建成功"
);
```
### 2. 参数错误
```java
// 使用标准错误码
CtripCreateOrderResponse response = CtripResponseCodeUtil.buildCreateOrderErrorResponse(
request,
CtripResponseCodeUtil.CtripResponseCodes.PARAM_ERROR,
CtripResponseCodeUtil.CtripResponseCodes.PARAM_ERROR_MESSAGE
);
```
### 3. 异常处理
```java
try {
// 业务逻辑
} catch (Exception e) {
String resultCode = CtripResponseCodeUtil.getResultCodeByException(e);
String resultMessage = CtripResponseCodeUtil.getResultMessageByException(e);
return CtripResponseCodeUtil.buildCreateOrderErrorResponse(request, resultCode, resultMessage);
}
```
## 验证规则
### 1. 响应码格式验证
- 必须为4位数字字符串
- 范围:0000-9999
- 不能为空或null
### 2. 响应码分类验证
```java
String category = CtripResponseCodeUtil.getResponseCodeCategory("1001");
// 返回: "SYSTEM_ERROR"
```
### 3. 响应码有效性验证
```java
boolean isValid = CtripResponseCodeUtil.isValidResponseCode("1001");
// 返回: true
```
## 注意事项
1. **标准性**:必须严格按照携程API平台标准返回响应码
2. **一致性**:所有携程相关接口都应使用统一的响应码
3. **可读性**:错误消息应该清晰明确,便于问题定位
4. **日志记录**:所有响应都应该记录日志,便于问题追踪
5. **异常处理**:系统异常应该映射到合适的标准响应码
## 工具类使用
项目已提供 `CtripResponseCodeUtil` 工具类,包含:
- 标准响应码定义
- 响应构建方法
- 异常映射方法
- 验证方法
建议所有携程相关接口都使用此工具类来确保响应码的标准性和一致性。
+169
View File
@@ -0,0 +1,169 @@
# 智能租户分配功能使用说明
## 功能概述
智能租户分配功能实现了订单的自动分配策略:用户扫码下单时,系统会根据配置的比例自动将订单分配给景区租户或平台租户,实现平台从景区订单中抽取成本的目的。
## 核心逻辑
### 分配策略
- **默认比例**:10单景区 + 1单平台
- **分配规则**:按用户ID + 二维码ID的组合进行计数
- **平台租户ID**:默认为 `webApp`
### 统计逻辑
- **景区统计**:只统计景区租户ID的订单
- **平台统计**:只统计平台租户ID的订单
- **首页统计**:按景区ID统计(不受租户ID影响)
## 配置管理
### 1. 配置文件
在 `application.yml` 中添加配置:
```yaml
tenant:
allocation:
enabled: false # 是否启用功能
allocation-ratio: 10 # 分配比例
platform-tenant-id: "webApp" # 平台租户ID
debug: false # 调试模式
force-platform-tenant: false # 强制平台租户(测试用)
```
### 2. 动态配置接口
#### 获取当前配置
```bash
GET /api-order/tenant-allocation/config/current
```
#### 更新配置
```bash
POST /api-order/tenant-allocation/config/update
参数:
- enabled: 是否启用
- allocation-ratio: 分配比例
- platform-tenant-id: 平台租户ID
- debug: 调试模式
- force-platform-tenant: 强制平台租户
```
#### 启用功能
```bash
POST /api-order/tenant-allocation/config/enable
```
#### 禁用功能
```bash
POST /api-order/tenant-allocation/config/disable
```
#### 测试配置
```bash
POST /api-order/tenant-allocation/config/test
参数:
- userId: 用户ID
- qrCodeId: 二维码ID
- testCount: 测试订单数量
```
## 测试接口
### 1. 测试分配逻辑
```bash
GET /api-order/order/tenant-allocation/test
参数:
- userId: 用户ID
- qrCodeId: 二维码ID
- expectedCount: 期望订单数量
```
### 2. 模拟订单分配
```bash
POST /api-order/order/tenant-allocation/simulate
参数:
- userId: 用户ID
- qrCodeId: 二维码ID
- orderCount: 模拟订单数量
```
### 3. 获取分配统计
```bash
GET /api-order/order/tenant-allocation/statistics
参数:
- qrCodeId: 二维码ID
```
## 使用场景
### 场景1:启用智能分配
1. 启用功能:
```bash
POST /api-order/tenant-allocation/config/enable
```
2. 验证配置:
```bash
POST /api-order/tenant-allocation/config/test?userId=123&qrCodeId=456&testCount=22
```
3. 用户扫码下单,系统自动分配租户
### 场景2:测试分配逻辑
```bash
POST /api-order/order/tenant-allocation/simulate?userId=123&qrCodeId=456&orderCount=22
```
预期结果:
- 总订单:22单
- 景区订单:20单(90.9%)
- 平台订单:2单(9.1%)
### 场景3:强制平台租户(测试用)
```bash
POST /api-order/tenant-allocation/config/update?force-platform-tenant=true
```
所有订单都会分配给平台租户,用于测试平台统计功能。
## 注意事项
### 1. 数据一致性
- 订单创建时就确定租户ID,避免后续转移
- 统计查询按租户ID筛选,确保准确性
- 首页统计按景区ID,不受租户分配影响
### 2. 配置变更
- 配置变更只影响新创建的订单
- 已创建的订单租户ID不会改变
- 建议在业务低峰期进行配置变更
### 3. 监控建议
- 定期检查分配比例是否符合预期
- 监控平台和景区的订单统计
- 关注日志中的分配记录
### 4. 回滚方案
如果出现问题,可以快速禁用功能:
```bash
POST /api-order/tenant-allocation/config/disable
```
所有新订单都会分配给景区租户,恢复原有逻辑。
## 扩展功能
### 1. 自定义分配比例
可以通过配置调整分配比例:
```yaml
tenant:
allocation:
allocation-ratio: 5 # 5单景区 + 1单平台
```
### 2. 多平台租户支持
未来可以扩展支持多个平台租户,根据业务需求进行分配。
### 3. 动态配置持久化
当前配置是内存配置,重启后会恢复默认值。未来可以扩展为数据库配置,支持持久化存储。