fix(hjmCar): 调整无坐标分页查询默认限制及状态

- 将无纬度或经度时的分页限制由2000缩减到500
- 设置无坐标查询时默认状态为1,优化数据筛选
- 删除了历史退款订单修复相关的控制器与服务代码
- 移除多个环境配置文件,清理无用资源
- 删除多项测试代码,去除无用单元测试与集成测试代码
This commit is contained in:
2026-04-29 22:14:07 +08:00
parent 4ec637d7f8
commit 01101d422f
31 changed files with 2 additions and 3078 deletions

View File

@@ -336,7 +336,8 @@ public class HjmCarController extends BaseController {
if (param.getLatitude() == null || param.getLatitude().isEmpty() ||
param.getLongitude() == null || param.getLongitude().isEmpty()) {
// 如果坐标为空,直接返回分页结果
param.setLimit(2000L);
param.setLimit(500L);
param.setStatus(1);
return success(hjmCarService.pageRel(param));
}

View File

@@ -1,72 +0,0 @@
package com.gxwebsoft.shop.controller;
import cn.hutool.core.util.ObjectUtil;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import com.gxwebsoft.shop.dto.RefundedOrderGltRepairRequest;
import com.gxwebsoft.shop.service.ShopOrderGltRepairService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
/**
* 历史订单修复:用于对“已退款的旧订单”补偿撤销水票相关数据。
*/
@Tag(name = "订单修复")
@RestController
@RequestMapping("/api/shop/shop-order/repair")
public class ShopOrderGltRepairController extends BaseController {
@Resource
private ShopOrderGltRepairService shopOrderGltRepairService;
@PreAuthorize("hasAuthority('shop:shopOrder:manage')")
@Operation(summary = "修复:已退款旧订单补偿撤销水票/释放计划/送水单支持dryRun预览")
@PostMapping("/revoke-glt-after-refund")
public ApiResult<?> revokeGltAfterRefund(@RequestBody RefundedOrderGltRepairRequest req) {
if (req == null) {
return fail("请求体不能为空");
}
Integer tenantId = ObjectUtil.defaultIfNull(req.getTenantId(), getTenantId());
if (tenantId == null) {
return fail("tenantId不能为空");
}
boolean dryRun = req.getDryRun() == null || req.getDryRun();
// 防误操作:既未指定订单,也未指定时间窗口时,只允许 dryRun
boolean noTargets = (req.getOrderIds() == null || req.getOrderIds().isEmpty())
&& (req.getOrderNos() == null || req.getOrderNos().isEmpty())
&& req.getRefundTimeStart() == null
&& req.getRefundTimeEnd() == null;
if (noTargets && !dryRun) {
return fail("请指定 orderIds/orderNos 或 refundTimeStart/refundTimeEnd否则仅允许 dryRun=true 预览");
}
ShopOrderGltRepairService.RepairResult r = shopOrderGltRepairService.revokeTicketsForRefundedOrders(
tenantId,
req.getOrderIds(),
req.getOrderNos(),
req.getRefundTimeStart(),
req.getRefundTimeEnd(),
req.getBatchSize(),
dryRun
);
Map<String, Object> data = new HashMap<>();
data.put("tenantId", tenantId);
data.put("dryRun", r.dryRun());
data.put("scannedOrders", r.scannedOrders());
data.put("ordersWithTicketsRevoked", r.ordersWithTicketsRevoked());
data.put("revokedTicketCount", r.revokedTicketCount());
data.put("processedOrderIds", r.processedOrderIds());
return success(data);
}
}

View File

@@ -1,109 +0,0 @@
package com.gxwebsoft.shop.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.glt.service.GltTicketRevokeService;
import com.gxwebsoft.shop.entity.ShopOrder;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
/**
* 历史订单修复:对已退款订单补偿撤销水票相关数据。
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class ShopOrderGltRepairService {
/** shop_order.order_status退款成功 */
private static final int ORDER_STATUS_REFUND_SUCCESS = 6;
private final ShopOrderService shopOrderService;
private final GltTicketRevokeService gltTicketRevokeService;
public RepairResult revokeTicketsForRefundedOrders(Integer tenantId,
List<Integer> orderIds,
List<String> orderNos,
LocalDateTime refundTimeStart,
LocalDateTime refundTimeEnd,
Integer batchSize,
boolean dryRun) {
if (tenantId == null) {
throw new IllegalArgumentException("tenantId不能为空");
}
int limit = batchSize == null ? 200 : Math.max(1, Math.min(batchSize, 2000));
List<ShopOrder> orders = new ArrayList<>();
// 1) 精准修复:指定 orderIds / orderNos
if (orderIds != null && !orderIds.isEmpty()) {
orders = shopOrderService.list(new LambdaQueryWrapper<ShopOrder>()
.eq(ShopOrder::getTenantId, tenantId)
.eq(ShopOrder::getDeleted, 0)
.eq(ShopOrder::getOrderStatus, ORDER_STATUS_REFUND_SUCCESS)
.in(ShopOrder::getOrderId, orderIds)
.last("limit " + limit));
} else if (orderNos != null && !orderNos.isEmpty()) {
orders = shopOrderService.list(new LambdaQueryWrapper<ShopOrder>()
.eq(ShopOrder::getTenantId, tenantId)
.eq(ShopOrder::getDeleted, 0)
.eq(ShopOrder::getOrderStatus, ORDER_STATUS_REFUND_SUCCESS)
.in(ShopOrder::getOrderNo, orderNos)
.last("limit " + limit));
} else {
// 2) 扫描修复:按 refundTime 窗口分页处理
LambdaQueryWrapper<ShopOrder> qw = new LambdaQueryWrapper<ShopOrder>()
.eq(ShopOrder::getTenantId, tenantId)
.eq(ShopOrder::getDeleted, 0)
.eq(ShopOrder::getOrderStatus, ORDER_STATUS_REFUND_SUCCESS);
if (refundTimeStart != null) {
qw.ge(ShopOrder::getRefundTime, refundTimeStart);
}
if (refundTimeEnd != null) {
qw.le(ShopOrder::getRefundTime, refundTimeEnd);
}
orders = shopOrderService.list(qw.orderByAsc(ShopOrder::getRefundTime).orderByAsc(ShopOrder::getOrderId).last("limit " + limit));
}
int scanned = orders == null ? 0 : orders.size();
int revokedTickets = 0;
int revokedOrders = 0;
List<Integer> processedOrderIds = new ArrayList<>();
if (orders != null) {
for (ShopOrder o : orders) {
if (o == null || o.getOrderId() == null) {
continue;
}
processedOrderIds.add(o.getOrderId());
if (dryRun) {
continue;
}
int revoked = gltTicketRevokeService.revokeByShopOrder(
tenantId,
o.getOrderId(),
o.getOrderNo(),
"历史退款订单补偿撤销水票"
);
if (revoked > 0) {
revokedTickets += revoked;
revokedOrders++;
}
}
}
return new RepairResult(scanned, revokedOrders, revokedTickets, processedOrderIds, dryRun);
}
public record RepairResult(int scannedOrders,
int ordersWithTicketsRevoked,
int revokedTicketCount,
List<Integer> processedOrderIds,
boolean dryRun) {
}
}

