37 lines
945 B
Go
37 lines
945 B
Go
package balance
|
|
|
|
import (
|
|
"context"
|
|
"likedream-goframe/internal/common/errors"
|
|
"likedream-goframe/internal/db"
|
|
"likedream-goframe/internal/ent/sysuser"
|
|
"likedream-goframe/internal/utils"
|
|
"sync"
|
|
|
|
"github.com/samber/oops"
|
|
"github.com/shopspring/decimal"
|
|
)
|
|
|
|
var BalanceService = &BalanceServiceV1{
|
|
lock: sync.Mutex{},
|
|
}
|
|
|
|
type BalanceServiceV1 struct {
|
|
lock sync.Mutex
|
|
}
|
|
|
|
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)
|
|
utils.OkOrPanic(err, oops.WithContext(ctx).Wrap)
|
|
defer tx.Rollback()
|
|
user := tx.SysUser.Query().Where(sysuser.ID(userId)).WithRoles().OnlyX(ctx)
|
|
newBalance := user.Balance.Add(balance)
|
|
if newBalance.LessThan(decimal.Zero) {
|
|
utils.OkOrPanic(errors.NewBusinessError(400, "余额不足"))
|
|
}
|
|
tx.SysUser.Update().Where(sysuser.ID(userId)).SetBalance(newBalance).SaveX(ctx)
|
|
tx.Commit()
|
|
}
|