Commit bce96b29a67044a6c6340054a9f5d73295c0ea93

Authored by puhui999
2 parents 42c47d9b 437185cb

Merge remote-tracking branch 'yudao/feature/mall_product' into feature/mall_product

# Conflicts:
#	yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/convert/order/TradeOrderConvert.java
#	yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/service/price/bo/TradePriceCalculateReqBO.java
#	yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/service/price/bo/TradePriceCalculateRespBO.java
Showing 188 changed files with 3212 additions and 961 deletions
sql/mysql/brokerage.sql
1 1 -- 增加配置表
2   -create table trade_config
  2 +CREATE TABLE trade_config
3 3 (
4   - id bigint auto_increment comment '自增主键' primary key,
5   - brokerage_enabled bit default 1 not null comment '是否启用分佣',
6   - brokerage_enabled_condition tinyint default 0 not null comment '分佣模式:1-人人分销 2-指定分销',
7   - brokerage_bind_mode tinyint default 0 not null comment '分销关系绑定模式: 1-没有推广人,2-新用户, 3-扫码覆盖',
8   - brokerage_post_urls varchar(2000) default '' null comment '分销海报图地址数组',
9   - brokerage_first_percent int default 0 not null comment '一级返佣比例',
10   - brokerage_second_percent int default 0 not null comment '二级返佣比例',
11   - brokerage_withdraw_min_price int default 0 not null comment '用户提现最低金额',
12   - brokerage_bank_names varchar(200) default '' not null comment '提现银行(字典类型=brokerage_bank_name)',
13   - brokerage_frozen_days int default 7 not null comment '佣金冻结时间(天)',
14   - brokerage_withdraw_type varchar(32) default '1,2,3,4' not null comment '提现方式:1-钱包;2-银行卡;3-微信;4-支付宝',
15   - creator varchar(64) default '' null comment '创建者',
16   - create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间',
17   - updater varchar(64) default '' null comment '更新者',
18   - update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '更新时间',
19   - deleted bit default b'0' not null comment '是否删除',
20   - tenant_id bigint default 0 not null comment '租户编号'
21   -) comment '交易中心配置';
  4 + id BIGINT AUTO_INCREMENT COMMENT '自增主键' PRIMARY KEY,
  5 + brokerage_enabled BIT DEFAULT 1 NOT NULL COMMENT '是否启用分佣',
  6 + brokerage_enabled_condition TINYINT DEFAULT 1 NOT NULL COMMENT '分佣模式:1-人人分销 2-指定分销',
  7 + brokerage_bind_mode TINYINT DEFAULT 1 NOT NULL COMMENT '分销关系绑定模式: 1-没有推广人,2-新用户, 3-扫码覆盖',
  8 + brokerage_poster_urls VARCHAR(2000) DEFAULT '' NULL COMMENT '分销海报图地址数组',
  9 + brokerage_first_percent INT DEFAULT 0 NOT NULL COMMENT '一级返佣比例',
  10 + brokerage_second_percent INT DEFAULT 0 NOT NULL COMMENT '二级返佣比例',
  11 + brokerage_withdraw_min_price INT DEFAULT 0 NOT NULL COMMENT '用户提现最低金额',
  12 + brokerage_withdraw_fee_percent INT DEFAULT 0 NOT NULL COMMENT '提现手续费百分比',
  13 + brokerage_bank_names VARCHAR(200) DEFAULT '' NOT NULL COMMENT '提现银行(字典类型=brokerage_bank_name)',
  14 + brokerage_frozen_days INT DEFAULT 7 NOT NULL COMMENT '佣金冻结时间(天)',
  15 + brokerage_withdraw_types VARCHAR(32) DEFAULT '1,2,3,4' NOT NULL COMMENT '提现方式:1-钱包;2-银行卡;3-微信;4-支付宝',
  16 + creator VARCHAR(64) DEFAULT '' NULL COMMENT '创建者',
  17 + create_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL COMMENT '创建时间',
  18 + updater VARCHAR(64) DEFAULT '' NULL COMMENT '更新者',
  19 + update_time DATETIME DEFAULT CURRENT_TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
  20 + deleted BIT DEFAULT b'0' NOT NULL COMMENT '是否删除',
  21 + tenant_id BIGINT DEFAULT 0 NOT NULL COMMENT '租户编号'
  22 +) COMMENT '交易中心配置';
  23 +
  24 +# alter table trade_config
  25 +# add brokerage_withdraw_fee_percent int default 0 not null comment '提现手续费百分比' after brokerage_withdraw_min_price;
22 26  
23 27 # alter table trade_brokerage_user
24 28 # add level int not null default 1 comment '等级' after frozen_price;
... ... @@ -36,8 +40,6 @@ create table trade_brokerage_user
36 40 brokerage_time datetime null comment '成为分销员时间',
37 41 price int default 0 not null comment '可用佣金',
38 42 frozen_price int default 0 not null comment '冻结佣金',
39   - level int default 1 not null comment '等级',
40   - path varchar(2000) null comment '路径',
41 43 creator varchar(64) default '' null comment '创建者',
42 44 create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间',
43 45 updater varchar(64) default '' null comment '更新者',
... ... @@ -83,7 +85,7 @@ create index idx_status on trade_brokerage_record (status) comment '状态';
83 85  
84 86 create table trade_brokerage_withdraw
85 87 (
86   - id int auto_increment comment '编号'
  88 + id bigint auto_increment comment '编号'
87 89 primary key,
88 90 user_id bigint not null comment '用户编号',
89 91 price int default 0 not null comment '提现金额',
... ... @@ -137,7 +139,8 @@ insert into system_dict_type(type, name)
137 139 values ('brokerage_record_biz_type', '佣金记录业务类型');
138 140 insert into system_dict_data(dict_type, label, value, sort)
139 141 values ('brokerage_record_biz_type', '订单返佣', 1, 1),
140   - ('brokerage_record_biz_type', '申请提现', 2, 2);
  142 + ('brokerage_record_biz_type', '申请提现', 2, 2),
  143 + ('brokerage_record_biz_type', '申请提现驳回', 3, 3);
141 144  
142 145 insert into system_dict_type(type, name)
143 146 values ('brokerage_record_status', '佣金记录状态');
... ...
sql/mysql/pay_wallet.sql
... ... @@ -10,6 +10,7 @@ CREATE TABLE `pay_wallet`
10 10 `balance` int NOT NULL DEFAULT 0 COMMENT '余额,单位分',
11 11 `total_expense` int NOT NULL DEFAULT 0 COMMENT '累计支出,单位分',
12 12 `total_recharge` int NOT NULL DEFAULT 0 COMMENT '累计充值,单位分',
  13 + `freeze_price` int NOT NULL DEFAULT 0 COMMENT '冻结金额,单位分',
13 14 `creator` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT '' COMMENT '创建者',
14 15 `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
15 16 `updater` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT '' COMMENT '更新者',
... ... @@ -50,18 +51,19 @@ CREATE TABLE `pay_wallet_recharge`
50 51 (
51 52 `id` bigint NOT NULL AUTO_INCREMENT COMMENT '编号',
52 53 `wallet_id` bigint NOT NULL COMMENT '会员钱包 id',
53   - `price` int NOT NULL COMMENT '用户实际到账余额,例如充 100 送 20,则该值是 120',
  54 + `total_price` int NOT NULL COMMENT '用户实际到账余额,例如充 100 送 20,则该值是 120',
54 55 `pay_price` int NOT NULL COMMENT '实际支付金额',
55   - `wallet_bonus` int NOT NULL COMMENT '钱包赠送金额',
  56 + `bonus_price` int NOT NULL COMMENT '钱包赠送金额',
56 57 `pay_status` bit(1) NOT NULL DEFAULT b'0' COMMENT '是否已支付:[0:未支付 1:已经支付过]',
57 58 `pay_order_id` bigint NULL COMMENT '支付订单编号',
58 59 `pay_channel_code` varchar(16) NULL COMMENT '支付成功的支付渠道',
59 60 `pay_time` datetime NULL COMMENT '订单支付时间',
60 61 `pay_refund_id` bigint NULL COMMENT '支付退款单编号',
61   - `refund_price` int NOT NULL DEFAULT 0 COMMENT '退款金额,包含赠送金额',
  62 + `refund_total_price` int NOT NULL DEFAULT 0 COMMENT '退款金额,包含赠送金额',
62 63 `refund_pay_price` int NOT NULL DEFAULT 0 COMMENT '退款支付金额',
63   - `refund_wallet_bonus` int NOT NULL DEFAULT 0 COMMENT '退款钱包赠送金额',
  64 + `refund_bonus_price` int NOT NULL DEFAULT 0 COMMENT '退款钱包赠送金额',
64 65 `refund_time` datetime NULL COMMENT '退款时间',
  66 + `refund_status` int NOT NULL DEFAULT 0 COMMENT '退款状态',
65 67 `creator` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT '' COMMENT '创建者',
66 68 `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
67 69 `updater` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT '' COMMENT '更新者',
... ...
sql/mysql/point.sql 0 → 100644
  1 +ALTER TABLE trade_order ADD COLUMN use_point int NOT NULL DEFAULT 0 COMMENT '使用的积分' AFTER point_price;
  2 +ALTER TABLE trade_order ADD COLUMN refund_point int NOT NULL DEFAULT 0 COMMENT '退还的使用积分' AFTER use_point;
  3 +ALTER TABLE trade_order ADD COLUMN give_point int NOT NULL DEFAULT 0 COMMENT '赠送的积分' AFTER refund_point;
  4 +
  5 +ALTER TABLE trade_order_item ADD COLUMN use_point int NOT NULL DEFAULT 0 COMMENT '使用的积分' AFTER point_price;
  6 +ALTER TABLE trade_order_item ADD COLUMN give_point int NOT NULL DEFAULT 0 COMMENT '赠送的积分' AFTER use_point;
... ...
yudao-framework/yudao-common/src/main/java/cn/iocoder/yudao/framework/common/util/number/MoneyUtils.java
1 1 package cn.iocoder.yudao.framework.common.util.number;
2 2  
  3 +import cn.hutool.core.math.Money;
3 4 import cn.hutool.core.util.NumberUtil;
4 5  
5 6 import java.math.BigDecimal;
... ... @@ -16,7 +17,7 @@ public class MoneyUtils {
16 17 * 计算百分比金额,四舍五入
17 18 *
18 19 * @param price 金额
19   - * @param rate 百分比,例如说 56.77% 则传入 56.77
  20 + * @param rate 百分比,例如说 56.77% 则传入 56.77
20 21 * @return 百分比金额
21 22 */
22 23 public static Integer calculateRatePrice(Integer price, Double rate) {
... ... @@ -27,24 +28,46 @@ public class MoneyUtils {
27 28 * 计算百分比金额,向下传入
28 29 *
29 30 * @param price 金额
30   - * @param rate 百分比,例如说 56.77% 则传入 56.77
  31 + * @param rate 百分比,例如说 56.77% 则传入 56.77
31 32 * @return 百分比金额
32 33 */
33 34 public static Integer calculateRatePriceFloor(Integer price, Double rate) {
34 35 return calculateRatePrice(price, rate, 0, RoundingMode.FLOOR).intValue();
35 36 }
36 37  
37   - /**
38   - * 计算百分比金额
39   - *
40   - * @param price 金额
41   - * @param rate 百分比,例如说 56.77% 则传入 56.77
42   - * @param scale 保留小数位数
43   - * @param roundingMode 舍入模式
44   - */
45   - public static BigDecimal calculateRatePrice(Number price, Number rate, int scale, RoundingMode roundingMode) {
46   - return NumberUtil.toBigDecimal(price).multiply(NumberUtil.toBigDecimal(rate)) // 乘以
47   - .divide(BigDecimal.valueOf(100), scale, roundingMode); // 除以 100
48   - }
  38 + /**
  39 + * 计算百分比金额
  40 + *
  41 + * @param price 金额
  42 + * @param rate 百分比,例如说 56.77% 则传入 56.77
  43 + * @param scale 保留小数位数
  44 + * @param roundingMode 舍入模式
  45 + */
  46 + public static BigDecimal calculateRatePrice(Number price, Number rate, int scale, RoundingMode roundingMode) {
  47 + return NumberUtil.toBigDecimal(price).multiply(NumberUtil.toBigDecimal(rate)) // 乘以
  48 + .divide(BigDecimal.valueOf(100), scale, roundingMode); // 除以 100
  49 + }
  50 +
  51 + /**
  52 + * 分转元
  53 + *
  54 + * @param fen 分
  55 + * @return 元
  56 + */
  57 + public static BigDecimal fenToYuan(int fen) {
  58 + return new Money(0, fen).getAmount();
  59 + }
  60 +
  61 + /**
  62 + * 分转元(字符串)
  63 + *
  64 + * 例如说 fen 为 1 时,则结果为 0.01
  65 + *
  66 + * @param fen 分
  67 + * @return 元
  68 + */
  69 + public static String fenToYuanStr(int fen) {
  70 + return new Money(0, fen).toString();
  71 + }
49 72  
50 73 }
... ...
yudao-framework/yudao-spring-boot-starter-biz-error-code/pom.xml
... ... @@ -14,7 +14,7 @@
14 14 <name>${project.artifactId}</name>
15 15 <description>
16 16 错误码 ErrorCode 的自动配置功能,提供如下功能:
17   - 1. 远程读取:项目启动时,从 system-server 服务,读取数据库中的 ErrorCode 错误码,实现错误码的提水可配置;
  17 + 1. 远程读取:项目启动时,从 system-server 服务,读取数据库中的 ErrorCode 错误码,实现错误码的提示可配置;
18 18 2. 自动更新:管理员在管理后台修数据库中的 ErrorCode 错误码时,项目自动从 system-server 服务加载最新的 ErrorCode 错误码;
19 19 3. 自动写入:项目启动时,将项目本地的错误码写到 system-server 服务中,方便管理员在管理后台编辑;
20 20 </description>
... ...
yudao-framework/yudao-spring-boot-starter-biz-pay/src/main/java/cn/iocoder/yudao/framework/pay/core/client/PayClient.java
... ... @@ -4,6 +4,8 @@ import cn.iocoder.yudao.framework.pay.core.client.dto.order.PayOrderRespDTO;
4 4 import cn.iocoder.yudao.framework.pay.core.client.dto.order.PayOrderUnifiedReqDTO;
5 5 import cn.iocoder.yudao.framework.pay.core.client.dto.refund.PayRefundRespDTO;
6 6 import cn.iocoder.yudao.framework.pay.core.client.dto.refund.PayRefundUnifiedReqDTO;
  7 +import cn.iocoder.yudao.framework.pay.core.client.dto.transfer.PayTransferRespDTO;
  8 +import cn.iocoder.yudao.framework.pay.core.client.dto.transfer.PayTransferUnifiedReqDTO;
7 9  
8 10 import java.util.Map;
9 11  
... ... @@ -76,4 +78,12 @@ public interface PayClient {
76 78 */
77 79 PayRefundRespDTO getRefund(String outTradeNo, String outRefundNo);
78 80  
  81 + /**
  82 + * 调用渠道,进行转账
  83 + *
  84 + * @param reqDTO 统一转账请求信息
  85 + * @return 转账信息
  86 + */
  87 + PayTransferRespDTO unifiedTransfer(PayTransferUnifiedReqDTO reqDTO);
  88 +
79 89 }
... ...
yudao-framework/yudao-spring-boot-starter-biz-pay/src/main/java/cn/iocoder/yudao/framework/pay/core/client/dto/transfer/PayTransferRespDTO.java 0 → 100644
  1 +package cn.iocoder.yudao.framework.pay.core.client.dto.transfer;
  2 +
  3 +import cn.iocoder.yudao.framework.pay.core.enums.transfer.PayTransferStatusRespEnum;
  4 +import lombok.Data;
  5 +
  6 +import java.time.LocalDateTime;
  7 +
  8 +/**
  9 + * 统一转账 Response DTO
  10 + *
  11 + * @author jason
  12 + */
  13 +@Data
  14 +public class PayTransferRespDTO {
  15 +
  16 + /**
  17 + * 转账状态
  18 + *
  19 + * 关联 {@link PayTransferStatusRespEnum#getStatus()}
  20 + */
  21 + private Integer status;
  22 +
  23 + /**
  24 + * 外部转账单号
  25 + *
  26 + */
  27 + private String outTransferNo;
  28 +
  29 + /**
  30 + * 支付渠道编号
  31 + */
  32 + private String channelOrderNo;
  33 +
  34 + /**
  35 + * 支付成功时间
  36 + */
  37 + private LocalDateTime successTime;
  38 +
  39 + /**
  40 + * 原始的返回结果
  41 + */
  42 + private Object rawData;
  43 +
  44 + /**
  45 + * 调用渠道的错误码
  46 + */
  47 + private String channelErrorCode;
  48 + /**
  49 + * 调用渠道报错时,错误信息
  50 + */
  51 + private String channelErrorMsg;
  52 +
  53 + /**
  54 + * 创建【WAITING】状态的转账返回
  55 + */
  56 + public static PayTransferRespDTO waitingOf(String channelOrderNo,
  57 + String outTransferNo, Object rawData) {
  58 + PayTransferRespDTO respDTO = new PayTransferRespDTO();
  59 + respDTO.status = PayTransferStatusRespEnum.WAITING.getStatus();
  60 + respDTO.channelOrderNo = channelOrderNo;
  61 + respDTO.outTransferNo = outTransferNo;
  62 + respDTO.rawData = rawData;
  63 + return respDTO;
  64 + }
  65 +
  66 + /**
  67 + * 创建【FAILURE】状态的转账返回
  68 + */
  69 + public static PayTransferRespDTO failureOf(String channelErrorCode, String channelErrorMsg,
  70 + String outTransferNo, Object rawData) {
  71 + PayTransferRespDTO respDTO = new PayTransferRespDTO();
  72 + respDTO.status = PayTransferStatusRespEnum.FAILURE.getStatus();
  73 + respDTO.channelErrorCode = channelErrorCode;
  74 + respDTO.channelErrorMsg = channelErrorMsg;
  75 + // 相对通用的字段
  76 + respDTO.outTransferNo = outTransferNo;
  77 + respDTO.rawData = rawData;
  78 + return respDTO;
  79 + }
  80 +
  81 + /**
  82 + * 创建【SUCCESS】状态的转账返回
  83 + */
  84 + public static PayTransferRespDTO successOf(String channelTransferNo, LocalDateTime successTime,
  85 + String outTransferNo, Object rawData) {
  86 + PayTransferRespDTO respDTO = new PayTransferRespDTO();
  87 + respDTO.status = PayTransferStatusRespEnum.SUCCESS.getStatus();
  88 + respDTO.channelOrderNo = channelTransferNo;
  89 + respDTO.successTime = successTime;
  90 + // 相对通用的字段
  91 + respDTO.outTransferNo = outTransferNo;
  92 + respDTO.rawData = rawData;
  93 + return respDTO;
  94 + }
  95 +
  96 +}
... ...
yudao-framework/yudao-spring-boot-starter-biz-pay/src/main/java/cn/iocoder/yudao/framework/pay/core/client/dto/transfer/PayTransferUnifiedReqDTO.java 0 → 100644
  1 +package cn.iocoder.yudao.framework.pay.core.client.dto.transfer;
  2 +
  3 +import cn.iocoder.yudao.framework.common.validation.InEnum;
  4 +import cn.iocoder.yudao.framework.pay.core.enums.transfer.PayTransferTypeEnum;
  5 +import lombok.Data;
  6 +import org.hibernate.validator.constraints.Length;
  7 +
  8 +import javax.validation.constraints.Min;
  9 +import javax.validation.constraints.NotEmpty;
  10 +import javax.validation.constraints.NotNull;
  11 +import java.util.Map;
  12 +
  13 +/**
  14 + * 统一转账 Request DTO
  15 + *
  16 + * @author jason
  17 + */
  18 +@Data
  19 +public class PayTransferUnifiedReqDTO {
  20 +
  21 + /**
  22 + * 转账类型
  23 + *
  24 + * 关联 {@link PayTransferTypeEnum#getType()}
  25 + */
  26 + @NotNull(message = "转账类型不能为空")
  27 + @InEnum(PayTransferTypeEnum.class)
  28 + private Integer type;
  29 +
  30 + /**
  31 + * 用户 IP
  32 + */
  33 + @NotEmpty(message = "用户 IP 不能为空")
  34 + private String userIp;
  35 +
  36 + @NotEmpty(message = "外部转账单编号不能为空")
  37 + private String outTransferNo;
  38 +
  39 + /**
  40 + * 转账金额,单位:分
  41 + */
  42 + @NotNull(message = "转账金额不能为空")
  43 + @Min(value = 1, message = "转账金额必须大于零")
  44 + private Integer price;
  45 +
  46 + /**
  47 + * 转账标题
  48 + */
  49 + @NotEmpty(message = "转账标题不能为空")
  50 + @Length(max = 128, message = "转账标题不能超过 128")
  51 + private String title;
  52 +
  53 + /**
  54 + * 收款方信息,转账类型不同,收款方信息不同
  55 + */
  56 + @NotEmpty(message = "收款方信息 不能为空")
  57 + private Map<String, String> payeeInfo;
  58 +
  59 + /**
  60 + * 支付渠道的额外参数
  61 + *
  62 + */
  63 + private Map<String, String> channelExtras;
  64 +
  65 +}
... ...
yudao-framework/yudao-spring-boot-starter-biz-pay/src/main/java/cn/iocoder/yudao/framework/pay/core/client/impl/AbstractPayClient.java
... ... @@ -8,6 +8,8 @@ import cn.iocoder.yudao.framework.pay.core.client.dto.order.PayOrderRespDTO;
8 8 import cn.iocoder.yudao.framework.pay.core.client.dto.order.PayOrderUnifiedReqDTO;
9 9 import cn.iocoder.yudao.framework.pay.core.client.dto.refund.PayRefundRespDTO;
10 10 import cn.iocoder.yudao.framework.pay.core.client.dto.refund.PayRefundUnifiedReqDTO;
  11 +import cn.iocoder.yudao.framework.pay.core.client.dto.transfer.PayTransferRespDTO;
  12 +import cn.iocoder.yudao.framework.pay.core.client.dto.transfer.PayTransferUnifiedReqDTO;
11 13 import cn.iocoder.yudao.framework.pay.core.client.exception.PayException;
12 14 import lombok.extern.slf4j.Slf4j;
13 15  
... ... @@ -181,6 +183,26 @@ public abstract class AbstractPayClient&lt;Config extends PayClientConfig&gt; implemen
181 183 protected abstract PayRefundRespDTO doGetRefund(String outTradeNo, String outRefundNo)
182 184 throws Throwable;
183 185  
  186 + @Override
  187 + public final PayTransferRespDTO unifiedTransfer(PayTransferUnifiedReqDTO reqDTO) {
  188 + ValidationUtils.validate(reqDTO);
  189 + PayTransferRespDTO resp;
  190 + try{
  191 + resp = doUnifiedTransfer(reqDTO);
  192 + }catch (ServiceException ex) { // 业务异常,都是实现类已经翻译,所以直接抛出即可
  193 + throw ex;
  194 + } catch (Throwable ex) {
  195 + // 系统异常,则包装成 PayException 异常抛出
  196 + log.error("[unifiedTransfer][客户端({}) request({}) 发起转账异常]",
  197 + getId(), toJsonString(reqDTO), ex);
  198 + throw buildPayException(ex);
  199 + }
  200 + return resp;
  201 + }
  202 +
  203 + protected abstract PayTransferRespDTO doUnifiedTransfer(PayTransferUnifiedReqDTO reqDTO)
  204 + throws Throwable;
  205 +
184 206 // ========== 各种工具方法 ==========
185 207  
186 208 private PayException buildPayException(Throwable ex) {
... ...
yudao-framework/yudao-spring-boot-starter-biz-pay/src/main/java/cn/iocoder/yudao/framework/pay/core/client/impl/PayClientFactoryImpl.java
... ... @@ -50,6 +50,8 @@ public class PayClientFactoryImpl implements PayClientFactory {
50 50 clientClass.put(ALIPAY_APP, AlipayAppPayClient.class);
51 51 clientClass.put(ALIPAY_PC, AlipayPcPayClient.class);
52 52 clientClass.put(ALIPAY_BAR, AlipayBarPayClient.class);
  53 + // 支付包转账客户端
  54 + clientClass.put(ALIPAY_TRANSFER, AlipayTransferClient.class);
53 55 // Mock 支付客户端
54 56 clientClass.put(MOCK, MockPayClient.class);
55 57 }
... ...
yudao-framework/yudao-spring-boot-starter-biz-pay/src/main/java/cn/iocoder/yudao/framework/pay/core/client/impl/alipay/AbstractAlipayPayClient.java
... ... @@ -150,6 +150,10 @@ public abstract class AbstractAlipayPayClient extends AbstractPayClient&lt;AlipayPa
150 150 // 2.1 执行请求
151 151 AlipayTradeRefundResponse response = client.execute(request);
152 152 if (!response.isSuccess()) {
  153 + // 当出现 ACQ.SYSTEM_ERROR, 退款可能成功也可能失败。 返回 WAIT 状态. 后续 job 会轮询
  154 + if (ObjectUtils.equalsAny(response.getSubCode(), "ACQ.SYSTEM_ERROR", "SYSTEM_ERROR")) {
  155 + return PayRefundRespDTO.waitingOf(null, reqDTO.getOutRefundNo(), response);
  156 + }
153 157 return PayRefundRespDTO.failureOf(response.getSubCode(), response.getSubMsg(), reqDTO.getOutRefundNo(), response);
154 158 }
155 159 // 2.2 创建返回结果
... ... @@ -198,6 +202,8 @@ public abstract class AbstractAlipayPayClient extends AbstractPayClient&lt;AlipayPa
198 202 return PayRefundRespDTO.waitingOf(null, outRefundNo, response);
199 203 }
200 204  
  205 +
  206 +
201 207 // ========== 各种工具方法 ==========
202 208  
203 209 protected String formatAmount(Integer amount) {
... ...
yudao-framework/yudao-spring-boot-starter-biz-pay/src/main/java/cn/iocoder/yudao/framework/pay/core/client/impl/alipay/AlipayAppPayClient.java
... ... @@ -2,6 +2,8 @@ package cn.iocoder.yudao.framework.pay.core.client.impl.alipay;
2 2  
3 3 import cn.iocoder.yudao.framework.pay.core.client.dto.order.PayOrderRespDTO;
4 4 import cn.iocoder.yudao.framework.pay.core.client.dto.order.PayOrderUnifiedReqDTO;
  5 +import cn.iocoder.yudao.framework.pay.core.client.dto.transfer.PayTransferRespDTO;
  6 +import cn.iocoder.yudao.framework.pay.core.client.dto.transfer.PayTransferUnifiedReqDTO;
5 7 import cn.iocoder.yudao.framework.pay.core.enums.channel.PayChannelEnum;
6 8 import cn.iocoder.yudao.framework.pay.core.enums.order.PayOrderDisplayModeEnum;
7 9 import com.alipay.api.AlipayApiException;
... ... @@ -57,4 +59,8 @@ public class AlipayAppPayClient extends AbstractAlipayPayClient {
57 59 reqDTO.getOutTradeNo(), response);
58 60 }
59 61  
  62 + @Override
  63 + protected PayTransferRespDTO doUnifiedTransfer(PayTransferUnifiedReqDTO reqDTO) {
  64 + throw new UnsupportedOperationException("支付宝【App 支付】不支持转账操作");
  65 + }
60 66 }
... ...
yudao-framework/yudao-spring-boot-starter-biz-pay/src/main/java/cn/iocoder/yudao/framework/pay/core/client/impl/alipay/AlipayBarPayClient.java
... ... @@ -5,6 +5,8 @@ import cn.hutool.core.map.MapUtil;
5 5 import cn.hutool.core.util.StrUtil;
6 6 import cn.iocoder.yudao.framework.pay.core.client.dto.order.PayOrderRespDTO;
7 7 import cn.iocoder.yudao.framework.pay.core.client.dto.order.PayOrderUnifiedReqDTO;
  8 +import cn.iocoder.yudao.framework.pay.core.client.dto.transfer.PayTransferRespDTO;
  9 +import cn.iocoder.yudao.framework.pay.core.client.dto.transfer.PayTransferUnifiedReqDTO;
8 10 import cn.iocoder.yudao.framework.pay.core.enums.channel.PayChannelEnum;
9 11 import cn.iocoder.yudao.framework.pay.core.enums.order.PayOrderDisplayModeEnum;
10 12 import com.alipay.api.AlipayApiException;
... ... @@ -75,4 +77,8 @@ public class AlipayBarPayClient extends AbstractAlipayPayClient {
75 77 reqDTO.getOutTradeNo(), response);
76 78 }
77 79  
  80 + @Override
  81 + protected PayTransferRespDTO doUnifiedTransfer(PayTransferUnifiedReqDTO reqDTO) {
  82 + throw new UnsupportedOperationException("支付宝【条码支付】不支持转账操作");
  83 + }
78 84 }
... ...
yudao-framework/yudao-spring-boot-starter-biz-pay/src/main/java/cn/iocoder/yudao/framework/pay/core/client/impl/alipay/AlipayPcPayClient.java
... ... @@ -4,6 +4,8 @@ import cn.hutool.core.util.ObjectUtil;
4 4 import cn.hutool.http.Method;
5 5 import cn.iocoder.yudao.framework.pay.core.client.dto.order.PayOrderRespDTO;
6 6 import cn.iocoder.yudao.framework.pay.core.client.dto.order.PayOrderUnifiedReqDTO;
  7 +import cn.iocoder.yudao.framework.pay.core.client.dto.transfer.PayTransferRespDTO;
  8 +import cn.iocoder.yudao.framework.pay.core.client.dto.transfer.PayTransferUnifiedReqDTO;
7 9 import cn.iocoder.yudao.framework.pay.core.enums.channel.PayChannelEnum;
8 10 import cn.iocoder.yudao.framework.pay.core.enums.order.PayOrderDisplayModeEnum;
9 11 import com.alipay.api.AlipayApiException;
... ... @@ -67,4 +69,8 @@ public class AlipayPcPayClient extends AbstractAlipayPayClient {
67 69 reqDTO.getOutTradeNo(), response);
68 70 }
69 71  
  72 + @Override
  73 + protected PayTransferRespDTO doUnifiedTransfer(PayTransferUnifiedReqDTO reqDTO) {
  74 + throw new UnsupportedOperationException("支付宝【PC 网站】不支持转账操作");
  75 + }
70 76 }
... ...
yudao-framework/yudao-spring-boot-starter-biz-pay/src/main/java/cn/iocoder/yudao/framework/pay/core/client/impl/alipay/AlipayQrPayClient.java
... ... @@ -2,6 +2,8 @@ package cn.iocoder.yudao.framework.pay.core.client.impl.alipay;
2 2  
3 3 import cn.iocoder.yudao.framework.pay.core.client.dto.order.PayOrderRespDTO;
4 4 import cn.iocoder.yudao.framework.pay.core.client.dto.order.PayOrderUnifiedReqDTO;
  5 +import cn.iocoder.yudao.framework.pay.core.client.dto.transfer.PayTransferRespDTO;
  6 +import cn.iocoder.yudao.framework.pay.core.client.dto.transfer.PayTransferUnifiedReqDTO;
5 7 import cn.iocoder.yudao.framework.pay.core.enums.channel.PayChannelEnum;
6 8 import cn.iocoder.yudao.framework.pay.core.enums.order.PayOrderDisplayModeEnum;
7 9 import com.alipay.api.AlipayApiException;
... ... @@ -54,4 +56,8 @@ public class AlipayQrPayClient extends AbstractAlipayPayClient {
54 56 reqDTO.getOutTradeNo(), response);
55 57 }
56 58  
  59 + @Override
  60 + protected PayTransferRespDTO doUnifiedTransfer(PayTransferUnifiedReqDTO reqDTO) {
  61 + throw new UnsupportedOperationException("支付宝【扫码支付】不支持转账操作");
  62 + }
57 63 }
... ...
yudao-framework/yudao-spring-boot-starter-biz-pay/src/main/java/cn/iocoder/yudao/framework/pay/core/client/impl/alipay/AlipayTransferClient.java 0 → 100644
  1 +package cn.iocoder.yudao.framework.pay.core.client.impl.alipay;
  2 +
  3 +import cn.hutool.core.map.MapUtil;
  4 +import cn.hutool.core.util.StrUtil;
  5 +import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
  6 +import cn.iocoder.yudao.framework.common.util.object.ObjectUtils;
  7 +import cn.iocoder.yudao.framework.pay.core.client.dto.order.PayOrderRespDTO;
  8 +import cn.iocoder.yudao.framework.pay.core.client.dto.order.PayOrderUnifiedReqDTO;
  9 +import cn.iocoder.yudao.framework.pay.core.client.dto.refund.PayRefundRespDTO;
  10 +import cn.iocoder.yudao.framework.pay.core.client.dto.refund.PayRefundUnifiedReqDTO;
  11 +import cn.iocoder.yudao.framework.pay.core.client.dto.transfer.PayTransferRespDTO;
  12 +import cn.iocoder.yudao.framework.pay.core.client.dto.transfer.PayTransferUnifiedReqDTO;
  13 +import cn.iocoder.yudao.framework.pay.core.enums.channel.PayChannelEnum;
  14 +import cn.iocoder.yudao.framework.pay.core.enums.transfer.PayTransferTypeEnum;
  15 +import com.alipay.api.AlipayApiException;
  16 +import com.alipay.api.domain.AlipayFundTransUniTransferModel;
  17 +import com.alipay.api.domain.Participant;
  18 +import com.alipay.api.request.AlipayFundTransUniTransferRequest;
  19 +import com.alipay.api.response.AlipayFundTransUniTransferResponse;
  20 +import lombok.extern.slf4j.Slf4j;
  21 +
  22 +import static cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants.BAD_REQUEST;
  23 +import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception0;
  24 +
  25 +/**
  26 + * 支付宝转账的 PayClient 实现类
  27 + *
  28 + * @author jason
  29 + */
  30 +@Slf4j
  31 +public class AlipayTransferClient extends AbstractAlipayPayClient {
  32 + public AlipayTransferClient(Long channelId, AlipayPayClientConfig config) {
  33 + super(channelId, PayChannelEnum.ALIPAY_TRANSFER.getCode(), config);
  34 + }
  35 + @Override
  36 + protected PayOrderRespDTO doUnifiedOrder(PayOrderUnifiedReqDTO reqDTO) {
  37 + throw new UnsupportedOperationException("支付宝转账不支持统一下单请求");
  38 + }
  39 + @Override
  40 + protected PayRefundRespDTO doUnifiedRefund(PayRefundUnifiedReqDTO reqDTO) {
  41 + throw new UnsupportedOperationException("支付宝转账不支持统一退款请求");
  42 + }
  43 + @Override
  44 + protected PayTransferRespDTO doUnifiedTransfer(PayTransferUnifiedReqDTO reqDTO) throws AlipayApiException {
  45 + // 1.1 构建 AlipayFundTransUniTransferModel
  46 + AlipayFundTransUniTransferModel model = new AlipayFundTransUniTransferModel();
  47 + // ① 通用的参数
  48 + model.setTransAmount(formatAmount(reqDTO.getPrice())); // 转账金额
  49 + model.setOrderTitle(reqDTO.getTitle()); // 转账业务的标题,用于在支付宝用户的账单里显示。
  50 + model.setOutBizNo(reqDTO.getOutTransferNo());
  51 + model.setProductCode("TRANS_ACCOUNT_NO_PWD"); // 销售产品码。单笔无密转账固定为 TRANS_ACCOUNT_NO_PWD
  52 + model.setBizScene("DIRECT_TRANSFER"); // 业务场景 单笔无密转账固定为 DIRECT_TRANSFER。
  53 + model.setBusinessParams(JsonUtils.toJsonString(reqDTO.getChannelExtras()));
  54 + PayTransferTypeEnum transferType = PayTransferTypeEnum.valueOf(reqDTO.getType());
  55 + switch(transferType){
  56 + case WX_BALANCE :
  57 + case WALLET_BALANCE : {
  58 + log.error("[doUnifiedTransfer],支付宝转账不支持的转账类型{}", transferType);
  59 + throw new UnsupportedOperationException(String.format("支付宝转账不支持转账类型: %s",transferType.getName()));
  60 + }
  61 + case ALIPAY_BALANCE : {
  62 + // ② 个性化的参数
  63 + Participant payeeInfo = new Participant();
  64 + payeeInfo.setIdentityType("ALIPAY_LOGON_ID");
  65 + String logonId = MapUtil.getStr(reqDTO.getPayeeInfo(), "ALIPAY_LOGON_ID");
  66 + if (StrUtil.isEmpty(logonId)) {
  67 + throw exception0(BAD_REQUEST.getCode(), "支付包登录 ID 不能为空");
  68 + }
  69 + String accountName = MapUtil.getStr(reqDTO.getPayeeInfo(), "ALIPAY_ACCOUNT_NAME");
  70 + if (StrUtil.isEmpty(accountName)) {
  71 + throw exception0(BAD_REQUEST.getCode(), "支付包账户名称不能为空");
  72 + }
  73 + payeeInfo.setIdentity(logonId); // 支付宝登录号
  74 + payeeInfo.setName(accountName); // 支付宝账号姓名
  75 + model.setPayeeInfo(payeeInfo);
  76 + // 1.2 构建 AlipayFundTransUniTransferRequest
  77 + AlipayFundTransUniTransferRequest request = new AlipayFundTransUniTransferRequest();
  78 + request.setBizModel(model);
  79 + // 执行请求
  80 + AlipayFundTransUniTransferResponse response = client.certificateExecute(request);
  81 + // 处理结果
  82 + if (!response.isSuccess()) {
  83 + // 当出现 SYSTEM_ERROR, 转账可能成功也可能失败。 返回 WAIT 状态. 后续 job 会轮询
  84 + if (ObjectUtils.equalsAny(response.getSubCode(), "SYSTEM_ERROR", "ACQ.SYSTEM_ERROR")) {
  85 + return PayTransferRespDTO.waitingOf(null, reqDTO.getOutTransferNo(), response);
  86 + }
  87 + return PayTransferRespDTO.failureOf(response.getSubCode(), response.getSubMsg(),
  88 + reqDTO.getOutTransferNo(), response);
  89 + }
  90 + return PayTransferRespDTO.successOf(response.getOrderId(), parseTime(response.getTransDate()),
  91 + response.getOutBizNo(), response);
  92 + }
  93 + case BANK_CARD : {
  94 + Participant payeeInfo = new Participant();
  95 + payeeInfo.setIdentityType("BANKCARD_ACCOUNT");
  96 + throw new UnsupportedOperationException("待实现");
  97 + }
  98 + default: {
  99 + throw new IllegalStateException("不正确的转账类型: " + transferType);
  100 + }
  101 + }
  102 + }
  103 +}
... ...
yudao-framework/yudao-spring-boot-starter-biz-pay/src/main/java/cn/iocoder/yudao/framework/pay/core/client/impl/alipay/AlipayWapPayClient.java
... ... @@ -3,6 +3,8 @@ package cn.iocoder.yudao.framework.pay.core.client.impl.alipay;
3 3 import cn.hutool.http.Method;
4 4 import cn.iocoder.yudao.framework.pay.core.client.dto.order.PayOrderRespDTO;
5 5 import cn.iocoder.yudao.framework.pay.core.client.dto.order.PayOrderUnifiedReqDTO;
  6 +import cn.iocoder.yudao.framework.pay.core.client.dto.transfer.PayTransferRespDTO;
  7 +import cn.iocoder.yudao.framework.pay.core.client.dto.transfer.PayTransferUnifiedReqDTO;
6 8 import cn.iocoder.yudao.framework.pay.core.enums.channel.PayChannelEnum;
7 9 import cn.iocoder.yudao.framework.pay.core.enums.order.PayOrderDisplayModeEnum;
8 10 import com.alipay.api.AlipayApiException;
... ... @@ -56,4 +58,8 @@ public class AlipayWapPayClient extends AbstractAlipayPayClient {
56 58 reqDTO.getOutTradeNo(), response);
57 59 }
58 60  
  61 + @Override
  62 + public PayTransferRespDTO doUnifiedTransfer(PayTransferUnifiedReqDTO reqDTO) {
  63 + throw new UnsupportedOperationException("支付宝【Wap 网站】不支持转账操作");
  64 + }
59 65 }
... ...
yudao-framework/yudao-spring-boot-starter-biz-pay/src/main/java/cn/iocoder/yudao/framework/pay/core/client/impl/mock/MockPayClient.java
... ... @@ -4,6 +4,8 @@ import cn.iocoder.yudao.framework.pay.core.client.dto.order.PayOrderRespDTO;
4 4 import cn.iocoder.yudao.framework.pay.core.client.dto.order.PayOrderUnifiedReqDTO;
5 5 import cn.iocoder.yudao.framework.pay.core.client.dto.refund.PayRefundRespDTO;
6 6 import cn.iocoder.yudao.framework.pay.core.client.dto.refund.PayRefundUnifiedReqDTO;
  7 +import cn.iocoder.yudao.framework.pay.core.client.dto.transfer.PayTransferRespDTO;
  8 +import cn.iocoder.yudao.framework.pay.core.client.dto.transfer.PayTransferUnifiedReqDTO;
7 9 import cn.iocoder.yudao.framework.pay.core.client.impl.AbstractPayClient;
8 10 import cn.iocoder.yudao.framework.pay.core.client.impl.NonePayClientConfig;
9 11 import cn.iocoder.yudao.framework.pay.core.enums.channel.PayChannelEnum;
... ... @@ -64,4 +66,8 @@ public class MockPayClient extends AbstractPayClient&lt;NonePayClientConfig&gt; {
64 66 throw new UnsupportedOperationException("模拟支付无支付回调");
65 67 }
66 68  
  69 + @Override
  70 + protected PayTransferRespDTO doUnifiedTransfer(PayTransferUnifiedReqDTO reqDTO) {
  71 + throw new UnsupportedOperationException("待实现");
  72 + }
67 73 }
... ...
yudao-framework/yudao-spring-boot-starter-biz-pay/src/main/java/cn/iocoder/yudao/framework/pay/core/client/impl/weixin/AbstractWxPayClient.java
... ... @@ -12,6 +12,8 @@ import cn.iocoder.yudao.framework.pay.core.client.dto.order.PayOrderRespDTO;
12 12 import cn.iocoder.yudao.framework.pay.core.client.dto.order.PayOrderUnifiedReqDTO;
13 13 import cn.iocoder.yudao.framework.pay.core.client.dto.refund.PayRefundRespDTO;
14 14 import cn.iocoder.yudao.framework.pay.core.client.dto.refund.PayRefundUnifiedReqDTO;
  15 +import cn.iocoder.yudao.framework.pay.core.client.dto.transfer.PayTransferRespDTO;
  16 +import cn.iocoder.yudao.framework.pay.core.client.dto.transfer.PayTransferUnifiedReqDTO;
15 17 import cn.iocoder.yudao.framework.pay.core.client.impl.AbstractPayClient;
16 18 import cn.iocoder.yudao.framework.pay.core.enums.order.PayOrderStatusRespEnum;
17 19 import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
... ... @@ -425,6 +427,10 @@ public abstract class AbstractWxPayClient extends AbstractPayClient&lt;WxPayClientC
425 427 }
426 428 }
427 429  
  430 + @Override
  431 + protected PayTransferRespDTO doUnifiedTransfer(PayTransferUnifiedReqDTO reqDTO) {
  432 + throw new UnsupportedOperationException("待实现");
  433 + }
428 434 // ========== 各种工具方法 ==========
429 435  
430 436 static String formatDateV2(LocalDateTime time) {
... ...
yudao-framework/yudao-spring-boot-starter-biz-pay/src/main/java/cn/iocoder/yudao/framework/pay/core/enums/channel/PayChannelEnum.java
... ... @@ -28,6 +28,7 @@ public enum PayChannelEnum {
28 28 ALIPAY_APP("alipay_app", "支付宝App 支付", AlipayPayClientConfig.class),
29 29 ALIPAY_QR("alipay_qr", "支付宝扫码支付", AlipayPayClientConfig.class),
30 30 ALIPAY_BAR("alipay_bar", "支付宝条码支付", AlipayPayClientConfig.class),
  31 + ALIPAY_TRANSFER("alipay_transfer", "支付宝转账", AlipayPayClientConfig.class),
31 32  
32 33 MOCK("mock", "模拟支付", NonePayClientConfig.class),
33 34  
... ...
yudao-framework/yudao-spring-boot-starter-biz-pay/src/main/java/cn/iocoder/yudao/framework/pay/core/enums/transfer/PayTransferStatusRespEnum.java 0 → 100644
  1 +package cn.iocoder.yudao.framework.pay.core.enums.transfer;
  2 +
  3 +import lombok.AllArgsConstructor;
  4 +import lombok.Getter;
  5 +
  6 +/**
  7 + * 渠道的转账状态枚举
  8 + *
  9 + * @author jason
  10 + */
  11 +@Getter
  12 +@AllArgsConstructor
  13 +public enum PayTransferStatusRespEnum {
  14 +
  15 + WAITING(0, "等待转账"),
  16 + SUCCESS(10, "转账成功"),
  17 + FAILURE(20, "转账失败");
  18 +
  19 + private final Integer status;
  20 + private final String name;
  21 +}
... ...
yudao-framework/yudao-spring-boot-starter-biz-pay/src/main/java/cn/iocoder/yudao/framework/pay/core/enums/transfer/PayTransferTypeEnum.java 0 → 100644
  1 +package cn.iocoder.yudao.framework.pay.core.enums.transfer;
  2 +
  3 +import cn.hutool.core.util.ArrayUtil;
  4 +import cn.iocoder.yudao.framework.common.core.IntArrayValuable;
  5 +import lombok.AllArgsConstructor;
  6 +import lombok.Getter;
  7 +
  8 +import java.util.Arrays;
  9 +
  10 +/**
  11 + * 转账类型枚举
  12 + *
  13 + * @author jason
  14 + */
  15 +@AllArgsConstructor
  16 +@Getter
  17 +public enum PayTransferTypeEnum implements IntArrayValuable {
  18 + ALIPAY_BALANCE(1, "支付宝余额"),
  19 + WX_BALANCE(2, "微信余额"),
  20 + BANK_CARD(3, "银行卡"),
  21 + WALLET_BALANCE(4, "钱包余额");
  22 +
  23 + private final Integer type;
  24 + private final String name;
  25 +
  26 + public static final int[] ARRAYS = Arrays.stream(values()).mapToInt(PayTransferTypeEnum::getType).toArray();
  27 +
  28 + @Override
  29 + public int[] array() {
  30 + return ARRAYS;
  31 + }
  32 +
  33 + public static PayTransferTypeEnum valueOf(Integer type) {
  34 + return ArrayUtil.firstMatch(item -> item.getType().equals(type), values());
  35 + }
  36 +}
... ...
yudao-framework/yudao-spring-boot-starter-mybatis/src/main/java/cn/iocoder/yudao/framework/mybatis/core/query/LambdaQueryWrapperX.java
... ... @@ -100,14 +100,6 @@ public class LambdaQueryWrapperX&lt;T&gt; extends LambdaQueryWrapper&lt;T&gt; {
100 100 return betweenIfPresent(column, val1, val2);
101 101 }
102 102  
103   - // TODO @疯狂:这个是 mysql 独有的,不好做成通用的哈。如果多层级,有没可能先查询一个层级,再查询一个层级;形成 set 后,直接去 in?
104   - public LambdaQueryWrapperX<T> findInSetIfPresent(SFunction<T, ?> column, Object val) {
105   - if (val != null) {
106   - return (LambdaQueryWrapperX<T>) super.apply("FIND_IN_SET({0}, " + columnToString(column) + ")", val);
107   - }
108   - return this;
109   - }
110   -
111 103 // ========== 重写父类方法,方便链式调用 ==========
112 104  
113 105 @Override
... ...
yudao-framework/yudao-spring-boot-starter-web/src/main/java/cn/iocoder/yudao/framework/jackson/config/YudaoJacksonAutoConfiguration.java
1 1 package cn.iocoder.yudao.framework.jackson.config;
2 2  
3   -import cn.iocoder.yudao.framework.jackson.core.databind.NumberSerializer;
  3 +import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
4 4 import cn.iocoder.yudao.framework.jackson.core.databind.LocalDateTimeDeserializer;
5 5 import cn.iocoder.yudao.framework.jackson.core.databind.LocalDateTimeSerializer;
6   -import cn.iocoder.yudao.framework.common.util.json.JsonUtils;
  6 +import cn.iocoder.yudao.framework.jackson.core.databind.NumberSerializer;
7 7 import com.fasterxml.jackson.databind.ObjectMapper;
8 8 import com.fasterxml.jackson.databind.module.SimpleModule;
  9 +import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
  10 +import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
  11 +import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
  12 +import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
9 13 import lombok.extern.slf4j.Slf4j;
10 14 import org.springframework.beans.BeansException;
11 15 import org.springframework.beans.factory.config.BeanPostProcessor;
12 16 import org.springframework.boot.autoconfigure.AutoConfiguration;
13 17 import org.springframework.context.annotation.Bean;
14 18  
  19 +import java.time.LocalDate;
15 20 import java.time.LocalDateTime;
  21 +import java.time.LocalTime;
16 22  
17 23 @AutoConfiguration
18 24 @Slf4j
... ... @@ -36,6 +42,10 @@ public class YudaoJacksonAutoConfiguration {
36 42 simpleModule
37 43 .addSerializer(Long.class, NumberSerializer.INSTANCE)
38 44 .addSerializer(Long.TYPE, NumberSerializer.INSTANCE)
  45 + .addSerializer(LocalDate.class, LocalDateSerializer.INSTANCE)
  46 + .addDeserializer(LocalDate.class, LocalDateDeserializer.INSTANCE)
  47 + .addSerializer(LocalTime.class, LocalTimeSerializer.INSTANCE)
  48 + .addDeserializer(LocalTime.class, LocalTimeDeserializer.INSTANCE)
39 49 .addSerializer(LocalDateTime.class, LocalDateTimeSerializer.INSTANCE)
40 50 .addDeserializer(LocalDateTime.class, LocalDateTimeDeserializer.INSTANCE);
41 51  
... ...
yudao-module-mall/yudao-module-product-api/src/main/java/cn/iocoder/yudao/module/product/api/sku/ProductSkuApi.java
... ... @@ -39,7 +39,7 @@ public interface ProductSkuApi {
39 39 List<ProductSkuRespDTO> getSkuListBySpuId(Collection<Long> spuIds);
40 40  
41 41 /**
42   - * 更新 SKU 库存
  42 + * 更新 SKU 库存(增加 or 减少)
43 43 *
44 44 * @param updateStockReqDTO 更新请求
45 45 */
... ...
yudao-module-mall/yudao-module-product-api/src/main/java/cn/iocoder/yudao/module/product/api/spu/dto/ProductSpuRespDTO.java
... ... @@ -111,6 +111,11 @@ public class ProductSpuRespDTO {
111 111 // ========== 物流相关字段 =========
112 112  
113 113 /**
  114 + * 赠送积分
  115 + */
  116 + private Integer giveIntegral;
  117 +
  118 + /**
114 119 * 物流配置模板编号
115 120 *
116 121 * 对应 TradeDeliveryExpressTemplateDO 的 id 编号
... ... @@ -132,4 +137,15 @@ public class ProductSpuRespDTO {
132 137 */
133 138 private Integer clickCount;
134 139  
  140 +
  141 + // ========== 分销相关字段 =========
  142 +
  143 + /**
  144 + * 分销类型
  145 + *
  146 + * false - 默认
  147 + * true - 自行设置
  148 + */
  149 + private Boolean subCommissionType;
  150 +
135 151 }
... ...
yudao-module-mall/yudao-module-product-biz/pom.xml
... ... @@ -23,12 +23,6 @@
23 23 <artifactId>yudao-module-product-api</artifactId>
24 24 <version>${revision}</version>
25 25 </dependency>
26   - <!-- TODO 芋艿:看看~~~ -->
27   - <dependency>
28   - <groupId>cn.iocoder.boot</groupId>
29   - <artifactId>yudao-module-trade-api</artifactId>
30   - <version>${revision}</version>
31   - </dependency>
32 26 <dependency>
33 27 <groupId>cn.iocoder.boot</groupId>
34 28 <artifactId>yudao-module-member-api</artifactId>
... ...
yudao-module-mall/yudao-module-product-biz/src/main/java/cn/iocoder/yudao/module/product/api/property/ProductPropertyValueApiImpl.java
1 1 package cn.iocoder.yudao.module.product.api.property;
2 2  
3 3 import cn.iocoder.yudao.module.product.api.property.dto.ProductPropertyValueDetailRespDTO;
4   -import cn.iocoder.yudao.module.product.convert.propertyvalue.ProductPropertyValueConvert;
  4 +import cn.iocoder.yudao.module.product.convert.property.ProductPropertyValueConvert;
5 5 import cn.iocoder.yudao.module.product.service.property.ProductPropertyValueService;
6 6 import org.springframework.stereotype.Service;
7 7 import org.springframework.validation.annotation.Validated;
... ...
yudao-module-mall/yudao-module-product-biz/src/main/java/cn/iocoder/yudao/module/product/controller/admin/property/ProductPropertyValueController.java
1 1 package cn.iocoder.yudao.module.product.controller.admin.property;
2 2  
3   -import cn.hutool.core.collection.CollectionUtil;
4   -import cn.hutool.crypto.symmetric.AES;
5 3 import cn.iocoder.yudao.framework.common.pojo.CommonResult;
6 4 import cn.iocoder.yudao.framework.common.pojo.PageResult;
7 5 import cn.iocoder.yudao.module.product.controller.admin.property.vo.value.ProductPropertyValueCreateReqVO;
8 6 import cn.iocoder.yudao.module.product.controller.admin.property.vo.value.ProductPropertyValuePageReqVO;
9 7 import cn.iocoder.yudao.module.product.controller.admin.property.vo.value.ProductPropertyValueRespVO;
10 8 import cn.iocoder.yudao.module.product.controller.admin.property.vo.value.ProductPropertyValueUpdateReqVO;
11   -import cn.iocoder.yudao.module.product.convert.propertyvalue.ProductPropertyValueConvert;
  9 +import cn.iocoder.yudao.module.product.convert.property.ProductPropertyValueConvert;
12 10 import cn.iocoder.yudao.module.product.service.property.ProductPropertyValueService;
13 11 import io.swagger.v3.oas.annotations.Operation;
14 12 import io.swagger.v3.oas.annotations.Parameter;
... ... @@ -20,9 +18,6 @@ import org.springframework.web.bind.annotation.*;
20 18 import javax.annotation.Resource;
21 19 import javax.validation.Valid;
22 20  
23   -import java.util.Arrays;
24   -import java.util.List;
25   -
26 21 import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
27 22  
28 23 @Tag(name = "管理后台 - 商品属性值")
... ...
yudao-module-mall/yudao-module-product-biz/src/main/java/cn/iocoder/yudao/module/product/controller/app/spu/AppProductSpuController.java
1 1 package cn.iocoder.yudao.module.product.controller.app.spu;
2 2  
  3 +import cn.hutool.core.collection.CollUtil;
3 4 import cn.iocoder.yudao.framework.common.pojo.CommonResult;
4 5 import cn.iocoder.yudao.framework.common.pojo.PageResult;
  6 +import cn.iocoder.yudao.module.member.api.level.MemberLevelApi;
  7 +import cn.iocoder.yudao.module.member.api.level.dto.MemberLevelRespDTO;
  8 +import cn.iocoder.yudao.module.member.api.user.MemberUserApi;
  9 +import cn.iocoder.yudao.module.member.api.user.dto.MemberUserRespDTO;
5 10 import cn.iocoder.yudao.module.product.controller.app.spu.vo.AppProductSpuDetailRespVO;
6   -import cn.iocoder.yudao.module.product.controller.app.spu.vo.AppProductSpuPageRespVO;
7 11 import cn.iocoder.yudao.module.product.controller.app.spu.vo.AppProductSpuPageReqVO;
  12 +import cn.iocoder.yudao.module.product.controller.app.spu.vo.AppProductSpuPageRespVO;
8 13 import cn.iocoder.yudao.module.product.convert.spu.ProductSpuConvert;
9 14 import cn.iocoder.yudao.module.product.dal.dataobject.sku.ProductSkuDO;
10 15 import cn.iocoder.yudao.module.product.dal.dataobject.spu.ProductSpuDO;
... ... @@ -23,10 +28,12 @@ import org.springframework.web.bind.annotation.RestController;
23 28  
24 29 import javax.annotation.Resource;
25 30 import javax.validation.Valid;
  31 +import java.util.Collections;
26 32 import java.util.List;
27 33  
28 34 import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
29 35 import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
  36 +import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
30 37 import static cn.iocoder.yudao.module.product.enums.ErrorCodeConstants.SPU_NOT_ENABLE;
31 38 import static cn.iocoder.yudao.module.product.enums.ErrorCodeConstants.SPU_NOT_EXISTS;
32 39  
... ... @@ -41,6 +48,11 @@ public class AppProductSpuController {
41 48 @Resource
42 49 private ProductSkuService productSkuService;
43 50  
  51 + @Resource
  52 + private MemberLevelApi memberLevelApi;
  53 + @Resource
  54 + private MemberUserApi memberUserApi;
  55 +
44 56 @GetMapping("/list")
45 57 @Operation(summary = "获得商品 SPU 列表")
46 58 @Parameters({
... ... @@ -51,14 +63,32 @@ public class AppProductSpuController {
51 63 @RequestParam("recommendType") String recommendType,
52 64 @RequestParam(value = "count", defaultValue = "10") Integer count) {
53 65 List<ProductSpuDO> list = productSpuService.getSpuList(recommendType, count);
54   - return success(ProductSpuConvert.INSTANCE.convertListForGetSpuList(list));
  66 + if (CollUtil.isEmpty(list)) {
  67 + return success(Collections.emptyList());
  68 + }
  69 +
  70 + // 拼接返回
  71 + List<AppProductSpuPageRespVO> voList = ProductSpuConvert.INSTANCE.convertListForGetSpuList(list);
  72 + // 处理 vip 价格
  73 + MemberLevelRespDTO memberLevel = getMemberLevel();
  74 + voList.forEach(vo -> vo.setVipPrice(calculateVipPrice(vo.getPrice(), memberLevel)));
  75 + return success(voList);
55 76 }
56 77  
57 78 @GetMapping("/page")
58 79 @Operation(summary = "获得商品 SPU 分页")
59 80 public CommonResult<PageResult<AppProductSpuPageRespVO>> getSpuPage(@Valid AppProductSpuPageReqVO pageVO) {
60 81 PageResult<ProductSpuDO> pageResult = productSpuService.getSpuPage(pageVO);
61   - return success(ProductSpuConvert.INSTANCE.convertPageForGetSpuPage(pageResult));
  82 + if (CollUtil.isEmpty(pageResult.getList())) {
  83 + return success(PageResult.empty(pageResult.getTotal()));
  84 + }
  85 +
  86 + // 拼接返回
  87 + PageResult<AppProductSpuPageRespVO> voPageResult = ProductSpuConvert.INSTANCE.convertPageForGetSpuPage(pageResult);
  88 + // 处理 vip 价格
  89 + MemberLevelRespDTO memberLevel = getMemberLevel();
  90 + voPageResult.getList().forEach(vo -> vo.setVipPrice(calculateVipPrice(vo.getPrice(), memberLevel)));
  91 + return success(voPageResult);
62 92 }
63 93  
64 94 @GetMapping("/get-detail")
... ... @@ -74,10 +104,40 @@ public class AppProductSpuController {
74 104 throw exception(SPU_NOT_ENABLE);
75 105 }
76 106  
77   - // 查询商品 SKU
  107 + // 拼接返回
78 108 List<ProductSkuDO> skus = productSkuService.getSkuListBySpuId(spu.getId());
79   - // 拼接
80   - return success(ProductSpuConvert.INSTANCE.convertForGetSpuDetail(spu, skus));
  109 + AppProductSpuDetailRespVO detailVO = ProductSpuConvert.INSTANCE.convertForGetSpuDetail(spu, skus);
  110 + // 处理 vip 价格
  111 + MemberLevelRespDTO memberLevel = getMemberLevel();
  112 + detailVO.setVipPrice(calculateVipPrice(detailVO.getPrice(), memberLevel));
  113 + return success(detailVO);
  114 + }
  115 +
  116 + private MemberLevelRespDTO getMemberLevel() {
  117 + Long userId = getLoginUserId();
  118 + if (userId == null) {
  119 + return null;
  120 + }
  121 + MemberUserRespDTO user = memberUserApi.getUser(userId);
  122 + if (user.getLevelId() == null || user.getLevelId() <= 0) {
  123 + return null;
  124 + }
  125 + return memberLevelApi.getMemberLevel(user.getLevelId());
  126 + }
  127 +
  128 + /**
  129 + * 计算会员 VIP 优惠价格
  130 + *
  131 + * @param price 原价
  132 + * @param memberLevel 会员等级
  133 + * @return 优惠价格
  134 + */
  135 + public Integer calculateVipPrice(Integer price, MemberLevelRespDTO memberLevel) {
  136 + if (memberLevel == null || memberLevel.getDiscountPercent() == null) {
  137 + return 0;
  138 + }
  139 + Integer newPrice = price * memberLevel.getDiscountPercent() / 100;
  140 + return price - newPrice;
81 141 }
82 142  
83 143 }
... ...
yudao-module-mall/yudao-module-product-biz/src/main/java/cn/iocoder/yudao/module/product/convert/propertyvalue/ProductPropertyValueConvert.java renamed to yudao-module-mall/yudao-module-product-biz/src/main/java/cn/iocoder/yudao/module/product/convert/property/ProductPropertyValueConvert.java
1   -package cn.iocoder.yudao.module.product.convert.propertyvalue;
  1 +package cn.iocoder.yudao.module.product.convert.property;
2 2  
3 3 import cn.iocoder.yudao.framework.common.pojo.PageResult;
4 4 import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
... ...
yudao-module-mall/yudao-module-product-biz/src/main/java/cn/iocoder/yudao/module/product/convert/spu/ProductSpuConvert.java
... ... @@ -79,8 +79,6 @@ public interface ProductSpuConvert {
79 79 ProductSpuDO spu = list.get(i);
80 80 AppProductSpuPageRespVO spuVO = voList.get(i);
81 81 spuVO.setUnitName(DictFrameworkUtils.getDictDataLabel(DictTypeConstants.PRODUCT_UNIT, spu.getUnit()));
82   - // 计算 vip 价格 TODO 芋艿:临时的逻辑,等 vip 支持后
83   - spuVO.setVipPrice((int) (spuVO.getPrice() * 0.9));
84 82 }
85 83 return voList;
86 84 }
... ... @@ -95,11 +93,6 @@ public interface ProductSpuConvert {
95 93 .setUnitName(DictFrameworkUtils.getDictDataLabel(DictTypeConstants.PRODUCT_UNIT, spu.getUnit()));
96 94 // 处理 SKU
97 95 spuVO.setSkus(convertListForGetSpuDetail(skus));
98   - // 计算 vip 价格 TODO 芋艿:临时的逻辑,等 vip 支持后
99   - if (true) {
100   - spuVO.setVipPrice((int) (spuVO.getPrice() * 0.9));
101   - spuVO.getSkus().forEach(sku -> sku.setVipPrice((int) (sku.getPrice() * 0.9)));
102   - }
103 96 return spuVO;
104 97 }
105 98  
... ...
yudao-module-mall/yudao-module-product-biz/src/main/java/cn/iocoder/yudao/module/product/dal/dataobject/spu/ProductSpuDO.java
... ... @@ -179,6 +179,7 @@ public class ProductSpuDO extends BaseDO {
179 179 @TableField(typeHandler = JacksonTypeHandler.class)
180 180 private List<Long> giveCouponTemplateIds;
181 181  
  182 + // TODO @puhui999:字段估计要改成 brokerageType
182 183 /**
183 184 * 分销类型
184 185 *
... ...
yudao-module-mall/yudao-module-product-biz/src/main/java/cn/iocoder/yudao/module/product/package-info.java
1 1 /**
2   - * trade 模块,主要实现交易相关功能
  2 + * product 模块,主要实现交易相关功能
3 3 * 例如:订单、退款、购物车等功能。
4 4 *
5 5 * 1. Controller URL:以 /product/ 开头,避免和其它 Module 冲突
... ...
yudao-module-mall/yudao-module-product-biz/src/main/java/cn/iocoder/yudao/module/product/service/property/ProductPropertyValueServiceImpl.java
... ... @@ -5,7 +5,7 @@ import cn.iocoder.yudao.framework.common.pojo.PageResult;
5 5 import cn.iocoder.yudao.module.product.controller.admin.property.vo.value.ProductPropertyValueCreateReqVO;
6 6 import cn.iocoder.yudao.module.product.controller.admin.property.vo.value.ProductPropertyValuePageReqVO;
7 7 import cn.iocoder.yudao.module.product.controller.admin.property.vo.value.ProductPropertyValueUpdateReqVO;
8   -import cn.iocoder.yudao.module.product.convert.propertyvalue.ProductPropertyValueConvert;
  8 +import cn.iocoder.yudao.module.product.convert.property.ProductPropertyValueConvert;
9 9 import cn.iocoder.yudao.module.product.dal.dataobject.property.ProductPropertyDO;
10 10 import cn.iocoder.yudao.module.product.dal.dataobject.property.ProductPropertyValueDO;
11 11 import cn.iocoder.yudao.module.product.dal.mysql.property.ProductPropertyValueMapper;
... ...
yudao-module-mall/yudao-module-promotion-api/src/main/java/cn/iocoder/yudao/module/promotion/api/bargain/BargainActivityApi.java
... ... @@ -11,7 +11,7 @@ public interface BargainActivityApi {
11 11 * 更新砍价活动库存
12 12 *
13 13 * @param id 砍价活动编号
14   - * @param count 购买数量
  14 + * @param count 购买数量
15 15 */
16 16 void updateBargainActivityStock(Long id, Integer count);
17 17  
... ...
yudao-module-mall/yudao-module-promotion-api/src/main/java/cn/iocoder/yudao/module/promotion/enums/ErrorCodeConstants.java
... ... @@ -56,7 +56,6 @@ public interface ErrorCodeConstants {
56 56 ErrorCode SECKILL_ACTIVITY_DELETE_FAIL_STATUS_NOT_CLOSED_OR_END = new ErrorCode(1013008004, "秒杀活动未关闭或未结束,不能删除");
57 57 ErrorCode SECKILL_ACTIVITY_CLOSE_FAIL_STATUS_CLOSED = new ErrorCode(1013008005, "秒杀活动已关闭,不能重复关闭");
58 58 ErrorCode SECKILL_ACTIVITY_UPDATE_STOCK_FAIL = new ErrorCode(1013008006, "秒杀失败,原因秒杀库存不足");
59   - ErrorCode SECKILL_ACTIVITY_APP_STATUS_CLOSED = new ErrorCode(1013008007, "秒杀活动已关闭");
60 59  
61 60 // ========== 秒杀时段 1013009000 ==========
62 61 ErrorCode SECKILL_CONFIG_NOT_EXISTS = new ErrorCode(1013009000, "秒杀时段不存在");
... ... @@ -69,7 +68,6 @@ public interface ErrorCodeConstants {
69 68 ErrorCode COMBINATION_ACTIVITY_STATUS_DISABLE_NOT_UPDATE = new ErrorCode(1013010002, "拼团活动已关闭不能修改");
70 69 ErrorCode COMBINATION_ACTIVITY_DELETE_FAIL_STATUS_NOT_CLOSED_OR_END = new ErrorCode(1013010003, "拼团活动未关闭或未结束,不能删除");
71 70 ErrorCode COMBINATION_ACTIVITY_STATUS_DISABLE = new ErrorCode(1013010004, "拼团失败,原因:拼团活动已关闭");
72   - ErrorCode COMBINATION_ACTIVITY_APP_STATUS_DISABLE = new ErrorCode(1013010005, "拼团活动已关闭");
73 71  
74 72 // ========== 拼团记录 1013011000 ==========
75 73 ErrorCode COMBINATION_RECORD_NOT_EXISTS = new ErrorCode(1013011000, "拼团不存在");
... ...
yudao-module-mall/yudao-module-promotion-api/src/main/java/cn/iocoder/yudao/module/promotion/enums/common/PromotionTypeEnum.java
... ... @@ -22,8 +22,9 @@ public enum PromotionTypeEnum implements IntArrayValuable {
22 22 DISCOUNT_ACTIVITY(4, "限时折扣"),
23 23 REWARD_ACTIVITY(5, "满减送"),
24 24  
25   - MEMBER(6, "会员折扣"),
26   - COUPON(7, "优惠劵")
  25 + MEMBER_LEVEL(6, "会员折扣"),
  26 + COUPON(7, "优惠劵"),
  27 + POINT(8, "积分")
27 28 ;
28 29  
29 30 public static final int[] ARRAYS = Arrays.stream(values()).mapToInt(PromotionTypeEnum::getType).toArray();
... ...
yudao-module-mall/yudao-module-promotion-biz/src/main/java/cn/iocoder/yudao/module/promotion/controller/app/combination/AppCombinationActivityController.java
... ... @@ -24,14 +24,12 @@ import org.springframework.web.bind.annotation.RequestParam;
24 24 import org.springframework.web.bind.annotation.RestController;
25 25  
26 26 import javax.annotation.Resource;
27   -import java.util.Arrays;
  27 +import java.util.Collections;
28 28 import java.util.List;
29 29  
30 30 import static cn.hutool.core.util.ObjectUtil.defaultIfNull;
31   -import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
32 31 import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
33 32 import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
34   -import static cn.iocoder.yudao.module.promotion.enums.ErrorCodeConstants.COMBINATION_ACTIVITY_APP_STATUS_DISABLE;
35 33  
36 34 @Tag(name = "用户 APP - 拼团活动")
37 35 @RestController
... ... @@ -44,7 +42,7 @@ public class AppCombinationActivityController {
44 42 @Resource
45 43 private ProductSpuApi spuApi;
46 44  
47   -
  45 + // TODO 芋艿:增加 Spring Cache
48 46 @GetMapping("/list")
49 47 @Operation(summary = "获得拼团活动列表", description = "用于小程序首页")
50 48 @Parameter(name = "count", description = "需要展示的数量", example = "6")
... ... @@ -52,11 +50,10 @@ public class AppCombinationActivityController {
52 50 @RequestParam(name = "count", defaultValue = "6") Integer count) {
53 51 List<CombinationActivityDO> list = activityService.getCombinationActivityListByCount(defaultIfNull(count, 6));
54 52 if (CollUtil.isEmpty(list)) {
55   - return success(CombinationActivityConvert.INSTANCE.convertAppList(list));
  53 + return success(Collections.emptyList());
56 54 }
57   -
  55 + // 拼接返回
58 56 List<ProductSpuRespDTO> spuList = spuApi.getSpuList(convertList(list, CombinationActivityDO::getSpuId));
59   - // TODO 芋艿:增加 Spring Cache
60 57 return success(CombinationActivityConvert.INSTANCE.convertAppList(list, spuList));
61 58 }
62 59  
... ... @@ -67,7 +64,7 @@ public class AppCombinationActivityController {
67 64 if (CollUtil.isEmpty(result.getList())) {
68 65 return success(PageResult.empty(result.getTotal()));
69 66 }
70   -
  67 + // 拼接返回
71 68 List<ProductSpuRespDTO> spuList = spuApi.getSpuList(convertList(result.getList(), CombinationActivityDO::getSpuId));
72 69 return success(CombinationActivityConvert.INSTANCE.convertAppPage(result, spuList));
73 70 }
... ... @@ -78,15 +75,12 @@ public class AppCombinationActivityController {
78 75 public CommonResult<AppCombinationActivityDetailRespVO> getCombinationActivityDetail(@RequestParam("id") Long id) {
79 76 // 1、获取活动
80 77 CombinationActivityDO combinationActivity = activityService.getCombinationActivity(id);
81   - if (combinationActivity == null) {
  78 + if (combinationActivity == null
  79 + || ObjectUtil.equal(combinationActivity.getStatus(), CommonStatusEnum.DISABLE.getStatus())) {
82 80 return success(null);
83 81 }
84   - if (ObjectUtil.equal(combinationActivity.getStatus(), CommonStatusEnum.DISABLE.getStatus())) {
85   - throw exception(COMBINATION_ACTIVITY_APP_STATUS_DISABLE);
86   - }
87   -
88 82 // 2、获取活动商品
89   - List<CombinationProductDO> products = activityService.getCombinationProductsByActivityIds(Arrays.asList(combinationActivity.getId()));
  83 + List<CombinationProductDO> products = activityService.getCombinationProductsByActivityId(combinationActivity.getId());
90 84 return success(CombinationActivityConvert.INSTANCE.convert3(combinationActivity, products));
91 85 }
92 86  
... ...
yudao-module-mall/yudao-module-promotion-biz/src/main/java/cn/iocoder/yudao/module/promotion/controller/app/seckill/AppSeckillActivityController.java
1 1 package cn.iocoder.yudao.module.promotion.controller.app.seckill;
2 2  
  3 +import cn.hutool.core.collection.CollUtil;
3 4 import cn.hutool.core.util.ObjectUtil;
4 5 import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
5 6 import cn.iocoder.yudao.framework.common.pojo.CommonResult;
... ... @@ -29,10 +30,8 @@ import org.springframework.web.bind.annotation.RestController;
29 30 import javax.annotation.Resource;
30 31 import java.util.List;
31 32  
32   -import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
33 33 import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
34 34 import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
35   -import static cn.iocoder.yudao.module.promotion.enums.ErrorCodeConstants.SECKILL_ACTIVITY_APP_STATUS_CLOSED;
36 35  
37 36 @Tag(name = "用户 App - 秒杀活动")
38 37 @RestController
... ... @@ -48,6 +47,7 @@ public class AppSeckillActivityController {
48 47 @Resource
49 48 private ProductSpuApi spuApi;
50 49  
  50 + // TODO 芋艿:需要增加 spring cache
51 51 @GetMapping("/get-now")
52 52 @Operation(summary = "获得当前秒杀活动", description = "获取当前正在进行的活动,提供给首页使用")
53 53 public CommonResult<AppSeckillActivityNowRespVO> getNowSeckillActivity() {
... ... @@ -61,7 +61,6 @@ public class AppSeckillActivityController {
61 61 List<SeckillActivityDO> activityList = activityService.getSeckillActivityListByConfigIdAndStatus(configList.getId(), CommonStatusEnum.ENABLE.getStatus());
62 62 // 3 获取 spu 信息
63 63 List<ProductSpuRespDTO> spuList = spuApi.getSpuList(convertList(activityList, SeckillActivityDO::getSpuId));
64   - // TODO 芋艿:需要增加 spring cache
65 64 return success(SeckillActivityConvert.INSTANCE.convert(configList, activityList, spuList));
66 65 }
67 66  
... ... @@ -70,7 +69,9 @@ public class AppSeckillActivityController {
70 69 public CommonResult<PageResult<AppSeckillActivityRespVO>> getSeckillActivityPage(AppSeckillActivityPageReqVO pageReqVO) {
71 70 // 1. 查询满足当前阶段的活动
72 71 PageResult<SeckillActivityDO> pageResult = activityService.getSeckillActivityAppPageByConfigId(pageReqVO);
73   -
  72 + if (CollUtil.isEmpty(pageResult.getList())) {
  73 + return success(PageResult.empty(pageResult.getTotal()));
  74 + }
74 75 // 2. 拼接数据
75 76 List<ProductSpuRespDTO> spuList = spuApi.getSpuList(convertList(pageResult.getList(), SeckillActivityDO::getSpuId));
76 77 return success(SeckillActivityConvert.INSTANCE.convertPage(pageResult, spuList));
... ... @@ -88,16 +89,14 @@ public class AppSeckillActivityController {
88 89  
89 90 // 2. 获取活动
90 91 SeckillActivityDO seckillActivity = activityService.getSeckillActivity(id);
91   - if (seckillActivity == null) {
  92 + if (seckillActivity == null
  93 + || ObjectUtil.equal(seckillActivity.getStatus(), CommonStatusEnum.DISABLE.getStatus())) {
92 94 return success(null);
93 95 }
94   - if (ObjectUtil.equal(seckillActivity.getStatus(), CommonStatusEnum.DISABLE.getStatus())) {
95   - throw exception(SECKILL_ACTIVITY_APP_STATUS_CLOSED);
96   - }
97 96  
98 97 // 3. 拼接数据
99   - List<SeckillProductDO> products = activityService.getSeckillProductListByActivityId(seckillActivity.getId());
100   - return success(SeckillActivityConvert.INSTANCE.convert3(seckillActivity, products, configList));
  98 + List<SeckillProductDO> productList = activityService.getSeckillProductListByActivityId(seckillActivity.getId());
  99 + return success(SeckillActivityConvert.INSTANCE.convert3(seckillActivity, productList, configList));
101 100 }
102 101  
103 102 }
... ...
yudao-module-mall/yudao-module-promotion-biz/src/main/java/cn/iocoder/yudao/module/promotion/controller/app/seckill/AppSeckillConfigController.java
... ... @@ -28,7 +28,8 @@ public class AppSeckillConfigController {
28 28 @GetMapping("/list")
29 29 @Operation(summary = "获得秒杀时间段列表")
30 30 public CommonResult<List<AppSeckillConfigRespVO>> getSeckillConfigList() {
31   - return success(SeckillConfigConvert.INSTANCE.convertList2(configService.getSeckillConfigListByStatus(CommonStatusEnum.ENABLE.getStatus())));
  31 + return success(SeckillConfigConvert.INSTANCE.convertList2(
  32 + configService.getSeckillConfigListByStatus(CommonStatusEnum.ENABLE.getStatus())));
32 33 }
33 34  
34 35 }
... ...
yudao-module-mall/yudao-module-promotion-biz/src/main/java/cn/iocoder/yudao/module/promotion/convert/bargain/BargainActivityConvert.java
... ... @@ -73,9 +73,7 @@ public interface BargainActivityConvert {
73 73 // 拼接关联属性
74 74 Map<Long, ProductSpuRespDTO> spuMap = convertMap(spuList, ProductSpuRespDTO::getId);
75 75 List<AppBargainActivityRespVO> list = CollectionUtils.convertList(result.getList(), item -> {
76   - findAndThen(spuMap, item.getSpuId(), spu -> {
77   - item.setPicUrl(spu.getPicUrl()).setMarketPrice(spu.getMarketPrice());
78   - });
  76 + findAndThen(spuMap, item.getSpuId(), spu -> item.setPicUrl(spu.getPicUrl()).setMarketPrice(spu.getMarketPrice()));
79 77 return item;
80 78 });
81 79 result.setList(list);
... ... @@ -88,9 +86,7 @@ public interface BargainActivityConvert {
88 86 List<AppBargainActivityRespVO> activityList = convertAppList(list);
89 87 Map<Long, ProductSpuRespDTO> spuMap = convertMap(spuList, ProductSpuRespDTO::getId);
90 88 return CollectionUtils.convertList(activityList, item -> {
91   - findAndThen(spuMap, item.getSpuId(), spu -> {
92   - item.setPicUrl(spu.getPicUrl()).setMarketPrice(spu.getMarketPrice());
93   - });
  89 + findAndThen(spuMap, item.getSpuId(), spu -> item.setPicUrl(spu.getPicUrl()).setMarketPrice(spu.getMarketPrice()));
94 90 return item;
95 91 });
96 92 }
... ...
yudao-module-mall/yudao-module-promotion-biz/src/main/java/cn/iocoder/yudao/module/promotion/convert/combination/CombinationActivityConvert.java
... ... @@ -61,9 +61,7 @@ public interface CombinationActivityConvert {
61 61 Map<Long, ProductSpuRespDTO> spuMap = convertMap(spuList, ProductSpuRespDTO::getId);
62 62 PageResult<CombinationActivityRespVO> pageResult = convertPage(page);
63 63 pageResult.getList().forEach(item -> {
64   - MapUtils.findAndThen(spuMap, item.getSpuId(), spu -> {
65   - item.setSpuName(spu.getName()).setPicUrl(spu.getPicUrl());
66   - });
  64 + MapUtils.findAndThen(spuMap, item.getSpuId(), spu -> item.setSpuName(spu.getName()).setPicUrl(spu.getPicUrl()));
67 65 item.setProducts(convertList2(productList));
68 66 });
69 67 return pageResult;
... ... @@ -118,9 +116,7 @@ public interface CombinationActivityConvert {
118 116 List<AppCombinationActivityRespVO> activityList = convertAppList(list);
119 117 Map<Long, ProductSpuRespDTO> spuMap = convertMap(spuList, ProductSpuRespDTO::getId);
120 118 return CollectionUtils.convertList(activityList, item -> {
121   - findAndThen(spuMap, item.getSpuId(), spu -> {
122   - item.setPicUrl(spu.getPicUrl()).setMarketPrice(spu.getMarketPrice());
123   - });
  119 + findAndThen(spuMap, item.getSpuId(), spu -> item.setPicUrl(spu.getPicUrl()).setMarketPrice(spu.getMarketPrice()));
124 120 return item;
125 121 });
126 122 }
... ...
yudao-module-mall/yudao-module-promotion-biz/src/main/java/cn/iocoder/yudao/module/promotion/convert/seckill/seckillactivity/SeckillActivityConvert.java
... ... @@ -114,11 +114,8 @@ public interface SeckillActivityConvert {
114 114 PageResult<AppSeckillActivityRespVO> result = convertPage1(pageResult);
115 115 Map<Long, ProductSpuRespDTO> spuMap = convertMap(spuList, ProductSpuRespDTO::getId);
116 116 List<AppSeckillActivityRespVO> list = CollectionUtils.convertList(result.getList(), item -> {
117   - findAndThen(spuMap, item.getSpuId(), spu -> {
118   - item.setPicUrl(spu.getPicUrl())
119   - .setMarketPrice(spu.getMarketPrice())
120   - .setUnitName(DictFrameworkUtils.getDictDataLabel(DictTypeConstants.PRODUCT_UNIT, spu.getUnit()));
121   - });
  117 + findAndThen(spuMap, item.getSpuId(), spu -> item.setPicUrl(spu.getPicUrl()).setMarketPrice(spu.getMarketPrice())
  118 + .setUnitName(DictFrameworkUtils.getDictDataLabel(DictTypeConstants.PRODUCT_UNIT, spu.getUnit())));
122 119 return item;
123 120 });
124 121 result.setList(list);
... ... @@ -132,6 +129,7 @@ public interface SeckillActivityConvert {
132 129 default AppSeckillActivityDetailRespVO convert3(SeckillActivityDO seckillActivity, List<SeckillProductDO> products, SeckillConfigDO filteredConfig) {
133 130 return convert2(seckillActivity)
134 131 .setProducts(convertList1(products))
  132 + // TODO @puhui999:要不要在里面 default 一个方法,处理这个事件;简洁一点;
135 133 .setStartTime(LocalDateTimeUtil.parse(LocalDateTimeUtil.format(seckillActivity.getStartTime(), "yyyy-MM-dd") + " " + filteredConfig.getStartTime(),
136 134 "yyyy-MM-dd HH:mm:ss")) // 活动开始日期和时段结合
137 135 .setEndTime(LocalDateTimeUtil.parse(LocalDateTimeUtil.format(seckillActivity.getEndTime(), "yyyy-MM-dd") + " " + filteredConfig.getEndTime(),
... ...
yudao-module-mall/yudao-module-promotion-biz/src/main/java/cn/iocoder/yudao/module/promotion/dal/mysql/bargain/BargainActivityMapper.java
... ... @@ -38,7 +38,7 @@ public interface BargainActivityMapper extends BaseMapperX&lt;BargainActivityDO&gt; {
38 38 * @param count 扣减的库存数量
39 39 * @return 影响的行数
40 40 */
41   - default int updateActivityStock(Long id, int count) {
  41 + default int updateStock(Long id, int count) {
42 42 return update(null, new LambdaUpdateWrapper<BargainActivityDO>()
43 43 .eq(BargainActivityDO::getId, id)
44 44 .ge(BargainActivityDO::getStock, count)
... ...
yudao-module-mall/yudao-module-promotion-biz/src/main/java/cn/iocoder/yudao/module/promotion/dal/mysql/combination/CombinationActivityMapper.java
... ... @@ -29,26 +29,12 @@ public interface CombinationActivityMapper extends BaseMapperX&lt;CombinationActivi
29 29 return selectList(CombinationActivityDO::getStatus, status);
30 30 }
31 31  
32   - /**
33   - * 查询 status 状态的活动分页
34   - *
35   - * @param pageParam 分页参数
36   - * @param status 状态
37   - * @return 活动分页
38   - */
39 32 default PageResult<CombinationActivityDO> selectPage(PageParam pageParam, Integer status) {
40 33 return selectPage(pageParam, new LambdaQueryWrapperX<CombinationActivityDO>()
41 34 .eq(CombinationActivityDO::getStatus, status));
42 35 }
43 36  
44   - /**
45   - * 查询 status 状态的活动分页
46   - *
47   - * @param status 状态
48   - * @param count 限制条数
49   - * @return 活动分页
50   - */
51   - default List<CombinationActivityDO> selectList(Integer status, Integer count) {
  37 + default List<CombinationActivityDO> selectListByStatus(Integer status, Integer count) {
52 38 return selectList(new LambdaQueryWrapperX<CombinationActivityDO>()
53 39 .eq(CombinationActivityDO::getStatus, status)
54 40 .last("LIMIT " + count));
... ...
yudao-module-mall/yudao-module-promotion-biz/src/main/java/cn/iocoder/yudao/module/promotion/dal/mysql/seckill/seckillactivity/SeckillActivityMapper.java
... ... @@ -41,7 +41,7 @@ public interface SeckillActivityMapper extends BaseMapperX&lt;SeckillActivityDO&gt; {
41 41 * @param count 扣减的库存数量
42 42 * @return 影响的行数
43 43 */
44   - default int updateActivityStock(Long id, int count) {
  44 + default int updateStock(Long id, int count) {
45 45 return update(null, new LambdaUpdateWrapper<SeckillActivityDO>()
46 46 .eq(SeckillActivityDO::getId, id)
47 47 .gt(SeckillActivityDO::getTotalStock, 0)
... ...
yudao-module-mall/yudao-module-promotion-biz/src/main/java/cn/iocoder/yudao/module/promotion/dal/mysql/seckill/seckillactivity/SeckillProductMapper.java
... ... @@ -16,8 +16,13 @@ import java.util.List;
16 16 @Mapper
17 17 public interface SeckillProductMapper extends BaseMapperX<SeckillProductDO> {
18 18  
19   - default List<SeckillProductDO> selectListByActivityId(Long id) {
20   - return selectList(SeckillProductDO::getActivityId, id);
  19 + default List<SeckillProductDO> selectListByActivityId(Long activityId) {
  20 + return selectList(SeckillProductDO::getActivityId, activityId);
  21 + }
  22 +
  23 + default SeckillProductDO selectByActivityIdAndSkuId(Long activityId, Long skuId) {
  24 + return selectOne(SeckillProductDO::getActivityId, activityId,
  25 + SeckillProductDO::getSkuId, skuId);
21 26 }
22 27  
23 28 default List<SeckillProductDO> selectListByActivityId(Collection<Long> ids) {
... ... @@ -31,7 +36,7 @@ public interface SeckillProductMapper extends BaseMapperX&lt;SeckillProductDO&gt; {
31 36 * @param count 扣减的库存数量
32 37 * @return 影响的行数
33 38 */
34   - default int updateActivityStock(Long id, int count) {
  39 + default int updateStock(Long id, int count) {
35 40 return update(null, new LambdaUpdateWrapper<SeckillProductDO>()
36 41 .eq(SeckillProductDO::getId, id)
37 42 .gt(SeckillProductDO::getStock, count)
... ...
yudao-module-mall/yudao-module-promotion-biz/src/main/java/cn/iocoder/yudao/module/promotion/service/bargain/BargainActivityServiceImpl.java
... ... @@ -75,16 +75,18 @@ public class BargainActivityServiceImpl implements BargainActivityService {
75 75 }
76 76  
77 77 @Override
78   - @Transactional(rollbackFor = Exception.class)
79 78 public void updateBargainActivityStock(Long id, Integer count) {
80 79 // 查询砍价活动
81 80 BargainActivityDO activity = getBargainActivity(id);
82 81 if (activity == null) {
83 82 throw exception(BARGAIN_ACTIVITY_NOT_EXISTS);
84 83 }
  84 + if (count > activity.getStock()) {
  85 + throw exception(BARGAIN_ACTIVITY_UPDATE_STOCK_FAIL);
  86 + }
85 87  
86 88 // 更新砍价库存
87   - int updateCount = bargainActivityMapper.updateActivityStock(id, count);
  89 + int updateCount = bargainActivityMapper.updateStock(id, count);
88 90 if (updateCount == 0) {
89 91 throw exception(BARGAIN_ACTIVITY_UPDATE_STOCK_FAIL);
90 92 }
... ...
yudao-module-mall/yudao-module-promotion-biz/src/main/java/cn/iocoder/yudao/module/promotion/service/combination/CombinationActivityService.java
... ... @@ -10,6 +10,7 @@ import cn.iocoder.yudao.module.promotion.dal.dataobject.combination.CombinationP
10 10  
11 11 import javax.validation.Valid;
12 12 import java.util.Collection;
  13 +import java.util.Collections;
13 14 import java.util.List;
14 15  
15 16 /**
... ... @@ -68,6 +69,16 @@ public interface CombinationActivityService {
68 69 /**
69 70 * 获得拼团活动商品列表
70 71 *
  72 + * @param activityId 拼团活动 id
  73 + * @return 拼团活动的商品列表
  74 + */
  75 + default List<CombinationProductDO> getCombinationProductsByActivityId(Long activityId) {
  76 + return getCombinationProductsByActivityIds(Collections.singletonList(activityId));
  77 + }
  78 +
  79 + /**
  80 + * 获得拼团活动商品列表
  81 + *
71 82 * @param activityIds 拼团活动 ids
72 83 * @return 拼团活动的商品列表
73 84 */
... ...
yudao-module-mall/yudao-module-promotion-biz/src/main/java/cn/iocoder/yudao/module/promotion/service/combination/CombinationActivityServiceImpl.java
... ... @@ -247,7 +247,7 @@ public class CombinationActivityServiceImpl implements CombinationActivityServic
247 247  
248 248 @Override
249 249 public List<CombinationActivityDO> getCombinationActivityListByCount(Integer count) {
250   - return combinationActivityMapper.selectList(CommonStatusEnum.ENABLE.getStatus(), count);
  250 + return combinationActivityMapper.selectListByStatus(CommonStatusEnum.ENABLE.getStatus(), count);
251 251 }
252 252  
253 253 @Override
... ...
yudao-module-mall/yudao-module-promotion-biz/src/main/java/cn/iocoder/yudao/module/promotion/service/combination/CombinationRecordServiceImpl.java
... ... @@ -96,12 +96,15 @@ public class CombinationRecordServiceImpl implements CombinationRecordService {
96 96 return recordDO;
97 97 }
98 98  
  99 + // TODO @puhui999:有一个应该在创建那要做下;就是当前 activityId 已经有未支付的订单,不允许在发起新的;要么支付,要么去掉先;
  100 +
99 101 @Override
100 102 @Transactional(rollbackFor = Exception.class)
101 103 public void createCombinationRecord(CombinationRecordCreateReqDTO reqDTO) {
102 104 // 1.1 校验拼团活动
103 105 CombinationActivityDO activity = combinationActivityService.validateCombinationActivityExists(reqDTO.getActivityId());
104 106 // 1.2 需要校验下,他当前是不是已经参加了该拼团;
  107 + // TODO @puhui999:拼团应该可以重复参加;应该去校验总共的上限哈,就是 activity.totalLimitCount
105 108 CombinationRecordDO recordDO = recordMapper.selectByUserIdAndOrderId(reqDTO.getUserId(), reqDTO.getOrderId());
106 109 if (recordDO != null) {
107 110 throw exception(COMBINATION_RECORD_EXISTS);
... ... @@ -111,6 +114,7 @@ public class CombinationRecordServiceImpl implements CombinationRecordService {
111 114 if (CollUtil.isNotEmpty(recordDOList)) {
112 115 throw exception(COMBINATION_RECORD_FAILED_HAVE_JOINED);
113 116 }
  117 + // TODO @puhui999:有个开始时间未校验
114 118 // 1.4 校验当前活动是否过期
115 119 if (LocalDateTime.now().isAfter(activity.getEndTime())) {
116 120 throw exception(COMBINATION_RECORD_FAILED_TIME_END);
... ... @@ -128,6 +132,8 @@ public class CombinationRecordServiceImpl implements CombinationRecordService {
128 132 }
129 133 }
130 134  
  135 + // TODO @puhui999:单次限购
  136 +
131 137 // 2. 创建拼团记录
132 138 MemberUserRespDTO user = memberUserApi.getUser(reqDTO.getUserId());
133 139 ProductSpuRespDTO spu = productSpuApi.getSpu(reqDTO.getSpuId());
... ...
yudao-module-mall/yudao-module-promotion-biz/src/main/java/cn/iocoder/yudao/module/promotion/service/seckill/SeckillActivityServiceImpl.java
... ... @@ -150,31 +150,25 @@ public class SeckillActivityServiceImpl implements SeckillActivityService {
150 150 @Override
151 151 @Transactional(rollbackFor = Exception.class)
152 152 public void updateSeckillStock(Long id, Long skuId, Integer count) {
153   - // 1、校验秒杀活动是否存在
  153 + // 1.1 校验活动库存是否充足
154 154 SeckillActivityDO seckillActivity = getSeckillActivity(id);
155   - // 1.1、校验库存是否充足
156   - if (seckillActivity.getTotalStock() < count) {
  155 + if (count > seckillActivity.getTotalStock()) {
157 156 throw exception(SECKILL_ACTIVITY_UPDATE_STOCK_FAIL);
158 157 }
159   -
160   - // 2、获取活动商品
161   - List<SeckillProductDO> products = getSeckillProductListByActivityId(id);
162   - // 2.1、过滤出购买的商品
163   - SeckillProductDO product = findFirst(products, item -> ObjectUtil.equal(skuId, item.getSkuId()));
164   - // 2.2、检查活动商品库存是否充足
165   - boolean isSufficient = product == null || (product.getStock() == 0 || (product.getStock() < count) || (product.getStock() - count) < 0);
166   - if (isSufficient) {
  158 + // 1.2 校验商品库存是否充足
  159 + SeckillProductDO product = seckillProductMapper.selectByActivityIdAndSkuId(id, skuId);
  160 + if (product == null || count > product.getStock()) {
167 161 throw exception(SECKILL_ACTIVITY_UPDATE_STOCK_FAIL);
168 162 }
169 163  
170   - // 3、更新活动商品库存
171   - int updateCount = seckillProductMapper.updateActivityStock(product.getId(), count);
  164 + // 2.1 更新活动商品库存
  165 + int updateCount = seckillProductMapper.updateStock(product.getId(), count);
172 166 if (updateCount == 0) {
173 167 throw exception(SECKILL_ACTIVITY_UPDATE_STOCK_FAIL);
174 168 }
175 169  
176   - // 4、更新活动库存
177   - updateCount = seckillActivityMapper.updateActivityStock(seckillActivity.getId(), count);
  170 + // 2.2 更新活动库存
  171 + updateCount = seckillActivityMapper.updateStock(seckillActivity.getId(), count);
178 172 if (updateCount == 0) {
179 173 throw exception(SECKILL_ACTIVITY_UPDATE_STOCK_FAIL);
180 174 }
... ...
yudao-module-mall/yudao-module-trade-api/src/main/java/cn/iocoder/yudao/module/trade/enums/DictTypeConstants.java 0 → 100644
  1 +package cn.iocoder.yudao.module.trade.enums;
  2 +
  3 +/**
  4 + * Trade 字典类型的枚举类
  5 + *
  6 + * @author owen
  7 + */
  8 +public interface DictTypeConstants {
  9 +
  10 + String BROKERAGE_WITHDRAW_STATUS = "brokerage_withdraw_status"; // 佣金提现状态
  11 +
  12 +}
... ...
yudao-module-mall/yudao-module-trade-api/src/main/java/cn/iocoder/yudao/module/trade/enums/ErrorCodeConstants.java
... ... @@ -12,12 +12,6 @@ import cn.iocoder.yudao.framework.common.exception.ErrorCode;
12 12 public interface ErrorCodeConstants {
13 13  
14 14 // ========== Order 模块 1011000000 ==========
15   - ErrorCode ORDER_CREATE_SKU_NOT_FOUND = new ErrorCode(1011000001, "商品 SKU 不存在");
16   - ErrorCode ORDER_CREATE_SPU_NOT_SALE = new ErrorCode(1011000002, "商品 SPU 不可售卖");
17   - ErrorCode ORDER_CREATE_SKU_STOCK_NOT_ENOUGH = new ErrorCode(1011000004, "商品 SKU 库存不足");
18   - ErrorCode ORDER_CREATE_SPU_NOT_FOUND = new ErrorCode(1011000005, "商品 SPU 不可售卖");
19   - ErrorCode ORDER_CREATE_ADDRESS_NOT_FOUND = new ErrorCode(1011000006, "收货地址不存在");
20   -
21 15 ErrorCode ORDER_ITEM_NOT_FOUND = new ErrorCode(1011000010, "交易订单项不存在");
22 16 ErrorCode ORDER_NOT_FOUND = new ErrorCode(1011000011, "交易订单不存在");
23 17 ErrorCode ORDER_ITEM_UPDATE_AFTER_SALE_STATUS_FAIL = new ErrorCode(1011000012, "交易订单项更新售后状态失败,请重试");
... ... @@ -37,6 +31,7 @@ public interface ErrorCodeConstants {
37 31 ErrorCode ORDER_UPDATE_PRICE_FAIL_PAID = new ErrorCode(1011000026, "支付订单调价失败,原因:支付订单已付款,不能调价");
38 32 ErrorCode ORDER_UPDATE_PRICE_FAIL_EQUAL = new ErrorCode(1011000027, "支付订单调价失败,原因:价格没有变化");
39 33 ErrorCode ORDER_UPDATE_PRICE_FAIL_NOT_ITEM = new ErrorCode(1011000028, "支付订单调价失败,原因:订单项不存在");
  34 + ErrorCode ORDER_DELETE_FAIL_STATUS_NOT_CANCEL = new ErrorCode(1011000029, "交易订单删除失败,订单不是【已取消】状态");
40 35  
41 36 // ========== After Sale 模块 1011000100 ==========
42 37 ErrorCode AFTER_SALE_NOT_FOUND = new ErrorCode(1011000100, "售后单不存在");
... ... @@ -58,8 +53,8 @@ public interface ErrorCodeConstants {
58 53  
59 54 // ========== Price 相关 1011003000 ============
60 55 ErrorCode PRICE_CALCULATE_PAY_PRICE_ILLEGAL = new ErrorCode(1011003000, "支付价格计算异常,原因:价格小于等于 0");
61   - ErrorCode PRICE_CALCULATE_DELIVERY_PRICE_USER_ADDR_IS_EMPTY = new ErrorCode(1011003001, "计算快递运费异常,收件人地址编号为空");
62 56 ErrorCode PRICE_CALCULATE_DELIVERY_PRICE_TEMPLATE_NOT_FOUND = new ErrorCode(1011003002, "计算快递运费异常,找不到对应的运费模板");
  57 + ErrorCode PRICE_CALCULATE_COUPON_NOT_MATCH_NORMAL_ORDER = new ErrorCode(1011003004, "参与秒杀、拼团、砍价的营销商品,无法使用优惠劵");
63 58  
64 59 // ========== 物流 Express 模块 1011004000 ==========
65 60 ErrorCode EXPRESS_NOT_EXISTS = new ErrorCode(1011004000, "快递公司不存在");
... ... @@ -92,5 +87,7 @@ public interface ErrorCodeConstants {
92 87 // ========== 分销提现 模块 1011008000 ==========
93 88 ErrorCode BROKERAGE_WITHDRAW_NOT_EXISTS = new ErrorCode(1011008000, "佣金提现记录不存在");
94 89 ErrorCode BROKERAGE_WITHDRAW_STATUS_NOT_AUDITING = new ErrorCode(1011008001, "佣金提现记录状态不是审核中");
  90 + ErrorCode BROKERAGE_WITHDRAW_MIN_PRICE = new ErrorCode(1011008002, "提现金额不能低于 {} 元");
  91 + ErrorCode BROKERAGE_WITHDRAW_USER_BALANCE_NOT_ENOUGH = new ErrorCode(1011008003, "您当前最多可提现 {} 元");
95 92  
96 93 }
... ...
yudao-module-mall/yudao-module-trade-api/src/main/java/cn/iocoder/yudao/module/trade/enums/brokerage/BrokerageRecordBizTypeEnum.java
... ... @@ -17,6 +17,7 @@ public enum BrokerageRecordBizTypeEnum implements IntArrayValuable {
17 17  
18 18 ORDER(1, "获得推广佣金", "获得推广佣金 {}", true),
19 19 WITHDRAW(2, "提现申请", "提现申请扣除佣金 {}", false),
  20 + WITHDRAW_REJECT(3, "提现申请驳回", "提现申请驳回返还佣金 {}", true),
20 21 ;
21 22  
22 23 public static final int[] ARRAYS = Arrays.stream(values()).mapToInt(BrokerageRecordBizTypeEnum::getType).toArray();
... ...
yudao-module-mall/yudao-module-trade-api/src/main/java/cn/iocoder/yudao/module/trade/enums/delivery/DeliveryExpressChargeModeEnum.java
... ... @@ -16,7 +16,7 @@ import java.util.Arrays;
16 16 @Getter
17 17 public enum DeliveryExpressChargeModeEnum implements IntArrayValuable {
18 18  
19   - PIECE(1, "按件"),
  19 + COUNT(1, "按件"),
20 20 WEIGHT(2,"按重量"),
21 21 VOLUME(3, "按体积");
22 22  
... ...
yudao-module-mall/yudao-module-trade-api/src/main/java/cn/iocoder/yudao/module/trade/enums/delivery/DeliveryTypeEnum.java
... ... @@ -15,16 +15,15 @@ import java.util.Arrays;
15 15 @AllArgsConstructor
16 16 public enum DeliveryTypeEnum implements IntArrayValuable {
17 17  
18   - NULL(0, "无需物流"),
19 18 EXPRESS(1, "快递发货"),
20 19 PICK_UP(2, "用户自提"),;
21 20  
22   - public static final int[] ARRAYS = Arrays.stream(values()).mapToInt(DeliveryTypeEnum::getMode).toArray();
  21 + public static final int[] ARRAYS = Arrays.stream(values()).mapToInt(DeliveryTypeEnum::getType).toArray();
23 22  
24 23 /**
25 24 * 配送方式
26 25 */
27   - private final Integer mode;
  26 + private final Integer type;
28 27 /**
29 28 * 状态名
30 29 */
... ...
yudao-module-mall/yudao-module-trade-api/src/main/java/cn/iocoder/yudao/module/trade/enums/order/TradeOrderOperateTypeEnum.java
... ... @@ -14,7 +14,10 @@ import lombok.RequiredArgsConstructor;
14 14 public enum TradeOrderOperateTypeEnum {
15 15  
16 16 MEMBER_CREATE(1, "用户下单"),
17   - TEST(2, "用户({nickname})做了({thing})"),
  17 + MEMBER_RECEIVE(30, "用户已收货"),
  18 + MEMBER_COMMENT(31, "用户评价"),
  19 + MEMBER_CANCEL(40, "取消订单"),
  20 + MEMBER_DELETE(41, "删除订单"),
18 21 ;
19 22  
20 23 /**
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/admin/aftersale/TradeAfterSaleController.java
... ... @@ -8,11 +8,11 @@ import cn.iocoder.yudao.module.member.api.user.MemberUserApi;
8 8 import cn.iocoder.yudao.module.member.api.user.dto.MemberUserRespDTO;
9 9 import cn.iocoder.yudao.module.pay.api.notify.dto.PayRefundNotifyReqDTO;
10 10 import cn.iocoder.yudao.module.trade.controller.admin.aftersale.vo.*;
  11 +import cn.iocoder.yudao.module.trade.controller.admin.aftersale.vo.log.TradeAfterSaleLogRespVO;
11 12 import cn.iocoder.yudao.module.trade.convert.aftersale.TradeAfterSaleConvert;
12 13 import cn.iocoder.yudao.module.trade.dal.dataobject.aftersale.TradeAfterSaleDO;
13 14 import cn.iocoder.yudao.module.trade.dal.dataobject.order.TradeOrderDO;
14 15 import cn.iocoder.yudao.module.trade.dal.dataobject.order.TradeOrderItemDO;
15   -import cn.iocoder.yudao.module.trade.framework.aftersalelog.core.dto.TradeAfterSaleLogRespVO;
16 16 import cn.iocoder.yudao.module.trade.framework.aftersalelog.core.service.AfterSaleLogService;
17 17 import cn.iocoder.yudao.module.trade.service.aftersale.TradeAfterSaleService;
18 18 import cn.iocoder.yudao.module.trade.service.order.TradeOrderQueryService;
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/admin/brokerage/record/BrokerageRecordController.java renamed to yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/admin/brokerage/BrokerageRecordController.java
1   -package cn.iocoder.yudao.module.trade.controller.admin.brokerage.record;
  1 +package cn.iocoder.yudao.module.trade.controller.admin.brokerage;
2 2  
3 3 import cn.iocoder.yudao.framework.common.pojo.CommonResult;
4 4 import cn.iocoder.yudao.framework.common.pojo.PageResult;
5 5 import cn.iocoder.yudao.module.member.api.user.MemberUserApi;
6 6 import cn.iocoder.yudao.module.member.api.user.dto.MemberUserRespDTO;
7   -import cn.iocoder.yudao.module.trade.controller.admin.brokerage.record.vo.BrokerageRecordPageReqVO;
8   -import cn.iocoder.yudao.module.trade.controller.admin.brokerage.record.vo.BrokerageRecordRespVO;
9   -import cn.iocoder.yudao.module.trade.convert.brokerage.record.BrokerageRecordConvert;
10   -import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.record.BrokerageRecordDO;
11   -import cn.iocoder.yudao.module.trade.service.brokerage.record.BrokerageRecordService;
  7 +import cn.iocoder.yudao.module.trade.controller.admin.brokerage.vo.record.BrokerageRecordPageReqVO;
  8 +import cn.iocoder.yudao.module.trade.controller.admin.brokerage.vo.record.BrokerageRecordRespVO;
  9 +import cn.iocoder.yudao.module.trade.convert.brokerage.BrokerageRecordConvert;
  10 +import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.BrokerageRecordDO;
  11 +import cn.iocoder.yudao.module.trade.service.brokerage.BrokerageRecordService;
12 12 import io.swagger.v3.oas.annotations.Operation;
13 13 import io.swagger.v3.oas.annotations.Parameter;
14 14 import io.swagger.v3.oas.annotations.tags.Tag;
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/admin/brokerage/user/BrokerageUserController.java renamed to yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/admin/brokerage/BrokerageUserController.java
1   -package cn.iocoder.yudao.module.trade.controller.admin.brokerage.user;
  1 +package cn.iocoder.yudao.module.trade.controller.admin.brokerage;
2 2  
3 3 import cn.iocoder.yudao.framework.common.pojo.CommonResult;
4 4 import cn.iocoder.yudao.framework.common.pojo.PageResult;
5 5 import cn.iocoder.yudao.module.member.api.user.MemberUserApi;
6 6 import cn.iocoder.yudao.module.member.api.user.dto.MemberUserRespDTO;
7   -import cn.iocoder.yudao.module.trade.controller.admin.brokerage.user.vo.*;
8   -import cn.iocoder.yudao.module.trade.convert.brokerage.user.BrokerageUserConvert;
9   -import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.user.BrokerageUserDO;
  7 +import cn.iocoder.yudao.module.trade.controller.admin.brokerage.vo.user.*;
  8 +import cn.iocoder.yudao.module.trade.convert.brokerage.BrokerageUserConvert;
  9 +import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.BrokerageUserDO;
10 10 import cn.iocoder.yudao.module.trade.enums.brokerage.BrokerageRecordBizTypeEnum;
11 11 import cn.iocoder.yudao.module.trade.enums.brokerage.BrokerageRecordStatusEnum;
  12 +import cn.iocoder.yudao.module.trade.enums.brokerage.BrokerageWithdrawStatusEnum;
  13 +import cn.iocoder.yudao.module.trade.service.brokerage.BrokerageWithdrawService;
12 14 import cn.iocoder.yudao.module.trade.service.brokerage.bo.UserBrokerageSummaryBO;
13   -import cn.iocoder.yudao.module.trade.service.brokerage.record.BrokerageRecordService;
14   -import cn.iocoder.yudao.module.trade.service.brokerage.user.BrokerageUserService;
  15 +import cn.iocoder.yudao.module.trade.service.brokerage.BrokerageRecordService;
  16 +import cn.iocoder.yudao.module.trade.service.brokerage.BrokerageUserService;
  17 +import cn.iocoder.yudao.module.trade.service.brokerage.bo.UserWithdrawSummaryBO;
15 18 import io.swagger.v3.oas.annotations.Operation;
16 19 import io.swagger.v3.oas.annotations.Parameter;
17 20 import io.swagger.v3.oas.annotations.tags.Tag;
... ... @@ -38,6 +41,8 @@ public class BrokerageUserController {
38 41 private BrokerageUserService brokerageUserService;
39 42 @Resource
40 43 private BrokerageRecordService brokerageRecordService;
  44 + @Resource
  45 + private BrokerageWithdrawService brokerageWithdrawService;
41 46  
42 47 @Resource
43 48 private MemberUserApi memberUserApi;
... ... @@ -87,6 +92,7 @@ public class BrokerageUserController {
87 92 Set<Long> userIds = convertSet(pageResult.getList(), BrokerageUserDO::getId);
88 93 // 查询用户信息
89 94 Map<Long, MemberUserRespDTO> userMap = memberUserApi.getUserMap(userIds);
  95 + // TODO @疯狂:看看下面两个 getBrokerageUserCountByBindUserId、getWithdrawSummaryByUserId 有没可能一次性出结果,不然 n 次有点太花性能了;
90 96 // 合计分佣订单
91 97 Map<Long, UserBrokerageSummaryBO> userOrderSummaryMap = convertMap(userIds,
92 98 userId -> userId,
... ... @@ -96,10 +102,13 @@ public class BrokerageUserController {
96 102 Map<Long, Long> brokerageUserCountMap = convertMap(userIds,
97 103 userId -> userId,
98 104 userId -> brokerageUserService.getBrokerageUserCountByBindUserId(userId, null));
99   -
100   - // todo 合计提现
101   -
102   - return success(BrokerageUserConvert.INSTANCE.convertPage(pageResult, userMap, brokerageUserCountMap, userOrderSummaryMap));
  105 + // 合计提现
  106 + Map<Long, UserWithdrawSummaryBO> withdrawMap = convertMap(userIds,
  107 + userId -> userId,
  108 + userId -> brokerageWithdrawService.getWithdrawSummaryByUserId(userId, BrokerageWithdrawStatusEnum.AUDIT_SUCCESS));
  109 + // 拼接返回
  110 + return success(BrokerageUserConvert.INSTANCE.convertPage(pageResult, userMap, brokerageUserCountMap,
  111 + userOrderSummaryMap, withdrawMap));
103 112 }
104 113  
105 114 }
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/admin/brokerage/withdraw/BrokerageWithdrawController.java renamed to yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/admin/brokerage/BrokerageWithdrawController.java
1   -package cn.iocoder.yudao.module.trade.controller.admin.brokerage.withdraw;
  1 +package cn.iocoder.yudao.module.trade.controller.admin.brokerage;
2 2  
3 3 import cn.iocoder.yudao.framework.common.pojo.CommonResult;
4 4 import cn.iocoder.yudao.framework.common.pojo.PageResult;
5 5 import cn.iocoder.yudao.module.member.api.user.MemberUserApi;
6 6 import cn.iocoder.yudao.module.member.api.user.dto.MemberUserRespDTO;
7   -import cn.iocoder.yudao.module.trade.controller.admin.brokerage.withdraw.vo.BrokerageWithdrawRejectReqVO;
8   -import cn.iocoder.yudao.module.trade.controller.admin.brokerage.withdraw.vo.BrokerageWithdrawPageReqVO;
9   -import cn.iocoder.yudao.module.trade.controller.admin.brokerage.withdraw.vo.BrokerageWithdrawRespVO;
10   -import cn.iocoder.yudao.module.trade.convert.brokerage.withdraw.BrokerageWithdrawConvert;
11   -import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.withdraw.BrokerageWithdrawDO;
  7 +import cn.iocoder.yudao.module.trade.controller.admin.brokerage.vo.withdraw.BrokerageWithdrawRejectReqVO;
  8 +import cn.iocoder.yudao.module.trade.controller.admin.brokerage.vo.withdraw.BrokerageWithdrawPageReqVO;
  9 +import cn.iocoder.yudao.module.trade.controller.admin.brokerage.vo.withdraw.BrokerageWithdrawRespVO;
  10 +import cn.iocoder.yudao.module.trade.convert.brokerage.BrokerageWithdrawConvert;
  11 +import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.BrokerageWithdrawDO;
12 12 import cn.iocoder.yudao.module.trade.enums.brokerage.BrokerageWithdrawStatusEnum;
13   -import cn.iocoder.yudao.module.trade.service.brokerage.withdraw.BrokerageWithdrawService;
  13 +import cn.iocoder.yudao.module.trade.service.brokerage.BrokerageWithdrawService;
14 14 import io.swagger.v3.oas.annotations.Operation;
15 15 import io.swagger.v3.oas.annotations.Parameter;
16 16 import io.swagger.v3.oas.annotations.tags.Tag;
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/admin/brokerage/record/vo/BrokerageRecordBaseVO.java renamed to yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/admin/brokerage/vo/record/BrokerageRecordBaseVO.java
1   -package cn.iocoder.yudao.module.trade.controller.admin.brokerage.record.vo;
  1 +package cn.iocoder.yudao.module.trade.controller.admin.brokerage.vo.record;
2 2  
3 3 import io.swagger.v3.oas.annotations.media.Schema;
4 4 import lombok.Data;
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/admin/brokerage/record/vo/BrokerageRecordPageReqVO.java renamed to yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/admin/brokerage/vo/record/BrokerageRecordPageReqVO.java
1   -package cn.iocoder.yudao.module.trade.controller.admin.brokerage.record.vo;
  1 +package cn.iocoder.yudao.module.trade.controller.admin.brokerage.vo.record;
2 2  
3 3 import cn.iocoder.yudao.framework.common.pojo.PageParam;
4 4 import io.swagger.v3.oas.annotations.media.Schema;
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/admin/brokerage/record/vo/BrokerageRecordRespVO.java renamed to yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/admin/brokerage/vo/record/BrokerageRecordRespVO.java
1   -package cn.iocoder.yudao.module.trade.controller.admin.brokerage.record.vo;
  1 +package cn.iocoder.yudao.module.trade.controller.admin.brokerage.vo.record;
2 2  
3 3 import io.swagger.v3.oas.annotations.media.Schema;
4 4 import lombok.Data;
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/admin/brokerage/user/vo/BrokerageUserBaseVO.java renamed to yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/admin/brokerage/vo/user/BrokerageUserBaseVO.java
1   -package cn.iocoder.yudao.module.trade.controller.admin.brokerage.user.vo;
  1 +package cn.iocoder.yudao.module.trade.controller.admin.brokerage.vo.user;
2 2  
3 3 import io.swagger.v3.oas.annotations.media.Schema;
4 4 import lombok.Data;
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/admin/brokerage/user/vo/BrokerageUserClearBrokerageUserReqVO.java renamed to yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/admin/brokerage/vo/user/BrokerageUserClearBrokerageUserReqVO.java
1   -package cn.iocoder.yudao.module.trade.controller.admin.brokerage.user.vo;
  1 +package cn.iocoder.yudao.module.trade.controller.admin.brokerage.vo.user;
2 2  
3 3 import io.swagger.v3.oas.annotations.media.Schema;
4 4 import lombok.Data;
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/admin/brokerage/user/vo/BrokerageUserPageReqVO.java renamed to yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/admin/brokerage/vo/user/BrokerageUserPageReqVO.java
1   -package cn.iocoder.yudao.module.trade.controller.admin.brokerage.user.vo;
  1 +package cn.iocoder.yudao.module.trade.controller.admin.brokerage.vo.user;
2 2  
3 3 import cn.iocoder.yudao.framework.common.pojo.PageParam;
4 4 import io.swagger.v3.oas.annotations.media.Schema;
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/admin/brokerage/user/vo/BrokerageUserRespVO.java renamed to yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/admin/brokerage/vo/user/BrokerageUserRespVO.java
1   -package cn.iocoder.yudao.module.trade.controller.admin.brokerage.user.vo;
  1 +package cn.iocoder.yudao.module.trade.controller.admin.brokerage.vo.user;
2 2  
3 3 import io.swagger.v3.oas.annotations.media.Schema;
4 4 import lombok.Data;
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/admin/brokerage/user/vo/BrokerageUserUpdateBrokerageEnabledReqVO.java renamed to yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/admin/brokerage/vo/user/BrokerageUserUpdateBrokerageEnabledReqVO.java
1   -package cn.iocoder.yudao.module.trade.controller.admin.brokerage.user.vo;
  1 +package cn.iocoder.yudao.module.trade.controller.admin.brokerage.vo.user;
2 2  
3 3 import io.swagger.v3.oas.annotations.media.Schema;
4 4 import lombok.Data;
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/admin/brokerage/user/vo/BrokerageUserUpdateBrokerageUserReqVO.java renamed to yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/admin/brokerage/vo/user/BrokerageUserUpdateBrokerageUserReqVO.java
1   -package cn.iocoder.yudao.module.trade.controller.admin.brokerage.user.vo;
  1 +package cn.iocoder.yudao.module.trade.controller.admin.brokerage.vo.user;
2 2  
3 3 import io.swagger.v3.oas.annotations.media.Schema;
4 4 import lombok.Data;
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/admin/brokerage/withdraw/vo/BrokerageWithdrawBaseVO.java renamed to yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/admin/brokerage/vo/withdraw/BrokerageWithdrawBaseVO.java
1   -package cn.iocoder.yudao.module.trade.controller.admin.brokerage.withdraw.vo;
  1 +package cn.iocoder.yudao.module.trade.controller.admin.brokerage.vo.withdraw;
2 2  
3 3 import io.swagger.v3.oas.annotations.media.Schema;
4 4 import lombok.Data;
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/admin/brokerage/withdraw/vo/BrokerageWithdrawPageReqVO.java renamed to yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/admin/brokerage/vo/withdraw/BrokerageWithdrawPageReqVO.java
1   -package cn.iocoder.yudao.module.trade.controller.admin.brokerage.withdraw.vo;
  1 +package cn.iocoder.yudao.module.trade.controller.admin.brokerage.vo.withdraw;
2 2  
3 3 import cn.iocoder.yudao.framework.common.pojo.PageParam;
4 4 import cn.iocoder.yudao.framework.common.validation.InEnum;
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/admin/brokerage/withdraw/vo/BrokerageWithdrawRejectReqVO.java renamed to yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/admin/brokerage/vo/withdraw/BrokerageWithdrawRejectReqVO.java
1   -package cn.iocoder.yudao.module.trade.controller.admin.brokerage.withdraw.vo;
  1 +package cn.iocoder.yudao.module.trade.controller.admin.brokerage.vo.withdraw;
2 2  
3 3 import io.swagger.v3.oas.annotations.media.Schema;
4 4 import lombok.Data;
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/admin/brokerage/withdraw/vo/BrokerageWithdrawRespVO.java renamed to yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/admin/brokerage/vo/withdraw/BrokerageWithdrawRespVO.java
1   -package cn.iocoder.yudao.module.trade.controller.admin.brokerage.withdraw.vo;
  1 +package cn.iocoder.yudao.module.trade.controller.admin.brokerage.vo.withdraw;
2 2  
3 3 import io.swagger.v3.oas.annotations.media.Schema;
4 4 import lombok.Data;
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/admin/config/vo/TradeConfigBaseVO.java
... ... @@ -19,6 +19,17 @@ import java.util.List;
19 19 */
20 20 @Data
21 21 public class TradeConfigBaseVO {
  22 + /**
  23 + * 是否启用全场包邮
  24 + */
  25 + @Schema(description = "是否启用全场包邮", requiredMode = Schema.RequiredMode.REQUIRED, example = "true")
  26 + @NotNull(message = "是否启用全场包邮不能为空")
  27 + private Boolean deliveryExpressFreeEnabled;
  28 +
  29 + @Schema(description = "全场包邮的最小金额", requiredMode = Schema.RequiredMode.REQUIRED, example = "1000")
  30 + @NotNull(message = "全场包邮的最小金额不能为空")
  31 + @PositiveOrZero(message = "全场包邮的最小金额不能是负数")
  32 + private Integer deliveryExpressFreePrice;
22 33  
23 34 // ========== 分销相关 ==========
24 35  
... ... @@ -37,7 +48,7 @@ public class TradeConfigBaseVO {
37 48 private Integer brokerageBindMode;
38 49  
39 50 @Schema(description = "分销海报图地址数组", requiredMode = Schema.RequiredMode.REQUIRED, example = "[https://www.iocoder.cn/yudao.jpg]")
40   - private List<String> brokeragePostUrls;
  51 + private List<String> brokeragePosterUrls;
41 52  
42 53 @Schema(description = "一级返佣比例", requiredMode = Schema.RequiredMode.REQUIRED, example = "5")
43 54 @NotNull(message = "一级返佣比例不能为空")
... ... @@ -54,6 +65,11 @@ public class TradeConfigBaseVO {
54 65 @PositiveOrZero(message = "用户提现最低金额不能是负数")
55 66 private Integer brokerageWithdrawMinPrice;
56 67  
  68 + @Schema(description = "用户提现手续费百分比", requiredMode = Schema.RequiredMode.REQUIRED, example = "1000")
  69 + @NotNull(message = "用户提现手续费百分比不能为空")
  70 + @PositiveOrZero(message = "用户提现手续费百分比不能是负数")
  71 + private Integer brokerageWithdrawFeePercent;
  72 +
57 73 @Schema(description = "提现银行", requiredMode = Schema.RequiredMode.REQUIRED, example = "[0, 1]")
58 74 @NotEmpty(message = "提现银行不能为空")
59 75 private List<Integer> brokerageBankNames;
... ... @@ -66,6 +82,6 @@ public class TradeConfigBaseVO {
66 82 @Schema(description = "提现方式", requiredMode = Schema.RequiredMode.REQUIRED, example = "[0, 1]")
67 83 @NotNull(message = "提现方式不能为空")
68 84 @InEnum(value = BrokerageWithdrawTypeEnum.class, message = "提现方式必须是 {value}")
69   - private List<Integer> brokerageWithdrawType;
  85 + private List<Integer> brokerageWithdrawTypes;
70 86  
71 87 }
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/app/brokerage/AppBrokerageRecordController.java
... ... @@ -6,7 +6,9 @@ import cn.iocoder.yudao.framework.security.core.annotations.PreAuthenticated;
6 6 import cn.iocoder.yudao.module.trade.controller.app.brokerage.vo.record.AppBrokerageProductPriceRespVO;
7 7 import cn.iocoder.yudao.module.trade.controller.app.brokerage.vo.record.AppBrokerageRecordPageReqVO;
8 8 import cn.iocoder.yudao.module.trade.controller.app.brokerage.vo.record.AppBrokerageRecordRespVO;
9   -import cn.iocoder.yudao.module.trade.service.brokerage.user.BrokerageUserService;
  9 +import cn.iocoder.yudao.module.trade.convert.brokerage.BrokerageRecordConvert;
  10 +import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.BrokerageRecordDO;
  11 +import cn.iocoder.yudao.module.trade.service.brokerage.BrokerageRecordService;
10 12 import io.swagger.v3.oas.annotations.Operation;
11 13 import io.swagger.v3.oas.annotations.tags.Tag;
12 14 import lombok.extern.slf4j.Slf4j;
... ... @@ -18,11 +20,9 @@ import org.springframework.web.bind.annotation.RestController;
18 20  
19 21 import javax.annotation.Resource;
20 22 import javax.validation.Valid;
21   -import java.time.LocalDateTime;
22 23  
23 24 import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
24 25 import static cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils.getLoginUserId;
25   -import static java.util.Arrays.asList;
26 26  
27 27 @Tag(name = "用户 APP - 分销用户")
28 28 @RestController
... ... @@ -31,30 +31,21 @@ import static java.util.Arrays.asList;
31 31 @Slf4j
32 32 public class AppBrokerageRecordController {
33 33 @Resource
34   - private BrokerageUserService brokerageUserService;
  34 + private BrokerageRecordService brokerageRecordService;
35 35  
36   - // TODO 芋艿:临时 mock =>
37 36 @GetMapping("/page")
38 37 @Operation(summary = "获得分销记录分页")
39 38 @PreAuthenticated
40 39 public CommonResult<PageResult<AppBrokerageRecordRespVO>> getBrokerageRecordPage(@Valid AppBrokerageRecordPageReqVO pageReqVO) {
41   - AppBrokerageRecordRespVO vo1 = new AppBrokerageRecordRespVO()
42   - .setId(1L).setPrice(10).setTitle("收到钱").setCreateTime(LocalDateTime.now())
43   - .setFinishTime(LocalDateTime.now());
44   - AppBrokerageRecordRespVO vo2 = new AppBrokerageRecordRespVO()
45   - .setId(2L).setPrice(-20).setTitle("提现钱").setCreateTime(LocalDateTime.now())
46   - .setFinishTime(LocalDateTime.now());
47   - return success(new PageResult<>(asList(vo1, vo2), 10L));
  40 + PageResult<BrokerageRecordDO> pageResult = brokerageRecordService.getBrokerageRecordPage(
  41 + BrokerageRecordConvert.INSTANCE.convert(pageReqVO, getLoginUserId()));
  42 + return success(BrokerageRecordConvert.INSTANCE.convertPage02(pageResult));
48 43 }
49 44  
50 45 @GetMapping("/get-product-brokerage-price")
51 46 @Operation(summary = "获得商品的分销金额")
52 47 public CommonResult<AppBrokerageProductPriceRespVO> getProductBrokeragePrice(@RequestParam("spuId") Long spuId) {
53   - AppBrokerageProductPriceRespVO respVO = new AppBrokerageProductPriceRespVO();
54   - respVO.setEnabled(brokerageUserService.getUserBrokerageEnabled(getLoginUserId()));
55   - respVO.setBrokerageMinPrice(1);
56   - respVO.setBrokerageMaxPrice(2);
57   - return success(respVO);
  48 + return success(brokerageRecordService.calculateProductBrokeragePrice(spuId, getLoginUserId()));
58 49 }
59 50  
60 51 }
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/app/brokerage/AppBrokerageUserController.java
1 1 package cn.iocoder.yudao.module.trade.controller.app.brokerage;
2 2  
  3 +import cn.hutool.core.date.LocalDateTimeUtil;
3 4 import cn.iocoder.yudao.framework.common.pojo.CommonResult;
4 5 import cn.iocoder.yudao.framework.common.pojo.PageResult;
5 6 import cn.iocoder.yudao.framework.security.core.annotations.PreAuthenticated;
  7 +import cn.iocoder.yudao.module.member.api.user.MemberUserApi;
  8 +import cn.iocoder.yudao.module.member.api.user.dto.MemberUserRespDTO;
6 9 import cn.iocoder.yudao.module.trade.controller.app.brokerage.vo.user.*;
7   -import cn.iocoder.yudao.module.trade.service.brokerage.user.BrokerageUserService;
  10 +import cn.iocoder.yudao.module.trade.convert.brokerage.BrokerageRecordConvert;
  11 +import cn.iocoder.yudao.module.trade.convert.brokerage.BrokerageUserConvert;
  12 +import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.BrokerageUserDO;
  13 +import cn.iocoder.yudao.module.trade.enums.brokerage.BrokerageRecordBizTypeEnum;
  14 +import cn.iocoder.yudao.module.trade.enums.brokerage.BrokerageWithdrawStatusEnum;
  15 +import cn.iocoder.yudao.module.trade.service.brokerage.BrokerageRecordService;
  16 +import cn.iocoder.yudao.module.trade.service.brokerage.BrokerageUserService;
  17 +import cn.iocoder.yudao.module.trade.service.brokerage.BrokerageWithdrawService;
  18 +import cn.iocoder.yudao.module.trade.service.brokerage.bo.UserWithdrawSummaryBO;
8 19 import io.swagger.v3.oas.annotations.Operation;
9 20 import io.swagger.v3.oas.annotations.Parameter;
10 21 import io.swagger.v3.oas.annotations.tags.Tag;
... ... @@ -16,11 +27,13 @@ import org.springframework.web.bind.annotation.*;
16 27 import javax.annotation.Resource;
17 28 import javax.validation.Valid;
18 29 import java.time.LocalDateTime;
  30 +import java.util.Map;
  31 +import java.util.Optional;
19 32  
20 33 import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
  34 +import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;
21 35 import static cn.iocoder.yudao.framework.common.util.date.DateUtils.FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND;
22 36 import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUserId;
23   -import static java.util.Arrays.asList;
24 37  
25 38 @Tag(name = "用户 APP - 分销用户")
26 39 @RestController
... ... @@ -30,16 +43,24 @@ import static java.util.Arrays.asList;
30 43 public class AppBrokerageUserController {
31 44 @Resource
32 45 private BrokerageUserService brokerageUserService;
  46 + @Resource
  47 + private BrokerageRecordService brokerageRecordService;
  48 + @Resource
  49 + private BrokerageWithdrawService brokerageWithdrawService;
  50 +
  51 + @Resource
  52 + private MemberUserApi memberUserApi;
33 53  
34   - // TODO 芋艿:临时 mock =>
35 54 @GetMapping("/get")
36 55 @Operation(summary = "获得个人分销信息")
37 56 @PreAuthenticated
38 57 public CommonResult<AppBrokerageUserRespVO> getBrokerageUser() {
  58 + Optional<BrokerageUserDO> user = Optional.ofNullable(brokerageUserService.getBrokerageUser(getLoginUserId()));
  59 + // 返回数据
39 60 AppBrokerageUserRespVO respVO = new AppBrokerageUserRespVO()
40   - .setBrokerageEnabled(true)
41   - .setPrice(2000)
42   - .setFrozenPrice(3000);
  61 + .setBrokerageEnabled(user.map(BrokerageUserDO::getBrokerageEnabled).orElse(false))
  62 + .setBrokeragePrice(user.map(BrokerageUserDO::getBrokeragePrice).orElse(0))
  63 + .setFrozenPrice(user.map(BrokerageUserDO::getFrozenPrice).orElse(0));
43 64 return success(respVO);
44 65 }
45 66  
... ... @@ -47,88 +68,70 @@ public class AppBrokerageUserController {
47 68 @Operation(summary = "绑定推广员")
48 69 @PreAuthenticated
49 70 public CommonResult<Boolean> bindBrokerageUser(@Valid @RequestBody AppBrokerageUserBindReqVO reqVO) {
50   - return success(brokerageUserService.bindBrokerageUser(getLoginUserId(), reqVO.getBindUserId(), false));
  71 + MemberUserRespDTO user = memberUserApi.getUser(getLoginUserId());
  72 + return success(brokerageUserService.bindBrokerageUser(user.getId(), reqVO.getBindUserId(), user.getCreateTime()));
51 73 }
52 74  
53   - // TODO 芋艿:临时 mock =>
54 75 @GetMapping("/get-summary")
55 76 @Operation(summary = "获得个人分销统计")
56 77 @PreAuthenticated
57 78 public CommonResult<AppBrokerageUserMySummaryRespVO> getBrokerageUserSummary() {
  79 + Long userId = getLoginUserId();
  80 + // TODO @疯狂:后面这种,要不也改成 convert;感觉 controller 这样更容易看到整体;核心其实是 86、8/87、9/90、9/91 这阶段
  81 + // 统计 yesterdayPrice、withdrawPrice、firstBrokerageUserCount、secondBrokerageUserCount 字段
  82 + LocalDateTime yesterday = LocalDateTime.now().minusDays(1);
  83 + LocalDateTime beginTime = LocalDateTimeUtil.beginOfDay(yesterday);
  84 + LocalDateTime endTime = LocalDateTimeUtil.endOfDay(yesterday);
58 85 AppBrokerageUserMySummaryRespVO respVO = new AppBrokerageUserMySummaryRespVO()
59   - .setYesterdayPrice(1)
60   - .setBrokeragePrice(2)
61   - .setFrozenPrice(3)
62   - .setWithdrawPrice(4)
63   - .setFirstBrokerageUserCount(166)
64   - .setSecondBrokerageUserCount(233);
  86 + .setYesterdayPrice(brokerageRecordService.getSummaryPriceByUserId(userId, BrokerageRecordBizTypeEnum.ORDER.getType(), beginTime, endTime))
  87 + .setWithdrawPrice(Optional.ofNullable(brokerageWithdrawService.getWithdrawSummaryByUserId(userId, BrokerageWithdrawStatusEnum.AUDIT_SUCCESS))
  88 + .map(UserWithdrawSummaryBO::getPrice).orElse(0))
  89 + .setBrokeragePrice(0).setFrozenPrice(0)
  90 + .setFirstBrokerageUserCount(brokerageUserService.getBrokerageUserCountByBindUserId(userId, 1))
  91 + .setSecondBrokerageUserCount(brokerageUserService.getBrokerageUserCountByBindUserId(userId, 2));
  92 + // 设置 brokeragePrice、frozenPrice 字段
  93 + Optional.ofNullable(brokerageUserService.getBrokerageUser(userId))
  94 + .ifPresent(user -> respVO.setBrokeragePrice(user.getBrokeragePrice()).setFrozenPrice(user.getFrozenPrice()));
65 95 return success(respVO);
66 96 }
67 97  
68   - // TODO 芋艿:临时 mock =>
69 98 @GetMapping("/rank-page-by-user-count")
70 99 @Operation(summary = "获得分销用户排行分页(基于用户量)")
71 100 @PreAuthenticated
72 101 public CommonResult<PageResult<AppBrokerageUserRankByUserCountRespVO>> getBrokerageUserRankPageByUserCount(AppBrokerageUserRankPageReqVO pageReqVO) {
73   - AppBrokerageUserRankByUserCountRespVO vo1 = new AppBrokerageUserRankByUserCountRespVO()
74   - .setId(1L).setNickname("芋1**艿").setAvatar("http://www.iocoder.cn/images/common/wechat_mp_2017_07_31_bak.jpg")
75   - .setBrokerageUserCount(10);
76   - AppBrokerageUserRankByUserCountRespVO vo2 = new AppBrokerageUserRankByUserCountRespVO()
77   - .setId(2L).setNickname("芋2**艿").setAvatar("http://www.iocoder.cn/images/common/wechat_mp_2017_07_31_bak.jpg")
78   - .setBrokerageUserCount(6);
79   - AppBrokerageUserRankByUserCountRespVO vo3 = new AppBrokerageUserRankByUserCountRespVO()
80   - .setId(3L).setNickname("芋3**艿").setAvatar("http://www.iocoder.cn/images/common/wechat_mp_2017_07_31_bak.jpg")
81   - .setBrokerageUserCount(4);
82   - AppBrokerageUserRankByUserCountRespVO vo4 = new AppBrokerageUserRankByUserCountRespVO()
83   - .setId(3L).setNickname("芋3**艿").setAvatar("http://www.iocoder.cn/images/common/wechat_mp_2017_07_31_bak.jpg")
84   - .setBrokerageUserCount(4);
85   - return success(new PageResult<>(asList(vo1, vo2, vo3, vo4), 10L));
  102 + // 分页查询
  103 + PageResult<AppBrokerageUserRankByUserCountRespVO> pageResult = brokerageUserService.getBrokerageUserRankPageByUserCount(pageReqVO);
  104 + // 拼接数据
  105 + Map<Long, MemberUserRespDTO> userMap = memberUserApi.getUserMap(convertSet(pageResult.getList(), AppBrokerageUserRankByUserCountRespVO::getId));
  106 + return success(BrokerageUserConvert.INSTANCE.convertPage03(pageResult, userMap));
86 107 }
87 108  
88   - // TODO 芋艿:临时 mock =>
89 109 @GetMapping("/rank-page-by-price")
90 110 @Operation(summary = "获得分销用户排行分页(基于佣金)")
91 111 @PreAuthenticated
92 112 public CommonResult<PageResult<AppBrokerageUserRankByPriceRespVO>> getBrokerageUserChildSummaryPageByPrice(AppBrokerageUserRankPageReqVO pageReqVO) {
93   - AppBrokerageUserRankByPriceRespVO vo1 = new AppBrokerageUserRankByPriceRespVO()
94   - .setId(1L).setNickname("芋1**艿").setAvatar("http://www.iocoder.cn/images/common/wechat_mp_2017_07_31_bak.jpg")
95   - .setBrokeragePrice(10);
96   - AppBrokerageUserRankByPriceRespVO vo2 = new AppBrokerageUserRankByPriceRespVO()
97   - .setId(2L).setNickname("芋2**艿").setAvatar("http://www.iocoder.cn/images/common/wechat_mp_2017_07_31_bak.jpg")
98   - .setBrokeragePrice(6);
99   - AppBrokerageUserRankByPriceRespVO vo3 = new AppBrokerageUserRankByPriceRespVO()
100   - .setId(3L).setNickname("芋3**艿").setAvatar("http://www.iocoder.cn/images/common/wechat_mp_2017_07_31_bak.jpg")
101   - .setBrokeragePrice(4);
102   - AppBrokerageUserRankByPriceRespVO vo4 = new AppBrokerageUserRankByPriceRespVO()
103   - .setId(3L).setNickname("芋3**艿").setAvatar("http://www.iocoder.cn/images/common/wechat_mp_2017_07_31_bak.jpg")
104   - .setBrokeragePrice(4);
105   - return success(new PageResult<>(asList(vo1, vo2, vo3, vo4), 10L));
  113 + // 分页查询
  114 + PageResult<AppBrokerageUserRankByPriceRespVO> pageResult = brokerageRecordService.getBrokerageUserChildSummaryPageByPrice(pageReqVO);
  115 + // 拼接数据
  116 + Map<Long, MemberUserRespDTO> userMap = memberUserApi.getUserMap(convertSet(pageResult.getList(), AppBrokerageUserRankByPriceRespVO::getId));
  117 + return success(BrokerageRecordConvert.INSTANCE.convertPage03(pageResult, userMap));
106 118 }
107 119  
108   - // TODO 芋艿:临时 mock =>
109 120 @GetMapping("/child-summary-page")
110 121 @Operation(summary = "获得下级分销统计分页")
111 122 @PreAuthenticated
112 123 public CommonResult<PageResult<AppBrokerageUserChildSummaryRespVO>> getBrokerageUserChildSummaryPage(
113 124 AppBrokerageUserChildSummaryPageReqVO pageReqVO) {
114   - AppBrokerageUserChildSummaryRespVO vo1 = new AppBrokerageUserChildSummaryRespVO()
115   - .setId(1L).setNickname("芋1**艿").setAvatar("http://www.iocoder.cn/images/common/wechat_mp_2017_07_31_bak.jpg")
116   - .setBrokeragePrice(10).setBrokeragePrice(20).setBrokerageOrderCount(30)
117   - .setBrokerageTime(LocalDateTime.now());
118   - AppBrokerageUserChildSummaryRespVO vo2 = new AppBrokerageUserChildSummaryRespVO()
119   - .setId(1L).setNickname("芋2**艿").setAvatar("http://www.iocoder.cn/images/common/wechat_mp_2017_07_31_bak.jpg")
120   - .setBrokeragePrice(20).setBrokeragePrice(30).setBrokerageOrderCount(40)
121   - .setBrokerageTime(LocalDateTime.now());
122   - return success(new PageResult<>(asList(vo1, vo2), 10L));
  125 + PageResult<AppBrokerageUserChildSummaryRespVO> pageResult = brokerageUserService.getBrokerageUserChildSummaryPage(pageReqVO, getLoginUserId());
  126 + return success(pageResult);
123 127 }
124 128  
125   - // TODO 芋艿:临时 mock =>
126 129 @GetMapping("/get-rank-by-price")
127 130 @Operation(summary = "获得分销用户排行(基于佣金)")
128 131 @Parameter(name = "times", description = "时间段", required = true)
129   - public CommonResult<Integer> bindBrokerageUser(
  132 + public CommonResult<Integer> getRankByPrice(
130 133 @RequestParam("times") @DateTimeFormat(pattern = FORMAT_YEAR_MONTH_DAY_HOUR_MINUTE_SECOND) LocalDateTime[] times) {
131   - return success(1);
  134 + return success(brokerageRecordService.getUserRankByPrice(getLoginUserId(), times));
132 135 }
133 136  
134 137 }
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/app/brokerage/AppBrokerageWithdrawController.java
... ... @@ -3,19 +3,24 @@ package cn.iocoder.yudao.module.trade.controller.app.brokerage;
3 3 import cn.iocoder.yudao.framework.common.pojo.CommonResult;
4 4 import cn.iocoder.yudao.framework.common.pojo.PageResult;
5 5 import cn.iocoder.yudao.framework.security.core.annotations.PreAuthenticated;
  6 +import cn.iocoder.yudao.module.system.api.dict.DictDataApi;
6 7 import cn.iocoder.yudao.module.trade.controller.app.brokerage.vo.withdraw.AppBrokerageWithdrawCreateReqVO;
  8 +import cn.iocoder.yudao.module.trade.controller.app.brokerage.vo.withdraw.AppBrokerageWithdrawPageReqVO;
7 9 import cn.iocoder.yudao.module.trade.controller.app.brokerage.vo.withdraw.AppBrokerageWithdrawRespVO;
  10 +import cn.iocoder.yudao.module.trade.convert.brokerage.BrokerageWithdrawConvert;
  11 +import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.BrokerageWithdrawDO;
  12 +import cn.iocoder.yudao.module.trade.service.brokerage.BrokerageWithdrawService;
8 13 import io.swagger.v3.oas.annotations.Operation;
9 14 import io.swagger.v3.oas.annotations.tags.Tag;
10 15 import lombok.extern.slf4j.Slf4j;
11 16 import org.springframework.validation.annotation.Validated;
12 17 import org.springframework.web.bind.annotation.*;
13 18  
  19 +import javax.annotation.Resource;
14 20 import javax.validation.Valid;
15   -import java.time.LocalDateTime;
16 21  
17 22 import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
18   -import static java.util.Arrays.asList;
  23 +import static cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils.getLoginUserId;
19 24  
20 25 @Tag(name = "用户 APP - 分销提现")
21 26 @RestController
... ... @@ -24,24 +29,27 @@ import static java.util.Arrays.asList;
24 29 @Slf4j
25 30 public class AppBrokerageWithdrawController {
26 31  
27   - // TODO 芋艿:临时 mock =>
  32 + @Resource
  33 + private BrokerageWithdrawService brokerageWithdrawService;
  34 +
  35 + @Resource
  36 + private DictDataApi dictDataApi;
  37 +
28 38 @GetMapping("/page")
29 39 @Operation(summary = "获得分销提现分页")
30 40 @PreAuthenticated
31   - public CommonResult<PageResult<AppBrokerageWithdrawRespVO>> getBrokerageWithdrawPage() {
32   - AppBrokerageWithdrawRespVO vo1 = new AppBrokerageWithdrawRespVO()
33   - .setId(1L).setStatus(10).setPrice(10).setStatusName("审批通过").setCreateTime(LocalDateTime.now());
34   - AppBrokerageWithdrawRespVO vo2 = new AppBrokerageWithdrawRespVO()
35   - .setId(2L).setStatus(0).setPrice(20).setStatusName("审批中").setCreateTime(LocalDateTime.now());
36   - return success(new PageResult<>(asList(vo1, vo2), 10L));
  41 + public CommonResult<PageResult<AppBrokerageWithdrawRespVO>> getBrokerageWithdrawPage(AppBrokerageWithdrawPageReqVO pageReqVO) {
  42 + // 分页查询
  43 + PageResult<BrokerageWithdrawDO> pageResult = brokerageWithdrawService.getBrokerageWithdrawPage(
  44 + BrokerageWithdrawConvert.INSTANCE.convert(pageReqVO, getLoginUserId()));
  45 + return success(BrokerageWithdrawConvert.INSTANCE.convertPage03(pageResult));
37 46 }
38 47  
39   - // TODO 芋艿:临时 mock =>
40 48 @PostMapping("/create")
41 49 @Operation(summary = "创建分销提现")
42 50 @PreAuthenticated
43 51 public CommonResult<Long> createBrokerageWithdraw(@RequestBody @Valid AppBrokerageWithdrawCreateReqVO createReqVO) {
44   - return success(1L);
  52 + return success(brokerageWithdrawService.createBrokerageWithdraw(createReqVO, getLoginUserId()));
45 53 }
46 54  
47 55 }
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/app/brokerage/vo/user/AppBrokerageUserChildSummaryRespVO.java
... ... @@ -27,7 +27,7 @@ public class AppBrokerageUserChildSummaryRespVO {
27 27 @Schema(description = "分销用户数量", requiredMode = Schema.RequiredMode.REQUIRED, example = "30")
28 28 private Integer brokerageUserCount;
29 29  
30   - @Schema(description = "成为分销员时间", requiredMode = Schema.RequiredMode.REQUIRED)
  30 + @Schema(description = "绑定推广员的时间", requiredMode = Schema.RequiredMode.REQUIRED)
31 31 private LocalDateTime brokerageTime;
32 32  
33 33 }
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/app/brokerage/vo/user/AppBrokerageUserMySummaryRespVO.java
... ... @@ -20,9 +20,9 @@ public class AppBrokerageUserMySummaryRespVO {
20 20 private Integer frozenPrice;
21 21  
22 22 @Schema(description = "分销用户数量(一级)", requiredMode = Schema.RequiredMode.REQUIRED, example = "10")
23   - private Integer firstBrokerageUserCount;
  23 + private Long firstBrokerageUserCount;
24 24  
25 25 @Schema(description = "分销用户数量(二级)", requiredMode = Schema.RequiredMode.REQUIRED, example = "10")
26   - private Integer secondBrokerageUserCount;
  26 + private Long secondBrokerageUserCount;
27 27  
28 28 }
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/app/brokerage/vo/user/AppBrokerageUserRespVO.java
... ... @@ -11,7 +11,7 @@ public class AppBrokerageUserRespVO {
11 11 private Boolean brokerageEnabled;
12 12  
13 13 @Schema(description = "可用的佣金,单位:分", requiredMode = Schema.RequiredMode.REQUIRED, example = "2408")
14   - private Integer price;
  14 + private Integer brokeragePrice;
15 15  
16 16 @Schema(description = "冻结的佣金,单位:分", requiredMode = Schema.RequiredMode.REQUIRED, example = "234")
17 17 private Integer frozenPrice;
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/app/brokerage/vo/withdraw/AppBrokerageWithdrawCreateReqVO.java
... ... @@ -8,8 +8,9 @@ import lombok.Data;
8 8 import org.hibernate.validator.constraints.URL;
9 9  
10 10 import javax.validation.Validator;
11   -import javax.validation.constraints.Min;
12 11 import javax.validation.constraints.NotBlank;
  12 +import javax.validation.constraints.NotNull;
  13 +import javax.validation.constraints.PositiveOrZero;
13 14  
14 15 @Schema(description = "用户 App - 分销提现创建 Request VO")
15 16 @Data
... ... @@ -20,7 +21,8 @@ public class AppBrokerageWithdrawCreateReqVO {
20 21 private Integer type;
21 22  
22 23 @Schema(description = "提现金额,单位:分", requiredMode = Schema.RequiredMode.REQUIRED, example = "1000")
23   - @Min(value = 1, message = "提现金额不能小于 1")
  24 + @PositiveOrZero(message = "提现金额不能小于 0")
  25 + @NotNull(message = "提现金额不能为空")
24 26 private Integer price;
25 27  
26 28 // ========== 银行卡、微信、支付宝 提现相关字段 ==========
... ... @@ -41,7 +43,7 @@ public class AppBrokerageWithdrawCreateReqVO {
41 43 @NotBlank(message = "持卡人姓名不能为空", groups = {Bank.class})
42 44 private String name;
43 45 @Schema(description = "提现银行", example = "1")
44   - @NotBlank(message = "提现银行不能为空", groups = {Bank.class})
  46 + @NotNull(message = "提现银行不能为空", groups = {Bank.class})
45 47 private Integer bankName;
46 48 @Schema(description = "开户地址", example = "海淀支行")
47 49 private String bankAddress;
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/app/brokerage/vo/withdraw/AppBrokerageWithdrawPageReqVO.java 0 → 100644
  1 +package cn.iocoder.yudao.module.trade.controller.app.brokerage.vo.withdraw;
  2 +
  3 +import cn.iocoder.yudao.framework.common.pojo.PageParam;
  4 +import cn.iocoder.yudao.framework.common.validation.InEnum;
  5 +import cn.iocoder.yudao.module.trade.enums.brokerage.BrokerageWithdrawStatusEnum;
  6 +import cn.iocoder.yudao.module.trade.enums.brokerage.BrokerageWithdrawTypeEnum;
  7 +import io.swagger.v3.oas.annotations.media.Schema;
  8 +import lombok.Data;
  9 +
  10 +@Schema(description = "应用 App - 分销提现分页 Request VO")
  11 +@Data
  12 +public class AppBrokerageWithdrawPageReqVO extends PageParam {
  13 +
  14 + @Schema(description = "类型", requiredMode = Schema.RequiredMode.REQUIRED, example = "1")
  15 + @InEnum(value = BrokerageWithdrawTypeEnum.class, message = "类型必须是 {value}")
  16 + private Integer type;
  17 +
  18 + @Schema(description = "状态", requiredMode = Schema.RequiredMode.REQUIRED, example = "1")
  19 + @InEnum(value = BrokerageWithdrawStatusEnum.class, message = "状态必须是 {value}")
  20 + private Integer status;
  21 +
  22 +}
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/app/config/AppTradeConfigController.java
1 1 package cn.iocoder.yudao.module.trade.controller.app.config;
2 2  
  3 +import cn.hutool.core.util.ObjUtil;
3 4 import cn.iocoder.yudao.framework.common.pojo.CommonResult;
4 5 import cn.iocoder.yudao.module.trade.controller.app.config.vo.AppTradeConfigRespVO;
  6 +import cn.iocoder.yudao.module.trade.convert.config.TradeConfigConvert;
  7 +import cn.iocoder.yudao.module.trade.dal.dataobject.config.TradeConfigDO;
  8 +import cn.iocoder.yudao.module.trade.service.config.TradeConfigService;
  9 +import io.swagger.v3.oas.annotations.Operation;
5 10 import io.swagger.v3.oas.annotations.tags.Tag;
6 11 import lombok.RequiredArgsConstructor;
7 12 import lombok.extern.slf4j.Slf4j;
... ... @@ -10,8 +15,9 @@ import org.springframework.web.bind.annotation.GetMapping;
10 15 import org.springframework.web.bind.annotation.RequestMapping;
11 16 import org.springframework.web.bind.annotation.RestController;
12 17  
  18 +import javax.annotation.Resource;
  19 +
13 20 import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
14   -import static java.util.Arrays.asList;
15 21  
16 22 @Tag(name = "用户 App - 交易配置")
17 23 @RestController
... ... @@ -21,17 +27,14 @@ import static java.util.Arrays.asList;
21 27 @Slf4j
22 28 public class AppTradeConfigController {
23 29  
  30 + @Resource
  31 + private TradeConfigService tradeConfigService;
  32 +
24 33 @GetMapping("/get")
  34 + @Operation(summary = "获得交易配置")
25 35 public CommonResult<AppTradeConfigRespVO> getTradeConfig() {
26   - AppTradeConfigRespVO respVO = new AppTradeConfigRespVO();
27   - respVO.setBrokeragePosterUrls(asList(
28   - "https://api.java.crmeb.net/crmebimage/product/2020/08/03/755bf516b1ca4b6db3bfeaa4dd5901cdh71kob20re.jpg",
29   - "https://api.java.crmeb.net/crmebimage/maintain/2021/03/01/406d729b84ed4ec9a2171bfcf6fd0634ughzbz9kfi.jpg",
30   - "https://api.java.crmeb.net/crmebimage/maintain/2021/03/01/efb1e4e7fe604fe1988b4213ce08cb11tdsyijtd2r.jpg"
31   - ));
32   - respVO.setBrokerageFrozenDays(10);
33   - respVO.setBrokerageWithdrawMinPrice(100);
34   - return success(respVO);
  36 + TradeConfigDO tradeConfig = ObjUtil.defaultIfNull(tradeConfigService.getTradeConfig(), new TradeConfigDO());
  37 + return success(TradeConfigConvert.INSTANCE.convert02(tradeConfig));
35 38 }
36 39  
37 40 }
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/app/config/vo/AppTradeConfigRespVO.java
... ... @@ -18,4 +18,7 @@ public class AppTradeConfigRespVO {
18 18 @Schema(description = "佣金提现最小金额,单位:分", requiredMode = Schema.RequiredMode.REQUIRED, example = "100")
19 19 private Integer brokerageWithdrawMinPrice;
20 20  
  21 + @Schema(description = "提现方式", requiredMode = Schema.RequiredMode.REQUIRED, example = "[1, 2]")
  22 + private List<Integer> brokerageWithdrawTypes;
  23 +
21 24 }
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/app/delivery/AppDeliverConfigController.java
... ... @@ -17,6 +17,7 @@ import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
17 17 @Validated
18 18 public class AppDeliverConfigController {
19 19  
  20 + // TODO @芋艿:这里后面干掉,合并到 AppTradeConfigController 中
20 21 @GetMapping("/get")
21 22 @Operation(summary = "获得配送配置")
22 23 public CommonResult<AppDeliveryConfigRespVO> getDeliveryConfig() {
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/app/order/AppTradeOrderController.http
... ... @@ -8,14 +8,15 @@ GET {{appApi}}/trade/order/settlement?type=0&amp;items[0].cartId=50&amp;couponId=1
8 8 Authorization: Bearer {{appToken}}
9 9 tenant-id: {{appTenentId}}
10 10  
11   -### /trade-order/create 创建订单(基于商品)
  11 +### /trade-order/create 创建订单(基于商品)【快递】
12 12 POST {{appApi}}/trade/order/create
13 13 Content-Type: application/json
14 14 Authorization: Bearer {{appToken}}
15 15 tenant-id: {{appTenentId}}
16 16  
17 17 {
18   - "type": 0,
  18 + "pointStatus": true,
  19 + "deliveryType": 1,
19 20 "addressId": 21,
20 21 "items": [
21 22 {
... ... @@ -26,6 +27,27 @@ tenant-id: {{appTenentId}}
26 27 "remark": "我是备注"
27 28 }
28 29  
  30 +### /trade-order/create 创建订单(基于商品)【自提】
  31 +POST {{appApi}}/trade/order/create
  32 +Content-Type: application/json
  33 +Authorization: Bearer {{appToken}}
  34 +tenant-id: {{appTenentId}}
  35 +
  36 +{
  37 + "pointStatus": true,
  38 + "deliveryType": 2,
  39 + "pickUpStoreId": 1,
  40 + "items": [
  41 + {
  42 + "skuId": 1,
  43 + "count": 2
  44 + }
  45 + ],
  46 + "remark": "我是备注",
  47 + "receiverName": "土豆",
  48 + "receiverMobile": "15601691300"
  49 +}
  50 +
29 51 ### 获得订单交易的分页
30 52 GET {{appApi}}/trade/order/page?pageNo=1&pageSize=10
31 53 Authorization: Bearer {{appToken}}
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/app/order/AppTradeOrderController.java
1 1 package cn.iocoder.yudao.module.trade.controller.app.order;
2 2  
3   -import cn.hutool.core.map.MapUtil;
4 3 import cn.iocoder.yudao.framework.common.pojo.CommonResult;
5 4 import cn.iocoder.yudao.framework.common.pojo.PageResult;
6 5 import cn.iocoder.yudao.framework.security.core.annotations.PreAuthenticated;
... ... @@ -12,11 +11,8 @@ import cn.iocoder.yudao.module.trade.convert.order.TradeOrderConvert;
12 11 import cn.iocoder.yudao.module.trade.dal.dataobject.delivery.DeliveryExpressDO;
13 12 import cn.iocoder.yudao.module.trade.dal.dataobject.order.TradeOrderDO;
14 13 import cn.iocoder.yudao.module.trade.dal.dataobject.order.TradeOrderItemDO;
15   -import cn.iocoder.yudao.module.trade.enums.order.TradeOrderOperateTypeEnum;
16 14 import cn.iocoder.yudao.module.trade.enums.order.TradeOrderStatusEnum;
17 15 import cn.iocoder.yudao.module.trade.framework.order.config.TradeOrderProperties;
18   -import cn.iocoder.yudao.module.trade.framework.order.core.annotations.TradeOrderLog;
19   -import cn.iocoder.yudao.module.trade.framework.order.core.utils.TradeOrderLogUtils;
20 16 import cn.iocoder.yudao.module.trade.service.delivery.DeliveryExpressService;
21 17 import cn.iocoder.yudao.module.trade.service.order.TradeOrderQueryService;
22 18 import cn.iocoder.yudao.module.trade.service.order.TradeOrderUpdateService;
... ... @@ -65,10 +61,7 @@ public class AppTradeOrderController {
65 61 @PostMapping("/create")
66 62 @Operation(summary = "创建订单")
67 63 @PreAuthenticated
68   - @TradeOrderLog(operateType = TradeOrderOperateTypeEnum.TEST)
69   - public CommonResult<AppTradeOrderCreateRespVO> createOrder(@RequestBody AppTradeOrderCreateReqVO createReqVO) {
70   - TradeOrderLogUtils.setOrderInfo(10L, 1, 2,
71   - MapUtil.<String, Object>builder().put("nickname", "小明").put("thing", "种土豆").build());
  64 + public CommonResult<AppTradeOrderCreateRespVO> createOrder(@Valid @RequestBody AppTradeOrderCreateReqVO createReqVO) {
72 65 TradeOrderDO order = tradeOrderUpdateService.createOrder(getLoginUserId(), getClientIP(), createReqVO);
73 66 return success(new AppTradeOrderCreateRespVO().setId(order.getId()).setPayOrderId(order.getPayOrderId()));
74 67 }
... ... @@ -163,7 +156,7 @@ public class AppTradeOrderController {
163 156 @Operation(summary = "删除交易订单")
164 157 @Parameter(name = "id", description = "交易订单编号")
165 158 public CommonResult<Boolean> deleteOrder(@RequestParam("id") Long id) {
166   - // TODO @芋艿:未实现,mock 用
  159 + tradeOrderUpdateService.deleteOrder(getLoginUserId(), id);
167 160 return success(true);
168 161 }
169 162  
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/app/order/vo/AppTradeOrderCreateReqVO.java
1 1 package cn.iocoder.yudao.module.trade.controller.app.order.vo;
2 2  
  3 +import com.fasterxml.jackson.annotation.JsonIgnore;
3 4 import io.swagger.v3.oas.annotations.media.Schema;
4 5 import lombok.Data;
5 6  
  7 +import javax.validation.constraints.AssertTrue;
  8 +
6 9 @Schema(description = "用户 App - 交易订单创建 Request VO")
7 10 @Data
8 11 public class AppTradeOrderCreateReqVO extends AppTradeOrderSettlementReqVO {
... ... @@ -10,4 +13,10 @@ public class AppTradeOrderCreateReqVO extends AppTradeOrderSettlementReqVO {
10 13 @Schema(description = "备注", example = "这个是我的订单哟")
11 14 private String remark;
12 15  
  16 + @AssertTrue(message = "配送方式不能为空")
  17 + @JsonIgnore
  18 + public boolean isDeliveryTypeNotNull() {
  19 + return getDeliveryType() != null;
  20 + }
  21 +
13 22 }
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/app/order/vo/AppTradeOrderSettlementReqVO.java
... ... @@ -30,7 +30,7 @@ public class AppTradeOrderSettlementReqVO {
30 30 private Boolean pointStatus;
31 31  
32 32 // ========== 配送相关相关字段 ==========
33   - @Schema(description = "配送方式", required = true, example = "1")
  33 + @Schema(description = "配送方式", example = "1")
34 34 @InEnum(value = DeliveryTypeEnum.class, message = "配送方式不正确")
35 35 private Integer deliveryType;
36 36  
... ... @@ -62,6 +62,8 @@ public class AppTradeOrderSettlementReqVO {
62 62 @Schema(description = "砍价活动编号", example = "123")
63 63 private Long bargainActivityId;
64 64  
  65 + // TODO @puhui999:可以写个参数校验,如果 seckillActivityId 或 combinationActivityId 或 combinationHeadId 的情况,items 应该只有一个
  66 +
65 67 @Data
66 68 @Schema(description = "用户 App - 商品项")
67 69 @Valid
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/controller/app/order/vo/AppTradeOrderSettlementRespVO.java
... ... @@ -82,6 +82,9 @@ public class AppTradeOrderSettlementRespVO {
82 82 @Schema(description = "积分抵扣的金额,单位:分", requiredMode = Schema.RequiredMode.REQUIRED, example = "50")
83 83 private Integer pointPrice;
84 84  
  85 + @Schema(description = "VIP 减免金额,单位:分", requiredMode = Schema.RequiredMode.REQUIRED, example = "30")
  86 + private Integer vipPrice;
  87 +
85 88 @Schema(description = "实际支付金额(总),单位:分", requiredMode = Schema.RequiredMode.REQUIRED, example = "450")
86 89 private Integer payPrice;
87 90  
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/convert/aftersale/TradeAfterSaleConvert.java
... ... @@ -6,6 +6,7 @@ import cn.iocoder.yudao.module.pay.api.refund.dto.PayRefundCreateReqDTO;
6 6 import cn.iocoder.yudao.module.product.api.property.dto.ProductPropertyValueDetailRespDTO;
7 7 import cn.iocoder.yudao.module.trade.controller.admin.aftersale.vo.TradeAfterSaleDetailRespVO;
8 8 import cn.iocoder.yudao.module.trade.controller.admin.aftersale.vo.TradeAfterSaleRespPageItemVO;
  9 +import cn.iocoder.yudao.module.trade.controller.admin.aftersale.vo.log.TradeAfterSaleLogRespVO;
9 10 import cn.iocoder.yudao.module.trade.controller.admin.base.member.user.MemberUserRespVO;
10 11 import cn.iocoder.yudao.module.trade.controller.admin.base.product.property.ProductPropertyValueDetailRespVO;
11 12 import cn.iocoder.yudao.module.trade.controller.admin.order.vo.TradeOrderBaseVO;
... ... @@ -15,7 +16,6 @@ import cn.iocoder.yudao.module.trade.dal.dataobject.aftersale.TradeAfterSaleDO;
15 16 import cn.iocoder.yudao.module.trade.dal.dataobject.aftersale.TradeAfterSaleLogDO;
16 17 import cn.iocoder.yudao.module.trade.dal.dataobject.order.TradeOrderDO;
17 18 import cn.iocoder.yudao.module.trade.dal.dataobject.order.TradeOrderItemDO;
18   -import cn.iocoder.yudao.module.trade.framework.aftersalelog.core.dto.TradeAfterSaleLogRespVO;
19 19 import cn.iocoder.yudao.module.trade.framework.order.config.TradeOrderProperties;
20 20 import org.mapstruct.Mapper;
21 21 import org.mapstruct.Mapping;
... ... @@ -68,7 +68,7 @@ public interface TradeAfterSaleConvert {
68 68 PageResult<AppTradeAfterSaleRespVO> convertPage02(PageResult<TradeAfterSaleDO> page);
69 69  
70 70 List<TradeAfterSaleLogRespVO> convertList(List<TradeAfterSaleLogDO> list);
71   -
  71 +
72 72 default TradeAfterSaleDetailRespVO convert(TradeAfterSaleDO afterSale, TradeOrderDO order, List<TradeOrderItemDO> orderItems,
73 73 MemberUserRespDTO user, List<TradeAfterSaleLogRespVO> logs) {
74 74 TradeAfterSaleDetailRespVO respVO = convert(afterSale, orderItems);
... ... @@ -81,7 +81,7 @@ public interface TradeAfterSaleConvert {
81 81 return respVO;
82 82 }
83 83  
84   - List<cn.iocoder.yudao.module.trade.controller.admin.aftersale.vo.log.TradeAfterSaleLogRespVO> convertList1(List<TradeAfterSaleLogRespVO> list);
  84 + List<TradeAfterSaleLogRespVO> convertList1(List<TradeAfterSaleLogRespVO> list);
85 85 @Mapping(target = "id", source = "afterSale.id")
86 86 TradeAfterSaleDetailRespVO convert(TradeAfterSaleDO afterSale, List<TradeOrderItemDO> orderItems);
87 87 TradeOrderBaseVO convert(TradeOrderDO order);
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/convert/brokerage/record/BrokerageRecordConvert.java renamed to yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/convert/brokerage/BrokerageRecordConvert.java
1   -package cn.iocoder.yudao.module.trade.convert.brokerage.record;
  1 +package cn.iocoder.yudao.module.trade.convert.brokerage;
2 2  
  3 +import cn.hutool.core.math.Money;
3 4 import cn.hutool.core.util.ObjectUtil;
4 5 import cn.hutool.core.util.StrUtil;
5 6 import cn.iocoder.yudao.framework.common.pojo.PageResult;
  7 +import cn.iocoder.yudao.framework.common.util.number.MoneyUtils;
6 8 import cn.iocoder.yudao.module.member.api.user.dto.MemberUserRespDTO;
7   -import cn.iocoder.yudao.module.trade.controller.admin.brokerage.record.vo.BrokerageRecordRespVO;
8   -import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.record.BrokerageRecordDO;
9   -import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.user.BrokerageUserDO;
  9 +import cn.iocoder.yudao.module.trade.controller.admin.brokerage.vo.record.BrokerageRecordPageReqVO;
  10 +import cn.iocoder.yudao.module.trade.controller.admin.brokerage.vo.record.BrokerageRecordRespVO;
  11 +import cn.iocoder.yudao.module.trade.controller.app.brokerage.vo.record.AppBrokerageRecordPageReqVO;
  12 +import cn.iocoder.yudao.module.trade.controller.app.brokerage.vo.record.AppBrokerageRecordRespVO;
  13 +import cn.iocoder.yudao.module.trade.controller.app.brokerage.vo.user.AppBrokerageUserRankByPriceRespVO;
  14 +import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.BrokerageRecordDO;
  15 +import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.BrokerageUserDO;
10 16 import cn.iocoder.yudao.module.trade.enums.brokerage.BrokerageRecordBizTypeEnum;
11 17 import cn.iocoder.yudao.module.trade.enums.brokerage.BrokerageRecordStatusEnum;
12 18 import org.mapstruct.Mapper;
  19 +import org.mapstruct.MappingTarget;
13 20 import org.mapstruct.factory.Mappers;
14 21  
15 22 import java.time.LocalDateTime;
... ... @@ -45,7 +52,7 @@ public interface BrokerageRecordConvert {
45 52 .setBizType(bizType.getType()).setBizId(bizId)
46 53 .setPrice(brokeragePrice).setTotalPrice(user.getBrokeragePrice())
47 54 .setTitle(title)
48   - .setDescription(StrUtil.format(bizType.getDescription(), String.format("¥%.2f", brokeragePrice / 100d)))
  55 + .setDescription(StrUtil.format(bizType.getDescription(), MoneyUtils.fenToYuanStr(Math.abs(brokeragePrice))))
49 56 .setStatus(status).setFrozenDays(brokerageFrozenDays).setUnfreezeTime(unfreezeTime)
50 57 .setSourceUserLevel(sourceUserLevel).setSourceUserId(sourceUserId);
51 58 }
... ... @@ -60,4 +67,17 @@ public interface BrokerageRecordConvert {
60 67 }
61 68 return result;
62 69 }
  70 +
  71 + BrokerageRecordPageReqVO convert(AppBrokerageRecordPageReqVO pageReqVO, Long userId);
  72 +
  73 + PageResult<AppBrokerageRecordRespVO> convertPage02(PageResult<BrokerageRecordDO> pageResult);
  74 +
  75 + default PageResult<AppBrokerageUserRankByPriceRespVO> convertPage03(PageResult<AppBrokerageUserRankByPriceRespVO> pageResult, Map<Long, MemberUserRespDTO> userMap) {
  76 + for (AppBrokerageUserRankByPriceRespVO vo : pageResult.getList()) {
  77 + copyTo(userMap.get(vo.getId()), vo);
  78 + }
  79 + return pageResult;
  80 + }
  81 +
  82 + void copyTo(MemberUserRespDTO from, @MappingTarget AppBrokerageUserRankByPriceRespVO to);
63 83 }
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/convert/brokerage/user/BrokerageUserConvert.java renamed to yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/convert/brokerage/BrokerageUserConvert.java
1   -package cn.iocoder.yudao.module.trade.convert.brokerage.user;
  1 +package cn.iocoder.yudao.module.trade.convert.brokerage;
2 2  
3 3 import cn.hutool.core.map.MapUtil;
4 4 import cn.iocoder.yudao.framework.common.pojo.PageResult;
5 5 import cn.iocoder.yudao.module.member.api.user.dto.MemberUserRespDTO;
6   -import cn.iocoder.yudao.module.trade.controller.admin.brokerage.user.vo.BrokerageUserRespVO;
7   -import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.user.BrokerageUserDO;
  6 +import cn.iocoder.yudao.module.trade.controller.admin.brokerage.vo.user.BrokerageUserRespVO;
  7 +import cn.iocoder.yudao.module.trade.controller.app.brokerage.vo.user.AppBrokerageUserRankByUserCountRespVO;
  8 +import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.BrokerageUserDO;
8 9 import cn.iocoder.yudao.module.trade.service.brokerage.bo.UserBrokerageSummaryBO;
  10 +import cn.iocoder.yudao.module.trade.service.brokerage.bo.UserWithdrawSummaryBO;
9 11 import org.mapstruct.Mapper;
  12 +import org.mapstruct.MappingTarget;
10 13 import org.mapstruct.factory.Mappers;
11 14  
12 15 import java.util.List;
... ... @@ -27,13 +30,14 @@ public interface BrokerageUserConvert {
27 30  
28 31 List<BrokerageUserRespVO> convertList(List<BrokerageUserDO> list);
29 32  
30   - PageResult<BrokerageUserRespVO> convertPage(PageResult<BrokerageUserDO> page);
  33 + PageResult<BrokerageUserRespVO> convertPage(PageResult<BrokerageUserDO> page, Map<Long, MemberUserRespDTO> userMap, Map<Long, Long> brokerageUserCountMap, Map<Long, UserBrokerageSummaryBO> userOrderSummaryMap);
31 34  
32 35 default PageResult<BrokerageUserRespVO> convertPage(PageResult<BrokerageUserDO> pageResult,
33 36 Map<Long, MemberUserRespDTO> userMap,
34 37 Map<Long, Long> brokerageUserCountMap,
35   - Map<Long, UserBrokerageSummaryBO> userOrderSummaryMap) {
36   - PageResult<BrokerageUserRespVO> result = convertPage(pageResult);
  38 + Map<Long, UserBrokerageSummaryBO> userOrderSummaryMap,
  39 + Map<Long, UserWithdrawSummaryBO> withdrawMap) {
  40 + PageResult<BrokerageUserRespVO> result = convertPage(pageResult, userMap, brokerageUserCountMap, userOrderSummaryMap);
37 41 for (BrokerageUserRespVO userVO : result.getList()) {
38 42 // 用户信息
39 43 copyTo(userMap.get(userVO.getId()), userVO);
... ... @@ -44,7 +48,10 @@ public interface BrokerageUserConvert {
44 48 Optional<UserBrokerageSummaryBO> orderSummaryOptional = Optional.ofNullable(userOrderSummaryMap.get(userVO.getId()));
45 49 userVO.setBrokerageOrderCount(orderSummaryOptional.map(UserBrokerageSummaryBO::getCount).orElse(0))
46 50 .setBrokerageOrderPrice(orderSummaryOptional.map(UserBrokerageSummaryBO::getPrice).orElse(0));
47   - // todo 已提现次数、已提现金额
  51 + // 已提现次数、已提现金额
  52 + Optional<UserWithdrawSummaryBO> withdrawSummaryOptional = Optional.ofNullable(withdrawMap.get(userVO.getId()));
  53 + userVO.setWithdrawCount(withdrawSummaryOptional.map(UserWithdrawSummaryBO::getCount).orElse(0))
  54 + .setWithdrawPrice(withdrawSummaryOptional.map(UserWithdrawSummaryBO::getPrice).orElse(0));
48 55 userVO.setWithdrawCount(0).setWithdrawPrice(0);
49 56 }
50 57 return result;
... ... @@ -55,4 +62,13 @@ public interface BrokerageUserConvert {
55 62 user -> target.setNickname(user.getNickname()).setAvatar(user.getAvatar()));
56 63 return target;
57 64 }
  65 +
  66 + default PageResult<AppBrokerageUserRankByUserCountRespVO> convertPage03(PageResult<AppBrokerageUserRankByUserCountRespVO> pageResult,
  67 + Map<Long, MemberUserRespDTO> userMap) {
  68 + pageResult.getList().forEach(vo -> copyTo(userMap.get(vo.getId()), vo));
  69 + return pageResult;
  70 + }
  71 +
  72 + void copyTo(MemberUserRespDTO from, @MappingTarget AppBrokerageUserRankByUserCountRespVO to);
  73 +
58 74 }
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/convert/brokerage/withdraw/BrokerageWithdrawConvert.java renamed to yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/convert/brokerage/BrokerageWithdrawConvert.java
1   -package cn.iocoder.yudao.module.trade.convert.brokerage.withdraw;
  1 +package cn.iocoder.yudao.module.trade.convert.brokerage;
2 2  
3 3 import cn.iocoder.yudao.framework.common.pojo.PageResult;
  4 +import cn.iocoder.yudao.framework.dict.core.util.DictFrameworkUtils;
4 5 import cn.iocoder.yudao.module.member.api.user.dto.MemberUserRespDTO;
5   -import cn.iocoder.yudao.module.trade.controller.admin.brokerage.withdraw.vo.BrokerageWithdrawRejectReqVO;
6   -import cn.iocoder.yudao.module.trade.controller.admin.brokerage.withdraw.vo.BrokerageWithdrawRespVO;
7   -import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.withdraw.BrokerageWithdrawDO;
  6 +import cn.iocoder.yudao.module.trade.controller.admin.brokerage.vo.withdraw.BrokerageWithdrawPageReqVO;
  7 +import cn.iocoder.yudao.module.trade.controller.admin.brokerage.vo.withdraw.BrokerageWithdrawRespVO;
  8 +import cn.iocoder.yudao.module.trade.controller.app.brokerage.vo.withdraw.AppBrokerageWithdrawCreateReqVO;
  9 +import cn.iocoder.yudao.module.trade.controller.app.brokerage.vo.withdraw.AppBrokerageWithdrawPageReqVO;
  10 +import cn.iocoder.yudao.module.trade.controller.app.brokerage.vo.withdraw.AppBrokerageWithdrawRespVO;
  11 +import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.BrokerageWithdrawDO;
  12 +import cn.iocoder.yudao.module.trade.enums.DictTypeConstants;
8 13 import org.mapstruct.Mapper;
9 14 import org.mapstruct.factory.Mappers;
10 15  
... ... @@ -22,7 +27,7 @@ public interface BrokerageWithdrawConvert {
22 27  
23 28 BrokerageWithdrawConvert INSTANCE = Mappers.getMapper(BrokerageWithdrawConvert.class);
24 29  
25   - BrokerageWithdrawDO convert(BrokerageWithdrawRejectReqVO bean);
  30 + BrokerageWithdrawDO convert(AppBrokerageWithdrawCreateReqVO createReqVO, Long userId, Integer feePrice);
26 31  
27 32 BrokerageWithdrawRespVO convert(BrokerageWithdrawDO bean);
28 33  
... ... @@ -38,4 +43,15 @@ public interface BrokerageWithdrawConvert {
38 43 return result;
39 44 }
40 45  
  46 + PageResult<AppBrokerageWithdrawRespVO> convertPage02(PageResult<BrokerageWithdrawDO> pageResult);
  47 +
  48 + default PageResult<AppBrokerageWithdrawRespVO> convertPage03(PageResult<BrokerageWithdrawDO> pageResult) {
  49 + PageResult<AppBrokerageWithdrawRespVO> result = convertPage02(pageResult);
  50 + for (AppBrokerageWithdrawRespVO vo : result.getList()) {
  51 + vo.setStatusName(DictFrameworkUtils.getDictDataLabel(DictTypeConstants.BROKERAGE_WITHDRAW_STATUS, vo.getStatus()));
  52 + }
  53 + return result;
  54 + }
  55 +
  56 + BrokerageWithdrawPageReqVO convert(AppBrokerageWithdrawPageReqVO pageReqVO, Long userId);
41 57 }
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/convert/config/TradeConfigConvert.java
... ... @@ -2,6 +2,7 @@ package cn.iocoder.yudao.module.trade.convert.config;
2 2  
3 3 import cn.iocoder.yudao.module.trade.controller.admin.config.vo.TradeConfigRespVO;
4 4 import cn.iocoder.yudao.module.trade.controller.admin.config.vo.TradeConfigSaveReqVO;
  5 +import cn.iocoder.yudao.module.trade.controller.app.config.vo.AppTradeConfigRespVO;
5 6 import cn.iocoder.yudao.module.trade.dal.dataobject.config.TradeConfigDO;
6 7 import org.mapstruct.Mapper;
7 8 import org.mapstruct.factory.Mappers;
... ... @@ -20,4 +21,5 @@ public interface TradeConfigConvert {
20 21  
21 22 TradeConfigRespVO convert(TradeConfigDO bean);
22 23  
  24 + AppTradeConfigRespVO convert02(TradeConfigDO tradeConfig);
23 25 }
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/convert/order/TradeOrderConvert.java
1 1 package cn.iocoder.yudao.module.trade.convert.order;
2 2  
  3 +import cn.hutool.core.util.BooleanUtil;
3 4 import cn.hutool.core.util.StrUtil;
4 5 import cn.iocoder.yudao.framework.common.pojo.PageResult;
5 6 import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
... ... @@ -14,6 +15,7 @@ import cn.iocoder.yudao.module.product.api.comment.dto.ProductCommentCreateReqDT
14 15 import cn.iocoder.yudao.module.product.api.property.dto.ProductPropertyValueDetailRespDTO;
15 16 import cn.iocoder.yudao.module.product.api.sku.dto.ProductSkuRespDTO;
16 17 import cn.iocoder.yudao.module.product.api.sku.dto.ProductSkuUpdateStockReqDTO;
  18 +import cn.iocoder.yudao.module.product.api.spu.dto.ProductSpuRespDTO;
17 19 import cn.iocoder.yudao.module.promotion.api.combination.dto.CombinationRecordCreateReqDTO;
18 20 import cn.iocoder.yudao.module.trade.api.order.dto.TradeOrderRespDTO;
19 21 import cn.iocoder.yudao.module.trade.controller.admin.base.member.user.MemberUserRespVO;
... ... @@ -56,6 +58,7 @@ public interface TradeOrderConvert {
56 58  
57 59 @Mappings({
58 60 @Mapping(target = "id", ignore = true),
  61 + @Mapping(source = "userId", target = "userId"),
59 62 @Mapping(source = "createReqVO.couponId", target = "couponId"),
60 63 @Mapping(target = "remark", ignore = true),
61 64 @Mapping(source = "createReqVO.remark", target = "userRemark"),
... ... @@ -64,14 +67,11 @@ public interface TradeOrderConvert {
64 67 @Mapping(source = "calculateRespBO.price.deliveryPrice", target = "deliveryPrice"),
65 68 @Mapping(source = "calculateRespBO.price.couponPrice", target = "couponPrice"),
66 69 @Mapping(source = "calculateRespBO.price.pointPrice", target = "pointPrice"),
67   - @Mapping(source = "calculateRespBO.price.payPrice", target = "payPrice"),
68   - @Mapping(source = "address.name", target = "receiverName"),
69   - @Mapping(source = "address.mobile", target = "receiverMobile"),
70   - @Mapping(source = "address.areaId", target = "receiverAreaId"),
71   - @Mapping(source = "address.detailAddress", target = "receiverDetailAddress"),
  70 + @Mapping(source = "calculateRespBO.price.vipPrice", target = "vipPrice"),
  71 + @Mapping(source = "calculateRespBO.price.payPrice", target = "payPrice")
72 72 })
73 73 TradeOrderDO convert(Long userId, String userIp, AppTradeOrderCreateReqVO createReqVO,
74   - TradePriceCalculateRespBO calculateRespBO, AddressRespDTO address);
  74 + TradePriceCalculateRespBO calculateRespBO);
75 75  
76 76 TradeOrderRespDTO convert(TradeOrderDO orderDO);
77 77  
... ... @@ -89,23 +89,16 @@ public interface TradeOrderConvert {
89 89 TradeOrderItemDO convert(TradePriceCalculateRespBO.OrderItem item);
90 90  
91 91 default ProductSkuUpdateStockReqDTO convert(List<TradeOrderItemDO> list) {
92   - return new ProductSkuUpdateStockReqDTO(TradeOrderConvert.INSTANCE.convertList(list));
  92 + List<ProductSkuUpdateStockReqDTO.Item> items = CollectionUtils.convertList(list, item ->
  93 + new ProductSkuUpdateStockReqDTO.Item().setId(item.getSkuId()).setIncrCount(-item.getCount()));
  94 + return new ProductSkuUpdateStockReqDTO(items);
93 95 }
94   -
95   - default ProductSkuUpdateStockReqDTO convertNegative(List<TradeOrderItemDO> list) {
96   - List<ProductSkuUpdateStockReqDTO.Item> items = TradeOrderConvert.INSTANCE.convertList(list);
97   - items.forEach(item -> item.setIncrCount(-item.getIncrCount()));
  96 + default ProductSkuUpdateStockReqDTO convertNegative(List<AppTradeOrderSettlementReqVO.Item> list) {
  97 + List<ProductSkuUpdateStockReqDTO.Item> items = CollectionUtils.convertList(list, item ->
  98 + new ProductSkuUpdateStockReqDTO.Item().setId(item.getSkuId()).setIncrCount(-item.getCount()));
98 99 return new ProductSkuUpdateStockReqDTO(items);
99 100 }
100 101  
101   - List<ProductSkuUpdateStockReqDTO.Item> convertList(List<TradeOrderItemDO> list);
102   -
103   - @Mappings({
104   - @Mapping(source = "skuId", target = "id"),
105   - @Mapping(source = "count", target = "incrCount"),
106   - })
107   - ProductSkuUpdateStockReqDTO.Item convert(TradeOrderItemDO bean);
108   -
109 102 default PayOrderCreateReqDTO convert(TradeOrderDO order, List<TradeOrderItemDO> orderItems,
110 103 TradePriceCalculateRespBO calculateRespBO, TradeOrderProperties orderProperties) {
111 104 PayOrderCreateReqDTO createReqDTO = new PayOrderCreateReqDTO()
... ... @@ -220,7 +213,11 @@ public interface TradeOrderConvert {
220 213  
221 214 default TradePriceCalculateReqBO convert(Long userId, AppTradeOrderSettlementReqVO settlementReqVO,
222 215 List<CartDO> cartList) {
223   - TradePriceCalculateReqBO reqBO = convert(settlementReqVO).setUserId(userId).setItems(new ArrayList<>(settlementReqVO.getItems().size()));
  216 + TradePriceCalculateReqBO reqBO = new TradePriceCalculateReqBO().setUserId(userId)
  217 + .setCouponId(settlementReqVO.getCouponId()).setPointStatus(settlementReqVO.getPointStatus())
  218 + .setDeliveryType(settlementReqVO.getDeliveryType()).setAddressId(settlementReqVO.getAddressId())
  219 + .setPickUpStoreId(settlementReqVO.getPickUpStoreId())
  220 + .setItems(new ArrayList<>(settlementReqVO.getItems().size()));
224 221 // 商品项的构建
225 222 Map<Long, CartDO> cartMap = convertMap(cartList, CartDO::getId);
226 223 for (AppTradeOrderSettlementReqVO.Item item : settlementReqVO.getItems()) {
... ... @@ -273,11 +270,16 @@ public interface TradeOrderConvert {
273 270  
274 271 TradeOrderDO convert(TradeOrderRemarkReqVO reqVO);
275 272  
276   - default BrokerageAddReqBO convert(MemberUserRespDTO user, TradeOrderItemDO item, ProductSkuRespDTO sku) {
277   - return new BrokerageAddReqBO().setBizId(String.valueOf(item.getId())).setSourceUserId(item.getUserId())
  273 + default BrokerageAddReqBO convert(MemberUserRespDTO user, TradeOrderItemDO item,
  274 + ProductSpuRespDTO spu, ProductSkuRespDTO sku) {
  275 + BrokerageAddReqBO bo = new BrokerageAddReqBO().setBizId(String.valueOf(item.getId())).setSourceUserId(item.getUserId())
278 276 .setBasePrice(item.getPayPrice() * item.getCount())
279 277 .setTitle(StrUtil.format("{}成功购买{}", user.getNickname(), item.getSpuName()))
280   - .setFirstFixedPrice(sku.getFirstBrokeragePrice()).setSecondFixedPrice(sku.getSecondBrokeragePrice());
  278 + .setFirstFixedPrice(0).setSecondFixedPrice(0);
  279 + if (BooleanUtil.isTrue(spu.getSubCommissionType())) {
  280 + bo.setFirstFixedPrice(sku.getFirstBrokeragePrice()).setSecondFixedPrice(sku.getSecondBrokeragePrice());
  281 + }
  282 + return bo;
281 283 }
282 284  
283 285 TradeBeforeOrderCreateReqBO convert(AppTradeOrderCreateReqVO createReqVO);
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/dal/dataobject/brokerage/record/BrokerageRecordDO.java renamed to yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/dal/dataobject/brokerage/BrokerageRecordDO.java
1   -package cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.record;
  1 +package cn.iocoder.yudao.module.trade.dal.dataobject.brokerage;
2 2  
3 3 import cn.iocoder.yudao.framework.mybatis.core.dataobject.BaseDO;
4 4 import cn.iocoder.yudao.module.trade.enums.brokerage.BrokerageRecordBizTypeEnum;
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/dal/dataobject/brokerage/user/BrokerageUserDO.java renamed to yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/dal/dataobject/brokerage/BrokerageUserDO.java
1   -package cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.user;
  1 +package cn.iocoder.yudao.module.trade.dal.dataobject.brokerage;
2 2  
3 3 import cn.iocoder.yudao.framework.mybatis.core.dataobject.BaseDO;
4 4 import com.baomidou.mybatisplus.annotation.KeySequence;
... ... @@ -59,13 +59,4 @@ public class BrokerageUserDO extends BaseDO {
59 59 * 冻结佣金
60 60 */
61 61 private Integer frozenPrice;
62   -
63   - /**
64   - * 等级
65   - */
66   - private Integer level;
67   - /**
68   - * 路径
69   - */
70   - private String path;
71 62 }
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/dal/dataobject/brokerage/withdraw/BrokerageWithdrawDO.java renamed to yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/dal/dataobject/brokerage/BrokerageWithdrawDO.java
1   -package cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.withdraw;
  1 +package cn.iocoder.yudao.module.trade.dal.dataobject.brokerage;
2 2  
3 3 import cn.iocoder.yudao.framework.mybatis.core.dataobject.BaseDO;
4 4 import cn.iocoder.yudao.module.trade.enums.brokerage.BrokerageWithdrawStatusEnum;
... ... @@ -29,7 +29,7 @@ public class BrokerageWithdrawDO extends BaseDO {
29 29 * 编号
30 30 */
31 31 @TableId
32   - private Integer id;
  32 + private Long id;
33 33 /**
34 34 * 用户编号
35 35 *
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/dal/dataobject/config/TradeConfigDO.java
... ... @@ -35,6 +35,17 @@ public class TradeConfigDO extends BaseDO {
35 35 @TableId
36 36 private Long id;
37 37  
  38 + // ========== 配送相关 ==========
  39 +
  40 + /**
  41 + * 是否启用全场包邮
  42 + */
  43 + private Boolean deliveryExpressFreeEnabled;
  44 + /**
  45 + * 全场包邮的最小金额,单位:分
  46 + */
  47 + private Integer deliveryExpressFreePrice;
  48 +
38 49 // ========== 分销相关 ==========
39 50  
40 51 /**
... ... @@ -57,7 +68,7 @@ public class TradeConfigDO extends BaseDO {
57 68 * 分销海报图地址数组
58 69 */
59 70 @TableField(typeHandler = JacksonTypeHandler.class)
60   - private List<String> brokeragePostUrls;
  71 + private List<String> brokeragePosterUrls;
61 72 /**
62 73 * 一级返佣比例
63 74 */
... ... @@ -71,6 +82,10 @@ public class TradeConfigDO extends BaseDO {
71 82 */
72 83 private Integer brokerageWithdrawMinPrice;
73 84 /**
  85 + * 用户提现手续费百分比
  86 + */
  87 + private Integer brokerageWithdrawFeePercent;
  88 + /**
74 89 * 提现银行
75 90 */
76 91 @TableField(typeHandler = IntegerListTypeHandler.class)
... ... @@ -85,6 +100,6 @@ public class TradeConfigDO extends BaseDO {
85 100 * 枚举 {@link BrokerageWithdrawTypeEnum 对应的类}
86 101 */
87 102 @TableField(typeHandler = IntegerListTypeHandler.class)
88   - private List<Integer> brokerageWithdrawType;
  103 + private List<Integer> brokerageWithdrawTypes;
89 104  
90 105 }
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/dal/dataobject/order/TradeOrderDO.java
... ... @@ -168,6 +168,7 @@ public class TradeOrderDO extends BaseDO {
168 168 * - {@link #discountPrice}
169 169 * + {@link #deliveryPrice}
170 170 * + {@link #adjustPrice}
  171 + * - {@link #vipPrice}
171 172 */
172 173 private Integer payPrice;
173 174  
... ... @@ -224,6 +225,10 @@ public class TradeOrderDO extends BaseDO {
224 225 * 关联 {@link DeliveryPickUpStoreDO#getId()}
225 226 */
226 227 private Long pickUpStoreId;
  228 + /**
  229 + * 自提核销码
  230 + */
  231 + private String pickUpVerifyCode;
227 232  
228 233 // ========== 售后基本信息 ==========
229 234 /**
... ... @@ -251,12 +256,27 @@ public class TradeOrderDO extends BaseDO {
251 256 * 对应 taobao 的 trade.coupon_fee 字段
252 257 */
253 258 private Integer couponPrice;
254   - // TODO 芋艿:需要记录使用的积分;
  259 + /**
  260 + * 使用的积分
  261 + */
  262 + private Integer usePoint;
255 263 /**
256 264 * 积分抵扣的金额,单位:分
257 265 *
258 266 * 对应 taobao 的 trade.point_fee 字段
259 267 */
260 268 private Integer pointPrice;
  269 + /**
  270 + * 赠送的积分
  271 + */
  272 + private Integer givePoint;
  273 + /**
  274 + * 退还的使用的积分
  275 + */
  276 + private Integer refundPoint;
  277 + /**
  278 + * VIP 减免金额,单位:分
  279 + */
  280 + private Integer vipPrice;
261 281  
262 282 }
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/dal/dataobject/order/TradeOrderItemDO.java
... ... @@ -126,6 +126,7 @@ public class TradeOrderItemDO extends BaseDO {
126 126 * - {@link #discountPrice}
127 127 * + {@link #deliveryPrice}
128 128 * + {@link #adjustPrice}
  129 + * - {@link #vipPrice}
129 130 */
130 131 private Integer payPrice;
131 132  
... ... @@ -143,6 +144,18 @@ public class TradeOrderItemDO extends BaseDO {
143 144 * 对应 taobao 的 trade.point_fee 字段
144 145 */
145 146 private Integer pointPrice;
  147 + /**
  148 + * 使用的积分
  149 + */
  150 + private Integer usePoint;
  151 + /**
  152 + * 赠送的积分
  153 + */
  154 + private Integer givePoint;
  155 + /**
  156 + * VIP 减免金额,单位:分
  157 + */
  158 + private Integer vipPrice;
146 159 // TODO @芋艿:如果商品 vip 折扣时,到底是新增一个 vipPrice 记录优惠记录,还是 vipDiscountPrice,记录 vip 的优惠;还是直接使用 vipPrice;
147 160 // 目前 crmeb 的选择,单独一个 vipPrice 记录优惠价格;感觉不一定合理,可以在看看有赞的;
148 161  
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/dal/mysql/brokerage/record/BrokerageRecordMapper.java renamed to yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/dal/mysql/brokerage/BrokerageRecordMapper.java
1   -package cn.iocoder.yudao.module.trade.dal.mysql.brokerage.record;
  1 +package cn.iocoder.yudao.module.trade.dal.mysql.brokerage;
2 2  
3 3 import cn.iocoder.yudao.framework.common.pojo.PageResult;
4 4 import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
5 5 import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
6   -import cn.iocoder.yudao.module.trade.controller.admin.brokerage.record.vo.BrokerageRecordPageReqVO;
7   -import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.record.BrokerageRecordDO;
  6 +import cn.iocoder.yudao.module.trade.controller.admin.brokerage.vo.record.BrokerageRecordPageReqVO;
  7 +import cn.iocoder.yudao.module.trade.controller.app.brokerage.vo.user.AppBrokerageUserRankByPriceRespVO;
  8 +import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.BrokerageRecordDO;
8 9 import cn.iocoder.yudao.module.trade.service.brokerage.bo.UserBrokerageSummaryBO;
9 10 import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  11 +import com.baomidou.mybatisplus.core.metadata.IPage;
10 12 import org.apache.ibatis.annotations.Mapper;
11 13 import org.apache.ibatis.annotations.Param;
12 14 import org.apache.ibatis.annotations.Select;
... ... @@ -23,7 +25,6 @@ import java.util.List;
23 25 public interface BrokerageRecordMapper extends BaseMapperX<BrokerageRecordDO> {
24 26  
25 27 default PageResult<BrokerageRecordDO> selectPage(BrokerageRecordPageReqVO reqVO) {
26   - // 分页查询
27 28 return selectPage(reqVO, new LambdaQueryWrapperX<BrokerageRecordDO>()
28 29 .eqIfPresent(BrokerageRecordDO::getUserId, reqVO.getUserId())
29 30 .eqIfPresent(BrokerageRecordDO::getBizType, reqVO.getBizType())
... ... @@ -52,9 +53,28 @@ public interface BrokerageRecordMapper extends BaseMapperX&lt;BrokerageRecordDO&gt; {
52 53 }
53 54  
54 55 @Select("SELECT COUNT(1), SUM(price) FROM trade_brokerage_record " +
55   - "WHERE user_id = #{userId} AND biz_type = #{bizType} AND status = #{status}")
  56 + "WHERE user_id = #{userId} AND biz_type = #{bizType} AND status = #{status} AND deleted = FALSE")
56 57 UserBrokerageSummaryBO selectCountAndSumPriceByUserIdAndBizTypeAndStatus(@Param("userId") Long userId,
57 58 @Param("bizType") Integer bizType,
58 59 @Param("status") Integer status);
59 60  
  61 + @Select("SELECT SUM(price) FROM trade_brokerage_record " +
  62 + "WHERE user_id = #{userId} AND biz_type = #{bizType} " +
  63 + "AND create_time BETWEEN #{beginTime} AND #{endTime} AND deleted = FALSE")
  64 + Integer selectSummaryPriceByUserIdAndBizTypeAndCreateTimeBetween(@Param("userId") Long userId,
  65 + @Param("bizType") Integer bizType,
  66 + @Param("beginTime") LocalDateTime beginTime,
  67 + @Param("endTime") LocalDateTime endTime);
  68 +
  69 + @Select("SELECT user_id AS id, SUM(price) AS brokeragePrice FROM trade_brokerage_record " +
  70 + "WHERE biz_type = #{bizType} AND status = #{status} AND deleted = FALSE " +
  71 + "AND unfreeze_time BETWEEN #{beginTime} AND #{endTime} " +
  72 + "GROUP BY user_id " +
  73 + "ORDER BY brokeragePrice DESC")
  74 + IPage<AppBrokerageUserRankByPriceRespVO> selectSummaryPricePageGroupByUserId(IPage<?> page,
  75 + @Param("bizType") Integer bizType,
  76 + @Param("status") Integer status,
  77 + @Param("beginTime") LocalDateTime beginTime,
  78 + @Param("endTime") LocalDateTime endTime);
  79 +
60 80 }
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/dal/mysql/brokerage/user/BrokerageUserMapper.java renamed to yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/dal/mysql/brokerage/BrokerageUserMapper.java
1   -package cn.iocoder.yudao.module.trade.dal.mysql.brokerage.user;
  1 +package cn.iocoder.yudao.module.trade.dal.mysql.brokerage;
2 2  
3 3 import cn.hutool.core.lang.Assert;
4 4 import cn.iocoder.yudao.framework.common.pojo.PageResult;
5 5 import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
6 6 import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
7   -import cn.iocoder.yudao.module.trade.controller.admin.brokerage.user.vo.BrokerageUserPageReqVO;
8   -import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.user.BrokerageUserDO;
  7 +import cn.iocoder.yudao.module.trade.controller.admin.brokerage.vo.user.BrokerageUserPageReqVO;
  8 +import cn.iocoder.yudao.module.trade.controller.app.brokerage.vo.user.AppBrokerageUserChildSummaryPageReqVO;
  9 +import cn.iocoder.yudao.module.trade.controller.app.brokerage.vo.user.AppBrokerageUserChildSummaryRespVO;
  10 +import cn.iocoder.yudao.module.trade.controller.app.brokerage.vo.user.AppBrokerageUserRankByUserCountRespVO;
  11 +import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.BrokerageUserDO;
9 12 import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
  13 +import com.baomidou.mybatisplus.core.metadata.IPage;
  14 +import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
10 15 import org.apache.ibatis.annotations.Mapper;
  16 +import org.apache.ibatis.annotations.Param;
  17 +import org.apache.ibatis.annotations.Select;
11 18  
  19 +import java.time.LocalDateTime;
12 20 import java.util.List;
13 21  
14 22 /**
... ... @@ -19,13 +27,12 @@ import java.util.List;
19 27 @Mapper
20 28 public interface BrokerageUserMapper extends BaseMapperX<BrokerageUserDO> {
21 29  
22   - default PageResult<BrokerageUserDO> selectPage(BrokerageUserPageReqVO reqVO, List<Integer> levels) {
  30 + default PageResult<BrokerageUserDO> selectPage(BrokerageUserPageReqVO reqVO, List<Long> bindUserIds) {
23 31 return selectPage(reqVO, new LambdaQueryWrapperX<BrokerageUserDO>()
24 32 .eqIfPresent(BrokerageUserDO::getBrokerageEnabled, reqVO.getBrokerageEnabled())
25 33 .betweenIfPresent(BrokerageUserDO::getCreateTime, reqVO.getCreateTime())
26 34 .betweenIfPresent(BrokerageUserDO::getBindUserTime, reqVO.getBindUserTime())
27   - .findInSetIfPresent(BrokerageUserDO::getPath, reqVO.getBindUserId())
28   - .inIfPresent(BrokerageUserDO::getLevel, levels)
  35 + .inIfPresent(BrokerageUserDO::getBindUserId, bindUserIds)
29 36 .orderByDesc(BrokerageUserDO::getId));
30 37 }
31 38  
... ... @@ -38,7 +45,7 @@ public interface BrokerageUserMapper extends BaseMapperX&lt;BrokerageUserDO&gt; {
38 45 default void updatePriceIncr(Long id, Integer incrCount) {
39 46 Assert.isTrue(incrCount > 0);
40 47 LambdaUpdateWrapper<BrokerageUserDO> lambdaUpdateWrapper = new LambdaUpdateWrapper<BrokerageUserDO>()
41   - .setSql(" price = price + " + incrCount)
  48 + .setSql(" brokerage_price = brokerage_price + " + incrCount)
42 49 .eq(BrokerageUserDO::getId, id);
43 50 update(null, lambdaUpdateWrapper);
44 51 }
... ... @@ -49,13 +56,14 @@ public interface BrokerageUserMapper extends BaseMapperX&lt;BrokerageUserDO&gt; {
49 56 *
50 57 * @param id 用户编号
51 58 * @param incrCount 增加佣金(负数)
  59 + * @return 更新行数
52 60 */
53   - default void updatePriceDecr(Long id, Integer incrCount) {
  61 + default int updatePriceDecr(Long id, Integer incrCount) {
54 62 Assert.isTrue(incrCount < 0);
55 63 LambdaUpdateWrapper<BrokerageUserDO> lambdaUpdateWrapper = new LambdaUpdateWrapper<BrokerageUserDO>()
56   - .setSql(" price = price + " + incrCount) // 负数,所以使用 + 号
  64 + .setSql(" brokerage_price = brokerage_price + " + incrCount) // 负数,所以使用 + 号
57 65 .eq(BrokerageUserDO::getId, id);
58   - update(null, lambdaUpdateWrapper);
  66 + return update(null, lambdaUpdateWrapper);
59 67 }
60 68  
61 69 /**
... ... @@ -98,7 +106,7 @@ public interface BrokerageUserMapper extends BaseMapperX&lt;BrokerageUserDO&gt; {
98 106 Assert.isTrue(incrCount < 0);
99 107 LambdaUpdateWrapper<BrokerageUserDO> lambdaUpdateWrapper = new LambdaUpdateWrapper<BrokerageUserDO>()
100 108 .setSql(" frozen_price = frozen_price + " + incrCount + // 负数,所以使用 + 号
101   - ", price = price + " + -incrCount) // 负数,所以使用 - 号
  109 + ", brokerage_price = brokerage_price + " + -incrCount) // 负数,所以使用 - 号
102 110 .eq(BrokerageUserDO::getId, id)
103 111 .ge(BrokerageUserDO::getFrozenPrice, -incrCount); // cas 逻辑
104 112 return update(null, lambdaUpdateWrapper);
... ... @@ -107,8 +115,7 @@ public interface BrokerageUserMapper extends BaseMapperX&lt;BrokerageUserDO&gt; {
107 115 default void updateBindUserIdAndBindUserTimeToNull(Long id) {
108 116 update(null, new LambdaUpdateWrapper<BrokerageUserDO>()
109 117 .eq(BrokerageUserDO::getId, id)
110   - .set(BrokerageUserDO::getBindUserId, null).set(BrokerageUserDO::getBindUserTime, null)
111   - .set(BrokerageUserDO::getLevel, 1).set(BrokerageUserDO::getPath, ""));
  118 + .set(BrokerageUserDO::getBindUserId, null).set(BrokerageUserDO::getBindUserTime, null));
112 119 }
113 120  
114 121 default void updateEnabledFalseAndBrokerageTimeToNull(Long id) {
... ... @@ -117,10 +124,26 @@ public interface BrokerageUserMapper extends BaseMapperX&lt;BrokerageUserDO&gt; {
117 124 .set(BrokerageUserDO::getBrokerageEnabled, false).set(BrokerageUserDO::getBrokerageTime, null));
118 125 }
119 126  
120   - default Long selectCountByBindUserIdAndLevelIn(Long bindUserId, List<Integer> levels) {
  127 + default Long selectCountByBindUserIdIn(List<Long> bindUserIds) {
121 128 return selectCount(new LambdaQueryWrapperX<BrokerageUserDO>()
122   - .findInSetIfPresent(BrokerageUserDO::getPath, bindUserId)
123   - .inIfPresent(BrokerageUserDO::getLevel, levels));
  129 + .inIfPresent(BrokerageUserDO::getBindUserId, bindUserIds));
  130 + }
  131 +
  132 + @Select("SELECT bind_user_id AS id, COUNT(1) AS brokerageUserCount FROM trade_brokerage_user " +
  133 + "WHERE bind_user_id IS NOT NULL AND deleted = FALSE " +
  134 + "AND bind_user_time BETWEEN #{beginTime} AND #{endTime} " +
  135 + "GROUP BY bind_user_id " +
  136 + "ORDER BY brokerageUserCount DESC")
  137 + IPage<AppBrokerageUserRankByUserCountRespVO> selectCountPageGroupByBindUserId(Page<?> page,
  138 + @Param("beginTime") LocalDateTime beginTime,
  139 + @Param("endTime") LocalDateTime endTime);
  140 +
  141 + IPage<AppBrokerageUserChildSummaryRespVO> selectSummaryPageByUserId(Page<?> page,
  142 + @Param("param") AppBrokerageUserChildSummaryPageReqVO param,
  143 + @Param("userId") Long userId);
  144 +
  145 + default List<BrokerageUserDO> selectListByBindUserId(Long bindUserId) {
  146 + return selectList(BrokerageUserDO::getBindUserId, bindUserId);
124 147 }
125 148  
126 149 }
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/dal/mysql/brokerage/withdraw/BrokerageWithdrawMapper.java renamed to yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/dal/mysql/brokerage/BrokerageWithdrawMapper.java
1   -package cn.iocoder.yudao.module.trade.dal.mysql.brokerage.withdraw;
  1 +package cn.iocoder.yudao.module.trade.dal.mysql.brokerage;
2 2  
3 3 import cn.iocoder.yudao.framework.common.pojo.PageResult;
4 4 import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
5 5 import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
6   -import cn.iocoder.yudao.module.trade.controller.admin.brokerage.withdraw.vo.BrokerageWithdrawPageReqVO;
7   -import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.withdraw.BrokerageWithdrawDO;
  6 +import cn.iocoder.yudao.module.trade.controller.admin.brokerage.vo.withdraw.BrokerageWithdrawPageReqVO;
  7 +import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.BrokerageWithdrawDO;
  8 +import cn.iocoder.yudao.module.trade.service.brokerage.bo.UserWithdrawSummaryBO;
8 9 import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
9 10 import org.apache.ibatis.annotations.Mapper;
  11 +import org.apache.ibatis.annotations.Param;
  12 +import org.apache.ibatis.annotations.Select;
10 13  
11 14 /**
12 15 * 佣金提现 Mapper
... ... @@ -34,4 +37,9 @@ public interface BrokerageWithdrawMapper extends BaseMapperX&lt;BrokerageWithdrawDO
34 37 .eq(BrokerageWithdrawDO::getStatus, status));
35 38 }
36 39  
  40 + @Select("SELECT COUNT(1) AS count, SUM(price) AS price FROM trade_brokerage_withdraw " +
  41 + "WHERE user_id = #{userId} AND status = #{status} AND deleted = FALSE")
  42 + UserWithdrawSummaryBO selectCountAndSumPriceByUserIdAndStatus(@Param("userId") Long userId,
  43 + @Param("status") Integer status);
  44 +
37 45 }
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/framework/aftersalelog/core/dto/TradeAfterSaleLogRespVO.java deleted
1   -package cn.iocoder.yudao.module.trade.framework.aftersalelog.core.dto;
2   -
3   -import io.swagger.v3.oas.annotations.media.Schema;
4   -import lombok.AllArgsConstructor;
5   -import lombok.Data;
6   -import lombok.NoArgsConstructor;
7   -
8   -import javax.validation.constraints.NotNull;
9   -import java.time.LocalDateTime;
10   -
11   -/**
12   - * 贸易售后日志详情 DTO
13   - *
14   - * @author HUIHUI
15   - */
16   -@Data
17   -@NoArgsConstructor
18   -@AllArgsConstructor
19   -public class TradeAfterSaleLogRespVO {
20   -
21   - @Schema(description = "编号", requiredMode = Schema.RequiredMode.REQUIRED, example = "20669")
22   - private Long id;
23   -
24   - @Schema(description = "用户编号", requiredMode = Schema.RequiredMode.REQUIRED, example = "22634")
25   - @NotNull(message = "用户编号不能为空")
26   - private Long userId;
27   -
28   - @Schema(description = "用户类型", requiredMode = Schema.RequiredMode.REQUIRED, example = "2")
29   - @NotNull(message = "用户类型不能为空")
30   - private Integer userType;
31   -
32   - @Schema(description = "售后编号", requiredMode = Schema.RequiredMode.REQUIRED, example = "3023")
33   - @NotNull(message = "售后编号不能为空")
34   - private Long afterSaleId;
35   -
36   - @Schema(description = "订单编号", requiredMode = Schema.RequiredMode.REQUIRED, example = "25870")
37   - @NotNull(message = "订单编号不能为空")
38   - private Long orderId;
39   -
40   - @Schema(description = "订单项编号", requiredMode = Schema.RequiredMode.REQUIRED, example = "23154")
41   - @NotNull(message = "订单项编号不能为空")
42   - private Long orderItemId;
43   -
44   - @Schema(description = "售后状态(之前)", example = "2")
45   - private Integer beforeStatus;
46   -
47   - @Schema(description = "售后状态(之后)", requiredMode = Schema.RequiredMode.REQUIRED, example = "1")
48   - @NotNull(message = "售后状态(之后)不能为空")
49   - private Integer afterStatus;
50   -
51   - @Schema(description = "操作明细", requiredMode = Schema.RequiredMode.REQUIRED, example = "维权完成,退款金额:¥37776.00")
52   - @NotNull(message = "操作明细不能为空")
53   - private String content;
54   -
55   - @Schema(description = "创建时间", requiredMode = Schema.RequiredMode.REQUIRED)
56   - private LocalDateTime createTime;
57   -
58   -}
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/framework/aftersalelog/core/service/AfterSaleLogService.java
1 1 package cn.iocoder.yudao.module.trade.framework.aftersalelog.core.service;
2 2  
3 3  
  4 +import cn.iocoder.yudao.module.trade.controller.admin.aftersale.vo.log.TradeAfterSaleLogRespVO;
4 5 import cn.iocoder.yudao.module.trade.framework.aftersalelog.core.dto.TradeAfterSaleLogCreateReqDTO;
5   -import cn.iocoder.yudao.module.trade.framework.aftersalelog.core.dto.TradeAfterSaleLogRespVO;
6 6  
7 7 import java.util.List;
8 8  
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/framework/order/core/aop/TradeOrderLogAspect.java
... ... @@ -63,6 +63,9 @@ public class TradeOrderLogAspect {
63 63 Long userId = getUserId();
64 64 // 1.2 订单信息
65 65 Long orderId = ORDER_ID.get();
  66 + if (orderId == null) { // 如果未设置,只有注解,说明不需要记录订单日志
  67 + return;
  68 + }
66 69 Integer beforeStatus = BEFORE_STATUS.get();
67 70 Integer afterStatus = AFTER_STATUS.get();
68 71 Map<String, Object> exts = ObjectUtil.defaultIfNull(EXTS.get(), emptyMap());
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/job/brokerage/BrokerageRecordUnfreezeJob.java
... ... @@ -3,7 +3,7 @@ package cn.iocoder.yudao.module.trade.job.brokerage;
3 3 import cn.hutool.core.util.StrUtil;
4 4 import cn.iocoder.yudao.framework.quartz.core.handler.JobHandler;
5 5 import cn.iocoder.yudao.framework.tenant.core.job.TenantJob;
6   -import cn.iocoder.yudao.module.trade.service.brokerage.record.BrokerageRecordService;
  6 +import cn.iocoder.yudao.module.trade.service.brokerage.BrokerageRecordService;
7 7 import org.springframework.stereotype.Component;
8 8  
9 9 import javax.annotation.Resource;
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/service/aftersale/TradeAfterSaleServiceImpl.java
... ... @@ -11,6 +11,7 @@ import cn.iocoder.yudao.module.pay.api.refund.dto.PayRefundCreateReqDTO;
11 11 import cn.iocoder.yudao.module.trade.controller.admin.aftersale.vo.TradeAfterSaleDisagreeReqVO;
12 12 import cn.iocoder.yudao.module.trade.controller.admin.aftersale.vo.TradeAfterSalePageReqVO;
13 13 import cn.iocoder.yudao.module.trade.controller.admin.aftersale.vo.TradeAfterSaleRefuseReqVO;
  14 +import cn.iocoder.yudao.module.trade.controller.admin.aftersale.vo.log.TradeAfterSaleLogRespVO;
14 15 import cn.iocoder.yudao.module.trade.controller.app.aftersale.vo.AppTradeAfterSaleCreateReqVO;
15 16 import cn.iocoder.yudao.module.trade.controller.app.aftersale.vo.AppTradeAfterSaleDeliveryReqVO;
16 17 import cn.iocoder.yudao.module.trade.convert.aftersale.TradeAfterSaleConvert;
... ... @@ -26,7 +27,6 @@ import cn.iocoder.yudao.module.trade.enums.aftersale.TradeAfterSaleWayEnum;
26 27 import cn.iocoder.yudao.module.trade.enums.order.TradeOrderItemAfterSaleStatusEnum;
27 28 import cn.iocoder.yudao.module.trade.enums.order.TradeOrderStatusEnum;
28 29 import cn.iocoder.yudao.module.trade.framework.aftersalelog.core.dto.TradeAfterSaleLogCreateReqDTO;
29   -import cn.iocoder.yudao.module.trade.framework.aftersalelog.core.dto.TradeAfterSaleLogRespVO;
30 30 import cn.iocoder.yudao.module.trade.framework.aftersalelog.core.service.AfterSaleLogService;
31 31 import cn.iocoder.yudao.module.trade.framework.order.config.TradeOrderProperties;
32 32 import cn.iocoder.yudao.module.trade.service.order.TradeOrderQueryService;
... ... @@ -449,6 +449,7 @@ public class TradeAfterSaleServiceImpl implements TradeAfterSaleService, AfterSa
449 449 }
450 450 }
451 451  
  452 + // TODO @puhui999:应该返回 do 哈。
452 453 @Override
453 454 public List<TradeAfterSaleLogRespVO> getLog(Long afterSaleId) {
454 455 // TODO 不熟悉流程先这么滴
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/service/brokerage/record/BrokerageRecordService.java renamed to yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/service/brokerage/BrokerageRecordService.java
1   -package cn.iocoder.yudao.module.trade.service.brokerage.record;
  1 +package cn.iocoder.yudao.module.trade.service.brokerage;
2 2  
3 3 import cn.iocoder.yudao.framework.common.pojo.PageResult;
4   -import cn.iocoder.yudao.module.trade.controller.admin.brokerage.record.vo.BrokerageRecordPageReqVO;
5   -import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.record.BrokerageRecordDO;
  4 +import cn.iocoder.yudao.module.trade.controller.admin.brokerage.vo.record.BrokerageRecordPageReqVO;
  5 +import cn.iocoder.yudao.module.trade.controller.app.brokerage.vo.record.AppBrokerageProductPriceRespVO;
  6 +import cn.iocoder.yudao.module.trade.controller.app.brokerage.vo.user.AppBrokerageUserRankByPriceRespVO;
  7 +import cn.iocoder.yudao.module.trade.controller.app.brokerage.vo.user.AppBrokerageUserRankPageReqVO;
  8 +import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.BrokerageRecordDO;
6 9 import cn.iocoder.yudao.module.trade.enums.brokerage.BrokerageRecordBizTypeEnum;
7 10 import cn.iocoder.yudao.module.trade.service.brokerage.bo.BrokerageAddReqBO;
8 11 import cn.iocoder.yudao.module.trade.service.brokerage.bo.UserBrokerageSummaryBO;
9 12  
10 13 import javax.validation.Valid;
  14 +import java.time.LocalDateTime;
11 15 import java.util.List;
12 16  
13 17 /**
... ... @@ -34,7 +38,7 @@ public interface BrokerageRecordService {
34 38 PageResult<BrokerageRecordDO> getBrokerageRecordPage(BrokerageRecordPageReqVO pageReqVO);
35 39  
36 40 /**
37   - * 增加佣金
  41 + * 增加佣金【多级分佣】
38 42 *
39 43 * @param userId 会员编号
40 44 * @param bizType 业务类型
... ... @@ -43,6 +47,17 @@ public interface BrokerageRecordService {
43 47 void addBrokerage(Long userId, BrokerageRecordBizTypeEnum bizType, @Valid List<BrokerageAddReqBO> list);
44 48  
45 49 /**
  50 + * 增加佣金【只针对自己】
  51 + *
  52 + * @param userId 会员编号
  53 + * @param bizType 业务类型
  54 + * @param bizId 业务编号
  55 + * @param brokeragePrice 佣金
  56 + * @param title 标题
  57 + */
  58 + void addBrokerage(Long userId, BrokerageRecordBizTypeEnum bizType, String bizId, Integer brokeragePrice, String title);
  59 +
  60 + /**
46 61 * 取消佣金:将佣金记录,状态修改为已失效
47 62 *
48 63 * @param userId 会员编号
... ... @@ -67,4 +82,41 @@ public interface BrokerageRecordService {
67 82 * @return 用户佣金汇总
68 83 */
69 84 UserBrokerageSummaryBO getUserBrokerageSummaryByUserId(Long userId, Integer bizType, Integer status);
  85 +
  86 + /**
  87 + * 获得用户佣金合计
  88 + *
  89 + * @param userId 用户编号
  90 + * @param bizType 业务类型
  91 + * @param beginTime 开始时间
  92 + * @param endTime 截止时间
  93 + * @return 用户佣金合计
  94 + */
  95 + Integer getSummaryPriceByUserId(Long userId, Integer bizType, LocalDateTime beginTime, LocalDateTime endTime);
  96 +
  97 + /**
  98 + * 获得用户佣金排行分页列表(基于佣金总数)
  99 + *
  100 + * @param pageReqVO 分页查询
  101 + * @return 排行榜分页
  102 + */
  103 + PageResult<AppBrokerageUserRankByPriceRespVO> getBrokerageUserChildSummaryPageByPrice(AppBrokerageUserRankPageReqVO pageReqVO);
  104 +
  105 + /**
  106 + * 获取用户的排名(基于佣金总数)
  107 + *
  108 + * @param userId 用户编号
  109 + * @param times 时间范围
  110 + * @return 用户的排名
  111 + */
  112 + Integer getUserRankByPrice(Long userId, LocalDateTime[] times);
  113 +
  114 + /**
  115 + * 计算商品被购买后,推广员可以得到的佣金
  116 + *
  117 + * @param spuId 商品编号
  118 + * @param userId 用户编号
  119 + * @return 用户佣金
  120 + */
  121 + AppBrokerageProductPriceRespVO calculateProductBrokeragePrice(Long spuId, Long userId);
70 122 }
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/service/brokerage/record/BrokerageRecordServiceImpl.java renamed to yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/service/brokerage/BrokerageRecordServiceImpl.java
1   -package cn.iocoder.yudao.module.trade.service.brokerage.record;
  1 +package cn.iocoder.yudao.module.trade.service.brokerage;
2 2  
3 3 import cn.hutool.core.collection.CollUtil;
  4 +import cn.hutool.core.collection.ListUtil;
  5 +import cn.hutool.core.util.ArrayUtil;
4 6 import cn.hutool.core.util.BooleanUtil;
5 7 import cn.hutool.core.util.ObjectUtil;
6 8 import cn.hutool.core.util.StrUtil;
7 9 import cn.hutool.extra.spring.SpringUtil;
8 10 import cn.iocoder.yudao.framework.common.pojo.PageResult;
9 11 import cn.iocoder.yudao.framework.common.util.number.MoneyUtils;
10   -import cn.iocoder.yudao.module.trade.controller.admin.brokerage.record.vo.BrokerageRecordPageReqVO;
11   -import cn.iocoder.yudao.module.trade.convert.brokerage.record.BrokerageRecordConvert;
12   -import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.record.BrokerageRecordDO;
13   -import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.user.BrokerageUserDO;
  12 +import cn.iocoder.yudao.framework.mybatis.core.util.MyBatisUtils;
  13 +import cn.iocoder.yudao.module.product.api.sku.ProductSkuApi;
  14 +import cn.iocoder.yudao.module.product.api.sku.dto.ProductSkuRespDTO;
  15 +import cn.iocoder.yudao.module.product.api.spu.ProductSpuApi;
  16 +import cn.iocoder.yudao.module.product.api.spu.dto.ProductSpuRespDTO;
  17 +import cn.iocoder.yudao.module.trade.controller.admin.brokerage.vo.record.BrokerageRecordPageReqVO;
  18 +import cn.iocoder.yudao.module.trade.controller.app.brokerage.vo.record.AppBrokerageProductPriceRespVO;
  19 +import cn.iocoder.yudao.module.trade.controller.app.brokerage.vo.user.AppBrokerageUserRankByPriceRespVO;
  20 +import cn.iocoder.yudao.module.trade.controller.app.brokerage.vo.user.AppBrokerageUserRankPageReqVO;
  21 +import cn.iocoder.yudao.module.trade.convert.brokerage.BrokerageRecordConvert;
  22 +import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.BrokerageRecordDO;
  23 +import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.BrokerageUserDO;
14 24 import cn.iocoder.yudao.module.trade.dal.dataobject.config.TradeConfigDO;
15   -import cn.iocoder.yudao.module.trade.dal.mysql.brokerage.record.BrokerageRecordMapper;
  25 +import cn.iocoder.yudao.module.trade.dal.mysql.brokerage.BrokerageRecordMapper;
16 26 import cn.iocoder.yudao.module.trade.enums.brokerage.BrokerageRecordBizTypeEnum;
17 27 import cn.iocoder.yudao.module.trade.enums.brokerage.BrokerageRecordStatusEnum;
18 28 import cn.iocoder.yudao.module.trade.service.brokerage.bo.BrokerageAddReqBO;
19 29 import cn.iocoder.yudao.module.trade.service.brokerage.bo.UserBrokerageSummaryBO;
20   -import cn.iocoder.yudao.module.trade.service.brokerage.user.BrokerageUserService;
21 30 import cn.iocoder.yudao.module.trade.service.config.TradeConfigService;
  31 +import com.baomidou.mybatisplus.core.metadata.IPage;
22 32 import lombok.extern.slf4j.Slf4j;
23 33 import org.springframework.stereotype.Service;
24 34 import org.springframework.transaction.annotation.Transactional;
... ... @@ -29,6 +39,13 @@ import java.time.LocalDateTime;
29 39 import java.util.ArrayList;
30 40 import java.util.List;
31 41 import java.util.Objects;
  42 +import java.util.Optional;
  43 +
  44 +import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
  45 +import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.getMaxValue;
  46 +import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.getMinValue;
  47 +import static cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils.getLoginUserId;
  48 +import static cn.iocoder.yudao.module.trade.enums.ErrorCodeConstants.BROKERAGE_WITHDRAW_USER_BALANCE_NOT_ENOUGH;
32 49  
33 50 /**
34 51 * 佣金记录 Service 实现类
... ... @@ -47,6 +64,11 @@ public class BrokerageRecordServiceImpl implements BrokerageRecordService {
47 64 @Resource
48 65 private BrokerageUserService brokerageUserService;
49 66  
  67 + @Resource
  68 + private ProductSpuApi productSpuApi;
  69 + @Resource
  70 + private ProductSkuApi productSkuApi;
  71 +
50 72 @Override
51 73 public BrokerageRecordDO getBrokerageRecord(Integer id) {
52 74 return brokerageRecordMapper.selectById(id);
... ... @@ -218,6 +240,55 @@ public class BrokerageRecordServiceImpl implements BrokerageRecordService {
218 240 return summaryBO != null ? summaryBO : new UserBrokerageSummaryBO(0, 0);
219 241 }
220 242  
  243 + @Override
  244 + public Integer getSummaryPriceByUserId(Long userId, Integer bizType, LocalDateTime beginTime, LocalDateTime endTime) {
  245 + return brokerageRecordMapper.selectSummaryPriceByUserIdAndBizTypeAndCreateTimeBetween(userId, bizType, beginTime, endTime);
  246 + }
  247 +
  248 + @Override
  249 + public PageResult<AppBrokerageUserRankByPriceRespVO> getBrokerageUserChildSummaryPageByPrice(AppBrokerageUserRankPageReqVO pageReqVO) {
  250 + IPage<AppBrokerageUserRankByPriceRespVO> pageResult = brokerageRecordMapper.selectSummaryPricePageGroupByUserId(MyBatisUtils.buildPage(pageReqVO),
  251 + BrokerageRecordBizTypeEnum.ORDER.getType(), BrokerageRecordStatusEnum.SETTLEMENT.getStatus(),
  252 + ArrayUtil.get(pageReqVO.getTimes(), 0), ArrayUtil.get(pageReqVO.getTimes(), 1));
  253 + return new PageResult<>(pageResult.getRecords(), pageResult.getTotal());
  254 + }
  255 +
  256 + @Override
  257 + public Integer getUserRankByPrice(Long userId, LocalDateTime[] times) {
  258 + AppBrokerageUserRankPageReqVO pageParam = new AppBrokerageUserRankPageReqVO().setTimes(times);
  259 + // 取前 100 名
  260 + pageParam.setPageSize(100);
  261 + PageResult<AppBrokerageUserRankByPriceRespVO> pageResult = getBrokerageUserChildSummaryPageByPrice(pageParam);
  262 + // 获得索引
  263 + int index = CollUtil.indexOf(pageResult.getList(), user -> Objects.equals(userId, user.getId()));
  264 + // 获得排名
  265 + return index + 1;
  266 + }
  267 +
  268 + @Override
  269 + @Transactional(rollbackFor = Exception.class)
  270 + public void addBrokerage(Long userId, BrokerageRecordBizTypeEnum bizType, String bizId, Integer brokeragePrice, String title) {
  271 + // 1. 校验佣金余额
  272 + BrokerageUserDO user = brokerageUserService.getBrokerageUser(userId);
  273 + int balance = Optional.of(user)
  274 + .map(BrokerageUserDO::getBrokeragePrice).orElse(0);
  275 + if (balance + brokeragePrice < 0) {
  276 + throw exception(BROKERAGE_WITHDRAW_USER_BALANCE_NOT_ENOUGH, MoneyUtils.fenToYuanStr(balance));
  277 + }
  278 +
  279 + // 2. 更新佣金余额
  280 + boolean success = brokerageUserService.updateUserPrice(userId, brokeragePrice);
  281 + if (!success) {
  282 + // 失败时,则抛出异常。只会出现扣减佣金时,余额不足的情况
  283 + throw exception(BROKERAGE_WITHDRAW_USER_BALANCE_NOT_ENOUGH, MoneyUtils.fenToYuanStr(balance));
  284 + }
  285 +
  286 + // 3. 新增记录
  287 + BrokerageRecordDO record = BrokerageRecordConvert.INSTANCE.convert(user, bizType, bizId, 0, brokeragePrice,
  288 + null, title, null, null);
  289 + brokerageRecordMapper.insert(record);
  290 + }
  291 +
221 292 @Transactional(rollbackFor = Exception.class)
222 293 public boolean unfreezeRecord(BrokerageRecordDO record) {
223 294 // 更新记录状态
... ... @@ -236,6 +307,47 @@ public class BrokerageRecordServiceImpl implements BrokerageRecordService {
236 307 return true;
237 308 }
238 309  
  310 + @Override
  311 + public AppBrokerageProductPriceRespVO calculateProductBrokeragePrice(Long spuId, Long userId) {
  312 + // 1. 构建默认的返回值
  313 + AppBrokerageProductPriceRespVO respVO = new AppBrokerageProductPriceRespVO().setEnabled(false)
  314 + .setBrokerageMinPrice(0).setBrokerageMaxPrice(0);
  315 +
  316 + // 2.1 校验分销功能是否开启
  317 + TradeConfigDO tradeConfig = tradeConfigService.getTradeConfig();
  318 + if (tradeConfig == null || BooleanUtil.isFalse(tradeConfig.getBrokerageEnabled())) {
  319 + return respVO;
  320 + }
  321 + // 2.2 校验用户是否有分销资格
  322 + respVO.setEnabled(brokerageUserService.getUserBrokerageEnabled(getLoginUserId()));
  323 + if (BooleanUtil.isFalse(respVO.getEnabled())) {
  324 + return respVO;
  325 + }
  326 + // 2.3 校验商品是否存在
  327 + ProductSpuRespDTO spu = productSpuApi.getSpu(spuId);
  328 + if (spu == null) {
  329 + return respVO;
  330 + }
  331 +
  332 + // 3.1 商品单独分佣模式
  333 + Integer fixedMinPrice = 0;
  334 + Integer fixedMaxPrice = 0;
  335 + Integer spuMinPrice = 0;
  336 + Integer spuMaxPrice = 0;
  337 + List<ProductSkuRespDTO> skuList = productSkuApi.getSkuListBySpuId(ListUtil.of(spuId));
  338 + if (BooleanUtil.isTrue(spu.getSubCommissionType())) {
  339 + fixedMinPrice = getMinValue(skuList, ProductSkuRespDTO::getFirstBrokeragePrice);
  340 + fixedMaxPrice = getMaxValue(skuList, ProductSkuRespDTO::getFirstBrokeragePrice);
  341 + // 3.2 全局分佣模式(根据商品价格比例计算)
  342 + } else {
  343 + spuMinPrice = getMinValue(skuList, ProductSkuRespDTO::getPrice);
  344 + spuMaxPrice = getMaxValue(skuList, ProductSkuRespDTO::getPrice);
  345 + }
  346 + respVO.setBrokerageMinPrice(calculatePrice(spuMinPrice, tradeConfig.getBrokerageFirstPercent(), fixedMinPrice));
  347 + respVO.setBrokerageMaxPrice(calculatePrice(spuMaxPrice, tradeConfig.getBrokerageFirstPercent(), fixedMaxPrice));
  348 + return respVO;
  349 + }
  350 +
239 351 /**
240 352 * 获得自身的代理对象,解决 AOP 生效问题
241 353 *
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/service/brokerage/user/BrokerageUserService.java renamed to yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/service/brokerage/BrokerageUserService.java
1   -package cn.iocoder.yudao.module.trade.service.brokerage.user;
  1 +package cn.iocoder.yudao.module.trade.service.brokerage;
2 2  
3 3 import cn.iocoder.yudao.framework.common.pojo.PageResult;
4 4 import cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils;
5   -import cn.iocoder.yudao.module.trade.controller.admin.brokerage.user.vo.BrokerageUserPageReqVO;
6   -import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.user.BrokerageUserDO;
  5 +import cn.iocoder.yudao.module.trade.controller.admin.brokerage.vo.user.BrokerageUserPageReqVO;
  6 +import cn.iocoder.yudao.module.trade.controller.app.brokerage.vo.user.AppBrokerageUserChildSummaryPageReqVO;
  7 +import cn.iocoder.yudao.module.trade.controller.app.brokerage.vo.user.AppBrokerageUserChildSummaryRespVO;
  8 +import cn.iocoder.yudao.module.trade.controller.app.brokerage.vo.user.AppBrokerageUserRankByUserCountRespVO;
  9 +import cn.iocoder.yudao.module.trade.controller.app.brokerage.vo.user.AppBrokerageUserRankPageReqVO;
  10 +import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.BrokerageUserDO;
7 11  
8 12 import javax.validation.constraints.NotNull;
9 13 import java.time.LocalDateTime;
... ... @@ -70,8 +74,9 @@ public interface BrokerageUserService {
70 74 *
71 75 * @param id 用户编号
72 76 * @param price 用户可用佣金
  77 + * @return 更新结果
73 78 */
74   - void updateUserPrice(Long id, Integer price);
  79 + boolean updateUserPrice(Long id, Integer price);
75 80  
76 81 /**
77 82 * 更新用户冻结佣金
... ... @@ -129,4 +134,21 @@ public interface BrokerageUserService {
129 134 * @return 是否有分销资格
130 135 */
131 136 Boolean getUserBrokerageEnabled(Long userId);
  137 +
  138 + /**
  139 + * 获得推广人排行
  140 + *
  141 + * @param pageReqVO 分页查询
  142 + * @return 推广人排行
  143 + */
  144 + PageResult<AppBrokerageUserRankByUserCountRespVO> getBrokerageUserRankPageByUserCount(AppBrokerageUserRankPageReqVO pageReqVO);
  145 +
  146 + /**
  147 + * 获得下级分销统计分页
  148 + *
  149 + * @param pageReqVO 分页查询
  150 + * @param userId 用户编号
  151 + * @return 下级分销统计分页
  152 + */
  153 + PageResult<AppBrokerageUserChildSummaryRespVO> getBrokerageUserChildSummaryPage(AppBrokerageUserChildSummaryPageReqVO pageReqVO, Long userId);
132 154 }
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/service/brokerage/user/BrokerageUserServiceImpl.java renamed to yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/service/brokerage/BrokerageUserServiceImpl.java
1   -package cn.iocoder.yudao.module.trade.service.brokerage.user;
  1 +package cn.iocoder.yudao.module.trade.service.brokerage;
2 2  
3 3 import cn.hutool.core.collection.CollUtil;
4 4 import cn.hutool.core.lang.Assert;
  5 +import cn.hutool.core.util.ArrayUtil;
5 6 import cn.hutool.core.util.BooleanUtil;
6   -import cn.hutool.core.util.ObjectUtil;
7   -import cn.hutool.core.util.StrUtil;
8 7 import cn.iocoder.yudao.framework.common.pojo.PageResult;
9   -import cn.iocoder.yudao.module.trade.controller.admin.brokerage.user.vo.BrokerageUserPageReqVO;
10   -import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.user.BrokerageUserDO;
  8 +import cn.iocoder.yudao.framework.mybatis.core.util.MyBatisUtils;
  9 +import cn.iocoder.yudao.module.trade.controller.admin.brokerage.vo.user.BrokerageUserPageReqVO;
  10 +import cn.iocoder.yudao.module.trade.controller.app.brokerage.vo.user.AppBrokerageUserChildSummaryPageReqVO;
  11 +import cn.iocoder.yudao.module.trade.controller.app.brokerage.vo.user.AppBrokerageUserChildSummaryRespVO;
  12 +import cn.iocoder.yudao.module.trade.controller.app.brokerage.vo.user.AppBrokerageUserRankByUserCountRespVO;
  13 +import cn.iocoder.yudao.module.trade.controller.app.brokerage.vo.user.AppBrokerageUserRankPageReqVO;
  14 +import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.BrokerageUserDO;
11 15 import cn.iocoder.yudao.module.trade.dal.dataobject.config.TradeConfigDO;
12   -import cn.iocoder.yudao.module.trade.dal.mysql.brokerage.user.BrokerageUserMapper;
  16 +import cn.iocoder.yudao.module.trade.dal.mysql.brokerage.BrokerageUserMapper;
13 17 import cn.iocoder.yudao.module.trade.enums.brokerage.BrokerageBindModeEnum;
14 18 import cn.iocoder.yudao.module.trade.enums.brokerage.BrokerageEnabledConditionEnum;
15 19 import cn.iocoder.yudao.module.trade.service.config.TradeConfigService;
  20 +import com.baomidou.mybatisplus.core.metadata.IPage;
16 21 import org.springframework.stereotype.Service;
17 22 import org.springframework.validation.annotation.Validated;
18 23  
19 24 import javax.annotation.Resource;
20 25 import java.time.LocalDateTime;
21   -import java.util.*;
  26 +import java.util.Collection;
  27 +import java.util.List;
  28 +import java.util.Objects;
  29 +import java.util.Optional;
22 30  
23 31 import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
  32 +import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
24 33 import static cn.iocoder.yudao.module.trade.enums.ErrorCodeConstants.*;
25 34  
26 35 /**
... ... @@ -50,14 +59,18 @@ public class BrokerageUserServiceImpl implements BrokerageUserService {
50 59  
51 60 @Override
52 61 public PageResult<BrokerageUserDO> getBrokerageUserPage(BrokerageUserPageReqVO pageReqVO) {
53   - List<Integer> levels = buildUserQueryLevels(pageReqVO.getBindUserId(), pageReqVO.getLevel());
54   - return brokerageUserMapper.selectPage(pageReqVO, levels);
  62 + List<Long> bindUserIds = buildBindUserIdsByLevel(pageReqVO.getBindUserId(), pageReqVO.getLevel());
  63 + return brokerageUserMapper.selectPage(pageReqVO, bindUserIds);
55 64 }
56 65  
57 66 @Override
58 67 public void updateBrokerageUserId(Long id, Long bindUserId) {
59 68 // 校验存在
60 69 BrokerageUserDO brokerageUser = validateBrokerageUserExists(id);
  70 + // 绑定关系未发生变化
  71 + if (Objects.equals(brokerageUser.getBindUserId(), bindUserId)) {
  72 + return;
  73 + }
61 74  
62 75 // 情况一:清除推广员
63 76 if (bindUserId == null) {
... ... @@ -66,12 +79,6 @@ public class BrokerageUserServiceImpl implements BrokerageUserService {
66 79 return;
67 80 }
68 81  
69   - // 绑定关系未发生变化
70   - // TODO @疯狂:这个放到“情况一”之前,貌似也没关系?
71   - if (Objects.equals(brokerageUser.getBindUserId(), bindUserId)) {
72   - return;
73   - }
74   -
75 82 // 情况二:修改推广员
76 83 validateCanBindUser(brokerageUser, bindUserId);
77 84 brokerageUserMapper.updateById(fillBindUserData(bindUserId, new BrokerageUserDO().setId(id)));
... ... @@ -110,12 +117,13 @@ public class BrokerageUserServiceImpl implements BrokerageUserService {
110 117 }
111 118  
112 119 @Override
113   - public void updateUserPrice(Long id, Integer price) {
  120 + public boolean updateUserPrice(Long id, Integer price) {
114 121 if (price > 0) {
115 122 brokerageUserMapper.updatePriceIncr(id, price);
116 123 } else if (price < 0) {
117   - brokerageUserMapper.updatePriceDecr(id, price);
  124 + return brokerageUserMapper.updatePriceDecr(id, price) > 0;
118 125 }
  126 + return true;
119 127 }
120 128  
121 129 @Override
... ... @@ -138,11 +146,11 @@ public class BrokerageUserServiceImpl implements BrokerageUserService {
138 146  
139 147 @Override
140 148 public Long getBrokerageUserCountByBindUserId(Long bindUserId, Integer level) {
141   - List<Integer> levels = buildUserQueryLevels(bindUserId, level);
142   - if (CollUtil.isEmpty(levels)) {
  149 + List<Long> bindUserIds = buildBindUserIdsByLevel(bindUserId, level);
  150 + if (CollUtil.isEmpty(bindUserIds)) {
143 151 return 0L;
144 152 }
145   - return brokerageUserMapper.selectCountByBindUserIdAndLevelIn(bindUserId, levels);
  153 + return brokerageUserMapper.selectCountByBindUserIdIn(bindUserIds);
146 154 }
147 155  
148 156 @Override
... ... @@ -176,21 +184,15 @@ public class BrokerageUserServiceImpl implements BrokerageUserService {
176 184 return true;
177 185 }
178 186  
  187 + /**
  188 + * 补全绑定用户的字段
  189 + *
  190 + * @param bindUserId 绑定的用户编号
  191 + * @param brokerageUser update 对象
  192 + * @return 补全后的 update 对象
  193 + */
179 194 private BrokerageUserDO fillBindUserData(Long bindUserId, BrokerageUserDO brokerageUser) {
180   - BrokerageUserDO bindUser = getBrokerageUser(bindUserId);
181   -
182   - Integer bindUserLevel = 0;
183   - String bindUserPath = "";
184   - if (bindUser != null) {
185   - bindUserLevel = ObjectUtil.defaultIfNull(bindUser.getLevel(), 0);
186   - bindUserPath = bindUser.getPath();
187   - }
188   -
189   - String path = StrUtil.isEmpty(bindUserPath)
190   - ? String.valueOf(bindUserId)
191   - : String.format("%s,%s", bindUserPath, bindUserId);
192   - return brokerageUser.setBindUserId(bindUserId).setBindUserTime(LocalDateTime.now())
193   - .setLevel(bindUserLevel + 1).setPath(path);
  195 + return brokerageUser.setBindUserId(bindUserId).setBindUserTime(LocalDateTime.now());
194 196 }
195 197  
196 198 @Override
... ... @@ -207,6 +209,19 @@ public class BrokerageUserServiceImpl implements BrokerageUserService {
207 209 .orElse(false);
208 210 }
209 211  
  212 + @Override
  213 + public PageResult<AppBrokerageUserRankByUserCountRespVO> getBrokerageUserRankPageByUserCount(AppBrokerageUserRankPageReqVO pageReqVO) {
  214 + IPage<AppBrokerageUserRankByUserCountRespVO> pageResult = brokerageUserMapper.selectCountPageGroupByBindUserId(MyBatisUtils.buildPage(pageReqVO),
  215 + ArrayUtil.get(pageReqVO.getTimes(), 0), ArrayUtil.get(pageReqVO.getTimes(), 1));
  216 + return new PageResult<>(pageResult.getRecords(), pageResult.getTotal());
  217 + }
  218 +
  219 + @Override
  220 + public PageResult<AppBrokerageUserChildSummaryRespVO> getBrokerageUserChildSummaryPage(AppBrokerageUserChildSummaryPageReqVO pageReqVO, Long userId) {
  221 + IPage<AppBrokerageUserChildSummaryRespVO> pageResult = brokerageUserMapper.selectSummaryPageByUserId(MyBatisUtils.buildPage(pageReqVO), pageReqVO, userId);
  222 + return new PageResult<>(pageResult.getRecords(), pageResult.getTotal());
  223 + }
  224 +
210 225 private boolean isUserCanBind(BrokerageUserDO user, Boolean isNewUser) {
211 226 // 校验分销功能是否启用
212 227 TradeConfigDO tradeConfig = tradeConfigService.getTradeConfig();
... ... @@ -221,6 +236,7 @@ public class BrokerageUserServiceImpl implements BrokerageUserService {
221 236  
222 237 // 校验分销关系绑定模式
223 238 if (BrokerageBindModeEnum.REGISTER.getMode().equals(tradeConfig.getBrokerageBindMode())) {
  239 + // TODO @疯狂:是不是把 isNewUser 挪到这里好点呀?
224 240 if (!BooleanUtil.isTrue(isNewUser)) {
225 241 throw exception(BROKERAGE_BIND_MODE_REGISTER); // 只有在注册时可以绑定
226 242 }
... ... @@ -246,29 +262,36 @@ public class BrokerageUserServiceImpl implements BrokerageUserService {
246 262 }
247 263  
248 264 // 下级不能绑定自己的上级
249   - if (StrUtil.split(bindUser.getPath(), ",").contains(String.valueOf(user.getId()))) {
250   - throw exception(BROKERAGE_BIND_LOOP);
  265 + for (int i = 0; i <= Short.MAX_VALUE; i++) {
  266 + if (Objects.equals(bindUser.getBindUserId(), user.getId())) {
  267 + throw exception(BROKERAGE_BIND_LOOP);
  268 + }
  269 + bindUser = getBrokerageUser(bindUser.getBindUserId());
  270 + // 找到根节点,结束循环
  271 + if (bindUser == null || bindUser.getBindUserId() == null) {
  272 + break;
  273 + }
251 274 }
252 275 }
253 276  
254   - // TODO @芋艿:这个层级,要微信讨论下;
255   - private List<Integer> buildUserQueryLevels(Long bindUserId, Integer level) {
256   - List<Integer> levels = new ArrayList<>(2);
257   -
258   - BrokerageUserDO bindUser = getBrokerageUser(bindUserId);
259   - if (bindUser == null) {
260   - return levels;
  277 + /**
  278 + * 根据绑定用户编号,获得绑定用户编号列表
  279 + *
  280 + * @param bindUserId 绑定用户编号
  281 + * @param level 绑定用户的层级。
  282 + * 如果 level 为空,则查询 1+2 两个层级
  283 + * @return 绑定用户编号列表
  284 + */
  285 + private List<Long> buildBindUserIdsByLevel(Long bindUserId, Integer level) {
  286 + Assert.isTrue(level == null || level <= 2, "目前只支持 level 小于等于 2");
  287 + List<Long> bindUserIds = CollUtil.newArrayList();
  288 + if (level == null || level == 1) {
  289 + bindUserIds.add(bindUserId);
261 290 }
262   -
263   - if (level == null) {
264   - // 默认查两层
265   - levels.add(bindUser.getLevel() + 1);
266   - levels.add(bindUser.getLevel() + 2);
267   - } else {
268   - levels.add(bindUser.getLevel() + level);
  291 + if (level == null || level == 2) {
  292 + bindUserIds.addAll(convertList(brokerageUserMapper.selectListByBindUserId(bindUserId), BrokerageUserDO::getId));
269 293 }
270   - return levels;
271   -
  294 + return bindUserIds;
272 295 }
273 296  
274 297 }
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/service/brokerage/withdraw/BrokerageWithdrawService.java renamed to yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/service/brokerage/BrokerageWithdrawService.java
1   -package cn.iocoder.yudao.module.trade.service.brokerage.withdraw;
  1 +package cn.iocoder.yudao.module.trade.service.brokerage;
2 2  
3 3 import cn.iocoder.yudao.framework.common.pojo.PageResult;
4   -import cn.iocoder.yudao.module.trade.controller.admin.brokerage.withdraw.vo.BrokerageWithdrawPageReqVO;
5   -import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.withdraw.BrokerageWithdrawDO;
  4 +import cn.iocoder.yudao.module.trade.controller.admin.brokerage.vo.withdraw.BrokerageWithdrawPageReqVO;
  5 +import cn.iocoder.yudao.module.trade.controller.app.brokerage.vo.withdraw.AppBrokerageWithdrawCreateReqVO;
  6 +import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.BrokerageWithdrawDO;
6 7 import cn.iocoder.yudao.module.trade.enums.brokerage.BrokerageWithdrawStatusEnum;
  8 +import cn.iocoder.yudao.module.trade.service.brokerage.bo.UserWithdrawSummaryBO;
7 9  
8 10 /**
9 11 * 佣金提现 Service 接口
... ... @@ -13,13 +15,12 @@ import cn.iocoder.yudao.module.trade.enums.brokerage.BrokerageWithdrawStatusEnum
13 15 public interface BrokerageWithdrawService {
14 16  
15 17 /**
16   - * 审核佣金提现
  18 + * 【管理员】审核佣金提现
17 19 *
18 20 * @param id 佣金编号
19 21 * @param status 审核状态
20 22 * @param auditReason 驳回原因
21 23 */
22   -
23 24 void auditBrokerageWithdraw(Integer id, BrokerageWithdrawStatusEnum status, String auditReason);
24 25  
25 26 /**
... ... @@ -37,4 +38,23 @@ public interface BrokerageWithdrawService {
37 38 * @return 佣金提现分页
38 39 */
39 40 PageResult<BrokerageWithdrawDO> getBrokerageWithdrawPage(BrokerageWithdrawPageReqVO pageReqVO);
  41 +
  42 + /**
  43 + * 【会员】创建佣金提现
  44 + *
  45 + * @param createReqVO 创建信息
  46 + * @param userId 会员用户编号
  47 + * @return 佣金提现编号
  48 + */
  49 + Long createBrokerageWithdraw(AppBrokerageWithdrawCreateReqVO createReqVO, Long userId);
  50 +
  51 + /**
  52 + * 汇总用户提现
  53 + *
  54 + * @param userId 用户编号
  55 + * @param status 提现状态
  56 + * @return 用户提现汇总
  57 + */
  58 + UserWithdrawSummaryBO getWithdrawSummaryByUserId(Long userId, BrokerageWithdrawStatusEnum status);
  59 +
40 60 }
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/service/brokerage/withdraw/BrokerageWithdrawServiceImpl.java renamed to yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/service/brokerage/BrokerageWithdrawServiceImpl.java
1   -package cn.iocoder.yudao.module.trade.service.brokerage.withdraw;
  1 +package cn.iocoder.yudao.module.trade.service.brokerage;
2 2  
3 3 import cn.hutool.core.date.LocalDateTimeUtil;
4 4 import cn.hutool.core.map.MapUtil;
5 5 import cn.hutool.core.util.ObjectUtil;
6 6 import cn.iocoder.yudao.framework.common.pojo.PageResult;
  7 +import cn.iocoder.yudao.framework.common.util.number.MoneyUtils;
7 8 import cn.iocoder.yudao.module.system.api.notify.NotifyMessageSendApi;
8 9 import cn.iocoder.yudao.module.system.api.notify.dto.NotifySendSingleToUserReqDTO;
9   -import cn.iocoder.yudao.module.trade.controller.admin.brokerage.withdraw.vo.BrokerageWithdrawPageReqVO;
10   -import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.withdraw.BrokerageWithdrawDO;
11   -import cn.iocoder.yudao.module.trade.dal.mysql.brokerage.withdraw.BrokerageWithdrawMapper;
  10 +import cn.iocoder.yudao.module.trade.controller.admin.brokerage.vo.withdraw.BrokerageWithdrawPageReqVO;
  11 +import cn.iocoder.yudao.module.trade.controller.app.brokerage.vo.withdraw.AppBrokerageWithdrawCreateReqVO;
  12 +import cn.iocoder.yudao.module.trade.convert.brokerage.BrokerageWithdrawConvert;
  13 +import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.BrokerageWithdrawDO;
  14 +import cn.iocoder.yudao.module.trade.dal.dataobject.config.TradeConfigDO;
  15 +import cn.iocoder.yudao.module.trade.dal.mysql.brokerage.BrokerageWithdrawMapper;
12 16 import cn.iocoder.yudao.module.trade.enums.MessageTemplateConstants;
  17 +import cn.iocoder.yudao.module.trade.enums.brokerage.BrokerageRecordBizTypeEnum;
13 18 import cn.iocoder.yudao.module.trade.enums.brokerage.BrokerageWithdrawStatusEnum;
14   -import cn.iocoder.yudao.module.trade.service.brokerage.record.BrokerageRecordService;
  19 +import cn.iocoder.yudao.module.trade.enums.brokerage.BrokerageWithdrawTypeEnum;
  20 +import cn.iocoder.yudao.module.trade.service.brokerage.bo.UserWithdrawSummaryBO;
  21 +import cn.iocoder.yudao.module.trade.service.config.TradeConfigService;
15 22 import org.springframework.stereotype.Service;
16 23 import org.springframework.transaction.annotation.Transactional;
17 24 import org.springframework.validation.annotation.Validated;
18 25  
19 26 import javax.annotation.Resource;
  27 +import javax.validation.Validator;
20 28 import java.time.LocalDateTime;
21 29 import java.util.Map;
22 30  
23 31 import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
24   -import static cn.iocoder.yudao.module.trade.enums.ErrorCodeConstants.BROKERAGE_WITHDRAW_NOT_EXISTS;
25   -import static cn.iocoder.yudao.module.trade.enums.ErrorCodeConstants.BROKERAGE_WITHDRAW_STATUS_NOT_AUDITING;
  32 +import static cn.iocoder.yudao.module.trade.enums.ErrorCodeConstants.*;
26 33  
27 34 /**
28 35 * 佣金提现 Service 实现类
... ... @@ -38,10 +45,15 @@ public class BrokerageWithdrawServiceImpl implements BrokerageWithdrawService {
38 45  
39 46 @Resource
40 47 private BrokerageRecordService brokerageRecordService;
  48 + @Resource
  49 + private TradeConfigService tradeConfigService;
41 50  
42 51 @Resource
43 52 private NotifyMessageSendApi notifyMessageSendApi;
44 53  
  54 + @Resource
  55 + private Validator validator;
  56 +
45 57 @Override
46 58 @Transactional(rollbackFor = Exception.class)
47 59 public void auditBrokerageWithdraw(Integer id, BrokerageWithdrawStatusEnum status, String auditReason) {
... ... @@ -62,19 +74,26 @@ public class BrokerageWithdrawServiceImpl implements BrokerageWithdrawService {
62 74 throw exception(BROKERAGE_WITHDRAW_STATUS_NOT_AUDITING);
63 75 }
64 76  
65   - // 3. 驳回时需要退还用户佣金
66 77 String templateCode = MessageTemplateConstants.BROKERAGE_WITHDRAW_AUDIT_APPROVE;
67   - if (BrokerageWithdrawStatusEnum.AUDIT_FAIL.equals(status)) {
  78 + if (BrokerageWithdrawStatusEnum.AUDIT_SUCCESS.equals(status)) {
  79 + // 3.1 通过时佣金转余额
  80 + if (BrokerageWithdrawTypeEnum.WALLET.getType().equals(withdraw.getType())) {
  81 + // todo
  82 + }
  83 + } else if (BrokerageWithdrawStatusEnum.AUDIT_FAIL.equals(status)) {
68 84 templateCode = MessageTemplateConstants.BROKERAGE_WITHDRAW_AUDIT_REJECT;
69 85  
70   - // todo @owen
71   -// brokerageRecordService.addBrokerage(withdraw.getUserId(), BrokerageRecordBizTypeEnum.WITHDRAW, withdraw.getPrice(), "");
  86 + // 3.2 驳回时需要退还用户佣金
  87 + brokerageRecordService.addBrokerage(withdraw.getUserId(), BrokerageRecordBizTypeEnum.WITHDRAW_REJECT,
  88 + String.valueOf(withdraw.getId()), withdraw.getPrice(), BrokerageRecordBizTypeEnum.WITHDRAW_REJECT.getTitle());
  89 + } else {
  90 + throw new IllegalArgumentException("不支持的提现状态");
72 91 }
73 92  
74 93 // 4. 通知用户
75 94 Map<String, Object> templateParams = MapUtil.<String, Object>builder()
76 95 .put("createTime", LocalDateTimeUtil.formatNormal(withdraw.getCreateTime()))
77   - .put("price", String.format("%.2f", withdraw.getPrice() / 100d))
  96 + .put("price", MoneyUtils.fenToYuanStr(withdraw.getPrice()))
78 97 .put("reason", withdraw.getAuditReason())
79 98 .build();
80 99 NotifySendSingleToUserReqDTO reqDTO = new NotifySendSingleToUserReqDTO()
... ... @@ -101,4 +120,59 @@ public class BrokerageWithdrawServiceImpl implements BrokerageWithdrawService {
101 120 return brokerageWithdrawMapper.selectPage(pageReqVO);
102 121 }
103 122  
  123 + @Override
  124 + @Transactional(rollbackFor = Exception.class)
  125 + public Long createBrokerageWithdraw(AppBrokerageWithdrawCreateReqVO createReqVO, Long userId) {
  126 + // 校验提现金额
  127 + TradeConfigDO tradeConfig = validateWithdrawPrice(createReqVO.getPrice());
  128 + // 校验提现参数
  129 + createReqVO.validate(validator);
  130 +
  131 + // 计算手续费
  132 + Integer feePrice = calculateFeePrice(createReqVO.getPrice(), tradeConfig.getBrokerageWithdrawFeePercent());
  133 + // 创建佣金提现记录
  134 + BrokerageWithdrawDO withdraw = BrokerageWithdrawConvert.INSTANCE.convert(createReqVO, userId, feePrice);
  135 + brokerageWithdrawMapper.insert(withdraw);
  136 +
  137 + // 创建用户佣金记录
  138 + brokerageRecordService.addBrokerage(userId, BrokerageRecordBizTypeEnum.WITHDRAW, String.valueOf(withdraw.getId()),
  139 + -createReqVO.getPrice(), BrokerageRecordBizTypeEnum.WITHDRAW.getTitle());
  140 +
  141 + return withdraw.getId();
  142 + }
  143 +
  144 + @Override
  145 + public UserWithdrawSummaryBO getWithdrawSummaryByUserId(Long userId, BrokerageWithdrawStatusEnum status) {
  146 + UserWithdrawSummaryBO summaryBO = brokerageWithdrawMapper.selectCountAndSumPriceByUserIdAndStatus(userId, status.getStatus());
  147 + return summaryBO != null ? summaryBO : new UserWithdrawSummaryBO(0, 0);
  148 + }
  149 +
  150 + /**
  151 + * 计算提现手续费
  152 + *
  153 + * @param withdrawPrice 提现金额
  154 + * @param percent 手续费百分比
  155 + * @return 提现手续费
  156 + */
  157 + Integer calculateFeePrice(Integer withdrawPrice, Integer percent) {
  158 + Integer feePrice = 0;
  159 + if (percent != null && percent > 0) {
  160 + feePrice = MoneyUtils.calculateRatePrice(withdrawPrice, Double.valueOf(percent));
  161 + }
  162 + return feePrice;
  163 + }
  164 +
  165 + /**
  166 + * 校验提现金额要求
  167 + *
  168 + * @param withdrawPrice 提现金额
  169 + * @return 分销配置
  170 + */
  171 + TradeConfigDO validateWithdrawPrice(Integer withdrawPrice) {
  172 + TradeConfigDO tradeConfig = tradeConfigService.getTradeConfig();
  173 + if (tradeConfig.getBrokerageWithdrawMinPrice() != null && withdrawPrice < tradeConfig.getBrokerageWithdrawMinPrice()) {
  174 + throw exception(BROKERAGE_WITHDRAW_MIN_PRICE, MoneyUtils.fenToYuanStr(tradeConfig.getBrokerageWithdrawMinPrice()));
  175 + }
  176 + return tradeConfig;
  177 + }
104 178 }
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/service/brokerage/bo/UserWithdrawSummaryBO.java 0 → 100644
  1 +package cn.iocoder.yudao.module.trade.service.brokerage.bo;
  2 +
  3 +import lombok.AllArgsConstructor;
  4 +import lombok.Data;
  5 +import lombok.NoArgsConstructor;
  6 +
  7 +/**
  8 + * 用户佣金提现合计 BO
  9 + *
  10 + * @author owen
  11 + */
  12 +@Data
  13 +@NoArgsConstructor
  14 +@AllArgsConstructor
  15 +public class UserWithdrawSummaryBO {
  16 +
  17 + /**
  18 + * 提现次数
  19 + */
  20 + private Integer count;
  21 + /**
  22 + * 提现金额
  23 + */
  24 + private Integer price;
  25 +
  26 +}
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/service/order/TradeOrderQueryServiceImpl.java
... ... @@ -106,7 +106,7 @@ public class TradeOrderQueryServiceImpl implements TradeOrderQueryService {
106 106 if (order == null) {
107 107 throw exception(ORDER_NOT_FOUND);
108 108 }
109   -
  109 + // 查询物流
110 110 return getExpressTrackList(order);
111 111 }
112 112  
... ... @@ -117,7 +117,7 @@ public class TradeOrderQueryServiceImpl implements TradeOrderQueryService {
117 117 if (order == null) {
118 118 throw exception(ORDER_NOT_FOUND);
119 119 }
120   -
  120 + // 查询物流
121 121 return getExpressTrackList(order);
122 122 }
123 123  
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/service/order/TradeOrderUpdateService.java
... ... @@ -63,6 +63,22 @@ public interface TradeOrderUpdateService {
63 63 void receiveOrder(Long userId, Long id);
64 64  
65 65 /**
  66 + * 【会员】取消订单
  67 + *
  68 + * @param userId 用户编号
  69 + * @param id 订单编号
  70 + */
  71 + void cancelOrder(Long userId, Long id);
  72 +
  73 + /**
  74 + * 【会员】删除订单
  75 + *
  76 + * @param userId 用户编号
  77 + * @param id 订单编号
  78 + */
  79 + void deleteOrder(Long userId, Long id);
  80 +
  81 + /**
66 82 * 【管理员】交易订单备注
67 83 *
68 84 * @param reqVO 请求
... ... @@ -117,11 +133,4 @@ public interface TradeOrderUpdateService {
117 133 */
118 134 Long createOrderItemComment(Long userId, AppTradeOrderItemCommentCreateReqVO createReqVO);
119 135  
120   - /**
121   - * 【会员】取消订单
122   - *
123   - * @param userId 用户ID
124   - * @param id 订单编号
125   - */
126   - void cancelOrder(Long userId, Long id);
127 136 }
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/service/order/TradeOrderUpdateServiceImpl.java
... ... @@ -3,6 +3,7 @@ package cn.iocoder.yudao.module.trade.service.order;
3 3 import cn.hutool.core.collection.CollUtil;
4 4 import cn.hutool.core.lang.Assert;
5 5 import cn.hutool.core.util.ObjectUtil;
  6 +import cn.hutool.core.util.RandomUtil;
6 7 import cn.hutool.core.util.StrUtil;
7 8 import cn.hutool.extra.spring.SpringUtil;
8 9 import cn.iocoder.yudao.framework.common.core.KeyValue;
... ... @@ -23,6 +24,7 @@ import cn.iocoder.yudao.module.pay.enums.order.PayOrderStatusEnum;
23 24 import cn.iocoder.yudao.module.product.api.comment.ProductCommentApi;
24 25 import cn.iocoder.yudao.module.product.api.comment.dto.ProductCommentCreateReqDTO;
25 26 import cn.iocoder.yudao.module.product.api.sku.ProductSkuApi;
  27 +import cn.iocoder.yudao.module.product.api.spu.ProductSpuApi;
26 28 import cn.iocoder.yudao.module.promotion.api.bargain.BargainRecordApi;
27 29 import cn.iocoder.yudao.module.promotion.api.combination.CombinationRecordApi;
28 30 import cn.iocoder.yudao.module.promotion.api.coupon.CouponApi;
... ... @@ -42,13 +44,14 @@ import cn.iocoder.yudao.module.trade.dal.dataobject.order.TradeOrderItemDO;
42 44 import cn.iocoder.yudao.module.trade.dal.mysql.order.TradeOrderItemMapper;
43 45 import cn.iocoder.yudao.module.trade.dal.mysql.order.TradeOrderMapper;
44 46 import cn.iocoder.yudao.module.trade.dal.redis.no.TradeOrderNoRedisDAO;
45   -import cn.iocoder.yudao.module.trade.enums.ErrorCodeConstants;
46 47 import cn.iocoder.yudao.module.trade.enums.brokerage.BrokerageRecordBizTypeEnum;
47 48 import cn.iocoder.yudao.module.trade.enums.delivery.DeliveryTypeEnum;
48 49 import cn.iocoder.yudao.module.trade.enums.order.*;
49 50 import cn.iocoder.yudao.module.trade.framework.order.config.TradeOrderProperties;
  51 +import cn.iocoder.yudao.module.trade.framework.order.core.annotations.TradeOrderLog;
  52 +import cn.iocoder.yudao.module.trade.framework.order.core.utils.TradeOrderLogUtils;
  53 +import cn.iocoder.yudao.module.trade.service.brokerage.BrokerageRecordService;
50 54 import cn.iocoder.yudao.module.trade.service.brokerage.bo.BrokerageAddReqBO;
51   -import cn.iocoder.yudao.module.trade.service.brokerage.record.BrokerageRecordService;
52 55 import cn.iocoder.yudao.module.trade.service.cart.CartService;
53 56 import cn.iocoder.yudao.module.trade.service.delivery.DeliveryExpressService;
54 57 import cn.iocoder.yudao.module.trade.service.message.TradeMessageService;
... ... @@ -105,6 +108,8 @@ public class TradeOrderUpdateServiceImpl implements TradeOrderUpdateService {
105 108 private TradeMessageService tradeMessageService;
106 109  
107 110 @Resource
  111 + private ProductSpuApi productSpuApi;
  112 + @Resource
108 113 private ProductSkuApi productSkuApi;
109 114 @Resource
110 115 private PayOrderApi payOrderApi;
... ... @@ -182,141 +187,127 @@ public class TradeOrderUpdateServiceImpl implements TradeOrderUpdateService {
182 187  
183 188 @Override
184 189 @Transactional(rollbackFor = Exception.class)
  190 + @TradeOrderLog(operateType = TradeOrderOperateTypeEnum.MEMBER_CREATE)
185 191 public TradeOrderDO createOrder(Long userId, String userIp, AppTradeOrderCreateReqVO createReqVO) {
186   - // 1、执行订单创建前置处理器
187   - // TODO @puhui999:最好也抽个 beforeOrderCreate 方法;不要 BO 各自处理参数岂不美哉?
188   - TradeBeforeOrderCreateReqBO beforeOrderCreateReqBO = TradeOrderConvert.INSTANCE.convert(createReqVO);
189   - beforeOrderCreateReqBO.setOrderType(validateActivity(createReqVO));
190   - beforeOrderCreateReqBO.setUserId(userId);
191   - beforeOrderCreateReqBO.setCount(getSumValue(createReqVO.getItems(), AppTradeOrderSettlementReqVO.Item::getCount, Integer::sum));
192   - // TODO @puhui999:这里有个纠结点;handler 的定义是只处理指定类型的订单的拓展逻辑;还是通用的 handler,类似可以处理优惠劵等等
193   - tradeOrderHandlers.forEach(handler -> handler.beforeOrderCreate(beforeOrderCreateReqBO));
194   -
195   - // 2. 价格计算
  192 + // 0. 价格计算
196 193 TradePriceCalculateRespBO calculateRespBO = calculatePrice(userId, createReqVO);
197 194  
  195 + // 1. 订单创建前的逻辑
  196 + beforeCreateTradeOrder(userId, createReqVO, calculateRespBO);
  197 +
198 198 // 2.1 插入 TradeOrderDO 订单
199 199 TradeOrderDO order = createTradeOrder(userId, userIp, createReqVO, calculateRespBO);
200 200 // 2.2 插入 TradeOrderItemDO 订单项
201 201 List<TradeOrderItemDO> orderItems = createTradeOrderItems(order, calculateRespBO);
202 202  
203   - // 3. 订单创建完后的逻辑
  203 + // 3. 订单创建后的逻辑
204 204 afterCreateTradeOrder(userId, createReqVO, order, orderItems, calculateRespBO);
205   -
206   - // TODO @LeeYan9: 是可以思考下, 订单的营销优惠记录, 应该记录在哪里, 微信讨论起来!
207 205 return order;
208 206 }
209 207  
210   -
211 208 // TODO @puhui999:订单超时,自动取消;
212 209  
213   - /**
214   - * 校验收件地址是否存在
215   - *
216   - * @param userId 用户编号
217   - * @param addressId 收件地址编号
218   - * @return 收件地址
219   - */
220   - private AddressRespDTO validateAddress(Long userId, Long addressId) {
221   - AddressRespDTO address = addressApi.getAddress(addressId, userId);
222   - if (address == null) {
223   - throw exception(ErrorCodeConstants.ORDER_CREATE_ADDRESS_NOT_FOUND);
224   - }
225   - return address;
226   - }
227   -
228 210 private TradeOrderDO createTradeOrder(Long userId, String clientIp, AppTradeOrderCreateReqVO createReqVO,
229 211 TradePriceCalculateRespBO calculateRespBO) {
230   - // 用户选择物流配送的时候才需要填写收货地址
231   - AddressRespDTO address = new AddressRespDTO();
232   - if (Objects.equals(createReqVO.getDeliveryType(), DeliveryTypeEnum.EXPRESS.getMode())) {
233   - // 用户收件地址的校验
234   - address = validateAddress(userId, createReqVO.getAddressId());
235   - }
236   - TradeOrderDO order = TradeOrderConvert.INSTANCE.convert(userId, clientIp, createReqVO, calculateRespBO, address);
237   - String no = orderNoRedisDAO.generate(TradeOrderNoRedisDAO.TRADE_ORDER_NO_PREFIX);
238   - order.setType(validateActivity(createReqVO));
239   - order.setNo(no);
  212 + TradeOrderDO order = TradeOrderConvert.INSTANCE.convert(userId, clientIp, createReqVO, calculateRespBO);
  213 + order.setType(calculateRespBO.getType());
  214 + order.setNo(orderNoRedisDAO.generate(TradeOrderNoRedisDAO.TRADE_ORDER_NO_PREFIX));
240 215 order.setStatus(TradeOrderStatusEnum.UNPAID.getStatus());
241 216 order.setRefundStatus(TradeOrderRefundStatusEnum.NONE.getStatus());
242 217 order.setProductCount(getSumValue(calculateRespBO.getItems(), TradePriceCalculateRespBO.OrderItem::getCount, Integer::sum));
243 218 order.setTerminal(TerminalEnum.H5.getTerminal()); // todo 数据来源?
244   - // 支付信息
  219 + // 支付 + 退款信息
245 220 order.setAdjustPrice(0).setPayStatus(false);
  221 + order.setRefundStatus(TradeOrderRefundStatusEnum.NONE.getStatus()).setRefundPrice(0);
246 222 // 物流信息
247 223 order.setDeliveryType(createReqVO.getDeliveryType());
248   - // 退款信息
249   - order.setRefundStatus(TradeOrderRefundStatusEnum.NONE.getStatus()).setRefundPrice(0);
  224 + if (Objects.equals(createReqVO.getDeliveryType(), DeliveryTypeEnum.EXPRESS.getType())) {
  225 + AddressRespDTO address = addressApi.getAddress(createReqVO.getAddressId(), userId);
  226 + Assert.notNull(address, "地址({}) 不能为空", createReqVO.getAddressId()); // 价格计算时,已经计算
  227 + order.setReceiverName(address.getName()).setReceiverMobile(address.getMobile())
  228 + .setReceiverAreaId(address.getAreaId()).setReceiverDetailAddress(address.getDetailAddress());
  229 + } else if (Objects.equals(createReqVO.getDeliveryType(), DeliveryTypeEnum.PICK_UP.getType())) {
  230 + order.setReceiverName(createReqVO.getReceiverName()).setReceiverMobile(createReqVO.getReceiverMobile());
  231 + order.setPickUpVerifyCode(RandomUtil.randomNumbers(8)); // 随机一个核销码,长度为 8 位
  232 + }
250 233 tradeOrderMapper.insert(order);
251   - // TODO @puhui999:如果是门店订单,则需要生成核销码;
252 234 return order;
253 235 }
254 236  
255   - /**
256   - * 校验活动,并返回订单类型
257   - *
258   - * @param createReqVO 请求参数
259   - * @return 订单类型
260   - */
261   - private Integer validateActivity(AppTradeOrderCreateReqVO createReqVO) {
262   - if (createReqVO.getSeckillActivityId() != null) {
263   - return TradeOrderTypeEnum.SECKILL.getType();
264   - }
265   - if (createReqVO.getCombinationActivityId() != null) {
266   - return TradeOrderTypeEnum.COMBINATION.getType();
267   - }
268   - // TODO 砍价敬请期待
269   - return TradeOrderTypeEnum.NORMAL.getType();
270   - }
271   -
272   - private List<TradeOrderItemDO> createTradeOrderItems(TradeOrderDO tradeOrderDO, TradePriceCalculateRespBO calculateRespBO) {
  237 + private List<TradeOrderItemDO> createTradeOrderItems(TradeOrderDO tradeOrderDO,
  238 + TradePriceCalculateRespBO calculateRespBO) {
273 239 List<TradeOrderItemDO> orderItems = TradeOrderConvert.INSTANCE.convertList(tradeOrderDO, calculateRespBO);
274 240 tradeOrderItemMapper.insertBatch(orderItems);
275 241 return orderItems;
276 242 }
277 243  
278 244 /**
279   - * 执行创建完创建完订单后的逻辑
  245 + * 订单创建前,执行前置逻辑
280 246 *
  247 + * @param userId 用户编号
  248 + * @param createReqVO 创建订单请求
  249 + * @param calculateRespBO 订单价格计算结果
  250 + */
  251 + private void beforeCreateTradeOrder(Long userId, AppTradeOrderCreateReqVO createReqVO,
  252 + TradePriceCalculateRespBO calculateRespBO) {
  253 + // 1. 执行订单创建前置处理器
  254 + TradeBeforeOrderCreateReqBO beforeOrderCreateReqBO = TradeOrderConvert.INSTANCE.convert(createReqVO);
  255 + beforeOrderCreateReqBO.setOrderType(calculateRespBO.getType());
  256 + beforeOrderCreateReqBO.setUserId(userId);
  257 + beforeOrderCreateReqBO.setCount(getSumValue(createReqVO.getItems(), AppTradeOrderSettlementReqVO.Item::getCount, Integer::sum));
  258 + // TODO @puhui999:这里有个纠结点;handler 的定义是只处理指定类型的订单的拓展逻辑;还是通用的 handler,类似可以处理优惠劵等等
  259 + tradeOrderHandlers.forEach(handler -> handler.beforeOrderCreate(beforeOrderCreateReqBO));
  260 +
  261 + // 2. 下单时扣减商品库存
  262 + productSkuApi.updateSkuStock(TradeOrderConvert.INSTANCE.convertNegative(createReqVO.getItems()));
  263 + }
  264 +
  265 + /**
  266 + * 订单创建后,执行后置逻辑
  267 + * <p>
281 268 * 例如说:优惠劵的扣减、积分的扣减、支付单的创建等等
282 269 *
283 270 * @param userId 用户编号
284 271 * @param createReqVO 创建订单请求
285   - * @param tradeOrderDO 交易订单
  272 + * @param order 交易订单
286 273 * @param calculateRespBO 订单价格计算结果
287 274 */
288 275 private void afterCreateTradeOrder(Long userId, AppTradeOrderCreateReqVO createReqVO,
289   - TradeOrderDO tradeOrderDO, List<TradeOrderItemDO> orderItems,
  276 + TradeOrderDO order, List<TradeOrderItemDO> orderItems,
290 277 TradePriceCalculateRespBO calculateRespBO) {
291   - // 执行订单创建后置处理器
292   - tradeOrderHandlers.forEach(handler -> handler.afterOrderCreate(TradeOrderConvert.INSTANCE.convert(userId, createReqVO, tradeOrderDO, orderItems.get(0))));
  278 + // 1. 执行订单创建后置处理器
  279 + // TODO @puhui999:从通用性来说,应该不用 orderItems.get(0)
  280 + tradeOrderHandlers.forEach(handler -> handler.afterOrderCreate(
  281 + TradeOrderConvert.INSTANCE.convert(userId, createReqVO, order, orderItems.get(0))));
293 282  
294   - // 扣减积分 TODO 芋艿:待实现,需要前置;
295   - // 这个是不是应该放到支付成功之后?如果支付后的话,可能积分可以重复使用哈。资源类,都要预扣
296   -
297   - // 有使用优惠券时更新 TODO 芋艿:需要前置;
  283 + // 2. 有使用优惠券时更新
  284 + // 不在前置扣减的原因,是因为优惠劵要记录使用的订单号
298 285 if (createReqVO.getCouponId() != null) {
299 286 couponApi.useCoupon(new CouponUseReqDTO().setId(createReqVO.getCouponId()).setUserId(userId)
300   - .setOrderId(tradeOrderDO.getId()));
  287 + .setOrderId(order.getId()));
301 288 }
302 289  
303   - // 下单时扣减商品库存
304   - productSkuApi.updateSkuStock(TradeOrderConvert.INSTANCE.convertNegative(orderItems));
  290 + // 3. 扣减积分(抵扣)
  291 + // 不在前置扣减的原因,是因为积分扣减时,需要记录关联业务
  292 + reduceUserPoint(order.getUserId(), order.getUsePoint(), MemberPointBizTypeEnum.ORDER_USE, order.getId());
305 293  
306   - // 删除购物车商品
  294 + // 4. 删除购物车商品
307 295 Set<Long> cartIds = convertSet(createReqVO.getItems(), AppTradeOrderSettlementReqVO.Item::getCartId);
308 296 if (CollUtil.isNotEmpty(cartIds)) {
309 297 cartService.deleteCart(userId, cartIds);
310 298 }
311 299  
312   - // 生成预支付
313   - createPayOrder(tradeOrderDO, orderItems, calculateRespBO);
  300 + // 5. 生成预支付
  301 + createPayOrder(order, orderItems, calculateRespBO);
314 302  
315   - // 增加订单日志 TODO 芋艿:待实现
316   - }
  303 + // 6. 插入订单日志
  304 + TradeOrderLogUtils.setOrderInfo(order.getId(), null, order.getStatus());
317 305  
  306 + // TODO @LeeYan9: 是可以思考下, 订单的营销优惠记录, 应该记录在哪里, 微信讨论起来!
  307 + }
318 308  
319   - private void createPayOrder(TradeOrderDO order, List<TradeOrderItemDO> orderItems, TradePriceCalculateRespBO calculateRespBO) {
  309 + private void createPayOrder(TradeOrderDO order, List<TradeOrderItemDO> orderItems,
  310 + TradePriceCalculateRespBO calculateRespBO) {
320 311 // 创建支付单,用于后续的支付
321 312 PayOrderCreateReqDTO payOrderCreateReqDTO = TradeOrderConvert.INSTANCE.convert(
322 313 order, orderItems, calculateRespBO, tradeOrderProperties);
... ... @@ -344,6 +335,7 @@ public class TradeOrderUpdateServiceImpl implements TradeOrderUpdateService {
344 335 }
345 336 // 校验活动
346 337 // 1、拼团活动
  338 + // TODO @puhui999:这块也抽象到 handler 里
347 339 if (Objects.equals(TradeOrderTypeEnum.COMBINATION.getType(), order.getType())) {
348 340 // 更新拼团状态 TODO puhui999:订单支付失败或订单支付过期删除这条拼团记录
349 341 combinationRecordApi.updateRecordStatusToInProgress(order.getUserId(), order.getId(), LocalDateTime.now());
... ... @@ -354,8 +346,8 @@ public class TradeOrderUpdateServiceImpl implements TradeOrderUpdateService {
354 346  
355 347 // TODO 芋艿:OrderLog
356 348  
357   - // 增加用户积分
358   - getSelf().addUserPointAsync(order.getUserId(), order.getPayPrice(), order.getId());
  349 + // 增加用户积分(赠送)
  350 + addUserPoint(order.getUserId(), order.getGivePoint(), MemberPointBizTypeEnum.ORDER_REWARD, order.getId());
359 351 // 增加用户经验
360 352 getSelf().addUserExperienceAsync(order.getUserId(), order.getPayPrice(), order.getId());
361 353 // 增加用户佣金
... ... @@ -421,7 +413,7 @@ public class TradeOrderUpdateServiceImpl implements TradeOrderUpdateService {
421 413 // 1.1 校验并获得交易订单(可发货)
422 414 TradeOrderDO order = validateOrderDeliverable(deliveryReqVO.getId());
423 415 // 1.2 校验 deliveryType 是否为快递,是快递才可以发货
424   - if (ObjectUtil.notEqual(order.getDeliveryType(), DeliveryTypeEnum.EXPRESS.getMode())) {
  416 + if (ObjectUtil.notEqual(order.getDeliveryType(), DeliveryTypeEnum.EXPRESS.getType())) {
425 417 throw exception(ORDER_DELIVERY_FAIL_DELIVERY_TYPE_NOT_EXPRESS);
426 418 }
427 419  
... ... @@ -494,6 +486,7 @@ public class TradeOrderUpdateServiceImpl implements TradeOrderUpdateService {
494 486  
495 487 @Override
496 488 @Transactional(rollbackFor = Exception.class)
  489 + @TradeOrderLog(operateType = TradeOrderOperateTypeEnum.MEMBER_RECEIVE)
497 490 public void receiveOrder(Long userId, Long id) {
498 491 // 校验并获得交易订单(可收货)
499 492 TradeOrderDO order = validateOrderReceivable(userId, id);
... ... @@ -504,7 +497,6 @@ public class TradeOrderUpdateServiceImpl implements TradeOrderUpdateService {
504 497 if (updateCount == 0) {
505 498 throw exception(ORDER_RECEIVE_FAIL_STATUS_NOT_DELIVERED);
506 499 }
507   - // TODO 芋艿:OrderLog
508 500  
509 501 // TODO 芋艿:lili 发送订单变化的消息
510 502  
... ... @@ -512,7 +504,8 @@ public class TradeOrderUpdateServiceImpl implements TradeOrderUpdateService {
512 504  
513 505 // TODO 芋艿:销售佣金的记录;
514 506  
515   - // TODO 芋艿:获得积分;
  507 + // 插入订单日志
  508 + TradeOrderLogUtils.setOrderInfo(order.getId(), order.getStatus(), TradeOrderStatusEnum.COMPLETED.getStatus());
516 509 }
517 510  
518 511 @Override
... ... @@ -660,11 +653,12 @@ public class TradeOrderUpdateServiceImpl implements TradeOrderUpdateService {
660 653 return;
661 654 }
662 655 // 计算总的退款金额
663   - TradeOrderDO order = tradeOrderMapper.selectById(tradeOrderItemMapper.selectById(id).getOrderId());
  656 + TradeOrderItemDO orderItem = tradeOrderItemMapper.selectById(id);
  657 + TradeOrderDO order = tradeOrderMapper.selectById(orderItem.getOrderId());
664 658 Integer orderRefundPrice = order.getRefundPrice() + refundPrice;
665 659 if (isAllOrderItemAfterSaleSuccess(order.getId())) { // 如果都售后成功,则需要取消订单
666 660 tradeOrderMapper.updateById(new TradeOrderDO().setId(order.getId())
667   - .setRefundStatus(TradeOrderRefundStatusEnum.ALL.getStatus()).setRefundPrice(orderRefundPrice)
  661 + .setRefundStatus(TradeOrderRefundStatusEnum.ALL.getStatus()).setRefundPrice(orderRefundPrice).setRefundPoint(order.getRefundPoint() + orderItem.getUsePoint())
668 662 .setCancelType(TradeOrderCancelTypeEnum.AFTER_SALE_CLOSE.getType()).setCancelTime(LocalDateTime.now()));
669 663  
670 664 // TODO 芋艿:记录订单日志
... ... @@ -675,16 +669,22 @@ public class TradeOrderUpdateServiceImpl implements TradeOrderUpdateService {
675 669 .setRefundStatus(TradeOrderRefundStatusEnum.PART.getStatus()).setRefundPrice(orderRefundPrice));
676 670 }
677 671  
678   - // 扣减用户积分
679   - getSelf().reduceUserPointAsync(order.getUserId(), orderRefundPrice, afterSaleId);
680   - // 扣减用户经验
681   - getSelf().reduceUserExperienceAsync(order.getUserId(), orderRefundPrice, afterSaleId);
682   - // 更新分佣记录为已失效
683   - getSelf().cancelBrokerageAsync(order.getUserId(), id);
  672 + // 售后成功后,执行数据回滚逻辑
  673 + if (Objects.equals(newAfterSaleStatus, TradeOrderItemAfterSaleStatusEnum.SUCCESS.getStatus())) {
  674 + // 扣减用户积分(赠送的)
  675 + reduceUserPoint(order.getUserId(), orderItem.getGivePoint(), MemberPointBizTypeEnum.AFTER_SALE_DEDUCT_GIVE, afterSaleId);
  676 + // 增加用户积分(返还抵扣)
  677 + addUserPoint(order.getUserId(), orderItem.getUsePoint(), MemberPointBizTypeEnum.AFTER_SALE_REFUND_USED, afterSaleId);
  678 + // 扣减用户经验
  679 + getSelf().reduceUserExperienceAsync(order.getUserId(), orderRefundPrice, afterSaleId);
  680 + // 更新分佣记录为已失效
  681 + getSelf().cancelBrokerageAsync(order.getUserId(), id);
  682 + }
684 683 }
685 684  
686 685 @Override
687 686 @Transactional(rollbackFor = Exception.class)
  687 + @TradeOrderLog(operateType = TradeOrderOperateTypeEnum.MEMBER_COMMENT)
688 688 public Long createOrderItemComment(Long userId, AppTradeOrderItemCommentCreateReqVO createReqVO) {
689 689 // 先通过订单项 ID,查询订单项是否存在
690 690 TradeOrderItemDO orderItem = tradeOrderItemMapper.selectByIdAndUserId(createReqVO.getOrderItemId(), userId);
... ... @@ -712,24 +712,27 @@ public class TradeOrderUpdateServiceImpl implements TradeOrderUpdateService {
712 712 List<TradeOrderItemDO> orderItems = tradeOrderItemMapper.selectListByOrderId(order.getId());
713 713 if (!anyMatch(orderItems, item -> Objects.equals(item.getCommentStatus(), Boolean.FALSE))) {
714 714 tradeOrderMapper.updateById(new TradeOrderDO().setId(order.getId()).setCommentStatus(Boolean.TRUE));
715   - // TODO 待实现:已完成评价,要不要写一条订单日志?目前 crmeb 会写,有赞可以研究下
  715 + // 增加订单日志
  716 + TradeOrderLogUtils.setOrderInfo(order.getId(), order.getStatus(), order.getStatus());
716 717 }
717 718 return comment;
718 719 }
719 720  
720 721 @Override
  722 + @Transactional(rollbackFor = Exception.class)
  723 + @TradeOrderLog(operateType = TradeOrderOperateTypeEnum.MEMBER_CANCEL)
721 724 public void cancelOrder(Long userId, Long id) {
722   - // 校验存在
  725 + // 1.1 校验存在
723 726 TradeOrderDO order = tradeOrderMapper.selectOrderByIdAndUserId(id, userId);
724 727 if (order == null) {
725 728 throw exception(ORDER_NOT_FOUND);
726 729 }
727   - // 校验状态
  730 + // 1.2 校验状态
728 731 if (ObjectUtil.notEqual(order.getStatus(), TradeOrderStatusEnum.UNPAID.getStatus())) {
729 732 throw exception(ORDER_CANCEL_FAIL_STATUS_NOT_UNPAID);
730 733 }
731 734  
732   - // 1.更新 TradeOrderDO 状态为已取消
  735 + // 2. 更新 TradeOrderDO 状态为已取消
733 736 int updateCount = tradeOrderMapper.updateByIdAndStatus(id, order.getStatus(),
734 737 new TradeOrderDO().setStatus(TradeOrderStatusEnum.CANCELED.getStatus())
735 738 .setCancelTime(LocalDateTime.now())
... ... @@ -738,21 +741,43 @@ public class TradeOrderUpdateServiceImpl implements TradeOrderUpdateService {
738 741 throw exception(ORDER_CANCEL_FAIL_STATUS_NOT_UNPAID);
739 742 }
740 743  
741   - // TODO 活动相关库存回滚需要活动 id,活动 id 怎么获取?app 端能否传过来
  744 + // 3. TODO 活动相关库存回滚需要活动 id,活动 id 怎么获取?app 端能否传过来;回复:从订单里拿呀
742 745 tradeOrderHandlers.forEach(handler -> handler.rollback());
743 746  
744   - // 2.回滚库存
  747 + // 4. 回滚库存
745 748 List<TradeOrderItemDO> orderItems = tradeOrderItemMapper.selectListByOrderId(id);
746 749 productSkuApi.updateSkuStock(TradeOrderConvert.INSTANCE.convert(orderItems));
747 750  
748   - // 3.回滚优惠券
749   - couponApi.returnUsedCoupon(order.getCouponId());
  751 + // 5. 回滚优惠券
  752 + if (order.getCouponId() > 0) {
  753 + couponApi.returnUsedCoupon(order.getCouponId());
  754 + }
750 755  
751   - // 4.回滚积分:积分是支付成功后才增加的吧? 回复:每个项目不同,目前看下来,确认收货貌似更合适,我再看看其它项目的业务选择;
  756 + // 6. 回滚积分(抵扣的)
  757 + addUserPoint(order.getUserId(), order.getUsePoint(), MemberPointBizTypeEnum.ORDER_CANCEL, order.getId());
752 758  
753   - // TODO 芋艿:OrderLog
  759 + // 7. 增加订单日志
  760 + TradeOrderLogUtils.setOrderInfo(order.getId(), order.getStatus(), TradeOrderStatusEnum.CANCELED.getStatus());
  761 + }
754 762  
755   - // TODO 芋艿:lili 发送订单变化的消息
  763 + @Override
  764 + @Transactional(rollbackFor = Exception.class)
  765 + @TradeOrderLog(operateType = TradeOrderOperateTypeEnum.MEMBER_DELETE)
  766 + public void deleteOrder(Long userId, Long id) {
  767 + // 1.1 校验存在
  768 + TradeOrderDO order = tradeOrderMapper.selectOrderByIdAndUserId(id, userId);
  769 + if (order == null) {
  770 + throw exception(ORDER_NOT_FOUND);
  771 + }
  772 + // 1.2 校验状态
  773 + if (ObjectUtil.notEqual(order.getStatus(), TradeOrderStatusEnum.CANCELED.getStatus())) {
  774 + throw exception(ORDER_DELETE_FAIL_STATUS_NOT_CANCEL);
  775 + }
  776 + // 2. 删除订单
  777 + tradeOrderMapper.deleteById(id);
  778 +
  779 + // 3. 记录日志
  780 + TradeOrderLogUtils.setOrderInfo(order.getId(), order.getStatus(), order.getStatus());
756 781 }
757 782  
758 783 /**
... ... @@ -779,28 +804,54 @@ public class TradeOrderUpdateServiceImpl implements TradeOrderUpdateService {
779 804 memberLevelApi.addExperience(userId, -refundPrice, bizType, String.valueOf(afterSaleId));
780 805 }
781 806  
782   - @Async
783   - protected void addUserPointAsync(Long userId, Integer payPrice, Long orderId) {
784   - int bizType = MemberPointBizTypeEnum.ORDER_BUY.getType();
785   - memberPointApi.addPoint(userId, payPrice, bizType, String.valueOf(orderId));
  807 + /**
  808 + * 添加用户积分
  809 + * <p>
  810 + * 目前是支付成功后,就会创建积分记录。
  811 + * <p>
  812 + * 业内还有两种做法,可以根据自己的业务调整:
  813 + * 1. 确认收货后,才创建积分记录
  814 + * 2. 支付 or 下单成功时,创建积分记录(冻结),确认收货解冻或者 n 天后解冻
  815 + *
  816 + * @param userId 用户编号
  817 + * @param point 增加积分数量
  818 + * @param bizType 业务编号
  819 + * @param bizId 业务编号
  820 + */
  821 + protected void addUserPoint(Long userId, Integer point, MemberPointBizTypeEnum bizType, Long bizId) {
  822 + if (point != null && point > 0) {
  823 + memberPointApi.addPoint(userId, point, bizType.getType(), String.valueOf(bizId));
  824 + }
786 825 }
787 826  
788   - @Async
789   - protected void reduceUserPointAsync(Long userId, Integer refundPrice, Long afterSaleId) {
790   - int bizType = MemberPointBizTypeEnum.ORDER_CANCEL.getType();
791   - memberPointApi.addPoint(userId, -refundPrice, bizType, String.valueOf(afterSaleId));
  827 + protected void reduceUserPoint(Long userId, Integer point, MemberPointBizTypeEnum bizType, Long bizId) {
  828 + if (point != null && point > 0) {
  829 + memberPointApi.reducePoint(userId, point, bizType.getType(), String.valueOf(bizId));
  830 + }
792 831 }
793 832  
794   -
  833 + /**
  834 + * 创建分销记录
  835 + *
  836 + * 目前是支付成功后,就会创建分销记录。
  837 + *
  838 + * 业内还有两种做法,可以根据自己的业务调整:
  839 + * 1. 确认收货后,才创建分销记录
  840 + * 2. 支付 or 下单成功时,创建分销记录(冻结),确认收货解冻或者 n 天后解冻
  841 + *
  842 + * @param userId 用户编号
  843 + * @param orderId 订单编号
  844 + */
795 845 @Async
796 846 protected void addBrokerageAsync(Long userId, Long orderId) {
797 847 MemberUserRespDTO user = memberUserApi.getUser(userId);
798 848 Assert.notNull(user);
799   -
  849 + // 每一个订单项,都会去生成分销记录
800 850 List<TradeOrderItemDO> orderItems = tradeOrderItemMapper.selectListByOrderId(orderId);
801   - List<BrokerageAddReqBO> list = convertList(orderItems,
802   - item -> TradeOrderConvert.INSTANCE.convert(user, item, productSkuApi.getSku(item.getSkuId())));
803   - brokerageRecordService.addBrokerage(userId, BrokerageRecordBizTypeEnum.ORDER, list);
  851 + List<BrokerageAddReqBO> addList = convertList(orderItems,
  852 + item -> TradeOrderConvert.INSTANCE.convert(user, item,
  853 + productSpuApi.getSpu(item.getSpuId()), productSkuApi.getSku(item.getSkuId())));
  854 + brokerageRecordService.addBrokerage(userId, BrokerageRecordBizTypeEnum.ORDER, addList);
804 855 }
805 856  
806 857 @Async
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/service/order/handler/TradeBargainHandler.java
... ... @@ -20,14 +20,17 @@ public class TradeBargainHandler implements TradeOrderHandler {
20 20 @Resource
21 21 private BargainActivityApi bargainActivityApi;
22 22  
  23 + // TODO @puhui999:先临时写在这里;在价格计算时,如果是秒杀商品,需要校验如下条件:
  24 + // 1. 商品存在、库存充足、单次限购;
  25 + // 2. 活动进行中、时间段符合
  26 +
23 27 @Override
24 28 public void beforeOrderCreate(TradeBeforeOrderCreateReqBO reqBO) {
25 29 // 如果是砍价订单
26 30 if (ObjectUtil.notEqual(TradeOrderTypeEnum.BARGAIN.getType(), reqBO.getOrderType())) {
27 31 return;
28 32 }
29   -
30   - // 额外扣减砍价的库存
  33 + // 扣减砍价活动的库存
31 34 bargainActivityApi.updateBargainActivityStock(reqBO.getBargainActivityId(), reqBO.getCount());
32 35 }
33 36  
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/service/order/handler/TradeCombinationHandler.java
... ... @@ -37,6 +37,11 @@ public class TradeCombinationHandler implements TradeOrderHandler {
37 37  
38 38 @Override
39 39 public void afterOrderCreate(TradeAfterOrderCreateReqBO reqBO) {
  40 + // TODO @puhui999:需要判断下;
  41 + if (true) {
  42 + return;
  43 + }
  44 +
40 45 // 创建砍价记录
41 46 combinationRecordApi.createCombinationRecord(TradeOrderConvert.INSTANCE.convert(reqBO));
42 47 }
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/service/order/handler/TradeOrderHandler.java
... ... @@ -24,9 +24,12 @@ public interface TradeOrderHandler {
24 24 */
25 25 void afterOrderCreate(TradeAfterOrderCreateReqBO reqBO);
26 26  
  27 + // TODO @puhui999:这个搞成订单取消
27 28 /**
28 29 * 回滚
29 30 */
30 31 void rollback();
31 32  
  33 + // TODO @puhui999:再搞个订单项取消哈
  34 +
32 35 }
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/service/order/handler/TradeSeckillHandler.java
... ... @@ -20,13 +20,17 @@ public class TradeSeckillHandler implements TradeOrderHandler {
20 20 @Resource
21 21 private SeckillActivityApi seckillActivityApi;
22 22  
  23 + // TODO @puhui999:先临时写在这里;在价格计算时,如果是秒杀商品,需要校验如下条件:
  24 + // 1. 商品存在、库存充足、单次限购;
  25 + // 2. 活动进行中、时间段符合
  26 +
23 27 @Override
24 28 public void beforeOrderCreate(TradeBeforeOrderCreateReqBO reqBO) {
25 29 // 如果是秒杀订单:额外扣减秒杀的库存;
26 30 if (ObjectUtil.notEqual(TradeOrderTypeEnum.SECKILL.getType(), reqBO.getOrderType())) {
27 31 return;
28 32 }
29   -
  33 + // 扣减秒杀活动的库存
30 34 seckillActivityApi.updateSeckillStock(reqBO.getSeckillActivityId(), reqBO.getSkuId(), reqBO.getCount());
31 35 }
32 36  
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/service/price/TradePriceServiceImpl.java
... ... @@ -41,7 +41,6 @@ public class TradePriceServiceImpl implements TradePriceService {
41 41 @Resource
42 42 private List<TradePriceCalculator> priceCalculators;
43 43  
44   - // TODO @疯狂:需要搞个 TradePriceCalculator,计算赠送积分;
45 44 @Override
46 45 public TradePriceCalculateRespBO calculatePrice(TradePriceCalculateReqBO calculateReqBO) {
47 46 // 1.1 获得商品 SKU 数组
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/service/price/bo/TradePriceCalculateReqBO.java
1 1 package cn.iocoder.yudao.module.trade.service.price.bo;
2 2  
3 3 import cn.iocoder.yudao.module.trade.enums.delivery.DeliveryTypeEnum;
4   -import cn.iocoder.yudao.module.trade.enums.order.TradeOrderTypeEnum;
5   -import io.swagger.v3.oas.annotations.media.Schema;
6 4 import lombok.Data;
7 5  
8 6 import javax.validation.Valid;
... ... @@ -19,13 +17,6 @@ import java.util.List;
19 17 public class TradePriceCalculateReqBO {
20 18  
21 19 /**
22   - * 订单类型
23   - *
24   - * 枚举 {@link TradeOrderTypeEnum}
25   - */
26   - private Integer type;
27   -
28   - /**
29 20 * 用户编号
30 21 *
31 22 * 对应 MemberUserDO 的 id 编号
... ... @@ -40,11 +31,10 @@ public class TradePriceCalculateReqBO {
40 31 private Long couponId;
41 32  
42 33 /**
43   - * 收货地址编号
44   - *
45   - * 对应 MemberAddressDO 的 id 编号
  34 + * 是否使用积分
46 35 */
47   - private Long addressId;
  36 + @NotNull(message = "是否使用积分不能为空")
  37 + private Boolean pointStatus;
48 38  
49 39 /**
50 40 * 配送方式
... ... @@ -52,29 +42,48 @@ public class TradePriceCalculateReqBO {
52 42 * 枚举 {@link DeliveryTypeEnum}
53 43 */
54 44 private Integer deliveryType;
  45 + /**
  46 + * 收货地址编号
  47 + *
  48 + * 对应 MemberAddressDO 的 id 编号
  49 + */
  50 + private Long addressId;
  51 + /**
  52 + * 自提门店编号
  53 + *
  54 + * 对应 PickUpStoreDO 的 id 编号
  55 + */
  56 + private Long pickUpStoreId;
  57 +
  58 + /**
  59 + * 商品 SKU 数组
  60 + */
  61 + @NotNull(message = "商品数组不能为空")
  62 + private List<Item> items;
55 63  
56 64 // ========== 秒杀活动相关字段 ==========
57   - @Schema(description = "秒杀活动编号", example = "1024")
  65 + /**
  66 + * 秒杀活动编号
  67 + */
58 68 private Long seckillActivityId;
59 69  
60 70 // ========== 拼团活动相关字段 ==========
61 71 // TODO @puhui999:是不是拼团记录的编号哈?
62   - @Schema(description = "拼团活动编号", example = "1024")
  72 + /**
  73 + * 拼团活动编号
  74 + */
63 75 private Long combinationActivityId;
64 76  
65   - @Schema(description = "拼团团长编号", example = "2048")
  77 + /**
  78 + * 拼团团长编号
  79 + */
66 80 private Long combinationHeadId;
67 81  
68 82 // ========== 砍价活动相关字段 ==========
69   - // TODO @puhui999:是不是砍价记录的编号哈?
70   - @Schema(description = "砍价活动编号", example = "123")
71   - private Long bargainActivityId;
72   -
73 83 /**
74   - * 商品 SKU 数组
  84 + * 砍价活动编号
75 85 */
76   - @NotNull(message = "商品数组不能为空")
77   - private List<Item> items;
  86 + private Long bargainActivityId;
78 87  
79 88 /**
80 89 * 商品 SKU
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/service/price/bo/TradePriceCalculateRespBO.java
... ... @@ -49,6 +49,16 @@ public class TradePriceCalculateRespBO {
49 49 private Long couponId;
50 50  
51 51 /**
  52 + * 使用的积分
  53 + */
  54 + private Integer usePoint;
  55 +
  56 + /**
  57 + * 使用的积分
  58 + */
  59 + private Integer givePoint;
  60 +
  61 + /**
52 62 * 订单价格
53 63 */
54 64 @Data
... ... @@ -85,6 +95,10 @@ public class TradePriceCalculateRespBO {
85 95 */
86 96 private Integer pointPrice;
87 97 /**
  98 + * VIP 减免金额,单位:分
  99 + */
  100 + private Integer vipPrice;
  101 + /**
88 102 * 秒杀、拼团、砍价活动商品的总金额,单位:分
89 103 *
90 104 * 基于 {@link OrderItem#getActivityPrice()} ()} * {@link OrderItem#getCount()} 求和
... ... @@ -102,6 +116,7 @@ public class TradePriceCalculateRespBO {
102 116 * - {@link #pointPrice}
103 117 * - {@link #discountPrice}
104 118 * + {@link #deliveryPrice}
  119 + * - {@link #vipPrice}
105 120 */
106 121 private Integer payPrice;
107 122  
... ... @@ -164,6 +179,14 @@ public class TradePriceCalculateRespBO {
164 179 */
165 180 private Integer pointPrice;
166 181 /**
  182 + * 使用的积分
  183 + */
  184 + private Integer usePoint;
  185 + /**
  186 + * VIP 减免金额,单位:分
  187 + */
  188 + private Integer vipPrice;
  189 + /**
167 190 * 秒杀、拼团、砍价活动商品的金额,单位:分
168 191 */
169 192 private Integer activityPrice;
... ... @@ -178,6 +201,7 @@ public class TradePriceCalculateRespBO {
178 201 * - {@link #pointPrice}
179 202 * - {@link #discountPrice}
180 203 * + {@link #deliveryPrice}
  204 + * - {@link #vipPrice}
181 205 */
182 206 private Integer payPrice;
183 207  
... ... @@ -217,6 +241,11 @@ public class TradePriceCalculateRespBO {
217 241 */
218 242 private List<ProductPropertyValueDetailRespDTO> properties;
219 243  
  244 + /**
  245 + * 使用的积分
  246 + */
  247 + private Integer givePoint;
  248 +
220 249 }
221 250  
222 251 /**
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/service/price/calculator/TradeCouponPriceCalculator.java
... ... @@ -2,6 +2,7 @@ package cn.iocoder.yudao.module.trade.service.price.calculator;
2 2  
3 3 import cn.hutool.core.collection.CollUtil;
4 4 import cn.hutool.core.lang.Assert;
  5 +import cn.hutool.core.util.ObjectUtil;
5 6 import cn.hutool.core.util.StrUtil;
6 7 import cn.iocoder.yudao.module.promotion.api.coupon.CouponApi;
7 8 import cn.iocoder.yudao.module.promotion.api.coupon.dto.CouponRespDTO;
... ... @@ -9,6 +10,7 @@ import cn.iocoder.yudao.module.promotion.api.coupon.dto.CouponValidReqDTO;
9 10 import cn.iocoder.yudao.module.promotion.enums.common.PromotionDiscountTypeEnum;
10 11 import cn.iocoder.yudao.module.promotion.enums.common.PromotionProductScopeEnum;
11 12 import cn.iocoder.yudao.module.promotion.enums.common.PromotionTypeEnum;
  13 +import cn.iocoder.yudao.module.trade.enums.order.TradeOrderTypeEnum;
12 14 import cn.iocoder.yudao.module.trade.service.price.bo.TradePriceCalculateReqBO;
13 15 import cn.iocoder.yudao.module.trade.service.price.bo.TradePriceCalculateRespBO;
14 16 import org.springframework.core.annotation.Order;
... ... @@ -22,6 +24,7 @@ import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionU
22 24 import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.filterList;
23 25 import static cn.iocoder.yudao.module.promotion.enums.ErrorCodeConstants.COUPON_NO_MATCH_MIN_PRICE;
24 26 import static cn.iocoder.yudao.module.promotion.enums.ErrorCodeConstants.COUPON_NO_MATCH_SPU;
  27 +import static cn.iocoder.yudao.module.trade.enums.ErrorCodeConstants.PRICE_CALCULATE_COUPON_NOT_MATCH_NORMAL_ORDER;
25 28  
26 29 /**
27 30 * 优惠劵的 {@link TradePriceCalculator} 实现类
... ... @@ -44,6 +47,10 @@ public class TradeCouponPriceCalculator implements TradePriceCalculator {
44 47 CouponRespDTO coupon = couponApi.validateCoupon(new CouponValidReqDTO()
45 48 .setId(param.getCouponId()).setUserId(param.getUserId()));
46 49 Assert.notNull(coupon, "校验通过的优惠劵({}),不能为空", param.getCouponId());
  50 + // 1.2 只有【普通】订单,才允许使用优惠劵
  51 + if (ObjectUtil.notEqual(result.getType(), TradeOrderTypeEnum.NORMAL.getType())) {
  52 + throw exception(PRICE_CALCULATE_COUPON_NOT_MATCH_NORMAL_ORDER);
  53 + }
47 54  
48 55 // 2.1 获得匹配的商品 SKU 数组
49 56 List<TradePriceCalculateRespBO.OrderItem> orderItems = filterMatchCouponOrderItems(result, coupon);
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/service/price/calculator/TradeDeliveryPriceCalculator.java
... ... @@ -2,11 +2,17 @@ package cn.iocoder.yudao.module.trade.service.price.calculator;
2 2  
3 3 import cn.hutool.core.collection.CollUtil;
4 4 import cn.hutool.core.lang.Assert;
  5 +import cn.hutool.core.util.StrUtil;
  6 +import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
5 7 import cn.iocoder.yudao.module.member.api.address.AddressApi;
6 8 import cn.iocoder.yudao.module.member.api.address.dto.AddressRespDTO;
  9 +import cn.iocoder.yudao.module.trade.dal.dataobject.config.TradeConfigDO;
  10 +import cn.iocoder.yudao.module.trade.dal.dataobject.delivery.DeliveryPickUpStoreDO;
7 11 import cn.iocoder.yudao.module.trade.enums.delivery.DeliveryExpressChargeModeEnum;
8 12 import cn.iocoder.yudao.module.trade.enums.delivery.DeliveryTypeEnum;
  13 +import cn.iocoder.yudao.module.trade.service.config.TradeConfigService;
9 14 import cn.iocoder.yudao.module.trade.service.delivery.DeliveryExpressTemplateService;
  15 +import cn.iocoder.yudao.module.trade.service.delivery.DeliveryPickUpStoreService;
10 16 import cn.iocoder.yudao.module.trade.service.delivery.bo.DeliveryExpressTemplateRespBO;
11 17 import cn.iocoder.yudao.module.trade.service.price.bo.TradePriceCalculateReqBO;
12 18 import cn.iocoder.yudao.module.trade.service.price.bo.TradePriceCalculateRespBO;
... ... @@ -22,8 +28,7 @@ import java.util.Set;
22 28  
23 29 import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
24 30 import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.*;
25   -import static cn.iocoder.yudao.module.trade.enums.ErrorCodeConstants.PRICE_CALCULATE_DELIVERY_PRICE_USER_ADDR_IS_EMPTY;
26   -import static cn.iocoder.yudao.module.trade.enums.ErrorCodeConstants.PRICE_CALCULATE_DELIVERY_PRICE_TEMPLATE_NOT_FOUND;
  31 +import static cn.iocoder.yudao.module.trade.enums.ErrorCodeConstants.*;
27 32  
28 33 /**
29 34 * 运费的 {@link TradePriceCalculator} 实现类
... ... @@ -37,29 +42,60 @@ public class TradeDeliveryPriceCalculator implements TradePriceCalculator {
37 42  
38 43 @Resource
39 44 private AddressApi addressApi;
  45 +
  46 + @Resource
  47 + private DeliveryPickUpStoreService deliveryPickUpStoreService;
40 48 @Resource
41 49 private DeliveryExpressTemplateService deliveryExpressTemplateService;
  50 + @Resource
  51 + private TradeConfigService tradeConfigService;
42 52  
43 53 @Override
44 54 public void calculate(TradePriceCalculateReqBO param, TradePriceCalculateRespBO result) {
45   - // TODO @芋艿:如果门店自提,需要校验是否开启;
46   - // 1.1 判断配送方式
47   - if (param.getDeliveryType() == null || DeliveryTypeEnum.PICK_UP.getMode().equals(param.getDeliveryType())) {
  55 + if (param.getDeliveryType() == null) {
  56 + return;
  57 + }
  58 + if (DeliveryTypeEnum.PICK_UP.getType().equals(param.getDeliveryType())) {
  59 + calculateByPickUp(param);
  60 + } else if (DeliveryTypeEnum.EXPRESS.getType().equals(param.getDeliveryType())) {
  61 + calculateExpress(param, result);
  62 + }
  63 + }
  64 +
  65 + private void calculateByPickUp(TradePriceCalculateReqBO param) {
  66 + if (param.getPickUpStoreId() == null) {
  67 + // 价格计算时,如果为空就不算~最终下单,会校验该字段不允许空
48 68 return;
49 69 }
  70 + DeliveryPickUpStoreDO pickUpStore = deliveryPickUpStoreService.getDeliveryPickUpStore(param.getPickUpStoreId());
  71 + if (pickUpStore == null || CommonStatusEnum.DISABLE.getStatus().equals(pickUpStore.getStatus())) {
  72 + throw exception(PICK_UP_STORE_NOT_EXISTS);
  73 + }
  74 + }
  75 +
  76 + // ========= 快递发货 ==========
  77 +
  78 + private void calculateExpress(TradePriceCalculateReqBO param, TradePriceCalculateRespBO result) {
  79 + // 0. 得到收件地址区域
50 80 if (param.getAddressId() == null) {
51   - throw exception(PRICE_CALCULATE_DELIVERY_PRICE_USER_ADDR_IS_EMPTY);
  81 + // 价格计算时,如果为空就不算~最终下单,会校验该字段不允许空
  82 + return;
52 83 }
53   - // 1.2 得到收件地址区域
54 84 AddressRespDTO address = addressApi.getAddress(param.getAddressId(), param.getUserId());
55 85 Assert.notNull(address, "收件人({})的地址,不能为空", param.getUserId());
56 86  
57   - // 2. 过滤出已选中的商品SKU
  87 + // 情况一:全局包邮
  88 + if (isGlobalExpressFree(result)) {
  89 + return;
  90 + }
  91 +
  92 + // 情况二:快递模版
  93 + // 2.1 过滤出已选中的商品 SKU
58 94 List<OrderItem> selectedItem = filterList(result.getItems(), OrderItem::getSelected);
59 95 Set<Long> deliveryTemplateIds = convertSet(selectedItem, OrderItem::getDeliveryTemplateId);
60 96 Map<Long, DeliveryExpressTemplateRespBO> expressTemplateMap =
61 97 deliveryExpressTemplateService.getExpressTemplateMapByIdsAndArea(deliveryTemplateIds, address.getAreaId());
62   - // 3. 计算配送费用
  98 + // 2.2 计算配送费用
63 99 if (CollUtil.isEmpty(expressTemplateMap)) {
64 100 log.error("[calculate][找不到商品 templateIds {} areaId{} 对应的运费模板]", deliveryTemplateIds, address.getAreaId());
65 101 throw exception(PRICE_CALCULATE_DELIVERY_PRICE_TEMPLATE_NOT_FOUND);
... ... @@ -67,13 +103,26 @@ public class TradeDeliveryPriceCalculator implements TradePriceCalculator {
67 103 calculateDeliveryPrice(selectedItem, expressTemplateMap, result);
68 104 }
69 105  
  106 + /**
  107 + * 是否全局包邮
  108 + *
  109 + * @param result 计算结果
  110 + * @return 是否包邮
  111 + */
  112 + private boolean isGlobalExpressFree(TradePriceCalculateRespBO result) {
  113 + TradeConfigDO config = tradeConfigService.getTradeConfig();
  114 + return config != null
  115 + && Boolean.TRUE.equals(config.getDeliveryExpressFreeEnabled()) // 开启包邮
  116 + && result.getPrice().getPayPrice() >= config.getDeliveryExpressFreePrice(); // 满足包邮的价格
  117 + }
  118 +
70 119 private void calculateDeliveryPrice(List<OrderItem> selectedSkus,
71 120 Map<Long, DeliveryExpressTemplateRespBO> expressTemplateMap,
72 121 TradePriceCalculateRespBO result) {
73 122 // 按商品运费模板来计算商品的运费:相同的运费模板可能对应多条订单商品 SKU
74   - Map<Long, List<OrderItem>> tplIdItemMap = convertMultiMap(selectedSkus, OrderItem::getDeliveryTemplateId);
  123 + Map<Long, List<OrderItem>> template2ItemMap = convertMultiMap(selectedSkus, OrderItem::getDeliveryTemplateId);
75 124 // 依次计算快递运费
76   - for (Map.Entry<Long, List<OrderItem>> entry : tplIdItemMap.entrySet()) {
  125 + for (Map.Entry<Long, List<OrderItem>> entry : template2ItemMap.entrySet()) {
77 126 Long templateId = entry.getKey();
78 127 List<OrderItem> orderItems = entry.getValue();
79 128 DeliveryExpressTemplateRespBO templateBO = expressTemplateMap.get(templateId);
... ... @@ -81,26 +130,12 @@ public class TradeDeliveryPriceCalculator implements TradePriceCalculator {
81 130 log.error("[calculateDeliveryPrice][不能计算快递运费,找不到 templateId({}) 对应的运费模板配置]", templateId);
82 131 continue;
83 132 }
84   - // 总件数, 总金额, 总重量, 总体积
85   - int totalCount = 0;
86   - int totalPrice = 0;
87   - double totalWeight = 0;
88   - double totalVolume = 0;
89   - for (OrderItem orderItem : orderItems) {
90   - totalCount += orderItem.getCount();
91   - totalPrice += orderItem.getPayPrice();
92   - totalWeight += totalWeight + orderItem.getWeight() * orderItem.getCount();
93   - totalVolume += totalVolume + orderItem.getVolume() * orderItem.getCount();
94   - }
95   - // 优先判断是否包邮. 如果包邮不计算快递运费
96   - if (isExpressFree(templateBO.getChargeMode(), totalCount, totalWeight,
97   - totalVolume, totalPrice, templateBO.getFree())) {
  133 + // 1. 优先判断是否包邮。如果包邮不计算快递运费
  134 + if (isExpressTemplateFree(orderItems, templateBO.getChargeMode(), templateBO.getFree())) {
98 135 continue;
99 136 }
100   - // 计算快递运费
101   - calculateExpressFeeByChargeMode(totalCount, totalWeight, totalVolume,
102   - templateBO.getChargeMode(), templateBO.getCharge(), orderItems);
103   -
  137 + // 2. 计算快递运费
  138 + calculateExpressFeeByChargeMode(orderItems, templateBO.getChargeMode(), templateBO.getCharge());
104 139 }
105 140 TradePriceCalculatorHelper.recountAllPrice(result);
106 141 }
... ... @@ -108,73 +143,44 @@ public class TradeDeliveryPriceCalculator implements TradePriceCalculator {
108 143 /**
109 144 * 按配送方式来计算运费
110 145 *
111   - * @param totalCount 总件数
112   - * @param totalWeight 总重量
113   - * @param totalVolume 总体积
  146 + * @param orderItems SKU 商品项目
114 147 * @param chargeMode 配送计费方式
115 148 * @param templateCharge 快递运费配置
116   - * @param orderItems SKU 商品项目
117 149 */
118   - private void calculateExpressFeeByChargeMode(double totalCount, double totalWeight, double totalVolume,
119   - int chargeMode, DeliveryExpressTemplateRespBO.Charge templateCharge,
120   - List<OrderItem> orderItems) {
  150 + private void calculateExpressFeeByChargeMode(List<OrderItem> orderItems, Integer chargeMode,
  151 + DeliveryExpressTemplateRespBO.Charge templateCharge) {
121 152 if (templateCharge == null) {
122 153 log.error("[calculateExpressFeeByChargeMode][计算快递运费时,找不到 SKU({}) 对应的运费模版]", orderItems);
123 154 return;
124 155 }
125   - DeliveryExpressChargeModeEnum chargeModeEnum = DeliveryExpressChargeModeEnum.valueOf(chargeMode);
126   - switch (chargeModeEnum) {
127   - case PIECE: {
128   - calculateExpressFee(totalCount, templateCharge, orderItems);
129   - break;
130   - }
131   - case WEIGHT: {
132   - calculateExpressFee(totalWeight, templateCharge, orderItems);
133   - break;
134   - }
135   - case VOLUME: {
136   - calculateExpressFee(totalVolume, templateCharge, orderItems);
137   - break;
138   - }
139   - }
140   - }
141   -
142   - /**
143   - * 计算 SKU 商品快递费用
144   - *
145   - * @param total 总件数/总重量/总体积
146   - * @param templateCharge 快递运费配置
147   - * @param orderItems SKU 商品项目
148   - */
149   - private void calculateExpressFee(double total, DeliveryExpressTemplateRespBO.Charge templateCharge, List<OrderItem> orderItems) {
  156 + double totalChargeValue = getTotalChargeValue(orderItems, chargeMode);
  157 + // 1. 计算 SKU 商品快递费用
150 158 int deliveryPrice;
151   - if (total <= templateCharge.getStartCount()) {
  159 + if (totalChargeValue <= templateCharge.getStartCount()) {
152 160 deliveryPrice = templateCharge.getStartPrice();
153 161 } else {
154   - double remainWeight = total - templateCharge.getStartCount();
  162 + double remainWeight = totalChargeValue - templateCharge.getStartCount();
155 163 // 剩余重量/ 续件 = 续件的次数. 向上取整
156 164 int extraNum = (int) Math.ceil(remainWeight / templateCharge.getExtraCount());
157 165 int extraPrice = templateCharge.getExtraPrice() * extraNum;
158 166 deliveryPrice = templateCharge.getStartPrice() + extraPrice;
159 167 }
160   - // 分摊快递费用到 SKU. 退费的时候,可能按照 SKU 考虑退费金额
161   - divideDeliveryPrice(deliveryPrice, orderItems);
162   - }
163 168  
164   - /**
165   - * 快递运费分摊到每个 SKU 商品上
166   - *
167   - * @param deliveryPrice 快递运费
168   - * @param orderItems SKU 商品
169   - */
170   - private void divideDeliveryPrice(int deliveryPrice, List<OrderItem> orderItems) {
171   - // TODO @jason:分摊的话,是不是要按照比例呀?重量、价格、数量等等,
172   - // 按比例是不是有点复杂。后面看看是否需要;
173   - // TODO 可以看看别的项目怎么搞的哈。
174   - int dividePrice = deliveryPrice / orderItems.size();
175   - for (OrderItem item : orderItems) {
  169 + // 2. 分摊快递费用到 SKU. 退费的时候,可能按照 SKU 考虑退费金额
  170 + int remainPrice = deliveryPrice;
  171 + for (int i = 0; i < orderItems.size(); i++) {
  172 + TradePriceCalculateRespBO.OrderItem item = orderItems.get(i);
  173 + int partPrice;
  174 + double chargeValue = getChargeValue(item, chargeMode);
  175 + if (i < orderItems.size() - 1) { // 减一的原因,是因为拆分时,如果按照比例,可能会出现.所以最后一个,使用反减
  176 + partPrice = (int) (deliveryPrice * (chargeValue / totalChargeValue));
  177 + remainPrice -= partPrice;
  178 + } else {
  179 + partPrice = remainPrice;
  180 + }
  181 + Assert.isTrue(partPrice >= 0, "分摊金额必须大于等于 0");
176 182 // 更新快递运费
177   - item.setDeliveryPrice(dividePrice);
  183 + item.setDeliveryPrice(partPrice);
178 184 TradePriceCalculatorHelper.recountPayPrice(item);
179 185 }
180 186 }
... ... @@ -183,42 +189,38 @@ public class TradeDeliveryPriceCalculator implements TradePriceCalculator {
183 189 * 检查是否包邮
184 190 *
185 191 * @param chargeMode 配送计费方式
186   - * @param totalCount 总件数
187   - * @param totalWeight 总重量
188   - * @param totalVolume 总体积
189   - * @param totalPrice 总金额
190 192 * @param templateFree 包邮配置
191 193 */
192   - private boolean isExpressFree(Integer chargeMode, int totalCount, double totalWeight,
193   - double totalVolume, int totalPrice, DeliveryExpressTemplateRespBO.Free templateFree) {
  194 + private boolean isExpressTemplateFree(List<OrderItem> orderItems, Integer chargeMode,
  195 + DeliveryExpressTemplateRespBO.Free templateFree) {
194 196 if (templateFree == null) {
195 197 return false;
196 198 }
  199 + double totalChargeValue = getTotalChargeValue(orderItems, chargeMode);
  200 + double totalPrice = TradePriceCalculatorHelper.calculateTotalPayPrice(orderItems);
  201 + return totalChargeValue >= templateFree.getFreeCount() && totalPrice >= templateFree.getFreePrice();
  202 + }
  203 +
  204 + private double getTotalChargeValue(List<OrderItem> orderItems, Integer chargeMode) {
  205 + double total = 0;
  206 + for (OrderItem orderItem : orderItems) {
  207 + total += getChargeValue(orderItem, chargeMode);
  208 + }
  209 + return total;
  210 + }
  211 +
  212 + private double getChargeValue(OrderItem orderItem, Integer chargeMode) {
197 213 DeliveryExpressChargeModeEnum chargeModeEnum = DeliveryExpressChargeModeEnum.valueOf(chargeMode);
198 214 switch (chargeModeEnum) {
199   - case PIECE:
200   - // 两个条件都满足才包邮
201   - if (totalCount >= templateFree.getFreeCount() && totalPrice >= templateFree.getFreePrice()) {
202   - return true;
203   - }
204   - break;
  215 + case COUNT:
  216 + return orderItem.getCount();
205 217 case WEIGHT:
206   - // freeCount 是不是应该是 double ??
207   - // TODO @jason:要不配置的时候,把它的单位和商品对齐?到底是 kg、还是斤
208   - // TODO @芋艿 目前 包邮 件数/重量/体积 都用的是这个字段
209   - // TODO @jason:那要不快递模版也改成 kg?这样是不是就不用 double ?
210   - if (totalWeight >= templateFree.getFreeCount()
211   - && totalPrice >= templateFree.getFreePrice()) {
212   - return true;
213   - }
214   - break;
  218 + return orderItem.getWeight() != null ? orderItem.getWeight() * orderItem.getCount() : 0;
215 219 case VOLUME:
216   - if (totalVolume >= templateFree.getFreeCount()
217   - && totalPrice >= templateFree.getFreePrice()) {
218   - return true;
219   - }
220   - break;
  220 + return orderItem.getVolume() != null ? orderItem.getVolume() * orderItem.getCount() : 0;
  221 + default:
  222 + throw new IllegalArgumentException(StrUtil.format("未知的计费模式({})", chargeMode));
221 223 }
222   - return false;
223 224 }
  225 +
224 226 }
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/service/price/calculator/TradeDiscountActivityPriceCalculator.java
1 1 package cn.iocoder.yudao.module.trade.service.price.calculator;
2 2  
3 3 import cn.hutool.core.collection.CollUtil;
  4 +import cn.hutool.core.util.ObjectUtil;
4 5 import cn.hutool.core.util.StrUtil;
5 6 import cn.iocoder.yudao.module.promotion.api.discount.DiscountActivityApi;
6 7 import cn.iocoder.yudao.module.promotion.api.discount.dto.DiscountProductRespDTO;
7 8 import cn.iocoder.yudao.module.promotion.enums.common.PromotionDiscountTypeEnum;
8 9 import cn.iocoder.yudao.module.promotion.enums.common.PromotionTypeEnum;
  10 +import cn.iocoder.yudao.module.trade.enums.order.TradeOrderTypeEnum;
9 11 import cn.iocoder.yudao.module.trade.service.price.bo.TradePriceCalculateReqBO;
10 12 import cn.iocoder.yudao.module.trade.service.price.bo.TradePriceCalculateRespBO;
11 13 import org.springframework.core.annotation.Order;
... ... @@ -33,6 +35,10 @@ public class TradeDiscountActivityPriceCalculator implements TradePriceCalculato
33 35  
34 36 @Override
35 37 public void calculate(TradePriceCalculateReqBO param, TradePriceCalculateRespBO result) {
  38 + // 0. 只有【普通】订单,才计算该优惠
  39 + if (ObjectUtil.notEqual(result.getType(), TradeOrderTypeEnum.NORMAL.getType())) {
  40 + return;
  41 + }
36 42 // 获得 SKU 对应的限时折扣活动
37 43 List<DiscountProductRespDTO> discountProducts = discountActivityApi.getMatchDiscountProductList(
38 44 convertSet(result.getItems(), TradePriceCalculateRespBO.OrderItem::getSkuId));
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/service/price/calculator/TradeMemberLevelPriceCalculator.java 0 → 100644
  1 +package cn.iocoder.yudao.module.trade.service.price.calculator;
  2 +
  3 +import cn.hutool.core.util.ObjectUtil;
  4 +import cn.iocoder.yudao.module.member.api.level.MemberLevelApi;
  5 +import cn.iocoder.yudao.module.member.api.level.dto.MemberLevelRespDTO;
  6 +import cn.iocoder.yudao.module.member.api.user.MemberUserApi;
  7 +import cn.iocoder.yudao.module.member.api.user.dto.MemberUserRespDTO;
  8 +import cn.iocoder.yudao.module.promotion.enums.common.PromotionTypeEnum;
  9 +import cn.iocoder.yudao.module.trade.enums.order.TradeOrderTypeEnum;
  10 +import cn.iocoder.yudao.module.trade.service.price.bo.TradePriceCalculateReqBO;
  11 +import cn.iocoder.yudao.module.trade.service.price.bo.TradePriceCalculateRespBO;
  12 +import org.springframework.core.annotation.Order;
  13 +import org.springframework.stereotype.Component;
  14 +
  15 +import javax.annotation.Resource;
  16 +
  17 +import static cn.iocoder.yudao.module.trade.service.price.calculator.TradePriceCalculatorHelper.formatPrice;
  18 +
  19 +/**
  20 + * 会员 VIP 折扣的 {@link TradePriceCalculator} 实现类
  21 + *
  22 + * @author 芋道源码
  23 + */
  24 +@Component
  25 +@Order(TradePriceCalculator.ORDER_MEMBER_LEVEL)
  26 +public class TradeMemberLevelPriceCalculator implements TradePriceCalculator {
  27 +
  28 + @Resource
  29 + private MemberLevelApi memberLevelApi;
  30 + @Resource
  31 + private MemberUserApi memberUserApi;
  32 +
  33 + @Override
  34 + public void calculate(TradePriceCalculateReqBO param, TradePriceCalculateRespBO result) {
  35 + // 0. 只有【普通】订单,才计算该优惠
  36 + if (ObjectUtil.notEqual(result.getType(), TradeOrderTypeEnum.NORMAL.getType())) {
  37 + return;
  38 + }
  39 + // 1. 获得用户的会员等级
  40 + MemberUserRespDTO user = memberUserApi.getUser(param.getUserId());
  41 + if (user.getLevelId() == null || user.getLevelId() <= 0) {
  42 + return;
  43 + }
  44 + MemberLevelRespDTO level = memberLevelApi.getMemberLevel(user.getLevelId());
  45 + if (level == null || level.getDiscountPercent() == null) {
  46 + return;
  47 + }
  48 +
  49 + // 2. 计算每个 SKU 的优惠金额
  50 + result.getItems().forEach(orderItem -> {
  51 + // 2.1 计算优惠金额
  52 + Integer vipPrice = calculateVipPrice(orderItem.getPayPrice(), level.getDiscountPercent());
  53 + if (vipPrice <= 0) {
  54 + return;
  55 + }
  56 +
  57 + // 2.2 记录优惠明细
  58 + if (orderItem.getSelected()) {
  59 + // 注意,只有在选中的情况下,才会记录到优惠明细。否则仅仅是更新 SKU 优惠金额,用于展示
  60 + TradePriceCalculatorHelper.addPromotion(result, orderItem,
  61 + level.getId(), level.getName(), PromotionTypeEnum.MEMBER_LEVEL.getType(),
  62 + String.format("会员等级折扣:省 %s 元", formatPrice(vipPrice)),
  63 + vipPrice);
  64 + }
  65 +
  66 + // 2.3 更新 SKU 的优惠金额
  67 + orderItem.setVipPrice(vipPrice);
  68 + TradePriceCalculatorHelper.recountPayPrice(orderItem);
  69 + });
  70 + TradePriceCalculatorHelper.recountAllPrice(result);
  71 + }
  72 +
  73 + /**
  74 + * 计算会员 VIP 优惠价格
  75 + *
  76 + * @param price 原价
  77 + * @param discountPercent 折扣
  78 + * @return 优惠价格
  79 + */
  80 + public Integer calculateVipPrice(Integer price, Integer discountPercent) {
  81 + if (discountPercent == null) {
  82 + return 0;
  83 + }
  84 + Integer newPrice = price * discountPercent / 100;
  85 + return price - newPrice;
  86 + }
  87 +
  88 +}
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/service/price/calculator/TradePointGiveCalculator.java 0 → 100644
  1 +package cn.iocoder.yudao.module.trade.service.price.calculator;
  2 +
  3 +import cn.hutool.core.util.BooleanUtil;
  4 +import cn.iocoder.yudao.framework.common.util.number.MoneyUtils;
  5 +import cn.iocoder.yudao.module.member.api.point.MemberPointApi;
  6 +import cn.iocoder.yudao.module.member.api.point.dto.MemberPointConfigRespDTO;
  7 +import cn.iocoder.yudao.module.trade.service.price.bo.TradePriceCalculateReqBO;
  8 +import cn.iocoder.yudao.module.trade.service.price.bo.TradePriceCalculateRespBO;
  9 +import lombok.extern.slf4j.Slf4j;
  10 +import org.springframework.core.annotation.Order;
  11 +import org.springframework.stereotype.Component;
  12 +
  13 +import javax.annotation.Resource;
  14 +import java.util.List;
  15 +import java.util.Optional;
  16 +
  17 +import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.filterList;
  18 +
  19 +/**
  20 + * 赠送积分的 {@link TradePriceCalculator} 实现类
  21 + *
  22 + * @author owen
  23 + */
  24 +@Component
  25 +@Order(TradePriceCalculator.ORDER_POINT_GIVE)
  26 +@Slf4j
  27 +public class TradePointGiveCalculator implements TradePriceCalculator {
  28 + @Resource
  29 + private MemberPointApi memberPointApi;
  30 +
  31 + @Override
  32 + public void calculate(TradePriceCalculateReqBO param, TradePriceCalculateRespBO result) {
  33 + // 1.1 校验积分功能是否开启
  34 + int givePointPerYuan = Optional.ofNullable(memberPointApi.getConfig())
  35 + .filter(config -> BooleanUtil.isTrue(config.getTradeDeductEnable()))
  36 + .map(MemberPointConfigRespDTO::getTradeGivePoint)
  37 + .orElse(0);
  38 + if (givePointPerYuan <= 0) {
  39 + return;
  40 + }
  41 + // 1.2 校验支付金额
  42 + if (result.getPrice().getPayPrice() <= 0) {
  43 + return;
  44 + }
  45 +
  46 + // 2.1 计算赠送积分
  47 + int givePoint = MoneyUtils.calculateRatePriceFloor(result.getPrice().getPayPrice(), (double) givePointPerYuan);
  48 + // 2.2 计算分摊的赠送积分
  49 + List<TradePriceCalculateRespBO.OrderItem> orderItems = filterList(result.getItems(), TradePriceCalculateRespBO.OrderItem::getSelected);
  50 + List<Integer> dividePoints = TradePriceCalculatorHelper.dividePrice(orderItems, givePoint);
  51 +
  52 + // 3.2 更新 SKU 赠送积分
  53 + for (int i = 0; i < orderItems.size(); i++) {
  54 + TradePriceCalculateRespBO.OrderItem orderItem = orderItems.get(i);
  55 + // 商品可能赠送了积分,所以这里要加上
  56 + orderItem.setGivePoint(orderItem.getGivePoint() + dividePoints.get(i));
  57 + TradePriceCalculatorHelper.recountPayPrice(orderItem);
  58 + }
  59 + // 3.3 更新订单赠送积分
  60 + TradePriceCalculatorHelper.recountAllGivePoint(result);
  61 + }
  62 +}
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/service/price/calculator/TradePointUsePriceCalculator.java 0 → 100644
  1 +package cn.iocoder.yudao.module.trade.service.price.calculator;
  2 +
  3 +import cn.hutool.core.util.BooleanUtil;
  4 +import cn.hutool.core.util.NumberUtil;
  5 +import cn.hutool.core.util.StrUtil;
  6 +import cn.iocoder.yudao.module.member.api.point.MemberPointApi;
  7 +import cn.iocoder.yudao.module.member.api.point.dto.MemberPointConfigRespDTO;
  8 +import cn.iocoder.yudao.module.member.api.user.MemberUserApi;
  9 +import cn.iocoder.yudao.module.member.api.user.dto.MemberUserRespDTO;
  10 +import cn.iocoder.yudao.module.promotion.enums.common.PromotionTypeEnum;
  11 +import cn.iocoder.yudao.module.trade.service.price.bo.TradePriceCalculateReqBO;
  12 +import cn.iocoder.yudao.module.trade.service.price.bo.TradePriceCalculateRespBO;
  13 +import lombok.extern.slf4j.Slf4j;
  14 +import org.springframework.core.annotation.Order;
  15 +import org.springframework.stereotype.Component;
  16 +
  17 +import javax.annotation.Resource;
  18 +import java.math.RoundingMode;
  19 +import java.util.List;
  20 +
  21 +import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.filterList;
  22 +
  23 +/**
  24 + * 使用积分的 {@link TradePriceCalculator} 实现类
  25 + *
  26 + * @author owen
  27 + */
  28 +@Component
  29 +@Order(TradePriceCalculator.ORDER_POINT_USE)
  30 +@Slf4j
  31 +public class TradePointUsePriceCalculator implements TradePriceCalculator {
  32 + @Resource
  33 + private MemberPointApi memberPointApi;
  34 + @Resource
  35 + private MemberUserApi memberUserApi;
  36 +
  37 + @Override
  38 + public void calculate(TradePriceCalculateReqBO param, TradePriceCalculateRespBO result) {
  39 + // 1.1 校验是否使用积分
  40 + if (!BooleanUtil.isTrue(param.getPointStatus())) {
  41 + result.setUsePoint(0);
  42 + return;
  43 + }
  44 + // 1.2 校验积分抵扣是否开启
  45 + MemberPointConfigRespDTO config = memberPointApi.getConfig();
  46 + if (!checkDeductPointEnable(config)) {
  47 + return;
  48 + }
  49 + // 1.3 校验用户积分余额
  50 + MemberUserRespDTO user = memberUserApi.getUser(param.getUserId());
  51 + if (user.getPoint() == null || user.getPoint() < 0) {
  52 + return;
  53 + }
  54 +
  55 + // 2.1 计算积分优惠金额
  56 + int pointPrice = calculatePointPrice(config, user.getPoint(), result);
  57 + // 2.1 计算分摊的积分、抵扣金额
  58 + List<TradePriceCalculateRespBO.OrderItem> orderItems = filterList(result.getItems(), TradePriceCalculateRespBO.OrderItem::getSelected);
  59 + List<Integer> dividePointPrices = TradePriceCalculatorHelper.dividePrice(orderItems, pointPrice);
  60 + List<Integer> divideUsePoints = TradePriceCalculatorHelper.dividePrice(orderItems, result.getUsePoint());
  61 +
  62 + // 3.1 记录优惠明细
  63 + TradePriceCalculatorHelper.addPromotion(result, orderItems,
  64 + param.getUserId(), "积分抵扣", PromotionTypeEnum.POINT.getType(),
  65 + StrUtil.format("积分抵扣:省 {} 元", TradePriceCalculatorHelper.formatPrice(pointPrice)),
  66 + dividePointPrices);
  67 + // 3.2 更新 SKU 优惠金额
  68 + for (int i = 0; i < orderItems.size(); i++) {
  69 + TradePriceCalculateRespBO.OrderItem orderItem = orderItems.get(i);
  70 + orderItem.setPointPrice(dividePointPrices.get(i));
  71 + orderItem.setUsePoint(divideUsePoints.get(i));
  72 + TradePriceCalculatorHelper.recountPayPrice(orderItem);
  73 + }
  74 + TradePriceCalculatorHelper.recountAllPrice(result);
  75 + }
  76 +
  77 + private boolean checkDeductPointEnable(MemberPointConfigRespDTO config) {
  78 + if (config == null) {
  79 + return false;
  80 + }
  81 + if (!BooleanUtil.isTrue(config.getTradeDeductEnable())) {
  82 + return false;
  83 + }
  84 +
  85 + // 有没有配置:1 积分抵扣多少分
  86 + return config.getTradeDeductUnitPrice() != null && config.getTradeDeductUnitPrice() > 0;
  87 + }
  88 +
  89 + private Integer calculatePointPrice(MemberPointConfigRespDTO config, Integer usePoint, TradePriceCalculateRespBO result) {
  90 + // 每个订单最多可以使用的积分数量
  91 + if (config.getTradeDeductMaxPrice() != null && config.getTradeDeductMaxPrice() > 0) {
  92 + usePoint = Math.min(usePoint, config.getTradeDeductMaxPrice());
  93 + }
  94 + // 积分优惠金额(分)
  95 + int pointPrice = usePoint * config.getTradeDeductUnitPrice();
  96 + // 0元购!!!:用户积分比较多时,积分可以抵扣的金额要大于支付金额, 这时需要根据支付金额反推使用多少积分
  97 + if (result.getPrice().getPayPrice() < pointPrice) {
  98 + pointPrice = result.getPrice().getPayPrice();
  99 + // 反推需要扣除的积分
  100 + usePoint = NumberUtil.toBigDecimal(pointPrice)
  101 + .divide(NumberUtil.toBigDecimal(config.getTradeDeductUnitPrice()), 0, RoundingMode.HALF_UP)
  102 + .intValue();
  103 + }
  104 + // 记录使用的积分
  105 + result.setUsePoint(usePoint);
  106 +
  107 + return pointPrice;
  108 + }
  109 +}
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/service/price/calculator/TradePriceCalculator.java
... ... @@ -6,19 +6,28 @@ import cn.iocoder.yudao.module.trade.service.price.bo.TradePriceCalculateRespBO;
6 6 /**
7 7 * 价格计算的计算器接口
8 8 *
  9 + * 优惠计算顺序:
  10 + * 1. <a href="https://help.youzan.com/displaylist/detail_4_4-1-53316">积分抵现、会员价、优惠券、粉丝专享价、满减送哪个优先计算?</>
  11 + *
9 12 * @author 芋道源码
10 13 */
11 14 public interface TradePriceCalculator {
12 15  
  16 + int ORDER_MEMBER_LEVEL = 5;
13 17 int ORDER_DISCOUNT_ACTIVITY = 10;
14 18 int ORDER_REWARD_ACTIVITY = 20;
15 19 int ORDER_COUPON = 30;
  20 + int ORDER_POINT_USE = 40;
16 21 /**
17 22 * 快递运费的计算
18 23 *
19 24 * 放在各种营销活动、优惠劵后面 TODO
20 25 */
21   - int ORDER_DELIVERY = 40;
  26 + int ORDER_DELIVERY = 50;
  27 + /**
  28 + * 赠送积分,放最后
  29 + */
  30 + int ORDER_POINT_GIVE = 999;
22 31  
23 32 void calculate(TradePriceCalculateReqBO param, TradePriceCalculateRespBO result);
24 33  
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/service/price/calculator/TradePriceCalculatorHelper.java
... ... @@ -4,6 +4,7 @@ import cn.hutool.core.lang.Assert;
4 4 import cn.iocoder.yudao.framework.common.util.collection.CollectionUtils;
5 5 import cn.iocoder.yudao.module.product.api.sku.dto.ProductSkuRespDTO;
6 6 import cn.iocoder.yudao.module.product.api.spu.dto.ProductSpuRespDTO;
  7 +import cn.iocoder.yudao.module.trade.enums.order.TradeOrderTypeEnum;
7 8 import cn.iocoder.yudao.module.trade.service.price.bo.TradePriceCalculateReqBO;
8 9 import cn.iocoder.yudao.module.trade.service.price.bo.TradePriceCalculateRespBO;
9 10  
... ... @@ -28,7 +29,7 @@ public class TradePriceCalculatorHelper {
28 29 List<ProductSpuRespDTO> spuList, List<ProductSkuRespDTO> skuList) {
29 30 // 创建 PriceCalculateRespDTO 对象
30 31 TradePriceCalculateRespBO result = new TradePriceCalculateRespBO();
31   - result.setType(param.getType());
  32 + result.setType(getOrderType(param));
32 33 result.setPromotions(new ArrayList<>());
33 34  
34 35 // 创建它的 OrderItem 属性
... ... @@ -51,13 +52,14 @@ public class TradePriceCalculatorHelper {
51 52 .setCount(item.getCount()).setCartId(item.getCartId()).setSelected(item.getSelected());
52 53 // sku 价格
53 54 orderItem.setPrice(sku.getPrice()).setPayPrice(sku.getPrice() * item.getCount())
54   - .setDiscountPrice(0).setDeliveryPrice(0).setCouponPrice(0).setPointPrice(0);
  55 + .setDiscountPrice(0).setDeliveryPrice(0).setCouponPrice(0).setPointPrice(0).setVipPrice(0);
55 56 // sku 信息
56 57 orderItem.setPicUrl(sku.getPicUrl()).setProperties(sku.getProperties())
57 58 .setWeight(sku.getWeight()).setVolume(sku.getVolume());
58 59 // spu 信息
59 60 orderItem.setSpuName(spu.getName()).setCategoryId(spu.getCategoryId())
60   - .setDeliveryTemplateId(spu.getDeliveryTemplateId());
  61 + .setDeliveryTemplateId(spu.getDeliveryTemplateId())
  62 + .setGivePoint(spu.getGiveIntegral()).setUsePoint(0);
61 63 if (orderItem.getPicUrl() == null) {
62 64 orderItem.setPicUrl(spu.getPicUrl());
63 65 }
... ... @@ -66,10 +68,28 @@ public class TradePriceCalculatorHelper {
66 68 // 创建它的 Price 属性
67 69 result.setPrice(new TradePriceCalculateRespBO.Price());
68 70 recountAllPrice(result);
  71 + recountAllGivePoint(result);
69 72 return result;
70 73 }
71 74  
72 75 /**
  76 + * 计算订单类型
  77 + *
  78 + * @param param 计算参数
  79 + * @return 订单类型
  80 + */
  81 + private static Integer getOrderType(TradePriceCalculateReqBO param) {
  82 + if (param.getSeckillActivityId() != null) {
  83 + return TradeOrderTypeEnum.SECKILL.getType();
  84 + }
  85 + if (param.getCombinationActivityId() != null) {
  86 + return TradeOrderTypeEnum.COMBINATION.getType();
  87 + }
  88 + // TODO 砍价敬请期待
  89 + return TradeOrderTypeEnum.NORMAL.getType();
  90 + }
  91 +
  92 + /**
73 93 * 基于订单项,重新计算 price 总价
74 94 *
75 95 * @param result 计算结果
... ... @@ -78,7 +98,7 @@ public class TradePriceCalculatorHelper {
78 98 // 先重置
79 99 TradePriceCalculateRespBO.Price price = result.getPrice();
80 100 price.setTotalPrice(0).setDiscountPrice(0).setDeliveryPrice(0)
81   - .setCouponPrice(0).setPointPrice(0).setPayPrice(0);
  101 + .setCouponPrice(0).setPointPrice(0).setVipPrice(0).setPayPrice(0);
82 102 // 再合计 item
83 103 result.getItems().forEach(item -> {
84 104 if (!item.getSelected()) {
... ... @@ -92,21 +112,33 @@ public class TradePriceCalculatorHelper {
92 112 price.setDeliveryPrice(price.getDeliveryPrice() + item.getDeliveryPrice());
93 113 price.setCouponPrice(price.getCouponPrice() + item.getCouponPrice());
94 114 price.setPointPrice(price.getPointPrice() + item.getPointPrice());
  115 + price.setVipPrice(price.getVipPrice() + item.getVipPrice());
95 116 price.setPayPrice(price.getPayPrice() + item.getPayPrice());
96 117 });
97 118 }
98 119  
99 120 /**
  121 + * 基于订单项,重新计算赠送积分
  122 + *
  123 + * @param result 计算结果
  124 + */
  125 + public static void recountAllGivePoint(TradePriceCalculateRespBO result) {
  126 + result.setGivePoint(getSumValue(result.getItems(), item -> item.getSelected() ? item.getGivePoint() : 0, Integer::sum));
  127 + }
  128 +
  129 + /**
100 130 * 重新计算单个订单项的支付金额
101 131 *
102 132 * @param orderItem 订单项
103 133 */
104 134 public static void recountPayPrice(TradePriceCalculateRespBO.OrderItem orderItem) {
105   - orderItem.setPayPrice(orderItem.getPrice()* orderItem.getCount()
  135 + orderItem.setPayPrice(orderItem.getPrice() * orderItem.getCount()
106 136 - orderItem.getDiscountPrice()
107 137 + orderItem.getDeliveryPrice()
108 138 - orderItem.getCouponPrice()
109   - - orderItem.getPointPrice());
  139 + - orderItem.getPointPrice()
  140 + - orderItem.getVipPrice()
  141 + );
110 142 }
111 143  
112 144 /**
... ... @@ -130,6 +162,15 @@ public class TradePriceCalculatorHelper {
130 162 if (orderItem.getPointPrice() == null) {
131 163 orderItem.setPointPrice(0);
132 164 }
  165 + if (orderItem.getUsePoint() == null) {
  166 + orderItem.setUsePoint(0);
  167 + }
  168 + if (orderItem.getGivePoint() == null) {
  169 + orderItem.setGivePoint(0);
  170 + }
  171 + if (orderItem.getVipPrice() == null) {
  172 + orderItem.setVipPrice(0);
  173 + }
133 174 recountPayPrice(orderItem);
134 175 });
135 176 }
... ... @@ -154,7 +195,7 @@ public class TradePriceCalculatorHelper {
154 195 */
155 196 public static Integer calculateTotalCount(List<TradePriceCalculateRespBO.OrderItem> orderItems) {
156 197 return getSumValue(orderItems,
157   - orderItem -> orderItem.getSelected() ? orderItem.getCount() : 0, // 未选中的情况下,不计算数量
  198 + orderItem -> orderItem.getSelected() ? orderItem.getCount() : 0, // 未选中的情况下,不计算数量
158 199 Integer::sum);
159 200 }
160 201  
... ... @@ -162,7 +203,7 @@ public class TradePriceCalculatorHelper {
162 203 * 按照支付金额,返回每个订单项的分摊金额数组
163 204 *
164 205 * @param orderItems 订单项数组
165   - * @param price 金额
  206 + * @param price 金额
166 207 * @return 分摊金额数组,和传入的 orderItems 一一对应
167 208 */
168 209 public static List<Integer> dividePrice(List<TradePriceCalculateRespBO.OrderItem> orderItems, Integer price) {
... ... @@ -195,12 +236,12 @@ public class TradePriceCalculatorHelper {
195 236 /**
196 237 * 添加【匹配】单个 OrderItem 的营销明细
197 238 *
198   - * @param result 价格计算结果
  239 + * @param result 价格计算结果
199 240 * @param orderItem 单个订单商品 SKU
200   - * @param id 营销编号
201   - * @param name 营销名字
202   - * @param description 满足条件的提示
203   - * @param type 营销类型
  241 + * @param id 营销编号
  242 + * @param name 营销名字
  243 + * @param description 满足条件的提示
  244 + * @param type 营销类型
204 245 * @param discountPrice 单个订单商品 SKU 的优惠价格(总)
205 246 */
206 247 public static void addPromotion(TradePriceCalculateRespBO result, TradePriceCalculateRespBO.OrderItem orderItem,
... ... @@ -211,7 +252,7 @@ public class TradePriceCalculatorHelper {
211 252 /**
212 253 * 添加【匹配】多个 OrderItem 的营销明细
213 254 *
214   - * @param result 价格计算结果
  255 + * @param result 价格计算结果
215 256 * @param orderItems 多个订单商品 SKU
216 257 * @param id 营销编号
217 258 * @param name 营销名字
... ... @@ -220,7 +261,7 @@ public class TradePriceCalculatorHelper {
220 261 * @param discountPrices 多个订单商品 SKU 的优惠价格(总),和 orderItems 一一对应
221 262 */
222 263 public static void addPromotion(TradePriceCalculateRespBO result, List<TradePriceCalculateRespBO.OrderItem> orderItems,
223   - Long id, String name, Integer type, String description, List<Integer> discountPrices) {
  264 + Long id, String name, Integer type, String description, List<Integer> discountPrices) {
224 265 // 创建营销明细 Item
225 266 List<TradePriceCalculateRespBO.PromotionItem> promotionItems = new ArrayList<>(discountPrices.size());
226 267 for (int i = 0; i < orderItems.size(); i++) {
... ... @@ -240,12 +281,12 @@ public class TradePriceCalculatorHelper {
240 281 /**
241 282 * 添加【不匹配】多个 OrderItem 的营销明细
242 283 *
243   - * @param result 价格计算结果
244   - * @param orderItems 多个订单商品 SKU
245   - * @param id 营销编号
246   - * @param name 营销名字
247   - * @param description 满足条件的提示
248   - * @param type 营销类型
  284 + * @param result 价格计算结果
  285 + * @param orderItems 多个订单商品 SKU
  286 + * @param id 营销编号
  287 + * @param name 营销名字
  288 + * @param description 满足条件的提示
  289 + * @param type 营销类型
249 290 */
250 291 public static void addNotMatchPromotion(TradePriceCalculateRespBO result, List<TradePriceCalculateRespBO.OrderItem> orderItems,
251 292 Long id, String name, Integer type, String description) {
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/java/cn/iocoder/yudao/module/trade/service/price/calculator/TradeRewardActivityPriceCalculator.java
1 1 package cn.iocoder.yudao.module.trade.service.price.calculator;
2 2  
3 3 import cn.hutool.core.collection.CollUtil;
  4 +import cn.hutool.core.util.ObjectUtil;
4 5 import cn.hutool.core.util.StrUtil;
5 6 import cn.iocoder.yudao.module.promotion.api.reward.RewardActivityApi;
6 7 import cn.iocoder.yudao.module.promotion.api.reward.dto.RewardActivityMatchRespDTO;
7 8 import cn.iocoder.yudao.module.promotion.enums.common.PromotionConditionTypeEnum;
8 9 import cn.iocoder.yudao.module.promotion.enums.common.PromotionTypeEnum;
  10 +import cn.iocoder.yudao.module.trade.enums.order.TradeOrderTypeEnum;
9 11 import cn.iocoder.yudao.module.trade.service.price.bo.TradePriceCalculateReqBO;
10 12 import cn.iocoder.yudao.module.trade.service.price.bo.TradePriceCalculateRespBO;
11 13 import org.springframework.core.annotation.Order;
... ... @@ -32,6 +34,10 @@ public class TradeRewardActivityPriceCalculator implements TradePriceCalculator
32 34  
33 35 @Override
34 36 public void calculate(TradePriceCalculateReqBO param, TradePriceCalculateRespBO result) {
  37 + // 0. 只有【普通】订单,才计算该优惠
  38 + if (ObjectUtil.notEqual(result.getType(), TradeOrderTypeEnum.NORMAL.getType())) {
  39 + return;
  40 + }
35 41 // 获得 SKU 对应的满减送活动
36 42 List<RewardActivityMatchRespDTO> rewardActivities = rewardActivityApi.getMatchRewardActivityList(
37 43 convertSet(result.getItems(), TradePriceCalculateRespBO.OrderItem::getSpuId));
... ...
yudao-module-mall/yudao-module-trade-biz/src/main/resources/mapper/brokerage/BrokerageUserMapper.xml 0 → 100644
  1 +<?xml version="1.0" encoding="UTF-8"?>
  2 +<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
  3 +<mapper namespace="cn.iocoder.yudao.module.trade.dal.mysql.brokerage.BrokerageUserMapper">
  4 +
  5 + <select id="selectSummaryPageByUserId"
  6 + resultType="cn.iocoder.yudao.module.trade.controller.app.brokerage.vo.user.AppBrokerageUserChildSummaryRespVO">
  7 + SELECT bu.id, bu.bind_user_time AS brokerageTime, u.nickname, u.avatar,
  8 + (SELECT SUM(price) FROM trade_brokerage_record r
  9 + WHERE r.user_id = u.id AND biz_type = 1 AND r.status = 1 AND r.deleted = FALSE) AS brokeragePrice,
  10 + (SELECT COUNT(1) FROM trade_brokerage_record r
  11 + WHERE r.user_id = u.id AND biz_type = 1 AND r.status = 1 AND r.deleted = FALSE) AS brokerageOrderCount,
  12 + (SELECT COUNT(1) FROM trade_brokerage_user c
  13 + WHERE c.bind_user_id = u.id AND c.deleted = FALSE) AS brokerageUserCount
  14 + FROM member_user AS u
  15 + JOIN trade_brokerage_user AS bu ON bu.id = u.id
  16 + <where>
  17 + <if test="param.nickname != null and param.nickname != ''">
  18 + AND u.nickname LIKE concat('', #{param.nickname}, '')
  19 + </if>
  20 + <if test="param.level == 1">
  21 + AND bu.bind_user_id = #{userId}
  22 + </if>
  23 + <if test="param.level == 2">
  24 + AND bu.bind_user_id IN (SELECT id FROM trade_brokerage_user c WHERE c.bind_user_id = #{userId})
  25 + </if>
  26 + </where>
  27 + <choose>
  28 + <when test="param.sortingField.field == 'userCount'">
  29 + ORDER BY brokerageUserCount ${param.sortingField.order}
  30 + </when>
  31 + <when test="param.sortingField.field == 'orderCount'">
  32 + ORDER BY brokerageOrderCount ${param.sortingField.order}
  33 + </when>
  34 + <when test="param.sortingField.field == 'price'">
  35 + ORDER BY brokeragePrice ${param.sortingField.order}
  36 + </when>
  37 + <otherwise>
  38 + ORDER BY bu.bind_user_time DESC
  39 + </otherwise>
  40 + </choose>
  41 + </select>
  42 +
  43 +</mapper>
... ...
yudao-module-mall/yudao-module-trade-biz/src/test/java/cn/iocoder/yudao/module/trade/service/brokerage/record/BrokerageRecordServiceImplTest.java renamed to yudao-module-mall/yudao-module-trade-biz/src/test/java/cn/iocoder/yudao/module/trade/service/brokerage/BrokerageRecordServiceImplTest.java
1   -package cn.iocoder.yudao.module.trade.service.brokerage.record;
  1 +package cn.iocoder.yudao.module.trade.service.brokerage;
2 2  
3 3 import cn.hutool.core.util.NumberUtil;
4 4 import cn.iocoder.yudao.framework.common.pojo.PageResult;
5 5 import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest;
6   -import cn.iocoder.yudao.module.trade.controller.admin.brokerage.record.vo.BrokerageRecordPageReqVO;
7   -import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.record.BrokerageRecordDO;
8   -import cn.iocoder.yudao.module.trade.dal.mysql.brokerage.record.BrokerageRecordMapper;
9   -import cn.iocoder.yudao.module.trade.service.brokerage.user.BrokerageUserService;
  6 +import cn.iocoder.yudao.module.trade.controller.admin.brokerage.vo.record.BrokerageRecordPageReqVO;
  7 +import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.BrokerageRecordDO;
  8 +import cn.iocoder.yudao.module.trade.dal.mysql.brokerage.BrokerageRecordMapper;
  9 +import cn.iocoder.yudao.module.trade.service.brokerage.BrokerageRecordServiceImpl;
  10 +import cn.iocoder.yudao.module.trade.service.brokerage.BrokerageUserService;
10 11 import cn.iocoder.yudao.module.trade.service.config.TradeConfigService;
11 12 import org.junit.jupiter.api.Disabled;
12 13 import org.junit.jupiter.api.Test;
... ...
yudao-module-mall/yudao-module-trade-biz/src/test/java/cn/iocoder/yudao/module/trade/service/brokerage/user/BrokerageUserServiceImplTest.java renamed to yudao-module-mall/yudao-module-trade-biz/src/test/java/cn/iocoder/yudao/module/trade/service/brokerage/BrokerageUserServiceImplTest.java
1   -package cn.iocoder.yudao.module.trade.service.brokerage.user;
  1 +package cn.iocoder.yudao.module.trade.service.brokerage;
2 2  
3 3 import cn.iocoder.yudao.framework.common.pojo.PageResult;
4 4 import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest;
5   -import cn.iocoder.yudao.module.trade.controller.admin.brokerage.user.vo.BrokerageUserPageReqVO;
6   -import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.user.BrokerageUserDO;
7   -import cn.iocoder.yudao.module.trade.dal.mysql.brokerage.user.BrokerageUserMapper;
  5 +import cn.iocoder.yudao.module.trade.controller.admin.brokerage.vo.user.BrokerageUserPageReqVO;
  6 +import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.BrokerageUserDO;
  7 +import cn.iocoder.yudao.module.trade.dal.mysql.brokerage.BrokerageUserMapper;
  8 +import cn.iocoder.yudao.module.trade.service.brokerage.BrokerageUserServiceImpl;
8 9 import org.junit.jupiter.api.Disabled;
9 10 import org.junit.jupiter.api.Test;
10 11 import org.springframework.context.annotation.Import;
... ...
yudao-module-mall/yudao-module-trade-biz/src/test/java/cn/iocoder/yudao/module/trade/service/withdraw/BrokerageWithdrawServiceImplTest.java renamed to yudao-module-mall/yudao-module-trade-biz/src/test/java/cn/iocoder/yudao/module/trade/service/brokerage/BrokerageWithdrawServiceImplTest.java
1   -package cn.iocoder.yudao.module.trade.service.withdraw;
  1 +package cn.iocoder.yudao.module.trade.service.brokerage;
2 2  
3 3 import cn.iocoder.yudao.framework.common.pojo.PageResult;
4 4 import cn.iocoder.yudao.framework.test.core.ut.BaseDbUnitTest;
5   -import cn.iocoder.yudao.module.trade.controller.admin.brokerage.withdraw.vo.BrokerageWithdrawPageReqVO;
6   -import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.withdraw.BrokerageWithdrawDO;
7   -import cn.iocoder.yudao.module.trade.dal.mysql.brokerage.withdraw.BrokerageWithdrawMapper;
8   -import cn.iocoder.yudao.module.trade.service.brokerage.withdraw.BrokerageWithdrawServiceImpl;
  5 +import cn.iocoder.yudao.module.system.api.notify.NotifyMessageSendApi;
  6 +import cn.iocoder.yudao.module.trade.controller.admin.brokerage.vo.withdraw.BrokerageWithdrawPageReqVO;
  7 +import cn.iocoder.yudao.module.trade.dal.dataobject.brokerage.BrokerageWithdrawDO;
  8 +import cn.iocoder.yudao.module.trade.dal.mysql.brokerage.BrokerageWithdrawMapper;
  9 +import cn.iocoder.yudao.module.trade.service.config.TradeConfigService;
9 10 import org.junit.jupiter.api.Disabled;
10 11 import org.junit.jupiter.api.Test;
  12 +import org.springframework.boot.test.mock.mockito.MockBean;
11 13 import org.springframework.context.annotation.Import;
12 14  
13 15 import javax.annotation.Resource;
  16 +import javax.validation.Validator;
14 17  
15 18 import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.buildBetweenTime;
16 19 import static cn.iocoder.yudao.framework.common.util.object.ObjectUtils.cloneIgnoreId;
... ... @@ -33,6 +36,19 @@ public class BrokerageWithdrawServiceImplTest extends BaseDbUnitTest {
33 36 @Resource
34 37 private BrokerageWithdrawMapper brokerageWithdrawMapper;
35 38  
  39 + @MockBean
  40 + private BrokerageRecordService brokerageRecordService;
  41 + @MockBean
  42 + private BrokerageUserService brokerageUserService;
  43 + @MockBean
  44 + private TradeConfigService tradeConfigService;
  45 +
  46 + @MockBean
  47 + private NotifyMessageSendApi notifyMessageSendApi;
  48 +
  49 + @Resource
  50 + private Validator validator;
  51 +
36 52 @Test
37 53 @Disabled // TODO 请修改 null 为需要的值,然后删除 @Disabled 注解
38 54 public void testGetBrokerageWithdrawPage() {
... ... @@ -85,4 +101,17 @@ public class BrokerageWithdrawServiceImplTest extends BaseDbUnitTest {
85 101 assertPojoEquals(dbBrokerageWithdraw, pageResult.getList().get(0));
86 102 }
87 103  
  104 + @Test
  105 + public void testCalculateFeePrice() {
  106 + Integer withdrawPrice = 100;
  107 + // 测试手续费比例未设置
  108 + Integer percent = null;
  109 + assertEquals(brokerageWithdrawService.calculateFeePrice(withdrawPrice, percent), 0);
  110 + // 测试手续费给为0
  111 + percent = 0;
  112 + assertEquals(brokerageWithdrawService.calculateFeePrice(withdrawPrice, percent), 0);
  113 + // 测试手续费
  114 + percent = 1;
  115 + assertEquals(brokerageWithdrawService.calculateFeePrice(withdrawPrice, percent), 1);
  116 + }
88 117 }
... ...
yudao-module-mall/yudao-module-trade-biz/src/test/java/cn/iocoder/yudao/module/trade/service/price/TradePriceServiceImplTest.java
... ... @@ -45,7 +45,7 @@ public class TradePriceServiceImplTest extends BaseMockitoUnitTest {
45 45 public void testCalculatePrice() {
46 46 // 准备参数
47 47 TradePriceCalculateReqBO calculateReqBO = new TradePriceCalculateReqBO()
48   - .setType(TradeOrderTypeEnum.NORMAL.getType()).setUserId(10L)
  48 + .setUserId(10L)
49 49 .setCouponId(20L).setAddressId(30L)
50 50 .setItems(Arrays.asList(
51 51 new TradePriceCalculateReqBO.Item().setSkuId(100L).setCount(1).setSelected(true),
... ...
yudao-module-mall/yudao-module-trade-biz/src/test/java/cn/iocoder/yudao/module/trade/service/price/calculator/TradeCouponPriceCalculatorTest.java
... ... @@ -7,6 +7,7 @@ import cn.iocoder.yudao.module.promotion.api.coupon.dto.CouponValidReqDTO;
7 7 import cn.iocoder.yudao.module.promotion.enums.common.PromotionDiscountTypeEnum;
8 8 import cn.iocoder.yudao.module.promotion.enums.common.PromotionProductScopeEnum;
9 9 import cn.iocoder.yudao.module.promotion.enums.common.PromotionTypeEnum;
  10 +import cn.iocoder.yudao.module.trade.enums.order.TradeOrderTypeEnum;
10 11 import cn.iocoder.yudao.module.trade.service.price.bo.TradePriceCalculateReqBO;
11 12 import cn.iocoder.yudao.module.trade.service.price.bo.TradePriceCalculateRespBO;
12 13 import org.junit.jupiter.api.Test;
... ... @@ -47,6 +48,7 @@ public class TradeCouponPriceCalculatorTest extends BaseMockitoUnitTest {
47 48 new TradePriceCalculateReqBO.Item().setSkuId(40L).setCount(5).setSelected(false) // 匹配优惠劵,但是未选中
48 49 ));
49 50 TradePriceCalculateRespBO result = new TradePriceCalculateRespBO()
  51 + .setType(TradeOrderTypeEnum.NORMAL.getType())
50 52 .setPrice(new TradePriceCalculateRespBO.Price())
51 53 .setPromotions(new ArrayList<>())
52 54 .setItems(asList(
... ...
yudao-module-mall/yudao-module-trade-biz/src/test/java/cn/iocoder/yudao/module/trade/service/price/calculator/TradeDeliveryPriceCalculatorTest.java
... ... @@ -4,8 +4,10 @@ import cn.hutool.core.map.MapUtil;
4 4 import cn.iocoder.yudao.framework.test.core.ut.BaseMockitoUnitTest;
5 5 import cn.iocoder.yudao.module.member.api.address.AddressApi;
6 6 import cn.iocoder.yudao.module.member.api.address.dto.AddressRespDTO;
  7 +import cn.iocoder.yudao.module.trade.dal.dataobject.config.TradeConfigDO;
7 8 import cn.iocoder.yudao.module.trade.enums.delivery.DeliveryExpressChargeModeEnum;
8 9 import cn.iocoder.yudao.module.trade.enums.delivery.DeliveryTypeEnum;
  10 +import cn.iocoder.yudao.module.trade.service.config.TradeConfigService;
9 11 import cn.iocoder.yudao.module.trade.service.delivery.DeliveryExpressTemplateService;
10 12 import cn.iocoder.yudao.module.trade.service.delivery.bo.DeliveryExpressTemplateRespBO;
11 13 import cn.iocoder.yudao.module.trade.service.price.bo.TradePriceCalculateReqBO;
... ... @@ -34,10 +36,14 @@ public class TradeDeliveryPriceCalculatorTest extends BaseMockitoUnitTest {
34 36  
35 37 @InjectMocks
36 38 private TradeDeliveryPriceCalculator calculator;
  39 +
37 40 @Mock
38 41 private AddressApi addressApi;
  42 +
39 43 @Mock
40 44 private DeliveryExpressTemplateService deliveryExpressTemplateService;
  45 + @Mock
  46 + private TradeConfigService tradeConfigService;
41 47  
42 48 private TradePriceCalculateReqBO reqBO;
43 49 private TradePriceCalculateRespBO resultBO;
... ... @@ -50,7 +56,7 @@ public class TradeDeliveryPriceCalculatorTest extends BaseMockitoUnitTest {
50 56 public void init(){
51 57 // 准备参数
52 58 reqBO = new TradePriceCalculateReqBO()
53   - .setDeliveryType(DeliveryTypeEnum.EXPRESS.getMode())
  59 + .setDeliveryType(DeliveryTypeEnum.EXPRESS.getType())
54 60 .setAddressId(10L)
55 61 .setUserId(1L)
56 62 .setItems(asList(
... ... @@ -85,13 +91,41 @@ public class TradeDeliveryPriceCalculatorTest extends BaseMockitoUnitTest {
85 91 item -> item.setFreeCount(20).setFreePrice(100));
86 92 // 准备 SP 运费模板数据
87 93 templateRespBO = randomPojo(DeliveryExpressTemplateRespBO.class,
88   - item -> item.setChargeMode(DeliveryExpressChargeModeEnum.PIECE.getType())
  94 + item -> item.setChargeMode(DeliveryExpressChargeModeEnum.COUNT.getType())
89 95 .setCharge(chargeBO).setFree(freeBO));
90 96 }
91 97  
92 98 @Test
  99 + @DisplayName("全场包邮")
  100 + public void testCalculate_expressGlobalFree() {
  101 + // mock 方法(全场包邮)
  102 + when(tradeConfigService.getTradeConfig()).thenReturn(new TradeConfigDO().setDeliveryExpressFreeEnabled(true)
  103 + .setDeliveryExpressFreePrice(2200));
  104 +
  105 + // 调用
  106 + calculator.calculate(reqBO, resultBO);
  107 + TradePriceCalculateRespBO.Price price = resultBO.getPrice();
  108 + assertThat(price)
  109 + .extracting("totalPrice","discountPrice","couponPrice","pointPrice","deliveryPrice","payPrice")
  110 + .containsExactly(2200, 0, 0, 0, 0, 2200);
  111 + assertThat(resultBO.getItems()).hasSize(3);
  112 + // 断言:SKU1
  113 + assertThat(resultBO.getItems().get(0))
  114 + .extracting("price", "count","discountPrice" ,"couponPrice", "pointPrice","deliveryPrice","payPrice")
  115 + .containsExactly(100, 2, 0, 0, 0, 0, 200);
  116 + // 断言:SKU2
  117 + assertThat(resultBO.getItems().get(1))
  118 + .extracting("price", "count","discountPrice" ,"couponPrice", "pointPrice","deliveryPrice","payPrice")
  119 + .containsExactly(200, 10, 0, 0, 0, 0, 2000);
  120 + // 断言:SKU3 未选中
  121 + assertThat(resultBO.getItems().get(2))
  122 + .extracting("price", "count","discountPrice" ,"couponPrice", "pointPrice","deliveryPrice","payPrice")
  123 + .containsExactly(300, 1, 0, 0, 0, 0, 300);
  124 + }
  125 +
  126 + @Test
93 127 @DisplayName("按件计算运费不包邮的情况")
94   - public void testCalculateByExpressTemplateCharge() {
  128 + public void testCalculate_expressTemplateCharge() {
95 129 // SKU 1 : 100 * 2 = 200
96 130 // SKU 2 :200 * 10 = 2000
97 131 // 运费 首件 1000 + 续件 2000 = 3000
... ... @@ -110,11 +144,11 @@ public class TradeDeliveryPriceCalculatorTest extends BaseMockitoUnitTest {
110 144 // 断言:SKU1
111 145 assertThat(resultBO.getItems().get(0))
112 146 .extracting("price", "count","discountPrice" ,"couponPrice", "pointPrice","deliveryPrice","payPrice")
113   - .containsExactly(100, 2, 0, 0, 0, 1500, 1700);
  147 + .containsExactly(100, 2, 0, 0, 0, 500, 700);
114 148 // 断言:SKU2
115 149 assertThat(resultBO.getItems().get(1))
116 150 .extracting("price", "count","discountPrice" ,"couponPrice", "pointPrice","deliveryPrice","payPrice")
117   - .containsExactly(200, 10, 0, 0, 0, 1500, 3500);
  151 + .containsExactly(200, 10, 0, 0, 0, 2500, 4500);
118 152 // 断言:SKU3 未选中
119 153 assertThat(resultBO.getItems().get(2))
120 154 .extracting("price", "count","discountPrice" ,"couponPrice", "pointPrice","deliveryPrice","payPrice")
... ... @@ -123,7 +157,7 @@ public class TradeDeliveryPriceCalculatorTest extends BaseMockitoUnitTest {
123 157  
124 158 @Test
125 159 @DisplayName("按件计算运费包邮的情况")
126   - public void testCalculateByExpressTemplateFree() {
  160 + public void testCalculate_expressTemplateFree() {
127 161 // SKU 1 : 100 * 2 = 200
128 162 // SKU 2 :200 * 10 = 2000
129 163 // 运费 0
... ...
yudao-module-mall/yudao-module-trade-biz/src/test/java/cn/iocoder/yudao/module/trade/service/price/calculator/TradeDiscountActivityPriceCalculatorTest.java
... ... @@ -5,6 +5,7 @@ import cn.iocoder.yudao.module.promotion.api.discount.DiscountActivityApi;
5 5 import cn.iocoder.yudao.module.promotion.api.discount.dto.DiscountProductRespDTO;
6 6 import cn.iocoder.yudao.module.promotion.enums.common.PromotionDiscountTypeEnum;
7 7 import cn.iocoder.yudao.module.promotion.enums.common.PromotionTypeEnum;
  8 +import cn.iocoder.yudao.module.trade.enums.order.TradeOrderTypeEnum;
8 9 import cn.iocoder.yudao.module.trade.service.price.bo.TradePriceCalculateReqBO;
9 10 import cn.iocoder.yudao.module.trade.service.price.bo.TradePriceCalculateRespBO;
10 11 import org.junit.jupiter.api.Test;
... ... @@ -42,6 +43,7 @@ public class TradeDiscountActivityPriceCalculatorTest extends BaseMockitoUnitTes
42 43 new TradePriceCalculateReqBO.Item().setSkuId(20L).setCount(3).setSelected(false) // 匹配活动,但未选中
43 44 ));
44 45 TradePriceCalculateRespBO result = new TradePriceCalculateRespBO()
  46 + .setType(TradeOrderTypeEnum.NORMAL.getType())
45 47 .setPrice(new TradePriceCalculateRespBO.Price())
46 48 .setPromotions(new ArrayList<>())
47 49 .setItems(asList(
... ...
yudao-module-mall/yudao-module-trade-biz/src/test/java/cn/iocoder/yudao/module/trade/service/price/calculator/TradeMemberLevelPriceCalculatorTest.java 0 → 100644
  1 +package cn.iocoder.yudao.module.trade.service.price.calculator;
  2 +
  3 +import cn.iocoder.yudao.framework.test.core.ut.BaseMockitoUnitTest;
  4 +import cn.iocoder.yudao.module.member.api.level.MemberLevelApi;
  5 +import cn.iocoder.yudao.module.member.api.level.dto.MemberLevelRespDTO;
  6 +import cn.iocoder.yudao.module.member.api.user.MemberUserApi;
  7 +import cn.iocoder.yudao.module.member.api.user.dto.MemberUserRespDTO;
  8 +import cn.iocoder.yudao.module.promotion.enums.common.PromotionTypeEnum;
  9 +import cn.iocoder.yudao.module.trade.enums.order.TradeOrderTypeEnum;
  10 +import cn.iocoder.yudao.module.trade.service.price.bo.TradePriceCalculateReqBO;
  11 +import cn.iocoder.yudao.module.trade.service.price.bo.TradePriceCalculateRespBO;
  12 +import org.junit.jupiter.api.Test;
  13 +import org.mockito.InjectMocks;
  14 +import org.mockito.Mock;
  15 +
  16 +import java.util.ArrayList;
  17 +
  18 +import static java.util.Arrays.asList;
  19 +import static org.junit.jupiter.api.Assertions.*;
  20 +import static org.mockito.ArgumentMatchers.eq;
  21 +import static org.mockito.Mockito.when;
  22 +
  23 +/**
  24 + * {@link TradeMemberLevelPriceCalculator} 的单元测试类
  25 + *
  26 + * @author 芋道源码
  27 + */
  28 +public class TradeMemberLevelPriceCalculatorTest extends BaseMockitoUnitTest {
  29 +
  30 + @InjectMocks
  31 + private TradeMemberLevelPriceCalculator memberLevelPriceCalculator;
  32 +
  33 + @Mock
  34 + private MemberLevelApi memberLevelApi;
  35 + @Mock
  36 + private MemberUserApi memberUserApi;
  37 +
  38 + @Test
  39 + public void testCalculate() {
  40 + // 准备参数
  41 + TradePriceCalculateReqBO param = new TradePriceCalculateReqBO()
  42 + .setUserId(1024L)
  43 + .setItems(asList(
  44 + new TradePriceCalculateReqBO.Item().setSkuId(10L).setCount(2).setSelected(true), // 匹配活动,且已选中
  45 + new TradePriceCalculateReqBO.Item().setSkuId(20L).setCount(3).setSelected(false) // 匹配活动,但未选中
  46 + ));
  47 + TradePriceCalculateRespBO result = new TradePriceCalculateRespBO()
  48 + .setType(TradeOrderTypeEnum.NORMAL.getType())
  49 + .setPrice(new TradePriceCalculateRespBO.Price())
  50 + .setPromotions(new ArrayList<>())
  51 + .setItems(asList(
  52 + new TradePriceCalculateRespBO.OrderItem().setSkuId(10L).setCount(2).setSelected(true)
  53 + .setPrice(100),
  54 + new TradePriceCalculateRespBO.OrderItem().setSkuId(20L).setCount(3).setSelected(false)
  55 + .setPrice(50)
  56 + ));
  57 + // 保证价格被初始化上
  58 + TradePriceCalculatorHelper.recountPayPrice(result.getItems());
  59 + TradePriceCalculatorHelper.recountAllPrice(result);
  60 +
  61 + // mock 方法(会员等级)
  62 + when(memberUserApi.getUser(eq(1024L))).thenReturn(new MemberUserRespDTO().setLevelId(2048L));
  63 + when(memberLevelApi.getMemberLevel(eq(2048L))).thenReturn(
  64 + new MemberLevelRespDTO().setId(2048L).setName("VIP 会员").setDiscountPercent(60));
  65 +
  66 + // 调用
  67 + memberLevelPriceCalculator.calculate(param, result);
  68 + // 断言:Price 部分
  69 + TradePriceCalculateRespBO.Price price = result.getPrice();
  70 + assertEquals(price.getTotalPrice(), 200);
  71 + assertEquals(price.getDiscountPrice(), 0);
  72 + assertEquals(price.getPointPrice(), 0);
  73 + assertEquals(price.getDeliveryPrice(), 0);
  74 + assertEquals(price.getCouponPrice(), 0);
  75 + assertEquals(price.getVipPrice(), 80);
  76 + assertEquals(price.getPayPrice(), 120);
  77 + assertNull(result.getCouponId());
  78 + // 断言:SKU 1
  79 + assertEquals(result.getItems().size(), 2);
  80 + TradePriceCalculateRespBO.OrderItem orderItem01 = result.getItems().get(0);
  81 + assertEquals(orderItem01.getSkuId(), 10L);
  82 + assertEquals(orderItem01.getCount(), 2);
  83 + assertEquals(orderItem01.getPrice(), 100);
  84 + assertEquals(orderItem01.getDiscountPrice(), 0);
  85 + assertEquals(orderItem01.getDeliveryPrice(), 0);
  86 + assertEquals(orderItem01.getCouponPrice(), 0);
  87 + assertEquals(orderItem01.getPointPrice(), 0);
  88 + assertEquals(orderItem01.getVipPrice(), 80);
  89 + assertEquals(orderItem01.getPayPrice(), 120);
  90 + // 断言:SKU 2
  91 + TradePriceCalculateRespBO.OrderItem orderItem02 = result.getItems().get(1);
  92 + assertEquals(orderItem02.getSkuId(), 20L);
  93 + assertEquals(orderItem02.getCount(), 3);
  94 + assertEquals(orderItem02.getPrice(), 50);
  95 + assertEquals(orderItem02.getDiscountPrice(), 0);
  96 + assertEquals(orderItem02.getDeliveryPrice(), 0);
  97 + assertEquals(orderItem02.getCouponPrice(), 0);
  98 + assertEquals(orderItem02.getPointPrice(), 0);
  99 + assertEquals(orderItem02.getVipPrice(), 60);
  100 + assertEquals(orderItem02.getPayPrice(), 90);
  101 + // 断言:Promotion 部分
  102 + assertEquals(result.getPromotions().size(), 1);
  103 + TradePriceCalculateRespBO.Promotion promotion01 = result.getPromotions().get(0);
  104 + assertEquals(promotion01.getId(), 2048L);
  105 + assertEquals(promotion01.getName(), "VIP 会员");
  106 + assertEquals(promotion01.getType(), PromotionTypeEnum.MEMBER_LEVEL.getType());
  107 + assertEquals(promotion01.getTotalPrice(), 200);
  108 + assertEquals(promotion01.getDiscountPrice(), 80);
  109 + assertTrue(promotion01.getMatch());
  110 + assertEquals(promotion01.getDescription(), "会员等级折扣:省 0.80 元");
  111 + TradePriceCalculateRespBO.PromotionItem promotionItem01 = promotion01.getItems().get(0);
  112 + assertEquals(promotion01.getItems().size(), 1);
  113 + assertEquals(promotionItem01.getSkuId(), 10L);
  114 + assertEquals(promotionItem01.getTotalPrice(), 200);
  115 + assertEquals(promotionItem01.getDiscountPrice(), 80);
  116 + }
  117 +
  118 +}
... ...
yudao-module-mall/yudao-module-trade-biz/src/test/java/cn/iocoder/yudao/module/trade/service/price/calculator/TradeRewardActivityPriceCalculatorTest.java
... ... @@ -5,6 +5,7 @@ import cn.iocoder.yudao.module.promotion.api.reward.RewardActivityApi;
5 5 import cn.iocoder.yudao.module.promotion.api.reward.dto.RewardActivityMatchRespDTO;
6 6 import cn.iocoder.yudao.module.promotion.enums.common.PromotionConditionTypeEnum;
7 7 import cn.iocoder.yudao.module.promotion.enums.common.PromotionTypeEnum;
  8 +import cn.iocoder.yudao.module.trade.enums.order.TradeOrderTypeEnum;
8 9 import cn.iocoder.yudao.module.trade.service.price.bo.TradePriceCalculateReqBO;
9 10 import cn.iocoder.yudao.module.trade.service.price.bo.TradePriceCalculateRespBO;
10 11 import org.junit.jupiter.api.Test;
... ... @@ -44,6 +45,7 @@ public class TradeRewardActivityPriceCalculatorTest extends BaseMockitoUnitTest
44 45 new TradePriceCalculateReqBO.Item().setSkuId(30L).setCount(4).setSelected(true) // 匹配活动 2
45 46 ));
46 47 TradePriceCalculateRespBO result = new TradePriceCalculateRespBO()
  48 + .setType(TradeOrderTypeEnum.NORMAL.getType())
47 49 .setPrice(new TradePriceCalculateRespBO.Price())
48 50 .setPromotions(new ArrayList<>())
49 51 .setItems(asList(
... ... @@ -157,6 +159,7 @@ public class TradeRewardActivityPriceCalculatorTest extends BaseMockitoUnitTest
157 159 new TradePriceCalculateReqBO.Item().setSkuId(30L).setCount(4).setSelected(true)
158 160 ));
159 161 TradePriceCalculateRespBO result = new TradePriceCalculateRespBO()
  162 + .setType(TradeOrderTypeEnum.NORMAL.getType())
160 163 .setPrice(new TradePriceCalculateRespBO.Price())
161 164 .setPromotions(new ArrayList<>())
162 165 .setItems(asList(
... ...
yudao-module-mall/yudao-module-trade-biz/src/test/resources/sql/create_tables.sql
... ... @@ -186,6 +186,6 @@ CREATE TABLE IF NOT EXISTS &quot;trade_brokerage_withdraw&quot;
186 186 "updater" varchar DEFAULT '',
187 187 "update_time" datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
188 188 "deleted" bit NOT NULL DEFAULT FALSE,
189   - "tenant_id" bigint not null default '0',目
  189 + "tenant_id" bigint not null default '0',
190 190 PRIMARY KEY ("id")
191 191 ) COMMENT '佣金提现';
192 192 \ No newline at end of file
... ...
yudao-module-member/yudao-module-member-api/pom.xml
... ... @@ -21,6 +21,13 @@
21 21 <groupId>cn.iocoder.boot</groupId>
22 22 <artifactId>yudao-common</artifactId>
23 23 </dependency>
  24 +
  25 + <!-- 参数校验 -->
  26 + <dependency>
  27 + <groupId>org.springframework.boot</groupId>
  28 + <artifactId>spring-boot-starter-validation</artifactId>
  29 + <optional>true</optional>
  30 + </dependency>
24 31 </dependencies>
25 32  
26 33 </project>
... ...
yudao-module-member/yudao-module-member-api/src/main/java/cn/iocoder/yudao/module/member/api/level/MemberLevelApi.java
1 1 package cn.iocoder.yudao.module.member.api.level;
2 2  
  3 +import cn.iocoder.yudao.module.member.api.level.dto.MemberLevelRespDTO;
3 4 import cn.iocoder.yudao.module.member.enums.MemberExperienceBizTypeEnum;
4 5  
5 6 /**
... ... @@ -10,6 +11,14 @@ import cn.iocoder.yudao.module.member.enums.MemberExperienceBizTypeEnum;
10 11 public interface MemberLevelApi {
11 12  
12 13 /**
  14 + * 获得会员等级
  15 + *
  16 + * @param id 会员等级编号
  17 + * @return 会员等级
  18 + */
  19 + MemberLevelRespDTO getMemberLevel(Long id);
  20 +
  21 + /**
13 22 * 增加会员经验
14 23 *
15 24 * @param userId 会员ID
... ...
yudao-module-member/yudao-module-member-api/src/main/java/cn/iocoder/yudao/module/member/api/level/dto/MemberLevelRespDTO.java 0 → 100644
  1 +package cn.iocoder.yudao.module.member.api.level.dto;
  2 +
  3 +import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
  4 +import lombok.Data;
  5 +
  6 +/**
  7 + * 会员等级 Resp DTO
  8 + *
  9 + * @author 芋道源码
  10 + */
  11 +@Data
  12 +public class MemberLevelRespDTO {
  13 +
  14 + /**
  15 + * 编号
  16 + */
  17 + private Long id;
  18 + /**
  19 + * 等级名称
  20 + */
  21 + private String name;
  22 + /**
  23 + * 等级
  24 + */
  25 + private Integer level;
  26 + /**
  27 + * 升级经验
  28 + */
  29 + private Integer experience;
  30 + /**
  31 + * 享受折扣
  32 + */
  33 + private Integer discountPercent;
  34 + /**
  35 + * 状态
  36 + *
  37 + * 枚举 {@link CommonStatusEnum}
  38 + */
  39 + private Integer status;
  40 +
  41 +}
... ...
yudao-module-member/yudao-module-member-api/src/main/java/cn/iocoder/yudao/module/member/api/point/MemberPointApi.java
1 1 package cn.iocoder.yudao.module.member.api.point;
2 2  
  3 +import cn.iocoder.yudao.module.member.api.point.dto.MemberPointConfigRespDTO;
3 4 import cn.iocoder.yudao.module.member.enums.point.MemberPointBizTypeEnum;
4 5  
  6 +import javax.validation.constraints.Min;
  7 +
5 8 /**
6 9 * 用户积分的 API 接口
7 10 *
... ... @@ -10,6 +13,13 @@ import cn.iocoder.yudao.module.member.enums.point.MemberPointBizTypeEnum;
10 13 public interface MemberPointApi {
11 14  
12 15 /**
  16 + * 获得积分配置
  17 + *
  18 + * @return 积分配置
  19 + */
  20 + MemberPointConfigRespDTO getConfig();
  21 +
  22 + /**
13 23 * 增加用户积分
14 24 *
15 25 * @param userId 用户编号
... ... @@ -17,6 +27,18 @@ public interface MemberPointApi {
17 27 * @param bizType 业务类型 {@link MemberPointBizTypeEnum}
18 28 * @param bizId 业务编号
19 29 */
20   - void addPoint(Long userId, Integer point, Integer bizType, String bizId);
  30 + void addPoint(Long userId, @Min(value = 1L, message = "积分必须是正数") Integer point,
  31 + Integer bizType, String bizId);
  32 +
  33 + /**
  34 + * 减少用户积分
  35 + *
  36 + * @param userId 用户编号
  37 + * @param point 积分
  38 + * @param bizType 业务类型 {@link MemberPointBizTypeEnum}
  39 + * @param bizId 业务编号
  40 + */
  41 + void reducePoint(Long userId, @Min(value = 1L, message = "积分必须是正数") Integer point,
  42 + Integer bizType, String bizId);
21 43  
22 44 }
... ...
yudao-module-member/yudao-module-member-api/src/main/java/cn/iocoder/yudao/module/member/api/point/dto/MemberPointConfigRespDTO.java 0 → 100644
  1 +package cn.iocoder.yudao.module.member.api.point.dto;
  2 +
  3 +import lombok.Data;
  4 +
  5 +/**
  6 + * 用户信息 Response DTO
  7 + *
  8 + * @author 芋道源码
  9 + */
  10 +@Data
  11 +public class MemberPointConfigRespDTO {
  12 + /**
  13 + * 积分抵扣开关
  14 + */
  15 + private Boolean tradeDeductEnable;
  16 + /**
  17 + * 积分抵扣,单位:分
  18 + * <p>
  19 + * 1 积分抵扣多少分
  20 + */
  21 + private Integer tradeDeductUnitPrice;
  22 + /**
  23 + * 积分抵扣最大值
  24 + */
  25 + private Integer tradeDeductMaxPrice;
  26 + /**
  27 + * 1 元赠送多少分
  28 + */
  29 + private Integer tradeGivePoint;
  30 +}
... ...
yudao-module-member/yudao-module-member-api/src/main/java/cn/iocoder/yudao/module/member/api/user/dto/MemberUserRespDTO.java
... ... @@ -3,6 +3,8 @@ package cn.iocoder.yudao.module.member.api.user.dto;
3 3 import cn.iocoder.yudao.framework.common.enums.CommonStatusEnum;
4 4 import lombok.Data;
5 5  
  6 +import java.time.LocalDateTime;
  7 +
6 8 /**
7 9 * 用户信息 Response DTO
8 10 *
... ... @@ -33,5 +35,20 @@ public class MemberUserRespDTO {
33 35 * 手机
34 36 */
35 37 private String mobile;
  38 + /**
  39 + * 创建时间(注册时间)
  40 + */
  41 + private LocalDateTime createTime;
36 42  
  43 + // ========== 其它信息 ==========
  44 +
  45 + /**
  46 + * 会员级别编号
  47 + */
  48 + private Long levelId;
  49 +
  50 + /**
  51 + * 积分
  52 + */
  53 + private Integer point;
37 54 }
... ...
yudao-module-member/yudao-module-member-api/src/main/java/cn/iocoder/yudao/module/member/enums/ErrorCodeConstants.java
... ... @@ -13,6 +13,7 @@ public interface ErrorCodeConstants {
13 13 ErrorCode USER_NOT_EXISTS = new ErrorCode(1004001000, "用户不存在");
14 14 ErrorCode USER_MOBILE_NOT_EXISTS = new ErrorCode(1004001001, "手机号未注册用户");
15 15 ErrorCode USER_MOBILE_USED = new ErrorCode(1004001002, "修改手机失败,该手机号({})已经被使用");
  16 + ErrorCode USER_POINT_NOT_ENOUGH = new ErrorCode(1004001003, "用户积分余额不足");
16 17  
17 18 // ========== AUTH 模块 1004003000 ==========
18 19 ErrorCode AUTH_LOGIN_BAD_CREDENTIALS = new ErrorCode(1004003000, "登录失败,账号密码不正确");
... ...
yudao-module-member/yudao-module-member-api/src/main/java/cn/iocoder/yudao/module/member/enums/point/MemberPointBizTypeEnum.java
... ... @@ -17,8 +17,12 @@ import java.util.Objects;
17 17 public enum MemberPointBizTypeEnum implements IntArrayValuable {
18 18  
19 19 SIGN(1, "签到", "签到获得 {} 积分", true),
20   - ORDER_BUY(10, "订单消费", "下单获得 {} 积分", true),
21   - ORDER_CANCEL(11, "订单取消", "退单获得 {} 积分", false); // 退回积分
  20 + ORDER_REWARD(10, "订单奖励", "下单获得 {} 积分", true),
  21 + ORDER_CANCEL(11, "订单取消", "订单取消,退还 {} 积分", true), // 退回积分
  22 + ORDER_USE(12, "订单使用", "下单使用 {} 积分", false), // 扣减积分
  23 + AFTER_SALE_REFUND_USED(13, "订单退款", "订单退款,退还 {} 积分", true), // 退回积分
  24 + AFTER_SALE_DEDUCT_GIVE(14, "订单退款", "订单退款,扣除赠送的 {} 积分", false), // 扣减积分
  25 + ;
22 26  
23 27 /**
24 28 * 类型
... ...
yudao-module-member/yudao-module-member-biz/src/main/java/cn/iocoder/yudao/module/member/api/level/MemberLevelApiImpl.java
1 1 package cn.iocoder.yudao.module.member.api.level;
2 2  
  3 +import cn.iocoder.yudao.module.member.api.level.dto.MemberLevelRespDTO;
  4 +import cn.iocoder.yudao.module.member.convert.level.MemberLevelConvert;
3 5 import cn.iocoder.yudao.module.member.enums.MemberExperienceBizTypeEnum;
4 6 import cn.iocoder.yudao.module.member.service.level.MemberLevelService;
5 7 import org.springframework.stereotype.Service;
... ... @@ -23,6 +25,11 @@ public class MemberLevelApiImpl implements MemberLevelApi {
23 25 private MemberLevelService memberLevelService;
24 26  
25 27 @Override
  28 + public MemberLevelRespDTO getMemberLevel(Long id) {
  29 + return MemberLevelConvert.INSTANCE.convert02(memberLevelService.getLevel(id));
  30 + }
  31 +
  32 + @Override
26 33 public void addExperience(Long userId, Integer experience, Integer bizType, String bizId) {
27 34 MemberExperienceBizTypeEnum bizTypeEnum = MemberExperienceBizTypeEnum.getByType(bizType);
28 35 if (bizTypeEnum == null) {
... ...
yudao-module-member/yudao-module-member-biz/src/main/java/cn/iocoder/yudao/module/member/api/point/MemberPointApiImpl.java
1 1 package cn.iocoder.yudao.module.member.api.point;
2 2  
  3 +import cn.hutool.core.lang.Assert;
  4 +import cn.iocoder.yudao.module.member.api.point.dto.MemberPointConfigRespDTO;
  5 +import cn.iocoder.yudao.module.member.convert.point.MemberPointConfigConvert;
3 6 import cn.iocoder.yudao.module.member.enums.point.MemberPointBizTypeEnum;
  7 +import cn.iocoder.yudao.module.member.service.point.MemberPointConfigService;
4 8 import cn.iocoder.yudao.module.member.service.point.MemberPointRecordService;
5 9 import org.springframework.stereotype.Service;
6 10 import org.springframework.validation.annotation.Validated;
... ... @@ -21,9 +25,17 @@ public class MemberPointApiImpl implements MemberPointApi {
21 25  
22 26 @Resource
23 27 private MemberPointRecordService memberPointRecordService;
  28 + @Resource
  29 + private MemberPointConfigService memberPointConfigService;
  30 +
  31 + @Override
  32 + public MemberPointConfigRespDTO getConfig() {
  33 + return MemberPointConfigConvert.INSTANCE.convert01(memberPointConfigService.getPointConfig());
  34 + }
24 35  
25 36 @Override
26 37 public void addPoint(Long userId, Integer point, Integer bizType, String bizId) {
  38 + Assert.isTrue(point > 0);
27 39 MemberPointBizTypeEnum bizTypeEnum = MemberPointBizTypeEnum.getByType(bizType);
28 40 if (bizTypeEnum == null) {
29 41 throw exception(POINT_RECORD_BIZ_NOT_SUPPORT);
... ... @@ -31,4 +43,14 @@ public class MemberPointApiImpl implements MemberPointApi {
31 43 memberPointRecordService.createPointRecord(userId, point, bizTypeEnum, bizId);
32 44 }
33 45  
  46 + @Override
  47 + public void reducePoint(Long userId, Integer point, Integer bizType, String bizId) {
  48 + Assert.isTrue(point > 0);
  49 + MemberPointBizTypeEnum bizTypeEnum = MemberPointBizTypeEnum.getByType(bizType);
  50 + if (bizTypeEnum == null) {
  51 + throw exception(POINT_RECORD_BIZ_NOT_SUPPORT);
  52 + }
  53 + memberPointRecordService.createPointRecord(userId, -point, bizTypeEnum, bizId);
  54 + }
  55 +
34 56 }
... ...
yudao-module-member/yudao-module-member-biz/src/main/java/cn/iocoder/yudao/module/member/convert/level/MemberLevelConvert.java
1 1 package cn.iocoder.yudao.module.member.convert.level;
2 2  
  3 +import cn.iocoder.yudao.module.member.api.level.dto.MemberLevelRespDTO;
3 4 import cn.iocoder.yudao.module.member.controller.admin.level.vo.level.MemberLevelCreateReqVO;
4 5 import cn.iocoder.yudao.module.member.controller.admin.level.vo.level.MemberLevelRespVO;
5 6 import cn.iocoder.yudao.module.member.controller.admin.level.vo.level.MemberLevelSimpleRespVO;
... ... @@ -33,4 +34,6 @@ public interface MemberLevelConvert {
33 34  
34 35 List<AppMemberLevelRespVO> convertList02(List<MemberLevelDO> list);
35 36  
  37 + MemberLevelRespDTO convert02(MemberLevelDO bean);
  38 +
36 39 }
... ...
yudao-module-member/yudao-module-member-biz/src/main/java/cn/iocoder/yudao/module/member/convert/point/MemberPointConfigConvert.java
1 1 package cn.iocoder.yudao.module.member.convert.point;
2 2  
  3 +import cn.iocoder.yudao.module.member.api.point.dto.MemberPointConfigRespDTO;
3 4 import cn.iocoder.yudao.module.member.controller.admin.point.vo.config.MemberPointConfigRespVO;
4 5 import cn.iocoder.yudao.module.member.controller.admin.point.vo.config.MemberPointConfigSaveReqVO;
5 6 import cn.iocoder.yudao.module.member.dal.dataobject.point.MemberPointConfigDO;
... ... @@ -20,4 +21,5 @@ public interface MemberPointConfigConvert {
20 21  
21 22 MemberPointConfigDO convert(MemberPointConfigSaveReqVO bean);
22 23  
  24 + MemberPointConfigRespDTO convert01(MemberPointConfigDO pointConfig);
23 25 }
... ...
yudao-module-member/yudao-module-member-biz/src/main/java/cn/iocoder/yudao/module/member/dal/mysql/user/MemberUserMapper.java
1 1 package cn.iocoder.yudao.module.member.dal.mysql.user;
2 2  
3 3 import cn.hutool.core.collection.CollUtil;
  4 +import cn.hutool.core.lang.Assert;
4 5 import cn.hutool.core.util.StrUtil;
5 6 import cn.iocoder.yudao.framework.common.pojo.PageResult;
6 7 import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
7 8 import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
8 9 import cn.iocoder.yudao.module.member.controller.admin.user.vo.MemberUserPageReqVO;
9 10 import cn.iocoder.yudao.module.member.dal.dataobject.user.MemberUserDO;
  11 +import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
10 12 import org.apache.ibatis.annotations.Mapper;
11 13  
12 14 import java.util.List;
... ... @@ -62,4 +64,33 @@ public interface MemberUserMapper extends BaseMapperX&lt;MemberUserDO&gt; {
62 64 .apply("FIND_IN_SET({0}, tag_ids)", tagId));
63 65 }
64 66  
  67 + /**
  68 + * 更新用户积分(增加)
  69 + *
  70 + * @param id 用户编号
  71 + * @param incrCount 增加积分(正数)
  72 + */
  73 + default void updatePointIncr(Long id, Integer incrCount) {
  74 + Assert.isTrue(incrCount > 0);
  75 + LambdaUpdateWrapper<MemberUserDO> lambdaUpdateWrapper = new LambdaUpdateWrapper<MemberUserDO>()
  76 + .setSql(" point = point + " + incrCount)
  77 + .eq(MemberUserDO::getId, id);
  78 + update(null, lambdaUpdateWrapper);
  79 + }
  80 +
  81 + /**
  82 + * 更新用户积分(减少)
  83 + *
  84 + * @param id 用户编号
  85 + * @param incrCount 增加积分(负数)
  86 + * @return 更新行数
  87 + */
  88 + default int updatePointDecr(Long id, Integer incrCount) {
  89 + Assert.isTrue(incrCount < 0);
  90 + LambdaUpdateWrapper<MemberUserDO> lambdaUpdateWrapper = new LambdaUpdateWrapper<MemberUserDO>()
  91 + .setSql(" point = point + " + incrCount) // 负数,所以使用 + 号
  92 + .eq(MemberUserDO::getId, id);
  93 + return update(null, lambdaUpdateWrapper);
  94 + }
  95 +
65 96 }
... ...
yudao-module-member/yudao-module-member-biz/src/main/java/cn/iocoder/yudao/module/member/service/point/MemberPointRecordServiceImpl.java
... ... @@ -5,7 +5,6 @@ import cn.hutool.core.util.StrUtil;
5 5 import cn.iocoder.yudao.framework.common.pojo.PageParam;
6 6 import cn.iocoder.yudao.framework.common.pojo.PageResult;
7 7 import cn.iocoder.yudao.module.member.controller.admin.point.vo.recrod.MemberPointRecordPageReqVO;
8   -import cn.iocoder.yudao.module.member.dal.dataobject.point.MemberPointConfigDO;
9 8 import cn.iocoder.yudao.module.member.dal.dataobject.point.MemberPointRecordDO;
10 9 import cn.iocoder.yudao.module.member.dal.dataobject.user.MemberUserDO;
11 10 import cn.iocoder.yudao.module.member.dal.mysql.point.MemberPointRecordMapper;
... ... @@ -14,6 +13,7 @@ import cn.iocoder.yudao.module.member.service.user.MemberUserService;
14 13 import lombok.extern.slf4j.Slf4j;
15 14 import org.apache.commons.lang3.StringUtils;
16 15 import org.springframework.stereotype.Service;
  16 +import org.springframework.transaction.annotation.Transactional;
17 17 import org.springframework.util.CollectionUtils;
18 18 import org.springframework.validation.annotation.Validated;
19 19  
... ... @@ -21,7 +21,9 @@ import javax.annotation.Resource;
21 21 import java.util.List;
22 22 import java.util.Set;
23 23  
  24 +import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
24 25 import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertSet;
  26 +import static cn.iocoder.yudao.module.member.enums.ErrorCodeConstants.USER_POINT_NOT_ENOUGH;
25 27  
26 28  
27 29 /**
... ... @@ -36,8 +38,6 @@ public class MemberPointRecordServiceImpl implements MemberPointRecordService {
36 38  
37 39 @Resource
38 40 private MemberPointRecordMapper memberPointRecordMapper;
39   - @Resource
40   - private MemberPointConfigService memberPointConfigService;
41 41  
42 42 @Resource
43 43 private MemberUserService memberUserService;
... ... @@ -64,32 +64,28 @@ public class MemberPointRecordServiceImpl implements MemberPointRecordService {
64 64 }
65 65  
66 66 @Override
  67 + @Transactional(rollbackFor = Exception.class)
67 68 public void createPointRecord(Long userId, Integer point, MemberPointBizTypeEnum bizType, String bizId) {
68   - MemberPointConfigDO pointConfig = memberPointConfigService.getPointConfig();
69   - if (pointConfig == null || pointConfig.getTradeGivePoint() == null) {
70   - log.error("[createPointRecord][增加积分失败:tradeGivePoint 未配置,userId({}) point({}) bizType({}) bizId({})]",
71   - userId, point, bizType.getType(), bizId);
72   - return;
  69 + // 1. 校验用户积分余额
  70 + MemberUserDO user = memberUserService.getUser(userId);
  71 + Integer userPoint = ObjectUtil.defaultIfNull(user.getPoint(), 0);
  72 + int totalPoint = userPoint + point; // 用户变动后的积分
  73 + if (totalPoint < 0) {
  74 + throw exception(USER_POINT_NOT_ENOUGH);
73 75 }
74 76  
75   - // 1. 根据配置的比例,换算实际的积分
76   - point = point * pointConfig.getTradeGivePoint();
77   - if (!bizType.isAdd() && point > 0) {
78   - point = -point;
  77 + // 2. 更新用户积分
  78 + boolean success = memberUserService.updateUserPoint(userId, point);
  79 + if (!success) {
  80 + throw exception(USER_POINT_NOT_ENOUGH);
79 81 }
80 82  
81   - // 2. 增加积分记录
82   - MemberUserDO user = memberUserService.getUser(userId);
83   - Integer userPoint = ObjectUtil.defaultIfNull(user.getPoint(), 0);
84   - Integer totalPoint = userPoint + point; // 用户变动后的积分
  83 + // 3. 增加积分记录
85 84 MemberPointRecordDO record = new MemberPointRecordDO()
86 85 .setUserId(userId).setBizId(bizId).setBizType(bizType.getType())
87 86 .setTitle(bizType.getName()).setDescription(StrUtil.format(bizType.getDescription(), point))
88 87 .setPoint(point).setTotalPoint(totalPoint);
89 88 memberPointRecordMapper.insert(record);
90   -
91   - // 3. 更新用户积分
92   - memberUserService.updateUserPoint(userId, totalPoint);
93 89 }
94 90  
95 91 }
... ...
yudao-module-member/yudao-module-member-biz/src/main/java/cn/iocoder/yudao/module/member/service/user/MemberUserService.java
... ... @@ -164,6 +164,7 @@ public interface MemberUserService {
164 164 *
165 165 * @param userId 用户编号
166 166 * @param point 积分数量
  167 + * @return 更新结果
167 168 */
168   - void updateUserPoint(Long userId, Integer point);
  169 + boolean updateUserPoint(Long userId, Integer point);
169 170 }
... ...
yudao-module-member/yudao-module-member-biz/src/main/java/cn/iocoder/yudao/module/member/service/user/MemberUserServiceImpl.java
... ... @@ -260,8 +260,13 @@ public class MemberUserServiceImpl implements MemberUserService {
260 260 }
261 261  
262 262 @Override
263   - public void updateUserPoint(Long userId, Integer point) {
264   - memberUserMapper.updateById(new MemberUserDO().setId(userId).setPoint(point));
  263 + public boolean updateUserPoint(Long id, Integer point) {
  264 + if (point > 0) {
  265 + memberUserMapper.updatePointIncr(id, point);
  266 + } else if (point < 0) {
  267 + return memberUserMapper.updatePointDecr(id, point) > 0;
  268 + }
  269 + return true;
265 270 }
266 271  
267 272 }
... ...
yudao-module-pay/yudao-module-pay-api/src/main/java/cn/iocoder/yudao/module/pay/enums/ErrorCodeConstants.java
... ... @@ -44,17 +44,21 @@ public interface ErrorCodeConstants {
44 44 ErrorCode WALLET_NOT_FOUND = new ErrorCode(1007007000, "用户钱包不存在");
45 45 ErrorCode WALLET_BALANCE_NOT_ENOUGH = new ErrorCode(1007007001, "钱包余额不足");
46 46 ErrorCode WALLET_TRANSACTION_NOT_FOUND = new ErrorCode(1007007002, "未找到对应的钱包交易");
47   - ErrorCode WALLET_REFUND_AMOUNT_ERROR = new ErrorCode(1007007003, "钱包退款金额不对");
48   - ErrorCode WALLET_REFUND_EXIST = new ErrorCode(1007007004, "已经存在钱包退款");
49   -
50   - // TODO @jason:把钱包充值,单独搞个错误码段哈;
51   -
52   - ErrorCode WALLET_RECHARGE_NOT_FOUND = new ErrorCode(1007007005, "钱包充值记录不存在");
53   - ErrorCode WALLET_RECHARGE_UPDATE_PAID_STATUS_NOT_UNPAID = new ErrorCode(1007007006, "钱包充值更新支付状态失败,钱包充值记录不是【未支付】状态");
54   - ErrorCode WALLET_RECHARGE_UPDATE_PAID_PAY_ORDER_ID_ERROR = new ErrorCode(1007007007, "钱包充值更新支付状态失败,支付单编号不匹配");
55   - ErrorCode WALLET_RECHARGE_UPDATE_PAID_PAY_ORDER_STATUS_NOT_SUCCESS = new ErrorCode(1007007008, "钱包充值更新支付状态失败,支付单状态不是【支付成功】状态");
56   - ErrorCode WALLET_RECHARGE_UPDATE_PAID_PAY_PRICE_NOT_MATCH = new ErrorCode(1007007009, "钱包充值更新支付状态失败,支付单金额不匹配");
  47 + ErrorCode WALLET_REFUND_EXIST = new ErrorCode(1007007003, "已经存在钱包退款");
  48 + ErrorCode WALLET_FREEZE_PRICE_NOT_ENOUGH = new ErrorCode(1007007004, "钱包冻结余额不足");
57 49  
  50 + // ========== 钱包充值模块 1007008000 ==========
  51 + ErrorCode WALLET_RECHARGE_NOT_FOUND = new ErrorCode(1007008000, "钱包充值记录不存在");
  52 + ErrorCode WALLET_RECHARGE_UPDATE_PAID_STATUS_NOT_UNPAID = new ErrorCode(1007008001, "钱包充值更新支付状态失败,钱包充值记录不是【未支付】状态");
  53 + ErrorCode WALLET_RECHARGE_UPDATE_PAID_PAY_ORDER_ID_ERROR = new ErrorCode(1007008002, "钱包充值更新支付状态失败,支付单编号不匹配");
  54 + ErrorCode WALLET_RECHARGE_UPDATE_PAID_PAY_ORDER_STATUS_NOT_SUCCESS = new ErrorCode(1007008003, "钱包充值更新支付状态失败,支付单状态不是【支付成功】状态");
  55 + ErrorCode WALLET_RECHARGE_UPDATE_PAID_PAY_PRICE_NOT_MATCH = new ErrorCode(1007008004, "钱包充值更新支付状态失败,支付单金额不匹配");
  56 + ErrorCode WALLET_RECHARGE_REFUND_FAIL_NOT_PAID = new ErrorCode(1007008005, "钱包发起退款失败,钱包充值订单未支付");
  57 + ErrorCode WALLET_RECHARGE_REFUND_FAIL_REFUNDED = new ErrorCode(1007008006, "钱包发起退款失败,钱包充值订单已退款");
  58 + ErrorCode WALLET_RECHARGE_REFUND_BALANCE_NOT_ENOUGH = new ErrorCode(1007008007, "钱包发起退款失败,钱包余额不足");
  59 + ErrorCode WALLET_RECHARGE_REFUND_FAIL_REFUND_ORDER_ID_ERROR = new ErrorCode(1007008008, "钱包退款更新失败,钱包退款单编号不匹配");
  60 + ErrorCode WALLET_RECHARGE_REFUND_FAIL_REFUND_NOT_FOUND = new ErrorCode(1007008009, "钱包退款更新失败,退款订单不存在");
  61 + ErrorCode WALLET_RECHARGE_REFUND_FAIL_REFUND_PRICE_NOT_MATCH = new ErrorCode(1007008010, "钱包退款更新失败,退款单金额不匹配");
58 62 // ========== 示例订单 1007900000 ==========
59 63 ErrorCode DEMO_ORDER_NOT_FOUND = new ErrorCode(1007900000, "示例订单不存在");
60 64 ErrorCode DEMO_ORDER_UPDATE_PAID_STATUS_NOT_UNPAID = new ErrorCode(1007900001, "示例订单更新支付状态失败,订单不是【未支付】状态");
... ...
yudao-module-pay/yudao-module-pay-biz/src/main/java/cn/iocoder/yudao/module/pay/controller/admin/wallet/PayWalletRechargeController.java 0 → 100644
  1 +package cn.iocoder.yudao.module.pay.controller.admin.wallet;
  2 +
  3 +import cn.iocoder.yudao.framework.common.pojo.CommonResult;
  4 +import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
  5 +import cn.iocoder.yudao.module.pay.api.notify.dto.PayRefundNotifyReqDTO;
  6 +import cn.iocoder.yudao.module.pay.service.wallet.PayWalletRechargeService;
  7 +import io.swagger.v3.oas.annotations.Operation;
  8 +import io.swagger.v3.oas.annotations.Parameter;
  9 +import io.swagger.v3.oas.annotations.tags.Tag;
  10 +import lombok.extern.slf4j.Slf4j;
  11 +import org.springframework.validation.annotation.Validated;
  12 +import org.springframework.web.bind.annotation.*;
  13 +
  14 +import javax.annotation.Resource;
  15 +import javax.annotation.security.PermitAll;
  16 +
  17 +import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
  18 +import static cn.iocoder.yudao.framework.common.util.servlet.ServletUtils.getClientIP;
  19 +
  20 +@Tag(name = "管理后台 - 钱包充值")
  21 +@RestController
  22 +@RequestMapping("/pay/wallet-recharge")
  23 +@Validated
  24 +@Slf4j
  25 +public class PayWalletRechargeController {
  26 +
  27 + @Resource
  28 + private PayWalletRechargeService walletRechargeService;
  29 +
  30 +
  31 + @GetMapping("/refund")
  32 + @Operation(summary = "发起钱包充值退款")
  33 + @Parameter(name = "id", description = "编号", required = true, example = "1024")
  34 + public CommonResult<Boolean> refundWalletRecharge(@RequestParam("id") Long id) {
  35 + walletRechargeService.refundWalletRecharge(id,getClientIP());
  36 + return success(true);
  37 + }
  38 +
  39 + @PostMapping("/update-refunded")
  40 + @Operation(summary = "更新钱包充值为已退款") // 由 pay-module 支付服务,进行回调,可见 PayNotifyJob
  41 + @PermitAll // 无需登录, 内部校验实现
  42 + @OperateLog(enable = false) // 禁用操作日志,因为没有操作人
  43 + public CommonResult<Boolean> updateWalletRechargeRefunded(@RequestBody PayRefundNotifyReqDTO notifyReqDTO) {
  44 + walletRechargeService.updateWalletRechargeRefunded(
  45 + Long.valueOf(notifyReqDTO.getMerchantOrderId()), notifyReqDTO.getPayRefundId());
  46 + return success(true);
  47 + }
  48 +}
... ...
yudao-module-pay/yudao-module-pay-biz/src/main/java/cn/iocoder/yudao/module/pay/controller/app/wallet/AppPayWalletRechargeController.java
... ... @@ -53,7 +53,4 @@ public class AppPayWalletRechargeController {
53 53 notifyReqDTO.getPayOrderId());
54 54 return success(true);
55 55 }
56   -
57   - // TODO @jason:管理后台,是不是可以搞个发起退款;
58   -
59 56 }
... ...
yudao-module-pay/yudao-module-pay-biz/src/main/java/cn/iocoder/yudao/module/pay/controller/app/wallet/vo/recharge/AppPayWalletRechargeCreateReqVO.java
... ... @@ -4,6 +4,7 @@ import io.swagger.v3.oas.annotations.media.Schema;
4 4 import lombok.Data;
5 5  
6 6 import javax.validation.constraints.DecimalMin;
  7 +import javax.validation.constraints.Min;
7 8 import javax.validation.constraints.NotNull;
8 9  
9 10 @Schema(description = "用户 APP - 创建钱包充值 Request VO")
... ... @@ -12,14 +13,14 @@ public class AppPayWalletRechargeCreateReqVO {
12 13  
13 14 @Schema(description = "支付金额", requiredMode = Schema.RequiredMode.REQUIRED, example = "1000")
14 15 @NotNull(message = "支付金额不能为空")
15   - // TODO @jason999:是不是 @Min 哈?
16   - @DecimalMin(value = "0", inclusive = false, message = "支付金额必须大于零")
  16 + @Min(value = 1, message = "支付金额必须大于零")
17 17 private Integer payPrice;
18 18  
19 19 // TODO @jason:这个是不是后端计算出来呀?不然前端可以直接搞了。。。
  20 + // TOTO 那是不是搞一个充值模板
20 21 @Schema(description = "钱包赠送金额", requiredMode = Schema.RequiredMode.REQUIRED, example = "1000")
21 22 @NotNull(message = "钱包赠送金额不能为空")
22 23 @DecimalMin(value = "0", message = "钱包赠送金额必须大于等于零")
23   - private Integer walletBonus;
  24 + private Integer bonusPrice;
24 25  
25 26 }
... ...
yudao-module-pay/yudao-module-pay-biz/src/main/java/cn/iocoder/yudao/module/pay/convert/wallet/PayWalletRechargeConvert.java
... ... @@ -4,6 +4,7 @@ import cn.iocoder.yudao.module.pay.controller.app.wallet.vo.recharge.AppPayWalle
4 4 import cn.iocoder.yudao.module.pay.controller.app.wallet.vo.recharge.AppPayWalletRechargeCreateRespVO;
5 5 import cn.iocoder.yudao.module.pay.dal.dataobject.wallet.PayWalletRechargeDO;
6 6 import org.mapstruct.Mapper;
  7 +import org.mapstruct.Mapping;
7 8 import org.mapstruct.factory.Mappers;
8 9  
9 10 /**
... ... @@ -14,14 +15,8 @@ public interface PayWalletRechargeConvert {
14 15  
15 16 PayWalletRechargeConvert INSTANCE = Mappers.getMapper(PayWalletRechargeConvert.class);
16 17  
17   - PayWalletRechargeDO convert(AppPayWalletRechargeCreateReqVO vo);
18   -
19   - // TODO @jason:好像 price 相加,可以写个表达式的,通过 @Mapping
20   - default PayWalletRechargeDO convert(Long walletId, AppPayWalletRechargeCreateReqVO vo) {
21   - PayWalletRechargeDO walletRecharge = convert(vo);
22   - return walletRecharge.setWalletId(walletId)
23   - .setPrice(walletRecharge.getPayPrice() + walletRecharge.getWalletBonus());
24   - }
  18 + @Mapping(target = "totalPrice", expression = "java(vo.getPayPrice() + vo.getBonusPrice() )")
  19 + PayWalletRechargeDO convert(Long walletId, AppPayWalletRechargeCreateReqVO vo);
25 20  
26 21 AppPayWalletRechargeCreateRespVO convert(PayWalletRechargeDO bean);
27 22  
... ...
yudao-module-pay/yudao-module-pay-biz/src/main/java/cn/iocoder/yudao/module/pay/dal/dataobject/wallet/PayWalletDO.java
... ... @@ -43,6 +43,11 @@ public class PayWalletDO extends BaseDO {
43 43 private Integer balance;
44 44  
45 45 /**
  46 + * 冻结金额,单位分
  47 + */
  48 + private Integer freezePrice;
  49 +
  50 + /**
46 51 * 累计支出,单位分
47 52 */
48 53 private Integer totalExpense;
... ...
yudao-module-pay/yudao-module-pay-biz/src/main/java/cn/iocoder/yudao/module/pay/dal/dataobject/wallet/PayWalletRechargeDO.java
... ... @@ -3,6 +3,7 @@ package cn.iocoder.yudao.module.pay.dal.dataobject.wallet;
3 3 import cn.iocoder.yudao.framework.mybatis.core.dataobject.BaseDO;
4 4 import cn.iocoder.yudao.module.pay.dal.dataobject.order.PayOrderDO;
5 5 import cn.iocoder.yudao.module.pay.dal.dataobject.refund.PayRefundDO;
  6 +import cn.iocoder.yudao.module.pay.enums.refund.PayRefundStatusEnum;
6 7 import com.baomidou.mybatisplus.annotation.KeySequence;
7 8 import com.baomidou.mybatisplus.annotation.TableId;
8 9 import com.baomidou.mybatisplus.annotation.TableName;
... ... @@ -31,22 +32,21 @@ public class PayWalletRechargeDO extends BaseDO {
31 32 */
32 33 private Long walletId;
33 34  
34   - // TODO @jason:要不改成 totalPrice?
35 35 /**
36 36 * 用户实际到账余额
37 37 *
38 38 * 例如充 100 送 20,则该值是 120
39 39 */
40   - private Integer price;
  40 + private Integer totalPrice;
41 41 /**
42 42 * 实际支付金额
43 43 */
44 44 private Integer payPrice;
45   - // TODO @jason:bonusPrice 哈,更统一一点;
  45 +
46 46 /**
47 47 * 钱包赠送金额
48 48 */
49   - private Integer walletBonus;
  49 + private Integer bonusPrice;
50 50  
51 51 /**
52 52 * 是否已支付
... ... @@ -62,6 +62,7 @@ public class PayWalletRechargeDO extends BaseDO {
62 62 * 关联 {@link PayOrderDO#getId()}
63 63 */
64 64 private Long payOrderId;
  65 +
65 66 /**
66 67 * 支付成功的支付渠道
67 68 *
... ... @@ -79,23 +80,31 @@ public class PayWalletRechargeDO extends BaseDO {
79 80 * 关联 {@link PayRefundDO#getId()}
80 81 */
81 82 private Long payRefundId;
82   - // TODO @jason:要不改成 refundTotalPrice?
  83 +
83 84 /**
84 85 * 退款金额,包含赠送金额
85 86 */
86   - private Integer refundPrice;
  87 + private Integer refundTotalPrice;
87 88 /**
88 89 * 退款支付金额
89 90 */
90 91 private Integer refundPayPrice;
91   - // TODO @jason:要不改成 refundBonusPrice?
  92 +
92 93 /**
93 94 * 退款钱包赠送金额
94 95 */
95   - private Integer refundWalletBonus;
  96 + private Integer refundBonusPrice;
  97 +
96 98 /**
97 99 * 退款时间
98 100 */
99 101 private LocalDateTime refundTime;
100 102  
  103 + /**
  104 + * 退款状态
  105 + *
  106 + * 枚举 {@link PayRefundStatusEnum}
  107 + */
  108 + private Integer refundStatus;
  109 +
101 110 }
... ...
yudao-module-pay/yudao-module-pay-biz/src/main/java/cn/iocoder/yudao/module/pay/dal/mysql/wallet/PayWalletMapper.java
... ... @@ -14,15 +14,13 @@ public interface PayWalletMapper extends BaseMapperX&lt;PayWalletDO&gt; {
14 14 PayWalletDO::getUserType, userType);
15 15 }
16 16  
17   - // TODO @jason:下面几个更新方法,把 id 放前面哈。一般来说,重要参数放前面;
18   -
19 17 /**
20 18 * 当消费退款时候, 更新钱包
21 19 *
22   - * @param price 消费金额
23 20 * @param id 钱包 id
  21 + * @param price 消费金额
24 22 */
25   - default int updateWhenConsumptionRefund(Integer price, Long id){
  23 + default int updateWhenConsumptionRefund(Long id, Integer price){
26 24 LambdaUpdateWrapper<PayWalletDO> lambdaUpdateWrapper = new LambdaUpdateWrapper<PayWalletDO>()
27 25 .setSql(" balance = balance + " + price
28 26 + ", total_expense = total_expense - " + price)
... ... @@ -36,7 +34,7 @@ public interface PayWalletMapper extends BaseMapperX&lt;PayWalletDO&gt; {
36 34 * @param price 消费金额
37 35 * @param id 钱包 id
38 36 */
39   - default int updateWhenConsumption(Integer price, Long id){
  37 + default int updateWhenConsumption(Long id, Integer price){
40 38 LambdaUpdateWrapper<PayWalletDO> lambdaUpdateWrapper = new LambdaUpdateWrapper<PayWalletDO>()
41 39 .setSql(" balance = balance - " + price
42 40 + ", total_expense = total_expense + " + price)
... ... @@ -47,17 +45,62 @@ public interface PayWalletMapper extends BaseMapperX&lt;PayWalletDO&gt; {
47 45  
48 46 /**
49 47 * 当充值的时候,更新钱包
50   - * @param price 钱包金额
  48 + *
51 49 * @param id 钱包 id
  50 + * @param price 钱包金额
52 51 */
53   - default int updateWhenRecharge(Integer price, Long id){
  52 + default int updateWhenRecharge(Long id, Integer price){
54 53 LambdaUpdateWrapper<PayWalletDO> lambdaUpdateWrapper = new LambdaUpdateWrapper<PayWalletDO>()
55 54 .setSql(" balance = balance + " + price
56 55 + ", total_recharge = total_recharge + " + price)
57 56 .eq(PayWalletDO::getId, id);
58 57 return update(null, lambdaUpdateWrapper);
59 58 }
60   -
  59 +
  60 + /**
  61 + * 冻结钱包部分余额
  62 + * @param id 钱包 id
  63 + * @param price 冻结金额
  64 + */
  65 + default int freezePrice(Long id, Integer price){
  66 + LambdaUpdateWrapper<PayWalletDO> lambdaUpdateWrapper = new LambdaUpdateWrapper<PayWalletDO>()
  67 + .setSql(" balance = balance - " + price
  68 + + ", freeze_price = freeze_price + " + price)
  69 + .eq(PayWalletDO::getId, id)
  70 + .ge(PayWalletDO::getBalance, price); // cas 逻辑
  71 + return update(null, lambdaUpdateWrapper);
  72 + }
  73 +
  74 + /**
  75 + * 解冻钱包余额
  76 + * @param id 钱包 id
  77 + * @param price 解冻金额
  78 + */
  79 + default int unFreezePrice(Long id, Integer price){
  80 + LambdaUpdateWrapper<PayWalletDO> lambdaUpdateWrapper = new LambdaUpdateWrapper<PayWalletDO>()
  81 + .setSql(" balance = balance + " + price
  82 + + ", freeze_price = freeze_price - " + price)
  83 + .eq(PayWalletDO::getId, id)
  84 + .ge(PayWalletDO::getFreezePrice, price); // cas 逻辑
  85 + return update(null, lambdaUpdateWrapper);
  86 + }
  87 +
  88 + /**
  89 + * 当充值退款时, 更新钱包
  90 + * @param id 钱包 id
  91 + * @param price 退款金额
  92 + */
  93 + default int updateWhenRechargeRefund(Long id, Integer price){
  94 + LambdaUpdateWrapper<PayWalletDO> lambdaUpdateWrapper = new LambdaUpdateWrapper<PayWalletDO>()
  95 + .setSql(" freeze_price = freeze_price - " + price
  96 + + ", total_recharge = total_recharge - " + price)
  97 + .eq(PayWalletDO::getId, id)
  98 + .ge(PayWalletDO::getFreezePrice, price)
  99 + .ge(PayWalletDO::getTotalRecharge, price);// cas 逻辑
  100 + return update(null, lambdaUpdateWrapper);
  101 + }
  102 +
  103 +
61 104 }
62 105  
63 106  
... ...
yudao-module-pay/yudao-module-pay-biz/src/main/java/cn/iocoder/yudao/module/pay/dal/mysql/wallet/PayWalletRechargeMapper.java
... ... @@ -13,6 +13,11 @@ public interface PayWalletRechargeMapper extends BaseMapperX&lt;PayWalletRechargeDO
13 13 .eq(PayWalletRechargeDO::getId, id).eq(PayWalletRechargeDO::getPayStatus, wherePayStatus));
14 14 }
15 15  
  16 + default int updateByIdAndRefunded(Long id, Integer whereRefundStatus, PayWalletRechargeDO updateObj){
  17 + return update(updateObj, new LambdaQueryWrapperX<PayWalletRechargeDO>()
  18 + .eq(PayWalletRechargeDO::getId, id).eq(PayWalletRechargeDO::getRefundStatus, whereRefundStatus));
  19 + }
  20 +
16 21 }
17 22  
18 23  
... ...
yudao-module-pay/yudao-module-pay-biz/src/main/java/cn/iocoder/yudao/module/pay/framework/pay/wallet/WalletPayClient.java
... ... @@ -8,6 +8,8 @@ import cn.iocoder.yudao.framework.pay.core.client.dto.order.PayOrderRespDTO;
8 8 import cn.iocoder.yudao.framework.pay.core.client.dto.order.PayOrderUnifiedReqDTO;
9 9 import cn.iocoder.yudao.framework.pay.core.client.dto.refund.PayRefundRespDTO;
10 10 import cn.iocoder.yudao.framework.pay.core.client.dto.refund.PayRefundUnifiedReqDTO;
  11 +import cn.iocoder.yudao.framework.pay.core.client.dto.transfer.PayTransferRespDTO;
  12 +import cn.iocoder.yudao.framework.pay.core.client.dto.transfer.PayTransferUnifiedReqDTO;
11 13 import cn.iocoder.yudao.framework.pay.core.client.impl.AbstractPayClient;
12 14 import cn.iocoder.yudao.framework.pay.core.client.impl.NonePayClientConfig;
13 15 import cn.iocoder.yudao.framework.pay.core.enums.channel.PayChannelEnum;
... ... @@ -174,4 +176,8 @@ public class WalletPayClient extends AbstractPayClient&lt;NonePayClientConfig&gt; {
174 176 throw new IllegalStateException(String.format("支付退款单[%s] 状态不正确", outRefundNo));
175 177 }
176 178  
  179 + @Override
  180 + public PayTransferRespDTO doUnifiedTransfer(PayTransferUnifiedReqDTO reqDTO) {
  181 + throw new UnsupportedOperationException("待实现");
  182 + }
177 183 }
... ...
yudao-module-pay/yudao-module-pay-biz/src/main/java/cn/iocoder/yudao/module/pay/service/wallet/PayWalletRechargeService.java
... ... @@ -29,4 +29,17 @@ public interface PayWalletRechargeService {
29 29 */
30 30 void updateWalletRechargerPaid(Long id, Long payOrderId);
31 31  
  32 + /**
  33 + * 发起钱包充值退款
  34 + * @param id 钱包充值编号
  35 + * @param userIp 用户 ip 地址
  36 + */
  37 + void refundWalletRecharge(Long id, String userIp);
  38 +
  39 + /**
  40 + * 更新钱包充值记录为已退款
  41 + * @param id 钱包充值 id
  42 + * @param payRefundId 退款单id
  43 + */
  44 + void updateWalletRechargeRefunded(Long id, Long payRefundId);
32 45 }
... ...
yudao-module-pay/yudao-module-pay-biz/src/main/java/cn/iocoder/yudao/module/pay/service/wallet/PayWalletRechargeServiceImpl.java
1 1 package cn.iocoder.yudao.module.pay.service.wallet;
2 2  
  3 +import cn.hutool.core.lang.Assert;
  4 +import cn.iocoder.yudao.framework.pay.core.enums.refund.PayRefundStatusRespEnum;
3 5 import cn.iocoder.yudao.module.pay.api.order.dto.PayOrderCreateReqDTO;
  6 +import cn.iocoder.yudao.module.pay.api.refund.dto.PayRefundCreateReqDTO;
4 7 import cn.iocoder.yudao.module.pay.controller.app.wallet.vo.recharge.AppPayWalletRechargeCreateReqVO;
5 8 import cn.iocoder.yudao.module.pay.convert.wallet.PayWalletRechargeConvert;
6 9 import cn.iocoder.yudao.module.pay.dal.dataobject.order.PayOrderDO;
  10 +import cn.iocoder.yudao.module.pay.dal.dataobject.refund.PayRefundDO;
7 11 import cn.iocoder.yudao.module.pay.dal.dataobject.wallet.PayWalletDO;
8 12 import cn.iocoder.yudao.module.pay.dal.dataobject.wallet.PayWalletRechargeDO;
9 13 import cn.iocoder.yudao.module.pay.dal.mysql.wallet.PayWalletRechargeMapper;
10 14 import cn.iocoder.yudao.module.pay.enums.member.PayWalletBizTypeEnum;
11 15 import cn.iocoder.yudao.module.pay.enums.order.PayOrderStatusEnum;
  16 +import cn.iocoder.yudao.module.pay.enums.refund.PayRefundStatusEnum;
12 17 import cn.iocoder.yudao.module.pay.service.order.PayOrderService;
  18 +import cn.iocoder.yudao.module.pay.service.refund.PayRefundService;
13 19 import lombok.extern.slf4j.Slf4j;
14 20 import org.springframework.stereotype.Service;
15 21 import org.springframework.transaction.annotation.Transactional;
... ... @@ -24,6 +30,7 @@ import static cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils.add
24 30 import static cn.iocoder.yudao.framework.common.util.json.JsonUtils.toJsonString;
25 31 import static cn.iocoder.yudao.framework.common.util.servlet.ServletUtils.getClientIP;
26 32 import static cn.iocoder.yudao.module.pay.enums.ErrorCodeConstants.*;
  33 +import static cn.iocoder.yudao.module.pay.enums.refund.PayRefundStatusEnum.*;
27 34  
28 35 /**
29 36 * 钱包充值 Service 实现类
... ... @@ -47,6 +54,8 @@ public class PayWalletRechargeServiceImpl implements PayWalletRechargeService {
47 54 private PayWalletService payWalletService;
48 55 @Resource
49 56 private PayOrderService payOrderService;
  57 + @Resource
  58 + private PayRefundService payRefundService;
50 59  
51 60 @Override
52 61 @Transactional(rollbackFor = Exception.class)
... ... @@ -66,8 +75,9 @@ public class PayWalletRechargeServiceImpl implements PayWalletRechargeService {
66 75 // 2.2 更新钱包充值记录中支付订单
67 76 walletRechargeMapper.updateById(new PayWalletRechargeDO().setPayOrderId(payOrderId)
68 77 .setId(walletRecharge.getId()));
69   - // TODO @jason:是不是你直接返回就好啦;然后 payOrderId 设置下;
70   - return walletRechargeMapper.selectById(walletRecharge.getId());
  78 +
  79 + walletRecharge.setPayOrderId(payOrderId);
  80 + return walletRecharge;
71 81 }
72 82  
73 83 @Override
... ... @@ -92,8 +102,116 @@ public class PayWalletRechargeServiceImpl implements PayWalletRechargeService {
92 102  
93 103 // 3. 更新钱包余额
94 104 // TODO @jason:这样的话,未来提现会不会把充值的,也提现走哈。类似先充 100,送 110;然后提现 110;
  105 + // TODO 需要钱包中加个可提现余额
95 106 payWalletService.addWalletBalance(walletRecharge.getWalletId(), String.valueOf(id),
96   - PayWalletBizTypeEnum.RECHARGE, walletRecharge.getPrice());
  107 + PayWalletBizTypeEnum.RECHARGE, walletRecharge.getTotalPrice());
  108 + }
  109 +
  110 + @Override
  111 + @Transactional(rollbackFor = Exception.class)
  112 + public void refundWalletRecharge(Long id, String userIp) {
  113 + // 1.1 获取钱包充值记录
  114 + PayWalletRechargeDO walletRecharge = walletRechargeMapper.selectById(id);
  115 + if (walletRecharge == null) {
  116 + log.error("[refundWalletRecharge][钱包充值记录不存在,钱包充值记录 id({})]", id);
  117 + throw exception(WALLET_RECHARGE_NOT_FOUND);
  118 + }
  119 + // 1.2 校验钱包充值是否可以发起退款
  120 + PayWalletDO wallet = validateWalletRechargeCanRefund(walletRecharge);
  121 + // 2 冻结退款的余额, 暂时只处理赠送的余额也全部退回
  122 + payWalletService.freezePrice(wallet.getId(), walletRecharge.getTotalPrice());
  123 + // 3 创建退款单
  124 + String walletRechargeId = String.valueOf(id);
  125 + String refundId = walletRechargeId + "-refund";
  126 + Long payRefundId = payRefundService.createPayRefund(new PayRefundCreateReqDTO()
  127 + .setAppId(WALLET_PAY_APP_ID).setUserIp(userIp)
  128 + .setMerchantOrderId(walletRechargeId)
  129 + .setMerchantRefundId(refundId)
  130 + .setReason("想退钱").setPrice(walletRecharge.getPayPrice()));
  131 + // 4 更新充值记录退款单号
  132 + walletRechargeMapper.updateById(new PayWalletRechargeDO().setPayRefundId(payRefundId)
  133 + .setRefundStatus(WAITING.getStatus()).setId(walletRecharge.getId()));
  134 + }
  135 +
  136 + @Override
  137 + @Transactional(rollbackFor = Exception.class)
  138 + public void updateWalletRechargeRefunded(Long id, Long payRefundId) {
  139 + // 1.1 获取钱包充值记录
  140 + PayWalletRechargeDO walletRecharge = walletRechargeMapper.selectById(id);
  141 + if (walletRecharge == null) {
  142 + log.error("[updateWalletRechargerPaid][钱包充值记录不存在,钱包充值记录 id({})]", id);
  143 + throw exception(WALLET_RECHARGE_NOT_FOUND);
  144 + }
  145 + // 1.2 校验钱包充值是否可以更新已退款
  146 + PayRefundDO payRefund = validateWalletRechargeCanRefunded(walletRecharge, payRefundId);
  147 +
  148 + PayWalletRechargeDO updateObj = new PayWalletRechargeDO().setId(id);
  149 + // 退款成功
  150 + if (PayRefundStatusEnum.isSuccess(payRefund.getStatus())) {
  151 + // 2.1 更新钱包余额
  152 + payWalletService.reduceWalletBalance(walletRecharge.getWalletId(), id,
  153 + PayWalletBizTypeEnum.RECHARGE_REFUND, walletRecharge.getTotalPrice());
  154 +
  155 + updateObj.setRefundStatus(SUCCESS.getStatus()).setRefundTime(payRefund.getSuccessTime())
  156 + .setRefundTotalPrice(walletRecharge.getTotalPrice()).setRefundPayPrice(walletRecharge.getPayPrice())
  157 + .setRefundBonusPrice(walletRecharge.getBonusPrice());
  158 + }
  159 + // 退款失败
  160 + if (PayRefundStatusRespEnum.isFailure(payRefund.getStatus())) {
  161 + // 2.2 解冻余额
  162 + payWalletService.unFreezePrice(walletRecharge.getWalletId(), walletRecharge.getTotalPrice());
  163 +
  164 + updateObj.setRefundStatus(FAILURE.getStatus());
  165 + }
  166 + // 3. 更新钱包充值的退款字段
  167 + walletRechargeMapper.updateByIdAndRefunded(id, WAITING.getStatus(), updateObj);
  168 + }
  169 +
  170 + private PayRefundDO validateWalletRechargeCanRefunded(PayWalletRechargeDO walletRecharge, Long payRefundId) {
  171 + // 1. 校验退款订单匹配
  172 + if (notEqual(walletRecharge.getPayRefundId(), payRefundId)) {
  173 + log.error("[validateWalletRechargeCanRefunded][钱包充值({}) 退款单不匹配({}),请进行处理!钱包充值的数据是:{}]",
  174 + walletRecharge.getId(), payRefundId, toJsonString(walletRecharge));
  175 + throw exception(WALLET_RECHARGE_REFUND_FAIL_REFUND_ORDER_ID_ERROR);
  176 + }
  177 +
  178 + // 2.1 校验退款订单
  179 + PayRefundDO payRefund = payRefundService.getRefund(payRefundId);
  180 + if (payRefund == null) {
  181 + log.error("[validateWalletRechargeCanRefunded][payRefund({})不存在]", payRefundId);
  182 + throw exception(WALLET_RECHARGE_REFUND_FAIL_REFUND_NOT_FOUND);
  183 + }
  184 + // 2.2 校验退款金额一致
  185 + if (notEqual(payRefund.getRefundPrice(), walletRecharge.getPayPrice())) {
  186 + log.error("[validateWalletRechargeCanRefunded][钱包({}) payRefund({}) 退款金额不匹配,请进行处理!钱包数据是:{},payRefund 数据是:{}]",
  187 + walletRecharge.getId(), payRefundId, toJsonString(walletRecharge), toJsonString(payRefund));
  188 + throw exception(WALLET_RECHARGE_REFUND_FAIL_REFUND_PRICE_NOT_MATCH);
  189 + }
  190 + // 2.3 校验退款订单商户订单是否匹配
  191 + if (notEqual(payRefund.getMerchantOrderId(), walletRecharge.getId().toString())) {
  192 + log.error("[validateWalletRechargeCanRefunded][钱包({}) 退款单不匹配({}),请进行处理!payRefund 数据是:{}]",
  193 + walletRecharge.getId(), payRefundId, toJsonString(payRefund));
  194 + throw exception(WALLET_RECHARGE_REFUND_FAIL_REFUND_ORDER_ID_ERROR);
  195 + }
  196 + return payRefund;
  197 + }
  198 +
  199 + private PayWalletDO validateWalletRechargeCanRefund(PayWalletRechargeDO walletRecharge) {
  200 + // 校验充值订单是否支付
  201 + if (!walletRecharge.getPayStatus()) {
  202 + throw exception(WALLET_RECHARGE_REFUND_FAIL_NOT_PAID);
  203 + }
  204 + // 校验充值订单是否已退款
  205 + if (walletRecharge.getPayRefundId() != null) {
  206 + throw exception(WALLET_RECHARGE_REFUND_FAIL_REFUNDED);
  207 + }
  208 + // 校验钱包余额是否足够
  209 + PayWalletDO wallet = payWalletService.getWallet(walletRecharge.getWalletId());
  210 + Assert.notNull(wallet, "用户钱包({}) 不存在", wallet.getId());
  211 + if (wallet.getBalance() < walletRecharge.getTotalPrice()) {
  212 + throw exception(WALLET_RECHARGE_REFUND_BALANCE_NOT_ENOUGH);
  213 + }
  214 + return wallet;
97 215 }
98 216  
99 217 private PayOrderDO validateWalletRechargerCanPaid(PayWalletRechargeDO walletRecharge, Long payOrderId) {
... ...
yudao-module-pay/yudao-module-pay-biz/src/main/java/cn/iocoder/yudao/module/pay/service/wallet/PayWalletService.java
... ... @@ -50,15 +50,14 @@ public interface PayWalletService {
50 50 /**
51 51 * 扣减钱包余额
52 52 *
53   - * @param userId 用户 id
54   - * @param userType 用户类型
  53 + * @param walletId 钱包 id
55 54 * @param bizId 业务关联 id
56 55 * @param bizType 业务关联分类
57 56 * @param price 扣减金额
58 57 * @return 钱包流水
59 58 */
60   - PayWalletTransactionDO reduceWalletBalance(Long userId, Integer userType,
61   - Long bizId, PayWalletBizTypeEnum bizType, Integer price);
  59 + PayWalletTransactionDO reduceWalletBalance(Long walletId, Long bizId,
  60 + PayWalletBizTypeEnum bizType, Integer price);
62 61  
63 62 /**
64 63 * 增加钱包余额
... ... @@ -72,4 +71,18 @@ public interface PayWalletService {
72 71 PayWalletTransactionDO addWalletBalance(Long walletId, String bizId,
73 72 PayWalletBizTypeEnum bizType, Integer price);
74 73  
  74 + /**
  75 + * 冻结钱包部分余额
  76 + *
  77 + * @param id 钱包编号
  78 + * @param price 冻结金额
  79 + */
  80 + void freezePrice(Long id, Integer price);
  81 +
  82 + /**
  83 + * 解冻钱包余额
  84 + * @param id 钱包编号
  85 + * @param price 解冻金额
  86 + */
  87 + void unFreezePrice(Long id, Integer price);
75 88 }
... ...
yudao-module-pay/yudao-module-pay-biz/src/main/java/cn/iocoder/yudao/module/pay/service/wallet/PayWalletServiceImpl.java
... ... @@ -68,8 +68,9 @@ public class PayWalletServiceImpl implements PayWalletService {
68 68 if (orderExtension == null) {
69 69 throw exception(PAY_ORDER_EXTENSION_NOT_FOUND);
70 70 }
  71 + PayWalletDO wallet = getOrCreateWallet(userId, userType);
71 72 // 2. 扣减余额
72   - return reduceWalletBalance(userId, userType, orderExtension.getOrderId(), PAYMENT, price);
  73 + return reduceWalletBalance(wallet.getId(), orderExtension.getOrderId(), PAYMENT, price);
73 74 }
74 75  
75 76 @Override
... ... @@ -81,7 +82,7 @@ public class PayWalletServiceImpl implements PayWalletService {
81 82 throw exception(REFUND_NOT_FOUND);
82 83 }
83 84 // 1.2 校验是否可以退款
84   - Long walletId = validateWalletCanRefund(payRefund.getId(), payRefund.getChannelOrderNo(), refundPrice);
  85 + Long walletId = validateWalletCanRefund(payRefund.getId(), payRefund.getChannelOrderNo());
85 86 PayWalletDO wallet = walletMapper.selectById(walletId);
86 87 Assert.notNull(wallet, "钱包 {} 不存在", walletId);
87 88  
... ... @@ -95,18 +96,12 @@ public class PayWalletServiceImpl implements PayWalletService {
95 96 * @param refundId 支付退款单 id
96 97 * @param walletPayNo 钱包支付 no
97 98 */
98   - private Long validateWalletCanRefund(Long refundId, String walletPayNo, Integer refundPrice) {
  99 + private Long validateWalletCanRefund(Long refundId, String walletPayNo) {
99 100 // 1. 校验钱包支付交易存在
100 101 PayWalletTransactionDO walletTransaction = walletTransactionService.getWalletTransactionByNo(walletPayNo);
101 102 if (walletTransaction == null) {
102 103 throw exception(WALLET_TRANSACTION_NOT_FOUND);
103 104 }
104   - // 原来的支付金额
105   - // TODO @jason:应该允许多次退款哈;
106   - int amount = - walletTransaction.getPrice();
107   - if (refundPrice != amount) {
108   - throw exception(WALLET_REFUND_AMOUNT_ERROR);
109   - }
110 105 PayWalletTransactionDO refundTransaction = walletTransactionService.getWalletTransaction(
111 106 String.valueOf(refundId), PAYMENT_REFUND);
112 107 if (refundTransaction != null) {
... ... @@ -116,22 +111,30 @@ public class PayWalletServiceImpl implements PayWalletService {
116 111 }
117 112  
118 113 @Override
119   - public PayWalletTransactionDO reduceWalletBalance(Long userId, Integer userType,
120   - Long bizId, PayWalletBizTypeEnum bizType, Integer price) {
  114 + public PayWalletTransactionDO reduceWalletBalance(Long walletId, Long bizId,
  115 + PayWalletBizTypeEnum bizType, Integer price) {
121 116 // 1. 获取钱包
122   - PayWalletDO payWallet = getOrCreateWallet(userId, userType);
  117 + PayWalletDO payWallet = getWallet(walletId);
  118 + if (payWallet == null) {
  119 + log.error("[reduceWalletBalance],用户钱包({})不存在.", walletId);
  120 + throw exception(WALLET_NOT_FOUND);
  121 + }
123 122  
124 123 // 2.1 扣除余额
125 124 int updateCounts = 0 ;
126 125 switch (bizType) {
127 126 case PAYMENT: {
128   - updateCounts = walletMapper.updateWhenConsumption(price, payWallet.getId());
  127 + updateCounts = walletMapper.updateWhenConsumption(payWallet.getId(), price);
129 128 break;
130 129 }
131 130 case RECHARGE_REFUND: {
132   - // TODO
  131 + updateCounts = walletMapper.updateWhenRechargeRefund(payWallet.getId(), price);
133 132 break;
134 133 }
  134 + default: {
  135 + // TODO 其它类型待实现
  136 + throw new UnsupportedOperationException("待实现");
  137 + }
135 138 }
136 139 if (updateCounts == 0) {
137 140 throw exception(WALLET_BALANCE_NOT_ENOUGH);
... ... @@ -156,14 +159,17 @@ public class PayWalletServiceImpl implements PayWalletService {
156 159 // 1.2 更新钱包金额
157 160 switch (bizType) {
158 161 case PAYMENT_REFUND: { // 退款更新
159   - walletMapper.updateWhenConsumptionRefund(price, payWallet.getId());
  162 + walletMapper.updateWhenConsumptionRefund(payWallet.getId(), price);
160 163 break;
161 164 }
162 165 case RECHARGE: { // 充值更新
163   - walletMapper.updateWhenRecharge(price, payWallet.getId());
  166 + walletMapper.updateWhenRecharge(payWallet.getId(), price);
164 167 break;
165 168 }
166   - // TODO 其它类型;这里可以先跑异常;避免有业务搞错;
  169 + default: {
  170 + // TODO 其它类型待实现
  171 + throw new UnsupportedOperationException("待实现");
  172 + }
167 173 }
168 174  
169 175 // 2. 生成钱包流水
... ... @@ -173,4 +179,20 @@ public class PayWalletServiceImpl implements PayWalletService {
173 179 return walletTransactionService.createWalletTransaction(transactionCreateReqBO);
174 180 }
175 181  
  182 + @Override
  183 + public void freezePrice(Long id, Integer price) {
  184 + int updateCounts = walletMapper.freezePrice(id, price);
  185 + if (updateCounts == 0) {
  186 + throw exception(WALLET_BALANCE_NOT_ENOUGH);
  187 + }
  188 + }
  189 +
  190 + @Override
  191 + public void unFreezePrice(Long id, Integer price) {
  192 + int updateCounts = walletMapper.unFreezePrice(id, price);
  193 + if (updateCounts == 0) {
  194 + throw exception(WALLET_FREEZE_PRICE_NOT_ENOUGH);
  195 + }
  196 + }
  197 +
176 198 }
... ...
yudao-module-system/yudao-module-system-api/src/main/java/cn/iocoder/yudao/module/system/api/dict/DictDataApi.java
... ... @@ -17,14 +17,14 @@ public interface DictDataApi {
17 17 * 2. 字典数据被禁用
18 18 *
19 19 * @param dictType 字典类型
20   - * @param values 字典数据值的数组
  20 + * @param values 字典数据值的数组
21 21 */
22 22 void validateDictDataList(String dictType, Collection<String> values);
23 23  
24 24 /**
25 25 * 获得指定的字典数据,从缓存中
26 26 *
27   - * @param type 字典类型
  27 + * @param type 字典类型
28 28 * @param value 字典数据值
29 29 * @return 字典数据
30 30 */
... ... @@ -33,7 +33,7 @@ public interface DictDataApi {
33 33 /**
34 34 * 解析获得指定的字典数据,从缓存中
35 35 *
36   - * @param type 字典类型
  36 + * @param type 字典类型
37 37 * @param label 字典数据标签
38 38 * @return 字典数据
39 39 */
... ...
yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/app/dict/AppDictDataController.java
1 1 package cn.iocoder.yudao.module.system.controller.app.dict;
2 2  
  3 +import cn.iocoder.yudao.framework.common.pojo.CommonResult;
  4 +import cn.iocoder.yudao.module.system.controller.app.dict.vo.AppDictDataRespVO;
  5 +import cn.iocoder.yudao.module.system.convert.dict.DictDataConvert;
  6 +import cn.iocoder.yudao.module.system.dal.dataobject.dict.DictDataDO;
  7 +import cn.iocoder.yudao.module.system.service.dict.DictDataService;
  8 +import io.swagger.v3.oas.annotations.Operation;
  9 +import io.swagger.v3.oas.annotations.Parameter;
  10 +import io.swagger.v3.oas.annotations.tags.Tag;
  11 +import org.springframework.validation.annotation.Validated;
  12 +import org.springframework.web.bind.annotation.GetMapping;
  13 +import org.springframework.web.bind.annotation.RequestMapping;
  14 +import org.springframework.web.bind.annotation.RequestParam;
  15 +import org.springframework.web.bind.annotation.RestController;
  16 +
  17 +import javax.annotation.Resource;
  18 +import java.util.List;
  19 +
  20 +import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
  21 +
  22 +@Tag(name = "用户 App - 字典数据")
  23 +@RestController
  24 +@RequestMapping("/system/dict-data")
  25 +@Validated
3 26 public class AppDictDataController {
  27 +
  28 + @Resource
  29 + private DictDataService dictDataService;
  30 +
  31 + @GetMapping("/type")
  32 + @Operation(summary = "根据字典类型查询字典数据信息")
  33 + @Parameter(name = "type", description = "字典类型", required = true, example = "common_status")
  34 + public CommonResult<List<AppDictDataRespVO>> getDictDataListByType(@RequestParam("type") String type) {
  35 + List<DictDataDO> list = dictDataService.getEnabledDictDataListByType(type);
  36 + return success(DictDataConvert.INSTANCE.convertList03(list));
  37 + }
  38 +
4 39 }
... ...
yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/controller/app/dict/vo/AppDictDataRespVO.java 0 → 100644
  1 +package cn.iocoder.yudao.module.system.controller.app.dict.vo;
  2 +
  3 +import io.swagger.v3.oas.annotations.media.Schema;
  4 +import lombok.AllArgsConstructor;
  5 +import lombok.Data;
  6 +import lombok.NoArgsConstructor;
  7 +
  8 +import javax.validation.constraints.NotBlank;
  9 +import javax.validation.constraints.Size;
  10 +
  11 +@Schema(description = "用户 App - 字典数据信息 Response VO")
  12 +@Data
  13 +@NoArgsConstructor
  14 +@AllArgsConstructor
  15 +public class AppDictDataRespVO {
  16 +
  17 + @Schema(description = "字典数据编号", requiredMode = Schema.RequiredMode.REQUIRED, example = "1024")
  18 + private Long id;
  19 +
  20 + @Schema(description = "字典标签", requiredMode = Schema.RequiredMode.REQUIRED, example = "芋道")
  21 + private String label;
  22 +
  23 + @Schema(description = "字典值", requiredMode = Schema.RequiredMode.REQUIRED, example = "iocoder")
  24 + private String value;
  25 +
  26 + @Schema(description = "字典类型", requiredMode = Schema.RequiredMode.REQUIRED, example = "sys_common_sex")
  27 + private String dictType;
  28 +
  29 +}
... ...
yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/convert/dict/DictDataConvert.java
... ... @@ -3,11 +3,11 @@ package cn.iocoder.yudao.module.system.convert.dict;
3 3 import cn.iocoder.yudao.framework.common.pojo.PageResult;
4 4 import cn.iocoder.yudao.module.system.api.dict.dto.DictDataRespDTO;
5 5 import cn.iocoder.yudao.module.system.controller.admin.dict.vo.data.*;
  6 +import cn.iocoder.yudao.module.system.controller.app.dict.vo.AppDictDataRespVO;
6 7 import cn.iocoder.yudao.module.system.dal.dataobject.dict.DictDataDO;
7 8 import org.mapstruct.Mapper;
8 9 import org.mapstruct.factory.Mappers;
9 10  
10   -import java.util.Collection;
11 11 import java.util.List;
12 12  
13 13 @Mapper
... ... @@ -29,4 +29,7 @@ public interface DictDataConvert {
29 29  
30 30 DictDataRespDTO convert02(DictDataDO bean);
31 31  
  32 + List<AppDictDataRespVO> convertList03(List<DictDataDO> list);
  33 +
  34 + List<DictDataRespDTO> convertList04(List<DictDataDO> list);
32 35 }
... ...
yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/dal/mysql/dict/DictDataMapper.java
... ... @@ -48,4 +48,10 @@ public interface DictDataMapper extends BaseMapperX&lt;DictDataDO&gt; {
48 48 .eqIfPresent(DictDataDO::getStatus, reqVO.getStatus()));
49 49 }
50 50  
  51 + default List<DictDataDO> selectListByTypeAndStatus(String dictType, Integer status) {
  52 + return selectList(new LambdaQueryWrapper<DictDataDO>()
  53 + .eq(DictDataDO::getDictType, dictType)
  54 + .eq(DictDataDO::getStatus, status));
  55 + }
  56 +
51 57 }
... ...
yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/dict/DictDataService.java
... ... @@ -63,6 +63,14 @@ public interface DictDataService {
63 63 List<DictDataDO> getDictDataList(DictDataExportReqVO reqVO);
64 64  
65 65 /**
  66 + * 获得字典数据列表
  67 + *
  68 + * @param dictType 字典类型
  69 + * @return 字典数据列表
  70 + */
  71 + List<DictDataDO> getEnabledDictDataListByType(String dictType);
  72 +
  73 + /**
66 74 * 获得字典数据详情
67 75 *
68 76 * @param id 字典数据编号
... ... @@ -84,7 +92,7 @@ public interface DictDataService {
84 92 * 2. 字典数据被禁用
85 93 *
86 94 * @param dictType 字典类型
87   - * @param values 字典数据值的数组
  95 + * @param values 字典数据值的数组
88 96 */
89 97 void validateDictDataList(String dictType, Collection<String> values);
90 98  
... ... @@ -92,7 +100,7 @@ public interface DictDataService {
92 100 * 获得指定的字典数据
93 101 *
94 102 * @param dictType 字典类型
95   - * @param value 字典数据值
  103 + * @param value 字典数据值
96 104 * @return 字典数据
97 105 */
98 106 DictDataDO getDictData(String dictType, String value);
... ... @@ -101,7 +109,7 @@ public interface DictDataService {
101 109 * 解析获得指定的字典数据,从缓存中
102 110 *
103 111 * @param dictType 字典类型
104   - * @param label 字典数据标签
  112 + * @param label 字典数据标签
105 113 * @return 字典数据
106 114 */
107 115 DictDataDO parseDictData(String dictType, String label);
... ...
yudao-module-system/yudao-module-system-biz/src/main/java/cn/iocoder/yudao/module/system/service/dict/DictDataServiceImpl.java
... ... @@ -49,7 +49,7 @@ public class DictDataServiceImpl implements DictDataService {
49 49  
50 50 @Override
51 51 public List<DictDataDO> getDictDataList() {
52   - List<DictDataDO> list = dictDataMapper.selectList();
  52 + List<DictDataDO> list = dictDataMapper.selectList(DictDataDO::getStatus, CommonStatusEnum.ENABLE.getStatus());
53 53 list.sort(COMPARATOR_TYPE_AND_SORT);
54 54 return list;
55 55 }
... ... @@ -67,6 +67,13 @@ public class DictDataServiceImpl implements DictDataService {
67 67 }
68 68  
69 69 @Override
  70 + public List<DictDataDO> getEnabledDictDataListByType(String dictType) {
  71 + List<DictDataDO> list = dictDataMapper.selectListByTypeAndStatus(dictType, CommonStatusEnum.ENABLE.getStatus());
  72 + list.sort(COMPARATOR_TYPE_AND_SORT);
  73 + return list;
  74 + }
  75 +
  76 + @Override
70 77 public DictDataDO getDictData(Long id) {
71 78 return dictDataMapper.selectById(id);
72 79 }
... ...
yudao-module-system/yudao-module-system-biz/src/test/java/cn/iocoder/yudao/module/system/service/dict/DictDataServiceImplTest.java
... ... @@ -43,10 +43,15 @@ public class DictDataServiceImplTest extends BaseDbUnitTest {
43 43 @Test
44 44 public void testGetDictDataList() {
45 45 // mock 数据
46   - DictDataDO dictDataDO01 = randomDictDataDO().setDictType("yunai").setSort(2);
  46 + DictDataDO dictDataDO01 = randomDictDataDO().setDictType("yunai").setSort(2)
  47 + .setStatus(CommonStatusEnum.ENABLE.getStatus());
47 48 dictDataMapper.insert(dictDataDO01);
48   - DictDataDO dictDataDO02 = randomDictDataDO().setDictType("yunai").setSort(1);
  49 + DictDataDO dictDataDO02 = randomDictDataDO().setDictType("yunai").setSort(1)
  50 + .setStatus(CommonStatusEnum.ENABLE.getStatus());
49 51 dictDataMapper.insert(dictDataDO02);
  52 + DictDataDO dictDataDO03 = randomDictDataDO().setDictType("yunai").setSort(3)
  53 + .setStatus(CommonStatusEnum.DISABLE.getStatus());
  54 + dictDataMapper.insert(dictDataDO03);
50 55 // 准备参数
51 56  
52 57 // 调用
... ...