View File

@@ -1,85 +0,0 @@
# 生产环境配置
# 数据源配置
spring:
datasource:
url: jdbc:mysql://1Panel-mysql-XsWW:3306/modules?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
username: modules
password: tYmmMGh5wpwXR3ae
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月份配送费"}]'

View File

@@ -1,73 +0,0 @@
# 开发环境配置
# 服务器配置
server:
port: 9200
# 数据源配置
spring:
datasource:
url: jdbc:mysql://8.134.55.105:13306/modules?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8
username: modules
password: tYmmMGh5wpwXR3ae
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
# redis
redis:
database: 0
host: 8.134.55.105
port: 16379
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":"配送费"}]'

View File

@@ -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月份配送费"}]'

View File

@@ -1,101 +0,0 @@
# 生产环境配置
server:
port: 9300
# 数据源配置
spring:
datasource:
url: jdbc:mysql://1Panel-mysql-Bqdt:3306/ysb?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
username: ysb
password: 5Zf45CE2YneBfXkR
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-Q1LE
port: 6379
password: redis_WSDb88
# 日志配置
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
# Mybatis-plus配置
mybatis-plus:
mapper-locations: classpath*:com/gxwebsoft/**/*Mapper.xml
configuration:
map-underscore-to-camel-case: true
cache-enabled: true
global-config:
banner: false
# SqlRunner.db().xxx 需要开启该开关,否则会报:
# Mapped Statements collection does not contain value for com.baomidou.mybatisplus.core.mapper.SqlRunner.Delete
enable-sql-runner: true
db-config:
id-type: auto
logic-delete-value: 1
logic-not-delete-value: 0
# 框架配置
config:
# 文件服务器
file-server: https://file-s209.shoplnk.cn
# 生产环境接口
server-url: https://server.websoft.top/api
# 业务模块接口
api-url: https://ysb-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月份配送费"}]'

View File

@@ -1,98 +0,0 @@
# 服务器配置
server:
port: 9200
# 数据源配置
spring:
datasource:
url: jdbc:mysql://47.119.165.234:13308/ysb?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
username: ysb
password: 5Zf45CE2YneBfXkR
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
druid:
remove-abandoned: true
# redis
redis:
database: 0
host: 47.119.165.234
port: 16379
password: redis_WSDb88
# 日志配置
logging:
level:
com.gxwebsoft: DEBUG
com.baomidou.mybatisplus: DEBUG
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
# Mybatis-plus配置
mybatis-plus:
mapper-locations: classpath*:com/gxwebsoft/**/*Mapper.xml
configuration:
map-underscore-to-camel-case: true
cache-enabled: true
global-config:
banner: false
# SqlRunner.db().xxx 需要开启该开关,否则会报:
# Mapped Statements collection does not contain value for com.baomidou.mybatisplus.core.mapper.SqlRunner.Delete
enable-sql-runner: true
db-config:
id-type: auto
logic-delete-value: 1
logic-not-delete-value: 0
# 框架配置
config:
# 文件服务器
file-server: https://file-s209.shoplnk.cn
# 生产环境接口
server-url: https://server.websoft.top/api
# 业务模块接口
api-url: https://ysb-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月份配送费"}]'

View File

