Files
new-api/model/redemption.go
Lich-Mac-Mini 06f9bde3c9 Merge tag 'v0.12.12' into codex/redeem-subscription
v0.12.12

# -----BEGIN PGP SIGNATURE-----
#
# iQIzBAABCAAdFiEELDLYXndFTEpGR0CuDPphNSmpkh0FAmnhzLIACgkQDPphNSmp
# kh19mg/+JdGRYXBMPXap8sJCWZ6QNkro5/PtNyy8GOiqDPb42Ud2QM7472P8IZj1
# TIVa/cjU4Vg+BJYKkvJ5oHmJBFLsvLUyjyhKEU7hdrgBBufNGriJsTERYNAwAzHo
# pnzbzVzQClN19ficvbobdkiT4zBpxmyC4kuWRcDePQga10wX2oTyAlBsZ2MZg2Go
# 2ceXPgkfatEMkwjULZtaVC3BxznQ5nhEpSPOSeJufKsf/tHpso3IfcoA7be62Mmd
# gh0syQUV4dH2PJ1kz/ihentLse4SDI1018fn6W2fBxAwcamaFP/Arr366c1pLck0
# IeISGUfoScSHGTu2dHJ3h0nuOqATyd/mXfzNnox58p+eQ+52eSfyiOyjx5sQ04WG
# SRgso3Zl6F/fBcCKy8YPHAIJVuoRJMSfi0QSdMD3pdhdwb6E5GQ+J2y80WDg7XN3
# PPrRRp5Quq4aSSMBVcuCvANIFHu6DeyLm8MIBbeujByXzW6ODDpEo74HxCeUKqE+
# Dbwo7c5GMY4mUdQTGo4QuFVB+OFcPY+d4uSRwt0YDT4s9ySJNyNJg2fv6JOwMQVx
# wIfpI5pOrgGDpQgTjeMw1NzA6oPHaOk41ZcqzJ1onB+hh0KYO+401cXFoVkZqxW/
# uHZTspy56M71HsCqNmB6MtqScNWlQhKuRxa4drMRqT+QddbiWHo=
# =Byz/
# -----END PGP SIGNATURE-----

# Conflicts:
#	model/redemption.go
#	web/package.json
#	web/src/components/table/redemptions/modals/EditRedemptionModal.jsx
2026-04-17 19:29:19 +08:00

257 lines
7.3 KiB
Go

