- 添加用户认证模块 (JWT + 密码管理) - 添加 ChatGPT 账户管理功能 - 添加卡密管理功能 (创建、批量生成、查询) - 添加邀请功能 - 配置数据库迁移和路由系统
90 lines
2.3 KiB
Go
90 lines
2.3 KiB
Go
package repository
|
|
|
|
import (
|
|
"database/sql"
|
|
|
|
"gpt-manager-go/internal/models"
|
|
)
|
|
|
|
// CardKeyRepository 卡密仓储
|
|
type CardKeyRepository struct {
|
|
db *sql.DB
|
|
}
|
|
|
|
// NewCardKeyRepository 创建仓储
|
|
func NewCardKeyRepository(db *sql.DB) *CardKeyRepository {
|
|
return &CardKeyRepository{db: db}
|
|
}
|
|
|
|
// FindByKey 根据卡密查找
|
|
func (r *CardKeyRepository) FindByKey(key string) (*models.CardKey, error) {
|
|
cardKey := &models.CardKey{}
|
|
err := r.db.QueryRow(`
|
|
SELECT id, key, max_uses, used_count, validity_type, expires_at, is_active, created_by_id, created_at
|
|
FROM card_keys WHERE key = $1
|
|
`, key).Scan(
|
|
&cardKey.ID, &cardKey.Key, &cardKey.MaxUses, &cardKey.UsedCount,
|
|
&cardKey.ValidityType, &cardKey.ExpiresAt, &cardKey.IsActive,
|
|
&cardKey.CreatedByID, &cardKey.CreatedAt,
|
|
)
|
|
if err == sql.ErrNoRows {
|
|
return nil, nil
|
|
}
|
|
return cardKey, err
|
|
}
|
|
|
|
// IncrementUsedCount 增加使用次数,如果达到最大次数则设为不活跃
|
|
func (r *CardKeyRepository) IncrementUsedCount(id int) error {
|
|
_, err := r.db.Exec(`
|
|
UPDATE card_keys
|
|
SET used_count = used_count + 1,
|
|
is_active = CASE WHEN used_count + 1 >= max_uses THEN false ELSE is_active END
|
|
WHERE id = $1
|
|
`, id)
|
|
return err
|
|
}
|
|
|
|
// Create 创建卡密
|
|
func (r *CardKeyRepository) Create(cardKey *models.CardKey) error {
|
|
return r.db.QueryRow(`
|
|
INSERT INTO card_keys (key, max_uses, used_count, validity_type, expires_at, is_active, created_by_id, created_at)
|
|
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
|
RETURNING id
|
|
`,
|
|
cardKey.Key,
|
|
cardKey.MaxUses,
|
|
cardKey.UsedCount,
|
|
cardKey.ValidityType,
|
|
cardKey.ExpiresAt,
|
|
cardKey.IsActive,
|
|
cardKey.CreatedByID,
|
|
cardKey.CreatedAt,
|
|
).Scan(&cardKey.ID)
|
|
}
|
|
|
|
// FindAll 获取所有卡密
|
|
func (r *CardKeyRepository) FindAll() ([]*models.CardKey, error) {
|
|
rows, err := r.db.Query(`
|
|
SELECT id, key, max_uses, used_count, validity_type, expires_at, is_active, created_by_id, created_at
|
|
FROM card_keys ORDER BY created_at DESC
|
|
`)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
defer rows.Close()
|
|
|
|
var cardKeys []*models.CardKey
|
|
for rows.Next() {
|
|
ck := &models.CardKey{}
|
|
if err := rows.Scan(
|
|
&ck.ID, &ck.Key, &ck.MaxUses, &ck.UsedCount,
|
|
&ck.ValidityType, &ck.ExpiresAt, &ck.IsActive,
|
|
&ck.CreatedByID, &ck.CreatedAt,
|
|
); err != nil {
|
|
return nil, err
|
|
}
|
|
cardKeys = append(cardKeys, ck)
|
|
}
|
|
return cardKeys, nil
|
|
}
|