@@ -1,231 +0,0 @@
package com.gxwebsoft;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gxwebsoft.glt.entity.GltUserTicket;
import com.gxwebsoft.glt.service.GltTicketRevokeService;
import com.gxwebsoft.glt.service.GltUserTicketService;
import com.gxwebsoft.hjm.controller.PushCallback;
import com.gxwebsoft.hjm.entity.HjmCar;
import com.gxwebsoft.hjm.service.HjmCarService;
import com.gxwebsoft.shop.entity.ShopOrder;
import com.gxwebsoft.shop.entity.ShopOrderGoods;
import com.gxwebsoft.shop.service.ShopOrderGoodsService;
import com.gxwebsoft.shop.service.ShopOrderService;
import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.NumberFormat;
import java.text.ParseException;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* Created by WebSoft on 2020-03-23 23:37
*/
@SpringBootTest
public class TestMain {
private static final Logger logger = LoggerFactory.getLogger(PushCallback.class);
@Resource
private HjmCarService hjmCarService;
@Resource
private ShopOrderService shopOrderService;
@Resource
private ShopOrderGoodsService shopOrderGoodsService;
@Resource
private GltUserTicketService gltUserTicketService;
@Resource
private GltTicketRevokeService gltTicketRevokeService;
/**
* 查询已退款订单ShopOrder关联的gltUserTicket仅处理租户ID=10584
*/
@Test
public void testOrderData() {
final int tenantId = 10584;
final int ORDER_STATUS_REFUND_SUCCESS = 6;
// 安全开关:默认只查询/打印;如需实际撤销,将其改为 true
final boolean doRevoke = false;
int lastOrderId = 0;
int batchSize = 200;
int scannedOrders = 0;
int ordersWithTickets = 0;
int matchedTickets = 0;
int revokedTickets = 0;
while (true) {
List<ShopOrder> orders = shopOrderService.list(new LambdaQueryWrapper<ShopOrder>()
.select(ShopOrder::getOrderId, ShopOrder::getOrderNo, ShopOrder::getRefundTime, ShopOrder::getRefundMoney,
ShopOrder::getOrderStatus, ShopOrder::getPayStatus, ShopOrder::getCreateTime)
.eq(ShopOrder::getTenantId, tenantId)
.eq(ShopOrder::getDeleted, 0)
.eq(ShopOrder::getOrderStatus, ORDER_STATUS_REFUND_SUCCESS)
.gt(ShopOrder::getOrderId, lastOrderId)
.orderByAsc(ShopOrder::getOrderId)
.last("limit " + batchSize));
if (orders == null || orders.isEmpty()) {
break;
}
for (ShopOrder o : orders) {
if (o == null || o.getOrderId() == null) {
continue;
}
scannedOrders++;
lastOrderId = Math.max(lastOrderId, o.getOrderId());
List<GltUserTicket> tickets = findTicketsByOrder(tenantId, o.getOrderId(), o.getOrderNo());
if (tickets == null || tickets.isEmpty()) {
tickets = findTicketsByOrderGoodsFallback(tenantId, o.getOrderId());
}
if (tickets == null || tickets.isEmpty()) {
continue;
}
ordersWithTickets++;
matchedTickets += tickets.size();
logger.info("已退款订单关联水票 - tenantId={}, orderId={}, orderNo={}, refundMoney={}, refundTime={}, tickets={}",
tenantId, o.getOrderId(), o.getOrderNo(), o.getRefundMoney(), o.getRefundTime(),
tickets.stream().filter(Objects::nonNull).map(GltUserTicket::getId).collect(Collectors.toList()));
if (doRevoke) {
int revoked = gltTicketRevokeService.revokeByShopOrder(
tenantId,
o.getOrderId(),
o.getOrderNo(),
"TestMain: 历史退款订单撤销水票"
);
revokedTickets += revoked;
}
}
}
logger.info("扫描完成 - tenantId={}, scannedOrders={}, ordersWithTickets={}, matchedTickets={}, doRevoke={}, revokedTickets={}",
tenantId, scannedOrders, ordersWithTickets, matchedTickets, doRevoke, revokedTickets);
}
private List<GltUserTicket> findTicketsByOrder(Integer tenantId, Integer orderId, String orderNo) {
LambdaQueryWrapper<GltUserTicket> qw = new LambdaQueryWrapper<GltUserTicket>()
.eq(GltUserTicket::getTenantId, tenantId)
.eq(GltUserTicket::getDeleted, 0);
if (orderId != null && StrUtil.isNotBlank(orderNo)) {
qw.and(w -> w.eq(GltUserTicket::getOrderId, orderId).or().eq(GltUserTicket::getOrderNo, orderNo));
} else if (orderId != null) {
qw.eq(GltUserTicket::getOrderId, orderId);
} else if (StrUtil.isNotBlank(orderNo)) {
qw.eq(GltUserTicket::getOrderNo, orderNo);
} else {
return List.of();
}
return gltUserTicketService.list(qw);
}
/**
* 兼容历史数据:部分水票仅记录了 order_goods_id未回填 order_id/order_no。
*/
private List<GltUserTicket> findTicketsByOrderGoodsFallback(Integer tenantId, Integer orderId) {
if (tenantId == null || orderId == null) {
return List.of();
}
List<ShopOrderGoods> goods = shopOrderGoodsService.list(new LambdaQueryWrapper<ShopOrderGoods>()
.select(ShopOrderGoods::getId)
.eq(ShopOrderGoods::getTenantId, tenantId)
.eq(ShopOrderGoods::getOrderId, orderId));
if (goods == null || goods.isEmpty()) {
return List.of();
}
List<Integer> orderGoodsIds = goods.stream()
.map(ShopOrderGoods::getId)
.filter(Objects::nonNull)
.distinct()
.collect(Collectors.toList());
if (orderGoodsIds.isEmpty()) {
return List.of();
}
return gltUserTicketService.list(new LambdaQueryWrapper<GltUserTicket>()
.eq(GltUserTicket::getTenantId, tenantId)
.eq(GltUserTicket::getDeleted, 0)
.in(GltUserTicket::getOrderGoodsId, orderGoodsIds));
}
/**
* 生成唯一的key用于jwt工具类
*/
@Test
public void testGenJwtKey() {
BigDecimal bigDecimal = new BigDecimal(NumberUtil.decimalFormat("0.00", 1 * 0.01));
System.out.println("实际付款金额111111111 = " + bigDecimal);
final HjmCar byGpsNo = hjmCarService.getByGpsNo("gps1");
System.out.println("byGpsNo = " + byGpsNo.getSpeed());
if(StrUtil.isBlank(byGpsNo.getSpeed())){
System.out.println("空的 = ");
}
if(byGpsNo.getSpeed() == null){
System.out.println("getSpeed = ");
}
// System.out.println(JwtUtil.encodeKey(JwtUtil.randomKey()));
// final String encrypt = CommonUtil.encrypt("123456");
// System.out.println("encrypt = " + encrypt);
//
// final String decrypt = CommonUtil.decrypt(encrypt);
// System.out.println("decrypt = " + decrypt);
}
// @Test
// public void mqtt() throws MqttException {
////tcp://MQTT安装的服务器地址:MQTT定义的端口号
// String HOST = "tcp://1.14.159.185:1883";
//
// //定义MQTT的ID可以在MQTT服务配置中指定
// String clientid = "mqttx_aec633ca2";
//
// MqttClient client;
// String userName = "swdev";
// String passWord = "Sw20250523";
//
// client = new MqttClient(HOST, clientid, new MemoryPersistence());
//
// final MqttConnectOptions mqttConnectOptions = new MqttConnectOptions();
// mqttConnectOptions.setUserName(userName);
// mqttConnectOptions.setPassword(passWord.toCharArray());
// mqttConnectOptions.setCleanSession(true);
//
// client.setCallback(new MqttCallback() {
// @Override
// public void connectionLost(Throwable throwable) {
// logger.info("连接丢失.............");
// }
//
// @Override
// public void messageArrived(String topic, MqttMessage mqttMessage) throws Exception {
// logger.info("接收消息主题 : " + topic);
// logger.info("接收消息Qos : " + mqttMessage.getQos());
// logger.info("接收消息内容 : " + new String(mqttMessage.getPayload()));
// }
//
// @Override
// public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
// logger.info("deliveryComplete.............");
// }
// });
// client.connect(mqttConnectOptions);
// client.subscribe("/SW_GSP/#", 2);
// while (true);
// }
}

View File

@@ -1,56 +0,0 @@
package com.gxwebsoft.bszx;
import com.gxwebsoft.bszx.service.BszxPayService;
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-31
*/
@SpringBootTest
@ActiveProfiles("test")
public class BszxOrderTotalTest {
@Resource
private BszxPayService bszxPayService;
@Test
void testBszxOrderTotal() {
// 测试百色中学订单总金额统计
BigDecimal total = bszxPayService.total();
// 验证返回值不为null
assertNotNull(total, "百色中学订单总金额不应该为null");
// 验证返回值大于等于0
assertTrue(total.compareTo(BigDecimal.ZERO) >= 0, "百色中学订单总金额应该大于等于0");
System.out.println("百色中学订单总金额统计结果:" + total);
}
@Test
void testBszxOrderTotalPerformance() {
// 测试性能
long startTime = System.currentTimeMillis();
BigDecimal total = bszxPayService.total();
long endTime = System.currentTimeMillis();
long duration = endTime - startTime;
System.out.println("百色中学订单总金额统计耗时:" + duration + "ms");
System.out.println("统计结果:" + total);
// 验证查询时间在合理范围内小于5秒
assertTrue(duration < 5000, "查询时间应该在5秒以内");
}
}

View File

@@ -1,66 +0,0 @@
package com.gxwebsoft.cms.service.impl;
import com.gxwebsoft.cms.entity.CmsApp;
import com.gxwebsoft.cms.mapper.CmsAppMapper;
import com.gxwebsoft.cms.service.CmsNavigationService;
import com.gxwebsoft.common.core.utils.RedisUtil;
import com.gxwebsoft.shop.vo.ShopVo;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Field;
import java.util.Collections;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class CmsAppServiceImplCacheTest {
@Test
void getSiteInfo_cacheValueIsJsonNull_shouldFallbackToDb() throws Exception {
Integer tenantId = 1;
RedisUtil redisUtil = mock(RedisUtil.class);
CmsNavigationService cmsNavigationService = mock(CmsNavigationService.class);
CmsAppMapper cmsAppMapper = mock(CmsAppMapper.class);
// 历史缓存可能存在字符串 "null"Jackson 解析后会得到 null需回源 DB。
when(redisUtil.get("SiteInfo:" + tenantId)).thenReturn("null");
when(cmsNavigationService.listRel(any())).thenReturn(Collections.emptyList());
CmsApp website = new CmsApp();
website.setTenantId(tenantId);
website.setTenantName("tenant");
website.setAppName("site");
when(cmsAppMapper.getByTenantId(tenantId)).thenReturn(website);
CmsAppServiceImpl service = new CmsAppServiceImpl();
setField(service, "redisUtil", redisUtil);
setField(service, "cmsNavigationService", cmsNavigationService);
setField(service, "baseMapper", cmsAppMapper);
ShopVo vo = service.getSiteInfo(tenantId);
assertNotNull(vo);
verify(redisUtil).delete("SiteInfo:" + tenantId);
verify(cmsAppMapper).getByTenantId(tenantId);
}
private static void setField(Object target, String fieldName, Object value) throws Exception {
Class<?> c = target.getClass();
while (c != null) {
try {
Field f = c.getDeclaredField(fieldName);
f.setAccessible(true);
f.set(target, value);
return;
} catch (NoSuchFieldException ignored) {
c = c.getSuperclass();
}
}
throw new NoSuchFieldException(fieldName);
}
}

View File

@@ -1,66 +0,0 @@
package com.gxwebsoft.cms.service.impl;
import com.gxwebsoft.cms.entity.CmsWebsite;
import com.gxwebsoft.cms.mapper.CmsWebsiteMapper;
import com.gxwebsoft.cms.service.CmsNavigationService;
import com.gxwebsoft.common.core.utils.RedisUtil;
import com.gxwebsoft.shop.vo.ShopVo;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Field;
import java.util.Collections;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class CmsWebsiteServiceImplCacheTest {
@Test
void getSiteInfo_cacheValueIsJsonNull_shouldFallbackToDb() throws Exception {
Integer tenantId = 1;
RedisUtil redisUtil = mock(RedisUtil.class);
CmsNavigationService cmsNavigationService = mock(CmsNavigationService.class);
CmsWebsiteMapper cmsWebsiteMapper = mock(CmsWebsiteMapper.class);
// 历史缓存可能存在字符串 "null"Jackson 解析后会得到 null需回源 DB。
when(redisUtil.get("SiteInfo:" + tenantId)).thenReturn("null");
when(cmsNavigationService.listRel(any())).thenReturn(Collections.emptyList());
CmsWebsite website = new CmsWebsite();
website.setTenantId(tenantId);
website.setTenantName("tenant");
website.setWebsiteName("site");
when(cmsWebsiteMapper.getByTenantId(tenantId)).thenReturn(website);
CmsWebsiteServiceImpl service = new CmsWebsiteServiceImpl();
setField(service, "redisUtil", redisUtil);
setField(service, "cmsNavigationService", cmsNavigationService);
setField(service, "baseMapper", cmsWebsiteMapper);
ShopVo vo = service.getSiteInfo(tenantId);
assertNotNull(vo);
verify(redisUtil).delete("SiteInfo:" + tenantId);
verify(cmsWebsiteMapper).getByTenantId(tenantId);
}
private static void setField(Object target, String fieldName, Object value) throws Exception {
Class<?> c = target.getClass();
while (c != null) {
try {
Field f = c.getDeclaredField(fieldName);
f.setAccessible(true);
f.set(target, value);
return;
} catch (NoSuchFieldException ignored) {
c = c.getSuperclass();
}
}
throw new NoSuchFieldException(fieldName);
}
}

View File

@@ -1,105 +0,0 @@
package com.gxwebsoft.credit.controller;
import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.credit.entity.CreditBankruptcy;
import com.gxwebsoft.credit.service.CreditBankruptcyService;
import com.gxwebsoft.credit.service.CreditCompanyRecordCountService;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.test.util.ReflectionTestUtils;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;
class CreditBankruptcyImportSheetSelectionTest {
@Test
void import_should_prefer_sheet_named_bankruptcy_reorganization() throws Exception {
MultipartFile file = buildWorkbookWithTwoSheets();
CreditBankruptcyController controller = new CreditBankruptcyController();
CreditBankruptcyService creditBankruptcyService = Mockito.mock(CreditBankruptcyService.class);
BatchImportSupport batchImportSupport = Mockito.mock(BatchImportSupport.class);
CreditCompanyRecordCountService recordCountService = Mockito.mock(CreditCompanyRecordCountService.class);
// Capture inserted entities; controller clears the chunk list after calling persistInsertOnlyChunk.
List<CreditBankruptcy> inserted = new ArrayList<>();
Mockito.when(batchImportSupport.persistInsertOnlyChunk(
Mockito.eq(creditBankruptcyService),
Mockito.anyList(),
Mockito.anyList(),
Mockito.anyInt(),
Mockito.any(),
Mockito.anyString(),
Mockito.anyList()
))
.thenAnswer(invocation -> {
@SuppressWarnings("unchecked")
List<CreditBankruptcy> items = new ArrayList<>((List<CreditBankruptcy>) invocation.getArgument(1));
inserted.addAll(items);
return items.size();
});
ReflectionTestUtils.setField(controller, "creditBankruptcyService", creditBankruptcyService);
ReflectionTestUtils.setField(controller, "batchImportSupport", batchImportSupport);
ReflectionTestUtils.setField(controller, "creditCompanyRecordCountService", recordCountService);
ApiResult<List<String>> result = controller.importBatch(file, null);
assertNotNull(result);
assertEquals(0, result.getCode());
assertTrue(result.getMessage().contains("成功导入1条"), "message=" + result.getMessage());
assertEquals(1, inserted.size());
// "历史破产重整" sheet is first; we should import from "破产重整" instead.
assertEquals("R1", inserted.get(0).getCode());
}
private static MultipartFile buildWorkbookWithTwoSheets() throws Exception {
try (Workbook workbook = new XSSFWorkbook()) {
// Put "历史破产重整" first to ensure old readAnySheet() behavior would import the wrong sheet.
writeBankruptcySheet(workbook.createSheet("历史破产重整"), "H1");
writeBankruptcySheet(workbook.createSheet("破产重整"), "R1");
try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
workbook.write(bos);
return new MockMultipartFile(
"file",
"bankruptcy.xlsx",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
bos.toByteArray()
);
}
}
}
private static void writeBankruptcySheet(Sheet sheet, String code) {
// Keep it simple: a single header row + single data row.
Row header = sheet.createRow(0);
header.createCell(0).setCellValue("案号");
header.createCell(1).setCellValue("案件类型");
header.createCell(2).setCellValue("当事人");
header.createCell(3).setCellValue("经办法院");
header.createCell(4).setCellValue("公开日期");
header.createCell(5).setCellValue("备注");
Row row = sheet.createRow(1);
row.createCell(0).setCellValue(code);
row.createCell(1).setCellValue("破产重整");
row.createCell(2).setCellValue("示例公司");
row.createCell(3).setCellValue("示例法院");
row.createCell(4).setCellValue("2026-01-01");
row.createCell(5).setCellValue("备注");
}
}

