package promo import ( "context" "github.com/redis/go-redis/v9" "gorm.io/gorm" ) type RuleWithPrice struct { Rule PromoPrice int64 `gorm:"column:promo_price"` } type Model interface { QueryEligibleRules(ctx context.Context, subscribeId int64) ([]*RuleWithPrice, error) InsertUsage(ctx context.Context, data *Usage, tx ...*gorm.DB) error } type defaultPromoModel struct { db *gorm.DB } func NewModel(db *gorm.DB, _ *redis.Client) Model { return &defaultPromoModel{db: db} } func (m *defaultPromoModel) QueryEligibleRules(ctx context.Context, subscribeId int64) ([]*RuleWithPrice, error) { var list []*RuleWithPrice err := m.db.WithContext(ctx). Table("promo_rule AS pr"). Select("pr.*, sp.promo_price"). Joins("JOIN subscribe_promo AS sp ON sp.promo_rule_id = pr.id"). Where("sp.subscribe_id = ? AND sp.promo_price > 0 AND pr.enabled = ?", subscribeId, true). Where("pr.deleted_at IS NULL"). Order("pr.priority DESC"). Order("pr.id ASC"). Find(&list).Error return list, err } func (m *defaultPromoModel) InsertUsage(ctx context.Context, data *Usage, tx ...*gorm.DB) error { db := m.db.WithContext(ctx) if len(tx) > 0 { db = tx[0].WithContext(ctx) } return db.Model(&Usage{}).Create(data).Error }