package app import ( "context" "encoding/json" "errors" "fmt" "strings" "time" "github.com/google/uuid" "github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5/pgtype" "github.com/jackc/pgx/v5/pgxpool" "golang.org/x/sync/singleflight" "github.com/geo-platform/tenant-api/internal/shared/auditlog" "github.com/geo-platform/tenant-api/internal/shared/auth" sharedcache "github.com/geo-platform/tenant-api/internal/shared/cache" "github.com/geo-platform/tenant-api/internal/shared/middleware" "github.com/geo-platform/tenant-api/internal/shared/response" sharedschedule "github.com/geo-platform/tenant-api/internal/shared/schedule" "github.com/geo-platform/tenant-api/internal/tenant/repository" ) type ScheduleTaskService struct { pool *pgxpool.Pool auditLogs *auditlog.AsyncWriter promptAsset *KolPromptAsset cache sharedcache.Cache cacheGroup singleflight.Group } func NewScheduleTaskService(pool *pgxpool.Pool, auditLogs *auditlog.AsyncWriter, promptAsset *KolPromptAsset) *ScheduleTaskService { return &ScheduleTaskService{pool: pool, auditLogs: auditLogs, promptAsset: promptAsset} } func (s *ScheduleTaskService) WithCache(c sharedcache.Cache) *ScheduleTaskService { s.cache = c return s } type ScheduleTaskRequest struct { TargetType string `json:"target_type"` PromptRuleID *int64 `json:"prompt_rule_id"` SubscriptionPromptID *int64 `json:"subscription_prompt_id"` BrandID *int64 `json:"brand_id"` Name string `json:"name" binding:"required"` CronExpr string `json:"cron_expr"` ScheduleKind string `json:"schedule_kind"` ScheduleDays []string `json:"schedule_days"` ScheduleTimeMode string `json:"schedule_time_mode"` RandomWindowStart string `json:"random_window_start"` RandomWindowEnd string `json:"random_window_end"` GenerationInput map[string]interface{} `json:"generation_input"` AutoPublish *bool `json:"auto_publish"` PublishAccountIDs []string `json:"publish_account_ids"` PublishEnterpriseSiteTargets []ScheduleEnterpriseSiteTarget `json:"publish_enterprise_site_targets"` CoverAssetURL *string `json:"cover_asset_url"` CoverImageAssetID *int64 `json:"cover_image_asset_id"` CoverMode string `json:"cover_mode"` CoverRandomScope string `json:"cover_random_scope"` CoverRandomFolderID *int64 `json:"cover_random_folder_id"` EnableWebSearch *bool `json:"enable_web_search"` GenerateCount *int `json:"generate_count"` StartAt *string `json:"start_at"` EndAt *string `json:"end_at"` } type ScheduleTaskResponse struct { ID int64 `json:"id"` WorkspaceID *int64 `json:"workspace_id"` TargetType string `json:"target_type"` PromptRuleID *int64 `json:"prompt_rule_id"` PromptRuleName *string `json:"prompt_rule_name"` SubscriptionPromptID *int64 `json:"subscription_prompt_id"` SubscriptionPromptName *string `json:"subscription_prompt_name"` SubscriptionPackageName *string `json:"subscription_package_name"` SubscriptionKolName *string `json:"subscription_kol_name"` BrandID *int64 `json:"brand_id"` BrandName *string `json:"brand_name"` Name string `json:"name"` CronExpr string `json:"cron_expr"` ScheduleKind string `json:"schedule_kind"` ScheduleDays []string `json:"schedule_days"` ScheduleTimeMode string `json:"schedule_time_mode"` RandomWindowStart string `json:"random_window_start"` RandomWindowEnd string `json:"random_window_end"` GenerationInput map[string]interface{} `json:"generation_input"` AutoPublish bool `json:"auto_publish"` PublishAccountIDs []string `json:"publish_account_ids"` PublishEnterpriseSiteTargets []ScheduleEnterpriseSiteTarget `json:"publish_enterprise_site_targets"` AutoPublishPlatforms []string `json:"auto_publish_platforms"` CoverAssetURL *string `json:"cover_asset_url"` CoverImageAssetID *int64 `json:"cover_image_asset_id"` CoverMode string `json:"cover_mode"` CoverRandomScope string `json:"cover_random_scope"` CoverRandomFolderID *int64 `json:"cover_random_folder_id"` EnableWebSearch bool `json:"enable_web_search"` GenerateCount int `json:"generate_count"` StartAt *string `json:"start_at"` EndAt *string `json:"end_at"` NextRunAt *string `json:"next_run_at"` Status string `json:"status"` LastRunAt *string `json:"last_run_at"` LastDispatchStatus *string `json:"last_dispatch_status"` LastDispatchError *string `json:"last_dispatch_error"` ConsecutiveFailures int `json:"consecutive_failures"` GenerationStatus *string `json:"generation_status"` ExecutionTime *string `json:"execution_time"` GeneratedArticles []InstantTaskArticleLink `json:"generated_articles"` CreatedAt string `json:"created_at"` UpdatedAt string `json:"updated_at"` } type ScheduleTaskListParams struct { PromptRuleID *int64 `json:"prompt_rule_id"` SubscriptionPromptID *int64 `json:"subscription_prompt_id"` TargetType *string `json:"target_type"` Status *string `json:"status"` Keyword *string `json:"keyword"` CreatedFrom *time.Time CreatedTo *time.Time Page int `json:"page"` PageSize int `json:"page_size"` } type ScheduleTaskListResponse struct { Items []ScheduleTaskResponse `json:"items"` Total int64 `json:"total"` } type ScheduleTaskStatusRequest struct { Status string `json:"status" binding:"required,oneof=enabled disabled"` } func (s *ScheduleTaskService) List(ctx context.Context, params ScheduleTaskListParams) (*ScheduleTaskListResponse, error) { actor := auth.MustActor(ctx) brandID, err := requireCurrentBrandID(ctx) if err != nil { return nil, err } return sharedcache.LoadJSON(ctx, s.cache, &s.cacheGroup, scheduleTaskListCacheKey(actor.TenantID, brandID, params), defaultCacheTTL(), func(loadCtx context.Context) (*ScheduleTaskListResponse, error) { return s.loadScheduleTasks(loadCtx, actor.TenantID, brandID, params) }) } func (s *ScheduleTaskService) Detail(ctx context.Context, id int64) (*ScheduleTaskResponse, error) { actor := auth.MustActor(ctx) brandID, err := requireCurrentBrandID(ctx) if err != nil { return nil, err } record, found, err := sharedcache.LoadJSONWithEmpty(ctx, s.cache, &s.cacheGroup, scheduleTaskDetailCacheKey(actor.TenantID, brandID, id), defaultCacheTTL(), defaultCacheEmptyTTL(), func(loadCtx context.Context) (*ScheduleTaskResponse, bool, error) { return s.loadScheduleTaskDetail(loadCtx, actor.TenantID, brandID, id) }) if err != nil { return nil, err } if !found || record == nil { return nil, response.ErrNotFound(40432, "schedule_not_found", "schedule task not found") } return record, nil } func (s *ScheduleTaskService) Create(ctx context.Context, req ScheduleTaskRequest) (*ScheduleTaskResponse, error) { actor := auth.MustActor(ctx) brandID, err := requireCurrentBrandID(ctx) if err != nil { return nil, err } req.BrandID = &brandID targetType, promptRuleID, subscriptionPromptID, err := normalizeScheduleTarget(req) if err != nil { return nil, err } plan, err := normalizeSchedulePlan(req) if err != nil { return nil, err } generationInput := clonePromptRuleExtraParams(req.GenerationInput) if targetType == ScheduleTargetPromptRule { if err := s.ensurePromptRuleExists(ctx, actor.TenantID, brandID, *promptRuleID); err != nil { return nil, err } generationInput = map[string]interface{}{} } else { generationInput, err = s.validateKolScheduleGenerationInput(ctx, actor.TenantID, *subscriptionPromptID, generationInput) if err != nil { return nil, err } } generateCount, err := normalizeScheduleGenerateCount(req.GenerateCount) if err != nil { return nil, err } enableWebSearch := boolValue(req.EnableWebSearch) publishConfig, err := s.normalizeAutoPublishConfig(ctx, actor, req) if err != nil { return nil, err } tx, err := s.pool.Begin(ctx) if err != nil { return nil, response.ErrInternal(50010, "create_failed", "failed to begin schedule task transaction") } defer tx.Rollback(ctx) var id int64 var createdAt time.Time var startAt pgtype.Timestamptz var endAt pgtype.Timestamptz var status string err = tx.QueryRow(ctx, ` INSERT INTO schedule_tasks ( tenant_id, workspace_id, operator_id, target_type, prompt_rule_id, subscription_prompt_id, brand_id, name, cron_expr, schedule_kind, schedule_days, schedule_time_mode, random_window_start, random_window_end, generation_input_json, enable_web_search, generate_count, auto_publish, publish_account_ids, publish_enterprise_site_targets, cover_asset_url, cover_image_asset_id, cover_mode, cover_random_scope, cover_random_folder_id, start_at, end_at ) VALUES ( $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11::jsonb, $12, $13::time, $14::time, $15::jsonb, $16, $17, $18, $19::jsonb, $20::jsonb, $21, $22, $23, $24, $25, $26::timestamptz, $27::timestamptz ) RETURNING id, created_at, start_at, end_at, status `, actor.TenantID, actor.PrimaryWorkspaceID, actor.UserID, targetType, promptRuleID, subscriptionPromptID, req.BrandID, req.Name, plan.CronExpr, plan.ScheduleKind, encodeScheduleDayKeys(plan.ScheduleDays), plan.ScheduleTimeMode, plan.RandomWindowStart, plan.RandomWindowEnd, encodeScheduleGenerationInput(generationInput), enableWebSearch, generateCount, publishConfig.AutoPublish, publishConfig.AccountIDsJSON, publishConfig.EnterpriseTargetsJSON, publishConfig.CoverAssetURL, publishConfig.CoverImageAssetID, publishConfig.CoverMode, publishConfig.CoverRandomScope, publishConfig.CoverRandomFolderID, req.StartAt, req.EndAt). Scan(&id, &createdAt, &startAt, &endAt, &status) if err != nil { return nil, response.ErrInternal(50010, "create_failed", "failed to create schedule task") } nextRunAt, err := computeScheduleNextRun(status, id, plan.CronExpr, plan.ScheduleDays, plan.ScheduleTimeMode, plan.RandomWindowStart, plan.RandomWindowEnd, timePtrFromTimestamp(startAt), timePtrFromTimestamp(endAt), time.Now()) if err != nil { return nil, response.ErrBadRequest(40015, "invalid_cron_expr", err.Error()) } if _, err := tx.Exec(ctx, ` UPDATE schedule_tasks SET next_run_at = $1, updated_at = NOW() WHERE id = $2 AND tenant_id = $3 `, nextRunAt, id, actor.TenantID); err != nil { return nil, response.ErrInternal(50010, "create_failed", "failed to initialize next run time") } if err := tx.Commit(ctx); err != nil { return nil, response.ErrInternal(50010, "create_failed", "failed to commit schedule task") } afterJSON, _ := json.Marshal(map[string]interface{}{ "id": id, "name": req.Name, "target_type": targetType, "cron_expr": plan.CronExpr, "schedule_days": plan.ScheduleDays, "schedule_time_mode": plan.ScheduleTimeMode, "enable_web_search": enableWebSearch, "generate_count": generateCount, "auto_publish": publishConfig.AutoPublish, }) result := "success" resourceType := "schedule_task" requestID := middleware.RequestIDFromContext(ctx) s.auditLogs.Log(auditlog.Entry{ OperatorID: actor.UserID, TenantID: &actor.TenantID, Module: "schedule_task", Action: "create", ResourceType: &resourceType, ResourceID: &id, RequestID: nilIfEmptyString(requestID), AfterJSON: afterJSON, Result: &result, }) invalidateScheduleTaskCaches(ctx, s.cache, actor.TenantID, &id) workspaceID := actor.PrimaryWorkspaceID return &ScheduleTaskResponse{ ID: id, WorkspaceID: &workspaceID, TargetType: targetType, PromptRuleID: promptRuleID, SubscriptionPromptID: subscriptionPromptID, BrandID: req.BrandID, Name: req.Name, CronExpr: plan.CronExpr, ScheduleKind: plan.ScheduleKind, ScheduleDays: plan.ScheduleDays, ScheduleTimeMode: plan.ScheduleTimeMode, RandomWindowStart: plan.RandomWindowStart, RandomWindowEnd: plan.RandomWindowEnd, GenerationInput: generationInput, AutoPublish: publishConfig.AutoPublish, PublishAccountIDs: publishConfig.AccountIDs, PublishEnterpriseSiteTargets: publishConfig.EnterpriseTargets, AutoPublishPlatforms: publishConfig.PlatformIDs, CoverAssetURL: publishConfig.CoverAssetURL, CoverImageAssetID: publishConfig.CoverImageAssetID, CoverMode: publishConfig.CoverMode, CoverRandomScope: publishConfig.CoverRandomScope, CoverRandomFolderID: publishConfig.CoverRandomFolderID, EnableWebSearch: enableWebSearch, GenerateCount: generateCount, Status: status, CreatedAt: timeStringFromDBValue(createdAt), NextRunAt: timeStringPtr(nextRunAt), }, nil } func (s *ScheduleTaskService) Update(ctx context.Context, id int64, req ScheduleTaskRequest) error { actor := auth.MustActor(ctx) brandID, err := requireCurrentBrandID(ctx) if err != nil { return err } req.BrandID = &brandID targetType, promptRuleID, subscriptionPromptID, err := normalizeScheduleTarget(req) if err != nil { return err } plan, err := normalizeSchedulePlan(req) if err != nil { return err } generationInput := clonePromptRuleExtraParams(req.GenerationInput) if targetType == ScheduleTargetPromptRule { if err := s.ensurePromptRuleExists(ctx, actor.TenantID, brandID, *promptRuleID); err != nil { return err } generationInput = map[string]interface{}{} } else { generationInput, err = s.validateKolScheduleGenerationInput(ctx, actor.TenantID, *subscriptionPromptID, generationInput) if err != nil { return err } } generateCount, err := normalizeScheduleGenerateCount(req.GenerateCount) if err != nil { return err } enableWebSearch := boolValue(req.EnableWebSearch) publishConfig, err := s.normalizeAutoPublishConfig(ctx, actor, req) if err != nil { return err } tx, err := s.pool.Begin(ctx) if err != nil { return response.ErrInternal(50010, "update_failed", "failed to begin schedule task transaction") } defer tx.Rollback(ctx) var status string var startAt pgtype.Timestamptz var endAt pgtype.Timestamptz err = tx.QueryRow(ctx, ` UPDATE schedule_tasks SET target_type = $1, prompt_rule_id = $2, subscription_prompt_id = $3, brand_id = $4, name = $5, cron_expr = $6, schedule_kind = $7, schedule_days = $8::jsonb, schedule_time_mode = $9, random_window_start = $10::time, random_window_end = $11::time, generation_input_json = $12::jsonb, enable_web_search = $13, generate_count = $14, workspace_id = $15, auto_publish = $16, publish_account_ids = $17::jsonb, publish_enterprise_site_targets = $18::jsonb, cover_asset_url = $19, cover_image_asset_id = $20, cover_mode = $21, cover_random_scope = $22, cover_random_folder_id = $23, start_at = $24::timestamptz, end_at = $25::timestamptz, operator_id = $26, last_dispatch_status = NULL, last_dispatch_error = NULL, consecutive_failures = 0, updated_at = NOW() WHERE id = $27 AND tenant_id = $28 AND brand_id = $29 AND deleted_at IS NULL RETURNING status, start_at, end_at `, targetType, promptRuleID, subscriptionPromptID, req.BrandID, req.Name, plan.CronExpr, plan.ScheduleKind, encodeScheduleDayKeys(plan.ScheduleDays), plan.ScheduleTimeMode, plan.RandomWindowStart, plan.RandomWindowEnd, encodeScheduleGenerationInput(generationInput), enableWebSearch, generateCount, actor.PrimaryWorkspaceID, publishConfig.AutoPublish, publishConfig.AccountIDsJSON, publishConfig.EnterpriseTargetsJSON, publishConfig.CoverAssetURL, publishConfig.CoverImageAssetID, publishConfig.CoverMode, publishConfig.CoverRandomScope, publishConfig.CoverRandomFolderID, req.StartAt, req.EndAt, actor.UserID, id, actor.TenantID, brandID). Scan(&status, &startAt, &endAt) if err != nil { return response.ErrNotFound(40432, "schedule_not_found", "schedule task not found") } nextRunAt, err := computeScheduleNextRun(status, id, plan.CronExpr, plan.ScheduleDays, plan.ScheduleTimeMode, plan.RandomWindowStart, plan.RandomWindowEnd, timePtrFromTimestamp(startAt), timePtrFromTimestamp(endAt), time.Now()) if err != nil { return response.ErrBadRequest(40015, "invalid_cron_expr", err.Error()) } if _, err := tx.Exec(ctx, ` UPDATE schedule_tasks SET next_run_at = $1, updated_at = NOW() WHERE id = $2 AND tenant_id = $3 `, nextRunAt, id, actor.TenantID); err != nil { return response.ErrInternal(50010, "update_failed", "failed to refresh next run time") } if err := tx.Commit(ctx); err != nil { return response.ErrInternal(50010, "update_failed", "failed to commit schedule task") } invalidateScheduleTaskCaches(ctx, s.cache, actor.TenantID, &id) return nil } func (s *ScheduleTaskService) Delete(ctx context.Context, id int64) error { actor := auth.MustActor(ctx) brandID, err := requireCurrentBrandID(ctx) if err != nil { return err } tag, err := s.pool.Exec(ctx, ` UPDATE schedule_tasks SET deleted_at = NOW(), updated_at = NOW() WHERE id = $1 AND tenant_id = $2 AND brand_id = $3 AND deleted_at IS NULL `, id, actor.TenantID, brandID) if err != nil || tag.RowsAffected() == 0 { return response.ErrNotFound(40432, "schedule_not_found", "schedule task not found") } afterJSON, _ := json.Marshal(map[string]interface{}{"id": id}) result := "success" resourceType := "schedule_task" requestID := middleware.RequestIDFromContext(ctx) s.auditLogs.Log(auditlog.Entry{ OperatorID: actor.UserID, TenantID: &actor.TenantID, Module: "schedule_task", Action: "delete", ResourceType: &resourceType, ResourceID: &id, RequestID: nilIfEmptyString(requestID), AfterJSON: afterJSON, Result: &result, }) invalidateScheduleTaskCaches(ctx, s.cache, actor.TenantID, &id) return nil } func (s *ScheduleTaskService) ToggleStatus(ctx context.Context, id int64, req ScheduleTaskStatusRequest) error { actor := auth.MustActor(ctx) brandID, err := requireCurrentBrandID(ctx) if err != nil { return err } tx, err := s.pool.Begin(ctx) if err != nil { return response.ErrInternal(50010, "update_failed", "failed to begin schedule task transaction") } defer tx.Rollback(ctx) var cronExpr string var status string var scheduleTimeMode string var randomWindowStart string var randomWindowEnd string var scheduleDaysJSON []byte var startAt pgtype.Timestamptz var endAt pgtype.Timestamptz err = tx.QueryRow(ctx, ` UPDATE schedule_tasks SET status = $1, operator_id = $2, updated_at = NOW() WHERE id = $3 AND tenant_id = $4 AND brand_id = $5 AND deleted_at IS NULL RETURNING cron_expr, status, schedule_days, schedule_time_mode, random_window_start::text, random_window_end::text, start_at, end_at `, req.Status, actor.UserID, id, actor.TenantID, brandID). Scan(&cronExpr, &status, &scheduleDaysJSON, &scheduleTimeMode, &randomWindowStart, &randomWindowEnd, &startAt, &endAt) if err != nil { return response.ErrNotFound(40432, "schedule_not_found", "schedule task not found") } nextRunAt, err := computeScheduleNextRun(status, id, cronExpr, decodeScheduleDayKeys(scheduleDaysJSON), scheduleTimeMode, randomWindowStart, randomWindowEnd, timePtrFromTimestamp(startAt), timePtrFromTimestamp(endAt), time.Now()) if err != nil { return response.ErrBadRequest(40015, "invalid_cron_expr", err.Error()) } if _, err := tx.Exec(ctx, ` UPDATE schedule_tasks SET next_run_at = $1, updated_at = NOW() WHERE id = $2 AND tenant_id = $3 `, nextRunAt, id, actor.TenantID); err != nil { return response.ErrInternal(50010, "update_failed", "failed to refresh next run time") } if err := tx.Commit(ctx); err != nil { return response.ErrInternal(50010, "update_failed", "failed to commit schedule task") } invalidateScheduleTaskCaches(ctx, s.cache, actor.TenantID, &id) return nil } func (s *ScheduleTaskService) loadScheduleTasks(ctx context.Context, tenantID, brandID int64, params ScheduleTaskListParams) (*ScheduleTaskListResponse, error) { if params.Page < 1 { params.Page = 1 } if params.PageSize < 1 || params.PageSize > 100 { params.PageSize = 20 } offset := (params.Page - 1) * params.PageSize var total int64 if err := s.pool.QueryRow(ctx, ` SELECT COUNT(*) FROM schedule_tasks WHERE tenant_id = $1 AND brand_id = $2 AND deleted_at IS NULL AND ($3::bigint IS NULL OR prompt_rule_id = $3) AND ($4::text IS NULL OR status = $4) AND ($5::text IS NULL OR name ILIKE '%' || $5 || '%') AND ($6::timestamptz IS NULL OR created_at >= $6) AND ($7::timestamptz IS NULL OR created_at <= $7) AND ($8::text IS NULL OR target_type = $8) AND ($9::bigint IS NULL OR subscription_prompt_id = $9) `, tenantID, brandID, params.PromptRuleID, params.Status, params.Keyword, params.CreatedFrom, params.CreatedTo, params.TargetType, params.SubscriptionPromptID).Scan(&total); err != nil { return nil, response.ErrInternal(50010, "count_failed", "failed to count schedule tasks") } rows, err := s.pool.Query(ctx, ` SELECT st.id, st.workspace_id, st.target_type, st.prompt_rule_id, st.subscription_prompt_id, st.brand_id, st.name, st.cron_expr, st.schedule_kind, st.schedule_days, st.schedule_time_mode, st.random_window_start::text, st.random_window_end::text, st.generation_input_json, st.auto_publish, st.publish_account_ids, st.publish_enterprise_site_targets, st.cover_asset_url, st.cover_image_asset_id, st.cover_mode, st.cover_random_scope, st.cover_random_folder_id, st.enable_web_search, st.generate_count, st.start_at, st.end_at, st.next_run_at, st.status, st.last_run_at, st.last_dispatch_status, st.last_dispatch_error, st.consecutive_failures, st.created_at, st.updated_at, pr.name AS prompt_rule_name, sp_prompt.name AS subscription_prompt_name, sp_pkg.name AS subscription_package_name, sp_profile.display_name AS subscription_kol_name, b.name AS brand_name FROM schedule_tasks st LEFT JOIN prompt_rules pr ON pr.id = st.prompt_rule_id LEFT JOIN kol_subscription_prompts sp ON sp.id = st.subscription_prompt_id LEFT JOIN kol_prompts sp_prompt ON sp_prompt.id = sp.prompt_id LEFT JOIN kol_packages sp_pkg ON sp_pkg.id = sp.package_id LEFT JOIN kol_profiles sp_profile ON sp_profile.id = sp_pkg.kol_profile_id LEFT JOIN brands b ON b.id = st.brand_id WHERE st.tenant_id = $1 AND st.brand_id = $2 AND st.deleted_at IS NULL AND ($3::bigint IS NULL OR st.prompt_rule_id = $3) AND ($4::text IS NULL OR st.status = $4) AND ($5::text IS NULL OR st.name ILIKE '%' || $5 || '%') AND ($6::timestamptz IS NULL OR st.created_at >= $6) AND ($7::timestamptz IS NULL OR st.created_at <= $7) AND ($10::text IS NULL OR st.target_type = $10) AND ($11::bigint IS NULL OR st.subscription_prompt_id = $11) ORDER BY st.created_at DESC LIMIT $8 OFFSET $9 `, tenantID, brandID, params.PromptRuleID, params.Status, params.Keyword, params.CreatedFrom, params.CreatedTo, params.PageSize, offset, params.TargetType, params.SubscriptionPromptID) if err != nil { return nil, response.ErrInternal(50010, "query_failed", "failed to list schedule tasks") } defer rows.Close() items := make([]ScheduleTaskResponse, 0) for rows.Next() { item, err := scanScheduleTaskResponse(rows) if err != nil { return nil, err } items = append(items, item) } if err := rows.Err(); err != nil { return nil, response.ErrInternal(50010, "scan_failed", "failed to iterate schedule tasks") } if err := s.populateScheduleTaskListDecorations(ctx, tenantID, items); err != nil { return nil, err } return &ScheduleTaskListResponse{Items: items, Total: total}, nil } func (s *ScheduleTaskService) loadScheduleTaskDetail(ctx context.Context, tenantID, brandID, taskID int64) (*ScheduleTaskResponse, bool, error) { row := s.pool.QueryRow(ctx, ` SELECT st.id, st.workspace_id, st.target_type, st.prompt_rule_id, st.subscription_prompt_id, st.brand_id, st.name, st.cron_expr, st.schedule_kind, st.schedule_days, st.schedule_time_mode, st.random_window_start::text, st.random_window_end::text, st.generation_input_json, st.auto_publish, st.publish_account_ids, st.publish_enterprise_site_targets, st.cover_asset_url, st.cover_image_asset_id, st.cover_mode, st.cover_random_scope, st.cover_random_folder_id, st.enable_web_search, st.generate_count, st.start_at, st.end_at, st.next_run_at, st.status, st.last_run_at, st.last_dispatch_status, st.last_dispatch_error, st.consecutive_failures, st.created_at, st.updated_at, pr.name AS prompt_rule_name, sp_prompt.name AS subscription_prompt_name, sp_pkg.name AS subscription_package_name, sp_profile.display_name AS subscription_kol_name, b.name AS brand_name FROM schedule_tasks st LEFT JOIN prompt_rules pr ON pr.id = st.prompt_rule_id LEFT JOIN kol_subscription_prompts sp ON sp.id = st.subscription_prompt_id LEFT JOIN kol_prompts sp_prompt ON sp_prompt.id = sp.prompt_id LEFT JOIN kol_packages sp_pkg ON sp_pkg.id = sp.package_id LEFT JOIN kol_profiles sp_profile ON sp_profile.id = sp_pkg.kol_profile_id LEFT JOIN brands b ON b.id = st.brand_id WHERE st.id = $1 AND st.tenant_id = $2 AND st.brand_id = $3 AND st.deleted_at IS NULL `, taskID, tenantID, brandID) item, err := scanScheduleTaskResponse(row) if err != nil { if errors.Is(err, pgx.ErrNoRows) { return nil, false, nil } return nil, false, err } if err := s.populateScheduleAutoPublishPlatforms(ctx, tenantID, &item); err != nil { return nil, false, err } if err := s.populateScheduleLatestGeneratedArticles(ctx, tenantID, &item); err != nil { return nil, false, err } return &item, true, nil } func (s *ScheduleTaskService) populateScheduleTaskListDecorations(ctx context.Context, tenantID int64, items []ScheduleTaskResponse) error { if len(items) == 0 { return nil } if err := s.populateScheduleAutoPublishPlatformsBatch(ctx, tenantID, items); err != nil { return err } return s.populateScheduleLatestGeneratedArticlesBatch(ctx, tenantID, items) } func (s *ScheduleTaskService) populateScheduleAutoPublishPlatforms(ctx context.Context, tenantID int64, item *ScheduleTaskResponse) error { if item == nil || !item.AutoPublish { return nil } platformIDs, err := loadPublishAccountPlatformsByIDs(ctx, s.pool, tenantID, item.PublishAccountIDs) if err != nil { return response.ErrInternal(50010, "query_failed", "failed to resolve schedule auto publish platforms") } item.AutoPublishPlatforms = platformIDs return nil } func (s *ScheduleTaskService) populateScheduleAutoPublishPlatformsBatch(ctx context.Context, tenantID int64, items []ScheduleTaskResponse) error { accountSet := make(map[string]struct{}) for _, item := range items { if !item.AutoPublish { continue } for _, accountID := range item.PublishAccountIDs { normalized := normalizeSchedulePublishAccountIDs([]string{accountID}) if len(normalized) == 0 { continue } accountSet[normalized[0]] = struct{}{} } } if len(accountSet) == 0 { return nil } accountIDs := make([]string, 0, len(accountSet)) for accountID := range accountSet { accountIDs = append(accountIDs, accountID) } rows, err := s.pool.Query(ctx, ` SELECT desktop_id::text, platform_id FROM platform_accounts WHERE tenant_id = $1 AND desktop_id::text = ANY($2::text[]) AND deleted_at IS NULL `, tenantID, accountIDs) if err != nil { return response.ErrInternal(50010, "query_failed", "failed to resolve schedule auto publish platforms") } defer rows.Close() platformsByAccount := make(map[string][]string, len(accountIDs)) for rows.Next() { var accountID string var platformID string if err := rows.Scan(&accountID, &platformID); err != nil { return response.ErrInternal(50010, "scan_failed", "failed to scan schedule auto publish platforms") } platformsByAccount[accountID] = append(platformsByAccount[accountID], platformID) } if err := rows.Err(); err != nil { return response.ErrInternal(50010, "scan_failed", "failed to iterate schedule auto publish platforms") } for idx := range items { if !items[idx].AutoPublish { continue } platformIDs := make([]string, 0, len(items[idx].PublishAccountIDs)) for _, accountID := range items[idx].PublishAccountIDs { normalized := normalizeSchedulePublishAccountIDs([]string{accountID}) if len(normalized) == 0 { continue } platformIDs = append(platformIDs, platformsByAccount[normalized[0]]...) } items[idx].AutoPublishPlatforms = emptyStringSliceIfNil(normalizePlatformIDs(platformIDs)) } return nil } func (s *ScheduleTaskService) populateScheduleLatestGeneratedArticles(ctx context.Context, tenantID int64, item *ScheduleTaskResponse) error { if item == nil || item.ID <= 0 { return nil } taskType := "custom_generation" if item.TargetType == ScheduleTargetKolSubscriptionPrompt { taskType = kolGenerationTaskType } rows, err := s.pool.Query(ctx, ` WITH latest_run AS ( SELECT COALESCE(NULLIF(gt.input_params_json ->> 'scheduled_for', ''), to_char(date_trunc('second', gt.created_at), 'YYYY-MM-DD"T"HH24:MI:SS"Z"')) AS run_key FROM generation_tasks gt WHERE gt.tenant_id = $1 AND gt.task_type = $3 AND COALESCE(NULLIF(gt.input_params_json ->> 'generation_mode', ''), '') = 'schedule' AND NULLIF(gt.input_params_json ->> 'schedule_task_id', '')::bigint = $2 ORDER BY gt.created_at DESC, gt.id DESC LIMIT 1 ) SELECT gt.id, COALESCE(a.id, gt.article_id) AS article_id, COALESCE(av.title, NULLIF(a.wizard_state_json ->> 'title', ''), NULLIF(gt.input_params_json ->> 'title', ''), NULLIF(gt.input_params_json ->> 'task_name', '')) AS article_title, COALESCE(a.generate_status, gt.status) AS article_generate_status, COALESCE(a.created_at, gt.created_at) AS article_created_at, COALESCE(gt.started_at, gt.completed_at, gt.created_at) AS execution_time FROM generation_tasks gt JOIN latest_run lr ON COALESCE(NULLIF(gt.input_params_json ->> 'scheduled_for', ''), to_char(date_trunc('second', gt.created_at), 'YYYY-MM-DD"T"HH24:MI:SS"Z"')) = lr.run_key LEFT JOIN articles a ON a.id = gt.article_id AND a.deleted_at IS NULL LEFT JOIN article_versions av ON av.id = a.current_version_id WHERE gt.tenant_id = $1 AND gt.task_type = $3 AND COALESCE(NULLIF(gt.input_params_json ->> 'generation_mode', ''), '') = 'schedule' AND NULLIF(gt.input_params_json ->> 'schedule_task_id', '')::bigint = $2 ORDER BY gt.created_at, gt.id `, tenantID, item.ID, taskType) if err != nil { return response.ErrInternal(50010, "query_failed", "failed to load schedule generated articles") } defer rows.Close() articles := make([]InstantTaskArticleLink, 0) statuses := make([]string, 0) var executionTime *string for rows.Next() { var taskID int64 var articleID *int64 var title *string var generateStatus string var createdAt interface{} var executionAt interface{} if err := rows.Scan(&taskID, &articleID, &title, &generateStatus, &createdAt, &executionAt); err != nil { return response.ErrInternal(50010, "scan_failed", err.Error()) } if executionTime == nil { executionTime = timeStringPtrFromDBValue(executionAt) } statuses = append(statuses, generateStatus) if articleID != nil && *articleID > 0 { articles = append(articles, InstantTaskArticleLink{ ArticleID: *articleID, Title: title, GenerateStatus: generateStatus, CreatedAt: timeStringFromDBValue(createdAt), }) } else { _ = taskID } } if err := rows.Err(); err != nil { return response.ErrInternal(50010, "scan_failed", "failed to iterate schedule generated articles") } item.GeneratedArticles = articles item.ExecutionTime = executionTime status := aggregateGeneratedArticleStatus(statuses) if status != "" { item.GenerationStatus = &status } return nil } func (s *ScheduleTaskService) populateScheduleLatestGeneratedArticlesBatch(ctx context.Context, tenantID int64, items []ScheduleTaskResponse) error { if len(items) == 0 { return nil } promptRuleTaskIDs := make([]int64, 0, len(items)) kolTaskIDs := make([]int64, 0, len(items)) indexByTaskID := make(map[int64]int, len(items)) for idx, item := range items { if item.ID <= 0 { continue } indexByTaskID[item.ID] = idx if item.TargetType == ScheduleTargetKolSubscriptionPrompt { kolTaskIDs = append(kolTaskIDs, item.ID) } else { promptRuleTaskIDs = append(promptRuleTaskIDs, item.ID) } } if err := s.populateScheduleLatestGeneratedArticlesBatchByType(ctx, tenantID, items, indexByTaskID, promptRuleTaskIDs, "custom_generation"); err != nil { return err } return s.populateScheduleLatestGeneratedArticlesBatchByType(ctx, tenantID, items, indexByTaskID, kolTaskIDs, kolGenerationTaskType) } func (s *ScheduleTaskService) populateScheduleLatestGeneratedArticlesBatchByType( ctx context.Context, tenantID int64, items []ScheduleTaskResponse, indexByTaskID map[int64]int, taskIDs []int64, taskType string, ) error { if len(taskIDs) == 0 { return nil } rows, err := s.pool.Query(ctx, ` WITH latest_run AS ( SELECT DISTINCT ON (NULLIF(gt.input_params_json ->> 'schedule_task_id', '')::bigint) NULLIF(gt.input_params_json ->> 'schedule_task_id', '')::bigint AS schedule_task_id, COALESCE(NULLIF(gt.input_params_json ->> 'scheduled_for', ''), to_char(date_trunc('second', gt.created_at), 'YYYY-MM-DD"T"HH24:MI:SS"Z"')) AS run_key FROM generation_tasks gt WHERE gt.tenant_id = $1 AND gt.task_type = $2 AND COALESCE(NULLIF(gt.input_params_json ->> 'generation_mode', ''), '') = 'schedule' AND NULLIF(gt.input_params_json ->> 'schedule_task_id', '')::bigint = ANY($3::bigint[]) ORDER BY NULLIF(gt.input_params_json ->> 'schedule_task_id', '')::bigint, gt.created_at DESC, gt.id DESC ) SELECT lr.schedule_task_id, gt.id, COALESCE(a.id, gt.article_id) AS article_id, COALESCE(av.title, NULLIF(a.wizard_state_json ->> 'title', ''), NULLIF(gt.input_params_json ->> 'title', ''), NULLIF(gt.input_params_json ->> 'task_name', '')) AS article_title, COALESCE(a.generate_status, gt.status) AS article_generate_status, COALESCE(a.created_at, gt.created_at) AS article_created_at, COALESCE(gt.started_at, gt.completed_at, gt.created_at) AS execution_time FROM latest_run lr JOIN generation_tasks gt ON gt.tenant_id = $1 AND gt.task_type = $2 AND COALESCE(NULLIF(gt.input_params_json ->> 'generation_mode', ''), '') = 'schedule' AND NULLIF(gt.input_params_json ->> 'schedule_task_id', '')::bigint = lr.schedule_task_id AND COALESCE(NULLIF(gt.input_params_json ->> 'scheduled_for', ''), to_char(date_trunc('second', gt.created_at), 'YYYY-MM-DD"T"HH24:MI:SS"Z"')) = lr.run_key LEFT JOIN articles a ON a.id = gt.article_id AND a.deleted_at IS NULL LEFT JOIN article_versions av ON av.id = a.current_version_id ORDER BY lr.schedule_task_id, gt.created_at, gt.id `, tenantID, taskType, taskIDs) if err != nil { return response.ErrInternal(50010, "query_failed", "failed to load schedule generated articles") } defer rows.Close() statusesByTask := make(map[int64][]string, len(taskIDs)) for rows.Next() { var scheduleTaskID int64 var taskID int64 var articleID *int64 var title *string var generateStatus string var createdAt interface{} var executionAt interface{} if err := rows.Scan(&scheduleTaskID, &taskID, &articleID, &title, &generateStatus, &createdAt, &executionAt); err != nil { return response.ErrInternal(50010, "scan_failed", err.Error()) } idx, ok := indexByTaskID[scheduleTaskID] if !ok { continue } if items[idx].ExecutionTime == nil { items[idx].ExecutionTime = timeStringPtrFromDBValue(executionAt) } statusesByTask[scheduleTaskID] = append(statusesByTask[scheduleTaskID], generateStatus) if articleID != nil && *articleID > 0 { items[idx].GeneratedArticles = append(items[idx].GeneratedArticles, InstantTaskArticleLink{ ArticleID: *articleID, Title: title, GenerateStatus: generateStatus, CreatedAt: timeStringFromDBValue(createdAt), }) } else { _ = taskID } } if err := rows.Err(); err != nil { return response.ErrInternal(50010, "scan_failed", "failed to iterate schedule generated articles") } for scheduleTaskID, statuses := range statusesByTask { status := aggregateGeneratedArticleStatus(statuses) if status == "" { continue } idx, ok := indexByTaskID[scheduleTaskID] if ok { items[idx].GenerationStatus = &status } } return nil } func aggregateGeneratedArticleStatus(statuses []string) string { if len(statuses) == 0 { return "" } completed := 0 failed := 0 running := 0 queued := 0 for _, status := range statuses { switch status { case "completed": completed++ case "failed": failed++ case "generating", "running": running++ case "queued", "pending": queued++ } } if running > 0 { return "running" } if queued > 0 { return "queued" } if completed > 0 && failed > 0 { return "partial_success" } if failed == len(statuses) { return "failed" } if completed == len(statuses) { return "completed" } return statuses[len(statuses)-1] } func scanScheduleTaskResponse(scanner interface { Scan(dest ...interface{}) error }) (ScheduleTaskResponse, error) { var item ScheduleTaskResponse var createdAt interface{} var updatedAt interface{} var startAt interface{} var endAt interface{} var nextRunAt interface{} var lastRunAt interface{} var publishAccountIDsJSON []byte var publishEnterpriseSiteTargetsJSON []byte var scheduleDaysJSON []byte var generationInputJSON []byte if err := scanner.Scan(&item.ID, &item.WorkspaceID, &item.TargetType, &item.PromptRuleID, &item.SubscriptionPromptID, &item.BrandID, &item.Name, &item.CronExpr, &item.ScheduleKind, &scheduleDaysJSON, &item.ScheduleTimeMode, &item.RandomWindowStart, &item.RandomWindowEnd, &generationInputJSON, &item.AutoPublish, &publishAccountIDsJSON, &publishEnterpriseSiteTargetsJSON, &item.CoverAssetURL, &item.CoverImageAssetID, &item.CoverMode, &item.CoverRandomScope, &item.CoverRandomFolderID, &item.EnableWebSearch, &item.GenerateCount, &startAt, &endAt, &nextRunAt, &item.Status, &lastRunAt, &item.LastDispatchStatus, &item.LastDispatchError, &item.ConsecutiveFailures, &createdAt, &updatedAt, &item.PromptRuleName, &item.SubscriptionPromptName, &item.SubscriptionPackageName, &item.SubscriptionKolName, &item.BrandName); err != nil { if errors.Is(err, pgx.ErrNoRows) { return ScheduleTaskResponse{}, pgx.ErrNoRows } return ScheduleTaskResponse{}, response.ErrInternal(50010, "scan_failed", err.Error()) } if item.TargetType == "" { item.TargetType = ScheduleTargetPromptRule } if item.ScheduleKind == "" { item.ScheduleKind = scheduleKindDaily } if item.ScheduleTimeMode == "" { item.ScheduleTimeMode = sharedschedule.TimeModeFixed } if item.RandomWindowStart == "" { item.RandomWindowStart = defaultRandomWindowStart } if item.RandomWindowEnd == "" { item.RandomWindowEnd = defaultRandomWindowEnd } if item.CoverMode == "" { item.CoverMode = ScheduleCoverModeSpecific } if item.CoverRandomScope == "" { item.CoverRandomScope = ScheduleCoverRandomScopeAll } item.ScheduleDays = decodeScheduleDayKeys(scheduleDaysJSON) item.GenerationInput = decodeScheduleGenerationInput(generationInputJSON) item.PublishAccountIDs = decodeSchedulePublishAccountIDs(publishAccountIDsJSON) item.PublishEnterpriseSiteTargets = DecodeScheduleEnterpriseSiteTargets(publishEnterpriseSiteTargetsJSON) item.CreatedAt = timeStringFromDBValue(createdAt) item.UpdatedAt = timeStringFromDBValue(updatedAt) item.StartAt = timeStringPtrFromDBValue(startAt) item.EndAt = timeStringPtrFromDBValue(endAt) item.NextRunAt = timeStringPtrFromDBValue(nextRunAt) item.LastRunAt = timeStringPtrFromDBValue(lastRunAt) return item, nil } func (s *ScheduleTaskService) ensurePromptRuleExists(ctx context.Context, tenantID, brandID, promptRuleID int64) error { var exists bool _ = s.pool.QueryRow(ctx, ` SELECT EXISTS(SELECT 1 FROM prompt_rules WHERE id = $1 AND tenant_id = $2 AND brand_id = $3 AND deleted_at IS NULL) `, promptRuleID, tenantID, brandID).Scan(&exists) if !exists { return response.ErrBadRequest(40001, "invalid_rule", "prompt rule not found or not active") } return nil } func (s *ScheduleTaskService) validateKolScheduleGenerationInput(ctx context.Context, tenantID, subscriptionPromptID int64, input map[string]interface{}) (map[string]interface{}, error) { input = normalizeKolScheduleGenerationInput(input) row, err := repository.NewKolSubscriptionRepository(s.pool).GetSubscriptionPromptByID(ctx, tenantID, subscriptionPromptID) if err != nil { return input, response.ErrInternal(50109, "kol_subscription_prompt_query_failed", err.Error()) } if row == nil { return input, ErrKolGenerationForbidden } now := time.Now() switch { case row.Status != "active": return input, ErrKolGenerationForbidden case row.SubscriptionStatus != "active": return input, ErrKolGenerationForbidden case row.SubscriptionEndAt != nil && row.SubscriptionEndAt.Before(now): return input, ErrKolGenerationForbidden case row.PackageStatus != "published": return input, ErrKolGenerationForbidden case row.PromptStatus != "active": return input, ErrKolGenerationForbidden } prompt, err := repository.NewKolPromptRepository(s.pool).GetByID(ctx, row.CreatorTenantID, row.PromptID) if err != nil { return input, response.ErrInternal(50110, "kol_prompt_query_failed", err.Error()) } if prompt == nil { return input, response.ErrInternal(50111, "kol_prompt_content_missing", "published prompt content not found") } content, err := loadKolPromptContent(ctx, s.cache, &s.cacheGroup, repository.NewKolPromptRepository(s.pool), s.promptAsset, prompt) if err != nil { return input, response.ErrInternal(50110, "kol_prompt_query_failed", err.Error()) } if strings.TrimSpace(content) == "" { return input, response.ErrInternal(50111, "kol_prompt_content_missing", "published prompt content not found") } schema, err := decodeKolSchema(prompt.SchemaJSON) if err != nil { return input, response.ErrInternal(50096, "kol_generation_schema_decode_failed", err.Error()) } cardConfig, err := decodeKolCardConfig(prompt.CardConfigJSON) if err != nil { return input, response.ErrInternal(50097, "kol_generation_card_config_decode_failed", err.Error()) } variables, _ := input["variables"].(map[string]interface{}) if variables == nil { variables = map[string]interface{}{} input["variables"] = variables } missing := make([]string, 0) for _, variable := range schema.Variables { _, hasValue, err := resolveKolVariableValue(variables, variable, variable.Key) if err != nil { return input, response.ErrBadRequest(40071, "kol_generation_variables_invalid", err.Error()) } if variable.Required && !hasValue { missing = append(missing, variable.Label) } } if len(missing) > 0 { return input, response.ErrBadRequest(40071, "kol_generation_variables_invalid", "missing variables: "+strings.Join(missing, ", ")) } if extractBool(input, "enable_web_search") && !kolCardConfigAllowsWebSearch(cardConfig) { return input, response.ErrBadRequest(40073, "kol_generation_web_search_disabled", "web search is disabled for this prompt") } knowledgeGroupIDs := extractKnowledgeGroupIDs(input["knowledge_group_ids"]) if len(knowledgeGroupIDs) > 0 && !kolCardConfigAllowsUserKnowledge(cardConfig) { return input, response.ErrBadRequest(40074, "kol_generation_knowledge_disabled", "knowledge selection is disabled for this prompt") } if len(knowledgeGroupIDs) > 0 { input["knowledge_group_ids"] = knowledgeGroupIDs } else { delete(input, "knowledge_group_ids") } return input, nil } type scheduleAutoPublishConfig struct { AutoPublish bool AccountIDs []string EnterpriseTargets []ScheduleEnterpriseSiteTarget PlatformIDs []string AccountIDsJSON []byte EnterpriseTargetsJSON []byte CoverAssetURL *string CoverImageAssetID *int64 CoverMode string CoverRandomScope string CoverRandomFolderID *int64 } func (s *ScheduleTaskService) normalizeAutoPublishConfig(ctx context.Context, actor auth.Actor, req ScheduleTaskRequest) (scheduleAutoPublishConfig, error) { autoPublish := boolValue(req.AutoPublish) accountIDs := normalizeSchedulePublishAccountIDs(req.PublishAccountIDs) enterpriseTargets := NormalizeScheduleEnterpriseSiteTargets(req.PublishEnterpriseSiteTargets) config := scheduleAutoPublishConfig{ AutoPublish: autoPublish, AccountIDs: accountIDs, EnterpriseTargets: enterpriseTargets, CoverMode: ScheduleCoverModeSpecific, CoverRandomScope: ScheduleCoverRandomScopeAll, } if !autoPublish { config.AccountIDs = []string{} config.EnterpriseTargets = []ScheduleEnterpriseSiteTarget{} config.AccountIDsJSON = []byte("[]") config.EnterpriseTargetsJSON = []byte("[]") return config, nil } if actor.PrimaryWorkspaceID <= 0 { return config, response.ErrBadRequest(40023, "workspace_required", "自动发布需要工作区上下文") } if len(accountIDs) == 0 && len(enterpriseTargets) == 0 { return config, response.ErrBadRequest(40024, "publish_targets_required", "开启自动发布后,请至少选择一个发布目标") } if err := validateOptionalPositiveInt64(req.CoverImageAssetID, "cover_image_asset_id"); err != nil { return config, err } coverMode, err := normalizeScheduleCoverMode(req.CoverMode) if err != nil { return config, err } randomScope := ScheduleCoverRandomScopeAll var randomFolderID *int64 if coverMode == ScheduleCoverModeRandom { randomScope, randomFolderID, err = s.normalizeScheduleCoverRandomSource(ctx, actor.TenantID, req.CoverRandomScope, req.CoverRandomFolderID) if err != nil { return config, err } } coverURL := strings.TrimSpace(stringPointerValue(req.CoverAssetURL)) if len(accountIDs) > 0 { platformIDs, err := s.loadPublishAccountPlatformIDs(ctx, actor.TenantID, actor.PrimaryWorkspaceID, accountIDs) if err != nil { return config, err } config.PlatformIDs = normalizePlatformIDs(platformIDs) if schedulePublishPlatformsRequireCover(platformIDs) && coverMode == ScheduleCoverModeSpecific && coverURL == "" { return config, response.ErrBadRequest(40025, "cover_required", "已选媒体账号的平台要求封面图,请先设置封面") } } if len(enterpriseTargets) > 0 { if err := s.validateScheduleEnterpriseSiteTargets(ctx, actor.TenantID, actor.PrimaryWorkspaceID, enterpriseTargets); err != nil { return config, err } } accountIDsJSON, err := json.Marshal(accountIDs) if err != nil { return config, response.ErrBadRequest(40026, "invalid_publish_account_ids", "媒体账号发布目标格式不正确") } enterpriseTargetsJSON, err := encodeScheduleEnterpriseSiteTargets(enterpriseTargets) if err != nil { return config, err } config.AccountIDsJSON = accountIDsJSON config.EnterpriseTargetsJSON = enterpriseTargetsJSON config.CoverMode = coverMode config.CoverRandomScope = randomScope config.CoverRandomFolderID = randomFolderID if coverMode == ScheduleCoverModeSpecific && coverURL != "" { config.CoverAssetURL = &coverURL config.CoverImageAssetID = req.CoverImageAssetID } return config, nil } func normalizeScheduleCoverMode(value string) (string, error) { switch strings.TrimSpace(value) { case "", ScheduleCoverModeSpecific: return ScheduleCoverModeSpecific, nil case ScheduleCoverModeRandom: return ScheduleCoverModeRandom, nil default: return "", response.ErrBadRequest(40076, "invalid_cover_mode", "封面图模式不正确") } } func (s *ScheduleTaskService) normalizeScheduleCoverRandomSource(ctx context.Context, tenantID int64, scope string, folderID *int64) (string, *int64, error) { normalizedScope := strings.TrimSpace(scope) if normalizedScope == "" { normalizedScope = ScheduleCoverRandomScopeAll } switch normalizedScope { case ScheduleCoverRandomScopeAll: return ScheduleCoverRandomScopeAll, nil, nil case ScheduleCoverRandomScopeFolder: if folderID == nil || *folderID <= 0 { return "", nil, response.ErrBadRequest(40077, "cover_random_folder_required", "请选择随机封面图片文件夹") } if err := s.ensureImageFolderExists(ctx, tenantID, *folderID); err != nil { return "", nil, err } return ScheduleCoverRandomScopeFolder, folderID, nil default: return "", nil, response.ErrBadRequest(40078, "invalid_cover_random_scope", "随机封面范围不正确") } } func (s *ScheduleTaskService) ensureImageFolderExists(ctx context.Context, tenantID, folderID int64) error { var exists bool if err := s.pool.QueryRow(ctx, ` SELECT EXISTS ( SELECT 1 FROM image_folders WHERE id = $1 AND tenant_id = $2 AND deleted_at IS NULL ) `, folderID, tenantID).Scan(&exists); err != nil { return response.ErrInternal(50010, "query_failed", "failed to validate image folder") } if !exists { return response.ErrBadRequest(40079, "image_folder_not_found", "随机封面图片文件夹不存在") } return nil } func (s *ScheduleTaskService) validateScheduleEnterpriseSiteTargets(ctx context.Context, tenantID, workspaceID int64, targets []ScheduleEnterpriseSiteTarget) error { for _, target := range targets { var status string if err := s.pool.QueryRow(ctx, ` SELECT status FROM enterprise_site_connections WHERE id = $1 AND tenant_id = $2 AND workspace_id = $3 AND deleted_at IS NULL `, target.SiteID, tenantID, workspaceID).Scan(&status); err != nil { if errors.Is(err, pgx.ErrNoRows) { return response.ErrBadRequest(40050, "invalid_publish_enterprise_site_targets", "企业站点连接不存在或已删除") } return response.ErrInternal(50231, "enterprise_site_lookup_failed", "企业站点连接读取失败") } if status == "disabled" { return response.ErrConflict(40942, "enterprise_site_disabled", "企业站点已禁用") } if strings.TrimSpace(target.CategoryID) == "" { return response.ErrBadRequest(40047, "enterprise_site_category_required", "请选择企业站点栏目") } var categoryExists bool if err := s.pool.QueryRow(ctx, ` SELECT EXISTS ( SELECT 1 FROM enterprise_site_categories WHERE tenant_id = $1 AND workspace_id = $2 AND connection_id = $3 AND remote_id = $4 ) `, tenantID, workspaceID, target.SiteID, target.CategoryID).Scan(&categoryExists); err != nil { return response.ErrInternal(50230, "enterprise_site_category_lookup_failed", "企业站点栏目校验失败") } if !categoryExists { return response.ErrBadRequest(40049, "enterprise_site_category_not_found", "企业站点栏目不存在,请先同步栏目") } } return nil } func (s *ScheduleTaskService) loadPublishAccountPlatformIDs(ctx context.Context, tenantID, workspaceID int64, accountIDs []string) ([]string, error) { rows, err := s.pool.Query(ctx, ` SELECT platform_id FROM platform_accounts WHERE tenant_id = $1 AND workspace_id = $2 AND desktop_id::text = ANY($3::text[]) AND deleted_at IS NULL `, tenantID, workspaceID, accountIDs) if err != nil { return nil, response.ErrInternal(50010, "publish_account_check_failed", "failed to validate publish accounts") } defer rows.Close() platformIDs := make([]string, 0, len(accountIDs)) for rows.Next() { var platformID string if err := rows.Scan(&platformID); err != nil { return nil, response.ErrInternal(50010, "publish_account_check_failed", "failed to parse publish accounts") } platformIDs = append(platformIDs, strings.TrimSpace(platformID)) } if err := rows.Err(); err != nil { return nil, response.ErrInternal(50010, "publish_account_check_failed", "failed to iterate publish accounts") } if len(platformIDs) != len(accountIDs) { return nil, response.ErrBadRequest(40027, "invalid_publish_accounts", "one or more publish accounts do not exist") } return platformIDs, nil } func schedulePublishPlatformsRequireCover(platformIDs []string) bool { for _, platformID := range platformIDs { if publishPlatformRequiresCover(platformID) { return true } } return false } func validateScheduleCronExpr(cronExpr string) error { if _, err := sharedschedule.Parse(cronExpr); err != nil { return response.ErrBadRequest(40015, "invalid_cron_expr", err.Error()) } return nil } func normalizeScheduleGenerateCount(value *int) (int, error) { if value == nil { return 1, nil } if *value < 1 || *value > 20 { return 0, response.ErrBadRequest(40022, "invalid_generate_count", "generate_count must be between 1 and 20") } return *value, nil } func boolValue(value *bool) bool { return value != nil && *value } func normalizeSchedulePublishAccountIDs(values []string) []string { seen := make(map[string]struct{}, len(values)) normalized := make([]string, 0, len(values)) for _, value := range values { raw := strings.TrimSpace(value) if raw == "" { continue } id, err := uuid.Parse(raw) if err != nil { continue } key := id.String() if _, ok := seen[key]; ok { continue } seen[key] = struct{}{} normalized = append(normalized, key) } return normalized } func decodeSchedulePublishAccountIDs(raw []byte) []string { var values []string if len(raw) == 0 { return []string{} } if err := json.Unmarshal(raw, &values); err != nil { return []string{} } return normalizeSchedulePublishAccountIDs(values) } func validateOptionalPositiveInt64(value *int64, field string) error { if value != nil && *value <= 0 { return response.ErrBadRequest(40028, "invalid_"+field, field+" must be a positive integer or null") } return nil } func timePtrFromTimestamp(value pgtype.Timestamptz) *time.Time { if !value.Valid { return nil } result := value.Time.Round(0) return &result } func timeStringPtr(value *time.Time) *string { if value == nil { return nil } text := value.Format(time.RFC3339) return &text } func timeStringFromDBValue(value interface{}) string { if value == nil { return "" } if timestamp, ok := value.(time.Time); ok { return timestamp.Round(0).Format(time.RFC3339) } return fmt.Sprintf("%v", value) } func timeStringPtrFromDBValue(value interface{}) *string { if value == nil { return nil } text := timeStringFromDBValue(value) return &text }