Skip to content

Commit

Permalink
fix: return quota to user when delete token (close #37)
Browse files Browse the repository at this point in the history
  • Loading branch information
songquanpeng committed May 4, 2023
1 parent 4fed003 commit 331177d
Show file tree
Hide file tree
Showing 4 changed files with 22 additions and 6 deletions.
2 changes: 1 addition & 1 deletion controller/relay.go
Original file line number Diff line number Diff line change
Expand Up @@ -137,7 +137,7 @@ func relayHelper(c *gin.Context) error {
ratio = common.RatioGPT3dot5
}
quota = int(float64(quota) * ratio)
err := model.ConsumeTokenQuota(tokenId, quota)
err := model.DecreaseTokenQuota(tokenId, quota)
if err != nil {
common.SysError("Error consuming token remain quota: " + err.Error())
}
Expand Down
2 changes: 1 addition & 1 deletion model/redemption.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ func Redeem(key string, tokenId int) (quota int, err error) {
if redemption.Status != common.RedemptionCodeStatusEnabled {
return 0, errors.New("该兑换码已被使用")
}
err = TopUpTokenQuota(tokenId, redemption.Quota)
err = IncreaseTokenQuota(tokenId, redemption.Quota)
if err != nil {
return 0, err
}
Expand Down
19 changes: 15 additions & 4 deletions model/token.go
Original file line number Diff line number Diff line change
Expand Up @@ -116,15 +116,26 @@ func DeleteTokenById(id int, userId int) (err error) {
if err != nil {
return err
}
quota := token.RemainQuota
if quota != 0 {
if quota > 0 {
err = IncreaseUserQuota(userId, quota)
} else {
err = DecreaseUserQuota(userId, quota)
}
}
if err != nil {
return err
}
return token.Delete()
}

func ConsumeTokenQuota(id int, quota int) (err error) {
err = DB.Model(&Token{}).Where("id = ?", id).Update("remain_quota", gorm.Expr("remain_quota - ?", quota)).Error
func IncreaseTokenQuota(id int, quota int) (err error) {
err = DB.Model(&Token{}).Where("id = ?", id).Update("remain_quota", gorm.Expr("remain_quota + ?", quota)).Error
return err
}

func TopUpTokenQuota(id int, quota int) (err error) {
err = DB.Model(&Token{}).Where("id = ?", id).Update("remain_quota", gorm.Expr("remain_quota + ?", quota)).Error
func DecreaseTokenQuota(id int, quota int) (err error) {
err = DB.Model(&Token{}).Where("id = ?", id).Update("remain_quota", gorm.Expr("remain_quota - ?", quota)).Error
return err
}
5 changes: 5 additions & 0 deletions model/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -225,6 +225,11 @@ func GetUserQuota(id int) (quota int, err error) {
return quota, err
}

func IncreaseUserQuota(id int, quota int) (err error) {
err = DB.Model(&User{}).Where("id = ?", id).Update("quota", gorm.Expr("quota + ?", quota)).Error
return err
}

func DecreaseUserQuota(id int, quota int) (err error) {
err = DB.Model(&User{}).Where("id = ?", id).Update("quota", gorm.Expr("quota - ?", quota)).Error
return err
Expand Down

0 comments on commit 331177d

Please sign in to comment.