Merge branch 'master' into dev_deploy
commit
fd522335f0
|
|
@ -7,12 +7,16 @@ import cn.hutool.core.text.csv.CsvUtil;
|
|||
import cn.iocoder.yudao.framework.common.util.object.ObjectUtils;
|
||||
import cn.iocoder.yudao.framework.ip.core.Area;
|
||||
import cn.iocoder.yudao.framework.ip.core.enums.AreaTypeEnum;
|
||||
import lombok.NonNull;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
|
||||
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
|
||||
|
||||
/**
|
||||
* 区域工具类
|
||||
|
|
@ -108,7 +112,7 @@ public class AreaUtils {
|
|||
// “递归”父节点
|
||||
area = area.getParent();
|
||||
if (area == null
|
||||
|| ObjectUtils.equalsAny(area.getId(), Area.ID_GLOBAL, Area.ID_CHINA)) { // 跳过父节点为中国的情况
|
||||
|| ObjectUtils.equalsAny(area.getId(), Area.ID_GLOBAL, Area.ID_CHINA)) { // 跳过父节点为中国的情况
|
||||
break;
|
||||
}
|
||||
sb.insert(0, separator);
|
||||
|
|
@ -116,4 +120,43 @@ public class AreaUtils {
|
|||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取指定类型的区域列表
|
||||
*
|
||||
* @param type 区域类型
|
||||
* @param func 转换函数
|
||||
* @param <T> 结果类型
|
||||
* @return 区域列表
|
||||
*/
|
||||
public static <T> List<T> getByType(AreaTypeEnum type, Function<Area, T> func) {
|
||||
return convertList(areas.values(), func, area -> type.getType().equals(area.getType()));
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据区域编号、上级区域类型,获取上级区域编号
|
||||
*
|
||||
* @param id 区域编号
|
||||
* @param type 区域类型
|
||||
* @return 上级区域编号
|
||||
*/
|
||||
public static Integer getParentIdByType(Integer id, @NonNull AreaTypeEnum type) {
|
||||
for (int i = 0; i < Byte.MAX_VALUE; i++) {
|
||||
Area area = AreaUtils.getArea(id);
|
||||
if (area == null) {
|
||||
return null;
|
||||
}
|
||||
// 情况一:匹配到,返回它
|
||||
if (type.getType().equals(area.getType())) {
|
||||
return area.getId();
|
||||
}
|
||||
// 情况二:找到根节点,返回空
|
||||
if (area.getParent() == null || area.getParent().getId() == null) {
|
||||
return null;
|
||||
}
|
||||
// 其它:继续向上查找
|
||||
id = area.getParent().getId();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,6 +4,8 @@ import cn.iocoder.yudao.framework.pay.core.client.dto.order.PayOrderRespDTO;
|
|||
import cn.iocoder.yudao.framework.pay.core.client.dto.order.PayOrderUnifiedReqDTO;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.dto.refund.PayRefundRespDTO;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.dto.refund.PayRefundUnifiedReqDTO;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.dto.transfer.PayTransferRespDTO;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.dto.transfer.PayTransferUnifiedReqDTO;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
|
|
@ -76,4 +78,12 @@ public interface PayClient {
|
|||
*/
|
||||
PayRefundRespDTO getRefund(String outTradeNo, String outRefundNo);
|
||||
|
||||
/**
|
||||
* 调用渠道,进行转账
|
||||
*
|
||||
* @param reqDTO 统一转账请求信息
|
||||
* @return 转账信息
|
||||
*/
|
||||
PayTransferRespDTO unifiedTransfer(PayTransferUnifiedReqDTO reqDTO);
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
package cn.iocoder.yudao.framework.pay.core.client;
|
||||
|
||||
import cn.iocoder.yudao.framework.pay.core.enums.channel.PayChannelEnum;
|
||||
|
||||
/**
|
||||
* 支付客户端的工厂接口
|
||||
*
|
||||
|
|
@ -25,4 +27,12 @@ public interface PayClientFactory {
|
|||
<Config extends PayClientConfig> void createOrUpdatePayClient(Long channelId, String channelCode,
|
||||
Config config);
|
||||
|
||||
/**
|
||||
* 注册支付客户端 Class,用于模块中实现的 PayClient
|
||||
*
|
||||
* @param channel 支付渠道的编码的枚举
|
||||
* @param payClientClass 支付客户端 class
|
||||
*/
|
||||
void registerPayClientClass(PayChannelEnum channel, Class<?> payClientClass);
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,96 @@
|
|||
package cn.iocoder.yudao.framework.pay.core.client.dto.transfer;
|
||||
|
||||
import cn.iocoder.yudao.framework.pay.core.enums.transfer.PayTransferStatusRespEnum;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 统一转账 Response DTO
|
||||
*
|
||||
* @author jason
|
||||
*/
|
||||
@Data
|
||||
public class PayTransferRespDTO {
|
||||
|
||||
/**
|
||||
* 转账状态
|
||||
*
|
||||
* 关联 {@link PayTransferStatusRespEnum#getStatus()}
|
||||
*/
|
||||
private Integer status;
|
||||
|
||||
/**
|
||||
* 外部转账单号
|
||||
*
|
||||
*/
|
||||
private String outTransferNo;
|
||||
|
||||
/**
|
||||
* 支付渠道编号
|
||||
*/
|
||||
private String channelOrderNo;
|
||||
|
||||
/**
|
||||
* 支付成功时间
|
||||
*/
|
||||
private LocalDateTime successTime;
|
||||
|
||||
/**
|
||||
* 原始的返回结果
|
||||
*/
|
||||
private Object rawData;
|
||||
|
||||
/**
|
||||
* 调用渠道的错误码
|
||||
*/
|
||||
private String channelErrorCode;
|
||||
/**
|
||||
* 调用渠道报错时,错误信息
|
||||
*/
|
||||
private String channelErrorMsg;
|
||||
|
||||
/**
|
||||
* 创建【WAITING】状态的转账返回
|
||||
*/
|
||||
public static PayTransferRespDTO waitingOf(String channelOrderNo,
|
||||
String outTransferNo, Object rawData) {
|
||||
PayTransferRespDTO respDTO = new PayTransferRespDTO();
|
||||
respDTO.status = PayTransferStatusRespEnum.WAITING.getStatus();
|
||||
respDTO.channelOrderNo = channelOrderNo;
|
||||
respDTO.outTransferNo = outTransferNo;
|
||||
respDTO.rawData = rawData;
|
||||
return respDTO;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建【CLOSED】状态的转账返回
|
||||
*/
|
||||
public static PayTransferRespDTO closedOf(String channelErrorCode, String channelErrorMsg,
|
||||
String outTransferNo, Object rawData) {
|
||||
PayTransferRespDTO respDTO = new PayTransferRespDTO();
|
||||
respDTO.status = PayTransferStatusRespEnum.CLOSED.getStatus();
|
||||
respDTO.channelErrorCode = channelErrorCode;
|
||||
respDTO.channelErrorMsg = channelErrorMsg;
|
||||
// 相对通用的字段
|
||||
respDTO.outTransferNo = outTransferNo;
|
||||
respDTO.rawData = rawData;
|
||||
return respDTO;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建【SUCCESS】状态的转账返回
|
||||
*/
|
||||
public static PayTransferRespDTO successOf(String channelTransferNo, LocalDateTime successTime,
|
||||
String outTransferNo, Object rawData) {
|
||||
PayTransferRespDTO respDTO = new PayTransferRespDTO();
|
||||
respDTO.status = PayTransferStatusRespEnum.SUCCESS.getStatus();
|
||||
respDTO.channelOrderNo = channelTransferNo;
|
||||
respDTO.successTime = successTime;
|
||||
// 相对通用的字段
|
||||
respDTO.outTransferNo = outTransferNo;
|
||||
respDTO.rawData = rawData;
|
||||
return respDTO;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,66 @@
|
|||
package cn.iocoder.yudao.framework.pay.core.client.dto.transfer;
|
||||
|
||||
import cn.iocoder.yudao.framework.common.validation.InEnum;
|
||||
import cn.iocoder.yudao.framework.pay.core.enums.transfer.PayTransferTypeEnum;
|
||||
import lombok.Data;
|
||||
import org.hibernate.validator.constraints.Length;
|
||||
|
||||
import javax.validation.constraints.Min;
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
import javax.validation.constraints.NotNull;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 统一转账 Request DTO
|
||||
*
|
||||
* @author jason
|
||||
*/
|
||||
@Data
|
||||
public class PayTransferUnifiedReqDTO {
|
||||
|
||||
/**
|
||||
* 转账类型
|
||||
*
|
||||
* 关联 {@link PayTransferTypeEnum#getType()}
|
||||
*/
|
||||
@NotNull(message = "转账类型不能为空")
|
||||
@InEnum(PayTransferTypeEnum.class)
|
||||
private Integer type;
|
||||
|
||||
/**
|
||||
* 用户 IP
|
||||
*/
|
||||
@NotEmpty(message = "用户 IP 不能为空")
|
||||
private String userIp;
|
||||
|
||||
@NotEmpty(message = "外部转账单编号不能为空")
|
||||
private String outTransferNo;
|
||||
|
||||
/**
|
||||
* 转账金额,单位:分
|
||||
*/
|
||||
@NotNull(message = "转账金额不能为空")
|
||||
@Min(value = 1, message = "转账金额必须大于零")
|
||||
private Integer price;
|
||||
|
||||
/**
|
||||
* 转账标题
|
||||
*/
|
||||
@NotEmpty(message = "转账标题不能为空")
|
||||
@Length(max = 128, message = "转账标题不能超过 128")
|
||||
private String title;
|
||||
|
||||
/**
|
||||
* 收款方信息。
|
||||
*
|
||||
* 转账类型 {@link #type} 不同,收款方信息不同
|
||||
*/
|
||||
@NotEmpty(message = "收款方信息 不能为空")
|
||||
private Map<String, String> payeeInfo;
|
||||
|
||||
/**
|
||||
* 支付渠道的额外参数
|
||||
*/
|
||||
private Map<String, String> channelExtras;
|
||||
|
||||
}
|
||||
|
|
@ -8,6 +8,8 @@ import cn.iocoder.yudao.framework.pay.core.client.dto.order.PayOrderRespDTO;
|
|||
import cn.iocoder.yudao.framework.pay.core.client.dto.order.PayOrderUnifiedReqDTO;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.dto.refund.PayRefundRespDTO;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.dto.refund.PayRefundUnifiedReqDTO;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.dto.transfer.PayTransferRespDTO;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.dto.transfer.PayTransferUnifiedReqDTO;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.exception.PayException;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
|
|
@ -181,6 +183,26 @@ public abstract class AbstractPayClient<Config extends PayClientConfig> implemen
|
|||
protected abstract PayRefundRespDTO doGetRefund(String outTradeNo, String outRefundNo)
|
||||
throws Throwable;
|
||||
|
||||
@Override
|
||||
public final PayTransferRespDTO unifiedTransfer(PayTransferUnifiedReqDTO reqDTO) {
|
||||
ValidationUtils.validate(reqDTO);
|
||||
PayTransferRespDTO resp;
|
||||
try{
|
||||
resp = doUnifiedTransfer(reqDTO);
|
||||
}catch (ServiceException ex) { // 业务异常,都是实现类已经翻译,所以直接抛出即可
|
||||
throw ex;
|
||||
} catch (Throwable ex) {
|
||||
// 系统异常,则包装成 PayException 异常抛出
|
||||
log.error("[unifiedTransfer][客户端({}) request({}) 发起转账异常]",
|
||||
getId(), toJsonString(reqDTO), ex);
|
||||
throw buildPayException(ex);
|
||||
}
|
||||
return resp;
|
||||
}
|
||||
|
||||
protected abstract PayTransferRespDTO doUnifiedTransfer(PayTransferUnifiedReqDTO reqDTO)
|
||||
throws Throwable;
|
||||
|
||||
// ========== 各种工具方法 ==========
|
||||
|
||||
private PayException buildPayException(Throwable ex) {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,31 @@
|
|||
package cn.iocoder.yudao.framework.pay.core.client.impl;
|
||||
|
||||
import cn.iocoder.yudao.framework.pay.core.client.PayClientConfig;
|
||||
import lombok.Data;
|
||||
|
||||
import javax.validation.Validator;
|
||||
|
||||
/**
|
||||
* 无需任何配置 PayClientConfig 实现类
|
||||
*
|
||||
* @author jason
|
||||
*/
|
||||
@Data
|
||||
public class NonePayClientConfig implements PayClientConfig {
|
||||
|
||||
/**
|
||||
* 配置名称
|
||||
* <p>
|
||||
* 如果不加任何属性,JsonUtils.parseObject2 解析会报错,所以暂时加个名称
|
||||
*/
|
||||
private String name;
|
||||
|
||||
public NonePayClientConfig(){
|
||||
this.name = "none-config";
|
||||
}
|
||||
|
||||
@Override
|
||||
public void validate(Validator validator) {
|
||||
// 无任何配置不需要校验
|
||||
}
|
||||
}
|
||||
|
|
@ -1,19 +1,22 @@
|
|||
package cn.iocoder.yudao.framework.pay.core.client.impl;
|
||||
|
||||
import cn.hutool.core.lang.Assert;
|
||||
import cn.hutool.core.util.ReflectUtil;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.PayClient;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.PayClientConfig;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.PayClientFactory;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.impl.alipay.*;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.impl.mock.MockPayClient;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.impl.mock.MockPayClientConfig;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.impl.weixin.*;
|
||||
import cn.iocoder.yudao.framework.pay.core.enums.channel.PayChannelEnum;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
import java.util.concurrent.ConcurrentMap;
|
||||
|
||||
import static cn.iocoder.yudao.framework.pay.core.enums.channel.PayChannelEnum.*;
|
||||
|
||||
/**
|
||||
* 支付客户端的工厂实现类
|
||||
*
|
||||
|
|
@ -24,10 +27,38 @@ public class PayClientFactoryImpl implements PayClientFactory {
|
|||
|
||||
/**
|
||||
* 支付客户端 Map
|
||||
*
|
||||
* key:渠道编号
|
||||
*/
|
||||
private final ConcurrentMap<Long, AbstractPayClient<?>> clients = new ConcurrentHashMap<>();
|
||||
|
||||
/**
|
||||
* 支付客户端 Class Map
|
||||
*/
|
||||
private final Map<PayChannelEnum, Class<?>> clientClass = new ConcurrentHashMap<>();
|
||||
|
||||
public PayClientFactoryImpl() {
|
||||
// 微信支付客户端
|
||||
clientClass.put(WX_PUB, WxPubPayClient.class);
|
||||
clientClass.put(WX_LITE, WxLitePayClient.class);
|
||||
clientClass.put(WX_APP, WxAppPayClient.class);
|
||||
clientClass.put(WX_BAR, WxBarPayClient.class);
|
||||
clientClass.put(WX_NATIVE, WxNativePayClient.class);
|
||||
// 支付包支付客户端
|
||||
clientClass.put(ALIPAY_WAP, AlipayWapPayClient.class);
|
||||
clientClass.put(ALIPAY_QR, AlipayQrPayClient.class);
|
||||
clientClass.put(ALIPAY_APP, AlipayAppPayClient.class);
|
||||
clientClass.put(ALIPAY_PC, AlipayPcPayClient.class);
|
||||
clientClass.put(ALIPAY_BAR, AlipayBarPayClient.class);
|
||||
// Mock 支付客户端
|
||||
clientClass.put(MOCK, MockPayClient.class);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void registerPayClientClass(PayChannelEnum channel, Class<?> payClientClass) {
|
||||
clientClass.put(channel, payClientClass);
|
||||
}
|
||||
|
||||
@Override
|
||||
public PayClient getPayClient(Long channelId) {
|
||||
AbstractPayClient<?> client = clients.get(channelId);
|
||||
|
|
@ -52,30 +83,13 @@ public class PayClientFactoryImpl implements PayClientFactory {
|
|||
}
|
||||
|
||||
@SuppressWarnings("unchecked")
|
||||
private <Config extends PayClientConfig> AbstractPayClient<Config> createPayClient(
|
||||
Long channelId, String channelCode, Config config) {
|
||||
private <Config extends PayClientConfig> AbstractPayClient<Config> createPayClient(Long channelId, String channelCode,
|
||||
Config config) {
|
||||
PayChannelEnum channelEnum = PayChannelEnum.getByCode(channelCode);
|
||||
Assert.notNull(channelEnum, String.format("支付渠道(%s) 为空", channelEnum));
|
||||
// 创建客户端
|
||||
switch (channelEnum) {
|
||||
// 微信支付
|
||||
case WX_PUB: return (AbstractPayClient<Config>) new WxPubPayClient(channelId, (WxPayClientConfig) config);
|
||||
case WX_LITE: return (AbstractPayClient<Config>) new WxLitePayClient(channelId, (WxPayClientConfig) config);
|
||||
case WX_APP: return (AbstractPayClient<Config>) new WxAppPayClient(channelId, (WxPayClientConfig) config);
|
||||
case WX_BAR: return (AbstractPayClient<Config>) new WxBarPayClient(channelId, (WxPayClientConfig) config);
|
||||
case WX_NATIVE: return (AbstractPayClient<Config>) new WxNativePayClient(channelId, (WxPayClientConfig) config);
|
||||
// 支付宝支付
|
||||
case ALIPAY_WAP: return (AbstractPayClient<Config>) new AlipayWapPayClient(channelId, (AlipayPayClientConfig) config);
|
||||
case ALIPAY_QR: return (AbstractPayClient<Config>) new AlipayQrPayClient(channelId, (AlipayPayClientConfig) config);
|
||||
case ALIPAY_APP: return (AbstractPayClient<Config>) new AlipayAppPayClient(channelId, (AlipayPayClientConfig) config);
|
||||
case ALIPAY_PC: return (AbstractPayClient<Config>) new AlipayPcPayClient(channelId, (AlipayPayClientConfig) config);
|
||||
case ALIPAY_BAR: return (AbstractPayClient<Config>) new AlipayBarPayClient(channelId, (AlipayPayClientConfig) config);
|
||||
// 其它支付
|
||||
case MOCK: return (AbstractPayClient<Config>) new MockPayClient(channelId, (MockPayClientConfig) config);
|
||||
}
|
||||
// 创建失败,错误日志 + 抛出异常
|
||||
log.error("[createPayClient][配置({}) 找不到合适的客户端实现]", config);
|
||||
throw new IllegalArgumentException(String.format("配置(%s) 找不到合适的客户端实现", config));
|
||||
Assert.notNull(channelEnum, String.format("支付渠道(%s) 为空", channelCode));
|
||||
Class<?> payClientClass = clientClass.get(channelEnum);
|
||||
Assert.notNull(payClientClass, String.format("支付渠道(%s) Class 为空", channelCode));
|
||||
return (AbstractPayClient<Config>) ReflectUtil.newInstance(payClientClass, channelId, config);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,27 +6,32 @@ import cn.hutool.core.lang.Assert;
|
|||
import cn.hutool.core.map.MapUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import cn.hutool.http.HttpUtil;
|
||||
import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
|
||||
import cn.iocoder.yudao.framework.common.util.object.ObjectUtils;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.dto.order.PayOrderRespDTO;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.dto.order.PayOrderUnifiedReqDTO;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.dto.refund.PayRefundRespDTO;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.dto.refund.PayRefundUnifiedReqDTO;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.dto.transfer.PayTransferRespDTO;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.dto.transfer.PayTransferUnifiedReqDTO;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.impl.AbstractPayClient;
|
||||
import cn.iocoder.yudao.framework.pay.core.enums.order.PayOrderStatusRespEnum;
|
||||
import cn.iocoder.yudao.framework.pay.core.enums.transfer.PayTransferTypeEnum;
|
||||
import com.alipay.api.AlipayApiException;
|
||||
import com.alipay.api.AlipayConfig;
|
||||
import com.alipay.api.AlipayResponse;
|
||||
import com.alipay.api.DefaultAlipayClient;
|
||||
import com.alipay.api.domain.AlipayTradeFastpayRefundQueryModel;
|
||||
import com.alipay.api.domain.AlipayTradeQueryModel;
|
||||
import com.alipay.api.domain.AlipayTradeRefundModel;
|
||||
import com.alipay.api.domain.*;
|
||||
import com.alipay.api.internal.util.AlipaySignature;
|
||||
import com.alipay.api.request.AlipayFundTransUniTransferRequest;
|
||||
import com.alipay.api.request.AlipayTradeFastpayRefundQueryRequest;
|
||||
import com.alipay.api.request.AlipayTradeQueryRequest;
|
||||
import com.alipay.api.request.AlipayTradeRefundRequest;
|
||||
import com.alipay.api.response.AlipayFundTransUniTransferResponse;
|
||||
import com.alipay.api.response.AlipayTradeFastpayRefundQueryResponse;
|
||||
import com.alipay.api.response.AlipayTradeQueryResponse;
|
||||
import com.alipay.api.response.AlipayTradeRefundResponse;
|
||||
import lombok.Getter;
|
||||
import lombok.SneakyThrows;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
|
|
@ -38,6 +43,9 @@ import java.util.Objects;
|
|||
import java.util.function.Supplier;
|
||||
|
||||
import static cn.hutool.core.date.DatePattern.NORM_DATETIME_FORMATTER;
|
||||
import static cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants.BAD_REQUEST;
|
||||
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception0;
|
||||
import static cn.iocoder.yudao.framework.pay.core.client.impl.alipay.AlipayPayClientConfig.MODE_CERTIFICATE;
|
||||
|
||||
/**
|
||||
* 支付宝抽象类,实现支付宝统一的接口、以及部分实现(退款)
|
||||
|
|
@ -47,6 +55,7 @@ import static cn.hutool.core.date.DatePattern.NORM_DATETIME_FORMATTER;
|
|||
@Slf4j
|
||||
public abstract class AbstractAlipayPayClient extends AbstractPayClient<AlipayPayClientConfig> {
|
||||
|
||||
@Getter // 仅用于单测场景
|
||||
protected DefaultAlipayClient client;
|
||||
|
||||
public AbstractAlipayPayClient(Long channelId, String channelCode, AlipayPayClientConfig config) {
|
||||
|
|
@ -103,16 +112,20 @@ public abstract class AbstractAlipayPayClient extends AbstractPayClient<AlipayPa
|
|||
// 1.2 构建 AlipayTradeQueryRequest 请求
|
||||
AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
|
||||
request.setBizModel(model);
|
||||
|
||||
// 2.1 执行请求
|
||||
AlipayTradeQueryResponse response = client.execute(request);
|
||||
AlipayTradeQueryResponse response;
|
||||
if (Objects.equals(config.getMode(), MODE_CERTIFICATE)) {
|
||||
// 证书模式
|
||||
response = client.certificateExecute(request);
|
||||
} else {
|
||||
response = client.execute(request);
|
||||
}
|
||||
if (!response.isSuccess()) { // 不成功,例如说订单不存在
|
||||
return PayOrderRespDTO.closedOf(response.getSubCode(), response.getSubMsg(),
|
||||
outTradeNo, response);
|
||||
}
|
||||
// 2.2 解析订单的状态
|
||||
Integer status = parseStatus(response.getTradeStatus());
|
||||
Assert.notNull(status, (Supplier<Throwable>) () -> {
|
||||
Assert.notNull(status, () -> {
|
||||
throw new IllegalArgumentException(StrUtil.format("body({}) 的 trade_status 不正确", response.getBody()));
|
||||
});
|
||||
return PayOrderRespDTO.of(status, response.getTradeNo(), response.getBuyerUserId(), LocalDateTimeUtil.of(response.getSendPayDate()),
|
||||
|
|
@ -146,9 +159,18 @@ public abstract class AbstractAlipayPayClient extends AbstractPayClient<AlipayPa
|
|||
request.setBizModel(model);
|
||||
|
||||
// 2.1 执行请求
|
||||
AlipayTradeRefundResponse response = client.execute(request);
|
||||
AlipayTradeRefundResponse response;
|
||||
if (Objects.equals(config.getMode(), MODE_CERTIFICATE)) { // 证书模式
|
||||
response = client.certificateExecute(request);
|
||||
} else {
|
||||
response = client.execute(request);
|
||||
}
|
||||
if (!response.isSuccess()) {
|
||||
return PayRefundRespDTO.failureOf(reqDTO.getOutRefundNo(), response);
|
||||
// 当出现 ACQ.SYSTEM_ERROR, 退款可能成功也可能失败。 返回 WAIT 状态. 后续 job 会轮询
|
||||
if (ObjectUtils.equalsAny(response.getSubCode(), "ACQ.SYSTEM_ERROR", "SYSTEM_ERROR")) {
|
||||
return PayRefundRespDTO.waitingOf(null, reqDTO.getOutRefundNo(), response);
|
||||
}
|
||||
return PayRefundRespDTO.failureOf(response.getSubCode(), response.getSubMsg(), reqDTO.getOutRefundNo(), response);
|
||||
}
|
||||
// 2.2 创建返回结果
|
||||
// 支付宝只要退款调用返回 success,就认为退款成功,不需要回调。具体可见 parseNotify 方法的说明。
|
||||
|
|
@ -179,7 +201,12 @@ public abstract class AbstractAlipayPayClient extends AbstractPayClient<AlipayPa
|
|||
request.setBizModel(model);
|
||||
|
||||
// 2.1 执行请求
|
||||
AlipayTradeFastpayRefundQueryResponse response = client.execute(request);
|
||||
AlipayTradeFastpayRefundQueryResponse response;
|
||||
if (Objects.equals(config.getMode(), MODE_CERTIFICATE)) { // 证书模式
|
||||
response = client.certificateExecute(request);
|
||||
} else {
|
||||
response = client.execute(request);
|
||||
}
|
||||
if (!response.isSuccess()) {
|
||||
// 明确不存在的情况,应该就是失败,可进行关闭
|
||||
if (ObjectUtils.equalsAny(response.getSubCode(), "TRADE_NOT_EXIST", "ACQ.TRADE_NOT_EXIST")) {
|
||||
|
|
@ -196,6 +223,70 @@ public abstract class AbstractAlipayPayClient extends AbstractPayClient<AlipayPa
|
|||
return PayRefundRespDTO.waitingOf(null, outRefundNo, response);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected PayTransferRespDTO doUnifiedTransfer(PayTransferUnifiedReqDTO reqDTO) throws AlipayApiException {
|
||||
// 1.1 校验公钥类型 必须使用公钥证书模式
|
||||
if (!Objects.equals(config.getMode(), MODE_CERTIFICATE)) {
|
||||
throw new IllegalStateException("支付宝单笔转账必须使用公钥证书模式");
|
||||
}
|
||||
|
||||
// 1.2 构建 AlipayFundTransUniTransferModel
|
||||
AlipayFundTransUniTransferModel model = new AlipayFundTransUniTransferModel();
|
||||
// ① 通用的参数
|
||||
model.setTransAmount(formatAmount(reqDTO.getPrice())); // 转账金额
|
||||
model.setOrderTitle(reqDTO.getTitle()); // 转账业务的标题,用于在支付宝用户的账单里显示。
|
||||
model.setOutBizNo(reqDTO.getOutTransferNo());
|
||||
model.setProductCode("TRANS_ACCOUNT_NO_PWD"); // 销售产品码。单笔无密转账固定为 TRANS_ACCOUNT_NO_PWD
|
||||
model.setBizScene("DIRECT_TRANSFER"); // 业务场景 单笔无密转账固定为 DIRECT_TRANSFER
|
||||
model.setBusinessParams(JsonUtils.toJsonString(reqDTO.getChannelExtras()));
|
||||
PayTransferTypeEnum transferType = PayTransferTypeEnum.typeOf(reqDTO.getType());
|
||||
switch (transferType) {
|
||||
// TODO @jason:是不是不用传递 transferType 参数哈?因为应该已经明确是支付宝啦?
|
||||
// @芋艿。 是不是还要考虑转账到银行卡。所以传 transferType 但是转账到银行卡不知道要如何测试??
|
||||
case ALIPAY_BALANCE: {
|
||||
// ② 个性化的参数
|
||||
Participant payeeInfo = new Participant();
|
||||
payeeInfo.setIdentityType("ALIPAY_LOGON_ID");
|
||||
String logonId = MapUtil.getStr(reqDTO.getPayeeInfo(), "ALIPAY_LOGON_ID");
|
||||
if (StrUtil.isEmpty(logonId)) {
|
||||
throw exception0(BAD_REQUEST.getCode(), "支付包登录 ID 不能为空");
|
||||
}
|
||||
String accountName = MapUtil.getStr(reqDTO.getPayeeInfo(), "ALIPAY_ACCOUNT_NAME");
|
||||
if (StrUtil.isEmpty(accountName)) {
|
||||
throw exception0(BAD_REQUEST.getCode(), "支付包账户名称不能为空");
|
||||
}
|
||||
payeeInfo.setIdentity(logonId); // 支付宝登录号
|
||||
payeeInfo.setName(accountName); // 支付宝账号姓名
|
||||
model.setPayeeInfo(payeeInfo);
|
||||
// 1.3 构建 AlipayFundTransUniTransferRequest
|
||||
AlipayFundTransUniTransferRequest request = new AlipayFundTransUniTransferRequest();
|
||||
request.setBizModel(model);
|
||||
// 执行请求
|
||||
AlipayFundTransUniTransferResponse response = client.certificateExecute(request);
|
||||
// 处理结果
|
||||
if (!response.isSuccess()) {
|
||||
// 当出现 SYSTEM_ERROR, 转账可能成功也可能失败。 返回 WAIT 状态. 后续 job 会轮询
|
||||
if (ObjectUtils.equalsAny(response.getSubCode(), "SYSTEM_ERROR", "ACQ.SYSTEM_ERROR")) {
|
||||
return PayTransferRespDTO.waitingOf(null, reqDTO.getOutTransferNo(), response);
|
||||
}
|
||||
return PayTransferRespDTO.closedOf(response.getSubCode(), response.getSubMsg(),
|
||||
reqDTO.getOutTransferNo(), response);
|
||||
}
|
||||
return PayTransferRespDTO.successOf(response.getOrderId(), parseTime(response.getTransDate()),
|
||||
response.getOutBizNo(), response);
|
||||
}
|
||||
case BANK_CARD: {
|
||||
Participant payeeInfo = new Participant();
|
||||
payeeInfo.setIdentityType("BANKCARD_ACCOUNT");
|
||||
// TODO 待实现
|
||||
throw new UnsupportedOperationException("待实现");
|
||||
}
|
||||
default: {
|
||||
throw new IllegalStateException("不正确的转账类型: " + transferType);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ========== 各种工具方法 ==========
|
||||
|
||||
protected String formatAmount(Integer amount) {
|
||||
|
|
|
|||
|
|
@ -56,5 +56,4 @@ public class AlipayAppPayClient extends AbstractAlipayPayClient {
|
|||
return PayOrderRespDTO.waitingOf(displayMode, response.getBody(),
|
||||
reqDTO.getOutTradeNo(), response);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -13,8 +13,12 @@ import com.alipay.api.request.AlipayTradePayRequest;
|
|||
import com.alipay.api.response.AlipayTradePayResponse;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Objects;
|
||||
|
||||
import static cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants.BAD_REQUEST;
|
||||
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception0;
|
||||
import static cn.iocoder.yudao.framework.pay.core.client.impl.alipay.AlipayPayClientConfig.MODE_CERTIFICATE;
|
||||
|
||||
/**
|
||||
* 支付宝【条码支付】的 PayClient 实现类
|
||||
|
|
@ -57,18 +61,25 @@ public class AlipayBarPayClient extends AbstractAlipayPayClient {
|
|||
request.setReturnUrl(reqDTO.getReturnUrl());
|
||||
|
||||
// 2.1 执行请求
|
||||
AlipayTradePayResponse response = client.execute(request);
|
||||
AlipayTradePayResponse response;
|
||||
if (Objects.equals(config.getMode(), MODE_CERTIFICATE)) {
|
||||
// 证书模式
|
||||
response = client.certificateExecute(request);
|
||||
} else {
|
||||
response = client.execute(request);
|
||||
}
|
||||
// 2.2 处理结果
|
||||
if (!response.isSuccess()) {
|
||||
return buildClosedPayOrderRespDTO(reqDTO, response);
|
||||
}
|
||||
if ("10000".equals(response.getCode())) { // 免密支付
|
||||
return PayOrderRespDTO.successOf(response.getTradeNo(), response.getBuyerUserId(), LocalDateTimeUtil.of(response.getGmtPayment()),
|
||||
response.getOutTradeNo(), response);
|
||||
LocalDateTime successTime = LocalDateTimeUtil.of(response.getGmtPayment());
|
||||
return PayOrderRespDTO.successOf(response.getTradeNo(), response.getBuyerUserId(), successTime,
|
||||
response.getOutTradeNo(), response)
|
||||
.setDisplayMode(displayMode).setDisplayContent("");
|
||||
}
|
||||
// 大额支付,需要用户输入密码,所以返回 waiting。此时,前端一般会进行轮询
|
||||
return PayOrderRespDTO.waitingOf(displayMode, "",
|
||||
reqDTO.getOutTradeNo(), response);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -66,5 +66,4 @@ public class AlipayPcPayClient extends AbstractAlipayPayClient {
|
|||
return PayOrderRespDTO.waitingOf(displayMode, response.getBody(),
|
||||
reqDTO.getOutTradeNo(), response);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -10,6 +10,10 @@ import com.alipay.api.request.AlipayTradePrecreateRequest;
|
|||
import com.alipay.api.response.AlipayTradePrecreateResponse;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
import static cn.iocoder.yudao.framework.pay.core.client.impl.alipay.AlipayPayClientConfig.MODE_CERTIFICATE;
|
||||
|
||||
/**
|
||||
* 支付宝【扫码支付】的 PayClient 实现类
|
||||
*
|
||||
|
|
@ -45,7 +49,13 @@ public class AlipayQrPayClient extends AbstractAlipayPayClient {
|
|||
request.setReturnUrl(reqDTO.getReturnUrl());
|
||||
|
||||
// 2.1 执行请求
|
||||
AlipayTradePrecreateResponse response = client.execute(request);
|
||||
AlipayTradePrecreateResponse response;
|
||||
if (Objects.equals(config.getMode(), MODE_CERTIFICATE)) {
|
||||
// 证书模式
|
||||
response = client.certificateExecute(request);
|
||||
} else {
|
||||
response = client.execute(request);
|
||||
}
|
||||
// 2.2 处理结果
|
||||
if (!response.isSuccess()) {
|
||||
return buildClosedPayOrderRespDTO(reqDTO, response);
|
||||
|
|
@ -53,5 +63,4 @@ public class AlipayQrPayClient extends AbstractAlipayPayClient {
|
|||
return PayOrderRespDTO.waitingOf(displayMode, response.getQrCode(),
|
||||
reqDTO.getOutTradeNo(), response);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -55,5 +55,4 @@ public class AlipayWapPayClient extends AbstractAlipayPayClient {
|
|||
return PayOrderRespDTO.waitingOf(displayMode, response.getBody(),
|
||||
reqDTO.getOutTradeNo(), response);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,7 +4,10 @@ import cn.iocoder.yudao.framework.pay.core.client.dto.order.PayOrderRespDTO;
|
|||
import cn.iocoder.yudao.framework.pay.core.client.dto.order.PayOrderUnifiedReqDTO;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.dto.refund.PayRefundRespDTO;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.dto.refund.PayRefundUnifiedReqDTO;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.dto.transfer.PayTransferRespDTO;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.dto.transfer.PayTransferUnifiedReqDTO;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.impl.AbstractPayClient;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.impl.NonePayClientConfig;
|
||||
import cn.iocoder.yudao.framework.pay.core.enums.channel.PayChannelEnum;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
|
@ -17,11 +20,11 @@ import java.util.Map;
|
|||
*
|
||||
* @author jason
|
||||
*/
|
||||
public class MockPayClient extends AbstractPayClient<MockPayClientConfig> {
|
||||
public class MockPayClient extends AbstractPayClient<NonePayClientConfig> {
|
||||
|
||||
private static final String MOCK_RESP_SUCCESS_DATA = "MOCK_SUCCESS";
|
||||
|
||||
public MockPayClient(Long channelId, MockPayClientConfig config) {
|
||||
public MockPayClient(Long channelId, NonePayClientConfig config) {
|
||||
super(channelId, PayChannelEnum.MOCK.getCode(), config);
|
||||
}
|
||||
|
||||
|
|
@ -63,4 +66,9 @@ public class MockPayClient extends AbstractPayClient<MockPayClientConfig> {
|
|||
throw new UnsupportedOperationException("模拟支付无支付回调");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected PayTransferRespDTO doUnifiedTransfer(PayTransferUnifiedReqDTO reqDTO) {
|
||||
throw new UnsupportedOperationException("待实现");
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,6 +12,8 @@ import cn.iocoder.yudao.framework.pay.core.client.dto.order.PayOrderRespDTO;
|
|||
import cn.iocoder.yudao.framework.pay.core.client.dto.order.PayOrderUnifiedReqDTO;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.dto.refund.PayRefundRespDTO;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.dto.refund.PayRefundUnifiedReqDTO;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.dto.transfer.PayTransferRespDTO;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.dto.transfer.PayTransferUnifiedReqDTO;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.impl.AbstractPayClient;
|
||||
import cn.iocoder.yudao.framework.pay.core.enums.order.PayOrderStatusRespEnum;
|
||||
import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
|
||||
|
|
@ -425,6 +427,10 @@ public abstract class AbstractWxPayClient extends AbstractPayClient<WxPayClientC
|
|||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected PayTransferRespDTO doUnifiedTransfer(PayTransferUnifiedReqDTO reqDTO) {
|
||||
throw new UnsupportedOperationException("待实现");
|
||||
}
|
||||
// ========== 各种工具方法 ==========
|
||||
|
||||
static String formatDateV2(LocalDateTime time) {
|
||||
|
|
|
|||
|
|
@ -2,8 +2,8 @@ package cn.iocoder.yudao.framework.pay.core.enums.channel;
|
|||
|
||||
import cn.hutool.core.util.ArrayUtil;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.PayClientConfig;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.impl.NonePayClientConfig;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.impl.alipay.AlipayPayClientConfig;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.impl.mock.MockPayClientConfig;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.impl.weixin.WxPayClientConfig;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
|
@ -28,8 +28,9 @@ public enum PayChannelEnum {
|
|||
ALIPAY_APP("alipay_app", "支付宝App 支付", AlipayPayClientConfig.class),
|
||||
ALIPAY_QR("alipay_qr", "支付宝扫码支付", AlipayPayClientConfig.class),
|
||||
ALIPAY_BAR("alipay_bar", "支付宝条码支付", AlipayPayClientConfig.class),
|
||||
MOCK("mock", "模拟支付", NonePayClientConfig.class),
|
||||
|
||||
MOCK("mock", "模拟支付", MockPayClientConfig.class);
|
||||
WALLET("wallet", "钱包支付", NonePayClientConfig.class);
|
||||
|
||||
/**
|
||||
* 编码
|
||||
|
|
|
|||
|
|
@ -0,0 +1,41 @@
|
|||
package cn.iocoder.yudao.framework.pay.core.enums.transfer;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* 渠道的转账状态枚举
|
||||
*
|
||||
* @author jason
|
||||
*/
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public enum PayTransferStatusRespEnum {
|
||||
|
||||
WAITING(0, "转账中"),
|
||||
|
||||
/**
|
||||
* TODO 转账到银行卡. 会有T+0 T+1 到账的请情况。 还未实现
|
||||
* TODO @jason:可以看看其它开源项目,针对这个场景,处理策略是怎么样的?例如说,每天主动轮询?这个状态的单子?
|
||||
*/
|
||||
IN_PROGRESS(10, "转账进行中"),
|
||||
|
||||
SUCCESS(20, "转账成功"),
|
||||
/**
|
||||
* 转账关闭 (失败,或者其它情况)
|
||||
*/
|
||||
CLOSED(30, "转账关闭");
|
||||
|
||||
private final Integer status;
|
||||
private final String name;
|
||||
|
||||
public static boolean isSuccess(Integer status) {
|
||||
return Objects.equals(status, SUCCESS.getStatus());
|
||||
}
|
||||
|
||||
public static boolean isClosed(Integer status) {
|
||||
return Objects.equals(status, CLOSED.getStatus());
|
||||
}
|
||||
}
|
||||
|
|
@ -0,0 +1,41 @@
|
|||
package cn.iocoder.yudao.framework.pay.core.enums.transfer;
|
||||
|
||||
import cn.hutool.core.util.ArrayUtil;
|
||||
import cn.iocoder.yudao.framework.common.core.IntArrayValuable;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* 转账类型枚举
|
||||
*
|
||||
* @author jason
|
||||
*/
|
||||
@AllArgsConstructor
|
||||
@Getter
|
||||
public enum PayTransferTypeEnum implements IntArrayValuable {
|
||||
|
||||
ALIPAY_BALANCE(1, "支付宝余额"),
|
||||
WX_BALANCE(2, "微信余额"),
|
||||
BANK_CARD(3, "银行卡"),
|
||||
WALLET_BALANCE(4, "钱包余额");
|
||||
|
||||
public static final String ALIPAY_LOGON_ID = "ALIPAY_LOGON_ID";
|
||||
public static final String ALIPAY_ACCOUNT_NAME = "ALIPAY_ACCOUNT_NAME";
|
||||
|
||||
private final Integer type;
|
||||
private final String name;
|
||||
|
||||
public static final int[] ARRAYS = Arrays.stream(values()).mapToInt(PayTransferTypeEnum::getType).toArray();
|
||||
|
||||
@Override
|
||||
public int[] array() {
|
||||
return ARRAYS;
|
||||
}
|
||||
|
||||
public static PayTransferTypeEnum typeOf(Integer type) {
|
||||
return ArrayUtil.firstMatch(item -> item.getType().equals(type), values());
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,221 @@
|
|||
package cn.iocoder.yudao.framework.pay.core.client.impl.alipay;
|
||||
|
||||
import cn.hutool.core.date.LocalDateTimeUtil;
|
||||
import cn.hutool.core.util.RandomUtil;
|
||||
import cn.iocoder.yudao.framework.common.exception.ServiceException;
|
||||
import cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants;
|
||||
import cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.dto.order.PayOrderUnifiedReqDTO;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.dto.refund.PayRefundRespDTO;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.dto.refund.PayRefundUnifiedReqDTO;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.exception.PayException;
|
||||
import cn.iocoder.yudao.framework.pay.core.enums.refund.PayRefundStatusRespEnum;
|
||||
import cn.iocoder.yudao.framework.test.core.ut.BaseMockitoUnitTest;
|
||||
import com.alipay.api.AlipayApiException;
|
||||
import com.alipay.api.DefaultAlipayClient;
|
||||
import com.alipay.api.DefaultSigner;
|
||||
import com.alipay.api.domain.AlipayTradeRefundModel;
|
||||
import com.alipay.api.request.AlipayTradeRefundRequest;
|
||||
import com.alipay.api.response.AlipayTradeRefundResponse;
|
||||
import lombok.Setter;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentMatcher;
|
||||
import org.mockito.Mock;
|
||||
|
||||
import javax.validation.ConstraintViolationException;
|
||||
import java.util.Date;
|
||||
|
||||
import static cn.iocoder.yudao.framework.pay.core.client.impl.alipay.AlipayPayClientConfig.MODE_PUBLIC_KEY;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* 支付宝 Client 的测试基类
|
||||
*
|
||||
* @author jason
|
||||
*/
|
||||
public abstract class AbstractAlipayClientTest extends BaseMockitoUnitTest {
|
||||
|
||||
protected AlipayPayClientConfig config = randomPojo(AlipayPayClientConfig.class, o -> {
|
||||
o.setServerUrl(randomURL());
|
||||
o.setPrivateKey(randomString());
|
||||
o.setMode(MODE_PUBLIC_KEY);
|
||||
o.setSignType(AlipayPayClientConfig.SIGN_TYPE_DEFAULT);
|
||||
o.setAppCertContent("");
|
||||
o.setAlipayPublicCertContent("");
|
||||
o.setRootCertContent("");
|
||||
});
|
||||
|
||||
@Mock
|
||||
protected DefaultAlipayClient defaultAlipayClient;
|
||||
|
||||
@Setter
|
||||
private AbstractAlipayPayClient client;
|
||||
|
||||
/**
|
||||
* 子类需要实现该方法. 设置 client 的具体实现
|
||||
*/
|
||||
@BeforeEach
|
||||
public abstract void setUp();
|
||||
|
||||
@Test
|
||||
@DisplayName("支付宝 Client 初始化")
|
||||
public void testDoInit() {
|
||||
// 调用
|
||||
client.doInit();
|
||||
// 断言
|
||||
DefaultAlipayClient realClient = client.getClient();
|
||||
assertNotSame(defaultAlipayClient, realClient);
|
||||
assertInstanceOf(DefaultSigner.class, realClient.getSigner());
|
||||
assertEquals(config.getPrivateKey(), ((DefaultSigner) realClient.getSigner()).getPrivateKey());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("支付宝 Client 统一退款:成功")
|
||||
public void testUnifiedRefund_success() throws AlipayApiException {
|
||||
// mock 方法
|
||||
String notifyUrl = randomURL();
|
||||
Date refundTime = randomDate();
|
||||
String outRefundNo = randomString();
|
||||
String outTradeNo = randomString();
|
||||
Integer refundAmount = randomInteger();
|
||||
AlipayTradeRefundResponse response = randomPojo(AlipayTradeRefundResponse.class, o -> {
|
||||
o.setSubCode("");
|
||||
o.setGmtRefundPay(refundTime);
|
||||
});
|
||||
when(defaultAlipayClient.execute(argThat((ArgumentMatcher<AlipayTradeRefundRequest>) request -> {
|
||||
assertInstanceOf(AlipayTradeRefundModel.class, request.getBizModel());
|
||||
AlipayTradeRefundModel bizModel = (AlipayTradeRefundModel) request.getBizModel();
|
||||
assertEquals(outRefundNo, bizModel.getOutRequestNo());
|
||||
assertEquals(outTradeNo, bizModel.getOutTradeNo());
|
||||
assertEquals(String.valueOf(refundAmount / 100.0), bizModel.getRefundAmount());
|
||||
return true;
|
||||
}))).thenReturn(response);
|
||||
// 准备请求参数
|
||||
PayRefundUnifiedReqDTO refundReqDTO = randomPojo(PayRefundUnifiedReqDTO.class, o -> {
|
||||
o.setOutRefundNo(outRefundNo);
|
||||
o.setOutTradeNo(outTradeNo);
|
||||
o.setNotifyUrl(notifyUrl);
|
||||
o.setRefundPrice(refundAmount);
|
||||
});
|
||||
|
||||
// 调用
|
||||
PayRefundRespDTO resp = client.unifiedRefund(refundReqDTO);
|
||||
// 断言
|
||||
assertEquals(PayRefundStatusRespEnum.SUCCESS.getStatus(), resp.getStatus());
|
||||
assertEquals(outRefundNo, resp.getOutRefundNo());
|
||||
assertNull(resp.getChannelRefundNo());
|
||||
assertEquals(LocalDateTimeUtil.of(refundTime), resp.getSuccessTime());
|
||||
assertSame(response, resp.getRawData());
|
||||
assertNull(resp.getChannelErrorCode());
|
||||
assertNull(resp.getChannelErrorMsg());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("支付宝 Client 统一退款:渠道返回失败")
|
||||
public void test_unified_refund_channel_failed() throws AlipayApiException {
|
||||
// mock 方法
|
||||
String notifyUrl = randomURL();
|
||||
String subCode = randomString();
|
||||
String subMsg = randomString();
|
||||
AlipayTradeRefundResponse response = randomPojo(AlipayTradeRefundResponse.class, o -> {
|
||||
o.setSubCode(subCode);
|
||||
o.setSubMsg(subMsg);
|
||||
});
|
||||
when(defaultAlipayClient.execute(argThat((ArgumentMatcher<AlipayTradeRefundRequest>) request -> {
|
||||
assertInstanceOf(AlipayTradeRefundModel.class, request.getBizModel());
|
||||
return true;
|
||||
}))).thenReturn(response);
|
||||
// 准备请求参数
|
||||
String outRefundNo = randomString();
|
||||
String outTradeNo = randomString();
|
||||
PayRefundUnifiedReqDTO refundReqDTO = randomPojo(PayRefundUnifiedReqDTO.class, o -> {
|
||||
o.setOutRefundNo(outRefundNo);
|
||||
o.setOutTradeNo(outTradeNo);
|
||||
o.setNotifyUrl(notifyUrl);
|
||||
});
|
||||
|
||||
// 调用
|
||||
PayRefundRespDTO resp = client.unifiedRefund(refundReqDTO);
|
||||
// 断言
|
||||
assertEquals(PayRefundStatusRespEnum.FAILURE.getStatus(), resp.getStatus());
|
||||
assertEquals(outRefundNo, resp.getOutRefundNo());
|
||||
assertNull(resp.getChannelRefundNo());
|
||||
assertNull(resp.getSuccessTime());
|
||||
assertSame(response, resp.getRawData());
|
||||
assertEquals(subCode, resp.getChannelErrorCode());
|
||||
assertEquals(subMsg, resp.getChannelErrorMsg());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("支付宝 Client 统一退款:参数校验不通过")
|
||||
public void testUnifiedRefund_paramInvalidate() {
|
||||
// 准备请求参数
|
||||
String notifyUrl = randomURL();
|
||||
PayRefundUnifiedReqDTO refundReqDTO = randomPojo(PayRefundUnifiedReqDTO.class, o -> {
|
||||
o.setOutTradeNo("");
|
||||
o.setNotifyUrl(notifyUrl);
|
||||
});
|
||||
|
||||
// 调用,并断言
|
||||
assertThrows(ConstraintViolationException.class, () -> client.unifiedRefund(refundReqDTO));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("支付宝 Client 统一退款:抛出业务异常")
|
||||
public void testUnifiedRefund_throwServiceException() throws AlipayApiException {
|
||||
// mock 方法
|
||||
when(defaultAlipayClient.execute(argThat((ArgumentMatcher<AlipayTradeRefundRequest>) request -> true)))
|
||||
.thenThrow(ServiceExceptionUtil.exception(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR));
|
||||
// 准备请求参数
|
||||
String notifyUrl = randomURL();
|
||||
PayRefundUnifiedReqDTO refundReqDTO = randomPojo(PayRefundUnifiedReqDTO.class, o -> o.setNotifyUrl(notifyUrl));
|
||||
|
||||
// 调用,并断言
|
||||
assertThrows(ServiceException.class, () -> client.unifiedRefund(refundReqDTO));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("支付宝 Client 统一退款:抛出系统异常")
|
||||
public void testUnifiedRefund_throwPayException() throws AlipayApiException {
|
||||
// mock 方法
|
||||
when(defaultAlipayClient.execute(argThat((ArgumentMatcher<AlipayTradeRefundRequest>) request -> true)))
|
||||
.thenThrow(new RuntimeException("系统异常"));
|
||||
// 准备请求参数
|
||||
String notifyUrl = randomURL();
|
||||
PayRefundUnifiedReqDTO refundReqDTO = randomPojo(PayRefundUnifiedReqDTO.class, o -> o.setNotifyUrl(notifyUrl));
|
||||
|
||||
// 调用,并断言
|
||||
assertThrows(PayException.class, () -> client.unifiedRefund(refundReqDTO));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("支付宝 Client 统一下单:参数校验不通过")
|
||||
public void testUnifiedOrder_paramInvalidate() {
|
||||
// 准备请求参数
|
||||
String outTradeNo = randomString();
|
||||
String notifyUrl = randomURL();
|
||||
PayOrderUnifiedReqDTO reqDTO = randomPojo(PayOrderUnifiedReqDTO.class, o -> {
|
||||
o.setOutTradeNo(outTradeNo);
|
||||
o.setNotifyUrl(notifyUrl);
|
||||
});
|
||||
|
||||
// 调用,并断言
|
||||
assertThrows(ConstraintViolationException.class, () -> client.unifiedOrder(reqDTO));
|
||||
}
|
||||
|
||||
protected PayOrderUnifiedReqDTO buildOrderUnifiedReqDTO(String notifyUrl, String outTradeNo, Integer price) {
|
||||
return randomPojo(PayOrderUnifiedReqDTO.class, o -> {
|
||||
o.setOutTradeNo(outTradeNo);
|
||||
o.setNotifyUrl(notifyUrl);
|
||||
o.setPrice(price);
|
||||
o.setSubject(RandomUtil.randomString(32));
|
||||
o.setBody(RandomUtil.randomString(32));
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,170 @@
|
|||
package cn.iocoder.yudao.framework.pay.core.client.impl.alipay;
|
||||
|
||||
import cn.hutool.core.date.LocalDateTimeUtil;
|
||||
import cn.iocoder.yudao.framework.common.exception.ServiceException;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.dto.order.PayOrderRespDTO;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.dto.order.PayOrderUnifiedReqDTO;
|
||||
import cn.iocoder.yudao.framework.pay.core.enums.order.PayOrderDisplayModeEnum;
|
||||
import cn.iocoder.yudao.framework.pay.core.enums.order.PayOrderStatusRespEnum;
|
||||
import com.alipay.api.AlipayApiException;
|
||||
import com.alipay.api.domain.AlipayTradePayModel;
|
||||
import com.alipay.api.request.AlipayTradePayRequest;
|
||||
import com.alipay.api.response.AlipayTradePayResponse;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentMatcher;
|
||||
import org.mockito.InjectMocks;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import static cn.iocoder.yudao.framework.pay.core.enums.order.PayOrderStatusRespEnum.CLOSED;
|
||||
import static cn.iocoder.yudao.framework.pay.core.enums.order.PayOrderStatusRespEnum.WAITING;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* {@link AlipayBarPayClient} 单元测试
|
||||
*
|
||||
* @author jason
|
||||
*/
|
||||
public class AlipayBarPayClientTest extends AbstractAlipayClientTest {
|
||||
|
||||
@InjectMocks
|
||||
private AlipayBarPayClient client = new AlipayBarPayClient(randomLongId(), config);
|
||||
|
||||
@Override
|
||||
@BeforeEach
|
||||
public void setUp() {
|
||||
setClient(client);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("支付宝条码支付:非免密码支付下单成功")
|
||||
public void testUnifiedOrder_success() throws AlipayApiException {
|
||||
// mock 方法
|
||||
String outTradeNo = randomString();
|
||||
String notifyUrl = randomURL();
|
||||
Integer price = randomInteger();
|
||||
String authCode = randomString();
|
||||
AlipayTradePayResponse response = randomPojo(AlipayTradePayResponse.class, o -> o.setSubCode(""));
|
||||
when(defaultAlipayClient.execute(argThat((ArgumentMatcher<AlipayTradePayRequest>) request -> {
|
||||
assertInstanceOf(AlipayTradePayModel.class, request.getBizModel());
|
||||
assertEquals(notifyUrl, request.getNotifyUrl());
|
||||
AlipayTradePayModel model = (AlipayTradePayModel) request.getBizModel();
|
||||
assertEquals(outTradeNo, model.getOutTradeNo());
|
||||
assertEquals(String.valueOf(price / 100.0), model.getTotalAmount());
|
||||
assertEquals(authCode, model.getAuthCode());
|
||||
return true;
|
||||
}))).thenReturn(response);
|
||||
// 准备请求参数
|
||||
PayOrderUnifiedReqDTO reqDTO = buildOrderUnifiedReqDTO(notifyUrl, outTradeNo, price);
|
||||
Map<String, String> extraParam = new HashMap<>();
|
||||
extraParam.put("auth_code", authCode);
|
||||
reqDTO.setChannelExtras(extraParam);
|
||||
|
||||
// 调用方法
|
||||
PayOrderRespDTO resp = client.unifiedOrder(reqDTO);
|
||||
// 断言
|
||||
assertEquals(WAITING.getStatus(), resp.getStatus());
|
||||
assertEquals(outTradeNo, resp.getOutTradeNo());
|
||||
assertNull(resp.getChannelOrderNo());
|
||||
assertNull(resp.getChannelUserId());
|
||||
assertNull(resp.getSuccessTime());
|
||||
assertEquals(PayOrderDisplayModeEnum.BAR_CODE.getMode(), resp.getDisplayMode());
|
||||
assertEquals("", resp.getDisplayContent());
|
||||
assertSame(response, resp.getRawData());
|
||||
assertNull(resp.getChannelErrorCode());
|
||||
assertNull(resp.getChannelErrorMsg());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("支付宝条码支付:免密码支付下单成功")
|
||||
public void testUnifiedOrder_code10000Success() throws AlipayApiException {
|
||||
// mock 方法
|
||||
String outTradeNo = randomString();
|
||||
String channelNo = randomString();
|
||||
String channelUserId = randomString();
|
||||
Date payTime = randomDate();
|
||||
AlipayTradePayResponse response = randomPojo(AlipayTradePayResponse.class, o -> {
|
||||
o.setSubCode("");
|
||||
o.setCode("10000");
|
||||
o.setOutTradeNo(outTradeNo);
|
||||
o.setTradeNo(channelNo);
|
||||
o.setBuyerUserId(channelUserId);
|
||||
o.setGmtPayment(payTime);
|
||||
});
|
||||
when(defaultAlipayClient.execute(argThat((ArgumentMatcher<AlipayTradePayRequest>) request -> true)))
|
||||
.thenReturn(response);
|
||||
// 准备请求参数
|
||||
String authCode = randomString();
|
||||
PayOrderUnifiedReqDTO reqDTO = buildOrderUnifiedReqDTO(randomURL(), outTradeNo, randomInteger());
|
||||
Map<String, String> extraParam = new HashMap<>();
|
||||
extraParam.put("auth_code", authCode);
|
||||
reqDTO.setChannelExtras(extraParam);
|
||||
|
||||
// 下单请求
|
||||
PayOrderRespDTO resp = client.unifiedOrder(reqDTO);
|
||||
// 断言
|
||||
assertEquals(PayOrderStatusRespEnum.SUCCESS.getStatus(), resp.getStatus());
|
||||
assertEquals(outTradeNo, resp.getOutTradeNo());
|
||||
assertEquals(channelNo, resp.getChannelOrderNo());
|
||||
assertEquals(channelUserId, resp.getChannelUserId());
|
||||
assertEquals(LocalDateTimeUtil.of(payTime), resp.getSuccessTime());
|
||||
assertEquals(PayOrderDisplayModeEnum.BAR_CODE.getMode(), resp.getDisplayMode());
|
||||
assertEquals("", resp.getDisplayContent());
|
||||
assertSame(response, resp.getRawData());
|
||||
assertNull(resp.getChannelErrorCode());
|
||||
assertNull(resp.getChannelErrorMsg());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("支付宝条码支付:没有传条码")
|
||||
public void testUnifiedOrder_emptyAuthCode() {
|
||||
// 准备参数
|
||||
PayOrderUnifiedReqDTO reqDTO = buildOrderUnifiedReqDTO(randomURL(), randomString(), randomInteger());
|
||||
|
||||
// 调用,并断言
|
||||
assertThrows(ServiceException.class, () -> client.unifiedOrder(reqDTO));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("支付宝条码支付:渠道返回失败")
|
||||
public void test_unified_order_channel_failed() throws AlipayApiException {
|
||||
// mock 方法
|
||||
String subCode = randomString();
|
||||
String subMsg = randomString();
|
||||
AlipayTradePayResponse response = randomPojo(AlipayTradePayResponse.class, o -> {
|
||||
o.setSubCode(subCode);
|
||||
o.setSubMsg(subMsg);
|
||||
});
|
||||
when(defaultAlipayClient.execute(argThat((ArgumentMatcher<AlipayTradePayRequest>) request -> true)))
|
||||
.thenReturn(response);
|
||||
// 准备请求参数
|
||||
String authCode = randomString();
|
||||
String outTradeNo = randomString();
|
||||
PayOrderUnifiedReqDTO reqDTO = buildOrderUnifiedReqDTO(randomURL(), outTradeNo, randomInteger());
|
||||
Map<String, String> extraParam = new HashMap<>();
|
||||
extraParam.put("auth_code", authCode);
|
||||
reqDTO.setChannelExtras(extraParam);
|
||||
|
||||
// 调用方法
|
||||
PayOrderRespDTO resp = client.unifiedOrder(reqDTO);
|
||||
// 断言
|
||||
assertEquals(CLOSED.getStatus(), resp.getStatus());
|
||||
assertEquals(outTradeNo, resp.getOutTradeNo());
|
||||
assertNull(resp.getChannelOrderNo());
|
||||
assertNull(resp.getChannelUserId());
|
||||
assertNull(resp.getSuccessTime());
|
||||
assertNull(resp.getDisplayMode());
|
||||
assertNull(resp.getDisplayContent());
|
||||
assertSame(response, resp.getRawData());
|
||||
assertEquals(subCode, resp.getChannelErrorCode());
|
||||
assertEquals(subMsg, resp.getChannelErrorMsg());
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,130 @@
|
|||
package cn.iocoder.yudao.framework.pay.core.client.impl.alipay;
|
||||
|
||||
import cn.hutool.http.Method;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.dto.order.PayOrderRespDTO;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.dto.order.PayOrderUnifiedReqDTO;
|
||||
import cn.iocoder.yudao.framework.pay.core.enums.order.PayOrderDisplayModeEnum;
|
||||
import com.alipay.api.AlipayApiException;
|
||||
import com.alipay.api.request.AlipayTradePagePayRequest;
|
||||
import com.alipay.api.response.AlipayTradePagePayResponse;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentMatcher;
|
||||
import org.mockito.InjectMocks;
|
||||
|
||||
import static cn.iocoder.yudao.framework.pay.core.enums.order.PayOrderStatusRespEnum.CLOSED;
|
||||
import static cn.iocoder.yudao.framework.pay.core.enums.order.PayOrderStatusRespEnum.WAITING;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* {@link AlipayPcPayClient} 单元测试
|
||||
*
|
||||
* @author jason
|
||||
*/
|
||||
public class AlipayPcPayClientTest extends AbstractAlipayClientTest {
|
||||
|
||||
@InjectMocks
|
||||
private AlipayPcPayClient client = new AlipayPcPayClient(randomLongId(), config);
|
||||
|
||||
@Override
|
||||
@BeforeEach
|
||||
public void setUp() {
|
||||
setClient(client);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("支付宝 PC 网站支付:URL Display Mode 下单成功")
|
||||
public void testUnifiedOrder_urlSuccess() throws AlipayApiException {
|
||||
// mock 方法
|
||||
String notifyUrl = randomURL();
|
||||
AlipayTradePagePayResponse response = randomPojo(AlipayTradePagePayResponse.class, o -> o.setSubCode(""));
|
||||
when(defaultAlipayClient.pageExecute(argThat((ArgumentMatcher<AlipayTradePagePayRequest>) request -> true),
|
||||
eq(Method.GET.name()))).thenReturn(response);
|
||||
// 准备请求参数
|
||||
String outTradeNo = randomString();
|
||||
Integer price = randomInteger();
|
||||
PayOrderUnifiedReqDTO reqDTO = buildOrderUnifiedReqDTO(notifyUrl, outTradeNo, price);
|
||||
reqDTO.setDisplayMode(null);
|
||||
|
||||
// 调用
|
||||
PayOrderRespDTO resp = client.unifiedOrder(reqDTO);
|
||||
// 断言
|
||||
assertEquals(WAITING.getStatus(), resp.getStatus());
|
||||
assertEquals(outTradeNo, resp.getOutTradeNo());
|
||||
assertNull(resp.getChannelOrderNo());
|
||||
assertNull(resp.getChannelUserId());
|
||||
assertNull(resp.getSuccessTime());
|
||||
assertEquals(PayOrderDisplayModeEnum.URL.getMode(), resp.getDisplayMode());
|
||||
assertEquals(response.getBody(), resp.getDisplayContent());
|
||||
assertSame(response, resp.getRawData());
|
||||
assertNull(resp.getChannelErrorCode());
|
||||
assertNull(resp.getChannelErrorMsg());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("支付宝 PC 网站支付:Form Display Mode 下单成功")
|
||||
public void testUnifiedOrder_formSuccess() throws AlipayApiException {
|
||||
// mock 方法
|
||||
String notifyUrl = randomURL();
|
||||
AlipayTradePagePayResponse response = randomPojo(AlipayTradePagePayResponse.class, o -> o.setSubCode(""));
|
||||
when(defaultAlipayClient.pageExecute(argThat((ArgumentMatcher<AlipayTradePagePayRequest>) request -> true),
|
||||
eq(Method.POST.name()))).thenReturn(response);
|
||||
// 准备请求参数
|
||||
String outTradeNo = randomString();
|
||||
Integer price = randomInteger();
|
||||
PayOrderUnifiedReqDTO reqDTO = buildOrderUnifiedReqDTO(notifyUrl, outTradeNo, price);
|
||||
reqDTO.setDisplayMode(PayOrderDisplayModeEnum.FORM.getMode());
|
||||
|
||||
// 调用
|
||||
PayOrderRespDTO resp = client.unifiedOrder(reqDTO);
|
||||
// 断言
|
||||
assertEquals(WAITING.getStatus(), resp.getStatus());
|
||||
assertEquals(outTradeNo, resp.getOutTradeNo());
|
||||
assertNull(resp.getChannelOrderNo());
|
||||
assertNull(resp.getChannelUserId());
|
||||
assertNull(resp.getSuccessTime());
|
||||
assertEquals(PayOrderDisplayModeEnum.FORM.getMode(), resp.getDisplayMode());
|
||||
assertEquals(response.getBody(), resp.getDisplayContent());
|
||||
assertSame(response, resp.getRawData());
|
||||
assertNull(resp.getChannelErrorCode());
|
||||
assertNull(resp.getChannelErrorMsg());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("支付宝 PC 网站支付:渠道返回失败")
|
||||
public void testUnifiedOrder_channelFailed() throws AlipayApiException {
|
||||
// mock 方法
|
||||
String subCode = randomString();
|
||||
String subMsg = randomString();
|
||||
AlipayTradePagePayResponse response = randomPojo(AlipayTradePagePayResponse.class, o -> {
|
||||
o.setSubCode(subCode);
|
||||
o.setSubMsg(subMsg);
|
||||
});
|
||||
when(defaultAlipayClient.pageExecute(argThat((ArgumentMatcher<AlipayTradePagePayRequest>) request -> true),
|
||||
eq(Method.GET.name()))).thenReturn(response);
|
||||
// 准备请求参数
|
||||
String outTradeNo = randomString();
|
||||
PayOrderUnifiedReqDTO reqDTO = buildOrderUnifiedReqDTO(randomURL(), outTradeNo, randomInteger());
|
||||
reqDTO.setDisplayMode(PayOrderDisplayModeEnum.URL.getMode());
|
||||
|
||||
// 调用
|
||||
PayOrderRespDTO resp = client.unifiedOrder(reqDTO);
|
||||
// 断言
|
||||
assertEquals(CLOSED.getStatus(), resp.getStatus());
|
||||
assertEquals(outTradeNo, resp.getOutTradeNo());
|
||||
assertNull(resp.getChannelOrderNo());
|
||||
assertNull(resp.getChannelUserId());
|
||||
assertNull(resp.getSuccessTime());
|
||||
assertNull(resp.getDisplayMode());
|
||||
assertNull(resp.getDisplayContent());
|
||||
assertSame(response, resp.getRawData());
|
||||
assertEquals(subCode, resp.getChannelErrorCode());
|
||||
assertEquals(subMsg, resp.getChannelErrorMsg());
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -1,99 +1,147 @@
|
|||
package cn.iocoder.yudao.framework.pay.core.client.impl.alipay;
|
||||
import cn.hutool.core.util.ReflectUtil;
|
||||
|
||||
import cn.iocoder.yudao.framework.common.exception.ServiceException;
|
||||
import cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants;
|
||||
import cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.dto.order.PayOrderRespDTO;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.dto.order.PayOrderUnifiedReqDTO;
|
||||
import cn.iocoder.yudao.framework.test.core.ut.BaseMockitoUnitTest;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.exception.PayException;
|
||||
import cn.iocoder.yudao.framework.pay.core.enums.order.PayOrderDisplayModeEnum;
|
||||
import com.alipay.api.AlipayApiException;
|
||||
import com.alipay.api.DefaultAlipayClient;
|
||||
import com.alipay.api.request.AlipayTradePrecreateRequest;
|
||||
import com.alipay.api.response.AlipayTradePrecreateResponse;
|
||||
import org.junit.jupiter.api.Disabled;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentMatcher;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
|
||||
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomPojo;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotSame;
|
||||
import static cn.iocoder.yudao.framework.pay.core.enums.order.PayOrderStatusRespEnum.CLOSED;
|
||||
import static cn.iocoder.yudao.framework.pay.core.enums.order.PayOrderStatusRespEnum.WAITING;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
public class AlipayQrPayClientTest extends BaseMockitoUnitTest {
|
||||
|
||||
private static final String SERVER_URL_SANDBOX = "https://openapi.alipaydev.com/gateway.do";
|
||||
|
||||
private final AlipayPayClientConfig config = new AlipayPayClientConfig()
|
||||
.setAppId("2021000118634035")
|
||||
.setServerUrl(SERVER_URL_SANDBOX)
|
||||
.setSignType(AlipayPayClientConfig.SIGN_TYPE_DEFAULT)
|
||||
// TODO @tina:key 可以随机就好,简洁一点哈。
|
||||
.setPrivateKey("MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCHsEV1cDupwJ" +
|
||||
"v890x84qbppUtRIfhaKSwSVN0thCcsDCaAsGR5MZslDkO8NCT9V4r2SVXjyY7eJUZlZd1M0C8T" +
|
||||
"01Tg4UOx5LUbic0O3A1uJMy6V1n9IyYwbAW3AEZhBd5bSbPgrqvmv3NeWSTQT6Anxnllf+2iDH" +
|
||||
"6zyA2fPl7cYyQtbZoDJQFGqr4F+cGh2R6akzRKNoBkAeMYwoY6es2lX8sJxCVPWUmxNUoL3tScw" +
|
||||
"lSpd7Bxw0q9c/X01jMwuQ0+Va358zgFiGERTE6yD01eu40OBDXOYO3z++y+TAYHlQQ2toMO63tr" +
|
||||
"epo88X3xV3R44/1DH+k2pAm2IF5ixiLrAgMBAAECggEAPx3SoXcseaD7rmcGcE0p4SMfbsUDdk" +
|
||||
"USmBBbtfF0GzwnqNLkWa+mgE0rWt9SmXngTQH97vByAYmLPl1s3G82ht1V7Sk7yQMe74lhFllr" +
|
||||
"8eEyTjeVx3dTK1EEM4TwN+936DTXdFsr4TELJEcJJdD0KaxcCcfBLRDs2wnitEFZ9N+GoZybVmY8w" +
|
||||
"0e0MI7PLObUZ2l0X4RurQnfG9ZxjXjC7PkeMVv7cGGylpNFi3BbvkRhdhLPDC2E6wqnr9e7zk+hiENi" +
|
||||
"vAezXrtxtwKovzCtnWJ1r0IO14Rh47H509Ic0wFnj+o5YyUL4LdmpL7yaaH6fM7zcSLFjNZPHvZCKPw" +
|
||||
"YcQKBgQDQFho98QvnL8ex4v6cry4VitGpjSXm1qP3vmMQk4rTsn8iPWtcxPjqGEqOQJjdi4Mi0VZKQO" +
|
||||
"LFwlH0kl95wNrD/isJ4O1yeYfX7YAXApzHqYNINzM79HemO3Yx1qLMW3okRFJ9pPRzbQ9qkTpsaegsm" +
|
||||
"yX316zOBhzGRYjKbutTYwKBgQCm7phr9XdFW5Vh+XR90mVs483nrLmMiDKg7YKxSLJ8amiDjzPejCn7i9" +
|
||||
"5Hah08P+2MIZLIPbh2VLacczR6ltRRzN5bg5etFuqSgfkuHyxpoDmpjbe08+Q2h8JBYqcC5Nhv1AKU4iOU" +
|
||||
"hVLHo/FBAQliMcGc/J3eiYTFC7EsNx382QKBgClb20doe7cttgFTXswBvaUmfFm45kmla924B7SpvrQpDD" +
|
||||
"/f+VDtDZRp05fGmxuduSjYdtA3aVtpLiTwWu22OUUvZZqHDGruYOO4Hvdz23mL5b4ayqImCwoNU4bAZIc9v1" +
|
||||
"8p/UNf3/55NNE3oGcf/bev9rH2OjCQ4nM+Ktwhg8CFAoGACSgvbkShzUkv0ZcIf9ppu+ZnJh1AdGgINvGwaJ" +
|
||||
"8vQ0nm/8h8NOoFZ4oNoGc+wU5Ubops7dUM6FjPR5e+OjdJ4E7Xp7d5O4J1TaIZlCEbo5OpdhaTDDcQvrkFu+Z4e" +
|
||||
"N0qzj+YAKjDAOOrXc4tbr5q0FsgXscwtcNfaBuzFVTUrUkCgYEAwzPnMNhWG3zOWLUs2QFA2GP4Y+J8cpUYfj6p" +
|
||||
"bKKzeLwyG9qBwF1NJpN8m+q9q7V9P2LY+9Lp9e1mGsGeqt5HMEA3P6vIpcqLJLqE/4PBLLRzfccTcmqb1m71+erx" +
|
||||
"TRhHBRkGS+I7dZEb3olQfnS1Y1tpMBxiwYwR3LW4oXuJwj8=")
|
||||
.setAlipayPublicKey("MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAnq90KnF4dTnlzzmxpujbI05OYqi5WxAS6cL0" +
|
||||
"gnZFv2gK51HExF8v/BaP7P979PhFMgWTqmOOI+Dtno5s+yD09XTY1WkshbLk6i4g2Xlr8fyW9ODnkU88RI2w9UdPhQU4cPPwBN" +
|
||||
"lrsYhKkVK2OxwM3kFqjoBBY0CZoZCsSQ3LDH5WeZqPArlsS6xa2zqJBuuoKjMrdpELl3eXSjP8K54eDJCbeetCZNKWLL3DPahTPB7LZ" +
|
||||
"ikfYmslb0QUvCgGapD0xkS7eVq70NaL1G57MWABs4tbfWgxike4Daj3EfUrzIVspQxj7w8HEj9WozJPgL88kSJSits0pqD3n5r8HSuseQIDAQAB");
|
||||
/**
|
||||
* {@link AlipayQrPayClient} 单元测试
|
||||
*
|
||||
* @author jason
|
||||
*/
|
||||
public class AlipayQrPayClientTest extends AbstractAlipayClientTest {
|
||||
|
||||
@InjectMocks
|
||||
AlipayQrPayClient client = new AlipayQrPayClient(10L,config);
|
||||
private AlipayQrPayClient client = new AlipayQrPayClient(randomLongId(), config);
|
||||
|
||||
@Mock
|
||||
private DefaultAlipayClient defaultAlipayClient;
|
||||
|
||||
@Test
|
||||
public void testDoInit(){
|
||||
client.doInit();
|
||||
assertNotSame(defaultAlipayClient, ReflectUtil.getFieldValue(client, "defaultAlipayClient"));
|
||||
@BeforeEach
|
||||
public void setUp() {
|
||||
setClient(client);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Disabled // TODO 芋艿:临时禁用
|
||||
public void create() throws AlipayApiException {
|
||||
// TODO @tina:参数可以尽量随机一点,使用随机方法。这样的好处是,避免对固定参数的依赖,导致可能仅仅满足固定参数的结果
|
||||
// 这里,设置可以直接随机整个对象。
|
||||
Long shopOrderId = System.currentTimeMillis();
|
||||
PayOrderUnifiedReqDTO reqDTO=new PayOrderUnifiedReqDTO();
|
||||
reqDTO.setOutTradeNo(String.valueOf(System.currentTimeMillis()));
|
||||
reqDTO.setPrice(1);
|
||||
reqDTO.setBody("内容:" + shopOrderId);
|
||||
reqDTO.setSubject("标题:"+shopOrderId);
|
||||
String notify="http://niubi.natapp1.cc/api/pay/order/notify";
|
||||
reqDTO.setNotifyUrl(notify);
|
||||
|
||||
AlipayTradePrecreateResponse response=randomPojo(AlipayTradePrecreateResponse.class,o->o.setQrCode("success"));
|
||||
|
||||
when(defaultAlipayClient.execute(argThat((ArgumentMatcher<AlipayTradePrecreateRequest>) request ->{
|
||||
assertEquals(notify,request.getNotifyUrl());
|
||||
@DisplayName("支付宝扫描支付:下单成功")
|
||||
public void testUnifiedOrder_success() throws AlipayApiException {
|
||||
// mock 方法
|
||||
String notifyUrl = randomURL();
|
||||
String qrCode = randomString();
|
||||
Integer price = randomInteger();
|
||||
AlipayTradePrecreateResponse response = randomPojo(AlipayTradePrecreateResponse.class, o -> {
|
||||
o.setQrCode(qrCode);
|
||||
o.setSubCode("");
|
||||
});
|
||||
when(defaultAlipayClient.execute(argThat((ArgumentMatcher<AlipayTradePrecreateRequest>) request -> {
|
||||
assertEquals(notifyUrl, request.getNotifyUrl());
|
||||
return true;
|
||||
}))).thenReturn(response);
|
||||
// 准备请求参数
|
||||
String outTradeNo = randomString();
|
||||
PayOrderUnifiedReqDTO reqDTO = buildOrderUnifiedReqDTO(notifyUrl, outTradeNo, price);
|
||||
|
||||
|
||||
// PayCommonResult<PayOrderUnifiedRespDTO> result = client.doUnifiedOrder(reqDTO);
|
||||
// // 断言
|
||||
// assertEquals(response.getCode(), result.getApiCode());
|
||||
// assertEquals(response.getMsg(), result.getApiMsg());
|
||||
// // TODO @tina:这个断言木有过?
|
||||
// assertEquals(GlobalErrorCodeConstants.SUCCESS.getCode(), result.getCode());
|
||||
// assertEquals(GlobalErrorCodeConstants.SUCCESS.getMsg(), result.getMsg());
|
||||
|
||||
// 调用
|
||||
PayOrderRespDTO resp = client.unifiedOrder(reqDTO);
|
||||
// 断言
|
||||
assertEquals(WAITING.getStatus(), resp.getStatus());
|
||||
assertEquals(outTradeNo, resp.getOutTradeNo());
|
||||
assertNull(resp.getChannelOrderNo());
|
||||
assertNull(resp.getChannelUserId());
|
||||
assertNull(resp.getSuccessTime());
|
||||
assertEquals(PayOrderDisplayModeEnum.QR_CODE.getMode(), resp.getDisplayMode());
|
||||
assertEquals(response.getQrCode(), resp.getDisplayContent());
|
||||
assertSame(response, resp.getRawData());
|
||||
assertNull(resp.getChannelErrorCode());
|
||||
assertNull(resp.getChannelErrorMsg());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("支付宝扫描支付:渠道返回失败")
|
||||
public void testUnifiedOrder_channelFailed() throws AlipayApiException {
|
||||
// mock 方法
|
||||
String notifyUrl = randomURL();
|
||||
String subCode = randomString();
|
||||
String subMsg = randomString();
|
||||
Integer price = randomInteger();
|
||||
AlipayTradePrecreateResponse response = randomPojo(AlipayTradePrecreateResponse.class, o -> {
|
||||
o.setSubCode(subCode);
|
||||
o.setSubMsg(subMsg);
|
||||
});
|
||||
// mock
|
||||
when(defaultAlipayClient.execute(argThat((ArgumentMatcher<AlipayTradePrecreateRequest>) request -> {
|
||||
assertEquals(notifyUrl, request.getNotifyUrl());
|
||||
return true;
|
||||
}))).thenReturn(response);
|
||||
// 准备请求参数
|
||||
String outTradeNo = randomString();
|
||||
PayOrderUnifiedReqDTO reqDTO = buildOrderUnifiedReqDTO(notifyUrl, outTradeNo, price);
|
||||
|
||||
// 调用
|
||||
PayOrderRespDTO resp = client.unifiedOrder(reqDTO);
|
||||
// 断言
|
||||
assertEquals(CLOSED.getStatus(), resp.getStatus());
|
||||
assertEquals(outTradeNo, resp.getOutTradeNo());
|
||||
assertNull(resp.getChannelOrderNo());
|
||||
assertNull(resp.getChannelUserId());
|
||||
assertNull(resp.getSuccessTime());
|
||||
assertNull(resp.getDisplayMode());
|
||||
assertNull(resp.getDisplayContent());
|
||||
assertSame(response, resp.getRawData());
|
||||
assertEquals(subCode, resp.getChannelErrorCode());
|
||||
assertEquals(subMsg, resp.getChannelErrorMsg());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("支付宝扫描支付, 抛出系统异常")
|
||||
public void testUnifiedOrder_throwPayException() throws AlipayApiException {
|
||||
// mock 方法
|
||||
String outTradeNo = randomString();
|
||||
String notifyUrl = randomURL();
|
||||
Integer price = randomInteger();
|
||||
when(defaultAlipayClient.execute(argThat((ArgumentMatcher<AlipayTradePrecreateRequest>) request -> {
|
||||
assertEquals(notifyUrl, request.getNotifyUrl());
|
||||
return true;
|
||||
}))).thenThrow(new RuntimeException("系统异常"));
|
||||
// 准备请求参数
|
||||
PayOrderUnifiedReqDTO reqDTO = buildOrderUnifiedReqDTO(notifyUrl, outTradeNo,price);
|
||||
|
||||
// 调用,并断言
|
||||
assertThrows(PayException.class, () -> client.unifiedOrder(reqDTO));
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("支付宝 Client 统一下单:抛出业务异常")
|
||||
public void testUnifiedOrder_throwServiceException() throws AlipayApiException {
|
||||
// mock 方法
|
||||
String outTradeNo = randomString();
|
||||
String notifyUrl = randomURL();
|
||||
Integer price = randomInteger();
|
||||
when(defaultAlipayClient.execute(argThat((ArgumentMatcher<AlipayTradePrecreateRequest>) request -> {
|
||||
assertEquals(notifyUrl, request.getNotifyUrl());
|
||||
return true;
|
||||
}))).thenThrow(ServiceExceptionUtil.exception(GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR));
|
||||
// 准备请求参数
|
||||
PayOrderUnifiedReqDTO reqDTO = buildOrderUnifiedReqDTO(notifyUrl, outTradeNo, price);
|
||||
|
||||
// 调用,并断言
|
||||
assertThrows(ServiceException.class, () -> client.unifiedOrder(reqDTO));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,110 @@
|
|||
package cn.iocoder.yudao.framework.pay.core.client.impl.alipay;
|
||||
|
||||
import cn.hutool.http.Method;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.dto.order.PayOrderRespDTO;
|
||||
import cn.iocoder.yudao.framework.pay.core.client.dto.order.PayOrderUnifiedReqDTO;
|
||||
import cn.iocoder.yudao.framework.pay.core.enums.order.PayOrderDisplayModeEnum;
|
||||
import com.alipay.api.AlipayApiException;
|
||||
import com.alipay.api.domain.AlipayTradeWapPayModel;
|
||||
import com.alipay.api.request.AlipayTradeWapPayRequest;
|
||||
import com.alipay.api.response.AlipayTradeWapPayResponse;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.mockito.ArgumentMatcher;
|
||||
import org.mockito.InjectMocks;
|
||||
|
||||
import static cn.iocoder.yudao.framework.pay.core.enums.order.PayOrderStatusRespEnum.CLOSED;
|
||||
import static cn.iocoder.yudao.framework.pay.core.enums.order.PayOrderStatusRespEnum.WAITING;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.*;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* {@link AlipayWapPayClient} 单元测试
|
||||
*
|
||||
* @author jason
|
||||
*/
|
||||
public class AlipayWapPayClientTest extends AbstractAlipayClientTest {
|
||||
|
||||
/**
|
||||
* 支付宝 H5 支付 Client
|
||||
*/
|
||||
@InjectMocks
|
||||
private AlipayWapPayClient client = new AlipayWapPayClient(randomLongId(), config);
|
||||
|
||||
@BeforeEach
|
||||
public void setUp() {
|
||||
setClient(client);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("支付宝 H5 支付:下单成功")
|
||||
public void testUnifiedOrder_success() throws AlipayApiException {
|
||||
// mock 方法
|
||||
String h5Body = randomString();
|
||||
Integer price = randomInteger();
|
||||
AlipayTradeWapPayResponse response = randomPojo(AlipayTradeWapPayResponse.class, o -> {
|
||||
o.setSubCode("");
|
||||
o.setBody(h5Body);
|
||||
});
|
||||
String notifyUrl = randomURL();
|
||||
when(defaultAlipayClient.pageExecute(argThat((ArgumentMatcher<AlipayTradeWapPayRequest>) request -> {
|
||||
assertInstanceOf(AlipayTradeWapPayModel.class, request.getBizModel());
|
||||
AlipayTradeWapPayModel bizModel = (AlipayTradeWapPayModel) request.getBizModel();
|
||||
assertEquals(String.valueOf(price / 100.0), bizModel.getTotalAmount());
|
||||
assertEquals(notifyUrl, request.getNotifyUrl());
|
||||
return true;
|
||||
}), eq(Method.GET.name()))).thenReturn(response);
|
||||
// 准备请求参数
|
||||
String outTradeNo = randomString();
|
||||
PayOrderUnifiedReqDTO reqDTO = buildOrderUnifiedReqDTO(notifyUrl, outTradeNo, price);
|
||||
|
||||
// 调用
|
||||
PayOrderRespDTO resp = client.unifiedOrder(reqDTO);
|
||||
// 断言
|
||||
assertEquals(WAITING.getStatus(), resp.getStatus());
|
||||
assertEquals(outTradeNo, resp.getOutTradeNo());
|
||||
assertNull(resp.getChannelOrderNo());
|
||||
assertNull(resp.getChannelUserId());
|
||||
assertNull(resp.getSuccessTime());
|
||||
assertEquals(PayOrderDisplayModeEnum.URL.getMode(), resp.getDisplayMode());
|
||||
assertEquals(response.getBody(), resp.getDisplayContent());
|
||||
assertSame(response, resp.getRawData());
|
||||
assertNull(resp.getChannelErrorCode());
|
||||
assertNull(resp.getChannelErrorMsg());
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("支付宝 H5 支付:渠道返回失败")
|
||||
public void test_unified_order_channel_failed() throws AlipayApiException {
|
||||
// mock 方法
|
||||
String subCode = randomString();
|
||||
String subMsg = randomString();
|
||||
AlipayTradeWapPayResponse response = randomPojo(AlipayTradeWapPayResponse.class, o -> {
|
||||
o.setSubCode(subCode);
|
||||
o.setSubMsg(subMsg);
|
||||
});
|
||||
when(defaultAlipayClient.pageExecute(argThat((ArgumentMatcher<AlipayTradeWapPayRequest>) request -> true),
|
||||
eq(Method.GET.name()))).thenReturn(response);
|
||||
String outTradeNo = randomString();
|
||||
PayOrderUnifiedReqDTO reqDTO = buildOrderUnifiedReqDTO(randomURL(), outTradeNo, randomInteger());
|
||||
|
||||
// 调用
|
||||
PayOrderRespDTO resp = client.unifiedOrder(reqDTO);
|
||||
// 断言
|
||||
assertEquals(CLOSED.getStatus(), resp.getStatus());
|
||||
assertEquals(outTradeNo, resp.getOutTradeNo());
|
||||
assertNull(resp.getChannelOrderNo());
|
||||
assertNull(resp.getChannelUserId());
|
||||
assertNull(resp.getSuccessTime());
|
||||
assertNull(resp.getDisplayMode());
|
||||
assertNull(resp.getDisplayContent());
|
||||
assertSame(response, resp.getRawData());
|
||||
assertEquals(subCode, resp.getChannelErrorCode());
|
||||
assertEquals(subMsg, resp.getChannelErrorMsg());
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,309 @@
|
|||
package cn.iocoder.yudao.framework.flowable.core.util;
|
||||
|
||||
import cn.hutool.core.collection.CollUtil;
|
||||
import org.flowable.bpmn.converter.BpmnXMLConverter;
|
||||
import org.flowable.bpmn.model.Process;
|
||||
import org.flowable.bpmn.model.*;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* 流程模型转操作工具类
|
||||
*/
|
||||
public class BpmnModelUtils {
|
||||
|
||||
/**
|
||||
* 根据节点,获取入口连线
|
||||
*
|
||||
* @param source 起始节点
|
||||
* @return 入口连线列表
|
||||
*/
|
||||
public static List<SequenceFlow> getElementIncomingFlows(FlowElement source) {
|
||||
if (source instanceof FlowNode) {
|
||||
return ((FlowNode) source).getIncomingFlows();
|
||||
}
|
||||
return new ArrayList<>();
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据节点,获取出口连线
|
||||
*
|
||||
* @param source 起始节点
|
||||
* @return 出口连线列表
|
||||
*/
|
||||
public static List<SequenceFlow> getElementOutgoingFlows(FlowElement source) {
|
||||
if (source instanceof FlowNode) {
|
||||
return ((FlowNode) source).getOutgoingFlows();
|
||||
}
|
||||
return new ArrayList<>();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取流程元素信息
|
||||
*
|
||||
* @param model bpmnModel 对象
|
||||
* @param flowElementId 元素 ID
|
||||
* @return 元素信息
|
||||
*/
|
||||
public static FlowElement getFlowElementById(BpmnModel model, String flowElementId) {
|
||||
Process process = model.getMainProcess();
|
||||
return process.getFlowElement(flowElementId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得 BPMN 流程中,指定的元素们
|
||||
*
|
||||
* @param model
|
||||
* @param clazz 指定元素。例如说,{@link UserTask}、{@link Gateway} 等等
|
||||
* @return 元素们
|
||||
*/
|
||||
public static <T extends FlowElement> List<T> getBpmnModelElements(BpmnModel model, Class<T> clazz) {
|
||||
List<T> result = new ArrayList<>();
|
||||
model.getProcesses().forEach(process -> {
|
||||
process.getFlowElements().forEach(flowElement -> {
|
||||
if (flowElement.getClass().isAssignableFrom(clazz)) {
|
||||
result.add((T) flowElement);
|
||||
}
|
||||
});
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 比较 两个bpmnModel 是否相同
|
||||
* @param oldModel 老的bpmn model
|
||||
* @param newModel 新的bpmn model
|
||||
*/
|
||||
public static boolean equals(BpmnModel oldModel, BpmnModel newModel) {
|
||||
// 由于 BpmnModel 未提供 equals 方法,所以只能转成字节数组,进行比较
|
||||
return Arrays.equals(getBpmnBytes(oldModel), getBpmnBytes(newModel));
|
||||
}
|
||||
|
||||
/**
|
||||
* 把 bpmnModel 转换成 byte[]
|
||||
* @param model bpmnModel
|
||||
*/
|
||||
public static byte[] getBpmnBytes(BpmnModel model) {
|
||||
if (model == null) {
|
||||
return new byte[0];
|
||||
}
|
||||
BpmnXMLConverter converter = new BpmnXMLConverter();
|
||||
return converter.convertToXML(model);
|
||||
}
|
||||
|
||||
// ========== 遍历相关的方法 ==========
|
||||
|
||||
/**
|
||||
* 找到 source 节点之前的所有用户任务节点
|
||||
*
|
||||
* @param source 起始节点
|
||||
* @param hasSequenceFlow 已经经过的连线的 ID,用于判断线路是否重复
|
||||
* @param userTaskList 已找到的用户任务节点
|
||||
* @return 用户任务节点 数组
|
||||
*/
|
||||
public static List<UserTask> getPreviousUserTaskList(FlowElement source, Set<String> hasSequenceFlow, List<UserTask> userTaskList) {
|
||||
userTaskList = userTaskList == null ? new ArrayList<>() : userTaskList;
|
||||
hasSequenceFlow = hasSequenceFlow == null ? new HashSet<>() : hasSequenceFlow;
|
||||
// 如果该节点为开始节点,且存在上级子节点,则顺着上级子节点继续迭代
|
||||
if (source instanceof StartEvent && source.getSubProcess() != null) {
|
||||
userTaskList = getPreviousUserTaskList(source.getSubProcess(), hasSequenceFlow, userTaskList);
|
||||
}
|
||||
|
||||
// 根据类型,获取入口连线
|
||||
List<SequenceFlow> sequenceFlows = getElementIncomingFlows(source);
|
||||
if (sequenceFlows == null) {
|
||||
return userTaskList;
|
||||
}
|
||||
// 循环找到目标元素
|
||||
for (SequenceFlow sequenceFlow : sequenceFlows) {
|
||||
// 如果发现连线重复,说明循环了,跳过这个循环
|
||||
if (hasSequenceFlow.contains(sequenceFlow.getId())) {
|
||||
continue;
|
||||
}
|
||||
// 添加已经走过的连线
|
||||
hasSequenceFlow.add(sequenceFlow.getId());
|
||||
// 类型为用户节点,则新增父级节点
|
||||
if (sequenceFlow.getSourceFlowElement() instanceof UserTask) {
|
||||
userTaskList.add((UserTask) sequenceFlow.getSourceFlowElement());
|
||||
}
|
||||
// 类型为子流程,则添加子流程开始节点出口处相连的节点
|
||||
if (sequenceFlow.getSourceFlowElement() instanceof SubProcess) {
|
||||
// 获取子流程用户任务节点
|
||||
List<UserTask> childUserTaskList = findChildProcessUserTaskList((StartEvent) ((SubProcess) sequenceFlow.getSourceFlowElement()).getFlowElements().toArray()[0], null, null);
|
||||
// 如果找到节点,则说明该线路找到节点,不继续向下找,反之继续
|
||||
if (CollUtil.isNotEmpty(childUserTaskList)) {
|
||||
userTaskList.addAll(childUserTaskList);
|
||||
}
|
||||
}
|
||||
// 继续迭代
|
||||
userTaskList = getPreviousUserTaskList(sequenceFlow.getSourceFlowElement(), hasSequenceFlow, userTaskList);
|
||||
}
|
||||
return userTaskList;
|
||||
}
|
||||
|
||||
/**
|
||||
* 迭代获取子流程用户任务节点
|
||||
*
|
||||
* @param source 起始节点
|
||||
* @param hasSequenceFlow 已经经过的连线的 ID,用于判断线路是否重复
|
||||
* @param userTaskList 需要撤回的用户任务列表
|
||||
* @return 用户任务节点
|
||||
*/
|
||||
public static List<UserTask> findChildProcessUserTaskList(FlowElement source, Set<String> hasSequenceFlow, List<UserTask> userTaskList) {
|
||||
hasSequenceFlow = hasSequenceFlow == null ? new HashSet<>() : hasSequenceFlow;
|
||||
userTaskList = userTaskList == null ? new ArrayList<>() : userTaskList;
|
||||
|
||||
// 根据类型,获取出口连线
|
||||
List<SequenceFlow> sequenceFlows = getElementOutgoingFlows(source);
|
||||
if (sequenceFlows == null) {
|
||||
return userTaskList;
|
||||
}
|
||||
// 循环找到目标元素
|
||||
for (SequenceFlow sequenceFlow : sequenceFlows) {
|
||||
// 如果发现连线重复,说明循环了,跳过这个循环
|
||||
if (hasSequenceFlow.contains(sequenceFlow.getId())) {
|
||||
continue;
|
||||
}
|
||||
// 添加已经走过的连线
|
||||
hasSequenceFlow.add(sequenceFlow.getId());
|
||||
// 如果为用户任务类型,且任务节点的 Key 正在运行的任务中存在,添加
|
||||
if (sequenceFlow.getTargetFlowElement() instanceof UserTask) {
|
||||
userTaskList.add((UserTask) sequenceFlow.getTargetFlowElement());
|
||||
continue;
|
||||
}
|
||||
// 如果节点为子流程节点情况,则从节点中的第一个节点开始获取
|
||||
if (sequenceFlow.getTargetFlowElement() instanceof SubProcess) {
|
||||
List<UserTask> childUserTaskList = findChildProcessUserTaskList((FlowElement) (((SubProcess) sequenceFlow.getTargetFlowElement()).getFlowElements().toArray()[0]), hasSequenceFlow, null);
|
||||
// 如果找到节点,则说明该线路找到节点,不继续向下找,反之继续
|
||||
if (CollUtil.isNotEmpty(childUserTaskList)) {
|
||||
userTaskList.addAll(childUserTaskList);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
// 继续迭代
|
||||
userTaskList = findChildProcessUserTaskList(sequenceFlow.getTargetFlowElement(), hasSequenceFlow, userTaskList);
|
||||
}
|
||||
return userTaskList;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 迭代从后向前扫描,判断目标节点相对于当前节点是否是串行
|
||||
* 不存在直接回退到子流程中的情况,但存在从子流程出去到父流程情况
|
||||
*
|
||||
* @param source 起始节点
|
||||
* @param target 目标节点
|
||||
* @param visitedElements 已经经过的连线的 ID,用于判断线路是否重复
|
||||
* @return 结果
|
||||
*/
|
||||
public static boolean isSequentialReachable(FlowElement source, FlowElement target, Set<String> visitedElements) {
|
||||
visitedElements = visitedElements == null ? new HashSet<>() : visitedElements;
|
||||
// 不能是开始事件和子流程
|
||||
if (source instanceof StartEvent && isInEventSubprocess(source)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// 根据类型,获取入口连线
|
||||
List<SequenceFlow> sequenceFlows = getElementIncomingFlows(source);
|
||||
if (CollUtil.isEmpty(sequenceFlows)) {
|
||||
return true;
|
||||
}
|
||||
// 循环找到目标元素
|
||||
for (SequenceFlow sequenceFlow : sequenceFlows) {
|
||||
// 如果发现连线重复,说明循环了,跳过这个循环
|
||||
if (visitedElements.contains(sequenceFlow.getId())) {
|
||||
continue;
|
||||
}
|
||||
// 添加已经走过的连线
|
||||
visitedElements.add(sequenceFlow.getId());
|
||||
// 这条线路存在目标节点,这条线路完成,进入下个线路
|
||||
FlowElement sourceFlowElement = sequenceFlow.getSourceFlowElement();
|
||||
if (target.getId().equals(sourceFlowElement.getId())) {
|
||||
continue;
|
||||
}
|
||||
// 如果目标节点为并行网关,则不继续
|
||||
if (sourceFlowElement instanceof ParallelGateway) {
|
||||
return false;
|
||||
}
|
||||
// 否则就继续迭代
|
||||
if (!isSequentialReachable(sourceFlowElement, target, visitedElements)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断当前节点是否属于不同的子流程
|
||||
*
|
||||
* @param flowElement 被判断的节点
|
||||
* @return true 表示属于子流程
|
||||
*/
|
||||
private static boolean isInEventSubprocess(FlowElement flowElement) {
|
||||
FlowElementsContainer flowElementsContainer = flowElement.getParentContainer();
|
||||
while (flowElementsContainer != null) {
|
||||
if (flowElementsContainer instanceof EventSubProcess) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (flowElementsContainer instanceof FlowElement) {
|
||||
flowElementsContainer = ((FlowElement) flowElementsContainer).getParentContainer();
|
||||
} else {
|
||||
flowElementsContainer = null;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据正在运行的任务节点,迭代获取子级任务节点列表,向后找
|
||||
*
|
||||
* @param source 起始节点
|
||||
* @param runTaskKeyList 正在运行的任务 Key,用于校验任务节点是否是正在运行的节点
|
||||
* @param hasSequenceFlow 已经经过的连线的 ID,用于判断线路是否重复
|
||||
* @param userTaskList 需要撤回的用户任务列表
|
||||
* @return 子级任务节点列表
|
||||
*/
|
||||
public static List<UserTask> iteratorFindChildUserTasks(FlowElement source, List<String> runTaskKeyList,
|
||||
Set<String> hasSequenceFlow, List<UserTask> userTaskList) {
|
||||
hasSequenceFlow = hasSequenceFlow == null ? new HashSet<>() : hasSequenceFlow;
|
||||
userTaskList = userTaskList == null ? new ArrayList<>() : userTaskList;
|
||||
// 如果该节点为开始节点,且存在上级子节点,则顺着上级子节点继续迭代
|
||||
if (source instanceof StartEvent && source.getSubProcess() != null) {
|
||||
userTaskList = iteratorFindChildUserTasks(source.getSubProcess(), runTaskKeyList, hasSequenceFlow, userTaskList);
|
||||
}
|
||||
|
||||
// 根据类型,获取出口连线
|
||||
List<SequenceFlow> sequenceFlows = getElementOutgoingFlows(source);
|
||||
if (sequenceFlows == null) {
|
||||
return userTaskList;
|
||||
}
|
||||
// 循环找到目标元素
|
||||
for (SequenceFlow sequenceFlow : sequenceFlows) {
|
||||
// 如果发现连线重复,说明循环了,跳过这个循环
|
||||
if (hasSequenceFlow.contains(sequenceFlow.getId())) {
|
||||
continue;
|
||||
}
|
||||
// 添加已经走过的连线
|
||||
hasSequenceFlow.add(sequenceFlow.getId());
|
||||
// 如果为用户任务类型,且任务节点的 Key 正在运行的任务中存在,添加
|
||||
if (sequenceFlow.getTargetFlowElement() instanceof UserTask && runTaskKeyList.contains((sequenceFlow.getTargetFlowElement()).getId())) {
|
||||
userTaskList.add((UserTask) sequenceFlow.getTargetFlowElement());
|
||||
continue;
|
||||
}
|
||||
// 如果节点为子流程节点情况,则从节点中的第一个节点开始获取
|
||||
if (sequenceFlow.getTargetFlowElement() instanceof SubProcess) {
|
||||
List<UserTask> childUserTaskList = iteratorFindChildUserTasks((FlowElement) (((SubProcess) sequenceFlow.getTargetFlowElement()).getFlowElements().toArray()[0]), runTaskKeyList, hasSequenceFlow, null);
|
||||
// 如果找到节点,则说明该线路找到节点,不继续向下找,反之继续
|
||||
if (CollUtil.isNotEmpty(childUserTaskList)) {
|
||||
userTaskList.addAll(childUserTaskList);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
// 继续迭代
|
||||
userTaskList = iteratorFindChildUserTasks(sequenceFlow.getTargetFlowElement(), runTaskKeyList, hasSequenceFlow, userTaskList);
|
||||
}
|
||||
return userTaskList;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -1,14 +1,7 @@
|
|||
package cn.iocoder.yudao.framework.flowable.core.util;
|
||||
|
||||
import org.flowable.bpmn.converter.BpmnXMLConverter;
|
||||
import org.flowable.bpmn.model.BpmnModel;
|
||||
import org.flowable.bpmn.model.FlowElement;
|
||||
import org.flowable.common.engine.impl.identity.Authentication;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Flowable 相关的工具方法
|
||||
*
|
||||
|
|
@ -26,49 +19,6 @@ public class FlowableUtils {
|
|||
Authentication.setAuthenticatedUserId(null);
|
||||
}
|
||||
|
||||
// ========== BPMN 相关的工具方法 ==========
|
||||
|
||||
/**
|
||||
* 获得 BPMN 流程中,指定的元素们
|
||||
*
|
||||
* @param model
|
||||
* @param clazz 指定元素。例如说,{@link org.flowable.bpmn.model.UserTask}、{@link org.flowable.bpmn.model.Gateway} 等等
|
||||
* @return 元素们
|
||||
*/
|
||||
public static <T extends FlowElement> List<T> getBpmnModelElements(BpmnModel model, Class<T> clazz) {
|
||||
List<T> result = new ArrayList<>();
|
||||
model.getProcesses().forEach(process -> {
|
||||
process.getFlowElements().forEach(flowElement -> {
|
||||
if (flowElement.getClass().isAssignableFrom(clazz)) {
|
||||
result.add((T) flowElement);
|
||||
}
|
||||
});
|
||||
});
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 比较 两个bpmnModel 是否相同
|
||||
* @param oldModel 老的bpmn model
|
||||
* @param newModel 新的bpmn model
|
||||
*/
|
||||
public static boolean equals(BpmnModel oldModel, BpmnModel newModel) {
|
||||
// 由于 BpmnModel 未提供 equals 方法,所以只能转成字节数组,进行比较
|
||||
return Arrays.equals(getBpmnBytes(oldModel), getBpmnBytes(newModel));
|
||||
}
|
||||
|
||||
/**
|
||||
* 把 bpmnModel 转换成 byte[]
|
||||
* @param model bpmnModel
|
||||
*/
|
||||
public static byte[] getBpmnBytes(BpmnModel model) {
|
||||
if (model == null) {
|
||||
return new byte[0];
|
||||
}
|
||||
BpmnXMLConverter converter = new BpmnXMLConverter();
|
||||
return converter.convertToXML(model);
|
||||
}
|
||||
|
||||
// ========== Execution 相关的工具方法 ==========
|
||||
|
||||
public static String formatCollectionVariable(String activityId) {
|
||||
|
|
|
|||
|
|
@ -110,6 +110,32 @@ spring:
|
|||
- Path=/app-api/promotion/**
|
||||
filters:
|
||||
- RewritePath=/app-api/promotion/v3/api-docs, /v3/api-docs
|
||||
## trade-server 服务
|
||||
- id: trade-admin-api # 路由的编号
|
||||
uri: grayLb://trade-server
|
||||
predicates: # 断言,作为路由的匹配条件,对应 RouteDefinition 数组
|
||||
- Path=/admin-api/trade/**
|
||||
filters:
|
||||
- RewritePath=/admin-api/trade/v3/api-docs, /v3/api-docs # 配置,保证转发到 /v3/api-docs
|
||||
- id: trade-app-api # 路由的编号
|
||||
uri: grayLb://trade-server
|
||||
predicates: # 断言,作为路由的匹配条件,对应 RouteDefinition 数组
|
||||
- Path=/app-api/trade/**
|
||||
filters:
|
||||
- RewritePath=/app-api/trade/v3/api-docs, /v3/api-docs
|
||||
## statistics-server 服务
|
||||
- id: statistics-admin-api # 路由的编号
|
||||
uri: grayLb://statistics-server
|
||||
predicates: # 断言,作为路由的匹配条件,对应 RouteDefinition 数组
|
||||
- Path=/admin-api/statistics/**
|
||||
filters:
|
||||
- RewritePath=/admin-api/statistics/v3/api-docs, /v3/api-docs # 配置,保证转发到 /v3/api-docs
|
||||
- id: statistics-app-api # 路由的编号
|
||||
uri: grayLb://statistics-server
|
||||
predicates: # 断言,作为路由的匹配条件,对应 RouteDefinition 数组
|
||||
- Path=/app-api/statistics/**
|
||||
filters:
|
||||
- RewritePath=/app-api/statistics/v3/api-docs, /v3/api-docs
|
||||
x-forwarded:
|
||||
prefix-enabled: false # 避免 Swagger 重复带上额外的 /admin-api/system 前缀
|
||||
|
||||
|
|
@ -142,3 +168,9 @@ knife4j:
|
|||
- name: promotion-server
|
||||
service-name: promotion-server
|
||||
url: /admin-api/promotion/v3/api-docs
|
||||
- name: trade-server
|
||||
service-name: trade-server
|
||||
url: /admin-api/trade/v3/api-docs
|
||||
- name: statistics-server
|
||||
service-name: statistics-server
|
||||
url: /admin-api/statistics/v3/api-docs
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
package cn.iocoder.yudao.module.bpm.api.task;
|
||||
|
||||
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
|
||||
import cn.iocoder.yudao.module.bpm.api.task.dto.BpmProcessInstanceCreateReqDTO;
|
||||
import cn.iocoder.yudao.module.bpm.enums.ApiConstants;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
|
|
@ -21,7 +22,7 @@ public interface BpmProcessInstanceApi {
|
|||
@PostMapping(PREFIX + "/create")
|
||||
@Operation(summary = "创建流程实例(提供给内部),返回实例编号")
|
||||
@Parameter(name = "userId", description = "用户编号", required = true, example = "1")
|
||||
String createProcessInstance(@RequestParam("userId") Long userId,
|
||||
@Valid @RequestBody BpmProcessInstanceCreateReqDTO reqDTO);
|
||||
CommonResult<String> createProcessInstance(@RequestParam("userId") Long userId,
|
||||
@Valid @RequestBody BpmProcessInstanceCreateReqDTO reqDTO);
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import cn.iocoder.yudao.framework.common.exception.ErrorCode;
|
|||
|
||||
/**
|
||||
* Bpm 错误码枚举类
|
||||
*
|
||||
* <p>
|
||||
* bpm 系统,使用 1-009-000-000 段
|
||||
*/
|
||||
public interface ErrorCodeConstants {
|
||||
|
|
@ -43,8 +43,17 @@ public interface ErrorCodeConstants {
|
|||
ErrorCode PROCESS_INSTANCE_CANCEL_FAIL_NOT_SELF = new ErrorCode(1_009_004_002, "流程取消失败,该流程不是你发起的");
|
||||
|
||||
// ========== 流程任务 1-009-005-000 ==========
|
||||
ErrorCode TASK_COMPLETE_FAIL_NOT_EXISTS = new ErrorCode(1_009_005_000, "审批任务失败,原因:该任务不处于未审批");
|
||||
ErrorCode TASK_COMPLETE_FAIL_ASSIGN_NOT_SELF = new ErrorCode(1_009_005_001, "审批任务失败,原因:该任务的审批人不是你");
|
||||
ErrorCode TASK_OPERATE_FAIL_ASSIGN_NOT_SELF = new ErrorCode(1_009_005_001, "操作失败,原因:该任务的审批人不是你");
|
||||
ErrorCode TASK_NOT_EXISTS = new ErrorCode(1_009_005_002, "流程任务不存在");
|
||||
ErrorCode TASK_IS_PENDING = new ErrorCode(1_009_005_003, "当前任务处于挂起状态,不能操作");
|
||||
ErrorCode TASK_TARGET_NODE_NOT_EXISTS = new ErrorCode(1_009_005_004, " 目标节点不存在");
|
||||
ErrorCode TASK_RETURN_FAIL_SOURCE_TARGET_ERROR = new ErrorCode(1_009_005_006, "回退任务失败,目标节点是在并行网关上或非同一路线上,不可跳转");
|
||||
ErrorCode TASK_DELEGATE_FAIL_USER_REPEAT = new ErrorCode(1_009_005_007, "任务委派失败,委派人和当前审批人为同一人");
|
||||
ErrorCode TASK_DELEGATE_FAIL_USER_NOT_EXISTS = new ErrorCode(1_009_005_008, "任务委派失败,被委派人不存在");
|
||||
ErrorCode TASK_ADD_SIGN_USER_NOT_EXIST = new ErrorCode(1_009_005_009, "任务加签:选择的用户不存在");
|
||||
ErrorCode TASK_ADD_SIGN_TYPE_ERROR = new ErrorCode(1_009_005_010, "任务加签:当前任务已经{},不能{}");
|
||||
ErrorCode TASK_ADD_SIGN_USER_REPEAT = new ErrorCode(1_009_005_011, "任务加签失败,加签人与现有审批人[{}]重复");
|
||||
ErrorCode TASK_SUB_SIGN_NO_PARENT = new ErrorCode(1_009_005_011, "任务减签失败,被减签的任务必须是通过加签生成的任务");
|
||||
|
||||
// ========== 流程任务分配规则 1-009-006-000 ==========
|
||||
ErrorCode TASK_ASSIGN_RULE_EXISTS = new ErrorCode(1_009_006_000, "流程({}) 的任务({}) 已经存在分配规则");
|
||||
|
|
|
|||
|
|
@ -0,0 +1,35 @@
|
|||
package cn.iocoder.yudao.module.bpm.enums.task;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
/**
|
||||
* 流程任务 -- comment类型枚举
|
||||
*/
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public enum BpmCommentTypeEnum {
|
||||
|
||||
APPROVE(1, "通过", ""),
|
||||
REJECT(2, "不通过", ""),
|
||||
CANCEL(3, "已取消", ""),
|
||||
BACK(4, "退回", ""),
|
||||
DELEGATE(5, "委派", ""),
|
||||
ADD_SIGN(6, "加签", "[{}]{}给了[{}],理由为:{}"),
|
||||
SUB_SIGN(7, "减签", "[{}]操作了【减签】,审批人[{}]的任务被取消"),
|
||||
;
|
||||
|
||||
/**
|
||||
* 操作类型
|
||||
*/
|
||||
private final Integer type;
|
||||
/**
|
||||
* 操作名字
|
||||
*/
|
||||
private final String name;
|
||||
/**
|
||||
* 操作描述
|
||||
*/
|
||||
private final String comment;
|
||||
|
||||
}
|
||||
|
|
@ -4,6 +4,9 @@ import cn.iocoder.yudao.framework.common.util.object.ObjectUtils;
|
|||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 流程实例的结果
|
||||
*
|
||||
|
|
@ -20,11 +23,35 @@ public enum BpmProcessInstanceResultEnum {
|
|||
|
||||
// ========== 流程任务独有的状态 ==========
|
||||
|
||||
BACK(5, "退回/驳回");
|
||||
BACK(5, "驳回"), // 退回
|
||||
DELEGATE(6, "委派"),
|
||||
/**
|
||||
* 【加签】源任务已经审批完成,但是它使用了后加签,后加签的任务未完成,源任务就会是这个状态
|
||||
* 相当于是 通过 APPROVE 的特殊状态
|
||||
* 例如:A审批, A 后加签了 B,并且审批通过了任务,但是 B 还未审批,则当前任务状态为“待后加签任务完成”
|
||||
*/
|
||||
SIGN_AFTER(7, "待后加签任务完成"),
|
||||
/**
|
||||
* 【加签】源任务未审批,但是向前加签了,所以源任务状态变为“待前加签任务完成”
|
||||
* 相当于是 处理中 PROCESS 的特殊状态
|
||||
* 例如:A 审批, A 前加签了 B,B 还未审核
|
||||
*/
|
||||
SIGN_BEFORE(8, "待前加签任务完成"),
|
||||
/**
|
||||
* 【加签】后加签任务被创建时的初始状态
|
||||
* 相当于是 处理中 PROCESS 的特殊状态
|
||||
* 因为需要源任务先完成,才能到后加签的人来审批,所以加了一个状态区分
|
||||
*/
|
||||
WAIT_BEFORE_TASK(9, "待前置任务完成");
|
||||
|
||||
/**
|
||||
* 能被减签的状态
|
||||
*/
|
||||
public static final List<Integer> CAN_SUB_SIGN_STATUS_LIST = Arrays.asList(PROCESS.result, WAIT_BEFORE_TASK.result);
|
||||
|
||||
/**
|
||||
* 结果
|
||||
*
|
||||
* <p>
|
||||
* 如果新增时,注意 {@link #isEndResult(Integer)} 是否需要变更
|
||||
*/
|
||||
private final Integer result;
|
||||
|
|
@ -35,14 +62,16 @@ public enum BpmProcessInstanceResultEnum {
|
|||
|
||||
/**
|
||||
* 判断该结果是否已经处于 End 最终结果
|
||||
*
|
||||
* <p>
|
||||
* 主要用于一些结果更新的逻辑,如果已经是最终结果,就不再进行更新
|
||||
*
|
||||
* @param result 结果
|
||||
* @return 是否
|
||||
*/
|
||||
public static boolean isEndResult(Integer result) {
|
||||
return ObjectUtils.equalsAny(result, APPROVE.getResult(), REJECT.getResult(), CANCEL.getResult(), BACK.getResult());
|
||||
return ObjectUtils.equalsAny(result, APPROVE.getResult(), REJECT.getResult(),
|
||||
CANCEL.getResult(), BACK.getResult(),
|
||||
SIGN_AFTER.getResult());
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,40 @@
|
|||
package cn.iocoder.yudao.module.bpm.enums.task;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
/**
|
||||
* 流程任务 -- 加签类型枚举类型
|
||||
*/
|
||||
@Getter
|
||||
@AllArgsConstructor
|
||||
public enum BpmTaskAddSignTypeEnum {
|
||||
|
||||
/**
|
||||
* 向前加签,需要前置任务审批完成,才回到原审批人
|
||||
*/
|
||||
BEFORE("before", "向前加签"),
|
||||
/**
|
||||
* 向后加签,需要后置任务全部审批完,才会通过原审批人节点
|
||||
*/
|
||||
AFTER("after", "向后加签"),
|
||||
/**
|
||||
* 创建后置加签时的过度状态,用于控制向后加签生成的任务状态
|
||||
*/
|
||||
AFTER_CHILDREN_TASK("afterChildrenTask", "向后加签生成的子任务");
|
||||
|
||||
private final String type;
|
||||
|
||||
private final String desc;
|
||||
|
||||
public static String formatDesc(String type) {
|
||||
for (BpmTaskAddSignTypeEnum value : values()) {
|
||||
if (value.type.equals(type)) {
|
||||
return value.desc;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
|
@ -86,18 +86,6 @@
|
|||
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Job 定时任务相关 -->
|
||||
<dependency>
|
||||
<groupId>cn.iocoder.cloud</groupId>
|
||||
<artifactId>yudao-spring-boot-starter-job</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- 消息队列相关 -->
|
||||
<dependency>
|
||||
<groupId>cn.iocoder.cloud</groupId>
|
||||
<artifactId>yudao-spring-boot-starter-mq</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- 服务保障相关 TODO 芋艿:暂时去掉 -->
|
||||
<!-- <dependency>-->
|
||||
<!-- <groupId>cn.iocoder.cloud</groupId>-->
|
||||
|
|
|
|||
|
|
@ -1,20 +1,23 @@
|
|||
package cn.iocoder.yudao.module.bpm.api.task;
|
||||
|
||||
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
|
||||
import cn.iocoder.yudao.module.bpm.api.task.dto.BpmProcessInstanceCreateReqDTO;
|
||||
import cn.iocoder.yudao.module.bpm.service.task.BpmProcessInstanceService;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.validation.Valid;
|
||||
|
||||
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
|
||||
|
||||
/**
|
||||
* Flowable 流程实例 Api 实现类
|
||||
*
|
||||
* @author 芋道源码
|
||||
* @author jason
|
||||
*/
|
||||
@Service
|
||||
@RestController
|
||||
@Validated
|
||||
public class BpmProcessInstanceApiImpl implements BpmProcessInstanceApi {
|
||||
|
||||
|
|
@ -22,7 +25,8 @@ public class BpmProcessInstanceApiImpl implements BpmProcessInstanceApi {
|
|||
private BpmProcessInstanceService processInstanceService;
|
||||
|
||||
@Override
|
||||
public String createProcessInstance(Long userId, @Valid BpmProcessInstanceCreateReqDTO reqDTO) {
|
||||
return processInstanceService.createProcessInstance(userId, reqDTO);
|
||||
public CommonResult<String> createProcessInstance(Long userId, @Valid BpmProcessInstanceCreateReqDTO reqDTO) {
|
||||
return success(processInstanceService.createProcessInstance(userId, reqDTO));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -74,4 +74,52 @@ public class BpmTaskController {
|
|||
return success(true);
|
||||
}
|
||||
|
||||
@GetMapping("/return-list")
|
||||
@Operation(summary = "获取所有可回退的节点", description = "用于【流程详情】的【回退】按钮")
|
||||
@Parameter(name = "taskId", description = "当前任务ID", required = true)
|
||||
@PreAuthorize("@ss.hasPermission('bpm:task:update')")
|
||||
public CommonResult<List<BpmTaskSimpleRespVO>> getReturnList(@RequestParam("taskId") String taskId) {
|
||||
return success(taskService.getReturnTaskList(taskId));
|
||||
}
|
||||
|
||||
@PutMapping("/return")
|
||||
@Operation(summary = "回退任务", description = "用于【流程详情】的【回退】按钮")
|
||||
@PreAuthorize("@ss.hasPermission('bpm:task:update')")
|
||||
public CommonResult<Boolean> returnTask(@Valid @RequestBody BpmTaskReturnReqVO reqVO) {
|
||||
taskService.returnTask(getLoginUserId(), reqVO);
|
||||
return success(true);
|
||||
}
|
||||
|
||||
@PutMapping("/delegate")
|
||||
@Operation(summary = "委派任务", description = "用于【流程详情】的【委派】按钮。和向前【加签】有点像,唯一区别是【委托】没有单独创立任务")
|
||||
@PreAuthorize("@ss.hasPermission('bpm:task:update')")
|
||||
public CommonResult<Boolean> delegateTask(@Valid @RequestBody BpmTaskDelegateReqVO reqVO) {
|
||||
taskService.delegateTask(getLoginUserId(), reqVO);
|
||||
return success(true);
|
||||
}
|
||||
|
||||
@PutMapping("/create-sign")
|
||||
@Operation(summary = "加签", description = "before 前加签,after 后加签")
|
||||
@PreAuthorize("@ss.hasPermission('bpm:task:update')")
|
||||
public CommonResult<Boolean> createSignTask(@Valid @RequestBody BpmTaskAddSignReqVO reqVO) {
|
||||
taskService.createSignTask(getLoginUserId(), reqVO);
|
||||
return success(true);
|
||||
}
|
||||
|
||||
@DeleteMapping("/delete-sign")
|
||||
@Operation(summary = "减签")
|
||||
@PreAuthorize("@ss.hasPermission('bpm:task:update')")
|
||||
public CommonResult<Boolean> deleteSignTask(@Valid @RequestBody BpmTaskSubSignReqVO reqVO) {
|
||||
taskService.deleteSignTask(getLoginUserId(), reqVO);
|
||||
return success(true);
|
||||
}
|
||||
|
||||
@GetMapping("children-list")
|
||||
@Operation(summary = "获取能被减签的任务")
|
||||
@Parameter(name = "parentId", description = "父级任务 ID", required = true)
|
||||
@PreAuthorize("@ss.hasPermission('bpm:task:update')")
|
||||
public CommonResult<List<BpmTaskSubSignRespVO>> getChildrenTaskList(@RequestParam("parentId") String parentId) {
|
||||
return success(taskService.getChildrenTaskList(parentId));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,30 @@
|
|||
package cn.iocoder.yudao.module.bpm.controller.admin.task.vo.task;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
import java.util.Set;
|
||||
|
||||
// TODO @海洋:类名,应该是 create 哈
|
||||
@Schema(description = "管理后台 - 加签流程任务的 Request VO")
|
||||
@Data
|
||||
public class BpmTaskAddSignReqVO {
|
||||
|
||||
@Schema(description = "需要加签的任务 ID")
|
||||
@NotEmpty(message = "任务编号不能为空")
|
||||
private String id;
|
||||
|
||||
@Schema(description = "加签的用户 ID")
|
||||
@NotEmpty(message = "加签用户 ID 不能为空")
|
||||
private Set<Long> userIdList;
|
||||
|
||||
@Schema(description = "加签类型,before 向前加签,after 向后加签")
|
||||
@NotEmpty(message = "加签类型不能为空")
|
||||
private String type;
|
||||
|
||||
@Schema(description = "加签原因")
|
||||
@NotEmpty(message = "加签原因不能为空")
|
||||
private String reason;
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,25 @@
|
|||
package cn.iocoder.yudao.module.bpm.controller.admin.task.vo.task;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
@Schema(description = "管理后台 - 委派流程任务的 Request VO")
|
||||
@Data
|
||||
public class BpmTaskDelegateReqVO {
|
||||
|
||||
@Schema(description = "任务编号", requiredMode = Schema.RequiredMode.REQUIRED, example = "1024")
|
||||
@NotEmpty(message = "任务编号不能为空")
|
||||
private String id;
|
||||
|
||||
@Schema(description = "被委派人 ID", requiredMode = Schema.RequiredMode.REQUIRED, example = "1")
|
||||
@NotNull(message = "被委派人 ID 不能为空")
|
||||
private Long delegateUserId;
|
||||
|
||||
@Schema(description = "委派原因", requiredMode = Schema.RequiredMode.REQUIRED, example = "做不了决定,需要你先帮忙瞅瞅")
|
||||
@NotEmpty(message = "委派原因不能为空")
|
||||
private String reason;
|
||||
|
||||
}
|
||||
|
|
@ -5,6 +5,8 @@ import lombok.Data;
|
|||
import lombok.EqualsAndHashCode;
|
||||
import lombok.ToString;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Schema(description = "管理后台 - 流程任务的 Response VO")
|
||||
@Data
|
||||
@EqualsAndHashCode(callSuper = true)
|
||||
|
|
@ -19,6 +21,14 @@ public class BpmTaskRespVO extends BpmTaskDonePageItemRespVO {
|
|||
*/
|
||||
private User assigneeUser;
|
||||
|
||||
/**
|
||||
* 父任务ID
|
||||
*/
|
||||
private String parentTaskId;
|
||||
|
||||
@Schema(description = "子任务(由加签生成)", requiredMode = Schema.RequiredMode.REQUIRED, example = "childrenTask")
|
||||
private List<BpmTaskRespVO> children;
|
||||
|
||||
@Schema(description = "用户信息")
|
||||
@Data
|
||||
public static class User {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,24 @@
|
|||
package cn.iocoder.yudao.module.bpm.controller.admin.task.vo.task;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
|
||||
@Schema(description = "管理后台 - 回退流程任务的 Request VO")
|
||||
@Data
|
||||
public class BpmTaskReturnReqVO {
|
||||
|
||||
@Schema(description = "任务编号", requiredMode = Schema.RequiredMode.REQUIRED, example = "1024")
|
||||
@NotEmpty(message = "任务编号不能为空")
|
||||
private String id;
|
||||
|
||||
@Schema(description = "回退到的任务 Key", requiredMode = Schema.RequiredMode.REQUIRED, example = "1")
|
||||
@NotEmpty(message = "回退到的任务 Key 不能为空")
|
||||
private String targetDefinitionKey;
|
||||
|
||||
@Schema(description = "回退意见", requiredMode = Schema.RequiredMode.REQUIRED, example = "我就是想驳回")
|
||||
@NotEmpty(message = "回退意见不能为空")
|
||||
private String reason;
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,16 @@
|
|||
package cn.iocoder.yudao.module.bpm.controller.admin.task.vo.task;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
@Schema(description = "管理后台 - 流程任务的精简 Response VO")
|
||||
@Data
|
||||
public class BpmTaskSimpleRespVO {
|
||||
|
||||
@Schema(description = "任务定义的标识", requiredMode = Schema.RequiredMode.REQUIRED, example = "Activity_one")
|
||||
private String definitionKey;
|
||||
|
||||
@Schema(description = "任务名词", requiredMode = Schema.RequiredMode.REQUIRED, example = "经理审批")
|
||||
private String name;
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
package cn.iocoder.yudao.module.bpm.controller.admin.task.vo.task;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
import javax.validation.constraints.NotEmpty;
|
||||
|
||||
// TODO @海洋:类名,应该是 delete 哈
|
||||
@Schema(description = "管理后台 - 减签流程任务的 Request VO")
|
||||
@Data
|
||||
public class BpmTaskSubSignReqVO {
|
||||
|
||||
@Schema(description = "被减签的任务 ID")
|
||||
@NotEmpty(message = "任务编号不能为空")
|
||||
private String id;
|
||||
|
||||
@Schema(description = "加签原因")
|
||||
@NotEmpty(message = "加签原因不能为空")
|
||||
private String reason;
|
||||
}
|
||||
|
|
@ -0,0 +1,15 @@
|
|||
package cn.iocoder.yudao.module.bpm.controller.admin.task.vo.task;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
@Schema(description = "管理后台 - 减签流程任务的 Response VO")
|
||||
@Data
|
||||
public class BpmTaskSubSignRespVO {
|
||||
@Schema(description = "审核的用户信息", requiredMode = Schema.RequiredMode.REQUIRED, example = "小李")
|
||||
private BpmTaskRespVO.User assigneeUser;
|
||||
@Schema(description = "任务 ID", requiredMode = Schema.RequiredMode.REQUIRED, example = "12312")
|
||||
private String id;
|
||||
@Schema(description = "任务名称", requiredMode = Schema.RequiredMode.REQUIRED, example = "经理审批")
|
||||
private String name;
|
||||
}
|
||||
|
|
@ -1,27 +1,34 @@
|
|||
package cn.iocoder.yudao.module.bpm.convert.task;
|
||||
|
||||
import cn.hutool.core.date.LocalDateTimeUtil;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
|
||||
import cn.iocoder.yudao.framework.common.util.collection.MapUtils;
|
||||
import cn.iocoder.yudao.framework.common.util.date.DateUtils;
|
||||
import cn.iocoder.yudao.framework.common.util.number.NumberUtils;
|
||||
import cn.iocoder.yudao.module.bpm.controller.admin.task.vo.task.BpmTaskDonePageItemRespVO;
|
||||
import cn.iocoder.yudao.module.bpm.controller.admin.task.vo.task.BpmTaskRespVO;
|
||||
import cn.iocoder.yudao.module.bpm.controller.admin.task.vo.task.BpmTaskTodoPageItemRespVO;
|
||||
import cn.iocoder.yudao.module.bpm.controller.admin.task.vo.task.*;
|
||||
import cn.iocoder.yudao.module.bpm.dal.dataobject.task.BpmTaskExtDO;
|
||||
import cn.iocoder.yudao.module.bpm.service.message.dto.BpmMessageSendWhenTaskCreatedReqDTO;
|
||||
import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO;
|
||||
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
|
||||
import org.flowable.bpmn.model.FlowElement;
|
||||
import org.flowable.common.engine.impl.db.SuspensionState;
|
||||
import org.flowable.engine.history.HistoricProcessInstance;
|
||||
import org.flowable.engine.runtime.ProcessInstance;
|
||||
import org.flowable.task.api.Task;
|
||||
import org.flowable.task.api.history.HistoricTaskInstance;
|
||||
import org.flowable.task.service.impl.persistence.entity.TaskEntityImpl;
|
||||
import org.mapstruct.*;
|
||||
import org.mapstruct.factory.Mappers;
|
||||
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertMultiMap;
|
||||
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.filterList;
|
||||
|
||||
/**
|
||||
* Bpm 任务 Convert
|
||||
*
|
||||
|
|
@ -47,8 +54,6 @@ public interface BpmTaskConvert {
|
|||
}
|
||||
|
||||
@Mapping(source = "suspended", target = "suspensionState", qualifiedByName = "convertSuspendedToSuspensionState")
|
||||
// @Mapping(target = "claimTime", expression = "java(bean.getClaimTime()==null?null: LocalDateTime.ofInstant(bean.getClaimTime().toInstant(),ZoneId.systemDefault()))")
|
||||
// @Mapping(target = "createTime", expression = "java(bean.getCreateTime()==null?null:LocalDateTime.ofInstant(bean.getCreateTime().toInstant(),ZoneId.systemDefault()))")
|
||||
BpmTaskTodoPageItemRespVO convert1(Task bean);
|
||||
|
||||
@Named("convertSuspendedToSuspensionState")
|
||||
|
|
@ -107,8 +112,6 @@ public interface BpmTaskConvert {
|
|||
}
|
||||
|
||||
@Mapping(source = "taskDefinitionKey", target = "definitionKey")
|
||||
// @Mapping(target = "createTime", expression = "java(bean.getCreateTime() == null ? null : LocalDateTime.ofInstant(bean.getCreateTime().toInstant(), ZoneId.systemDefault()))")
|
||||
// @Mapping(target = "endTime", expression = "java(bean.getEndTime() == null ? null : LocalDateTime.ofInstant(bean.getEndTime().toInstant(), ZoneId.systemDefault()))")
|
||||
BpmTaskRespVO convert3(HistoricTaskInstance bean);
|
||||
|
||||
BpmTaskRespVO.User convert3(AdminUserRespDTO bean);
|
||||
|
|
@ -142,4 +145,57 @@ public interface BpmTaskConvert {
|
|||
return reqDTO;
|
||||
}
|
||||
|
||||
default List<BpmTaskSimpleRespVO> convertList(List<? extends FlowElement> elementList) {
|
||||
return CollectionUtils.convertList(elementList, element -> new BpmTaskSimpleRespVO()
|
||||
.setName(element.getName())
|
||||
.setDefinitionKey(element.getId()));
|
||||
}
|
||||
|
||||
//此处不用 mapstruct 映射,因为 TaskEntityImpl 还有很多其他属性,这里我们只设置我们需要的
|
||||
//使用 mapstruct 会将里面嵌套的各个属性值都设置进去,会出现意想不到的问题
|
||||
default TaskEntityImpl convert(TaskEntityImpl task,TaskEntityImpl parentTask){
|
||||
task.setCategory(parentTask.getCategory());
|
||||
task.setDescription(parentTask.getDescription());
|
||||
task.setTenantId(parentTask.getTenantId());
|
||||
task.setName(parentTask.getName());
|
||||
task.setParentTaskId(parentTask.getId());
|
||||
task.setProcessDefinitionId(parentTask.getProcessDefinitionId());
|
||||
task.setProcessInstanceId(parentTask.getProcessInstanceId());
|
||||
task.setTaskDefinitionKey(parentTask.getTaskDefinitionKey());
|
||||
task.setTaskDefinitionId(parentTask.getTaskDefinitionId());
|
||||
task.setPriority(parentTask.getPriority());
|
||||
task.setCreateTime(new Date());
|
||||
return task;
|
||||
}
|
||||
|
||||
default List<BpmTaskSubSignRespVO> convertList(List<BpmTaskExtDO> bpmTaskExtDOList,
|
||||
Map<Long, AdminUserRespDTO> userMap,
|
||||
Map<String, Task> idTaskMap){
|
||||
return CollectionUtils.convertList(bpmTaskExtDOList, task -> {
|
||||
BpmTaskSubSignRespVO bpmTaskSubSignRespVO = new BpmTaskSubSignRespVO()
|
||||
.setId(task.getTaskId()).setName(task.getName());
|
||||
// 后加签任务不会直接设置 assignee ,所以不存在 assignee 的情况,则去取 owner
|
||||
Task sourceTask = idTaskMap.get(task.getTaskId());
|
||||
String assignee = ObjectUtil.defaultIfBlank(sourceTask.getOwner(),sourceTask.getAssignee());
|
||||
MapUtils.findAndThen(userMap,NumberUtils.parseLong(assignee),
|
||||
assignUser-> bpmTaskSubSignRespVO.setAssigneeUser(convert3(assignUser)));
|
||||
return bpmTaskSubSignRespVO;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换任务为父子级
|
||||
*
|
||||
* @param sourceList 原始数据
|
||||
* @return 转换后的父子级数组
|
||||
*/
|
||||
default List<BpmTaskRespVO> convertChildrenList(List<BpmTaskRespVO> sourceList) {
|
||||
List<BpmTaskRespVO> childrenTaskList = filterList(sourceList, r -> StrUtil.isNotEmpty(r.getParentTaskId()));
|
||||
Map<String, List<BpmTaskRespVO>> parentChildrenTaskListMap = convertMultiMap(childrenTaskList, BpmTaskRespVO::getParentTaskId);
|
||||
for (BpmTaskRespVO bpmTaskRespVO : sourceList) {
|
||||
bpmTaskRespVO.setChildren(parentChildrenTaskListMap.get(bpmTaskRespVO.getId()));
|
||||
}
|
||||
return filterList(sourceList, r -> StrUtil.isEmpty(r.getParentTaskId()));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,7 +1,9 @@
|
|||
package cn.iocoder.yudao.module.bpm.dal.mysql.task;
|
||||
|
||||
import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
|
||||
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
|
||||
import cn.iocoder.yudao.module.bpm.dal.dataobject.task.BpmTaskExtDO;
|
||||
import cn.iocoder.yudao.module.bpm.enums.task.BpmProcessInstanceResultEnum;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
|
||||
|
|
@ -19,8 +21,19 @@ public interface BpmTaskExtMapper extends BaseMapperX<BpmTaskExtDO> {
|
|||
return selectList(BpmTaskExtDO::getTaskId, taskIds);
|
||||
}
|
||||
|
||||
// TODO @海:BpmProcessInstanceResultEnum.CAN_SUB_SIGN_STATUS_LIST) 应该作为条件,mapper 不要有业务
|
||||
default List<BpmTaskExtDO> selectProcessListByTaskIds(Collection<String> taskIds) {
|
||||
return selectList(new LambdaQueryWrapperX<BpmTaskExtDO>()
|
||||
.in(BpmTaskExtDO::getTaskId, taskIds)
|
||||
.in(BpmTaskExtDO::getResult, BpmProcessInstanceResultEnum.CAN_SUB_SIGN_STATUS_LIST));
|
||||
}
|
||||
|
||||
default BpmTaskExtDO selectByTaskId(String taskId) {
|
||||
return selectOne(BpmTaskExtDO::getTaskId, taskId);
|
||||
}
|
||||
|
||||
default void updateBatchByTaskIdList(List<String> taskIdList, BpmTaskExtDO updateObj) {
|
||||
update(updateObj, new LambdaQueryWrapper<BpmTaskExtDO>().in(BpmTaskExtDO::getTaskId, taskIdList));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -0,0 +1,24 @@
|
|||
package cn.iocoder.yudao.module.bpm.framework.web.config;
|
||||
|
||||
import cn.iocoder.yudao.framework.swagger.config.YudaoSwaggerAutoConfiguration;
|
||||
import org.springdoc.core.GroupedOpenApi;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
/**
|
||||
* bpm 模块的 web 组件的 Configuration
|
||||
*
|
||||
* @author 芋道源码
|
||||
*/
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
public class BpmWebConfiguration {
|
||||
|
||||
/**
|
||||
* bpm 模块的 API 分组
|
||||
*/
|
||||
@Bean
|
||||
public GroupedOpenApi bpmGroupedOpenApi() {
|
||||
return YudaoSwaggerAutoConfiguration.buildGroupedOpenApi("bpm");
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
/**
|
||||
* bpm 模块的 web 配置
|
||||
*/
|
||||
package cn.iocoder.yudao.module.bpm.framework.web;
|
||||
|
|
@ -12,6 +12,7 @@ import javax.validation.Valid;
|
|||
* @author yunlongn
|
||||
*/
|
||||
public interface BpmModelService {
|
||||
|
||||
/**
|
||||
* 获得流程模型分页
|
||||
*
|
||||
|
|
@ -74,4 +75,12 @@ public interface BpmModelService {
|
|||
*/
|
||||
BpmnModel getBpmnModel(String id);
|
||||
|
||||
/**
|
||||
* 获得流程定义编号对应的 BPMN Model
|
||||
*
|
||||
* @param processDefinitionId 流程定义编号
|
||||
* @return BPMN Model
|
||||
*/
|
||||
BpmnModel getBpmnModelByDefinitionId(String processDefinitionId);
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -233,6 +233,11 @@ public class BpmModelServiceImpl implements BpmModelService {
|
|||
return converter.convertToBpmnModel(new BytesStreamSource(bpmnBytes), true, true);
|
||||
}
|
||||
|
||||
@Override
|
||||
public BpmnModel getBpmnModelByDefinitionId(String processDefinitionId) {
|
||||
return repositoryService.getBpmnModel(processDefinitionId);
|
||||
}
|
||||
|
||||
private void checkKeyNCName(String key) {
|
||||
if (!ValidationUtils.isXmlNCName(key)) {
|
||||
throw exception(MODEL_KEY_VALID);
|
||||
|
|
@ -283,5 +288,4 @@ public class BpmModelServiceImpl implements BpmModelService {
|
|||
processDefinitionService.updateProcessDefinitionState(oldDefinition.getId(), SuspensionState.SUSPENDED.getStateCode());
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ import cn.hutool.core.util.ObjectUtil;
|
|||
import cn.hutool.core.util.StrUtil;
|
||||
import cn.iocoder.yudao.framework.common.pojo.PageResult;
|
||||
import cn.iocoder.yudao.framework.common.util.object.PageUtils;
|
||||
import cn.iocoder.yudao.framework.flowable.core.util.FlowableUtils;
|
||||
import cn.iocoder.yudao.framework.flowable.core.util.BpmnModelUtils;
|
||||
import cn.iocoder.yudao.module.bpm.controller.admin.definition.vo.process.BpmProcessDefinitionListReqVO;
|
||||
import cn.iocoder.yudao.module.bpm.controller.admin.definition.vo.process.BpmProcessDefinitionPageItemRespVO;
|
||||
import cn.iocoder.yudao.module.bpm.controller.admin.definition.vo.process.BpmProcessDefinitionPageReqVO;
|
||||
|
|
@ -200,7 +200,7 @@ public class BpmProcessDefinitionServiceImpl implements BpmProcessDefinitionServ
|
|||
BpmnModel newModel = buildBpmnModel(createReqDTO.getBpmnBytes());
|
||||
BpmnModel oldModel = getBpmnModel(oldProcessDefinition.getId());
|
||||
// 对比字节变化
|
||||
if (!FlowableUtils.equals(oldModel, newModel)) {
|
||||
if (!BpmnModelUtils.equals(oldModel, newModel)) {
|
||||
return false;
|
||||
}
|
||||
// 最终发现都一致,则返回 true
|
||||
|
|
|
|||
|
|
@ -7,7 +7,7 @@ import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
|
|||
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
|
||||
import cn.iocoder.yudao.framework.common.util.object.ObjectUtils;
|
||||
import cn.iocoder.yudao.framework.datapermission.core.annotation.DataPermission;
|
||||
import cn.iocoder.yudao.framework.flowable.core.util.FlowableUtils;
|
||||
import cn.iocoder.yudao.framework.flowable.core.util.BpmnModelUtils;
|
||||
import cn.iocoder.yudao.module.bpm.controller.admin.definition.vo.rule.BpmTaskAssignRuleCreateReqVO;
|
||||
import cn.iocoder.yudao.module.bpm.controller.admin.definition.vo.rule.BpmTaskAssignRuleRespVO;
|
||||
import cn.iocoder.yudao.module.bpm.controller.admin.definition.vo.rule.BpmTaskAssignRuleUpdateReqVO;
|
||||
|
|
@ -15,8 +15,8 @@ import cn.iocoder.yudao.module.bpm.convert.definition.BpmTaskAssignRuleConvert;
|
|||
import cn.iocoder.yudao.module.bpm.dal.dataobject.definition.BpmTaskAssignRuleDO;
|
||||
import cn.iocoder.yudao.module.bpm.dal.dataobject.definition.BpmUserGroupDO;
|
||||
import cn.iocoder.yudao.module.bpm.dal.mysql.definition.BpmTaskAssignRuleMapper;
|
||||
import cn.iocoder.yudao.module.bpm.enums.definition.BpmTaskAssignRuleTypeEnum;
|
||||
import cn.iocoder.yudao.module.bpm.enums.DictTypeConstants;
|
||||
import cn.iocoder.yudao.module.bpm.enums.definition.BpmTaskAssignRuleTypeEnum;
|
||||
import cn.iocoder.yudao.module.bpm.framework.flowable.core.behavior.script.BpmTaskAssignScript;
|
||||
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
|
||||
import cn.iocoder.yudao.module.system.api.dept.PostApi;
|
||||
|
|
@ -114,7 +114,7 @@ public class BpmTaskAssignRuleServiceImpl implements BpmTaskAssignRuleService {
|
|||
return Collections.emptyList();
|
||||
}
|
||||
// 获得用户任务,只有用户任务才可以设置分配规则
|
||||
List<UserTask> userTasks = FlowableUtils.getBpmnModelElements(model, UserTask.class);
|
||||
List<UserTask> userTasks = BpmnModelUtils.getBpmnModelElements(model, UserTask.class);
|
||||
if (CollUtil.isEmpty(userTasks)) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,5 @@
|
|||
package cn.iocoder.yudao.module.bpm.service.oa;
|
||||
|
||||
import cn.hutool.core.date.DateUtil;
|
||||
import cn.hutool.core.date.LocalDateTimeUtil;
|
||||
import cn.iocoder.yudao.framework.common.pojo.PageResult;
|
||||
import cn.iocoder.yudao.module.bpm.api.task.BpmProcessInstanceApi;
|
||||
|
|
@ -57,7 +56,7 @@ public class BpmOALeaveServiceImpl implements BpmOALeaveService {
|
|||
processInstanceVariables.put("day", day);
|
||||
String processInstanceId = processInstanceApi.createProcessInstance(userId,
|
||||
new BpmProcessInstanceCreateReqDTO().setProcessDefinitionKey(PROCESS_KEY)
|
||||
.setVariables(processInstanceVariables).setBusinessKey(String.valueOf(leave.getId())));
|
||||
.setVariables(processInstanceVariables).setBusinessKey(String.valueOf(leave.getId()))).getCheckedData();
|
||||
|
||||
// 将工作流的编号,更新到 OA 请假单中
|
||||
leaveMapper.updateById(new BpmOALeaveDO().setId(leave.getId()).setProcessInstanceId(processInstanceId));
|
||||
|
|
|
|||
|
|
@ -1,9 +1,9 @@
|
|||
package cn.iocoder.yudao.module.bpm.service.task;
|
||||
|
||||
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
|
||||
import cn.iocoder.yudao.framework.common.pojo.PageResult;
|
||||
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
|
||||
import cn.iocoder.yudao.module.bpm.controller.admin.task.vo.task.*;
|
||||
import cn.iocoder.yudao.module.bpm.dal.dataobject.task.BpmTaskExtDO;
|
||||
import org.flowable.task.api.Task;
|
||||
|
||||
import javax.validation.Valid;
|
||||
|
|
@ -23,7 +23,6 @@ public interface BpmTaskService {
|
|||
*
|
||||
* @param userId 用户编号
|
||||
* @param pageReqVO 分页请求
|
||||
*
|
||||
* @return 流程任务分页
|
||||
*/
|
||||
PageResult<BpmTaskTodoPageItemRespVO> getTodoTaskPage(Long userId, BpmTaskTodoPageReqVO pageReqVO);
|
||||
|
|
@ -33,7 +32,6 @@ public interface BpmTaskService {
|
|||
*
|
||||
* @param userId 用户编号
|
||||
* @param pageReqVO 分页请求
|
||||
*
|
||||
* @return 流程任务分页
|
||||
*/
|
||||
PageResult<BpmTaskDonePageItemRespVO> getDoneTaskPage(Long userId, BpmTaskDonePageReqVO pageReqVO);
|
||||
|
|
@ -42,19 +40,17 @@ public interface BpmTaskService {
|
|||
* 获得流程任务 Map
|
||||
*
|
||||
* @param processInstanceIds 流程实例的编号数组
|
||||
*
|
||||
* @return 流程任务 Map
|
||||
*/
|
||||
default Map<String, List<Task>> getTaskMapByProcessInstanceIds(List<String> processInstanceIds) {
|
||||
return CollectionUtils.convertMultiMap(getTasksByProcessInstanceIds(processInstanceIds),
|
||||
Task::getProcessInstanceId);
|
||||
Task::getProcessInstanceId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得流程任务列表
|
||||
*
|
||||
* @param processInstanceIds 流程实例的编号数组
|
||||
*
|
||||
* @return 流程任务列表
|
||||
*/
|
||||
List<Task> getTasksByProcessInstanceIds(List<String> processInstanceIds);
|
||||
|
|
@ -63,11 +59,19 @@ public interface BpmTaskService {
|
|||
* 获得指令流程实例的流程任务列表,包括所有状态的
|
||||
*
|
||||
* @param processInstanceId 流程实例的编号
|
||||
*
|
||||
* @return 流程任务列表
|
||||
*/
|
||||
List<BpmTaskRespVO> getTaskListByProcessInstanceId(String processInstanceId);
|
||||
|
||||
|
||||
/**
|
||||
* 通过任务 ID 集合,获取任务扩展表信息集合
|
||||
*
|
||||
* @param taskIdList 任务 ID 集合
|
||||
* @return 任务列表
|
||||
*/
|
||||
List<BpmTaskExtDO> getTaskListByTaskIdList(List<String> taskIdList);
|
||||
|
||||
/**
|
||||
* 通过任务
|
||||
*
|
||||
|
|
@ -128,4 +132,53 @@ public interface BpmTaskService {
|
|||
*/
|
||||
void updateTaskExtAssign(Task task);
|
||||
|
||||
/**
|
||||
* 获取当前任务的可回退的流程集合
|
||||
*
|
||||
* @param taskId 当前的任务 ID
|
||||
* @return 可以回退的节点列表
|
||||
*/
|
||||
List<BpmTaskSimpleRespVO> getReturnTaskList(String taskId);
|
||||
|
||||
/**
|
||||
* 将任务回退到指定的 targetDefinitionKey 位置
|
||||
*
|
||||
* @param userId 用户编号
|
||||
* @param reqVO 回退的任务key和当前所在的任务ID
|
||||
*/
|
||||
void returnTask(Long userId, BpmTaskReturnReqVO reqVO);
|
||||
|
||||
|
||||
/**
|
||||
* 将指定任务委派给其他人处理,等接收人处理后再回到原审批人手中审批
|
||||
*
|
||||
* @param userId 用户编号
|
||||
* @param reqVO 被委派人和被委派的任务编号理由参数
|
||||
*/
|
||||
void delegateTask(Long userId, BpmTaskDelegateReqVO reqVO);
|
||||
|
||||
/**
|
||||
* 任务加签
|
||||
*
|
||||
* @param userId 被加签的用户和任务 ID,加签类型
|
||||
* @param reqVO 当前用户 ID
|
||||
*/
|
||||
void createSignTask(Long userId, BpmTaskAddSignReqVO reqVO);
|
||||
|
||||
/**
|
||||
* 任务减签名
|
||||
*
|
||||
* @param userId 当前用户ID
|
||||
* @param reqVO 被减签的任务 ID,理由
|
||||
*/
|
||||
void deleteSignTask(Long userId, BpmTaskSubSignReqVO reqVO);
|
||||
|
||||
/**
|
||||
* 获取指定任务的子任务和审批人信息
|
||||
*
|
||||
* @param parentId 指定任务ID
|
||||
* @return 子任务列表
|
||||
*/
|
||||
List<BpmTaskSubSignRespVO> getChildrenTaskList(String parentId);
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,45 +2,63 @@ package cn.iocoder.yudao.module.bpm.service.task;
|
|||
|
||||
import cn.hutool.core.collection.CollUtil;
|
||||
import cn.hutool.core.util.ArrayUtil;
|
||||
import cn.hutool.core.util.IdUtil;
|
||||
import cn.hutool.core.util.ObjectUtil;
|
||||
import cn.hutool.core.util.StrUtil;
|
||||
import cn.iocoder.yudao.framework.common.pojo.PageResult;
|
||||
import cn.iocoder.yudao.framework.common.util.date.DateUtils;
|
||||
import cn.iocoder.yudao.framework.common.util.number.NumberUtils;
|
||||
import cn.iocoder.yudao.framework.common.util.object.PageUtils;
|
||||
import cn.iocoder.yudao.framework.flowable.core.util.BpmnModelUtils;
|
||||
import cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils;
|
||||
import cn.iocoder.yudao.module.bpm.controller.admin.task.vo.task.*;
|
||||
import cn.iocoder.yudao.module.bpm.convert.task.BpmTaskConvert;
|
||||
import cn.iocoder.yudao.module.bpm.dal.dataobject.task.BpmTaskExtDO;
|
||||
import cn.iocoder.yudao.module.bpm.dal.mysql.task.BpmTaskExtMapper;
|
||||
import cn.iocoder.yudao.module.bpm.enums.task.BpmCommentTypeEnum;
|
||||
import cn.iocoder.yudao.module.bpm.enums.task.BpmProcessInstanceDeleteReasonEnum;
|
||||
import cn.iocoder.yudao.module.bpm.enums.task.BpmProcessInstanceResultEnum;
|
||||
import cn.iocoder.yudao.module.bpm.enums.task.BpmTaskAddSignTypeEnum;
|
||||
import cn.iocoder.yudao.module.bpm.service.definition.BpmModelService;
|
||||
import cn.iocoder.yudao.module.bpm.service.message.BpmMessageService;
|
||||
import cn.iocoder.yudao.module.system.api.dept.DeptApi;
|
||||
import cn.iocoder.yudao.module.system.api.dept.dto.DeptRespDTO;
|
||||
import cn.iocoder.yudao.module.system.api.user.AdminUserApi;
|
||||
import cn.iocoder.yudao.module.system.api.user.dto.AdminUserRespDTO;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.flowable.bpmn.model.BpmnModel;
|
||||
import org.flowable.bpmn.model.FlowElement;
|
||||
import org.flowable.bpmn.model.UserTask;
|
||||
import org.flowable.engine.HistoryService;
|
||||
import org.flowable.engine.ManagementService;
|
||||
import org.flowable.engine.RuntimeService;
|
||||
import org.flowable.engine.TaskService;
|
||||
import org.flowable.engine.history.HistoricProcessInstance;
|
||||
import org.flowable.engine.runtime.ProcessInstance;
|
||||
import org.flowable.task.api.DelegationState;
|
||||
import org.flowable.task.api.Task;
|
||||
import org.flowable.task.api.TaskInfo;
|
||||
import org.flowable.task.api.TaskQuery;
|
||||
import org.flowable.task.api.history.HistoricTaskInstance;
|
||||
import org.flowable.task.api.history.HistoricTaskInstanceQuery;
|
||||
import org.flowable.task.service.impl.persistence.entity.TaskEntity;
|
||||
import org.flowable.task.service.impl.persistence.entity.TaskEntityImpl;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.transaction.support.TransactionSynchronization;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import javax.validation.Valid;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.*;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
|
||||
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertMap;
|
||||
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;
|
||||
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.*;
|
||||
import static cn.iocoder.yudao.module.bpm.enums.ErrorCodeConstants.*;
|
||||
import static cn.iocoder.yudao.module.bpm.enums.ErrorCodeConstants.TASK_TARGET_NODE_NOT_EXISTS;
|
||||
|
||||
/**
|
||||
* 流程任务实例 Service 实现类
|
||||
|
|
@ -56,23 +74,32 @@ public class BpmTaskServiceImpl implements BpmTaskService {
|
|||
private TaskService taskService;
|
||||
@Resource
|
||||
private HistoryService historyService;
|
||||
@Resource
|
||||
private RuntimeService runtimeService;
|
||||
|
||||
@Resource
|
||||
private BpmProcessInstanceService processInstanceService;
|
||||
@Resource
|
||||
private BpmModelService bpmModelService;
|
||||
@Resource
|
||||
private BpmMessageService messageService;
|
||||
|
||||
@Resource
|
||||
private AdminUserApi adminUserApi;
|
||||
@Resource
|
||||
private DeptApi deptApi;
|
||||
|
||||
@Resource
|
||||
private BpmTaskExtMapper taskExtMapper;
|
||||
|
||||
@Resource
|
||||
private BpmMessageService messageService;
|
||||
private ManagementService managementService;
|
||||
|
||||
@Override
|
||||
public PageResult<BpmTaskTodoPageItemRespVO> getTodoTaskPage(Long userId, BpmTaskTodoPageReqVO pageVO) {
|
||||
// 查询待办任务
|
||||
TaskQuery taskQuery = taskService.createTaskQuery().taskAssignee(String.valueOf(userId)) // 分配给自己
|
||||
.orderByTaskCreateTime().desc(); // 创建时间倒序
|
||||
.orderByTaskCreateTime().desc(); // 创建时间倒序
|
||||
if (StrUtil.isNotBlank(pageVO.getName())) {
|
||||
taskQuery.taskNameLike("%" + pageVO.getName() + "%");
|
||||
}
|
||||
|
|
@ -90,21 +117,21 @@ public class BpmTaskServiceImpl implements BpmTaskService {
|
|||
|
||||
// 获得 ProcessInstance Map
|
||||
Map<String, ProcessInstance> processInstanceMap =
|
||||
processInstanceService.getProcessInstanceMap(convertSet(tasks, Task::getProcessInstanceId));
|
||||
processInstanceService.getProcessInstanceMap(convertSet(tasks, Task::getProcessInstanceId));
|
||||
// 获得 User Map
|
||||
Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMap(
|
||||
convertSet(processInstanceMap.values(), instance -> Long.valueOf(instance.getStartUserId())));
|
||||
convertSet(processInstanceMap.values(), instance -> Long.valueOf(instance.getStartUserId())));
|
||||
// 拼接结果
|
||||
return new PageResult<>(BpmTaskConvert.INSTANCE.convertList1(tasks, processInstanceMap, userMap),
|
||||
taskQuery.count());
|
||||
taskQuery.count());
|
||||
}
|
||||
|
||||
@Override
|
||||
public PageResult<BpmTaskDonePageItemRespVO> getDoneTaskPage(Long userId, BpmTaskDonePageReqVO pageVO) {
|
||||
// 查询已办任务
|
||||
HistoricTaskInstanceQuery taskQuery = historyService.createHistoricTaskInstanceQuery().finished() // 已完成
|
||||
.taskAssignee(String.valueOf(userId)) // 分配给自己
|
||||
.orderByHistoricTaskInstanceEndTime().desc(); // 审批时间倒序
|
||||
.taskAssignee(String.valueOf(userId)) // 分配给自己
|
||||
.orderByHistoricTaskInstanceEndTime().desc(); // 审批时间倒序
|
||||
if (StrUtil.isNotBlank(pageVO.getName())) {
|
||||
taskQuery.taskNameLike("%" + pageVO.getName() + "%");
|
||||
}
|
||||
|
|
@ -122,19 +149,19 @@ public class BpmTaskServiceImpl implements BpmTaskService {
|
|||
|
||||
// 获得 TaskExtDO Map
|
||||
List<BpmTaskExtDO> bpmTaskExtDOs =
|
||||
taskExtMapper.selectListByTaskIds(convertSet(tasks, HistoricTaskInstance::getId));
|
||||
taskExtMapper.selectListByTaskIds(convertSet(tasks, HistoricTaskInstance::getId));
|
||||
Map<String, BpmTaskExtDO> bpmTaskExtDOMap = convertMap(bpmTaskExtDOs, BpmTaskExtDO::getTaskId);
|
||||
// 获得 ProcessInstance Map
|
||||
Map<String, HistoricProcessInstance> historicProcessInstanceMap =
|
||||
processInstanceService.getHistoricProcessInstanceMap(
|
||||
convertSet(tasks, HistoricTaskInstance::getProcessInstanceId));
|
||||
processInstanceService.getHistoricProcessInstanceMap(
|
||||
convertSet(tasks, HistoricTaskInstance::getProcessInstanceId));
|
||||
// 获得 User Map
|
||||
Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMap(
|
||||
convertSet(historicProcessInstanceMap.values(), instance -> Long.valueOf(instance.getStartUserId())));
|
||||
convertSet(historicProcessInstanceMap.values(), instance -> Long.valueOf(instance.getStartUserId())));
|
||||
// 拼接结果
|
||||
return new PageResult<>(
|
||||
BpmTaskConvert.INSTANCE.convertList2(tasks, bpmTaskExtDOMap, historicProcessInstanceMap, userMap),
|
||||
taskQuery.count());
|
||||
BpmTaskConvert.INSTANCE.convertList2(tasks, bpmTaskExtDOMap, historicProcessInstanceMap, userMap),
|
||||
taskQuery.count());
|
||||
}
|
||||
|
||||
@Override
|
||||
|
|
@ -169,33 +196,242 @@ public class BpmTaskServiceImpl implements BpmTaskService {
|
|||
Map<Long, DeptRespDTO> deptMap = deptApi.getDeptMap(convertSet(userMap.values(), AdminUserRespDTO::getDeptId));
|
||||
|
||||
// 拼接数据
|
||||
return BpmTaskConvert.INSTANCE.convertList3(tasks, bpmTaskExtDOMap, processInstance, userMap, deptMap);
|
||||
List<BpmTaskRespVO> result = BpmTaskConvert.INSTANCE.convertList3(tasks, bpmTaskExtDOMap, processInstance, userMap, deptMap);
|
||||
return BpmTaskConvert.INSTANCE.convertChildrenList(result);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<BpmTaskExtDO> getTaskListByTaskIdList(List<String> taskIdList) {
|
||||
return taskExtMapper.selectListByTaskIds(taskIdList);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void approveTask(Long userId, @Valid BpmTaskApproveReqVO reqVO) {
|
||||
// 校验任务存在
|
||||
Task task = checkTask(userId, reqVO.getId());
|
||||
// 校验流程实例存在
|
||||
// 1.1 校验任务存在
|
||||
Task task = validateTask(userId, reqVO.getId());
|
||||
// 1.2 校验流程实例存在
|
||||
ProcessInstance instance = processInstanceService.getProcessInstance(task.getProcessInstanceId());
|
||||
if (instance == null) {
|
||||
throw exception(PROCESS_INSTANCE_NOT_EXISTS);
|
||||
}
|
||||
|
||||
// 情况一:被委派的任务,不调用 complete 去完成任务
|
||||
if (DelegationState.PENDING.equals(task.getDelegationState())) {
|
||||
approveDelegateTask(reqVO, task);
|
||||
return;
|
||||
}
|
||||
|
||||
// 情况二:后加签的任务
|
||||
if (BpmTaskAddSignTypeEnum.AFTER.getType().equals(task.getScopeType())) {
|
||||
// 后加签处理
|
||||
approveAfterSignTask(task, reqVO);
|
||||
return;
|
||||
}
|
||||
|
||||
// 情况三:自己审批的任务,调用 complete 去完成任务
|
||||
// 完成任务,审批通过
|
||||
taskService.complete(task.getId(), instance.getProcessVariables());
|
||||
|
||||
// 更新任务拓展表为通过
|
||||
taskExtMapper.updateByTaskId(
|
||||
new BpmTaskExtDO().setTaskId(task.getId()).setResult(BpmProcessInstanceResultEnum.APPROVE.getResult())
|
||||
.setReason(reqVO.getReason()));
|
||||
new BpmTaskExtDO().setTaskId(task.getId()).setResult(BpmProcessInstanceResultEnum.APPROVE.getResult())
|
||||
.setReason(reqVO.getReason()));
|
||||
// 处理加签任务
|
||||
handleParentTask(task);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 审批通过存在“后加签”的任务。
|
||||
* <p>
|
||||
* 注意:该任务不能马上完成,需要一个中间状态(SIGN_AFTER),并激活剩余所有子任务(PROCESS)为可审批处理
|
||||
*
|
||||
* @param task 当前任务
|
||||
* @param reqVO 前端请求参数
|
||||
*/
|
||||
private void approveAfterSignTask(Task task, BpmTaskApproveReqVO reqVO) {
|
||||
// 1. 有向后加签,则该任务状态临时设置为 ADD_SIGN_AFTER 状态
|
||||
taskExtMapper.updateByTaskId(
|
||||
new BpmTaskExtDO().setTaskId(task.getId()).setResult(BpmProcessInstanceResultEnum.SIGN_AFTER.getResult())
|
||||
.setReason(reqVO.getReason()).setEndTime(LocalDateTime.now()));
|
||||
|
||||
// 2. 激活子任务
|
||||
List<String> childrenTaskIdList = getChildrenTaskIdList(task.getId());
|
||||
for (String childrenTaskId : childrenTaskIdList) {
|
||||
taskService.resolveTask(childrenTaskId);
|
||||
}
|
||||
// 2.1 更新任务扩展表中子任务为进行中
|
||||
taskExtMapper.updateBatchByTaskIdList(childrenTaskIdList,
|
||||
new BpmTaskExtDO().setResult(BpmProcessInstanceResultEnum.PROCESS.getResult()));
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理当前任务的父任务,主要处理“加签”的情况
|
||||
*
|
||||
* @param task 当前任务
|
||||
*/
|
||||
private void handleParentTask(Task task) {
|
||||
String parentTaskId = task.getParentTaskId();
|
||||
if (StrUtil.isBlank(parentTaskId)) {
|
||||
return;
|
||||
}
|
||||
// 1. 判断当前任务的父任务是否还有子任务
|
||||
Long childrenTaskCount = getChildrenTaskCount(parentTaskId);
|
||||
if (childrenTaskCount > 0) {
|
||||
return;
|
||||
}
|
||||
// 2. 获取父任务
|
||||
Task parentTask = validateTaskExist(parentTaskId);
|
||||
|
||||
// 3. 处理加签情况
|
||||
String scopeType = parentTask.getScopeType();
|
||||
if(!validateSignType(scopeType)){
|
||||
return;
|
||||
}
|
||||
// 3.1 情况一:处理向前加签
|
||||
if (BpmTaskAddSignTypeEnum.BEFORE.getType().equals(scopeType)) {
|
||||
// 3.1.1 如果是向前加签的任务,则调用 resolveTask 指派父任务,将 owner 重新赋值给父任务的 assignee,这样它就可以被审批
|
||||
taskService.resolveTask(parentTaskId);
|
||||
// 3.1.2 更新任务拓展表为处理中
|
||||
taskExtMapper.updateByTaskId(
|
||||
new BpmTaskExtDO().setTaskId(parentTask.getId()).setResult(BpmProcessInstanceResultEnum.PROCESS.getResult()));
|
||||
} else if (BpmTaskAddSignTypeEnum.AFTER.getType().equals(scopeType)) {
|
||||
// 3.2 情况二:处理向后加签
|
||||
handleParentTaskForAfterSign(parentTask);
|
||||
}
|
||||
|
||||
// 4. 子任务已处理完成,清空 scopeType 字段,修改 parentTask 信息,方便后续可以继续向前后向后加签
|
||||
// 再查询一次的原因是避免报错:Task was updated by another transaction concurrently
|
||||
// 因为前面处理后可能会导致 parentTask rev 字段被修改,需要重新获取最新的
|
||||
parentTask = getTask(parentTaskId);
|
||||
if (parentTask == null) {
|
||||
// 为空的情况是:已经通过 handleAfterSign 方法将任务完成了,所以 ru_task 表会查不到数据
|
||||
return;
|
||||
}
|
||||
clearTaskScopeTypeAndSave(parentTask);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 处理后加签任务
|
||||
*
|
||||
* @param parentTask 当前审批任务的父任务
|
||||
*/
|
||||
// TODO @海:这个逻辑,怎么感觉可以是 parentTask 的 parent,再去调用 handleParentTask 方法;可以微信聊下;
|
||||
private void handleParentTaskForAfterSign(Task parentTask) {
|
||||
String parentTaskId = parentTask.getId();
|
||||
// 1. 更新 parentTask 的任务拓展表为通过,并调用 complete 完成自己
|
||||
BpmTaskExtDO currentTaskExt = taskExtMapper.selectByTaskId(parentTask.getId());
|
||||
BpmTaskExtDO currentTaskExtUpdateObj = new BpmTaskExtDO().setTaskId(parentTask.getId())
|
||||
.setResult(BpmProcessInstanceResultEnum.APPROVE.getResult());
|
||||
if (currentTaskExt.getEndTime() == null) {
|
||||
// 1.1 有这个判断是因为,以前没设置过结束时间,才去设置
|
||||
currentTaskExtUpdateObj.setEndTime(LocalDateTime.now());
|
||||
}
|
||||
taskExtMapper.updateByTaskId(currentTaskExtUpdateObj);
|
||||
// 1.2 完成自己(因为它已经没有子任务,所以也可以完成)
|
||||
taskService.complete(parentTaskId);
|
||||
|
||||
// 2. 如果有父级,递归查询上级任务是否都已经完成
|
||||
if (StrUtil.isEmpty(parentTask.getParentTaskId())) {
|
||||
return;
|
||||
}
|
||||
// 2.1 判断整条链路的任务是否完成
|
||||
// 例如从 A 任务加签了一个 B 任务,B 任务又加签了一个 C 任务,C 任务加签了 D 任务
|
||||
// 此时,D 任务完成,要一直往上找到祖先任务 A调用 complete 方法完成 A 任务
|
||||
boolean allChildrenTaskFinish = true;
|
||||
while (StrUtil.isNotBlank(parentTask.getParentTaskId())) {
|
||||
parentTask = validateTaskExist(parentTask.getParentTaskId());
|
||||
BpmTaskExtDO parentTaskExt = taskExtMapper.selectByTaskId(parentTask.getId());
|
||||
if (parentTaskExt == null) {
|
||||
break;
|
||||
}
|
||||
boolean currentTaskFinish = BpmProcessInstanceResultEnum.isEndResult(parentTaskExt.getResult());
|
||||
// 2.2 如果 allChildrenTaskFinish 已经被赋值为 false,则不会再赋值为 true,因为整个链路没有完成
|
||||
if (allChildrenTaskFinish) {
|
||||
allChildrenTaskFinish = currentTaskFinish;
|
||||
}
|
||||
// 2.3 任务已完成则不处理
|
||||
if (currentTaskFinish) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 3 处理非完成状态的任务
|
||||
// 3.1 判断当前任务的父任务是否还有子任务
|
||||
Long childrenTaskCount = getChildrenTaskCount(parentTaskExt.getTaskId());
|
||||
if (childrenTaskCount > 0) {
|
||||
continue;
|
||||
}
|
||||
// 3.2 没有子任务,判断当前任务状态是否为 ADD_SIGN_BEFORE 待前加签任务完成
|
||||
if (BpmProcessInstanceResultEnum.SIGN_BEFORE.getResult().equals(parentTaskExt.getResult())) {
|
||||
// 3.3 需要修改该任务状态为处理中
|
||||
taskService.resolveTask(parentTaskExt.getTaskId());
|
||||
parentTaskExt.setResult(BpmProcessInstanceResultEnum.PROCESS.getResult());
|
||||
taskExtMapper.updateByTaskId(parentTaskExt);
|
||||
}
|
||||
// 3.4 清空 scopeType 字段,用于任务没有子任务时使用该方法,方便任务可以再次被不同的方式加签
|
||||
parentTask = validateTaskExist(parentTaskExt.getTaskId());
|
||||
clearTaskScopeTypeAndSave(parentTask);
|
||||
}
|
||||
|
||||
// 4. 完成最后的顶级祖先任务
|
||||
if (allChildrenTaskFinish) {
|
||||
taskService.complete(parentTask.getId());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 清空 scopeType 字段,用于任务没有子任务时使用该方法,方便任务可以再次被不同的方式加签
|
||||
*
|
||||
* @param task 需要被清空的任务
|
||||
*/
|
||||
private void clearTaskScopeTypeAndSave(Task task) {
|
||||
TaskEntityImpl taskImpl = (TaskEntityImpl) task;
|
||||
taskImpl.setScopeType(null);
|
||||
taskService.saveTask(task);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取子任务个数
|
||||
*
|
||||
* @param parentTaskId 父任务 ID
|
||||
* @return 剩余子任务个数
|
||||
*/
|
||||
private Long getChildrenTaskCount(String parentTaskId) {
|
||||
String tableName = managementService.getTableName(TaskEntity.class);
|
||||
String sql = "SELECT COUNT(1) from " + tableName + " WHERE PARENT_TASK_ID_=#{parentTaskId}";
|
||||
return taskService.createNativeTaskQuery().sql(sql).parameter("parentTaskId", parentTaskId).count();
|
||||
}
|
||||
|
||||
/**
|
||||
* 审批被委派的任务
|
||||
*
|
||||
* @param reqVO 前端请求参数,包含当前任务ID,审批意见等
|
||||
* @param task 当前被审批的任务
|
||||
*/
|
||||
private void approveDelegateTask(BpmTaskApproveReqVO reqVO, Task task) {
|
||||
// 1. 添加审批意见
|
||||
AdminUserRespDTO currentUser = adminUserApi.getUser(WebFrameworkUtils.getLoginUserId()).getCheckedData();
|
||||
AdminUserRespDTO sourceApproveUser = adminUserApi.getUser(NumberUtils.parseLong(task.getOwner())).getCheckedData();
|
||||
Assert.notNull(sourceApproveUser, "委派任务找不到原审批人,需要检查数据");
|
||||
String comment = StrUtil.format("[{}]完成委派任务,任务重新回到[{}]手中,审批意见为:{}", currentUser.getNickname(),
|
||||
sourceApproveUser.getNickname(), reqVO.getReason());
|
||||
taskService.addComment(reqVO.getId(), task.getProcessInstanceId(),
|
||||
BpmCommentTypeEnum.DELEGATE.getType().toString(), comment);
|
||||
|
||||
// 2.1 调用 resolveTask 完成任务。
|
||||
// 底层调用 TaskHelper.changeTaskAssignee(task, task.getOwner()):将 owner 设置为 assignee
|
||||
taskService.resolveTask(task.getId());
|
||||
// 2.2 更新任务拓展表为【处理中】
|
||||
taskExtMapper.updateByTaskId(
|
||||
new BpmTaskExtDO().setTaskId(task.getId()).setResult(BpmProcessInstanceResultEnum.PROCESS.getResult())
|
||||
.setReason(reqVO.getReason()));
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void rejectTask(Long userId, @Valid BpmTaskRejectReqVO reqVO) {
|
||||
Task task = checkTask(userId, reqVO.getId());
|
||||
Task task = validateTask(userId, reqVO.getId());
|
||||
// 校验流程实例存在
|
||||
ProcessInstance instance = processInstanceService.getProcessInstance(task.getProcessInstanceId());
|
||||
if (instance == null) {
|
||||
|
|
@ -207,14 +443,14 @@ public class BpmTaskServiceImpl implements BpmTaskService {
|
|||
|
||||
// 更新任务拓展表为不通过
|
||||
taskExtMapper.updateByTaskId(
|
||||
new BpmTaskExtDO().setTaskId(task.getId()).setResult(BpmProcessInstanceResultEnum.REJECT.getResult())
|
||||
.setEndTime(LocalDateTime.now()).setReason(reqVO.getReason()));
|
||||
new BpmTaskExtDO().setTaskId(task.getId()).setResult(BpmProcessInstanceResultEnum.REJECT.getResult())
|
||||
.setEndTime(LocalDateTime.now()).setReason(reqVO.getReason()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateTaskAssignee(Long userId, BpmTaskUpdateAssigneeReqVO reqVO) {
|
||||
// 校验任务存在
|
||||
Task task = checkTask(userId, reqVO.getId());
|
||||
Task task = validateTask(userId, reqVO.getId());
|
||||
// 更新负责人
|
||||
updateTaskAssignee(task.getId(), reqVO.getAssigneeUserId());
|
||||
}
|
||||
|
|
@ -230,21 +466,22 @@ public class BpmTaskServiceImpl implements BpmTaskService {
|
|||
* @param userId 用户 id
|
||||
* @param taskId task id
|
||||
*/
|
||||
private Task checkTask(Long userId, String taskId) {
|
||||
Task task = getTask(taskId);
|
||||
if (task == null) {
|
||||
throw exception(TASK_COMPLETE_FAIL_NOT_EXISTS);
|
||||
}
|
||||
private Task validateTask(Long userId, String taskId) {
|
||||
Task task = validateTaskExist(taskId);
|
||||
if (!Objects.equals(userId, NumberUtils.parseLong(task.getAssignee()))) {
|
||||
throw exception(TASK_COMPLETE_FAIL_ASSIGN_NOT_SELF);
|
||||
throw exception(TASK_OPERATE_FAIL_ASSIGN_NOT_SELF);
|
||||
}
|
||||
return task;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void createTaskExt(Task task) {
|
||||
BpmTaskExtDO taskExtDO =
|
||||
BpmTaskConvert.INSTANCE.convert2TaskExt(task).setResult(BpmProcessInstanceResultEnum.PROCESS.getResult());
|
||||
BpmTaskExtDO taskExtDO = BpmTaskConvert.INSTANCE.convert2TaskExt(task)
|
||||
.setResult(BpmProcessInstanceResultEnum.PROCESS.getResult());
|
||||
// 向后加签生成的任务,状态不能为进行中,需要等前面父任务完成
|
||||
if (BpmTaskAddSignTypeEnum.AFTER_CHILDREN_TASK.getType().equals(task.getScopeType())) {
|
||||
taskExtDO.setResult(BpmProcessInstanceResultEnum.WAIT_BEFORE_TASK.getResult());
|
||||
}
|
||||
taskExtMapper.insert(taskExtDO);
|
||||
}
|
||||
|
||||
|
|
@ -292,21 +529,31 @@ public class BpmTaskServiceImpl implements BpmTaskService {
|
|||
@Override
|
||||
public void updateTaskExtAssign(Task task) {
|
||||
BpmTaskExtDO taskExtDO =
|
||||
new BpmTaskExtDO().setAssigneeUserId(NumberUtils.parseLong(task.getAssignee())).setTaskId(task.getId());
|
||||
new BpmTaskExtDO().setAssigneeUserId(NumberUtils.parseLong(task.getAssignee())).setTaskId(task.getId());
|
||||
taskExtMapper.updateByTaskId(taskExtDO);
|
||||
// 发送通知。在事务提交时,批量执行操作,所以直接查询会无法查询到 ProcessInstance,所以这里是通过监听事务的提交来实现。
|
||||
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
|
||||
@Override
|
||||
public void afterCommit() {
|
||||
ProcessInstance processInstance =
|
||||
processInstanceService.getProcessInstance(task.getProcessInstanceId());
|
||||
AdminUserRespDTO startUser = adminUserApi.getUser(Long.valueOf(processInstance.getStartUserId())).getCheckedData();
|
||||
messageService.sendMessageWhenTaskAssigned(
|
||||
BpmTaskConvert.INSTANCE.convert(processInstance, startUser, task));
|
||||
if (StrUtil.isNotEmpty(task.getAssignee())) {
|
||||
ProcessInstance processInstance =
|
||||
processInstanceService.getProcessInstance(task.getProcessInstanceId());
|
||||
AdminUserRespDTO startUser = adminUserApi.getUser(Long.valueOf(processInstance.getStartUserId())).getCheckedData();
|
||||
messageService.sendMessageWhenTaskAssigned(
|
||||
BpmTaskConvert.INSTANCE.convert(processInstance, startUser, task));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private Task validateTaskExist(String id) {
|
||||
Task task = getTask(id);
|
||||
if (task == null) {
|
||||
throw exception(TASK_NOT_EXISTS);
|
||||
}
|
||||
return task;
|
||||
}
|
||||
|
||||
private Task getTask(String id) {
|
||||
return taskService.createTaskQuery().taskId(id).singleResult();
|
||||
}
|
||||
|
|
@ -315,4 +562,409 @@ public class BpmTaskServiceImpl implements BpmTaskService {
|
|||
return historyService.createHistoricTaskInstanceQuery().taskId(id).singleResult();
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<BpmTaskSimpleRespVO> getReturnTaskList(String taskId) {
|
||||
// 1. 校验当前任务 task 存在
|
||||
Task task = validateTaskExist(taskId);
|
||||
// 根据流程定义获取流程模型信息
|
||||
BpmnModel bpmnModel = bpmModelService.getBpmnModelByDefinitionId(task.getProcessDefinitionId());
|
||||
FlowElement source = BpmnModelUtils.getFlowElementById(bpmnModel, task.getTaskDefinitionKey());
|
||||
if (source == null) {
|
||||
throw exception(TASK_NOT_EXISTS);
|
||||
}
|
||||
|
||||
// 2.1 查询该任务的前置任务节点的 key 集合
|
||||
List<UserTask> previousUserList = BpmnModelUtils.getPreviousUserTaskList(source, null, null);
|
||||
if (CollUtil.isEmpty(previousUserList)) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
// 2.2 过滤:只有串行可到达的节点,才可以回退。类似非串行、子流程无法退回
|
||||
previousUserList.removeIf(userTask -> !BpmnModelUtils.isSequentialReachable(source, userTask, null));
|
||||
return BpmTaskConvert.INSTANCE.convertList(previousUserList);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void returnTask(Long userId, BpmTaskReturnReqVO reqVO) {
|
||||
// 1.1 当前任务 task
|
||||
Task task = validateTask(userId, reqVO.getId());
|
||||
if (task.isSuspended()) {
|
||||
throw exception(TASK_IS_PENDING);
|
||||
}
|
||||
// 1.2 校验源头和目标节点的关系,并返回目标元素
|
||||
FlowElement targetElement = validateTargetTaskCanReturn(task.getTaskDefinitionKey(), reqVO.getTargetDefinitionKey(), task.getProcessDefinitionId());
|
||||
|
||||
// 2. 调用 flowable 框架的回退逻辑
|
||||
returnTask0(task, targetElement, reqVO);
|
||||
|
||||
// 3. 更新任务扩展表
|
||||
taskExtMapper.updateByTaskId(new BpmTaskExtDO().setTaskId(task.getId())
|
||||
.setResult(BpmProcessInstanceResultEnum.BACK.getResult())
|
||||
.setEndTime(LocalDateTime.now()).setReason(reqVO.getReason()));
|
||||
}
|
||||
|
||||
/**
|
||||
* 回退流程节点时,校验目标任务节点是否可回退
|
||||
*
|
||||
* @param sourceKey 当前任务节点 Key
|
||||
* @param targetKey 目标任务节点 key
|
||||
* @param processDefinitionId 当前流程定义 ID
|
||||
* @return 目标任务节点元素
|
||||
*/
|
||||
private FlowElement validateTargetTaskCanReturn(String sourceKey, String targetKey, String processDefinitionId) {
|
||||
// 1.1 获取流程模型信息
|
||||
BpmnModel bpmnModel = bpmModelService.getBpmnModelByDefinitionId(processDefinitionId);
|
||||
// 1.3 获取当前任务节点元素
|
||||
FlowElement source = BpmnModelUtils.getFlowElementById(bpmnModel, sourceKey);
|
||||
// 1.3 获取跳转的节点元素
|
||||
FlowElement target = BpmnModelUtils.getFlowElementById(bpmnModel, targetKey);
|
||||
if (target == null) {
|
||||
throw exception(TASK_TARGET_NODE_NOT_EXISTS);
|
||||
}
|
||||
|
||||
// 2.2 只有串行可到达的节点,才可以回退。类似非串行、子流程无法退回
|
||||
if (!BpmnModelUtils.isSequentialReachable(source, target, null)) {
|
||||
throw exception(TASK_RETURN_FAIL_SOURCE_TARGET_ERROR);
|
||||
}
|
||||
return target;
|
||||
}
|
||||
|
||||
/**
|
||||
* 执行回退逻辑
|
||||
*
|
||||
* @param currentTask 当前回退的任务
|
||||
* @param targetElement 需要回退到的目标任务
|
||||
* @param reqVO 前端参数封装
|
||||
*/
|
||||
public void returnTask0(Task currentTask, FlowElement targetElement, BpmTaskReturnReqVO reqVO) {
|
||||
// 1. 获得所有需要回撤的任务 taskDefinitionKey,用于稍后的 moveActivityIdsToSingleActivityId 回撤
|
||||
// 1.1 获取所有正常进行的任务节点 Key
|
||||
List<Task> taskList = taskService.createTaskQuery().processInstanceId(currentTask.getProcessInstanceId()).list();
|
||||
List<String> runTaskKeyList = convertList(taskList, Task::getTaskDefinitionKey);
|
||||
// 1.2 通过 targetElement 的出口连线,计算在 runTaskKeyList 有哪些 key 需要被撤回
|
||||
// 为什么不直接使用 runTaskKeyList 呢?因为可能存在多个审批分支,例如说:A -> B -> C 和 D -> F,而只要 C 撤回到 A,需要排除掉 F
|
||||
List<UserTask> returnUserTaskList = BpmnModelUtils.iteratorFindChildUserTasks(targetElement, runTaskKeyList, null, null);
|
||||
List<String> returnTaskKeyList = convertList(returnUserTaskList, UserTask::getId);
|
||||
|
||||
// 2. 给当前要被回退的 task 数组,设置回退意见
|
||||
taskList.forEach(task -> {
|
||||
// 需要排除掉,不需要设置回退意见的任务
|
||||
if (!returnTaskKeyList.contains(task.getTaskDefinitionKey())) {
|
||||
return;
|
||||
}
|
||||
taskService.addComment(task.getId(), currentTask.getProcessInstanceId(),
|
||||
BpmCommentTypeEnum.BACK.getType().toString(), reqVO.getReason());
|
||||
});
|
||||
|
||||
// 3. 执行驳回
|
||||
runtimeService.createChangeActivityStateBuilder()
|
||||
.processInstanceId(currentTask.getProcessInstanceId())
|
||||
.moveActivityIdsToSingleActivityId(returnTaskKeyList, // 当前要跳转的节点列表( 1 或多)
|
||||
reqVO.getTargetDefinitionKey()) // targetKey 跳转到的节点(1)
|
||||
.changeState();
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void delegateTask(Long userId, BpmTaskDelegateReqVO reqVO) {
|
||||
// 1.1 校验任务
|
||||
Task task = validateTaskCanDelegate(userId, reqVO);
|
||||
// 1.2 校验目标用户存在
|
||||
AdminUserRespDTO delegateUser = adminUserApi.getUser(reqVO.getDelegateUserId()).getCheckedData();
|
||||
if (delegateUser == null) {
|
||||
throw exception(TASK_DELEGATE_FAIL_USER_NOT_EXISTS);
|
||||
}
|
||||
|
||||
// 2. 添加审批意见
|
||||
AdminUserRespDTO currentUser = adminUserApi.getUser(userId).getCheckedData();
|
||||
String comment = StrUtil.format("[{}]将任务委派给[{}],委派理由为:{}", currentUser.getNickname(),
|
||||
delegateUser.getNickname(), reqVO.getReason());
|
||||
String taskId = reqVO.getId();
|
||||
taskService.addComment(taskId, task.getProcessInstanceId(),
|
||||
BpmCommentTypeEnum.DELEGATE.getType().toString(), comment);
|
||||
|
||||
// 3.1 设置任务所有人 (owner) 为原任务的处理人 (assignee)
|
||||
taskService.setOwner(taskId, task.getAssignee());
|
||||
// 3.2 执行委派,将任务委派给 receiveId
|
||||
taskService.delegateTask(taskId, reqVO.getDelegateUserId().toString());
|
||||
// 3.3 更新任务拓展表为【委派】
|
||||
taskExtMapper.updateByTaskId(
|
||||
new BpmTaskExtDO().setTaskId(task.getId()).setResult(BpmProcessInstanceResultEnum.DELEGATE.getResult())
|
||||
.setReason(reqVO.getReason()));
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验任务委派参数
|
||||
*
|
||||
* @param userId 用户编号
|
||||
* @param reqVO 任务编号,接收人ID
|
||||
* @return 当前任务信息
|
||||
*/
|
||||
private Task validateTaskCanDelegate(Long userId, BpmTaskDelegateReqVO reqVO) {
|
||||
// 校验任务
|
||||
Task task = validateTask(userId, reqVO.getId());
|
||||
// 校验当前审批人和被委派人不是同一人
|
||||
if (task.getAssignee().equals(reqVO.getDelegateUserId().toString())) {
|
||||
throw exception(TASK_DELEGATE_FAIL_USER_REPEAT);
|
||||
}
|
||||
return task;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void createSignTask(Long userId, BpmTaskAddSignReqVO reqVO) {
|
||||
// 1. 获取和校验任务
|
||||
TaskEntityImpl taskEntity = validateAddSign(userId, reqVO);
|
||||
List<AdminUserRespDTO> userList = adminUserApi.getUserList(reqVO.getUserIdList()).getCheckedData();
|
||||
if (CollUtil.isEmpty(userList)) {
|
||||
throw exception(TASK_ADD_SIGN_USER_NOT_EXIST);
|
||||
}
|
||||
|
||||
// 2. 处理当前任务
|
||||
// 2.1 开启计数功能,主要用于为了让表 ACT_RU_TASK 中的 SUB_TASK_COUNT_ 字段记录下总共有多少子任务,后续可能有用
|
||||
taskEntity.setCountEnabled(true);
|
||||
if (reqVO.getType().equals(BpmTaskAddSignTypeEnum.BEFORE.getType())) {
|
||||
// 2.2 向前加签,设置 owner,置空 assign。等子任务都完成后,再调用 resolveTask 重新将 owner 设置为 assign
|
||||
// 原因是:不能和向前加签的子任务一起审批,需要等前面的子任务都完成才能审批
|
||||
taskEntity.setOwner(taskEntity.getAssignee());
|
||||
taskEntity.setAssignee(null);
|
||||
// 2.3 更新扩展表状态
|
||||
taskExtMapper.updateByTaskId(
|
||||
new BpmTaskExtDO().setTaskId(taskEntity.getId())
|
||||
.setResult(BpmProcessInstanceResultEnum.SIGN_BEFORE.getResult())
|
||||
.setReason(reqVO.getReason()));
|
||||
}
|
||||
// 2.4 记录加签方式,完成任务时需要用到判断
|
||||
taskEntity.setScopeType(reqVO.getType());
|
||||
// 2.5 保存当前任务修改后的值
|
||||
taskService.saveTask(taskEntity);
|
||||
|
||||
// 3. 创建加签任务
|
||||
createSignTask(convertList(reqVO.getUserIdList(), String::valueOf), taskEntity);
|
||||
|
||||
// 4. 记录加签 comment,拼接结果为: [当前用户]向前加签/向后加签给了[多个用户],理由为:reason
|
||||
AdminUserRespDTO currentUser = adminUserApi.getUser(userId).getCheckedData();
|
||||
String comment = StrUtil.format(BpmCommentTypeEnum.ADD_SIGN.getComment(), currentUser.getNickname(),
|
||||
BpmTaskAddSignTypeEnum.formatDesc(reqVO.getType()), String.join(",", convertList(userList, AdminUserRespDTO::getNickname)), reqVO.getReason());
|
||||
taskService.addComment(reqVO.getId(), taskEntity.getProcessInstanceId(),
|
||||
BpmCommentTypeEnum.ADD_SIGN.getType().toString(), comment);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 校验任务的加签是否一致
|
||||
* <p>
|
||||
* 1. 如果存在“向前加签”的任务,则不能“向后加签”
|
||||
* 2. 如果存在“向后加签”的任务,则不能“向前加签”
|
||||
*
|
||||
* @param userId 当前用户 ID
|
||||
* @param reqVO 请求参数,包含任务 ID 和加签类型
|
||||
* @return 当前任务
|
||||
*/
|
||||
private TaskEntityImpl validateAddSign(Long userId, BpmTaskAddSignReqVO reqVO) {
|
||||
TaskEntityImpl taskEntity = (TaskEntityImpl) validateTask(userId, reqVO.getId());
|
||||
// 向前加签和向后加签不能同时存在
|
||||
if (StrUtil.isNotBlank(taskEntity.getScopeType())
|
||||
&& ObjectUtil.notEqual(BpmTaskAddSignTypeEnum.AFTER_CHILDREN_TASK.getType(), taskEntity.getScopeType())
|
||||
&& ObjectUtil.notEqual(taskEntity.getScopeType(), reqVO.getType())) {
|
||||
throw exception(TASK_ADD_SIGN_TYPE_ERROR,
|
||||
BpmTaskAddSignTypeEnum.formatDesc(taskEntity.getScopeType()), BpmTaskAddSignTypeEnum.formatDesc(reqVO.getType()));
|
||||
}
|
||||
// 同一个 key 的任务,审批人不重复
|
||||
List<Task> taskList = taskService.createTaskQuery().processInstanceId(taskEntity.getProcessInstanceId())
|
||||
.taskDefinitionKey(taskEntity.getTaskDefinitionKey()).list();
|
||||
List<Long> currentAssigneeList = convertList(taskList, task -> NumberUtils.parseLong(task.getAssignee()));
|
||||
// 保留交集在 currentAssigneeList 中
|
||||
currentAssigneeList.retainAll(reqVO.getUserIdList());
|
||||
if (CollUtil.isNotEmpty(currentAssigneeList)) {
|
||||
List<AdminUserRespDTO> userList = adminUserApi.getUserList(currentAssigneeList).getCheckedData();
|
||||
throw exception(TASK_ADD_SIGN_USER_REPEAT, String.join(",", convertList(userList, AdminUserRespDTO::getNickname)));
|
||||
}
|
||||
return taskEntity;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建加签子任务
|
||||
*
|
||||
* @param addSingUserIdList 被加签的用户 ID
|
||||
* @param taskEntity 被加签的任务
|
||||
*/
|
||||
private void createSignTask(List<String> addSingUserIdList, TaskEntityImpl taskEntity) {
|
||||
if (CollUtil.isEmpty(addSingUserIdList)) {
|
||||
return;
|
||||
}
|
||||
// 创建加签人的新任务,全部基于 taskEntity 为父任务来创建
|
||||
for (String addSignId : addSingUserIdList) {
|
||||
if (StrUtil.isBlank(addSignId)) {
|
||||
continue;
|
||||
}
|
||||
createSignTask(taskEntity, addSignId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建加签子任务
|
||||
*
|
||||
* @param parentTask 父任务
|
||||
* @param assignee 子任务的执行人
|
||||
*/
|
||||
private void createSignTask(TaskEntityImpl parentTask, String assignee) {
|
||||
// 1. 生成子任务
|
||||
TaskEntityImpl task = (TaskEntityImpl) taskService.newTask(IdUtil.fastSimpleUUID());
|
||||
task = BpmTaskConvert.INSTANCE.convert(task, parentTask);
|
||||
if (BpmTaskAddSignTypeEnum.BEFORE.getType().equals(parentTask.getScopeType())) {
|
||||
// 2.1 前加签,设置审批人
|
||||
task.setAssignee(assignee);
|
||||
} else {
|
||||
// 2.2.1 设置 owner 不设置 assignee 是因为不能同时审批,需要等父任务完成
|
||||
task.setOwner(assignee);
|
||||
// 2.2.2 设置向后加签任务的 scopeType 为 afterChildrenTask,用于设置任务扩展表的状态
|
||||
task.setScopeType(BpmTaskAddSignTypeEnum.AFTER_CHILDREN_TASK.getType());
|
||||
}
|
||||
// 2. 保存子任务
|
||||
taskService.saveTask(task);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void deleteSignTask(Long userId, BpmTaskSubSignReqVO reqVO) {
|
||||
// 1.1 校验 task 可以被减签
|
||||
Task task = validateSubSign(reqVO.getId());
|
||||
// 1.2 校验取消人存在
|
||||
AdminUserRespDTO cancelUser = null;
|
||||
if (StrUtil.isNotBlank(task.getAssignee())) {
|
||||
cancelUser = adminUserApi.getUser(NumberUtils.parseLong(task.getAssignee())).getCheckedData();
|
||||
}
|
||||
if (cancelUser == null && StrUtil.isNotBlank(task.getOwner())) {
|
||||
cancelUser = adminUserApi.getUser(NumberUtils.parseLong(task.getOwner())).getCheckedData();
|
||||
}
|
||||
Assert.notNull(cancelUser, "任务中没有所有者和审批人,数据错误");
|
||||
|
||||
// 2. 删除任务和对应子任务
|
||||
// 2.1 获取所有需要删除的任务 ID ,包含当前任务和所有子任务
|
||||
List<String> allTaskIdList = getAllChildTaskIds(task.getId());
|
||||
// 2.2 删除任务和所有子任务
|
||||
taskService.deleteTasks(allTaskIdList);
|
||||
// 2.3 修改扩展表状态为取消
|
||||
AdminUserRespDTO user = adminUserApi.getUser(userId).getCheckedData();
|
||||
taskExtMapper.updateBatchByTaskIdList(allTaskIdList, new BpmTaskExtDO().setResult(BpmProcessInstanceResultEnum.CANCEL.getResult())
|
||||
.setReason(StrUtil.format("由于{}操作[减签],任务被取消", user.getNickname())));
|
||||
|
||||
// 3. 记录日志到父任务中。先记录日志是因为,通过 handleParentTask 方法之后,任务可能被完成了,并且不存在了,会报异常,所以先记录
|
||||
String comment = StrUtil.format(BpmCommentTypeEnum.SUB_SIGN.getComment(), user.getNickname(), cancelUser.getNickname());
|
||||
taskService.addComment(task.getParentTaskId(), task.getProcessInstanceId(),
|
||||
BpmCommentTypeEnum.SUB_SIGN.getType().toString(), comment);
|
||||
|
||||
// 4. 处理当前任务的父任务
|
||||
handleParentTask(task);
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验任务是否能被减签
|
||||
*
|
||||
* @param id 任务ID
|
||||
* @return 任务信息
|
||||
*/
|
||||
private Task validateSubSign(String id) {
|
||||
Task task = validateTaskExist(id);
|
||||
|
||||
// 必须有 scopeType
|
||||
String scopeType = task.getScopeType();
|
||||
if (StrUtil.isEmpty(scopeType)) {
|
||||
throw exception(TASK_SUB_SIGN_NO_PARENT);
|
||||
}
|
||||
// 并且值为 向前和向后加签
|
||||
if (!validateSignType(scopeType)) {
|
||||
throw exception(TASK_SUB_SIGN_NO_PARENT);
|
||||
}
|
||||
return task;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断当前类型是否为加签
|
||||
* @param scopeType 任务的 scopeType
|
||||
* @return 当前 scopeType 为加签则返回 true
|
||||
*/
|
||||
private boolean validateSignType(String scopeType){
|
||||
return StrUtil.equalsAny(scopeType,BpmTaskAddSignTypeEnum.BEFORE.getType(),scopeType, BpmTaskAddSignTypeEnum.AFTER.getType());
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取所有要被取消的删除的任务 ID 集合
|
||||
*
|
||||
* @param parentTaskId 父级任务ID
|
||||
* @return 所有任务ID
|
||||
*/
|
||||
public List<String> getAllChildTaskIds(String parentTaskId) {
|
||||
List<String> allChildTaskIds = new ArrayList<>();
|
||||
// 1. 递归获取子级
|
||||
Stack<String> stack = new Stack<>();
|
||||
// 1.1 将根任务ID入栈
|
||||
stack.push(parentTaskId);
|
||||
//控制遍历的次数不超过 Byte.MAX_VALUE,避免脏数据造成死循环
|
||||
int count = 0;
|
||||
// TODO @海:< 的前后空格,要注意哈;
|
||||
while (!stack.isEmpty() && count<Byte.MAX_VALUE) {
|
||||
// 1.2 弹出栈顶任务ID
|
||||
String taskId = stack.pop();
|
||||
// 1.3 将任务ID添加到结果集合中
|
||||
allChildTaskIds.add(taskId);
|
||||
// 1.4 获取该任务的子任务列表
|
||||
// TODO @海:有个更高效的写法;一次性去 in 一层;不然每个节点,都去查询一次 db, 太浪费了;每次 in,最终就是 O(h) 查询,而不是 O(n) 查询;
|
||||
List<String> childrenTaskIdList = getChildrenTaskIdList(taskId);
|
||||
if (CollUtil.isNotEmpty(childrenTaskIdList)) {
|
||||
for (String childTaskId : childrenTaskIdList) {
|
||||
// 1.5 将子任务ID入栈,以便后续处理
|
||||
stack.push(childTaskId);
|
||||
}
|
||||
}
|
||||
count++;
|
||||
}
|
||||
return allChildTaskIds;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取指定父级任务的所有子任务 ID 集合
|
||||
*
|
||||
* @param parentTaskId 父任务 ID
|
||||
* @return 所有子任务的 ID 集合
|
||||
*/
|
||||
private List<String> getChildrenTaskIdList(String parentTaskId) {
|
||||
return convertList(getChildrenTaskList0(parentTaskId), Task::getId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取指定父级任务的所有子任务 ID 集合
|
||||
*
|
||||
* @param parentTaskId 父任务 ID
|
||||
* @return 所有子任务的 ID 集合
|
||||
*/
|
||||
private List<Task> getChildrenTaskList0(String parentTaskId) {
|
||||
String tableName = managementService.getTableName(TaskEntity.class);
|
||||
// taskService.createTaskQuery() 没有 parentId 参数,所以写 sql 查询
|
||||
String sql = "select ID_,OWNER_,ASSIGNEE_ from " + tableName + " where PARENT_TASK_ID_=#{parentTaskId}";
|
||||
return taskService.createNativeTaskQuery().sql(sql).parameter("parentTaskId", parentTaskId).list();
|
||||
}
|
||||
|
||||
|
||||
@Override
|
||||
public List<BpmTaskSubSignRespVO> getChildrenTaskList(String parentId) {
|
||||
// 1. 只查询进行中的任务 后加签的任务,可能不存在 assignee,所以还需要查询 owner
|
||||
List<Task> taskList = getChildrenTaskList0(parentId);
|
||||
if (CollUtil.isEmpty(taskList)) {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
List<String> childrenTaskIdList = convertList(taskList, Task::getId);
|
||||
|
||||
// 2.1 将 owner 和 assignee 统一到一个集合中
|
||||
List<Long> userIds = convertListByFlatMap(taskList, control ->
|
||||
Stream.of(NumberUtils.parseLong(control.getAssignee()), NumberUtils.parseLong(control.getOwner()))
|
||||
.filter(Objects::nonNull));
|
||||
// 2.2 组装数据
|
||||
Map<Long, AdminUserRespDTO> userMap = adminUserApi.getUserMap(userIds);
|
||||
List<BpmTaskExtDO> taskExtList = taskExtMapper.selectProcessListByTaskIds(childrenTaskIdList);
|
||||
Map<String, Task> idTaskMap = convertMap(taskList, TaskInfo::getId);
|
||||
return BpmTaskConvert.INSTANCE.convertList(taskExtList, userMap, idTaskMap);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -24,8 +24,8 @@
|
|||
<module>yudao-module-product-biz</module>
|
||||
<module>yudao-module-trade-api</module>
|
||||
<module>yudao-module-trade-biz</module>
|
||||
<!-- <module>yudao-module-statistics-api</module>-->
|
||||
<!-- <module>yudao-module-statistics-biz</module>-->
|
||||
<module>yudao-module-statistics-api</module>
|
||||
<module>yudao-module-statistics-biz</module>
|
||||
</modules>
|
||||
|
||||
</project>
|
||||
|
|
|
|||
|
|
@ -1,133 +0,0 @@
|
|||
package cn.iocoder.yudao.module.product.service.brand;
|
||||
|
||||
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
|
||||
import cn.iocoder.yudao.framework.common.pojo.PageResult;
|
||||
import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest;
|
||||
import cn.iocoder.yudao.module.product.controller.admin.brand.vo.ProductBrandCreateReqVO;
|
||||
import cn.iocoder.yudao.module.product.controller.admin.brand.vo.ProductBrandPageReqVO;
|
||||
import cn.iocoder.yudao.module.product.controller.admin.brand.vo.ProductBrandUpdateReqVO;
|
||||
import cn.iocoder.yudao.module.product.dal.dataobject.brand.ProductBrandDO;
|
||||
import cn.iocoder.yudao.module.product.dal.mysql.brand.ProductBrandMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.context.annotation.Import;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildTime;
|
||||
import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomLongId;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomPojo;
|
||||
import static cn.iocoder.yudao.module.product.enums.ErrorCodeConstants.BRAND_NOT_EXISTS;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* {@link ProductBrandServiceImpl} 的单元测试类
|
||||
*
|
||||
* @author 芋道源码
|
||||
*/
|
||||
@Import(ProductBrandServiceImpl.class)
|
||||
public class ProductBrandServiceImplTest extends BaseDbUnitTest {
|
||||
|
||||
@Resource
|
||||
private ProductBrandServiceImpl brandService;
|
||||
|
||||
@Resource
|
||||
private ProductBrandMapper brandMapper;
|
||||
|
||||
@Test
|
||||
public void testCreateBrand_success() {
|
||||
// 准备参数
|
||||
ProductBrandCreateReqVO reqVO = randomPojo(ProductBrandCreateReqVO.class);
|
||||
|
||||
// 调用
|
||||
Long brandId = brandService.createBrand(reqVO);
|
||||
// 断言
|
||||
assertNotNull(brandId);
|
||||
// 校验记录的属性是否正确
|
||||
ProductBrandDO brand = brandMapper.selectById(brandId);
|
||||
assertPojoEquals(reqVO, brand);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUpdateBrand_success() {
|
||||
// mock 数据
|
||||
ProductBrandDO dbBrand = randomPojo(ProductBrandDO.class);
|
||||
brandMapper.insert(dbBrand);// @Sql: 先插入出一条存在的数据
|
||||
// 准备参数
|
||||
ProductBrandUpdateReqVO reqVO = randomPojo(ProductBrandUpdateReqVO.class, o -> {
|
||||
o.setId(dbBrand.getId()); // 设置更新的 ID
|
||||
});
|
||||
|
||||
// 调用
|
||||
brandService.updateBrand(reqVO);
|
||||
// 校验是否更新正确
|
||||
ProductBrandDO brand = brandMapper.selectById(reqVO.getId()); // 获取最新的
|
||||
assertPojoEquals(reqVO, brand);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUpdateBrand_notExists() {
|
||||
// 准备参数
|
||||
ProductBrandUpdateReqVO reqVO = randomPojo(ProductBrandUpdateReqVO.class);
|
||||
|
||||
// 调用, 并断言异常
|
||||
assertServiceException(() -> brandService.updateBrand(reqVO), BRAND_NOT_EXISTS);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteBrand_success() {
|
||||
// mock 数据
|
||||
ProductBrandDO dbBrand = randomPojo(ProductBrandDO.class);
|
||||
brandMapper.insert(dbBrand);// @Sql: 先插入出一条存在的数据
|
||||
// 准备参数
|
||||
Long id = dbBrand.getId();
|
||||
|
||||
// 调用
|
||||
brandService.deleteBrand(id);
|
||||
// 校验数据不存在了
|
||||
assertNull(brandMapper.selectById(id));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteBrand_notExists() {
|
||||
// 准备参数
|
||||
Long id = randomLongId();
|
||||
|
||||
// 调用, 并断言异常
|
||||
assertServiceException(() -> brandService.deleteBrand(id), BRAND_NOT_EXISTS);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetBrandPage() {
|
||||
// mock 数据
|
||||
ProductBrandDO dbBrand = randomPojo(ProductBrandDO.class, o -> { // 等会查询到
|
||||
o.setName("芋道源码");
|
||||
o.setStatus(CommonStatusEnum.ENABLE.getStatus());
|
||||
o.setCreateTime(buildTime(2022, 2, 1));
|
||||
});
|
||||
brandMapper.insert(dbBrand);
|
||||
// 测试 name 不匹配
|
||||
brandMapper.insert(cloneIgnoreId(dbBrand, o -> o.setName("源码")));
|
||||
// 测试 status 不匹配
|
||||
brandMapper.insert(cloneIgnoreId(dbBrand, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus())));
|
||||
// 测试 createTime 不匹配
|
||||
brandMapper.insert(cloneIgnoreId(dbBrand, o -> o.setCreateTime(buildTime(2022, 3, 1))));
|
||||
// 准备参数
|
||||
ProductBrandPageReqVO reqVO = new ProductBrandPageReqVO();
|
||||
reqVO.setName("芋道");
|
||||
reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus());
|
||||
reqVO.setCreateTime((new LocalDateTime[]{buildTime(2022, 1, 1), buildTime(2022, 2, 25)}));
|
||||
|
||||
// 调用
|
||||
PageResult<ProductBrandDO> pageResult = brandService.getBrandPage(reqVO);
|
||||
// 断言
|
||||
assertEquals(1, pageResult.getTotal());
|
||||
assertEquals(1, pageResult.getList().size());
|
||||
assertPojoEquals(dbBrand, pageResult.getList().get(0));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -1,161 +0,0 @@
|
|||
package cn.iocoder.yudao.module.product.service.category;
|
||||
|
||||
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
|
||||
import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest;
|
||||
import cn.iocoder.yudao.module.product.controller.admin.category.vo.ProductCategoryCreateReqVO;
|
||||
import cn.iocoder.yudao.module.product.controller.admin.category.vo.ProductCategoryListReqVO;
|
||||
import cn.iocoder.yudao.module.product.controller.admin.category.vo.ProductCategoryUpdateReqVO;
|
||||
import cn.iocoder.yudao.module.product.dal.dataobject.category.ProductCategoryDO;
|
||||
import cn.iocoder.yudao.module.product.dal.mysql.category.ProductCategoryMapper;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.context.annotation.Import;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.List;
|
||||
|
||||
import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomLongId;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomPojo;
|
||||
import static cn.iocoder.yudao.module.product.dal.dataobject.category.ProductCategoryDO.PARENT_ID_NULL;
|
||||
import static cn.iocoder.yudao.module.product.enums.ErrorCodeConstants.CATEGORY_NOT_EXISTS;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* {@link ProductCategoryServiceImpl} 的单元测试类
|
||||
*
|
||||
* @author 芋道源码
|
||||
*/
|
||||
@Import(ProductCategoryServiceImpl.class)
|
||||
public class ProductCategoryServiceImplTest extends BaseDbUnitTest {
|
||||
|
||||
@Resource
|
||||
private ProductCategoryServiceImpl productCategoryService;
|
||||
|
||||
@Resource
|
||||
private ProductCategoryMapper productCategoryMapper;
|
||||
|
||||
@Test
|
||||
public void testCreateCategory_success() {
|
||||
// 准备参数
|
||||
ProductCategoryCreateReqVO reqVO = randomPojo(ProductCategoryCreateReqVO.class);
|
||||
|
||||
// mock 父类
|
||||
ProductCategoryDO parentProductCategory = randomPojo(ProductCategoryDO.class, o -> {
|
||||
reqVO.setParentId(o.getId());
|
||||
o.setParentId(PARENT_ID_NULL);
|
||||
});
|
||||
productCategoryMapper.insert(parentProductCategory);
|
||||
|
||||
// 调用
|
||||
Long categoryId = productCategoryService.createCategory(reqVO);
|
||||
// 断言
|
||||
assertNotNull(categoryId);
|
||||
// 校验记录的属性是否正确
|
||||
ProductCategoryDO category = productCategoryMapper.selectById(categoryId);
|
||||
assertPojoEquals(reqVO, category);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUpdateCategory_success() {
|
||||
// mock 数据
|
||||
ProductCategoryDO dbCategory = randomPojo(ProductCategoryDO.class);
|
||||
productCategoryMapper.insert(dbCategory);// @Sql: 先插入出一条存在的数据
|
||||
// 准备参数
|
||||
ProductCategoryUpdateReqVO reqVO = randomPojo(ProductCategoryUpdateReqVO.class, o -> {
|
||||
o.setId(dbCategory.getId()); // 设置更新的 ID
|
||||
});
|
||||
// mock 父类
|
||||
ProductCategoryDO parentProductCategory = randomPojo(ProductCategoryDO.class, o -> o.setId(reqVO.getParentId()));
|
||||
productCategoryMapper.insert(parentProductCategory);
|
||||
|
||||
// 调用
|
||||
productCategoryService.updateCategory(reqVO);
|
||||
// 校验是否更新正确
|
||||
ProductCategoryDO category = productCategoryMapper.selectById(reqVO.getId()); // 获取最新的
|
||||
assertPojoEquals(reqVO, category);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUpdateCategory_notExists() {
|
||||
// 准备参数
|
||||
ProductCategoryUpdateReqVO reqVO = randomPojo(ProductCategoryUpdateReqVO.class);
|
||||
|
||||
// 调用, 并断言异常
|
||||
assertServiceException(() -> productCategoryService.updateCategory(reqVO), CATEGORY_NOT_EXISTS);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteCategory_success() {
|
||||
// mock 数据
|
||||
ProductCategoryDO dbCategory = randomPojo(ProductCategoryDO.class);
|
||||
productCategoryMapper.insert(dbCategory);// @Sql: 先插入出一条存在的数据
|
||||
// 准备参数
|
||||
Long id = dbCategory.getId();
|
||||
|
||||
// 调用
|
||||
productCategoryService.deleteCategory(id);
|
||||
// 校验数据不存在了
|
||||
assertNull(productCategoryMapper.selectById(id));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteCategory_notExists() {
|
||||
// 准备参数
|
||||
Long id = randomLongId();
|
||||
|
||||
// 调用, 并断言异常
|
||||
assertServiceException(() -> productCategoryService.deleteCategory(id), CATEGORY_NOT_EXISTS);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetCategoryLevel() {
|
||||
// mock 数据
|
||||
ProductCategoryDO category1 = randomPojo(ProductCategoryDO.class,
|
||||
o -> o.setParentId(PARENT_ID_NULL));
|
||||
productCategoryMapper.insert(category1);
|
||||
ProductCategoryDO category2 = randomPojo(ProductCategoryDO.class,
|
||||
o -> o.setParentId(category1.getId()));
|
||||
productCategoryMapper.insert(category2);
|
||||
ProductCategoryDO category3 = randomPojo(ProductCategoryDO.class,
|
||||
o -> o.setParentId(category2.getId()));
|
||||
productCategoryMapper.insert(category3);
|
||||
|
||||
// 调用,并断言
|
||||
assertEquals(productCategoryService.getCategoryLevel(category1.getId()), 1);
|
||||
assertEquals(productCategoryService.getCategoryLevel(category2.getId()), 2);
|
||||
assertEquals(productCategoryService.getCategoryLevel(category3.getId()), 3);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetCategoryList() {
|
||||
// mock 数据
|
||||
ProductCategoryDO dbCategory = randomPojo(ProductCategoryDO.class, o -> { // 等会查询到
|
||||
o.setName("奥特曼");
|
||||
o.setStatus(CommonStatusEnum.ENABLE.getStatus());
|
||||
o.setParentId(PARENT_ID_NULL);
|
||||
});
|
||||
productCategoryMapper.insert(dbCategory);
|
||||
// 测试 name 不匹配
|
||||
productCategoryMapper.insert(cloneIgnoreId(dbCategory, o -> o.setName("奥特块")));
|
||||
// 测试 status 不匹配
|
||||
productCategoryMapper.insert(cloneIgnoreId(dbCategory, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus())));
|
||||
// 测试 parentId 不匹配
|
||||
productCategoryMapper.insert(cloneIgnoreId(dbCategory, o -> o.setParentId(3333L)));
|
||||
// 准备参数
|
||||
ProductCategoryListReqVO reqVO = new ProductCategoryListReqVO();
|
||||
reqVO.setName("特曼");
|
||||
reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus());
|
||||
reqVO.setParentId(PARENT_ID_NULL);
|
||||
|
||||
// 调用
|
||||
List<ProductCategoryDO> list = productCategoryService.getEnableCategoryList(reqVO);
|
||||
List<ProductCategoryDO> all = productCategoryService.getEnableCategoryList(new ProductCategoryListReqVO());
|
||||
// 断言
|
||||
assertEquals(1, list.size());
|
||||
assertEquals(4, all.size());
|
||||
assertPojoEquals(dbCategory, list.get(0));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -1,193 +0,0 @@
|
|||
package cn.iocoder.yudao.module.product.service.comment;
|
||||
|
||||
import cn.hutool.core.date.DateUtil;
|
||||
import cn.hutool.core.util.RandomUtil;
|
||||
import cn.iocoder.yudao.framework.common.pojo.PageResult;
|
||||
import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest;
|
||||
import cn.iocoder.yudao.module.product.controller.admin.comment.vo.ProductCommentPageReqVO;
|
||||
import cn.iocoder.yudao.module.product.controller.admin.comment.vo.ProductCommentReplyReqVO;
|
||||
import cn.iocoder.yudao.module.product.controller.admin.comment.vo.ProductCommentRespVO;
|
||||
import cn.iocoder.yudao.module.product.controller.admin.comment.vo.ProductCommentUpdateVisibleReqVO;
|
||||
import cn.iocoder.yudao.module.product.controller.app.comment.vo.AppCommentPageReqVO;
|
||||
import cn.iocoder.yudao.module.product.controller.app.comment.vo.AppCommentStatisticsRespVO;
|
||||
import cn.iocoder.yudao.module.product.convert.comment.ProductCommentConvert;
|
||||
import cn.iocoder.yudao.module.product.dal.dataobject.comment.ProductCommentDO;
|
||||
import cn.iocoder.yudao.module.product.dal.mysql.comment.ProductCommentMapper;
|
||||
import cn.iocoder.yudao.module.product.enums.comment.ProductCommentScoresEnum;
|
||||
import cn.iocoder.yudao.module.product.service.sku.ProductSkuService;
|
||||
import cn.iocoder.yudao.module.product.service.spu.ProductSpuService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.context.annotation.Import;
|
||||
import org.springframework.context.annotation.Lazy;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Date;
|
||||
|
||||
import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomPojo;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
|
||||
// TODO 芋艿:单测详细 review 下
|
||||
/**
|
||||
* {@link ProductCommentServiceImpl} 的单元测试类
|
||||
*
|
||||
* @author wangzhs
|
||||
*/
|
||||
@Import(ProductCommentServiceImpl.class)
|
||||
public class ProductCommentServiceImplTest extends BaseDbUnitTest {
|
||||
|
||||
@Resource
|
||||
private ProductCommentMapper productCommentMapper;
|
||||
|
||||
@Resource
|
||||
@Lazy
|
||||
private ProductCommentServiceImpl productCommentService;
|
||||
|
||||
@MockBean
|
||||
private ProductSpuService productSpuService;
|
||||
@MockBean
|
||||
private ProductSkuService productSkuService;
|
||||
|
||||
public String generateNo() {
|
||||
return DateUtil.format(new Date(), "yyyyMMddHHmmss") + RandomUtil.randomInt(100000, 999999);
|
||||
}
|
||||
|
||||
public Long generateId() {
|
||||
return RandomUtil.randomLong(100000, 999999);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateCommentAndGet_success() {
|
||||
// mock 测试
|
||||
ProductCommentDO productComment = randomPojo(ProductCommentDO.class);
|
||||
productCommentMapper.insert(productComment);
|
||||
|
||||
// 断言
|
||||
// 校验记录的属性是否正确
|
||||
ProductCommentDO comment = productCommentMapper.selectById(productComment.getId());
|
||||
assertPojoEquals(productComment, comment);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetCommentPage_success() {
|
||||
// 准备参数
|
||||
ProductCommentDO productComment = randomPojo(ProductCommentDO.class, o -> {
|
||||
o.setUserNickname("王二狗");
|
||||
o.setSpuName("感冒药");
|
||||
o.setScores(ProductCommentScoresEnum.FOUR.getScores());
|
||||
o.setReplyStatus(Boolean.TRUE);
|
||||
o.setVisible(Boolean.TRUE);
|
||||
o.setId(generateId());
|
||||
o.setUserId(generateId());
|
||||
o.setAnonymous(Boolean.TRUE);
|
||||
o.setOrderId(generateId());
|
||||
o.setOrderItemId(generateId());
|
||||
o.setSpuId(generateId());
|
||||
o.setSkuId(generateId());
|
||||
o.setDescriptionScores(ProductCommentScoresEnum.FOUR.getScores());
|
||||
o.setBenefitScores(ProductCommentScoresEnum.FOUR.getScores());
|
||||
o.setContent("真好吃");
|
||||
o.setReplyUserId(generateId());
|
||||
o.setReplyContent("确实");
|
||||
o.setReplyTime(LocalDateTime.now());
|
||||
o.setCreateTime(LocalDateTime.now());
|
||||
o.setUpdateTime(LocalDateTime.now());
|
||||
});
|
||||
productCommentMapper.insert(productComment);
|
||||
|
||||
Long orderId = productComment.getOrderId();
|
||||
Long spuId = productComment.getSpuId();
|
||||
|
||||
// 测试 userNickname 不匹配
|
||||
productCommentMapper.insert(cloneIgnoreId(productComment, o -> o.setUserNickname("王三").setScores(ProductCommentScoresEnum.ONE.getScores())));
|
||||
// 测试 orderId 不匹配
|
||||
productCommentMapper.insert(cloneIgnoreId(productComment, o -> o.setOrderId(generateId())));
|
||||
// 测试 spuId 不匹配
|
||||
productCommentMapper.insert(cloneIgnoreId(productComment, o -> o.setSpuId(generateId())));
|
||||
// 测试 spuName 不匹配
|
||||
productCommentMapper.insert(cloneIgnoreId(productComment, o -> o.setSpuName("感康")));
|
||||
// 测试 scores 不匹配
|
||||
productCommentMapper.insert(cloneIgnoreId(productComment, o -> o.setScores(ProductCommentScoresEnum.ONE.getScores())));
|
||||
// 测试 replied 不匹配
|
||||
productCommentMapper.insert(cloneIgnoreId(productComment, o -> o.setReplyStatus(Boolean.FALSE)));
|
||||
// 测试 visible 不匹配
|
||||
productCommentMapper.insert(cloneIgnoreId(productComment, o -> o.setVisible(Boolean.FALSE)));
|
||||
|
||||
// 调用
|
||||
ProductCommentPageReqVO productCommentPageReqVO = new ProductCommentPageReqVO();
|
||||
productCommentPageReqVO.setUserNickname("王二");
|
||||
productCommentPageReqVO.setOrderId(orderId);
|
||||
productCommentPageReqVO.setSpuId(spuId);
|
||||
productCommentPageReqVO.setSpuName("感冒药");
|
||||
productCommentPageReqVO.setScores(ProductCommentScoresEnum.FOUR.getScores());
|
||||
productCommentPageReqVO.setReplyStatus(Boolean.TRUE);
|
||||
|
||||
PageResult<ProductCommentDO> commentPage = productCommentService.getCommentPage(productCommentPageReqVO);
|
||||
PageResult<ProductCommentRespVO> result = ProductCommentConvert.INSTANCE.convertPage(productCommentMapper.selectPage(productCommentPageReqVO));
|
||||
assertEquals(result.getTotal(), commentPage.getTotal());
|
||||
|
||||
PageResult<ProductCommentDO> all = productCommentService.getCommentPage(new ProductCommentPageReqVO());
|
||||
assertEquals(8, all.getTotal());
|
||||
|
||||
// 测试获取所有商品分页评论数据
|
||||
PageResult<ProductCommentDO> result1 = productCommentService.getCommentPage(new AppCommentPageReqVO(), Boolean.TRUE);
|
||||
assertEquals(7, result1.getTotal());
|
||||
|
||||
// 测试获取所有商品分页中评数据
|
||||
PageResult<ProductCommentDO> result2 = productCommentService.getCommentPage(new AppCommentPageReqVO().setType(AppCommentPageReqVO.MEDIOCRE_COMMENT), Boolean.TRUE);
|
||||
assertEquals(2, result2.getTotal());
|
||||
|
||||
// 测试获取指定 spuId 商品分页中评数据
|
||||
PageResult<ProductCommentDO> result3 = productCommentService.getCommentPage(new AppCommentPageReqVO().setSpuId(spuId).setType(AppCommentPageReqVO.MEDIOCRE_COMMENT), Boolean.TRUE);
|
||||
assertEquals(2, result3.getTotal());
|
||||
|
||||
// 测试分页 tab count
|
||||
AppCommentStatisticsRespVO tabsCount = productCommentService.getCommentStatistics(spuId, Boolean.TRUE);
|
||||
assertEquals(4, tabsCount.getGoodCount());
|
||||
assertEquals(2, tabsCount.getMediocreCount());
|
||||
assertEquals(0, tabsCount.getNegativeCount());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUpdateCommentVisible_success() {
|
||||
// mock 测试
|
||||
ProductCommentDO productComment = randomPojo(ProductCommentDO.class, o -> {
|
||||
o.setVisible(Boolean.TRUE);
|
||||
});
|
||||
productCommentMapper.insert(productComment);
|
||||
|
||||
Long productCommentId = productComment.getId();
|
||||
|
||||
ProductCommentUpdateVisibleReqVO updateReqVO = new ProductCommentUpdateVisibleReqVO();
|
||||
updateReqVO.setId(productCommentId);
|
||||
updateReqVO.setVisible(Boolean.FALSE);
|
||||
productCommentService.updateCommentVisible(updateReqVO);
|
||||
|
||||
ProductCommentDO productCommentDO = productCommentMapper.selectById(productCommentId);
|
||||
assertFalse(productCommentDO.getVisible());
|
||||
}
|
||||
|
||||
|
||||
@Test
|
||||
public void testCommentReply_success() {
|
||||
// mock 测试
|
||||
ProductCommentDO productComment = randomPojo(ProductCommentDO.class);
|
||||
productCommentMapper.insert(productComment);
|
||||
|
||||
Long productCommentId = productComment.getId();
|
||||
|
||||
ProductCommentReplyReqVO replyVO = new ProductCommentReplyReqVO();
|
||||
replyVO.setId(productCommentId);
|
||||
replyVO.setReplyContent("测试");
|
||||
productCommentService.replyComment(replyVO, 1L);
|
||||
|
||||
ProductCommentDO productCommentDO = productCommentMapper.selectById(productCommentId);
|
||||
assertEquals("测试", productCommentDO.getReplyContent());
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -1,205 +0,0 @@
|
|||
package cn.iocoder.yudao.module.product.service.sku;
|
||||
|
||||
import cn.hutool.core.util.RandomUtil;
|
||||
import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest;
|
||||
import cn.iocoder.yudao.framework.test.core.util.AssertUtils;
|
||||
import cn.iocoder.yudao.module.product.api.sku.dto.ProductSkuUpdateStockReqDTO;
|
||||
import cn.iocoder.yudao.module.product.controller.admin.sku.vo.ProductSkuCreateOrUpdateReqVO;
|
||||
import cn.iocoder.yudao.module.product.dal.dataobject.sku.ProductSkuDO;
|
||||
import cn.iocoder.yudao.module.product.dal.mysql.sku.ProductSkuMapper;
|
||||
import cn.iocoder.yudao.module.product.service.property.ProductPropertyService;
|
||||
import cn.iocoder.yudao.module.product.service.property.ProductPropertyValueService;
|
||||
import cn.iocoder.yudao.module.product.service.spu.ProductSpuService;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.context.annotation.Import;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomPojo;
|
||||
import static cn.iocoder.yudao.module.product.enums.ErrorCodeConstants.SKU_NOT_EXISTS;
|
||||
import static cn.iocoder.yudao.module.product.enums.ErrorCodeConstants.SKU_STOCK_NOT_ENOUGH;
|
||||
import static java.util.Collections.singletonList;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
import static org.mockito.ArgumentMatchers.argThat;
|
||||
import static org.mockito.Mockito.verify;
|
||||
|
||||
/**
|
||||
* {@link ProductSkuServiceImpl} 的单元测试
|
||||
*
|
||||
* @author 芋道源码
|
||||
*/
|
||||
@Import(ProductSkuServiceImpl.class)
|
||||
public class ProductSkuServiceTest extends BaseDbUnitTest {
|
||||
|
||||
@Resource
|
||||
private ProductSkuService productSkuService;
|
||||
|
||||
@Resource
|
||||
private ProductSkuMapper productSkuMapper;
|
||||
|
||||
@MockBean
|
||||
private ProductSpuService productSpuService;
|
||||
@MockBean
|
||||
private ProductPropertyService productPropertyService;
|
||||
@MockBean
|
||||
private ProductPropertyValueService productPropertyValueService;
|
||||
|
||||
public Long generateId() {
|
||||
return RandomUtil.randomLong(100000, 999999);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUpdateSkuList() {
|
||||
// mock 数据
|
||||
ProductSkuDO sku01 = randomPojo(ProductSkuDO.class, o -> { // 测试更新
|
||||
o.setSpuId(1L);
|
||||
o.setProperties(singletonList(new ProductSkuDO.Property(
|
||||
10L, "颜色", 20L, "红色")));
|
||||
});
|
||||
productSkuMapper.insert(sku01);
|
||||
ProductSkuDO sku02 = randomPojo(ProductSkuDO.class, o -> { // 测试删除
|
||||
o.setSpuId(1L);
|
||||
o.setProperties(singletonList(new ProductSkuDO.Property(
|
||||
10L, "颜色", 30L, "蓝色")));
|
||||
|
||||
});
|
||||
productSkuMapper.insert(sku02);
|
||||
// 准备参数
|
||||
Long spuId = 1L;
|
||||
String spuName = "测试商品";
|
||||
List<ProductSkuCreateOrUpdateReqVO> skus = Arrays.asList(
|
||||
randomPojo(ProductSkuCreateOrUpdateReqVO.class, o -> { // 测试更新
|
||||
o.setProperties(singletonList(new ProductSkuCreateOrUpdateReqVO.Property(
|
||||
10L, "颜色", 20L, "红色")));
|
||||
}),
|
||||
randomPojo(ProductSkuCreateOrUpdateReqVO.class, o -> { // 测试新增
|
||||
o.setProperties(singletonList(new ProductSkuCreateOrUpdateReqVO.Property(
|
||||
10L, "颜色", 20L, "红色")));
|
||||
})
|
||||
);
|
||||
|
||||
// 调用
|
||||
productSkuService.updateSkuList(spuId, skus);
|
||||
// 断言
|
||||
List<ProductSkuDO> dbSkus = productSkuMapper.selectListBySpuId(spuId);
|
||||
assertEquals(dbSkus.size(), 2);
|
||||
// 断言更新的
|
||||
assertEquals(dbSkus.get(0).getId(), sku01.getId());
|
||||
assertPojoEquals(dbSkus.get(0), skus.get(0), "properties");
|
||||
assertEquals(skus.get(0).getProperties().size(), 1);
|
||||
assertPojoEquals(dbSkus.get(0).getProperties().get(0), skus.get(0).getProperties().get(0));
|
||||
// 断言新增的
|
||||
assertNotEquals(dbSkus.get(1).getId(), sku02.getId());
|
||||
assertPojoEquals(dbSkus.get(1), skus.get(1), "properties");
|
||||
assertEquals(skus.get(1).getProperties().size(), 1);
|
||||
assertPojoEquals(dbSkus.get(1).getProperties().get(0), skus.get(1).getProperties().get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUpdateSkuStock_incrSuccess() {
|
||||
// 准备参数
|
||||
ProductSkuUpdateStockReqDTO updateStockReqDTO = new ProductSkuUpdateStockReqDTO()
|
||||
.setItems(singletonList(new ProductSkuUpdateStockReqDTO.Item().setId(1L).setIncrCount(10)));
|
||||
// mock 数据
|
||||
productSkuMapper.insert(randomPojo(ProductSkuDO.class, o -> {
|
||||
o.setId(1L).setSpuId(10L).setStock(20);
|
||||
o.getProperties().forEach(p -> {
|
||||
// 指定 id 范围 解决 Value too long
|
||||
p.setPropertyId(generateId());
|
||||
p.setValueId(generateId());
|
||||
});
|
||||
}));
|
||||
|
||||
// 调用
|
||||
productSkuService.updateSkuStock(updateStockReqDTO);
|
||||
// 断言
|
||||
ProductSkuDO sku = productSkuMapper.selectById(1L);
|
||||
assertEquals(sku.getStock(), 30);
|
||||
verify(productSpuService).updateSpuStock(argThat(spuStockIncrCounts -> {
|
||||
assertEquals(spuStockIncrCounts.size(), 1);
|
||||
assertEquals(spuStockIncrCounts.get(10L), 10);
|
||||
return true;
|
||||
}));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUpdateSkuStock_decrSuccess() {
|
||||
// 准备参数
|
||||
ProductSkuUpdateStockReqDTO updateStockReqDTO = new ProductSkuUpdateStockReqDTO()
|
||||
.setItems(singletonList(new ProductSkuUpdateStockReqDTO.Item().setId(1L).setIncrCount(-10)));
|
||||
// mock 数据
|
||||
productSkuMapper.insert(randomPojo(ProductSkuDO.class, o -> {
|
||||
o.setId(1L).setSpuId(10L).setStock(20);
|
||||
o.getProperties().forEach(p -> {
|
||||
// 指定 id 范围 解决 Value too long
|
||||
p.setPropertyId(generateId());
|
||||
p.setValueId(generateId());
|
||||
});
|
||||
}));
|
||||
|
||||
// 调用
|
||||
productSkuService.updateSkuStock(updateStockReqDTO);
|
||||
// 断言
|
||||
ProductSkuDO sku = productSkuMapper.selectById(1L);
|
||||
assertEquals(sku.getStock(), 10);
|
||||
verify(productSpuService).updateSpuStock(argThat(spuStockIncrCounts -> {
|
||||
assertEquals(spuStockIncrCounts.size(), 1);
|
||||
assertEquals(spuStockIncrCounts.get(10L), -10);
|
||||
return true;
|
||||
}));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUpdateSkuStock_decrFail() {
|
||||
// 准备参数
|
||||
ProductSkuUpdateStockReqDTO updateStockReqDTO = new ProductSkuUpdateStockReqDTO()
|
||||
.setItems(singletonList(new ProductSkuUpdateStockReqDTO.Item().setId(1L).setIncrCount(-30)));
|
||||
// mock 数据
|
||||
productSkuMapper.insert(randomPojo(ProductSkuDO.class, o -> {
|
||||
o.setId(1L).setSpuId(10L).setStock(20);
|
||||
o.getProperties().forEach(p -> {
|
||||
// 指定 id 范围 解决 Value too long
|
||||
p.setPropertyId(generateId());
|
||||
p.setValueId(generateId());
|
||||
});
|
||||
}));
|
||||
// 调用并断言
|
||||
AssertUtils.assertServiceException(() -> productSkuService.updateSkuStock(updateStockReqDTO),
|
||||
SKU_STOCK_NOT_ENOUGH);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteSku_success() {
|
||||
ProductSkuDO dbSku = randomPojo(ProductSkuDO.class, o -> {
|
||||
o.setId(generateId()).setSpuId(generateId());
|
||||
o.getProperties().forEach(p -> {
|
||||
// 指定 id 范围 解决 Value too long
|
||||
p.setPropertyId(generateId());
|
||||
p.setValueId(generateId());
|
||||
});
|
||||
});
|
||||
// mock 数据
|
||||
productSkuMapper.insert(dbSku);
|
||||
// 准备参数
|
||||
Long id = dbSku.getId();
|
||||
|
||||
// 调用
|
||||
productSkuService.deleteSku(id);
|
||||
// 校验数据不存在了
|
||||
assertNull(productSkuMapper.selectById(id));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteSku_notExists() {
|
||||
// 准备参数
|
||||
Long id = 1L;
|
||||
|
||||
// 调用, 并断言异常
|
||||
assertServiceException(() -> productSkuService.deleteSku(id), SKU_NOT_EXISTS);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,503 +0,0 @@
|
|||
package cn.iocoder.yudao.module.product.service.spu;
|
||||
|
||||
import cn.hutool.core.date.DateUtil;
|
||||
import cn.hutool.core.map.MapUtil;
|
||||
import cn.hutool.core.util.RandomUtil;
|
||||
import cn.iocoder.yudao.framework.common.exception.ServiceException;
|
||||
import cn.iocoder.yudao.framework.common.pojo.PageResult;
|
||||
import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest;
|
||||
import cn.iocoder.yudao.module.product.controller.admin.sku.vo.ProductSkuCreateOrUpdateReqVO;
|
||||
import cn.iocoder.yudao.module.product.controller.admin.spu.vo.ProductSpuCreateReqVO;
|
||||
import cn.iocoder.yudao.module.product.controller.admin.spu.vo.ProductSpuPageReqVO;
|
||||
import cn.iocoder.yudao.module.product.controller.admin.spu.vo.ProductSpuRespVO;
|
||||
import cn.iocoder.yudao.module.product.controller.admin.spu.vo.ProductSpuUpdateReqVO;
|
||||
import cn.iocoder.yudao.module.product.convert.spu.ProductSpuConvert;
|
||||
import cn.iocoder.yudao.module.product.dal.dataobject.spu.ProductSpuDO;
|
||||
import cn.iocoder.yudao.module.product.dal.mysql.spu.ProductSpuMapper;
|
||||
import cn.iocoder.yudao.module.product.enums.spu.ProductSpuStatusEnum;
|
||||
import cn.iocoder.yudao.module.product.service.brand.ProductBrandServiceImpl;
|
||||
import cn.iocoder.yudao.module.product.service.category.ProductCategoryServiceImpl;
|
||||
import cn.iocoder.yudao.module.product.service.property.ProductPropertyService;
|
||||
import cn.iocoder.yudao.module.product.service.property.ProductPropertyValueService;
|
||||
import cn.iocoder.yudao.module.product.service.sku.ProductSkuServiceImpl;
|
||||
import com.google.common.collect.Lists;
|
||||
import org.junit.jupiter.api.Assertions;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.boot.test.mock.mockito.MockBean;
|
||||
import org.springframework.context.annotation.Import;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.math.RoundingMode;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomPojo;
|
||||
import static org.assertj.core.util.Lists.newArrayList;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
// TODO @芋艿:review 下单元测试
|
||||
|
||||
/**
|
||||
* {@link ProductSpuServiceImpl} 的单元测试类
|
||||
*
|
||||
* @author 芋道源码
|
||||
*/
|
||||
@Import(ProductSpuServiceImpl.class)
|
||||
public class ProductSpuServiceImplTest extends BaseDbUnitTest {
|
||||
|
||||
@Resource
|
||||
private ProductSpuServiceImpl productSpuService;
|
||||
|
||||
@Resource
|
||||
private ProductSpuMapper productSpuMapper;
|
||||
|
||||
@MockBean
|
||||
private ProductSkuServiceImpl productSkuService;
|
||||
@MockBean
|
||||
private ProductCategoryServiceImpl categoryService;
|
||||
@MockBean
|
||||
private ProductBrandServiceImpl brandService;
|
||||
@MockBean
|
||||
private ProductPropertyService productPropertyService;
|
||||
@MockBean
|
||||
private ProductPropertyValueService productPropertyValueService;
|
||||
|
||||
public String generateNo() {
|
||||
return DateUtil.format(new Date(), "yyyyMMddHHmmss") + RandomUtil.randomInt(100000, 999999);
|
||||
}
|
||||
|
||||
public Long generateId() {
|
||||
return RandomUtil.randomLong(100000, 999999);
|
||||
}
|
||||
|
||||
public int generaInt(){return RandomUtil.randomInt(1,9999999);}
|
||||
|
||||
// TODO @芋艿:单测后续 review 哈
|
||||
|
||||
@Test
|
||||
public void testCreateSpu_success() {
|
||||
// 准备参数
|
||||
ProductSkuCreateOrUpdateReqVO skuCreateOrUpdateReqVO = randomPojo(ProductSkuCreateOrUpdateReqVO.class,o->{
|
||||
// 限制范围为正整数
|
||||
o.setCostPrice(generaInt());
|
||||
o.setPrice(generaInt());
|
||||
o.setMarketPrice(generaInt());
|
||||
o.setStock(generaInt());
|
||||
o.setWarnStock(10);
|
||||
o.setFirstBrokeragePrice(generaInt());
|
||||
o.setSecondBrokeragePrice(generaInt());
|
||||
// 限制分数为两位数
|
||||
o.setWeight(RandomUtil.randomDouble(10,2, RoundingMode.HALF_UP));
|
||||
o.setVolume(RandomUtil.randomDouble(10,2, RoundingMode.HALF_UP));
|
||||
});
|
||||
ProductSpuCreateReqVO createReqVO = randomPojo(ProductSpuCreateReqVO.class,o->{
|
||||
o.setCategoryId(generateId());
|
||||
o.setBrandId(generateId());
|
||||
o.setUnit(RandomUtil.randomInt(1,20)); // 限制商品单位范围
|
||||
o.setSort(RandomUtil.randomInt(1,100)); // 限制排序范围
|
||||
o.setGiveIntegral(generaInt()); // 限制范围为正整数
|
||||
o.setVirtualSalesCount(generaInt()); // 限制范围为正整数
|
||||
o.setActivityOrders(newArrayList(1,3,2,4,5)); // 活动排序
|
||||
o.setSkus(newArrayList(skuCreateOrUpdateReqVO,skuCreateOrUpdateReqVO,skuCreateOrUpdateReqVO));
|
||||
});
|
||||
when(categoryService.getCategoryLevel(eq(createReqVO.getCategoryId()))).thenReturn(2);
|
||||
Long spu = productSpuService.createSpu(createReqVO);
|
||||
ProductSpuDO productSpuDO = productSpuMapper.selectById(spu);
|
||||
assertPojoEquals(createReqVO, productSpuDO);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUpdateSpu_success() {
|
||||
// 准备参数
|
||||
ProductSpuDO createReqVO = randomPojo(ProductSpuDO.class,o->{
|
||||
o.setCategoryId(generateId());
|
||||
o.setBrandId(generateId());
|
||||
o.setDeliveryTemplateId(generateId());
|
||||
o.setUnit(RandomUtil.randomInt(1,20)); // 限制商品单位范围
|
||||
o.setSort(RandomUtil.randomInt(1,100)); // 限制排序范围
|
||||
o.setGiveIntegral(generaInt()); // 限制范围为正整数
|
||||
o.setVirtualSalesCount(generaInt()); // 限制范围为正整数
|
||||
o.setActivityOrders(newArrayList(1,3,2,4,5)); // 活动排序
|
||||
o.setPrice(generaInt()); // 限制范围为正整数
|
||||
o.setMarketPrice(generaInt()); // 限制范围为正整数
|
||||
o.setCostPrice(generaInt()); // 限制范围为正整数
|
||||
o.setStock(generaInt()); // 限制范围为正整数
|
||||
o.setGiveIntegral(generaInt()); // 限制范围为正整数
|
||||
o.setSalesCount(generaInt()); // 限制范围为正整数
|
||||
o.setBrowseCount(generaInt()); // 限制范围为正整数
|
||||
});
|
||||
productSpuMapper.insert(createReqVO);
|
||||
// 准备参数
|
||||
ProductSkuCreateOrUpdateReqVO skuCreateOrUpdateReqVO = randomPojo(ProductSkuCreateOrUpdateReqVO.class,o->{
|
||||
// 限制范围为正整数
|
||||
o.setCostPrice(generaInt());
|
||||
o.setPrice(generaInt());
|
||||
o.setMarketPrice(generaInt());
|
||||
o.setStock(generaInt());
|
||||
o.setWarnStock(10);
|
||||
o.setFirstBrokeragePrice(generaInt());
|
||||
o.setSecondBrokeragePrice(generaInt());
|
||||
// 限制分数为两位数
|
||||
o.setWeight(RandomUtil.randomDouble(10,2, RoundingMode.HALF_UP));
|
||||
o.setVolume(RandomUtil.randomDouble(10,2, RoundingMode.HALF_UP));
|
||||
});
|
||||
// 准备参数
|
||||
ProductSpuUpdateReqVO reqVO = randomPojo(ProductSpuUpdateReqVO.class, o -> {
|
||||
o.setId(createReqVO.getId()); // 设置更新的 ID
|
||||
o.setCategoryId(generateId());
|
||||
o.setBrandId(generateId());
|
||||
o.setUnit(RandomUtil.randomInt(1,20)); // 限制商品单位范围
|
||||
o.setSort(RandomUtil.randomInt(1,100)); // 限制排序范围
|
||||
o.setGiveIntegral(generaInt()); // 限制范围为正整数
|
||||
o.setVirtualSalesCount(generaInt()); // 限制范围为正整数
|
||||
o.setActivityOrders(newArrayList(1,3,2,4,5)); // 活动排序
|
||||
o.setGiveIntegral(generaInt()); // 限制范围为正整数
|
||||
o.setSalesCount(generaInt()); // 限制范围为正整数
|
||||
o.setBrowseCount(generaInt()); // 限制范围为正整数
|
||||
o.setStatus(0);
|
||||
o.setSkus(newArrayList(skuCreateOrUpdateReqVO,skuCreateOrUpdateReqVO,skuCreateOrUpdateReqVO));
|
||||
});
|
||||
when(categoryService.getCategoryLevel(eq(reqVO.getCategoryId()))).thenReturn(2);
|
||||
// 调用
|
||||
productSpuService.updateSpu(reqVO);
|
||||
// 校验是否更新正确
|
||||
ProductSpuDO spu = productSpuMapper.selectById(reqVO.getId()); // 获取最新的
|
||||
assertPojoEquals(reqVO, spu);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testValidateSpuExists_exception() {
|
||||
ProductSpuUpdateReqVO reqVO = randomPojo(ProductSpuUpdateReqVO.class);
|
||||
// 调用
|
||||
Assertions.assertThrows(ServiceException.class, () -> productSpuService.updateSpu(reqVO));
|
||||
}
|
||||
|
||||
@Test
|
||||
void deleteSpu() {
|
||||
// 准备参数
|
||||
ProductSpuDO createReqVO = randomPojo(ProductSpuDO.class,o->{
|
||||
o.setCategoryId(generateId());
|
||||
o.setBrandId(generateId());
|
||||
o.setDeliveryTemplateId(generateId());
|
||||
o.setUnit(RandomUtil.randomInt(1,20)); // 限制商品单位范围
|
||||
o.setSort(RandomUtil.randomInt(1,100)); // 限制排序范围
|
||||
o.setGiveIntegral(generaInt()); // 限制范围为正整数
|
||||
o.setVirtualSalesCount(generaInt()); // 限制范围为正整数
|
||||
o.setActivityOrders(newArrayList(1,3,2,4,5)); // 活动排序
|
||||
o.setPrice(generaInt()); // 限制范围为正整数
|
||||
o.setMarketPrice(generaInt()); // 限制范围为正整数
|
||||
o.setCostPrice(generaInt()); // 限制范围为正整数
|
||||
o.setStock(generaInt()); // 限制范围为正整数
|
||||
o.setGiveIntegral(generaInt()); // 限制范围为正整数
|
||||
o.setSalesCount(generaInt()); // 限制范围为正整数
|
||||
o.setBrowseCount(generaInt()); // 限制范围为正整数
|
||||
o.setStatus(-1); // 加入回收站才可删除
|
||||
});
|
||||
productSpuMapper.insert(createReqVO);
|
||||
|
||||
// 调用
|
||||
productSpuService.deleteSpu(createReqVO.getId());
|
||||
|
||||
Assertions.assertNull(productSpuMapper.selectById(createReqVO.getId()));
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSpu() {
|
||||
// 准备参数
|
||||
ProductSpuDO createReqVO = randomPojo(ProductSpuDO.class,o->{
|
||||
o.setCategoryId(generateId());
|
||||
o.setBrandId(generateId());
|
||||
o.setDeliveryTemplateId(generateId());
|
||||
o.setUnit(RandomUtil.randomInt(1,20)); // 限制商品单位范围
|
||||
o.setSort(RandomUtil.randomInt(1,100)); // 限制排序范围
|
||||
o.setGiveIntegral(generaInt()); // 限制范围为正整数
|
||||
o.setVirtualSalesCount(generaInt()); // 限制范围为正整数
|
||||
o.setActivityOrders(newArrayList(1,3,2,4,5)); // 活动排序
|
||||
o.setPrice(generaInt()); // 限制范围为正整数
|
||||
o.setMarketPrice(generaInt()); // 限制范围为正整数
|
||||
o.setCostPrice(generaInt()); // 限制范围为正整数
|
||||
o.setStock(generaInt()); // 限制范围为正整数
|
||||
o.setGiveIntegral(generaInt()); // 限制范围为正整数
|
||||
o.setSalesCount(generaInt()); // 限制范围为正整数
|
||||
o.setBrowseCount(generaInt()); // 限制范围为正整数
|
||||
});
|
||||
productSpuMapper.insert(createReqVO);
|
||||
|
||||
ProductSpuDO spu = productSpuService.getSpu(createReqVO.getId());
|
||||
assertPojoEquals(createReqVO, spu);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSpuList() {
|
||||
// 准备参数
|
||||
ArrayList<ProductSpuDO> createReqVOs = Lists.newArrayList(randomPojo(ProductSpuDO.class,o->{
|
||||
o.setCategoryId(generateId());
|
||||
o.setBrandId(generateId());
|
||||
o.setDeliveryTemplateId(generateId());
|
||||
o.setUnit(RandomUtil.randomInt(1,20)); // 限制商品单位范围
|
||||
o.setSort(RandomUtil.randomInt(1,100)); // 限制排序范围
|
||||
o.setGiveIntegral(generaInt()); // 限制范围为正整数
|
||||
o.setVirtualSalesCount(generaInt()); // 限制范围为正整数
|
||||
o.setActivityOrders(newArrayList(1,3,2,4,5)); // 活动排序
|
||||
o.setPrice(generaInt()); // 限制范围为正整数
|
||||
o.setMarketPrice(generaInt()); // 限制范围为正整数
|
||||
o.setCostPrice(generaInt()); // 限制范围为正整数
|
||||
o.setStock(generaInt()); // 限制范围为正整数
|
||||
o.setGiveIntegral(generaInt()); // 限制范围为正整数
|
||||
o.setSalesCount(generaInt()); // 限制范围为正整数
|
||||
o.setBrowseCount(generaInt()); // 限制范围为正整数
|
||||
}), randomPojo(ProductSpuDO.class,o->{
|
||||
o.setCategoryId(generateId());
|
||||
o.setBrandId(generateId());
|
||||
o.setDeliveryTemplateId(generateId());
|
||||
o.setUnit(RandomUtil.randomInt(1,20)); // 限制商品单位范围
|
||||
o.setSort(RandomUtil.randomInt(1,100)); // 限制排序范围
|
||||
o.setGiveIntegral(generaInt()); // 限制范围为正整数
|
||||
o.setVirtualSalesCount(generaInt()); // 限制范围为正整数
|
||||
o.setActivityOrders(newArrayList(1,3,2,4,5)); // 活动排序
|
||||
o.setPrice(generaInt()); // 限制范围为正整数
|
||||
o.setMarketPrice(generaInt()); // 限制范围为正整数
|
||||
o.setCostPrice(generaInt()); // 限制范围为正整数
|
||||
o.setStock(generaInt()); // 限制范围为正整数
|
||||
o.setGiveIntegral(generaInt()); // 限制范围为正整数
|
||||
o.setSalesCount(generaInt()); // 限制范围为正整数
|
||||
o.setBrowseCount(generaInt()); // 限制范围为正整数
|
||||
}));
|
||||
productSpuMapper.insertBatch(createReqVOs);
|
||||
|
||||
// 调用
|
||||
List<ProductSpuDO> spuList = productSpuService.getSpuList(createReqVOs.stream().map(ProductSpuDO::getId).collect(Collectors.toList()));
|
||||
Assertions.assertIterableEquals(createReqVOs, spuList);
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSpuPage_alarmStock_empty() {
|
||||
// 准备参数
|
||||
ArrayList<ProductSpuDO> createReqVOs = Lists.newArrayList(randomPojo(ProductSpuDO.class,o->{
|
||||
o.setCategoryId(generateId());
|
||||
o.setBrandId(generateId());
|
||||
o.setDeliveryTemplateId(generateId());
|
||||
o.setUnit(RandomUtil.randomInt(1,20)); // 限制商品单位范围
|
||||
o.setSort(RandomUtil.randomInt(1,100)); // 限制排序范围
|
||||
o.setGiveIntegral(generaInt()); // 限制范围为正整数
|
||||
o.setVirtualSalesCount(generaInt()); // 限制范围为正整数
|
||||
o.setActivityOrders(newArrayList(1,3,2,4,5)); // 活动排序
|
||||
o.setPrice(generaInt()); // 限制范围为正整数
|
||||
o.setMarketPrice(generaInt()); // 限制范围为正整数
|
||||
o.setCostPrice(generaInt()); // 限制范围为正整数
|
||||
o.setStock(11); // 限制范围为正整数
|
||||
o.setGiveIntegral(generaInt()); // 限制范围为正整数
|
||||
o.setSalesCount(generaInt()); // 限制范围为正整数
|
||||
o.setBrowseCount(generaInt()); // 限制范围为正整数
|
||||
}), randomPojo(ProductSpuDO.class,o->{
|
||||
o.setCategoryId(generateId());
|
||||
o.setBrandId(generateId());
|
||||
o.setDeliveryTemplateId(generateId());
|
||||
o.setUnit(RandomUtil.randomInt(1,20)); // 限制商品单位范围
|
||||
o.setSort(RandomUtil.randomInt(1,100)); // 限制排序范围
|
||||
o.setGiveIntegral(generaInt()); // 限制范围为正整数
|
||||
o.setVirtualSalesCount(generaInt()); // 限制范围为正整数
|
||||
o.setActivityOrders(newArrayList(1,3,2,4,5)); // 活动排序
|
||||
o.setPrice(generaInt()); // 限制范围为正整数
|
||||
o.setMarketPrice(generaInt()); // 限制范围为正整数
|
||||
o.setCostPrice(generaInt()); // 限制范围为正整数
|
||||
o.setStock(11); // 限制范围为正整数
|
||||
o.setGiveIntegral(generaInt()); // 限制范围为正整数
|
||||
o.setSalesCount(generaInt()); // 限制范围为正整数
|
||||
o.setBrowseCount(generaInt()); // 限制范围为正整数
|
||||
}));
|
||||
productSpuMapper.insertBatch(createReqVOs);
|
||||
// 调用
|
||||
ProductSpuPageReqVO productSpuPageReqVO = new ProductSpuPageReqVO();
|
||||
productSpuPageReqVO.setTabType(ProductSpuPageReqVO.ALERT_STOCK);
|
||||
|
||||
PageResult<ProductSpuDO> spuPage = productSpuService.getSpuPage(productSpuPageReqVO);
|
||||
|
||||
PageResult<Object> result = PageResult.empty();
|
||||
Assertions.assertIterableEquals(result.getList(), spuPage.getList());
|
||||
assertEquals(spuPage.getTotal(), result.getTotal());
|
||||
}
|
||||
|
||||
@Test
|
||||
void getSpuPage_alarmStock() {
|
||||
// 准备参数
|
||||
ArrayList<ProductSpuDO> createReqVOs = Lists.newArrayList(randomPojo(ProductSpuDO.class,o->{
|
||||
o.setCategoryId(generateId());
|
||||
o.setBrandId(generateId());
|
||||
o.setDeliveryTemplateId(generateId());
|
||||
o.setUnit(RandomUtil.randomInt(1,20)); // 限制商品单位范围
|
||||
o.setSort(RandomUtil.randomInt(1,100)); // 限制排序范围
|
||||
o.setGiveIntegral(generaInt()); // 限制范围为正整数
|
||||
o.setVirtualSalesCount(generaInt()); // 限制范围为正整数
|
||||
o.setActivityOrders(newArrayList(1,3,2,4,5)); // 活动排序
|
||||
o.setPrice(generaInt()); // 限制范围为正整数
|
||||
o.setMarketPrice(generaInt()); // 限制范围为正整数
|
||||
o.setCostPrice(generaInt()); // 限制范围为正整数
|
||||
o.setStock(5); // 限制范围为正整数
|
||||
o.setGiveIntegral(generaInt()); // 限制范围为正整数
|
||||
o.setSalesCount(generaInt()); // 限制范围为正整数
|
||||
o.setBrowseCount(generaInt()); // 限制范围为正整数
|
||||
}), randomPojo(ProductSpuDO.class,o->{
|
||||
o.setCategoryId(generateId());
|
||||
o.setBrandId(generateId());
|
||||
o.setDeliveryTemplateId(generateId());
|
||||
o.setUnit(RandomUtil.randomInt(1,20)); // 限制商品单位范围
|
||||
o.setSort(RandomUtil.randomInt(1,100)); // 限制排序范围
|
||||
o.setGiveIntegral(generaInt()); // 限制范围为正整数
|
||||
o.setVirtualSalesCount(generaInt()); // 限制范围为正整数
|
||||
o.setActivityOrders(newArrayList(1,3,2,4,5)); // 活动排序
|
||||
o.setPrice(generaInt()); // 限制范围为正整数
|
||||
o.setMarketPrice(generaInt()); // 限制范围为正整数
|
||||
o.setCostPrice(generaInt()); // 限制范围为正整数
|
||||
o.setStock(9); // 限制范围为正整数
|
||||
o.setGiveIntegral(generaInt()); // 限制范围为正整数
|
||||
o.setSalesCount(generaInt()); // 限制范围为正整数
|
||||
o.setBrowseCount(generaInt()); // 限制范围为正整数
|
||||
}));
|
||||
productSpuMapper.insertBatch(createReqVOs);
|
||||
// 调用
|
||||
ProductSpuPageReqVO productSpuPageReqVO = new ProductSpuPageReqVO();
|
||||
productSpuPageReqVO.setTabType(ProductSpuPageReqVO.ALERT_STOCK);
|
||||
PageResult<ProductSpuDO> spuPage = productSpuService.getSpuPage(productSpuPageReqVO);
|
||||
assertEquals(createReqVOs.size(), spuPage.getTotal());
|
||||
}
|
||||
|
||||
@Test
|
||||
void testGetSpuPage() {
|
||||
// 准备参数
|
||||
ProductSpuDO createReqVO = randomPojo(ProductSpuDO.class,o->{
|
||||
o.setCategoryId(generateId());
|
||||
o.setBrandId(generateId());
|
||||
o.setDeliveryTemplateId(generateId());
|
||||
o.setUnit(RandomUtil.randomInt(1,20)); // 限制商品单位范围
|
||||
o.setSort(RandomUtil.randomInt(1,100)); // 限制排序范围
|
||||
o.setGiveIntegral(generaInt()); // 限制范围为正整数
|
||||
o.setVirtualSalesCount(generaInt()); // 限制范围为正整数
|
||||
o.setActivityOrders(newArrayList(1,3,2,4,5)); // 活动排序
|
||||
o.setPrice(generaInt()); // 限制范围为正整数
|
||||
o.setMarketPrice(generaInt()); // 限制范围为正整数
|
||||
o.setCostPrice(generaInt()); // 限制范围为正整数
|
||||
o.setStock(generaInt()); // 限制范围为正整数
|
||||
o.setGiveIntegral(generaInt()); // 限制范围为正整数
|
||||
o.setSalesCount(generaInt()); // 限制范围为正整数
|
||||
o.setBrowseCount(generaInt()); // 限制范围为正整数
|
||||
});
|
||||
|
||||
// 准备参数
|
||||
productSpuMapper.insert(createReqVO);
|
||||
// 测试 status 不匹配
|
||||
productSpuMapper.insert(cloneIgnoreId(createReqVO, o -> o.setStatus(ProductSpuStatusEnum.DISABLE.getStatus())));
|
||||
productSpuMapper.insert(cloneIgnoreId(createReqVO, o -> o.setStatus(ProductSpuStatusEnum.RECYCLE.getStatus())));
|
||||
// 测试 SpecType 不匹配
|
||||
productSpuMapper.insert(cloneIgnoreId(createReqVO, o -> o.setSpecType(true)));
|
||||
// 测试 BrandId 不匹配
|
||||
productSpuMapper.insert(cloneIgnoreId(createReqVO, o -> o.setBrandId(generateId())));
|
||||
// 测试 CategoryId 不匹配
|
||||
productSpuMapper.insert(cloneIgnoreId(createReqVO, o -> o.setCategoryId(generateId())));
|
||||
|
||||
// 调用
|
||||
ProductSpuPageReqVO productSpuPageReqVO = new ProductSpuPageReqVO();
|
||||
// 查询条件 按需打开
|
||||
//productSpuPageReqVO.setTabType(ProductSpuPageReqVO.ALERT_STOCK);
|
||||
//productSpuPageReqVO.setTabType(ProductSpuPageReqVO.RECYCLE_BIN);
|
||||
//productSpuPageReqVO.setTabType(ProductSpuPageReqVO.FOR_SALE);
|
||||
//productSpuPageReqVO.setTabType(ProductSpuPageReqVO.IN_WAREHOUSE);
|
||||
//productSpuPageReqVO.setTabType(ProductSpuPageReqVO.SOLD_OUT);
|
||||
//productSpuPageReqVO.setName(createReqVO.getName());
|
||||
//productSpuPageReqVO.setCategoryId(createReqVO.getCategoryId());
|
||||
|
||||
PageResult<ProductSpuDO> spuPage = productSpuService.getSpuPage(productSpuPageReqVO);
|
||||
|
||||
PageResult<ProductSpuRespVO> result = ProductSpuConvert.INSTANCE.convertPage(productSpuMapper.selectPage(productSpuPageReqVO));
|
||||
assertEquals(result.getTotal(), spuPage.getTotal());
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成笛卡尔积
|
||||
*
|
||||
* @param data 数据
|
||||
* @return 笛卡尔积
|
||||
*/
|
||||
public static <T> List<List<T>> cartesianProduct(List<List<T>> data) {
|
||||
List<List<T>> res = null; // 结果集(当前为第N个List,则该处存放的就为前N-1个List的笛卡尔积集合)
|
||||
for (List<T> list : data) { // 遍历数据
|
||||
List<List<T>> temp = new ArrayList<>(); // 临时结果集,存放本次循环后生成的笛卡尔积集合
|
||||
if (res == null) { // 结果集为null表示第一次循环既list为第一个List
|
||||
for (T t : list) { // 便利第一个List
|
||||
// 利用stream生成List,第一个List的笛卡尔积集合约等于自己本身(需要创建一个List并把对象添加到当中),存放到临时结果集
|
||||
temp.add(Stream.of(t).collect(Collectors.toList()));
|
||||
}
|
||||
res = temp; // 将临时结果集赋值给结果集
|
||||
continue; // 跳过本次循环
|
||||
}
|
||||
// 不为第一个List,计算前面的集合(笛卡尔积)和当前List的笛卡尔积集合
|
||||
for (T t : list) { // 便利
|
||||
for (List<T> rl : res) { // 便利前面的笛卡尔积集合
|
||||
// 利用stream生成List
|
||||
temp.add(Stream.concat(rl.stream(), Stream.of(t)).collect(Collectors.toList()));
|
||||
}
|
||||
}
|
||||
res = temp; // 将临时结果集赋值给结果集
|
||||
}
|
||||
// 返回结果
|
||||
return res;
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUpdateSpuStock() {
|
||||
// 准备参数
|
||||
Map<Long, Integer> stockIncrCounts = MapUtil.builder(1L, 10).put(2L, -20).build();
|
||||
// mock 方法(数据)
|
||||
productSpuMapper.insert(randomPojo(ProductSpuDO.class, o ->{
|
||||
o.setCategoryId(generateId());
|
||||
o.setBrandId(generateId());
|
||||
o.setDeliveryTemplateId(generateId());
|
||||
o.setUnit(RandomUtil.randomInt(1,20)); // 限制商品单位范围
|
||||
o.setSort(RandomUtil.randomInt(1,100)); // 限制排序范围
|
||||
o.setGiveIntegral(generaInt()); // 限制范围为正整数
|
||||
o.setVirtualSalesCount(generaInt()); // 限制范围为正整数
|
||||
o.setActivityOrders(newArrayList(1,3,2,4,5)); // 活动排序
|
||||
o.setPrice(generaInt()); // 限制范围为正整数
|
||||
o.setMarketPrice(generaInt()); // 限制范围为正整数
|
||||
o.setCostPrice(generaInt()); // 限制范围为正整数
|
||||
o.setStock(generaInt()); // 限制范围为正整数
|
||||
o.setGiveIntegral(generaInt()); // 限制范围为正整数
|
||||
o.setSalesCount(generaInt()); // 限制范围为正整数
|
||||
o.setBrowseCount(generaInt()); // 限制范围为正整数
|
||||
o.setId(1L).setStock(20);
|
||||
}));
|
||||
productSpuMapper.insert(randomPojo(ProductSpuDO.class, o -> {
|
||||
o.setCategoryId(generateId());
|
||||
o.setBrandId(generateId());
|
||||
o.setDeliveryTemplateId(generateId());
|
||||
o.setUnit(RandomUtil.randomInt(1,20)); // 限制商品单位范围
|
||||
o.setSort(RandomUtil.randomInt(1,100)); // 限制排序范围
|
||||
o.setGiveIntegral(generaInt()); // 限制范围为正整数
|
||||
o.setVirtualSalesCount(generaInt()); // 限制范围为正整数
|
||||
o.setActivityOrders(newArrayList(1,3,2,4,5)); // 活动排序
|
||||
o.setPrice(generaInt()); // 限制范围为正整数
|
||||
o.setMarketPrice(generaInt()); // 限制范围为正整数
|
||||
o.setCostPrice(generaInt()); // 限制范围为正整数
|
||||
o.setStock(generaInt()); // 限制范围为正整数
|
||||
o.setGiveIntegral(generaInt()); // 限制范围为正整数
|
||||
o.setSalesCount(generaInt()); // 限制范围为正整数
|
||||
o.setBrowseCount(generaInt()); // 限制范围为正整数
|
||||
o.setId(2L).setStock(30);
|
||||
}));
|
||||
|
||||
// 调用
|
||||
productSpuService.updateSpuStock(stockIncrCounts);
|
||||
// 断言
|
||||
assertEquals(productSpuService.getSpu(1L).getStock(), 30);
|
||||
assertEquals(productSpuService.getSpu(2L).getStock(), 10);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -1,18 +1,28 @@
|
|||
package cn.iocoder.yudao.module.promotion.api.bargain;
|
||||
|
||||
/**
|
||||
* 砍价活动 Api 接口
|
||||
*
|
||||
* @author HUIHUI
|
||||
*/
|
||||
import cn.iocoder.yudao.module.promotion.enums.ApiConstants;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.Parameters;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import org.springframework.cloud.openfeign.FeignClient;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
|
||||
// TODO 芋艿:commonresult
|
||||
@FeignClient(name = ApiConstants.NAME) // TODO 芋艿:fallbackFactory =
|
||||
@Tag(name = "RPC 服务 - 砍价活动")
|
||||
public interface BargainActivityApi {
|
||||
|
||||
/**
|
||||
* 更新砍价活动库存
|
||||
*
|
||||
* @param id 砍价活动编号
|
||||
* @param count 购买数量
|
||||
*/
|
||||
void updateBargainActivityStock(Long id, Integer count);
|
||||
String PREFIX = ApiConstants.PREFIX + "/bargain-activity";
|
||||
|
||||
@PutMapping(PREFIX + "/update-stock")
|
||||
@Operation(summary = "更新砍价活动库存")
|
||||
@Parameters({
|
||||
@Parameter(name = "id", description = "砍价活动编号", required = true, example = "1024"),
|
||||
@Parameter(name = "count", description = "购买数量", required = true, example = "1"),
|
||||
})
|
||||
void updateBargainActivityStock(@RequestParam("id") Long id,
|
||||
@RequestParam("count") Integer count);
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,34 +1,40 @@
|
|||
package cn.iocoder.yudao.module.promotion.api.bargain;
|
||||
|
||||
import cn.iocoder.yudao.module.promotion.api.bargain.dto.BargainValidateJoinRespDTO;
|
||||
import cn.iocoder.yudao.module.promotion.enums.ApiConstants;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.Parameters;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import org.springframework.cloud.openfeign.FeignClient;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
|
||||
/**
|
||||
* 砍价记录 API 接口
|
||||
*
|
||||
* @author HUIHUI
|
||||
*/
|
||||
@FeignClient(name = ApiConstants.NAME) // TODO 芋艿:fallbackFactory =
|
||||
@Tag(name = "RPC 服务 - 砍价记录")
|
||||
public interface BargainRecordApi {
|
||||
|
||||
/**
|
||||
* 【下单前】校验是否参与砍价活动
|
||||
* <p>
|
||||
* 如果校验失败,则抛出业务异常
|
||||
*
|
||||
* @param userId 用户编号
|
||||
* @param bargainRecordId 砍价活动编号
|
||||
* @param skuId SKU 编号
|
||||
* @return 砍价信息
|
||||
*/
|
||||
BargainValidateJoinRespDTO validateJoinBargain(Long userId, Long bargainRecordId, Long skuId);
|
||||
String PREFIX = ApiConstants.PREFIX + "/bargain-record";
|
||||
|
||||
/**
|
||||
* 更新砍价记录的订单编号
|
||||
*
|
||||
* 在砍价成功后,用户发起订单后,会记录该订单编号
|
||||
*
|
||||
* @param id 砍价记录编号
|
||||
* @param orderId 订单编号
|
||||
*/
|
||||
void updateBargainRecordOrderId(Long id, Long orderId);
|
||||
@GetMapping(PREFIX + "/validate-join")
|
||||
@Operation(summary = "【下单前】校验是否参与砍价活动") // 如果校验失败,则抛出业务异常
|
||||
@Parameters({
|
||||
@Parameter(name = "userId", description = "用户编号", required = true, example = "1024"),
|
||||
@Parameter(name = "bargainRecordId", description = "砍价记录编号", required = true, example = "2048"),
|
||||
@Parameter(name = "skuId", description = "SKU 编号", required = true, example = "4096"),
|
||||
})
|
||||
BargainValidateJoinRespDTO validateJoinBargain(@RequestParam("userId") Long userId,
|
||||
@RequestParam("bargainRecordId") Long bargainRecordId,
|
||||
@RequestParam("skuId") Long skuId);
|
||||
|
||||
@PutMapping(PREFIX + "/update-order-id")
|
||||
@Operation(summary = "更新砍价记录的订单编号") // 在砍价成功后,用户发起订单后,会记录该订单编号
|
||||
@Parameters({
|
||||
@Parameter(name = "id", description = "砍价记录编号", required = true, example = "1024"),
|
||||
@Parameter(name = "orderId", description = "订单编号", required = true, example = "2048"),
|
||||
})
|
||||
void updateBargainRecordOrderId(@RequestParam("id") Long id,
|
||||
@RequestParam("oderId") Long orderId);
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,10 +0,0 @@
|
|||
package cn.iocoder.yudao.module.promotion.api.combination;
|
||||
|
||||
/**
|
||||
* 拼团活动 Api 接口
|
||||
*
|
||||
* @author HUIHUI
|
||||
*/
|
||||
public interface CombinationActivityApi {
|
||||
|
||||
}
|
||||
|
|
@ -3,51 +3,52 @@ package cn.iocoder.yudao.module.promotion.api.combination;
|
|||
import cn.iocoder.yudao.module.promotion.api.combination.dto.CombinationRecordCreateReqDTO;
|
||||
import cn.iocoder.yudao.module.promotion.api.combination.dto.CombinationRecordCreateRespDTO;
|
||||
import cn.iocoder.yudao.module.promotion.api.combination.dto.CombinationValidateJoinRespDTO;
|
||||
import cn.iocoder.yudao.module.promotion.enums.ApiConstants;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.Parameters;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import org.springframework.cloud.openfeign.FeignClient;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
|
||||
import javax.validation.Valid;
|
||||
|
||||
/**
|
||||
* 拼团记录 API 接口
|
||||
*
|
||||
* @author HUIHUI
|
||||
*/
|
||||
@FeignClient(name = ApiConstants.NAME) // TODO 芋艿:fallbackFactory =
|
||||
@Tag(name = "RPC 服务 - 拼团记录")
|
||||
public interface CombinationRecordApi {
|
||||
|
||||
/**
|
||||
* 校验是否满足拼团条件
|
||||
*
|
||||
* @param userId 用户编号
|
||||
* @param activityId 活动编号
|
||||
* @param headId 团长编号
|
||||
* @param skuId sku 编号
|
||||
* @param count 数量
|
||||
*/
|
||||
void validateCombinationRecord(Long userId, Long activityId, Long headId, Long skuId, Integer count);
|
||||
String PREFIX = ApiConstants.PREFIX + "/combination-record";
|
||||
|
||||
/**
|
||||
* 创建开团记录
|
||||
*
|
||||
* @param reqDTO 请求 DTO
|
||||
* @return 拼团信息
|
||||
*/
|
||||
CombinationRecordCreateRespDTO createCombinationRecord(@Valid CombinationRecordCreateReqDTO reqDTO);
|
||||
@GetMapping(PREFIX + "/validate")
|
||||
@Operation(summary = "校验是否满足拼团条件")
|
||||
@Parameters({
|
||||
@Parameter(name = "userId", description = "用户编号", required = true, example = "1024"),
|
||||
@Parameter(name = "activityId", description = "活动编号", required = true, example = "2048"),
|
||||
@Parameter(name = "headId", description = "团长编号", required = true, example = "4096"),
|
||||
@Parameter(name = "skuId", description = "SKU 编号", required = true, example = "8192"),
|
||||
@Parameter(name = "count", description = "数量", required = true, example = "1"),
|
||||
})
|
||||
void validateCombinationRecord(@RequestParam("userId") Long userId,
|
||||
@RequestParam("activityId") Long activityId,
|
||||
@RequestParam("headId") Long headId,
|
||||
@RequestParam("skuId") Long skuId,
|
||||
@RequestParam("count") Integer count);
|
||||
|
||||
/**
|
||||
* 查询拼团记录是否成功
|
||||
*
|
||||
* @param userId 用户编号
|
||||
* @param orderId 订单编号
|
||||
* @return 拼团是否成功
|
||||
*/
|
||||
boolean isCombinationRecordSuccess(Long userId, Long orderId);
|
||||
@PostMapping("/create")
|
||||
@Operation(summary = "创建开团记录")
|
||||
CombinationRecordCreateRespDTO createCombinationRecord(@RequestBody @Valid CombinationRecordCreateReqDTO reqDTO);
|
||||
|
||||
/**
|
||||
* 更新拼团状态为【失败】
|
||||
*
|
||||
* @param userId 用户编号
|
||||
* @param orderId 订单编号
|
||||
*/
|
||||
void updateRecordStatusToFailed(Long userId, Long orderId);
|
||||
@GetMapping("/is-success")
|
||||
@Operation(summary = "查询拼团记录是否成功")
|
||||
@Parameters({
|
||||
@Parameter(name = "userId", description = "用户编号", required = true, example = "1024"),
|
||||
@Parameter(name = "orderId", description = "订单编号", required = true, example = "2048"),
|
||||
})
|
||||
boolean isCombinationRecordSuccess(@RequestParam("userId") Long userId,
|
||||
@RequestParam("orderId") Long orderId);
|
||||
|
||||
/**
|
||||
* 【下单前】校验是否满足拼团活动条件
|
||||
|
|
@ -61,7 +62,19 @@ public interface CombinationRecordApi {
|
|||
* @param count 数量
|
||||
* @return 拼团信息
|
||||
*/
|
||||
CombinationValidateJoinRespDTO validateJoinCombination(Long userId, Long activityId, Long headId,
|
||||
Long skuId, Integer count);
|
||||
@GetMapping("/validate-join")
|
||||
@Operation(summary = "【下单前】校验是否满足拼团活动条件") // 如果校验失败,则抛出业务异常
|
||||
@Parameters({
|
||||
@Parameter(name = "userId", description = "用户编号", required = true, example = "1024"),
|
||||
@Parameter(name = "activityId", description = "活动编号", required = true, example = "2048"),
|
||||
@Parameter(name = "headId", description = "团长编号", required = true, example = "4096"),
|
||||
@Parameter(name = "skuId", description = "SKU 编号", required = true, example = "8192"),
|
||||
@Parameter(name = "count", description = "数量", required = true, example = "1"),
|
||||
})
|
||||
CombinationValidateJoinRespDTO validateJoinCombination(@RequestParam("userId") Long userId,
|
||||
@RequestParam("activityId") Long activityId,
|
||||
@RequestParam("headId") Long headId,
|
||||
@RequestParam("skuId") Long skuId,
|
||||
@RequestParam("count") Integer count);
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -3,36 +3,34 @@ package cn.iocoder.yudao.module.promotion.api.coupon;
|
|||
import cn.iocoder.yudao.module.promotion.api.coupon.dto.CouponRespDTO;
|
||||
import cn.iocoder.yudao.module.promotion.api.coupon.dto.CouponUseReqDTO;
|
||||
import cn.iocoder.yudao.module.promotion.api.coupon.dto.CouponValidReqDTO;
|
||||
import cn.iocoder.yudao.module.promotion.enums.ApiConstants;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import org.springframework.cloud.openfeign.FeignClient;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
|
||||
import javax.validation.Valid;
|
||||
|
||||
/**
|
||||
* 优惠劵 API 接口
|
||||
*
|
||||
* @author 芋道源码
|
||||
*/
|
||||
@FeignClient(name = ApiConstants.NAME) // TODO 芋艿:fallbackFactory =
|
||||
@Tag(name = "RPC 服务 - 优惠劵")
|
||||
public interface CouponApi {
|
||||
|
||||
/**
|
||||
* 使用优惠劵
|
||||
*
|
||||
* @param useReqDTO 使用请求
|
||||
*/
|
||||
void useCoupon(@Valid CouponUseReqDTO useReqDTO);
|
||||
String PREFIX = ApiConstants.PREFIX + "/coupon";
|
||||
|
||||
/**
|
||||
* 退还已使用的优惠券
|
||||
*
|
||||
* @param id 优惠券编号
|
||||
*/
|
||||
void returnUsedCoupon(Long id);
|
||||
@PutMapping(PREFIX + "/use")
|
||||
@Operation(summary = "使用优惠劵")
|
||||
void useCoupon(@RequestBody @Valid CouponUseReqDTO useReqDTO);
|
||||
|
||||
/**
|
||||
* 校验优惠劵
|
||||
*
|
||||
* @param validReqDTO 校验请求
|
||||
* @return 优惠劵
|
||||
*/
|
||||
@PutMapping(PREFIX + "/return-used")
|
||||
@Parameter(name = "id", description = "优惠券编号", required = true, example = "1")
|
||||
void returnUsedCoupon(@RequestParam("id") Long id);
|
||||
|
||||
@GetMapping(PREFIX + "/get")
|
||||
@Operation(summary = "校验优惠劵")
|
||||
CouponRespDTO validateCoupon(@Valid CouponValidReqDTO validReqDTO);
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,23 +0,0 @@
|
|||
package cn.iocoder.yudao.module.promotion.api.coupon;
|
||||
|
||||
import cn.iocoder.yudao.module.promotion.api.coupon.dto.CouponTemplateRespDTO;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 优惠劵模版 API 接口
|
||||
*
|
||||
* @author HUIHUI
|
||||
*/
|
||||
public interface CouponTemplateApi {
|
||||
|
||||
/**
|
||||
* 获得优惠券模版的精简信息列表
|
||||
*
|
||||
* @param ids 优惠券模版编号
|
||||
* @return 优惠券模版的精简信息列表
|
||||
*/
|
||||
List<CouponTemplateRespDTO> getCouponTemplateListByIds(Collection<Long> ids);
|
||||
|
||||
}
|
||||
|
|
@ -1,23 +1,26 @@
|
|||
package cn.iocoder.yudao.module.promotion.api.discount;
|
||||
|
||||
import cn.iocoder.yudao.module.promotion.api.discount.dto.DiscountProductRespDTO;
|
||||
import cn.iocoder.yudao.module.promotion.enums.ApiConstants;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import org.springframework.cloud.openfeign.FeignClient;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 限时折扣 API 接口
|
||||
*
|
||||
* @author 芋道源码
|
||||
*/
|
||||
@FeignClient(name = ApiConstants.NAME) // TODO 芋艿:fallbackFactory =
|
||||
@Tag(name = "RPC 服务 - 限时折扣")
|
||||
public interface DiscountActivityApi {
|
||||
|
||||
/**
|
||||
* 获得商品匹配的的限时折扣信息
|
||||
*
|
||||
* @param skuIds 商品 SKU 编号数组
|
||||
* @return 限时折扣信息
|
||||
*/
|
||||
List<DiscountProductRespDTO> getMatchDiscountProductList(Collection<Long> skuIds);
|
||||
String PREFIX = ApiConstants.PREFIX + "/discount-activity";
|
||||
|
||||
@GetMapping(PREFIX + "/list-by-sku-id")
|
||||
@Operation(summary = "获得商品匹配的的限时折扣信息")
|
||||
@Parameter(name = "skuIds", description = "商品 SKU 编号数组", required = true, example = "[1, 2]")
|
||||
List<DiscountProductRespDTO> getMatchDiscountProductList(@RequestParam("skuIds") Collection<Long> skuIds);
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,24 +1,26 @@
|
|||
package cn.iocoder.yudao.module.promotion.api.reward;
|
||||
|
||||
import cn.iocoder.yudao.module.promotion.api.reward.dto.RewardActivityMatchRespDTO;
|
||||
import cn.iocoder.yudao.module.promotion.enums.ApiConstants;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import org.springframework.cloud.openfeign.FeignClient;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 满减送活动 API 接口
|
||||
*
|
||||
* @author 芋道源码
|
||||
*/
|
||||
@FeignClient(name = ApiConstants.NAME) // TODO 芋艿:fallbackFactory =
|
||||
@Tag(name = "RPC 服务 - 满减送")
|
||||
public interface RewardActivityApi {
|
||||
|
||||
String PREFIX = ApiConstants.PREFIX + "/reward-activity";
|
||||
|
||||
/**
|
||||
* 基于指定的 SPU 编号数组,获得它们匹配的满减送活动
|
||||
*
|
||||
* @param spuIds SPU 编号数组
|
||||
* @return 满减送活动列表
|
||||
*/
|
||||
List<RewardActivityMatchRespDTO> getMatchRewardActivityList(Collection<Long> spuIds);
|
||||
@GetMapping(PREFIX + "/list-by-spu-id")
|
||||
@Operation(summary = "获得商品匹配的的满减送活动信息")
|
||||
@Parameter(name = "spuIds", description = "商品 SPU 编号数组", required = true, example = "[1, 2]")
|
||||
List<RewardActivityMatchRespDTO> getMatchRewardActivityList(@RequestParam("spuIds") Collection<Long> spuIds);
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,42 +1,53 @@
|
|||
package cn.iocoder.yudao.module.promotion.api.seckill;
|
||||
|
||||
import cn.iocoder.yudao.module.promotion.api.seckill.dto.SeckillValidateJoinRespDTO;
|
||||
import cn.iocoder.yudao.module.promotion.enums.ApiConstants;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.Parameter;
|
||||
import io.swagger.v3.oas.annotations.Parameters;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import org.springframework.cloud.openfeign.FeignClient;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
|
||||
/**
|
||||
* 秒杀活动 API 接口
|
||||
*
|
||||
* @author HUIHUI
|
||||
*/
|
||||
@FeignClient(name = ApiConstants.NAME) // TODO 芋艿:fallbackFactory =
|
||||
@Tag(name = "RPC 服务 - 秒杀活动")
|
||||
public interface SeckillActivityApi {
|
||||
|
||||
/**
|
||||
* 更新秒杀库存(减少)
|
||||
*
|
||||
* @param id 活动编号
|
||||
* @param skuId sku 编号
|
||||
* @param count 数量(正数)
|
||||
*/
|
||||
void updateSeckillStockDecr(Long id, Long skuId, Integer count);
|
||||
String PREFIX = ApiConstants.PREFIX + "/discount-activity";
|
||||
|
||||
/**
|
||||
* 更新秒杀库存(增加)
|
||||
*
|
||||
* @param id 活动编号
|
||||
* @param skuId sku 编号
|
||||
* @param count 数量(正数)
|
||||
*/
|
||||
void updateSeckillStockIncr(Long id, Long skuId, Integer count);
|
||||
@PutMapping(PREFIX + "/update-stock-decr")
|
||||
@Operation(summary = "更新秒杀库存(减少)")
|
||||
@Parameters({
|
||||
@Parameter(name = "id", description = "活动编号", required = true, example = "1"),
|
||||
@Parameter(name = "skuId", description = "SKU 编号", required = true, example = "2"),
|
||||
@Parameter(name = "count", description = "数量", required = true, example = "3"),
|
||||
})
|
||||
void updateSeckillStockDecr(@RequestParam("id") Long id,
|
||||
@RequestParam("skuId") Long skuId,
|
||||
@RequestParam("count")Integer count);
|
||||
|
||||
/**
|
||||
* 【下单前】校验是否参与秒杀活动
|
||||
*
|
||||
* 如果校验失败,则抛出业务异常
|
||||
*
|
||||
* @param activityId 活动编号
|
||||
* @param skuId SKU 编号
|
||||
* @param count 数量
|
||||
* @return 秒杀信息
|
||||
*/
|
||||
SeckillValidateJoinRespDTO validateJoinSeckill(Long activityId, Long skuId, Integer count);
|
||||
@PutMapping(PREFIX + "/update-stock-incr")
|
||||
@Operation(summary = "更新秒杀库存(增加)")
|
||||
@Parameters({
|
||||
@Parameter(name = "id", description = "活动编号", required = true, example = "1"),
|
||||
@Parameter(name = "skuId", description = "SKU 编号", required = true, example = "2"),
|
||||
@Parameter(name = "count", description = "数量", required = true, example = "3"),
|
||||
})
|
||||
void updateSeckillStockIncr(@RequestParam("id") Long id,
|
||||
@RequestParam("skuId") Long skuId,
|
||||
@RequestParam("count")Integer count);
|
||||
|
||||
@GetMapping("/validate-join")
|
||||
@Operation(summary = "【下单前】校验是否参与秒杀活动") // 如果校验失败,则抛出业务异常
|
||||
@Parameters({
|
||||
@Parameter(name = "activityId", description = "活动编号", required = true, example = "1"),
|
||||
@Parameter(name = "skuId", description = "SKU 编号", required = true, example = "2"),
|
||||
@Parameter(name = "count", description = "数量", required = true, example = "3"),
|
||||
})
|
||||
SeckillValidateJoinRespDTO validateJoinSeckill(@RequestParam("activityId") Long activityId,
|
||||
@RequestParam("skuId") Long skuId,
|
||||
@RequestParam("count")Integer count);
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,13 +0,0 @@
|
|||
package cn.iocoder.yudao.module.promotion.api.combination;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
/**
|
||||
* 拼团活动 Api 接口实现类
|
||||
*
|
||||
* @author HUIHUI
|
||||
*/
|
||||
@Service
|
||||
public class CombinationActivityApiImpl implements CombinationActivityApi {
|
||||
|
||||
}
|
||||
|
|
@ -44,11 +44,6 @@ public class CombinationRecordApiImpl implements CombinationRecordApi {
|
|||
return CombinationRecordStatusEnum.isSuccess(record.getStatus());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateRecordStatusToFailed(Long userId, Long orderId) {
|
||||
recordService.updateCombinationRecordStatusByUserIdAndOrderId(CombinationRecordStatusEnum.FAILED.getStatus(), userId, orderId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CombinationValidateJoinRespDTO validateJoinCombination(Long userId, Long activityId, Long headId, Long skuId, Integer count) {
|
||||
return recordService.validateJoinCombination(userId, activityId, headId, skuId, count);
|
||||
|
|
|
|||
|
|
@ -1,33 +0,0 @@
|
|||
package cn.iocoder.yudao.module.promotion.api.coupon;
|
||||
|
||||
import cn.hutool.core.collection.CollUtil;
|
||||
import cn.iocoder.yudao.module.promotion.api.coupon.dto.CouponTemplateRespDTO;
|
||||
import cn.iocoder.yudao.module.promotion.convert.coupon.CouponTemplateConvert;
|
||||
import cn.iocoder.yudao.module.promotion.service.coupon.CouponTemplateService;
|
||||
import org.springframework.stereotype.Service;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 优惠劵模版 API 接口实现类
|
||||
*
|
||||
* @author HUIHUI
|
||||
*/
|
||||
@Service
|
||||
public class CouponTemplateApiImpl implements CouponTemplateApi {
|
||||
|
||||
@Resource
|
||||
private CouponTemplateService couponTemplateService;
|
||||
|
||||
@Override
|
||||
public List<CouponTemplateRespDTO> getCouponTemplateListByIds(Collection<Long> ids) {
|
||||
if (CollUtil.isEmpty(ids)) { // 防御一下
|
||||
return Collections.emptyList();
|
||||
}
|
||||
return CouponTemplateConvert.INSTANCE.convertList(couponTemplateService.getCouponTemplateListByIds(ids));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -96,13 +96,13 @@ public class AppCouponTemplateController {
|
|||
*/
|
||||
private Long getProductScopeValue(Integer productScope, Long spuId) {
|
||||
// 通用券:没有商品范围
|
||||
if (productScope == null || ObjectUtils.equalsAny(productScope, PromotionProductScopeEnum.ALL.getScope(), null)) {
|
||||
if (ObjectUtils.equalsAny(productScope, PromotionProductScopeEnum.ALL.getScope(), null)) {
|
||||
return null;
|
||||
}
|
||||
// 品类券:查询商品的品类编号
|
||||
if (Objects.equals(productScope, PromotionProductScopeEnum.CATEGORY.getScope()) && spuId != null) {
|
||||
return Optional.ofNullable(productSpuApi.getSpu(spuId).getCheckedData())
|
||||
.map(ProductSpuRespDTO::getCategoryId).orElse(null);
|
||||
ProductSpuRespDTO spu = productSpuApi.getSpu(spuId).getCheckedData();
|
||||
return spu != null ? spu.getCategoryId() : null;
|
||||
}
|
||||
// 商品卷:直接返回
|
||||
return spuId;
|
||||
|
|
|
|||
|
|
@ -75,8 +75,4 @@ public interface CouponTemplateMapper extends BaseMapperX<CouponTemplateDO> {
|
|||
return canTakeConsumer;
|
||||
}
|
||||
|
||||
default List<CouponTemplateDO> selectListByIds(Collection<Long> ids) {
|
||||
return selectList(new LambdaQueryWrapperX<CouponTemplateDO>().in(CouponTemplateDO::getId, ids));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -108,8 +108,8 @@ public class CombinationActivityServiceImpl implements CombinationActivityServic
|
|||
}
|
||||
|
||||
// 2. 校验商品 sku 都存在
|
||||
Map<Long, ProductSkuRespDTO> skuMap = convertMap(productSkuApi.getSkuListBySpuId(singletonList(spuId)).getCheckedData(),
|
||||
ProductSkuRespDTO::getId);
|
||||
List<ProductSkuRespDTO> skus = productSkuApi.getSkuListBySpuId(singletonList(spuId)).getCheckedData();
|
||||
Map<Long, ProductSkuRespDTO> skuMap = convertMap(skus, ProductSkuRespDTO::getId);
|
||||
products.forEach(product -> {
|
||||
if (!skuMap.containsKey(product.getSkuId())) {
|
||||
throw exception(SKU_NOT_EXISTS);
|
||||
|
|
|
|||
|
|
@ -21,15 +21,6 @@ import java.util.Map;
|
|||
*/
|
||||
public interface CombinationRecordService {
|
||||
|
||||
/**
|
||||
* 更新拼团状态
|
||||
*
|
||||
* @param status 状态
|
||||
* @param userId 用户编号
|
||||
* @param orderId 订单编号
|
||||
*/
|
||||
void updateCombinationRecordStatusByUserIdAndOrderId(Integer status, Long userId, Long orderId);
|
||||
|
||||
/**
|
||||
* 【下单前】校验是否满足拼团活动条件
|
||||
*
|
||||
|
|
@ -62,15 +53,6 @@ public interface CombinationRecordService {
|
|||
*/
|
||||
CombinationRecordDO getCombinationRecord(Long userId, Long orderId);
|
||||
|
||||
/**
|
||||
* 获取拼团记录
|
||||
*
|
||||
* @param userId 用户 id
|
||||
* @param activityId 活动 id
|
||||
* @return 拼团记录列表
|
||||
*/
|
||||
List<CombinationRecordDO> getCombinationRecordListByUserIdAndActivityId(Long userId, Long activityId);
|
||||
|
||||
/**
|
||||
* 【下单前】校验是否满足拼团活动条件
|
||||
*
|
||||
|
|
|
|||
|
|
@ -66,16 +66,6 @@ public class CombinationRecordServiceImpl implements CombinationRecordService {
|
|||
@Resource
|
||||
private TradeOrderApi tradeOrderApi;
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void updateCombinationRecordStatusByUserIdAndOrderId(Integer status, Long userId, Long orderId) {
|
||||
// 校验拼团是否存在
|
||||
CombinationRecordDO record = validateCombinationRecord(userId, orderId);
|
||||
|
||||
// 更新状态
|
||||
combinationRecordMapper.updateById(new CombinationRecordDO().setId(record.getId()).setStatus(status));
|
||||
}
|
||||
|
||||
private CombinationRecordDO validateCombinationRecord(Long userId, Long orderId) {
|
||||
// 校验拼团是否存在
|
||||
CombinationRecordDO recordDO = combinationRecordMapper.selectByUserIdAndOrderId(userId, orderId);
|
||||
|
|
@ -229,11 +219,6 @@ public class CombinationRecordServiceImpl implements CombinationRecordService {
|
|||
return combinationRecordMapper.selectByUserIdAndOrderId(userId, orderId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<CombinationRecordDO> getCombinationRecordListByUserIdAndActivityId(Long userId, Long activityId) {
|
||||
return combinationRecordMapper.selectListByUserIdAndActivityId(userId, activityId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public CombinationValidateJoinRespDTO validateJoinCombination(Long userId, Long activityId, Long headId,
|
||||
Long skuId, Integer count) {
|
||||
|
|
|
|||
|
|
@ -7,7 +7,6 @@ import cn.hutool.core.util.ObjectUtil;
|
|||
import cn.hutool.core.util.StrUtil;
|
||||
import cn.hutool.extra.spring.SpringUtil;
|
||||
import cn.iocoder.yudao.framework.common.pojo.PageResult;
|
||||
import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
|
||||
import cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils;
|
||||
import cn.iocoder.yudao.module.member.api.user.MemberUserApi;
|
||||
import cn.iocoder.yudao.module.member.api.user.dto.MemberUserRespDTO;
|
||||
|
|
@ -80,12 +79,11 @@ public class CouponServiceImpl implements CouponService {
|
|||
public PageResult<CouponDO> getCouponPage(CouponPageReqVO pageReqVO) {
|
||||
// 获得用户编号
|
||||
if (StrUtil.isNotEmpty(pageReqVO.getNickname())) {
|
||||
Set<Long> userIds = CollectionUtils.convertSet(memberUserApi.getUserListByNickname(pageReqVO.getNickname()).getCheckedData(),
|
||||
MemberUserRespDTO::getId);
|
||||
if (CollUtil.isEmpty(userIds)) {
|
||||
List<MemberUserRespDTO> users = memberUserApi.getUserListByNickname(pageReqVO.getNickname()).getCheckedData();
|
||||
if (CollUtil.isEmpty(users)) {
|
||||
return PageResult.empty();
|
||||
}
|
||||
pageReqVO.setUserIds(userIds);
|
||||
pageReqVO.setUserIds(convertSet(users, MemberUserRespDTO::getId));
|
||||
}
|
||||
// 分页查询
|
||||
return couponMapper.selectPage(pageReqVO);
|
||||
|
|
|
|||
|
|
@ -8,7 +8,6 @@ import cn.iocoder.yudao.module.promotion.dal.dataobject.coupon.CouponTemplateDO;
|
|||
import cn.iocoder.yudao.module.promotion.enums.coupon.CouponTakeTypeEnum;
|
||||
|
||||
import javax.validation.Valid;
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
|
|
@ -92,12 +91,4 @@ public interface CouponTemplateService {
|
|||
List<CouponTemplateDO> getCouponTemplateList(List<Integer> canTakeTypes, Integer productScope,
|
||||
Long productScopeValue, Integer count);
|
||||
|
||||
/**
|
||||
* 获得优惠券模版列表
|
||||
*
|
||||
* @param ids 优惠券模版编号
|
||||
* @return 优惠券模版列表
|
||||
*/
|
||||
List<CouponTemplateDO> getCouponTemplateListByIds(Collection<Long> ids);
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -127,9 +127,4 @@ public class CouponTemplateServiceImpl implements CouponTemplateService {
|
|||
return couponTemplateMapper.selectList(canTakeTypes, productScope, productScopeValue, count);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<CouponTemplateDO> getCouponTemplateListByIds(Collection<Long> ids) {
|
||||
return couponTemplateMapper.selectListByIds(ids);
|
||||
}
|
||||
|
||||
}
|
||||
|
|
|
|||
|
|
@ -123,8 +123,8 @@ public class SeckillActivityServiceImpl implements SeckillActivityService {
|
|||
}
|
||||
|
||||
// 2. 校验商品 sku 都存在
|
||||
Map<Long, ProductSkuRespDTO> skuMap = convertMap(productSkuApi.getSkuListBySpuId(singletonList(spuId)).getCheckedData(),
|
||||
ProductSkuRespDTO::getId);
|
||||
List<ProductSkuRespDTO> skus = productSkuApi.getSkuListBySpuId(singletonList(spuId)).getCheckedData();
|
||||
Map<Long, ProductSkuRespDTO> skuMap = convertMap(skus, ProductSkuRespDTO::getId);
|
||||
products.forEach(product -> {
|
||||
if (!skuMap.containsKey(product.getSkuId())) {
|
||||
throw exception(SKU_NOT_EXISTS);
|
||||
|
|
|
|||
|
|
@ -1,139 +0,0 @@
|
|||
package cn.iocoder.yudao.module.promotion.service.article;
|
||||
|
||||
import cn.iocoder.yudao.framework.common.pojo.PageResult;
|
||||
import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest;
|
||||
import cn.iocoder.yudao.module.promotion.controller.admin.article.vo.category.ArticleCategoryCreateReqVO;
|
||||
import cn.iocoder.yudao.module.promotion.controller.admin.article.vo.category.ArticleCategoryPageReqVO;
|
||||
import cn.iocoder.yudao.module.promotion.controller.admin.article.vo.category.ArticleCategoryUpdateReqVO;
|
||||
import cn.iocoder.yudao.module.promotion.dal.dataobject.article.ArticleCategoryDO;
|
||||
import cn.iocoder.yudao.module.promotion.dal.mysql.article.ArticleCategoryMapper;
|
||||
import org.junit.jupiter.api.Disabled;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.context.annotation.Import;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildBetweenTime;
|
||||
import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomLongId;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomPojo;
|
||||
import static cn.iocoder.yudao.module.promotion.enums.ErrorCodeConstants.ARTICLE_CATEGORY_NOT_EXISTS;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
// TODO 芋艿:review 单测
|
||||
/**
|
||||
* {@link ArticleCategoryServiceImpl} 的单元测试类
|
||||
*
|
||||
* @author HUIHUI
|
||||
*/
|
||||
@Import(ArticleCategoryServiceImpl.class)
|
||||
public class ArticleCategoryServiceImplTest extends BaseDbUnitTest {
|
||||
|
||||
@Resource
|
||||
private ArticleCategoryServiceImpl articleCategoryService;
|
||||
|
||||
@Resource
|
||||
private ArticleCategoryMapper articleCategoryMapper;
|
||||
|
||||
@Test
|
||||
public void testCreateArticleCategory_success() {
|
||||
// 准备参数
|
||||
ArticleCategoryCreateReqVO reqVO = randomPojo(ArticleCategoryCreateReqVO.class);
|
||||
|
||||
// 调用
|
||||
Long articleCategoryId = articleCategoryService.createArticleCategory(reqVO);
|
||||
// 断言
|
||||
assertNotNull(articleCategoryId);
|
||||
// 校验记录的属性是否正确
|
||||
ArticleCategoryDO articleCategory = articleCategoryMapper.selectById(articleCategoryId);
|
||||
assertPojoEquals(reqVO, articleCategory);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUpdateArticleCategory_success() {
|
||||
// mock 数据
|
||||
ArticleCategoryDO dbArticleCategory = randomPojo(ArticleCategoryDO.class);
|
||||
articleCategoryMapper.insert(dbArticleCategory);// @Sql: 先插入出一条存在的数据
|
||||
// 准备参数
|
||||
ArticleCategoryUpdateReqVO reqVO = randomPojo(ArticleCategoryUpdateReqVO.class, o -> {
|
||||
o.setId(dbArticleCategory.getId()); // 设置更新的 ID
|
||||
});
|
||||
|
||||
// 调用
|
||||
articleCategoryService.updateArticleCategory(reqVO);
|
||||
// 校验是否更新正确
|
||||
ArticleCategoryDO articleCategory = articleCategoryMapper.selectById(reqVO.getId()); // 获取最新的
|
||||
assertPojoEquals(reqVO, articleCategory);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUpdateArticleCategory_notExists() {
|
||||
// 准备参数
|
||||
ArticleCategoryUpdateReqVO reqVO = randomPojo(ArticleCategoryUpdateReqVO.class);
|
||||
|
||||
// 调用, 并断言异常
|
||||
assertServiceException(() -> articleCategoryService.updateArticleCategory(reqVO), ARTICLE_CATEGORY_NOT_EXISTS);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteArticleCategory_success() {
|
||||
// mock 数据
|
||||
ArticleCategoryDO dbArticleCategory = randomPojo(ArticleCategoryDO.class);
|
||||
articleCategoryMapper.insert(dbArticleCategory);// @Sql: 先插入出一条存在的数据
|
||||
// 准备参数
|
||||
Long id = dbArticleCategory.getId();
|
||||
|
||||
// 调用
|
||||
articleCategoryService.deleteArticleCategory(id);
|
||||
// 校验数据不存在了
|
||||
assertNull(articleCategoryMapper.selectById(id));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteArticleCategory_notExists() {
|
||||
// 准备参数
|
||||
Long id = randomLongId();
|
||||
|
||||
// 调用, 并断言异常
|
||||
assertServiceException(() -> articleCategoryService.deleteArticleCategory(id), ARTICLE_CATEGORY_NOT_EXISTS);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Disabled // TODO 请修改 null 为需要的值,然后删除 @Disabled 注解
|
||||
public void testGetArticleCategoryPage() {
|
||||
// mock 数据
|
||||
ArticleCategoryDO dbArticleCategory = randomPojo(ArticleCategoryDO.class, o -> { // 等会查询到
|
||||
o.setName(null);
|
||||
o.setPicUrl(null);
|
||||
o.setStatus(null);
|
||||
o.setSort(null);
|
||||
o.setCreateTime(null);
|
||||
});
|
||||
articleCategoryMapper.insert(dbArticleCategory);
|
||||
// 测试 name 不匹配
|
||||
articleCategoryMapper.insert(cloneIgnoreId(dbArticleCategory, o -> o.setName(null)));
|
||||
// 测试 picUrl 不匹配
|
||||
articleCategoryMapper.insert(cloneIgnoreId(dbArticleCategory, o -> o.setPicUrl(null)));
|
||||
// 测试 status 不匹配
|
||||
articleCategoryMapper.insert(cloneIgnoreId(dbArticleCategory, o -> o.setStatus(null)));
|
||||
// 测试 sort 不匹配
|
||||
articleCategoryMapper.insert(cloneIgnoreId(dbArticleCategory, o -> o.setSort(null)));
|
||||
// 测试 createTime 不匹配
|
||||
articleCategoryMapper.insert(cloneIgnoreId(dbArticleCategory, o -> o.setCreateTime(null)));
|
||||
// 准备参数
|
||||
ArticleCategoryPageReqVO reqVO = new ArticleCategoryPageReqVO();
|
||||
reqVO.setName(null);
|
||||
reqVO.setStatus(null);
|
||||
reqVO.setCreateTime(buildBetweenTime(2023, 2, 1, 2023, 2, 28));
|
||||
|
||||
// 调用
|
||||
PageResult<ArticleCategoryDO> pageResult = articleCategoryService.getArticleCategoryPage(reqVO);
|
||||
// 断言
|
||||
assertEquals(1, pageResult.getTotal());
|
||||
assertEquals(1, pageResult.getList().size());
|
||||
assertPojoEquals(dbArticleCategory, pageResult.getList().get(0));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -1,167 +0,0 @@
|
|||
package cn.iocoder.yudao.module.promotion.service.article;
|
||||
|
||||
import cn.iocoder.yudao.framework.common.pojo.PageResult;
|
||||
import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest;
|
||||
import cn.iocoder.yudao.module.promotion.controller.admin.article.vo.article.ArticleCreateReqVO;
|
||||
import cn.iocoder.yudao.module.promotion.controller.admin.article.vo.article.ArticlePageReqVO;
|
||||
import cn.iocoder.yudao.module.promotion.controller.admin.article.vo.article.ArticleUpdateReqVO;
|
||||
import cn.iocoder.yudao.module.promotion.dal.dataobject.article.ArticleDO;
|
||||
import cn.iocoder.yudao.module.promotion.dal.mysql.article.ArticleMapper;
|
||||
import org.junit.jupiter.api.Disabled;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.context.annotation.Import;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildBetweenTime;
|
||||
import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomLongId;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomPojo;
|
||||
import static cn.iocoder.yudao.module.promotion.enums.ErrorCodeConstants.ARTICLE_NOT_EXISTS;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* {@link ArticleServiceImpl} 的单元测试类
|
||||
*
|
||||
* @author HUIHUI
|
||||
*/
|
||||
@Import(ArticleServiceImpl.class)
|
||||
public class ArticleServiceImplTest extends BaseDbUnitTest {
|
||||
|
||||
@Resource
|
||||
private ArticleServiceImpl articleService;
|
||||
|
||||
@Resource
|
||||
private ArticleMapper articleMapper;
|
||||
|
||||
@Test
|
||||
public void testCreateArticle_success() {
|
||||
// 准备参数
|
||||
ArticleCreateReqVO reqVO = randomPojo(ArticleCreateReqVO.class);
|
||||
|
||||
// 调用
|
||||
Long articleId = articleService.createArticle(reqVO);
|
||||
// 断言
|
||||
assertNotNull(articleId);
|
||||
// 校验记录的属性是否正确
|
||||
ArticleDO article = articleMapper.selectById(articleId);
|
||||
assertPojoEquals(reqVO, article);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUpdateArticle_success() {
|
||||
// mock 数据
|
||||
ArticleDO dbArticle = randomPojo(ArticleDO.class);
|
||||
articleMapper.insert(dbArticle);// @Sql: 先插入出一条存在的数据
|
||||
// 准备参数
|
||||
ArticleUpdateReqVO reqVO = randomPojo(ArticleUpdateReqVO.class, o -> {
|
||||
o.setId(dbArticle.getId()); // 设置更新的 ID
|
||||
});
|
||||
|
||||
// 调用
|
||||
articleService.updateArticle(reqVO);
|
||||
// 校验是否更新正确
|
||||
ArticleDO article = articleMapper.selectById(reqVO.getId()); // 获取最新的
|
||||
assertPojoEquals(reqVO, article);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUpdateArticle_notExists() {
|
||||
// 准备参数
|
||||
ArticleUpdateReqVO reqVO = randomPojo(ArticleUpdateReqVO.class);
|
||||
|
||||
// 调用, 并断言异常
|
||||
assertServiceException(() -> articleService.updateArticle(reqVO), ARTICLE_NOT_EXISTS);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteArticle_success() {
|
||||
// mock 数据
|
||||
ArticleDO dbArticle = randomPojo(ArticleDO.class);
|
||||
articleMapper.insert(dbArticle);// @Sql: 先插入出一条存在的数据
|
||||
// 准备参数
|
||||
Long id = dbArticle.getId();
|
||||
|
||||
// 调用
|
||||
articleService.deleteArticle(id);
|
||||
// 校验数据不存在了
|
||||
assertNull(articleMapper.selectById(id));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteArticle_notExists() {
|
||||
// 准备参数
|
||||
Long id = randomLongId();
|
||||
|
||||
// 调用, 并断言异常
|
||||
assertServiceException(() -> articleService.deleteArticle(id), ARTICLE_NOT_EXISTS);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Disabled // TODO 请修改 null 为需要的值,然后删除 @Disabled 注解
|
||||
public void testGetArticlePage() {
|
||||
// mock 数据
|
||||
ArticleDO dbArticle = randomPojo(ArticleDO.class, o -> { // 等会查询到
|
||||
o.setCategoryId(null);
|
||||
o.setTitle(null);
|
||||
o.setAuthor(null);
|
||||
o.setPicUrl(null);
|
||||
o.setIntroduction(null);
|
||||
o.setBrowseCount(null);
|
||||
o.setSort(null);
|
||||
o.setStatus(null);
|
||||
o.setSpuId(null);
|
||||
o.setRecommendHot(null);
|
||||
o.setRecommendBanner(null);
|
||||
o.setContent(null);
|
||||
o.setCreateTime(null);
|
||||
});
|
||||
articleMapper.insert(dbArticle);
|
||||
// 测试 categoryId 不匹配
|
||||
articleMapper.insert(cloneIgnoreId(dbArticle, o -> o.setCategoryId(null)));
|
||||
// 测试 title 不匹配
|
||||
articleMapper.insert(cloneIgnoreId(dbArticle, o -> o.setTitle(null)));
|
||||
// 测试 author 不匹配
|
||||
articleMapper.insert(cloneIgnoreId(dbArticle, o -> o.setAuthor(null)));
|
||||
// 测试 picUrl 不匹配
|
||||
articleMapper.insert(cloneIgnoreId(dbArticle, o -> o.setPicUrl(null)));
|
||||
// 测试 introduction 不匹配
|
||||
articleMapper.insert(cloneIgnoreId(dbArticle, o -> o.setIntroduction(null)));
|
||||
// 测试 browseCount 不匹配
|
||||
articleMapper.insert(cloneIgnoreId(dbArticle, o -> o.setBrowseCount(null)));
|
||||
// 测试 sort 不匹配
|
||||
articleMapper.insert(cloneIgnoreId(dbArticle, o -> o.setSort(null)));
|
||||
// 测试 status 不匹配
|
||||
articleMapper.insert(cloneIgnoreId(dbArticle, o -> o.setStatus(null)));
|
||||
// 测试 spuId 不匹配
|
||||
articleMapper.insert(cloneIgnoreId(dbArticle, o -> o.setSpuId(null)));
|
||||
// 测试 recommendHot 不匹配
|
||||
articleMapper.insert(cloneIgnoreId(dbArticle, o -> o.setRecommendHot(null)));
|
||||
// 测试 recommendBanner 不匹配
|
||||
articleMapper.insert(cloneIgnoreId(dbArticle, o -> o.setRecommendBanner(null)));
|
||||
// 测试 content 不匹配
|
||||
articleMapper.insert(cloneIgnoreId(dbArticle, o -> o.setContent(null)));
|
||||
// 测试 createTime 不匹配
|
||||
articleMapper.insert(cloneIgnoreId(dbArticle, o -> o.setCreateTime(null)));
|
||||
// 准备参数
|
||||
ArticlePageReqVO reqVO = new ArticlePageReqVO();
|
||||
reqVO.setCategoryId(null);
|
||||
reqVO.setTitle(null);
|
||||
reqVO.setAuthor(null);
|
||||
reqVO.setStatus(null);
|
||||
reqVO.setSpuId(null);
|
||||
reqVO.setRecommendHot(null);
|
||||
reqVO.setRecommendBanner(null);
|
||||
reqVO.setCreateTime(buildBetweenTime(2023, 2, 1, 2023, 2, 28));
|
||||
|
||||
// 调用
|
||||
PageResult<ArticleDO> pageResult = articleService.getArticlePage(reqVO);
|
||||
// 断言
|
||||
assertEquals(1, pageResult.getTotal());
|
||||
assertEquals(1, pageResult.getList().size());
|
||||
assertPojoEquals(dbArticle, pageResult.getList().get(0));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -1,198 +0,0 @@
|
|||
package cn.iocoder.yudao.module.promotion.service.combination;
|
||||
|
||||
import cn.iocoder.yudao.framework.common.pojo.PageResult;
|
||||
import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest;
|
||||
import cn.iocoder.yudao.module.promotion.controller.admin.combination.vo.activity.CombinationActivityCreateReqVO;
|
||||
import cn.iocoder.yudao.module.promotion.controller.admin.combination.vo.activity.CombinationActivityPageReqVO;
|
||||
import cn.iocoder.yudao.module.promotion.controller.admin.combination.vo.activity.CombinationActivityUpdateReqVO;
|
||||
import cn.iocoder.yudao.module.promotion.dal.dataobject.combination.CombinationActivityDO;
|
||||
import cn.iocoder.yudao.module.promotion.dal.mysql.combination.CombinationActivityMapper;
|
||||
import org.junit.jupiter.api.Disabled;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.context.annotation.Import;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomLongId;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomPojo;
|
||||
import static cn.iocoder.yudao.module.promotion.enums.ErrorCodeConstants.COMBINATION_ACTIVITY_NOT_EXISTS;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
// TODO 芋艿:等完成后,在补全单测
|
||||
/**
|
||||
* {@link CombinationActivityServiceImpl} 的单元测试类
|
||||
*
|
||||
* @author HUIHUI
|
||||
*/
|
||||
@Import(CombinationActivityServiceImpl.class)
|
||||
public class CombinationActivityServiceImplTest extends BaseDbUnitTest {
|
||||
|
||||
@Resource
|
||||
private CombinationActivityServiceImpl combinationActivityService;
|
||||
|
||||
@Resource
|
||||
private CombinationActivityMapper combinationActivityMapper;
|
||||
|
||||
@Test
|
||||
public void testCreateCombinationActivity_success() {
|
||||
// 准备参数
|
||||
CombinationActivityCreateReqVO reqVO = randomPojo(CombinationActivityCreateReqVO.class);
|
||||
|
||||
// 调用
|
||||
Long combinationActivityId = combinationActivityService.createCombinationActivity(reqVO);
|
||||
// 断言
|
||||
assertNotNull(combinationActivityId);
|
||||
// 校验记录的属性是否正确
|
||||
CombinationActivityDO combinationActivity = combinationActivityMapper.selectById(combinationActivityId);
|
||||
assertPojoEquals(reqVO, combinationActivity);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUpdateCombinationActivity_success() {
|
||||
// mock 数据
|
||||
CombinationActivityDO dbCombinationActivity = randomPojo(CombinationActivityDO.class);
|
||||
combinationActivityMapper.insert(dbCombinationActivity);// @Sql: 先插入出一条存在的数据
|
||||
// 准备参数
|
||||
CombinationActivityUpdateReqVO reqVO = randomPojo(CombinationActivityUpdateReqVO.class, o -> {
|
||||
o.setId(dbCombinationActivity.getId()); // 设置更新的 ID
|
||||
});
|
||||
|
||||
// 调用
|
||||
combinationActivityService.updateCombinationActivity(reqVO);
|
||||
// 校验是否更新正确
|
||||
CombinationActivityDO combinationActivity = combinationActivityMapper.selectById(reqVO.getId()); // 获取最新的
|
||||
assertPojoEquals(reqVO, combinationActivity);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUpdateCombinationActivity_notExists() {
|
||||
// 准备参数
|
||||
CombinationActivityUpdateReqVO reqVO = randomPojo(CombinationActivityUpdateReqVO.class);
|
||||
|
||||
// 调用, 并断言异常
|
||||
assertServiceException(() -> combinationActivityService.updateCombinationActivity(reqVO), COMBINATION_ACTIVITY_NOT_EXISTS);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteCombinationActivity_success() {
|
||||
// mock 数据
|
||||
CombinationActivityDO dbCombinationActivity = randomPojo(CombinationActivityDO.class);
|
||||
combinationActivityMapper.insert(dbCombinationActivity);// @Sql: 先插入出一条存在的数据
|
||||
// 准备参数
|
||||
Long id = dbCombinationActivity.getId();
|
||||
|
||||
// 调用
|
||||
combinationActivityService.deleteCombinationActivity(id);
|
||||
// 校验数据不存在了
|
||||
assertNull(combinationActivityMapper.selectById(id));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteCombinationActivity_notExists() {
|
||||
// 准备参数
|
||||
Long id = randomLongId();
|
||||
|
||||
// 调用, 并断言异常
|
||||
assertServiceException(() -> combinationActivityService.deleteCombinationActivity(id), COMBINATION_ACTIVITY_NOT_EXISTS);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Disabled // TODO 请修改 null 为需要的值,然后删除 @Disabled 注解
|
||||
public void testGetCombinationActivityPage() {
|
||||
// mock 数据
|
||||
CombinationActivityDO dbCombinationActivity = randomPojo(CombinationActivityDO.class, o -> { // 等会查询到
|
||||
o.setName(null);
|
||||
//o.setSpuId(null);
|
||||
o.setTotalLimitCount(null);
|
||||
o.setSingleLimitCount(null);
|
||||
o.setStartTime(null);
|
||||
o.setEndTime(null);
|
||||
o.setUserSize(null);
|
||||
o.setVirtualGroup(null);
|
||||
o.setStatus(null);
|
||||
o.setLimitDuration(null);
|
||||
o.setCreateTime(null);
|
||||
});
|
||||
combinationActivityMapper.insert(dbCombinationActivity);
|
||||
// 测试 name 不匹配
|
||||
combinationActivityMapper.insert(cloneIgnoreId(dbCombinationActivity, o -> o.setName(null)));
|
||||
// 测试 spuId 不匹配
|
||||
//combinationActivityMapper.insert(cloneIgnoreId(dbCombinationActivity, o -> o.setSpuId(null)));
|
||||
// 测试 totalLimitCount 不匹配
|
||||
combinationActivityMapper.insert(cloneIgnoreId(dbCombinationActivity, o -> o.setTotalLimitCount(null)));
|
||||
// 测试 singleLimitCount 不匹配
|
||||
combinationActivityMapper.insert(cloneIgnoreId(dbCombinationActivity, o -> o.setSingleLimitCount(null)));
|
||||
// 测试 startTime 不匹配
|
||||
combinationActivityMapper.insert(cloneIgnoreId(dbCombinationActivity, o -> o.setStartTime(null)));
|
||||
// 测试 endTime 不匹配
|
||||
combinationActivityMapper.insert(cloneIgnoreId(dbCombinationActivity, o -> o.setEndTime(null)));
|
||||
// 测试 userSize 不匹配
|
||||
combinationActivityMapper.insert(cloneIgnoreId(dbCombinationActivity, o -> o.setUserSize(null)));
|
||||
// 测试 virtualGroup 不匹配
|
||||
combinationActivityMapper.insert(cloneIgnoreId(dbCombinationActivity, o -> o.setVirtualGroup(null)));
|
||||
// 测试 status 不匹配
|
||||
combinationActivityMapper.insert(cloneIgnoreId(dbCombinationActivity, o -> o.setStatus(null)));
|
||||
// 测试 limitDuration 不匹配
|
||||
combinationActivityMapper.insert(cloneIgnoreId(dbCombinationActivity, o -> o.setLimitDuration(null)));
|
||||
// 测试 createTime 不匹配
|
||||
combinationActivityMapper.insert(cloneIgnoreId(dbCombinationActivity, o -> o.setCreateTime(null)));
|
||||
// 准备参数
|
||||
CombinationActivityPageReqVO reqVO = new CombinationActivityPageReqVO();
|
||||
reqVO.setName(null);
|
||||
reqVO.setStatus(null);
|
||||
|
||||
// 调用
|
||||
PageResult<CombinationActivityDO> pageResult = combinationActivityService.getCombinationActivityPage(reqVO);
|
||||
// 断言
|
||||
assertEquals(1, pageResult.getTotal());
|
||||
assertEquals(1, pageResult.getList().size());
|
||||
assertPojoEquals(dbCombinationActivity, pageResult.getList().get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Disabled // TODO 请修改 null 为需要的值,然后删除 @Disabled 注解
|
||||
public void testGetCombinationActivityList() {
|
||||
// mock 数据
|
||||
CombinationActivityDO dbCombinationActivity = randomPojo(CombinationActivityDO.class, o -> { // 等会查询到
|
||||
o.setName(null);
|
||||
//o.setSpuId(null);
|
||||
o.setTotalLimitCount(null);
|
||||
o.setSingleLimitCount(null);
|
||||
o.setStartTime(null);
|
||||
o.setEndTime(null);
|
||||
o.setUserSize(null);
|
||||
o.setVirtualGroup(null);
|
||||
o.setStatus(null);
|
||||
o.setLimitDuration(null);
|
||||
o.setCreateTime(null);
|
||||
});
|
||||
combinationActivityMapper.insert(dbCombinationActivity);
|
||||
// 测试 name 不匹配
|
||||
combinationActivityMapper.insert(cloneIgnoreId(dbCombinationActivity, o -> o.setName(null)));
|
||||
// 测试 spuId 不匹配
|
||||
//combinationActivityMapper.insert(cloneIgnoreId(dbCombinationActivity, o -> o.setSpuId(null)));
|
||||
// 测试 totalLimitCount 不匹配
|
||||
combinationActivityMapper.insert(cloneIgnoreId(dbCombinationActivity, o -> o.setTotalLimitCount(null)));
|
||||
// 测试 singleLimitCount 不匹配
|
||||
combinationActivityMapper.insert(cloneIgnoreId(dbCombinationActivity, o -> o.setSingleLimitCount(null)));
|
||||
// 测试 startTime 不匹配
|
||||
combinationActivityMapper.insert(cloneIgnoreId(dbCombinationActivity, o -> o.setStartTime(null)));
|
||||
// 测试 endTime 不匹配
|
||||
combinationActivityMapper.insert(cloneIgnoreId(dbCombinationActivity, o -> o.setEndTime(null)));
|
||||
// 测试 userSize 不匹配
|
||||
combinationActivityMapper.insert(cloneIgnoreId(dbCombinationActivity, o -> o.setUserSize(null)));
|
||||
// 测试 virtualGroup 不匹配
|
||||
combinationActivityMapper.insert(cloneIgnoreId(dbCombinationActivity, o -> o.setVirtualGroup(null)));
|
||||
// 测试 status 不匹配
|
||||
combinationActivityMapper.insert(cloneIgnoreId(dbCombinationActivity, o -> o.setStatus(null)));
|
||||
// 测试 limitDuration 不匹配
|
||||
combinationActivityMapper.insert(cloneIgnoreId(dbCombinationActivity, o -> o.setLimitDuration(null)));
|
||||
// 测试 createTime 不匹配
|
||||
combinationActivityMapper.insert(cloneIgnoreId(dbCombinationActivity, o -> o.setCreateTime(null)));
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -1,147 +0,0 @@
|
|||
package cn.iocoder.yudao.module.promotion.service.coupon;
|
||||
|
||||
import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
|
||||
import cn.iocoder.yudao.framework.common.pojo.PageResult;
|
||||
import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest;
|
||||
import cn.iocoder.yudao.module.promotion.controller.admin.coupon.vo.template.CouponTemplateCreateReqVO;
|
||||
import cn.iocoder.yudao.module.promotion.controller.admin.coupon.vo.template.CouponTemplatePageReqVO;
|
||||
import cn.iocoder.yudao.module.promotion.controller.admin.coupon.vo.template.CouponTemplateUpdateReqVO;
|
||||
import cn.iocoder.yudao.module.promotion.dal.dataobject.coupon.CouponTemplateDO;
|
||||
import cn.iocoder.yudao.module.promotion.dal.mysql.coupon.CouponTemplateMapper;
|
||||
import cn.iocoder.yudao.module.promotion.enums.common.PromotionDiscountTypeEnum;
|
||||
import cn.iocoder.yudao.module.promotion.enums.common.PromotionProductScopeEnum;
|
||||
import cn.iocoder.yudao.module.promotion.enums.coupon.CouponTemplateValidityTypeEnum;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.context.annotation.Import;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import static cn.hutool.core.util.RandomUtil.randomEle;
|
||||
import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildTime;
|
||||
import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomLongId;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomPojo;
|
||||
import static cn.iocoder.yudao.module.promotion.enums.ErrorCodeConstants.COUPON_TEMPLATE_NOT_EXISTS;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* {@link CouponTemplateServiceImpl} 的单元测试类
|
||||
*
|
||||
* @author 芋道源码
|
||||
*/
|
||||
@Import(CouponTemplateServiceImpl.class)
|
||||
public class CouponTemplateServiceImplTest extends BaseDbUnitTest {
|
||||
|
||||
@Resource
|
||||
private CouponTemplateServiceImpl couponTemplateService;
|
||||
|
||||
@Resource
|
||||
private CouponTemplateMapper couponTemplateMapper;
|
||||
|
||||
@Test
|
||||
public void testCreateCouponTemplate_success() {
|
||||
// 准备参数
|
||||
CouponTemplateCreateReqVO reqVO = randomPojo(CouponTemplateCreateReqVO.class,
|
||||
o -> o.setProductScope(randomEle(PromotionProductScopeEnum.values()).getScope())
|
||||
.setValidityType(randomEle(CouponTemplateValidityTypeEnum.values()).getType())
|
||||
.setDiscountType(randomEle(PromotionDiscountTypeEnum.values()).getType()));
|
||||
|
||||
// 调用
|
||||
Long couponTemplateId = couponTemplateService.createCouponTemplate(reqVO);
|
||||
// 断言
|
||||
assertNotNull(couponTemplateId);
|
||||
// 校验记录的属性是否正确
|
||||
CouponTemplateDO couponTemplate = couponTemplateMapper.selectById(couponTemplateId);
|
||||
assertPojoEquals(reqVO, couponTemplate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUpdateCouponTemplate_success() {
|
||||
// mock 数据
|
||||
CouponTemplateDO dbCouponTemplate = randomPojo(CouponTemplateDO.class);
|
||||
couponTemplateMapper.insert(dbCouponTemplate);// @Sql: 先插入出一条存在的数据
|
||||
// 准备参数
|
||||
CouponTemplateUpdateReqVO reqVO = randomPojo(CouponTemplateUpdateReqVO.class, o -> {
|
||||
o.setId(dbCouponTemplate.getId()); // 设置更新的 ID
|
||||
// 其它通用字段
|
||||
o.setProductScope(randomEle(PromotionProductScopeEnum.values()).getScope())
|
||||
.setValidityType(randomEle(CouponTemplateValidityTypeEnum.values()).getType())
|
||||
.setDiscountType(randomEle(PromotionDiscountTypeEnum.values()).getType());
|
||||
});
|
||||
|
||||
// 调用
|
||||
couponTemplateService.updateCouponTemplate(reqVO);
|
||||
// 校验是否更新正确
|
||||
CouponTemplateDO couponTemplate = couponTemplateMapper.selectById(reqVO.getId()); // 获取最新的
|
||||
assertPojoEquals(reqVO, couponTemplate);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUpdateCouponTemplate_notExists() {
|
||||
// 准备参数
|
||||
CouponTemplateUpdateReqVO reqVO = randomPojo(CouponTemplateUpdateReqVO.class);
|
||||
|
||||
// 调用, 并断言异常
|
||||
assertServiceException(() -> couponTemplateService.updateCouponTemplate(reqVO), COUPON_TEMPLATE_NOT_EXISTS);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteCouponTemplate_success() {
|
||||
// mock 数据
|
||||
CouponTemplateDO dbCouponTemplate = randomPojo(CouponTemplateDO.class);
|
||||
couponTemplateMapper.insert(dbCouponTemplate);// @Sql: 先插入出一条存在的数据
|
||||
// 准备参数
|
||||
Long id = dbCouponTemplate.getId();
|
||||
|
||||
// 调用
|
||||
couponTemplateService.deleteCouponTemplate(id);
|
||||
// 校验数据不存在了
|
||||
assertNull(couponTemplateMapper.selectById(id));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteCouponTemplate_notExists() {
|
||||
// 准备参数
|
||||
Long id = randomLongId();
|
||||
|
||||
// 调用, 并断言异常
|
||||
assertServiceException(() -> couponTemplateService.deleteCouponTemplate(id), COUPON_TEMPLATE_NOT_EXISTS);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetCouponTemplatePage() {
|
||||
// mock 数据
|
||||
CouponTemplateDO dbCouponTemplate = randomPojo(CouponTemplateDO.class, o -> { // 等会查询到
|
||||
o.setName("芋艿");
|
||||
o.setStatus(CommonStatusEnum.ENABLE.getStatus());
|
||||
o.setDiscountType(PromotionDiscountTypeEnum.PERCENT.getType());
|
||||
o.setCreateTime(buildTime(2022, 2, 2));
|
||||
});
|
||||
couponTemplateMapper.insert(dbCouponTemplate);
|
||||
// 测试 name 不匹配
|
||||
couponTemplateMapper.insert(cloneIgnoreId(dbCouponTemplate, o -> o.setName("土豆")));
|
||||
// 测试 status 不匹配
|
||||
couponTemplateMapper.insert(cloneIgnoreId(dbCouponTemplate, o -> o.setStatus(CommonStatusEnum.DISABLE.getStatus())));
|
||||
// 测试 type 不匹配
|
||||
couponTemplateMapper.insert(cloneIgnoreId(dbCouponTemplate, o -> o.setDiscountType(PromotionDiscountTypeEnum.PRICE.getType())));
|
||||
// 测试 createTime 不匹配
|
||||
couponTemplateMapper.insert(cloneIgnoreId(dbCouponTemplate, o -> o.setCreateTime(buildTime(2022, 1, 1))));
|
||||
// 准备参数
|
||||
CouponTemplatePageReqVO reqVO = new CouponTemplatePageReqVO();
|
||||
reqVO.setName("芋艿");
|
||||
reqVO.setStatus(CommonStatusEnum.ENABLE.getStatus());
|
||||
reqVO.setDiscountType(PromotionDiscountTypeEnum.PERCENT.getType());
|
||||
reqVO.setCreateTime((new LocalDateTime[]{buildTime(2022, 2, 1), buildTime(2022, 2, 3)}));
|
||||
|
||||
// 调用
|
||||
PageResult<CouponTemplateDO> pageResult = couponTemplateService.getCouponTemplatePage(reqVO);
|
||||
// 断言
|
||||
assertEquals(1, pageResult.getTotal());
|
||||
assertEquals(1, pageResult.getList().size());
|
||||
assertPojoEquals(dbCouponTemplate, pageResult.getList().get(0));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -1,36 +0,0 @@
|
|||
package cn.iocoder.yudao.module.promotion.service.decorate;
|
||||
|
||||
import cn.iocoder.yudao.framework.test.core.ut.BaseMockitoUnitTest;
|
||||
import cn.iocoder.yudao.module.promotion.dal.mysql.decorate.DecorateComponentMapper;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
|
||||
// TODO @芋艿:后续 review 下
|
||||
/**
|
||||
* @author jason
|
||||
*/
|
||||
public class DecorateComponentServiceImplTest extends BaseMockitoUnitTest {
|
||||
|
||||
@InjectMocks
|
||||
private DecorateComponentServiceImpl decoratePageService;
|
||||
|
||||
@Mock
|
||||
private DecorateComponentMapper decorateComponentMapper;
|
||||
|
||||
@BeforeEach
|
||||
public void init(){
|
||||
|
||||
}
|
||||
|
||||
// @Test
|
||||
// void testResp(){
|
||||
// List<DecorateComponentDO> list = new ArrayList<>(1);
|
||||
// DecorateComponentDO decorateDO = new DecorateComponentDO()
|
||||
// .setPage(INDEX.getPage()).setValue("")
|
||||
// .setCode(ROLLING_NEWS.getCode()).setId(1L);
|
||||
// list.add(decorateDO);
|
||||
// //mock 方法
|
||||
// Mockito.when(decorateComponentMapper.selectListByPageAndStatus(eq(1))).thenReturn(list);
|
||||
// }
|
||||
}
|
||||
|
|
@ -1,210 +0,0 @@
|
|||
package cn.iocoder.yudao.module.promotion.service.discount;
|
||||
|
||||
import cn.iocoder.yudao.framework.common.pojo.PageResult;
|
||||
import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest;
|
||||
import cn.iocoder.yudao.module.promotion.controller.admin.discount.vo.DiscountActivityBaseVO;
|
||||
import cn.iocoder.yudao.module.promotion.controller.admin.discount.vo.DiscountActivityCreateReqVO;
|
||||
import cn.iocoder.yudao.module.promotion.controller.admin.discount.vo.DiscountActivityPageReqVO;
|
||||
import cn.iocoder.yudao.module.promotion.controller.admin.discount.vo.DiscountActivityUpdateReqVO;
|
||||
import cn.iocoder.yudao.module.promotion.dal.dataobject.discount.DiscountActivityDO;
|
||||
import cn.iocoder.yudao.module.promotion.dal.dataobject.discount.DiscountProductDO;
|
||||
import cn.iocoder.yudao.module.promotion.dal.mysql.discount.DiscountActivityMapper;
|
||||
import cn.iocoder.yudao.module.promotion.dal.mysql.discount.DiscountProductMapper;
|
||||
import cn.iocoder.yudao.module.promotion.enums.common.PromotionActivityStatusEnum;
|
||||
import cn.iocoder.yudao.module.promotion.enums.common.PromotionDiscountTypeEnum;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.context.annotation.Import;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.addTime;
|
||||
import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildTime;
|
||||
import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomLongId;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomPojo;
|
||||
import static cn.iocoder.yudao.module.promotion.enums.ErrorCodeConstants.DISCOUNT_ACTIVITY_NOT_EXISTS;
|
||||
import static java.util.Arrays.asList;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* {@link DiscountActivityServiceImpl} 的单元测试类
|
||||
*
|
||||
* @author 芋道源码
|
||||
*/
|
||||
@Import(DiscountActivityServiceImpl.class)
|
||||
public class DiscountActivityServiceImplTest extends BaseDbUnitTest {
|
||||
|
||||
@Resource
|
||||
private DiscountActivityServiceImpl discountActivityService;
|
||||
|
||||
@Resource
|
||||
private DiscountActivityMapper discountActivityMapper;
|
||||
@Resource
|
||||
private DiscountProductMapper discountProductMapper;
|
||||
|
||||
@Test
|
||||
public void testCreateDiscountActivity_success() {
|
||||
// 准备参数
|
||||
DiscountActivityCreateReqVO reqVO = randomPojo(DiscountActivityCreateReqVO.class, o -> {
|
||||
// 用于触发进行中的状态
|
||||
o.setStartTime(addTime(Duration.ofDays(1))).setEndTime(addTime(Duration.ofDays(2)));
|
||||
// 设置商品
|
||||
o.setProducts(asList(new DiscountActivityBaseVO.Product().setSpuId(1L).setSkuId(2L)
|
||||
.setDiscountType(PromotionDiscountTypeEnum.PRICE.getType()).setDiscountPrice(3),
|
||||
new DiscountActivityBaseVO.Product().setSpuId(10L).setSkuId(20L)
|
||||
.setDiscountType(PromotionDiscountTypeEnum.PERCENT.getType()).setDiscountPercent(30)));
|
||||
});
|
||||
|
||||
// 调用
|
||||
Long discountActivityId = discountActivityService.createDiscountActivity(reqVO);
|
||||
// 断言
|
||||
assertNotNull(discountActivityId);
|
||||
// 校验活动
|
||||
DiscountActivityDO discountActivity = discountActivityMapper.selectById(discountActivityId);
|
||||
assertPojoEquals(reqVO, discountActivity);
|
||||
assertEquals(discountActivity.getStatus(), PromotionActivityStatusEnum.WAIT.getStatus());
|
||||
// 校验商品
|
||||
List<DiscountProductDO> discountProducts = discountProductMapper.selectList(DiscountProductDO::getActivityId, discountActivity.getId());
|
||||
assertEquals(discountProducts.size(), reqVO.getProducts().size());
|
||||
for (int i = 0; i < reqVO.getProducts().size(); i++) {
|
||||
DiscountActivityBaseVO.Product product = reqVO.getProducts().get(i);
|
||||
DiscountProductDO discountProduct = discountProducts.get(i);
|
||||
assertEquals(discountProduct.getActivityId(), discountActivity.getId());
|
||||
assertEquals(discountProduct.getSpuId(), product.getSpuId());
|
||||
assertEquals(discountProduct.getSkuId(), product.getSkuId());
|
||||
assertEquals(discountProduct.getDiscountType(), product.getDiscountType());
|
||||
assertEquals(discountProduct.getDiscountPrice(), product.getDiscountPrice());
|
||||
assertEquals(discountProduct.getDiscountPercent(), product.getDiscountPercent());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUpdateDiscountActivity_success() {
|
||||
// mock 数据(商品)
|
||||
DiscountActivityDO dbDiscountActivity = randomPojo(DiscountActivityDO.class);
|
||||
discountActivityMapper.insert(dbDiscountActivity);// @Sql: 先插入出一条存在的数据
|
||||
// mock 数据(活动)
|
||||
DiscountProductDO dbDiscountProduct01 = randomPojo(DiscountProductDO.class, o -> o.setActivityId(dbDiscountActivity.getId())
|
||||
.setSpuId(1L).setSkuId(2L).setDiscountType(PromotionDiscountTypeEnum.PRICE.getType()).setDiscountPrice(3).setDiscountPercent(null));
|
||||
DiscountProductDO dbDiscountProduct02 = randomPojo(DiscountProductDO.class, o -> o.setActivityId(dbDiscountActivity.getId())
|
||||
.setSpuId(10L).setSkuId(20L).setDiscountType(PromotionDiscountTypeEnum.PERCENT.getType()).setDiscountPercent(30).setDiscountPrice(null));
|
||||
discountProductMapper.insert(dbDiscountProduct01);
|
||||
discountProductMapper.insert(dbDiscountProduct02);
|
||||
// 准备参数
|
||||
DiscountActivityUpdateReqVO reqVO = randomPojo(DiscountActivityUpdateReqVO.class, o -> {
|
||||
o.setId(dbDiscountActivity.getId()); // 设置更新的 ID
|
||||
// 用于触发进行中的状态
|
||||
o.setStartTime(addTime(Duration.ofDays(1))).setEndTime(addTime(Duration.ofDays(2)));
|
||||
// 设置商品
|
||||
o.setProducts(asList(new DiscountActivityBaseVO.Product().setSpuId(1L).setSkuId(2L)
|
||||
.setDiscountType(PromotionDiscountTypeEnum.PRICE.getType()).setDiscountPrice(3).setDiscountPercent(null),
|
||||
new DiscountActivityBaseVO.Product().setSpuId(100L).setSkuId(200L)
|
||||
.setDiscountType(PromotionDiscountTypeEnum.PERCENT.getType()).setDiscountPercent(30).setDiscountPrice(null)));
|
||||
});
|
||||
|
||||
// 调用
|
||||
discountActivityService.updateDiscountActivity(reqVO);
|
||||
// 校验活动
|
||||
DiscountActivityDO discountActivity = discountActivityMapper.selectById(reqVO.getId()); // 获取最新的
|
||||
assertPojoEquals(reqVO, discountActivity);
|
||||
assertEquals(discountActivity.getStatus(), PromotionActivityStatusEnum.WAIT.getStatus());
|
||||
// 校验商品
|
||||
List<DiscountProductDO> discountProducts = discountProductMapper.selectList(DiscountProductDO::getActivityId, discountActivity.getId());
|
||||
assertEquals(discountProducts.size(), reqVO.getProducts().size());
|
||||
for (int i = 0; i < reqVO.getProducts().size(); i++) {
|
||||
DiscountActivityBaseVO.Product product = reqVO.getProducts().get(i);
|
||||
DiscountProductDO discountProduct = discountProducts.get(i);
|
||||
assertEquals(discountProduct.getActivityId(), discountActivity.getId());
|
||||
assertEquals(discountProduct.getSpuId(), product.getSpuId());
|
||||
assertEquals(discountProduct.getSkuId(), product.getSkuId());
|
||||
assertEquals(discountProduct.getDiscountType(), product.getDiscountType());
|
||||
assertEquals(discountProduct.getDiscountPrice(), product.getDiscountPrice());
|
||||
assertEquals(discountProduct.getDiscountPercent(), product.getDiscountPercent());
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCloseDiscountActivity() {
|
||||
// mock 数据
|
||||
DiscountActivityDO dbDiscountActivity = randomPojo(DiscountActivityDO.class,
|
||||
o -> o.setStatus(PromotionActivityStatusEnum.WAIT.getStatus()));
|
||||
discountActivityMapper.insert(dbDiscountActivity);// @Sql: 先插入出一条存在的数据
|
||||
// 准备参数
|
||||
Long id = dbDiscountActivity.getId();
|
||||
|
||||
// 调用
|
||||
discountActivityService.closeRewardActivity(id);
|
||||
// 校验状态
|
||||
DiscountActivityDO discountActivity = discountActivityMapper.selectById(id);
|
||||
assertEquals(discountActivity.getStatus(), PromotionActivityStatusEnum.CLOSE.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUpdateDiscountActivity_notExists() {
|
||||
// 准备参数
|
||||
DiscountActivityUpdateReqVO reqVO = randomPojo(DiscountActivityUpdateReqVO.class);
|
||||
|
||||
// 调用, 并断言异常
|
||||
assertServiceException(() -> discountActivityService.updateDiscountActivity(reqVO), DISCOUNT_ACTIVITY_NOT_EXISTS);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteDiscountActivity_success() {
|
||||
// mock 数据
|
||||
DiscountActivityDO dbDiscountActivity = randomPojo(DiscountActivityDO.class,
|
||||
o -> o.setStatus(PromotionActivityStatusEnum.CLOSE.getStatus()));
|
||||
discountActivityMapper.insert(dbDiscountActivity);// @Sql: 先插入出一条存在的数据
|
||||
// 准备参数
|
||||
Long id = dbDiscountActivity.getId();
|
||||
|
||||
// 调用
|
||||
discountActivityService.deleteDiscountActivity(id);
|
||||
// 校验数据不存在了
|
||||
assertNull(discountActivityMapper.selectById(id));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteDiscountActivity_notExists() {
|
||||
// 准备参数
|
||||
Long id = randomLongId();
|
||||
|
||||
// 调用, 并断言异常
|
||||
assertServiceException(() -> discountActivityService.deleteDiscountActivity(id), DISCOUNT_ACTIVITY_NOT_EXISTS);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetDiscountActivityPage() {
|
||||
// mock 数据
|
||||
DiscountActivityDO dbDiscountActivity = randomPojo(DiscountActivityDO.class, o -> { // 等会查询到
|
||||
o.setName("芋艿");
|
||||
o.setStatus(PromotionActivityStatusEnum.WAIT.getStatus());
|
||||
o.setCreateTime(buildTime(2021, 1, 15));
|
||||
});
|
||||
discountActivityMapper.insert(dbDiscountActivity);
|
||||
// 测试 name 不匹配
|
||||
discountActivityMapper.insert(cloneIgnoreId(dbDiscountActivity, o -> o.setName("土豆")));
|
||||
// 测试 status 不匹配
|
||||
discountActivityMapper.insert(cloneIgnoreId(dbDiscountActivity, o -> o.setStatus(PromotionActivityStatusEnum.END.getStatus())));
|
||||
// 测试 createTime 不匹配
|
||||
discountActivityMapper.insert(cloneIgnoreId(dbDiscountActivity, o -> o.setCreateTime(buildTime(2021, 2, 10))));
|
||||
// 准备参数
|
||||
DiscountActivityPageReqVO reqVO = new DiscountActivityPageReqVO();
|
||||
reqVO.setName("芋艿");
|
||||
reqVO.setStatus(PromotionActivityStatusEnum.WAIT.getStatus());
|
||||
reqVO.setCreateTime((new LocalDateTime[]{buildTime(2021, 1, 1), buildTime(2021, 1, 31)}));
|
||||
|
||||
// 调用
|
||||
PageResult<DiscountActivityDO> pageResult = discountActivityService.getDiscountActivityPage(reqVO);
|
||||
// 断言
|
||||
assertEquals(1, pageResult.getTotal());
|
||||
assertEquals(1, pageResult.getList().size());
|
||||
assertPojoEquals(dbDiscountActivity, pageResult.getList().get(0));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -1,218 +0,0 @@
|
|||
package cn.iocoder.yudao.module.promotion.service.reward;
|
||||
|
||||
import cn.iocoder.yudao.framework.common.pojo.PageResult;
|
||||
import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest;
|
||||
import cn.iocoder.yudao.module.promotion.controller.admin.reward.vo.RewardActivityCreateReqVO;
|
||||
import cn.iocoder.yudao.module.promotion.controller.admin.reward.vo.RewardActivityPageReqVO;
|
||||
import cn.iocoder.yudao.module.promotion.controller.admin.reward.vo.RewardActivityUpdateReqVO;
|
||||
import cn.iocoder.yudao.module.promotion.dal.dataobject.reward.RewardActivityDO;
|
||||
import cn.iocoder.yudao.module.promotion.dal.mysql.reward.RewardActivityMapper;
|
||||
import cn.iocoder.yudao.module.promotion.enums.common.PromotionActivityStatusEnum;
|
||||
import cn.iocoder.yudao.module.promotion.enums.common.PromotionConditionTypeEnum;
|
||||
import cn.iocoder.yudao.module.promotion.enums.common.PromotionProductScopeEnum;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.context.annotation.Import;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.time.Duration;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import static cn.hutool.core.util.RandomUtil.randomEle;
|
||||
import static cn.iocoder.yudao.framework.common.util.collection.SetUtils.asSet;
|
||||
import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.addTime;
|
||||
import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomLongId;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomPojo;
|
||||
import static cn.iocoder.yudao.module.promotion.enums.ErrorCodeConstants.REWARD_ACTIVITY_NOT_EXISTS;
|
||||
import static java.util.Arrays.asList;
|
||||
import static java.util.Collections.singletonList;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* {@link RewardActivityServiceImpl} 的单元测试类
|
||||
*
|
||||
* @author 芋道源码
|
||||
*/
|
||||
@Import(RewardActivityServiceImpl.class)
|
||||
public class RewardActivityServiceImplTest extends BaseDbUnitTest {
|
||||
|
||||
@Resource
|
||||
private RewardActivityServiceImpl rewardActivityService;
|
||||
|
||||
@Resource
|
||||
private RewardActivityMapper rewardActivityMapper;
|
||||
|
||||
@Test
|
||||
public void testCreateRewardActivity_success() {
|
||||
// 准备参数
|
||||
RewardActivityCreateReqVO reqVO = randomPojo(RewardActivityCreateReqVO.class, o -> {
|
||||
o.setConditionType(randomEle(PromotionConditionTypeEnum.values()).getType());
|
||||
o.setProductScope(randomEle(PromotionProductScopeEnum.values()).getScope());
|
||||
// 用于触发进行中的状态
|
||||
o.setStartTime(addTime(Duration.ofDays(1))).setEndTime(addTime(Duration.ofDays(2)));
|
||||
});
|
||||
|
||||
// 调用
|
||||
Long rewardActivityId = rewardActivityService.createRewardActivity(reqVO);
|
||||
// 断言
|
||||
assertNotNull(rewardActivityId);
|
||||
// 校验记录的属性是否正确
|
||||
RewardActivityDO rewardActivity = rewardActivityMapper.selectById(rewardActivityId);
|
||||
assertPojoEquals(reqVO, rewardActivity, "rules");
|
||||
assertEquals(rewardActivity.getStatus(), PromotionActivityStatusEnum.WAIT.getStatus());
|
||||
for (int i = 0; i < reqVO.getRules().size(); i++) {
|
||||
assertPojoEquals(reqVO.getRules().get(i), rewardActivity.getRules().get(i));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUpdateRewardActivity_success() {
|
||||
// mock 数据
|
||||
RewardActivityDO dbRewardActivity = randomPojo(RewardActivityDO.class, o -> o.setStatus(PromotionActivityStatusEnum.WAIT.getStatus()));
|
||||
rewardActivityMapper.insert(dbRewardActivity);// @Sql: 先插入出一条存在的数据
|
||||
// 准备参数
|
||||
RewardActivityUpdateReqVO reqVO = randomPojo(RewardActivityUpdateReqVO.class, o -> {
|
||||
o.setId(dbRewardActivity.getId()); // 设置更新的 ID
|
||||
o.setConditionType(randomEle(PromotionConditionTypeEnum.values()).getType());
|
||||
o.setProductScope(randomEle(PromotionProductScopeEnum.values()).getScope());
|
||||
// 用于触发进行中的状态
|
||||
o.setStartTime(addTime(Duration.ofDays(1))).setEndTime(addTime(Duration.ofDays(2)));
|
||||
});
|
||||
|
||||
// 调用
|
||||
rewardActivityService.updateRewardActivity(reqVO);
|
||||
// 校验是否更新正确
|
||||
RewardActivityDO rewardActivity = rewardActivityMapper.selectById(reqVO.getId()); // 获取最新的
|
||||
assertPojoEquals(reqVO, rewardActivity, "rules");
|
||||
assertEquals(rewardActivity.getStatus(), PromotionActivityStatusEnum.WAIT.getStatus());
|
||||
for (int i = 0; i < reqVO.getRules().size(); i++) {
|
||||
assertPojoEquals(reqVO.getRules().get(i), rewardActivity.getRules().get(i));
|
||||
}
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCloseRewardActivity() {
|
||||
// mock 数据
|
||||
RewardActivityDO dbRewardActivity = randomPojo(RewardActivityDO.class, o -> o.setStatus(PromotionActivityStatusEnum.WAIT.getStatus()));
|
||||
rewardActivityMapper.insert(dbRewardActivity);// @Sql: 先插入出一条存在的数据
|
||||
// 准备参数
|
||||
Long id = dbRewardActivity.getId();
|
||||
|
||||
// 调用
|
||||
rewardActivityService.closeRewardActivity(id);
|
||||
// 校验状态
|
||||
RewardActivityDO rewardActivity = rewardActivityMapper.selectById(id);
|
||||
assertEquals(rewardActivity.getStatus(), PromotionActivityStatusEnum.CLOSE.getStatus());
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUpdateRewardActivity_notExists() {
|
||||
// 准备参数
|
||||
RewardActivityUpdateReqVO reqVO = randomPojo(RewardActivityUpdateReqVO.class);
|
||||
|
||||
// 调用, 并断言异常
|
||||
assertServiceException(() -> rewardActivityService.updateRewardActivity(reqVO), REWARD_ACTIVITY_NOT_EXISTS);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteRewardActivity_success() {
|
||||
// mock 数据
|
||||
RewardActivityDO dbRewardActivity = randomPojo(RewardActivityDO.class, o -> o.setStatus(PromotionActivityStatusEnum.CLOSE.getStatus()));
|
||||
rewardActivityMapper.insert(dbRewardActivity);// @Sql: 先插入出一条存在的数据
|
||||
// 准备参数
|
||||
Long id = dbRewardActivity.getId();
|
||||
|
||||
// 调用
|
||||
rewardActivityService.deleteRewardActivity(id);
|
||||
// 校验数据不存在了
|
||||
assertNull(rewardActivityMapper.selectById(id));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteRewardActivity_notExists() {
|
||||
// 准备参数
|
||||
Long id = randomLongId();
|
||||
|
||||
// 调用, 并断言异常
|
||||
assertServiceException(() -> rewardActivityService.deleteRewardActivity(id), REWARD_ACTIVITY_NOT_EXISTS);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetRewardActivityPage() {
|
||||
// mock 数据
|
||||
RewardActivityDO dbRewardActivity = randomPojo(RewardActivityDO.class, o -> { // 等会查询到
|
||||
o.setName("芋艿");
|
||||
o.setStatus(PromotionActivityStatusEnum.CLOSE.getStatus());
|
||||
});
|
||||
rewardActivityMapper.insert(dbRewardActivity);
|
||||
// 测试 name 不匹配
|
||||
rewardActivityMapper.insert(cloneIgnoreId(dbRewardActivity, o -> o.setName("土豆")));
|
||||
// 测试 status 不匹配
|
||||
rewardActivityMapper.insert(cloneIgnoreId(dbRewardActivity, o -> o.setStatus(PromotionActivityStatusEnum.RUN.getStatus())));
|
||||
// 准备参数
|
||||
RewardActivityPageReqVO reqVO = new RewardActivityPageReqVO();
|
||||
reqVO.setName("芋艿");
|
||||
reqVO.setStatus(PromotionActivityStatusEnum.CLOSE.getStatus());
|
||||
|
||||
// 调用
|
||||
PageResult<RewardActivityDO> pageResult = rewardActivityService.getRewardActivityPage(reqVO);
|
||||
// 断言
|
||||
assertEquals(1, pageResult.getTotal());
|
||||
assertEquals(1, pageResult.getList().size());
|
||||
assertPojoEquals(dbRewardActivity, pageResult.getList().get(0), "rules");
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetRewardActivities_all() {
|
||||
// mock 数据
|
||||
RewardActivityDO allActivity = randomPojo(RewardActivityDO.class, o -> o.setStatus(PromotionActivityStatusEnum.RUN.getStatus())
|
||||
.setProductScope(PromotionProductScopeEnum.ALL.getScope()));
|
||||
rewardActivityMapper.insert(allActivity);
|
||||
RewardActivityDO productActivity = randomPojo(RewardActivityDO.class, o -> o.setStatus(PromotionActivityStatusEnum.RUN.getStatus())
|
||||
.setProductScope(PromotionProductScopeEnum.SPU.getScope()).setProductSpuIds(asList(1L, 2L)));
|
||||
rewardActivityMapper.insert(productActivity);
|
||||
// 准备参数
|
||||
Set<Long> spuIds = asSet(1L, 2L);
|
||||
|
||||
// 调用 TODO getMatchRewardActivities 没有这个方法,但是找到了 getMatchRewardActivityList
|
||||
//Map<RewardActivityDO, Set<Long>> matchRewardActivities = rewardActivityService.getMatchRewardActivities(spuIds);
|
||||
// 断言
|
||||
//assertEquals(matchRewardActivities.size(), 1);
|
||||
//Map.Entry<RewardActivityDO, Set<Long>> next = matchRewardActivities.entrySet().iterator().next();
|
||||
//assertPojoEquals(next.getKey(), allActivity);
|
||||
//assertEquals(next.getValue(), spuIds);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testGetRewardActivities_product() {
|
||||
// mock 数据
|
||||
RewardActivityDO productActivity01 = randomPojo(RewardActivityDO.class, o -> o.setStatus(PromotionActivityStatusEnum.RUN.getStatus())
|
||||
.setProductScope(PromotionProductScopeEnum.SPU.getScope()).setProductSpuIds(asList(1L, 2L)));
|
||||
rewardActivityMapper.insert(productActivity01);
|
||||
RewardActivityDO productActivity02 = randomPojo(RewardActivityDO.class, o -> o.setStatus(PromotionActivityStatusEnum.RUN.getStatus())
|
||||
.setProductScope(PromotionProductScopeEnum.SPU.getScope()).setProductSpuIds(singletonList(3L)));
|
||||
rewardActivityMapper.insert(productActivity02);
|
||||
// 准备参数
|
||||
Set<Long> spuIds = asSet(1L, 2L, 3L);
|
||||
|
||||
// 调用 TODO getMatchRewardActivities 没有这个方法,但是找到了 getMatchRewardActivityList
|
||||
//Map<RewardActivityDO, Set<Long>> matchRewardActivities = rewardActivityService.getMatchRewardActivities(spuIds);
|
||||
// 断言
|
||||
//assertEquals(matchRewardActivities.size(), 2);
|
||||
//matchRewardActivities.forEach((activity, activitySpuIds) -> {
|
||||
// if (activity.getId().equals(productActivity01.getId())) {
|
||||
// assertPojoEquals(activity, productActivity01);
|
||||
// assertEquals(activitySpuIds, asSet(1L, 2L));
|
||||
// } else if (activity.getId().equals(productActivity02.getId())) {
|
||||
// assertPojoEquals(activity, productActivity02);
|
||||
// assertEquals(activitySpuIds, asSet(3L));
|
||||
// } else {
|
||||
// fail();
|
||||
// }
|
||||
//});
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -1,171 +0,0 @@
|
|||
package cn.iocoder.yudao.module.promotion.service.seckillactivity;
|
||||
|
||||
import cn.iocoder.yudao.framework.common.pojo.PageResult;
|
||||
import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest;
|
||||
import cn.iocoder.yudao.module.promotion.controller.admin.seckill.vo.activity.SeckillActivityCreateReqVO;
|
||||
import cn.iocoder.yudao.module.promotion.controller.admin.seckill.vo.activity.SeckillActivityPageReqVO;
|
||||
import cn.iocoder.yudao.module.promotion.controller.admin.seckill.vo.activity.SeckillActivityUpdateReqVO;
|
||||
import cn.iocoder.yudao.module.promotion.dal.dataobject.seckill.SeckillActivityDO;
|
||||
import cn.iocoder.yudao.module.promotion.dal.mysql.seckill.seckillactivity.SeckillActivityMapper;
|
||||
import cn.iocoder.yudao.module.promotion.service.seckill.SeckillActivityServiceImpl;
|
||||
import org.junit.jupiter.api.Disabled;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.context.annotation.Import;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomLongId;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomPojo;
|
||||
import static cn.iocoder.yudao.module.promotion.enums.ErrorCodeConstants.SECKILL_ACTIVITY_NOT_EXISTS;
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
/**
|
||||
* {@link SeckillActivityServiceImpl} 的单元测试类
|
||||
*
|
||||
* @author 芋道源码
|
||||
*/
|
||||
@Import(SeckillActivityServiceImpl.class)
|
||||
@Disabled // TODO 芋艿:未来开启
|
||||
public class SeckillActivityServiceImplTest extends BaseDbUnitTest {
|
||||
|
||||
@Resource
|
||||
private SeckillActivityServiceImpl seckillActivityService;
|
||||
|
||||
@Resource
|
||||
private SeckillActivityMapper seckillActivityMapper;
|
||||
|
||||
@Test
|
||||
public void testCreateSeckillActivity_success() {
|
||||
// 准备参数
|
||||
SeckillActivityCreateReqVO reqVO = randomPojo(SeckillActivityCreateReqVO.class);
|
||||
|
||||
// 调用
|
||||
Long seckillActivityId = seckillActivityService.createSeckillActivity(reqVO);
|
||||
// 断言
|
||||
assertNotNull(seckillActivityId);
|
||||
// 校验记录的属性是否正确
|
||||
SeckillActivityDO seckillActivity = seckillActivityMapper.selectById(seckillActivityId);
|
||||
assertPojoEquals(reqVO, seckillActivity);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUpdateSeckillActivity_success() {
|
||||
// mock 数据
|
||||
SeckillActivityDO dbSeckillActivity = randomPojo(SeckillActivityDO.class);
|
||||
seckillActivityMapper.insert(dbSeckillActivity);// @Sql: 先插入出一条存在的数据
|
||||
// 准备参数
|
||||
SeckillActivityUpdateReqVO reqVO = randomPojo(SeckillActivityUpdateReqVO.class, o -> {
|
||||
o.setId(dbSeckillActivity.getId()); // 设置更新的 ID
|
||||
});
|
||||
|
||||
// 调用
|
||||
seckillActivityService.updateSeckillActivity(reqVO);
|
||||
// 校验是否更新正确
|
||||
SeckillActivityDO seckillActivity = seckillActivityMapper.selectById(reqVO.getId()); // 获取最新的
|
||||
assertPojoEquals(reqVO, seckillActivity);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUpdateSeckillActivity_notExists() {
|
||||
// 准备参数
|
||||
SeckillActivityUpdateReqVO reqVO = randomPojo(SeckillActivityUpdateReqVO.class);
|
||||
|
||||
// 调用, 并断言异常
|
||||
assertServiceException(() -> seckillActivityService.updateSeckillActivity(reqVO), SECKILL_ACTIVITY_NOT_EXISTS);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteSeckillActivity_success() {
|
||||
// mock 数据
|
||||
SeckillActivityDO dbSeckillActivity = randomPojo(SeckillActivityDO.class);
|
||||
seckillActivityMapper.insert(dbSeckillActivity);// @Sql: 先插入出一条存在的数据
|
||||
// 准备参数
|
||||
Long id = dbSeckillActivity.getId();
|
||||
|
||||
// 调用
|
||||
seckillActivityService.deleteSeckillActivity(id);
|
||||
// 校验数据不存在了
|
||||
assertNull(seckillActivityMapper.selectById(id));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteSeckillActivity_notExists() {
|
||||
// 准备参数
|
||||
Long id = randomLongId();
|
||||
|
||||
// 调用, 并断言异常
|
||||
assertServiceException(() -> seckillActivityService.deleteSeckillActivity(id), SECKILL_ACTIVITY_NOT_EXISTS);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Disabled // TODO 请修改 null 为需要的值,然后删除 @Disabled 注解
|
||||
public void testGetSeckillActivityPage() {
|
||||
// mock 数据
|
||||
SeckillActivityDO dbSeckillActivity = randomPojo(SeckillActivityDO.class, o -> { // 等会查询到
|
||||
o.setName(null);
|
||||
o.setStatus(null);
|
||||
o.setConfigIds(null);
|
||||
o.setCreateTime(null);
|
||||
});
|
||||
seckillActivityMapper.insert(dbSeckillActivity);
|
||||
// 测试 name 不匹配
|
||||
seckillActivityMapper.insert(cloneIgnoreId(dbSeckillActivity, o -> o.setName(null)));
|
||||
// 测试 status 不匹配
|
||||
seckillActivityMapper.insert(cloneIgnoreId(dbSeckillActivity, o -> o.setStatus(null)));
|
||||
// 测试 timeId 不匹配
|
||||
seckillActivityMapper.insert(cloneIgnoreId(dbSeckillActivity, o -> o.setConfigIds(null)));
|
||||
// 测试 createTime 不匹配
|
||||
seckillActivityMapper.insert(cloneIgnoreId(dbSeckillActivity, o -> o.setCreateTime(null)));
|
||||
// 准备参数
|
||||
SeckillActivityPageReqVO reqVO = new SeckillActivityPageReqVO();
|
||||
reqVO.setName(null);
|
||||
reqVO.setStatus(null);
|
||||
reqVO.setConfigId(null);
|
||||
reqVO.setCreateTime((new LocalDateTime[]{}));
|
||||
|
||||
// 调用
|
||||
PageResult<SeckillActivityDO> pageResult = seckillActivityService.getSeckillActivityPage(reqVO);
|
||||
// 断言
|
||||
assertEquals(1, pageResult.getTotal());
|
||||
assertEquals(1, pageResult.getList().size());
|
||||
assertPojoEquals(dbSeckillActivity, pageResult.getList().get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Disabled // TODO 请修改 null 为需要的值,然后删除 @Disabled 注解
|
||||
public void testGetSeckillActivityList() {
|
||||
// mock 数据
|
||||
SeckillActivityDO dbSeckillActivity = randomPojo(SeckillActivityDO.class, o -> { // 等会查询到
|
||||
o.setName(null);
|
||||
o.setStatus(null);
|
||||
o.setConfigIds(null);
|
||||
o.setCreateTime(null);
|
||||
});
|
||||
seckillActivityMapper.insert(dbSeckillActivity);
|
||||
// 测试 name 不匹配
|
||||
seckillActivityMapper.insert(cloneIgnoreId(dbSeckillActivity, o -> o.setName(null)));
|
||||
// 测试 status 不匹配
|
||||
seckillActivityMapper.insert(cloneIgnoreId(dbSeckillActivity, o -> o.setStatus(null)));
|
||||
// 测试 timeId 不匹配
|
||||
seckillActivityMapper.insert(cloneIgnoreId(dbSeckillActivity, o -> o.setConfigIds(null)));
|
||||
// 测试 createTime 不匹配
|
||||
seckillActivityMapper.insert(cloneIgnoreId(dbSeckillActivity, o -> o.setCreateTime(null)));
|
||||
// 准备参数
|
||||
// SeckillActivityExportReqVO reqVO = new SeckillActivityExportReqVO();
|
||||
// reqVO.setName(null);
|
||||
// reqVO.setStatus(null);
|
||||
// reqVO.setTimeId(null);
|
||||
// reqVO.setCreateTime((new Date[]{}));
|
||||
//
|
||||
// // 调用
|
||||
// List<SeckillActivityDO> list = seckillActivityService.getSeckillActivityList(reqVO);
|
||||
// // 断言
|
||||
// assertEquals(1, list.size());
|
||||
// assertPojoEquals(dbSeckillActivity, list.get(0));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -1,190 +0,0 @@
|
|||
package cn.iocoder.yudao.module.promotion.service.seckillconfig;
|
||||
|
||||
import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest;
|
||||
import cn.iocoder.yudao.module.promotion.controller.admin.seckill.vo.config.SeckillConfigCreateReqVO;
|
||||
import cn.iocoder.yudao.module.promotion.controller.admin.seckill.vo.config.SeckillConfigUpdateReqVO;
|
||||
import cn.iocoder.yudao.module.promotion.dal.dataobject.seckill.SeckillConfigDO;
|
||||
import cn.iocoder.yudao.module.promotion.dal.mysql.seckill.seckillconfig.SeckillConfigMapper;
|
||||
import cn.iocoder.yudao.module.promotion.service.seckill.SeckillConfigServiceImpl;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import org.junit.jupiter.api.Disabled;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.context.annotation.Import;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
|
||||
import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertPojoEquals;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.AssertUtils.assertServiceException;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomLongId;
|
||||
import static cn.iocoder.yudao.framework.test.core.util.RandomUtils.randomPojo;
|
||||
import static cn.iocoder.yudao.module.promotion.enums.ErrorCodeConstants.SECKILL_CONFIG_NOT_EXISTS;
|
||||
import static org.junit.jupiter.api.Assertions.assertNotNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
|
||||
/**
|
||||
* {@link SeckillConfigServiceImpl} 的单元测试类
|
||||
*
|
||||
* @author 芋道源码
|
||||
*/
|
||||
@Import(SeckillConfigServiceImpl.class)
|
||||
@Disabled // TODO 芋艿:未来开启;后续要 review 下
|
||||
public class SeckillConfigServiceImplTest extends BaseDbUnitTest {
|
||||
|
||||
@Resource
|
||||
private SeckillConfigServiceImpl SeckillConfigService;
|
||||
|
||||
@Resource
|
||||
private SeckillConfigMapper seckillConfigMapper;
|
||||
|
||||
@Resource
|
||||
private ObjectMapper objectMapper;
|
||||
|
||||
@Test
|
||||
public void testJacksonSerializ() {
|
||||
|
||||
// 准备参数
|
||||
SeckillConfigCreateReqVO reqVO = randomPojo(SeckillConfigCreateReqVO.class);
|
||||
// ObjectMapper objectMapper = new ObjectMapper();
|
||||
try {
|
||||
String string = objectMapper.writeValueAsString(reqVO);
|
||||
System.out.println(string);
|
||||
} catch (JsonProcessingException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testCreateSeckillConfig_success() {
|
||||
// 准备参数
|
||||
SeckillConfigCreateReqVO reqVO = randomPojo(SeckillConfigCreateReqVO.class);
|
||||
|
||||
// 调用
|
||||
Long SeckillConfigId = SeckillConfigService.createSeckillConfig(reqVO);
|
||||
// 断言
|
||||
assertNotNull(SeckillConfigId);
|
||||
// 校验记录的属性是否正确
|
||||
SeckillConfigDO SeckillConfig = seckillConfigMapper.selectById(SeckillConfigId);
|
||||
assertPojoEquals(reqVO, SeckillConfig);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUpdateSeckillConfig_success() {
|
||||
// mock 数据
|
||||
SeckillConfigDO dbSeckillConfig = randomPojo(SeckillConfigDO.class);
|
||||
seckillConfigMapper.insert(dbSeckillConfig);// @Sql: 先插入出一条存在的数据
|
||||
// 准备参数
|
||||
SeckillConfigUpdateReqVO reqVO = randomPojo(SeckillConfigUpdateReqVO.class, o -> {
|
||||
o.setId(dbSeckillConfig.getId()); // 设置更新的 ID
|
||||
});
|
||||
|
||||
// 调用
|
||||
SeckillConfigService.updateSeckillConfig(reqVO);
|
||||
// 校验是否更新正确
|
||||
SeckillConfigDO SeckillConfig = seckillConfigMapper.selectById(reqVO.getId()); // 获取最新的
|
||||
assertPojoEquals(reqVO, SeckillConfig);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testUpdateSeckillConfig_notExists() {
|
||||
// 准备参数
|
||||
SeckillConfigUpdateReqVO reqVO = randomPojo(SeckillConfigUpdateReqVO.class);
|
||||
|
||||
// 调用, 并断言异常
|
||||
assertServiceException(() -> SeckillConfigService.updateSeckillConfig(reqVO), SECKILL_CONFIG_NOT_EXISTS);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteSeckillConfig_success() {
|
||||
// mock 数据
|
||||
SeckillConfigDO dbSeckillConfig = randomPojo(SeckillConfigDO.class);
|
||||
seckillConfigMapper.insert(dbSeckillConfig);// @Sql: 先插入出一条存在的数据
|
||||
// 准备参数
|
||||
Long id = dbSeckillConfig.getId();
|
||||
|
||||
// 调用
|
||||
SeckillConfigService.deleteSeckillConfig(id);
|
||||
// 校验数据不存在了
|
||||
assertNull(seckillConfigMapper.selectById(id));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testDeleteSeckillConfig_notExists() {
|
||||
// 准备参数
|
||||
Long id = randomLongId();
|
||||
|
||||
// 调用, 并断言异常
|
||||
assertServiceException(() -> SeckillConfigService.deleteSeckillConfig(id), SECKILL_CONFIG_NOT_EXISTS);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Disabled // TODO 请修改 null 为需要的值,然后删除 @Disabled 注解
|
||||
public void testGetSeckillConfigPage() {
|
||||
// mock 数据
|
||||
// SeckillConfigDO dbSeckillConfig = randomPojo(SeckillConfigDO.class, o -> { // 等会查询到
|
||||
// o.setName(null);
|
||||
// o.setStartTime(null);
|
||||
// o.setEndTime(null);
|
||||
// o.setCreateTime(null);
|
||||
// });
|
||||
// seckillConfigMapper.insert(dbSeckillConfig);
|
||||
// // 测试 name 不匹配
|
||||
// seckillConfigMapper.insert(cloneIgnoreId(dbSeckillConfig, o -> o.setName(null)));
|
||||
// // 测试 startTime 不匹配
|
||||
// seckillConfigMapper.insert(cloneIgnoreId(dbSeckillConfig, o -> o.setStartTime(null)));
|
||||
// // 测试 endTime 不匹配
|
||||
// seckillConfigMapper.insert(cloneIgnoreId(dbSeckillConfig, o -> o.setEndTime(null)));
|
||||
// // 测试 createTime 不匹配
|
||||
// seckillConfigMapper.insert(cloneIgnoreId(dbSeckillConfig, o -> o.setCreateTime(null)));
|
||||
// // 准备参数
|
||||
// SeckillConfigPageReqVO reqVO = new SeckillConfigPageReqVO();
|
||||
// reqVO.setName(null);
|
||||
//// reqVO.setStartTime((new LocalTime()));
|
||||
//// reqVO.setEndTime((new LocalTime[]{}));
|
||||
//// reqVO.setCreateTime((new Date[]{}));
|
||||
//
|
||||
// // 调用
|
||||
// PageResult<SeckillConfigDO> pageResult = SeckillConfigService.getSeckillConfigPage(reqVO);
|
||||
// // 断言
|
||||
// assertEquals(1, pageResult.getTotal());
|
||||
// assertEquals(1, pageResult.getList().size());
|
||||
// assertPojoEquals(dbSeckillConfig, pageResult.getList().get(0));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Disabled // TODO 请修改 null 为需要的值,然后删除 @Disabled 注解
|
||||
public void testGetSeckillConfigList() {
|
||||
// mock 数据
|
||||
SeckillConfigDO dbSeckillConfig = randomPojo(SeckillConfigDO.class, o -> { // 等会查询到
|
||||
o.setName(null);
|
||||
o.setStartTime(null);
|
||||
o.setEndTime(null);
|
||||
o.setCreateTime(null);
|
||||
});
|
||||
seckillConfigMapper.insert(dbSeckillConfig);
|
||||
// 测试 name 不匹配
|
||||
seckillConfigMapper.insert(cloneIgnoreId(dbSeckillConfig, o -> o.setName(null)));
|
||||
// 测试 startTime 不匹配
|
||||
seckillConfigMapper.insert(cloneIgnoreId(dbSeckillConfig, o -> o.setStartTime(null)));
|
||||
// 测试 endTime 不匹配
|
||||
seckillConfigMapper.insert(cloneIgnoreId(dbSeckillConfig, o -> o.setEndTime(null)));
|
||||
// 测试 createTime 不匹配
|
||||
seckillConfigMapper.insert(cloneIgnoreId(dbSeckillConfig, o -> o.setCreateTime(null)));
|
||||
// 准备参数
|
||||
// SeckillConfigExportReqVO reqVO = new SeckillConfigExportReqVO();
|
||||
// reqVO.setName(null);
|
||||
// reqVO.setStartTime((new LocalTime[]{}));
|
||||
// reqVO.setEndTime((new LocalTime[]{}));
|
||||
// reqVO.setCreateTime((new Date[]{}));
|
||||
//
|
||||
// // 调用
|
||||
// List<SeckillConfigDO> list = SeckillConfigService.getSeckillConfigList(reqVO);
|
||||
// // 断言
|
||||
// assertEquals(1, list.size());
|
||||
// assertPojoEquals(dbSeckillConfig, list.get(0));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,47 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<parent>
|
||||
<groupId>cn.iocoder.cloud</groupId>
|
||||
<artifactId>yudao-module-mall</artifactId>
|
||||
<version>${revision}</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>yudao-module-statistics-api</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>${project.artifactId}</name>
|
||||
<description>
|
||||
statistics 模块 API,暴露给其它模块调用
|
||||
</description>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>cn.iocoder.cloud</groupId>
|
||||
<artifactId>yudao-common</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Web 相关 -->
|
||||
<dependency>
|
||||
<groupId>org.springdoc</groupId>
|
||||
<artifactId>springdoc-openapi-ui</artifactId>
|
||||
<scope>provided</scope>
|
||||
</dependency>
|
||||
|
||||
<!-- 参数校验 -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-validation</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
|
||||
<!-- RPC 远程调用相关 -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-openfeign</artifactId>
|
||||
<optional>true</optional>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
/**
|
||||
* TODO 占位,无特殊含义
|
||||
*/
|
||||
package cn.iocoder.yudao.module.statistics.api;
|
||||
|
|
@ -0,0 +1,48 @@
|
|||
package cn.iocoder.yudao.module.statistics.enums;
|
||||
|
||||
import cn.iocoder.yudao.framework.common.core.IntArrayValuable;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Getter;
|
||||
|
||||
import java.util.Arrays;
|
||||
|
||||
/**
|
||||
* 时间范围类型的枚举
|
||||
*
|
||||
* @author owen
|
||||
*/
|
||||
@AllArgsConstructor
|
||||
@Getter
|
||||
public enum TimeRangeTypeEnum implements IntArrayValuable {
|
||||
|
||||
/**
|
||||
* 天
|
||||
*/
|
||||
DAY(1),
|
||||
/**
|
||||
* 周
|
||||
*/
|
||||
WEEK(7),
|
||||
/**
|
||||
* 月
|
||||
*/
|
||||
MONTH(30),
|
||||
/**
|
||||
* 年
|
||||
*/
|
||||
YEAR(365),
|
||||
;
|
||||
|
||||
public static final int[] ARRAYS = Arrays.stream(values()).mapToInt(TimeRangeTypeEnum::getType).toArray();
|
||||
|
||||
/**
|
||||
* 类型
|
||||
*/
|
||||
private final Integer type;
|
||||
|
||||
@Override
|
||||
public int[] array() {
|
||||
return ARRAYS;
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,4 @@
|
|||
/**
|
||||
* TODO 占位,无特殊含义
|
||||
*/
|
||||
package cn.iocoder.yudao.module.statistics.enums;
|
||||
|
|
@ -0,0 +1,141 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<parent>
|
||||
<groupId>cn.iocoder.cloud</groupId>
|
||||
<artifactId>yudao-module-mall</artifactId>
|
||||
<version>${revision}</version>
|
||||
</parent>
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<artifactId>yudao-module-statistics-biz</artifactId>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>${project.artifactId}</name>
|
||||
<description>
|
||||
statistics 模块,主要实现统计相关功能
|
||||
例如:统计商品、会员、交易等功能。
|
||||
</description>
|
||||
|
||||
<dependencies>
|
||||
<!-- Spring Cloud 基础 -->
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-bootstrap</artifactId>
|
||||
</dependency>
|
||||
|
||||
<dependency>
|
||||
<groupId>cn.iocoder.cloud</groupId>
|
||||
<artifactId>yudao-spring-boot-starter-env</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- 依赖服务 -->
|
||||
<dependency>
|
||||
<groupId>cn.iocoder.cloud</groupId>
|
||||
<artifactId>yudao-module-statistics-api</artifactId>
|
||||
<version>${revision}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>cn.iocoder.cloud</groupId>
|
||||
<artifactId>yudao-module-promotion-api</artifactId>
|
||||
<version>${revision}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>cn.iocoder.cloud</groupId>
|
||||
<artifactId>yudao-module-product-api</artifactId>
|
||||
<version>${revision}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>cn.iocoder.cloud</groupId>
|
||||
<artifactId>yudao-module-trade-api</artifactId>
|
||||
<version>${revision}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>cn.iocoder.cloud</groupId>
|
||||
<artifactId>yudao-module-member-api</artifactId>
|
||||
<version>${revision}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>cn.iocoder.cloud</groupId>
|
||||
<artifactId>yudao-module-pay-api</artifactId>
|
||||
<version>${revision}</version>
|
||||
</dependency>
|
||||
|
||||
<!-- 业务组件 -->
|
||||
<dependency>
|
||||
<groupId>cn.iocoder.cloud</groupId>
|
||||
<artifactId>yudao-spring-boot-starter-biz-operatelog</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>cn.iocoder.cloud</groupId>
|
||||
<artifactId>yudao-spring-boot-starter-biz-tenant</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>cn.iocoder.cloud</groupId>
|
||||
<artifactId>yudao-spring-boot-starter-biz-ip</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Web 相关 -->
|
||||
<dependency>
|
||||
<groupId>cn.iocoder.cloud</groupId>
|
||||
<artifactId>yudao-spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>cn.iocoder.cloud</groupId>
|
||||
<artifactId>yudao-spring-boot-starter-security</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- DB 相关 -->
|
||||
<dependency>
|
||||
<groupId>cn.iocoder.cloud</groupId>
|
||||
<artifactId>yudao-spring-boot-starter-mybatis</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- RPC 远程调用相关 -->
|
||||
<dependency>
|
||||
<groupId>cn.iocoder.cloud</groupId>
|
||||
<artifactId>yudao-spring-boot-starter-rpc</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Registry 注册中心相关 -->
|
||||
<dependency>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Config 配置中心相关 -->
|
||||
<dependency>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Job 定时任务相关 -->
|
||||
<dependency>
|
||||
<groupId>cn.iocoder.cloud</groupId>
|
||||
<artifactId>yudao-spring-boot-starter-job</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- Test 测试相关 -->
|
||||
<dependency>
|
||||
<groupId>cn.iocoder.cloud</groupId>
|
||||
<artifactId>yudao-spring-boot-starter-test</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- 工具类相关 -->
|
||||
<dependency>
|
||||
<groupId>cn.iocoder.cloud</groupId>
|
||||
<artifactId>yudao-spring-boot-starter-excel</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>cn.iocoder.cloud</groupId>
|
||||
<artifactId>yudao-spring-boot-starter-biz-dict</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- 监控相关 -->
|
||||
<dependency>
|
||||
<groupId>cn.iocoder.cloud</groupId>
|
||||
<artifactId>yudao-spring-boot-starter-monitor</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
</project>
|
||||
|
|
@ -0,0 +1,30 @@
|
|||
package cn.iocoder.yudao.module.statistics;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
/**
|
||||
* 项目的启动类
|
||||
*
|
||||
* 如果你碰到启动的问题,请认真阅读 https://cloud.iocoder.cn/quick-start/ 文章
|
||||
* 如果你碰到启动的问题,请认真阅读 https://cloud.iocoder.cn/quick-start/ 文章
|
||||
* 如果你碰到启动的问题,请认真阅读 https://cloud.iocoder.cn/quick-start/ 文章
|
||||
*
|
||||
* @author 芋道源码
|
||||
*/
|
||||
@SpringBootApplication
|
||||
public class StatisticsServerApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
// 如果你碰到启动的问题,请认真阅读 https://cloud.iocoder.cn/quick-start/ 文章
|
||||
// 如果你碰到启动的问题,请认真阅读 https://cloud.iocoder.cn/quick-start/ 文章
|
||||
// 如果你碰到启动的问题,请认真阅读 https://cloud.iocoder.cn/quick-start/ 文章
|
||||
|
||||
SpringApplication.run(StatisticsServerApplication.class, args);
|
||||
|
||||
// 如果你碰到启动的问题,请认真阅读 https://cloud.iocoder.cn/quick-start/ 文章
|
||||
// 如果你碰到启动的问题,请认真阅读 https://cloud.iocoder.cn/quick-start/ 文章
|
||||
// 如果你碰到启动的问题,请认真阅读 https://cloud.iocoder.cn/quick-start/ 文章
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,20 @@
|
|||
package cn.iocoder.yudao.module.statistics.controller.admin.common.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Schema(description = "管理后台 - 数据对照 Response VO")
|
||||
@Data
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class DataComparisonRespVO<T> {
|
||||
|
||||
@Schema(description = "当前数据", requiredMode = Schema.RequiredMode.REQUIRED, example = "1024")
|
||||
private T value;
|
||||
|
||||
@Schema(description = "参照数据", requiredMode = Schema.RequiredMode.REQUIRED, example = "1024")
|
||||
private T reference;
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,121 @@
|
|||
package cn.iocoder.yudao.module.statistics.controller.admin.member;
|
||||
|
||||
import cn.hutool.core.util.ArrayUtil;
|
||||
import cn.hutool.core.util.NumberUtil;
|
||||
import cn.iocoder.yudao.framework.common.enums.UserTypeEnum;
|
||||
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
|
||||
import cn.iocoder.yudao.module.statistics.controller.admin.common.vo.DataComparisonRespVO;
|
||||
import cn.iocoder.yudao.module.statistics.controller.admin.member.vo.*;
|
||||
import cn.iocoder.yudao.module.statistics.convert.member.MemberStatisticsConvert;
|
||||
import cn.iocoder.yudao.module.statistics.service.infra.ApiAccessLogStatisticsService;
|
||||
import cn.iocoder.yudao.module.statistics.service.member.MemberStatisticsService;
|
||||
import cn.iocoder.yudao.module.statistics.service.trade.TradeOrderStatisticsService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.security.access.prepost.PreAuthorize;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.annotation.Resource;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
|
||||
|
||||
@Tag(name = "管理后台 - 会员统计")
|
||||
@RestController
|
||||
@RequestMapping("/statistics/member")
|
||||
@Validated
|
||||
@Slf4j
|
||||
public class MemberStatisticsController {
|
||||
|
||||
@Resource
|
||||
private MemberStatisticsService memberStatisticsService;
|
||||
@Resource
|
||||
private TradeOrderStatisticsService tradeOrderStatisticsService;
|
||||
@Resource
|
||||
private ApiAccessLogStatisticsService apiAccessLogStatisticsService;
|
||||
|
||||
// TODO 芋艿:已经 review
|
||||
@GetMapping("/summary")
|
||||
@Operation(summary = "获得会员统计(实时统计)")
|
||||
@PreAuthorize("@ss.hasPermission('statistics:member:query')")
|
||||
public CommonResult<MemberSummaryRespVO> getMemberSummary() {
|
||||
return success(memberStatisticsService.getMemberSummary());
|
||||
}
|
||||
|
||||
// TODO 芋艿:已经 review
|
||||
@GetMapping("/analyse")
|
||||
@Operation(summary = "获得会员分析数据")
|
||||
@PreAuthorize("@ss.hasPermission('statistics:member:query')")
|
||||
public CommonResult<MemberAnalyseRespVO> getMemberAnalyse(MemberAnalyseReqVO reqVO) {
|
||||
// 1. 查询数据
|
||||
LocalDateTime beginTime = ArrayUtil.get(reqVO.getTimes(), 0);
|
||||
LocalDateTime endTime = ArrayUtil.get(reqVO.getTimes(), 1);
|
||||
// 1.1 查询分析对照数据
|
||||
DataComparisonRespVO<MemberAnalyseDataRespVO> comparisonData = memberStatisticsService.getMemberAnalyseComparisonData(beginTime, endTime);
|
||||
// TODO @疯狂:这个可能有点特殊,要按照 create_time 来查询;不然它的漏斗就不统一;因为是访问数量 > 今日下单人 > 今日支付人;是一个统一的维度;
|
||||
// 1.2 查询成交用户数量
|
||||
Integer payUserCount = tradeOrderStatisticsService.getPayUserCount(beginTime, endTime);
|
||||
// 1.3 计算客单价
|
||||
int atv = 0;
|
||||
if (payUserCount != null && payUserCount > 0) {
|
||||
// TODO @疯狂:类似上面的 payUserCount
|
||||
Integer payPrice = tradeOrderStatisticsService.getOrderPayPrice(beginTime, endTime);
|
||||
atv = NumberUtil.div(payPrice, payUserCount).intValue();
|
||||
}
|
||||
// 1.4 查询访客数量
|
||||
Integer visitUserCount = apiAccessLogStatisticsService.getIpCount(UserTypeEnum.MEMBER.getValue(), beginTime, endTime);
|
||||
// 1.5 下单用户数量
|
||||
Integer orderUserCount = tradeOrderStatisticsService.getOrderUserCount(beginTime, endTime);
|
||||
|
||||
// 2. 拼接返回
|
||||
return success(MemberStatisticsConvert.INSTANCE.convert(visitUserCount, orderUserCount, payUserCount, atv, comparisonData));
|
||||
}
|
||||
|
||||
// TODO 芋艿:已经 review
|
||||
@GetMapping("/area-statistics-list")
|
||||
@Operation(summary = "按照省份,获得会员统计列表")
|
||||
@PreAuthorize("@ss.hasPermission('statistics:member:query')")
|
||||
public CommonResult<List<MemberAreaStatisticsRespVO>> getMemberAreaStatisticsList() {
|
||||
return success(memberStatisticsService.getMemberAreaStatisticsList());
|
||||
}
|
||||
|
||||
// TODO 芋艿:已经 review
|
||||
@GetMapping("/sex-statistics-list")
|
||||
@Operation(summary = "按照性别,获得会员统计列表")
|
||||
@PreAuthorize("@ss.hasPermission('statistics:member:query')")
|
||||
public CommonResult<List<MemberSexStatisticsRespVO>> getMemberSexStatisticsList() {
|
||||
return success(memberStatisticsService.getMemberSexStatisticsList());
|
||||
}
|
||||
|
||||
// TODO 芋艿:已经 review
|
||||
@GetMapping("/terminal-statistics-list")
|
||||
@Operation(summary = "按照终端,获得会员统计列表")
|
||||
@PreAuthorize("@ss.hasPermission('statistics:member:query')")
|
||||
public CommonResult<List<MemberTerminalStatisticsRespVO>> getMemberTerminalStatisticsList() {
|
||||
return success(memberStatisticsService.getMemberTerminalStatisticsList());
|
||||
}
|
||||
|
||||
// TODO 芋艿:已经 review
|
||||
// TODO @疯狂:要注意 date 的排序;
|
||||
@GetMapping("/user-count-comparison")
|
||||
@Operation(summary = "获得用户数量对照")
|
||||
@PreAuthorize("@ss.hasPermission('statistics:member:query')")
|
||||
public CommonResult<DataComparisonRespVO<MemberCountRespVO>> getUserCountComparison() {
|
||||
return success(memberStatisticsService.getUserCountComparison());
|
||||
}
|
||||
|
||||
// TODO 芋艿:已经 review
|
||||
@GetMapping("/register-count-list")
|
||||
@Operation(summary = "获得会员注册数量列表")
|
||||
@PreAuthorize("@ss.hasPermission('statistics:member:query')")
|
||||
public CommonResult<List<MemberRegisterCountRespVO>> getMemberRegisterCountList(MemberAnalyseReqVO reqVO) {
|
||||
return success(memberStatisticsService.getMemberRegisterCountList(
|
||||
ArrayUtil.get(reqVO.getTimes(), 0), ArrayUtil.get(reqVO.getTimes(), 1)));
|
||||
}
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
package cn.iocoder.yudao.module.statistics.controller.admin.member.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
@Schema(description = "管理后台 - 会员分析数据 Response VO")
|
||||
@Data
|
||||
public class MemberAnalyseDataRespVO {
|
||||
|
||||
@Schema(description = "会员数量", requiredMode = Schema.RequiredMode.REQUIRED, example = "1024")
|
||||
private Integer registerUserCount;
|
||||
|
||||
@Schema(description = "活跃用户数量", requiredMode = Schema.RequiredMode.REQUIRED, example = "1024")
|
||||
private Integer visitUserCount;
|
||||
|
||||
@Schema(description = "充值会员数量", requiredMode = Schema.RequiredMode.REQUIRED, example = "221")
|
||||
private Integer rechargeUserCount;
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,19 @@
|
|||
package cn.iocoder.yudao.module.statistics.controller.admin.member.vo;
|
||||
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
import org.springframework.format.annotation.DateTimeFormat;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
import static cn.iocoder.yudao.framework.common.util.date.DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND;
|
||||
|
||||
@Schema(description = "管理后台 - 会员分析 Request VO")
|
||||
@Data
|
||||
public class MemberAnalyseReqVO {
|
||||
|
||||
@DateTimeFormat(pattern = FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND)
|
||||
@Schema(description = "时间范围")
|
||||
private LocalDateTime[] times;
|
||||
|
||||
}
|
||||
|
|
@ -0,0 +1,26 @@
|
|||
package cn.iocoder.yudao.module.statistics.controller.admin.member.vo;
|
||||
|
||||
import cn.iocoder.yudao.module.statistics.controller.admin.common.vo.DataComparisonRespVO;
|
||||
import io.swagger.v3.oas.annotations.media.Schema;
|
||||
import lombok.Data;
|
||||
|
||||
@Schema(description = "管理后台 - 会员分析 Response VO")
|
||||
@Data
|
||||
public class MemberAnalyseRespVO {
|
||||
|
||||
@Schema(description = "访客数量", requiredMode = Schema.RequiredMode.REQUIRED, example = "1024")
|
||||
private Integer visitUserCount;
|
||||
|
||||
@Schema(description = "下单用户数量", requiredMode = Schema.RequiredMode.REQUIRED, example = "1024")
|
||||
private Integer orderUserCount;
|
||||
|
||||
@Schema(description = "成交用户数量", requiredMode = Schema.RequiredMode.REQUIRED, example = "1024")
|
||||
private Integer payUserCount;
|
||||
|
||||
@Schema(description = "客单价,单位:分", requiredMode = Schema.RequiredMode.REQUIRED, example = "1024")
|
||||
private Integer atv;
|
||||
|
||||
@Schema(description = "对照数据", requiredMode = Schema.RequiredMode.REQUIRED)
|
||||
private DataComparisonRespVO<MemberAnalyseDataRespVO> comparison;
|
||||
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue