(quota int)
| 272 | } |
| 273 | |
| 274 | func (user *User) TransferAffQuotaToQuota(quota int) error { |
| 275 | // 检查quota是否小于最小额度 |
| 276 | if float64(quota) < common.QuotaPerUnit { |
| 277 | return fmt.Errorf("转移额度最小为%s!", common.LogQuota(int(common.QuotaPerUnit))) |
| 278 | } |
| 279 | |
| 280 | // 开始数据库事务 |
| 281 | tx := DB.Begin() |
| 282 | if tx.Error != nil { |
| 283 | return tx.Error |
| 284 | } |
| 285 | defer tx.Rollback() // 确保在函数退出时事务能回滚 |
| 286 | |
| 287 | // 加锁查询用户以确保数据一致性 |
| 288 | err := tx.Set("gorm:query_option", "FOR UPDATE").First(&user, user.Id).Error |
| 289 | if err != nil { |
| 290 | return err |
| 291 | } |
| 292 | |
| 293 | // 再次检查用户的AffQuota是否足够 |
| 294 | if user.AffQuota < quota { |
| 295 | return errors.New("邀请额度不足!") |
| 296 | } |
| 297 | |
| 298 | // 更新用户额度 |
| 299 | user.AffQuota -= quota |
| 300 | user.Quota += quota |
| 301 | |
| 302 | // 保存用户状态 |
| 303 | if err := tx.Save(user).Error; err != nil { |
| 304 | return err |
| 305 | } |
| 306 | |
| 307 | // 提交事务 |
| 308 | return tx.Commit().Error |
| 309 | } |
| 310 | |
| 311 | func (user *User) Insert(inviterId int) error { |
| 312 | var err error |
no test coverage detected