new-api/model/redemption.go
zizi 0a0616a370 feat: add subscription redemption support to redemption codes
Redemption codes can now redeem either quota (existing) or a subscription
plan (new). The Redemption model gains Type (1=quota, 2=subscription) and
PlanId fields. When Type=2, Redeem() calls CreateUserSubscriptionFromPlanTx
to activate the plan, reusing all existing subscription logic (purchase
limits, group upgrade, quota reset, expiry). Old codes default to Type=0
which behaves identically to Type=1 (quota).
2026-05-19 01:10:14 +08:00

236 lines
6.6 KiB
Go
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

package model
import (
"errors"
"fmt"
"strconv"
"github.com/QuantumNous/new-api/common"
"github.com/QuantumNous/new-api/logger"
"gorm.io/gorm"
)
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"`
Type int `json:"type" gorm:"default:1"` // 1=额度 2=订阅
Quota int `json:"quota" gorm:"default:100"`
PlanId int `json:"plan_id" gorm:"default:0"` // Type=2 时关联的订阅套餐
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"` // 过期时间0 表示不过期
}
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()
}
}()
// Build query based on keyword type
query := tx.Model(&Redemption{})
// Only try to convert to ID if the string represents a valid integer
if id, err := strconv.Atoi(keyword); err == nil {
query = query.Where("id = ? OR name LIKE ?", id, keyword+"%")
} else {
query = query.Where("name LIKE ?", keyword+"%")
}
// Get total count
err = query.Count(&total).Error
if err != nil {
tx.Rollback()
return nil, 0, err
}
// Get paginated data
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 为空!")
}
redemption := Redemption{Id: id}
var err error = nil
err = DB.First(&redemption, "id = ?", id).Error
return &redemption, err
}
// RedeemResult 兑换结果
type RedeemResult struct {
Type int // 1=额度 2=订阅
Quota int // Type=1 时返回兑换的额度
PlanId int // Type=2 时返回套餐ID
}
func Redeem(key string, userId int) (*RedeemResult, error) {
if key == "" {
return nil, errors.New("未提供兑换码")
}
if userId == 0 {
return nil, errors.New("无效的 user id")
}
redemption := &Redemption{}
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("无效的兑换码")
}
if redemption.Status != common.RedemptionCodeStatusEnabled {
return errors.New("该兑换码已被使用")
}
if redemption.ExpiredTime != 0 && redemption.ExpiredTime < common.GetTimestamp() {
return errors.New("该兑换码已过期")
}
switch redemption.Type {
case common.RedemptionTypeQuota, 0:
err = tx.Model(&User{}).Where("id = ?", userId).Update("quota", gorm.Expr("quota + ?", redemption.Quota)).Error
if err != nil {
return err
}
case common.RedemptionTypeSubscription:
plan, planErr := GetSubscriptionPlanById(redemption.PlanId)
if planErr != nil {
return errors.New("兑换码关联的订阅套餐不存在")
}
if !plan.Enabled {
return errors.New("兑换码关联的订阅套餐已禁用")
}
_, subErr := CreateUserSubscriptionFromPlanTx(tx, userId, plan, "redemption")
if subErr != nil {
return subErr
}
default:
return errors.New("无效的兑换码类型")
}
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
}
result := &RedeemResult{Type: redemption.Type}
switch redemption.Type {
case common.RedemptionTypeSubscription:
result.PlanId = redemption.PlanId
RecordLog(userId, LogTypeTopup, fmt.Sprintf("通过兑换码兑换订阅套餐套餐ID %d兑换码ID %d", redemption.PlanId, redemption.Id))
default:
result.Quota = redemption.Quota
RecordLog(userId, LogTypeTopup, fmt.Sprintf("通过兑换码充值 %s兑换码ID %d", logger.LogQuota(redemption.Quota), redemption.Id))
}
return result, nil
}
func (redemption *Redemption) Insert() error {
var err error
err = DB.Create(redemption).Error
return err
}
func (redemption *Redemption) SelectUpdate() error {
// This can update zero values
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 {
var err error
err = DB.Model(redemption).Select("name", "status", "quota", "redeemed_time", "expired_time", "type", "plan_id").Updates(redemption).Error
return err
}
func (redemption *Redemption) Delete() error {
var err error
err = DB.Delete(redemption).Error
return err
}
func DeleteRedemptionById(id int) (err error) {
if id == 0 {
return errors.New("id 为空!")
}
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
}