View File

@@ -1,51 +0,0 @@
package com.gxwebsoft.credit.controller;
import com.gxwebsoft.credit.entity.CreditXgxf;
import com.gxwebsoft.credit.param.CreditXgxfImportParam;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Method;
import static org.junit.jupiter.api.Assertions.assertEquals;
class CreditXgxfImportMappingTest {
private static CreditXgxf convert(CreditXgxfImportParam param) throws Exception {
CreditXgxfController controller = new CreditXgxfController();
Method m = CreditXgxfController.class.getDeclaredMethod("convertImportParamToEntity", CreditXgxfImportParam.class);
m.setAccessible(true);
return (CreditXgxf) m.invoke(controller, param);
}
@Test
void mapsAlternateUpstreamHeadersForParties() throws Exception {
CreditXgxfImportParam param = new CreditXgxfImportParam();
param.setCaseNumber("2024示例案号");
param.setPlaintiffAppellant2("申请执行人A");
param.setAppellee2("被执行人B");
param.setCourtName2("执行法院C");
CreditXgxf entity = convert(param);
assertEquals("申请执行人A", entity.getPlaintiffAppellant());
assertEquals("被执行人B", entity.getAppellee());
assertEquals("执行法院C", entity.getCourtName());
}
@Test
void prefersCanonicalHeadersWhenBothPresent() throws Exception {
CreditXgxfImportParam param = new CreditXgxfImportParam();
param.setCaseNumber("2024示例案号");
param.setPlaintiffAppellant("原告A");
param.setPlaintiffAppellant2("申请执行人A");
param.setAppellee("被告B");
param.setAppellee2("被执行人B");
param.setCourtName("法院C");
param.setCourtName2("执行法院C");
CreditXgxf entity = convert(param);
assertEquals("原告A", entity.getPlaintiffAppellant());
assertEquals("被告B", entity.getAppellee());
assertEquals("法院C", entity.getCourtName());
}
}

View File

@@ -1,93 +0,0 @@
package com.gxwebsoft.credit.controller;
import com.gxwebsoft.credit.param.CreditPatentImportParam;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.junit.jupiter.api.Test;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayOutputStream;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
class ExcelImportSupportPatentImportTest {
@Test
void import_should_map_parentheses_headers() throws Exception {
MultipartFile file = buildPatentWorkbookFile("公开(公告)号", "申请(专利权)人");
ExcelImportSupport.ImportResult<CreditPatentImportParam> result = ExcelImportSupport.readAnySheet(
file,
CreditPatentImportParam.class,
p -> p == null || (ImportHelper.isBlank(p.getRegisterNo()) && ImportHelper.isBlank(p.getName()))
);
assertNotNull(result);
assertEquals(1, result.getData().size());
CreditPatentImportParam row = result.getData().get(0);
assertEquals("CN2024XXXXXXXX.X", row.getRegisterNo());
assertEquals("CN1XXXXXXXXX", row.getPublicNo());
assertEquals("示例科技有限公司", row.getPatentApplicant());
}
@Test
void import_should_handle_fullwidth_parentheses_headers() throws Exception {
MultipartFile file = buildPatentWorkbookFile("公开(公告)号", "申请(专利权)人");
ExcelImportSupport.ImportResult<CreditPatentImportParam> result = ExcelImportSupport.readAnySheet(
file,
CreditPatentImportParam.class,
p -> p == null || (ImportHelper.isBlank(p.getRegisterNo()) && ImportHelper.isBlank(p.getName()))
);
assertNotNull(result);
assertEquals(1, result.getData().size());
CreditPatentImportParam row = result.getData().get(0);
assertEquals("CN2024XXXXXXXX.X", row.getRegisterNo());
assertEquals("CN1XXXXXXXXX", row.getPublicNo());
assertEquals("示例科技有限公司", row.getPatentApplicant());
}
private static MultipartFile buildPatentWorkbookFile(String publicNoHeader, String applicantHeader) throws Exception {
try (Workbook workbook = new XSSFWorkbook()) {
Sheet sheet = workbook.createSheet("专利");
Row header = sheet.createRow(0);
header.createCell(0).setCellValue("发明名称");
header.createCell(1).setCellValue("专利类型");
header.createCell(2).setCellValue("法律状态");
header.createCell(3).setCellValue("申请号");
header.createCell(4).setCellValue("申请日");
header.createCell(5).setCellValue(publicNoHeader);
header.createCell(6).setCellValue("公开(公告)日期");
header.createCell(7).setCellValue("发明人");
header.createCell(8).setCellValue(applicantHeader);
header.createCell(9).setCellValue("备注");
Row row = sheet.createRow(1);
row.createCell(0).setCellValue("一种示例装置及方法");
row.createCell(1).setCellValue("发明专利");
row.createCell(2).setCellValue("有效");
row.createCell(3).setCellValue("CN2024XXXXXXXX.X");
row.createCell(4).setCellValue("2024-01-01");
row.createCell(5).setCellValue("CN1XXXXXXXXX");
row.createCell(6).setCellValue("2024-06-01");
row.createCell(7).setCellValue("张三;李四");
row.createCell(8).setCellValue("示例科技有限公司");
row.createCell(9).setCellValue("备注信息");
try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
workbook.write(bos);
return new MockMultipartFile(
"file",
"patent.xlsx",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
bos.toByteArray()
);
}
}
}
}

