🐛 修改余额问题

This commit is contained in:
sugarBecomer
2025-11-03 21:46:01 +08:00
parent 7d8c14a045
commit 132472de12
+8 -2
View File
@@ -6,21 +6,27 @@ import (
"likedream-goframe/internal/db" "likedream-goframe/internal/db"
"likedream-goframe/internal/ent/sysuser" "likedream-goframe/internal/ent/sysuser"
"likedream-goframe/internal/utils" "likedream-goframe/internal/utils"
"sync"
"github.com/samber/oops" "github.com/samber/oops"
"github.com/shopspring/decimal" "github.com/shopspring/decimal"
) )
var BalanceService = &BalanceServiceV1{} var BalanceService = &BalanceServiceV1{
lock: sync.Mutex{},
}
type BalanceServiceV1 struct { type BalanceServiceV1 struct {
lock sync.Mutex
} }
func (v *BalanceServiceV1) ChangeUserBalance(ctx context.Context, userId int64, balance decimal.Decimal) { func (v *BalanceServiceV1) ChangeUserBalance(ctx context.Context, userId int64, balance decimal.Decimal) {
v.lock.Lock()
defer v.lock.Unlock()
tx, err := db.Global.Tx(ctx) tx, err := db.Global.Tx(ctx)
utils.OkOrPanic(err, oops.WithContext(ctx).Wrap) utils.OkOrPanic(err, oops.WithContext(ctx).Wrap)
defer tx.Rollback() defer tx.Rollback()
user := tx.SysUser.Query().Where(sysuser.ID(userId)).WithRoles().ForUpdate().OnlyX(ctx) user := tx.SysUser.Query().Where(sysuser.ID(userId)).WithRoles().OnlyX(ctx)
newBalance := user.Balance.Add(balance) newBalance := user.Balance.Add(balance)
if newBalance.LessThan(decimal.Zero) { if newBalance.LessThan(decimal.Zero) {
utils.OkOrPanic(errors.NewBusinessError(400, "余额不足")) utils.OkOrPanic(errors.NewBusinessError(400, "余额不足"))