Merge remote-tracking branch 'origin/master' into feature/auth

# Conflicts:
#	yudao-dependencies/pom.xml
This commit is contained in:
xingyu
2023-09-13 12:00:10 +08:00
616 changed files with 4821 additions and 46941 deletions

View File

@ -31,4 +31,9 @@ public class PayOrderApiImpl implements PayOrderApi {
return PayOrderConvert.INSTANCE.convert2(order);
}
@Override
public void updatePayOrderPriceById(Long payOrderId, Integer payPrice) {
payOrderService.updatePayOrderPriceById(payOrderId, payPrice);
}
}

View File

@ -5,13 +5,16 @@ import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.excel.core.util.ExcelUtils;
import cn.iocoder.yudao.framework.operatelog.core.annotations.OperateLog;
import cn.iocoder.yudao.framework.pay.core.enums.channel.PayChannelEnum;
import cn.iocoder.yudao.module.pay.controller.admin.order.vo.*;
import cn.iocoder.yudao.module.pay.convert.order.PayOrderConvert;
import cn.iocoder.yudao.module.pay.dal.dataobject.app.PayAppDO;
import cn.iocoder.yudao.module.pay.dal.dataobject.order.PayOrderDO;
import cn.iocoder.yudao.module.pay.dal.dataobject.order.PayOrderExtensionDO;
import cn.iocoder.yudao.module.pay.framework.pay.wallet.WalletPayClient;
import cn.iocoder.yudao.module.pay.service.app.PayAppService;
import cn.iocoder.yudao.module.pay.service.order.PayOrderService;
import com.google.common.collect.Maps;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
@ -26,11 +29,14 @@ import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.framework.common.util.collection.CollectionUtils.convertList;
import static cn.iocoder.yudao.framework.common.util.servlet.ServletUtils.getClientIP;
import static cn.iocoder.yudao.framework.operatelog.core.enums.OperateTypeEnum.EXPORT;
import static cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils.getLoginUserId;
import static cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils.getLoginUserType;
@Tag(name = "管理后台 - 支付订单")
@RestController
@ -70,6 +76,16 @@ public class PayOrderController {
@PostMapping("/submit")
@Operation(summary = "提交支付订单")
public CommonResult<PayOrderSubmitRespVO> submitPayOrder(@RequestBody PayOrderSubmitReqVO reqVO) {
// 1. 钱包支付事,需要额外传 user_id 和 user_type
if (Objects.equals(reqVO.getChannelCode(), PayChannelEnum.WALLET.getCode())) {
Map<String, String> channelExtras = reqVO.getChannelExtras() == null ?
Maps.newHashMapWithExpectedSize(2) : reqVO.getChannelExtras();
channelExtras.put(WalletPayClient.USER_ID_KEY, String.valueOf(getLoginUserId()));
channelExtras.put(WalletPayClient.USER_TYPE_KEY, String.valueOf(getLoginUserType()));
reqVO.setChannelExtras(channelExtras);
}
// 2. 提交支付
PayOrderSubmitRespVO respVO = orderService.submitOrder(reqVO, getClientIP());
return success(respVO);
}

View File

@ -37,7 +37,7 @@ public class AppPayWalletController {
@Operation(summary = "获取钱包")
@PreAuthenticated
public CommonResult<AppPayWalletRespVO> getPayWallet() {
PayWalletDO wallet = payWalletService.getPayWallet(getLoginUserId(), UserTypeEnum.MEMBER.getValue());
PayWalletDO wallet = payWalletService.getOrCreateWallet(getLoginUserId(), UserTypeEnum.MEMBER.getValue());
return success(PayWalletConvert.INSTANCE.convert(wallet));
}

View File

@ -15,9 +15,6 @@ public class AppPayWalletTransactionRespVO {
@Schema(description = "业务分类", requiredMode = Schema.RequiredMode.REQUIRED, example = "1")
private Integer bizType;
@Schema(description = "交易时间", requiredMode = Schema.RequiredMode.REQUIRED, example = "100")
private LocalDateTime transactionTime;
@Schema(description = "交易金额,单位分", requiredMode = Schema.RequiredMode.REQUIRED, example = "100")
private Long price;

View File

@ -11,9 +11,9 @@ public class AppPayWalletRespVO {
private Integer balance;
@Schema(description = "累计支出, 单位分", requiredMode = Schema.RequiredMode.REQUIRED, example = "1000")
private Long totalExpense;
private Integer totalExpense;
@Schema(description = "累计充值, 单位分", requiredMode = Schema.RequiredMode.REQUIRED, example = "2000")
private Long totalRecharge;
private Integer totalRecharge;
}

View File

@ -3,6 +3,7 @@ package cn.iocoder.yudao.module.pay.convert.wallet;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.pay.controller.app.wallet.vo.transaction.AppPayWalletTransactionRespVO;
import cn.iocoder.yudao.module.pay.dal.dataobject.wallet.PayWalletTransactionDO;
import cn.iocoder.yudao.module.pay.service.wallet.bo.CreateWalletTransactionBO;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;
@ -12,4 +13,7 @@ public interface PayWalletTransactionConvert {
PayWalletTransactionConvert INSTANCE = Mappers.getMapper(PayWalletTransactionConvert.class);
PageResult<AppPayWalletTransactionRespVO> convertPage(PageResult<PayWalletTransactionDO> page);
PayWalletTransactionDO convert(CreateWalletTransactionBO bean);
}

View File

@ -45,10 +45,10 @@ public class PayWalletDO extends BaseDO {
/**
* 累计支出,单位分
*/
private Long totalExpense;
private Integer totalExpense;
/**
* 累计充值,单位分
*/
private Long totalRecharge;
private Integer totalRecharge;
}

View File

@ -7,8 +7,6 @@ import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 会员钱包流水 DO
*
@ -24,6 +22,7 @@ public class PayWalletTransactionDO extends BaseDO {
*/
@TableId
private Long id;
/**
* 流水号
*/
@ -42,34 +41,26 @@ public class PayWalletTransactionDO extends BaseDO {
* 枚举 {@link PayWalletBizTypeEnum#getType()}
*/
private Integer bizType;
// TODO @jason使用 string因为可能有业务是 string 接入哈。
/**
* 关联业务编号
*/
private Long bizId;
private String bizId;
// TODO @jason想了下改成 title流水标题因为账户明细那会看到这个
/**
* 附加说明
* 流水说明
*/
private String description;
private String title;
// TODO @jason使用 price 哈。项目里,金额都是用这个为主;
/**
* 交易金额,单位分
*
* 正值表示余额增加,负值表示余额减少
*/
private Integer amount;
private Integer price;
/**
* 交易后余额,单位分
*/
private Integer balance;
// TODO @jason使用 createTime 就够啦
/**
* 交易时间
*/
private LocalDateTime transactionTime;
}

View File

@ -3,6 +3,7 @@ package cn.iocoder.yudao.module.pay.dal.mysql.wallet;
import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
import cn.iocoder.yudao.module.pay.dal.dataobject.wallet.PayWalletDO;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.apache.ibatis.annotations.Mapper;
@Mapper
@ -12,6 +13,35 @@ public interface PayWalletMapper extends BaseMapperX<PayWalletDO> {
return selectOne(PayWalletDO::getUserId, userId,
PayWalletDO::getUserType, userType);
}
/**
* 当消费退款时候, 更新钱包
*
* @param price 消费金额
* @param id 钱包 id
*/
default int updateWhenConsumptionRefund(Integer price, Long id){
LambdaUpdateWrapper<PayWalletDO> lambdaUpdateWrapper = new LambdaUpdateWrapper<PayWalletDO>()
.setSql(" balance = balance + " + price
+ ", total_expense = total_expense - " + price)
.eq(PayWalletDO::getId, id);
return update(null, lambdaUpdateWrapper);
}
/**
* 当消费时候, 更新钱包
*
* @param price 消费金额
* @param id 钱包 id
*/
default int updateWhenConsumption(Integer price, Long id){
LambdaUpdateWrapper<PayWalletDO> lambdaUpdateWrapper = new LambdaUpdateWrapper<PayWalletDO>()
.setSql(" balance = balance - " + price
+ ", total_expense = total_expense + " + price)
.eq(PayWalletDO::getId, id)
.ge(PayWalletDO::getBalance, price); // cas 逻辑
return update(null, lambdaUpdateWrapper);
}
}

View File

@ -18,9 +18,9 @@ public interface PayWalletTransactionMapper extends BaseMapperX<PayWalletTransac
LambdaQueryWrapperX<PayWalletTransactionDO> query = new LambdaQueryWrapperX<PayWalletTransactionDO>()
.eq(PayWalletTransactionDO::getWalletId, walletId);
if (Objects.equals(pageReqVO.getType(), AppPayWalletTransactionPageReqVO.TYPE_INCOME)) {
query.gt(PayWalletTransactionDO::getAmount, 0);
query.gt(PayWalletTransactionDO::getPrice, 0);
} else if (Objects.equals(pageReqVO.getType(), AppPayWalletTransactionPageReqVO.TYPE_EXPENSE)) {
query.lt(PayWalletTransactionDO::getAmount, 0);
query.lt(PayWalletTransactionDO::getPrice, 0);
}
query.orderByDesc(PayWalletTransactionDO::getId);
return selectPage(pageReqVO, query);
@ -30,9 +30,8 @@ public interface PayWalletTransactionMapper extends BaseMapperX<PayWalletTransac
return selectOne(PayWalletTransactionDO::getNo, no);
}
default PayWalletTransactionDO selectByWalletIdAndBiz(Long walletId, Long bizId, Integer bizType) {
return selectOne(PayWalletTransactionDO::getWalletId, walletId,
PayWalletTransactionDO::getBizId, bizId,
default PayWalletTransactionDO selectByBiz(String bizId, Integer bizType) {
return selectOne(PayWalletTransactionDO::getBizId, bizId,
PayWalletTransactionDO::getBizType, bizType);
}

View File

@ -1,5 +1,7 @@
package cn.iocoder.yudao.module.pay.framework.pay.wallet;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.iocoder.yudao.framework.common.exception.ServiceException;
import cn.iocoder.yudao.framework.pay.core.client.dto.order.PayOrderRespDTO;
@ -9,13 +11,23 @@ import cn.iocoder.yudao.framework.pay.core.client.dto.refund.PayRefundUnifiedReq
import cn.iocoder.yudao.framework.pay.core.client.impl.AbstractPayClient;
import cn.iocoder.yudao.framework.pay.core.client.impl.NonePayClientConfig;
import cn.iocoder.yudao.framework.pay.core.enums.channel.PayChannelEnum;
import cn.iocoder.yudao.framework.pay.core.enums.refund.PayRefundStatusRespEnum;
import cn.iocoder.yudao.module.pay.dal.dataobject.order.PayOrderExtensionDO;
import cn.iocoder.yudao.module.pay.dal.dataobject.refund.PayRefundDO;
import cn.iocoder.yudao.module.pay.dal.dataobject.wallet.PayWalletTransactionDO;
import cn.iocoder.yudao.module.pay.enums.member.PayWalletBizTypeEnum;
import cn.iocoder.yudao.module.pay.enums.order.PayOrderStatusEnum;
import cn.iocoder.yudao.module.pay.service.order.PayOrderService;
import cn.iocoder.yudao.module.pay.service.refund.PayRefundService;
import cn.iocoder.yudao.module.pay.service.wallet.PayWalletService;
import cn.iocoder.yudao.module.pay.service.wallet.PayWalletTransactionService;
import lombok.extern.slf4j.Slf4j;
import java.util.Map;
import static cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants.INTERNAL_SERVER_ERROR;
import static cn.iocoder.yudao.module.pay.enums.ErrorCodeConstants.ORDER_EXTENSION_NOT_FOUND;
import static cn.iocoder.yudao.module.pay.enums.ErrorCodeConstants.REFUND_NOT_FOUND;
/**
* 钱包支付的 PayClient 实现类
@ -25,7 +37,13 @@ import static cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeC
@Slf4j
public class WalletPayClient extends AbstractPayClient<NonePayClientConfig> {
public static final String USER_ID_KEY = "user_id";
public static final String USER_TYPE_KEY = "user_type";
private PayWalletService wallService;
private PayWalletTransactionService walletTransactionService;
private PayOrderService orderService;
private PayRefundService refundService;
public WalletPayClient(Long channelId, NonePayClientConfig config) {
super(channelId, PayChannelEnum.WALLET.getCode(), config);
@ -36,14 +54,22 @@ public class WalletPayClient extends AbstractPayClient<NonePayClientConfig> {
if (wallService == null) {
wallService = SpringUtil.getBean(PayWalletService.class);
}
if (walletTransactionService == null) {
walletTransactionService = SpringUtil.getBean(PayWalletTransactionService.class);
}
}
@Override
protected PayOrderRespDTO doUnifiedOrder(PayOrderUnifiedReqDTO reqDTO) {
try {
PayWalletTransactionDO transaction = wallService.pay(reqDTO.getOutTradeNo(), reqDTO.getPrice());
Long userId = MapUtil.getLong(reqDTO.getChannelExtras(), USER_ID_KEY);
Integer userType = MapUtil.getInt(reqDTO.getChannelExtras(), USER_TYPE_KEY);
Assert.notNull(userId, "用户 id 不能为空");
Assert.notNull(userType, "用户类型不能为空");
PayWalletTransactionDO transaction = wallService.orderPay(userId, userType, reqDTO.getOutTradeNo(),
reqDTO.getPrice());
return PayOrderRespDTO.successOf(transaction.getNo(), transaction.getCreator(),
transaction.getTransactionTime(),
transaction.getCreateTime(),
reqDTO.getOutTradeNo(), transaction);
} catch (Throwable ex) {
log.error("[doUnifiedOrder] 失败", ex);
@ -66,15 +92,39 @@ public class WalletPayClient extends AbstractPayClient<NonePayClientConfig> {
@Override
protected PayOrderRespDTO doGetOrder(String outTradeNo) {
throw new UnsupportedOperationException("待实现");
if (orderService == null) {
orderService = SpringUtil.getBean(PayOrderService.class);
}
PayOrderExtensionDO orderExtension = orderService.getOrderExtensionByNo(outTradeNo);
// 支付交易拓展单不存在, 返回关闭状态
if (orderExtension == null) {
return PayOrderRespDTO.closedOf(String.valueOf(ORDER_EXTENSION_NOT_FOUND.getCode()),
ORDER_EXTENSION_NOT_FOUND.getMsg(), outTradeNo, "");
}
// 关闭状态
if (PayOrderStatusEnum.isClosed(orderExtension.getStatus())) {
return PayOrderRespDTO.closedOf(orderExtension.getChannelErrorCode(),
orderExtension.getChannelErrorMsg(), outTradeNo, "");
}
// 成功状态
if (PayOrderStatusEnum.isSuccess(orderExtension.getStatus())) {
PayWalletTransactionDO walletTransaction = walletTransactionService.getWalletTransaction(
String.valueOf(orderExtension.getOrderId()), PayWalletBizTypeEnum.PAYMENT);
Assert.notNull(walletTransaction, "支付单 {} 钱包流水不能为空", outTradeNo);
return PayOrderRespDTO.successOf(walletTransaction.getNo(), walletTransaction.getCreator(),
walletTransaction.getCreateTime(), outTradeNo, walletTransaction);
}
// 其它状态为无效状态
log.error("[doGetOrder] 支付单 {} 的状态不正确", outTradeNo);
throw new IllegalStateException(String.format("支付单[%s] 状态不正确", outTradeNo));
}
@Override
protected PayRefundRespDTO doUnifiedRefund(PayRefundUnifiedReqDTO reqDTO) {
try {
PayWalletTransactionDO payWalletTransaction = wallService.refund(reqDTO.getOutRefundNo(),
PayWalletTransactionDO payWalletTransaction = wallService.orderRefund(reqDTO.getOutRefundNo(),
reqDTO.getRefundPrice(), reqDTO.getReason());
return PayRefundRespDTO.successOf(payWalletTransaction.getNo(), payWalletTransaction.getTransactionTime(),
return PayRefundRespDTO.successOf(payWalletTransaction.getNo(), payWalletTransaction.getCreateTime(),
reqDTO.getOutRefundNo(), payWalletTransaction);
} catch (Throwable ex) {
log.error("[doUnifiedRefund] 失败", ex);
@ -97,7 +147,31 @@ public class WalletPayClient extends AbstractPayClient<NonePayClientConfig> {
@Override
protected PayRefundRespDTO doGetRefund(String outTradeNo, String outRefundNo) {
throw new UnsupportedOperationException("待实现");
if (refundService == null) {
refundService = SpringUtil.getBean(PayRefundService.class);
}
PayRefundDO payRefund = refundService.getRefundByNo(outRefundNo);
// 支付退款单不存在, 返回退款失败状态
if (payRefund == null) {
return PayRefundRespDTO.failureOf(String.valueOf(REFUND_NOT_FOUND), REFUND_NOT_FOUND.getMsg(),
outRefundNo, "");
}
// 退款失败
if (PayRefundStatusRespEnum.isFailure(payRefund.getStatus())) {
return PayRefundRespDTO.failureOf(payRefund.getChannelErrorCode(), payRefund.getChannelErrorMsg(),
outRefundNo, "");
}
// 退款成功
if (PayRefundStatusRespEnum.isSuccess(payRefund.getStatus())) {
PayWalletTransactionDO walletTransaction = walletTransactionService.getWalletTransaction(
String.valueOf(payRefund.getId()), PayWalletBizTypeEnum.PAYMENT_REFUND);
Assert.notNull(walletTransaction, "支付退款单 {} 钱包流水不能为空", outRefundNo);
return PayRefundRespDTO.successOf(walletTransaction.getNo(), walletTransaction.getCreateTime(),
outRefundNo, walletTransaction);
}
// 其它状态为无效状态
log.error("[doGetRefund] 支付退款单 {} 的状态不正确", outRefundNo);
throw new IllegalStateException(String.format("支付退款单[%s] 状态不正确", outRefundNo));
}
}

View File

@ -33,7 +33,7 @@ public interface PayOrderService {
/**
* 获得支付订单
*
* @param appId 应用编号
* @param appId 应用编号
* @param merchantOrderId 商户订单编号
* @return 支付订单
*/
@ -75,7 +75,7 @@ public interface PayOrderService {
* 提交支付
* 此时,会发起支付渠道的调用
*
* @param reqVO 提交请求
* @param reqVO 提交请求
* @param userIp 提交 IP
* @return 提交结果
*/
@ -93,11 +93,19 @@ public interface PayOrderService {
/**
* 更新支付订单的退款金额
*
* @param id 编号
* @param id 编号
* @param incrRefundPrice 增加的退款金额
*/
void updateOrderRefundPrice(Long id, Integer incrRefundPrice);
/**
* 更新支付订单价格
*
* @param payOrderId 支付单编号
* @param payPrice 支付单价格
*/
void updatePayOrderPriceById(Long payOrderId, Integer payPrice);
/**
* 获得支付订单
*

View File

@ -6,6 +6,7 @@ import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.date.LocalDateTimeUtils;
import cn.iocoder.yudao.framework.common.util.number.MoneyUtils;
import cn.iocoder.yudao.framework.pay.core.client.PayClient;
import cn.iocoder.yudao.framework.pay.core.client.PayClientFactory;
import cn.iocoder.yudao.framework.pay.core.client.dto.order.PayOrderRespDTO;
@ -31,7 +32,6 @@ import cn.iocoder.yudao.module.pay.framework.pay.config.PayProperties;
import cn.iocoder.yudao.module.pay.service.app.PayAppService;
import cn.iocoder.yudao.module.pay.service.channel.PayChannelService;
import cn.iocoder.yudao.module.pay.service.notify.PayNotifyService;
import cn.iocoder.yudao.module.pay.util.MoneyUtils;
import com.google.common.annotations.VisibleForTesting;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
@ -411,6 +411,18 @@ public class PayOrderServiceImpl implements PayOrderService {
}
}
@Override
public void updatePayOrderPriceById(Long payOrderId, Integer payPrice) {
// TODO @puhui999不能直接这样修改哈应该只有未支付状态的订单才可以改另外如果价格如果没变可以直接 return 哈;
PayOrderDO order = orderMapper.selectById(payOrderId);
if (order == null) {
throw exception(ORDER_NOT_FOUND);
}
order.setPrice(payPrice);
orderMapper.updateById(order);
}
@Override
public PayOrderExtensionDO getOrderExtension(Long id) {
return orderExtensionMapper.selectById(id);

View File

@ -2,6 +2,7 @@ package cn.iocoder.yudao.module.pay.service.wallet;
import cn.iocoder.yudao.module.pay.dal.dataobject.wallet.PayWalletDO;
import cn.iocoder.yudao.module.pay.dal.dataobject.wallet.PayWalletTransactionDO;
import cn.iocoder.yudao.module.pay.enums.member.PayWalletBizTypeEnum;
/**
* 钱包 Service 接口
@ -10,30 +11,59 @@ import cn.iocoder.yudao.module.pay.dal.dataobject.wallet.PayWalletTransactionDO;
*/
public interface PayWalletService {
// TODO @jason改成 getOrCreateWallet因为目前解耦用户注册时不会创建钱包需要这里兜底处理
/**
* 获取钱包信息
*
* 如果不存在,则创建钱包。由于用户注册时候不会创建钱包
*
* @param userId 用户编号
* @param userType 用户类型
*/
PayWalletDO getPayWallet(Long userId, Integer userType);
PayWalletDO getOrCreateWallet(Long userId, Integer userType);
/**
* 钱包支付
* 钱包订单支付
*
* @param userId 用户 id
* @param userType 用户类型
* @param outTradeNo 外部订单号
* @param price 金额
*/
PayWalletTransactionDO pay(String outTradeNo, Integer price);
PayWalletTransactionDO orderPay(Long userId, Integer userType, String outTradeNo, Integer price);
/**
* 钱包支付退款
* 钱包订单支付退款
*
* @param outRefundNo 外部退款号
* @param refundPrice 退款金额
* @param reason 退款原因
*/
PayWalletTransactionDO refund(String outRefundNo, Integer refundPrice, String reason);
PayWalletTransactionDO orderRefund(String outRefundNo, Integer refundPrice, String reason);
/**
* 扣减钱包余额
*
* @param userId 用户 id
* @param userType 用户类型
* @param bizId 业务关联 id
* @param bizType 业务关联分类
* @param price 扣减金额
* @return 钱包流水
*/
PayWalletTransactionDO reduceWalletBalance(Long userId, Integer userType,
Long bizId, PayWalletBizTypeEnum bizType, Integer price);
/**
* 增加钱包余额
*
* @param userId 用户 id
* @param userType 用户类型
* @param bizId 业务关联 id
* @param bizType 业务关联分类
* @param price 增加金额
* @return 钱包流水
*/
PayWalletTransactionDO addWalletBalance(Long userId, Integer userType,
Long bizId, PayWalletBizTypeEnum bizType, Integer price);
}

View File

@ -1,13 +1,15 @@
package cn.iocoder.yudao.module.pay.service.wallet;
import cn.hutool.core.lang.Assert;
import cn.iocoder.yudao.module.pay.dal.dataobject.order.PayOrderExtensionDO;
import cn.iocoder.yudao.module.pay.dal.dataobject.refund.PayRefundDO;
import cn.iocoder.yudao.module.pay.dal.dataobject.wallet.PayWalletDO;
import cn.iocoder.yudao.module.pay.dal.dataobject.wallet.PayWalletTransactionDO;
import cn.iocoder.yudao.module.pay.dal.mysql.wallet.PayWalletMapper;
import cn.iocoder.yudao.module.pay.dal.redis.no.PayNoRedisDAO;
import cn.iocoder.yudao.module.pay.enums.member.PayWalletBizTypeEnum;
import cn.iocoder.yudao.module.pay.service.order.PayOrderService;
import cn.iocoder.yudao.module.pay.service.refund.PayRefundService;
import cn.iocoder.yudao.module.pay.service.wallet.bo.CreateWalletTransactionBO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
@ -17,8 +19,6 @@ import javax.annotation.Resource;
import java.time.LocalDateTime;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils.getLoginUserId;
import static cn.iocoder.yudao.framework.web.core.util.WebFrameworkUtils.getLoginUserType;
import static cn.iocoder.yudao.module.pay.enums.ErrorCodeConstants.*;
import static cn.iocoder.yudao.module.pay.enums.member.PayWalletBizTypeEnum.PAYMENT;
import static cn.iocoder.yudao.module.pay.enums.member.PayWalletBizTypeEnum.PAYMENT_REFUND;
@ -32,105 +32,55 @@ import static cn.iocoder.yudao.module.pay.enums.member.PayWalletBizTypeEnum.PAYM
@Slf4j
public class PayWalletServiceImpl implements PayWalletService {
/**
* 余额支付的 no 前缀
*/
private static final String WALLET_PAY_NO_PREFIX = "WP";
/**
* 余额退款的 no 前缀
*/
private static final String WALLET_REFUND_NO_PREFIX = "WR";
@Resource
private PayWalletMapper payWalletMapper;
private PayWalletMapper walletMapper;
@Resource
private PayNoRedisDAO noRedisDAO;
@Resource
private PayWalletTransactionService payWalletTransactionService;
private PayWalletTransactionService walletTransactionService;
@Resource
@Lazy
private PayOrderService payOrderService;
private PayOrderService orderService;
@Resource
@Lazy
private PayRefundService payRefundService;
private PayRefundService refundService;
@Override
public PayWalletDO getPayWallet(Long userId, Integer userType) {
return payWalletMapper.selectByUserIdAndType(userId, userType);
public PayWalletDO getOrCreateWallet(Long userId, Integer userType) {
PayWalletDO wallet = walletMapper.selectByUserIdAndType(userId, userType);
if (wallet == null) {
wallet = new PayWalletDO().setUserId(userId).setUserType(userType)
.setBalance(0).setTotalExpense(0).setTotalRecharge(0);
wallet.setCreateTime(LocalDateTime.now());
walletMapper.insert(wallet);
}
return wallet;
}
// TODO @jason可以做的更抽象一点pay(bizType, bizId, price)reduceWalletBalance
// TODO @jason最好是明确传入哪个 userId 或者 walletId
@Override
@Transactional(rollbackFor = Exception.class)
public PayWalletTransactionDO pay(String outTradeNo, Integer price) {
// 1.1 判断支付交易拓展单是否存
PayOrderExtensionDO orderExtension = payOrderService.getOrderExtensionByNo(outTradeNo);
public PayWalletTransactionDO orderPay(Long userId, Integer userType, String outTradeNo, Integer price) {
// 1. 判断支付交易拓展单是否存
PayOrderExtensionDO orderExtension = orderService.getOrderExtensionByNo(outTradeNo);
if (orderExtension == null) {
throw exception(ORDER_EXTENSION_NOT_FOUND);
}
// 1.2 判断余额是否足够
PayWalletDO payWallet = validatePayWallet();
int afterBalance = payWallet.getBalance() - price;
if (afterBalance < 0) {
throw exception(WALLET_BALANCE_NOT_ENOUGH);
}
// 2.1 扣除余额
// TODO @jason不要直接整个更新而是 new 一个出来更新;然后要考虑并发,要 where 余额 > price以及 - price
payWallet.setBalance(afterBalance);
payWallet.setTotalExpense(payWallet.getTotalExpense() + price);
payWalletMapper.updateById(payWallet);
// 2.2 生成钱包流水
String walletNo = noRedisDAO.generate(WALLET_PAY_NO_PREFIX);
PayWalletTransactionDO walletTransaction = new PayWalletTransactionDO().setWalletId(payWallet.getId())
.setNo(walletNo).setAmount(price * -1).setBalance(afterBalance).setTransactionTime(LocalDateTime.now())
.setBizId(orderExtension.getOrderId()).setBizType(PAYMENT.getType());
payWalletTransactionService.createWalletTransaction(walletTransaction);
return walletTransaction;
// 2. 扣减余额
return reduceWalletBalance(userId, userType, orderExtension.getOrderId(), PAYMENT, price);
}
// TODO @jason不要在 service 里去使用用户上下文,这样和 request 就耦合了。
private PayWalletDO validatePayWallet() {
Long userId = getLoginUserId();
Integer userType = getLoginUserType();
PayWalletDO payWallet = getPayWallet(userId, userType);
if (payWallet == null) {
log.error("[validatePayWallet] 用户 {} 钱包不存在", userId);
throw exception(WALLET_NOT_FOUND);
}
return payWallet;
}
// TODO @jason可以做的更抽象一点pay(bizType, bizId, price)addWalletBalance这样如果后续充值应该也是能复用这个方法的
@Override
@Transactional(rollbackFor = Exception.class)
public PayWalletTransactionDO refund(String outRefundNo, Integer refundPrice, String reason) {
public PayWalletTransactionDO orderRefund(String outRefundNo, Integer refundPrice, String reason) {
// 1.1 判断退款单是否存在
PayRefundDO payRefund = payRefundService.getRefundByNo(outRefundNo);
PayRefundDO payRefund = refundService.getRefundByNo(outRefundNo);
if (payRefund == null) {
throw exception(REFUND_NOT_FOUND);
}
// 1.2 校验是否可以退款
PayWalletDO payWallet = validatePayWallet();
validateWalletCanRefund(payRefund.getId(), payRefund.getChannelOrderNo(), payWallet.getId(), refundPrice);
// TODO @jason不要直接整个更新而是 new 一个出来更新;然后要考虑并发,要 where 余额 + 金
Integer afterBalance = payWallet.getBalance() + refundPrice;
payWallet.setBalance(afterBalance);
payWallet.setTotalExpense(payWallet.getTotalExpense() + refundPrice * -1L);
payWalletMapper.updateById(payWallet);
// 2.2 生成钱包流水
String walletNo = noRedisDAO.generate(WALLET_REFUND_NO_PREFIX);
PayWalletTransactionDO newWalletTransaction = new PayWalletTransactionDO().setWalletId(payWallet.getId())
.setNo(walletNo).setAmount(refundPrice).setBalance(afterBalance).setTransactionTime(LocalDateTime.now())
.setBizId(payRefund.getId()).setBizType(PAYMENT_REFUND.getType())
.setDescription(reason);
payWalletTransactionService.createWalletTransaction(newWalletTransaction);
return newWalletTransaction;
Long walletId = validateWalletCanRefund(payRefund.getId(), payRefund.getChannelOrderNo(), refundPrice);
PayWalletDO wallet = walletMapper.selectById(walletId);
Assert.notNull(wallet, "钱包 {} 不存在", walletId);
// 2. 增加余
return addWalletBalance(wallet.getUserId(), wallet.getUserType(), payRefund.getId(), PAYMENT_REFUND, refundPrice);
}
/**
@ -138,24 +88,78 @@ public class PayWalletServiceImpl implements PayWalletService {
*
* @param refundId 支付退款单 id
* @param walletPayNo 钱包支付 no
* @param walletId 钱包 id
*/
// TODO @jason不要使用基本类型
private void validateWalletCanRefund(long refundId, String walletPayNo, long walletId, int refundPrice) {
// 查询钱包支付交易
PayWalletTransactionDO payWalletTransaction = payWalletTransactionService.getWalletTransactionByNo(walletPayNo);
if (payWalletTransaction == null) {
private Long validateWalletCanRefund(Long refundId, String walletPayNo, Integer refundPrice) {
// 1. 校验钱包支付交易存在
PayWalletTransactionDO walletTransaction = walletTransactionService.getWalletTransactionByNo(walletPayNo);
if (walletTransaction == null) {
throw exception(WALLET_TRANSACTION_NOT_FOUND);
}
// 原来的支付金额
int amount = payWalletTransaction.getAmount() * -1; // TODO @jason直接 - payWalletTransaction.getAmount() 即可
// TODO @jason应该允许多次退款哈
int amount = - walletTransaction.getPrice();
if (refundPrice != amount) {
throw exception(WALLET_REFUND_AMOUNT_ERROR);
}
PayWalletTransactionDO refundTransaction = payWalletTransactionService.getWalletTransaction(walletId, refundId, PAYMENT_REFUND);
PayWalletTransactionDO refundTransaction = walletTransactionService.getWalletTransaction(
String.valueOf(refundId), PAYMENT_REFUND);
if (refundTransaction != null) {
throw exception(WALLET_REFUND_EXIST);
}
return walletTransaction.getWalletId();
}
@Override
public PayWalletTransactionDO reduceWalletBalance(Long userId, Integer userType,
Long bizId, PayWalletBizTypeEnum bizType, Integer price) {
// 1. 获取钱包
PayWalletDO payWallet = getOrCreateWallet(userId, userType);
// 2.1 扣除余额
int updateCounts = 0 ;
switch (bizType) {
case PAYMENT: {
updateCounts = walletMapper.updateWhenConsumption(price, payWallet.getId());
break;
}
case RECHARGE_REFUND: {
// TODO
break;
}
}
if (updateCounts == 0) {
throw exception(WALLET_BALANCE_NOT_ENOUGH);
}
// 2.2 生成钱包流水
Integer afterBalance = payWallet.getBalance() - price;
CreateWalletTransactionBO bo = new CreateWalletTransactionBO().setWalletId(payWallet.getId())
.setPrice(-price).setBalance(afterBalance).setBizId(String.valueOf(bizId))
.setBizType(bizType.getType()).setTitle(bizType.getDescription());
return walletTransactionService.createWalletTransaction(bo);
}
@Override
public PayWalletTransactionDO addWalletBalance(Long userId, Integer userType,
Long bizId, PayWalletBizTypeEnum bizType, Integer price) {
// 1. 获取钱包
PayWalletDO payWallet = getOrCreateWallet(userId, userType);
switch (bizType) {
case PAYMENT_REFUND: {
// 更新退款
walletMapper.updateWhenConsumptionRefund(price, payWallet.getId());
break;
}
case RECHARGE: {
//TODO
break;
}
}
// 2. 生成钱包流水
CreateWalletTransactionBO bo = new CreateWalletTransactionBO().setWalletId(payWallet.getId())
.setPrice(price).setBalance(payWallet.getBalance()+price).setBizId(String.valueOf(bizId))
.setBizType(bizType.getType()).setTitle(bizType.getDescription());
return walletTransactionService.createWalletTransaction(bo);
}
}

View File

@ -4,6 +4,9 @@ import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.pay.controller.app.wallet.vo.transaction.AppPayWalletTransactionPageReqVO;
import cn.iocoder.yudao.module.pay.dal.dataobject.wallet.PayWalletTransactionDO;
import cn.iocoder.yudao.module.pay.enums.member.PayWalletBizTypeEnum;
import cn.iocoder.yudao.module.pay.service.wallet.bo.CreateWalletTransactionBO;
import javax.validation.Valid;
/**
* 钱包余额流水 Service 接口
@ -25,10 +28,10 @@ public interface PayWalletTransactionService {
/**
* 新增钱包余额流水
*
* @param payWalletTransaction 余额流水
* @return id
* @param bo 创建钱包流水 bo
* @return 新建的钱包 do
*/
Long createWalletTransaction(PayWalletTransactionDO payWalletTransaction);
PayWalletTransactionDO createWalletTransaction(@Valid CreateWalletTransactionBO bo);
/**
* 根据 no获取钱包余流水
@ -40,11 +43,10 @@ public interface PayWalletTransactionService {
/**
* 获取钱包流水
*
* @param walletId 钱包编号
* @param bizId 业务编号
* @param type 业务类型
* @return 钱包流水
*/
PayWalletTransactionDO getWalletTransaction(Long walletId, Long bizId, PayWalletBizTypeEnum type);
PayWalletTransactionDO getWalletTransaction(String bizId, PayWalletBizTypeEnum type);
}

View File

@ -2,18 +2,18 @@ package cn.iocoder.yudao.module.pay.service.wallet;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.pay.controller.app.wallet.vo.transaction.AppPayWalletTransactionPageReqVO;
import cn.iocoder.yudao.module.pay.convert.wallet.PayWalletTransactionConvert;
import cn.iocoder.yudao.module.pay.dal.dataobject.wallet.PayWalletDO;
import cn.iocoder.yudao.module.pay.dal.dataobject.wallet.PayWalletTransactionDO;
import cn.iocoder.yudao.module.pay.dal.mysql.wallet.PayWalletTransactionMapper;
import cn.iocoder.yudao.module.pay.dal.redis.no.PayNoRedisDAO;
import cn.iocoder.yudao.module.pay.enums.member.PayWalletBizTypeEnum;
import cn.iocoder.yudao.module.pay.service.wallet.bo.CreateWalletTransactionBO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.pay.enums.ErrorCodeConstants.WALLET_NOT_FOUND;
/**
* 钱包流水 Service 实现类
*
@ -23,27 +23,31 @@ import static cn.iocoder.yudao.module.pay.enums.ErrorCodeConstants.WALLET_NOT_FO
@Slf4j
public class PayWalletTransactionServiceImpl implements PayWalletTransactionService {
@Resource
private PayWalletService payWalletService;
/**
* 钱包流水的 no 前缀
*/
private static final String WALLET_NO_PREFIX = "W";
@Resource
private PayWalletService payWalletService;
@Resource
private PayWalletTransactionMapper payWalletTransactionMapper;
@Resource
private PayNoRedisDAO noRedisDAO;
@Override
public PageResult<PayWalletTransactionDO> getWalletTransactionPage(Long userId, Integer userType,
AppPayWalletTransactionPageReqVO pageVO) {
PayWalletDO wallet = payWalletService.getPayWallet(userId, userType);
if (wallet == null) {
log.error("[getWalletTransactionPage][用户({}/{}) 钱包不存在", userId, userType);
throw exception(WALLET_NOT_FOUND);
}
PayWalletDO wallet = payWalletService.getOrCreateWallet(userId, userType);
return payWalletTransactionMapper.selectPage(wallet.getId(), pageVO);
}
@Override
public Long createWalletTransaction(PayWalletTransactionDO payWalletTransaction) {
payWalletTransactionMapper.insert(payWalletTransaction);
return payWalletTransaction.getId();
public PayWalletTransactionDO createWalletTransaction(CreateWalletTransactionBO bo) {
PayWalletTransactionDO transaction = PayWalletTransactionConvert.INSTANCE.convert(bo)
.setNo(noRedisDAO.generate(WALLET_NO_PREFIX));
payWalletTransactionMapper.insert(transaction);
return transaction;
}
@Override
@ -52,8 +56,8 @@ public class PayWalletTransactionServiceImpl implements PayWalletTransactionServ
}
@Override
public PayWalletTransactionDO getWalletTransaction(Long walletId, Long bizId, PayWalletBizTypeEnum type) {
return payWalletTransactionMapper.selectByWalletIdAndBiz(walletId, bizId, type.getType());
public PayWalletTransactionDO getWalletTransaction(String bizId, PayWalletBizTypeEnum type) {
return payWalletTransactionMapper.selectByBiz(bizId, type.getType());
}
}

View File

@ -0,0 +1,50 @@
package cn.iocoder.yudao.module.pay.service.wallet.bo;
import cn.iocoder.yudao.module.pay.enums.member.PayWalletBizTypeEnum;
import lombok.Data;
/**
* 创建钱包流水 BO
*
* @author jason
*/
@Data
public class CreateWalletTransactionBO {
// TODO @jasonbo 的话,最好加个参数校验哈;
/**
* 钱包编号
*
*/
private Long walletId;
/**
* 交易金额,单位分
*
* 正值表示余额增加,负值表示余额减少
*/
private Integer price;
/**
* 交易后余额,单位分
*/
private Integer balance;
/**
* 关联业务分类
*
* 枚举 {@link PayWalletBizTypeEnum#getType()}
*/
private Integer bizType;
/**
* 关联业务编号
*/
private String bizId;
/**
* 流水说明
*/
private String title;
}

View File

@ -1,39 +0,0 @@
package cn.iocoder.yudao.module.pay.util;
import cn.hutool.core.util.NumberUtil;
import java.math.BigDecimal;
import java.math.RoundingMode;
/**
* 金额工具类
*
* @author 芋道源码
*/
public class MoneyUtils {
/**
* 计算百分比金额,四舍五入
*
* @param price 金额
* @param rate 百分比,例如说 56.77% 则传入 56.77
* @return 百分比金额
*/
public static Integer calculateRatePrice(Integer price, Double rate) {
return calculateRatePrice(price, rate, 0, RoundingMode.HALF_UP).intValue();
}
/**
* 计算百分比金额
*
* @param price 金额
* @param rate 百分比,例如说 56.77% 则传入 56.77
* @param scale 保留小数位数
* @param roundingMode 舍入模式
*/
public static BigDecimal calculateRatePrice(Number price, Number rate, int scale, RoundingMode roundingMode) {
return NumberUtil.toBigDecimal(price).multiply(NumberUtil.toBigDecimal(rate)) // 乘以
.divide(BigDecimal.valueOf(100), scale, roundingMode); // 除以 100
}
}