package model
import (
"errors"
"fmt"
"strconv"
"strings"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/logger"
"gorm.io/gorm"
)
const (
RedemptionTypeQuota = "quota"
RedemptionTypeSubscription = "subscription"
)
type RedeemResult struct {
RedeemType string `json:"redeem_type"`
Quota int `json:"quota,omitempty"`
PlanId int `json:"plan_id,omitempty"`
PlanTitle string `json:"plan_title,omitempty"`
SubscriptionId int `json:"subscription_id,omitempty"`
}
type Redemption struct {
Id int `json:"id"`
UserId int `json:"user_id"`
Key string `json:"key" gorm:"type:char(32);uniqueIndex"`
Status int `json:"status" gorm:"default:1"`
Name string `json:"name" gorm:"index"`
Quota int `json:"quota" gorm:"default:100"`
RedeemType string `json:"redeem_type" gorm:"type:varchar(32);not null;default:'quota'"`
PlanId int `json:"plan_id" gorm:"default:0;index"`
SourceNote string `json:"source_note" gorm:"type:varchar(255);default:''"`
PlanTitle string `json:"plan_title" gorm:"-:all"`
CreatedTime int64 `json:"created_time" gorm:"bigint"`
RedeemedTime int64 `json:"redeemed_time" gorm:"bigint"`
Count int `json:"count" gorm:"-:all"` // only for api request
UsedUserId int `json:"used_user_id"`
DeletedAt gorm.DeletedAt `gorm:"index"`
ExpiredTime int64 `json:"expired_time" gorm:"bigint"`
}
func NormalizeRedemptionType(raw string) string {
switch strings.TrimSpace(strings.ToLower(raw)) {
case "", RedemptionTypeQuota:
return RedemptionTypeQuota
case RedemptionTypeSubscription:
return RedemptionTypeSubscription
default:
return ""
}
}
func GetAllRedemptions(startIdx int, num int) (redemptions []*Redemption, total int64, err error) {
tx := DB.Begin()
if tx.Error != nil {
return nil, 0, tx.Error
}
defer func() {
if r := recover(); r != nil {
tx.Rollback()
}
}()
err = tx.Model(&Redemption{}).Count(&total).Error
if err != nil {
tx.Rollback()
return nil, 0, err
}
err = tx.Order("id desc").Limit(num).Offset(startIdx).Find(&redemptions).Error
if err != nil {
tx.Rollback()
return nil, 0, err
}
if err = tx.Commit().Error; err != nil {
return nil, 0, err
}
return redemptions, total, nil
}
func SearchRedemptions(keyword string, startIdx int, num int) (redemptions []*Redemption, total int64, err error) {
tx := DB.Begin()
if tx.Error != nil {
return nil, 0, tx.Error
}
defer func() {
if r := recover(); r != nil {
tx.Rollback()
}
}()
query := tx.Model(&Redemption{})
if id, err := strconv.Atoi(keyword); err == nil {
query = query.Where("id = ? OR name LIKE ?", id, keyword+"%")
} else {
query = query.Where("name LIKE ?", keyword+"%")
}
err = query.Count(&total).Error
if err != nil {
tx.Rollback()
return nil, 0, err
}
err = query.Order("id desc").Limit(num).Offset(startIdx).Find(&redemptions).Error
if err != nil {
tx.Rollback()
return nil, 0, err
}
if err = tx.Commit().Error; err != nil {
return nil, 0, err
}
return redemptions, total, nil
}
func GetRedemptionById(id int) (*Redemption, error) {
if id == 0 {
return nil, errors.New("id is empty")
}
redemption := Redemption{Id: id}
err := DB.First(&redemption, "id = ?", id).Error
return &redemption, err
}
func Redeem(key string, userId int) (result *RedeemResult, err error) {
if key == "" {
return nil, errors.New("redemption code is required")
}
if userId == 0 {
return nil, errors.New("invalid user id")
}
redemption := &Redemption{}
result = &RedeemResult{}
logMessage := ""
upgradeGroup := ""
keyCol := "`key`"
if common.UsingPostgreSQL {
keyCol = `"key"`
}
common.RandomSleep()
err = DB.Transaction(func(tx *gorm.DB) error {
err := tx.Set("gorm:query_option", "FOR UPDATE").Where(keyCol+" = ?", key).First(redemption).Error
if err != nil {
return errors.New("invalid redemption code")
}
if redemption.Status != common.RedemptionCodeStatusEnabled {
return errors.New("redemption code is unavailable")
}
if redemption.ExpiredTime != 0 && redemption.ExpiredTime < common.GetTimestamp() {
return errors.New("redemption code is expired")
}
redeemType := NormalizeRedemptionType(redemption.RedeemType)
if redeemType == "" {
return errors.New("invalid redemption type")
}
switch redeemType {
case RedemptionTypeQuota:
err = tx.Model(&User{}).Where("id = ?", userId).Update("quota", gorm.Expr("quota + ?", redemption.Quota)).Error
if err != nil {
return err
}
result.RedeemType = RedemptionTypeQuota
result.Quota = redemption.Quota
logMessage = fmt.Sprintf("通过兑换码充值 %s,兑换码ID %d", logger.LogQuota(redemption.Quota), redemption.Id)
case RedemptionTypeSubscription:
if redemption.PlanId <= 0 {
return errors.New("invalid subscription plan id")
}
plan, err := getSubscriptionPlanByIdTx(tx, redemption.PlanId)
if err != nil {
return err
}
sub, err := CreateUserSubscriptionFromPlanTx(tx, userId, plan, "redeem")
if err != nil {
return err
}
result.RedeemType = RedemptionTypeSubscription
result.PlanId = plan.Id
result.PlanTitle = plan.Title
result.SubscriptionId = sub.Id
upgradeGroup = strings.TrimSpace(plan.UpgradeGroup)
logMessage = fmt.Sprintf("通过兑换码开通订阅套餐 %s,兑换码ID %d", plan.Title, redemption.Id)
}
redemption.RedeemType = redeemType
redemption.RedeemedTime = common.GetTimestamp()
redemption.Status = common.RedemptionCodeStatusUsed
redemption.UsedUserId = userId
err = tx.Save(redemption).Error
return err
})
if err != nil {
common.SysError("redemption failed: " + err.Error())
return nil, ErrRedeemFailed
}
if upgradeGroup != "" {
_ = UpdateUserGroupCache(userId, upgradeGroup)
}
if logMessage != "" {
RecordLog(userId, LogTypeTopup, logMessage)
}
return result, nil
}
func (redemption *Redemption) Insert() error {
redemption.RedeemType = NormalizeRedemptionType(redemption.RedeemType)
if redemption.RedeemType == "" {
redemption.RedeemType = RedemptionTypeQuota
}
return DB.Create(redemption).Error
}
func (redemption *Redemption) SelectUpdate() error {
return DB.Model(redemption).Select("redeemed_time", "status").Updates(redemption).Error
}
// Update Make sure your token's fields is completed, because this will update non-zero values
func (redemption *Redemption) Update() error {
return DB.Model(redemption).Select("name", "status", "quota", "redeem_type", "plan_id", "source_note", "redeemed_time", "expired_time").Updates(redemption).Error
}
func (redemption *Redemption) Delete() error {
return DB.Delete(redemption).Error
}
func DeleteRedemptionById(id int) (err error) {
if id == 0 {
return errors.New("id is empty")
}
redemption := Redemption{Id: id}
err = DB.Where(redemption).First(&redemption).Error
if err != nil {
return err
}
return redemption.Delete()
}
func DeleteInvalidRedemptions() (int64, error) {
now := common.GetTimestamp()
result := DB.Where("status IN ? OR (status = ? AND expired_time != 0 AND expired_time < ?)", []int{common.RedemptionCodeStatusUsed, common.RedemptionCodeStatusDisabled}, common.RedemptionCodeStatusEnabled, now).Delete(&Redemption{})
return result.RowsAffected, result.Error
}