11
This commit is contained in:
30
src/test/java/com/gxwebsoft/RedisTest.java
Normal file
30
src/test/java/com/gxwebsoft/RedisTest.java
Normal file
@@ -0,0 +1,30 @@
|
||||
package com.gxwebsoft;
|
||||
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
@SpringBootTest
|
||||
public class RedisTest {
|
||||
@Resource
|
||||
private StringRedisTemplate stringRedisTemplate;
|
||||
//
|
||||
// @Test
|
||||
// public void test(){
|
||||
//// stringRedisTemplate.opsForValue().set("test:add:2",Long.toString(1L));
|
||||
//// stringRedisTemplate.opsForValue().increment("test:add:2",10L);
|
||||
//// stringRedisTemplate.opsForValue().decrement("test:add:2",2L);
|
||||
//// stringRedisTemplate.opsForValue().append("test:add:2","ssss");
|
||||
// HashMap<String, String> map = new HashMap<>();
|
||||
// map.put("name","李四");
|
||||
// map.put("phone","13800138001");
|
||||
// HashMap<String, String> map2 = new HashMap<>();
|
||||
// map2.put("name","赵六");
|
||||
// map2.put("phone","13800138001");
|
||||
// HashMap<String, String> map3 = new HashMap<>();
|
||||
// map3.put("name","张三");
|
||||
// map3.put("phone","13800138001");
|
||||
// stringRedisTemplate.opsForSet().add("test:set:2", JSONUtil.toJSONString(map),JSONUtil.toJSONString(map2),JSONUtil.toJSONString(map3));
|
||||
// }
|
||||
}
|
||||
95
src/test/java/com/gxwebsoft/TestMain.java
Normal file
95
src/test/java/com/gxwebsoft/TestMain.java
Normal file
@@ -0,0 +1,95 @@
|
||||
package com.gxwebsoft;
|
||||
|
||||
import cn.hutool.core.util.NumberUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import com.gxwebsoft.hjm.controller.PushCallback;
|
||||
import com.gxwebsoft.hjm.entity.HjmCar;
|
||||
import com.gxwebsoft.hjm.service.HjmCarService;
|
||||
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;
|
||||
|
||||
/**
|
||||
* 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;
|
||||
|
||||
/**
|
||||
* 生成唯一的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);
|
||||
// }
|
||||
}
|
||||
13
src/test/java/com/gxwebsoft/WebSoftApplicationTests.java
Normal file
13
src/test/java/com/gxwebsoft/WebSoftApplicationTests.java
Normal file
@@ -0,0 +1,13 @@
|
||||
package com.gxwebsoft;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
@SpringBootTest
|
||||
public class WebSoftApplicationTests {
|
||||
|
||||
@Test
|
||||
public void contextLoads() {
|
||||
}
|
||||
|
||||
}
|
||||
110
src/test/java/com/gxwebsoft/WxDev.java
Normal file
110
src/test/java/com/gxwebsoft/WxDev.java
Normal file
@@ -0,0 +1,110 @@
|
||||
package com.gxwebsoft;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import okhttp3.*;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.Instant;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
@Service
|
||||
public class WxDev {
|
||||
|
||||
@Value("${wechat.appid}")
|
||||
private String appId;
|
||||
@Value("${wechat.secret}")
|
||||
private String secret;
|
||||
|
||||
private final StringRedisTemplate redisTemplate;
|
||||
|
||||
private final OkHttpClient http = new OkHttpClient();
|
||||
private final ObjectMapper om = new ObjectMapper();
|
||||
|
||||
/** 简单本地缓存 access_token(生产建议放 Redis) */
|
||||
private final AtomicReference<String> cachedToken = new AtomicReference<>();
|
||||
private volatile long tokenExpireEpoch = 0L; // 过期的 epoch 秒
|
||||
|
||||
public WxDev(StringRedisTemplate redisTemplate) {
|
||||
this.redisTemplate = redisTemplate;
|
||||
}
|
||||
|
||||
/** 获取/刷新 access_token */
|
||||
public String getAccessToken() throws IOException {
|
||||
long now = Instant.now().getEpochSecond();
|
||||
System.out.println("cachedToken.get = " + cachedToken.get());
|
||||
if (cachedToken.get() != null && now < tokenExpireEpoch - 60) {
|
||||
return cachedToken.get();
|
||||
}
|
||||
HttpUrl url = HttpUrl.parse("https://api.weixin.qq.com/cgi-bin/token")
|
||||
.newBuilder()
|
||||
.addQueryParameter("grant_type", "client_credential")
|
||||
.addQueryParameter("appid", "wx51962d6ac21f2ed2")
|
||||
.addQueryParameter("secret", "d821f98de8a6c1ba7bc7e0ee84bcbc8e")
|
||||
.build();
|
||||
Request req = new Request.Builder().url(url).get().build();
|
||||
try (Response resp = http.newCall(req).execute()) {
|
||||
String body = resp.body().string();
|
||||
JsonNode json = om.readTree(body);
|
||||
if (json.has("access_token")) {
|
||||
String token = json.get("access_token").asText();
|
||||
int expiresIn = json.get("expires_in").asInt(7200);
|
||||
System.out.println("token1 = " + token);
|
||||
cachedToken.set(token);
|
||||
tokenExpireEpoch = now + expiresIn;
|
||||
return token;
|
||||
} else {
|
||||
throw new IOException("Get access_token failed: " + body);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 调用 getwxacodeunlimit,返回图片二进制 */
|
||||
public byte[] getUnlimitedCode(String scene, String page, Integer width,
|
||||
Boolean isHyaline, String envVersion) throws IOException {
|
||||
String accessToken = getAccessToken();
|
||||
System.out.println("accessToken = " + accessToken);
|
||||
HttpUrl url = HttpUrl.parse("https://api.weixin.qq.com/wxa/getwxacodeunlimit")
|
||||
.newBuilder()
|
||||
.addQueryParameter("access_token", accessToken)
|
||||
.build();
|
||||
|
||||
// 构造请求 JSON
|
||||
// 注意:scene 仅支持可见字符,长度上限 32,尽量 URL-safe(字母数字下划线等)
|
||||
// page 必须是已发布小程序内的路径(不带开头斜杠也可)
|
||||
var root = om.createObjectNode();
|
||||
root.put("scene", scene);
|
||||
if (page != null) root.put("page", page);
|
||||
if (width != null) root.put("width", width); // 默认 430,建议 280~1280
|
||||
if (isHyaline != null) root.put("is_hyaline", isHyaline);
|
||||
if (envVersion != null) root.put("env_version", envVersion); // release/trial/develop
|
||||
|
||||
RequestBody reqBody = RequestBody.create(
|
||||
root.toString(), MediaType.parse("application/json; charset=utf-8"));
|
||||
Request req = new Request.Builder().url(url).post(reqBody).build();
|
||||
|
||||
try (Response resp = http.newCall(req).execute()) {
|
||||
if (!resp.isSuccessful()) {
|
||||
throw new IOException("HTTP " + resp.code() + " calling getwxacodeunlimit");
|
||||
}
|
||||
MediaType ct = resp.body().contentType();
|
||||
byte[] bytes = resp.body().bytes();
|
||||
// 微信出错时返回 JSON,需要识别一下
|
||||
if (ct != null && ct.subtype() != null && ct.subtype().contains("json")) {
|
||||
String err = new String(bytes);
|
||||
throw new IOException("WeChat error: " + err);
|
||||
}
|
||||
return bytes; // 成功就是图片二进制(PNG)
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void getQrCode() throws IOException {
|
||||
final byte[] test = getUnlimitedCode("register", "pages/index/index",180,false,"develop");
|
||||
System.out.println("test = " + test);
|
||||
}
|
||||
}
|
||||
56
src/test/java/com/gxwebsoft/bszx/BszxOrderTotalTest.java
Normal file
56
src/test/java/com/gxwebsoft/bszx/BszxOrderTotalTest.java
Normal file
@@ -0,0 +1,56 @@
|
||||
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秒以内");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package com.gxwebsoft.common.core.controller;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.gxwebsoft.common.core.dto.qr.CreateEncryptedQrCodeRequest;
|
||||
import com.gxwebsoft.common.core.utils.EncryptedQrCodeUtil;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.http.MediaType;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.mockito.ArgumentMatchers.*;
|
||||
import static org.mockito.Mockito.when;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
|
||||
|
||||
/**
|
||||
* QR码控制器测试
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2025-08-18
|
||||
*/
|
||||
@WebMvcTest(QrCodeController.class)
|
||||
public class QrCodeControllerTest {
|
||||
|
||||
@Autowired
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@MockBean
|
||||
private EncryptedQrCodeUtil encryptedQrCodeUtil;
|
||||
|
||||
@Autowired
|
||||
private ObjectMapper objectMapper;
|
||||
|
||||
@Test
|
||||
public void testCreateEncryptedQrCodeWithValidRequest() throws Exception {
|
||||
// 准备测试数据
|
||||
CreateEncryptedQrCodeRequest request = new CreateEncryptedQrCodeRequest();
|
||||
request.setData("test data");
|
||||
request.setWidth(200);
|
||||
request.setHeight(200);
|
||||
request.setExpireMinutes(30L);
|
||||
request.setBusinessType("TEST");
|
||||
|
||||
Map<String, Object> mockResult = new HashMap<>();
|
||||
mockResult.put("qrCodeBase64", "base64_encoded_image");
|
||||
mockResult.put("token", "test_token");
|
||||
|
||||
when(encryptedQrCodeUtil.generateEncryptedQrCode(anyString(), anyInt(), anyInt(), anyLong(), anyString()))
|
||||
.thenReturn(mockResult);
|
||||
|
||||
// 执行测试
|
||||
mockMvc.perform(post("/api/qr-code/create-encrypted-qr-code")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(request)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.code").value(200))
|
||||
.andExpect(jsonPath("$.message").value("生成加密二维码成功"))
|
||||
.andExpect(jsonPath("$.data.qrCodeBase64").value("base64_encoded_image"))
|
||||
.andExpect(jsonPath("$.data.token").value("test_token"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateEncryptedQrCodeWithInvalidRequest() throws Exception {
|
||||
// 准备无效的测试数据(data为空)
|
||||
CreateEncryptedQrCodeRequest request = new CreateEncryptedQrCodeRequest();
|
||||
request.setData(""); // 空字符串,应该触发验证失败
|
||||
request.setWidth(200);
|
||||
request.setHeight(200);
|
||||
request.setExpireMinutes(30L);
|
||||
|
||||
// 执行测试
|
||||
mockMvc.perform(post("/api/qr-code/create-encrypted-qr-code")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(request)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.code").value(500))
|
||||
.andExpect(jsonPath("$.message").value("数据不能为空"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateEncryptedQrCodeWithInvalidSize() throws Exception {
|
||||
// 准备无效的测试数据(尺寸超出范围)
|
||||
CreateEncryptedQrCodeRequest request = new CreateEncryptedQrCodeRequest();
|
||||
request.setData("test data");
|
||||
request.setWidth(2000); // 超出最大值1000
|
||||
request.setHeight(200);
|
||||
request.setExpireMinutes(30L);
|
||||
|
||||
// 执行测试
|
||||
mockMvc.perform(post("/api/qr-code/create-encrypted-qr-code")
|
||||
.contentType(MediaType.APPLICATION_JSON)
|
||||
.content(objectMapper.writeValueAsString(request)))
|
||||
.andExpect(status().isOk())
|
||||
.andExpect(jsonPath("$.code").value(500))
|
||||
.andExpect(jsonPath("$.message").value("宽度不能大于1000像素"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package com.gxwebsoft.common.core.utils;
|
||||
|
||||
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.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* 加密二维码工具类测试
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2025-08-18
|
||||
*/
|
||||
@SpringBootTest
|
||||
@ActiveProfiles("dev")
|
||||
public class EncryptedQrCodeUtilTest {
|
||||
|
||||
@Resource
|
||||
private EncryptedQrCodeUtil encryptedQrCodeUtil;
|
||||
|
||||
@Test
|
||||
public void testGenerateAndDecryptData() {
|
||||
// 测试数据
|
||||
String originalData = "https://www.example.com/user/123";
|
||||
Long expireMinutes = 30L;
|
||||
|
||||
// 生成加密数据
|
||||
Map<String, String> encryptedInfo = encryptedQrCodeUtil.generateEncryptedData(originalData, expireMinutes);
|
||||
|
||||
assertNotNull(encryptedInfo);
|
||||
assertNotNull(encryptedInfo.get("token"));
|
||||
assertNotNull(encryptedInfo.get("encryptedData"));
|
||||
assertEquals(expireMinutes.toString(), encryptedInfo.get("expireMinutes"));
|
||||
|
||||
// 解密数据
|
||||
String decryptedData = encryptedQrCodeUtil.decryptData(
|
||||
encryptedInfo.get("token"),
|
||||
encryptedInfo.get("encryptedData")
|
||||
);
|
||||
|
||||
assertEquals(originalData, decryptedData);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGenerateEncryptedQrCode() {
|
||||
// 测试数据
|
||||
String originalData = "测试二维码数据";
|
||||
int width = 300;
|
||||
int height = 300;
|
||||
Long expireMinutes = 60L;
|
||||
|
||||
// 生成加密二维码
|
||||
Map<String, Object> result = encryptedQrCodeUtil.generateEncryptedQrCode(
|
||||
originalData, width, height, expireMinutes
|
||||
);
|
||||
|
||||
assertNotNull(result);
|
||||
assertNotNull(result.get("qrCodeBase64"));
|
||||
assertNotNull(result.get("token"));
|
||||
assertEquals(originalData, result.get("originalData"));
|
||||
assertEquals(expireMinutes.toString(), result.get("expireMinutes"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testTokenValidation() {
|
||||
// 生成测试数据
|
||||
String originalData = "token验证测试";
|
||||
Map<String, String> encryptedInfo = encryptedQrCodeUtil.generateEncryptedData(originalData, 30L);
|
||||
String token = encryptedInfo.get("token");
|
||||
|
||||
// 验证token有效性
|
||||
assertTrue(encryptedQrCodeUtil.isTokenValid(token));
|
||||
|
||||
// 使token失效
|
||||
encryptedQrCodeUtil.invalidateToken(token);
|
||||
|
||||
// 再次验证token应该无效
|
||||
assertFalse(encryptedQrCodeUtil.isTokenValid(token));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testInvalidToken() {
|
||||
// 测试无效token
|
||||
assertFalse(encryptedQrCodeUtil.isTokenValid("invalid_token"));
|
||||
assertFalse(encryptedQrCodeUtil.isTokenValid(""));
|
||||
assertFalse(encryptedQrCodeUtil.isTokenValid(null));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDecryptWithInvalidToken() {
|
||||
// 测试用无效token解密
|
||||
assertThrows(RuntimeException.class, () -> {
|
||||
encryptedQrCodeUtil.decryptData("invalid_token", "encrypted_data");
|
||||
});
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGenerateEncryptedQrCodeWithBusinessType() {
|
||||
// 测试数据
|
||||
String originalData = "用户登录数据";
|
||||
int width = 200;
|
||||
int height = 200;
|
||||
Long expireMinutes = 30L;
|
||||
String businessType = "LOGIN";
|
||||
|
||||
// 生成带业务类型的加密二维码
|
||||
Map<String, Object> result = encryptedQrCodeUtil.generateEncryptedQrCode(
|
||||
originalData, width, height, expireMinutes, businessType
|
||||
);
|
||||
|
||||
assertNotNull(result);
|
||||
assertNotNull(result.get("qrCodeBase64"));
|
||||
assertNotNull(result.get("token"));
|
||||
assertEquals(originalData, result.get("originalData"));
|
||||
assertEquals(expireMinutes.toString(), result.get("expireMinutes"));
|
||||
assertEquals(businessType, result.get("businessType"));
|
||||
|
||||
System.out.println("=== 带BusinessType的二维码生成测试 ===");
|
||||
System.out.println("原始数据: " + originalData);
|
||||
System.out.println("业务类型: " + businessType);
|
||||
System.out.println("Token: " + result.get("token"));
|
||||
System.out.println("二维码Base64长度: " + ((String)result.get("qrCodeBase64")).length());
|
||||
|
||||
// 验证不传businessType的情况
|
||||
Map<String, Object> resultWithoutType = encryptedQrCodeUtil.generateEncryptedQrCode(
|
||||
originalData, width, height, expireMinutes
|
||||
);
|
||||
|
||||
assertNull(resultWithoutType.get("businessType"));
|
||||
System.out.println("不传BusinessType时的结果: " + resultWithoutType.get("businessType"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
package com.gxwebsoft.common.system.controller;
|
||||
|
||||
import com.gxwebsoft.common.system.entity.User;
|
||||
import com.gxwebsoft.common.system.service.UserService;
|
||||
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 WxLoginControllerTest {
|
||||
|
||||
@Resource
|
||||
private UserService userService;
|
||||
|
||||
/**
|
||||
* 测试从scene参数解析租户ID的逻辑
|
||||
*/
|
||||
@Test
|
||||
public void testExtractTenantIdFromScene() {
|
||||
log.info("=== 开始测试scene参数解析 ===");
|
||||
|
||||
// 测试用户ID 33103
|
||||
Integer testUserId = 33103;
|
||||
|
||||
// 查询用户信息
|
||||
User user = userService.getByIdIgnoreTenant(testUserId);
|
||||
if (user != null) {
|
||||
log.info("用户ID {} 对应的租户ID: {}", testUserId, user.getTenantId());
|
||||
log.info("用户信息 - 用户名: {}, 手机: {}", user.getUsername(), user.getPhone());
|
||||
} else {
|
||||
log.warn("未找到用户ID: {}", testUserId);
|
||||
}
|
||||
|
||||
// 测试不同的scene格式
|
||||
String[] testScenes = {
|
||||
"uid_33103",
|
||||
"uid_1",
|
||||
"uid_999999",
|
||||
"invalid_scene",
|
||||
null
|
||||
};
|
||||
|
||||
for (String scene : testScenes) {
|
||||
log.info("测试scene: {} -> 预期解析结果", scene);
|
||||
// 这里模拟解析逻辑
|
||||
if (scene != null && scene.startsWith("uid_")) {
|
||||
try {
|
||||
String userIdStr = scene.substring(4);
|
||||
Integer userId = Integer.parseInt(userIdStr);
|
||||
User testUser = userService.getByIdIgnoreTenant(userId);
|
||||
if (testUser != null) {
|
||||
log.info(" 解析成功: 用户ID {} -> 租户ID {}", userId, testUser.getTenantId());
|
||||
} else {
|
||||
log.info(" 用户不存在: 用户ID {} -> 默认租户ID 10550", userId);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.info(" 解析异常: {} -> 默认租户ID 10550", e.getMessage());
|
||||
}
|
||||
} else {
|
||||
log.info(" 无效格式 -> 默认租户ID 10550");
|
||||
}
|
||||
}
|
||||
|
||||
log.info("=== scene参数解析测试完成 ===");
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试查找特定用户
|
||||
*/
|
||||
@Test
|
||||
public void testFindSpecificUsers() {
|
||||
log.info("=== 开始查找特定用户 ===");
|
||||
|
||||
// 查找租户10550的用户
|
||||
Integer[] testUserIds = {1, 2, 3, 33103, 10001, 10002};
|
||||
|
||||
for (Integer userId : testUserIds) {
|
||||
User user = userService.getByIdIgnoreTenant(userId);
|
||||
if (user != null) {
|
||||
log.info("用户ID: {}, 租户ID: {}, 用户名: {}, 手机: {}",
|
||||
userId, user.getTenantId(), user.getUsername(), user.getPhone());
|
||||
} else {
|
||||
log.info("用户ID: {} - 不存在", userId);
|
||||
}
|
||||
}
|
||||
|
||||
log.info("=== 特定用户查找完成 ===");
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试URL解析
|
||||
*/
|
||||
@Test
|
||||
public void testUrlParsing() {
|
||||
log.info("=== 开始测试URL解析 ===");
|
||||
|
||||
String testUrl = "127.0.0.1:9200/api/wx-login/getOrderQRCodeUnlimited/uid_33103";
|
||||
log.info("测试URL: {}", testUrl);
|
||||
|
||||
// 提取scene部分
|
||||
String[] parts = testUrl.split("/");
|
||||
String scene = parts[parts.length - 1]; // 最后一部分
|
||||
log.info("提取的scene: {}", scene);
|
||||
|
||||
// 解析用户ID
|
||||
if (scene.startsWith("uid_")) {
|
||||
String userIdStr = scene.substring(4);
|
||||
try {
|
||||
Integer userId = Integer.parseInt(userIdStr);
|
||||
log.info("解析的用户ID: {}", userId);
|
||||
|
||||
User user = userService.getByIdIgnoreTenant(userId);
|
||||
if (user != null) {
|
||||
log.info("对应的租户ID: {}", user.getTenantId());
|
||||
} else {
|
||||
log.warn("用户不存在");
|
||||
}
|
||||
} catch (NumberFormatException e) {
|
||||
log.error("用户ID格式错误: {}", userIdStr);
|
||||
}
|
||||
}
|
||||
|
||||
log.info("=== URL解析测试完成 ===");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
package com.gxwebsoft.common.system.service;
|
||||
|
||||
import com.gxwebsoft.common.system.entity.User;
|
||||
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 UserIgnoreTenantTest {
|
||||
|
||||
@Resource
|
||||
private UserService userService;
|
||||
|
||||
/**
|
||||
* 测试忽略租户隔离查询用户
|
||||
*/
|
||||
@Test
|
||||
public void testGetByIdIgnoreTenant() {
|
||||
// 测试用户ID(请根据实际数据库中的用户ID进行调整)
|
||||
Integer testUserId = 1;
|
||||
|
||||
log.info("=== 开始测试忽略租户隔离查询用户功能 ===");
|
||||
|
||||
// 1. 使用普通方法查询用户(受租户隔离影响)
|
||||
User userNormal = userService.getById(testUserId);
|
||||
log.info("普通查询结果 - 用户ID: {}, 用户信息: {}", testUserId,
|
||||
userNormal != null ? userNormal.getUsername() : "null");
|
||||
|
||||
// 2. 使用忽略租户隔离方法查询用户
|
||||
User userIgnoreTenant = userService.getByIdIgnoreTenant(testUserId);
|
||||
log.info("忽略租户隔离查询结果 - 用户ID: {}, 用户信息: {}", testUserId,
|
||||
userIgnoreTenant != null ? userIgnoreTenant.getUsername() : "null");
|
||||
|
||||
// 3. 验证结果
|
||||
if (userIgnoreTenant != null) {
|
||||
log.info("✅ 忽略租户隔离查询成功!");
|
||||
log.info("用户详情 - ID: {}, 用户名: {}, 昵称: {}, 租户ID: {}",
|
||||
userIgnoreTenant.getUserId(),
|
||||
userIgnoreTenant.getUsername(),
|
||||
userIgnoreTenant.getNickname(),
|
||||
userIgnoreTenant.getTenantId());
|
||||
} else {
|
||||
log.error("❌ 忽略租户隔离查询失败!");
|
||||
}
|
||||
|
||||
log.info("=== 忽略租户隔离查询用户功能测试完成 ===");
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试参数验证
|
||||
*/
|
||||
@Test
|
||||
public void testGetByIdIgnoreTenantValidation() {
|
||||
log.info("=== 开始测试参数验证 ===");
|
||||
|
||||
// 测试null用户ID
|
||||
User result1 = userService.getByIdIgnoreTenant(null);
|
||||
log.info("null用户ID测试结果: {}", result1 == null ? "成功(返回null)" : "失败");
|
||||
|
||||
// 测试不存在的用户ID
|
||||
User result2 = userService.getByIdIgnoreTenant(999999);
|
||||
log.info("不存在用户ID测试结果: {}", result2 == null ? "成功(返回null)" : "失败");
|
||||
|
||||
log.info("=== 参数验证测试完成 ===");
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试跨租户查询
|
||||
*/
|
||||
@Test
|
||||
public void testCrossTenantQuery() {
|
||||
log.info("=== 开始测试跨租户查询 ===");
|
||||
|
||||
// 查询不同租户的用户(请根据实际数据调整)
|
||||
Integer[] testUserIds = {1, 2, 3, 4, 5};
|
||||
|
||||
for (Integer userId : testUserIds) {
|
||||
User user = userService.getByIdIgnoreTenant(userId);
|
||||
if (user != null) {
|
||||
log.info("用户ID: {}, 用户名: {}, 租户ID: {}",
|
||||
user.getUserId(), user.getUsername(), user.getTenantId());
|
||||
} else {
|
||||
log.info("用户ID: {} - 不存在", userId);
|
||||
}
|
||||
}
|
||||
|
||||
log.info("=== 跨租户查询测试完成 ===");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,174 @@
|
||||
package com.gxwebsoft.common.system.service;
|
||||
|
||||
import com.alibaba.fastjson.JSONObject;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.gxwebsoft.cms.entity.CmsWebsiteField;
|
||||
import com.gxwebsoft.cms.service.CmsWebsiteFieldService;
|
||||
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 WeixinConfigTest {
|
||||
|
||||
@Resource
|
||||
private SettingService settingService;
|
||||
|
||||
@Resource
|
||||
private CmsWebsiteFieldService cmsWebsiteFieldService;
|
||||
|
||||
/**
|
||||
* 测试从cms_website_field表获取微信小程序配置
|
||||
*/
|
||||
@Test
|
||||
public void testGetWeixinConfigFromWebsiteField() {
|
||||
Integer tenantId = 10550;
|
||||
|
||||
log.info("=== 开始测试从cms_website_field表获取微信小程序配置 ===");
|
||||
|
||||
// 1. 查看cms_website_field表中的所有配置
|
||||
List<CmsWebsiteField> allFields = cmsWebsiteFieldService.list(
|
||||
new LambdaQueryWrapper<CmsWebsiteField>()
|
||||
.eq(CmsWebsiteField::getTenantId, tenantId)
|
||||
.eq(CmsWebsiteField::getDeleted, 0)
|
||||
);
|
||||
|
||||
log.info("租户{}的所有cms_website_field配置:", tenantId);
|
||||
for (CmsWebsiteField field : allFields) {
|
||||
log.info(" - ID: {}, Name: {}, Value: {}", field.getId(), field.getName(), field.getValue());
|
||||
}
|
||||
|
||||
// 2. 查找AppID配置
|
||||
CmsWebsiteField appIdField = cmsWebsiteFieldService.getOne(
|
||||
new LambdaQueryWrapper<CmsWebsiteField>()
|
||||
.eq(CmsWebsiteField::getName, "AppID")
|
||||
.eq(CmsWebsiteField::getTenantId, tenantId)
|
||||
.eq(CmsWebsiteField::getDeleted, 0)
|
||||
);
|
||||
|
||||
log.info("AppID配置: {}", appIdField);
|
||||
|
||||
// 3. 查找AppSecret配置
|
||||
CmsWebsiteField appSecretField = cmsWebsiteFieldService.getOne(
|
||||
new LambdaQueryWrapper<CmsWebsiteField>()
|
||||
.eq(CmsWebsiteField::getName, "AppSecret")
|
||||
.eq(CmsWebsiteField::getTenantId, tenantId)
|
||||
.eq(CmsWebsiteField::getDeleted, 0)
|
||||
);
|
||||
|
||||
log.info("AppSecret配置: {}", appSecretField);
|
||||
|
||||
// 4. 测试获取微信小程序配置
|
||||
try {
|
||||
JSONObject config = settingService.getBySettingKeyIgnoreTenant("mp-weixin", tenantId);
|
||||
log.info("✅ 成功获取微信小程序配置: {}", config);
|
||||
} catch (Exception e) {
|
||||
log.error("❌ 获取微信小程序配置失败: {}", e.getMessage());
|
||||
}
|
||||
|
||||
log.info("=== 微信小程序配置测试完成 ===");
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试不同name的查询
|
||||
*/
|
||||
@Test
|
||||
public void testDifferentNameQueries() {
|
||||
Integer tenantId = 10550;
|
||||
|
||||
log.info("=== 开始测试不同name的查询 ===");
|
||||
|
||||
String[] nameVariations = {"AppID", "appId", "APPID", "app_id", "AppSecret", "appSecret", "APPSECRET", "app_secret"};
|
||||
|
||||
for (String name : nameVariations) {
|
||||
CmsWebsiteField field = cmsWebsiteFieldService.getOne(
|
||||
new LambdaQueryWrapper<CmsWebsiteField>()
|
||||
.eq(CmsWebsiteField::getName, name)
|
||||
.eq(CmsWebsiteField::getTenantId, tenantId)
|
||||
.eq(CmsWebsiteField::getDeleted, 0)
|
||||
);
|
||||
|
||||
if (field != null) {
|
||||
log.info("找到配置 - Name: {}, Value: {}", name, field.getValue());
|
||||
} else {
|
||||
log.info("未找到配置 - Name: {}", name);
|
||||
}
|
||||
}
|
||||
|
||||
log.info("=== 不同name查询测试完成 ===");
|
||||
}
|
||||
|
||||
/**
|
||||
* 测试创建测试配置
|
||||
*/
|
||||
@Test
|
||||
public void testCreateTestConfig() {
|
||||
Integer tenantId = 10550;
|
||||
|
||||
log.info("=== 开始创建测试配置 ===");
|
||||
|
||||
// 创建AppID配置
|
||||
CmsWebsiteField appIdField = new CmsWebsiteField();
|
||||
appIdField.setName("AppID");
|
||||
appIdField.setValue("wx1234567890abcdef"); // 测试AppID
|
||||
appIdField.setTenantId(tenantId);
|
||||
appIdField.setType(0); // 文本类型
|
||||
appIdField.setComments("微信小程序AppID");
|
||||
appIdField.setDeleted(0);
|
||||
|
||||
// 创建AppSecret配置
|
||||
CmsWebsiteField appSecretField = new CmsWebsiteField();
|
||||
appSecretField.setName("AppSecret");
|
||||
appSecretField.setValue("abcdef1234567890abcdef1234567890"); // 测试AppSecret
|
||||
appSecretField.setTenantId(tenantId);
|
||||
appSecretField.setType(0); // 文本类型
|
||||
appSecretField.setComments("微信小程序AppSecret");
|
||||
appSecretField.setDeleted(0);
|
||||
|
||||
try {
|
||||
// 检查是否已存在
|
||||
CmsWebsiteField existingAppId = cmsWebsiteFieldService.getOne(
|
||||
new LambdaQueryWrapper<CmsWebsiteField>()
|
||||
.eq(CmsWebsiteField::getName, "AppID")
|
||||
.eq(CmsWebsiteField::getTenantId, tenantId)
|
||||
);
|
||||
|
||||
if (existingAppId == null) {
|
||||
cmsWebsiteFieldService.save(appIdField);
|
||||
log.info("✅ 创建AppID配置成功");
|
||||
} else {
|
||||
log.info("AppID配置已存在,跳过创建");
|
||||
}
|
||||
|
||||
CmsWebsiteField existingAppSecret = cmsWebsiteFieldService.getOne(
|
||||
new LambdaQueryWrapper<CmsWebsiteField>()
|
||||
.eq(CmsWebsiteField::getName, "AppSecret")
|
||||
.eq(CmsWebsiteField::getTenantId, tenantId)
|
||||
);
|
||||
|
||||
if (existingAppSecret == null) {
|
||||
cmsWebsiteFieldService.save(appSecretField);
|
||||
log.info("✅ 创建AppSecret配置成功");
|
||||
} else {
|
||||
log.info("AppSecret配置已存在,跳过创建");
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
log.error("❌ 创建测试配置失败: {}", e.getMessage());
|
||||
}
|
||||
|
||||
log.info("=== 创建测试配置完成 ===");
|
||||
}
|
||||
}
|
||||
44
src/test/java/com/gxwebsoft/config/MqttPropertiesTest.java
Normal file
44
src/test/java/com/gxwebsoft/config/MqttPropertiesTest.java
Normal file
@@ -0,0 +1,44 @@
|
||||
package com.gxwebsoft.config;
|
||||
|
||||
import com.gxwebsoft.common.core.config.MqttProperties;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
/**
|
||||
* MQTT配置属性测试类
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2025-07-02
|
||||
*/
|
||||
@SpringBootTest
|
||||
@ActiveProfiles("dev")
|
||||
public class MqttPropertiesTest {
|
||||
|
||||
@Resource
|
||||
private MqttProperties mqttProperties;
|
||||
|
||||
@Test
|
||||
public void testMqttPropertiesLoading() {
|
||||
System.out.println("=== MQTT配置属性测试 ===");
|
||||
System.out.println("Host: " + mqttProperties.getHost());
|
||||
System.out.println("Username: " + mqttProperties.getUsername());
|
||||
System.out.println("Password: " + (mqttProperties.getPassword() != null ? "***" : "null"));
|
||||
System.out.println("ClientIdPrefix: " + mqttProperties.getClientIdPrefix());
|
||||
System.out.println("Topic: " + mqttProperties.getTopic());
|
||||
System.out.println("QoS: " + mqttProperties.getQos());
|
||||
System.out.println("ConnectionTimeout: " + mqttProperties.getConnectionTimeout());
|
||||
System.out.println("KeepAliveInterval: " + mqttProperties.getKeepAliveInterval());
|
||||
System.out.println("AutoReconnect: " + mqttProperties.isAutoReconnect());
|
||||
System.out.println("CleanSession: " + mqttProperties.isCleanSession());
|
||||
|
||||
// 验证关键配置不为空
|
||||
assert mqttProperties.getHost() != null : "Host不能为空";
|
||||
assert mqttProperties.getClientIdPrefix() != null : "ClientIdPrefix不能为空";
|
||||
assert mqttProperties.getTopic() != null : "Topic不能为空";
|
||||
|
||||
System.out.println("MQTT配置属性测试通过!");
|
||||
}
|
||||
}
|
||||
51
src/test/java/com/gxwebsoft/config/ServerUrlConfigTest.java
Normal file
51
src/test/java/com/gxwebsoft/config/ServerUrlConfigTest.java
Normal file
@@ -0,0 +1,51 @@
|
||||
package com.gxwebsoft.config;
|
||||
|
||||
import com.gxwebsoft.common.core.config.ConfigProperties;
|
||||
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 static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* 服务器URL配置测试
|
||||
* 验证server-url配置是否正确从配置文件读取
|
||||
*/
|
||||
@SpringBootTest
|
||||
@ActiveProfiles("dev")
|
||||
public class ServerUrlConfigTest {
|
||||
|
||||
@Autowired
|
||||
private ConfigProperties configProperties;
|
||||
|
||||
@Test
|
||||
public void testServerUrlConfiguration() {
|
||||
// 验证配置属性不为空
|
||||
assertNotNull(configProperties, "ConfigProperties should not be null");
|
||||
|
||||
// 验证server-url配置正确读取
|
||||
String serverUrl = configProperties.getServerUrl();
|
||||
assertNotNull(serverUrl, "Server URL should not be null");
|
||||
assertFalse(serverUrl.isEmpty(), "Server URL should not be empty");
|
||||
|
||||
// 在开发环境下,应该是本地地址
|
||||
assertTrue(serverUrl.contains("127.0.0.1") || serverUrl.contains("localhost"),
|
||||
"In dev environment, server URL should contain localhost or 127.0.0.1");
|
||||
|
||||
System.out.println("当前配置的服务器URL: " + serverUrl);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testServerUrlFormat() {
|
||||
String serverUrl = configProperties.getServerUrl();
|
||||
|
||||
// 验证URL格式
|
||||
assertTrue(serverUrl.startsWith("http://") || serverUrl.startsWith("https://"),
|
||||
"Server URL should start with http:// or https://");
|
||||
assertTrue(serverUrl.endsWith("/api"),
|
||||
"Server URL should end with /api");
|
||||
|
||||
System.out.println("服务器URL格式验证通过: " + serverUrl);
|
||||
}
|
||||
}
|
||||
435
src/test/java/com/gxwebsoft/generator/ShopGenerator.java
Normal file
435
src/test/java/com/gxwebsoft/generator/ShopGenerator.java
Normal file
@@ -0,0 +1,435 @@
|
||||
package com.gxwebsoft.generator;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.core.toolkit.StringPool;
|
||||
import com.baomidou.mybatisplus.generator.AutoGenerator;
|
||||
import com.baomidou.mybatisplus.generator.InjectionConfig;
|
||||
import com.baomidou.mybatisplus.generator.config.*;
|
||||
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
|
||||
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
|
||||
import com.gxwebsoft.generator.engine.BeetlTemplateEnginePlus;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.io.*;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.regex.Pattern;
|
||||
import java.util.regex.Matcher;
|
||||
|
||||
/**
|
||||
* CMS模块-代码生成工具
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2021-09-05 00:31:14
|
||||
*/
|
||||
public class ShopGenerator {
|
||||
// 输出位置
|
||||
private static final String OUTPUT_LOCATION = System.getProperty("user.dir");
|
||||
//private static final String OUTPUT_LOCATION = "D:/codegen"; // 不想生成到项目中可以写磁盘路径
|
||||
// JAVA输出目录
|
||||
private static final String OUTPUT_DIR = "/src/main/java";
|
||||
// Vue文件输出位置
|
||||
private static final String OUTPUT_LOCATION_VUE = "/Users/gxwebsoft/VUE/mp-vue";
|
||||
// UniApp文件输出目录
|
||||
private static final String OUTPUT_LOCATION_UNIAPP = "/Users/gxwebsoft/VUE/template-10550";
|
||||
// Vue文件输出目录
|
||||
private static final String OUTPUT_DIR_VUE = "/src";
|
||||
// 作者名称
|
||||
private static final String AUTHOR = "科技小王子";
|
||||
// 是否在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_DRIVER = "com.mysql.cj.jdbc.Driver";
|
||||
private static final String DB_USERNAME = "modules";
|
||||
private static final String DB_PASSWORD = "8YdLnk7KsPAyDXGA";
|
||||
// 包名
|
||||
private static final String PACKAGE_NAME = "com.gxwebsoft";
|
||||
// 模块名
|
||||
private static final String MODULE_NAME = "shop";
|
||||
// 需要生成的表
|
||||
private static final String[] TABLE_NAMES = new String[]{
|
||||
// "shop_spec",
|
||||
// "shop_spec_value",
|
||||
// "shop_goods",
|
||||
// "shop_category",
|
||||
// "shop_goods_spec",
|
||||
// "shop_goods_sku",
|
||||
// "shop_goods_category",
|
||||
// "shop_coupon",
|
||||
// "shop_goods_description",
|
||||
// "shop_goods_log",
|
||||
// "shop_goods_relation",
|
||||
// "shop_goods_comment",
|
||||
// "shop_goods_rule",
|
||||
// "shop_brand",
|
||||
// "shop_merchant",
|
||||
// "shop_merchant_type",
|
||||
// "shop_merchant_apply",
|
||||
// "shop_merchant_account",
|
||||
// "shop_chat_message",
|
||||
// "shop_chat_conversation",
|
||||
// "shop_user_collection",
|
||||
// "shop_goods_role_commission"
|
||||
// "shop_commission_role"
|
||||
// "shop_order",
|
||||
// "shop_order_info",
|
||||
// "shop_order_info_log",
|
||||
// "shop_order_goods",
|
||||
// "shop_wechat_deposit",
|
||||
// "shop_users",
|
||||
// "shop_user_address",
|
||||
// "shop_user_balance_log",
|
||||
// "shop_recharge_order",
|
||||
// 经销商表
|
||||
// "shop_dealer_apply",
|
||||
// "shop_dealer_capital",
|
||||
// "shop_dealer_order",
|
||||
// "shop_dealer_referee",
|
||||
// "shop_dealer_setting",
|
||||
// "shop_dealer_user",
|
||||
// "shop_user_referee",
|
||||
// "shop_dealer_withdraw",
|
||||
// "shop_user_coupon",
|
||||
// "shop_cart",
|
||||
// "shop_count",
|
||||
// "shop_order_delivery",
|
||||
// "shop_order_delivery_goods",
|
||||
// "shop_order_extract",
|
||||
// "shop_splash",
|
||||
// "shop_goods_income_config"
|
||||
// "shop_express",
|
||||
// "shop_express_template",
|
||||
// "shop_express_template_detail",
|
||||
// "shop_gift"
|
||||
"shop_article"
|
||||
};
|
||||
// 需要去除的表前缀
|
||||
private static final String[] TABLE_PREFIX = new String[]{
|
||||
"tb_"
|
||||
};
|
||||
// 不需要作为查询参数的字段
|
||||
private static final String[] PARAM_EXCLUDE_FIELDS = new String[]{
|
||||
"tenant_id",
|
||||
"create_time",
|
||||
"update_time"
|
||||
};
|
||||
// 查询参数使用String的类型
|
||||
private static final String[] PARAM_TO_STRING_TYPE = new String[]{
|
||||
"Date",
|
||||
"LocalDate",
|
||||
"LocalTime",
|
||||
"LocalDateTime"
|
||||
};
|
||||
// 查询参数使用EQ的类型
|
||||
private static final String[] PARAM_EQ_TYPE = new String[]{
|
||||
"Integer",
|
||||
"Boolean",
|
||||
"BigDecimal"
|
||||
};
|
||||
// 是否添加权限注解
|
||||
private static final boolean AUTH_ANNOTATION = true;
|
||||
// 是否添加日志注解
|
||||
private static final boolean LOG_ANNOTATION = true;
|
||||
// controller的mapping前缀
|
||||
private static final String CONTROLLER_MAPPING_PREFIX = "/api";
|
||||
// 模板所在位置
|
||||
private static final String TEMPLATES_DIR = "/src/test/java/com/gxwebsoft/generator/templates";
|
||||
|
||||
public static void main(String[] args) {
|
||||
// 代码生成器
|
||||
AutoGenerator mpg = new AutoGenerator();
|
||||
|
||||
// 全局配置
|
||||
GlobalConfig gc = new GlobalConfig();
|
||||
gc.setOutputDir(OUTPUT_LOCATION + OUTPUT_DIR);
|
||||
gc.setAuthor(AUTHOR);
|
||||
gc.setOpen(false);
|
||||
gc.setFileOverride(true);
|
||||
gc.setEnableCache(ENABLE_CACHE);
|
||||
gc.setSwagger2(true);
|
||||
gc.setIdType(IdType.AUTO);
|
||||
gc.setServiceName("%sService");
|
||||
mpg.setGlobalConfig(gc);
|
||||
|
||||
// 数据源配置
|
||||
DataSourceConfig dsc = new DataSourceConfig();
|
||||
dsc.setUrl(DB_URL);
|
||||
// dsc.setSchemaName("public");
|
||||
dsc.setDriverName(DB_DRIVER);
|
||||
dsc.setUsername(DB_USERNAME);
|
||||
dsc.setPassword(DB_PASSWORD);
|
||||
mpg.setDataSource(dsc);
|
||||
|
||||
// 包配置
|
||||
PackageConfig pc = new PackageConfig();
|
||||
pc.setModuleName(MODULE_NAME);
|
||||
pc.setParent(PACKAGE_NAME);
|
||||
mpg.setPackageInfo(pc);
|
||||
|
||||
// 策略配置
|
||||
StrategyConfig strategy = new StrategyConfig();
|
||||
strategy.setNaming(NamingStrategy.underline_to_camel);
|
||||
strategy.setColumnNaming(NamingStrategy.underline_to_camel);
|
||||
strategy.setInclude(TABLE_NAMES);
|
||||
strategy.setTablePrefix(TABLE_PREFIX);
|
||||
strategy.setSuperControllerClass(PACKAGE_NAME + ".common.core.web.BaseController");
|
||||
strategy.setEntityLombokModel(true);
|
||||
strategy.setRestControllerStyle(true);
|
||||
strategy.setControllerMappingHyphenStyle(true);
|
||||
strategy.setLogicDeleteFieldName("deleted");
|
||||
mpg.setStrategy(strategy);
|
||||
|
||||
// 模板配置
|
||||
TemplateConfig templateConfig = new TemplateConfig();
|
||||
templateConfig.setController(TEMPLATES_DIR + "/controller.java");
|
||||
templateConfig.setEntity(TEMPLATES_DIR + "/entity.java");
|
||||
templateConfig.setMapper(TEMPLATES_DIR + "/mapper.java");
|
||||
templateConfig.setXml(TEMPLATES_DIR + "/mapper.xml");
|
||||
templateConfig.setService(TEMPLATES_DIR + "/service.java");
|
||||
templateConfig.setServiceImpl(TEMPLATES_DIR + "/serviceImpl.java");
|
||||
mpg.setTemplate(templateConfig);
|
||||
mpg.setTemplateEngine(new BeetlTemplateEnginePlus());
|
||||
|
||||
// 自定义模板配置
|
||||
InjectionConfig cfg = new InjectionConfig() {
|
||||
@Override
|
||||
public void initMap() {
|
||||
Map<String, Object> map = new HashMap<>();
|
||||
map.put("packageName", PACKAGE_NAME);
|
||||
map.put("paramExcludeFields", PARAM_EXCLUDE_FIELDS);
|
||||
map.put("paramToStringType", PARAM_TO_STRING_TYPE);
|
||||
map.put("paramEqType", PARAM_EQ_TYPE);
|
||||
map.put("authAnnotation", AUTH_ANNOTATION);
|
||||
map.put("logAnnotation", LOG_ANNOTATION);
|
||||
map.put("controllerMappingPrefix", CONTROLLER_MAPPING_PREFIX);
|
||||
// 添加项目类型标识,用于模板中的条件判断
|
||||
map.put("isUniApp", false); // Vue 项目
|
||||
map.put("isVueAdmin", true); // 后台管理项目
|
||||
this.setMap(map);
|
||||
}
|
||||
};
|
||||
String templatePath = TEMPLATES_DIR + "/param.java.btl";
|
||||
List<FileOutConfig> focList = new ArrayList<>();
|
||||
focList.add(new FileOutConfig(templatePath) {
|
||||
@Override
|
||||
public String outputFile(TableInfo tableInfo) {
|
||||
return OUTPUT_LOCATION + OUTPUT_DIR + "/"
|
||||
+ PACKAGE_NAME.replace(".", "/")
|
||||
+ "/" + pc.getModuleName() + "/param/"
|
||||
+ tableInfo.getEntityName() + "Param" + StringPool.DOT_JAVA;
|
||||
}
|
||||
});
|
||||
/**
|
||||
* 以下是生成VUE项目代码
|
||||
* 生成文件的路径 /api/shop/goods/index.ts
|
||||
*/
|
||||
templatePath = TEMPLATES_DIR + "/index.ts.btl";
|
||||
|
||||
focList.add(new FileOutConfig(templatePath) {
|
||||
@Override
|
||||
public String outputFile(TableInfo tableInfo) {
|
||||
return OUTPUT_LOCATION_VUE + OUTPUT_DIR_VUE
|
||||
+ "/api/" + pc.getModuleName() + "/"
|
||||
+ tableInfo.getEntityPath() + "/" + "index.ts";
|
||||
}
|
||||
});
|
||||
// UniApp 使用专门的模板
|
||||
String uniappTemplatePath = TEMPLATES_DIR + "/index.ts.uniapp.btl";
|
||||
focList.add(new FileOutConfig(uniappTemplatePath) {
|
||||
@Override
|
||||
public String outputFile(TableInfo tableInfo) {
|
||||
return OUTPUT_LOCATION_UNIAPP + OUTPUT_DIR_VUE
|
||||
+ "/api/" + pc.getModuleName() + "/"
|
||||
+ tableInfo.getEntityPath() + "/" + "index.ts";
|
||||
}
|
||||
});
|
||||
// 生成TS文件 (/api/shop/goods/model/index.ts)
|
||||
templatePath = TEMPLATES_DIR + "/model.ts.btl";
|
||||
focList.add(new FileOutConfig(templatePath) {
|
||||
@Override
|
||||
public String outputFile(TableInfo tableInfo) {
|
||||
return OUTPUT_LOCATION_VUE + OUTPUT_DIR_VUE
|
||||
+ "/api/" + pc.getModuleName() + "/"
|
||||
+ tableInfo.getEntityPath() + "/model/" + "index.ts";
|
||||
}
|
||||
});
|
||||
// UniApp 使用专门的 model 模板
|
||||
String uniappModelTemplatePath = TEMPLATES_DIR + "/model.ts.uniapp.btl";
|
||||
focList.add(new FileOutConfig(uniappModelTemplatePath) {
|
||||
@Override
|
||||
public String outputFile(TableInfo tableInfo) {
|
||||
return OUTPUT_LOCATION_UNIAPP + OUTPUT_DIR_VUE
|
||||
+ "/api/" + pc.getModuleName() + "/"
|
||||
+ tableInfo.getEntityPath() + "/model/" + "index.ts";
|
||||
}
|
||||
});
|
||||
// 生成Vue文件(/views/shop/goods/index.vue)
|
||||
templatePath = TEMPLATES_DIR + "/index.vue.btl";
|
||||
focList.add(new FileOutConfig(templatePath) {
|
||||
@Override
|
||||
public String outputFile(TableInfo tableInfo) {
|
||||
return OUTPUT_LOCATION_VUE + OUTPUT_DIR_VUE
|
||||
+ "/views/" + pc.getModuleName() + "/"
|
||||
+ tableInfo.getEntityPath() + "/" + "index.vue";
|
||||
}
|
||||
});
|
||||
|
||||
// 生成components文件(/views/shop/goods/components/edit.vue)
|
||||
templatePath = TEMPLATES_DIR + "/components.edit.vue.btl";
|
||||
focList.add(new FileOutConfig(templatePath) {
|
||||
@Override
|
||||
public String outputFile(TableInfo tableInfo) {
|
||||
return OUTPUT_LOCATION_VUE + OUTPUT_DIR_VUE
|
||||
+ "/views/" + pc.getModuleName() + "/"
|
||||
+ tableInfo.getEntityPath() + "/components/" + tableInfo.getEntityPath() + "Edit.vue";
|
||||
}
|
||||
});
|
||||
|
||||
// 生成components文件(/views/shop/goods/components/search.vue)
|
||||
templatePath = TEMPLATES_DIR + "/components.search.vue.btl";
|
||||
focList.add(new FileOutConfig(templatePath) {
|
||||
@Override
|
||||
public String outputFile(TableInfo tableInfo) {
|
||||
return OUTPUT_LOCATION_VUE + OUTPUT_DIR_VUE
|
||||
+ "/views/" + pc.getModuleName() + "/"
|
||||
+ tableInfo.getEntityPath() + "/components/" + "search.vue";
|
||||
}
|
||||
});
|
||||
|
||||
// ========== 移动端页面文件生成 ==========
|
||||
// 生成移动端列表页面配置文件 (/src/shop/goods/index.config.ts)
|
||||
templatePath = TEMPLATES_DIR + "/index.config.ts.btl";
|
||||
focList.add(new FileOutConfig(templatePath) {
|
||||
@Override
|
||||
public String outputFile(TableInfo tableInfo) {
|
||||
return OUTPUT_LOCATION_UNIAPP + OUTPUT_DIR_VUE
|
||||
+ "/" + pc.getModuleName() + "/"
|
||||
+ tableInfo.getEntityPath() + "/" + "index.config.ts";
|
||||
}
|
||||
});
|
||||
|
||||
// 生成移动端列表页面组件文件 (/src/shop/goods/index.tsx)
|
||||
templatePath = TEMPLATES_DIR + "/index.tsx.btl";
|
||||
focList.add(new FileOutConfig(templatePath) {
|
||||
@Override
|
||||
public String outputFile(TableInfo tableInfo) {
|
||||
return OUTPUT_LOCATION_UNIAPP + OUTPUT_DIR_VUE
|
||||
+ "/" + pc.getModuleName() + "/"
|
||||
+ tableInfo.getEntityPath() + "/" + "index.tsx";
|
||||
}
|
||||
});
|
||||
|
||||
// 生成移动端新增/编辑页面配置文件 (/src/shop/goods/add.config.ts)
|
||||
templatePath = TEMPLATES_DIR + "/add.config.ts.btl";
|
||||
focList.add(new FileOutConfig(templatePath) {
|
||||
@Override
|
||||
public String outputFile(TableInfo tableInfo) {
|
||||
return OUTPUT_LOCATION_UNIAPP + OUTPUT_DIR_VUE
|
||||
+ "/" + pc.getModuleName() + "/"
|
||||
+ tableInfo.getEntityPath() + "/" + "add.config.ts";
|
||||
}
|
||||
});
|
||||
|
||||
// 生成移动端新增/编辑页面组件文件 (/src/shop/goods/add.tsx)
|
||||
templatePath = TEMPLATES_DIR + "/add.tsx.btl";
|
||||
focList.add(new FileOutConfig(templatePath) {
|
||||
@Override
|
||||
public String outputFile(TableInfo tableInfo) {
|
||||
return OUTPUT_LOCATION_UNIAPP + OUTPUT_DIR_VUE
|
||||
+ "/" + pc.getModuleName() + "/"
|
||||
+ tableInfo.getEntityPath() + "/" + "add.tsx";
|
||||
}
|
||||
});
|
||||
|
||||
cfg.setFileOutConfigList(focList);
|
||||
mpg.setCfg(cfg);
|
||||
|
||||
mpg.execute();
|
||||
|
||||
// 自动更新 app.config.ts
|
||||
updateAppConfig(TABLE_NAMES, MODULE_NAME);
|
||||
}
|
||||
|
||||
/**
|
||||
* 自动更新 app.config.ts 文件,添加新生成的页面路径
|
||||
*/
|
||||
private static void updateAppConfig(String[] tableNames, String moduleName) {
|
||||
String appConfigPath = OUTPUT_LOCATION_UNIAPP + OUTPUT_DIR_VUE + "/app.config.ts";
|
||||
|
||||
try {
|
||||
// 读取原文件内容
|
||||
String content = new String(Files.readAllBytes(Paths.get(appConfigPath)));
|
||||
|
||||
// 为每个表生成页面路径
|
||||
StringBuilder newPages = new StringBuilder();
|
||||
for (String tableName : tableNames) {
|
||||
String entityPath = tableName.replaceAll("_", "");
|
||||
// 转换为驼峰命名
|
||||
String[] parts = tableName.split("_");
|
||||
StringBuilder camelCase = new StringBuilder(parts[0]);
|
||||
for (int i = 1; i < parts.length; i++) {
|
||||
camelCase.append(parts[i].substring(0, 1).toUpperCase()).append(parts[i].substring(1));
|
||||
}
|
||||
entityPath = camelCase.toString();
|
||||
|
||||
newPages.append(" '").append(entityPath).append("/index',\n");
|
||||
newPages.append(" '").append(entityPath).append("/add',\n");
|
||||
}
|
||||
|
||||
// 查找对应模块的子包配置
|
||||
String modulePattern = "\"root\":\\s*\"" + moduleName + "\",\\s*\"pages\":\\s*\\[([^\\]]*)]";
|
||||
Pattern pattern = Pattern.compile(modulePattern, Pattern.DOTALL);
|
||||
Matcher matcher = pattern.matcher(content);
|
||||
|
||||
if (matcher.find()) {
|
||||
String existingPages = matcher.group(1);
|
||||
|
||||
// 检查页面是否已存在,避免重复添加
|
||||
boolean needUpdate = false;
|
||||
String[] newPageArray = newPages.toString().split("\n");
|
||||
for (String newPage : newPageArray) {
|
||||
if (!newPage.trim().isEmpty() && !existingPages.contains(newPage.trim().replace(" ", "").replace(",", ""))) {
|
||||
needUpdate = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (needUpdate) {
|
||||
// 备份原文件
|
||||
String backupPath = appConfigPath + ".backup." + System.currentTimeMillis();
|
||||
Files.copy(Paths.get(appConfigPath), Paths.get(backupPath));
|
||||
System.out.println("已备份原文件到: " + backupPath);
|
||||
|
||||
// 在现有页面列表末尾添加新页面
|
||||
String updatedPages = existingPages.trim();
|
||||
if (!updatedPages.endsWith(",")) {
|
||||
updatedPages += ",";
|
||||
}
|
||||
updatedPages += "\n" + newPages.toString().trim();
|
||||
|
||||
// 替换内容
|
||||
String updatedContent = content.replace(matcher.group(1), updatedPages);
|
||||
|
||||
// 写入更新后的内容
|
||||
Files.write(Paths.get(appConfigPath), updatedContent.getBytes());
|
||||
|
||||
System.out.println("✅ 已自动更新 app.config.ts,添加了以下页面路径:");
|
||||
System.out.println(newPages.toString());
|
||||
} else {
|
||||
System.out.println("ℹ️ app.config.ts 中已包含所有页面路径,无需更新");
|
||||
}
|
||||
} else {
|
||||
System.out.println("⚠️ 未找到 " + moduleName + " 模块的子包配置,请手动添加页面路径");
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
System.err.println("❌ 更新 app.config.ts 失败: " + e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package com.gxwebsoft.generator.engine;
|
||||
|
||||
import com.baomidou.mybatisplus.generator.config.builder.ConfigBuilder;
|
||||
import com.baomidou.mybatisplus.generator.engine.AbstractTemplateEngine;
|
||||
import org.beetl.core.Configuration;
|
||||
import org.beetl.core.GroupTemplate;
|
||||
import org.beetl.core.Template;
|
||||
import org.beetl.core.resource.FileResourceLoader;
|
||||
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Beetl模板引擎实现文件输出
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2021-09-05 00:30:28
|
||||
*/
|
||||
public class BeetlTemplateEnginePlus extends AbstractTemplateEngine {
|
||||
private GroupTemplate groupTemplate;
|
||||
|
||||
@Override
|
||||
public AbstractTemplateEngine init(ConfigBuilder configBuilder) {
|
||||
super.init(configBuilder);
|
||||
try {
|
||||
Configuration cfg = Configuration.defaultConfiguration();
|
||||
groupTemplate = new GroupTemplate(new FileResourceLoader(), cfg);
|
||||
} catch (IOException e) {
|
||||
logger.error(e.getMessage(), e);
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void writer(Map<String, Object> objectMap, String templatePath, String outputFile) throws Exception {
|
||||
Template template = groupTemplate.getTemplate(templatePath);
|
||||
try (FileOutputStream fileOutputStream = new FileOutputStream(outputFile)) {
|
||||
template.binding(objectMap);
|
||||
template.renderTo(fileOutputStream);
|
||||
}
|
||||
logger.debug("模板:" + templatePath + "; 文件:" + outputFile);
|
||||
}
|
||||
|
||||
@Override
|
||||
public String templateFilePath(String filePath) {
|
||||
return filePath + ".btl";
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
export default definePageConfig({
|
||||
navigationBarTitleText: '新增${table.comment!'数据'}',
|
||||
navigationBarTextStyle: 'black'
|
||||
})
|
||||
115
src/test/java/com/gxwebsoft/generator/templates/add.tsx.btl
Normal file
115
src/test/java/com/gxwebsoft/generator/templates/add.tsx.btl
Normal file
@@ -0,0 +1,115 @@
|
||||
import {useEffect, useState, useRef} from "react";
|
||||
import {useRouter} from '@tarojs/taro'
|
||||
import {Button, Loading, CellGroup, Input, TextArea, Form} from '@nutui/nutui-react-taro'
|
||||
import Taro from '@tarojs/taro'
|
||||
import {View} from '@tarojs/components'
|
||||
import {${entity}} from "@/api/${package.ModuleName}/${table.entityPath}/model";
|
||||
import {get${entity}, list${entity}, update${entity}, add${entity}} from "@/api/${package.ModuleName}/${table.entityPath}";
|
||||
|
||||
const Add${entity} = () => {
|
||||
const {params} = useRouter();
|
||||
const [loading, setLoading] = useState<boolean>(true)
|
||||
const [FormData, setFormData] = useState<${entity}>({})
|
||||
const formRef = useRef<any>(null)
|
||||
|
||||
const reload = async () => {
|
||||
if (params.id) {
|
||||
const data = await get${entity}(Number(params.id))
|
||||
setFormData(data)
|
||||
} else {
|
||||
setFormData({})
|
||||
}
|
||||
}
|
||||
|
||||
// 提交表单
|
||||
const submitSucceed = async (values: any) => {
|
||||
try {
|
||||
if (params.id) {
|
||||
// 编辑模式
|
||||
await update${entity}({
|
||||
...values,
|
||||
id: Number(params.id)
|
||||
})
|
||||
} else {
|
||||
// 新增模式
|
||||
await add${entity}(values)
|
||||
}
|
||||
|
||||
Taro.showToast({
|
||||
title: `操作成功`,
|
||||
icon: 'success'
|
||||
})
|
||||
|
||||
setTimeout(() => {
|
||||
return Taro.navigateBack()
|
||||
}, 1000)
|
||||
} catch (error) {
|
||||
Taro.showToast({
|
||||
title: `操作失败`,
|
||||
icon: 'error'
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const submitFailed = (error: any) => {
|
||||
console.log(error, 'err...')
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
reload().then(() => {
|
||||
setLoading(false)
|
||||
})
|
||||
}, []);
|
||||
|
||||
if (loading) {
|
||||
return <Loading className={'px-2'}>加载中</Loading>
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<Form
|
||||
ref={formRef}
|
||||
divider
|
||||
initialValues={FormData}
|
||||
labelPosition="left"
|
||||
onFinish={(values) => submitSucceed(values)}
|
||||
onFinishFailed={(errors) => submitFailed(errors)}
|
||||
footer={
|
||||
<div
|
||||
style={{
|
||||
display: 'flex',
|
||||
justifyContent: 'center',
|
||||
width: '100%'
|
||||
}}
|
||||
>
|
||||
<Button
|
||||
nativeType="submit"
|
||||
type="success"
|
||||
size="large"
|
||||
className={'w-full'}
|
||||
block
|
||||
>
|
||||
{params.id ? '更新' : '保存'}
|
||||
</Button>
|
||||
</div>
|
||||
}
|
||||
>
|
||||
<CellGroup style={{padding: '4px 0'}}>
|
||||
<% for(field in table.fields){ %>
|
||||
<% if(field.propertyName != 'id' && field.propertyName != 'createTime' && field.propertyName != 'updateTime'){ %>
|
||||
<Form.Item name="${field.propertyName}" label="${field.comment!field.propertyName}" initialValue={FormData.${field.propertyName}} required>
|
||||
<% if(field.propertyType == 'String' && field.comment?? && (field.comment?contains('描述') || field.comment?contains('备注') || field.comment?contains('内容'))){ %>
|
||||
<TextArea maxLength={200} placeholder="请输入${field.comment!'内容'}"/>
|
||||
<% } else { %>
|
||||
<Input placeholder="请输入${field.comment!'字段'}" maxLength={50}/>
|
||||
<% } %>
|
||||
</Form.Item>
|
||||
<% } %>
|
||||
<% } %>
|
||||
</CellGroup>
|
||||
</Form>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default Add${entity};
|
||||
@@ -0,0 +1,47 @@
|
||||
// 完整的列配置(可根据需要启用更多列)
|
||||
const allColumns = ref<ColumnItem[]>([
|
||||
<% for(field in table.fields) { %>
|
||||
<% if(field.propertyName != 'tenantId'){ %>
|
||||
{
|
||||
title: '${field.comment!field.propertyName}',
|
||||
dataIndex: '${field.propertyName}',
|
||||
key: '${field.propertyName}',
|
||||
align: 'center',
|
||||
<% if(field.keyFlag){ %>
|
||||
width: 90,
|
||||
<% } else if(field.propertyName == 'createTime' || field.propertyName == 'updateTime'){ %>
|
||||
width: 120,
|
||||
sorter: true,
|
||||
ellipsis: true,
|
||||
customRender: ({ text }) => toDateString(text, 'yyyy-MM-dd')
|
||||
<% } else if(field.propertyType == 'String'){ %>
|
||||
width: 150,
|
||||
ellipsis: true
|
||||
<% } else if(field.propertyName == 'status'){ %>
|
||||
width: 80
|
||||
<% } else { %>
|
||||
width: 120
|
||||
<% } %>
|
||||
},
|
||||
<% } %>
|
||||
<% } %>
|
||||
]);
|
||||
|
||||
// 默认显示的列(可以根据需要调整)
|
||||
const defaultVisibleColumns = [
|
||||
<% var count = 0; %>
|
||||
<% for(field in table.fields) { %>
|
||||
<% if(field.keyFlag || field.propertyName == 'name' || field.propertyName == 'title' || field.propertyName == 'status' || field.propertyName == 'createTime'){ %>
|
||||
'${field.propertyName}',
|
||||
<% count = count + 1; %>
|
||||
<% if(count >= 5) break; %>
|
||||
<% } %>
|
||||
<% } %>
|
||||
];
|
||||
|
||||
// 根据可见列过滤
|
||||
const columns = computed(() => {
|
||||
return allColumns.value.filter(col =>
|
||||
defaultVisibleColumns.includes(col.dataIndex) || col.key === 'action'
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,221 @@
|
||||
<!-- 编辑弹窗 -->
|
||||
<template>
|
||||
<ele-modal
|
||||
:width="800"
|
||||
:visible="visible"
|
||||
:maskClosable="false"
|
||||
:maxable="maxable"
|
||||
:title="isUpdate ? '编辑${table.comment!}' : '添加${table.comment!}'"
|
||||
:body-style="{ paddingBottom: '28px' }"
|
||||
@update:visible="updateVisible"
|
||||
@ok="save"
|
||||
>
|
||||
<a-form
|
||||
ref="formRef"
|
||||
:model="form"
|
||||
:rules="rules"
|
||||
:label-col="styleResponsive ? { md: 4, sm: 5, xs: 24 } : { flex: '90px' }"
|
||||
:wrapper-col="
|
||||
styleResponsive ? { md: 19, sm: 19, xs: 24 } : { flex: '1' }
|
||||
"
|
||||
>
|
||||
<% for(field in table.fields) { %>
|
||||
<% if(field.propertyName == 'comments'){ %>
|
||||
<a-form-item label="${field.comment!}" name="${field.propertyName}">
|
||||
<a-textarea
|
||||
:rows="4"
|
||||
:maxlength="200"
|
||||
placeholder="请输入描述"
|
||||
v-model:value="form.${field.propertyName}"
|
||||
/>
|
||||
</a-form-item>
|
||||
<% } %>
|
||||
<% else if(field.propertyName == 'sortNumber'){ %>
|
||||
<a-form-item label="${field.comment!}" name="${field.propertyName}">
|
||||
<a-input-number
|
||||
:min="0"
|
||||
:max="9999"
|
||||
class="ele-fluid"
|
||||
placeholder="请输入排序号"
|
||||
v-model:value="form.${field.propertyName}"
|
||||
/>
|
||||
</a-form-item>
|
||||
<% } %>
|
||||
<% else if(field.propertyName == 'status'){ %>
|
||||
<a-form-item label="${field.comment!}" name="${field.propertyName}">
|
||||
<a-radio-group v-model:value="form.status">
|
||||
<a-radio :value="0">显示</a-radio>
|
||||
<a-radio :value="1">隐藏</a-radio>
|
||||
</a-radio-group>
|
||||
</a-form-item>
|
||||
<% } %>
|
||||
<% else if(field.propertyName == 'image'){ %>
|
||||
<a-form-item
|
||||
label="${field.comment!}"
|
||||
name="${field.propertyName}">
|
||||
<SelectFile
|
||||
:placeholder="`请选择图片`"
|
||||
:limit="1"
|
||||
:data="images"
|
||||
@done="chooseImage"
|
||||
@del="onDeleteItem"
|
||||
/>
|
||||
</a-form-item>
|
||||
<% } %>
|
||||
<% else if(field.keyFlag){ %>
|
||||
<% } %>
|
||||
<% else if(field.propertyName == 'tenantId'){ %>
|
||||
<% } %>
|
||||
<% else if(field.propertyName == 'createTime'){ %>
|
||||
<% } %>
|
||||
<% else { %>
|
||||
<a-form-item label="${field.comment!}" name="${field.propertyName}">
|
||||
<a-input
|
||||
allow-clear
|
||||
placeholder="请输入${field.comment!}"
|
||||
v-model:value="form.${field.propertyName}"
|
||||
/>
|
||||
</a-form-item>
|
||||
<% } %>
|
||||
<% } %>
|
||||
</a-form>
|
||||
</ele-modal>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { ref, reactive, watch } from 'vue';
|
||||
import { Form, message } from 'ant-design-vue';
|
||||
import { assignObject, uuid } from 'ele-admin-pro';
|
||||
import { add${entity}, update${entity} } from '@/api/${package.ModuleName}/${table.entityPath}';
|
||||
import { ${entity} } from '@/api/${package.ModuleName}/${table.entityPath}/model';
|
||||
import { useThemeStore } from '@/store/modules/theme';
|
||||
import { storeToRefs } from 'pinia';
|
||||
import { ItemType } from 'ele-admin-pro/es/ele-image-upload/types';
|
||||
import { FormInstance } from 'ant-design-vue/es/form';
|
||||
import { FileRecord } from '@/api/system/file/model';
|
||||
|
||||
// 是否是修改
|
||||
const isUpdate = ref(false);
|
||||
const useForm = Form.useForm;
|
||||
// 是否开启响应式布局
|
||||
const themeStore = useThemeStore();
|
||||
const { styleResponsive } = storeToRefs(themeStore);
|
||||
|
||||
const props = defineProps<{
|
||||
// 弹窗是否打开
|
||||
visible: boolean;
|
||||
// 修改回显的数据
|
||||
data?: ${entity} | null;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'done'): void;
|
||||
(e: 'update:visible', visible: boolean): void;
|
||||
}>();
|
||||
|
||||
// 提交状态
|
||||
const loading = ref(false);
|
||||
// 是否显示最大化切换按钮
|
||||
const maxable = ref(true);
|
||||
// 表格选中数据
|
||||
const formRef = ref<FormInstance | null>(null);
|
||||
const images = ref<ItemType[]>([]);
|
||||
|
||||
// 用户信息
|
||||
const form = reactive<${entity}>({
|
||||
<% for(field in table.fields) { %>
|
||||
${field.propertyName}: undefined,
|
||||
<% } %>
|
||||
${table.entityPath}Id: undefined,
|
||||
${table.entityPath}Name: '',
|
||||
status: 0,
|
||||
comments: '',
|
||||
sortNumber: 100
|
||||
});
|
||||
|
||||
/* 更新visible */
|
||||
const updateVisible = (value: boolean) => {
|
||||
emit('update:visible', value);
|
||||
};
|
||||
|
||||
// 表单验证规则
|
||||
const rules = reactive({
|
||||
${table.entityPath}Name: [
|
||||
{
|
||||
required: true,
|
||||
type: 'string',
|
||||
message: '请填写${table.comment!}名称',
|
||||
trigger: 'blur'
|
||||
}
|
||||
]
|
||||
});
|
||||
|
||||
const chooseImage = (data: FileRecord) => {
|
||||
images.value.push({
|
||||
uid: data.id,
|
||||
url: data.path,
|
||||
status: 'done'
|
||||
});
|
||||
form.image = data.path;
|
||||
};
|
||||
|
||||
const onDeleteItem = (index: number) => {
|
||||
images.value.splice(index, 1);
|
||||
form.image = '';
|
||||
};
|
||||
|
||||
const { resetFields } = useForm(form, rules);
|
||||
|
||||
/* 保存编辑 */
|
||||
const save = () => {
|
||||
if (!formRef.value) {
|
||||
return;
|
||||
}
|
||||
formRef.value
|
||||
.validate()
|
||||
.then(() => {
|
||||
loading.value = true;
|
||||
const formData = {
|
||||
...form
|
||||
};
|
||||
const saveOrUpdate = isUpdate.value ? update${entity} : add${entity};
|
||||
saveOrUpdate(formData)
|
||||
.then((msg) => {
|
||||
loading.value = false;
|
||||
message.success(msg);
|
||||
updateVisible(false);
|
||||
emit('done');
|
||||
})
|
||||
.catch((e) => {
|
||||
loading.value = false;
|
||||
message.error(e.message);
|
||||
});
|
||||
})
|
||||
.catch(() => {});
|
||||
};
|
||||
|
||||
watch(
|
||||
() => props.visible,
|
||||
(visible) => {
|
||||
if (visible) {
|
||||
images.value = [];
|
||||
if (props.data) {
|
||||
assignObject(form, props.data);
|
||||
if(props.data.image){
|
||||
images.value.push({
|
||||
uid: uuid(),
|
||||
url: props.data.image,
|
||||
status: 'done'
|
||||
})
|
||||
}
|
||||
isUpdate.value = true;
|
||||
} else {
|
||||
isUpdate.value = false;
|
||||
}
|
||||
} else {
|
||||
resetFields();
|
||||
}
|
||||
},
|
||||
{ immediate: true }
|
||||
);
|
||||
</script>
|
||||
@@ -0,0 +1,42 @@
|
||||
<!-- 搜索表单 -->
|
||||
<template>
|
||||
<a-space :size="10" style="flex-wrap: wrap">
|
||||
<a-button type="primary" class="ele-btn-icon" @click="add">
|
||||
<template #icon>
|
||||
<PlusOutlined />
|
||||
</template>
|
||||
<span>添加</span>
|
||||
</a-button>
|
||||
</a-space>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { PlusOutlined } from '@ant-design/icons-vue';
|
||||
import type { GradeParam } from '@/api/user/grade/model';
|
||||
import { watch } from 'vue';
|
||||
|
||||
const props = withDefaults(
|
||||
defineProps<{
|
||||
// 选中的角色
|
||||
selection?: [];
|
||||
}>(),
|
||||
{}
|
||||
);
|
||||
|
||||
const emit = defineEmits<{
|
||||
(e: 'search', where?: GradeParam): void;
|
||||
(e: 'add'): void;
|
||||
(e: 'remove'): void;
|
||||
(e: 'batchMove'): void;
|
||||
}>();
|
||||
|
||||
// 新增
|
||||
const add = () => {
|
||||
emit('add');
|
||||
};
|
||||
|
||||
watch(
|
||||
() => props.selection,
|
||||
() => {}
|
||||
);
|
||||
</script>
|
||||
@@ -0,0 +1,278 @@
|
||||
<%
|
||||
var serviceIns = strutil.toLowerCase(strutil.subStringTo(table.serviceName, 0, 1)) + strutil.subString(table.serviceName, 1);
|
||||
var authPre = package.ModuleName + ':' + table.entityPath;
|
||||
var idFieldName, idPropertyName;
|
||||
for(field in table.fields) {
|
||||
if(field.keyFlag) {
|
||||
idFieldName = field.name;
|
||||
idPropertyName = field.propertyName;
|
||||
}
|
||||
}
|
||||
%>
|
||||
package ${package.Controller};
|
||||
|
||||
<% if(isNotEmpty(superControllerClassPackage)) { %>
|
||||
import ${superControllerClassPackage};
|
||||
<% } %>
|
||||
import ${cfg.packageName!}.${package.ModuleName}.service.${entity}Service;
|
||||
import ${cfg.packageName!}.${package.ModuleName}.entity.${entity};
|
||||
import ${cfg.packageName!}.${package.ModuleName}.param.${entity}Param;
|
||||
import ${cfg.packageName!}.common.core.web.ApiResult;
|
||||
import ${cfg.packageName!}.common.core.web.PageResult;
|
||||
import ${cfg.packageName!}.common.core.web.PageParam;
|
||||
import ${cfg.packageName!}.common.core.web.BatchParam;
|
||||
import ${cfg.packageName!}.common.core.annotation.OperationLog;
|
||||
import ${cfg.packageName!}.common.system.entity.User;
|
||||
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.*;
|
||||
<% if(!restControllerStyle) { %>
|
||||
import org.springframework.stereotype.Controller;
|
||||
<% } %>
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* ${table.comment!}控制器
|
||||
*
|
||||
* @author ${author}
|
||||
* @since ${date(), 'yyyy-MM-dd HH:mm:ss'}
|
||||
*/
|
||||
<% if(swagger2) { %>
|
||||
@Tag(name = "${table.comment!}管理")
|
||||
<% } %>
|
||||
<% if(restControllerStyle) { %>
|
||||
@RestController
|
||||
<% } else { %>
|
||||
@Controller
|
||||
<% } %>
|
||||
@RequestMapping("${cfg.controllerMappingPrefix!}<% if(isNotEmpty(package.ModuleName)){ %>/${package.ModuleName}<% } %>/<% if(isNotEmpty(controllerMappingHyphenStyle)){ %>${controllerMappingHyphen}<% }else{ %>${table.entityPath}<% } %>")
|
||||
<% if(kotlin) { %>
|
||||
class ${table.controllerName}<% if(isNotEmpty(superControllerClass)) { %> : ${superControllerClass}()<% } %>
|
||||
<% } else if(isNotEmpty(superControllerClass)) { %>
|
||||
public class ${table.controllerName} extends ${superControllerClass} {
|
||||
<% } else { %>
|
||||
public class ${table.controllerName} {
|
||||
<% } %>
|
||||
@Resource
|
||||
private ${table.serviceName} ${serviceIns};
|
||||
|
||||
<% if(!swagger2) { %>
|
||||
/**
|
||||
* 分页查询${table.comment!}
|
||||
*/
|
||||
<% } %>
|
||||
<% if(cfg.authAnnotation) { %>
|
||||
@PreAuthorize("hasAuthority('${authPre}:list')")
|
||||
<% } %>
|
||||
<% if(swagger2) { %>
|
||||
@Operation(summary = "分页查询${table.comment!}")
|
||||
<% } %>
|
||||
<% if(!restControllerStyle) { %>
|
||||
@ResponseBody
|
||||
<% } %>
|
||||
@GetMapping("/page")
|
||||
public ApiResult<PageResult<${entity}>> page(${entity}Param param) {
|
||||
// 使用关联查询
|
||||
return success(${serviceIns}.pageRel(param));
|
||||
}
|
||||
|
||||
<% if(!swagger2) { %>
|
||||
/**
|
||||
* 查询全部${table.comment!}
|
||||
*/
|
||||
<% } %>
|
||||
<% if(cfg.authAnnotation) { %>
|
||||
@PreAuthorize("hasAuthority('${authPre}:list')")
|
||||
<% } %>
|
||||
<% if(swagger2) { %>
|
||||
@Operation(summary = "查询全部${table.comment!}")
|
||||
<% } %>
|
||||
<% if(!restControllerStyle) { %>
|
||||
@ResponseBody
|
||||
<% } %>
|
||||
@GetMapping()
|
||||
public ApiResult<List<${entity}>> list(${entity}Param param) {
|
||||
// 使用关联查询
|
||||
return success(${serviceIns}.listRel(param));
|
||||
}
|
||||
|
||||
<% if(!swagger2) { %>
|
||||
/**
|
||||
* 根据id查询${table.comment!}
|
||||
*/
|
||||
<% } %>
|
||||
@PreAuthorize("hasAuthority('${authPre}:list')")
|
||||
@Operation(summary = "根据id查询${table.comment!}")
|
||||
@GetMapping("/{id}")
|
||||
public ApiResult<${entity}> get(@PathVariable("id") Integer id) {
|
||||
// 使用关联查询
|
||||
return success(${serviceIns}.getByIdRel(id));
|
||||
}
|
||||
|
||||
<% if(!swagger2) { %>
|
||||
/**
|
||||
* 添加${table.comment!}
|
||||
*/
|
||||
<% } %>
|
||||
<% if(cfg.authAnnotation) { %>
|
||||
@PreAuthorize("hasAuthority('${authPre}:save')")
|
||||
<% } %>
|
||||
<% if(cfg.logAnnotation) { %>
|
||||
@OperationLog
|
||||
<% } %>
|
||||
<% if(swagger2) { %>
|
||||
@Operation(summary = "添加${table.comment!}")
|
||||
<% } %>
|
||||
<% if(!restControllerStyle) { %>
|
||||
@ResponseBody
|
||||
<% } %>
|
||||
@PostMapping()
|
||||
public ApiResult<?> save(@RequestBody ${entity} ${table.entityPath}) {
|
||||
<% var hasUserIdField = false; %>
|
||||
<% for(field in table.fields){ %>
|
||||
<% if(field.propertyName == 'userId'){ %>
|
||||
<% hasUserIdField = true; %>
|
||||
<% } %>
|
||||
<% } %>
|
||||
<% if(hasUserIdField){ %>
|
||||
// 记录当前登录用户id
|
||||
User loginUser = getLoginUser();
|
||||
if (loginUser != null) {
|
||||
${table.entityPath}.setUserId(loginUser.getUserId());
|
||||
}
|
||||
<% } %>
|
||||
if (${serviceIns}.save(${table.entityPath})) {
|
||||
return success("添加成功");
|
||||
}
|
||||
return fail("添加失败");
|
||||
}
|
||||
|
||||
<% if(!swagger2) { %>
|
||||
/**
|
||||
* 修改${table.comment!}
|
||||
*/
|
||||
<% } %>
|
||||
<% if(cfg.authAnnotation) { %>
|
||||
@PreAuthorize("hasAuthority('${authPre}:update')")
|
||||
<% } %>
|
||||
<% if(cfg.logAnnotation) { %>
|
||||
@OperationLog
|
||||
<% } %>
|
||||
<% if(swagger2) { %>
|
||||
@Operation(summary = "修改${table.comment!}")
|
||||
<% } %>
|
||||
<% if(!restControllerStyle) { %>
|
||||
@ResponseBody
|
||||
<% } %>
|
||||
@PutMapping()
|
||||
public ApiResult<?> update(@RequestBody ${entity} ${table.entityPath}) {
|
||||
if (${serviceIns}.updateById(${table.entityPath})) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
<% if(!swagger2) { %>
|
||||
/**
|
||||
* 删除${table.comment!}
|
||||
*/
|
||||
<% } %>
|
||||
<% if(cfg.authAnnotation) { %>
|
||||
@PreAuthorize("hasAuthority('${authPre}:remove')")
|
||||
<% } %>
|
||||
<% if(cfg.logAnnotation) { %>
|
||||
@OperationLog
|
||||
<% } %>
|
||||
<% if(swagger2) { %>
|
||||
@Operation(summary = "删除${table.comment!}")
|
||||
<% } %>
|
||||
<% if(!restControllerStyle) { %>
|
||||
@ResponseBody
|
||||
<% } %>
|
||||
@DeleteMapping("/{id}")
|
||||
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
||||
if (${serviceIns}.removeById(id)) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
<% if(!swagger2) { %>
|
||||
/**
|
||||
* 批量添加${table.comment!}
|
||||
*/
|
||||
<% } %>
|
||||
<% if(cfg.authAnnotation) { %>
|
||||
@PreAuthorize("hasAuthority('${authPre}:save')")
|
||||
<% } %>
|
||||
<% if(cfg.logAnnotation) { %>
|
||||
@OperationLog
|
||||
<% } %>
|
||||
<% if(swagger2) { %>
|
||||
@Operation(summary = "批量添加${table.comment!}")
|
||||
<% } %>
|
||||
<% if(!restControllerStyle) { %>
|
||||
@ResponseBody
|
||||
<% } %>
|
||||
@PostMapping("/batch")
|
||||
public ApiResult<?> saveBatch(@RequestBody List<${entity}> list) {
|
||||
if (${serviceIns}.saveBatch(list)) {
|
||||
return success("添加成功");
|
||||
}
|
||||
return fail("添加失败");
|
||||
}
|
||||
|
||||
<% if(!swagger2) { %>
|
||||
/**
|
||||
* 批量修改${table.comment!}
|
||||
*/
|
||||
<% } %>
|
||||
<% if(cfg.authAnnotation) { %>
|
||||
@PreAuthorize("hasAuthority('${authPre}:update')")
|
||||
<% } %>
|
||||
<% if(cfg.logAnnotation) { %>
|
||||
@OperationLog
|
||||
<% } %>
|
||||
<% if(swagger2) { %>
|
||||
@Operation(summary = "批量修改${table.comment!}")
|
||||
<% } %>
|
||||
<% if(!restControllerStyle) { %>
|
||||
@ResponseBody
|
||||
<% } %>
|
||||
@PutMapping("/batch")
|
||||
public ApiResult<?> removeBatch(@RequestBody BatchParam<${entity}> batchParam) {
|
||||
if (batchParam.update(${serviceIns}, "${idFieldName!}")) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
<% if(!swagger2) { %>
|
||||
/**
|
||||
* 批量删除${table.comment!}
|
||||
*/
|
||||
<% } %>
|
||||
<% if(cfg.authAnnotation) { %>
|
||||
@PreAuthorize("hasAuthority('${authPre}:remove')")
|
||||
<% } %>
|
||||
<% if(cfg.logAnnotation) { %>
|
||||
@OperationLog
|
||||
<% } %>
|
||||
<% if(swagger2) { %>
|
||||
@Operation(summary = "批量删除${table.comment!}")
|
||||
<% } %>
|
||||
<% if(!restControllerStyle) { %>
|
||||
@ResponseBody
|
||||
<% } %>
|
||||
@DeleteMapping("/batch")
|
||||
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
||||
if (${serviceIns}.removeByIds(ids)) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
}
|
||||
157
src/test/java/com/gxwebsoft/generator/templates/entity.java.btl
Normal file
157
src/test/java/com/gxwebsoft/generator/templates/entity.java.btl
Normal file
@@ -0,0 +1,157 @@
|
||||
package ${package.Entity};
|
||||
|
||||
<% for(pkg in table.importPackages) { %>
|
||||
import ${pkg};
|
||||
<% } %>
|
||||
<% if(swagger2) { %>
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
<% } %>
|
||||
<% if(entityLombokModel) { %>
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
<% if(chainModel) { %>
|
||||
import lombok.experimental.Accessors;
|
||||
<% } %>
|
||||
<% } %>
|
||||
|
||||
/**
|
||||
* ${table.comment!}
|
||||
*
|
||||
* @author ${author}
|
||||
* @since ${date(), 'yyyy-MM-dd HH:mm:ss'}
|
||||
*/
|
||||
<% if(entityLombokModel) { %>
|
||||
@Data
|
||||
<% if(isNotEmpty(superEntityClass)) { %>
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
<% } else { %>
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
<% } %>
|
||||
<% if(chainModel) { %>
|
||||
@Accessors(chain = true)
|
||||
<% } %>
|
||||
<% } %>
|
||||
<% if(swagger2) { %>
|
||||
@Schema(name = "${entity}对象", description = "${table.comment!''}")
|
||||
<% } %>
|
||||
<% if(table.convert) { %>
|
||||
@TableName("${table.name}")
|
||||
<% } %>
|
||||
<% if(isNotEmpty(superEntityClass)) { %>
|
||||
public class ${entity} extends ${superEntityClass}<% if(activeRecord) { %><${entity}><% } %>{
|
||||
<% } else if(activeRecord) { %>
|
||||
public class ${entity} extends Model<${entity}> {
|
||||
<% } else { %>
|
||||
public class ${entity} implements Serializable {
|
||||
<% } %>
|
||||
<% if(entitySerialVersionUID) { %>
|
||||
private static final long serialVersionUID = 1L;
|
||||
<% } %>
|
||||
<% /** -----------BEGIN 字段循环遍历----------- **/ %>
|
||||
<% for(field in table.fields) { %>
|
||||
<%
|
||||
var keyPropertyName;
|
||||
if(field.keyFlag) {
|
||||
keyPropertyName = field.propertyName;
|
||||
}
|
||||
%>
|
||||
|
||||
<% if(isNotEmpty(field.comment)) { %>
|
||||
<% if(swagger2) { %>
|
||||
@Schema(description = "${field.comment}")
|
||||
<% }else{ %>
|
||||
/**
|
||||
* ${field.comment}
|
||||
*/
|
||||
<% } %>
|
||||
<% } %>
|
||||
<% /* 主键 */ %>
|
||||
<% if(field.keyFlag) { %>
|
||||
<% if(field.keyIdentityFlag) { %>
|
||||
@TableId(value = "${field.annotationColumnName}", type = IdType.AUTO)
|
||||
<% } else if(isNotEmpty(idType)) { %>
|
||||
@TableId(value = "${field.annotationColumnName}", type = IdType.${idType})
|
||||
<% } else if(field.convert) { %>
|
||||
@TableId("${field.annotationColumnName}")
|
||||
<% } %>
|
||||
<% /* 普通字段 */ %>
|
||||
<% } else if(isNotEmpty(field.fill)) { %>
|
||||
<% if(field.convert){ %>
|
||||
@TableField(value = "${field.annotationColumnName}", fill = FieldFill.${field.fill})
|
||||
<% }else{ %>
|
||||
@TableField(fill = FieldFill.${field.fill})
|
||||
<% } %>
|
||||
<% } else if(field.convert) { %>
|
||||
@TableField("${field.annotationColumnName}")
|
||||
<% } %>
|
||||
<% /* 乐观锁注解 */ %>
|
||||
<% if(versionFieldName!'' == field.name) { %>
|
||||
@Version
|
||||
<% } %>
|
||||
<% /* 逻辑删除注解 */ %>
|
||||
<% if(logicDeleteFieldName!'' == field.name) { %>
|
||||
@TableLogic
|
||||
<% } %>
|
||||
private ${field.propertyType} ${field.propertyName};
|
||||
<% } %>
|
||||
<% /** -----------END 字段循环遍历----------- **/ %>
|
||||
|
||||
<% if(!entityLombokModel) { %>
|
||||
<% for(field in table.fields) { %>
|
||||
<%
|
||||
var getprefix = '';
|
||||
if(field.propertyType == 'boolean') {
|
||||
getprefix = 'is';
|
||||
} else {
|
||||
getprefix = 'get';
|
||||
}
|
||||
%>
|
||||
public ${field.propertyType} ${getprefix}${field.capitalName}() {
|
||||
return ${field.propertyName};
|
||||
}
|
||||
|
||||
<% if(chainModel) { %>
|
||||
public ${entity} set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
|
||||
<% } else { %>
|
||||
public void set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
|
||||
<% } %>
|
||||
this.${field.propertyName} = ${field.propertyName};
|
||||
<% if(chainModel){ %>
|
||||
return this;
|
||||
<% } %>
|
||||
}
|
||||
|
||||
<% } %>
|
||||
<% } %>
|
||||
<% if(entityColumnConstant) { %>
|
||||
<% for(field in table.fields) { %>
|
||||
public static final String ${strutil.toUpperCase(field.name)} = "${field.name}";
|
||||
|
||||
<% } %>
|
||||
<% } %>
|
||||
<% if(activeRecord) { %>
|
||||
@Override
|
||||
protected Serializable pkVal() {
|
||||
<% if(isNotEmpty(keyPropertyName)){ %>
|
||||
return this.${keyPropertyName};
|
||||
<% }else{ %>
|
||||
return null;
|
||||
<% } %>
|
||||
}
|
||||
|
||||
<% } %>
|
||||
<% if(!entityLombokModel){ %>
|
||||
@Override
|
||||
public String toString() {
|
||||
return "${entity}{" +
|
||||
<% for(field in table.fields){ %>
|
||||
<% if(fieldLP.index==0){ %>
|
||||
"${field.propertyName}=" + ${field.propertyName} +
|
||||
<% }else{ %>
|
||||
", ${field.propertyName}=" + ${field.propertyName} +
|
||||
<% } %>
|
||||
<% } %>
|
||||
"}";
|
||||
}
|
||||
<% } %>
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
export default definePageConfig({
|
||||
navigationBarTitleText: '${table.comment!'数据'}管理',
|
||||
navigationBarTextStyle: 'black'
|
||||
})
|
||||
105
src/test/java/com/gxwebsoft/generator/templates/index.ts.btl
Normal file
105
src/test/java/com/gxwebsoft/generator/templates/index.ts.btl
Normal file
@@ -0,0 +1,105 @@
|
||||
import request from '@/utils/request';
|
||||
import type { ApiResult, PageResult } from '@/api';
|
||||
import type { ${entity}, ${entity}Param } from './model';
|
||||
|
||||
/**
|
||||
* 分页查询${table.comment!}
|
||||
*/
|
||||
export async function page${entity}(params: ${entity}Param) {
|
||||
const res = await request.get<ApiResult<PageResult<${entity}>>>(
|
||||
'/${package.ModuleName}/${controllerMappingHyphen}/page',
|
||||
{
|
||||
params
|
||||
}
|
||||
);
|
||||
if (res.data.code === 0) {
|
||||
return res.data.data;
|
||||
}
|
||||
return Promise.reject(new Error(res.data.message));
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询${table.comment!}列表
|
||||
*/
|
||||
export async function list${entity}(params?: ${entity}Param) {
|
||||
const res = await request.get<ApiResult<${entity}[]>>(
|
||||
'/${package.ModuleName}/${controllerMappingHyphen}',
|
||||
{
|
||||
params
|
||||
}
|
||||
);
|
||||
if (res.data.code === 0 && res.data.data) {
|
||||
return res.data.data;
|
||||
}
|
||||
return Promise.reject(new Error(res.data.message));
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加${table.comment!}
|
||||
*/
|
||||
export async function add${entity}(data: ${entity}) {
|
||||
const res = await request.post<ApiResult<unknown>>(
|
||||
'/${package.ModuleName}/${controllerMappingHyphen}',
|
||||
data
|
||||
);
|
||||
if (res.data.code === 0) {
|
||||
return res.data.message;
|
||||
}
|
||||
return Promise.reject(new Error(res.data.message));
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改${table.comment!}
|
||||
*/
|
||||
export async function update${entity}(data: ${entity}) {
|
||||
const res = await request.put<ApiResult<unknown>>(
|
||||
'/${package.ModuleName}/${controllerMappingHyphen}',
|
||||
data
|
||||
);
|
||||
if (res.data.code === 0) {
|
||||
return res.data.message;
|
||||
}
|
||||
return Promise.reject(new Error(res.data.message));
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除${table.comment!}
|
||||
*/
|
||||
export async function remove${entity}(id?: number) {
|
||||
const res = await request.delete<ApiResult<unknown>>(
|
||||
'/${package.ModuleName}/${controllerMappingHyphen}/' + id
|
||||
);
|
||||
if (res.data.code === 0) {
|
||||
return res.data.message;
|
||||
}
|
||||
return Promise.reject(new Error(res.data.message));
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量删除${table.comment!}
|
||||
*/
|
||||
export async function removeBatch${entity}(data: (number | undefined)[]) {
|
||||
const res = await request.delete<ApiResult<unknown>>(
|
||||
'/${package.ModuleName}/${controllerMappingHyphen}/batch',
|
||||
{
|
||||
data
|
||||
}
|
||||
);
|
||||
if (res.data.code === 0) {
|
||||
return res.data.message;
|
||||
}
|
||||
return Promise.reject(new Error(res.data.message));
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据id查询${table.comment!}
|
||||
*/
|
||||
export async function get${entity}(id: number) {
|
||||
const res = await request.get<ApiResult<${entity}>>(
|
||||
'/${package.ModuleName}/${controllerMappingHyphen}/' + id
|
||||
);
|
||||
if (res.data.code === 0 && res.data.data) {
|
||||
return res.data.data;
|
||||
}
|
||||
return Promise.reject(new Error(res.data.message));
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
import request from '@/utils/request';
|
||||
import type { ApiResult, PageResult } from '@/api/index';
|
||||
import type { ${entity}, ${entity}Param } from './model';
|
||||
|
||||
/**
|
||||
* 分页查询${table.comment!}
|
||||
*/
|
||||
export async function page${entity}(params: ${entity}Param) {
|
||||
const res = await request.get<ApiResult<PageResult<${entity}>>>(
|
||||
'/${package.ModuleName}/${controllerMappingHyphen}/page',
|
||||
params
|
||||
);
|
||||
if (res.code === 0) {
|
||||
return res.data;
|
||||
}
|
||||
return Promise.reject(new Error(res.message));
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询${table.comment!}列表
|
||||
*/
|
||||
export async function list${entity}(params?: ${entity}Param) {
|
||||
const res = await request.get<ApiResult<${entity}[]>>(
|
||||
'/${package.ModuleName}/${controllerMappingHyphen}',
|
||||
params
|
||||
);
|
||||
if (res.code === 0 && res.data) {
|
||||
return res.data;
|
||||
}
|
||||
return Promise.reject(new Error(res.message));
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加${table.comment!}
|
||||
*/
|
||||
export async function add${entity}(data: ${entity}) {
|
||||
const res = await request.post<ApiResult<unknown>>(
|
||||
'/${package.ModuleName}/${controllerMappingHyphen}',
|
||||
data
|
||||
);
|
||||
if (res.code === 0) {
|
||||
return res.message;
|
||||
}
|
||||
return Promise.reject(new Error(res.message));
|
||||
}
|
||||
|
||||
/**
|
||||
* 修改${table.comment!}
|
||||
*/
|
||||
export async function update${entity}(data: ${entity}) {
|
||||
const res = await request.put<ApiResult<unknown>>(
|
||||
'/${package.ModuleName}/${controllerMappingHyphen}',
|
||||
data
|
||||
);
|
||||
if (res.code === 0) {
|
||||
return res.message;
|
||||
}
|
||||
return Promise.reject(new Error(res.message));
|
||||
}
|
||||
|
||||
/**
|
||||
* 删除${table.comment!}
|
||||
*/
|
||||
export async function remove${entity}(id?: number) {
|
||||
const res = await request.del<ApiResult<unknown>>(
|
||||
'/${package.ModuleName}/${controllerMappingHyphen}/' + id
|
||||
);
|
||||
if (res.code === 0) {
|
||||
return res.message;
|
||||
}
|
||||
return Promise.reject(new Error(res.message));
|
||||
}
|
||||
|
||||
/**
|
||||
* 批量删除${table.comment!}
|
||||
*/
|
||||
export async function removeBatch${entity}(data: (number | undefined)[]) {
|
||||
const res = await request.del<ApiResult<unknown>>(
|
||||
'/${package.ModuleName}/${controllerMappingHyphen}/batch',
|
||||
{
|
||||
data
|
||||
}
|
||||
);
|
||||
if (res.code === 0) {
|
||||
return res.message;
|
||||
}
|
||||
return Promise.reject(new Error(res.message));
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据id查询${table.comment!}
|
||||
*/
|
||||
export async function get${entity}(id: number) {
|
||||
const res = await request.get<ApiResult<${entity}>>(
|
||||
'/${package.ModuleName}/${controllerMappingHyphen}/' + id
|
||||
);
|
||||
if (res.code === 0 && res.data) {
|
||||
return res.data;
|
||||
}
|
||||
return Promise.reject(new Error(res.message));
|
||||
}
|
||||
171
src/test/java/com/gxwebsoft/generator/templates/index.tsx.btl
Normal file
171
src/test/java/com/gxwebsoft/generator/templates/index.tsx.btl
Normal file
@@ -0,0 +1,171 @@
|
||||
import {useState} from "react";
|
||||
import Taro, {useDidShow} from '@tarojs/taro'
|
||||
import {Button, Cell, CellGroup, Space, Empty, ConfigProvider, Divider} from '@nutui/nutui-react-taro'
|
||||
import {Dongdong, ArrowRight, CheckNormal, Checked} from '@nutui/icons-react-taro'
|
||||
import {View} from '@tarojs/components'
|
||||
import {${entity}} from "@/api/${package.ModuleName}/${table.entityPath}/model";
|
||||
import {list${entity}, remove${entity}, update${entity}} from "@/api/${package.ModuleName}/${table.entityPath}";
|
||||
|
||||
const ${entity}List = () => {
|
||||
const [list, setList] = useState<${entity}[]>([])
|
||||
<% var hasIsDefaultField = false; %>
|
||||
<% for(field in table.fields){ %>
|
||||
<% if(field.propertyName == 'isDefault'){ %>
|
||||
<% hasIsDefaultField = true; %>
|
||||
<% } %>
|
||||
<% } %>
|
||||
<% if(hasIsDefaultField){ %>
|
||||
const [selectedItem, setSelectedItem] = useState<${entity}>()
|
||||
<% } %>
|
||||
|
||||
const reload = () => {
|
||||
list${entity}({
|
||||
// 添加查询条件
|
||||
})
|
||||
.then(data => {
|
||||
setList(data || [])
|
||||
<% if(hasIsDefaultField){ %>
|
||||
// 设置默认选中项
|
||||
setSelectedItem(data.find(item => item.isDefault))
|
||||
<% } %>
|
||||
})
|
||||
.catch(() => {
|
||||
Taro.showToast({
|
||||
title: '获取数据失败',
|
||||
icon: 'error'
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
<% if(hasIsDefaultField){ %>
|
||||
const onDefault = async (item: ${entity}) => {
|
||||
if (selectedItem) {
|
||||
await update${entity}({
|
||||
...selectedItem,
|
||||
isDefault: false
|
||||
})
|
||||
}
|
||||
await update${entity}({
|
||||
<% var primaryKey = 'id'; %>
|
||||
<% for(field in table.fields){ %>
|
||||
<% if(field.keyFlag){ %>
|
||||
<% primaryKey = field.propertyName; %>
|
||||
<% } %>
|
||||
<% } %>
|
||||
${primaryKey}: item.${primaryKey},
|
||||
isDefault: true
|
||||
})
|
||||
Taro.showToast({
|
||||
title: '设置成功',
|
||||
icon: 'success'
|
||||
});
|
||||
reload();
|
||||
}
|
||||
|
||||
const selectItem = async (item: ${entity}) => {
|
||||
if (selectedItem) {
|
||||
await update${entity}({
|
||||
...selectedItem,
|
||||
isDefault: false
|
||||
})
|
||||
}
|
||||
await update${entity}({
|
||||
${primaryKey}: item.${primaryKey},
|
||||
isDefault: true
|
||||
})
|
||||
setTimeout(() => {
|
||||
Taro.navigateBack()
|
||||
},500)
|
||||
}
|
||||
<% } %>
|
||||
|
||||
const onDel = async (id?: number) => {
|
||||
await remove${entity}(id)
|
||||
Taro.showToast({
|
||||
title: '删除成功',
|
||||
icon: 'success'
|
||||
});
|
||||
reload();
|
||||
}
|
||||
|
||||
useDidShow(() => {
|
||||
reload()
|
||||
});
|
||||
|
||||
if (list.length == 0) {
|
||||
return (
|
||||
<ConfigProvider>
|
||||
<div className={'h-full flex flex-col justify-center items-center'} style={{
|
||||
height: 'calc(100vh - 300px)',
|
||||
}}>
|
||||
<Empty
|
||||
style={{
|
||||
backgroundColor: 'transparent'
|
||||
}}
|
||||
description="暂无数据"
|
||||
/>
|
||||
<Space>
|
||||
<Button onClick={() => Taro.navigateTo({url: '/${package.ModuleName}/${table.entityPath}/add'})}>新增${table.comment!'数据'}</Button>
|
||||
</Space>
|
||||
</div>
|
||||
</ConfigProvider>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
{list.map((item, _) => (
|
||||
<Cell.Group key={item.${primaryKey}}>
|
||||
<% if(hasIsDefaultField){ %>
|
||||
<Cell className={'flex flex-col gap-1'} onClick={() => selectItem(item)}>
|
||||
<% } else { %>
|
||||
<Cell className={'flex flex-col gap-1'}>
|
||||
<% } %>
|
||||
<View>
|
||||
<% var displayFields = []; %>
|
||||
<% for(field in table.fields){ %>
|
||||
<% if(field.propertyName != 'id' && field.propertyName != 'createTime' && field.propertyName != 'updateTime' && field.propertyName != 'isDefault'){ %>
|
||||
<% displayFields.add(field); %>
|
||||
<% if(displayFields.size() >= 2) break; %>
|
||||
<% } %>
|
||||
<% } %>
|
||||
<% if(displayFields.size() > 0){ %>
|
||||
<View className={'font-medium text-sm'}>{item.${displayFields[0].propertyName}}</View>
|
||||
<% } %>
|
||||
</View>
|
||||
<% if(displayFields.size() > 1){ %>
|
||||
<View className={'text-xs'}>
|
||||
{item.${displayFields[1].propertyName}}
|
||||
</View>
|
||||
<% } %>
|
||||
</Cell>
|
||||
<Cell
|
||||
align="center"
|
||||
<% if(hasIsDefaultField){ %>
|
||||
title={
|
||||
<View className={'flex items-center gap-1'} onClick={() => onDefault(item)}>
|
||||
{item.isDefault ? <Checked className={'text-green-600'} size={16}/> : <CheckNormal size={16}/>}
|
||||
<View className={'text-gray-400'}>默认选项</View>
|
||||
</View>
|
||||
}
|
||||
<% } %>
|
||||
extra={
|
||||
<>
|
||||
<View className={'text-gray-400'} onClick={() => onDel(item.${primaryKey})}>
|
||||
删除
|
||||
</View>
|
||||
<Divider direction={'vertical'}/>
|
||||
<View className={'text-gray-400'}
|
||||
onClick={() => Taro.navigateTo({url: '/${package.ModuleName}/${table.entityPath}/add?id=' + item.${primaryKey}})}>
|
||||
修改
|
||||
</View>
|
||||
</>
|
||||
}
|
||||
/>
|
||||
</Cell.Group>
|
||||
))}
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
export default ${entity}List;
|
||||
242
src/test/java/com/gxwebsoft/generator/templates/index.vue.btl
Normal file
242
src/test/java/com/gxwebsoft/generator/templates/index.vue.btl
Normal file
@@ -0,0 +1,242 @@
|
||||
<template>
|
||||
<a-page-header :title="getPageTitle()" @back="() => $router.go(-1)">
|
||||
<a-card :bordered="false" :body-style="{ padding: '16px' }">
|
||||
<ele-pro-table
|
||||
ref="tableRef"
|
||||
row-key="${table.entityPath}Id"
|
||||
:columns="columns"
|
||||
:datasource="datasource"
|
||||
:customRow="customRow"
|
||||
tool-class="ele-toolbar-form"
|
||||
class="sys-org-table"
|
||||
>
|
||||
<template #toolbar>
|
||||
<search
|
||||
@search="reload"
|
||||
:selection="selection"
|
||||
@add="openEdit"
|
||||
@remove="removeBatch"
|
||||
@batchMove="openMove"
|
||||
/>
|
||||
</template>
|
||||
<template #bodyCell="{ column, record }">
|
||||
<template v-if="column.key === 'image'">
|
||||
<a-image :src="record.image" :width="50" />
|
||||
</template>
|
||||
<template v-if="column.key === 'status'">
|
||||
<a-tag v-if="record.status === 0" color="green">显示</a-tag>
|
||||
<a-tag v-if="record.status === 1" color="red">隐藏</a-tag>
|
||||
</template>
|
||||
<template v-if="column.key === 'action'">
|
||||
<a-space>
|
||||
<a @click="openEdit(record)">修改</a>
|
||||
<a-divider type="vertical" />
|
||||
<a-popconfirm
|
||||
title="确定要删除此记录吗?"
|
||||
@confirm="remove(record)"
|
||||
>
|
||||
<a class="ele-text-danger">删除</a>
|
||||
</a-popconfirm>
|
||||
</a-space>
|
||||
</template>
|
||||
</template>
|
||||
</ele-pro-table>
|
||||
</a-card>
|
||||
|
||||
<!-- 编辑弹窗 -->
|
||||
<${entity}Edit v-model:visible="showEdit" :data="current" @done="reload" />
|
||||
</a-page-header>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { createVNode, ref, computed } from 'vue';
|
||||
import { message, Modal } from 'ant-design-vue';
|
||||
import { ExclamationCircleOutlined } from '@ant-design/icons-vue';
|
||||
import type { EleProTable } from 'ele-admin-pro';
|
||||
import { toDateString } from 'ele-admin-pro';
|
||||
import type {
|
||||
DatasourceFunction,
|
||||
ColumnItem
|
||||
} from 'ele-admin-pro/es/ele-pro-table/types';
|
||||
import Search from './components/search.vue';
|
||||
import {getPageTitle} from '@/utils/common';
|
||||
import ${entity}Edit from './components/${table.entityPath}Edit.vue';
|
||||
import { page${entity}, remove${entity}, removeBatch${entity} } from '@/api/${package.ModuleName}/${table.entityPath}';
|
||||
import type { ${entity}, ${entity}Param } from '@/api/${package.ModuleName}/${table.entityPath}/model';
|
||||
|
||||
// 表格实例
|
||||
const tableRef = ref<InstanceType<typeof EleProTable> | null>(null);
|
||||
|
||||
// 表格选中数据
|
||||
const selection = ref<${entity}[]>([]);
|
||||
// 当前编辑数据
|
||||
const current = ref<${entity} | null>(null);
|
||||
// 是否显示编辑弹窗
|
||||
const showEdit = ref(false);
|
||||
// 是否显示批量移动弹窗
|
||||
const showMove = ref(false);
|
||||
// 加载状态
|
||||
const loading = ref(true);
|
||||
|
||||
// 表格数据源
|
||||
const datasource: DatasourceFunction = ({
|
||||
page,
|
||||
limit,
|
||||
where,
|
||||
orders,
|
||||
filters
|
||||
}) => {
|
||||
if (filters) {
|
||||
where.status = filters.status;
|
||||
}
|
||||
return page${entity}({
|
||||
...where,
|
||||
...orders,
|
||||
page,
|
||||
limit
|
||||
});
|
||||
};
|
||||
|
||||
// 完整的列配置(包含所有字段)
|
||||
const allColumns = ref<ColumnItem[]>([
|
||||
<% for(field in table.fields) { %>
|
||||
<% if(field.propertyName != 'tenantId'){ %>
|
||||
{
|
||||
title: '${field.comment!field.propertyName}',
|
||||
dataIndex: '${field.propertyName}',
|
||||
key: '${field.propertyName}',
|
||||
<% if(field.keyFlag){ %>
|
||||
width: 90,
|
||||
<% } else if(field.propertyName == 'createTime' || field.propertyName == 'updateTime'){ %>
|
||||
width: 200,
|
||||
align: 'center',
|
||||
sorter: true,
|
||||
ellipsis: true,
|
||||
customRender: ({ text }) => toDateString(text, 'yyyy-MM-dd HH:mm:ss')
|
||||
<% } else if(field.propertyType == 'String'){ %>
|
||||
ellipsis: true
|
||||
<% } else if(field.propertyName == 'status'){ %>
|
||||
width: 120
|
||||
<% } else { %>
|
||||
width: 120
|
||||
<% } %>
|
||||
},
|
||||
<% } %>
|
||||
<% } %>
|
||||
{
|
||||
title: '操作',
|
||||
key: 'action',
|
||||
width: 180,
|
||||
fixed: 'right',
|
||||
align: 'center',
|
||||
hideInSetting: true
|
||||
}
|
||||
]);
|
||||
|
||||
// 默认显示的核心列(最多5个主要字段)
|
||||
const defaultVisibleColumns = [
|
||||
<% var count = 0; %>
|
||||
<% for(field in table.fields) { %>
|
||||
<% if(field.keyFlag || field.propertyName == 'name' || field.propertyName == 'title' || field.propertyName == 'status' || field.propertyName == 'createTime'){ %>
|
||||
'${field.propertyName}',
|
||||
<% count = count + 1; %>
|
||||
<% if(count >= 5) break; %>
|
||||
<% } %>
|
||||
<% } %>
|
||||
'action'
|
||||
];
|
||||
|
||||
// 根据默认可见列过滤显示的列
|
||||
const columns = computed(() => {
|
||||
return allColumns.value.filter(col =>
|
||||
defaultVisibleColumns.includes(col.dataIndex) || col.key === 'action'
|
||||
);
|
||||
});
|
||||
|
||||
/* 搜索 */
|
||||
const reload = (where?: ${entity}Param) => {
|
||||
selection.value = [];
|
||||
tableRef?.value?.reload({ where: where });
|
||||
};
|
||||
|
||||
/* 打开编辑弹窗 */
|
||||
const openEdit = (row?: ${entity}) => {
|
||||
current.value = row ?? null;
|
||||
showEdit.value = true;
|
||||
};
|
||||
|
||||
/* 打开批量移动弹窗 */
|
||||
const openMove = () => {
|
||||
showMove.value = true;
|
||||
};
|
||||
|
||||
/* 删除单个 */
|
||||
const remove = (row: ${entity}) => {
|
||||
const hide = message.loading('请求中..', 0);
|
||||
remove${entity}(row.${table.entityPath}Id)
|
||||
.then((msg) => {
|
||||
hide();
|
||||
message.success(msg);
|
||||
reload();
|
||||
})
|
||||
.catch((e) => {
|
||||
hide();
|
||||
message.error(e.message);
|
||||
});
|
||||
};
|
||||
|
||||
/* 批量删除 */
|
||||
const removeBatch = () => {
|
||||
if (!selection.value.length) {
|
||||
message.error('请至少选择一条数据');
|
||||
return;
|
||||
}
|
||||
Modal.confirm({
|
||||
title: '提示',
|
||||
content: '确定要删除选中的记录吗?',
|
||||
icon: createVNode(ExclamationCircleOutlined),
|
||||
maskClosable: true,
|
||||
onOk: () => {
|
||||
const hide = message.loading('请求中..', 0);
|
||||
removeBatch${entity}(selection.value.map((d) => d.${table.entityPath}Id))
|
||||
.then((msg) => {
|
||||
hide();
|
||||
message.success(msg);
|
||||
reload();
|
||||
})
|
||||
.catch((e) => {
|
||||
hide();
|
||||
message.error(e.message);
|
||||
});
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
/* 查询 */
|
||||
const query = () => {
|
||||
loading.value = true;
|
||||
};
|
||||
|
||||
/* 自定义行属性 */
|
||||
const customRow = (record: ${entity}) => {
|
||||
return {
|
||||
// 行点击事件
|
||||
onClick: () => {
|
||||
// console.log(record);
|
||||
},
|
||||
// 行双击事件
|
||||
onDblclick: () => {
|
||||
openEdit(record);
|
||||
}
|
||||
};
|
||||
};
|
||||
query();
|
||||
</script>
|
||||
|
||||
<script lang="ts">
|
||||
export default {
|
||||
name: '${entity}'
|
||||
};
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped></style>
|
||||
@@ -0,0 +1,41 @@
|
||||
package ${package.Mapper};
|
||||
|
||||
import ${superMapperClassPackage};
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import ${package.Entity}.${entity};
|
||||
import ${cfg.packageName!}.${package.ModuleName}.param.${entity}Param;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* ${table.comment!}Mapper
|
||||
*
|
||||
* @author ${author}
|
||||
* @since ${date(), 'yyyy-MM-dd HH:mm:ss'}
|
||||
*/
|
||||
<% if(kotlin){ %>
|
||||
interface ${table.mapperName} : ${superMapperClass}<${entity}>
|
||||
<% }else{ %>
|
||||
public interface ${table.mapperName} extends ${superMapperClass}<${entity}> {
|
||||
|
||||
/**
|
||||
* 分页查询
|
||||
*
|
||||
* @param page 分页对象
|
||||
* @param param 查询参数
|
||||
* @return List<${entity}>
|
||||
*/
|
||||
List<${entity}> selectPageRel(@Param("page") IPage<${entity}> page,
|
||||
@Param("param") ${entity}Param param);
|
||||
|
||||
/**
|
||||
* 查询全部
|
||||
*
|
||||
* @param param 查询参数
|
||||
* @return List<User>
|
||||
*/
|
||||
List<${entity}> selectListRel(@Param("param") ${entity}Param param);
|
||||
|
||||
}
|
||||
<% } %>
|
||||
100
src/test/java/com/gxwebsoft/generator/templates/mapper.xml.btl
Normal file
100
src/test/java/com/gxwebsoft/generator/templates/mapper.xml.btl
Normal file
@@ -0,0 +1,100 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="${package.Mapper}.${table.mapperName}">
|
||||
<% if(enableCache) { %>
|
||||
|
||||
<!-- 开启二级缓存 -->
|
||||
<cache type="org.mybatis.caches.ehcache.LoggingEhcache"/>
|
||||
<% } %>
|
||||
<% if(baseResultMap) { %>
|
||||
|
||||
<!-- 通用查询映射结果 -->
|
||||
<resultMap id="BaseResultMap" type="${package.Entity}.${entity}">
|
||||
<% /** 生成主键排在第一位 **/ %>
|
||||
<% for(field in table.fields) { %>
|
||||
<% if(field.keyFlag){ %>
|
||||
<id column="${field.name}" property="${field.propertyName}" />
|
||||
<% } %>
|
||||
<% } %>
|
||||
<% /** 生成公共字段 **/ %>
|
||||
<% for(field in table.commonFields) { %>
|
||||
<result column="${field.name}" property="${field.propertyName}" />
|
||||
<% } %>
|
||||
<% /** 生成普通字段 **/ %>
|
||||
<% for(field in table.fields) { %>
|
||||
<% if(!field.keyFlag) { %>
|
||||
<result column="${field.name}" property="${field.propertyName}" />
|
||||
<% } %>
|
||||
<% } %>
|
||||
</resultMap>
|
||||
<% } %>
|
||||
<% if(baseColumnList) { %>
|
||||
|
||||
<!-- 通用查询结果列 -->
|
||||
<sql id="Base_Column_List">
|
||||
<% for(field in table.commonFields) { %>
|
||||
${field.columnName},
|
||||
<% } %>
|
||||
${table.fieldNames}
|
||||
</sql>
|
||||
<% } %>
|
||||
|
||||
<!-- 关联查询sql -->
|
||||
<sql id="selectSql">
|
||||
SELECT a.*
|
||||
FROM ${table.name} a
|
||||
<where>
|
||||
<% for(field in table.fields) { %>
|
||||
<% if(field.keyFlag) { %>
|
||||
<% /** 主键字段 **/ %>
|
||||
<if test="param.${field.propertyName} != null">
|
||||
AND a.${field.name} = #{param.${field.propertyName}}
|
||||
</if>
|
||||
<% } else if(field.name == logicDeleteFieldName) { %>
|
||||
<% /** 逻辑删除字段 **/ %>
|
||||
<if test="param.deleted != null">
|
||||
AND a.deleted = #{param.deleted}
|
||||
</if>
|
||||
<if test="param.deleted == null">
|
||||
AND a.deleted = 0
|
||||
</if>
|
||||
<% } else if(field.name == 'create_time') { %>
|
||||
<% /** 创建时间字段 **/ %>
|
||||
<if test="param.createTimeStart != null">
|
||||
AND a.create_time >= #{param.createTimeStart}
|
||||
</if>
|
||||
<if test="param.createTimeEnd != null">
|
||||
AND a.create_time <= #{param.createTimeEnd}
|
||||
</if>
|
||||
<% } else if(array.contain(cfg.paramExcludeFields, field.name)) { %>
|
||||
<% /** 排除的字段 **/ %>
|
||||
<% } else if(array.contain(cfg.paramEqType, field.propertyType)) { %>
|
||||
<% /** 使用EQ的字段 **/ %>
|
||||
<if test="param.${field.propertyName} != null">
|
||||
AND a.${field.name} = #{param.${field.propertyName}}
|
||||
</if>
|
||||
<% } else { %>
|
||||
<% /** 其它类型使用LIKE **/ %>
|
||||
<if test="param.${field.propertyName} != null">
|
||||
AND a.${field.name} LIKE CONCAT('%', #{param.${field.propertyName}}, '%')
|
||||
</if>
|
||||
<% } %>
|
||||
<% } %>
|
||||
<if test="param.keywords != null">
|
||||
AND (a.comments LIKE CONCAT('%', #{param.keywords}, '%')
|
||||
)
|
||||
</if>
|
||||
</where>
|
||||
</sql>
|
||||
|
||||
<!-- 分页查询 -->
|
||||
<select id="selectPageRel" resultType="${package.Entity}.${entity}">
|
||||
<include refid="selectSql"></include>
|
||||
</select>
|
||||
|
||||
<!-- 查询全部 -->
|
||||
<select id="selectListRel" resultType="${package.Entity}.${entity}">
|
||||
<include refid="selectSql"></include>
|
||||
</select>
|
||||
|
||||
</mapper>
|
||||
43
src/test/java/com/gxwebsoft/generator/templates/model.ts.btl
Normal file
43
src/test/java/com/gxwebsoft/generator/templates/model.ts.btl
Normal file
@@ -0,0 +1,43 @@
|
||||
import type { PageParam } from '@/api';
|
||||
|
||||
/**
|
||||
* ${table.comment!}
|
||||
*/
|
||||
export interface ${entity} {
|
||||
<% /** -----------BEGIN 字段循环遍历----------- **/ %>
|
||||
<% for(field in table.fields) { %>
|
||||
<%
|
||||
var keyPropertyName;
|
||||
if(field.keyFlag) {
|
||||
keyPropertyName = field.propertyName;
|
||||
}
|
||||
%>
|
||||
<% /* 主键 */ %>
|
||||
<% if(field.keyFlag) { %>
|
||||
<% /* 普通字段 */ %>
|
||||
<% } else if(isNotEmpty(field.fill)) { %>
|
||||
<% if(field.convert){ %>
|
||||
@TableField(value = "${field.annotationColumnName}", fill = FieldFill.${field.fill})
|
||||
<% }else{ %>
|
||||
@TableField(fill = FieldFill.${field.fill})
|
||||
<% } %>
|
||||
<% } else if(field.convert) { %>
|
||||
@TableField("${field.annotationColumnName}")
|
||||
<% } %>
|
||||
// ${field.comment}
|
||||
${field.propertyName}?: <% if(field.propertyType == 'Integer') { %>number<% }else{ %>string<% } %>;
|
||||
<% } %>
|
||||
<% /** -----------END 字段循环遍历----------- **/ %>
|
||||
}
|
||||
|
||||
/**
|
||||
* ${table.comment!}搜索条件
|
||||
*/
|
||||
export interface ${entity}Param extends PageParam {
|
||||
<% for(field in table.fields) { %>
|
||||
<% if(field.keyFlag) { %>
|
||||
${field.propertyName}?: number;
|
||||
<% } %>
|
||||
<% } %>
|
||||
keywords?: string;
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import type { PageParam } from '@/api/index';
|
||||
|
||||
/**
|
||||
* ${table.comment!}
|
||||
*/
|
||||
export interface ${entity} {
|
||||
<% /** -----------BEGIN 字段循环遍历----------- **/ %>
|
||||
<% for(field in table.fields) { %>
|
||||
<%
|
||||
var keyPropertyName;
|
||||
if(field.keyFlag) {
|
||||
keyPropertyName = field.propertyName;
|
||||
}
|
||||
%>
|
||||
<% /* 主键 */ %>
|
||||
<% if(field.keyFlag) { %>
|
||||
<% /* 普通字段 */ %>
|
||||
<% } else if(isNotEmpty(field.fill)) { %>
|
||||
<% if(field.convert){ %>
|
||||
@TableField(value = "${field.annotationColumnName}", fill = FieldFill.${field.fill})
|
||||
<% }else{ %>
|
||||
@TableField(fill = FieldFill.${field.fill})
|
||||
<% } %>
|
||||
<% } else if(field.convert) { %>
|
||||
@TableField("${field.annotationColumnName}")
|
||||
<% } %>
|
||||
// ${field.comment}
|
||||
${field.propertyName}?: <% if(field.propertyType == 'Integer') { %>number<% }else{ %>string<% } %>;
|
||||
<% } %>
|
||||
<% /** -----------END 字段循环遍历----------- **/ %>
|
||||
}
|
||||
|
||||
/**
|
||||
* ${table.comment!}搜索条件
|
||||
*/
|
||||
export interface ${entity}Param extends PageParam {
|
||||
<% for(field in table.fields) { %>
|
||||
<% if(field.keyFlag) { %>
|
||||
${field.propertyName}?: number;
|
||||
<% } %>
|
||||
<% } %>
|
||||
keywords?: string;
|
||||
}
|
||||
146
src/test/java/com/gxwebsoft/generator/templates/param.java.btl
Normal file
146
src/test/java/com/gxwebsoft/generator/templates/param.java.btl
Normal file
@@ -0,0 +1,146 @@
|
||||
package ${cfg.packageName!}.${package.ModuleName}.param;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import ${cfg.packageName!}.common.core.annotation.QueryField;
|
||||
import ${cfg.packageName!}.common.core.annotation.QueryType;
|
||||
import ${cfg.packageName!}.common.core.web.BaseParam;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
<% if(swagger2) { %>
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
<% } %>
|
||||
<% if(entityLombokModel) { %>
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
<% if(chainModel) { %>
|
||||
import lombok.experimental.Accessors;
|
||||
<% } %>
|
||||
<% } %>
|
||||
|
||||
/**
|
||||
* ${table.comment!}查询参数
|
||||
*
|
||||
* @author ${author}
|
||||
* @since ${date(), 'yyyy-MM-dd HH:mm:ss'}
|
||||
*/
|
||||
<% if(entityLombokModel) { %>
|
||||
@Data
|
||||
<% if(isNotEmpty(superEntityClass)) { %>
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
<% } else { %>
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
<% } %>
|
||||
<% if(chainModel) { %>
|
||||
@Accessors(chain = true)
|
||||
<% } %>
|
||||
<% } %>
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
<% if(swagger2) { %>
|
||||
@Schema(name = "${entity}Param对象", description = "${table.comment!''}查询参数")
|
||||
<% } %>
|
||||
public class ${entity}Param extends BaseParam {
|
||||
<% if(entitySerialVersionUID) { %>
|
||||
private static final long serialVersionUID = 1L;
|
||||
<% } %>
|
||||
<% /** -----------BEGIN 字段循环遍历----------- **/ %>
|
||||
<% for(field in table.fields) { %>
|
||||
<%
|
||||
var keyPropertyName;
|
||||
if(field.keyFlag) {
|
||||
keyPropertyName = field.propertyName;
|
||||
}
|
||||
// 排除的字段
|
||||
if(array.contain(cfg.paramExcludeFields, field.name)) {
|
||||
continue;
|
||||
}
|
||||
%>
|
||||
|
||||
<% if(isNotEmpty(field.comment)) { %>
|
||||
<% if(swagger2) { %>
|
||||
@Schema(description = "${field.comment}")
|
||||
<% }else{ %>
|
||||
/**
|
||||
* ${field.comment}
|
||||
*/
|
||||
<% } %>
|
||||
<% } %>
|
||||
<% /* 主键 */ %>
|
||||
<% if(field.keyFlag) { %>
|
||||
@QueryField(type = QueryType.EQ)
|
||||
<% /* 使用EQ的字段 */ %>
|
||||
<% } else if(array.contain(cfg.paramEqType, field.propertyType)) { %>
|
||||
@QueryField(type = QueryType.EQ)
|
||||
<% } %>
|
||||
<% /* 使用String类型的字段 */ %>
|
||||
<% if(array.contain(cfg.paramToStringType, field.propertyType)) { %>
|
||||
private String ${field.propertyName};
|
||||
<% } else { %>
|
||||
<% /* 普通字段 */ %>
|
||||
private ${field.propertyType} ${field.propertyName};
|
||||
<% } %>
|
||||
<% } %>
|
||||
<% /** -----------END 字段循环遍历----------- **/ %>
|
||||
|
||||
<% if(!entityLombokModel) { %>
|
||||
<% for(field in table.fields) { %>
|
||||
<%
|
||||
var getprefix = '';
|
||||
if(field.propertyType == 'boolean') {
|
||||
getprefix = 'is';
|
||||
} else {
|
||||
getprefix = 'get';
|
||||
}
|
||||
// 排除的字段
|
||||
if(array.contain(cfg.paramExcludeFields, field.name)) {
|
||||
continue;
|
||||
}
|
||||
%>
|
||||
<% if(array.contain(cfg.paramToStringType, field.propertyType)) { %>
|
||||
public String ${getprefix}${field.capitalName}() {
|
||||
<% } else { %>
|
||||
public ${field.propertyType} ${getprefix}${field.capitalName}() {
|
||||
<% } %>
|
||||
return ${field.propertyName};
|
||||
}
|
||||
|
||||
<% if(chainModel) { %>
|
||||
<% if(array.contain(cfg.paramToStringType, field.propertyType)) { %>
|
||||
public ${entity} set${field.capitalName}(String ${field.propertyName}) {
|
||||
<% } else { %>
|
||||
public ${entity} set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
|
||||
<% } %>
|
||||
<% } else { %>
|
||||
<% if(array.contain(cfg.paramToStringType, field.propertyType)) { %>
|
||||
public void set${field.capitalName}(String ${field.propertyName}) {
|
||||
<% } else { %>
|
||||
public void set${field.capitalName}(${field.propertyType} ${field.propertyName}) {
|
||||
<% } %>
|
||||
<% } %>
|
||||
this.${field.propertyName} = ${field.propertyName};
|
||||
<% if(chainModel){ %>
|
||||
return this;
|
||||
<% } %>
|
||||
}
|
||||
|
||||
<% } %>
|
||||
<% } %>
|
||||
<% if(!entityLombokModel) { %>
|
||||
@Override
|
||||
public String toString() {
|
||||
return "${entity}{" +
|
||||
<% for(field in table.fields) { %>
|
||||
<%
|
||||
// 排除的字段
|
||||
if(array.contain(cfg.paramExcludeFields, field.name)) {
|
||||
continue;
|
||||
}
|
||||
%>
|
||||
<% if(fieldLP.index == 0) { %>
|
||||
"${field.propertyName}=" + ${field.propertyName} +
|
||||
<% } else { %>
|
||||
", ${field.propertyName}=" + ${field.propertyName} +
|
||||
<% } %>
|
||||
<% } %>
|
||||
"}";
|
||||
}
|
||||
<% } %>
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
<%
|
||||
var idPropertyName, idComment;
|
||||
for(field in table.fields) {
|
||||
if(field.keyFlag) {
|
||||
idPropertyName = field.propertyName;
|
||||
idComment = field.comment;
|
||||
}
|
||||
}
|
||||
%>
|
||||
package ${package.Service};
|
||||
|
||||
import ${superServiceClassPackage};
|
||||
import ${cfg.packageName!}.common.core.web.PageResult;
|
||||
import ${package.Entity}.${entity};
|
||||
import ${cfg.packageName!}.${package.ModuleName}.param.${entity}Param;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* ${table.comment!}Service
|
||||
*
|
||||
* @author ${author}
|
||||
* @since ${date(), 'yyyy-MM-dd HH:mm:ss'}
|
||||
*/
|
||||
<% if(kotlin){ %>
|
||||
interface ${table.serviceName} : ${superServiceClass}<${entity}>
|
||||
<% }else{ %>
|
||||
public interface ${table.serviceName} extends ${superServiceClass}<${entity}> {
|
||||
|
||||
/**
|
||||
* 分页关联查询
|
||||
*
|
||||
* @param param 查询参数
|
||||
* @return PageResult<${entity}>
|
||||
*/
|
||||
PageResult<${entity}> pageRel(${entity}Param param);
|
||||
|
||||
/**
|
||||
* 关联查询全部
|
||||
*
|
||||
* @param param 查询参数
|
||||
* @return List<${entity}>
|
||||
*/
|
||||
List<${entity}> listRel(${entity}Param param);
|
||||
|
||||
/**
|
||||
* 根据id查询
|
||||
*
|
||||
* @param ${idPropertyName!} ${idComment!}
|
||||
* @return ${entity}
|
||||
*/
|
||||
${entity} getByIdRel(Integer ${idPropertyName!});
|
||||
|
||||
}
|
||||
<% } %>
|
||||
@@ -0,0 +1,62 @@
|
||||
<%
|
||||
var idPropertyName, idCapitalName;
|
||||
for(field in table.fields) {
|
||||
if(field.keyFlag) {
|
||||
idPropertyName = field.propertyName;
|
||||
idCapitalName = field.capitalName;
|
||||
}
|
||||
}
|
||||
%>
|
||||
package ${package.ServiceImpl};
|
||||
|
||||
import ${superServiceImplClassPackage};
|
||||
import ${package.Mapper}.${table.mapperName};
|
||||
import ${package.Service}.${table.serviceName};
|
||||
import ${package.Entity}.${entity};
|
||||
import ${cfg.packageName!}.${package.ModuleName}.param.${entity}Param;
|
||||
import ${cfg.packageName!}.common.core.web.PageParam;
|
||||
import ${cfg.packageName!}.common.core.web.PageResult;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* ${table.comment!}Service实现
|
||||
*
|
||||
* @author ${author}
|
||||
* @since ${date(), 'yyyy-MM-dd HH:mm:ss'}
|
||||
*/
|
||||
@Service
|
||||
<% if(kotlin){ %>
|
||||
open class ${table.serviceImplName} : ${superServiceImplClass}<${table.mapperName}, ${entity}>(), ${table.serviceName} {
|
||||
|
||||
}
|
||||
<% }else{ %>
|
||||
public class ${table.serviceImplName} extends ${superServiceImplClass}<${table.mapperName}, ${entity}> implements ${table.serviceName} {
|
||||
|
||||
@Override
|
||||
public PageResult<${entity}> pageRel(${entity}Param param) {
|
||||
PageParam<${entity}, ${entity}Param> page = new PageParam<>(param);
|
||||
page.setDefaultOrder("sort_number asc, create_time desc");
|
||||
List<${entity}> list = baseMapper.selectPageRel(page, param);
|
||||
return new PageResult<>(list, page.getTotal());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<${entity}> listRel(${entity}Param param) {
|
||||
List<${entity}> list = baseMapper.selectListRel(param);
|
||||
// 排序
|
||||
PageParam<${entity}, ${entity}Param> page = new PageParam<>();
|
||||
page.setDefaultOrder("sort_number asc, create_time desc");
|
||||
return page.sortRecords(list);
|
||||
}
|
||||
|
||||
@Override
|
||||
public ${entity} getByIdRel(Integer ${idPropertyName!}) {
|
||||
${entity}Param param = new ${entity}Param();
|
||||
param.set${idCapitalName!}(${idPropertyName!});
|
||||
return param.getOne(baseMapper.selectListRel(param));
|
||||
}
|
||||
|
||||
}
|
||||
<% } %>
|
||||
@@ -0,0 +1,89 @@
|
||||
// 智能表格列配置 - 使用 hideInTable 控制显示
|
||||
// 所有字段都会生成,但非核心字段默认隐藏,用户可通过列设置显示
|
||||
|
||||
const columns = ref<ColumnItem[]>([
|
||||
<% var coreFieldCount = 0; %>
|
||||
<% for(field in table.fields) { %>
|
||||
<% if(field.propertyName != 'tenantId' && field.propertyName != 'deleted' && field.propertyName != 'version'){ %>
|
||||
<%
|
||||
// 定义核心字段优先级
|
||||
var priority = 0;
|
||||
var isCoreField = false;
|
||||
|
||||
if(field.keyFlag) {
|
||||
priority = 10;
|
||||
isCoreField = true;
|
||||
} else if(field.propertyName == 'name' || field.propertyName == 'title') {
|
||||
priority = 9;
|
||||
isCoreField = true;
|
||||
} else if(field.propertyName == 'code') {
|
||||
priority = 8;
|
||||
isCoreField = true;
|
||||
} else if(field.propertyName == 'status') {
|
||||
priority = 7;
|
||||
isCoreField = true;
|
||||
} else if(field.propertyName == 'sort') {
|
||||
priority = 6;
|
||||
isCoreField = true;
|
||||
} else if(field.propertyName == 'createTime') {
|
||||
priority = 5;
|
||||
isCoreField = true;
|
||||
} else if(field.propertyName == 'updateTime') {
|
||||
priority = 3;
|
||||
isCoreField = false; // 更新时间默认隐藏
|
||||
} else if(field.propertyType == 'String' && (field.propertyName.contains('remark') || field.propertyName.contains('description') || field.propertyName.contains('content'))) {
|
||||
priority = 1;
|
||||
isCoreField = false; // 长文本字段默认隐藏
|
||||
} else {
|
||||
priority = 4;
|
||||
isCoreField = false; // 其他字段默认隐藏
|
||||
}
|
||||
|
||||
// 限制核心字段数量(最多6个)
|
||||
if(isCoreField && coreFieldCount >= 6) {
|
||||
isCoreField = false;
|
||||
}
|
||||
if(isCoreField) {
|
||||
coreFieldCount = coreFieldCount + 1;
|
||||
}
|
||||
%>
|
||||
{
|
||||
title: '${field.comment!field.propertyName}',
|
||||
dataIndex: '${field.propertyName}',
|
||||
key: '${field.propertyName}',
|
||||
align: 'center',
|
||||
<% if(!isCoreField){ %>
|
||||
hideInTable: true, // 非核心字段默认隐藏,可通过列设置显示
|
||||
<% } %>
|
||||
<% if(field.keyFlag){ %>
|
||||
width: 90,
|
||||
<% } else if(field.propertyName == 'createTime' || field.propertyName == 'updateTime'){ %>
|
||||
width: 120,
|
||||
sorter: true,
|
||||
ellipsis: true,
|
||||
customRender: ({ text }) => toDateString(text, 'yyyy-MM-dd')
|
||||
<% } else if(field.propertyType == 'String' && (field.propertyName.contains('remark') || field.propertyName.contains('description') || field.propertyName.contains('content'))){ %>
|
||||
width: 200,
|
||||
ellipsis: true
|
||||
<% } else if(field.propertyType == 'String'){ %>
|
||||
width: 150,
|
||||
ellipsis: true
|
||||
<% } else if(field.propertyName == 'status'){ %>
|
||||
width: 80
|
||||
<% } else if(field.propertyName == 'sort'){ %>
|
||||
width: 80
|
||||
<% } else { %>
|
||||
width: 120
|
||||
<% } %>
|
||||
},
|
||||
<% } %>
|
||||
<% } %>
|
||||
{
|
||||
title: '操作',
|
||||
key: 'action',
|
||||
width: 180,
|
||||
fixed: 'right',
|
||||
align: 'center',
|
||||
hideInSetting: true // 操作列不允许隐藏
|
||||
}
|
||||
]);
|
||||
@@ -0,0 +1,60 @@
|
||||
/**
|
||||
* 表格列显示配置
|
||||
* 用于控制代码生成器生成的表格默认显示哪些列
|
||||
*/
|
||||
|
||||
// 优先显示的字段名(按优先级排序)
|
||||
const PRIORITY_FIELDS = [
|
||||
'id', // 主键ID
|
||||
'name', // 名称
|
||||
'title', // 标题
|
||||
'code', // 编码
|
||||
'status', // 状态
|
||||
'sort', // 排序
|
||||
'createTime', // 创建时间
|
||||
'updateTime' // 更新时间
|
||||
];
|
||||
|
||||
// 字段类型优先级配置
|
||||
const FIELD_TYPE_PRIORITY = {
|
||||
'keyFlag': 10, // 主键字段最高优先级
|
||||
'String': 8, // 字符串字段
|
||||
'Integer': 6, // 整数字段
|
||||
'Boolean': 5, // 布尔字段
|
||||
'Date': 4, // 日期字段
|
||||
'BigDecimal': 3, // 数值字段
|
||||
'Text': 1 // 文本字段最低优先级
|
||||
};
|
||||
|
||||
// 排除的字段(不显示在表格中)
|
||||
const EXCLUDED_FIELDS = [
|
||||
'tenantId', // 租户ID
|
||||
'deleted', // 逻辑删除标记
|
||||
'version', // 版本号
|
||||
'remark', // 备注(通常内容较长)
|
||||
'description', // 描述(通常内容较长)
|
||||
'content' // 内容(通常内容较长)
|
||||
];
|
||||
|
||||
// 默认显示的最大列数
|
||||
const MAX_DEFAULT_COLUMNS = 6;
|
||||
|
||||
// 特殊字段的宽度配置
|
||||
const FIELD_WIDTH_CONFIG = {
|
||||
'id': 90,
|
||||
'status': 80,
|
||||
'sort': 80,
|
||||
'createTime': 120,
|
||||
'updateTime': 120,
|
||||
'default_string': 150,
|
||||
'default_number': 120,
|
||||
'default_other': 120
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
PRIORITY_FIELDS,
|
||||
FIELD_TYPE_PRIORITY,
|
||||
EXCLUDED_FIELDS,
|
||||
MAX_DEFAULT_COLUMNS,
|
||||
FIELD_WIDTH_CONFIG
|
||||
};
|
||||
@@ -0,0 +1,263 @@
|
||||
<template>
|
||||
<a-page-header :title="getPageTitle()" @back="() => $router.go(-1)">
|
||||
<a-card :bordered="false" :body-style="{ padding: '16px' }">
|
||||
<ele-pro-table
|
||||
ref="tableRef"
|
||||
row-key="id"
|
||||
:columns="columns"
|
||||
:datasource="datasource"
|
||||
:customRow="customRow"
|
||||
tool-class="ele-toolbar-form"
|
||||
class="sys-table"
|
||||
>
|
||||
<template #toolbar>
|
||||
<search
|
||||
@search="reload"
|
||||
:selection="selection"
|
||||
@add="openEdit"
|
||||
@remove="removeBatch"
|
||||
/>
|
||||
|
||||
<!-- 列设置按钮 -->
|
||||
<a-tooltip title="列设置">
|
||||
<a-button
|
||||
type="text"
|
||||
@click="showColumnSetting = true"
|
||||
:icon="h(SettingOutlined)"
|
||||
/>
|
||||
</a-tooltip>
|
||||
</template>
|
||||
|
||||
<template #bodyCell="{ column, record }">
|
||||
<template v-if="column.key === 'status'">
|
||||
<a-tag v-if="record.status === 0" color="green">启用</a-tag>
|
||||
<a-tag v-if="record.status === 1" color="red">禁用</a-tag>
|
||||
</template>
|
||||
<template v-if="column.key === 'action'">
|
||||
<a-space>
|
||||
<a @click="openEdit(record)">修改</a>
|
||||
<a-divider type="vertical" />
|
||||
<a-popconfirm
|
||||
title="确定要删除此记录吗?"
|
||||
@confirm="remove(record)"
|
||||
>
|
||||
<a class="ele-text-danger">删除</a>
|
||||
</a-popconfirm>
|
||||
</a-space>
|
||||
</template>
|
||||
</template>
|
||||
</ele-pro-table>
|
||||
</a-card>
|
||||
|
||||
<!-- 列设置弹窗 -->
|
||||
<a-modal
|
||||
v-model:visible="showColumnSetting"
|
||||
title="列设置"
|
||||
width="400px"
|
||||
@ok="applyColumnSettings"
|
||||
>
|
||||
<div class="column-settings">
|
||||
<div class="setting-item" v-for="col in allColumns" :key="col.key">
|
||||
<a-checkbox
|
||||
v-model:checked="col.visible"
|
||||
:disabled="col.required"
|
||||
>
|
||||
{{ col.title }}
|
||||
<a-tag v-if="col.required" size="small" color="blue">必显</a-tag>
|
||||
</a-checkbox>
|
||||
</div>
|
||||
</div>
|
||||
</a-modal>
|
||||
</a-page-header>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { createVNode, ref, h, computed } from 'vue';
|
||||
import { message, Modal } from 'ant-design-vue';
|
||||
import { ExclamationCircleOutlined, SettingOutlined } from '@ant-design/icons-vue';
|
||||
import type { EleProTable } from 'ele-admin-pro';
|
||||
import { toDateString } from 'ele-admin-pro';
|
||||
import type {
|
||||
DatasourceFunction,
|
||||
ColumnItem
|
||||
} from 'ele-admin-pro/es/ele-pro-table/types';
|
||||
|
||||
// 列设置相关
|
||||
const showColumnSetting = ref(false);
|
||||
|
||||
// 所有列的配置(包含可见性控制)
|
||||
const allColumns = ref([
|
||||
{
|
||||
title: 'ID',
|
||||
dataIndex: 'id',
|
||||
key: 'id',
|
||||
width: 90,
|
||||
align: 'center',
|
||||
visible: true,
|
||||
required: true // 必须显示的列
|
||||
},
|
||||
{
|
||||
title: '名称',
|
||||
dataIndex: 'name',
|
||||
key: 'name',
|
||||
width: 150,
|
||||
align: 'center',
|
||||
ellipsis: true,
|
||||
visible: true,
|
||||
required: true
|
||||
},
|
||||
{
|
||||
title: '编码',
|
||||
dataIndex: 'code',
|
||||
key: 'code',
|
||||
width: 120,
|
||||
align: 'center',
|
||||
visible: true,
|
||||
required: false
|
||||
},
|
||||
{
|
||||
title: '状态',
|
||||
dataIndex: 'status',
|
||||
key: 'status',
|
||||
width: 80,
|
||||
align: 'center',
|
||||
visible: true,
|
||||
required: true
|
||||
},
|
||||
{
|
||||
title: '排序',
|
||||
dataIndex: 'sort',
|
||||
key: 'sort',
|
||||
width: 80,
|
||||
align: 'center',
|
||||
visible: true,
|
||||
required: false
|
||||
},
|
||||
{
|
||||
title: '创建人',
|
||||
dataIndex: 'createBy',
|
||||
key: 'createBy',
|
||||
width: 120,
|
||||
align: 'center',
|
||||
visible: false, // 默认隐藏
|
||||
required: false
|
||||
},
|
||||
{
|
||||
title: '创建时间',
|
||||
dataIndex: 'createTime',
|
||||
key: 'createTime',
|
||||
width: 120,
|
||||
align: 'center',
|
||||
sorter: true,
|
||||
ellipsis: true,
|
||||
customRender: ({ text }) => toDateString(text, 'yyyy-MM-dd'),
|
||||
visible: true,
|
||||
required: false
|
||||
},
|
||||
{
|
||||
title: '更新人',
|
||||
dataIndex: 'updateBy',
|
||||
key: 'updateBy',
|
||||
width: 120,
|
||||
align: 'center',
|
||||
visible: false, // 默认隐藏
|
||||
required: false
|
||||
},
|
||||
{
|
||||
title: '更新时间',
|
||||
dataIndex: 'updateTime',
|
||||
key: 'updateTime',
|
||||
width: 120,
|
||||
align: 'center',
|
||||
sorter: true,
|
||||
ellipsis: true,
|
||||
customRender: ({ text }) => toDateString(text, 'yyyy-MM-dd'),
|
||||
visible: false, // 默认隐藏
|
||||
required: false
|
||||
},
|
||||
{
|
||||
title: '备注',
|
||||
dataIndex: 'remark',
|
||||
key: 'remark',
|
||||
width: 200,
|
||||
align: 'center',
|
||||
ellipsis: true,
|
||||
visible: false, // 默认隐藏
|
||||
required: false
|
||||
},
|
||||
{
|
||||
title: '操作',
|
||||
key: 'action',
|
||||
width: 180,
|
||||
fixed: 'right',
|
||||
align: 'center',
|
||||
visible: true,
|
||||
required: true
|
||||
}
|
||||
]);
|
||||
|
||||
// 根据可见性过滤列
|
||||
const columns = computed(() => {
|
||||
return allColumns.value
|
||||
.filter(col => col.visible)
|
||||
.map(col => {
|
||||
const { visible, required, ...columnConfig } = col;
|
||||
return columnConfig;
|
||||
});
|
||||
});
|
||||
|
||||
// 应用列设置
|
||||
const applyColumnSettings = () => {
|
||||
showColumnSetting.value = false;
|
||||
message.success('列设置已应用');
|
||||
};
|
||||
|
||||
// 其他业务逻辑...
|
||||
const tableRef = ref<InstanceType<typeof EleProTable> | null>(null);
|
||||
const selection = ref([]);
|
||||
|
||||
const datasource: DatasourceFunction = ({ page, limit, where, orders }) => {
|
||||
// 实际的数据源逻辑
|
||||
return Promise.resolve({
|
||||
list: [],
|
||||
total: 0
|
||||
});
|
||||
};
|
||||
|
||||
const reload = () => {
|
||||
tableRef?.value?.reload();
|
||||
};
|
||||
|
||||
const openEdit = (record?: any) => {
|
||||
// 编辑逻辑
|
||||
};
|
||||
|
||||
const remove = (record: any) => {
|
||||
// 删除逻辑
|
||||
};
|
||||
|
||||
const removeBatch = () => {
|
||||
// 批量删除逻辑
|
||||
};
|
||||
|
||||
const customRow = (record: any) => {
|
||||
return {
|
||||
onClick: () => {
|
||||
// 行点击事件
|
||||
}
|
||||
};
|
||||
};
|
||||
</script>
|
||||
|
||||
<style lang="less" scoped>
|
||||
.column-settings {
|
||||
.setting-item {
|
||||
padding: 8px 0;
|
||||
border-bottom: 1px solid #f0f0f0;
|
||||
|
||||
&:last-child {
|
||||
border-bottom: none;
|
||||
}
|
||||
}
|
||||
}
|
||||
</style>
|
||||
136
src/test/java/com/gxwebsoft/house/HousePosterTest.java
Normal file
136
src/test/java/com/gxwebsoft/house/HousePosterTest.java
Normal file
@@ -0,0 +1,136 @@
|
||||
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房源信息测试通过!");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
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("价格(低-高)"));
|
||||
}
|
||||
}
|
||||
136
src/test/java/com/gxwebsoft/payment/enums/PaymentTypeTest.java
Normal file
136
src/test/java/com/gxwebsoft/payment/enums/PaymentTypeTest.java
Normal file
@@ -0,0 +1,136 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
79
src/test/java/com/gxwebsoft/shop/CertificatePathTest.java
Normal file
79
src/test/java/com/gxwebsoft/shop/CertificatePathTest.java
Normal file
@@ -0,0 +1,79 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
174
src/test/java/com/gxwebsoft/shop/MultiSpecOrderTest.java
Normal file
174
src/test/java/com/gxwebsoft/shop/MultiSpecOrderTest.java
Normal file
@@ -0,0 +1,174 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
170
src/test/java/com/gxwebsoft/shop/OrderBusinessServiceTest.java
Normal file
170
src/test/java/com/gxwebsoft/shop/OrderBusinessServiceTest.java
Normal file
@@ -0,0 +1,170 @@
|
||||
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
|
||||
));
|
||||
}
|
||||
}
|
||||
56
src/test/java/com/gxwebsoft/shop/OrderTotalTest.java
Normal file
56
src/test/java/com/gxwebsoft/shop/OrderTotalTest.java
Normal file
@@ -0,0 +1,56 @@
|
||||
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秒以内");
|
||||
}
|
||||
}
|
||||
315
src/test/java/com/gxwebsoft/shop/OrderValidationTest.java
Normal file
315
src/test/java/com/gxwebsoft/shop/OrderValidationTest.java
Normal file
@@ -0,0 +1,315 @@
|
||||
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不能为空"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,75 @@
|
||||
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"), "截断后的文本不应包含无效字符");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
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 + " 张过期优惠券");
|
||||
}
|
||||
}
|
||||
145
src/test/java/com/gxwebsoft/shop/service/ShopGoodsSalesTest.java
Normal file
145
src/test/java/com/gxwebsoft/shop/service/ShopGoodsSalesTest.java
Normal file
@@ -0,0 +1,145 @@
|
||||
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("=== 批量累加测试完成 ===");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,136 @@
|
||||
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("=== 批量查询性能测试完成 ===");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
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("=== 配置属性测试 ===");
|
||||
|
||||
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("=== 配置属性测试完成 ===");
|
||||
}
|
||||
}
|
||||
99
src/test/java/com/gxwebsoft/test/CertificatePathFixTest.java
Normal file
99
src/test/java/com/gxwebsoft/test/CertificatePathFixTest.java
Normal file
@@ -0,0 +1,99 @@
|
||||
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("=== 目录结构验证完成 ===");
|
||||
}
|
||||
}
|
||||
107
src/test/java/com/gxwebsoft/test/CertificateTest.java
Normal file
107
src/test/java/com/gxwebsoft/test/CertificateTest.java
Normal file
@@ -0,0 +1,107 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,119 @@
|
||||
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("=== 环境切换测试完成 ===");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
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=== 所有租户证书测试完成 ===");
|
||||
}
|
||||
}
|
||||
89
src/test/java/com/gxwebsoft/test/WechatPayConfigTest.java
Normal file
89
src/test/java/com/gxwebsoft/test/WechatPayConfigTest.java
Normal file
@@ -0,0 +1,89 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
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 密钥未配置");
|
||||
}
|
||||
}
|
||||
}
|
||||
158
src/test/java/com/gxwebsoft/test/WechatPayPathTest.java
Normal file
158
src/test/java/com/gxwebsoft/test/WechatPayPathTest.java
Normal file
@@ -0,0 +1,158 @@
|
||||
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());
|
||||
}
|
||||
}
|
||||
}
|
||||
150
src/test/java/com/gxwebsoft/test/WechatPayPublicKeyTest.java
Normal file
150
src/test/java/com/gxwebsoft/test/WechatPayPublicKeyTest.java
Normal file
@@ -0,0 +1,150 @@
|
||||
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