(key string, userId int)
| 49 | } |
| 50 | |
| 51 | func Redeem(key string, userId int) (quota int64, err error) { |
| 52 | if key == "" { |
| 53 | return 0, errors.New("未提供兑换码") |
| 54 | } |
| 55 | if userId == 0 { |
| 56 | return 0, errors.New("无效的 user id") |
| 57 | } |
| 58 | redemption := &Redemption{} |
| 59 | |
| 60 | keyCol := "`key`" |
| 61 | if common.UsingPostgreSQL { |
| 62 | keyCol = `"key"` |
| 63 | } |
| 64 | |
| 65 | err = DB.Transaction(func(tx *gorm.DB) error { |
| 66 | err := tx.Set("gorm:query_option", "FOR UPDATE").Where(keyCol+" = ?", key).First(redemption).Error |
| 67 | if err != nil { |
| 68 | return errors.New("无效的兑换码") |
| 69 | } |
| 70 | if redemption.Status != RedemptionCodeStatusEnabled { |
| 71 | return errors.New("该兑换码已被使用") |
| 72 | } |
| 73 | err = tx.Model(&User{}).Where("id = ?", userId).Update("quota", gorm.Expr("quota + ?", redemption.Quota)).Error |
| 74 | if err != nil { |
| 75 | return err |
| 76 | } |
| 77 | redemption.RedeemedTime = helper.GetTimestamp() |
| 78 | redemption.Status = RedemptionCodeStatusUsed |
| 79 | err = tx.Save(redemption).Error |
| 80 | return err |
| 81 | }) |
| 82 | if err != nil { |
| 83 | return 0, errors.New("兑换失败," + err.Error()) |
| 84 | } |
| 85 | RecordLog(userId, LogTypeTopup, fmt.Sprintf("通过兑换码充值 %s", common.LogQuota(redemption.Quota))) |
| 86 | return redemption.Quota, nil |
| 87 | } |
| 88 | |
| 89 | func (redemption *Redemption) Insert() error { |
| 90 | var err error |
no test coverage detected