Files
tyapi-server/internal/domains/product/entities/subscription.go
2025-07-31 15:41:00 +08:00

52 lines
1.5 KiB
Go
Raw 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 entities
import (
"time"
"github.com/google/uuid"
"github.com/shopspring/decimal"
"gorm.io/gorm"
)
// Subscription 订阅实体
type Subscription struct {
ID string `gorm:"primaryKey;type:varchar(36)" comment:"订阅ID"`
UserID string `gorm:"type:varchar(36);not null;index" comment:"用户ID"`
ProductID string `gorm:"type:varchar(36);not null;index" comment:"产品ID"`
Price decimal.Decimal `gorm:"type:decimal(10,2);not null" comment:"订阅价格"`
APIUsed int64 `gorm:"default:0" comment:"已使用API调用次数"`
Version int64 `gorm:"default:1" comment:"乐观锁版本号"`
// 关联关系
Product *Product `gorm:"foreignKey:ProductID" comment:"产品"`
CreatedAt time.Time `gorm:"autoCreateTime" comment:"创建时间"`
UpdatedAt time.Time `gorm:"autoUpdateTime" comment:"更新时间"`
DeletedAt gorm.DeletedAt `gorm:"index" comment:"软删除时间"`
}
// BeforeCreate GORM钩子创建前自动生成UUID
func (s *Subscription) BeforeCreate(tx *gorm.DB) error {
if s.ID == "" {
s.ID = uuid.New().String()
}
return nil
}
// IsValid 检查订阅是否有效
func (s *Subscription) IsValid() bool {
return s.DeletedAt.Time.IsZero()
}
// IncrementAPIUsage 增加API使用次数
func (s *Subscription) IncrementAPIUsage(count int64) {
s.APIUsed += count
s.Version++ // 增加版本号
}
// ResetAPIUsage 重置API使用次数
func (s *Subscription) ResetAPIUsage() {
s.APIUsed = 0
s.Version++ // 增加版本号
}