feat(platform): 开源发布 - 初始化 Open AI Canvas
This commit is contained in:
commit
aea35896eb
365 files changed
+66410
No files matched your search
@@ -0,0 +1,147 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"infinite-canvas/backend/internal/model"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrBulkUserNotFound = errors.New("bulk user not found")
|
||||
ErrBulkCurrentAdmin = errors.New("bulk includes current admin")
|
||||
ErrBulkLastActiveAdmin = errors.New("bulk removes last active admin")
|
||||
)
|
||||
|
||||
type AdminUserCounts struct {
|
||||
LedgerEntries int64 `json:"ledgerEntries"`
|
||||
Tasks int64 `json:"tasks"`
|
||||
APICalls int64 `json:"apiCalls"`
|
||||
AuditEvents int64 `json:"auditEvents"`
|
||||
}
|
||||
|
||||
func (r *Repository) AppendAdminAudit(event *model.AdminAuditEvent) error {
|
||||
return r.db.Create(event).Error
|
||||
}
|
||||
|
||||
// BulkDisableUsers 把管理员保留校验、会话清理、状态更新和审计写入放在同一事务中,避免部分停用。
|
||||
func (r *Repository) BulkDisableUsers(actorID string, userIDs []string, events []model.AdminAuditEvent, now time.Time) ([]model.User, error) {
|
||||
var users []model.User
|
||||
err := r.db.Transaction(func(tx *gorm.DB) error {
|
||||
query := tx.Where("id IN ?", userIDs)
|
||||
if r.Dialect() == "postgres" {
|
||||
query = query.Clauses(clause.Locking{Strength: "UPDATE"})
|
||||
}
|
||||
if err := query.Find(&users).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if len(users) != len(userIDs) {
|
||||
return ErrBulkUserNotFound
|
||||
}
|
||||
for _, user := range users {
|
||||
if user.ID == actorID {
|
||||
return ErrBulkCurrentAdmin
|
||||
}
|
||||
}
|
||||
var remainingAdmins int64
|
||||
if err := tx.Model(&model.User{}).
|
||||
Where("role = ? AND status = ? AND id NOT IN ?", model.UserRoleAdmin, model.UserStatusActive, userIDs).
|
||||
Count(&remainingAdmins).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if remainingAdmins == 0 {
|
||||
return ErrBulkLastActiveAdmin
|
||||
}
|
||||
if err := tx.Delete(&model.AuthSession{}, "user_id IN ?", userIDs).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Model(&model.User{}).Where("id IN ?", userIDs).Updates(map[string]any{"status": model.UserStatusDisabled, "updated_at": now}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if len(events) > 0 {
|
||||
if err := tx.Create(&events).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for index := range users {
|
||||
users[index].Status = model.UserStatusDisabled
|
||||
users[index].UpdatedAt = now
|
||||
}
|
||||
return nil
|
||||
})
|
||||
return users, err
|
||||
}
|
||||
|
||||
func (r *Repository) AdminAuditEvents(targetType string, targetID string, limit int, offset int) ([]model.AdminAuditEvent, int64, error) {
|
||||
query := r.db.Model(&model.AdminAuditEvent{})
|
||||
if targetType != "" {
|
||||
query = query.Where("target_type = ?", targetType)
|
||||
}
|
||||
if targetID != "" {
|
||||
query = query.Where("target_id = ?", targetID)
|
||||
}
|
||||
var total int64
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
var events []model.AdminAuditEvent
|
||||
err := query.Order("created_at desc").Limit(limit).Offset(offset).Find(&events).Error
|
||||
return events, total, err
|
||||
}
|
||||
|
||||
func (r *Repository) AdminUserCounts(userID string) (AdminUserCounts, error) {
|
||||
var counts AdminUserCounts
|
||||
queries := []struct {
|
||||
model any
|
||||
where string
|
||||
value *int64
|
||||
}{
|
||||
{&model.CreditLedgerEntry{}, "user_id = ?", &counts.LedgerEntries},
|
||||
{&model.Task{}, "user_id = ?", &counts.Tasks},
|
||||
{&model.ApiCallLog{}, "user_id = ?", &counts.APICalls},
|
||||
{&model.AdminAuditEvent{}, "target_type = 'user' AND target_id = ?", &counts.AuditEvents},
|
||||
}
|
||||
for _, query := range queries {
|
||||
if err := r.db.Model(query.model).Where(query.where, userID).Count(query.value).Error; err != nil {
|
||||
return AdminUserCounts{}, err
|
||||
}
|
||||
}
|
||||
return counts, nil
|
||||
}
|
||||
|
||||
func (r *Repository) AdminUserTasks(userID string, limit int, offset int) ([]model.Task, int64, error) {
|
||||
query := r.db.Model(&model.Task{}).Where("user_id = ?", userID)
|
||||
var total int64
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
var tasks []model.Task
|
||||
err := query.Select("id", "user_id", "session_id", "project_id", "type", "status", "stage", "progress", "operation", "provider", "model", "billing_order_id", "provider_request_id", "poll_stage", "attempts", "started_at", "completed_at", "created_at", "updated_at").
|
||||
Order("created_at desc").Limit(limit).Offset(offset).Find(&tasks).Error
|
||||
return tasks, total, err
|
||||
}
|
||||
|
||||
func (r *Repository) DisableRedeemBatch(batchID string, now time.Time) (int64, error) {
|
||||
result := r.db.Model(&model.RedeemCode{}).
|
||||
Where("batch_id = ? AND status = ? AND (expires_at IS NULL OR expires_at > ?)", batchID, model.RedeemCodeUnused, now).
|
||||
Updates(map[string]any{"status": model.RedeemCodeDisabled, "updated_at": now})
|
||||
return result.RowsAffected, result.Error
|
||||
}
|
||||
|
||||
func (r *Repository) DisableRedeemCode(batchID string, codeID string, now time.Time) (bool, error) {
|
||||
result := r.db.Model(&model.RedeemCode{}).
|
||||
Where("id = ? AND batch_id = ? AND status = ? AND (expires_at IS NULL OR expires_at > ?)", codeID, batchID, model.RedeemCodeUnused, now).
|
||||
Updates(map[string]any{"status": model.RedeemCodeDisabled, "updated_at": now})
|
||||
return result.RowsAffected == 1, result.Error
|
||||
}
|
||||
|
||||
func (r *Repository) APICallLog(id string) (*model.ApiCallLog, error) {
|
||||
var log model.ApiCallLog
|
||||
if err := r.db.First(&log, "id = ?", id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &log, nil
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"infinite-canvas/backend/internal/model"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
type AnalyticsFilter struct {
|
||||
From time.Time
|
||||
To time.Time
|
||||
UserID string
|
||||
Model string
|
||||
ChannelID string
|
||||
Capability string
|
||||
}
|
||||
|
||||
type APICallLogFilter struct {
|
||||
AnalyticsFilter
|
||||
Keyword string
|
||||
Status string
|
||||
IDs []string
|
||||
Page int
|
||||
Limit int
|
||||
}
|
||||
|
||||
func (r *Repository) RecordUserActivity(userID string, event string, count int, now time.Time) error {
|
||||
if userID == "" {
|
||||
return nil
|
||||
}
|
||||
if count <= 0 {
|
||||
count = 1
|
||||
}
|
||||
day := time.Date(now.UTC().Year(), now.UTC().Month(), now.UTC().Day(), 0, 0, 0, 0, time.UTC)
|
||||
activity := model.UserDailyActivity{ID: userID + ":" + day.Format("2006-01-02"), Day: day, UserID: userID, CreatedAt: now, UpdatedAt: now}
|
||||
updates := map[string]any{"updated_at": now}
|
||||
switch event {
|
||||
case "login":
|
||||
activity.LoginCount = count
|
||||
updates["login_count"] = gorm.Expr("login_count + ?", count)
|
||||
case "task":
|
||||
activity.TaskCount = count
|
||||
updates["task_count"] = gorm.Expr("task_count + ?", count)
|
||||
case "agent_message":
|
||||
activity.AgentMessageCount = count
|
||||
updates["agent_message_count"] = gorm.Expr("agent_message_count + ?", count)
|
||||
case "canvas":
|
||||
activity.CanvasActive = true
|
||||
updates["canvas_active"] = true
|
||||
case "asset":
|
||||
activity.AssetCount = count
|
||||
updates["asset_count"] = gorm.Expr("asset_count + ?", count)
|
||||
case "resource":
|
||||
activity.ResourceCount = count
|
||||
updates["resource_count"] = gorm.Expr("resource_count + ?", count)
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
if event != "login" {
|
||||
activity.FirstActiveAt = &now
|
||||
activity.LastActiveAt = &now
|
||||
updates["first_active_at"] = gorm.Expr("COALESCE(first_active_at, ?)", now)
|
||||
updates["last_active_at"] = now
|
||||
}
|
||||
return r.db.Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{{Name: "day"}, {Name: "user_id"}},
|
||||
DoUpdates: clause.Assignments(updates),
|
||||
}).Create(&activity).Error
|
||||
}
|
||||
|
||||
func (r *Repository) AnalyticsTasks(filter AnalyticsFilter) ([]model.Task, error) {
|
||||
var tasks []model.Task
|
||||
query := r.db.Select("id", "user_id", "type", "status", "operation", "provider", "model", "started_at", "completed_at", "created_at").Where("created_at >= ? AND created_at < ?", filter.From, filter.To)
|
||||
if filter.UserID != "" {
|
||||
query = query.Where("user_id = ?", filter.UserID)
|
||||
}
|
||||
if filter.Model != "" {
|
||||
query = query.Where("model = ?", filter.Model)
|
||||
}
|
||||
if filter.Capability != "" {
|
||||
if filter.Capability == "text" {
|
||||
query = query.Where("type LIKE ? OR type LIKE ? OR type LIKE ?", "%text%", "%storyboard%", "%agent%")
|
||||
} else {
|
||||
query = query.Where("type LIKE ?", "%"+filter.Capability+"%")
|
||||
}
|
||||
}
|
||||
return tasks, query.Find(&tasks).Error
|
||||
}
|
||||
|
||||
func (r *Repository) AnalyticsAPICallLogs(filter AnalyticsFilter) ([]model.ApiCallLog, error) {
|
||||
var logs []model.ApiCallLog
|
||||
query := r.apiCallLogQuery(filter)
|
||||
return logs, query.Find(&logs).Error
|
||||
}
|
||||
|
||||
func (r *Repository) AnalyticsActivities(filter AnalyticsFilter) ([]model.UserDailyActivity, error) {
|
||||
var activities []model.UserDailyActivity
|
||||
query := r.db.Where("day >= ? AND day < ?", filter.From, filter.To)
|
||||
if filter.UserID != "" {
|
||||
query = query.Where("user_id = ?", filter.UserID)
|
||||
}
|
||||
return activities, query.Find(&activities).Error
|
||||
}
|
||||
|
||||
func (r *Repository) QueryAPICallLogs(filter APICallLogFilter) ([]model.ApiCallLog, int64, error) {
|
||||
if filter.Page <= 0 {
|
||||
filter.Page = 1
|
||||
}
|
||||
if filter.Limit <= 0 || filter.Limit > 200 {
|
||||
filter.Limit = 50
|
||||
}
|
||||
query := r.apiCallLogQuery(filter.AnalyticsFilter)
|
||||
if value := strings.TrimSpace(filter.Keyword); value != "" {
|
||||
pattern := "%" + strings.ToLower(value) + "%"
|
||||
query = query.
|
||||
Joins("LEFT JOIN users ON users.id = api_call_logs.user_id").
|
||||
Joins("LEFT JOIN model_channels ON model_channels.id = api_call_logs.channel_id").
|
||||
Where(
|
||||
"lower(api_call_logs.user_id) LIKE ? OR lower(users.username) LIKE ? OR lower(users.display_name) LIKE ? OR lower(api_call_logs.channel_id) LIKE ? OR lower(model_channels.name) LIKE ? OR lower(api_call_logs.model) LIKE ? OR lower(api_call_logs.path) LIKE ? OR lower(api_call_logs.provider_request_id) LIKE ?",
|
||||
pattern, pattern, pattern, pattern, pattern, pattern, pattern, pattern,
|
||||
)
|
||||
}
|
||||
if filter.Status != "" {
|
||||
query = query.Where("api_call_logs.status = ?", filter.Status)
|
||||
}
|
||||
var total int64
|
||||
if err := query.Model(&model.ApiCallLog{}).Distinct("api_call_logs.id").Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
var logs []model.ApiCallLog
|
||||
err := query.Select("api_call_logs.*").Order("api_call_logs.created_at desc").Offset((filter.Page - 1) * filter.Limit).Limit(filter.Limit).Find(&logs).Error
|
||||
return logs, total, err
|
||||
}
|
||||
|
||||
func (r *Repository) ExportAPICallLogs(filter APICallLogFilter, limit int) ([]model.ApiCallLog, error) {
|
||||
if limit <= 0 || limit > 10_000 {
|
||||
limit = 10_000
|
||||
}
|
||||
query := r.apiCallLogQuery(filter.AnalyticsFilter)
|
||||
if len(filter.IDs) > 0 {
|
||||
query = query.Where("api_call_logs.id IN ?", filter.IDs)
|
||||
}
|
||||
if value := strings.TrimSpace(filter.Keyword); value != "" {
|
||||
pattern := "%" + strings.ToLower(value) + "%"
|
||||
query = query.Joins("LEFT JOIN users ON users.id = api_call_logs.user_id").Joins("LEFT JOIN model_channels ON model_channels.id = api_call_logs.channel_id").Where(
|
||||
"lower(api_call_logs.user_id) LIKE ? OR lower(users.username) LIKE ? OR lower(users.display_name) LIKE ? OR lower(api_call_logs.channel_id) LIKE ? OR lower(model_channels.name) LIKE ? OR lower(api_call_logs.model) LIKE ? OR lower(api_call_logs.path) LIKE ? OR lower(api_call_logs.provider_request_id) LIKE ?",
|
||||
pattern, pattern, pattern, pattern, pattern, pattern, pattern, pattern,
|
||||
)
|
||||
}
|
||||
if filter.Status != "" {
|
||||
query = query.Where("api_call_logs.status = ?", filter.Status)
|
||||
}
|
||||
var logs []model.ApiCallLog
|
||||
err := query.Select("api_call_logs.*").Order("api_call_logs.created_at desc").Limit(limit).Find(&logs).Error
|
||||
return logs, err
|
||||
}
|
||||
|
||||
func (r *Repository) apiCallLogQuery(filter AnalyticsFilter) *gorm.DB {
|
||||
query := r.db.Where("api_call_logs.created_at >= ? AND api_call_logs.created_at < ?", filter.From, filter.To)
|
||||
if filter.UserID != "" {
|
||||
query = query.Where("api_call_logs.user_id = ?", filter.UserID)
|
||||
}
|
||||
if filter.Model != "" {
|
||||
query = query.Where("api_call_logs.model = ?", filter.Model)
|
||||
}
|
||||
if filter.ChannelID != "" {
|
||||
query = query.Where("api_call_logs.channel_id = ?", filter.ChannelID)
|
||||
}
|
||||
if filter.Capability != "" {
|
||||
query = query.Where("api_call_logs.capability = ?", filter.Capability)
|
||||
}
|
||||
return query
|
||||
}
|
||||
|
||||
func (r *Repository) ModelPricings() ([]model.ModelPricing, error) {
|
||||
var items []model.ModelPricing
|
||||
return items, r.db.Order("model asc, capability asc").Find(&items).Error
|
||||
}
|
||||
|
||||
func (r *Repository) ModelPricing(channelID string, modelName string, capability string) (*model.ModelPricing, error) {
|
||||
var pricing model.ModelPricing
|
||||
query := r.db.Where("model = ? AND capability = ?", modelName, capability)
|
||||
if channelID != "" {
|
||||
query = query.Where("channel_id IN ?", []string{channelID, ""}).Order("channel_id desc")
|
||||
} else {
|
||||
query = query.Where("channel_id = ?", "")
|
||||
}
|
||||
if err := query.First(&pricing).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &pricing, nil
|
||||
}
|
||||
|
||||
func (r *Repository) ModelPricingByID(id string) (*model.ModelPricing, error) {
|
||||
var pricing model.ModelPricing
|
||||
if err := r.db.First(&pricing, "id = ?", id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &pricing, nil
|
||||
}
|
||||
|
||||
func (r *Repository) DeleteModelPricing(id string) error {
|
||||
return r.db.Delete(&model.ModelPricing{}, "id = ?", id).Error
|
||||
}
|
||||
|
||||
func (r *Repository) CurrentQueuedTaskCount() (int64, error) {
|
||||
var count int64
|
||||
err := r.db.Model(&model.Task{}).Where("status IN ?", []model.TaskStatus{model.TaskStatusQueued, model.TaskStatusRunning}).Count(&count).Error
|
||||
return count, err
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"infinite-canvas/backend/internal/model"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
func (r *Repository) AdminAnnouncements(keyword string, status model.AnnouncementStatus, limit int, offset int) ([]model.Announcement, int64, error) {
|
||||
var announcements []model.Announcement
|
||||
var total int64
|
||||
query := r.db.Model(&model.Announcement{})
|
||||
if value := strings.TrimSpace(keyword); value != "" {
|
||||
pattern := "%" + strings.ToLower(value) + "%"
|
||||
query = query.Where("lower(title) LIKE ? OR lower(content) LIKE ?", pattern, pattern)
|
||||
}
|
||||
if status == model.AnnouncementStatusActive || status == model.AnnouncementStatusClosed {
|
||||
query = query.Where("status = ?", status)
|
||||
}
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if err := query.Order("published_at desc").Limit(limit).Offset(offset).Find(&announcements).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
return announcements, total, nil
|
||||
}
|
||||
|
||||
func (r *Repository) AnnouncementFeed(userID string) ([]model.Announcement, int64, error) {
|
||||
var announcements []model.Announcement
|
||||
var unreadCount int64
|
||||
err := r.db.Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Where("status = ?", model.AnnouncementStatusActive).Order("published_at desc").Find(&announcements).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Model(&model.Announcement{}).
|
||||
Joins("LEFT JOIN user_announcement_reads ON user_announcement_reads.announcement_id = announcements.id AND user_announcement_reads.user_id = ?", userID).
|
||||
Where("announcements.status = ? AND user_announcement_reads.id IS NULL", model.AnnouncementStatusActive).
|
||||
Count(&unreadCount).Error
|
||||
})
|
||||
return announcements, unreadCount, err
|
||||
}
|
||||
|
||||
func (r *Repository) Announcement(id string) (*model.Announcement, error) {
|
||||
var announcement model.Announcement
|
||||
if err := r.db.First(&announcement, "id = ?", id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &announcement, nil
|
||||
}
|
||||
|
||||
func (r *Repository) CloseAnnouncement(id string, closedAt time.Time) (bool, error) {
|
||||
result := r.db.Model(&model.Announcement{}).
|
||||
Where("id = ? AND status = ?", id, model.AnnouncementStatusActive).
|
||||
Updates(map[string]any{"status": model.AnnouncementStatusClosed, "closed_at": closedAt, "updated_at": closedAt})
|
||||
return result.RowsAffected == 1, result.Error
|
||||
}
|
||||
|
||||
func (r *Repository) MarkAnnouncementsRead(userID string, announcementIDs []string, readAt time.Time) error {
|
||||
if len(announcementIDs) == 0 {
|
||||
return nil
|
||||
}
|
||||
var activeIDs []string
|
||||
if err := r.db.Model(&model.Announcement{}).Where("id IN ? AND status = ?", announcementIDs, model.AnnouncementStatusActive).Pluck("id", &activeIDs).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if len(activeIDs) == 0 {
|
||||
return nil
|
||||
}
|
||||
reads := make([]model.UserAnnouncementRead, 0, len(activeIDs))
|
||||
for _, id := range activeIDs {
|
||||
reads = append(reads, model.UserAnnouncementRead{ID: newRepositoryID(), UserID: userID, AnnouncementID: id, ReadAt: readAt})
|
||||
}
|
||||
return r.db.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "user_id"}, {Name: "announcement_id"}}, DoNothing: true}).Create(&reads).Error
|
||||
}
|
||||
@@ -0,0 +1,648 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"infinite-canvas/backend/internal/model"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInsufficientCredits = errors.New("insufficient credits")
|
||||
ErrRedeemCodeInvalid = errors.New("redeem code invalid")
|
||||
ErrActiveTaskLimit = errors.New("active task limit reached")
|
||||
ErrTaskNotRetryable = errors.New("task is not retryable")
|
||||
ErrBillingStateConflict = errors.New("billing state conflict")
|
||||
)
|
||||
|
||||
// 先抢占唯一业务键再更新账户,确保注册和签到奖励在多实例并发下只入账一次。
|
||||
func (r *Repository) GrantCreditsOnce(userID string, entryType model.CreditLedgerType, amount int64, referenceKey string, note string) (*model.CreditAccount, bool, error) {
|
||||
var account model.CreditAccount
|
||||
granted := false
|
||||
err := r.db.Transaction(func(tx *gorm.DB) error {
|
||||
account = model.CreditAccount{UserID: userID}
|
||||
if err := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&account).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
entry := model.CreditLedgerEntry{ID: newRepositoryID(), UserID: userID, Type: entryType, AmountMicrocredits: amount, ReferenceKey: &referenceKey, Note: note}
|
||||
created := tx.Clauses(clause.OnConflict{Columns: []clause.Column{{Name: "reference_key"}}, DoNothing: true}).Create(&entry)
|
||||
if created.Error != nil {
|
||||
return created.Error
|
||||
}
|
||||
if created.RowsAffected == 0 {
|
||||
return tx.First(&account, "user_id = ?", userID).Error
|
||||
}
|
||||
granted = true
|
||||
if err := tx.Model(&model.CreditAccount{}).Where("user_id = ?", userID).Updates(map[string]any{
|
||||
"available_microcredits": gorm.Expr("available_microcredits + ?", amount),
|
||||
"version": gorm.Expr("version + 1"),
|
||||
"updated_at": time.Now(),
|
||||
}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.First(&account, "user_id = ?", userID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Model(&entry).Updates(map[string]any{
|
||||
"available_delta_microcredits": amount,
|
||||
"available_after_microcredits": account.AvailableMicrocredits,
|
||||
"reserved_after_microcredits": account.ReservedMicrocredits,
|
||||
}).Error
|
||||
})
|
||||
return &account, granted, err
|
||||
}
|
||||
|
||||
type AdminRedeemCodeRow struct {
|
||||
model.RedeemCode
|
||||
RedeemedUsername string `json:"redeemedUsername" gorm:"column:redeemed_username"`
|
||||
RedeemedDisplayName string `json:"redeemedDisplayName" gorm:"column:redeemed_display_name"`
|
||||
}
|
||||
|
||||
func (r *Repository) ChannelModels(channelID string, includeDisabled bool) ([]model.ChannelModel, error) {
|
||||
var items []model.ChannelModel
|
||||
query := r.db.Where("channel_id = ?", channelID).Order("created_at asc")
|
||||
if !includeDisabled {
|
||||
query = query.Where("enabled = ?", true)
|
||||
}
|
||||
return items, query.Find(&items).Error
|
||||
}
|
||||
|
||||
func (r *Repository) ChannelModelByID(channelID string, id string) (*model.ChannelModel, error) {
|
||||
var item model.ChannelModel
|
||||
if err := r.db.First(&item, "id = ? AND channel_id = ?", id, channelID).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &item, nil
|
||||
}
|
||||
|
||||
func (r *Repository) ChannelModelByKey(channelID string, modelKey string) (*model.ChannelModel, error) {
|
||||
var item model.ChannelModel
|
||||
if err := r.db.First(&item, "channel_id = ? AND model_key = ? AND enabled = ?", channelID, modelKey, true).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &item, nil
|
||||
}
|
||||
|
||||
func (r *Repository) SaveChannelModel(item *model.ChannelModel) error {
|
||||
return r.db.Save(item).Error
|
||||
}
|
||||
|
||||
func (r *Repository) CreditAccount(userID string) (*model.CreditAccount, error) {
|
||||
account := model.CreditAccount{UserID: userID}
|
||||
if err := r.db.Clauses(clause.OnConflict{DoNothing: true}).Create(&account).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := r.db.First(&account, "user_id = ?", userID).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &account, nil
|
||||
}
|
||||
|
||||
func (r *Repository) CreditAccounts(userIDs []string) ([]model.CreditAccount, error) {
|
||||
if len(userIDs) == 0 {
|
||||
return []model.CreditAccount{}, nil
|
||||
}
|
||||
var accounts []model.CreditAccount
|
||||
err := r.db.Where("user_id IN ?", userIDs).Find(&accounts).Error
|
||||
return accounts, err
|
||||
}
|
||||
|
||||
func (r *Repository) CreditLedger(userID string, entryType string, limit int, offset int) ([]model.CreditLedgerEntry, int64, error) {
|
||||
var items []model.CreditLedgerEntry
|
||||
var total int64
|
||||
query := r.db.Model(&model.CreditLedgerEntry{}).Where("user_id = ? AND type <> ?", userID, model.CreditLedgerReserve)
|
||||
switch entryType {
|
||||
case "income":
|
||||
query = query.Where("type IN ?", []model.CreditLedgerType{model.CreditLedgerRedeem, model.CreditLedgerAdminGrant, model.CreditLedgerAdminAdjust, model.CreditLedgerSignupBonus, model.CreditLedgerCheckinBonus})
|
||||
case "consume":
|
||||
query = query.Where("type = ?", model.CreditLedgerConsume)
|
||||
case "refund":
|
||||
query = query.Where("type = ?", model.CreditLedgerRefund)
|
||||
}
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if limit <= 0 || limit > 100 {
|
||||
limit = 30
|
||||
}
|
||||
if offset < 0 {
|
||||
offset = 0
|
||||
}
|
||||
err := query.Order("created_at desc").Limit(limit).Offset(offset).Find(&items).Error
|
||||
return items, total, err
|
||||
}
|
||||
|
||||
func (r *Repository) CreditLedgerReferenceExists(referenceKey string) (bool, error) {
|
||||
var count int64
|
||||
err := r.db.Model(&model.CreditLedgerEntry{}).Where("reference_key = ?", referenceKey).Count(&count).Error
|
||||
return count > 0, err
|
||||
}
|
||||
|
||||
func (r *Repository) CreateTaskWithCreditReservation(task *model.Task, order *model.BillingOrder) error {
|
||||
return r.db.Transaction(func(tx *gorm.DB) error {
|
||||
if err := enforceActiveTaskLimit(tx, task.UserID); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := reserveBillingOrder(tx, order); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Create(task).Error
|
||||
})
|
||||
}
|
||||
|
||||
func (r *Repository) CreateTaskWithActiveLimit(task *model.Task) error {
|
||||
return r.db.Transaction(func(tx *gorm.DB) error {
|
||||
if err := enforceActiveTaskLimit(tx, task.UserID); err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Create(task).Error
|
||||
})
|
||||
}
|
||||
|
||||
func (r *Repository) RetryTaskWithBilling(userID string, taskID string, order *model.BillingOrder) (*model.Task, error) {
|
||||
var task model.Task
|
||||
err := r.db.Transaction(func(tx *gorm.DB) error {
|
||||
if err := enforceActiveTaskLimit(tx, userID); err != nil {
|
||||
return err
|
||||
}
|
||||
if order != nil {
|
||||
if err := reserveBillingOrder(tx, order); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
updates := map[string]any{
|
||||
"status": model.TaskStatusQueued, "stage": "等待队列调度", "progress": 5, "error": "", "result_json": "",
|
||||
"started_at": nil, "completed_at": nil, "updated_at": time.Now(),
|
||||
}
|
||||
if order != nil {
|
||||
updates["billing_order_id"] = order.ID
|
||||
}
|
||||
updated := tx.Model(&model.Task{}).
|
||||
Where("id = ? AND user_id = ? AND status IN ?", taskID, userID, []model.TaskStatus{model.TaskStatusFailed, model.TaskStatusCancelled}).
|
||||
Updates(updates)
|
||||
if updated.Error != nil {
|
||||
return updated.Error
|
||||
}
|
||||
if updated.RowsAffected != 1 {
|
||||
return ErrTaskNotRetryable
|
||||
}
|
||||
return tx.First(&task, "id = ? AND user_id = ?", taskID, userID).Error
|
||||
})
|
||||
return &task, err
|
||||
}
|
||||
|
||||
func enforceActiveTaskLimit(tx *gorm.DB, userID string) error {
|
||||
var count int64
|
||||
if err := tx.Model(&model.Task{}).Where("user_id = ? AND status IN ?", userID, []model.TaskStatus{model.TaskStatusQueued, model.TaskStatusRunning}).Count(&count).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if count >= 5 {
|
||||
return ErrActiveTaskLimit
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Repository) ReserveBillingOrder(order *model.BillingOrder) error {
|
||||
return r.db.Transaction(func(tx *gorm.DB) error {
|
||||
return reserveBillingOrder(tx, order)
|
||||
})
|
||||
}
|
||||
|
||||
func reserveBillingOrder(tx *gorm.DB, order *model.BillingOrder) error {
|
||||
account := model.CreditAccount{UserID: order.UserID}
|
||||
if err := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&account).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
updated := tx.Model(&model.CreditAccount{}).
|
||||
Where("user_id = ? AND available_microcredits >= ?", order.UserID, order.AmountMicrocredits).
|
||||
Updates(map[string]any{
|
||||
"available_microcredits": gorm.Expr("available_microcredits - ?", order.AmountMicrocredits),
|
||||
"reserved_microcredits": gorm.Expr("reserved_microcredits + ?", order.AmountMicrocredits),
|
||||
"version": gorm.Expr("version + 1"),
|
||||
"updated_at": time.Now(),
|
||||
})
|
||||
if updated.Error != nil {
|
||||
return updated.Error
|
||||
}
|
||||
if updated.RowsAffected != 1 {
|
||||
return ErrInsufficientCredits
|
||||
}
|
||||
if err := tx.First(&account, "user_id = ?", order.UserID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Create(order).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Create(&model.CreditLedgerEntry{
|
||||
ID: newRepositoryID(),
|
||||
UserID: order.UserID,
|
||||
Type: model.CreditLedgerReserve,
|
||||
AvailableDeltaMicrocredits: -order.AmountMicrocredits,
|
||||
ReservedDeltaMicrocredits: order.AmountMicrocredits,
|
||||
AvailableAfterMicrocredits: account.AvailableMicrocredits,
|
||||
ReservedAfterMicrocredits: account.ReservedMicrocredits,
|
||||
BillingOrderID: order.ID,
|
||||
Model: order.Model,
|
||||
ChannelID: order.ChannelID,
|
||||
Scene: order.Scene,
|
||||
}).Error
|
||||
}
|
||||
|
||||
func (r *Repository) BillingOrder(id string) (*model.BillingOrder, error) {
|
||||
var order model.BillingOrder
|
||||
if err := r.db.First(&order, "id = ?", id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &order, nil
|
||||
}
|
||||
|
||||
func (r *Repository) BillingOrdersByTaskIDs(userID string, taskIDs []string) (map[string]model.BillingOrder, error) {
|
||||
result := make(map[string]model.BillingOrder, len(taskIDs))
|
||||
if len(taskIDs) == 0 {
|
||||
return result, nil
|
||||
}
|
||||
var orders []model.BillingOrder
|
||||
if err := r.db.Where("user_id = ? AND task_id IN ?", userID, taskIDs).Find(&orders).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, order := range orders {
|
||||
if order.TaskID != "" {
|
||||
result[order.TaskID] = order
|
||||
}
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func (r *Repository) AdminBillingOrders(status string, keyword string, limit int, offset int) ([]model.BillingOrder, int64, error) {
|
||||
var items []model.BillingOrder
|
||||
var total int64
|
||||
query := r.db.Model(&model.BillingOrder{})
|
||||
if status == "review" {
|
||||
query = query.Joins("LEFT JOIN tasks ON tasks.id = billing_orders.task_id").Where(
|
||||
"billing_orders.status = ? OR (billing_orders.status = ? AND billing_orders.updated_at < ?) OR (billing_orders.status = ? AND tasks.status IN ?)",
|
||||
model.BillingStatusUncertain, model.BillingStatusRunning, time.Now().Add(-40*time.Minute), model.BillingStatusReserved,
|
||||
[]model.TaskStatus{model.TaskStatusFailed, model.TaskStatusCancelled},
|
||||
)
|
||||
} else if status != "" && status != "all" {
|
||||
query = query.Where("billing_orders.status = ?", status)
|
||||
}
|
||||
if value := strings.TrimSpace(keyword); value != "" {
|
||||
pattern := "%" + strings.ToLower(value) + "%"
|
||||
query = query.Joins("LEFT JOIN users ON users.id = billing_orders.user_id").Where(
|
||||
"lower(billing_orders.model) LIKE ? OR lower(billing_orders.scene) LIKE ? OR lower(billing_orders.provider_request_id) LIKE ? OR lower(users.username) LIKE ? OR lower(users.display_name) LIKE ?",
|
||||
pattern, pattern, pattern, pattern, pattern,
|
||||
)
|
||||
}
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if err := query.Select("billing_orders.*").Order("billing_orders.created_at desc").Limit(limit).Offset(offset).Find(&items).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
return items, total, nil
|
||||
}
|
||||
|
||||
func (r *Repository) TaskHasSuccessfulBillableCall(taskID string) (bool, error) {
|
||||
var count int64
|
||||
err := r.db.Model(&model.ApiCallLog{}).
|
||||
Where("task_id = ? AND billable = ? AND status = ?", taskID, true, model.ApiCallStatusSucceeded).
|
||||
Count(&count).Error
|
||||
return count > 0, err
|
||||
}
|
||||
|
||||
func (r *Repository) RecordBillingResolution(id string, actorUserID string, note string) error {
|
||||
return r.db.Model(&model.BillingOrder{}).Where("id = ?", id).Updates(map[string]any{
|
||||
"resolved_by": actorUserID, "resolution_note": note, "updated_at": time.Now(),
|
||||
}).Error
|
||||
}
|
||||
|
||||
func (r *Repository) UpdateBillingProviderRequestID(id string, providerRequestID string) error {
|
||||
if id == "" || providerRequestID == "" {
|
||||
return nil
|
||||
}
|
||||
return r.db.Model(&model.BillingOrder{}).Where("id = ?", id).Updates(map[string]any{
|
||||
"provider_request_id": providerRequestID, "updated_at": time.Now(),
|
||||
}).Error
|
||||
}
|
||||
|
||||
func (r *Repository) MarkBillingRunning(id string) error {
|
||||
if id == "" {
|
||||
return nil
|
||||
}
|
||||
var order model.BillingOrder
|
||||
if err := r.db.Select("id", "status").First(&order, "id = ?", id).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if order.Status == model.BillingStatusRunning {
|
||||
return nil
|
||||
}
|
||||
now := time.Now()
|
||||
result := r.db.Model(&model.BillingOrder{}).
|
||||
Where("id = ? AND status = ?", id, model.BillingStatusReserved).
|
||||
Updates(map[string]any{"status": model.BillingStatusRunning, "started_at": &now, "updated_at": now})
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
if result.RowsAffected != 1 {
|
||||
return ErrBillingStateConflict
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Repository) MarkBillingUncertain(id string, errorText string) error {
|
||||
return r.db.Model(&model.BillingOrder{}).
|
||||
Where("id = ? AND status IN ?", id, []model.BillingStatus{model.BillingStatusReserved, model.BillingStatusRunning}).
|
||||
Updates(map[string]any{"status": model.BillingStatusUncertain, "error": errorText, "updated_at": time.Now()}).Error
|
||||
}
|
||||
|
||||
func (r *Repository) SettleBillingOrder(id string, providerRequestID string) error {
|
||||
return r.db.Transaction(func(tx *gorm.DB) error {
|
||||
var order model.BillingOrder
|
||||
if err := tx.First(&order, "id = ?", id).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if order.Status == model.BillingStatusSettled {
|
||||
return nil
|
||||
}
|
||||
if order.Status == model.BillingStatusRefunded {
|
||||
return errors.New("billing order already refunded")
|
||||
}
|
||||
updated := tx.Model(&model.CreditAccount{}).
|
||||
Where("user_id = ? AND reserved_microcredits >= ?", order.UserID, order.AmountMicrocredits).
|
||||
Updates(map[string]any{
|
||||
"reserved_microcredits": gorm.Expr("reserved_microcredits - ?", order.AmountMicrocredits),
|
||||
"version": gorm.Expr("version + 1"),
|
||||
"updated_at": time.Now(),
|
||||
})
|
||||
if updated.Error != nil {
|
||||
return updated.Error
|
||||
}
|
||||
if updated.RowsAffected != 1 {
|
||||
return errors.New("reserved credit balance is inconsistent")
|
||||
}
|
||||
var account model.CreditAccount
|
||||
if err := tx.First(&account, "user_id = ?", order.UserID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
now := time.Now()
|
||||
orderUpdates := map[string]any{"status": model.BillingStatusSettled, "settled_at": &now, "updated_at": now}
|
||||
if providerRequestID != "" {
|
||||
orderUpdates["provider_request_id"] = providerRequestID
|
||||
}
|
||||
if err := tx.Model(&order).Updates(orderUpdates).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Create(&model.CreditLedgerEntry{
|
||||
ID: newRepositoryID(),
|
||||
UserID: order.UserID,
|
||||
Type: model.CreditLedgerConsume,
|
||||
AmountMicrocredits: -order.AmountMicrocredits,
|
||||
ReservedDeltaMicrocredits: -order.AmountMicrocredits,
|
||||
AvailableAfterMicrocredits: account.AvailableMicrocredits,
|
||||
ReservedAfterMicrocredits: account.ReservedMicrocredits,
|
||||
BillingOrderID: order.ID,
|
||||
Model: order.Model,
|
||||
ChannelID: order.ChannelID,
|
||||
Scene: order.Scene,
|
||||
}).Error
|
||||
})
|
||||
}
|
||||
|
||||
func (r *Repository) RefundBillingOrder(id string, errorText string) error {
|
||||
return r.db.Transaction(func(tx *gorm.DB) error {
|
||||
var order model.BillingOrder
|
||||
if err := tx.First(&order, "id = ?", id).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if order.Status == model.BillingStatusRefunded {
|
||||
return nil
|
||||
}
|
||||
if order.Status == model.BillingStatusSettled {
|
||||
return errors.New("settled billing order requires a manual refund")
|
||||
}
|
||||
updated := tx.Model(&model.CreditAccount{}).
|
||||
Where("user_id = ? AND reserved_microcredits >= ?", order.UserID, order.AmountMicrocredits).
|
||||
Updates(map[string]any{
|
||||
"available_microcredits": gorm.Expr("available_microcredits + ?", order.AmountMicrocredits),
|
||||
"reserved_microcredits": gorm.Expr("reserved_microcredits - ?", order.AmountMicrocredits),
|
||||
"version": gorm.Expr("version + 1"),
|
||||
"updated_at": time.Now(),
|
||||
})
|
||||
if updated.Error != nil {
|
||||
return updated.Error
|
||||
}
|
||||
if updated.RowsAffected != 1 {
|
||||
return errors.New("reserved credit balance is inconsistent")
|
||||
}
|
||||
var account model.CreditAccount
|
||||
if err := tx.First(&account, "user_id = ?", order.UserID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
now := time.Now()
|
||||
if err := tx.Model(&order).Updates(map[string]any{"status": model.BillingStatusRefunded, "error": errorText, "refunded_at": &now, "updated_at": now}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Create(&model.CreditLedgerEntry{
|
||||
ID: newRepositoryID(),
|
||||
UserID: order.UserID,
|
||||
Type: model.CreditLedgerRefund,
|
||||
AmountMicrocredits: order.AmountMicrocredits,
|
||||
AvailableDeltaMicrocredits: order.AmountMicrocredits,
|
||||
ReservedDeltaMicrocredits: -order.AmountMicrocredits,
|
||||
AvailableAfterMicrocredits: account.AvailableMicrocredits,
|
||||
ReservedAfterMicrocredits: account.ReservedMicrocredits,
|
||||
BillingOrderID: order.ID,
|
||||
Model: order.Model,
|
||||
ChannelID: order.ChannelID,
|
||||
Scene: order.Scene,
|
||||
Note: errorText,
|
||||
}).Error
|
||||
})
|
||||
}
|
||||
|
||||
func (r *Repository) AdjustCredits(userID string, actorUserID string, amount int64, note string) (*model.CreditAccount, error) {
|
||||
var account model.CreditAccount
|
||||
err := r.db.Transaction(func(tx *gorm.DB) error {
|
||||
account = model.CreditAccount{UserID: userID}
|
||||
if err := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&account).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
updated := tx.Model(&model.CreditAccount{}).
|
||||
Where("user_id = ? AND available_microcredits + ? >= 0", userID, amount).
|
||||
Updates(map[string]any{
|
||||
"available_microcredits": gorm.Expr("available_microcredits + ?", amount),
|
||||
"version": gorm.Expr("version + 1"),
|
||||
"updated_at": time.Now(),
|
||||
})
|
||||
if updated.Error != nil {
|
||||
return updated.Error
|
||||
}
|
||||
if updated.RowsAffected != 1 {
|
||||
return ErrInsufficientCredits
|
||||
}
|
||||
if err := tx.First(&account, "user_id = ?", userID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
entryType := model.CreditLedgerAdminAdjust
|
||||
if amount > 0 {
|
||||
entryType = model.CreditLedgerAdminGrant
|
||||
}
|
||||
return tx.Create(&model.CreditLedgerEntry{
|
||||
ID: newRepositoryID(),
|
||||
UserID: userID,
|
||||
Type: entryType,
|
||||
AmountMicrocredits: amount,
|
||||
AvailableDeltaMicrocredits: amount,
|
||||
AvailableAfterMicrocredits: account.AvailableMicrocredits,
|
||||
ReservedAfterMicrocredits: account.ReservedMicrocredits,
|
||||
ActorUserID: actorUserID,
|
||||
Note: note,
|
||||
}).Error
|
||||
})
|
||||
return &account, err
|
||||
}
|
||||
|
||||
func (r *Repository) CreateRedeemBatch(batch *model.RedeemBatch, codes []model.RedeemCode) error {
|
||||
return r.db.Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Create(batch).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.CreateInBatches(&codes, 200).Error
|
||||
})
|
||||
}
|
||||
|
||||
func (r *Repository) AdminRedeemBatches(keyword string, validity string, limit int, offset int) ([]model.RedeemBatch, int64, error) {
|
||||
var items []model.RedeemBatch
|
||||
var total int64
|
||||
query := r.db.Model(&model.RedeemBatch{})
|
||||
if value := strings.TrimSpace(keyword); value != "" {
|
||||
pattern := "%" + strings.ToLower(value) + "%"
|
||||
query = query.Where("lower(note) LIKE ? OR CAST(amount_microcredits AS TEXT) LIKE ? OR CAST(count AS TEXT) LIKE ?", pattern, pattern, pattern)
|
||||
}
|
||||
if validity == "active" {
|
||||
query = query.Where("expires_at IS NULL OR expires_at > ?", time.Now())
|
||||
} else if validity == "expired" {
|
||||
query = query.Where("expires_at IS NOT NULL AND expires_at <= ?", time.Now())
|
||||
}
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
now := time.Now()
|
||||
listQuery := query.Select(`redeem_batches.id, redeem_batches.amount_microcredits, redeem_batches.count,
|
||||
redeem_batches.note, redeem_batches.created_by, redeem_batches.expires_at, redeem_batches.created_at,
|
||||
(SELECT COUNT(*) FROM redeem_codes rc WHERE rc.batch_id = redeem_batches.id AND rc.status = 'unused' AND (rc.expires_at IS NULL OR rc.expires_at > ?)) AS available_count,
|
||||
(SELECT COUNT(*) FROM redeem_codes rc WHERE rc.batch_id = redeem_batches.id AND rc.status = 'redeemed') AS redeemed_count,
|
||||
(SELECT COUNT(*) FROM redeem_codes rc WHERE rc.batch_id = redeem_batches.id AND rc.status = 'disabled') AS disabled_count,
|
||||
(SELECT COUNT(*) FROM redeem_codes rc WHERE rc.batch_id = redeem_batches.id AND rc.status = 'unused' AND rc.expires_at IS NOT NULL AND rc.expires_at <= ?) AS expired_count`, now, now)
|
||||
if err := listQuery.Order("created_at desc").Limit(limit).Offset(offset).Find(&items).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
return items, total, nil
|
||||
}
|
||||
|
||||
func (r *Repository) RedeemBatch(id string) (*model.RedeemBatch, error) {
|
||||
var batch model.RedeemBatch
|
||||
now := time.Now()
|
||||
query := r.db.Model(&model.RedeemBatch{}).Select(`redeem_batches.*,
|
||||
(SELECT COUNT(*) FROM redeem_codes rc WHERE rc.batch_id = redeem_batches.id AND rc.status = 'unused' AND (rc.expires_at IS NULL OR rc.expires_at > ?)) AS available_count,
|
||||
(SELECT COUNT(*) FROM redeem_codes rc WHERE rc.batch_id = redeem_batches.id AND rc.status = 'redeemed') AS redeemed_count,
|
||||
(SELECT COUNT(*) FROM redeem_codes rc WHERE rc.batch_id = redeem_batches.id AND rc.status = 'disabled') AS disabled_count,
|
||||
(SELECT COUNT(*) FROM redeem_codes rc WHERE rc.batch_id = redeem_batches.id AND rc.status = 'unused' AND rc.expires_at IS NOT NULL AND rc.expires_at <= ?) AS expired_count`, now, now)
|
||||
if err := query.First(&batch, "redeem_batches.id = ?", id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &batch, nil
|
||||
}
|
||||
|
||||
func (r *Repository) AdminRedeemCodes(batchID string, status string, limit int, offset int) ([]AdminRedeemCodeRow, int64, error) {
|
||||
var items []AdminRedeemCodeRow
|
||||
var total int64
|
||||
query := r.db.Model(&model.RedeemCode{}).Where("redeem_codes.batch_id = ?", batchID)
|
||||
now := time.Now()
|
||||
switch status {
|
||||
case "available":
|
||||
query = query.Where("redeem_codes.status = ? AND (redeem_codes.expires_at IS NULL OR redeem_codes.expires_at > ?)", model.RedeemCodeUnused, now)
|
||||
case "redeemed":
|
||||
query = query.Where("redeem_codes.status = ?", model.RedeemCodeRedeemed)
|
||||
case "disabled":
|
||||
query = query.Where("redeem_codes.status = ?", model.RedeemCodeDisabled)
|
||||
case "expired":
|
||||
query = query.Where("redeem_codes.status = ? AND redeem_codes.expires_at IS NOT NULL AND redeem_codes.expires_at <= ?", model.RedeemCodeUnused, now)
|
||||
}
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
err := query.Select("redeem_codes.*, users.username AS redeemed_username, users.display_name AS redeemed_display_name").
|
||||
Joins("LEFT JOIN users ON users.id = redeem_codes.redeemed_by").
|
||||
Order("redeem_codes.created_at asc, redeem_codes.id asc").Limit(limit).Offset(offset).Scan(&items).Error
|
||||
return items, total, err
|
||||
}
|
||||
|
||||
func (r *Repository) RedeemCode(userID string, codeHash string, redeemedIP string) (*model.CreditAccount, error) {
|
||||
var account model.CreditAccount
|
||||
err := r.db.Transaction(func(tx *gorm.DB) error {
|
||||
var code model.RedeemCode
|
||||
if err := tx.First(&code, "code_hash = ?", codeHash).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return ErrRedeemCodeInvalid
|
||||
}
|
||||
return err
|
||||
}
|
||||
now := time.Now()
|
||||
query := tx.Model(&model.RedeemCode{}).Where("id = ? AND status = ?", code.ID, model.RedeemCodeUnused)
|
||||
if code.ExpiresAt != nil {
|
||||
query = query.Where("expires_at > ?", now)
|
||||
}
|
||||
updated := query.Updates(map[string]any{"status": model.RedeemCodeRedeemed, "redeemed_by": userID, "redeemed_at": &now, "redeemed_ip": redeemedIP, "updated_at": now})
|
||||
if updated.Error != nil {
|
||||
return updated.Error
|
||||
}
|
||||
if updated.RowsAffected != 1 {
|
||||
return ErrRedeemCodeInvalid
|
||||
}
|
||||
account = model.CreditAccount{UserID: userID}
|
||||
if err := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&account).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Model(&model.CreditAccount{}).Where("user_id = ?", userID).Updates(map[string]any{
|
||||
"available_microcredits": gorm.Expr("available_microcredits + ?", code.AmountMicrocredits),
|
||||
"version": gorm.Expr("version + 1"),
|
||||
"updated_at": now,
|
||||
}).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.First(&account, "user_id = ?", userID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Create(&model.CreditLedgerEntry{
|
||||
ID: newRepositoryID(),
|
||||
UserID: userID,
|
||||
Type: model.CreditLedgerRedeem,
|
||||
AmountMicrocredits: code.AmountMicrocredits,
|
||||
AvailableDeltaMicrocredits: code.AmountMicrocredits,
|
||||
AvailableAfterMicrocredits: account.AvailableMicrocredits,
|
||||
ReservedAfterMicrocredits: account.ReservedMicrocredits,
|
||||
RedeemCodeID: code.ID,
|
||||
Note: "兑换码充值",
|
||||
}).Error
|
||||
})
|
||||
return &account, err
|
||||
}
|
||||
|
||||
func newRepositoryID() string {
|
||||
return randomRepositorySuffix()
|
||||
}
|
||||
|
||||
func randomRepositorySuffix() string {
|
||||
var value [16]byte
|
||||
if _, err := rand.Read(value[:]); err != nil {
|
||||
return "fallback"
|
||||
}
|
||||
return hex.EncodeToString(value[:])
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"infinite-canvas/backend/internal/model"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
func (r *Repository) UserIdentity(provider string, subject string) (*model.UserIdentity, error) {
|
||||
var identity model.UserIdentity
|
||||
if err := r.db.First(&identity, "provider = ? AND subject = ?", provider, subject).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &identity, nil
|
||||
}
|
||||
|
||||
func (r *Repository) UserIdentityForUser(userID string, provider string) (*model.UserIdentity, error) {
|
||||
var identity model.UserIdentity
|
||||
if err := r.db.First(&identity, "user_id = ? AND provider = ?", userID, provider).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &identity, nil
|
||||
}
|
||||
|
||||
func (r *Repository) CreateOAuthState(state *model.OAuthState) error {
|
||||
return r.db.Create(state).Error
|
||||
}
|
||||
|
||||
func (r *Repository) ConsumeOAuthState(provider string, stateHash string) (*model.OAuthState, error) {
|
||||
var state model.OAuthState
|
||||
err := r.db.Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.First(&state, "provider = ? AND state_hash = ? AND used_at IS NULL AND expires_at > ?", provider, stateHash, time.Now()).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
now := time.Now()
|
||||
updated := tx.Model(&model.OAuthState{}).Where("id = ? AND used_at IS NULL", state.ID).Update("used_at", &now)
|
||||
if updated.Error != nil {
|
||||
return updated.Error
|
||||
}
|
||||
if updated.RowsAffected != 1 {
|
||||
return gorm.ErrRecordNotFound
|
||||
}
|
||||
state.UsedAt = &now
|
||||
return nil
|
||||
})
|
||||
return &state, err
|
||||
}
|
||||
|
||||
func (r *Repository) CreateOAuthUser(user *model.User, identity *model.UserIdentity) error {
|
||||
return r.db.Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Create(user).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if err := tx.Create(identity).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Create(&model.CreditAccount{UserID: user.ID}).Error
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,804 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"infinite-canvas/backend/internal/model"
|
||||
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
var ErrDailyUploadLimitExceeded = errors.New("daily upload limit exceeded")
|
||||
|
||||
type Repository struct {
|
||||
db *gorm.DB
|
||||
}
|
||||
|
||||
type UserStorageUsage struct {
|
||||
AssetCount int64
|
||||
AssetBytes int64
|
||||
CanvasCount int64
|
||||
CanvasBytes int64
|
||||
SessionCount int64
|
||||
SessionBytes int64
|
||||
TaskCount int64
|
||||
TaskBytes int64
|
||||
APICallCount int64
|
||||
}
|
||||
|
||||
func New(db *gorm.DB) *Repository {
|
||||
return &Repository{db: db}
|
||||
}
|
||||
|
||||
func (r *Repository) Dialect() string {
|
||||
return r.db.Dialector.Name()
|
||||
}
|
||||
|
||||
func (r *Repository) UserStorageUsage(userID string) (UserStorageUsage, error) {
|
||||
var usage UserStorageUsage
|
||||
query := `
|
||||
SELECT
|
||||
(SELECT COUNT(*) FROM assets WHERE user_id = ?) AS asset_count,
|
||||
(SELECT COALESCE(SUM(length(CAST(COALESCE(payload_json, '') AS BLOB))), 0) FROM assets WHERE user_id = ?) AS asset_bytes,
|
||||
(SELECT COUNT(*) FROM canvas_projects WHERE user_id = ?) AS canvas_count,
|
||||
(SELECT COALESCE(SUM(length(CAST(COALESCE(payload_json, '') AS BLOB))), 0) FROM canvas_projects WHERE user_id = ?) AS canvas_bytes,
|
||||
(SELECT COUNT(*) FROM sessions WHERE user_id = ?) AS session_count,
|
||||
(SELECT COALESCE(SUM(length(CAST(COALESCE(prompt, '') AS BLOB)) + length(CAST(COALESCE(canvas_snapshot_json, '') AS BLOB)) + length(CAST(COALESCE(canvas_ops_json, '') AS BLOB))), 0) FROM sessions WHERE user_id = ?)
|
||||
+ (SELECT COALESCE(SUM(length(CAST(COALESCE(content, '') AS BLOB)) + length(CAST(COALESCE(payload, '') AS BLOB))), 0) FROM messages WHERE user_id = ?) AS session_bytes,
|
||||
(SELECT COUNT(*) FROM tasks WHERE user_id = ?) AS task_count,
|
||||
(SELECT COALESCE(SUM(length(CAST(COALESCE(prompt, '') AS BLOB)) + length(CAST(COALESCE(input_json, '') AS BLOB)) + length(CAST(COALESCE(result_json, '') AS BLOB)) + length(CAST(COALESCE(error, '') AS BLOB))), 0) FROM tasks WHERE user_id = ?)
|
||||
+ (SELECT COALESCE(SUM(length(CAST(COALESCE(message, '') AS BLOB)) + length(CAST(COALESCE(payload, '') AS BLOB))), 0) FROM task_logs WHERE user_id = ?)
|
||||
+ (SELECT COALESCE(SUM(length(CAST(COALESCE(url, '') AS BLOB)) + length(CAST(COALESCE(payload, '') AS BLOB))), 0) FROM results WHERE user_id = ?)
|
||||
+ (SELECT COALESCE(SUM(length(CAST(COALESCE(path, '') AS BLOB)) + length(CAST(COALESCE(model, '') AS BLOB)) + length(CAST(COALESCE(provider_request_id, '') AS BLOB)) + length(CAST(COALESCE(error_code, '') AS BLOB)) + length(CAST(COALESCE(error, '') AS BLOB)) + length(CAST(COALESCE(upstream_url, '') AS BLOB))), 0) FROM api_call_logs WHERE user_id = ?) AS task_bytes,
|
||||
(SELECT COUNT(*) FROM api_call_logs WHERE user_id = ?) AS api_call_count
|
||||
`
|
||||
if r.Dialect() == "postgres" {
|
||||
query = strings.ReplaceAll(query, "length(CAST(COALESCE(", "octet_length(COALESCE(")
|
||||
query = strings.ReplaceAll(query, ", '') AS BLOB))", ", ''))")
|
||||
}
|
||||
err := r.db.Raw(query, userID, userID, userID, userID, userID, userID, userID, userID, userID, userID, userID, userID, userID).Scan(&usage).Error
|
||||
return usage, err
|
||||
}
|
||||
|
||||
func (r *Repository) Create(value any) error {
|
||||
return r.db.Create(value).Error
|
||||
}
|
||||
|
||||
func (r *Repository) Save(value any) error {
|
||||
return r.db.Save(value).Error
|
||||
}
|
||||
|
||||
func (r *Repository) AllTasks() ([]model.Task, error) {
|
||||
var tasks []model.Task
|
||||
return tasks, r.db.Find(&tasks).Error
|
||||
}
|
||||
|
||||
func (r *Repository) AllAssets() ([]model.Asset, error) {
|
||||
var assets []model.Asset
|
||||
return assets, r.db.Find(&assets).Error
|
||||
}
|
||||
|
||||
func (r *Repository) AllCanvasProjects() ([]model.CanvasProject, error) {
|
||||
var projects []model.CanvasProject
|
||||
return projects, r.db.Find(&projects).Error
|
||||
}
|
||||
|
||||
func (r *Repository) CleanupDuplicateTaskPayloads() error {
|
||||
return r.db.Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Model(&model.TaskLog{}).Where("length(payload) > ?", 4000).Update("payload", "").Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Delete(&model.Result{}, "kind = ? AND session_id = ?", "generation_result", "").Error
|
||||
})
|
||||
}
|
||||
|
||||
func (r *Repository) BackupSQLite(path string) error {
|
||||
if r.Dialect() != "sqlite" {
|
||||
return errors.New("当前数据库不是 SQLite,不能执行 SQLite 备份")
|
||||
}
|
||||
escaped := strings.ReplaceAll(path, "'", "''")
|
||||
return r.db.Exec("VACUUM INTO '" + escaped + "'").Error
|
||||
}
|
||||
|
||||
func (r *Repository) Vacuum() error {
|
||||
if r.Dialect() != "sqlite" {
|
||||
return nil
|
||||
}
|
||||
return r.db.Exec("VACUUM").Error
|
||||
}
|
||||
|
||||
func (r *Repository) Delete(value any, query any, args ...any) error {
|
||||
conds := append([]any{query}, args...)
|
||||
return r.db.Delete(value, conds...).Error
|
||||
}
|
||||
|
||||
func (r *Repository) UserCount() (int64, error) {
|
||||
var count int64
|
||||
err := r.db.Model(&model.User{}).Count(&count).Error
|
||||
return count, err
|
||||
}
|
||||
|
||||
func (r *Repository) User(id string) (*model.User, error) {
|
||||
var user model.User
|
||||
if err := r.db.First(&user, "id = ?", id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
func (r *Repository) UserByAccount(account string) (*model.User, error) {
|
||||
var user model.User
|
||||
if err := r.db.Where("lower(username) = lower(?) OR lower(email) = lower(?)", account, account).First(&user).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
func (r *Repository) UserByUsername(username string) (*model.User, error) {
|
||||
var user model.User
|
||||
if err := r.db.Where("lower(username) = lower(?)", username).First(&user).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
func (r *Repository) UserByEmail(email string) (*model.User, error) {
|
||||
var user model.User
|
||||
if err := r.db.Where("email <> '' AND lower(email) = lower(?)", email).First(&user).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
func (r *Repository) Users() ([]model.User, error) {
|
||||
var users []model.User
|
||||
err := r.db.Order("created_at desc").Find(&users).Error
|
||||
return users, err
|
||||
}
|
||||
|
||||
func (r *Repository) AdminUsers(keyword string, role model.UserRole, status model.UserStatus, limit int, offset int) ([]model.User, int64, error) {
|
||||
var users []model.User
|
||||
var total int64
|
||||
query := r.db.Model(&model.User{})
|
||||
if value := strings.TrimSpace(keyword); value != "" {
|
||||
pattern := "%" + strings.ToLower(value) + "%"
|
||||
query = query.Where("lower(username) LIKE ? OR lower(display_name) LIKE ? OR lower(email) LIKE ?", pattern, pattern, pattern)
|
||||
}
|
||||
if role == model.UserRoleAdmin || role == model.UserRoleUser {
|
||||
query = query.Where("role = ?", role)
|
||||
}
|
||||
if status == model.UserStatusActive || status == model.UserStatusDisabled {
|
||||
query = query.Where("status = ?", status)
|
||||
}
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if err := query.Order("created_at desc").Limit(limit).Offset(offset).Find(&users).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
return users, total, nil
|
||||
}
|
||||
|
||||
func (r *Repository) AdminUserReferences() ([]model.User, error) {
|
||||
var users []model.User
|
||||
err := r.db.Select("id", "username", "display_name").Order("created_at desc").Limit(100).Find(&users).Error
|
||||
return users, err
|
||||
}
|
||||
|
||||
func (r *Repository) ActiveAdminCountExcluding(userID string) (int64, error) {
|
||||
var count int64
|
||||
query := r.db.Model(&model.User{}).Where("role = ? AND status = ?", model.UserRoleAdmin, model.UserStatusActive)
|
||||
if userID != "" {
|
||||
query = query.Where("id <> ?", userID)
|
||||
}
|
||||
err := query.Count(&count).Error
|
||||
return count, err
|
||||
}
|
||||
|
||||
func (r *Repository) AuthSession(id string) (*model.AuthSession, error) {
|
||||
var session model.AuthSession
|
||||
if err := r.db.First(&session, "id = ?", id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &session, nil
|
||||
}
|
||||
|
||||
func (r *Repository) DeleteAuthSession(id string) error {
|
||||
return r.db.Delete(&model.AuthSession{}, "id = ?", id).Error
|
||||
}
|
||||
|
||||
func (r *Repository) DeleteExpiredAuthSessions() error {
|
||||
return r.db.Delete(&model.AuthSession{}, "expires_at <= ?", time.Now()).Error
|
||||
}
|
||||
|
||||
func (r *Repository) DeleteUserAuthSessions(userID string) error {
|
||||
return r.db.Delete(&model.AuthSession{}, "user_id = ?", userID).Error
|
||||
}
|
||||
|
||||
func (r *Repository) LatestEmailVerificationCode(email string, purpose string) (*model.EmailVerificationCode, error) {
|
||||
var code model.EmailVerificationCode
|
||||
if err := r.db.Where("email = ? AND purpose = ? AND used_at IS NULL", email, purpose).Order("created_at desc").First(&code).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &code, nil
|
||||
}
|
||||
|
||||
func (r *Repository) MarkEmailVerificationCodeUsed(id string, usedAt time.Time) error {
|
||||
return r.db.Model(&model.EmailVerificationCode{}).Where("id = ? AND used_at IS NULL", id).Update("used_at", usedAt).Error
|
||||
}
|
||||
|
||||
func (r *Repository) DeleteEmailVerificationCode(id string) error {
|
||||
return r.db.Delete(&model.EmailVerificationCode{}, "id = ?", id).Error
|
||||
}
|
||||
|
||||
func (r *Repository) CreateUserWithEmailVerification(user *model.User, verificationCodeID string, usedAt time.Time) error {
|
||||
return r.db.Transaction(func(tx *gorm.DB) error {
|
||||
result := tx.Model(&model.EmailVerificationCode{}).Where("id = ? AND used_at IS NULL AND expires_at > ?", verificationCodeID, usedAt).Update("used_at", usedAt)
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
if result.RowsAffected != 1 {
|
||||
return errors.New("email verification code is no longer valid")
|
||||
}
|
||||
return tx.Create(user).Error
|
||||
})
|
||||
}
|
||||
|
||||
func (r *Repository) DeleteExpiredEmailVerificationCodes(now time.Time) error {
|
||||
return r.db.Delete(&model.EmailVerificationCode{}, "expires_at <= ? OR used_at IS NOT NULL", now).Error
|
||||
}
|
||||
|
||||
func (r *Repository) Task(id string) (*model.Task, error) {
|
||||
var task model.Task
|
||||
if err := r.db.First(&task, "id = ?", id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &task, nil
|
||||
}
|
||||
|
||||
func (r *Repository) TaskForUser(userID string, id string) (*model.Task, error) {
|
||||
var task model.Task
|
||||
if err := r.db.First(&task, "id = ? AND user_id = ?", id, userID).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &task, nil
|
||||
}
|
||||
|
||||
func (r *Repository) ActiveTaskCountForUser(userID string) (int64, error) {
|
||||
var count int64
|
||||
err := r.db.Model(&model.Task{}).Where("user_id = ? AND status IN ?", userID, []model.TaskStatus{model.TaskStatusQueued, model.TaskStatusRunning}).Count(&count).Error
|
||||
return count, err
|
||||
}
|
||||
|
||||
// 任务领取以数据库租约为真相;PostgreSQL 锁行跳过竞争任务,SQLite 继续依赖条件更新保证单实例原子性。
|
||||
func (r *Repository) ClaimNextTask(owner string, leaseDuration time.Duration) (*model.Task, error) {
|
||||
var task model.Task
|
||||
now := time.Now()
|
||||
leaseExpiresAt := now.Add(leaseDuration)
|
||||
err := r.db.Transaction(func(tx *gorm.DB) error {
|
||||
query := tx.Where("status = ? OR (status = ? AND (lease_expires_at IS NULL OR lease_expires_at <= ?))", model.TaskStatusQueued, model.TaskStatusRunning, now).
|
||||
Order("created_at asc").Limit(1)
|
||||
if r.Dialect() == "postgres" {
|
||||
query = query.Clauses(clause.Locking{Strength: "UPDATE", Options: "SKIP LOCKED"})
|
||||
}
|
||||
result := query.Find(&task)
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
if result.RowsAffected == 0 {
|
||||
task = model.Task{}
|
||||
return nil
|
||||
}
|
||||
claim := tx.Model(&model.Task{}).Where("id = ?", task.ID)
|
||||
if r.Dialect() != "postgres" {
|
||||
claim = claim.Where("status = ? OR (status = ? AND (lease_expires_at IS NULL OR lease_expires_at <= ?))", model.TaskStatusQueued, model.TaskStatusRunning, now)
|
||||
}
|
||||
updated := claim.
|
||||
Updates(map[string]any{
|
||||
"status": model.TaskStatusRunning,
|
||||
"stage": "后端接管任务",
|
||||
"progress": 15,
|
||||
"attempts": gorm.Expr("attempts + ?", 1),
|
||||
"started_at": gorm.Expr("COALESCE(started_at, ?)", now),
|
||||
"lease_owner": owner,
|
||||
"lease_expires_at": leaseExpiresAt,
|
||||
"updated_at": now,
|
||||
})
|
||||
if updated.Error != nil {
|
||||
return updated.Error
|
||||
}
|
||||
if updated.RowsAffected == 0 {
|
||||
task = model.Task{}
|
||||
return nil
|
||||
}
|
||||
return tx.First(&task, "id = ?", task.ID).Error
|
||||
})
|
||||
if err != nil || task.ID == "" {
|
||||
return nil, err
|
||||
}
|
||||
return &task, nil
|
||||
}
|
||||
|
||||
func (r *Repository) RenewTaskLease(id string, owner string, leaseDuration time.Duration) error {
|
||||
result := r.db.Model(&model.Task{}).
|
||||
Where("id = ? AND status = ? AND lease_owner = ?", id, model.TaskStatusRunning, owner).
|
||||
Updates(map[string]any{"lease_expires_at": time.Now().Add(leaseDuration), "updated_at": time.Now()})
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
if result.RowsAffected != 1 {
|
||||
return errors.New("任务租约已失效")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (r *Repository) UpdateTaskProviderState(id string, providerRequestID string, pollStage string, nextPollAt *time.Time) error {
|
||||
updates := map[string]any{"poll_stage": pollStage, "next_poll_at": nextPollAt, "updated_at": time.Now()}
|
||||
if strings.TrimSpace(providerRequestID) != "" {
|
||||
updates["provider_request_id"] = strings.TrimSpace(providerRequestID)
|
||||
}
|
||||
return r.db.Model(&model.Task{}).Where("id = ?", id).Updates(updates).Error
|
||||
}
|
||||
|
||||
func (r *Repository) UpdateTaskProgress(id string, stage string, progress int) error {
|
||||
return r.db.Model(&model.Task{}).Where("id = ?", id).Updates(map[string]any{
|
||||
"stage": stage, "progress": progress, "updated_at": time.Now(),
|
||||
}).Error
|
||||
}
|
||||
|
||||
func (r *Repository) SaveTaskCompletion(task *model.Task, session *model.Session, message *model.Message, results []model.Result) error {
|
||||
return r.db.Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Save(task).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if session != nil {
|
||||
if err := tx.Save(session).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if message != nil {
|
||||
if err := tx.Create(message).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
for index := range results {
|
||||
if err := tx.Create(&results[index]).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (r *Repository) CancelTaskIfStatus(userID string, id string, expected model.TaskStatus, now time.Time) (bool, error) {
|
||||
result := r.db.Model(&model.Task{}).
|
||||
Where("id = ? AND user_id = ? AND status = ?", id, userID, expected).
|
||||
Updates(map[string]any{
|
||||
"status": model.TaskStatusCancelled, "stage": "任务已取消", "completed_at": &now, "updated_at": now,
|
||||
})
|
||||
return result.RowsAffected == 1, result.Error
|
||||
}
|
||||
|
||||
func (r *Repository) Tasks(userID string, limit int, projectID string, activeOnly bool) ([]model.Task, error) {
|
||||
var tasks []model.Task
|
||||
if limit <= 0 || limit > 100 {
|
||||
limit = 50
|
||||
}
|
||||
query := r.db.Select("id", "session_id", "project_id", "type", "status", "stage", "progress", "prompt", "operation", "provider", "model", "billing_order_id", "attempts", "started_at", "completed_at", "created_at", "updated_at").
|
||||
Where("user_id = ?", userID)
|
||||
if strings.TrimSpace(projectID) != "" {
|
||||
query = query.Where("project_id = ?", strings.TrimSpace(projectID))
|
||||
}
|
||||
if activeOnly {
|
||||
query = query.Where("status IN ?", []model.TaskStatus{model.TaskStatusQueued, model.TaskStatusRunning})
|
||||
}
|
||||
err := query.Order("created_at desc").Limit(limit).Find(&tasks).Error
|
||||
return tasks, err
|
||||
}
|
||||
|
||||
func (r *Repository) Session(id string) (*model.Session, error) {
|
||||
var session model.Session
|
||||
if err := r.db.First(&session, "id = ?", id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &session, nil
|
||||
}
|
||||
|
||||
func (r *Repository) SessionForUser(userID string, id string) (*model.Session, error) {
|
||||
var session model.Session
|
||||
if err := r.db.First(&session, "id = ? AND user_id = ?", id, userID).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &session, nil
|
||||
}
|
||||
|
||||
func (r *Repository) DeleteSessionDraft(userID string, id string) error {
|
||||
return r.db.Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Delete(&model.Message{}, "user_id = ? AND session_id = ?", userID, id).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
return tx.Delete(&model.Session{}, "id = ? AND user_id = ?", id, userID).Error
|
||||
})
|
||||
}
|
||||
|
||||
func (r *Repository) SessionMessages(userID string, sessionID string) ([]model.Message, error) {
|
||||
var messages []model.Message
|
||||
err := r.db.Order("created_at asc").Find(&messages, "user_id = ? AND session_id = ?", userID, sessionID).Error
|
||||
return messages, err
|
||||
}
|
||||
|
||||
func (r *Repository) SessionTasks(userID string, sessionID string) ([]model.Task, error) {
|
||||
var tasks []model.Task
|
||||
err := r.db.Select("id", "user_id", "session_id", "project_id", "type", "status", "prompt", "operation", "provider", "model", "attempts", "started_at", "completed_at", "created_at", "updated_at").
|
||||
Order("created_at asc").
|
||||
Find(&tasks, "user_id = ? AND session_id = ?", userID, sessionID).Error
|
||||
return tasks, err
|
||||
}
|
||||
|
||||
func (r *Repository) SessionResults(userID string, sessionID string) ([]model.Result, error) {
|
||||
var results []model.Result
|
||||
err := r.db.Order("created_at asc").Find(&results, "user_id = ? AND session_id = ?", userID, sessionID).Error
|
||||
return results, err
|
||||
}
|
||||
|
||||
func (r *Repository) TaskLogs(userID string, taskID string) ([]model.TaskLog, error) {
|
||||
var logs []model.TaskLog
|
||||
err := r.db.Order("created_at asc").Find(&logs, "user_id = ? AND task_id = ?", userID, taskID).Error
|
||||
return logs, err
|
||||
}
|
||||
|
||||
func (r *Repository) SystemChannels(includeDisabled bool) ([]model.ModelChannel, error) {
|
||||
var channels []model.ModelChannel
|
||||
query := r.db.Order("created_at asc").Where("scope = ?", model.ChannelScopeSystem)
|
||||
if !includeDisabled {
|
||||
query = query.Where("enabled = ?", true)
|
||||
}
|
||||
err := query.Find(&channels).Error
|
||||
return channels, err
|
||||
}
|
||||
|
||||
func (r *Repository) AdminSystemChannels(keyword string, interfaceType string, status string, limit int, offset int) ([]model.ModelChannel, int64, error) {
|
||||
var channels []model.ModelChannel
|
||||
var total int64
|
||||
query := r.db.Model(&model.ModelChannel{}).Where("scope = ?", model.ChannelScopeSystem)
|
||||
if value := strings.TrimSpace(keyword); value != "" {
|
||||
pattern := "%" + strings.ToLower(value) + "%"
|
||||
query = query.Where("lower(name) LIKE ? OR lower(base_url) LIKE ?", pattern, pattern)
|
||||
}
|
||||
if value := strings.TrimSpace(interfaceType); value != "" && value != "all" {
|
||||
query = query.Where("interface_type = ?", value)
|
||||
}
|
||||
if status == "enabled" {
|
||||
query = query.Where("enabled = ?", true)
|
||||
} else if status == "disabled" {
|
||||
query = query.Where("enabled = ?", false)
|
||||
}
|
||||
if err := query.Count(&total).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
if err := query.Order("created_at desc").Limit(limit).Offset(offset).Find(&channels).Error; err != nil {
|
||||
return nil, 0, err
|
||||
}
|
||||
return channels, total, nil
|
||||
}
|
||||
|
||||
func (r *Repository) AdminSystemChannelReferences() ([]model.ModelChannel, error) {
|
||||
var channels []model.ModelChannel
|
||||
err := r.db.Select("id", "name").Where("scope = ?", model.ChannelScopeSystem).Order("created_at asc").Find(&channels).Error
|
||||
return channels, err
|
||||
}
|
||||
|
||||
func (r *Repository) SystemChannel(id string) (*model.ModelChannel, error) {
|
||||
var channel model.ModelChannel
|
||||
if err := r.db.First(&channel, "id = ? AND scope = ? AND enabled = ?", id, model.ChannelScopeSystem, true).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &channel, nil
|
||||
}
|
||||
|
||||
func (r *Repository) AdminSystemChannel(id string) (*model.ModelChannel, error) {
|
||||
var channel model.ModelChannel
|
||||
if err := r.db.First(&channel, "id = ? AND scope = ?", id, model.ChannelScopeSystem).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &channel, nil
|
||||
}
|
||||
|
||||
func (r *Repository) ApiCallLogs(userID string, admin bool, limit int) ([]model.ApiCallLog, error) {
|
||||
var logs []model.ApiCallLog
|
||||
if limit <= 0 || limit > 200 {
|
||||
limit = 100
|
||||
}
|
||||
query := r.db.Order("created_at desc").Limit(limit)
|
||||
if !admin {
|
||||
query = query.Where("user_id = ?", userID)
|
||||
}
|
||||
err := query.Find(&logs).Error
|
||||
return logs, err
|
||||
}
|
||||
|
||||
func (r *Repository) SystemSetting(key string) (*model.SystemSetting, error) {
|
||||
var setting model.SystemSetting
|
||||
if err := r.db.First(&setting, "key = ?", key).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &setting, nil
|
||||
}
|
||||
|
||||
func (r *Repository) SaveSystemSetting(setting *model.SystemSetting) error {
|
||||
return r.db.Save(setting).Error
|
||||
}
|
||||
|
||||
func (r *Repository) LatestUserOSSSetting(userID string) (*model.UserOSSSetting, error) {
|
||||
var setting model.UserOSSSetting
|
||||
if err := r.db.Where("user_id = ?", userID).Order("created_at desc, id desc").First(&setting).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &setting, nil
|
||||
}
|
||||
|
||||
func (r *Repository) UserOSSSettingForUser(userID string, id string) (*model.UserOSSSetting, error) {
|
||||
var setting model.UserOSSSetting
|
||||
if err := r.db.First(&setting, "id = ? AND user_id = ?", id, userID).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &setting, nil
|
||||
}
|
||||
|
||||
func (r *Repository) CreateUserOSSSetting(setting *model.UserOSSSetting) error {
|
||||
return r.db.Create(setting).Error
|
||||
}
|
||||
|
||||
func (r *Repository) ReserveDailyUpload(userID string, day string, size int64, limit int64) error {
|
||||
usage := model.UserDailyUploadUsage{ID: userID + ":" + day, UserID: userID, Day: day}
|
||||
return r.db.Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Clauses(clause.OnConflict{DoNothing: true}).Create(&usage).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
result := tx.Model(&model.UserDailyUploadUsage{}).
|
||||
Where("id = ? AND bytes + ? < ?", usage.ID, size, limit).
|
||||
Updates(map[string]any{"bytes": gorm.Expr("bytes + ?", size), "updated_at": time.Now()})
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
if result.RowsAffected == 0 {
|
||||
return ErrDailyUploadLimitExceeded
|
||||
}
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (r *Repository) ReleaseDailyUpload(userID string, day string, size int64) error {
|
||||
id := userID + ":" + day
|
||||
return r.db.Model(&model.UserDailyUploadUsage{}).
|
||||
Where("id = ?", id).
|
||||
Updates(map[string]any{
|
||||
"bytes": gorm.Expr("CASE WHEN bytes >= ? THEN bytes - ? ELSE 0 END", size, size),
|
||||
"updated_at": time.Now(),
|
||||
}).Error
|
||||
}
|
||||
|
||||
func (r *Repository) UserStoredFileBytes(userID string) (int64, error) {
|
||||
var total int64
|
||||
err := r.db.Raw(`
|
||||
SELECT
|
||||
(SELECT COALESCE(SUM(size), 0) FROM resources WHERE user_id = ?)
|
||||
+ (SELECT COALESCE(SUM(size), 0) FROM session_files WHERE user_id = ?)
|
||||
`, userID, userID).Scan(&total).Error
|
||||
return total, err
|
||||
}
|
||||
|
||||
func (r *Repository) DailyUploadBytes(userID string, day string) (int64, error) {
|
||||
var total int64
|
||||
err := r.db.Model(&model.UserDailyUploadUsage{}).Select("COALESCE(bytes, 0)").Where("user_id = ? AND day = ?", userID, day).Scan(&total).Error
|
||||
return total, err
|
||||
}
|
||||
|
||||
func (r *Repository) CreateResource(resource *model.Resource) error {
|
||||
return r.db.Create(resource).Error
|
||||
}
|
||||
|
||||
func (r *Repository) SaveResource(resource *model.Resource) error {
|
||||
return r.db.Save(resource).Error
|
||||
}
|
||||
|
||||
func (r *Repository) ResourceForUser(userID string, id string) (*model.Resource, error) {
|
||||
var resource model.Resource
|
||||
if err := r.db.First(&resource, "id = ? AND user_id = ?", id, userID).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &resource, nil
|
||||
}
|
||||
|
||||
func (r *Repository) Resources(userID string, limit int) ([]model.Resource, error) {
|
||||
var resources []model.Resource
|
||||
if limit <= 0 || limit > 500 {
|
||||
limit = 200
|
||||
}
|
||||
err := r.db.Order("created_at desc").Limit(limit).Find(&resources, "user_id = ?", userID).Error
|
||||
return resources, err
|
||||
}
|
||||
|
||||
func (r *Repository) Assets(userID string) ([]model.Asset, error) {
|
||||
var assets []model.Asset
|
||||
err := r.db.Order("updated_at desc").Find(&assets, "user_id = ?", userID).Error
|
||||
return assets, err
|
||||
}
|
||||
|
||||
func (r *Repository) AssetSummaries(userID string) ([]model.Asset, error) {
|
||||
var assets []model.Asset
|
||||
err := r.db.Select("id", "kind", "title", "created_at", "updated_at").Order("updated_at desc").Find(&assets, "user_id = ?", userID).Error
|
||||
return assets, err
|
||||
}
|
||||
|
||||
func (r *Repository) AssetForUser(userID string, id string) (*model.Asset, error) {
|
||||
var asset model.Asset
|
||||
if err := r.db.First(&asset, "id = ? AND user_id = ?", id, userID).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &asset, nil
|
||||
}
|
||||
|
||||
func (r *Repository) UpsertAsset(asset *model.Asset) error {
|
||||
result := r.db.Model(&model.Asset{}).
|
||||
Where("id = ? AND user_id = ?", asset.ID, asset.UserID).
|
||||
Updates(map[string]any{"kind": asset.Kind, "title": asset.Title, "payload_json": asset.PayloadJSON, "updated_at": asset.UpdatedAt})
|
||||
if result.Error != nil || result.RowsAffected > 0 {
|
||||
return result.Error
|
||||
}
|
||||
return r.db.Create(asset).Error
|
||||
}
|
||||
|
||||
func (r *Repository) DeleteAsset(userID string, id string) error {
|
||||
return r.db.Delete(&model.Asset{}, "id = ? AND user_id = ?", id, userID).Error
|
||||
}
|
||||
|
||||
func (r *Repository) ReplaceAssets(userID string, assets []model.Asset) error {
|
||||
return r.db.Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Delete(&model.Asset{}, "user_id = ?", userID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if len(assets) == 0 {
|
||||
return nil
|
||||
}
|
||||
return tx.Create(&assets).Error
|
||||
})
|
||||
}
|
||||
|
||||
func (r *Repository) CanvasProjects(userID string) ([]model.CanvasProject, error) {
|
||||
var projects []model.CanvasProject
|
||||
err := r.db.Order("updated_at desc").Find(&projects, "user_id = ?", userID).Error
|
||||
return projects, err
|
||||
}
|
||||
|
||||
func (r *Repository) CanvasProjectSummaries(userID string) ([]model.CanvasProject, error) {
|
||||
var projects []model.CanvasProject
|
||||
err := r.db.Select("id", "title", "created_at", "updated_at").Order("updated_at desc").Find(&projects, "user_id = ?", userID).Error
|
||||
return projects, err
|
||||
}
|
||||
|
||||
func (r *Repository) CanvasProjectForUser(userID string, id string) (*model.CanvasProject, error) {
|
||||
var project model.CanvasProject
|
||||
if err := r.db.First(&project, "id = ? AND user_id = ?", id, userID).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &project, nil
|
||||
}
|
||||
|
||||
func (r *Repository) UpsertCanvasProject(project *model.CanvasProject) error {
|
||||
result := r.db.Model(&model.CanvasProject{}).
|
||||
Where("id = ? AND user_id = ?", project.ID, project.UserID).
|
||||
Updates(map[string]any{"title": project.Title, "payload_json": project.PayloadJSON, "updated_at": project.UpdatedAt})
|
||||
if result.Error != nil || result.RowsAffected > 0 {
|
||||
return result.Error
|
||||
}
|
||||
return r.db.Create(project).Error
|
||||
}
|
||||
|
||||
func (r *Repository) DeleteCanvasProject(userID string, id string) error {
|
||||
return r.db.Delete(&model.CanvasProject{}, "id = ? AND user_id = ?", id, userID).Error
|
||||
}
|
||||
|
||||
func (r *Repository) CanvasShareForProject(userID string, projectID string) (*model.CanvasShare, error) {
|
||||
var share model.CanvasShare
|
||||
if err := r.db.First(&share, "user_id = ? AND project_id = ?", userID, projectID).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &share, nil
|
||||
}
|
||||
|
||||
func (r *Repository) CanvasShareByTokenHash(tokenHash string) (*model.CanvasShare, error) {
|
||||
var share model.CanvasShare
|
||||
if err := r.db.First(&share, "token_hash = ? AND enabled = ?", tokenHash, true).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &share, nil
|
||||
}
|
||||
|
||||
func (r *Repository) DeleteCanvasShare(userID string, projectID string) error {
|
||||
return r.db.Delete(&model.CanvasShare{}, "user_id = ? AND project_id = ?", userID, projectID).Error
|
||||
}
|
||||
|
||||
func (r *Repository) ReplaceCanvasProjects(userID string, projects []model.CanvasProject) error {
|
||||
return r.db.Transaction(func(tx *gorm.DB) error {
|
||||
if err := tx.Delete(&model.CanvasProject{}, "user_id = ?", userID).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
if len(projects) == 0 {
|
||||
return nil
|
||||
}
|
||||
return tx.Create(&projects).Error
|
||||
})
|
||||
}
|
||||
|
||||
func (r *Repository) StoryboardPromptTemplates() ([]model.StoryboardPromptTemplate, error) {
|
||||
var templates []model.StoryboardPromptTemplate
|
||||
err := r.db.Order("updated_at desc").Find(&templates).Error
|
||||
return templates, err
|
||||
}
|
||||
|
||||
func (r *Repository) StoryboardPromptTemplate(id string) (*model.StoryboardPromptTemplate, error) {
|
||||
var template model.StoryboardPromptTemplate
|
||||
if err := r.db.First(&template, "id = ?", id).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &template, nil
|
||||
}
|
||||
|
||||
func (r *Repository) ActiveStoryboardPromptTemplate() (*model.StoryboardPromptTemplate, error) {
|
||||
var template model.StoryboardPromptTemplate
|
||||
if err := r.db.Order("updated_at desc").First(&template, "enabled = ?", true).Error; err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &template, nil
|
||||
}
|
||||
|
||||
func (r *Repository) StoryboardPromptTemplateCount() (int64, error) {
|
||||
var count int64
|
||||
err := r.db.Model(&model.StoryboardPromptTemplate{}).Count(&count).Error
|
||||
return count, err
|
||||
}
|
||||
|
||||
func (r *Repository) SaveStoryboardPromptTemplate(template *model.StoryboardPromptTemplate) error {
|
||||
return r.db.Transaction(func(tx *gorm.DB) error {
|
||||
if template.Enabled {
|
||||
if err := tx.Model(&model.StoryboardPromptTemplate{}).Where("id <> ?", template.ID).Update("enabled", false).Error; err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return tx.Save(template).Error
|
||||
})
|
||||
}
|
||||
|
||||
func (r *Repository) DeleteStoryboardPromptTemplate(id string) error {
|
||||
return r.db.Delete(&model.StoryboardPromptTemplate{}, "id = ?", id).Error
|
||||
}
|
||||
|
||||
func (r *Repository) UserSkillState(userID string, skillDir string) (*model.UserSkillState, error) {
|
||||
var state model.UserSkillState
|
||||
if err := r.db.First(&state, "user_id = ? AND skill_dir = ?", userID, skillDir).Error; err != nil {
|
||||
if errors.Is(err, gorm.ErrRecordNotFound) {
|
||||
return nil, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
return &state, nil
|
||||
}
|
||||
|
||||
func (r *Repository) UserSkillStates(userID string) ([]model.UserSkillState, error) {
|
||||
var states []model.UserSkillState
|
||||
err := r.db.Order("updated_at desc").Find(&states, "user_id = ?", userID).Error
|
||||
return states, err
|
||||
}
|
||||
|
||||
func (r *Repository) UserSkillStatesByDirs(userID string, skillDirs []string) ([]model.UserSkillState, error) {
|
||||
if len(skillDirs) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
var states []model.UserSkillState
|
||||
err := r.db.Find(&states, "user_id = ? AND skill_dir IN ?", userID, skillDirs).Error
|
||||
return states, err
|
||||
}
|
||||
Reference in new issue
Block a user