View File

@@ -1,22 +0,0 @@
package com.gxwebsoft.glt;
import com.gxwebsoft.glt.mapper.GltUserTicketLogMapper;
import com.gxwebsoft.glt.mapper.GltUserTicketMapper;
import com.gxwebsoft.glt.mapper.GltUserTicketReleaseMapper;
import com.gxwebsoft.glt.service.impl.GltUserTicketAutoReleaseServiceImpl;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Import;
@SpringBootConfiguration
@EnableAutoConfiguration
@MapperScan(basePackageClasses = {
GltUserTicketMapper.class,
GltUserTicketReleaseMapper.class,
GltUserTicketLogMapper.class
})
@Import(GltUserTicketAutoReleaseServiceImpl.class)
public class AutoReleaseTestApplication {
}

View File

@@ -1,69 +0,0 @@
package com.gxwebsoft.glt.service;
import com.gxwebsoft.glt.entity.GltUserTicket;
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.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.*;
@ExtendWith(MockitoExtension.class)
class GltTicketRevokeServiceTest {
@Mock
private GltUserTicketService gltUserTicketService;
@Mock
private GltUserTicketReleaseService gltUserTicketReleaseService;
@Mock
private GltTicketOrderService gltTicketOrderService;
@Mock
private com.gxwebsoft.shop.service.ShopOrderGoodsService shopOrderGoodsService;
@InjectMocks
private GltTicketRevokeService gltTicketRevokeService;
@Test
void revokeByShopOrder_noTenant_noop() {
int revoked = gltTicketRevokeService.revokeByShopOrder(null, 1, "O1", "r");
assertEquals(0, revoked);
verifyNoInteractions(gltUserTicketService, gltUserTicketReleaseService, gltTicketOrderService, shopOrderGoodsService);
}
@Test
void revokeByShopOrder_noTickets_noop() {
when(gltUserTicketService.list(any())).thenReturn(List.of());
when(shopOrderGoodsService.list(any())).thenReturn(List.of());
int revoked = gltTicketRevokeService.revokeByShopOrder(10584, 1, "O1", "r");
assertEquals(0, revoked);
verify(gltUserTicketService, times(1)).list(any());
verify(shopOrderGoodsService, times(1)).list(any());
verifyNoMoreInteractions(gltUserTicketService, shopOrderGoodsService);
verifyNoInteractions(gltUserTicketReleaseService, gltTicketOrderService);
}
@Test
void revokeByShopOrder_hasTickets_revokesAll() {
GltUserTicket t = new GltUserTicket();
t.setId(123);
t.setTenantId(10584);
when(gltUserTicketService.list(any())).thenReturn(List.of(t));
when(gltUserTicketService.update(isNull(), any())).thenReturn(true);
when(gltTicketOrderService.update(isNull(), any())).thenReturn(true);
when(gltUserTicketReleaseService.update(isNull(), any())).thenReturn(true);
int revoked = gltTicketRevokeService.revokeByShopOrder(10584, 1, "O1", "退款撤销");
assertEquals(1, revoked);
verify(gltTicketOrderService, times(1)).update(isNull(), any());
verify(gltUserTicketReleaseService, times(1)).update(isNull(), any());
verify(gltUserTicketService, times(1)).update(isNull(), any());
verifyNoInteractions(shopOrderGoodsService);
}
}

View File

