Compare commits
12 Commits
896491fa0b
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
| ddebb6f16c | |||
| aea60e330d | |||
| 77a276e643 | |||
| 3b723a74c6 | |||
| 6a48722b67 | |||
| ced6178271 | |||
| 5775ad862d | |||
| 04d82682de | |||
| 41fb24b9ff | |||
| 044d87cfde | |||
| 7fe347d7bc | |||
| 3f546f7e70 |
34
docs/sql/2026-03-18_credit_user_add_indexes.sql
Normal file
34
docs/sql/2026-03-18_credit_user_add_indexes.sql
Normal file
@@ -0,0 +1,34 @@
|
||||
-- credit_user 索引优化(MySQL/InnoDB)
|
||||
--
|
||||
-- 背景:
|
||||
-- - credit_user 列表分页默认排序:sort_number asc, create_time desc
|
||||
-- - 常见过滤:tenant_id(TenantLine 自动追加)、deleted=0、company_id、user_id、create_time 范围
|
||||
-- - 统计/刷新关联数:WHERE deleted=0 AND company_id IN (...) GROUP BY company_id
|
||||
--
|
||||
-- 使用前建议先查看现有索引,避免重复:
|
||||
-- SHOW INDEX FROM credit_user;
|
||||
--
|
||||
-- 注意:
|
||||
-- - 大表加索引会消耗 IO/CPU,建议在低峰执行。
|
||||
-- - MySQL 8 可考虑:ALTER TABLE ... ALGORITHM=INPLACE, LOCK=NONE(视版本/引擎而定)。
|
||||
|
||||
-- 1) 覆盖默认分页排序 + 逻辑删除 + 租户隔离
|
||||
-- 典型:WHERE tenant_id=? AND deleted=0 ORDER BY sort_number, create_time DESC LIMIT ...
|
||||
CREATE INDEX idx_credit_user_tenant_deleted_sort_create_id
|
||||
ON credit_user (tenant_id, deleted, sort_number, create_time, id);
|
||||
|
||||
-- 2) 企业维度查询/统计(也服务于 credit_company 记录数刷新)
|
||||
-- 典型:WHERE tenant_id=? AND company_id=? AND deleted=0 ...
|
||||
-- 典型:WHERE tenant_id=? AND deleted=0 AND company_id IN (...) GROUP BY company_id
|
||||
CREATE INDEX idx_credit_user_tenant_company_deleted
|
||||
ON credit_user (tenant_id, company_id, deleted);
|
||||
|
||||
-- 3) 用户维度查询(后台常按录入人/负责人筛选)
|
||||
-- 典型:WHERE tenant_id=? AND user_id=? AND deleted=0 ...
|
||||
CREATE INDEX idx_credit_user_tenant_user_deleted
|
||||
ON credit_user (tenant_id, user_id, deleted);
|
||||
|
||||
-- 可选:如果你们经常按 type 过滤(0/1),再加这个(否则先别加,避免过多索引影响写入)
|
||||
-- CREATE INDEX idx_credit_user_tenant_type_deleted
|
||||
-- ON credit_user (tenant_id, type, deleted);
|
||||
|
||||
@@ -42,7 +42,6 @@ import java.time.Instant;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
import static com.gxwebsoft.common.core.constants.PlatformConstants.MP_WEIXIN;
|
||||
import static com.gxwebsoft.common.core.constants.RedisConstants.ACCESS_TOKEN_KEY;
|
||||
@@ -246,27 +245,30 @@ public class WxLoginController extends BaseController {
|
||||
* @param userParam 需要传微信凭证code
|
||||
*/
|
||||
private String getPhoneByCode(UserParam userParam) {
|
||||
// 获取手机号码
|
||||
String apiUrl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + getAccessToken();
|
||||
HashMap<String, Object> paramMap = new HashMap<>();
|
||||
if (StrUtil.isBlank(userParam.getCode())) {
|
||||
throw new BusinessException("code不能为空");
|
||||
}
|
||||
paramMap.put("code", userParam.getCode());
|
||||
// 执行post请求
|
||||
String post = HttpUtil.post(apiUrl, JSON.toJSONString(paramMap));
|
||||
JSONObject json = JSON.parseObject(post);
|
||||
if (json.get("errcode").equals(0)) {
|
||||
JSONObject phoneInfo = JSON.parseObject(json.getString("phone_info"));
|
||||
// 微信用户的手机号码
|
||||
final String phoneNumber = phoneInfo.getString("phoneNumber");
|
||||
// 验证手机号码
|
||||
// if (userParam.getNotVerifyPhone() == null && !Validator.isMobile(phoneNumber)) {
|
||||
// String key = ACCESS_TOKEN_KEY.concat(":").concat(getTenantId().toString());
|
||||
// redisTemplate.delete(key);
|
||||
// throw new BusinessException("手机号码格式不正确");
|
||||
// }
|
||||
return phoneNumber;
|
||||
|
||||
// access_token 失效/过期时自动刷新并重试一次
|
||||
for (int attempt = 0; attempt < 2; attempt++) {
|
||||
String accessToken = (attempt == 0) ? getAccessToken(false) : getAccessToken(true);
|
||||
String apiUrl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken;
|
||||
|
||||
String post = HttpUtil.post(apiUrl, JSON.toJSONString(paramMap));
|
||||
JSONObject json = JSON.parseObject(post);
|
||||
|
||||
Integer errcode = json.getInteger("errcode");
|
||||
if (errcode != null && errcode.equals(0)) {
|
||||
JSONObject phoneInfo = JSON.parseObject(json.getString("phone_info"));
|
||||
return phoneInfo.getString("phoneNumber");
|
||||
}
|
||||
|
||||
if (errcode != null && (errcode == 40001 || errcode == 42001 || errcode == 40014)) {
|
||||
continue;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
@@ -285,6 +287,10 @@ public class WxLoginController extends BaseController {
|
||||
* <a href="https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/mp-access-token/getAccessToken.html">...</a>
|
||||
*/
|
||||
public String getAccessToken() {
|
||||
return getAccessToken(false);
|
||||
}
|
||||
|
||||
private String getAccessToken(boolean forceRefresh) {
|
||||
Integer tenantId = getTenantId();
|
||||
String key = ACCESS_TOKEN_KEY.concat(":").concat(tenantId.toString());
|
||||
|
||||
@@ -294,9 +300,13 @@ public class WxLoginController extends BaseController {
|
||||
throw new BusinessException("请先配置小程序");
|
||||
}
|
||||
|
||||
if (forceRefresh) {
|
||||
redisTemplate.delete(key);
|
||||
}
|
||||
|
||||
// 从缓存获取access_token
|
||||
String value = redisTemplate.opsForValue().get(key);
|
||||
if (value != null) {
|
||||
if (!forceRefresh && value != null) {
|
||||
// 解析access_token
|
||||
JSONObject response = JSON.parseObject(value);
|
||||
String accessToken = response.getString("access_token");
|
||||
@@ -305,23 +315,38 @@ public class WxLoginController extends BaseController {
|
||||
}
|
||||
}
|
||||
|
||||
// 微信获取凭证接口
|
||||
String apiUrl = "https://api.weixin.qq.com/cgi-bin/token";
|
||||
// 组装url参数
|
||||
String url = apiUrl.concat("?grant_type=client_credential")
|
||||
.concat("&appid=").concat(setting.getString("appId"))
|
||||
.concat("&secret=").concat(setting.getString("appSecret"));
|
||||
String appId = setting.getString("appId");
|
||||
String appSecret = setting.getString("appSecret");
|
||||
|
||||
// 执行get请求
|
||||
String result = HttpUtil.get(url);
|
||||
// 解析access_token
|
||||
// 微信稳定版获取凭证接口(避免并发刷新导致旧token失效)
|
||||
String apiUrl = "https://api.weixin.qq.com/cgi-bin/stable_token";
|
||||
JSONObject reqBody = new JSONObject();
|
||||
reqBody.put("grant_type", "client_credential");
|
||||
reqBody.put("appid", appId);
|
||||
reqBody.put("secret", appSecret);
|
||||
reqBody.put("force_refresh", forceRefresh);
|
||||
|
||||
String result = HttpRequest.post(apiUrl)
|
||||
.header("Content-Type", "application/json")
|
||||
.body(reqBody.toJSONString())
|
||||
.execute()
|
||||
.body();
|
||||
JSONObject response = JSON.parseObject(result);
|
||||
if (response.getString("access_token") != null) {
|
||||
// 存入缓存
|
||||
redisTemplate.opsForValue().set(key, result, 7000L, TimeUnit.SECONDS);
|
||||
return response.getString("access_token");
|
||||
|
||||
Integer errcode = response.getInteger("errcode");
|
||||
if (errcode != null && errcode != 0) {
|
||||
throw new BusinessException("获取access_token失败: " + response.getString("errmsg") + " (errcode: " + errcode + ")");
|
||||
}
|
||||
throw new BusinessException("小程序配置不正确");
|
||||
|
||||
String accessToken = response.getString("access_token");
|
||||
Integer expiresIn = response.getInteger("expires_in");
|
||||
if (accessToken != null) {
|
||||
long ttlSeconds = Math.max((expiresIn != null ? expiresIn : 7200) - 300L, 60L);
|
||||
redisTemplate.opsForValue().set(key, result, ttlSeconds, TimeUnit.SECONDS);
|
||||
return accessToken;
|
||||
}
|
||||
|
||||
throw new BusinessException("获取access_token失败: " + result);
|
||||
}
|
||||
|
||||
@Operation(summary = "获取微信openId并更新")
|
||||
@@ -576,23 +601,29 @@ public class WxLoginController extends BaseController {
|
||||
throw new IOException("小程序配置不完整,缺少 appId 或 appSecret");
|
||||
}
|
||||
|
||||
HttpUrl url = HttpUrl.parse("https://api.weixin.qq.com/cgi-bin/token")
|
||||
.newBuilder()
|
||||
.addQueryParameter("grant_type", "client_credential")
|
||||
.addQueryParameter("appid", appId)
|
||||
.addQueryParameter("secret", appSecret)
|
||||
.build();
|
||||
HttpUrl url = HttpUrl.parse("https://api.weixin.qq.com/cgi-bin/stable_token").newBuilder().build();
|
||||
var root = om.createObjectNode();
|
||||
root.put("grant_type", "client_credential");
|
||||
root.put("appid", appId);
|
||||
root.put("secret", appSecret);
|
||||
root.put("force_refresh", false);
|
||||
|
||||
Request req = new Request.Builder().url(url).get().build();
|
||||
okhttp3.RequestBody reqBody = okhttp3.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()) {
|
||||
String body = resp.body().string();
|
||||
JsonNode json = om.readTree(body);
|
||||
if (json.has("errcode") && json.get("errcode").asInt() != 0) {
|
||||
throw new IOException("Get access_token failed: " + body);
|
||||
}
|
||||
if (json.has("access_token")) {
|
||||
String token = json.get("access_token").asText();
|
||||
long expiresIn = json.get("expires_in").asInt(7200);
|
||||
|
||||
// 缓存完整的JSON响应,与其他方法保持一致
|
||||
redisUtil.set(key, body, expiresIn, TimeUnit.SECONDS);
|
||||
long ttlSeconds = Math.max(expiresIn - 300L, 60L);
|
||||
redisUtil.set(key, body, ttlSeconds, TimeUnit.SECONDS);
|
||||
tokenExpireEpoch = now + expiresIn;
|
||||
System.out.println("获取新的access_token成功(Local),租户ID: " + tenantId);
|
||||
return token;
|
||||
@@ -686,7 +717,7 @@ public class WxLoginController extends BaseController {
|
||||
// 获取当前线程的租户ID
|
||||
Integer tenantId = getTenantId();
|
||||
if (tenantId == null) {
|
||||
tenantId = 10550; // 默认租户
|
||||
tenantId = 10584; // 默认租户
|
||||
}
|
||||
|
||||
System.out.println("=== 开始调试获取AccessToken,租户ID: " + tenantId + " ===");
|
||||
@@ -748,14 +779,14 @@ public class WxLoginController extends BaseController {
|
||||
}
|
||||
}
|
||||
|
||||
// 如果无法解析,默认使用租户10550
|
||||
System.out.println("无法解析scene参数,使用默认租户ID: 10550");
|
||||
return 10550;
|
||||
// 如果无法解析,默认使用租户10584
|
||||
System.out.println("无法解析scene参数,使用默认租户ID: 10584");
|
||||
return 10584;
|
||||
|
||||
} catch (Exception e) {
|
||||
System.err.println("解析scene参数异常: " + e.getMessage());
|
||||
// 出现异常时,默认使用租户10550
|
||||
return 10550;
|
||||
// 出现异常时,默认使用租户10584
|
||||
return 10584;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -789,10 +820,21 @@ public class WxLoginController extends BaseController {
|
||||
String appId = wxConfig.getString("appId");
|
||||
String appSecret = wxConfig.getString("appSecret");
|
||||
|
||||
String apiUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
|
||||
String apiUrl = "https://api.weixin.qq.com/cgi-bin/stable_token";
|
||||
System.out.println("调用微信API获取token - 租户ID: " + tenantId + ", AppID: " + (appId != null ? appId.substring(0, Math.min(8, appId.length())) + "..." : "null"));
|
||||
System.out.println("微信API请求URL: " + apiUrl.replaceAll("secret=[^&]*", "secret=***"));
|
||||
String result = HttpUtil.get(apiUrl);
|
||||
System.out.println("微信API请求URL: " + apiUrl);
|
||||
|
||||
JSONObject reqBody = new JSONObject();
|
||||
reqBody.put("grant_type", "client_credential");
|
||||
reqBody.put("appid", appId);
|
||||
reqBody.put("secret", appSecret);
|
||||
reqBody.put("force_refresh", false);
|
||||
|
||||
String result = HttpRequest.post(apiUrl)
|
||||
.header("Content-Type", "application/json")
|
||||
.body(reqBody.toJSONString())
|
||||
.execute()
|
||||
.body();
|
||||
System.out.println("微信API响应: " + result);
|
||||
JSONObject json = JSON.parseObject(result);
|
||||
|
||||
@@ -800,14 +842,15 @@ public class WxLoginController extends BaseController {
|
||||
if (json.containsKey("errcode")) {
|
||||
Integer errcode = json.getInteger("errcode");
|
||||
String errmsg = json.getString("errmsg");
|
||||
System.err.println("微信API错误 - errcode: " + errcode + ", errmsg: " + errmsg);
|
||||
|
||||
if (errcode == 40125) {
|
||||
throw new RuntimeException("微信AppSecret配置错误,请检查并更新正确的AppSecret");
|
||||
} else if (errcode == 40013) {
|
||||
throw new RuntimeException("微信AppID配置错误,请检查并更新正确的AppID");
|
||||
} else {
|
||||
throw new RuntimeException("微信API调用失败: " + errmsg + " (errcode: " + errcode + ")");
|
||||
if (errcode != null && errcode != 0) {
|
||||
System.err.println("微信API错误 - errcode: " + errcode + ", errmsg: " + errmsg);
|
||||
if (errcode == 40125) {
|
||||
throw new RuntimeException("微信AppSecret配置错误,请检查并更新正确的AppSecret");
|
||||
} else if (errcode == 40013) {
|
||||
throw new RuntimeException("微信AppID配置错误,请检查并更新正确的AppID");
|
||||
} else {
|
||||
throw new RuntimeException("微信API调用失败: " + errmsg + " (errcode: " + errcode + ")");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -816,7 +859,8 @@ public class WxLoginController extends BaseController {
|
||||
Integer expiresIn = json.getInteger("expires_in");
|
||||
|
||||
// 缓存access_token,存储完整JSON响应(与getAccessToken方法保持一致)
|
||||
redisUtil.set(key, result, (long) (expiresIn - 300), TimeUnit.SECONDS);
|
||||
long ttlSeconds = Math.max((expiresIn != null ? expiresIn : 7200) - 300L, 60L);
|
||||
redisUtil.set(key, result, ttlSeconds, TimeUnit.SECONDS);
|
||||
|
||||
System.out.println("获取新的access_token成功,租户ID: " + tenantId);
|
||||
return accessToken;
|
||||
|
||||
@@ -102,7 +102,7 @@
|
||||
AND a.deleted = 0
|
||||
</if>
|
||||
<if test="param.roleId != null">
|
||||
AND a.user_id IN (SELECT user_id FROM sys_user_role WHERE role_id=#{param.roleId})
|
||||
AND a.user_id IN (SELECT user_id FROM gxwebsoft_core.sys_user_role WHERE role_id=#{param.roleId})
|
||||
</if>
|
||||
<if test="param.userIds != null">
|
||||
AND a.user_id IN
|
||||
@@ -259,6 +259,7 @@
|
||||
LEFT JOIN gxwebsoft_core.sys_user_referee h ON a.user_id = h.user_id and h.deleted = 0
|
||||
WHERE a.user_id = #{userId}
|
||||
AND a.deleted = 0
|
||||
LIMIT 1
|
||||
</select>
|
||||
|
||||
</mapper>
|
||||
|
||||
@@ -0,0 +1,129 @@
|
||||
package com.gxwebsoft.credit.controller;
|
||||
|
||||
import com.gxwebsoft.common.core.web.BaseController;
|
||||
import com.gxwebsoft.credit.service.CreditMpCustomerService;
|
||||
import com.gxwebsoft.credit.entity.CreditMpCustomer;
|
||||
import com.gxwebsoft.credit.param.CreditMpCustomerParam;
|
||||
import com.gxwebsoft.common.core.web.ApiResult;
|
||||
import com.gxwebsoft.common.core.web.PageResult;
|
||||
import com.gxwebsoft.common.core.web.PageParam;
|
||||
import com.gxwebsoft.common.core.web.BatchParam;
|
||||
import com.gxwebsoft.common.core.annotation.OperationLog;
|
||||
import com.gxwebsoft.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.*;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 小程序端客户控制器
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2026-03-16 20:59:17
|
||||
*/
|
||||
@Tag(name = "小程序端客户管理")
|
||||
@RestController
|
||||
@RequestMapping("/api/credit/credit-mp-customer")
|
||||
public class CreditMpCustomerController extends BaseController {
|
||||
@Resource
|
||||
private CreditMpCustomerService creditMpCustomerService;
|
||||
|
||||
@PreAuthorize("hasAuthority('credit:creditMpCustomer:list')")
|
||||
@Operation(summary = "分页查询小程序端客户")
|
||||
@GetMapping("/page")
|
||||
public ApiResult<PageResult<CreditMpCustomer>> page(CreditMpCustomerParam param) {
|
||||
// 使用关联查询
|
||||
return success(creditMpCustomerService.pageRel(param));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('credit:creditMpCustomer:list')")
|
||||
@Operation(summary = "查询全部小程序端客户")
|
||||
@GetMapping()
|
||||
public ApiResult<List<CreditMpCustomer>> list(CreditMpCustomerParam param) {
|
||||
// 使用关联查询
|
||||
return success(creditMpCustomerService.listRel(param));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('credit:creditMpCustomer:list')")
|
||||
@Operation(summary = "根据id查询小程序端客户")
|
||||
@GetMapping("/{id}")
|
||||
public ApiResult<CreditMpCustomer> get(@PathVariable("id") Integer id) {
|
||||
// 使用关联查询
|
||||
return success(creditMpCustomerService.getByIdRel(id));
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('credit:creditMpCustomer:save')")
|
||||
@OperationLog
|
||||
@Operation(summary = "添加小程序端客户")
|
||||
@PostMapping()
|
||||
public ApiResult<?> save(@RequestBody CreditMpCustomer creditMpCustomer) {
|
||||
// 记录当前登录用户id
|
||||
User loginUser = getLoginUser();
|
||||
if (loginUser != null) {
|
||||
creditMpCustomer.setUserId(loginUser.getUserId());
|
||||
}
|
||||
if (creditMpCustomerService.save(creditMpCustomer)) {
|
||||
return success("添加成功");
|
||||
}
|
||||
return fail("添加失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('credit:creditMpCustomer:update')")
|
||||
@OperationLog
|
||||
@Operation(summary = "修改小程序端客户")
|
||||
@PutMapping()
|
||||
public ApiResult<?> update(@RequestBody CreditMpCustomer creditMpCustomer) {
|
||||
if (creditMpCustomerService.updateById(creditMpCustomer)) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('credit:creditMpCustomer:remove')")
|
||||
@OperationLog
|
||||
@Operation(summary = "删除小程序端客户")
|
||||
@DeleteMapping("/{id}")
|
||||
public ApiResult<?> remove(@PathVariable("id") Integer id) {
|
||||
if (creditMpCustomerService.removeById(id)) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('credit:creditMpCustomer:save')")
|
||||
@OperationLog
|
||||
@Operation(summary = "批量添加小程序端客户")
|
||||
@PostMapping("/batch")
|
||||
public ApiResult<?> saveBatch(@RequestBody List<CreditMpCustomer> list) {
|
||||
if (creditMpCustomerService.saveBatch(list)) {
|
||||
return success("添加成功");
|
||||
}
|
||||
return fail("添加失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('credit:creditMpCustomer:update')")
|
||||
@OperationLog
|
||||
@Operation(summary = "批量修改小程序端客户")
|
||||
@PutMapping("/batch")
|
||||
public ApiResult<?> removeBatch(@RequestBody BatchParam<CreditMpCustomer> batchParam) {
|
||||
if (batchParam.update(creditMpCustomerService, "id")) {
|
||||
return success("修改成功");
|
||||
}
|
||||
return fail("修改失败");
|
||||
}
|
||||
|
||||
@PreAuthorize("hasAuthority('credit:creditMpCustomer:remove')")
|
||||
@OperationLog
|
||||
@Operation(summary = "批量删除小程序端客户")
|
||||
@DeleteMapping("/batch")
|
||||
public ApiResult<?> removeBatch(@RequestBody List<Integer> ids) {
|
||||
if (creditMpCustomerService.removeByIds(ids)) {
|
||||
return success("删除成功");
|
||||
}
|
||||
return fail("删除失败");
|
||||
}
|
||||
|
||||
}
|
||||
113
src/main/java/com/gxwebsoft/credit/entity/CreditMpCustomer.java
Normal file
113
src/main/java/com/gxwebsoft/credit/entity/CreditMpCustomer.java
Normal file
@@ -0,0 +1,113 @@
|
||||
package com.gxwebsoft.credit.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import java.time.LocalDateTime;
|
||||
import com.baomidou.mybatisplus.annotation.TableLogic;
|
||||
import java.io.Serializable;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
/**
|
||||
* 小程序端客户
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2026-03-16 20:59:17
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@Schema(name = "CreditMpCustomer对象", description = "小程序端客户")
|
||||
public class CreditMpCustomer implements Serializable {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Schema(description = "ID")
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Integer id;
|
||||
|
||||
@Schema(description = "拖欠方")
|
||||
private String toUser;
|
||||
|
||||
@Schema(description = "拖欠金额")
|
||||
private String price;
|
||||
|
||||
@Schema(description = "拖欠年数")
|
||||
private String years;
|
||||
|
||||
@Schema(description = "链接")
|
||||
private String url;
|
||||
|
||||
@Schema(description = "状态")
|
||||
private String statusTxt;
|
||||
|
||||
@Schema(description = "企业ID")
|
||||
private Integer companyId;
|
||||
|
||||
@Schema(description = "所在省份")
|
||||
private String province;
|
||||
|
||||
@Schema(description = "所在城市")
|
||||
private String city;
|
||||
|
||||
@Schema(description = "所在辖区")
|
||||
private String region;
|
||||
|
||||
@Schema(description = "文件路径")
|
||||
private String files;
|
||||
|
||||
@Schema(description = "是否有数据")
|
||||
private Boolean hasData;
|
||||
|
||||
@Schema(description = "步骤, 0未受理1已受理2材料提交3合同签订4执行回款5完结")
|
||||
private Integer step;
|
||||
|
||||
@Schema(description = "备注")
|
||||
private String comments;
|
||||
|
||||
@Schema(description = "是否推荐")
|
||||
private Integer recommend;
|
||||
|
||||
@Schema(description = "排序(数字越小越靠前)")
|
||||
private Integer sortNumber;
|
||||
|
||||
@Schema(description = "状态, 0未受理, 1已受理")
|
||||
private Integer status;
|
||||
|
||||
@Schema(description = "是否删除, 0否, 1是")
|
||||
@TableLogic
|
||||
private Integer deleted;
|
||||
|
||||
@Schema(description = "用户ID")
|
||||
private Integer userId;
|
||||
|
||||
@Schema(description = "用户昵称")
|
||||
@TableField(exist = false)
|
||||
private String nickname;
|
||||
|
||||
@Schema(description = "用户手机号")
|
||||
@TableField(exist = false)
|
||||
private String phone;
|
||||
|
||||
@Schema(description = "用户头像")
|
||||
@TableField(exist = false)
|
||||
private String avatar;
|
||||
|
||||
@Schema(description = "真实姓名")
|
||||
@TableField(exist = false)
|
||||
private String realName;
|
||||
|
||||
@Schema(description = "租户id")
|
||||
private Integer tenantId;
|
||||
|
||||
@Schema(description = "创建时间")
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
private LocalDateTime createTime;
|
||||
|
||||
@Schema(description = "修改时间")
|
||||
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
|
||||
private LocalDateTime updateTime;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.gxwebsoft.credit.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.gxwebsoft.credit.entity.CreditMpCustomer;
|
||||
import com.gxwebsoft.credit.param.CreditMpCustomerParam;
|
||||
import org.apache.ibatis.annotations.Param;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 小程序端客户Mapper
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2026-03-16 20:59:17
|
||||
*/
|
||||
public interface CreditMpCustomerMapper extends BaseMapper<CreditMpCustomer> {
|
||||
|
||||
/**
|
||||
* 分页查询
|
||||
*
|
||||
* @param page 分页对象
|
||||
* @param param 查询参数
|
||||
* @return List<CreditMpCustomer>
|
||||
*/
|
||||
List<CreditMpCustomer> selectPageRel(@Param("page") IPage<CreditMpCustomer> page,
|
||||
@Param("param") CreditMpCustomerParam param);
|
||||
|
||||
/**
|
||||
* 查询全部
|
||||
*
|
||||
* @param param 查询参数
|
||||
* @return List<User>
|
||||
*/
|
||||
List<CreditMpCustomer> selectListRel(@Param("param") CreditMpCustomerParam param);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,95 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
|
||||
<mapper namespace="com.gxwebsoft.credit.mapper.CreditMpCustomerMapper">
|
||||
|
||||
<!-- 关联查询sql -->
|
||||
<sql id="selectSql">
|
||||
SELECT a.*, u.nickname AS nickname, u.avatar AS avatar, u.phone AS phone, u.real_name AS realName
|
||||
FROM credit_mp_customer a
|
||||
LEFT JOIN gxwebsoft_core.sys_user u ON u.user_id = a.user_id
|
||||
<where>
|
||||
<if test="param.id != null">
|
||||
AND a.id = #{param.id}
|
||||
</if>
|
||||
<if test="param.toUser != null">
|
||||
AND a.to_user LIKE CONCAT('%', #{param.toUser}, '%')
|
||||
</if>
|
||||
<if test="param.price != null">
|
||||
AND a.price LIKE CONCAT('%', #{param.price}, '%')
|
||||
</if>
|
||||
<if test="param.years != null">
|
||||
AND a.years LIKE CONCAT('%', #{param.years}, '%')
|
||||
</if>
|
||||
<if test="param.url != null">
|
||||
AND a.url LIKE CONCAT('%', #{param.url}, '%')
|
||||
</if>
|
||||
<if test="param.statusTxt != null">
|
||||
AND a.status_txt LIKE CONCAT('%', #{param.statusTxt}, '%')
|
||||
</if>
|
||||
<if test="param.companyId != null">
|
||||
AND a.company_id = #{param.companyId}
|
||||
</if>
|
||||
<if test="param.province != null">
|
||||
AND a.province LIKE CONCAT('%', #{param.province}, '%')
|
||||
</if>
|
||||
<if test="param.city != null">
|
||||
AND a.city LIKE CONCAT('%', #{param.city}, '%')
|
||||
</if>
|
||||
<if test="param.region != null">
|
||||
AND a.region LIKE CONCAT('%', #{param.region}, '%')
|
||||
</if>
|
||||
<if test="param.files != null">
|
||||
AND a.files LIKE CONCAT('%', #{param.files}, '%')
|
||||
</if>
|
||||
<if test="param.hasData != null">
|
||||
AND a.has_data = #{param.hasData}
|
||||
</if>
|
||||
<if test="param.comments != null">
|
||||
AND a.comments LIKE CONCAT('%', #{param.comments}, '%')
|
||||
</if>
|
||||
<if test="param.recommend != null">
|
||||
AND a.recommend = #{param.recommend}
|
||||
</if>
|
||||
<if test="param.sortNumber != null">
|
||||
AND a.sort_number = #{param.sortNumber}
|
||||
</if>
|
||||
<if test="param.status != null">
|
||||
AND a.status = #{param.status}
|
||||
</if>
|
||||
<if test="param.deleted != null">
|
||||
AND a.deleted = #{param.deleted}
|
||||
</if>
|
||||
<if test="param.deleted == null">
|
||||
AND a.deleted = 0
|
||||
</if>
|
||||
<if test="param.userId != null">
|
||||
AND a.user_id = #{param.userId}
|
||||
</if>
|
||||
<if test="param.step != null">
|
||||
AND a.step = #{param.step}
|
||||
</if>
|
||||
<if test="param.createTimeStart != null">
|
||||
AND a.create_time >= #{param.createTimeStart}
|
||||
</if>
|
||||
<if test="param.createTimeEnd != null">
|
||||
AND a.create_time <= #{param.createTimeEnd}
|
||||
</if>
|
||||
<if test="param.keywords != null">
|
||||
AND (a.comments LIKE CONCAT('%', #{param.keywords}, '%')
|
||||
OR a.to_user LIKE CONCAT('%', #{param.keywords}, '%')
|
||||
)
|
||||
</if>
|
||||
</where>
|
||||
</sql>
|
||||
|
||||
<!-- 分页查询 -->
|
||||
<select id="selectPageRel" resultType="com.gxwebsoft.credit.entity.CreditMpCustomer">
|
||||
<include refid="selectSql"></include>
|
||||
</select>
|
||||
|
||||
<!-- 查询全部 -->
|
||||
<select id="selectListRel" resultType="com.gxwebsoft.credit.entity.CreditMpCustomer">
|
||||
<include refid="selectSql"></include>
|
||||
</select>
|
||||
|
||||
</mapper>
|
||||
@@ -0,0 +1,91 @@
|
||||
package com.gxwebsoft.credit.param;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import com.gxwebsoft.common.core.annotation.QueryField;
|
||||
import com.gxwebsoft.common.core.annotation.QueryType;
|
||||
import com.gxwebsoft.common.core.web.BaseParam;
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
import lombok.EqualsAndHashCode;
|
||||
|
||||
/**
|
||||
* 小程序端客户查询参数
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2026-03-16 20:59:17
|
||||
*/
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = false)
|
||||
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||
@Schema(name = "CreditMpCustomerParam对象", description = "小程序端客户查询参数")
|
||||
public class CreditMpCustomerParam extends BaseParam {
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
@Schema(description = "ID")
|
||||
@QueryField(type = QueryType.EQ)
|
||||
private Integer id;
|
||||
|
||||
@Schema(description = "拖欠方")
|
||||
private String toUser;
|
||||
|
||||
@Schema(description = "拖欠金额")
|
||||
private String price;
|
||||
|
||||
@Schema(description = "拖欠年数")
|
||||
private String years;
|
||||
|
||||
@Schema(description = "链接")
|
||||
private String url;
|
||||
|
||||
@Schema(description = "状态")
|
||||
private String statusTxt;
|
||||
|
||||
@Schema(description = "企业ID")
|
||||
@QueryField(type = QueryType.EQ)
|
||||
private Integer companyId;
|
||||
|
||||
@Schema(description = "所在省份")
|
||||
private String province;
|
||||
|
||||
@Schema(description = "所在城市")
|
||||
private String city;
|
||||
|
||||
@Schema(description = "所在辖区")
|
||||
private String region;
|
||||
|
||||
@Schema(description = "文件路径")
|
||||
private String files;
|
||||
|
||||
@Schema(description = "是否有数据")
|
||||
@QueryField(type = QueryType.EQ)
|
||||
private Boolean hasData;
|
||||
|
||||
@Schema(description = "步骤, 0未受理1已受理2材料提交3合同签订4执行回款5完结")
|
||||
@QueryField(type = QueryType.EQ)
|
||||
private Integer step;
|
||||
|
||||
@Schema(description = "备注")
|
||||
private String comments;
|
||||
|
||||
@Schema(description = "是否推荐")
|
||||
@QueryField(type = QueryType.EQ)
|
||||
private Integer recommend;
|
||||
|
||||
@Schema(description = "排序(数字越小越靠前)")
|
||||
@QueryField(type = QueryType.EQ)
|
||||
private Integer sortNumber;
|
||||
|
||||
@Schema(description = "状态, 0正常, 1冻结")
|
||||
@QueryField(type = QueryType.EQ)
|
||||
private Integer status;
|
||||
|
||||
@Schema(description = "是否删除, 0否, 1是")
|
||||
@QueryField(type = QueryType.EQ)
|
||||
private Integer deleted;
|
||||
|
||||
@Schema(description = "用户ID")
|
||||
@QueryField(type = QueryType.EQ)
|
||||
private Integer userId;
|
||||
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package com.gxwebsoft.credit.service;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.service.IService;
|
||||
import com.gxwebsoft.common.core.web.PageResult;
|
||||
import com.gxwebsoft.credit.entity.CreditMpCustomer;
|
||||
import com.gxwebsoft.credit.param.CreditMpCustomerParam;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 小程序端客户Service
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2026-03-16 20:59:17
|
||||
*/
|
||||
public interface CreditMpCustomerService extends IService<CreditMpCustomer> {
|
||||
|
||||
/**
|
||||
* 分页关联查询
|
||||
*
|
||||
* @param param 查询参数
|
||||
* @return PageResult<CreditMpCustomer>
|
||||
*/
|
||||
PageResult<CreditMpCustomer> pageRel(CreditMpCustomerParam param);
|
||||
|
||||
/**
|
||||
* 关联查询全部
|
||||
*
|
||||
* @param param 查询参数
|
||||
* @return List<CreditMpCustomer>
|
||||
*/
|
||||
List<CreditMpCustomer> listRel(CreditMpCustomerParam param);
|
||||
|
||||
/**
|
||||
* 根据id查询
|
||||
*
|
||||
* @param id ID
|
||||
* @return CreditMpCustomer
|
||||
*/
|
||||
CreditMpCustomer getByIdRel(Integer id);
|
||||
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.gxwebsoft.credit.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
|
||||
import com.gxwebsoft.credit.mapper.CreditMpCustomerMapper;
|
||||
import com.gxwebsoft.credit.service.CreditMpCustomerService;
|
||||
import com.gxwebsoft.credit.entity.CreditMpCustomer;
|
||||
import com.gxwebsoft.credit.param.CreditMpCustomerParam;
|
||||
import com.gxwebsoft.common.core.web.PageParam;
|
||||
import com.gxwebsoft.common.core.web.PageResult;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 小程序端客户Service实现
|
||||
*
|
||||
* @author 科技小王子
|
||||
* @since 2026-03-16 20:59:17
|
||||
*/
|
||||
@Service
|
||||
public class CreditMpCustomerServiceImpl extends ServiceImpl<CreditMpCustomerMapper, CreditMpCustomer> implements CreditMpCustomerService {
|
||||
|
||||
@Override
|
||||
public PageResult<CreditMpCustomer> pageRel(CreditMpCustomerParam param) {
|
||||
PageParam<CreditMpCustomer, CreditMpCustomerParam> page = new PageParam<>(param);
|
||||
page.setDefaultOrder("sort_number asc, create_time desc");
|
||||
List<CreditMpCustomer> list = baseMapper.selectPageRel(page, param);
|
||||
return new PageResult<>(list, page.getTotal());
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<CreditMpCustomer> listRel(CreditMpCustomerParam param) {
|
||||
List<CreditMpCustomer> list = baseMapper.selectListRel(param);
|
||||
// 排序
|
||||
PageParam<CreditMpCustomer, CreditMpCustomerParam> page = new PageParam<>();
|
||||
page.setDefaultOrder("sort_number asc, create_time desc");
|
||||
return page.sortRecords(list);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CreditMpCustomer getByIdRel(Integer id) {
|
||||
CreditMpCustomerParam param = new CreditMpCustomerParam();
|
||||
param.setId(id);
|
||||
return param.getOne(baseMapper.selectListRel(param));
|
||||
}
|
||||
|
||||
}
|
||||
@@ -52,6 +52,34 @@ public class GltTicketOrderController extends BaseController {
|
||||
return success(gltTicketOrderService.pageRel(param));
|
||||
}
|
||||
|
||||
@PreAuthorize("isAuthenticated()")
|
||||
@Operation(summary = "配送员端:分页查询可接单的送水订单")
|
||||
@GetMapping("/rider/available")
|
||||
public ApiResult<PageResult<GltTicketOrder>> riderAvailablePage(GltTicketOrderParam param) {
|
||||
User loginUser = getLoginUser();
|
||||
if (loginUser == null) {
|
||||
return fail("请先登录", null);
|
||||
}
|
||||
Integer tenantId = getTenantId();
|
||||
param.setTenantId(tenantId);
|
||||
// 仅允许配送员访问
|
||||
requireActiveRider(loginUser.getUserId(), tenantId);
|
||||
|
||||
// 查询未分配的待配送订单(riderId 为空或0)
|
||||
// 设置为0表示查询未分配的订单,XML中会处理为 IS NULL OR = 0
|
||||
param.setRiderId(0);
|
||||
if (param.getDeliveryStatus() == null) {
|
||||
param.setDeliveryStatus(GltTicketOrderService.DELIVERY_STATUS_WAITING);
|
||||
}
|
||||
// 配送员端默认按期望配送时间优先
|
||||
if (StrUtil.isBlank(param.getSort())) {
|
||||
param.setSort("sendTime asc, createTime desc");
|
||||
}
|
||||
|
||||
// 使用现有的关联查询方法,通过参数控制
|
||||
return success(gltTicketOrderService.pageRel(param));
|
||||
}
|
||||
|
||||
@PreAuthorize("isAuthenticated()")
|
||||
@Operation(summary = "配送员端:分页查询我的送水订单")
|
||||
@GetMapping("/rider/page")
|
||||
@@ -65,8 +93,12 @@ public class GltTicketOrderController extends BaseController {
|
||||
// 仅允许配送员访问
|
||||
requireActiveRider(loginUser.getUserId(), tenantId);
|
||||
|
||||
// 关键修复:配送员只能看到分配给自己的订单
|
||||
param.setRiderId(loginUser.getUserId());
|
||||
|
||||
// 默认查询待配送和配送中的订单
|
||||
if (param.getDeliveryStatus() == null) {
|
||||
// 可以通过参数传递多个状态,这里简化为只查待配送
|
||||
param.setDeliveryStatus(GltTicketOrderService.DELIVERY_STATUS_WAITING);
|
||||
}
|
||||
// 配送员端默认按期望配送时间优先
|
||||
|
||||
@@ -32,7 +32,12 @@
|
||||
AND a.store_id = #{param.storeId}
|
||||
</if>
|
||||
<if test="param.riderId != null">
|
||||
AND a.rider_id = #{param.riderId}
|
||||
<if test="param.riderId == 0">
|
||||
AND (a.rider_id IS NULL OR a.rider_id = 0)
|
||||
</if>
|
||||
<if test="param.riderId != 0">
|
||||
AND a.rider_id = #{param.riderId}
|
||||
</if>
|
||||
</if>
|
||||
<if test="param.deliveryStatus != null">
|
||||
AND a.delivery_status = #{param.deliveryStatus}
|
||||
|
||||
@@ -146,7 +146,9 @@ public class DealerOrderSettlement10584Task {
|
||||
.eq(ShopOrder::getTenantId, TENANT_ID)
|
||||
.eq(ShopOrder::getDeleted, 0)
|
||||
.eq(ShopOrder::getPayStatus, true)
|
||||
.eq(ShopOrder::getIsSettled, 0);
|
||||
.eq(ShopOrder::getIsSettled, 0)
|
||||
// 退款/取消订单不结算,避免“退款后仍发放分红/分润/佣金”
|
||||
.and(w -> w.notIn(ShopOrder::getOrderStatus, 2, 4, 5, 6, 7).or().isNull(ShopOrder::getOrderStatus));
|
||||
|
||||
if (waterFormIds != null && !waterFormIds.isEmpty()) {
|
||||
qw.and(w -> w.eq(ShopOrder::getDeliveryStatus, 20).or().in(ShopOrder::getFormId, waterFormIds));
|
||||
@@ -162,7 +164,9 @@ public class DealerOrderSettlement10584Task {
|
||||
LambdaUpdateWrapper<ShopOrder> uw = new LambdaUpdateWrapper<ShopOrder>()
|
||||
.eq(ShopOrder::getOrderId, orderId)
|
||||
.eq(ShopOrder::getTenantId, TENANT_ID)
|
||||
.eq(ShopOrder::getIsSettled, 0);
|
||||
.eq(ShopOrder::getIsSettled, 0)
|
||||
// 二次防御:退款/取消订单不允许被“认领结算”
|
||||
.and(w -> w.notIn(ShopOrder::getOrderStatus, 2, 4, 5, 6, 7).or().isNull(ShopOrder::getOrderStatus));
|
||||
|
||||
if (waterFormIds != null && !waterFormIds.isEmpty()) {
|
||||
uw.and(w -> w.eq(ShopOrder::getDeliveryStatus, 20).or().in(ShopOrder::getFormId, waterFormIds));
|
||||
|
||||
@@ -105,6 +105,8 @@ public class ShopOrderController extends BaseController {
|
||||
private ShopStoreFenceService shopStoreFenceService;
|
||||
@Resource
|
||||
private GltTicketRevokeService gltTicketRevokeService;
|
||||
@Resource
|
||||
private ShopDealerCommissionRollbackService shopDealerCommissionRollbackService;
|
||||
|
||||
@Operation(summary = "分页查询订单")
|
||||
@GetMapping("/page")
|
||||
@@ -559,6 +561,24 @@ public class ShopOrderController extends BaseController {
|
||||
current.getTenantId(), current.getOrderId(), current.getOrderNo(), e);
|
||||
}
|
||||
|
||||
// 退款成功后回退分红/分润/佣金(从 ShopDealerUser 中扣回;以 ShopDealerCapital 明细为准)
|
||||
try {
|
||||
Integer tenantId = ObjectUtil.defaultIfNull(current.getTenantId(), getTenantId());
|
||||
ShopOrder rollbackOrder = new ShopOrder();
|
||||
rollbackOrder.setTenantId(tenantId);
|
||||
rollbackOrder.setOrderNo(current.getOrderNo());
|
||||
rollbackOrder.setPayPrice(current.getPayPrice());
|
||||
rollbackOrder.setTotalPrice(current.getTotalPrice());
|
||||
boolean rollbackOk = shopDealerCommissionRollbackService.rollbackOnOrderRefund(rollbackOrder, refundAmount);
|
||||
if (!rollbackOk) {
|
||||
logger.error("退款成功但回退分红/分润/佣金失败 - tenantId={}, orderId={}, orderNo={}",
|
||||
tenantId, current.getOrderId(), current.getOrderNo());
|
||||
}
|
||||
} catch (Exception e) {
|
||||
logger.error("退款成功但回退分红/分润/佣金异常 - tenantId={}, orderId={}, orderNo={}",
|
||||
current.getTenantId(), current.getOrderId(), current.getOrderNo(), e);
|
||||
}
|
||||
|
||||
logger.info("订单退款请求成功 - 订单号: {}, 退款单号: {}, 微信退款单号: {}",
|
||||
current.getOrderNo(), refundNo, refundResponse.getTransactionId());
|
||||
return success("退款成功");
|
||||
|
||||
@@ -37,6 +37,10 @@ public class ShopDealerCapital implements Serializable {
|
||||
@Schema(description = "订单编号")
|
||||
private String orderNo;
|
||||
|
||||
@Schema(description = "订单状态")
|
||||
@TableField(exist = false)
|
||||
private Integer orderStatus;
|
||||
|
||||
@Schema(description = "资金流动类型 (10佣金收入 20提现支出 30转账支出 40转账收入 50佣金解冻 60配送奖励)")
|
||||
private Integer flowType;
|
||||
|
||||
|
||||
@@ -4,11 +4,12 @@
|
||||
|
||||
<!-- 关联查询sql -->
|
||||
<sql id="selectSql">
|
||||
SELECT a.*, b.order_no, b.month, c.nickname AS nickName, d.nickname AS toNickName
|
||||
SELECT a.*, b.order_no, b.month, c.nickname AS nickName, d.nickname AS toNickName, e.order_status AS orderStatus
|
||||
FROM shop_dealer_capital a
|
||||
LEFT JOIN shop_dealer_order b ON a.order_no = b.order_no
|
||||
LEFT JOIN gxwebsoft_core.sys_user c ON a.user_id = c.user_id and c.deleted = 0
|
||||
LEFT JOIN gxwebsoft_core.sys_user d ON a.to_user_id = d.user_id and d.deleted = 0
|
||||
LEFT JOIN shop_order e ON a.order_no = e.order_no
|
||||
<where>
|
||||
<if test="param.id != null">
|
||||
AND a.id = #{param.id}
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.gxwebsoft.shop.service;
|
||||
|
||||
import com.gxwebsoft.shop.entity.ShopOrder;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/**
|
||||
* 分销/分红/分润:订单退款回退
|
||||
*/
|
||||
public interface ShopDealerCommissionRollbackService {
|
||||
|
||||
/**
|
||||
* 订单退款成功后,按订单号回退已入账(冻结/可提现)的分销佣金/分红/分润等金额。
|
||||
*
|
||||
* @param order 订单(必须包含 tenantId、orderNo)
|
||||
* @param refundAmount 退款金额(允许为空;为空则按全额退款处理)
|
||||
* @return true=执行成功或无可回退数据;false=执行失败
|
||||
*/
|
||||
boolean rollbackOnOrderRefund(ShopOrder order, BigDecimal refundAmount);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,189 @@
|
||||
package com.gxwebsoft.shop.service.impl;
|
||||
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.gxwebsoft.shop.entity.ShopDealerCapital;
|
||||
import com.gxwebsoft.shop.entity.ShopDealerOrder;
|
||||
import com.gxwebsoft.shop.entity.ShopDealerUser;
|
||||
import com.gxwebsoft.shop.entity.ShopOrder;
|
||||
import com.gxwebsoft.shop.service.ShopDealerCapitalService;
|
||||
import com.gxwebsoft.shop.service.ShopDealerCommissionRollbackService;
|
||||
import com.gxwebsoft.shop.service.ShopDealerOrderService;
|
||||
import com.gxwebsoft.shop.service.ShopDealerUserService;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
public class ShopDealerCommissionRollbackServiceImpl implements ShopDealerCommissionRollbackService {
|
||||
|
||||
private static final int FLOW_TYPE_COMMISSION_INCOME = 10;
|
||||
private static final int FLOW_TYPE_COMMISSION_UNFREEZE_MARKER = 50;
|
||||
private static final int FLOW_TYPE_DELIVERY_REWARD = 60;
|
||||
|
||||
@Resource
|
||||
private ShopDealerCapitalService shopDealerCapitalService;
|
||||
|
||||
@Resource
|
||||
private ShopDealerUserService shopDealerUserService;
|
||||
|
||||
@Resource
|
||||
private ShopDealerOrderService shopDealerOrderService;
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public boolean rollbackOnOrderRefund(ShopOrder order, BigDecimal refundAmount) {
|
||||
if (order == null || order.getTenantId() == null || order.getOrderNo() == null || order.getOrderNo().isBlank()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
Integer tenantId = order.getTenantId();
|
||||
String orderNo = order.getOrderNo();
|
||||
|
||||
BigDecimal orderBaseAmount = ObjectUtil.defaultIfNull(order.getPayPrice(), order.getTotalPrice());
|
||||
BigDecimal ratio = resolveRefundRatio(orderBaseAmount, refundAmount);
|
||||
|
||||
List<ShopDealerCapital> capitals = shopDealerCapitalService.list(
|
||||
new LambdaQueryWrapper<ShopDealerCapital>()
|
||||
.eq(ShopDealerCapital::getTenantId, tenantId)
|
||||
.eq(ShopDealerCapital::getOrderNo, orderNo)
|
||||
.in(ShopDealerCapital::getFlowType, FLOW_TYPE_COMMISSION_INCOME, FLOW_TYPE_DELIVERY_REWARD)
|
||||
.isNotNull(ShopDealerCapital::getUserId)
|
||||
.isNotNull(ShopDealerCapital::getMoney)
|
||||
.gt(ShopDealerCapital::getMoney, BigDecimal.ZERO)
|
||||
);
|
||||
|
||||
if (capitals == null || capitals.isEmpty()) {
|
||||
// 仍标记分销订单失效,避免后续统计误判
|
||||
markDealerOrderInvalid(tenantId, orderNo);
|
||||
return true;
|
||||
}
|
||||
|
||||
Map<Integer, BigDecimal> freezeDeductByUser = new HashMap<>();
|
||||
Map<Integer, BigDecimal> moneyDeductByUser = new HashMap<>();
|
||||
Map<Integer, BigDecimal> totalDeductByUser = new HashMap<>();
|
||||
|
||||
for (ShopDealerCapital cap : capitals) {
|
||||
Integer dealerUserId = cap.getUserId();
|
||||
BigDecimal amount = cap.getMoney();
|
||||
if (dealerUserId == null || amount == null || amount.signum() <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
BigDecimal rollbackAmount = amount.multiply(ratio).setScale(2, RoundingMode.HALF_UP);
|
||||
if (rollbackAmount.signum() <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
totalDeductByUser.merge(dealerUserId, rollbackAmount, BigDecimal::add);
|
||||
|
||||
Integer flowType = cap.getFlowType();
|
||||
if (flowType != null && flowType == FLOW_TYPE_DELIVERY_REWARD) {
|
||||
moneyDeductByUser.merge(dealerUserId, rollbackAmount, BigDecimal::add);
|
||||
continue;
|
||||
}
|
||||
|
||||
// 佣金收入:若已解冻(有 flowType=50 marker),则从可提现扣回;否则从冻结扣回
|
||||
boolean unfrozen = hasUnfreezeMarker(tenantId, cap);
|
||||
if (unfrozen) {
|
||||
moneyDeductByUser.merge(dealerUserId, rollbackAmount, BigDecimal::add);
|
||||
} else {
|
||||
freezeDeductByUser.merge(dealerUserId, rollbackAmount, BigDecimal::add);
|
||||
}
|
||||
}
|
||||
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
for (Map.Entry<Integer, BigDecimal> entry : totalDeductByUser.entrySet()) {
|
||||
Integer dealerUserId = entry.getKey();
|
||||
BigDecimal totalDeduct = entry.getValue();
|
||||
if (dealerUserId == null || totalDeduct == null || totalDeduct.signum() <= 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
BigDecimal freezeDeduct = freezeDeductByUser.getOrDefault(dealerUserId, BigDecimal.ZERO);
|
||||
BigDecimal moneyDeduct = moneyDeductByUser.getOrDefault(dealerUserId, BigDecimal.ZERO);
|
||||
|
||||
LambdaUpdateWrapper<ShopDealerUser> uw = new LambdaUpdateWrapper<ShopDealerUser>()
|
||||
.eq(ShopDealerUser::getTenantId, tenantId)
|
||||
.eq(ShopDealerUser::getUserId, dealerUserId)
|
||||
.setSql("total_money = IFNULL(total_money,0) - " + totalDeduct.toPlainString())
|
||||
.set(ShopDealerUser::getUpdateTime, now);
|
||||
|
||||
if (freezeDeduct.signum() > 0) {
|
||||
uw.setSql("freeze_money = IFNULL(freeze_money,0) - " + freezeDeduct.toPlainString());
|
||||
}
|
||||
if (moneyDeduct.signum() > 0) {
|
||||
uw.setSql("money = IFNULL(money,0) - " + moneyDeduct.toPlainString());
|
||||
}
|
||||
|
||||
boolean updated = shopDealerUserService.update(uw);
|
||||
if (!updated) {
|
||||
log.warn("订单退款扣回分销金额失败:未找到分销账户 - tenantId={}, orderNo={}, dealerUserId={}, totalDeduct={}, freezeDeduct={}, moneyDeduct={}",
|
||||
tenantId, orderNo, dealerUserId, totalDeduct, freezeDeduct, moneyDeduct);
|
||||
}
|
||||
}
|
||||
|
||||
markDealerOrderInvalid(tenantId, orderNo);
|
||||
return true;
|
||||
}
|
||||
|
||||
private boolean hasUnfreezeMarker(Integer tenantId, ShopDealerCapital cap) {
|
||||
if (tenantId == null || cap == null || cap.getId() == null || cap.getUserId() == null || cap.getOrderNo() == null) {
|
||||
return false;
|
||||
}
|
||||
String markerComment = buildUnfreezeMarkerComment(cap.getId());
|
||||
return shopDealerCapitalService.count(
|
||||
new LambdaQueryWrapper<ShopDealerCapital>()
|
||||
.eq(ShopDealerCapital::getTenantId, tenantId)
|
||||
.eq(ShopDealerCapital::getFlowType, FLOW_TYPE_COMMISSION_UNFREEZE_MARKER)
|
||||
.eq(ShopDealerCapital::getUserId, cap.getUserId())
|
||||
.eq(ShopDealerCapital::getOrderNo, cap.getOrderNo())
|
||||
.eq(ShopDealerCapital::getComments, markerComment)
|
||||
) > 0;
|
||||
}
|
||||
|
||||
private String buildUnfreezeMarkerComment(Integer capitalId) {
|
||||
return "佣金解冻(capitalId=" + capitalId + ")";
|
||||
}
|
||||
|
||||
private BigDecimal resolveRefundRatio(BigDecimal orderBaseAmount, BigDecimal refundAmount) {
|
||||
if (refundAmount == null || refundAmount.signum() <= 0) {
|
||||
return BigDecimal.ONE;
|
||||
}
|
||||
if (orderBaseAmount == null || orderBaseAmount.signum() <= 0) {
|
||||
return BigDecimal.ONE;
|
||||
}
|
||||
if (refundAmount.compareTo(orderBaseAmount) >= 0) {
|
||||
return BigDecimal.ONE;
|
||||
}
|
||||
return refundAmount.divide(orderBaseAmount, 10, RoundingMode.HALF_UP);
|
||||
}
|
||||
|
||||
private void markDealerOrderInvalid(Integer tenantId, String orderNo) {
|
||||
if (tenantId == null || orderNo == null || orderNo.isBlank()) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
shopDealerOrderService.update(
|
||||
new LambdaUpdateWrapper<ShopDealerOrder>()
|
||||
.eq(ShopDealerOrder::getTenantId, tenantId)
|
||||
.eq(ShopDealerOrder::getOrderNo, orderNo)
|
||||
.set(ShopDealerOrder::getIsInvalid, 1)
|
||||
.set(ShopDealerOrder::getUpdateTime, LocalDateTime.now())
|
||||
);
|
||||
} catch (Exception e) {
|
||||
log.warn("订单退款标记分销订单失效失败 - tenantId={}, orderNo={}", tenantId, orderNo, e);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,9 +4,9 @@ server:
|
||||
# 数据源配置
|
||||
spring:
|
||||
datasource:
|
||||
url: jdbc:mysql://1Panel-mysql-XsWW:3306/modules?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
|
||||
username: modules
|
||||
password: tYmmMGh5wpwXR3ae
|
||||
url: jdbc:mysql://1Panel-mysql-XsWW:3306/gltdb?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
|
||||
username: gltdb
|
||||
password: EeD4FtzyA5ksj7Bk
|
||||
driver-class-name: com.mysql.cj.jdbc.Driver
|
||||
type: com.alibaba.druid.pool.DruidDataSource
|
||||
druid:
|
||||
|
||||
@@ -4,7 +4,7 @@ server:
|
||||
# 多环境配置
|
||||
spring:
|
||||
profiles:
|
||||
active: glt2
|
||||
active: ysb2
|
||||
|
||||
application:
|
||||
name: server
|
||||
|
||||
381
src/test/java/com/gxwebsoft/generator/YsbGenerator.java
Normal file
381
src/test/java/com/gxwebsoft/generator/YsbGenerator.java
Normal file
@@ -0,0 +1,381 @@
|
||||
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.nio.file.Files;
|
||||
import java.nio.file.Paths;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
/**
|
||||
* CMS模块-代码生成工具
|
||||
*
|
||||
* @author WebSoft
|
||||
* @since 2021-09-05 00:31:14
|
||||
*/
|
||||
public class YsbGenerator {
|
||||
// 输出位置
|
||||
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-10579";
|
||||
// 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://47.119.165.234:13308/ysb?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 = "ysb";
|
||||
private static final String DB_PASSWORD = "5Zf45CE2YneBfXkR";
|
||||
// 包名
|
||||
private static final String PACKAGE_NAME = "com.gxwebsoft";
|
||||
// 模块名
|
||||
private static final String MODULE_NAME = "credit";
|
||||
// 需要生成的表
|
||||
private static final String[] TABLE_NAMES = new String[]{
|
||||
"credit_mp_customer",
|
||||
};
|
||||
// 需要去除的表前缀
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user