修改余额改为使用芋道新更新的

This commit is contained in:
XinWei 2024-10-08 14:10:21 +08:00
parent 00b8b3ab61
commit 38fd2ecc6a
8 changed files with 224 additions and 110 deletions

View File

@ -1,20 +1,20 @@
<template>
<Dialog title="修改用户余额" v-model="dialogVisible" width="600">
<Dialog v-model="dialogVisible" title="修改用户余额" width="600">
<el-form
ref="formRef"
v-loading="formLoading"
:model="formData"
:rules="formRules"
label-width="100px"
v-loading="formLoading"
label-width="130px"
>
<el-form-item label="用户编号" prop="userId">
<el-input v-model="formData.userId" class="!w-240px" disabled />
<el-form-item label="用户编号" prop="id">
<el-input v-model="formData.id" class="!w-240px" disabled />
</el-form-item>
<el-form-item label="用户昵称" prop="nickname">
<el-input v-model="formData.nickname" class="!w-240px" disabled />
</el-form-item>
<el-form-item label="变动前余额" prop="balance">
<el-input-number v-model="formData.balance" class="!w-240px" :precision="2" disabled />
<el-form-item label="变动前余额(元)" prop="balance">
<el-input :model-value="formData.balance" class="!w-240px" disabled />
</el-form-item>
<el-form-item label="变动类型" prop="changeType">
<el-radio-group v-model="formData.changeType">
@ -22,24 +22,32 @@
<el-radio :label="-1">减少</el-radio>
</el-radio-group>
</el-form-item>
<el-form-item label="变动余额" prop="changePoint">
<el-input-number v-model="formData.changePoint" class="!w-240px" :min="0" :precision="2" />
<el-form-item label="变动余额(元)" prop="changeBalance">
<el-input-number
v-model="formData.changeBalance"
:min="0"
:precision="2"
:step="0.1"
class="!w-240px"
/>
</el-form-item>
<el-form-item label="变动后余额">
<el-input-number v-model="pointResult" class="!w-240px" :precision="2" disabled />
<el-form-item label="变动后余额(元)">
<el-input :model-value="balanceResult" class="!w-240px" disabled />
</el-form-item>
</el-form>
<template #footer>
<el-button @click="submitForm" type="primary" :disabled="formLoading"> </el-button>
<el-button :disabled="formLoading" type="primary" @click="submitForm"> </el-button>
<el-button @click="dialogVisible = false"> </el-button>
</template>
</Dialog>
</template>
<script setup lang="ts">
import * as UserApi from '@/api/pay/wallet/balance'
import * as UserApi2 from '@/api/member/user'
<script lang="ts" setup>
import * as UserApi from '@/api/member/user'
import * as WalletApi from '@/api/pay/wallet/balance'
import { convertToInteger, formatToFraction } from '@/utils'
/** 修改用户余额表单 */
defineOptions({ name: 'UpdatePointForm' })
defineOptions({ name: 'UpdateBalanceForm' })
const { t } = useI18n() //
const message = useMessage() //
@ -48,14 +56,13 @@ const dialogVisible = ref(false) // 弹窗的是否展示
const formLoading = ref(false) // 12
const formData = ref({
id: undefined,
userId: undefined,
nickname: undefined,
balance: 0,
changePoint: 0,
balance: '0',
changeBalance: 0,
changeType: 1
})
const formRules = reactive({
changePoint: [{ required: true, message: '变动余额不能为空', trigger: 'blur' }]
changeBalance: [{ required: true, message: '变动余额不能为空', trigger: 'blur' }]
})
const formRef = ref() // Ref
@ -67,14 +74,13 @@ const open = async (id?: number) => {
if (id) {
formLoading.value = true
try {
const param = { userId: id }
const wallet = await UserApi.getWallet(param)
formData.value = wallet
formData.value.balance = wallet.balance / 100.0;
const user = await UserApi2.getUser(id);
formData.value.nickname = user.nickname;
const user = await UserApi.getUser(id)
const wallet = await WalletApi.getWallet({ userId: user.id || 0 })
formData.value.id = user.id
formData.value.nickname = user.nickname
formData.value.balance = formatToFraction(wallet.balance)
formData.value.changeType = 1 //
formData.value.changePoint = 0 // 0
formData.value.changeBalance = 0 // 0
} finally {
formLoading.value = false
}
@ -90,11 +96,11 @@ const submitForm = async () => {
const valid = await formRef.value.validate()
if (!valid) return
if (formData.value.changePoint < 1) {
message.error('变动余额不能小于 1')
if (formData.value.changeBalance <= 0) {
message.error('变动余额不能为零')
return
}
if (pointResult.value < 0) {
if (convertToInteger(balanceResult.value) < 0) {
message.error('变动后的余额不能小于 0')
return
}
@ -102,9 +108,9 @@ const submitForm = async () => {
//
formLoading.value = true
try {
await UserApi.updateWalletBalance({
id: formData.value.id,
balance: formData.value.changePoint * formData.value.changeType
await WalletApi.updateWalletBalance({
userId: formData.value.id,
balance: convertToInteger(formData.value.changeBalance) * formData.value.changeType
})
message.success(t('common.updateSuccess'))
@ -121,14 +127,18 @@ const resetForm = () => {
formData.value = {
id: undefined,
nickname: undefined,
balance: undefined,
reason: undefined
balance: '0',
changeBalance: 0,
changeType: 1
}
formRef.value?.resetFields()
}
/** 变动后的余额 */
const pointResult = computed(
() => formData.value.balance + formData.value.changePoint * formData.value.changeType
const balanceResult = computed(() =>
formatToFraction(
convertToInteger(formData.value.balance) +
convertToInteger(formData.value.changeBalance) * formData.value.changeType
)
)
</script>

View File

@ -19,8 +19,8 @@ public enum PayWalletBizTypeEnum implements IntArrayValuable {
RECHARGE_REFUND(2, "充值退款"),
PAYMENT(3, "支付"),
PAYMENT_REFUND(4, "支付退款"),
ADMIN_MODIFY(5, "管理员修改");
// ADMIN_MODIFY(5, "管理员修改");
UPDATE_BALANCE(5, "更新余额");
// TODO 后续增加
/**

View File

@ -2,12 +2,10 @@ package cn.iocoder.yudao.module.pay.controller.admin.wallet;
import cn.iocoder.yudao.framework.common.pojo.CommonResult;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.module.pay.controller.admin.wallet.vo.wallet.PayWalletPageReqVO;
import cn.iocoder.yudao.module.pay.controller.admin.wallet.vo.wallet.PayWalletRespVO;
import cn.iocoder.yudao.module.pay.controller.admin.wallet.vo.wallet.PayWalletUserBalanceVo;
import cn.iocoder.yudao.module.pay.controller.admin.wallet.vo.wallet.PayWalletUserReqVO;
import cn.iocoder.yudao.module.pay.controller.admin.wallet.vo.wallet.*;
import cn.iocoder.yudao.module.pay.convert.wallet.PayWalletConvert;
import cn.iocoder.yudao.module.pay.dal.dataobject.wallet.PayWalletDO;
import cn.iocoder.yudao.module.pay.enums.wallet.PayWalletBizTypeEnum;
import cn.iocoder.yudao.module.pay.service.wallet.PayWalletService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
@ -20,7 +18,9 @@ import javax.annotation.Resource;
import javax.validation.Valid;
import static cn.iocoder.yudao.framework.common.enums.UserTypeEnum.MEMBER;
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.common.pojo.CommonResult.success;
import static cn.iocoder.yudao.module.pay.enums.ErrorCodeConstants.WALLET_NOT_FOUND;
@Tag(name = "管理后台 - 用户钱包")
@RestController
@ -40,11 +40,27 @@ public class PayWalletController {
return success(PayWalletConvert.INSTANCE.convert02(wallet));
}
@PostMapping("/update")
@PreAuthorize("@ss.hasPermission('pay:wallet:update')")
@Operation(summary = "修改用户钱包余额(后台操作)")
public CommonResult<Boolean> updateWallet(@Valid @RequestBody PayWalletUserBalanceVo reqVo){
payWalletService.updateWallet(reqVo);
// @PostMapping("/update")
// @PreAuthorize("@ss.hasPermission('pay:wallet:update')")
// @Operation(summary = "修改用户钱包余额(后台操作)")
// public CommonResult<Boolean> updateWallet(@Valid @RequestBody PayWalletUserBalanceVo reqVo){
// payWalletService.updateWallet(reqVo);
// return success(true);
// }
@PutMapping("/update-balance")
@Operation(summary = "更新会员用户余额")
@PreAuthorize("@ss.hasPermission('pay:wallet:update-balance')")
public CommonResult<Boolean> updateWalletBalance(@Valid @RequestBody PayWalletUpdateBalanceReqVO updateReqVO) {
// 获得用户钱包
PayWalletDO wallet = payWalletService.getOrCreateWallet(updateReqVO.getUserId(), MEMBER.getValue());
if (wallet == null) {
log.error("[updateWalletBalance]updateReqVO({}) 用户钱包不存在.", updateReqVO);
throw exception(WALLET_NOT_FOUND);
}
// 更新钱包余额
payWalletService.addWalletBalance(wallet.getId(), String.valueOf(updateReqVO.getUserId()),
PayWalletBizTypeEnum.UPDATE_BALANCE, updateReqVO.getBalance());
return success(true);
}

View File

@ -0,0 +1,20 @@
package cn.iocoder.yudao.module.pay.controller.admin.wallet.vo.wallet;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import javax.validation.constraints.NotNull;
@Schema(description = "管理后台 - 修改钱包余额 Request VO")
@Data
public class PayWalletUpdateBalanceReqVO {
@Schema(description = "用户编号", requiredMode = Schema.RequiredMode.REQUIRED, example = "23788")
@NotNull(message = "用户编号不能为空")
private Long userId;
@Schema(description = "变动余额,正数为增加,负数为减少", requiredMode = Schema.RequiredMode.REQUIRED, example = "100")
@NotNull(message = "变动余额不能为空")
private Integer balance;
}

View File

@ -15,7 +15,14 @@ public interface RedisKeyConstants {
* 过期时间不固定
*/
String PAY_NOTIFY_LOCK = "pay_notify:lock:%d";
/**
* 支付钱包的分布式锁
*
* KEY 格式pay_wallet:lock:%d
* VALUE 数据格式HASH // RLock.classRedisson Lock 使用 Hash 数据结构
* 过期时间不固定
*/
String PAY_WALLET_LOCK = "pay_wallet:lock:%d";
/**
* 支付序号的缓存
*

View File

@ -0,0 +1,43 @@
package cn.iocoder.yudao.module.pay.dal.redis.wallet;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Repository;
import javax.annotation.Resource;
import java.util.concurrent.Callable;
import java.util.concurrent.TimeUnit;
import static cn.iocoder.yudao.module.pay.dal.redis.RedisKeyConstants.PAY_WALLET_LOCK;
/**
* 支付钱包的锁 Redis DAO
*
* @author 芋道源码
*/
@Repository
public class PayWalletLockRedisDAO {
@Resource
private RedissonClient redissonClient;
public <V> V lock(Long id, Long timeoutMillis, Callable<V> callable) throws Exception {
String lockKey = formatKey(id);
RLock lock = redissonClient.getLock(lockKey);
try {
lock.lock(timeoutMillis, TimeUnit.MILLISECONDS);
// 执行逻辑
return callable.call();
} catch (Exception e) {
throw e;
} finally {
lock.unlock();
}
}
private static String formatKey(Long id) {
return String.format(PAY_WALLET_LOCK, id);
}
}

View File

@ -98,10 +98,10 @@ public interface PayWalletService {
*/
void unfreezePrice(Long id, Integer price);
/**
* 修改钱包余额后台操作
* @param reqVo
* @return void
*/
void updateWallet(PayWalletUserBalanceVo reqVo);
// /**
// * 修改钱包余额后台操作
// * @param reqVo
// * @return void
// */
// void updateWallet(PayWalletUserBalanceVo reqVo);
}

View File

@ -2,6 +2,7 @@ package cn.iocoder.yudao.module.pay.service.wallet;
import cn.hutool.core.lang.Assert;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.date.DateUtils;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.pay.controller.admin.wallet.vo.wallet.PayWalletPageReqVO;
import cn.iocoder.yudao.module.pay.controller.admin.wallet.vo.wallet.PayWalletUserBalanceVo;
@ -10,10 +11,12 @@ 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.wallet.PayWalletLockRedisDAO;
import cn.iocoder.yudao.module.pay.enums.wallet.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.WalletTransactionCreateReqBO;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
@ -36,7 +39,10 @@ import static cn.iocoder.yudao.module.pay.enums.wallet.PayWalletBizTypeEnum.PAYM
@Service
@Slf4j
public class PayWalletServiceImpl implements PayWalletService {
/**
* 通知超时时间单位毫秒
*/
public static final long UPDATE_TIMEOUT_MILLIS = 120 * DateUtils.SECOND_MILLIS;
@Resource
private PayWalletMapper walletMapper;
@ -50,6 +56,9 @@ public class PayWalletServiceImpl implements PayWalletService {
@Lazy // 延迟加载避免循环依赖
private PayRefundService refundService;
@Resource
private PayWalletLockRedisDAO lockRedisDAO;
@Override
public PayWalletDO getOrCreateWallet(Long userId, Integer userType) {
PayWalletDO wallet = walletMapper.selectByUserIdAndType(userId, userType);
@ -161,15 +170,20 @@ public class PayWalletServiceImpl implements PayWalletService {
}
@Override
@Transactional(rollbackFor = Exception.class)
@SneakyThrows
public PayWalletTransactionDO addWalletBalance(Long walletId, String bizId,
PayWalletBizTypeEnum bizType, Integer price) {
// 1.1 获取钱包
// 1. 获取钱包
PayWalletDO payWallet = getWallet(walletId);
if (payWallet == null) {
log.error("[addWalletBalance],用户钱包({})不存在.", walletId);
log.error("[addWalletBalance][用户钱包({})不存在]", walletId);
throw exception(WALLET_NOT_FOUND);
}
// 1.2 更新钱包金额
// 2. 加锁更新钱包余额目的避免钱包流水的并发更新时余额变化不连贯
return lockRedisDAO.lock(walletId, UPDATE_TIMEOUT_MILLIS, () -> {
// 2. 更新钱包金额
switch (bizType) {
case PAYMENT_REFUND: { // 退款更新
walletMapper.updateWhenConsumptionRefund(payWallet.getId(), price);
@ -179,17 +193,21 @@ public class PayWalletServiceImpl implements PayWalletService {
walletMapper.updateWhenRecharge(payWallet.getId(), price);
break;
}
case UPDATE_BALANCE: // 更新余额
walletMapper.updateWhenRecharge(payWallet.getId(), price);
break;
default: {
// TODO 其它类型待实现
throw new UnsupportedOperationException("待实现");
}
}
// 2. 生成钱包流水
// 3. 生成钱包流水
WalletTransactionCreateReqBO transactionCreateReqBO = new WalletTransactionCreateReqBO()
.setWalletId(payWallet.getId()).setPrice(price).setBalance(payWallet.getBalance() + price)
.setBizId(bizId).setBizType(bizType.getType()).setTitle(bizType.getDescription());
return walletTransactionService.createWalletTransaction(transactionCreateReqBO);
});
}
@Override
@ -208,37 +226,37 @@ public class PayWalletServiceImpl implements PayWalletService {
}
}
@Override
public void updateWallet(PayWalletUserBalanceVo reqVo) {
// 如果
if (reqVo.getBalance().compareTo(BigDecimal.ZERO) == 0) {
return;
}
// 把单位从元转为分
BigDecimal change = new BigDecimal("100");
// 查出对应钱包信息
PayWalletDO walletDO = walletMapper.selectById(reqVo.getId());
if (reqVo.getBalance().compareTo(new BigDecimal("21474836.47")) > 0) {
throw exception(WALLET_RECHARGE_RANGE_EXCEPTION);
}
// 总共改变的金额
long changeBalance = (reqVo.getBalance().multiply(change)).longValue();
// 总余额
long totalBalance = walletDO.getBalance() + changeBalance;
// 总充值
long totalRecharge = walletDO.getTotalRecharge() + changeBalance;
if (totalBalance > 2147483647 || totalRecharge > 2147483647 || totalBalance < 0 || totalRecharge < 0) {
throw exception(WALLET_RECHARGE_RANGE_EXCEPTION);
}
walletDO.setBalance((int) totalBalance);
walletDO.setTotalRecharge((int) totalRecharge);
walletMapper.updateById(walletDO);
String title = "后台操作给用户" + (totalBalance > 0 ? "增加" : "减少") + "余额" + Math.abs(changeBalance)/100.0 + "";
WalletTransactionCreateReqBO transactionCreateReqBO = new WalletTransactionCreateReqBO()
.setWalletId(reqVo.getId()).setPrice((int) changeBalance).setBalance((int) totalBalance)
.setBizType(PayWalletBizTypeEnum.ADMIN_MODIFY.getType()).setBizId("0").setTitle(title);
walletTransactionService.createWalletTransaction(transactionCreateReqBO);
}
// @Override
// public void updateWallet(PayWalletUserBalanceVo reqVo) {
// // 如果
// if (reqVo.getBalance().compareTo(BigDecimal.ZERO) == 0) {
// return;
// }
// // 把单位从元转为分
// BigDecimal change = new BigDecimal("100");
// // 查出对应钱包信息
// PayWalletDO walletDO = walletMapper.selectById(reqVo.getId());
// if (reqVo.getBalance().compareTo(new BigDecimal("21474836.47")) > 0) {
// throw exception(WALLET_RECHARGE_RANGE_EXCEPTION);
// }
// // 总共改变的金额
// long changeBalance = (reqVo.getBalance().multiply(change)).longValue();
// // 总余额
// long totalBalance = walletDO.getBalance() + changeBalance;
// // 总充值
// long totalRecharge = walletDO.getTotalRecharge() + changeBalance;
// if (totalBalance > 2147483647 || totalRecharge > 2147483647 || totalBalance < 0 || totalRecharge < 0) {
// throw exception(WALLET_RECHARGE_RANGE_EXCEPTION);
// }
// walletDO.setBalance((int) totalBalance);
// walletDO.setTotalRecharge((int) totalRecharge);
// walletMapper.updateById(walletDO);
// String title = "后台操作给用户" + (totalBalance > 0 ? "增加" : "减少") + "余额" + Math.abs(changeBalance)/100.0 + "";
// WalletTransactionCreateReqBO transactionCreateReqBO = new WalletTransactionCreateReqBO()
// .setWalletId(reqVo.getId()).setPrice((int) changeBalance).setBalance((int) totalBalance)
// .setBizType(PayWalletBizTypeEnum.ADMIN_MODIFY.getType()).setBizId("0").setTitle(title);
// walletTransactionService.createWalletTransaction(transactionCreateReqBO);
//
// }
}