Compare commits
9 Commits
47ef45054a
...
dev
| Author | SHA1 | Date | |
|---|---|---|---|
| a306f53336 | |||
| 8fca992e37 | |||
| 026824d31d | |||
| 1575bf504c | |||
| 47ae81ca9f | |||
| d9e4371735 | |||
| eadaa8c4dd | |||
| fa5260d583 | |||
| 0c4bdc3031 |
@@ -33,7 +33,29 @@
|
||||
"usedAt": 1776000797914,
|
||||
"industryId": "all"
|
||||
}
|
||||
],
|
||||
"d11a5ebd8e064cc19ff4a85b8d931dac": [
|
||||
{
|
||||
"expertId": "SeniorDeveloper",
|
||||
"name": "吴八哥",
|
||||
"profession": "高级开发工程师",
|
||||
"avatarUrl": "https://acc-1258344699.cos.accelerate.myqcloud.com/workbuddy/experts/avatars/02-Engineering/SeniorDeveloper/SeniorDeveloper.png",
|
||||
"promptUrl": "https://acc-1258344699.cos.accelerate.myqcloud.com/workbuddy/experts/experts/02-Engineering/SeniorDeveloper/SeniorDeveloper_zh.md",
|
||||
"usedAt": 1776443595917,
|
||||
"industryId": "02-Engineering"
|
||||
}
|
||||
],
|
||||
"e339ec20b1ef45479756bdfdf93c3654": [
|
||||
{
|
||||
"expertId": "SeniorDeveloper",
|
||||
"name": "吴八哥",
|
||||
"profession": "高级开发工程师",
|
||||
"avatarUrl": "https://acc-1258344699.cos.accelerate.myqcloud.com/workbuddy/experts/avatars/02-Engineering/SeniorDeveloper/SeniorDeveloper.png",
|
||||
"promptUrl": "https://acc-1258344699.cos.accelerate.myqcloud.com/workbuddy/experts/experts/02-Engineering/SeniorDeveloper/SeniorDeveloper_zh.md",
|
||||
"usedAt": 1776696820692,
|
||||
"industryId": "02-Engineering"
|
||||
}
|
||||
]
|
||||
},
|
||||
"lastUpdated": 1776017699886
|
||||
"lastUpdated": 1776699418893
|
||||
}
|
||||
75
.workbuddy/memory/2026-04-16.md
Normal file
75
.workbuddy/memory/2026-04-16.md
Normal file
@@ -0,0 +1,75 @@
|
||||
# 2026-04-16 工作记录
|
||||
|
||||
## 支付回调状态不更新问题诊断与修复
|
||||
|
||||
**问题接口**: `POST /api/shop/shop-order/notify/{tenantId}`
|
||||
|
||||
### 发现的 Bug
|
||||
|
||||
1. **根因 Bug**:`ShopOrderServiceImpl.updateByOutTradeNo()` 第837行有 `order.setExpirationTime(null)`,强制覆盖了 Controller 中设置的 `expirationTime`(`LocalDateTime.now().plusYears(10)`),导致 XML 中 expirationTime 条件不生效。**已修复**:删除了该行。
|
||||
|
||||
2. **XML 缺少 `update_time`**:`ShopOrderMapper.xml` 的 `updateByOutTradeNo` SQL 的 `<set>` 块中没有 `update_time = NOW()` 和 `expiration_time` 字段。**已修复**:新增了这两个字段更新。
|
||||
|
||||
3. **回调地址路由问题**:Controller 路由为 `/notify/{tenantId}`,但测试访问的 `/notify`(无 tenantId)不存在,返回 fail。正确回调地址格式为 `https://glt-api.websoft.top/api/shop/shop-order/notify/{tenantId}`(需带租户ID)。**待检查**:数据库 Payment 表的 `notify_url` 字段是否正确配置了带 tenantId 的完整路径。
|
||||
|
||||
### 修复文件
|
||||
- `src/main/java/com/gxwebsoft/shop/service/impl/ShopOrderServiceImpl.java`
|
||||
- `src/main/java/com/gxwebsoft/shop/mapper/xml/ShopOrderMapper.xml`
|
||||
|
||||
---
|
||||
|
||||
## 支付回调签名验证失败:Transaction 类错误(00:29修复)
|
||||
|
||||
**错误日志关键信息**:
|
||||
```
|
||||
signature verification failed, signType[WECHATPAY2-SHA256-RSA2048]
|
||||
serial[test] message[test\ntest\n{"test":"test"}] sign[test]
|
||||
```
|
||||
|
||||
### 根本原因(最致命)
|
||||
|
||||
`ShopOrderController.java` 导入了 **服务商模式** 的 Transaction 类:
|
||||
```java
|
||||
// 错误(服务商模式)
|
||||
import com.wechat.pay.java.service.partnerpayments.jsapi.model.Transaction;
|
||||
```
|
||||
而 `ShopOrderServiceImpl.java` 下单时用的是**直连商户模式**:
|
||||
```java
|
||||
// 正确(直连商户模式)
|
||||
import com.wechat.pay.java.service.payments.model.Transaction;
|
||||
```
|
||||
两个 Transaction 包路径不同,字段结构有差异(服务商 Transaction 有 spAppid/spMchid 等字段),用错误的类解析回调会导致字段映射失败,交易状态无法正确读取。**已修复**:改为正确的直连商户模式 Transaction。
|
||||
|
||||
---
|
||||
|
||||
## 配送员提成直接入账(01:15修改)
|
||||
|
||||
**文件**:`src/main/java/com/gxwebsoft/glt/service/impl/GltTicketOrderServiceImpl.java`
|
||||
|
||||
**变更**:配送员提成(ticketOrderId 关联送水订单)从进入 `freeze_money` 改为直接进入 `money`(可提现余额)。修改了 2 处 `LambdaUpdateWrapper` SQL(`freeze_money` → `money`),注释同步更新。`total_money` 不变(仍累计)。
|
||||
|
||||
---
|
||||
|
||||
---
|
||||
|
||||
## 分销佣金解冻任务分析(DealerCommissionUnfreeze10584Task)
|
||||
|
||||
**订单号**:2038841514750459904
|
||||
|
||||
### 解冻规则
|
||||
- **送水套餐**(shop_order.form_id IN 水票模板的 goods_id):该订单关联的水票第一条送水订单 deliveryStatus=40(已完成)才触发解冻
|
||||
- **非送水套餐**(form_id 不在水票模板中):shop_order.order_status=1 即触发解冻
|
||||
|
||||
### "已送达"≠"已完成"的关键区别
|
||||
- deliveryStatus=30(送达待确认):配送员拍照确认送达,此时**不触发解冻**
|
||||
- deliveryStatus=40(已完成):需用户手动确认收货 OR 超时24h自动确认后才到达此状态
|
||||
|
||||
### 常见未解冻原因(按排查优先级)
|
||||
1. 送水订单停在 deliveryStatus=30(送达待确认),未到 40(已完成)
|
||||
2. shop_order.form_id 在水票模板里,走的是"送水套餐"逻辑,但没有找到对应的 glt_user_ticket 记录
|
||||
3. glt_user_ticket 记录缺失或 order_no 字段为空
|
||||
4. 已有 flowType=50 的解冻 marker(说明已解冻)
|
||||
|
||||
### 次要原因
|
||||
|
||||
`RSAAutoCertificateConfig` 每次回调都重新 `build()`,SDK 内部会发一次 `serial=test` 的探测验签,网络问题或并发场景下可能导致首次回调失败。**已优化**:添加 `notifyConfigCache`(ConcurrentHashMap)按 mchId 缓存 config,避免重复初始化。
|
||||
13
.workbuddy/memory/2026-04-18.md
Normal file
13
.workbuddy/memory/2026-04-18.md
Normal file
@@ -0,0 +1,13 @@
|
||||
# 2026-04-18 工作日志
|
||||
|
||||
## 排查解冻任务未触发问题
|
||||
- 用户反馈:GltTicketOrder订单已完成配送,但部分订单未触发解冻(freezeMoney未转到money)
|
||||
- 完整梳理了资金流转链路:结算→冻结→解冻
|
||||
- 识别出5个可能原因:
|
||||
1. GltTicketOrder.userTicketId为NULL(解冻任务硬性过滤条件)
|
||||
2. GltUserTicket.orderNo缺失导致关联断裂
|
||||
3. isFirstTicketOrderFinished()"第一条"逻辑阻断后续订单解冻
|
||||
4. loadWaterFormIds()返回空集导致整个解冻任务跳过
|
||||
5. 配送员提成orderNo格式不匹配(非bug,配送员提成本身不经过冻结)
|
||||
- 提供了5条排查SQL和修复建议
|
||||
- 关键文件:DealerCommissionUnfreeze10584Task.java、GltTicketOrderServiceImpl.java
|
||||
18
.workbuddy/memory/2026-04-21.md
Normal file
18
.workbuddy/memory/2026-04-21.md
Normal file
@@ -0,0 +1,18 @@
|
||||
# 2026-04-21 日志
|
||||
|
||||
## WxLoginController.getOrderQRCodeUnlimited 修复(完整)
|
||||
|
||||
### 根因
|
||||
1. `extractTenantIdFromScene` 通过 `selectByIdIgnoreTenant` 反查用户获取 tenantId,userId=35280 在多租户下有2条记录 → `TooManyResultsException`
|
||||
2. 异常被 catch 后 fallback 到默认租户 10550,Redis 中无 `mp-weixin:10550` 缓存 → 最终失败
|
||||
3. 第 452 行 `website.getRunning().equals(2)` 存在 NPE 风险
|
||||
|
||||
### 修复内容
|
||||
- **后端 WxLoginController**: scene 格式改为 `uid_userId_tenantId`,优先从 scene 直接解析 tenantId;兼容旧 `uid_userId` 格式时改用 `selectList` 避免多条记录异常
|
||||
- **后端 UserMapper/UserService**: `selectByIdIgnoreTenant` 返回类型从 `User` 改为 `List<User>`;新增 `listByIdIgnoreTenant` 方法
|
||||
- **后端 NPE 修复**: `website.getRunning().equals(2)` → `website != null && Integer.valueOf(2).equals(website.getRunning())`
|
||||
- **前端 3 个 vue**: scene 从 `uid_${userId}` 改为 `uid_${userId}_${tenantId}`(从 tenantStore.company.tenantId 获取)
|
||||
- shopDealerUser/index.vue
|
||||
- shopDealerUserShop/index.vue
|
||||
- shopDealerUserDelivery/index.vue
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
# MEMORY.md - 长期记忆
|
||||
|
||||
## 项目概况
|
||||
- 后端:/Users/gxwebsoft/JAVA/java-10584(Spring Boot + MyBatis-Plus)
|
||||
- 后台管理:/Users/gxwebsoft/VUE/mp-10584
|
||||
- 小程序端:/Users/gxwebsoft/VUE/template-10584
|
||||
- 多租户架构(tenantId 隔离),主力租户 10584
|
||||
|
||||
## 技术栈
|
||||
- 后端:Spring Boot + MyBatis-Plus + FastJSON 2.x
|
||||
- 前端:Nuxt/Vue3 + TypeScript + Ant Design Vue4 + Tailwind
|
||||
- 小程序:Uni-app/Taro
|
||||
- 开发环境:Mac + Node.js v22 + JetBrains + Docker + pnpm
|
||||
|
||||
## 业务规则备忘
|
||||
|
||||
### 分销佣金解冻规则(10584)
|
||||
- 结算:DealerOrderSettlement10584Task 每10秒,佣金先入 freezeMoney
|
||||
- 解冻:DealerCommissionUnfreeze10584Task 每20秒,freezeMoney→money
|
||||
- 送水套餐解冻条件:同一userTicketId下第一条送水订单deliveryStatus=40
|
||||
- 非送水套餐解冻条件:ShopOrder.orderStatus=1 且 payStatus=true
|
||||
- 幂等标记:ShopDealerCapital(flowType=50, comments="佣金解冻(capitalId=xxx)")
|
||||
- 配送员提成:直接入money(不经过冻结),orderNo格式="gltTicketOrder:"+id
|
||||
|
||||
### 送水订单状态流转
|
||||
- 10(待配送)→20(配送中)→30(待客户确认)→40(已完成)
|
||||
- delivered()配送员确认送达时就会同步ShopOrder.orderStatus=1
|
||||
- confirmReceive()/autoConfirmTimeout()也会同步
|
||||
|
||||
### 已知排查问题
|
||||
- 解冻任务可能因 userTicketId为空、GltUserTicket.orderNo缺失、"第一条未完成"阻断等原因未触发
|
||||
- 解冻任务依赖 loadWaterFormIds() 不为空,否则整个任务跳过
|
||||
|
||||
5
.workbuddy/settings.local.json
Normal file
5
.workbuddy/settings.local.json
Normal file
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"enabledPlugins": {
|
||||
"modern-webapp@cb_teams_marketplace": true
|
||||
}
|
||||
}
|
||||
4
pom.xml
4
pom.xml
@@ -4,10 +4,10 @@
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>com.gxwebsoft</groupId>
|
||||
<artifactId>glt-api</artifactId>
|
||||
<artifactId>mp-api</artifactId>
|
||||
<version>1.0</version>
|
||||
|
||||
<name>glt-api</name>
|
||||
<name>mp-api</name>
|
||||
<description>WebSoftApi project for Spring Boot</description>
|
||||
|
||||
<parent>
|
||||
|
||||
@@ -227,6 +227,10 @@ public class CmsNavigation implements Serializable {
|
||||
@TableField(exist = false)
|
||||
private String text;
|
||||
|
||||
@Schema(description = "栏目文章")
|
||||
@TableField(exist = false)
|
||||
private List<CmsArticle> articles;
|
||||
|
||||
public String getCategoryName() {
|
||||
return this.title;
|
||||
}
|
||||
|
||||
@@ -4,9 +4,11 @@ import cn.hutool.core.util.ObjectUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import com.gxwebsoft.cms.entity.CmsArticle;
|
||||
import com.gxwebsoft.cms.entity.CmsDesign;
|
||||
import com.gxwebsoft.cms.entity.CmsModel;
|
||||
import com.gxwebsoft.cms.mapper.CmsNavigationMapper;
|
||||
import com.gxwebsoft.cms.service.CmsArticleService;
|
||||
import com.gxwebsoft.cms.service.CmsDesignService;
|
||||
import com.gxwebsoft.cms.service.CmsModelService;
|
||||
import com.gxwebsoft.cms.service.CmsNavigationService;
|
||||
@@ -38,6 +40,8 @@ public class CmsNavigationServiceImpl extends ServiceImpl<CmsNavigationMapper, C
|
||||
private CmsModelService cmsModelService;
|
||||
@Resource
|
||||
private UserService userService;
|
||||
@Resource
|
||||
private CmsArticleService cmsArticleService;
|
||||
|
||||
@Override
|
||||
public PageResult<CmsNavigation> pageRel(CmsNavigationParam param) {
|
||||
@@ -53,6 +57,11 @@ public class CmsNavigationServiceImpl extends ServiceImpl<CmsNavigationMapper, C
|
||||
// 排序
|
||||
PageParam<CmsNavigation, CmsNavigationParam> page = new PageParam<>();
|
||||
page.setDefaultOrder("sort_number asc, position asc,navigation_id asc");
|
||||
list.forEach(item -> {
|
||||
// 关联信息
|
||||
final List<CmsArticle> articleList = cmsArticleService.list(new LambdaQueryWrapper<CmsArticle>().eq(CmsArticle::getCategoryId, item.getNavigationId()).last("limit 5"));
|
||||
item.setArticles(articleList);
|
||||
});
|
||||
return page.sortRecords(list);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.gxwebsoft.common.core.service;
|
||||
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.gxwebsoft.common.system.entity.Payment;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
@@ -26,6 +27,9 @@ public class EnvironmentAwarePaymentService {
|
||||
@Value("${config.server-url:}")
|
||||
private String serverUrl;
|
||||
|
||||
@Value("${config.api-url:}")
|
||||
private String apiUrl;
|
||||
|
||||
// 开发环境回调地址配置
|
||||
@Value("${payment.dev.notify-url:http://frps-10550.s209.websoft.top/api/shop/shop-order/notify}")
|
||||
private String devNotifyUrl;
|
||||
@@ -73,8 +77,8 @@ public class EnvironmentAwarePaymentService {
|
||||
// 生产环境使用生产回调地址
|
||||
return prodNotifyUrl;
|
||||
} else {
|
||||
// 默认使用配置的服务器地址
|
||||
return serverUrl + "/shop/shop-order/notify";
|
||||
// 默认使用 API 网关地址(支付回调需要公网可访问的 API 地址)
|
||||
return (StrUtil.isNotBlank(apiUrl) ? apiUrl : serverUrl) + "/shop/shop-order/notify";
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -40,6 +40,7 @@ import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.time.Instant;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
@@ -449,7 +450,7 @@ public class WxLoginController extends BaseController {
|
||||
|
||||
// 判断应用运行状态
|
||||
final CmsWebsite website = cmsWebsiteService.getByTenantId(tenantId);
|
||||
if(website.getRunning().equals(2)){
|
||||
if(website != null && Integer.valueOf(2).equals(website.getRunning())){
|
||||
map.put("check_path",false);
|
||||
map.put("env_version","trial");
|
||||
}
|
||||
@@ -725,26 +726,43 @@ public class WxLoginController extends BaseController {
|
||||
|
||||
/**
|
||||
* 从scene参数中提取租户ID
|
||||
* scene格式可能是: uid_33103 或其他包含用户ID的格式
|
||||
* scene格式: uid_userId_tenantId(优先)或 uid_userId(兼容旧格式)
|
||||
*/
|
||||
private Integer extractTenantIdFromScene(String scene) {
|
||||
try {
|
||||
System.out.println("解析scene参数: " + scene);
|
||||
|
||||
// 如果scene包含uid_前缀,提取用户ID
|
||||
if (scene != null && scene.startsWith("uid_")) {
|
||||
String userIdStr = scene.substring(4); // 去掉"uid_"前缀
|
||||
Integer userId = Integer.parseInt(userIdStr);
|
||||
System.out.println("userId = " + userId);
|
||||
String content = scene.substring(4); // 去掉"uid_"前缀
|
||||
|
||||
// 根据用户ID查询用户信息,获取租户ID
|
||||
User user = userService.getByIdIgnoreTenant(userId);
|
||||
System.out.println("user = " + user);
|
||||
if (user != null) {
|
||||
System.out.println("从用户ID " + userId + " 获取到租户ID: " + user.getTenantId());
|
||||
return user.getTenantId();
|
||||
} else {
|
||||
System.err.println("未找到用户ID: " + userId);
|
||||
// 优先解析 uid_userId_tenantId 格式
|
||||
String[] parts = content.split("_");
|
||||
if (parts.length >= 2) {
|
||||
try {
|
||||
Integer tenantId = Integer.parseInt(parts[1]);
|
||||
System.out.println("从scene直接解析到tenantId = " + tenantId);
|
||||
return tenantId;
|
||||
} catch (NumberFormatException e) {
|
||||
System.err.println("scene中tenantId格式异常: " + parts[1]);
|
||||
}
|
||||
}
|
||||
|
||||
// 兼容旧格式 uid_userId:根据用户ID查询租户ID
|
||||
if (parts.length == 1) {
|
||||
Integer userId = Integer.parseInt(parts[0]);
|
||||
System.out.println("userId = " + userId);
|
||||
try {
|
||||
List<User> users = userService.listByIdIgnoreTenant(userId);
|
||||
System.out.println("查询到用户数量 = " + (users != null ? users.size() : 0));
|
||||
if (users != null && !users.isEmpty()) {
|
||||
System.out.println("从用户ID " + userId + " 获取到租户ID: " + users.get(0).getTenantId());
|
||||
return users.get(0).getTenantId();
|
||||
} else {
|
||||
System.err.println("未找到用户ID: " + userId);
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
System.err.println("查询用户异常: " + ex.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -60,7 +60,7 @@ public interface UserMapper extends BaseMapper<User> {
|
||||
* @return User
|
||||
*/
|
||||
@InterceptorIgnore(tenantLine = "true")
|
||||
User selectByIdIgnoreTenant(@Param("userId") Integer userId);
|
||||
List<User> selectByIdIgnoreTenant(@Param("userId") Integer userId);
|
||||
|
||||
@InterceptorIgnore(tenantLine = "true")
|
||||
List<User> pageAdminByPhone(@Param("param") UserParam param);
|
||||
|
||||
@@ -117,6 +117,11 @@ public interface UserService extends IService<User>, UserDetailsService {
|
||||
*/
|
||||
User getByIdIgnoreTenant(Integer userId);
|
||||
|
||||
/**
|
||||
* 根据用户ID查询用户列表(忽略租户隔离)
|
||||
*/
|
||||
List<User> listByIdIgnoreTenant(Integer userId);
|
||||
|
||||
List<User> pageAdminByPhone(UserParam param);
|
||||
|
||||
List<User> listByAlert();
|
||||
|
||||
@@ -2,6 +2,9 @@ package com.gxwebsoft.common.system.service.impl;
|
||||
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
@@ -224,6 +227,15 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements Us
|
||||
if (userId == null) {
|
||||
return null;
|
||||
}
|
||||
List<User> users = baseMapper.selectByIdIgnoreTenant(userId);
|
||||
return users != null && !users.isEmpty() ? users.get(0) : null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<User> listByIdIgnoreTenant(Integer userId) {
|
||||
if (userId == null) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
return baseMapper.selectByIdIgnoreTenant(userId);
|
||||
}
|
||||
|
||||
|
||||
@@ -845,13 +845,13 @@ public class GltTicketOrderServiceImpl extends ServiceImpl<GltTicketOrderMapper,
|
||||
return;
|
||||
}
|
||||
|
||||
// 送水订单提成:先入冻结金额 freeze_money(与分销订单佣金一致)
|
||||
// 送水订单提成:直接入账可提现余额 money(配送员提成即时可用,无需冻结)
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
boolean updated = shopDealerUserService.update(
|
||||
new LambdaUpdateWrapper<ShopDealerUser>()
|
||||
.eq(ShopDealerUser::getTenantId, tenantId)
|
||||
.eq(ShopDealerUser::getUserId, riderId)
|
||||
.setSql("freeze_money = IFNULL(freeze_money,0) + " + money.toPlainString())
|
||||
.setSql("money = IFNULL(money,0) + " + money.toPlainString())
|
||||
.setSql("total_money = IFNULL(total_money,0) + " + money.toPlainString())
|
||||
.set(ShopDealerUser::getUpdateTime, now)
|
||||
);
|
||||
@@ -878,7 +878,8 @@ public class GltTicketOrderServiceImpl extends ServiceImpl<GltTicketOrderMapper,
|
||||
newDealerUser.setFreezeMoney(BigDecimal.ZERO);
|
||||
newDealerUser.setTotalMoney(BigDecimal.ZERO);
|
||||
try {
|
||||
User sysUser = userMapper.selectByIdIgnoreTenant(riderId);
|
||||
List<User> sysUsers = userMapper.selectByIdIgnoreTenant(riderId);
|
||||
User sysUser = (sysUsers != null && !sysUsers.isEmpty()) ? sysUsers.get(0) : null;
|
||||
if (sysUser != null) {
|
||||
newDealerUser.setRealName(sysUser.getRealName() != null ? sysUser.getRealName() : sysUser.getNickname());
|
||||
newDealerUser.setMobile(sysUser.getPhone());
|
||||
@@ -895,7 +896,7 @@ public class GltTicketOrderServiceImpl extends ServiceImpl<GltTicketOrderMapper,
|
||||
new LambdaUpdateWrapper<ShopDealerUser>()
|
||||
.eq(ShopDealerUser::getTenantId, tenantId)
|
||||
.eq(ShopDealerUser::getUserId, riderId)
|
||||
.setSql("freeze_money = IFNULL(freeze_money,0) + " + money.toPlainString())
|
||||
.setSql("money = IFNULL(money,0) + " + money.toPlainString())
|
||||
.setSql("total_money = IFNULL(total_money,0) + " + money.toPlainString())
|
||||
.set(ShopDealerUser::getUpdateTime, now)
|
||||
);
|
||||
|
||||
@@ -33,6 +33,7 @@ import java.math.RoundingMode;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
@@ -48,7 +49,7 @@ import java.util.concurrent.atomic.AtomicBoolean;
|
||||
* <p>1) 送水套餐(formId in 水票模板 goodsId):订单号关联的水票产生了第一次送水订单,且该第一次送水订单状态=已完成(40) -> 解冻。</p>
|
||||
* <p>2) 非送水套餐(formId not in 水票模板 goodsId):订单已确认收货(orderStatus=1) -> 解冻。</p>
|
||||
*
|
||||
* <p>实现策略:以 ShopDealerCapital(flowType=10) 的“佣金明细”为解冻粒度,
|
||||
* <p>实现策略:以 ShopDealerCapital(flowType=10) 的"佣金明细"为解冻粒度,
|
||||
* 每条佣金明细对应生成一条 ShopDealerCapital(flowType=50) 作为幂等标记,并执行
|
||||
* ShopDealerUser.freezeMoney -> ShopDealerUser.money 的转移。</p>
|
||||
*/
|
||||
@@ -76,7 +77,7 @@ public class DealerCommissionUnfreeze10584Task {
|
||||
if (rawRate == null || rawRate.signum() <= 0) {
|
||||
return null;
|
||||
}
|
||||
// 如果录入 >= 1,按“百分比”处理(1 => 1%)
|
||||
// 如果录入 >= 1,按"百分比"处理(1 => 1%)
|
||||
if (rawRate.compareTo(BigDecimal.ONE) >= 0) {
|
||||
return rawRate.movePointLeft(2);
|
||||
}
|
||||
@@ -115,7 +116,7 @@ public class DealerCommissionUnfreeze10584Task {
|
||||
|
||||
private final AtomicBoolean running = new AtomicBoolean(false);
|
||||
|
||||
@Scheduled(cron = "${dealer.commission.unfreeze10584.cron:0/20 * * * * ?}")
|
||||
@Scheduled(cron = "${dealer.commission.unfreeze10584.cron:0/50 * * * * ?}")
|
||||
@IgnoreTenant("定时任务无登录态,需忽略租户隔离;内部使用 tenantId=10584 精确过滤")
|
||||
public void run() {
|
||||
if (!running.compareAndSet(false, true)) {
|
||||
@@ -124,46 +125,77 @@ public class DealerCommissionUnfreeze10584Task {
|
||||
}
|
||||
|
||||
try {
|
||||
// ========== 步骤1: 加载水票模板 ==========
|
||||
Set<Integer> waterFormIds = loadWaterFormIds();
|
||||
log.info("【步骤1】加载水票模板 - tenantId={}, waterFormIds={}", TENANT_ID, waterFormIds);
|
||||
if (waterFormIds.isEmpty()) {
|
||||
// 送水/非送水的判断依赖模板 goodsId;拿不到会导致误判,宁可跳过本轮。
|
||||
log.warn("分销佣金解冻任务跳过:未找到水票模板 goodsId - tenantId={}", TENANT_ID);
|
||||
return;
|
||||
}
|
||||
|
||||
// 先按“最近确认收货”的订单扫描,避免总是卡在很早的历史订单上。
|
||||
// ========== 步骤2: 扫描非送水订单(优先最新) ==========
|
||||
Set<String> eligibleOrderNos = new HashSet<>();
|
||||
eligibleOrderNos.addAll(findEligibleNonWaterOrderNos(waterFormIds, true));
|
||||
eligibleOrderNos.addAll(findEligibleWaterOrderNosByFirstFinishedTicketOrder(waterFormIds));
|
||||
List<String> nonWaterOrders = findEligibleNonWaterOrderNos(waterFormIds, true);
|
||||
log.info("【步骤2】扫描非送水订单(最新优先)- tenantId={}, count={}, orderNos={}", TENANT_ID, nonWaterOrders.size(), nonWaterOrders.size() <= 20 ? nonWaterOrders : nonWaterOrders.subList(0, 20));
|
||||
eligibleOrderNos.addAll(nonWaterOrders);
|
||||
|
||||
// ========== 步骤3: 扫描送水订单(第一条送水完成) ==========
|
||||
Set<String> waterOrders = findEligibleWaterOrderNosByFirstFinishedTicketOrder(waterFormIds);
|
||||
log.info("【步骤3】扫描送水订单(第一条送水完成)- tenantId={}, count={}, orderNos={}", TENANT_ID, waterOrders.size(), waterOrders);
|
||||
eligibleOrderNos.addAll(waterOrders);
|
||||
|
||||
if (eligibleOrderNos.isEmpty()) {
|
||||
log.info("【步骤4-9】无可处理订单,本轮结束 - tenantId={}", TENANT_ID);
|
||||
return;
|
||||
}
|
||||
// 订单太多时不打印完整列表
|
||||
String orderNosSummary = eligibleOrderNos.size() <= 30 ? eligibleOrderNos.toString() : eligibleOrderNos.size() + " orders (too many to show)";
|
||||
log.info("【步骤4】汇总待处理订单 - tenantId={}, totalCount={}, orderNos={}", TENANT_ID, eligibleOrderNos.size(), orderNosSummary);
|
||||
|
||||
// 配送奖励(与佣金解冻独立):按订单发放,幂等保证不会重复入账
|
||||
// ========== 步骤5: 发放配送奖励 ==========
|
||||
log.info("【步骤5】开始发放配送奖励 - tenantId={}, orderCount={}", TENANT_ID, eligibleOrderNos.size());
|
||||
int rewarded = 0;
|
||||
List<String> rewardedOrders = new ArrayList<>();
|
||||
for (String orderNo : eligibleOrderNos) {
|
||||
try {
|
||||
if (settleDeliveryRewardIfNeeded(orderNo)) {
|
||||
rewarded++;
|
||||
rewardedOrders.add(orderNo);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("发放配送奖励失败,将在下次任务重试 - tenantId={}, orderNo={}", TENANT_ID, orderNo, e);
|
||||
}
|
||||
}
|
||||
log.info("【步骤5】配送奖励发放完成 - tenantId={}, rewardedCount={}, rewardedOrders={}", TENANT_ID, rewarded, rewardedOrders);
|
||||
|
||||
// ========== 步骤6: 查询佣金明细 ==========
|
||||
log.info("【步骤6】查询佣金明细(flowType=10)- tenantId={}, orderCount={}", TENANT_ID, eligibleOrderNos.size());
|
||||
List<ShopDealerCapital> capitals = findCapitalsByEligibleOrderNos(eligibleOrderNos);
|
||||
String capitalsSummary = capitals.size() <= 50
|
||||
? capitals.stream().map(c -> "capitalId=" + c.getId() + ", orderNo=" + c.getOrderNo() + ", amount=" + c.getMoney()).toList().toString()
|
||||
: capitals.size() + " capitals (too many to show)";
|
||||
log.info("【步骤6】查询到佣金明细 - tenantId={}, count={}, capitals={}", TENANT_ID, capitals.size(), capitalsSummary);
|
||||
|
||||
if (capitals.isEmpty()) {
|
||||
// 若本轮没有取到佣金明细,回退再按“最早确认收货”的订单扫一轮,尽量覆盖历史遗留未解冻。
|
||||
// ========== 步骤6.1: 兜底扫描历史订单 ==========
|
||||
log.info("【步骤6.1】本轮未取到佣金明细,执行兜底扫描(最早确认收货) - tenantId={}", TENANT_ID);
|
||||
eligibleOrderNos.clear();
|
||||
eligibleOrderNos.addAll(findEligibleNonWaterOrderNos(waterFormIds, false));
|
||||
eligibleOrderNos.addAll(findEligibleWaterOrderNosByFirstFinishedTicketOrder(waterFormIds));
|
||||
List<String> fallbackNonWater = findEligibleNonWaterOrderNos(waterFormIds, false);
|
||||
log.info("【步骤6.1】兜底-非送水订单 - tenantId={}, count={}", TENANT_ID, fallbackNonWater.size());
|
||||
eligibleOrderNos.addAll(fallbackNonWater);
|
||||
|
||||
Set<String> fallbackWater = findEligibleWaterOrderNosByFirstFinishedTicketOrder(waterFormIds);
|
||||
log.info("【步骤6.1】兜底-送水订单 - tenantId={}, count={}", TENANT_ID, fallbackWater.size());
|
||||
eligibleOrderNos.addAll(fallbackWater);
|
||||
|
||||
// 兜底扫描出来的订单也补发配送奖励(幂等)
|
||||
log.info("【步骤6.1】兜底扫描后补发配送奖励 - tenantId={}, orderCount={}", TENANT_ID, eligibleOrderNos.size());
|
||||
for (String orderNo : eligibleOrderNos) {
|
||||
try {
|
||||
if (settleDeliveryRewardIfNeeded(orderNo)) {
|
||||
rewarded++;
|
||||
rewardedOrders.add(orderNo + "(兜底)");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("发放配送奖励失败,将在下次任务重试 - tenantId={}, orderNo={}", TENANT_ID, orderNo, e);
|
||||
@@ -171,32 +203,41 @@ public class DealerCommissionUnfreeze10584Task {
|
||||
}
|
||||
|
||||
capitals = findCapitalsByEligibleOrderNos(eligibleOrderNos);
|
||||
log.info("【步骤6.1】兜底扫描到佣金明细 - tenantId={}, count={}", TENANT_ID, capitals.size());
|
||||
}
|
||||
|
||||
if (capitals.isEmpty()) {
|
||||
log.info("【步骤7-9】仍未查到佣金明细,本轮结束 - tenantId={}", TENANT_ID);
|
||||
return;
|
||||
}
|
||||
|
||||
// ========== 步骤7: 执行佣金解冻 ==========
|
||||
log.info("【步骤7】开始执行佣金解冻 - tenantId={}, totalCount={}", TENANT_ID, capitals.size());
|
||||
int unfrozen = 0;
|
||||
List<String> unfrozenDetails = new ArrayList<>();
|
||||
for (ShopDealerCapital cap : capitals) {
|
||||
try {
|
||||
boolean ok = unfreezeOneCapitalIfNeeded(cap);
|
||||
if (ok) {
|
||||
unfrozen++;
|
||||
unfrozenDetails.add("capitalId=" + cap.getId() + ", orderNo=" + cap.getOrderNo() + ", amount=" + cap.getMoney());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("解冻佣金失败,将在下次任务重试 - tenantId={}, capitalId={}, orderNo={}, userId={}",
|
||||
TENANT_ID, cap != null ? cap.getId() : null, cap != null ? cap.getOrderNo() : null, cap != null ? cap.getUserId() : null, e);
|
||||
}
|
||||
}
|
||||
log.info("【步骤7】佣金解冻完成 - tenantId={}, unfrozenDetails={}", TENANT_ID, unfrozenDetails);
|
||||
|
||||
if (unfrozen > 0) {
|
||||
log.info("分销佣金解冻完成 - tenantId={}, eligibleOrderNos={}, scannedCapitals={}, unfrozen={}",
|
||||
TENANT_ID, eligibleOrderNos.size(), capitals.size(), unfrozen);
|
||||
}
|
||||
if (rewarded > 0) {
|
||||
log.info("配送奖励发放完成 - tenantId={}, eligibleOrderNos={}, rewarded={}", TENANT_ID, eligibleOrderNos.size(), rewarded);
|
||||
}
|
||||
// ========== 步骤8: 更新分销订单状态 ==========
|
||||
log.info("【步骤8】检查并更新分销订单状态(isUnfreeze=1)- tenantId={}, unfrozenCount={}", TENANT_ID, unfrozen);
|
||||
|
||||
// ========== 步骤9: 汇总报告 ==========
|
||||
log.info("========================================");
|
||||
log.info("【步骤9】本轮任务执行完毕 - tenantId={}", TENANT_ID);
|
||||
log.info(" - 配送奖励: rewarded={}, orders={}", rewarded, rewardedOrders);
|
||||
log.info(" - 佣金解冻: unfrozen={}, details={}", unfrozen, unfrozenDetails);
|
||||
log.info("========================================");
|
||||
} finally {
|
||||
running.set(false);
|
||||
}
|
||||
@@ -204,8 +245,10 @@ public class DealerCommissionUnfreeze10584Task {
|
||||
|
||||
private boolean settleDeliveryRewardIfNeeded(String orderNo) {
|
||||
if (orderNo == null || orderNo.isBlank()) {
|
||||
log.debug("【步骤5.X】配送奖励跳过:orderNo为空 - tenantId={}", TENANT_ID);
|
||||
return false;
|
||||
}
|
||||
log.debug("【步骤5.X】开始处理配送奖励 - tenantId={}, orderNo={}", TENANT_ID, orderNo);
|
||||
|
||||
ShopOrder order = shopOrderService.getOne(
|
||||
new LambdaQueryWrapper<ShopOrder>()
|
||||
@@ -215,13 +258,16 @@ public class DealerCommissionUnfreeze10584Task {
|
||||
.last("limit 1")
|
||||
);
|
||||
if (order == null) {
|
||||
log.debug("【步骤5.X】配送奖励跳过:订单不存在 - tenantId={}, orderNo={}", TENANT_ID, orderNo);
|
||||
return false;
|
||||
}
|
||||
|
||||
Integer riderId = order.getRiderId();
|
||||
if (riderId == null || riderId <= 0) {
|
||||
log.debug("【步骤5.X】配送奖励跳过:无配送员 - tenantId={}, orderNo={}", TENANT_ID, orderNo);
|
||||
return false;
|
||||
}
|
||||
log.debug("【步骤5.X】找到配送员 - tenantId={}, orderNo={}, riderId={}", TENANT_ID, orderNo, riderId);
|
||||
|
||||
// 快速幂等检查:已发放则跳过(事务内仍会二次校验避免并发重复)
|
||||
boolean already = shopDealerCapitalService.count(
|
||||
@@ -231,147 +277,162 @@ public class DealerCommissionUnfreeze10584Task {
|
||||
.eq(ShopDealerCapital::getOrderNo, orderNo)
|
||||
) > 0;
|
||||
if (already) {
|
||||
log.debug("【步骤5.X】配送奖励跳过:已发放(幂等)- tenantId={}, orderNo={}", TENANT_ID, orderNo);
|
||||
return false;
|
||||
}
|
||||
log.debug("【步骤5.X】进入事务 - tenantId={}, orderNo={}", TENANT_ID, orderNo);
|
||||
|
||||
return Boolean.TRUE.equals(transactionTemplate.execute(status -> {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
try {
|
||||
return Boolean.TRUE.equals(transactionTemplate.execute(status -> {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
log.debug("【步骤5.X】事务内开始 - tenantId={}, orderNo={}", TENANT_ID, orderNo);
|
||||
|
||||
// 锁定配送员资金明细 marker,确保并发幂等
|
||||
ShopDealerCapital existedMarker = shopDealerCapitalService.getOne(
|
||||
new LambdaQueryWrapper<ShopDealerCapital>()
|
||||
.eq(ShopDealerCapital::getTenantId, TENANT_ID)
|
||||
.eq(ShopDealerCapital::getFlowType, FLOW_TYPE_DELIVERY_REWARD)
|
||||
.eq(ShopDealerCapital::getOrderNo, orderNo)
|
||||
.last("limit 1 for update")
|
||||
);
|
||||
if (existedMarker != null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Integer orderId = order.getOrderId();
|
||||
if (orderId == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
List<ShopOrderGoods> orderGoodsList = shopOrderGoodsService.list(
|
||||
new LambdaQueryWrapper<ShopOrderGoods>()
|
||||
.eq(ShopOrderGoods::getTenantId, TENANT_ID)
|
||||
.eq(ShopOrderGoods::getOrderId, orderId)
|
||||
);
|
||||
if (orderGoodsList == null || orderGoodsList.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
List<Integer> goodsIds = orderGoodsList.stream()
|
||||
.map(ShopOrderGoods::getGoodsId)
|
||||
.filter(Objects::nonNull)
|
||||
.distinct()
|
||||
.toList();
|
||||
if (goodsIds.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Map<Integer, BigDecimal> goodsDeliveryMoneyMap = shopGoodsService.list(
|
||||
new LambdaQueryWrapper<ShopGoods>()
|
||||
.eq(ShopGoods::getTenantId, TENANT_ID)
|
||||
.in(ShopGoods::getGoodsId, goodsIds)
|
||||
).stream().collect(java.util.stream.Collectors.toMap(
|
||||
ShopGoods::getGoodsId,
|
||||
g -> g.getDeliveryMoney() != null ? g.getDeliveryMoney() : BigDecimal.ZERO,
|
||||
(a, b) -> a
|
||||
));
|
||||
|
||||
BigDecimal reward = BigDecimal.ZERO;
|
||||
for (ShopOrderGoods og : orderGoodsList) {
|
||||
Integer goodsId = og.getGoodsId();
|
||||
if (goodsId == null) {
|
||||
continue;
|
||||
// 锁定配送员资金明细 marker,确保并发幂等
|
||||
ShopDealerCapital existedMarker = shopDealerCapitalService.getOne(
|
||||
new LambdaQueryWrapper<ShopDealerCapital>()
|
||||
.eq(ShopDealerCapital::getTenantId, TENANT_ID)
|
||||
.eq(ShopDealerCapital::getFlowType, FLOW_TYPE_DELIVERY_REWARD)
|
||||
.eq(ShopDealerCapital::getOrderNo, orderNo)
|
||||
.last("limit 1 for update")
|
||||
);
|
||||
if (existedMarker != null) {
|
||||
log.debug("【步骤5.X】配送奖励跳过:事务内检测已存在 - tenantId={}, orderNo={}", TENANT_ID, orderNo);
|
||||
return false;
|
||||
}
|
||||
int qty = og.getTotalNum() == null ? 0 : og.getTotalNum();
|
||||
if (qty <= 0) {
|
||||
continue;
|
||||
}
|
||||
BigDecimal rawRate = goodsDeliveryMoneyMap.getOrDefault(goodsId, BigDecimal.ZERO);
|
||||
BigDecimal rate = normalizeDeliveryRate(rawRate);
|
||||
if (rate == null || rate.signum() <= 0) {
|
||||
continue;
|
||||
}
|
||||
BigDecimal unitPrice = og.getPrice() != null ? og.getPrice() : BigDecimal.ZERO;
|
||||
if (unitPrice.signum() <= 0) {
|
||||
continue;
|
||||
}
|
||||
BigDecimal lineAmount = unitPrice.multiply(BigDecimal.valueOf(qty));
|
||||
reward = reward.add(lineAmount.multiply(rate));
|
||||
}
|
||||
|
||||
reward = reward.setScale(2, RoundingMode.HALF_UP);
|
||||
if (reward.signum() <= 0) {
|
||||
return false;
|
||||
}
|
||||
Integer orderId = order.getOrderId();
|
||||
if (orderId == null) {
|
||||
log.debug("【步骤5.X】配送奖励跳过:orderId为空 - tenantId={}, orderNo={}", TENANT_ID, orderNo);
|
||||
return false;
|
||||
}
|
||||
|
||||
// 锁定/创建配送员分销账户
|
||||
ShopDealerUser dealerUser = shopDealerUserService.getOne(
|
||||
new LambdaQueryWrapper<ShopDealerUser>()
|
||||
.eq(ShopDealerUser::getTenantId, TENANT_ID)
|
||||
.eq(ShopDealerUser::getUserId, riderId)
|
||||
.last("limit 1 for update")
|
||||
);
|
||||
if (dealerUser == null) {
|
||||
ShopDealerUser newDealerUser = new ShopDealerUser();
|
||||
newDealerUser.setTenantId(TENANT_ID);
|
||||
newDealerUser.setUserId(riderId);
|
||||
newDealerUser.setType(0);
|
||||
newDealerUser.setIsDelete(0);
|
||||
newDealerUser.setSortNumber(0);
|
||||
newDealerUser.setFirstNum(0);
|
||||
newDealerUser.setSecondNum(0);
|
||||
newDealerUser.setThirdNum(0);
|
||||
newDealerUser.setMoney(BigDecimal.ZERO);
|
||||
newDealerUser.setFreezeMoney(BigDecimal.ZERO);
|
||||
newDealerUser.setTotalMoney(BigDecimal.ZERO);
|
||||
newDealerUser.setCreateTime(now);
|
||||
newDealerUser.setUpdateTime(now);
|
||||
shopDealerUserService.save(newDealerUser);
|
||||
List<ShopOrderGoods> orderGoodsList = shopOrderGoodsService.list(
|
||||
new LambdaQueryWrapper<ShopOrderGoods>()
|
||||
.eq(ShopOrderGoods::getTenantId, TENANT_ID)
|
||||
.eq(ShopOrderGoods::getOrderId, orderId)
|
||||
);
|
||||
if (orderGoodsList == null || orderGoodsList.isEmpty()) {
|
||||
log.debug("【步骤5.X】配送奖励跳过:订单商品为空 - tenantId={}, orderNo={}", TENANT_ID, orderNo);
|
||||
return false;
|
||||
}
|
||||
|
||||
dealerUser = shopDealerUserService.getOne(
|
||||
List<Integer> goodsIds = orderGoodsList.stream()
|
||||
.map(ShopOrderGoods::getGoodsId)
|
||||
.filter(Objects::nonNull)
|
||||
.distinct()
|
||||
.toList();
|
||||
if (goodsIds.isEmpty()) {
|
||||
log.debug("【步骤5.X】配送奖励跳过:商品ID列表为空 - tenantId={}, orderNo={}", TENANT_ID, orderNo);
|
||||
return false;
|
||||
}
|
||||
|
||||
Map<Integer, BigDecimal> goodsDeliveryMoneyMap = shopGoodsService.list(
|
||||
new LambdaQueryWrapper<ShopGoods>()
|
||||
.eq(ShopGoods::getTenantId, TENANT_ID)
|
||||
.in(ShopGoods::getGoodsId, goodsIds)
|
||||
).stream().collect(java.util.stream.Collectors.toMap(
|
||||
ShopGoods::getGoodsId,
|
||||
g -> g.getDeliveryMoney() != null ? g.getDeliveryMoney() : BigDecimal.ZERO,
|
||||
(a, b) -> a
|
||||
));
|
||||
|
||||
BigDecimal reward = BigDecimal.ZERO;
|
||||
for (ShopOrderGoods og : orderGoodsList) {
|
||||
Integer goodsId = og.getGoodsId();
|
||||
if (goodsId == null) {
|
||||
continue;
|
||||
}
|
||||
int qty = og.getTotalNum() == null ? 0 : og.getTotalNum();
|
||||
if (qty <= 0) {
|
||||
continue;
|
||||
}
|
||||
BigDecimal rawRate = goodsDeliveryMoneyMap.getOrDefault(goodsId, BigDecimal.ZERO);
|
||||
BigDecimal rate = normalizeDeliveryRate(rawRate);
|
||||
if (rate == null || rate.signum() <= 0) {
|
||||
continue;
|
||||
}
|
||||
BigDecimal unitPrice = og.getPrice() != null ? og.getPrice() : BigDecimal.ZERO;
|
||||
if (unitPrice.signum() <= 0) {
|
||||
continue;
|
||||
}
|
||||
BigDecimal lineAmount = unitPrice.multiply(BigDecimal.valueOf(qty));
|
||||
reward = reward.add(lineAmount.multiply(rate));
|
||||
}
|
||||
|
||||
reward = reward.setScale(2, RoundingMode.HALF_UP);
|
||||
if (reward.signum() <= 0) {
|
||||
log.debug("【步骤5.X】配送奖励跳过:计算金额为0 - tenantId={}, orderNo={}", TENANT_ID, orderNo);
|
||||
return false;
|
||||
}
|
||||
log.debug("【步骤5.X】计算配送奖励 - tenantId={}, orderNo={}, reward={}", TENANT_ID, orderNo, reward);
|
||||
|
||||
// 锁定/创建配送员分销账户
|
||||
ShopDealerUser dealerUser = shopDealerUserService.getOne(
|
||||
new LambdaQueryWrapper<ShopDealerUser>()
|
||||
.eq(ShopDealerUser::getTenantId, TENANT_ID)
|
||||
.eq(ShopDealerUser::getUserId, riderId)
|
||||
.last("limit 1 for update")
|
||||
);
|
||||
if (dealerUser == null) {
|
||||
log.warn("配送奖励入账失败:未找到/创建分销账户 - tenantId={}, orderNo={}, riderId={}", TENANT_ID, orderNo, riderId);
|
||||
log.info("【步骤5.X】创建配送员分销账户 - tenantId={}, orderNo={}, riderId={}", TENANT_ID, orderNo, riderId);
|
||||
ShopDealerUser newDealerUser = new ShopDealerUser();
|
||||
newDealerUser.setTenantId(TENANT_ID);
|
||||
newDealerUser.setUserId(riderId);
|
||||
newDealerUser.setType(0);
|
||||
newDealerUser.setIsDelete(0);
|
||||
newDealerUser.setSortNumber(0);
|
||||
newDealerUser.setFirstNum(0);
|
||||
newDealerUser.setSecondNum(0);
|
||||
newDealerUser.setThirdNum(0);
|
||||
newDealerUser.setMoney(BigDecimal.ZERO);
|
||||
newDealerUser.setFreezeMoney(BigDecimal.ZERO);
|
||||
newDealerUser.setTotalMoney(BigDecimal.ZERO);
|
||||
newDealerUser.setCreateTime(now);
|
||||
newDealerUser.setUpdateTime(now);
|
||||
shopDealerUserService.save(newDealerUser);
|
||||
|
||||
dealerUser = shopDealerUserService.getOne(
|
||||
new LambdaQueryWrapper<ShopDealerUser>()
|
||||
.eq(ShopDealerUser::getTenantId, TENANT_ID)
|
||||
.eq(ShopDealerUser::getUserId, riderId)
|
||||
.last("limit 1 for update")
|
||||
);
|
||||
if (dealerUser == null) {
|
||||
log.warn("配送奖励入账失败:未找到/创建分销账户 - tenantId={}, orderNo={}, riderId={}", TENANT_ID, orderNo, riderId);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
BigDecimal moneyVal = dealerUser.getMoney() != null ? dealerUser.getMoney() : BigDecimal.ZERO;
|
||||
BigDecimal totalMoneyVal = dealerUser.getTotalMoney() != null ? dealerUser.getTotalMoney() : BigDecimal.ZERO;
|
||||
dealerUser.setMoney(moneyVal.add(reward));
|
||||
dealerUser.setTotalMoney(totalMoneyVal.add(reward));
|
||||
dealerUser.setUpdateTime(now);
|
||||
if (!shopDealerUserService.updateById(dealerUser)) {
|
||||
log.warn("配送奖励入账失败:更新分销账户失败 - tenantId={}, orderNo={}, riderId={}, reward={}", TENANT_ID, orderNo, riderId, reward);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
BigDecimal moneyVal = dealerUser.getMoney() != null ? dealerUser.getMoney() : BigDecimal.ZERO;
|
||||
BigDecimal totalMoneyVal = dealerUser.getTotalMoney() != null ? dealerUser.getTotalMoney() : BigDecimal.ZERO;
|
||||
dealerUser.setMoney(moneyVal.add(reward));
|
||||
dealerUser.setTotalMoney(totalMoneyVal.add(reward));
|
||||
dealerUser.setUpdateTime(now);
|
||||
if (!shopDealerUserService.updateById(dealerUser)) {
|
||||
log.warn("配送奖励入账失败:更新分销账户失败 - tenantId={}, orderNo={}, riderId={}, reward={}", TENANT_ID, orderNo, riderId, reward);
|
||||
return false;
|
||||
}
|
||||
ShopDealerCapital cap = new ShopDealerCapital();
|
||||
cap.setUserId(riderId);
|
||||
cap.setOrderNo(orderNo);
|
||||
cap.setFlowType(FLOW_TYPE_DELIVERY_REWARD);
|
||||
cap.setMoney(reward);
|
||||
cap.setComments("配送奖励");
|
||||
cap.setToUserId(order.getUserId());
|
||||
cap.setMonth(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM")));
|
||||
cap.setTenantId(TENANT_ID);
|
||||
cap.setCreateTime(now);
|
||||
cap.setUpdateTime(now);
|
||||
shopDealerCapitalService.save(cap);
|
||||
|
||||
ShopDealerCapital cap = new ShopDealerCapital();
|
||||
cap.setUserId(riderId);
|
||||
cap.setOrderNo(orderNo);
|
||||
cap.setFlowType(FLOW_TYPE_DELIVERY_REWARD);
|
||||
cap.setMoney(reward);
|
||||
cap.setComments("配送奖励");
|
||||
cap.setToUserId(order.getUserId());
|
||||
cap.setMonth(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM")));
|
||||
cap.setTenantId(TENANT_ID);
|
||||
cap.setCreateTime(now);
|
||||
cap.setUpdateTime(now);
|
||||
shopDealerCapitalService.save(cap);
|
||||
|
||||
log.info("配送奖励发放成功 - tenantId={}, orderNo={}, riderId={}, reward={}", TENANT_ID, orderNo, riderId, reward);
|
||||
return true;
|
||||
}));
|
||||
log.info("【步骤5.X】配送奖励发放成功 - tenantId={}, orderNo={}, riderId={}, reward={}", TENANT_ID, orderNo, riderId, reward);
|
||||
return true;
|
||||
}));
|
||||
} catch (Exception e) {
|
||||
log.error("【步骤5.X】配送奖励发放异常 - tenantId={}, orderNo={}, error={}", TENANT_ID, orderNo, e.getMessage(), e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private Set<Integer> loadWaterFormIds() {
|
||||
@@ -408,10 +469,11 @@ public class DealerCommissionUnfreeze10584Task {
|
||||
}
|
||||
|
||||
private Set<String> findEligibleWaterOrderNosByFirstFinishedTicketOrder(Set<Integer> waterFormIds) {
|
||||
// 缓存减少 DB 往返:userTicketId -> 是否“第一次送水单已完成”
|
||||
// 缓存减少 DB 往返:userTicketId -> 是否"第一次送水单已完成"
|
||||
Map<Integer, Boolean> firstFinishedCache = new HashMap<>();
|
||||
Map<Integer, String> userTicketOrderNoCache = new HashMap<>();
|
||||
|
||||
log.info("【步骤3.1】查询已完成的送水订单 - tenantId={}, limit={}", TENANT_ID, MAX_ELIGIBLE_TICKET_ORDERS_PER_RUN);
|
||||
List<GltTicketOrder> finishedTicketOrders = gltTicketOrderService.list(
|
||||
new LambdaQueryWrapper<GltTicketOrder>()
|
||||
.eq(GltTicketOrder::getTenantId, TENANT_ID)
|
||||
@@ -421,21 +483,27 @@ public class DealerCommissionUnfreeze10584Task {
|
||||
.orderByDesc(GltTicketOrder::getId)
|
||||
.last("limit " + MAX_ELIGIBLE_TICKET_ORDERS_PER_RUN)
|
||||
);
|
||||
log.info("【步骤3.1】查到已完成的送水订单数量 - tenantId={}, count={}", TENANT_ID, finishedTicketOrders.size());
|
||||
|
||||
Set<String> orderNos = new HashSet<>();
|
||||
int checked = 0, skippedNull = 0, skippedNotFirst = 0, skippedNoOrderNo = 0, skippedNotWater = 0;
|
||||
for (GltTicketOrder ticketOrder : finishedTicketOrders) {
|
||||
Integer userTicketId = ticketOrder.getUserTicketId();
|
||||
checked++;
|
||||
if (userTicketId == null) {
|
||||
skippedNull++;
|
||||
continue;
|
||||
}
|
||||
|
||||
boolean firstFinished = firstFinishedCache.computeIfAbsent(userTicketId, id -> isFirstTicketOrderFinished(id));
|
||||
if (!firstFinished) {
|
||||
skippedNotFirst++;
|
||||
continue;
|
||||
}
|
||||
|
||||
String orderNo = userTicketOrderNoCache.computeIfAbsent(userTicketId, id -> findOrderNoByUserTicketId(id));
|
||||
if (orderNo == null || orderNo.isBlank()) {
|
||||
skippedNoOrderNo++;
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -449,6 +517,7 @@ public class DealerCommissionUnfreeze10584Task {
|
||||
.last("limit 1")
|
||||
);
|
||||
if (shopOrder == null || shopOrder.getFormId() == null || !waterFormIds.contains(shopOrder.getFormId())) {
|
||||
skippedNotWater++;
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -457,6 +526,8 @@ public class DealerCommissionUnfreeze10584Task {
|
||||
break;
|
||||
}
|
||||
}
|
||||
log.info("【步骤3.2】送水订单筛选完成 - tenantId={}, checked={}, skippedNull={}, skippedNotFirst={}, skippedNoOrderNo={}, skippedNotWater={}, matched={}, orderNos={}",
|
||||
TENANT_ID, checked, skippedNull, skippedNotFirst, skippedNoOrderNo, skippedNotWater, orderNos.size(), orderNos);
|
||||
return orderNos;
|
||||
}
|
||||
|
||||
@@ -493,7 +564,9 @@ public class DealerCommissionUnfreeze10584Task {
|
||||
if (eligibleOrderNos == null || eligibleOrderNos.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
return shopDealerCapitalService.list(
|
||||
// 先按 eligibleOrderNos 集合的顺序(最新订单优先)处理佣金
|
||||
// 注意:MyBatis-Plus 的 in 查询会保持 in() 列表的顺序
|
||||
List<ShopDealerCapital> capitals = shopDealerCapitalService.list(
|
||||
new LambdaQueryWrapper<ShopDealerCapital>()
|
||||
.eq(ShopDealerCapital::getTenantId, TENANT_ID)
|
||||
.eq(ShopDealerCapital::getFlowType, 10)
|
||||
@@ -502,6 +575,14 @@ public class DealerCommissionUnfreeze10584Task {
|
||||
.orderByAsc(ShopDealerCapital::getId)
|
||||
.last("limit " + MAX_CAPITALS_PER_RUN)
|
||||
);
|
||||
// 按 eligibleOrderNos 的顺序重新排序(最新订单优先)
|
||||
List<String> orderList = List.copyOf(eligibleOrderNos);
|
||||
capitals.sort((a, b) -> {
|
||||
int idxA = orderList.indexOf(a.getOrderNo());
|
||||
int idxB = orderList.indexOf(b.getOrderNo());
|
||||
return Integer.compare(idxA, idxB);
|
||||
});
|
||||
return capitals;
|
||||
}
|
||||
|
||||
private boolean unfreezeOneCapitalIfNeeded(ShopDealerCapital cap) {
|
||||
@@ -546,7 +627,7 @@ public class DealerCommissionUnfreeze10584Task {
|
||||
return false;
|
||||
}
|
||||
|
||||
// RR 隔离级别下,先锁 user 行,再用锁定读检查 marker,避免“读到旧快照”导致重复解冻。
|
||||
// RR 隔离级别下,先锁 user 行,再用锁定读检查 marker,避免"读到旧快照"导致重复解冻。
|
||||
ShopDealerCapital existedMarker = shopDealerCapitalService.getOne(
|
||||
new LambdaQueryWrapper<ShopDealerCapital>()
|
||||
.eq(ShopDealerCapital::getTenantId, TENANT_ID)
|
||||
@@ -590,7 +671,7 @@ public class DealerCommissionUnfreeze10584Task {
|
||||
marker.setUpdateTime(now);
|
||||
shopDealerCapitalService.save(marker);
|
||||
|
||||
// 佣金全部解冻完成后,将分销订单状态置为“已解冻”(0)。
|
||||
// 佣金全部解冻完成后,将分销订单状态置为"已解冻"(0)。
|
||||
// 以当前任务生成的 flowType=50 marker 数量作为完成度判断,避免提前将订单置为已解冻。
|
||||
setDealerOrderUnfrozenIfCompleted(orderNo, now);
|
||||
|
||||
|
||||
@@ -620,7 +620,8 @@ public class DealerOrderSettlement10584Task {
|
||||
newDealerUser.setTotalMoney(BigDecimal.ZERO);
|
||||
// 尽量补齐基础信息,避免表字段 NOT NULL 导致插入失败(插入失败会让门店分佣“找到了人但入不了账”)。
|
||||
try {
|
||||
User sysUser = userMapper.selectByIdIgnoreTenant(dealerUserId);
|
||||
List<User> sysUsers = userMapper.selectByIdIgnoreTenant(dealerUserId);
|
||||
User sysUser = (sysUsers != null && !sysUsers.isEmpty()) ? sysUsers.get(0) : null;
|
||||
if (sysUser != null) {
|
||||
newDealerUser.setRealName(sysUser.getRealName() != null ? sysUser.getRealName() : sysUser.getNickname());
|
||||
newDealerUser.setMobile(sysUser.getPhone());
|
||||
|
||||
@@ -25,6 +25,7 @@ import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 分销商订单记录表控制器
|
||||
@@ -168,4 +169,22 @@ public class ShopDealerOrderController extends BaseController {
|
||||
}
|
||||
return fail("导入失败", null);
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('shop:shopDealerOrder:update')")
|
||||
@OperationLog
|
||||
@Operation(summary = "手动触发单条订单佣金解冻")
|
||||
@PostMapping("/unfreeze")
|
||||
public ApiResult<String> manualUnfreeze(@RequestBody Map<String, Object> body) {
|
||||
String orderNo = (String) body.get("orderNo");
|
||||
if (orderNo == null || orderNo.isBlank()) {
|
||||
return fail("订单编号不能为空", null);
|
||||
}
|
||||
Integer tenantId = getTenantId();
|
||||
try {
|
||||
String detail = shopDealerOrderService.manualUnfreeze(orderNo, tenantId);
|
||||
return success("解冻执行完成", detail);
|
||||
} catch (Exception e) {
|
||||
return fail(e.getMessage(),null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -35,7 +35,7 @@ import com.wechat.pay.java.core.notification.NotificationConfig;
|
||||
import com.wechat.pay.java.core.notification.NotificationParser;
|
||||
import com.wechat.pay.java.core.notification.RequestParam;
|
||||
import com.wechat.pay.java.core.RSAAutoCertificateConfig;
|
||||
import com.wechat.pay.java.service.partnerpayments.jsapi.model.Transaction;
|
||||
import com.wechat.pay.java.service.payments.model.Transaction;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
@@ -53,6 +53,7 @@ import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* 订单控制器
|
||||
@@ -65,6 +66,8 @@ import java.util.Objects;
|
||||
@RequestMapping("/api/shop/shop-order")
|
||||
public class ShopOrderController extends BaseController {
|
||||
private static final Logger logger = LoggerFactory.getLogger(ShopOrderController.class);
|
||||
/** 按商户号缓存 NotificationConfig,避免每次回调都重新拉取平台证书 */
|
||||
private final ConcurrentHashMap<String, NotificationConfig> notifyConfigCache = new ConcurrentHashMap<>();
|
||||
@Resource
|
||||
private ShopOrderService shopOrderService;
|
||||
@Resource
|
||||
@@ -438,15 +441,16 @@ public class ShopOrderController extends BaseController {
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('shop:shopOrder:refund')")
|
||||
@Operation(summary = "订单退款操作(申请退款/同意退款)", description = "orderStatus=4 申请退款;orderStatus=6 同意退款并发起原路退款")
|
||||
@Operation(summary = "订单退款操作(申请退款/同意退款/拒绝退款)", description = "orderStatus=4 申请退款;orderStatus=5 拒绝退款;orderStatus=6 同意退款并发起原路退款;orderStatus=7 客户端申请退款")
|
||||
@PutMapping("/refund")
|
||||
public ApiResult<?> refund(@RequestBody ShopOrder req) {
|
||||
if (req == null || req.getOrderId() == null || req.getOrderStatus() == null) {
|
||||
return fail("orderId 和 orderStatus 不能为空");
|
||||
}
|
||||
if (!Objects.equals(req.getOrderStatus(), 4) && !Objects.equals(req.getOrderStatus(), 6) && !Objects.equals(req.getOrderStatus(), 7)) {
|
||||
return fail("orderStatus 仅支持 4(申请退款) 或 6(同意退款) 或 7(客户端申请退款)");
|
||||
}
|
||||
if (req == null || req.getOrderId() == null || req.getOrderStatus() == null) {
|
||||
return fail("orderId 和 orderStatus 不能为空");
|
||||
}
|
||||
if (!Objects.equals(req.getOrderStatus(), 4) && !Objects.equals(req.getOrderStatus(), 5)
|
||||
&& !Objects.equals(req.getOrderStatus(), 6) && !Objects.equals(req.getOrderStatus(), 7)) {
|
||||
return fail("orderStatus 仅支持 4(申请退款)、5(拒绝退款)、6(同意退款)、7(客户端申请退款)");
|
||||
}
|
||||
|
||||
ShopOrder current = shopOrderService.getById(req.getOrderId());
|
||||
if (current == null) {
|
||||
@@ -791,90 +795,100 @@ public class ShopOrderController extends BaseController {
|
||||
.body(body)
|
||||
.build();
|
||||
|
||||
// 创建通知配置 - 使用与下单方法相同的证书配置逻辑
|
||||
// 创建通知配置 - 使用与下单方法相同的证书配置逻辑(按 mchId 缓存,避免重复拉取平台证书)
|
||||
NotificationConfig config;
|
||||
try {
|
||||
if (active.equals("dev")) {
|
||||
// 开发环境 - 构建包含租户号的私钥路径
|
||||
String tenantCertPath = "dev/wechat/" + tenantId;
|
||||
String privateKeyPath = tenantCertPath + "/" + certConfig.getWechatPay().getDev().getPrivateKeyFile();
|
||||
final String mchId = payment.getMchId();
|
||||
config = notifyConfigCache.get(mchId);
|
||||
if (config == null) {
|
||||
try {
|
||||
NotificationConfig newConfig;
|
||||
if (active.equals("dev")) {
|
||||
// 开发环境 - 构建包含租户号的私钥路径
|
||||
String tenantCertPath = "dev/wechat/" + tenantId;
|
||||
String privateKeyPath = tenantCertPath + "/" + certConfig.getWechatPay().getDev().getPrivateKeyFile();
|
||||
|
||||
logger.info("开发环境异步通知证书路径: {}", privateKeyPath);
|
||||
logger.info("租户ID: {}, 证书目录: {}", tenantId, tenantCertPath);
|
||||
logger.info("开发环境异步通知证书路径: {}", privateKeyPath);
|
||||
logger.info("租户ID: {}, 证书目录: {}", tenantId, tenantCertPath);
|
||||
|
||||
// 检查证书文件是否存在
|
||||
if (!certificateLoader.certificateExists(privateKeyPath)) {
|
||||
logger.error("证书文件不存在: {}", privateKeyPath);
|
||||
throw new RuntimeException("证书文件不存在: " + privateKeyPath);
|
||||
// 检查证书文件是否存在
|
||||
if (!certificateLoader.certificateExists(privateKeyPath)) {
|
||||
logger.error("证书文件不存在: {}", privateKeyPath);
|
||||
throw new RuntimeException("证书文件不存在: " + privateKeyPath);
|
||||
}
|
||||
|
||||
String privateKey = certificateLoader.loadCertificatePath(privateKeyPath);
|
||||
|
||||
// 使用验证器获取有效的 APIv3 密钥
|
||||
String apiV3Key = wechatPayConfigValidator.getValidApiV3Key(payment);
|
||||
|
||||
logger.info("私钥文件加载成功: {}", privateKey);
|
||||
logger.info("使用APIv3密钥来源: {}", payment.getApiKey() != null && !payment.getApiKey().trim().isEmpty() ? "数据库配置" : "配置文件默认");
|
||||
logger.info("APIv3密钥长度: {}", apiV3Key != null ? apiV3Key.length() : 0);
|
||||
logger.info("商户证书序列号: {}", payment.getMerchantSerialNumber());
|
||||
|
||||
// 使用自动证书配置
|
||||
newConfig = new RSAAutoCertificateConfig.Builder()
|
||||
.merchantId(mchId)
|
||||
.privateKeyFromPath(privateKey)
|
||||
.merchantSerialNumber(payment.getMerchantSerialNumber())
|
||||
.apiV3Key(apiV3Key)
|
||||
.build();
|
||||
|
||||
logger.info("✅ 开发环境使用自动证书配置创建通知解析器成功");
|
||||
} else {
|
||||
// 生产环境 - 使用自动证书配置
|
||||
final String certRootPath = certConfig.getCertRootPath();
|
||||
logger.info("生产环境证书根路径: {}", certRootPath);
|
||||
|
||||
String privateKeyRelativePath = payment.getApiclientKey();
|
||||
logger.info("数据库中的私钥相对路径: {}", privateKeyRelativePath);
|
||||
|
||||
// 生产环境已经没有/file目录,所有路径都直接拼接到根路径
|
||||
String privateKeyFullPath;
|
||||
// 处理数据库中可能存在的历史路径格式
|
||||
String cleanPath = privateKeyRelativePath;
|
||||
if (privateKeyRelativePath.startsWith("/file/")) {
|
||||
// 去掉历史的 /file/ 前缀
|
||||
cleanPath = privateKeyRelativePath.substring(6);
|
||||
} else if (privateKeyRelativePath.startsWith("file/")) {
|
||||
// 去掉历史的 file/ 前缀
|
||||
cleanPath = privateKeyRelativePath.substring(5);
|
||||
}
|
||||
// 确保路径以 / 开头
|
||||
if (!cleanPath.startsWith("/")) {
|
||||
cleanPath = "/" + cleanPath;
|
||||
}
|
||||
privateKeyFullPath = certRootPath + cleanPath;
|
||||
|
||||
logger.info("生产环境私钥完整路径: {}", privateKeyFullPath);
|
||||
String privateKey = certificateLoader.loadCertificatePath(privateKeyFullPath);
|
||||
String apiV3Key = payment.getApiKey();
|
||||
|
||||
// 使用自动证书配置
|
||||
newConfig = new RSAAutoCertificateConfig.Builder()
|
||||
.merchantId(mchId)
|
||||
.privateKeyFromPath(privateKey)
|
||||
.merchantSerialNumber(payment.getMerchantSerialNumber())
|
||||
.apiV3Key(apiV3Key)
|
||||
.build();
|
||||
|
||||
logger.info("✅ 生产环境使用自动证书配置创建通知解析器成功");
|
||||
}
|
||||
|
||||
String privateKey = certificateLoader.loadCertificatePath(privateKeyPath);
|
||||
|
||||
// 使用验证器获取有效的 APIv3 密钥
|
||||
String apiV3Key = wechatPayConfigValidator.getValidApiV3Key(payment);
|
||||
|
||||
logger.info("私钥文件加载成功: {}", privateKey);
|
||||
logger.info("使用APIv3密钥来源: {}", payment.getApiKey() != null && !payment.getApiKey().trim().isEmpty() ? "数据库配置" : "配置文件默认");
|
||||
logger.info("APIv3密钥长度: {}", apiV3Key != null ? apiV3Key.length() : 0);
|
||||
logger.info("商户证书序列号: {}", payment.getMerchantSerialNumber());
|
||||
|
||||
// 使用自动证书配置
|
||||
config = new RSAAutoCertificateConfig.Builder()
|
||||
.merchantId(payment.getMchId())
|
||||
.privateKeyFromPath(privateKey)
|
||||
.merchantSerialNumber(payment.getMerchantSerialNumber())
|
||||
.apiV3Key(apiV3Key)
|
||||
.build();
|
||||
|
||||
logger.info("✅ 开发环境使用自动证书配置创建通知解析器成功");
|
||||
} else {
|
||||
// 生产环境 - 使用自动证书配置
|
||||
final String certRootPath = certConfig.getCertRootPath();
|
||||
logger.info("生产环境证书根路径: {}", certRootPath);
|
||||
|
||||
String privateKeyRelativePath = payment.getApiclientKey();
|
||||
logger.info("数据库中的私钥相对路径: {}", privateKeyRelativePath);
|
||||
|
||||
// 生产环境已经没有/file目录,所有路径都直接拼接到根路径
|
||||
String privateKeyFullPath;
|
||||
// 处理数据库中可能存在的历史路径格式
|
||||
String cleanPath = privateKeyRelativePath;
|
||||
if (privateKeyRelativePath.startsWith("/file/")) {
|
||||
// 去掉历史的 /file/ 前缀
|
||||
cleanPath = privateKeyRelativePath.substring(6);
|
||||
} else if (privateKeyRelativePath.startsWith("file/")) {
|
||||
// 去掉历史的 file/ 前缀
|
||||
cleanPath = privateKeyRelativePath.substring(5);
|
||||
}
|
||||
// 确保路径以 / 开头
|
||||
if (!cleanPath.startsWith("/")) {
|
||||
cleanPath = "/" + cleanPath;
|
||||
}
|
||||
privateKeyFullPath = certRootPath + cleanPath;
|
||||
|
||||
logger.info("生产环境私钥完整路径: {}", privateKeyFullPath);
|
||||
String privateKey = certificateLoader.loadCertificatePath(privateKeyFullPath);
|
||||
String apiV3Key = payment.getApiKey();
|
||||
|
||||
// 使用自动证书配置
|
||||
config = new RSAAutoCertificateConfig.Builder()
|
||||
.merchantId(payment.getMchId())
|
||||
.privateKeyFromPath(privateKey)
|
||||
.merchantSerialNumber(payment.getMerchantSerialNumber())
|
||||
.apiV3Key(apiV3Key)
|
||||
.build();
|
||||
|
||||
logger.info("✅ 生产环境使用自动证书配置创建通知解析器成功");
|
||||
// 放入缓存
|
||||
notifyConfigCache.putIfAbsent(mchId, newConfig);
|
||||
config = notifyConfigCache.get(mchId);
|
||||
} catch (Exception e) {
|
||||
logger.error("❌ 创建通知配置失败 - 租户ID: {}, 商户号: {}", tenantId, mchId, e);
|
||||
logger.error("🔍 错误详情: {}", e.getMessage());
|
||||
logger.error("💡 请检查:");
|
||||
logger.error("1. 证书文件是否存在且路径正确");
|
||||
logger.error("2. APIv3密钥是否配置正确");
|
||||
logger.error("3. 商户证书序列号是否正确");
|
||||
logger.error("4. 网络连接是否正常");
|
||||
throw new RuntimeException("微信支付通知配置失败: " + e.getMessage(), e);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error("❌ 创建通知配置失败 - 租户ID: {}, 商户号: {}", tenantId, payment.getMchId(), e);
|
||||
logger.error("🔍 错误详情: {}", e.getMessage());
|
||||
logger.error("💡 请检查:");
|
||||
logger.error("1. 证书文件是否存在且路径正确");
|
||||
logger.error("2. APIv3密钥是否配置正确");
|
||||
logger.error("3. 商户证书序列号是否正确");
|
||||
logger.error("4. 网络连接是否正常");
|
||||
throw new RuntimeException("微信支付通知配置失败: " + e.getMessage(), e);
|
||||
} else {
|
||||
logger.info("✅ 使用缓存的通知配置 - 商户号: {}", mchId);
|
||||
}
|
||||
|
||||
// 初始化 NotificationParser
|
||||
|
||||
@@ -329,6 +329,10 @@
|
||||
<update id="updateByOutTradeNo" parameterType="com.gxwebsoft.cms.entity.CmsWebsite">
|
||||
UPDATE shop_order
|
||||
<set>
|
||||
update_time = NOW(),
|
||||
<if test="param.expirationTime != null">
|
||||
expiration_time = #{param.expirationTime},
|
||||
</if>
|
||||
<if test="param.payType != null">
|
||||
pay_type = #{param.payType},
|
||||
</if>
|
||||
|
||||
@@ -39,4 +39,13 @@ public interface ShopDealerOrderService extends IService<ShopDealerOrder> {
|
||||
*/
|
||||
ShopDealerOrder getByIdRel(Integer id);
|
||||
|
||||
/**
|
||||
* 手动触发单条订单的佣金解冻(保留与定时任务相同的前置条件检查)
|
||||
*
|
||||
* @param orderNo 分销订单号
|
||||
* @param tenantId 租户ID
|
||||
* @return 解冻结果描述(包含成功/失败详情)
|
||||
*/
|
||||
String manualUnfreeze(String orderNo, Integer tenantId);
|
||||
|
||||
}
|
||||
|
||||
@@ -1,15 +1,43 @@
|
||||
package com.gxwebsoft.shop.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import com.gxwebsoft.shop.mapper.ShopDealerOrderMapper;
|
||||
import com.gxwebsoft.shop.service.ShopDealerOrderService;
|
||||
import com.gxwebsoft.common.core.exception.BusinessException;
|
||||
import com.gxwebsoft.glt.entity.GltTicketOrder;
|
||||
import com.gxwebsoft.glt.entity.GltTicketTemplate;
|
||||
import com.gxwebsoft.glt.entity.GltUserTicket;
|
||||
import com.gxwebsoft.glt.service.GltTicketOrderService;
|
||||
import com.gxwebsoft.glt.service.GltTicketTemplateService;
|
||||
import com.gxwebsoft.glt.service.GltUserTicketService;
|
||||
import com.gxwebsoft.shop.entity.ShopDealerCapital;
|
||||
import com.gxwebsoft.shop.entity.ShopDealerOrder;
|
||||
import com.gxwebsoft.shop.entity.ShopDealerUser;
|
||||
import com.gxwebsoft.shop.entity.ShopGoods;
|
||||
import com.gxwebsoft.shop.entity.ShopOrder;
|
||||
import com.gxwebsoft.shop.entity.ShopOrderGoods;
|
||||
import com.gxwebsoft.shop.mapper.ShopDealerOrderMapper;
|
||||
import com.gxwebsoft.shop.service.ShopDealerCapitalService;
|
||||
import com.gxwebsoft.shop.service.ShopDealerOrderService;
|
||||
import com.gxwebsoft.shop.param.ShopDealerOrderParam;
|
||||
import com.gxwebsoft.common.core.web.PageParam;
|
||||
import com.gxwebsoft.common.core.web.PageResult;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 分销商订单记录表Service实现
|
||||
@@ -18,8 +46,41 @@ import java.util.List;
|
||||
* @since 2025-08-12 11:55:18
|
||||
*/
|
||||
@Service
|
||||
@Slf4j
|
||||
public class ShopDealerOrderServiceImpl extends ServiceImpl<ShopDealerOrderMapper, ShopDealerOrder> implements ShopDealerOrderService {
|
||||
|
||||
private static final int ORDER_STATUS_CONFIRMED_RECEIVE = 1;
|
||||
private static final int FLOW_TYPE_COMMISSION = 10;
|
||||
private static final int FLOW_TYPE_UNFREEZE = 50;
|
||||
private static final int FLOW_TYPE_DELIVERY_REWARD = 60;
|
||||
|
||||
@Resource
|
||||
private TransactionTemplate transactionTemplate;
|
||||
|
||||
@Resource
|
||||
private com.gxwebsoft.shop.service.ShopOrderService shopOrderService;
|
||||
|
||||
@Resource
|
||||
private com.gxwebsoft.shop.service.ShopOrderGoodsService shopOrderGoodsService;
|
||||
|
||||
@Resource
|
||||
private com.gxwebsoft.shop.service.ShopGoodsService shopGoodsService;
|
||||
|
||||
@Resource
|
||||
private ShopDealerCapitalService shopDealerCapitalService;
|
||||
|
||||
@Resource
|
||||
private com.gxwebsoft.shop.service.ShopDealerUserService shopDealerUserService;
|
||||
|
||||
@Resource
|
||||
private GltUserTicketService gltUserTicketService;
|
||||
|
||||
@Resource
|
||||
private GltTicketOrderService gltTicketOrderService;
|
||||
|
||||
@Resource
|
||||
private GltTicketTemplateService gltTicketTemplateService;
|
||||
|
||||
@Override
|
||||
public PageResult<ShopDealerOrder> pageRel(ShopDealerOrderParam param) {
|
||||
PageParam<ShopDealerOrder, ShopDealerOrderParam> page = new PageParam<>(param);
|
||||
@@ -44,4 +105,436 @@ public class ShopDealerOrderServiceImpl extends ServiceImpl<ShopDealerOrderMappe
|
||||
return param.getOne(baseMapper.selectListRel(param));
|
||||
}
|
||||
|
||||
// ==================== 手动解冻 ====================
|
||||
|
||||
@Override
|
||||
public String manualUnfreeze(String orderNo, Integer tenantId) {
|
||||
StringBuilder result = new StringBuilder();
|
||||
result.append("【手动解冻】orderNo=").append(orderNo).append(", tenantId=").append(tenantId).append("\n");
|
||||
|
||||
// 1) 查分销订单
|
||||
ShopDealerOrder dealerOrder = this.getOne(
|
||||
new LambdaQueryWrapper<ShopDealerOrder>()
|
||||
.eq(ShopDealerOrder::getTenantId, tenantId)
|
||||
.eq(ShopDealerOrder::getOrderNo, orderNo)
|
||||
.last("limit 1")
|
||||
);
|
||||
if (dealerOrder == null) {
|
||||
throw new BusinessException("分销订单不存在: " + orderNo);
|
||||
}
|
||||
result.append(" 分销订单ID=").append(dealerOrder.getId())
|
||||
.append(", isSettled=").append(dealerOrder.getIsSettled())
|
||||
.append(", isUnfreeze=").append(dealerOrder.getIsUnfreeze()).append("\n");
|
||||
|
||||
if (dealerOrder.getIsSettled() == null || dealerOrder.getIsSettled() != 1) {
|
||||
throw new BusinessException("订单未结算,无法解冻");
|
||||
}
|
||||
if (dealerOrder.getIsUnfreeze() != null && dealerOrder.getIsUnfreeze() == 1) {
|
||||
throw new BusinessException("订单已解冻,无需重复操作");
|
||||
}
|
||||
|
||||
// 2) 查商城订单,判断解冻前置条件
|
||||
ShopOrder shopOrder = shopOrderService.getOne(
|
||||
new LambdaQueryWrapper<ShopOrder>()
|
||||
.eq(ShopOrder::getTenantId, tenantId)
|
||||
.eq(ShopOrder::getDeleted, 0)
|
||||
.eq(ShopOrder::getOrderNo, orderNo)
|
||||
.last("limit 1")
|
||||
);
|
||||
if (shopOrder == null) {
|
||||
throw new BusinessException("商城订单不存在: " + orderNo);
|
||||
}
|
||||
result.append(" 商城订单: payStatus=").append(shopOrder.getPayStatus())
|
||||
.append(", orderStatus=").append(shopOrder.getOrderStatus())
|
||||
.append(", formId=").append(shopOrder.getFormId()).append("\n");
|
||||
|
||||
// 3) 加载水票模板 goodsId 集合(用于判断是否送水套餐)
|
||||
Set<Integer> waterFormIds = gltTicketTemplateService.list(
|
||||
new LambdaQueryWrapper<GltTicketTemplate>()
|
||||
.eq(GltTicketTemplate::getTenantId, tenantId)
|
||||
.eq(GltTicketTemplate::getDeleted, 0)
|
||||
.isNotNull(GltTicketTemplate::getGoodsId)
|
||||
).stream()
|
||||
.map(GltTicketTemplate::getGoodsId)
|
||||
.collect(Collectors.toSet());
|
||||
result.append(" 水票模板goodsId集合: ").append(waterFormIds).append("\n");
|
||||
|
||||
boolean isWaterOrder = shopOrder.getFormId() != null && waterFormIds.contains(shopOrder.getFormId());
|
||||
result.append(" 是否送水套餐: ").append(isWaterOrder).append("\n");
|
||||
|
||||
// 4) 检查解冻前置条件
|
||||
if (isWaterOrder) {
|
||||
// 送水套餐:至少有一条送水订单 deliveryStatus=40(已完成)
|
||||
GltUserTicket userTicket = gltUserTicketService.getOne(
|
||||
new LambdaQueryWrapper<GltUserTicket>()
|
||||
.eq(GltUserTicket::getTenantId, tenantId)
|
||||
.eq(GltUserTicket::getDeleted, 0)
|
||||
.eq(GltUserTicket::getOrderNo, orderNo)
|
||||
.last("limit 1")
|
||||
);
|
||||
if (userTicket == null) {
|
||||
// 兜底:通过 orderId 反查
|
||||
userTicket = gltUserTicketService.getOne(
|
||||
new LambdaQueryWrapper<GltUserTicket>()
|
||||
.eq(GltUserTicket::getTenantId, tenantId)
|
||||
.eq(GltUserTicket::getDeleted, 0)
|
||||
.eq(GltUserTicket::getOrderId, shopOrder.getOrderId())
|
||||
.last("limit 1")
|
||||
);
|
||||
}
|
||||
if (userTicket == null) {
|
||||
throw new BusinessException("未找到关联的水票记录,无法确认送水状态");
|
||||
}
|
||||
|
||||
GltTicketOrder firstTicketOrder = gltTicketOrderService.getOne(
|
||||
new LambdaQueryWrapper<GltTicketOrder>()
|
||||
.eq(GltTicketOrder::getTenantId, tenantId)
|
||||
.eq(GltTicketOrder::getDeleted, 0)
|
||||
.eq(GltTicketOrder::getUserTicketId, userTicket.getId())
|
||||
.orderByAsc(GltTicketOrder::getId)
|
||||
.last("limit 1")
|
||||
);
|
||||
|
||||
boolean firstFinished = firstTicketOrder != null
|
||||
&& firstTicketOrder.getDeliveryStatus() != null
|
||||
&& firstTicketOrder.getDeliveryStatus() == GltTicketOrderService.DELIVERY_STATUS_FINISHED;
|
||||
|
||||
result.append(" 送水订单检查: userTicketId=").append(userTicket.getId())
|
||||
.append(", firstTicketOrderId=").append(firstTicketOrder != null ? firstTicketOrder.getId() : "null")
|
||||
.append(", deliveryStatus=").append(firstTicketOrder != null ? firstTicketOrder.getDeliveryStatus() : "null")
|
||||
.append(", firstFinished=").append(firstFinished).append("\n");
|
||||
|
||||
if (!firstFinished) {
|
||||
throw new BusinessException("送水套餐订单尚未完成第一次配送确认收货,不满足解冻条件");
|
||||
}
|
||||
} else {
|
||||
// 非送水套餐:商城订单 orderStatus=1(已确认收货)
|
||||
boolean orderCompleted = shopOrder.getOrderStatus() != null
|
||||
&& shopOrder.getOrderStatus() == ORDER_STATUS_CONFIRMED_RECEIVE
|
||||
&& shopOrder.getPayStatus() != null
|
||||
&& shopOrder.getPayStatus();
|
||||
|
||||
result.append(" 非送水订单检查: orderStatus=").append(shopOrder.getOrderStatus())
|
||||
.append(", payStatus=").append(shopOrder.getPayStatus())
|
||||
.append(", completed=").append(orderCompleted).append("\n");
|
||||
|
||||
if (!orderCompleted) {
|
||||
throw new BusinessException("订单尚未确认收货,不满足解冻条件 (orderStatus=" + shopOrder.getOrderStatus() + ")");
|
||||
}
|
||||
}
|
||||
|
||||
// 5) 发放配送奖励(幂等)
|
||||
result.append(" 开始发放配送奖励...\n");
|
||||
try {
|
||||
boolean rewarded = settleDeliveryRewardIfNeeded(orderNo, tenantId);
|
||||
result.append(" 配送奖励结果: ").append(rewarded ? "已发放" : "跳过(无配送员/已发放)").append("\n");
|
||||
} catch (Exception e) {
|
||||
result.append(" 配送奖励异常: ").append(e.getMessage()).append("\n");
|
||||
log.warn("手动解冻-配送奖励发放失败 - orderNo={}, error={}", orderNo, e.getMessage(), e);
|
||||
}
|
||||
|
||||
// 6) 查询该订单的佣金明细(flowType=10)
|
||||
List<ShopDealerCapital> capitals = shopDealerCapitalService.list(
|
||||
new LambdaQueryWrapper<ShopDealerCapital>()
|
||||
.eq(ShopDealerCapital::getTenantId, tenantId)
|
||||
.eq(ShopDealerCapital::getFlowType, FLOW_TYPE_COMMISSION)
|
||||
.eq(ShopDealerCapital::getOrderNo, orderNo)
|
||||
);
|
||||
result.append(" 佣金明细(flowType=10)数量: ").append(capitals.size()).append("\n");
|
||||
|
||||
if (capitals.isEmpty()) {
|
||||
throw new BusinessException("未找到佣金明细(flowType=10),无法解冻");
|
||||
}
|
||||
|
||||
// 7) 逐条执行解冻
|
||||
int unfrozen = 0;
|
||||
for (ShopDealerCapital cap : capitals) {
|
||||
try {
|
||||
boolean ok = unfreezeOneCapitalIfNeeded(cap, tenantId);
|
||||
if (ok) {
|
||||
unfrozen++;
|
||||
result.append(" 解冻成功: capitalId=").append(cap.getId())
|
||||
.append(", userId=").append(cap.getUserId())
|
||||
.append(", amount=").append(cap.getMoney()).append("\n");
|
||||
} else {
|
||||
result.append(" 解冻跳过(已解冻/幂等): capitalId=").append(cap.getId()).append("\n");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
result.append(" 解冻失败: capitalId=").append(cap.getId())
|
||||
.append(", error=").append(e.getMessage()).append("\n");
|
||||
log.error("手动解冻-单条佣金解冻失败 - orderNo={}, capitalId={}, error={}", orderNo, cap.getId(), e.getMessage(), e);
|
||||
}
|
||||
}
|
||||
|
||||
// 8) 检查是否全部解冻完成
|
||||
if (unfrozen > 0) {
|
||||
long totalCommissions = shopDealerCapitalService.count(
|
||||
new LambdaQueryWrapper<ShopDealerCapital>()
|
||||
.eq(ShopDealerCapital::getTenantId, tenantId)
|
||||
.eq(ShopDealerCapital::getFlowType, FLOW_TYPE_COMMISSION)
|
||||
.eq(ShopDealerCapital::getOrderNo, orderNo)
|
||||
);
|
||||
long unfrozenMarkers = shopDealerCapitalService.count(
|
||||
new LambdaQueryWrapper<ShopDealerCapital>()
|
||||
.eq(ShopDealerCapital::getTenantId, tenantId)
|
||||
.eq(ShopDealerCapital::getFlowType, FLOW_TYPE_UNFREEZE)
|
||||
.eq(ShopDealerCapital::getOrderNo, orderNo)
|
||||
.like(ShopDealerCapital::getComments, "佣金解冻(capitalId=")
|
||||
);
|
||||
result.append(" 解冻进度: ").append(unfrozenMarkers).append("/").append(totalCommissions).append("\n");
|
||||
|
||||
if (unfrozenMarkers >= totalCommissions) {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
boolean updated = this.update(
|
||||
new LambdaUpdateWrapper<ShopDealerOrder>()
|
||||
.eq(ShopDealerOrder::getTenantId, tenantId)
|
||||
.eq(ShopDealerOrder::getOrderNo, orderNo)
|
||||
.set(ShopDealerOrder::getIsUnfreeze, 1)
|
||||
.set(ShopDealerOrder::getUnfreezeTime, now)
|
||||
.set(ShopDealerOrder::getUpdateTime, now)
|
||||
);
|
||||
result.append(" 订单解冻状态更新: ").append(updated ? "成功(isUnfreeze=1)" : "失败").append("\n");
|
||||
}
|
||||
}
|
||||
|
||||
result.append("【手动解冻完成】共解冻 ").append(unfrozen).append("/").append(capitals.size()).append(" 条佣金");
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 发放配送奖励(从定时任务复制,支持 tenantId 参数)
|
||||
*/
|
||||
private boolean settleDeliveryRewardIfNeeded(String orderNo, Integer tenantId) {
|
||||
if (orderNo == null || orderNo.isBlank() || tenantId == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
ShopOrder order = shopOrderService.getOne(
|
||||
new LambdaQueryWrapper<ShopOrder>()
|
||||
.eq(ShopOrder::getTenantId, tenantId)
|
||||
.eq(ShopOrder::getDeleted, 0)
|
||||
.eq(ShopOrder::getOrderNo, orderNo)
|
||||
.last("limit 1")
|
||||
);
|
||||
if (order == null) return false;
|
||||
|
||||
Integer riderId = order.getRiderId();
|
||||
if (riderId == null || riderId <= 0) return false;
|
||||
|
||||
// 幂等检查
|
||||
boolean already = shopDealerCapitalService.count(
|
||||
new LambdaQueryWrapper<ShopDealerCapital>()
|
||||
.eq(ShopDealerCapital::getTenantId, tenantId)
|
||||
.eq(ShopDealerCapital::getFlowType, FLOW_TYPE_DELIVERY_REWARD)
|
||||
.eq(ShopDealerCapital::getOrderNo, orderNo)
|
||||
) > 0;
|
||||
if (already) return false;
|
||||
|
||||
return Boolean.TRUE.equals(transactionTemplate.execute(status -> {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
|
||||
// 锁定 marker 幂等
|
||||
ShopDealerCapital existedMarker = shopDealerCapitalService.getOne(
|
||||
new LambdaQueryWrapper<ShopDealerCapital>()
|
||||
.eq(ShopDealerCapital::getTenantId, tenantId)
|
||||
.eq(ShopDealerCapital::getFlowType, FLOW_TYPE_DELIVERY_REWARD)
|
||||
.eq(ShopDealerCapital::getOrderNo, orderNo)
|
||||
.last("limit 1 for update")
|
||||
);
|
||||
if (existedMarker != null) return false;
|
||||
|
||||
Integer orderId = order.getOrderId();
|
||||
if (orderId == null) return false;
|
||||
|
||||
List<ShopOrderGoods> orderGoodsList = shopOrderGoodsService.list(
|
||||
new LambdaQueryWrapper<ShopOrderGoods>()
|
||||
.eq(ShopOrderGoods::getTenantId, tenantId)
|
||||
.eq(ShopOrderGoods::getOrderId, orderId)
|
||||
);
|
||||
if (orderGoodsList == null || orderGoodsList.isEmpty()) return false;
|
||||
|
||||
List<Integer> goodsIds = orderGoodsList.stream()
|
||||
.map(ShopOrderGoods::getGoodsId)
|
||||
.filter(Objects::nonNull)
|
||||
.distinct()
|
||||
.toList();
|
||||
if (goodsIds.isEmpty()) return false;
|
||||
|
||||
Map<Integer, BigDecimal> goodsDeliveryMoneyMap = shopGoodsService.list(
|
||||
new LambdaQueryWrapper<ShopGoods>()
|
||||
.eq(ShopGoods::getTenantId, tenantId)
|
||||
.in(ShopGoods::getGoodsId, goodsIds)
|
||||
).stream().collect(Collectors.toMap(
|
||||
ShopGoods::getGoodsId,
|
||||
g -> g.getDeliveryMoney() != null ? g.getDeliveryMoney() : BigDecimal.ZERO,
|
||||
(a, b) -> a
|
||||
));
|
||||
|
||||
BigDecimal reward = BigDecimal.ZERO;
|
||||
for (ShopOrderGoods og : orderGoodsList) {
|
||||
Integer goodsId = og.getGoodsId();
|
||||
if (goodsId == null) continue;
|
||||
int qty = og.getTotalNum() == null ? 0 : og.getTotalNum();
|
||||
if (qty <= 0) continue;
|
||||
BigDecimal rawRate = goodsDeliveryMoneyMap.getOrDefault(goodsId, BigDecimal.ZERO);
|
||||
BigDecimal rate = normalizeDeliveryRate(rawRate);
|
||||
if (rate == null || rate.signum() <= 0) continue;
|
||||
BigDecimal unitPrice = og.getPrice() != null ? og.getPrice() : BigDecimal.ZERO;
|
||||
if (unitPrice.signum() <= 0) continue;
|
||||
BigDecimal lineAmount = unitPrice.multiply(BigDecimal.valueOf(qty));
|
||||
reward = reward.add(lineAmount.multiply(rate));
|
||||
}
|
||||
|
||||
reward = reward.setScale(2, RoundingMode.HALF_UP);
|
||||
if (reward.signum() <= 0) return false;
|
||||
|
||||
// 锁定/创建配送员分销账户
|
||||
ShopDealerUser dealerUser = shopDealerUserService.getOne(
|
||||
new LambdaQueryWrapper<ShopDealerUser>()
|
||||
.eq(ShopDealerUser::getTenantId, tenantId)
|
||||
.eq(ShopDealerUser::getUserId, riderId)
|
||||
.last("limit 1 for update")
|
||||
);
|
||||
if (dealerUser == null) {
|
||||
ShopDealerUser newDealerUser = new ShopDealerUser();
|
||||
newDealerUser.setTenantId(tenantId);
|
||||
newDealerUser.setUserId(riderId);
|
||||
newDealerUser.setType(0);
|
||||
newDealerUser.setIsDelete(0);
|
||||
newDealerUser.setSortNumber(0);
|
||||
newDealerUser.setFirstNum(0);
|
||||
newDealerUser.setSecondNum(0);
|
||||
newDealerUser.setThirdNum(0);
|
||||
newDealerUser.setMoney(BigDecimal.ZERO);
|
||||
newDealerUser.setFreezeMoney(BigDecimal.ZERO);
|
||||
newDealerUser.setTotalMoney(BigDecimal.ZERO);
|
||||
newDealerUser.setCreateTime(now);
|
||||
newDealerUser.setUpdateTime(now);
|
||||
shopDealerUserService.save(newDealerUser);
|
||||
dealerUser = shopDealerUserService.getOne(
|
||||
new LambdaQueryWrapper<ShopDealerUser>()
|
||||
.eq(ShopDealerUser::getTenantId, tenantId)
|
||||
.eq(ShopDealerUser::getUserId, riderId)
|
||||
.last("limit 1 for update")
|
||||
);
|
||||
if (dealerUser == null) return false;
|
||||
}
|
||||
|
||||
BigDecimal moneyVal = dealerUser.getMoney() != null ? dealerUser.getMoney() : BigDecimal.ZERO;
|
||||
BigDecimal totalMoneyVal = dealerUser.getTotalMoney() != null ? dealerUser.getTotalMoney() : BigDecimal.ZERO;
|
||||
dealerUser.setMoney(moneyVal.add(reward));
|
||||
dealerUser.setTotalMoney(totalMoneyVal.add(reward));
|
||||
dealerUser.setUpdateTime(now);
|
||||
if (!shopDealerUserService.updateById(dealerUser)) return false;
|
||||
|
||||
ShopDealerCapital cap = new ShopDealerCapital();
|
||||
cap.setUserId(riderId);
|
||||
cap.setOrderNo(orderNo);
|
||||
cap.setFlowType(FLOW_TYPE_DELIVERY_REWARD);
|
||||
cap.setMoney(reward);
|
||||
cap.setComments("配送奖励");
|
||||
cap.setToUserId(order.getUserId());
|
||||
cap.setMonth(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM")));
|
||||
cap.setTenantId(tenantId);
|
||||
cap.setCreateTime(now);
|
||||
cap.setUpdateTime(now);
|
||||
shopDealerCapitalService.save(cap);
|
||||
|
||||
log.info("手动解冻-配送奖励发放成功 - orderNo={}, riderId={}, reward={}", orderNo, riderId, reward);
|
||||
return true;
|
||||
}));
|
||||
}
|
||||
|
||||
/**
|
||||
* 解冻单条佣金(从定时任务复制,支持 tenantId 参数)
|
||||
*/
|
||||
private boolean unfreezeOneCapitalIfNeeded(ShopDealerCapital cap, Integer tenantId) {
|
||||
if (cap == null) return false;
|
||||
Integer capitalId = cap.getId();
|
||||
Integer dealerUserId = cap.getUserId();
|
||||
String orderNo = cap.getOrderNo();
|
||||
BigDecimal amount = cap.getMoney();
|
||||
if (capitalId == null || dealerUserId == null || orderNo == null || orderNo.isBlank() || amount == null || amount.signum() <= 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
String markerComment = "佣金解冻(capitalId=" + capitalId + ")";
|
||||
|
||||
// 快速幂等检查
|
||||
boolean already = shopDealerCapitalService.count(
|
||||
new LambdaQueryWrapper<ShopDealerCapital>()
|
||||
.eq(ShopDealerCapital::getTenantId, tenantId)
|
||||
.eq(ShopDealerCapital::getFlowType, FLOW_TYPE_UNFREEZE)
|
||||
.eq(ShopDealerCapital::getUserId, dealerUserId)
|
||||
.eq(ShopDealerCapital::getOrderNo, orderNo)
|
||||
.eq(ShopDealerCapital::getComments, markerComment)
|
||||
) > 0;
|
||||
if (already) return false;
|
||||
|
||||
return Boolean.TRUE.equals(transactionTemplate.execute(status -> {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
|
||||
ShopDealerUser dealerUser = shopDealerUserService.getOne(
|
||||
new LambdaQueryWrapper<ShopDealerUser>()
|
||||
.eq(ShopDealerUser::getTenantId, tenantId)
|
||||
.eq(ShopDealerUser::getUserId, dealerUserId)
|
||||
.last("limit 1 for update")
|
||||
);
|
||||
if (dealerUser == null) {
|
||||
log.warn("手动解冻失败:未找到分销账户 - orderNo={}, dealerUserId={}, amount={}", orderNo, dealerUserId, amount);
|
||||
return false;
|
||||
}
|
||||
|
||||
// 二次幂等检查
|
||||
ShopDealerCapital existedMarker = shopDealerCapitalService.getOne(
|
||||
new LambdaQueryWrapper<ShopDealerCapital>()
|
||||
.eq(ShopDealerCapital::getTenantId, tenantId)
|
||||
.eq(ShopDealerCapital::getFlowType, FLOW_TYPE_UNFREEZE)
|
||||
.eq(ShopDealerCapital::getUserId, dealerUserId)
|
||||
.eq(ShopDealerCapital::getOrderNo, orderNo)
|
||||
.eq(ShopDealerCapital::getComments, markerComment)
|
||||
.last("limit 1 for update")
|
||||
);
|
||||
if (existedMarker != null) return false;
|
||||
|
||||
BigDecimal freezeMoney = dealerUser.getFreezeMoney() != null ? dealerUser.getFreezeMoney() : BigDecimal.ZERO;
|
||||
if (freezeMoney.compareTo(amount) < 0) {
|
||||
log.warn("手动解冻失败:冻结金额不足 - orderNo={}, dealerUserId={}, freezeMoney={}, amount={}",
|
||||
orderNo, dealerUserId, freezeMoney, amount);
|
||||
return false;
|
||||
}
|
||||
|
||||
BigDecimal moneyVal = dealerUser.getMoney() != null ? dealerUser.getMoney() : BigDecimal.ZERO;
|
||||
dealerUser.setFreezeMoney(freezeMoney.subtract(amount));
|
||||
dealerUser.setMoney(moneyVal.add(amount));
|
||||
dealerUser.setUpdateTime(now);
|
||||
if (!shopDealerUserService.updateById(dealerUser)) {
|
||||
log.warn("手动解冻失败:更新分销账户失败 - orderNo={}, dealerUserId={}, amount={}", orderNo, dealerUserId, amount);
|
||||
return false;
|
||||
}
|
||||
|
||||
ShopDealerCapital marker = new ShopDealerCapital();
|
||||
marker.setUserId(dealerUserId);
|
||||
marker.setOrderNo(orderNo);
|
||||
marker.setFlowType(FLOW_TYPE_UNFREEZE);
|
||||
marker.setMoney(amount);
|
||||
marker.setComments(markerComment);
|
||||
marker.setToUserId(cap.getToUserId());
|
||||
marker.setMonth(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM")));
|
||||
marker.setTenantId(tenantId);
|
||||
marker.setCreateTime(now);
|
||||
marker.setUpdateTime(now);
|
||||
shopDealerCapitalService.save(marker);
|
||||
|
||||
log.info("手动解冻成功 - orderNo={}, dealerUserId={}, amount={}, capitalId={}", orderNo, dealerUserId, amount, capitalId);
|
||||
return true;
|
||||
}));
|
||||
}
|
||||
|
||||
private static BigDecimal normalizeDeliveryRate(BigDecimal rawRate) {
|
||||
if (rawRate == null || rawRate.signum() <= 0) return null;
|
||||
if (rawRate.compareTo(BigDecimal.ONE) >= 0) return rawRate.movePointLeft(2);
|
||||
return rawRate;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -834,7 +834,6 @@ public class ShopOrderServiceImpl extends ServiceImpl<ShopOrderMapper, ShopOrder
|
||||
|
||||
@Override
|
||||
public void updateByOutTradeNo(ShopOrder order) {
|
||||
order.setExpirationTime(null);
|
||||
baseMapper.updateByOutTradeNo(order);
|
||||
|
||||
// 处理支付成功后的业务逻辑
|
||||
|
||||
@@ -1,73 +0,0 @@
|
||||
# 开发环境配置
|
||||
|
||||
# 服务器配置
|
||||
server:
|
||||
port: 9200
|
||||
|
||||
# 数据源配置
|
||||
spring:
|
||||
datasource:
|
||||
url: jdbc:mysql://1Panel-mysql-XsWW:3306/gltdb?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
|
||||
username: gltdb
|
||||
password: EeD4FtzyA5ksj7Bk
|
||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
type: com.alibaba.druid.pool.DruidDataSource
|
||||
|
||||
# redis
|
||||
redis:
|
||||
database: 0
|
||||
host: 1Panel-redis-GmNr
|
||||
port: 6379
|
||||
password: redis_t74P8C
|
||||
|
||||
# 日志配置
|
||||
logging:
|
||||
level:
|
||||
com.gxwebsoft: DEBUG
|
||||
com.baomidou.mybatisplus: DEBUG
|
||||
|
||||
socketio:
|
||||
host: localhost #IP地址
|
||||
|
||||
# MQTT配置
|
||||
mqtt:
|
||||
enabled: false # 添加开关来禁用MQTT服务
|
||||
host: tcp://132.232.214.96:1883
|
||||
username: swdev
|
||||
password: Sw20250523
|
||||
client-id-prefix: hjm_car_
|
||||
topic: /SW_GPS/#
|
||||
qos: 2
|
||||
connection-timeout: 10
|
||||
keep-alive-interval: 20
|
||||
auto-reconnect: true
|
||||
|
||||
# 框架配置
|
||||
config:
|
||||
# 基础模块接口
|
||||
server-url: https://glt-server.websoft.top/api
|
||||
# 业务模块接口
|
||||
api-url: https://glt-api.websoft.top/api
|
||||
upload-path: /Users/gxwebsoft/Documents/uploads/ # window(D:\Temp)
|
||||
|
||||
# 开发环境证书配置
|
||||
certificate:
|
||||
load-mode: CLASSPATH # 开发环境从classpath加载
|
||||
wechat-pay:
|
||||
dev:
|
||||
private-key-file: "apiclient_key.pem"
|
||||
apiclient-cert-file: "apiclient_cert.pem"
|
||||
wechatpay-cert-file: "wechatpay_cert.pem"
|
||||
|
||||
# 阿里云翻译配置
|
||||
aliyun:
|
||||
translate:
|
||||
access-key-id: LTAI5tEsyhW4GCKbds1qsopg
|
||||
access-key-secret: zltFlQrYVAoq2KMFDWgLa3GhkMNeyO
|
||||
endpoint: mt.cn-hangzhou.aliyuncs.com
|
||||
|
||||
# 微信支付-商家转账(升级版)转账场景报备信息(必须与商户平台 transfer_scene_id=1005 的报备信息一致)
|
||||
wechatpay:
|
||||
transfer:
|
||||
scene-id: 1005
|
||||
scene-report-infos-json: '[{"info_type":"岗位类型","info_content":"业务员"},{"info_type":"报酬说明","info_content":"配送费"}]'
|
||||
@@ -1,86 +0,0 @@
|
||||
# 服务器配置
|
||||
server:
|
||||
port: 9300
|
||||
# 数据源配置
|
||||
spring:
|
||||
datasource:
|
||||
url: jdbc:mysql://1Panel-mysql-XsWW:3306/gltdb?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
|
||||
username: gltdb
|
||||
password: EeD4FtzyA5ksj7Bk
|
||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
type: com.alibaba.druid.pool.DruidDataSource
|
||||
druid:
|
||||
remove-abandoned: true
|
||||
|
||||
# redis
|
||||
redis:
|
||||
database: 0
|
||||
host: 1Panel-redis-GmNr
|
||||
port: 6379
|
||||
password: redis_t74P8C
|
||||
|
||||
# 日志配置
|
||||
logging:
|
||||
file:
|
||||
name: websoft-modules.log
|
||||
level:
|
||||
root: WARN
|
||||
com.gxwebsoft: ERROR
|
||||
com.baomidou.mybatisplus: ERROR
|
||||
|
||||
socketio:
|
||||
host: 0.0.0.0 #IP地址
|
||||
|
||||
# MQTT配置
|
||||
mqtt:
|
||||
enabled: false # 启用MQTT服务
|
||||
host: tcp://132.232.214.96:1883
|
||||
username: swdev
|
||||
password: Sw20250523
|
||||
client-id-prefix: hjm_car_
|
||||
topic: /SW_GPS/#
|
||||
qos: 2
|
||||
connection-timeout: 10
|
||||
keep-alive-interval: 20
|
||||
auto-reconnect: true
|
||||
|
||||
# 框架配置
|
||||
config:
|
||||
# 文件服务器
|
||||
file-server: https://file-s209.shoplnk.cn
|
||||
# 生产环境接口
|
||||
server-url: https://glt-server.websoft.top/api
|
||||
# 业务模块接口
|
||||
api-url: https://glt-api.websoft.top/api
|
||||
upload-path: /www/wwwroot/file.ws
|
||||
|
||||
# 阿里云OSS云存储
|
||||
endpoint: https://oss-cn-shenzhen.aliyuncs.com
|
||||
accessKeyId: LTAI4GKGZ9Z2Z8JZ77c3GNZP
|
||||
accessKeySecret: BiDkpS7UXj72HWwDWaFZxiXjNFBNCM
|
||||
bucketName: oss-gxwebsoft
|
||||
bucketDomain: https://oss.wsdns.cn
|
||||
aliyunDomain: https://oss-gxwebsoft.oss-cn-shenzhen.aliyuncs.com
|
||||
|
||||
# 生产环境证书配置
|
||||
certificate:
|
||||
load-mode: VOLUME # 生产环境从Docker挂载卷加载
|
||||
cert-root-path: /www/wwwroot/file.ws
|
||||
|
||||
# 支付配置缓存
|
||||
payment:
|
||||
cache:
|
||||
# 支付配置缓存键前缀,生产环境使用 Payment:1* 格式
|
||||
key-prefix: "Payment:1"
|
||||
# 缓存过期时间(小时)
|
||||
expire-hours: 24
|
||||
# 阿里云翻译配置
|
||||
aliyun:
|
||||
translate:
|
||||
access-key-id: LTAI5tEsyhW4GCKbds1qsopg
|
||||
access-key-secret: zltFlQrYVAoq2KMFDWgLa3GhkMNeyO
|
||||
endpoint: mt.cn-hangzhou.aliyuncs.com
|
||||
wechatpay:
|
||||
transfer:
|
||||
scene-id: 1005
|
||||
scene-report-infos-json: '[{"info_type":"岗位类型","info_content":"配送员"},{"info_type":"报酬说明","info_content":"12月份配送费"}]'
|
||||
@@ -42,10 +42,10 @@ public class ShopGenerator {
|
||||
// 是否在xml中添加二级缓存配置
|
||||
private static final boolean ENABLE_CACHE = false;
|
||||
// 数据库连接配置
|
||||
private static final String DB_URL = "jdbc:mysql://8.134.169.209:13306/modules?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8";
|
||||
private static final String DB_URL = "jdbc:mysql://8.134.55.105:13306/modules?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8";
|
||||
private static final String DB_DRIVER = "com.mysql.cj.jdbc.Driver";
|
||||
private static final String DB_USERNAME = "modules";
|
||||
private static final String DB_PASSWORD = "8YdLnk7KsPAyDXGA";
|
||||
private static final String DB_PASSWORD = "tYmmMGh5wpwXR3ae";
|
||||
// 包名
|
||||
private static final String PACKAGE_NAME = "com.gxwebsoft";
|
||||
// 模块名
|
||||
|
||||
@@ -1,136 +0,0 @@
|
||||
package com.gxwebsoft.payment.enums;
|
||||
|
||||
import com.gxwebsoft.payment.utils.PaymentTypeCompatibilityUtil;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* 支付方式枚举测试类
|
||||
* 验证支付方式优化后的功能正确性
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2025-08-30
|
||||
*/
|
||||
@DisplayName("支付方式枚举测试")
|
||||
class PaymentTypeTest {
|
||||
|
||||
@Test
|
||||
@DisplayName("测试核心支付方式")
|
||||
void testCorePaymentTypes() {
|
||||
// 测试8种核心支付方式
|
||||
assertEquals(PaymentType.BALANCE, PaymentType.getByCode(0));
|
||||
assertEquals(PaymentType.WECHAT, PaymentType.getByCode(1));
|
||||
assertEquals(PaymentType.ALIPAY, PaymentType.getByCode(2));
|
||||
assertEquals(PaymentType.UNION_PAY, PaymentType.getByCode(3));
|
||||
assertEquals(PaymentType.CASH, PaymentType.getByCode(4));
|
||||
assertEquals(PaymentType.POS, PaymentType.getByCode(5));
|
||||
assertEquals(PaymentType.FREE, PaymentType.getByCode(6));
|
||||
assertEquals(PaymentType.POINTS, PaymentType.getByCode(7));
|
||||
|
||||
// 验证核心支付方式标识
|
||||
assertTrue(PaymentType.BALANCE.isCorePaymentType());
|
||||
assertTrue(PaymentType.WECHAT.isCorePaymentType());
|
||||
assertTrue(PaymentType.ALIPAY.isCorePaymentType());
|
||||
assertTrue(PaymentType.UNION_PAY.isCorePaymentType());
|
||||
assertTrue(PaymentType.CASH.isCorePaymentType());
|
||||
assertTrue(PaymentType.POS.isCorePaymentType());
|
||||
assertTrue(PaymentType.FREE.isCorePaymentType());
|
||||
assertTrue(PaymentType.POINTS.isCorePaymentType());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("测试废弃支付方式")
|
||||
void testDeprecatedPaymentTypes() {
|
||||
// 测试废弃支付方式标识
|
||||
assertTrue(PaymentType.WECHAT_NATIVE.isDeprecated());
|
||||
assertTrue(PaymentType.MEMBER_CARD_OLD.isDeprecated());
|
||||
assertTrue(PaymentType.VIP_MONTHLY.isDeprecated());
|
||||
|
||||
// 验证废弃支付方式仍然可以通过代码获取(向后兼容)
|
||||
assertEquals(PaymentType.WECHAT_NATIVE, PaymentType.getByCode(102));
|
||||
assertEquals(PaymentType.FREE_OLD, PaymentType.getByCode(12));
|
||||
assertEquals(PaymentType.POINTS_OLD, PaymentType.getByCode(15));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("测试支付方式分类")
|
||||
void testPaymentTypeCategories() {
|
||||
// 测试微信支付类型
|
||||
assertTrue(PaymentType.WECHAT.isWechatPay());
|
||||
assertTrue(PaymentType.WECHAT_NATIVE.isWechatPay());
|
||||
|
||||
// 测试第三方支付
|
||||
assertTrue(PaymentType.WECHAT.isThirdPartyPay());
|
||||
assertTrue(PaymentType.ALIPAY.isThirdPartyPay());
|
||||
assertTrue(PaymentType.UNION_PAY.isThirdPartyPay());
|
||||
|
||||
// 测试在线支付
|
||||
assertTrue(PaymentType.WECHAT.isOnlinePay());
|
||||
assertTrue(PaymentType.ALIPAY.isOnlinePay());
|
||||
assertFalse(PaymentType.CASH.isOnlinePay());
|
||||
assertFalse(PaymentType.POS.isOnlinePay());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("测试兼容性工具类")
|
||||
void testCompatibilityUtil() {
|
||||
// 测试废弃支付方式转换
|
||||
assertEquals(Integer.valueOf(0), PaymentTypeCompatibilityUtil.convertToCore(2)); // 会员卡 -> 余额
|
||||
assertEquals(Integer.valueOf(1), PaymentTypeCompatibilityUtil.convertToCore(102)); // 微信Native -> 微信
|
||||
assertEquals(Integer.valueOf(2), PaymentTypeCompatibilityUtil.convertToCore(3)); // 支付宝编号调整
|
||||
assertEquals(Integer.valueOf(6), PaymentTypeCompatibilityUtil.convertToCore(12)); // 免费编号调整
|
||||
assertEquals(Integer.valueOf(7), PaymentTypeCompatibilityUtil.convertToCore(15)); // 积分编号调整
|
||||
assertEquals(Integer.valueOf(3), PaymentTypeCompatibilityUtil.convertToCore(19)); // 银联编号调整
|
||||
|
||||
// 测试核心支付方式不变
|
||||
assertEquals(Integer.valueOf(0), PaymentTypeCompatibilityUtil.convertToCore(0)); // 余额支付
|
||||
assertEquals(Integer.valueOf(1), PaymentTypeCompatibilityUtil.convertToCore(1)); // 微信支付
|
||||
assertEquals(Integer.valueOf(4), PaymentTypeCompatibilityUtil.convertToCore(4)); // 现金支付
|
||||
assertEquals(Integer.valueOf(5), PaymentTypeCompatibilityUtil.convertToCore(5)); // POS机支付
|
||||
|
||||
// 测试废弃检查
|
||||
assertTrue(PaymentTypeCompatibilityUtil.isDeprecated(102)); // 微信Native
|
||||
assertTrue(PaymentTypeCompatibilityUtil.isDeprecated(12)); // 免费(旧)
|
||||
assertTrue(PaymentTypeCompatibilityUtil.isDeprecated(15)); // 积分(旧)
|
||||
assertFalse(PaymentTypeCompatibilityUtil.isDeprecated(0)); // 余额支付
|
||||
assertFalse(PaymentTypeCompatibilityUtil.isDeprecated(1)); // 微信支付
|
||||
|
||||
// 测试核心支付方式检查
|
||||
assertTrue(PaymentTypeCompatibilityUtil.isCorePaymentType(0)); // 余额支付
|
||||
assertTrue(PaymentTypeCompatibilityUtil.isCorePaymentType(1)); // 微信支付
|
||||
assertTrue(PaymentTypeCompatibilityUtil.isCorePaymentType(2)); // 支付宝支付
|
||||
assertTrue(PaymentTypeCompatibilityUtil.isCorePaymentType(7)); // 积分支付
|
||||
assertFalse(PaymentTypeCompatibilityUtil.isCorePaymentType(102)); // 微信Native
|
||||
assertFalse(PaymentTypeCompatibilityUtil.isCorePaymentType(12)); // 免费(旧)
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("测试迁移消息")
|
||||
void testMigrationMessages() {
|
||||
// 测试废弃支付方式的迁移消息
|
||||
String message = PaymentTypeCompatibilityUtil.getMigrationMessage(102);
|
||||
assertNotNull(message);
|
||||
assertTrue(message.contains("微信Native"));
|
||||
assertTrue(message.contains("微信支付"));
|
||||
|
||||
// 测试核心支付方式无迁移消息
|
||||
assertNull(PaymentTypeCompatibilityUtil.getMigrationMessage(0));
|
||||
assertNull(PaymentTypeCompatibilityUtil.getMigrationMessage(1));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("测试迁移报告生成")
|
||||
void testMigrationReport() {
|
||||
String report = PaymentTypeCompatibilityUtil.generateMigrationReport();
|
||||
assertNotNull(report);
|
||||
assertTrue(report.contains("核心支付方式"));
|
||||
assertTrue(report.contains("废弃支付方式映射"));
|
||||
assertTrue(report.contains("余额支付"));
|
||||
assertTrue(report.contains("微信支付"));
|
||||
|
||||
System.out.println("=== 支付方式迁移报告 ===");
|
||||
System.out.println(report);
|
||||
}
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
package com.gxwebsoft.shop;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* 证书路径构建测试
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2025-08-09
|
||||
*/
|
||||
public class CertificatePathTest {
|
||||
|
||||
@Test
|
||||
public void testDevCertificatePath() {
|
||||
// 模拟开发环境配置
|
||||
String uploadPath = "/Users/gxwebsoft/JAVA/mp-java/src/main/resources/";
|
||||
Integer tenantId = 10324;
|
||||
String privateKeyFile = "apiclient_key.pem";
|
||||
|
||||
// 构建证书路径
|
||||
String tenantCertPath = uploadPath + "dev/wechat/" + tenantId;
|
||||
String privateKeyPath = tenantCertPath + "/" + privateKeyFile;
|
||||
|
||||
// 验证路径构建结果
|
||||
String expectedTenantPath = "/Users/gxwebsoft/JAVA/mp-java/src/main/resources/dev/wechat/10324";
|
||||
String expectedPrivateKeyPath = "/Users/gxwebsoft/JAVA/mp-java/src/main/resources/dev/wechat/10324/apiclient_key.pem";
|
||||
|
||||
assertEquals(expectedTenantPath, tenantCertPath);
|
||||
assertEquals(expectedPrivateKeyPath, privateKeyPath);
|
||||
|
||||
System.out.println("开发环境证书路径测试通过:");
|
||||
System.out.println("租户证书目录: " + tenantCertPath);
|
||||
System.out.println("私钥文件路径: " + privateKeyPath);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testProdCertificatePath() {
|
||||
// 模拟生产环境配置
|
||||
String uploadPath = "/www/wwwroot/file.ws";
|
||||
Integer tenantId = 10324;
|
||||
String privateKeyFile = "apiclient_key.pem";
|
||||
|
||||
// 构建证书路径(生产环境不使用upload-path,而是从数据库读取)
|
||||
// 这里只是为了对比展示
|
||||
String tenantCertPath = uploadPath + "dev/wechat/" + tenantId;
|
||||
String privateKeyPath = tenantCertPath + "/" + privateKeyFile;
|
||||
|
||||
// 验证路径构建结果
|
||||
String expectedTenantPath = "/www/wwwroot/file.ws/dev/wechat/10324";
|
||||
String expectedPrivateKeyPath = "/www/wwwroot/file.ws/dev/wechat/10324/apiclient_key.pem";
|
||||
|
||||
assertEquals(expectedTenantPath, tenantCertPath);
|
||||
assertEquals(expectedPrivateKeyPath, privateKeyPath);
|
||||
|
||||
System.out.println("生产环境证书路径测试通过:");
|
||||
System.out.println("租户证书目录: " + tenantCertPath);
|
||||
System.out.println("私钥文件路径: " + privateKeyPath);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMultipleTenants() {
|
||||
String uploadPath = "/Users/gxwebsoft/JAVA/mp-java/src/main/resources/";
|
||||
String privateKeyFile = "apiclient_key.pem";
|
||||
|
||||
// 测试多个租户的路径构建
|
||||
Integer[] tenantIds = {10324, 10325, 10326};
|
||||
|
||||
for (Integer tenantId : tenantIds) {
|
||||
String tenantCertPath = uploadPath + "dev/wechat/" + tenantId;
|
||||
String privateKeyPath = tenantCertPath + "/" + privateKeyFile;
|
||||
|
||||
assertTrue(tenantCertPath.contains(tenantId.toString()));
|
||||
assertTrue(privateKeyPath.endsWith(privateKeyFile));
|
||||
|
||||
System.out.println("租户 " + tenantId + " 证书路径: " + privateKeyPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,174 +0,0 @@
|
||||
package com.gxwebsoft.shop;
|
||||
|
||||
import com.gxwebsoft.common.system.entity.User;
|
||||
import com.gxwebsoft.shop.dto.OrderCreateRequest;
|
||||
import com.gxwebsoft.shop.entity.ShopGoods;
|
||||
import com.gxwebsoft.shop.entity.ShopGoodsSku;
|
||||
import com.gxwebsoft.shop.service.OrderBusinessService;
|
||||
import com.gxwebsoft.shop.service.ShopGoodsService;
|
||||
import com.gxwebsoft.shop.service.ShopGoodsSkuService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Arrays;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/**
|
||||
* 多规格订单测试类
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2025-07-30
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
public class MultiSpecOrderTest {
|
||||
|
||||
@Mock
|
||||
private ShopGoodsService shopGoodsService;
|
||||
|
||||
@Mock
|
||||
private ShopGoodsSkuService shopGoodsSkuService;
|
||||
|
||||
@InjectMocks
|
||||
private OrderBusinessService orderBusinessService;
|
||||
|
||||
private User testUser;
|
||||
private ShopGoods testGoods;
|
||||
private ShopGoodsSku testSku;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
// 创建测试用户
|
||||
testUser = new User();
|
||||
testUser.setUserId(1);
|
||||
testUser.setTenantId(1);
|
||||
testUser.setOpenid("test_openid");
|
||||
testUser.setPhone("13800138000");
|
||||
|
||||
// 创建测试商品
|
||||
testGoods = new ShopGoods();
|
||||
testGoods.setGoodsId(1);
|
||||
testGoods.setName("测试商品");
|
||||
testGoods.setPrice(new BigDecimal("100.00"));
|
||||
testGoods.setStock(50);
|
||||
testGoods.setStatus(0); // 正常状态
|
||||
testGoods.setImage("test.jpg");
|
||||
|
||||
// 创建测试SKU
|
||||
testSku = new ShopGoodsSku();
|
||||
testSku.setId(1);
|
||||
testSku.setGoodsId(1);
|
||||
testSku.setPrice(new BigDecimal("120.00"));
|
||||
testSku.setStock(20);
|
||||
testSku.setStatus(0); // 正常状态
|
||||
testSku.setSku("颜色:红色|尺寸:L");
|
||||
testSku.setImage("sku_test.jpg");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateOrderWithSingleSpec() {
|
||||
// 测试单规格商品下单
|
||||
when(shopGoodsService.getById(1)).thenReturn(testGoods);
|
||||
|
||||
OrderCreateRequest request = createOrderRequest(false);
|
||||
|
||||
// 这里需要mock其他依赖服务,实际测试中需要完整的Spring上下文
|
||||
// 此测试主要验证多规格逻辑的正确性
|
||||
|
||||
assertNotNull(request);
|
||||
assertEquals(1, request.getGoodsItems().size());
|
||||
assertNull(request.getGoodsItems().get(0).getSkuId());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateOrderWithMultiSpec() {
|
||||
// 测试多规格商品下单
|
||||
when(shopGoodsService.getById(1)).thenReturn(testGoods);
|
||||
when(shopGoodsSkuService.getById(1)).thenReturn(testSku);
|
||||
|
||||
OrderCreateRequest request = createOrderRequest(true);
|
||||
|
||||
assertNotNull(request);
|
||||
assertEquals(1, request.getGoodsItems().size());
|
||||
assertEquals(Integer.valueOf(1), request.getGoodsItems().get(0).getSkuId());
|
||||
assertEquals("颜色:红色|尺寸:L", request.getGoodsItems().get(0).getSpecInfo());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testSkuValidation() {
|
||||
// 测试SKU验证逻辑
|
||||
when(shopGoodsService.getById(1)).thenReturn(testGoods);
|
||||
|
||||
// 测试SKU不存在的情况
|
||||
when(shopGoodsSkuService.getById(999)).thenReturn(null);
|
||||
|
||||
OrderCreateRequest request = createOrderRequest(true);
|
||||
request.getGoodsItems().get(0).setSkuId(999); // 不存在的SKU ID
|
||||
|
||||
// 在实际测试中,这里应该抛出BusinessException
|
||||
// assertThrows(BusinessException.class, () -> orderBusinessService.createOrder(request, testUser));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testStockValidation() {
|
||||
// 测试库存验证
|
||||
testSku.setStock(1); // 设置库存为1
|
||||
when(shopGoodsService.getById(1)).thenReturn(testGoods);
|
||||
when(shopGoodsSkuService.getById(1)).thenReturn(testSku);
|
||||
|
||||
OrderCreateRequest request = createOrderRequest(true);
|
||||
request.getGoodsItems().get(0).setQuantity(5); // 购买数量超过库存
|
||||
|
||||
// 在实际测试中,这里应该抛出BusinessException
|
||||
// assertThrows(BusinessException.class, () -> orderBusinessService.createOrder(request, testUser));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testPriceCalculation() {
|
||||
// 测试价格计算
|
||||
when(shopGoodsService.getById(1)).thenReturn(testGoods);
|
||||
when(shopGoodsSkuService.getById(1)).thenReturn(testSku);
|
||||
|
||||
// 多规格商品应该使用SKU价格(120.00),而不是商品价格(100.00)
|
||||
OrderCreateRequest request = createOrderRequest(true);
|
||||
request.getGoodsItems().get(0).setQuantity(2);
|
||||
|
||||
// 期望总价格 = SKU价格(120.00) * 数量(2) = 240.00
|
||||
BigDecimal expectedTotal = new BigDecimal("240.00");
|
||||
request.setTotalPrice(expectedTotal);
|
||||
|
||||
assertEquals(expectedTotal, request.getTotalPrice());
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建订单请求对象
|
||||
*/
|
||||
private OrderCreateRequest createOrderRequest(boolean withSku) {
|
||||
OrderCreateRequest request = new OrderCreateRequest();
|
||||
request.setType(0);
|
||||
request.setTotalPrice(new BigDecimal("100.00"));
|
||||
request.setPayPrice(new BigDecimal("100.00"));
|
||||
request.setTotalNum(1);
|
||||
request.setTenantId(1);
|
||||
|
||||
OrderCreateRequest.OrderGoodsItem item = new OrderCreateRequest.OrderGoodsItem();
|
||||
item.setGoodsId(1);
|
||||
item.setQuantity(1);
|
||||
|
||||
if (withSku) {
|
||||
item.setSkuId(1);
|
||||
item.setSpecInfo("颜色:红色|尺寸:L");
|
||||
}
|
||||
|
||||
request.setGoodsItems(Arrays.asList(item));
|
||||
return request;
|
||||
}
|
||||
}
|
||||
@@ -1,170 +0,0 @@
|
||||
package com.gxwebsoft.shop;
|
||||
|
||||
import com.gxwebsoft.common.system.entity.User;
|
||||
import com.gxwebsoft.shop.dto.OrderCreateRequest;
|
||||
import com.gxwebsoft.shop.entity.ShopGoods;
|
||||
import com.gxwebsoft.shop.entity.ShopOrder;
|
||||
import com.gxwebsoft.shop.entity.ShopOrderGoods;
|
||||
import com.gxwebsoft.shop.service.OrderBusinessService;
|
||||
import com.gxwebsoft.shop.service.ShopGoodsService;
|
||||
import com.gxwebsoft.shop.service.ShopOrderGoodsService;
|
||||
import com.gxwebsoft.shop.service.ShopOrderService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Arrays;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/**
|
||||
* 订单业务服务测试类
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2025-01-26
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
public class OrderBusinessServiceTest {
|
||||
|
||||
@Mock
|
||||
private ShopOrderService shopOrderService;
|
||||
|
||||
@Mock
|
||||
private ShopOrderGoodsService shopOrderGoodsService;
|
||||
|
||||
@Mock
|
||||
private ShopGoodsService shopGoodsService;
|
||||
|
||||
@InjectMocks
|
||||
private OrderBusinessService orderBusinessService;
|
||||
|
||||
private User testUser;
|
||||
private OrderCreateRequest testRequest;
|
||||
private ShopGoods testGoods;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
// 准备测试用户
|
||||
testUser = new User();
|
||||
testUser.setUserId(1);
|
||||
testUser.setOpenid("test_openid");
|
||||
testUser.setPhone("13800138000");
|
||||
|
||||
// 准备测试商品
|
||||
testGoods = new ShopGoods();
|
||||
testGoods.setGoodsId(10018);
|
||||
testGoods.setName("科技小王子大米年卡套餐2.5kg");
|
||||
testGoods.setPrice(new BigDecimal("99.00"));
|
||||
testGoods.setImage("test_image.jpg");
|
||||
|
||||
// 准备测试订单请求
|
||||
testRequest = new OrderCreateRequest();
|
||||
testRequest.setType(0);
|
||||
testRequest.setTotalPrice(new BigDecimal("99.00"));
|
||||
testRequest.setPayPrice(new BigDecimal("99.00"));
|
||||
testRequest.setTotalNum(1);
|
||||
testRequest.setPayType(1);
|
||||
testRequest.setTenantId(1);
|
||||
testRequest.setAddressId(10832);
|
||||
testRequest.setComments("科技小王子大米年卡套餐2.5kg");
|
||||
testRequest.setDeliveryType(0);
|
||||
|
||||
// 准备商品项列表
|
||||
OrderCreateRequest.OrderGoodsItem goodsItem = new OrderCreateRequest.OrderGoodsItem();
|
||||
goodsItem.setGoodsId(10018);
|
||||
goodsItem.setQuantity(1);
|
||||
goodsItem.setPayType(1);
|
||||
|
||||
testRequest.setGoodsItems(Arrays.asList(goodsItem));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateOrderWithGoods() {
|
||||
// Mock 商品查询
|
||||
when(shopGoodsService.getById(10018)).thenReturn(testGoods);
|
||||
|
||||
// Mock 订单保存
|
||||
when(shopOrderService.save(any(ShopOrder.class))).thenAnswer(invocation -> {
|
||||
ShopOrder order = invocation.getArgument(0);
|
||||
order.setOrderId(1); // 模拟数据库生成的ID
|
||||
return true;
|
||||
});
|
||||
|
||||
// Mock 订单商品批量保存
|
||||
when(shopOrderGoodsService.saveBatch(anyList())).thenReturn(true);
|
||||
|
||||
// Mock 微信支付订单创建
|
||||
HashMap<String, String> wxOrderInfo = new HashMap<>();
|
||||
wxOrderInfo.put("prepay_id", "test_prepay_id");
|
||||
when(shopOrderService.createWxOrder(any(ShopOrder.class))).thenReturn(wxOrderInfo);
|
||||
|
||||
// 执行测试
|
||||
Map<String, String> result = orderBusinessService.createOrder(testRequest, testUser);
|
||||
|
||||
// 验证结果
|
||||
assert result != null;
|
||||
assert result.containsKey("prepay_id");
|
||||
|
||||
// 验证方法调用
|
||||
verify(shopGoodsService, times(1)).getById(10018);
|
||||
verify(shopOrderService, times(1)).save(any(ShopOrder.class));
|
||||
verify(shopOrderGoodsService, times(1)).saveBatch(anyList());
|
||||
verify(shopOrderService, times(1)).createWxOrder(any(ShopOrder.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testCreateOrderWithMultipleGoods() {
|
||||
// 准备多个商品项
|
||||
OrderCreateRequest.OrderGoodsItem goodsItem1 = new OrderCreateRequest.OrderGoodsItem();
|
||||
goodsItem1.setGoodsId(10018);
|
||||
goodsItem1.setQuantity(1);
|
||||
goodsItem1.setPayType(1);
|
||||
|
||||
OrderCreateRequest.OrderGoodsItem goodsItem2 = new OrderCreateRequest.OrderGoodsItem();
|
||||
goodsItem2.setGoodsId(10019);
|
||||
goodsItem2.setQuantity(2);
|
||||
goodsItem2.setPayType(1);
|
||||
|
||||
testRequest.setGoodsItems(Arrays.asList(goodsItem1, goodsItem2));
|
||||
testRequest.setTotalPrice(new BigDecimal("297.00")); // 99 + 99*2
|
||||
|
||||
// Mock 商品查询
|
||||
when(shopGoodsService.getById(10018)).thenReturn(testGoods);
|
||||
|
||||
ShopGoods testGoods2 = new ShopGoods();
|
||||
testGoods2.setGoodsId(10019);
|
||||
testGoods2.setName("测试商品2");
|
||||
testGoods2.setPrice(new BigDecimal("99.00"));
|
||||
testGoods2.setImage("test_image2.jpg");
|
||||
when(shopGoodsService.getById(10019)).thenReturn(testGoods2);
|
||||
|
||||
// Mock 其他服务
|
||||
when(shopOrderService.save(any(ShopOrder.class))).thenAnswer(invocation -> {
|
||||
ShopOrder order = invocation.getArgument(0);
|
||||
order.setOrderId(1);
|
||||
return true;
|
||||
});
|
||||
when(shopOrderGoodsService.saveBatch(anyList())).thenReturn(true);
|
||||
when(shopOrderService.createWxOrder(any(ShopOrder.class))).thenReturn(new HashMap<>());
|
||||
|
||||
// 执行测试
|
||||
orderBusinessService.createOrder(testRequest, testUser);
|
||||
|
||||
// 验证商品查询次数
|
||||
verify(shopGoodsService, times(1)).getById(10018);
|
||||
verify(shopGoodsService, times(1)).getById(10019);
|
||||
|
||||
// 验证保存的商品项数量
|
||||
verify(shopOrderGoodsService, times(1)).saveBatch(argThat(list ->
|
||||
((List<ShopOrderGoods>) list).size() == 2
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -1,56 +0,0 @@
|
||||
package com.gxwebsoft.shop;
|
||||
|
||||
import com.gxwebsoft.shop.service.ShopOrderService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.math.BigDecimal;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* 订单总金额统计测试
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2025-07-30
|
||||
*/
|
||||
@SpringBootTest
|
||||
@ActiveProfiles("test")
|
||||
public class OrderTotalTest {
|
||||
|
||||
@Resource
|
||||
private ShopOrderService shopOrderService;
|
||||
|
||||
@Test
|
||||
void testOrderTotal() {
|
||||
// 测试订单总金额统计
|
||||
BigDecimal total = shopOrderService.total();
|
||||
|
||||
// 验证返回值不为null
|
||||
assertNotNull(total, "订单总金额不应该为null");
|
||||
|
||||
// 验证返回值大于等于0
|
||||
assertTrue(total.compareTo(BigDecimal.ZERO) >= 0, "订单总金额应该大于等于0");
|
||||
|
||||
System.out.println("订单总金额统计结果:" + total);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testOrderTotalPerformance() {
|
||||
// 测试性能
|
||||
long startTime = System.currentTimeMillis();
|
||||
|
||||
BigDecimal total = shopOrderService.total();
|
||||
|
||||
long endTime = System.currentTimeMillis();
|
||||
long duration = endTime - startTime;
|
||||
|
||||
System.out.println("订单总金额统计耗时:" + duration + "ms");
|
||||
System.out.println("统计结果:" + total);
|
||||
|
||||
// 验证查询时间在合理范围内(小于5秒)
|
||||
assertTrue(duration < 5000, "查询时间应该在5秒以内");
|
||||
}
|
||||
}
|
||||
@@ -1,315 +0,0 @@
|
||||
package com.gxwebsoft.shop;
|
||||
|
||||
import com.gxwebsoft.common.core.exception.BusinessException;
|
||||
import com.gxwebsoft.common.system.entity.User;
|
||||
import com.gxwebsoft.shop.config.OrderConfigProperties;
|
||||
import com.gxwebsoft.shop.dto.OrderCreateRequest;
|
||||
import com.gxwebsoft.shop.entity.ShopGoods;
|
||||
import com.gxwebsoft.shop.entity.ShopOrder;
|
||||
import com.gxwebsoft.shop.service.OrderBusinessService;
|
||||
import com.gxwebsoft.shop.service.ShopGoodsService;
|
||||
import com.gxwebsoft.shop.service.ShopOrderGoodsService;
|
||||
import com.gxwebsoft.shop.service.ShopOrderService;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.Arrays;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.Mockito.*;
|
||||
|
||||
/**
|
||||
* 订单验证测试类
|
||||
* 测试商品信息后台验证逻辑
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class OrderValidationTest {
|
||||
|
||||
@Mock
|
||||
private ShopOrderService shopOrderService;
|
||||
|
||||
@Mock
|
||||
private ShopOrderGoodsService shopOrderGoodsService;
|
||||
|
||||
@Mock
|
||||
private ShopGoodsService shopGoodsService;
|
||||
|
||||
@Mock
|
||||
private OrderConfigProperties orderConfig;
|
||||
|
||||
@InjectMocks
|
||||
private OrderBusinessService orderBusinessService;
|
||||
|
||||
private User testUser;
|
||||
private OrderCreateRequest testRequest;
|
||||
private ShopGoods testGoods;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
// 准备测试用户
|
||||
testUser = new User();
|
||||
testUser.setUserId(1);
|
||||
testUser.setNickname("测试用户");
|
||||
testUser.setPhone("13800138000");
|
||||
|
||||
// 准备测试商品
|
||||
testGoods = new ShopGoods();
|
||||
testGoods.setGoodsId(10018);
|
||||
testGoods.setName("测试商品");
|
||||
testGoods.setPrice(new BigDecimal("99.00"));
|
||||
testGoods.setStatus(0); // 上架状态
|
||||
testGoods.setStock(100); // 库存100
|
||||
testGoods.setCanBuyNumber(10); // 最大购买数量10
|
||||
testGoods.setCode("TEST001");
|
||||
|
||||
// 准备测试订单请求
|
||||
testRequest = new OrderCreateRequest();
|
||||
testRequest.setType(0);
|
||||
testRequest.setTitle("测试订单");
|
||||
testRequest.setTotalPrice(new BigDecimal("99.00"));
|
||||
testRequest.setTenantId(1);
|
||||
|
||||
// 准备商品项
|
||||
OrderCreateRequest.OrderGoodsItem goodsItem = new OrderCreateRequest.OrderGoodsItem();
|
||||
goodsItem.setGoodsId(10018);
|
||||
goodsItem.setQuantity(1);
|
||||
testRequest.setGoodsItems(Arrays.asList(goodsItem));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testValidateOrderRequest_Success() {
|
||||
// Mock 商品查询
|
||||
when(shopGoodsService.getById(10018)).thenReturn(testGoods);
|
||||
when(orderConfig.getTenantRule(1)).thenReturn(null);
|
||||
|
||||
// 执行验证 - 应该成功
|
||||
assertDoesNotThrow(() -> {
|
||||
// 使用反射调用私有方法进行测试
|
||||
java.lang.reflect.Method method = OrderBusinessService.class
|
||||
.getDeclaredMethod("validateOrderRequest", OrderCreateRequest.class, User.class);
|
||||
method.setAccessible(true);
|
||||
method.invoke(orderBusinessService, testRequest, testUser);
|
||||
});
|
||||
|
||||
// 验证总金额被正确设置
|
||||
assertEquals(new BigDecimal("99.00"), testRequest.getTotalPrice());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testValidateOrderRequest_GoodsNotFound() {
|
||||
// Mock 商品不存在
|
||||
when(shopGoodsService.getById(10018)).thenReturn(null);
|
||||
|
||||
// 执行验证 - 应该抛出异常
|
||||
Exception exception = assertThrows(Exception.class, () -> {
|
||||
java.lang.reflect.Method method = OrderBusinessService.class
|
||||
.getDeclaredMethod("validateOrderRequest", OrderCreateRequest.class, User.class);
|
||||
method.setAccessible(true);
|
||||
method.invoke(orderBusinessService, testRequest, testUser);
|
||||
});
|
||||
|
||||
// 检查是否是 InvocationTargetException 包装的 BusinessException
|
||||
assertTrue(exception instanceof java.lang.reflect.InvocationTargetException);
|
||||
Throwable cause = exception.getCause();
|
||||
assertTrue(cause instanceof BusinessException);
|
||||
assertTrue(cause.getMessage().contains("商品不存在"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testValidateOrderRequest_GoodsOffShelf() {
|
||||
// 设置商品为下架状态
|
||||
testGoods.setStatus(1);
|
||||
when(shopGoodsService.getById(10018)).thenReturn(testGoods);
|
||||
|
||||
// 执行验证 - 应该抛出异常
|
||||
Exception exception = assertThrows(Exception.class, () -> {
|
||||
java.lang.reflect.Method method = OrderBusinessService.class
|
||||
.getDeclaredMethod("validateOrderRequest", OrderCreateRequest.class, User.class);
|
||||
method.setAccessible(true);
|
||||
method.invoke(orderBusinessService, testRequest, testUser);
|
||||
});
|
||||
|
||||
// 检查是否是 InvocationTargetException 包装的 BusinessException
|
||||
assertTrue(exception instanceof java.lang.reflect.InvocationTargetException);
|
||||
Throwable cause = exception.getCause();
|
||||
assertTrue(cause instanceof BusinessException);
|
||||
assertTrue(cause.getMessage().contains("商品已下架"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testValidateOrderRequest_InsufficientStock() {
|
||||
// 设置库存不足
|
||||
testGoods.setStock(0);
|
||||
when(shopGoodsService.getById(10018)).thenReturn(testGoods);
|
||||
|
||||
// 执行验证 - 应该抛出异常
|
||||
Exception exception = assertThrows(Exception.class, () -> {
|
||||
java.lang.reflect.Method method = OrderBusinessService.class
|
||||
.getDeclaredMethod("validateOrderRequest", OrderCreateRequest.class, User.class);
|
||||
method.setAccessible(true);
|
||||
method.invoke(orderBusinessService, testRequest, testUser);
|
||||
});
|
||||
|
||||
// 检查是否是 InvocationTargetException 包装的 BusinessException
|
||||
assertTrue(exception instanceof java.lang.reflect.InvocationTargetException);
|
||||
Throwable cause = exception.getCause();
|
||||
assertTrue(cause instanceof BusinessException);
|
||||
assertTrue(cause.getMessage().contains("商品库存不足"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testValidateOrderRequest_ExceedBuyLimit() {
|
||||
// 设置购买数量超过限制
|
||||
testRequest.getGoodsItems().get(0).setQuantity(15); // 超过最大购买数量10
|
||||
when(shopGoodsService.getById(10018)).thenReturn(testGoods);
|
||||
|
||||
// 执行验证 - 应该抛出异常
|
||||
Exception exception = assertThrows(Exception.class, () -> {
|
||||
java.lang.reflect.Method method = OrderBusinessService.class
|
||||
.getDeclaredMethod("validateOrderRequest", OrderCreateRequest.class, User.class);
|
||||
method.setAccessible(true);
|
||||
method.invoke(orderBusinessService, testRequest, testUser);
|
||||
});
|
||||
|
||||
// 检查是否是 InvocationTargetException 包装的 BusinessException
|
||||
assertTrue(exception instanceof java.lang.reflect.InvocationTargetException);
|
||||
Throwable cause = exception.getCause();
|
||||
assertTrue(cause instanceof BusinessException);
|
||||
assertTrue(cause.getMessage().contains("购买数量超过限制"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testValidateOrderRequest_PriceCalculation() {
|
||||
// 设置多个商品项
|
||||
OrderCreateRequest.OrderGoodsItem goodsItem1 = new OrderCreateRequest.OrderGoodsItem();
|
||||
goodsItem1.setGoodsId(10018);
|
||||
goodsItem1.setQuantity(2);
|
||||
|
||||
OrderCreateRequest.OrderGoodsItem goodsItem2 = new OrderCreateRequest.OrderGoodsItem();
|
||||
goodsItem2.setGoodsId(10019);
|
||||
goodsItem2.setQuantity(1);
|
||||
|
||||
testRequest.setGoodsItems(Arrays.asList(goodsItem1, goodsItem2));
|
||||
testRequest.setTotalPrice(new BigDecimal("297.00")); // 99*2 + 99*1
|
||||
|
||||
// 准备第二个商品
|
||||
ShopGoods testGoods2 = new ShopGoods();
|
||||
testGoods2.setGoodsId(10019);
|
||||
testGoods2.setName("测试商品2");
|
||||
testGoods2.setPrice(new BigDecimal("99.00"));
|
||||
testGoods2.setStatus(0);
|
||||
testGoods2.setStock(100);
|
||||
|
||||
when(shopGoodsService.getById(10018)).thenReturn(testGoods);
|
||||
when(shopGoodsService.getById(10019)).thenReturn(testGoods2);
|
||||
when(orderConfig.getTenantRule(1)).thenReturn(null);
|
||||
|
||||
// 执行验证 - 应该成功
|
||||
assertDoesNotThrow(() -> {
|
||||
java.lang.reflect.Method method = OrderBusinessService.class
|
||||
.getDeclaredMethod("validateOrderRequest", OrderCreateRequest.class, User.class);
|
||||
method.setAccessible(true);
|
||||
method.invoke(orderBusinessService, testRequest, testUser);
|
||||
});
|
||||
|
||||
// 验证总金额计算正确
|
||||
assertEquals(new BigDecimal("297.00"), testRequest.getTotalPrice());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testValidateOrderRequest_PriceDiscrepancy() {
|
||||
// 设置前端传入的金额与后台计算不一致
|
||||
testRequest.setTotalPrice(new BigDecimal("88.00")); // 错误的金额
|
||||
when(shopGoodsService.getById(10018)).thenReturn(testGoods);
|
||||
|
||||
// 执行验证 - 应该抛出异常
|
||||
Exception exception = assertThrows(Exception.class, () -> {
|
||||
java.lang.reflect.Method method = OrderBusinessService.class
|
||||
.getDeclaredMethod("validateOrderRequest", OrderCreateRequest.class, User.class);
|
||||
method.setAccessible(true);
|
||||
method.invoke(orderBusinessService, testRequest, testUser);
|
||||
});
|
||||
|
||||
// 检查是否是 InvocationTargetException 包装的 BusinessException
|
||||
assertTrue(exception instanceof java.lang.reflect.InvocationTargetException);
|
||||
Throwable cause = exception.getCause();
|
||||
assertTrue(cause instanceof BusinessException);
|
||||
assertTrue(cause.getMessage().contains("订单金额计算错误"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void testBuildShopOrder_RequiredFields() throws Exception {
|
||||
// Mock 配置
|
||||
OrderConfigProperties.DefaultConfig defaultConfig = new OrderConfigProperties.DefaultConfig();
|
||||
defaultConfig.setDefaultComments("默认备注");
|
||||
when(orderConfig.getDefaultConfig()).thenReturn(defaultConfig);
|
||||
|
||||
// 使用反射调用 buildShopOrder 方法
|
||||
java.lang.reflect.Method buildMethod = OrderBusinessService.class
|
||||
.getDeclaredMethod("buildShopOrder", OrderCreateRequest.class, User.class);
|
||||
buildMethod.setAccessible(true);
|
||||
|
||||
ShopOrder result = (ShopOrder) buildMethod.invoke(orderBusinessService, testRequest, testUser);
|
||||
|
||||
// 验证必需字段都已设置
|
||||
assertNotNull(result.getPayPrice(), "payPrice 不能为空");
|
||||
assertNotNull(result.getPrice(), "price 不能为空");
|
||||
assertNotNull(result.getReducePrice(), "reducePrice 不能为空");
|
||||
assertNotNull(result.getMoney(), "money 不能为空");
|
||||
assertNotNull(result.getPayStatus(), "payStatus 不能为空");
|
||||
assertNotNull(result.getOrderStatus(), "orderStatus 不能为空");
|
||||
assertNotNull(result.getDeliveryStatus(), "deliveryStatus 不能为空");
|
||||
assertNotNull(result.getPayType(), "payType 不能为空");
|
||||
|
||||
// 验证默认值
|
||||
assertEquals(testRequest.getTotalPrice(), result.getPayPrice());
|
||||
assertEquals(testRequest.getTotalPrice(), result.getPrice());
|
||||
assertEquals(BigDecimal.ZERO, result.getReducePrice());
|
||||
assertEquals(testRequest.getTotalPrice(), result.getMoney());
|
||||
assertEquals(false, result.getPayStatus());
|
||||
assertEquals(Integer.valueOf(0), result.getOrderStatus());
|
||||
assertEquals(Integer.valueOf(10), result.getDeliveryStatus());
|
||||
assertEquals(Integer.valueOf(1), result.getPayType());
|
||||
|
||||
// 验证关键字段 - 租户ID(影响微信支付证书路径)
|
||||
assertNotNull(result.getTenantId(), "tenantId 不能为空");
|
||||
assertEquals(testRequest.getTenantId(), result.getTenantId(), "tenantId 必须正确设置");
|
||||
}
|
||||
|
||||
@Test
|
||||
void testBuildShopOrder_TenantIdValidation() throws Exception {
|
||||
// 创建一个新的请求对象,租户ID为空
|
||||
OrderCreateRequest requestWithoutTenant = new OrderCreateRequest();
|
||||
requestWithoutTenant.setType(0);
|
||||
requestWithoutTenant.setTitle("测试订单");
|
||||
requestWithoutTenant.setTotalPrice(new BigDecimal("99.00"));
|
||||
requestWithoutTenant.setTenantId(null); // 设置为空
|
||||
|
||||
// 准备商品项
|
||||
OrderCreateRequest.OrderGoodsItem goodsItem = new OrderCreateRequest.OrderGoodsItem();
|
||||
goodsItem.setGoodsId(10018);
|
||||
goodsItem.setQuantity(1);
|
||||
requestWithoutTenant.setGoodsItems(Arrays.asList(goodsItem));
|
||||
|
||||
// 使用反射调用 buildShopOrder 方法
|
||||
java.lang.reflect.Method buildMethod = OrderBusinessService.class
|
||||
.getDeclaredMethod("buildShopOrder", OrderCreateRequest.class, User.class);
|
||||
buildMethod.setAccessible(true);
|
||||
|
||||
// 执行验证 - 应该抛出异常
|
||||
Exception exception = assertThrows(Exception.class, () -> {
|
||||
buildMethod.invoke(orderBusinessService, requestWithoutTenant, testUser);
|
||||
});
|
||||
|
||||
// 检查是否是 InvocationTargetException 包装的 BusinessException
|
||||
assertTrue(exception instanceof java.lang.reflect.InvocationTargetException);
|
||||
Throwable cause = exception.getCause();
|
||||
assertTrue(cause instanceof BusinessException);
|
||||
assertTrue(cause.getMessage().contains("租户ID不能为空"));
|
||||
}
|
||||
}
|
||||
@@ -1,75 +0,0 @@
|
||||
package com.gxwebsoft.shop;
|
||||
|
||||
import com.gxwebsoft.common.core.utils.WechatPayUtils;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* 微信支付商品描述字段测试
|
||||
* 验证字节长度限制处理
|
||||
*/
|
||||
@SpringBootTest
|
||||
public class WechatPayDescriptionTest {
|
||||
|
||||
@Test
|
||||
public void testTruncateToByteLimit() {
|
||||
// 测试正常情况 - 字符串长度在限制内
|
||||
String shortText = "正常商品描述";
|
||||
String result1 = WechatPayUtils.truncateToByteLimit(shortText, 127);
|
||||
assertEquals(shortText, result1);
|
||||
assertTrue(result1.getBytes(StandardCharsets.UTF_8).length <= 127);
|
||||
|
||||
// 测试超长中文字符串
|
||||
String longText = "【湾区认证】【百千万工程帮扶产品 通过远方320项检测 湾区认证 丰江桥佛手瓜面】独特风味低脂轻食便捷速食非油炸 720g/袋";
|
||||
String result2 = WechatPayUtils.truncateToByteLimit(longText, 127);
|
||||
assertNotNull(result2);
|
||||
assertTrue(result2.getBytes(StandardCharsets.UTF_8).length <= 127);
|
||||
System.out.println("原始文本字节数: " + longText.getBytes(StandardCharsets.UTF_8).length);
|
||||
System.out.println("截断后文本: " + result2);
|
||||
System.out.println("截断后字节数: " + result2.getBytes(StandardCharsets.UTF_8).length);
|
||||
|
||||
// 测试null和空字符串
|
||||
assertNull(WechatPayUtils.truncateToByteLimit(null, 127));
|
||||
assertEquals("", WechatPayUtils.truncateToByteLimit("", 127));
|
||||
|
||||
// 测试英文字符串
|
||||
String englishText = "This is a very long English description that might exceed the byte limit for WeChat Pay description field";
|
||||
String result3 = WechatPayUtils.truncateToByteLimit(englishText, 127);
|
||||
assertNotNull(result3);
|
||||
assertTrue(result3.getBytes(StandardCharsets.UTF_8).length <= 127);
|
||||
|
||||
// 测试混合字符串
|
||||
String mixedText = "Product Name 产品名称 with special characters @#$%^&*()";
|
||||
String result4 = WechatPayUtils.truncateToByteLimit(mixedText, 50);
|
||||
assertNotNull(result4);
|
||||
assertTrue(result4.getBytes(StandardCharsets.UTF_8).length <= 50);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testSpecificErrorCase() {
|
||||
// 测试错误信息中的具体案例
|
||||
String errorText = "【湾区认证】【百千万工程帮扶产品 通过远方320项检测 湾区认证 丰江桥佛手瓜面】独特风味低脂轻食便捷速食非油炸 720g/袋";
|
||||
|
||||
// 验证原始文本确实超过127字节
|
||||
int originalBytes = errorText.getBytes(StandardCharsets.UTF_8).length;
|
||||
System.out.println("原始文本: " + errorText);
|
||||
System.out.println("原始字节数: " + originalBytes);
|
||||
assertTrue(originalBytes > 127, "原始文本应该超过127字节");
|
||||
|
||||
// 测试截断
|
||||
String truncated = WechatPayUtils.processDescription(errorText);
|
||||
int truncatedBytes = truncated.getBytes(StandardCharsets.UTF_8).length;
|
||||
|
||||
System.out.println("截断后文本: " + truncated);
|
||||
System.out.println("截断后字节数: " + truncatedBytes);
|
||||
|
||||
// 验证截断后的文本符合要求
|
||||
assertNotNull(truncated);
|
||||
assertTrue(truncatedBytes <= 127, "截断后字节数应该不超过127");
|
||||
assertFalse(truncated.contains("\uFFFD"), "截断后的文本不应包含无效字符");
|
||||
}
|
||||
}
|
||||
@@ -1,113 +0,0 @@
|
||||
package com.gxwebsoft.shop.service;
|
||||
|
||||
import com.gxwebsoft.shop.entity.ShopUserCoupon;
|
||||
import com.gxwebsoft.shop.service.CouponStatusService.CouponStatusResult;
|
||||
import com.gxwebsoft.shop.service.CouponStatusService.CouponValidationResult;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* 优惠券状态管理服务测试
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2025-01-15
|
||||
*/
|
||||
@SpringBootTest
|
||||
@ActiveProfiles("dev")
|
||||
public class CouponStatusServiceTest {
|
||||
|
||||
@Autowired
|
||||
private CouponStatusService couponStatusService;
|
||||
|
||||
@Test
|
||||
public void testCouponStatusConstants() {
|
||||
// 测试状态常量
|
||||
assertEquals(0, ShopUserCoupon.STATUS_UNUSED);
|
||||
assertEquals(1, ShopUserCoupon.STATUS_USED);
|
||||
assertEquals(2, ShopUserCoupon.STATUS_EXPIRED);
|
||||
|
||||
// 测试类型常量
|
||||
assertEquals(10, ShopUserCoupon.TYPE_REDUCE);
|
||||
assertEquals(20, ShopUserCoupon.TYPE_DISCOUNT);
|
||||
assertEquals(30, ShopUserCoupon.TYPE_FREE);
|
||||
|
||||
// 测试适用范围常量
|
||||
assertEquals(10, ShopUserCoupon.APPLY_ALL);
|
||||
assertEquals(20, ShopUserCoupon.APPLY_GOODS);
|
||||
assertEquals(30, ShopUserCoupon.APPLY_CATEGORY);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCouponStatusMethods() {
|
||||
// 创建测试优惠券
|
||||
ShopUserCoupon coupon = new ShopUserCoupon();
|
||||
coupon.setStatus(ShopUserCoupon.STATUS_UNUSED);
|
||||
coupon.setEndTime(LocalDateTime.now().plusDays(7));
|
||||
|
||||
// 测试可用状态
|
||||
assertTrue(coupon.isAvailable());
|
||||
assertFalse(coupon.isUsed());
|
||||
assertFalse(coupon.isExpired());
|
||||
assertEquals("可使用", coupon.getStatusDesc());
|
||||
|
||||
// 测试已使用状态
|
||||
coupon.markAsUsed(123, "ORDER123");
|
||||
assertTrue(coupon.isUsed());
|
||||
assertFalse(coupon.isAvailable());
|
||||
assertEquals("已使用", coupon.getStatusDesc());
|
||||
assertEquals(Integer.valueOf(123), coupon.getOrderId());
|
||||
assertEquals("ORDER123", coupon.getOrderNo());
|
||||
|
||||
// 测试过期状态
|
||||
coupon.setStatus(ShopUserCoupon.STATUS_UNUSED);
|
||||
coupon.setEndTime(LocalDateTime.now().minusDays(1));
|
||||
assertTrue(coupon.isExpired());
|
||||
assertFalse(coupon.isAvailable());
|
||||
assertEquals("已过期", coupon.getStatusDesc());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testValidateCouponForOrder() {
|
||||
// 这个测试需要数据库中有实际的优惠券数据
|
||||
// 这里只是演示测试结构
|
||||
|
||||
List<Integer> goodsIds = Arrays.asList(1, 2, 3);
|
||||
BigDecimal totalAmount = new BigDecimal("150.00");
|
||||
|
||||
// 注意:这个测试需要实际的优惠券ID,在真实环境中需要先创建测试数据
|
||||
// CouponValidationResult result = couponStatusService.validateCouponForOrder(1L, totalAmount, goodsIds);
|
||||
// assertNotNull(result);
|
||||
|
||||
System.out.println("优惠券验证测试需要实际的数据库数据");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetUserCouponsGroupByStatus() {
|
||||
// 这个测试需要数据库中有实际的用户和优惠券数据
|
||||
// 这里只是演示测试结构
|
||||
|
||||
// 注意:这个测试需要实际的用户ID,在真实环境中需要先创建测试数据
|
||||
// CouponStatusResult result = couponStatusService.getUserCouponsGroupByStatus(1);
|
||||
// assertNotNull(result);
|
||||
// assertTrue(result.getTotalCount() >= 0);
|
||||
|
||||
System.out.println("用户优惠券分组测试需要实际的数据库数据");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUpdateExpiredCoupons() {
|
||||
// 测试批量更新过期优惠券
|
||||
int updatedCount = couponStatusService.updateExpiredCoupons();
|
||||
assertTrue(updatedCount >= 0);
|
||||
System.out.println("更新了 " + updatedCount + " 张过期优惠券");
|
||||
}
|
||||
}
|
||||
@@ -1,145 +0,0 @@
|
||||
package com.gxwebsoft.shop.service;
|
||||
|
||||
import com.gxwebsoft.shop.entity.ShopGoods;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
/**
|
||||
* 商品销量累加功能测试
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2025-08-23
|
||||
*/
|
||||
@Slf4j
|
||||
@SpringBootTest
|
||||
@ActiveProfiles("dev")
|
||||
public class ShopGoodsSalesTest {
|
||||
|
||||
@Resource
|
||||
private ShopGoodsService shopGoodsService;
|
||||
|
||||
/**
|
||||
* 测试累加商品销量功能
|
||||
*/
|
||||
@Test
|
||||
public void testAddSaleCount() {
|
||||
// 测试商品ID(请根据实际数据库中的商品ID进行调整)
|
||||
Integer testGoodsId = 1;
|
||||
Integer addCount = 5;
|
||||
|
||||
log.info("=== 开始测试商品销量累加功能 ===");
|
||||
|
||||
// 1. 查询商品当前销量
|
||||
ShopGoods goodsBefore = shopGoodsService.getById(testGoodsId);
|
||||
if (goodsBefore == null) {
|
||||
log.error("测试失败:商品不存在 - 商品ID: {}", testGoodsId);
|
||||
return;
|
||||
}
|
||||
|
||||
Integer salesBefore = goodsBefore.getSales() != null ? goodsBefore.getSales() : 0;
|
||||
log.info("累加前商品销量 - 商品ID: {}, 商品名称: {}, 当前销量: {}",
|
||||
testGoodsId, goodsBefore.getName(), salesBefore);
|
||||
|
||||
// 2. 执行销量累加
|
||||
boolean result = shopGoodsService.addSaleCount(testGoodsId, addCount);
|
||||
log.info("销量累加操作结果: {}", result ? "成功" : "失败");
|
||||
|
||||
// 3. 查询累加后的销量
|
||||
ShopGoods goodsAfter = shopGoodsService.getById(testGoodsId);
|
||||
Integer salesAfter = goodsAfter.getSales() != null ? goodsAfter.getSales() : 0;
|
||||
log.info("累加后商品销量 - 商品ID: {}, 商品名称: {}, 累加后销量: {}",
|
||||
testGoodsId, goodsAfter.getName(), salesAfter);
|
||||
|
||||
// 4. 验证结果
|
||||
Integer expectedSales = salesBefore + addCount;
|
||||
if (salesAfter.equals(expectedSales)) {
|
||||
log.info("✅ 测试成功!销量正确累加 - 预期: {}, 实际: {}", expectedSales, salesAfter);
|
||||
} else {
|
||||
log.error("❌ 测试失败!销量累加不正确 - 预期: {}, 实际: {}", expectedSales, salesAfter);
|
||||
}
|
||||
|
||||
log.info("=== 商品销量累加功能测试完成 ===");
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试参数验证
|
||||
*/
|
||||
@Test
|
||||
public void testAddSaleCountValidation() {
|
||||
log.info("=== 开始测试参数验证 ===");
|
||||
|
||||
// 测试null商品ID
|
||||
boolean result1 = shopGoodsService.addSaleCount(null, 5);
|
||||
log.info("null商品ID测试结果: {}", result1 ? "失败(应该返回false)" : "成功");
|
||||
|
||||
// 测试null销量
|
||||
boolean result2 = shopGoodsService.addSaleCount(1, null);
|
||||
log.info("null销量测试结果: {}", result2 ? "失败(应该返回false)" : "成功");
|
||||
|
||||
// 测试负数销量
|
||||
boolean result3 = shopGoodsService.addSaleCount(1, -1);
|
||||
log.info("负数销量测试结果: {}", result3 ? "失败(应该返回false)" : "成功");
|
||||
|
||||
// 测试零销量
|
||||
boolean result4 = shopGoodsService.addSaleCount(1, 0);
|
||||
log.info("零销量测试结果: {}", result4 ? "失败(应该返回false)" : "成功");
|
||||
|
||||
// 测试不存在的商品ID
|
||||
boolean result5 = shopGoodsService.addSaleCount(999999, 5);
|
||||
log.info("不存在商品ID测试结果: {}", result5 ? "失败(应该返回false)" : "成功");
|
||||
|
||||
log.info("=== 参数验证测试完成 ===");
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试大批量累加
|
||||
*/
|
||||
@Test
|
||||
public void testBatchAddSaleCount() {
|
||||
Integer testGoodsId = 1;
|
||||
|
||||
log.info("=== 开始测试批量累加 ===");
|
||||
|
||||
// 查询初始销量
|
||||
ShopGoods goodsBefore = shopGoodsService.getById(testGoodsId);
|
||||
if (goodsBefore == null) {
|
||||
log.error("测试失败:商品不存在 - 商品ID: {}", testGoodsId);
|
||||
return;
|
||||
}
|
||||
|
||||
Integer salesBefore = goodsBefore.getSales() != null ? goodsBefore.getSales() : 0;
|
||||
log.info("批量累加前销量: {}", salesBefore);
|
||||
|
||||
// 模拟多次购买
|
||||
int totalAdded = 0;
|
||||
for (int i = 1; i <= 10; i++) {
|
||||
boolean result = shopGoodsService.addSaleCount(testGoodsId, i);
|
||||
if (result) {
|
||||
totalAdded += i;
|
||||
log.info("第{}次累加成功,累加数量: {}", i, i);
|
||||
} else {
|
||||
log.error("第{}次累加失败", i);
|
||||
}
|
||||
}
|
||||
|
||||
// 验证最终结果
|
||||
ShopGoods goodsAfter = shopGoodsService.getById(testGoodsId);
|
||||
Integer salesAfter = goodsAfter.getSales() != null ? goodsAfter.getSales() : 0;
|
||||
Integer expectedSales = salesBefore + totalAdded;
|
||||
|
||||
log.info("批量累加结果 - 累加前: {}, 总累加量: {}, 累加后: {}, 预期: {}",
|
||||
salesBefore, totalAdded, salesAfter, expectedSales);
|
||||
|
||||
if (salesAfter.equals(expectedSales)) {
|
||||
log.info("✅ 批量累加测试成功!");
|
||||
} else {
|
||||
log.error("❌ 批量累加测试失败!");
|
||||
}
|
||||
|
||||
log.info("=== 批量累加测试完成 ===");
|
||||
}
|
||||
}
|
||||
@@ -1,136 +0,0 @@
|
||||
package com.gxwebsoft.shop.service;
|
||||
|
||||
import com.gxwebsoft.shop.entity.ShopOrderGoods;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 订单商品忽略租户隔离功能测试
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2025-08-23
|
||||
*/
|
||||
@Slf4j
|
||||
@SpringBootTest
|
||||
@ActiveProfiles("dev")
|
||||
public class ShopOrderGoodsIgnoreTenantTest {
|
||||
|
||||
@Resource
|
||||
private ShopOrderGoodsService shopOrderGoodsService;
|
||||
|
||||
/**
|
||||
* 测试忽略租户隔离查询订单商品
|
||||
*/
|
||||
@Test
|
||||
public void testGetListByOrderIdIgnoreTenant() {
|
||||
// 测试订单ID(请根据实际数据库中的订单ID进行调整)
|
||||
Integer testOrderId = 1;
|
||||
|
||||
log.info("=== 开始测试忽略租户隔离查询订单商品功能 ===");
|
||||
|
||||
// 1. 使用普通方法查询订单商品(受租户隔离影响)
|
||||
List<ShopOrderGoods> orderGoodsNormal = shopOrderGoodsService.getListByOrderId(testOrderId);
|
||||
log.info("普通查询结果 - 订单ID: {}, 商品数量: {}", testOrderId,
|
||||
orderGoodsNormal != null ? orderGoodsNormal.size() : 0);
|
||||
|
||||
// 2. 使用忽略租户隔离方法查询订单商品
|
||||
List<ShopOrderGoods> orderGoodsIgnoreTenant = shopOrderGoodsService.getListByOrderIdIgnoreTenant(testOrderId);
|
||||
log.info("忽略租户隔离查询结果 - 订单ID: {}, 商品数量: {}", testOrderId,
|
||||
orderGoodsIgnoreTenant != null ? orderGoodsIgnoreTenant.size() : 0);
|
||||
|
||||
// 3. 验证结果
|
||||
if (orderGoodsIgnoreTenant != null && !orderGoodsIgnoreTenant.isEmpty()) {
|
||||
log.info("✅ 忽略租户隔离查询成功!");
|
||||
for (ShopOrderGoods orderGoods : orderGoodsIgnoreTenant) {
|
||||
log.info("订单商品详情 - ID: {}, 商品ID: {}, 商品名称: {}, 数量: {}, 租户ID: {}",
|
||||
orderGoods.getId(),
|
||||
orderGoods.getGoodsId(),
|
||||
orderGoods.getGoodsName(),
|
||||
orderGoods.getTotalNum(),
|
||||
orderGoods.getTenantId());
|
||||
}
|
||||
} else {
|
||||
log.warn("⚠️ 忽略租户隔离查询结果为空,可能订单不存在或没有商品");
|
||||
}
|
||||
|
||||
log.info("=== 忽略租户隔离查询订单商品功能测试完成 ===");
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试参数验证
|
||||
*/
|
||||
@Test
|
||||
public void testGetListByOrderIdIgnoreTenantValidation() {
|
||||
log.info("=== 开始测试参数验证 ===");
|
||||
|
||||
// 测试null订单ID
|
||||
List<ShopOrderGoods> result1 = shopOrderGoodsService.getListByOrderIdIgnoreTenant(null);
|
||||
log.info("null订单ID测试结果: {}", result1.isEmpty() ? "成功(返回空列表)" : "失败");
|
||||
|
||||
// 测试不存在的订单ID
|
||||
List<ShopOrderGoods> result2 = shopOrderGoodsService.getListByOrderIdIgnoreTenant(999999);
|
||||
log.info("不存在订单ID测试结果: {}", result2.isEmpty() ? "成功(返回空列表)" : "失败");
|
||||
|
||||
log.info("=== 参数验证测试完成 ===");
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试跨租户查询
|
||||
*/
|
||||
@Test
|
||||
public void testCrossTenantQuery() {
|
||||
log.info("=== 开始测试跨租户查询 ===");
|
||||
|
||||
// 查询不同租户的订单商品(请根据实际数据调整)
|
||||
Integer[] testOrderIds = {1, 2, 3, 4, 5};
|
||||
|
||||
for (Integer orderId : testOrderIds) {
|
||||
List<ShopOrderGoods> orderGoodsList = shopOrderGoodsService.getListByOrderIdIgnoreTenant(orderId);
|
||||
if (orderGoodsList != null && !orderGoodsList.isEmpty()) {
|
||||
log.info("订单ID: {}, 商品数量: {}", orderId, orderGoodsList.size());
|
||||
for (ShopOrderGoods orderGoods : orderGoodsList) {
|
||||
log.info(" - 商品: {} (ID: {}), 数量: {}, 租户: {}",
|
||||
orderGoods.getGoodsName(),
|
||||
orderGoods.getGoodsId(),
|
||||
orderGoods.getTotalNum(),
|
||||
orderGoods.getTenantId());
|
||||
}
|
||||
} else {
|
||||
log.info("订单ID: {} - 无商品或不存在", orderId);
|
||||
}
|
||||
}
|
||||
|
||||
log.info("=== 跨租户查询测试完成 ===");
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试批量查询性能
|
||||
*/
|
||||
@Test
|
||||
public void testBatchQuery() {
|
||||
log.info("=== 开始测试批量查询性能 ===");
|
||||
|
||||
Integer[] testOrderIds = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
|
||||
|
||||
long startTime = System.currentTimeMillis();
|
||||
|
||||
int totalGoods = 0;
|
||||
for (Integer orderId : testOrderIds) {
|
||||
List<ShopOrderGoods> orderGoodsList = shopOrderGoodsService.getListByOrderIdIgnoreTenant(orderId);
|
||||
totalGoods += orderGoodsList.size();
|
||||
}
|
||||
|
||||
long endTime = System.currentTimeMillis();
|
||||
long duration = endTime - startTime;
|
||||
|
||||
log.info("批量查询结果 - 查询订单数: {}, 总商品数: {}, 耗时: {}ms",
|
||||
testOrderIds.length, totalGoods, duration);
|
||||
|
||||
log.info("=== 批量查询性能测试完成 ===");
|
||||
}
|
||||
}
|
||||
@@ -1,141 +0,0 @@
|
||||
package com.gxwebsoft.shop.service;
|
||||
|
||||
import com.gxwebsoft.common.system.entity.User;
|
||||
import com.gxwebsoft.common.system.service.UserService;
|
||||
import com.gxwebsoft.shop.entity.ShopOrder;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/**
|
||||
* 订单更新业务测试
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2025-08-23
|
||||
*/
|
||||
@Slf4j
|
||||
@SpringBootTest
|
||||
@ActiveProfiles("dev")
|
||||
public class ShopOrderUpdate10550ServiceTest {
|
||||
|
||||
@Resource
|
||||
private ShopOrderUpdate10550Service shopOrderUpdate10550Service;
|
||||
|
||||
@Resource
|
||||
private UserService userService;
|
||||
|
||||
/**
|
||||
* 测试用户等级升级功能
|
||||
*/
|
||||
@Test
|
||||
public void testUserGradeUpgrade() {
|
||||
log.info("=== 开始测试用户等级升级功能 ===");
|
||||
|
||||
// 创建测试订单
|
||||
ShopOrder testOrder = createTestOrder();
|
||||
|
||||
// 查询用户升级前的信息
|
||||
User userBefore = userService.getByIdIgnoreTenant(testOrder.getUserId());
|
||||
if (userBefore != null) {
|
||||
log.info("升级前用户信息 - ID: {}, 等级: {}, 消费金额: {}",
|
||||
userBefore.getUserId(), userBefore.getGradeId(), userBefore.getExpendMoney());
|
||||
}
|
||||
|
||||
// 执行订单更新业务
|
||||
shopOrderUpdate10550Service.update(testOrder);
|
||||
|
||||
// 查询用户升级后的信息
|
||||
User userAfter = userService.getByIdIgnoreTenant(testOrder.getUserId());
|
||||
if (userAfter != null) {
|
||||
log.info("升级后用户信息 - ID: {}, 等级: {}, 消费金额: {}",
|
||||
userAfter.getUserId(), userAfter.getGradeId(), userAfter.getExpendMoney());
|
||||
}
|
||||
|
||||
log.info("=== 用户等级升级功能测试完成 ===");
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试合伙人条件配置获取
|
||||
*/
|
||||
@Test
|
||||
public void testPartnerConditionConfig() {
|
||||
log.info("=== 开始测试合伙人条件配置获取 ===");
|
||||
|
||||
// 创建测试订单
|
||||
ShopOrder testOrder = createTestOrder();
|
||||
|
||||
// 执行订单更新业务(会在日志中显示合伙人条件)
|
||||
shopOrderUpdate10550Service.update(testOrder);
|
||||
|
||||
log.info("=== 合伙人条件配置获取测试完成 ===");
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试异常处理
|
||||
*/
|
||||
@Test
|
||||
public void testExceptionHandling() {
|
||||
log.info("=== 开始测试异常处理 ===");
|
||||
|
||||
// 测试null订单
|
||||
try {
|
||||
shopOrderUpdate10550Service.update(null);
|
||||
log.info("null订单处理:正常(应该有异常日志)");
|
||||
} catch (Exception e) {
|
||||
log.info("null订单处理:捕获异常 - {}", e.getMessage());
|
||||
}
|
||||
|
||||
// 测试无效用户ID的订单
|
||||
ShopOrder invalidOrder = new ShopOrder();
|
||||
invalidOrder.setOrderId(999999);
|
||||
invalidOrder.setUserId(999999);
|
||||
invalidOrder.setTenantId(10550);
|
||||
invalidOrder.setPayPrice(new BigDecimal("100.00"));
|
||||
|
||||
try {
|
||||
shopOrderUpdate10550Service.update(invalidOrder);
|
||||
log.info("无效用户订单处理:正常(应该有警告日志)");
|
||||
} catch (Exception e) {
|
||||
log.info("无效用户订单处理:捕获异常 - {}", e.getMessage());
|
||||
}
|
||||
|
||||
log.info("=== 异常处理测试完成 ===");
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试批量订单处理
|
||||
*/
|
||||
@Test
|
||||
public void testBatchOrderProcessing() {
|
||||
log.info("=== 开始测试批量订单处理 ===");
|
||||
|
||||
// 模拟多个订单
|
||||
for (int i = 1; i <= 5; i++) {
|
||||
ShopOrder order = createTestOrder();
|
||||
order.setOrderId(1000 + i);
|
||||
order.setPayPrice(new BigDecimal("50.00").multiply(BigDecimal.valueOf(i)));
|
||||
|
||||
log.info("处理第{}个订单 - 订单ID: {}, 金额: {}", i, order.getOrderId(), order.getPayPrice());
|
||||
shopOrderUpdate10550Service.update(order);
|
||||
}
|
||||
|
||||
log.info("=== 批量订单处理测试完成 ===");
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建测试订单
|
||||
*/
|
||||
private ShopOrder createTestOrder() {
|
||||
ShopOrder order = new ShopOrder();
|
||||
order.setOrderId(1001);
|
||||
order.setUserId(1); // 请根据实际数据库中的用户ID调整
|
||||
order.setTenantId(10550);
|
||||
order.setPayPrice(new BigDecimal("500.00")); // 测试金额
|
||||
order.setTotalPrice(new BigDecimal("500.00"));
|
||||
return order;
|
||||
}
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
package com.gxwebsoft.shop.util;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.function.Function;
|
||||
import java.util.function.Predicate;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
class UpstreamUserFinderTest {
|
||||
|
||||
@Test
|
||||
void findFirstNMatchingUpstreamUsers_skipsNonMatchingAndKeepsOrder() {
|
||||
// 100 -> 101 -> 102 -> 103 -> null
|
||||
Map<Integer, Integer> parent = Map.of(
|
||||
100, 101,
|
||||
101, 102,
|
||||
102, 103
|
||||
);
|
||||
Set<Integer> shopRoleUsers = Set.of(102, 103);
|
||||
|
||||
Function<Integer, Integer> parentResolver = parent::get;
|
||||
Predicate<Integer> matcher = shopRoleUsers::contains;
|
||||
|
||||
List<Integer> got = UpstreamUserFinder.findFirstNMatchingUpstreamUsers(100, 2, 20, parentResolver, matcher);
|
||||
assertEquals(List.of(102, 103), got);
|
||||
}
|
||||
|
||||
@Test
|
||||
void findFirstNMatchingUpstreamUsers_returnsSingleWhenOnlyOneMatchExists() {
|
||||
// 200 -> 201 -> 202 -> null
|
||||
Map<Integer, Integer> parent = Map.of(
|
||||
200, 201,
|
||||
201, 202
|
||||
);
|
||||
Set<Integer> shopRoleUsers = Set.of(201);
|
||||
|
||||
List<Integer> got = UpstreamUserFinder.findFirstNMatchingUpstreamUsers(200, 2, 20, parent::get, shopRoleUsers::contains);
|
||||
assertEquals(List.of(201), got);
|
||||
}
|
||||
|
||||
@Test
|
||||
void findFirstNMatchingUpstreamUsers_stopsOnCycle() {
|
||||
// 300 -> 301 -> 302 -> 301 (cycle)
|
||||
Map<Integer, Integer> parent = Map.of(
|
||||
300, 301,
|
||||
301, 302,
|
||||
302, 301
|
||||
);
|
||||
Set<Integer> shopRoleUsers = Set.of(301, 302);
|
||||
|
||||
List<Integer> got = UpstreamUserFinder.findFirstNMatchingUpstreamUsers(300, 2, 20, parent::get, shopRoleUsers::contains);
|
||||
assertEquals(List.of(301, 302), got);
|
||||
}
|
||||
|
||||
@Test
|
||||
void findFirstNMatchingUpstreamUsers_returnsEmptyForNullStart() {
|
||||
List<Integer> got = UpstreamUserFinder.findFirstNMatchingUpstreamUsers(null, 2, 20, x -> null, x -> true);
|
||||
assertEquals(List.of(), got);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,155 +0,0 @@
|
||||
package com.gxwebsoft.test;
|
||||
|
||||
import com.gxwebsoft.common.core.config.ConfigProperties;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.io.File;
|
||||
|
||||
/**
|
||||
* 证书路径拼接测试
|
||||
* 验证开发环境的路径拼接规则:配置文件upload-path + dev/wechat/ + 租户ID
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2025-08-09
|
||||
*/
|
||||
@SpringBootTest
|
||||
@ActiveProfiles("dev")
|
||||
public class CertificatePathConcatenationTest {
|
||||
|
||||
@Value("${spring.profiles.active:prod}")
|
||||
private String activeProfile;
|
||||
|
||||
@Resource
|
||||
private ConfigProperties configProperties;
|
||||
|
||||
@Test
|
||||
public void testCertificatePathConcatenation() {
|
||||
System.out.println("=== 证书路径拼接测试 ===");
|
||||
System.out.println("当前环境: " + activeProfile);
|
||||
|
||||
if ("dev".equals(activeProfile)) {
|
||||
testDevEnvironmentPathConcatenation();
|
||||
} else {
|
||||
testProdEnvironmentPathConcatenation();
|
||||
}
|
||||
|
||||
System.out.println("=== 证书路径拼接测试完成 ===");
|
||||
}
|
||||
|
||||
private void testDevEnvironmentPathConcatenation() {
|
||||
System.out.println("--- 开发环境路径拼接测试 ---");
|
||||
|
||||
// 获取配置文件中的upload-path
|
||||
String uploadPath = configProperties.getUploadPath();
|
||||
System.out.println("配置文件upload-path: " + uploadPath);
|
||||
|
||||
// 拼接规则:配置文件upload-path + dev/wechat/ + 租户ID
|
||||
String tenantId = "10550";
|
||||
String certBasePath = uploadPath + "dev/wechat/" + tenantId + "/";
|
||||
String privateKeyPath = certBasePath + "apiclient_key.pem";
|
||||
String certPath = certBasePath + "apiclient_cert.pem";
|
||||
|
||||
System.out.println("拼接规则: upload-path + dev/wechat/ + 租户ID");
|
||||
System.out.println("租户ID: " + tenantId);
|
||||
System.out.println("证书基础路径: " + certBasePath);
|
||||
System.out.println("私钥文件路径: " + privateKeyPath);
|
||||
System.out.println("证书文件路径: " + certPath);
|
||||
|
||||
// 验证路径是否正确
|
||||
File privateKeyFile = new File(privateKeyPath);
|
||||
File certFile = new File(certPath);
|
||||
|
||||
System.out.println("--- 文件存在性验证 ---");
|
||||
System.out.println("私钥文件存在: " + privateKeyFile.exists());
|
||||
System.out.println("证书文件存在: " + certFile.exists());
|
||||
|
||||
if (privateKeyFile.exists()) {
|
||||
System.out.println("✅ 私钥文件路径拼接正确");
|
||||
System.out.println(" 文件大小: " + privateKeyFile.length() + " bytes");
|
||||
} else {
|
||||
System.out.println("❌ 私钥文件路径拼接错误或文件不存在");
|
||||
}
|
||||
|
||||
if (certFile.exists()) {
|
||||
System.out.println("✅ 证书文件路径拼接正确");
|
||||
System.out.println(" 文件大小: " + certFile.length() + " bytes");
|
||||
} else {
|
||||
System.out.println("❌ 证书文件路径拼接错误或文件不存在");
|
||||
}
|
||||
|
||||
// 验证期望的路径
|
||||
String expectedPath = "/Users/gxwebsoft/JAVA/cms-java-code/src/main/resources/dev/wechat/10550/";
|
||||
System.out.println("--- 路径验证 ---");
|
||||
System.out.println("期望的证书路径: " + expectedPath);
|
||||
System.out.println("实际拼接路径: " + certBasePath);
|
||||
System.out.println("路径匹配: " + expectedPath.equals(certBasePath));
|
||||
|
||||
if (expectedPath.equals(certBasePath)) {
|
||||
System.out.println("✅ 路径拼接规则正确");
|
||||
} else {
|
||||
System.out.println("❌ 路径拼接规则需要调整");
|
||||
System.out.println(" 请检查配置文件中的upload-path设置");
|
||||
}
|
||||
}
|
||||
|
||||
private void testProdEnvironmentPathConcatenation() {
|
||||
System.out.println("--- 生产环境路径配置测试 ---");
|
||||
System.out.println("生产环境使用数据库配置的证书路径");
|
||||
System.out.println("路径格式: {uploadPath}/file/{relativePath}");
|
||||
|
||||
String uploadPath = configProperties.getUploadPath();
|
||||
System.out.println("配置的upload-path: " + uploadPath);
|
||||
|
||||
// 模拟生产环境路径拼接
|
||||
String relativePath = "wechat/10550/apiclient_key.pem";
|
||||
String prodPath = uploadPath + "file/" + relativePath;
|
||||
System.out.println("生产环境示例路径: " + prodPath);
|
||||
System.out.println("✅ 生产环境路径配置逻辑正确");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testMultipleTenantPaths() {
|
||||
System.out.println("=== 多租户路径拼接测试 ===");
|
||||
|
||||
if (!"dev".equals(activeProfile)) {
|
||||
System.out.println("跳过:仅在开发环境测试多租户路径");
|
||||
return;
|
||||
}
|
||||
|
||||
String uploadPath = configProperties.getUploadPath();
|
||||
String[] tenantIds = {"10324", "10398", "10547", "10549", "10550"};
|
||||
|
||||
System.out.println("配置文件upload-path: " + uploadPath);
|
||||
System.out.println("测试多个租户的证书路径拼接:");
|
||||
|
||||
for (String tenantId : tenantIds) {
|
||||
String certBasePath = uploadPath + "dev/wechat/" + tenantId + "/";
|
||||
String privateKeyPath = certBasePath + "apiclient_key.pem";
|
||||
|
||||
File privateKeyFile = new File(privateKeyPath);
|
||||
System.out.println("租户 " + tenantId + ": " + (privateKeyFile.exists() ? "✅" : "❌") + " " + privateKeyPath);
|
||||
}
|
||||
|
||||
System.out.println("=== 多租户路径拼接测试完成 ===");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testConfigurationProperties() {
|
||||
System.out.println("=== 配置属性测试1 ===");
|
||||
|
||||
System.out.println("当前环境: " + activeProfile);
|
||||
System.out.println("ConfigProperties注入: " + (configProperties != null ? "✅" : "❌"));
|
||||
|
||||
if (configProperties != null) {
|
||||
System.out.println("upload-path: " + configProperties.getUploadPath());
|
||||
System.out.println("upload-location: " + configProperties.getUploadLocation());
|
||||
System.out.println("server-url: " + configProperties.getServerUrl());
|
||||
}
|
||||
|
||||
System.out.println("=== 配置属性测试完成 ===");
|
||||
}
|
||||
}
|
||||
@@ -1,99 +0,0 @@
|
||||
package com.gxwebsoft.test;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
|
||||
import java.io.File;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
|
||||
/**
|
||||
* 证书路径修复验证测试
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2025-08-09
|
||||
*/
|
||||
@SpringBootTest
|
||||
@ActiveProfiles("dev")
|
||||
public class CertificatePathFixTest {
|
||||
|
||||
private static final String CERT_BASE_PATH = "/Users/gxwebsoft/JAVA/cms-java-code/src/main/resources/dev/wechat/10550";
|
||||
|
||||
@Test
|
||||
public void testCertificatePathFix() {
|
||||
System.out.println("=== 证书路径修复验证测试 ===");
|
||||
|
||||
// 验证证书目录存在
|
||||
File certDir = new File(CERT_BASE_PATH);
|
||||
assert certDir.exists() && certDir.isDirectory() : "证书目录不存在: " + CERT_BASE_PATH;
|
||||
System.out.println("✅ 证书目录存在: " + CERT_BASE_PATH);
|
||||
|
||||
// 验证私钥文件
|
||||
String privateKeyPath = CERT_BASE_PATH + "/apiclient_key.pem";
|
||||
File privateKeyFile = new File(privateKeyPath);
|
||||
assert privateKeyFile.exists() && privateKeyFile.isFile() : "私钥文件不存在: " + privateKeyPath;
|
||||
System.out.println("✅ 私钥文件存在: " + privateKeyPath);
|
||||
System.out.println(" 文件大小: " + privateKeyFile.length() + " bytes");
|
||||
|
||||
// 验证证书文件
|
||||
String certPath = CERT_BASE_PATH + "/apiclient_cert.pem";
|
||||
File certFile = new File(certPath);
|
||||
assert certFile.exists() && certFile.isFile() : "证书文件不存在: " + certPath;
|
||||
System.out.println("✅ 证书文件存在: " + certPath);
|
||||
System.out.println(" 文件大小: " + certFile.length() + " bytes");
|
||||
|
||||
// 验证文件内容格式
|
||||
try {
|
||||
String privateKeyContent = Files.readString(Paths.get(privateKeyPath));
|
||||
assert privateKeyContent.contains("-----BEGIN PRIVATE KEY-----") : "私钥文件格式错误";
|
||||
System.out.println("✅ 私钥文件格式正确");
|
||||
|
||||
String certContent = Files.readString(Paths.get(certPath));
|
||||
assert certContent.contains("-----BEGIN CERTIFICATE-----") : "证书文件格式错误";
|
||||
System.out.println("✅ 证书文件格式正确");
|
||||
|
||||
} catch (Exception e) {
|
||||
throw new RuntimeException("读取证书文件失败: " + e.getMessage(), e);
|
||||
}
|
||||
|
||||
System.out.println("=== 证书路径修复验证完成 ===");
|
||||
System.out.println("🎉 所有证书文件验证通过!");
|
||||
System.out.println();
|
||||
System.out.println("📋 修复内容总结:");
|
||||
System.out.println("1. 修复了 SettingServiceImpl 中的硬编码证书路径");
|
||||
System.out.println("2. 更新了 WechatCertAutoConfig 中的默认开发环境配置");
|
||||
System.out.println("3. 证书路径已指向正确位置: " + CERT_BASE_PATH);
|
||||
System.out.println();
|
||||
System.out.println("🔧 下一步建议:");
|
||||
System.out.println("1. 重启应用程序以使配置生效");
|
||||
System.out.println("2. 测试微信支付功能是否正常工作");
|
||||
System.out.println("3. 检查应用日志确认证书加载成功");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCertificatePathStructure() {
|
||||
System.out.println("=== 证书目录结构验证 ===");
|
||||
|
||||
File baseDir = new File("/Users/gxwebsoft/JAVA/cms-java-code/src/main/resources/dev/wechat");
|
||||
if (baseDir.exists()) {
|
||||
File[] tenantDirs = baseDir.listFiles(File::isDirectory);
|
||||
if (tenantDirs != null) {
|
||||
System.out.println("发现租户证书目录:");
|
||||
for (File tenantDir : tenantDirs) {
|
||||
System.out.println(" - 租户ID: " + tenantDir.getName());
|
||||
|
||||
File privateKey = new File(tenantDir, "apiclient_key.pem");
|
||||
File cert = new File(tenantDir, "apiclient_cert.pem");
|
||||
File p12 = new File(tenantDir, "apiclient_cert.p12");
|
||||
|
||||
System.out.println(" 私钥文件: " + (privateKey.exists() ? "✅" : "❌"));
|
||||
System.out.println(" 证书文件: " + (cert.exists() ? "✅" : "❌"));
|
||||
System.out.println(" P12文件: " + (p12.exists() ? "✅" : "❌"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
System.out.println("=== 目录结构验证完成 ===");
|
||||
}
|
||||
}
|
||||
@@ -1,107 +0,0 @@
|
||||
package com.gxwebsoft.test;
|
||||
|
||||
import com.gxwebsoft.common.core.config.CertificateProperties;
|
||||
import com.gxwebsoft.common.core.utils.CertificateLoader;
|
||||
import com.gxwebsoft.common.core.utils.WechatCertAutoConfig;
|
||||
import com.wechat.pay.java.core.Config;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
|
||||
/**
|
||||
* 证书测试类
|
||||
*/
|
||||
@SpringBootTest
|
||||
@ActiveProfiles("dev")
|
||||
public class CertificateTest {
|
||||
|
||||
@Autowired
|
||||
private CertificateProperties certConfig;
|
||||
|
||||
@Autowired
|
||||
private CertificateLoader certificateLoader;
|
||||
|
||||
@Autowired
|
||||
private WechatCertAutoConfig wechatCertAutoConfig;
|
||||
|
||||
@Test
|
||||
public void testCertificateLoading() {
|
||||
try {
|
||||
System.out.println("=== 证书加载测试 ===");
|
||||
|
||||
// 测试租户ID
|
||||
String tenantId = "10550";
|
||||
String tenantCertPath = "dev/wechat/" + tenantId;
|
||||
String privateKeyPath = tenantCertPath + "/" + certConfig.getWechatPay().getDev().getPrivateKeyFile();
|
||||
|
||||
System.out.println("证书路径: " + privateKeyPath);
|
||||
System.out.println("加载模式: " + certConfig.getLoadMode());
|
||||
System.out.println("开发环境证书路径前缀: " + certConfig.getDevCertPath());
|
||||
|
||||
// 检查证书文件是否存在
|
||||
boolean exists = certificateLoader.certificateExists(privateKeyPath);
|
||||
System.out.println("证书文件是否存在: " + exists);
|
||||
|
||||
if (!exists) {
|
||||
System.err.println("❌ 证书文件不存在: " + privateKeyPath);
|
||||
System.out.println("💡 请确认证书文件已放置在正确位置:");
|
||||
System.out.println(" src/main/resources/dev/wechat/10550/apiclient_key.pem");
|
||||
return;
|
||||
}
|
||||
|
||||
// 测试证书加载
|
||||
String privateKeyFile = certificateLoader.loadCertificatePath(privateKeyPath);
|
||||
System.out.println("✅ 私钥文件加载成功: " + privateKeyFile);
|
||||
|
||||
// 测试自动证书配置
|
||||
System.out.println("=== 测试自动证书配置 ===");
|
||||
Config config = wechatCertAutoConfig.createAutoConfig(
|
||||
"1723321338", // 测试商户号
|
||||
privateKeyFile,
|
||||
"test-serial-number", // 测试序列号
|
||||
"test-api-key" // 测试API密钥
|
||||
);
|
||||
|
||||
System.out.println("✅ 自动证书配置创建成功");
|
||||
|
||||
} catch (Exception e) {
|
||||
System.err.println("❌ 证书测试失败: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testNotificationCertificateConfig() {
|
||||
try {
|
||||
System.out.println("=== 异步通知证书配置测试 ===");
|
||||
|
||||
// 模拟异步通知中的证书配置逻辑
|
||||
String tenantId = "10550";
|
||||
String tenantCertPath = "dev/wechat/" + tenantId;
|
||||
String privateKeyPath = tenantCertPath + "/" + certConfig.getWechatPay().getDev().getPrivateKeyFile();
|
||||
|
||||
System.out.println("租户ID: " + tenantId);
|
||||
System.out.println("证书目录: " + tenantCertPath);
|
||||
System.out.println("私钥路径: " + privateKeyPath);
|
||||
|
||||
// 检查证书文件是否存在
|
||||
if (!certificateLoader.certificateExists(privateKeyPath)) {
|
||||
System.err.println("❌ 证书文件不存在: " + privateKeyPath);
|
||||
throw new RuntimeException("证书文件不存在: " + privateKeyPath);
|
||||
}
|
||||
|
||||
String privateKey = certificateLoader.loadCertificatePath(privateKeyPath);
|
||||
String apiV3Key = certConfig.getWechatPay().getDev().getApiV3Key();
|
||||
|
||||
System.out.println("✅ 私钥文件加载成功: " + privateKey);
|
||||
System.out.println("APIv3密钥配置: " + (apiV3Key != null ? "已配置" : "未配置"));
|
||||
|
||||
System.out.println("✅ 异步通知证书配置测试通过");
|
||||
|
||||
} catch (Exception e) {
|
||||
System.err.println("❌ 异步通知证书配置测试失败: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,119 +0,0 @@
|
||||
package com.gxwebsoft.test;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.io.File;
|
||||
|
||||
/**
|
||||
* 基于环境的证书路径配置测试
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2025-08-09
|
||||
*/
|
||||
@SpringBootTest
|
||||
@ActiveProfiles("dev")
|
||||
public class EnvironmentBasedCertificateTest {
|
||||
|
||||
@Value("${spring.profiles.active:prod}")
|
||||
private String activeProfile;
|
||||
|
||||
@Test
|
||||
public void testEnvironmentBasedCertificateConfig() {
|
||||
System.out.println("=== 环境基础证书配置测试 ===");
|
||||
System.out.println("当前激活的环境: " + activeProfile);
|
||||
|
||||
if ("dev".equals(activeProfile)) {
|
||||
System.out.println("✅ 检测到开发环境");
|
||||
testDevEnvironmentCertificates();
|
||||
} else {
|
||||
System.out.println("✅ 检测到生产环境");
|
||||
testProdEnvironmentCertificates();
|
||||
}
|
||||
|
||||
System.out.println("=== 环境基础证书配置测试完成 ===");
|
||||
}
|
||||
|
||||
private void testDevEnvironmentCertificates() {
|
||||
System.out.println("--- 开发环境证书路径测试 ---");
|
||||
|
||||
String devCertPath = "/Users/gxwebsoft/JAVA/cms-java-code/src/main/resources/dev/wechat/10550";
|
||||
String privateKeyPath = devCertPath + "/apiclient_key.pem";
|
||||
String certPath = devCertPath + "/apiclient_cert.pem";
|
||||
|
||||
System.out.println("开发环境证书目录: " + devCertPath);
|
||||
System.out.println("私钥文件路径: " + privateKeyPath);
|
||||
System.out.println("证书文件路径: " + certPath);
|
||||
|
||||
// 验证文件存在
|
||||
File privateKeyFile = new File(privateKeyPath);
|
||||
File certFile = new File(certPath);
|
||||
|
||||
assert privateKeyFile.exists() : "开发环境私钥文件不存在: " + privateKeyPath;
|
||||
assert certFile.exists() : "开发环境证书文件不存在: " + certPath;
|
||||
|
||||
System.out.println("✅ 开发环境证书文件验证通过");
|
||||
System.out.println(" - 私钥文件大小: " + privateKeyFile.length() + " bytes");
|
||||
System.out.println(" - 证书文件大小: " + certFile.length() + " bytes");
|
||||
}
|
||||
|
||||
private void testProdEnvironmentCertificates() {
|
||||
System.out.println("--- 生产环境证书路径测试 ---");
|
||||
System.out.println("生产环境将使用数据库配置的证书路径");
|
||||
System.out.println("证书路径格式: {uploadPath}/file/{relativePath}");
|
||||
System.out.println("✅ 生产环境配置逻辑正确");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCertificatePathLogic() {
|
||||
System.out.println("=== 证书路径逻辑测试 ===");
|
||||
|
||||
// 模拟不同环境的路径构建逻辑
|
||||
String uploadPath = "/www/wwwroot/file.ws/";
|
||||
String relativePath = "wechat/10550/apiclient_key.pem";
|
||||
|
||||
if ("dev".equals(activeProfile)) {
|
||||
// 开发环境:使用固定的本地路径
|
||||
String devPath = "/Users/gxwebsoft/JAVA/cms-java-code/src/main/resources/dev/wechat/10550/apiclient_key.pem";
|
||||
System.out.println("开发环境路径: " + devPath);
|
||||
|
||||
File devFile = new File(devPath);
|
||||
System.out.println("开发环境文件存在: " + devFile.exists());
|
||||
} else {
|
||||
// 生产环境:使用数据库配置的路径
|
||||
String prodPath = uploadPath + "file/" + relativePath;
|
||||
System.out.println("生产环境路径: " + prodPath);
|
||||
System.out.println("生产环境路径构建逻辑正确");
|
||||
}
|
||||
|
||||
System.out.println("=== 证书路径逻辑测试完成 ===");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testEnvironmentSwitching() {
|
||||
System.out.println("=== 环境切换测试 ===");
|
||||
|
||||
// 测试环境判断逻辑
|
||||
System.out.println("当前环境: " + activeProfile);
|
||||
|
||||
if ("dev".equals(activeProfile)) {
|
||||
System.out.println("✅ 开发环境配置:");
|
||||
System.out.println(" - 使用本地固定证书路径");
|
||||
System.out.println(" - 路径: /Users/gxwebsoft/JAVA/cms-java-code/src/main/resources/dev/wechat/10550/");
|
||||
System.out.println(" - 优点: 开发便利,无需配置数据库路径");
|
||||
} else if ("prod".equals(activeProfile)) {
|
||||
System.out.println("✅ 生产环境配置:");
|
||||
System.out.println(" - 使用数据库存储的证书路径");
|
||||
System.out.println(" - 路径格式: {uploadPath}/file/{relativePath}");
|
||||
System.out.println(" - 优点: 灵活配置,支持多租户");
|
||||
} else {
|
||||
System.out.println("⚠️ 未知环境: " + activeProfile);
|
||||
System.out.println(" - 默认使用生产环境配置");
|
||||
}
|
||||
|
||||
System.out.println("=== 环境切换测试完成 ===");
|
||||
}
|
||||
}
|
||||
@@ -1,101 +0,0 @@
|
||||
package com.gxwebsoft.test;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
import org.springframework.core.io.Resource;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
|
||||
/**
|
||||
* 异步通知证书修复验证测试
|
||||
*/
|
||||
public class NotificationCertificateFixTest {
|
||||
|
||||
@Test
|
||||
public void testCertificatePathFix() {
|
||||
System.out.println("=== 异步通知证书路径修复验证 ===");
|
||||
|
||||
// 模拟异步通知中的证书路径构建逻辑
|
||||
String tenantId = "10550";
|
||||
String devCertPath = "dev";
|
||||
String certDir = "wechat";
|
||||
String privateKeyFile = "apiclient_key.pem";
|
||||
|
||||
// 修复后的路径构建逻辑
|
||||
String tenantCertPath = devCertPath + "/" + certDir + "/" + tenantId;
|
||||
String privateKeyPath = tenantCertPath + "/" + privateKeyFile;
|
||||
|
||||
System.out.println("租户ID: " + tenantId);
|
||||
System.out.println("证书目录: " + tenantCertPath);
|
||||
System.out.println("私钥路径: " + privateKeyPath);
|
||||
|
||||
// 测试从classpath加载证书
|
||||
try {
|
||||
Resource resource = new ClassPathResource(privateKeyPath);
|
||||
System.out.println("证书资源存在: " + resource.exists());
|
||||
|
||||
if (resource.exists()) {
|
||||
// 模拟CertificateLoader.loadFromClasspath的逻辑
|
||||
Path tempFile = Files.createTempFile("cert_", ".pem");
|
||||
try (InputStream inputStream = resource.getInputStream()) {
|
||||
Files.copy(inputStream, tempFile, java.nio.file.StandardCopyOption.REPLACE_EXISTING);
|
||||
}
|
||||
|
||||
String tempPath = tempFile.toAbsolutePath().toString();
|
||||
System.out.println("✅ 证书加载成功: " + tempPath);
|
||||
|
||||
// 验证临时文件
|
||||
File tempCertFile = new File(tempPath);
|
||||
System.out.println("临时证书文件大小: " + tempCertFile.length() + " bytes");
|
||||
|
||||
// 清理临时文件
|
||||
Files.deleteIfExists(tempFile);
|
||||
|
||||
} else {
|
||||
System.err.println("❌ 证书文件不存在: " + privateKeyPath);
|
||||
}
|
||||
|
||||
} catch (IOException e) {
|
||||
System.err.println("❌ 证书加载失败: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
System.out.println("=== 测试完成 ===");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testAllTenantCertificates() {
|
||||
System.out.println("=== 测试所有租户证书 ===");
|
||||
|
||||
String[] tenantIds = {"10398", "10550"};
|
||||
String devCertPath = "dev";
|
||||
String certDir = "wechat";
|
||||
String privateKeyFile = "apiclient_key.pem";
|
||||
|
||||
for (String tenantId : tenantIds) {
|
||||
System.out.println("\n--- 测试租户: " + tenantId + " ---");
|
||||
|
||||
String tenantCertPath = devCertPath + "/" + certDir + "/" + tenantId;
|
||||
String privateKeyPath = tenantCertPath + "/" + privateKeyFile;
|
||||
|
||||
System.out.println("证书路径: " + privateKeyPath);
|
||||
|
||||
try {
|
||||
Resource resource = new ClassPathResource(privateKeyPath);
|
||||
if (resource.exists()) {
|
||||
System.out.println("✅ 租户 " + tenantId + " 证书存在");
|
||||
} else {
|
||||
System.out.println("❌ 租户 " + tenantId + " 证书不存在");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.err.println("❌ 租户 " + tenantId + " 证书检查失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
System.out.println("\n=== 所有租户证书测试完成 ===");
|
||||
}
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
package com.gxwebsoft.test;
|
||||
|
||||
import com.gxwebsoft.common.core.config.CertificateProperties;
|
||||
import com.gxwebsoft.common.core.utils.CertificateLoader;
|
||||
import com.gxwebsoft.common.core.utils.WechatCertAutoConfig;
|
||||
import com.gxwebsoft.common.core.service.PaymentCacheService;
|
||||
import com.gxwebsoft.common.system.entity.Payment;
|
||||
import com.wechat.pay.java.core.Config;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
|
||||
/**
|
||||
* 微信支付配置测试
|
||||
*/
|
||||
@SpringBootTest
|
||||
@ActiveProfiles("dev")
|
||||
public class WechatPayConfigTest {
|
||||
|
||||
@Autowired
|
||||
private CertificateProperties certConfig;
|
||||
|
||||
@Autowired
|
||||
private CertificateLoader certificateLoader;
|
||||
|
||||
@Autowired
|
||||
private WechatCertAutoConfig wechatCertAutoConfig;
|
||||
|
||||
@Autowired
|
||||
private PaymentCacheService paymentCacheService;
|
||||
|
||||
@Test
|
||||
public void testWechatPayConfig() {
|
||||
try {
|
||||
System.out.println("=== 微信支付配置测试 ===");
|
||||
|
||||
// 测试租户ID
|
||||
String tenantId = "10550";
|
||||
String tenantCertPath = "dev/wechat/" + tenantId;
|
||||
String privateKeyPath = tenantCertPath + "/" + certConfig.getWechatPay().getDev().getPrivateKeyFile();
|
||||
|
||||
System.out.println("证书路径: " + privateKeyPath);
|
||||
System.out.println("加载模式: " + certConfig.getLoadMode());
|
||||
|
||||
// 测试证书加载
|
||||
String privateKeyFile = certificateLoader.loadCertificatePath(privateKeyPath);
|
||||
System.out.println("私钥文件路径: " + privateKeyFile);
|
||||
|
||||
// 测试数据库支付配置
|
||||
System.out.println("=== 测试数据库支付配置 ===");
|
||||
try {
|
||||
Payment payment = paymentCacheService.getPaymentConfig(0, 10550); // 微信支付,租户ID 10550
|
||||
System.out.println("数据库配置获取成功:");
|
||||
System.out.println("商户号: " + payment.getMchId());
|
||||
System.out.println("序列号: " + payment.getMerchantSerialNumber());
|
||||
System.out.println("API密钥: " + (payment.getApiKey() != null ? "已配置(长度:" + payment.getApiKey().length() + ")" : "未配置"));
|
||||
System.out.println("应用ID: " + payment.getAppId());
|
||||
|
||||
// 使用数据库配置进行测试
|
||||
if (payment.getMchId() != null && payment.getMerchantSerialNumber() != null && payment.getApiKey() != null) {
|
||||
Config dbConfig = wechatCertAutoConfig.createAutoConfig(
|
||||
payment.getMchId(),
|
||||
privateKeyFile,
|
||||
payment.getMerchantSerialNumber(),
|
||||
payment.getApiKey()
|
||||
);
|
||||
System.out.println("使用数据库配置创建成功: " + (dbConfig != null));
|
||||
} else {
|
||||
System.out.println("数据库配置不完整,无法创建微信支付配置");
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
System.err.println("数据库配置获取失败: " + e.getMessage());
|
||||
|
||||
// 回退到配置文件参数
|
||||
System.out.println("=== 回退到配置文件参数 ===");
|
||||
String devApiKey = certConfig.getWechatPay().getDev().getApiV3Key();
|
||||
System.out.println("API密钥: " + (devApiKey != null ? "已配置(长度:" + devApiKey.length() + ")" : "未配置"));
|
||||
}
|
||||
|
||||
System.out.println("=== 测试完成 ===");
|
||||
|
||||
} catch (Exception e) {
|
||||
System.err.println("微信支付配置测试失败: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,134 +0,0 @@
|
||||
package com.gxwebsoft.test;
|
||||
|
||||
import com.gxwebsoft.common.core.config.CertificateProperties;
|
||||
import com.gxwebsoft.common.core.utils.CertificateLoader;
|
||||
import com.gxwebsoft.common.core.utils.RedisUtil;
|
||||
import com.gxwebsoft.common.system.entity.Payment;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
|
||||
/**
|
||||
* 微信支付配置验证测试
|
||||
*/
|
||||
@SpringBootTest
|
||||
@ActiveProfiles("dev")
|
||||
public class WechatPayConfigValidationTest {
|
||||
|
||||
@Autowired
|
||||
private CertificateProperties certConfig;
|
||||
|
||||
@Autowired
|
||||
private CertificateLoader certificateLoader;
|
||||
|
||||
@Autowired
|
||||
private RedisUtil redisUtil;
|
||||
|
||||
@Test
|
||||
public void testWechatPayConfigValidation() {
|
||||
System.out.println("=== 微信支付配置验证 ===");
|
||||
|
||||
// 1. 检查配置文件中的 APIv3 密钥
|
||||
String configApiV3Key = certConfig.getWechatPay().getDev().getApiV3Key();
|
||||
System.out.println("配置文件 APIv3 密钥: " + configApiV3Key);
|
||||
System.out.println("配置文件 APIv3 密钥长度: " + (configApiV3Key != null ? configApiV3Key.length() : 0));
|
||||
|
||||
// 2. 检查 Redis 中的支付配置
|
||||
String tenantId = "10550";
|
||||
String redisKey = "Payment:1:" + tenantId;
|
||||
Payment payment = redisUtil.get(redisKey, Payment.class);
|
||||
|
||||
if (payment != null) {
|
||||
System.out.println("\n=== Redis 支付配置 ===");
|
||||
System.out.println("商户号: " + payment.getMchId());
|
||||
System.out.println("应用ID: " + payment.getAppId());
|
||||
System.out.println("数据库 APIv3 密钥: " + payment.getApiKey());
|
||||
System.out.println("数据库 APIv3 密钥长度: " + (payment.getApiKey() != null ? payment.getApiKey().length() : 0));
|
||||
System.out.println("商户证书序列号: " + payment.getMerchantSerialNumber());
|
||||
|
||||
// 3. 比较两个 APIv3 密钥
|
||||
System.out.println("\n=== APIv3 密钥比较 ===");
|
||||
boolean keysMatch = (configApiV3Key != null && configApiV3Key.equals(payment.getApiKey()));
|
||||
System.out.println("配置文件与数据库密钥是否一致: " + keysMatch);
|
||||
|
||||
if (!keysMatch) {
|
||||
System.out.println("⚠️ 警告: 配置文件与数据库中的 APIv3 密钥不一致!");
|
||||
System.out.println("配置文件密钥: " + configApiV3Key);
|
||||
System.out.println("数据库密钥: " + payment.getApiKey());
|
||||
}
|
||||
|
||||
} else {
|
||||
System.out.println("❌ 未找到 Redis 中的支付配置: " + redisKey);
|
||||
|
||||
// 尝试其他可能的键格式
|
||||
String[] possibleKeys = {
|
||||
"Payment:1:10550",
|
||||
"Payment:0:10550",
|
||||
"Payment:10",
|
||||
"Payment:1" + "0" // Payment:10
|
||||
};
|
||||
|
||||
System.out.println("\n=== 尝试其他 Redis 键格式 ===");
|
||||
for (String key : possibleKeys) {
|
||||
Payment p = redisUtil.get(key, Payment.class);
|
||||
if (p != null) {
|
||||
System.out.println("✅ 找到支付配置: " + key);
|
||||
System.out.println(" 商户号: " + p.getMchId());
|
||||
System.out.println(" APIv3密钥: " + p.getApiKey());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 4. 验证证书文件
|
||||
System.out.println("\n=== 证书文件验证 ===");
|
||||
String tenantCertPath = "dev/wechat/" + tenantId;
|
||||
String privateKeyPath = tenantCertPath + "/" + certConfig.getWechatPay().getDev().getPrivateKeyFile();
|
||||
|
||||
boolean certExists = certificateLoader.certificateExists(privateKeyPath);
|
||||
System.out.println("证书文件存在: " + certExists);
|
||||
System.out.println("证书路径: " + privateKeyPath);
|
||||
|
||||
if (certExists) {
|
||||
try {
|
||||
String privateKey = certificateLoader.loadCertificatePath(privateKeyPath);
|
||||
System.out.println("✅ 证书加载成功: " + privateKey);
|
||||
} catch (Exception e) {
|
||||
System.out.println("❌ 证书加载失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
System.out.println("\n=== 验证完成 ===");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testApiV3KeyValidation() {
|
||||
System.out.println("=== APIv3 密钥格式验证 ===");
|
||||
|
||||
String configKey = certConfig.getWechatPay().getDev().getApiV3Key();
|
||||
|
||||
if (configKey != null) {
|
||||
System.out.println("APIv3 密钥: " + configKey);
|
||||
System.out.println("密钥长度: " + configKey.length());
|
||||
|
||||
// APIv3 密钥应该是32位字符串
|
||||
if (configKey.length() == 32) {
|
||||
System.out.println("✅ APIv3 密钥长度正确 (32位)");
|
||||
} else {
|
||||
System.out.println("❌ APIv3 密钥长度错误,应为32位,实际为: " + configKey.length());
|
||||
}
|
||||
|
||||
// 检查是否包含特殊字符
|
||||
boolean hasSpecialChars = !configKey.matches("^[a-zA-Z0-9]+$");
|
||||
if (hasSpecialChars) {
|
||||
System.out.println("⚠️ APIv3 密钥包含特殊字符,可能导致解密失败");
|
||||
} else {
|
||||
System.out.println("✅ APIv3 密钥格式正确 (仅包含字母和数字)");
|
||||
}
|
||||
|
||||
} else {
|
||||
System.out.println("❌ APIv3 密钥未配置");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,158 +0,0 @@
|
||||
package com.gxwebsoft.test;
|
||||
|
||||
import com.gxwebsoft.common.core.config.CertificateProperties;
|
||||
import com.gxwebsoft.common.core.service.PaymentCacheService;
|
||||
import com.gxwebsoft.common.core.utils.CertificateLoader;
|
||||
import com.gxwebsoft.common.system.entity.Payment;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
/**
|
||||
* 微信支付路径处理测试
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2025-07-29
|
||||
*/
|
||||
@SpringBootTest
|
||||
public class WechatPayPathTest {
|
||||
|
||||
@Autowired
|
||||
private PaymentCacheService paymentCacheService;
|
||||
|
||||
@Autowired
|
||||
private CertificateLoader certificateLoader;
|
||||
|
||||
@Autowired
|
||||
private CertificateProperties certConfig;
|
||||
|
||||
@Test
|
||||
public void testPublicKeyPathHandling() {
|
||||
try {
|
||||
System.out.println("=== 微信支付公钥路径处理测试 ===");
|
||||
|
||||
// 测试租户ID
|
||||
Integer tenantId = 10547;
|
||||
|
||||
// 获取支付配置
|
||||
Payment payment = paymentCacheService.getWechatPayConfig(tenantId);
|
||||
if (payment == null) {
|
||||
System.err.println("❌ 支付配置不存在");
|
||||
return;
|
||||
}
|
||||
|
||||
System.out.println("数据库配置信息:");
|
||||
System.out.println("租户ID: " + tenantId);
|
||||
System.out.println("商户号: " + payment.getMchId());
|
||||
System.out.println("公钥文件配置: " + payment.getPubKey());
|
||||
System.out.println("公钥ID: " + payment.getPubKeyId());
|
||||
|
||||
// 测试路径处理逻辑
|
||||
if (payment.getPubKey() != null && !payment.getPubKey().isEmpty()) {
|
||||
System.out.println("\n=== 路径处理测试 ===");
|
||||
|
||||
String pubKeyPath;
|
||||
if (payment.getPubKey().startsWith("dev/wechat/") || payment.getPubKey().startsWith("/")) {
|
||||
// 如果数据库中存储的是完整路径,直接使用
|
||||
pubKeyPath = payment.getPubKey();
|
||||
System.out.println("✅ 检测到完整路径,直接使用: " + pubKeyPath);
|
||||
} else {
|
||||
// 如果是相对路径,需要拼接租户目录
|
||||
String tenantCertPath = "dev/wechat/" + tenantId;
|
||||
pubKeyPath = tenantCertPath + "/" + payment.getPubKey();
|
||||
System.out.println("✅ 检测到相对路径,拼接后: " + pubKeyPath);
|
||||
}
|
||||
|
||||
// 测试文件是否存在
|
||||
System.out.println("\n=== 文件存在性检查 ===");
|
||||
if (certificateLoader.certificateExists(pubKeyPath)) {
|
||||
try {
|
||||
String actualPath = certificateLoader.loadCertificatePath(pubKeyPath);
|
||||
System.out.println("✅ 公钥文件存在: " + actualPath);
|
||||
|
||||
// 检查文件大小
|
||||
java.io.File file = new java.io.File(actualPath);
|
||||
if (file.exists()) {
|
||||
System.out.println("文件大小: " + file.length() + " 字节");
|
||||
System.out.println("文件可读: " + file.canRead());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
System.err.println("❌ 加载公钥文件失败: " + e.getMessage());
|
||||
}
|
||||
} else {
|
||||
System.err.println("❌ 公钥文件不存在: " + pubKeyPath);
|
||||
|
||||
// 提供修复建议
|
||||
System.out.println("\n=== 修复建议 ===");
|
||||
if (payment.getPubKey().contains("/")) {
|
||||
System.out.println("1. 检查数据库中的路径是否正确");
|
||||
System.out.println("2. 确认文件是否已上传到指定位置");
|
||||
System.out.println("3. 当前配置的路径: " + payment.getPubKey());
|
||||
} else {
|
||||
System.out.println("1. 将公钥文件放置到: src/main/resources/dev/wechat/" + tenantId + "/");
|
||||
System.out.println("2. 或者更新数据库配置为完整路径");
|
||||
}
|
||||
}
|
||||
|
||||
// 测试其他证书文件
|
||||
System.out.println("\n=== 其他证书文件检查 ===");
|
||||
String tenantCertPath = "dev/wechat/" + tenantId;
|
||||
String privateKeyPath = tenantCertPath + "/" + certConfig.getWechatPay().getDev().getPrivateKeyFile();
|
||||
String merchantCertPath = tenantCertPath + "/" + certConfig.getWechatPay().getDev().getApiclientCertFile();
|
||||
|
||||
System.out.println("私钥文件: " + privateKeyPath + " - " +
|
||||
(certificateLoader.certificateExists(privateKeyPath) ? "✅ 存在" : "❌ 不存在"));
|
||||
System.out.println("商户证书: " + merchantCertPath + " - " +
|
||||
(certificateLoader.certificateExists(merchantCertPath) ? "✅ 存在" : "❌ 不存在"));
|
||||
|
||||
} else {
|
||||
System.out.println("⚠️ 未配置公钥信息");
|
||||
}
|
||||
|
||||
System.out.println("\n=== 测试完成 ===");
|
||||
|
||||
} catch (Exception e) {
|
||||
System.err.println("❌ 测试失败: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateCorrectDirectoryStructure() {
|
||||
System.out.println("=== 创建正确的目录结构建议 ===");
|
||||
|
||||
try {
|
||||
Integer tenantId = 10547;
|
||||
Payment payment = paymentCacheService.getWechatPayConfig(tenantId);
|
||||
|
||||
if (payment != null && payment.getPubKey() != null) {
|
||||
System.out.println("当前数据库配置的公钥路径: " + payment.getPubKey());
|
||||
|
||||
if (payment.getPubKey().contains("/")) {
|
||||
// 包含路径分隔符,说明是完整路径
|
||||
System.out.println("\n建议的文件放置位置:");
|
||||
System.out.println("src/main/resources/" + payment.getPubKey());
|
||||
|
||||
// 创建目录的命令
|
||||
String dirPath = payment.getPubKey().substring(0, payment.getPubKey().lastIndexOf("/"));
|
||||
System.out.println("\n创建目录的命令:");
|
||||
System.out.println("mkdir -p src/main/resources/" + dirPath);
|
||||
|
||||
// 复制文件的命令
|
||||
System.out.println("\n如果您有公钥文件,可以这样复制:");
|
||||
System.out.println("cp your_public_key.pem src/main/resources/" + payment.getPubKey());
|
||||
} else {
|
||||
// 只是文件名,需要放在租户目录下
|
||||
System.out.println("\n建议的文件放置位置:");
|
||||
System.out.println("src/main/resources/dev/wechat/" + tenantId + "/" + payment.getPubKey());
|
||||
|
||||
System.out.println("\n或者更新数据库配置为:");
|
||||
System.out.println("UPDATE sys_payment SET pub_key = 'dev/wechat/" + tenantId + "/" + payment.getPubKey() + "' WHERE tenant_id = " + tenantId + " AND type = 0;");
|
||||
}
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
System.err.println("获取配置失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,150 +0,0 @@
|
||||
package com.gxwebsoft.test;
|
||||
|
||||
import com.gxwebsoft.common.core.config.CertificateProperties;
|
||||
import com.gxwebsoft.common.core.service.PaymentCacheService;
|
||||
import com.gxwebsoft.common.core.utils.CertificateLoader;
|
||||
import com.gxwebsoft.common.core.utils.WechatCertAutoConfig;
|
||||
import com.gxwebsoft.common.system.entity.Payment;
|
||||
import com.wechat.pay.java.core.Config;
|
||||
import com.wechat.pay.java.core.RSAPublicKeyConfig;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
/**
|
||||
* 微信支付公钥配置测试
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2025-07-29
|
||||
*/
|
||||
@SpringBootTest
|
||||
public class WechatPayPublicKeyTest {
|
||||
|
||||
@Autowired
|
||||
private PaymentCacheService paymentCacheService;
|
||||
|
||||
@Autowired
|
||||
private CertificateLoader certificateLoader;
|
||||
|
||||
@Autowired
|
||||
private CertificateProperties certConfig;
|
||||
|
||||
@Autowired
|
||||
private WechatCertAutoConfig wechatCertAutoConfig;
|
||||
|
||||
@Test
|
||||
public void testPublicKeyConfiguration() {
|
||||
try {
|
||||
System.out.println("=== 微信支付公钥配置测试 ===");
|
||||
|
||||
// 测试租户ID
|
||||
Integer tenantId = 10547;
|
||||
|
||||
// 获取支付配置
|
||||
Payment payment = paymentCacheService.getWechatPayConfig(tenantId);
|
||||
System.out.println("支付配置获取成功:");
|
||||
System.out.println("商户号: " + payment.getMchId());
|
||||
System.out.println("应用ID: " + payment.getAppId());
|
||||
System.out.println("序列号: " + payment.getMerchantSerialNumber());
|
||||
System.out.println("API密钥: " + (payment.getApiKey() != null ? "已配置(长度:" + payment.getApiKey().length() + ")" : "未配置"));
|
||||
System.out.println("公钥文件: " + payment.getPubKey());
|
||||
System.out.println("公钥ID: " + payment.getPubKeyId());
|
||||
|
||||
// 测试证书文件加载
|
||||
String tenantCertPath = "dev/wechat/" + tenantId;
|
||||
String privateKeyPath = tenantCertPath + "/" + certConfig.getWechatPay().getDev().getPrivateKeyFile();
|
||||
|
||||
System.out.println("\n=== 证书文件检查 ===");
|
||||
System.out.println("私钥路径: " + privateKeyPath);
|
||||
|
||||
if (certificateLoader.certificateExists(privateKeyPath)) {
|
||||
String privateKey = certificateLoader.loadCertificatePath(privateKeyPath);
|
||||
System.out.println("✅ 私钥文件加载成功: " + privateKey);
|
||||
|
||||
// 检查是否配置了公钥
|
||||
if (payment.getPubKey() != null && !payment.getPubKey().isEmpty() &&
|
||||
payment.getPubKeyId() != null && !payment.getPubKeyId().isEmpty()) {
|
||||
|
||||
System.out.println("\n=== 公钥配置测试 ===");
|
||||
String pubKeyPath = tenantCertPath + "/" + payment.getPubKey();
|
||||
System.out.println("公钥路径: " + pubKeyPath);
|
||||
|
||||
if (certificateLoader.certificateExists(pubKeyPath)) {
|
||||
String pubKeyFile = certificateLoader.loadCertificatePath(pubKeyPath);
|
||||
System.out.println("✅ 公钥文件加载成功: " + pubKeyFile);
|
||||
|
||||
// 测试RSA公钥配置
|
||||
try {
|
||||
Config config = new RSAPublicKeyConfig.Builder()
|
||||
.merchantId(payment.getMchId())
|
||||
.privateKeyFromPath(privateKey)
|
||||
.publicKeyFromPath(pubKeyFile)
|
||||
.publicKeyId(payment.getPubKeyId())
|
||||
.merchantSerialNumber(payment.getMerchantSerialNumber())
|
||||
.apiV3Key(payment.getApiKey())
|
||||
.build();
|
||||
|
||||
System.out.println("✅ RSA公钥配置创建成功");
|
||||
System.out.println("配置类型: " + config.getClass().getSimpleName());
|
||||
|
||||
} catch (Exception e) {
|
||||
System.err.println("❌ RSA公钥配置失败: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
} else {
|
||||
System.err.println("❌ 公钥文件不存在: " + pubKeyPath);
|
||||
System.out.println("💡 建议: 请将公钥文件放置到指定位置");
|
||||
}
|
||||
|
||||
} else {
|
||||
System.out.println("\n⚠️ 未配置公钥信息");
|
||||
System.out.println("💡 建议: 在数据库中配置 pubKey 和 pubKeyId 字段");
|
||||
|
||||
// 测试自动证书配置
|
||||
System.out.println("\n=== 自动证书配置测试 ===");
|
||||
try {
|
||||
Config autoConfig = wechatCertAutoConfig.createAutoConfig(
|
||||
payment.getMchId(),
|
||||
privateKey,
|
||||
payment.getMerchantSerialNumber(),
|
||||
payment.getApiKey()
|
||||
);
|
||||
System.out.println("✅ 自动证书配置创建成功");
|
||||
System.out.println("配置类型: " + autoConfig.getClass().getSimpleName());
|
||||
} catch (Exception e) {
|
||||
System.err.println("❌ 自动证书配置失败: " + e.getMessage());
|
||||
System.err.println("错误类型: " + e.getClass().getName());
|
||||
|
||||
if (e.getMessage() != null && e.getMessage().contains("certificate")) {
|
||||
System.err.println("🔍 这是证书相关错误,建议使用公钥模式");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} else {
|
||||
System.err.println("❌ 私钥文件不存在: " + privateKeyPath);
|
||||
}
|
||||
|
||||
System.out.println("\n=== 测试完成 ===");
|
||||
|
||||
} catch (Exception e) {
|
||||
System.err.println("❌ 测试失败: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateSamplePublicKeyConfig() {
|
||||
System.out.println("=== 创建示例公钥配置 ===");
|
||||
System.out.println("如果您的后台使用公钥模式,请在数据库中配置以下字段:");
|
||||
System.out.println("1. pubKey: 公钥文件名,例如 'wechatpay_public_key.pem'");
|
||||
System.out.println("2. pubKeyId: 公钥ID,例如 'PUB_KEY_ID_0112422897022025011300326200001208'");
|
||||
System.out.println("3. 将公钥文件放置到: src/main/resources/dev/wechat/{tenantId}/");
|
||||
System.out.println("\n示例SQL更新语句:");
|
||||
System.out.println("UPDATE sys_payment SET ");
|
||||
System.out.println(" pub_key = 'wechatpay_public_key.pem',");
|
||||
System.out.println(" pub_key_id = 'PUB_KEY_ID_0112422897022025011300326200001208'");
|
||||
System.out.println("WHERE tenant_id = 10547 AND type = 0;");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user