钱包 review 修改

plp
jason 3 years ago
parent 557b09a157
commit 5858f57fe9

@ -8,8 +8,8 @@ CREATE TABLE `pay_wallet`
`user_id` bigint NOT NULL COMMENT '', `user_id` bigint NOT NULL COMMENT '',
`user_type` tinyint NOT NULL DEFAULT 0 COMMENT '', `user_type` tinyint NOT NULL DEFAULT 0 COMMENT '',
`balance` int NOT NULL DEFAULT 0 COMMENT '', `balance` int NOT NULL DEFAULT 0 COMMENT '',
`total_expense` bigint NOT NULL DEFAULT 0 COMMENT '', `total_expense` int NOT NULL DEFAULT 0 COMMENT '',
`total_recharge` bigint NOT NULL DEFAULT 0 COMMENT '', `total_recharge` int NOT NULL DEFAULT 0 COMMENT '',
`creator` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT '' COMMENT '', `creator` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT '' COMMENT '',
`create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '', `create_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '',
`updater` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT '' COMMENT '', `updater` varchar(64) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci NULL DEFAULT '' COMMENT '',

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

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

@ -37,8 +37,6 @@ public class PayWalletDO extends BaseDO {
*/ */
private Integer userType; private Integer userType;
// TODO @jason三个都搞 integer应该要统一哈
/** /**
* *
*/ */
@ -47,10 +45,10 @@ public class PayWalletDO extends BaseDO {
/** /**
* *
*/ */
private Long totalExpense; private Integer totalExpense;
/** /**
* *
*/ */
private Long totalRecharge; private Integer totalRecharge;
} }

@ -3,8 +3,7 @@ package cn.iocoder.yudao.module.pay.dal.mysql.wallet;
import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX; import cn.iocoder.yudao.framework.mybatis.core.mapper.BaseMapperX;
import cn.iocoder.yudao.module.pay.dal.dataobject.wallet.PayWalletDO; import cn.iocoder.yudao.module.pay.dal.dataobject.wallet.PayWalletDO;
import cn.iocoder.yudao.module.pay.enums.member.PayWalletBizTypeEnum; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
@Mapper @Mapper
@ -15,56 +14,31 @@ public interface PayWalletMapper extends BaseMapperX<PayWalletDO> {
PayWalletDO::getUserType, userType); PayWalletDO::getUserType, userType);
} }
// TODO @jason减少时需要 update price -= ? where price >= ?,避免并发问题。现在基于 price 来过滤,虽然也能解决并发问题,但是冲突概率会高一点;可以看到 TradeBrokerageUserMapper 的做法;
/** /**
* * 退
* *
* @param bizType * @param price
* @param balance
* @param totalRecharge
* @param totalExpense
* @param price
* @param id id * @param id id
*/ */
default int updateWhenDecBalance(PayWalletBizTypeEnum bizType, Integer balance, Long totalRecharge, default int updateWhenConsumptionRefund(Integer price, Long id){
Long totalExpense, Integer price, Long id) { LambdaUpdateWrapper<PayWalletDO> lambdaUpdateWrapper = new LambdaUpdateWrapper<PayWalletDO>()
// TODO @jason这种偏判断的最红放在 service 层mapper 可以写多个方法; .setSql(" balance = balance + " + price + ", total_expense = total_expense - " + price)
PayWalletDO updateDO = new PayWalletDO().setBalance(balance - price); .eq(PayWalletDO::getId, id);
if(bizType == PayWalletBizTypeEnum.PAYMENT){ return update(null, lambdaUpdateWrapper);
updateDO.setTotalExpense(totalExpense + price);
}
if (bizType == PayWalletBizTypeEnum.RECHARGE_REFUND) {
updateDO.setTotalRecharge(totalRecharge - price);
}
return update(updateDO,
new LambdaQueryWrapper<PayWalletDO>().eq(PayWalletDO::getId, id)
.eq(PayWalletDO::getBalance, balance)
.ge(PayWalletDO::getBalance, price));
} }
// TODO @jason类似上面的修改建议哈
/** /**
* *
* *
* @param bizType * @param price
* @param balance
* @param totalRecharge
* @param totalExpense
* @param price
* @param id id * @param id id
*/ */
default int updateWhenIncBalance(PayWalletBizTypeEnum bizType, Integer balance, Long totalRecharge, default int updateWhenConsumption(Integer price, Long id){
Long totalExpense, Integer price, Long id) { LambdaUpdateWrapper<PayWalletDO> lambdaUpdateWrapper = new LambdaUpdateWrapper<PayWalletDO>()
PayWalletDO updateDO = new PayWalletDO().setBalance(balance + price); .setSql(" balance = balance - " + price + ", total_expense = total_expense + " + price)
if (bizType == PayWalletBizTypeEnum.PAYMENT_REFUND) { .eq(PayWalletDO::getId, id)
updateDO.setTotalExpense(totalExpense - price); .ge(PayWalletDO::getBalance, price); // cas 逻辑
} return update(null, lambdaUpdateWrapper);
if (bizType == PayWalletBizTypeEnum.RECHARGE) {
updateDO.setTotalExpense(totalRecharge + price);
}
return update(updateDO,
new LambdaQueryWrapper<PayWalletDO>().eq(PayWalletDO::getId, id)
.eq(PayWalletDO::getBalance, balance));
} }
} }