@@ -1,209 +0,0 @@
package com.gxwebsoft.glt.service;
import com.gxwebsoft.glt.AutoReleaseTestApplication;
import com.gxwebsoft.glt.entity.GltUserTicket;
import com.gxwebsoft.glt.entity.GltUserTicketLog;
import com.gxwebsoft.glt.entity.GltUserTicketRelease;
import com.gxwebsoft.glt.mapper.GltUserTicketLogMapper;
import com.gxwebsoft.glt.mapper.GltUserTicketMapper;
import com.gxwebsoft.glt.mapper.GltUserTicketReleaseMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import java.time.LocalDateTime;
import java.util.List;
import static org.junit.jupiter.api.Assertions.*;
@SpringBootTest(
classes = AutoReleaseTestApplication.class,
properties = {
"spring.datasource.url=jdbc:h2:mem:auto_release;MODE=MySQL;DB_CLOSE_DELAY=-1;DATABASE_TO_LOWER=TRUE",
"spring.datasource.driver-class-name=org.h2.Driver",
"spring.datasource.username=sa",
"spring.datasource.password=",
"spring.sql.init.mode=always",
"spring.sql.init.schema-locations=classpath:schema-auto-release-h2.sql",
"mybatis-plus.configuration.map-underscore-to-camel-case=true",
"mybatis-plus.global-config.db-config.logic-delete-value=1",
"mybatis-plus.global-config.db-config.logic-not-delete-value=0"
}
)
class GltUserTicketAutoReleaseServiceTest {
@Autowired
private JdbcTemplate jdbcTemplate;
@Autowired
private GltUserTicketMapper userTicketMapper;
@Autowired
private GltUserTicketReleaseMapper releaseMapper;
@Autowired
private GltUserTicketLogMapper logMapper;
@Autowired
private GltUserTicketAutoReleaseService autoReleaseService;
@BeforeEach
void clean() {
jdbcTemplate.execute("DELETE FROM glt_user_ticket_log");
jdbcTemplate.execute("DELETE FROM glt_user_ticket_release");
jdbcTemplate.execute("DELETE FROM glt_user_ticket");
}
@Test
void releaseDue_success_updatesTicketReleaseAndWritesLog() {
LocalDateTime now = LocalDateTime.of(2026, 2, 6, 12, 0, 0);
GltUserTicket ticket = new GltUserTicket();
ticket.setTemplateId(1);
ticket.setGoodsId(1);
ticket.setOrderId(1);
ticket.setOrderNo("T-001");
ticket.setOrderGoodsId(1);
ticket.setTotalQty(10);
ticket.setAvailableQty(0);
ticket.setFrozenQty(10);
ticket.setUsedQty(0);
ticket.setReleasedQty(0);
ticket.setUserId(100);
ticket.setSortNumber(0);
ticket.setComments("test");
ticket.setStatus(0);
ticket.setDeleted(0);
ticket.setTenantId(10584);
ticket.setCreateTime(now);
ticket.setUpdateTime(now);
assertEquals(1, userTicketMapper.insert(ticket));
assertNotNull(ticket.getId());
GltUserTicketRelease rel = new GltUserTicketRelease();
rel.setUserTicketId(ticket.getId().longValue());
rel.setUserId(100);
rel.setPeriodNo(1);
rel.setReleaseQty(3);
rel.setReleaseTime(now.minusSeconds(1));
rel.setStatus(0);
rel.setDeleted(0);
rel.setTenantId(10584);
rel.setCreateTime(now);
rel.setUpdateTime(now);
assertEquals(1, releaseMapper.insert(rel));
assertNotNull(rel.getId());
int releasedCount = autoReleaseService.releaseDue(now, 100);
assertEquals(1, releasedCount);
GltUserTicket after = userTicketMapper.selectById(ticket.getId());
assertNotNull(after);
assertEquals(3, after.getAvailableQty());
assertEquals(7, after.getFrozenQty());
assertEquals(3, after.getReleasedQty());
GltUserTicketRelease relAfter = releaseMapper.selectById(rel.getId());
assertNotNull(relAfter);
assertEquals(1, relAfter.getStatus());
List<GltUserTicketLog> logs = logMapper.selectList(null);
assertEquals(1, logs.size());
assertEquals(ticket.getId(), logs.get(0).getUserTicketId());
assertEquals(3, logs.get(0).getChangeAvailable());
assertEquals(-3, logs.get(0).getChangeFrozen());
}
@Test
void releaseDue_notDue_noop() {
LocalDateTime now = LocalDateTime.of(2026, 2, 6, 12, 0, 0);
GltUserTicket ticket = new GltUserTicket();
ticket.setTotalQty(10);
ticket.setAvailableQty(0);
ticket.setFrozenQty(10);
ticket.setUsedQty(0);
ticket.setReleasedQty(0);
ticket.setUserId(100);
ticket.setStatus(0);
ticket.setDeleted(0);
ticket.setTenantId(10584);
ticket.setCreateTime(now);
ticket.setUpdateTime(now);
userTicketMapper.insert(ticket);
GltUserTicketRelease rel = new GltUserTicketRelease();
rel.setUserTicketId(ticket.getId().longValue());
rel.setUserId(100);
rel.setPeriodNo(1);
rel.setReleaseQty(3);
rel.setReleaseTime(now.plusDays(1));
rel.setStatus(0);
rel.setDeleted(0);
rel.setTenantId(10584);
rel.setCreateTime(now);
rel.setUpdateTime(now);
releaseMapper.insert(rel);
int releasedCount = autoReleaseService.releaseDue(now, 100);
assertEquals(0, releasedCount);
GltUserTicket after = userTicketMapper.selectById(ticket.getId());
assertNotNull(after);
assertEquals(0, after.getAvailableQty());
assertEquals(10, after.getFrozenQty());
GltUserTicketRelease relAfter = releaseMapper.selectById(rel.getId());
assertNotNull(relAfter);
assertEquals(0, relAfter.getStatus());
assertEquals(0, logMapper.selectCount(null));
}
@Test
void releaseDue_frozenInsufficient_marksFailed() {
LocalDateTime now = LocalDateTime.of(2026, 2, 6, 12, 0, 0);
GltUserTicket ticket = new GltUserTicket();
ticket.setTotalQty(2);
ticket.setAvailableQty(0);
ticket.setFrozenQty(2);
ticket.setUsedQty(0);
ticket.setReleasedQty(0);
ticket.setUserId(100);
ticket.setStatus(0);
ticket.setDeleted(0);
ticket.setTenantId(10584);
ticket.setCreateTime(now);
ticket.setUpdateTime(now);
userTicketMapper.insert(ticket);
GltUserTicketRelease rel = new GltUserTicketRelease();
rel.setUserTicketId(ticket.getId().longValue());
rel.setUserId(100);
rel.setPeriodNo(1);
rel.setReleaseQty(3);
rel.setReleaseTime(now.minusSeconds(1));
rel.setStatus(0);
rel.setDeleted(0);
rel.setTenantId(10584);
rel.setCreateTime(now);
rel.setUpdateTime(now);
releaseMapper.insert(rel);
int releasedCount = autoReleaseService.releaseDue(now, 100);
assertEquals(0, releasedCount);
GltUserTicket after = userTicketMapper.selectById(ticket.getId());
assertNotNull(after);
assertEquals(0, after.getAvailableQty());
assertEquals(2, after.getFrozenQty());
GltUserTicketRelease relAfter = releaseMapper.selectById(rel.getId());
assertNotNull(relAfter);
assertEquals(2, relAfter.getStatus());
assertEquals(0, logMapper.selectCount(null));
}
}

View File

