Files
likedream/internal/service/balance/balance_service.go
T
sugarBecomer 97ab3a7a1d 🐛 代理设置
2025-11-07 19:23:01 +08:00

44 lines
998 B
Go

package balance
import (
"context"
"likedream-goframe/internal/common/errors"
"likedream-goframe/internal/db"
"likedream-goframe/internal/ent"
"likedream-goframe/internal/ent/sysuser"
"likedream-goframe/internal/utils"
"github.com/shopspring/decimal"
)
var BalanceService = &BalanceServiceV1{}
type BalanceServiceV1 struct {
}
func (v *BalanceServiceV1) ChangeUserBalance(ctx context.Context, userId int64, balance decimal.Decimal) error {
return db.WithTx(ctx, func(c context.Context, tx *ent.Tx) {
// 使用 SELECT ... FOR UPDATE 锁定用户记录
user, err := tx.SysUser.Query().
Where(sysuser.ID(userId)).
ForUpdate().
Only(ctx)
if err != nil {
utils.OkOrPanic(err)
}
newBalance := user.Balance.Add(balance)
if newBalance.LessThan(decimal.Zero) {
utils.OkOrPanic(errors.NewBusinessError(400, "余额不足"))
}
// 更新余额
tx.SysUser.Update().
Where(sysuser.ID(userId)).
SetBalance(newBalance).
ExecX(ctx)
tx.Commit()
}, nil)
}