@ -62,13 +62,12 @@ public class WalletPayClient extends AbstractPayClient<NonePayClientConfig> {
@Override @Override
protected PayOrderRespDTO doUnifiedOrder(PayOrderUnifiedReqDTO reqDTO) { protected PayOrderRespDTO doUnifiedOrder(PayOrderUnifiedReqDTO reqDTO) {
try { try {
// TODO @jason直接 getLong 和 getInt 会不会更简洁哈 Long userId = MapUtil.getLong(reqDTO.getChannelExtras(), USER_ID_KEY);
String userId = MapUtil.getStr(reqDTO.getChannelExtras(), USER_ID_KEY); Integer userType = MapUtil.getInt(reqDTO.getChannelExtras(), USER_TYPE_KEY);
String userType = MapUtil.getStr(reqDTO.getChannelExtras(), USER_TYPE_KEY); Assert.notNull(userId, "用户 id 不能为空");
Assert.notEmpty(userId, "用户 id 不能为空"); Assert.notNull(userType, "用户类型不能为空");
Assert.notEmpty(userType, "用户类型不能为空"); PayWalletTransactionDO transaction = wallService.orderPay(userId, userType, reqDTO.getOutTradeNo(),
PayWalletTransactionDO transaction = wallService.orderPay(Long.valueOf(userId), Integer.valueOf(userType), reqDTO.getPrice());
reqDTO.getOutTradeNo(), reqDTO.getPrice());
return PayOrderRespDTO.successOf(transaction.getNo(), transaction.getCreator(), return PayOrderRespDTO.successOf(transaction.getNo(), transaction.getCreator(),
transaction.getCreateTime(), transaction.getCreateTime(),
reqDTO.getOutTradeNo(), transaction); reqDTO.getOutTradeNo(), transaction);

@ -6,10 +6,10 @@ 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.PayWalletDO;
import cn.iocoder.yudao.module.pay.dal.dataobject.wallet.PayWalletTransactionDO; 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.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.enums.member.PayWalletBizTypeEnum;
import cn.iocoder.yudao.module.pay.service.order.PayOrderService; 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.refund.PayRefundService;
import cn.iocoder.yudao.module.pay.service.wallet.bo.CreateWalletTransactionBO;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy; import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@ -18,7 +18,6 @@ import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.time.LocalDateTime; import java.time.LocalDateTime;
import static cn.iocoder.yudao.framework.common.exception.enums.GlobalErrorCodeConstants.TOO_MANY_REQUESTS;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception; import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.pay.enums.ErrorCodeConstants.*; 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;
@ -33,20 +32,8 @@ import static cn.iocoder.yudao.module.pay.enums.member.PayWalletBizTypeEnum.PAYM
@Slf4j @Slf4j
public class PayWalletServiceImpl implements PayWalletService { 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 @Resource
private PayWalletMapper walletMapper; private PayWalletMapper walletMapper;
@Resource
private PayNoRedisDAO noRedisDAO;
@Resource @Resource
private PayWalletTransactionService walletTransactionService; private PayWalletTransactionService walletTransactionService;
@Resource @Resource
@ -61,7 +48,7 @@ public class PayWalletServiceImpl implements PayWalletService {
PayWalletDO wallet = walletMapper.selectByUserIdAndType(userId, userType); PayWalletDO wallet = walletMapper.selectByUserIdAndType(userId, userType);
if (wallet == null) { if (wallet == null) {
wallet = new PayWalletDO().setUserId(userId).setUserType(userType) wallet = new PayWalletDO().setUserId(userId).setUserType(userType)
.setBalance(0).setTotalExpense(0L).setTotalRecharge(0L); .setBalance(0).setTotalExpense(0).setTotalRecharge(0);
wallet.setCreateTime(LocalDateTime.now()); wallet.setCreateTime(LocalDateTime.now());
walletMapper.insert(wallet); walletMapper.insert(wallet);
} }
@ -127,68 +114,50 @@ public class PayWalletServiceImpl implements PayWalletService {
Long bizId, PayWalletBizTypeEnum bizType, Integer price) { Long bizId, PayWalletBizTypeEnum bizType, Integer price) {
// 1.1 获取钱包 // 1.1 获取钱包
PayWalletDO payWallet = getOrCreateWallet(userId, userType); PayWalletDO payWallet = getOrCreateWallet(userId, userType);
// 1.2 判断余额是否足够
int afterBalance = payWallet.getBalance() - price;
if (afterBalance < 0) {
throw exception(WALLET_BALANCE_NOT_ENOUGH);
}
// TODO jason建议基于 where price >= 来做哈;然后抛出 WALLET_BALANCE_NOT_ENOUGH
// 2.1 扣除余额 // 2.1 扣除余额
int number = walletMapper.updateWhenDecBalance(bizType, payWallet.getBalance(), int number = 0 ;
payWallet.getTotalRecharge(), payWallet.getTotalExpense(), price, payWallet.getId()); switch (bizType) {
case PAYMENT: {
number = walletMapper.updateWhenConsumption(price, payWallet.getId());
break;
}
case RECHARGE_REFUND: {
// TODO
break;
}
}
if (number == 0) { if (number == 0) {
throw exception(TOO_MANY_REQUESTS); throw exception(WALLET_BALANCE_NOT_ENOUGH);
} }
int afterBalance = payWallet.getBalance() - price;
// 2.2 生成钱包流水 // 2.2 生成钱包流水
// TODO @jasonwalletNo 交给 payWalletTransactionService 自己生成哈; CreateWalletTransactionBO bo = new CreateWalletTransactionBO().setWalletId(payWallet.getId())
String walletNo = generateWalletNo(bizType); .setPrice(-price).setBalance(afterBalance).setBizId(String.valueOf(bizId))
PayWalletTransactionDO walletTransaction = new PayWalletTransactionDO().setWalletId(payWallet.getId()) .setBizType(bizType.getType()).setTitle(bizType.getDescription());
.setNo(walletNo).setPrice(-price).setBalance(afterBalance) return walletTransactionService.createWalletTransaction(bo);
.setBizId(String.valueOf(bizId)).setBizType(bizType.getType()).setTitle(bizType.getDescription());
// TODO @jason是不是可以 createWalletTransaction 搞个 bo 参数,然后 PayWalletTransactionDO 交回给 walletTransactionService 更好;然后把参数简化下
walletTransactionService.createWalletTransaction(walletTransaction);
return walletTransaction;
} }
@Override @Override
public PayWalletTransactionDO addWalletBalance(Long userId, Integer userType, public PayWalletTransactionDO addWalletBalance(Long userId, Integer userType,
Long bizId, PayWalletBizTypeEnum bizType, Integer price) { Long bizId, PayWalletBizTypeEnum bizType, Integer price) {
// 1.1 获取钱包 // 获取钱包
PayWalletDO payWallet = getOrCreateWallet(userId, userType); PayWalletDO payWallet = getOrCreateWallet(userId, userType);
switch (bizType) {
// 2.1 增加余额 case PAYMENT_REFUND: {
// TODO @jason类似上面的思路哈 // 更新退款
int number = walletMapper.updateWhenIncBalance(bizType, payWallet.getBalance(), payWallet.getTotalRecharge(), walletMapper.updateWhenConsumptionRefund(price, payWallet.getId());
payWallet.getTotalExpense(), price, payWallet.getId());
if (number == 0) {
throw exception(TOO_MANY_REQUESTS);
}
// 2.2 生成钱包流水
String walletNo = generateWalletNo(bizType);
PayWalletTransactionDO newWalletTransaction = new PayWalletTransactionDO().setWalletId(payWallet.getId())
.setNo(walletNo).setPrice(price).setBalance(payWallet.getBalance()+price)
.setBizId(String.valueOf(bizId)).setBizType(bizType.getType())
.setTitle(bizType.getDescription());
walletTransactionService.createWalletTransaction(newWalletTransaction);
return newWalletTransaction;
}
private String generateWalletNo(PayWalletBizTypeEnum bizType) {
// TODO @jason对于余额来说是不是直接 W+序号就行了,它其实不关注业务;;;不然就耦合啦
String no = "";
switch(bizType){
case PAYMENT:
no = noRedisDAO.generate(WALLET_PAY_NO_PREFIX);
break; break;
case PAYMENT_REFUND: }
no = noRedisDAO.generate(WALLET_REFUND_NO_PREFIX); case RECHARGE: {
//TODO
break; break;
default : }
} }
return no; // 2.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);
} }
} }

@ -4,6 +4,7 @@ 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.controller.app.wallet.vo.transaction.AppPayWalletTransactionPageReqVO;
import cn.iocoder.yudao.module.pay.dal.dataobject.wallet.PayWalletTransactionDO; 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.member.PayWalletBizTypeEnum;
import cn.iocoder.yudao.module.pay.service.wallet.bo.CreateWalletTransactionBO;
/** /**
* Service * Service
@ -25,10 +26,10 @@ public interface PayWalletTransactionService {
/** /**
* *
* *
* @param payWalletTransaction * @param bo bo
* @return id * @return do
*/ */
Long createWalletTransaction(PayWalletTransactionDO payWalletTransaction); PayWalletTransactionDO createWalletTransaction(CreateWalletTransactionBO bo);
/** /**
* no * no

@ -2,10 +2,13 @@ package cn.iocoder.yudao.module.pay.service.wallet;
import cn.iocoder.yudao.framework.common.pojo.PageResult; 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.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.PayWalletDO;
import cn.iocoder.yudao.module.pay.dal.dataobject.wallet.PayWalletTransactionDO; 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.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.enums.member.PayWalletBizTypeEnum;
import cn.iocoder.yudao.module.pay.service.wallet.bo.CreateWalletTransactionBO;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@ -19,11 +22,16 @@ import javax.annotation.Resource;
@Service @Service
@Slf4j @Slf4j
public class PayWalletTransactionServiceImpl implements PayWalletTransactionService { public class PayWalletTransactionServiceImpl implements PayWalletTransactionService {
/**
* no
*/
private static final String WALLET_NO_PREFIX = "W";
@Resource @Resource
private PayWalletService payWalletService; private PayWalletService payWalletService;
@Resource @Resource
private PayWalletTransactionMapper payWalletTransactionMapper; private PayWalletTransactionMapper payWalletTransactionMapper;
@Resource
private PayNoRedisDAO noRedisDAO;
@Override @Override
public PageResult<PayWalletTransactionDO> getWalletTransactionPage(Long userId, Integer userType, public PageResult<PayWalletTransactionDO> getWalletTransactionPage(Long userId, Integer userType,
@ -33,9 +41,11 @@ public class PayWalletTransactionServiceImpl implements PayWalletTransactionServ
} }
@Override @Override
public Long createWalletTransaction(PayWalletTransactionDO payWalletTransaction) { public PayWalletTransactionDO createWalletTransaction(CreateWalletTransactionBO bo) {
payWalletTransactionMapper.insert(payWalletTransaction); PayWalletTransactionDO transactionDO = PayWalletTransactionConvert.INSTANCE.convert(bo);
return payWalletTransaction.getId(); transactionDO.setNo(noRedisDAO.generate(WALLET_NO_PREFIX));
payWalletTransactionMapper.insert(transactionDO);
return transactionDO;
} }
@Override @Override

@ -0,0 +1,48 @@
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 {
/**
*
*
*/
private Long walletId;
/**
*
*
*
*/
private Integer price;
/**
*
*/
private Integer balance;
/**
*
*
* {@link PayWalletBizTypeEnum#getType()}
*/
private Integer bizType;
/**
*
*/
private String bizId;
/**
*
*/
private String title;
}
Loading…
Cancel
Save