@@ -1,136 +0,0 @@
package com.gxwebsoft.house;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.gxwebsoft.house.entity.HouseInfo;
import com.gxwebsoft.house.service.HouseInfoService;
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;
/**
* 房产海报生成测试
*/
@SpringBootTest
@ActiveProfiles("dev")
public class HousePosterTest {
@Resource
private HouseInfoService houseInfoService;
@Test
public void testGeneratePoster() throws Exception {
// 创建测试房源信息
HouseInfo houseInfo = new HouseInfo();
houseInfo.setHouseId(1);
houseInfo.setHouseTitle("精装修三室两厅,拎包入住");
houseInfo.setHouseType("3室2厅1卫");
houseInfo.setExtent("120㎡");
houseInfo.setFloor("15/30层");
houseInfo.setRent(new BigDecimal("3500"));
houseInfo.setMonthlyRent(new BigDecimal("3500"));
houseInfo.setAddress("深圳市南山区科技园南区");
houseInfo.setPhone("13800138000");
houseInfo.setHouseLabel("近地铁,精装修,家电齐全");
houseInfo.setTenantId(1);
// 创建测试图片文件数据(使用您提供的格式)
JSONArray filesArray = new JSONArray();
JSONObject file1 = new JSONObject();
file1.put("size", 53148);
file1.put("type", "image");
file1.put("url", "https://oss.wsdns.cn/20250507/3a2f69042a6e41f2882030d7059a4247.jpg?x-oss-process=image/resize,w_1680/quality,Q_90");
file1.put("status", "success");
file1.put("message", "");
filesArray.add(file1);
JSONObject file2 = new JSONObject();
file2.put("size", 35301);
file2.put("type", "image");
file2.put("url", "https://oss.wsdns.cn/20250507/b375176af0b1403da6c4ff66ea4bc503.jpg?x-oss-process=image/resize,w_1680/quality,Q_90");
file2.put("status", "success");
file2.put("message", "");
filesArray.add(file2);
houseInfo.setFiles(filesArray.toJSONString());
// 生成海报
String posterUrl = houseInfoService.generatePoster(houseInfo);
System.out.println("生成的海报URL: " + posterUrl);
// 验证结果
assert posterUrl != null : "海报生成失败返回null";
assert posterUrl.contains("/poster/") : "海报URL格式不正确";
assert posterUrl.contains(".jpg") : "海报文件格式不正确";
System.out.println("房产海报生成测试通过!");
System.out.println("海报包含小程序码扫码可查看房源详情页sub_pages/house/detail/" + houseInfo.getHouseId());
}
@Test
public void testGeneratePosterWithMinimalData() throws Exception {
// 测试最小数据集
HouseInfo houseInfo = new HouseInfo();
houseInfo.setHouseId(2);
houseInfo.setHouseTitle("简单房源");
houseInfo.setTenantId(1);
// 只有一张图片
JSONArray filesArray = new JSONArray();
JSONObject file = new JSONObject();
file.put("size", 53148);
file.put("type", "image");
file.put("url", "https://oss.wsdns.cn/20250507/3a2f69042a6e41f2882030d7059a4247.jpg?x-oss-process=image/resize,w_1680/quality,Q_90");
file.put("status", "success");
file.put("message", "");
filesArray.add(file);
houseInfo.setFiles(filesArray.toJSONString());
// 生成海报
String posterUrl = houseInfoService.generatePoster(houseInfo);
System.out.println("最小数据海报URL: " + posterUrl);
// 验证结果
assert posterUrl != null : "最小数据海报生成失败";
System.out.println("最小数据房产海报生成测试通过!");
}
@Test
public void testGeneratePosterWithEmptyFiles() throws Exception {
// 测试空文件数据
HouseInfo houseInfo = new HouseInfo();
houseInfo.setHouseId(3);
houseInfo.setHouseTitle("无图片房源");
houseInfo.setTenantId(1);
houseInfo.setFiles("[]"); // 空数组
// 生成海报
String posterUrl = houseInfoService.generatePoster(houseInfo);
System.out.println("空文件海报URL: " + posterUrl);
// 验证结果 - 应该返回null
assert posterUrl == null : "空文件应该返回null";
System.out.println("空文件房产海报测试通过!");
}
@Test
public void testGeneratePosterWithNullHouseInfo() throws Exception {
// 测试null房源信息
String posterUrl = houseInfoService.generatePoster(null);
// 验证结果 - 应该返回null
assert posterUrl == null : "null房源信息应该返回null";
System.out.println("null房源信息测试通过");
}
}

View File

@@ -1,38 +0,0 @@
package com.gxwebsoft.house.util;
/**
* SortSceneUtil手动测试类
* 用于验证URL解码功能
*
* @author 科技小王子
* @since 2025-08-04
*/
public class SortSceneUtilManualTest {
public static void main(String[] args) {
// 测试URL编码的参数
String urlEncoded = "%E4%BB%B7%E6%A0%BC(%E4%BD%8E-%E9%AB%98)";
System.out.println("原始URL编码参数: " + urlEncoded);
String result = SortSceneUtil.normalizeSortScene(urlEncoded);
System.out.println("标准化后的参数: " + result);
System.out.println("是否为价格升序: " + SortSceneUtil.isPriceAsc(urlEncoded));
// 测试其他格式
String[] testCases = {
"价格(低-高)",
"价格(高-低)",
"%E4%BB%B7%E6%A0%BC(%E9%AB%98-%E4%BD%8E)",
"最新发布",
"综合排序",
"面积(小-大)",
"面积(大-小)"
};
System.out.println("\n=== 测试各种排序场景 ===");
for (String testCase : testCases) {
String normalized = SortSceneUtil.normalizeSortScene(testCase);
System.out.println("输入: " + testCase + " -> 输出: " + normalized);
}
}
}

View File

@@ -1,63 +0,0 @@
package com.gxwebsoft.house.util;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/**
* SortSceneUtil测试类
*
* @author 科技小王子
* @since 2025-08-04
*/
public class SortSceneUtilTest {
@Test
public void testNormalizeSortScene() {
// 测试URL编码的参数
String urlEncoded = "%E4%BB%B7%E6%A0%BC(%E4%BD%8E-%E9%AB%98)";
String result = SortSceneUtil.normalizeSortScene(urlEncoded);
assertEquals("价格(低-高)", result);
// 测试已解码的参数
String decoded = "价格(低-高)";
result = SortSceneUtil.normalizeSortScene(decoded);
assertEquals("价格(低-高)", result);
// 测试空值
result = SortSceneUtil.normalizeSortScene(null);
assertNull(result);
result = SortSceneUtil.normalizeSortScene("");
assertNull(result);
result = SortSceneUtil.normalizeSortScene(" ");
assertNull(result);
}
@Test
public void testIsPriceAsc() {
assertTrue(SortSceneUtil.isPriceAsc("价格(低-高)"));
assertTrue(SortSceneUtil.isPriceAsc("%E4%BB%B7%E6%A0%BC(%E4%BD%8E-%E9%AB%98)"));
assertFalse(SortSceneUtil.isPriceAsc("价格(高-低)"));
assertFalse(SortSceneUtil.isPriceAsc("最新发布"));
}
@Test
public void testIsPriceDesc() {
assertTrue(SortSceneUtil.isPriceDesc("价格(高-低)"));
assertFalse(SortSceneUtil.isPriceDesc("价格(低-高)"));
assertFalse(SortSceneUtil.isPriceDesc("最新发布"));
}
@Test
public void testIsLatest() {
assertTrue(SortSceneUtil.isLatest("最新发布"));
assertFalse(SortSceneUtil.isLatest("价格(低-高)"));
}
@Test
public void testIsComprehensive() {
assertTrue(SortSceneUtil.isComprehensive("综合排序"));
assertFalse(SortSceneUtil.isComprehensive("价格(低-高)"));
}
}

View File

@@ -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);
}
}

View File

@@ -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("=== 配置属性测试完成 ===");
}
}

View File

@@ -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("=== 目录结构验证完成 ===");
}
}

View File

@@ -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();
}
}
}

View File

@@ -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("=== 环境切换测试完成 ===");
}
}

View File

@@ -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=== 所有租户证书测试完成 ===");
}
}

View File

@@ -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();
}
}
}

View File

@@ -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 密钥未配置");
}
}
}

View File

@@ -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());
}
}
}

View File

@@ -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;");
}
}