feat(schedule-tasks): support auto-publish via media accounts

Replace the legacy target_platform string on schedule tasks with a
workspace-aware auto-publish payload (auto_publish + publish_account_ids
JSONB + cover_asset_url + cover_image_asset_id) and migrate the schema,
sqlc queries, generated models, domain struct, ScheduleTaskService DTOs,
and dispatch worker to round-trip the new fields. PromptRuleGeneration
gains a WithPublishJobService hook so executeGeneration can enqueue an
auto-publish job once the article is ready, and worker-generate wires
the publish-job service in. On the admin-web side, extract
PublishArticleModal's account-card builders into a shared
publish-account-cards module, rebuild GenerateTaskDrawer's schedule
mode around account selection plus a CoverPickerModal, and surface the
new "auto publish" column on ScheduleTaskTab. Shared types and i18n
strings cover the new fields.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-04-30 01:32:19 +08:00
parent c9267d2fae
commit 6e6e19cccb
22 changed files with 1380 additions and 603 deletions
@@ -2,6 +2,7 @@ package scheduler
import (
"context"
"encoding/json"
"sync"
"time"
@@ -37,19 +38,23 @@ type ScheduleDispatchWorker struct {
}
type dueScheduleTask struct {
ID int64
TenantID int64
OperatorID *int64
PromptRuleID int64
BrandID *int64
Name string
CronExpr string
TargetPlatform *string
EnableWebSearch bool
GenerateCount int
StartAt *time.Time
EndAt *time.Time
ScheduledFor time.Time
ID int64
TenantID int64
WorkspaceID int64
OperatorID *int64
PromptRuleID int64
BrandID *int64
Name string
CronExpr string
AutoPublish bool
PublishAccountIDs []string
CoverAssetURL *string
CoverImageAssetID *int64
EnableWebSearch bool
GenerateCount int
StartAt *time.Time
EndAt *time.Time
ScheduledFor time.Time
}
type scheduleTaskCacheUpdate struct {
@@ -250,7 +255,8 @@ func (w *ScheduleDispatchWorker) claimDueSchedules(ctx context.Context) ([]dueSc
defer tx.Rollback(ctx)
rows, err := tx.Query(ctx, `
SELECT id, tenant_id, operator_id, prompt_rule_id, brand_id, name, cron_expr, target_platform,
SELECT id, tenant_id, workspace_id, operator_id, prompt_rule_id, brand_id, name, cron_expr,
auto_publish, publish_account_ids, cover_asset_url, cover_image_asset_id,
enable_web_search, generate_count, start_at, end_at, next_run_at
FROM schedule_tasks
WHERE deleted_at IS NULL
@@ -273,21 +279,27 @@ func (w *ScheduleDispatchWorker) claimDueSchedules(ctx context.Context) ([]dueSc
}, 0, w.batchSize)
for rows.Next() {
var (
task dueScheduleTask
operatorID pgtype.Int8
startAt pgtype.Timestamptz
endAt pgtype.Timestamptz
nextRunAt pgtype.Timestamptz
task dueScheduleTask
workspaceID pgtype.Int8
operatorID pgtype.Int8
publishAccountIDsJSON []byte
startAt pgtype.Timestamptz
endAt pgtype.Timestamptz
nextRunAt pgtype.Timestamptz
)
if err := rows.Scan(
&task.ID,
&task.TenantID,
&workspaceID,
&operatorID,
&task.PromptRuleID,
&task.BrandID,
&task.Name,
&task.CronExpr,
&task.TargetPlatform,
&task.AutoPublish,
&publishAccountIDsJSON,
&task.CoverAssetURL,
&task.CoverImageAssetID,
&task.EnableWebSearch,
&task.GenerateCount,
&startAt,
@@ -300,7 +312,11 @@ func (w *ScheduleDispatchWorker) claimDueSchedules(ctx context.Context) ([]dueSc
task.StartAt = timePtrFromTimestamp(startAt)
task.EndAt = timePtrFromTimestamp(endAt)
if workspaceID.Valid {
task.WorkspaceID = workspaceID.Int64
}
task.OperatorID = int64PtrFromInt8(operatorID)
task.PublishAccountIDs = decodeDueSchedulePublishAccountIDs(publishAccountIDsJSON)
if task.GenerateCount <= 0 {
task.GenerateCount = 1
}
@@ -372,16 +388,20 @@ func (w *ScheduleDispatchWorker) dispatch(parent context.Context, task dueSchedu
for idx := 0; idx < generateCount; idx++ {
ctx, cancel := context.WithTimeout(parent, w.timeout)
resp, err := w.promptRuleService.EnqueueScheduledGeneration(ctx, tenantapp.SchedulePromptRuleGenerationInput{
ScheduleTaskID: task.ID,
OperatorID: task.OperatorID,
TenantID: task.TenantID,
PromptRuleID: task.PromptRuleID,
BrandID: task.BrandID,
Name: task.Name,
TargetPlatform: task.TargetPlatform,
EnableWebSearch: task.EnableWebSearch,
GenerateCount: generateCount,
ScheduledFor: task.ScheduledFor,
ScheduleTaskID: task.ID,
OperatorID: task.OperatorID,
TenantID: task.TenantID,
PromptRuleID: task.PromptRuleID,
BrandID: task.BrandID,
Name: task.Name,
WorkspaceID: task.WorkspaceID,
AutoPublish: task.AutoPublish,
PublishAccountIDs: task.PublishAccountIDs,
CoverAssetURL: task.CoverAssetURL,
CoverImageAssetID: task.CoverImageAssetID,
EnableWebSearch: task.EnableWebSearch,
GenerateCount: generateCount,
ScheduledFor: task.ScheduledFor,
})
cancel()
if err != nil {
@@ -522,3 +542,26 @@ func int64PtrFromInt8(value pgtype.Int8) *int64 {
result := value.Int64
return &result
}
func decodeDueSchedulePublishAccountIDs(raw []byte) []string {
if len(raw) == 0 {
return []string{}
}
var values []string
if err := json.Unmarshal(raw, &values); err != nil {
return []string{}
}
result := make([]string, 0, len(values))
seen := make(map[string]struct{}, len(values))
for _, value := range values {
if value == "" {
continue
}
if _, ok := seen[value]; ok {
continue
}
seen[value] = struct{}{}
result = append(result, value)
}
return result
}
@@ -9,6 +9,7 @@ import (
"time"
"github.com/jackc/pgx/v5/pgxpool"
"go.uber.org/zap"
"github.com/geo-platform/tenant-api/internal/shared/auth"
sharedcache "github.com/geo-platform/tenant-api/internal/shared/cache"
@@ -31,6 +32,8 @@ type PromptRuleGenerationService struct {
articleTimeout time.Duration
maxOutputTokens int64
cache sharedcache.Cache
publishJobs *PublishJobService
logger *zap.Logger
}
type promptRuleGenerationJob struct {
@@ -46,10 +49,9 @@ type promptRuleGenerationJob struct {
}
type GenerateFromRuleRequest struct {
PromptRuleID int64 `json:"prompt_rule_id" binding:"required"`
BrandID *int64 `json:"brand_id"`
TargetPlatform *string `json:"target_platform"`
ExtraParams map[string]interface{} `json:"extra_params"`
PromptRuleID int64 `json:"prompt_rule_id" binding:"required"`
BrandID *int64 `json:"brand_id"`
ExtraParams map[string]interface{} `json:"extra_params"`
}
type GenerateFromRuleResponse struct {
@@ -69,16 +71,20 @@ type GenerateFromRuleItem struct {
}
type SchedulePromptRuleGenerationInput struct {
ScheduleTaskID int64
OperatorID *int64
TenantID int64
PromptRuleID int64
BrandID *int64
Name string
TargetPlatform *string
EnableWebSearch bool
GenerateCount int
ScheduledFor time.Time
ScheduleTaskID int64
OperatorID *int64
TenantID int64
PromptRuleID int64
BrandID *int64
Name string
WorkspaceID int64
AutoPublish bool
PublishAccountIDs []string
CoverAssetURL *string
CoverImageAssetID *int64
EnableWebSearch bool
GenerateCount int
ScheduledFor time.Time
}
type promptRuleGenerationRecord struct {
@@ -96,13 +102,12 @@ type promptRuleGenerationRecord struct {
const promptRuleGeneratingTitlePlaceholder = "标题生成中"
type enqueuePromptRuleGenerationInput struct {
OperatorID *int64
TenantID int64
PromptRuleID int64
BrandID *int64
TargetPlatform *string
ExtraParams map[string]interface{}
FallbackName string
OperatorID *int64
TenantID int64
PromptRuleID int64
BrandID *int64
ExtraParams map[string]interface{}
FallbackName string
}
func NewPromptRuleGenerationService(
@@ -138,6 +143,16 @@ func (s *PromptRuleGenerationService) WithCache(c sharedcache.Cache) *PromptRule
return s
}
func (s *PromptRuleGenerationService) WithPublishJobService(publishJobs *PublishJobService) *PromptRuleGenerationService {
s.publishJobs = publishJobs
return s
}
func (s *PromptRuleGenerationService) WithLogger(logger *zap.Logger) *PromptRuleGenerationService {
s.logger = logger
return s
}
func (s *PromptRuleGenerationService) GenerateFromRule(ctx context.Context, req GenerateFromRuleRequest) (*GenerateFromRuleResponse, error) {
actor := auth.MustActor(ctx)
extra := clonePromptRuleExtraParams(req.ExtraParams)
@@ -159,13 +174,12 @@ func (s *PromptRuleGenerationService) GenerateFromRule(ctx context.Context, req
var lastErr error
for idx := 0; idx < generateCount; idx++ {
result, enqueueErr := s.enqueuePromptRuleGeneration(ctx, enqueuePromptRuleGenerationInput{
OperatorID: &actor.UserID,
TenantID: actor.TenantID,
PromptRuleID: req.PromptRuleID,
BrandID: req.BrandID,
TargetPlatform: req.TargetPlatform,
ExtraParams: clonePromptRuleExtraParams(extra),
FallbackName: "即时任务",
OperatorID: &actor.UserID,
TenantID: actor.TenantID,
PromptRuleID: req.PromptRuleID,
BrandID: req.BrandID,
ExtraParams: clonePromptRuleExtraParams(extra),
FallbackName: "即时任务",
})
if enqueueErr != nil {
lastErr = enqueueErr
@@ -193,6 +207,19 @@ func (s *PromptRuleGenerationService) EnqueueScheduledGeneration(ctx context.Con
"schedule_task_id": input.ScheduleTaskID,
"enable_web_search": input.EnableWebSearch,
}
if input.WorkspaceID > 0 {
extra["workspace_id"] = input.WorkspaceID
}
if input.AutoPublish {
extra["schedule_auto_publish"] = true
extra["schedule_publish_account_ids"] = input.PublishAccountIDs
if input.CoverAssetURL != nil {
extra["schedule_cover_asset_url"] = strings.TrimSpace(*input.CoverAssetURL)
}
if input.CoverImageAssetID != nil {
extra["schedule_cover_image_asset_id"] = *input.CoverImageAssetID
}
}
if input.GenerateCount > 0 {
extra["generate_count"] = input.GenerateCount
}
@@ -204,13 +231,12 @@ func (s *PromptRuleGenerationService) EnqueueScheduledGeneration(ctx context.Con
}
return s.enqueuePromptRuleGeneration(ctx, enqueuePromptRuleGenerationInput{
OperatorID: input.OperatorID,
TenantID: input.TenantID,
PromptRuleID: input.PromptRuleID,
BrandID: input.BrandID,
TargetPlatform: input.TargetPlatform,
ExtraParams: extra,
FallbackName: "定时任务",
OperatorID: input.OperatorID,
TenantID: input.TenantID,
PromptRuleID: input.PromptRuleID,
BrandID: input.BrandID,
ExtraParams: extra,
FallbackName: "定时任务",
})
}
@@ -254,10 +280,12 @@ func (s *PromptRuleGenerationService) enqueuePromptRuleGeneration(ctx context.Co
inputParams := map[string]interface{}{
"prompt_rule_id": input.PromptRuleID,
"task_name": taskName,
"target_platform": strings.TrimSpace(derefString(input.TargetPlatform)),
"enable_web_search": extractBool(extra, "enable_web_search"),
"generate_count": generateCount,
}
if workspaceID := extractInt(extra, "workspace_id"); workspaceID > 0 {
inputParams["workspace_id"] = workspaceID
}
if generationMode != "" {
inputParams["generation_mode"] = generationMode
}
@@ -267,10 +295,15 @@ func (s *PromptRuleGenerationService) enqueuePromptRuleGeneration(ctx context.Co
if scheduledFor := strings.TrimSpace(extractString(extra, "scheduled_for")); scheduledFor != "" {
inputParams["scheduled_for"] = scheduledFor
}
platformIDs := parsePlatformIDs(derefString(input.TargetPlatform))
if len(platformIDs) > 0 {
inputParams["target_platforms"] = platformIDs
if extractBool(extra, "schedule_auto_publish") {
inputParams["schedule_auto_publish"] = true
inputParams["schedule_publish_account_ids"] = extractStringList(extra["schedule_publish_account_ids"], 64)
if coverURL := strings.TrimSpace(extractString(extra, "schedule_cover_asset_url")); coverURL != "" {
inputParams["schedule_cover_asset_url"] = coverURL
}
if coverImageAssetID := extractInt(extra, "schedule_cover_image_asset_id"); coverImageAssetID > 0 {
inputParams["schedule_cover_image_asset_id"] = coverImageAssetID
}
}
if input.BrandID != nil {
inputParams["brand_id"] = *input.BrandID
@@ -301,7 +334,16 @@ func (s *PromptRuleGenerationService) enqueuePromptRuleGeneration(ctx context.Co
}
inputJSON, _ := json.Marshal(inputParams)
wizardStateJSON, _ := mergeArticleWizardState(nil, promptRuleGeneratingTitlePlaceholder, platformIDs, nil, NullableInt64Input{})
var coverAssetURL *string
var coverImageAssetID NullableInt64Input
if coverURL := strings.TrimSpace(extractString(inputParams, "schedule_cover_asset_url")); coverURL != "" {
coverAssetURL = &coverURL
}
if rawCoverImageAssetID := int64(extractInt(inputParams, "schedule_cover_image_asset_id")); rawCoverImageAssetID > 0 {
coverImageAssetID.Set = true
coverImageAssetID.Value = &rawCoverImageAssetID
}
wizardStateJSON, _ := mergeArticleWizardState(nil, promptRuleGeneratingTitlePlaceholder, nil, coverAssetURL, coverImageAssetID)
tx, err := s.pool.Begin(ctx)
if err != nil {
@@ -557,6 +599,74 @@ func (s *PromptRuleGenerationService) executeGeneration(ctx context.Context, job
if s.streamEnabled {
s.streams.Complete(job.ArticleID, job.TaskID, title, content)
}
s.enqueueScheduleAutoPublish(cleanupCtx, job, title)
}
func (s *PromptRuleGenerationService) enqueueScheduleAutoPublish(ctx context.Context, job promptRuleGenerationJob, title string) {
if s == nil || s.publishJobs == nil || !extractBool(job.InputParams, "schedule_auto_publish") {
return
}
workspaceID := int64(extractInt(job.InputParams, "workspace_id"))
accountIDs := extractStringList(job.InputParams["schedule_publish_account_ids"], 64)
coverURL := strings.TrimSpace(extractString(job.InputParams, "schedule_cover_asset_url"))
if workspaceID <= 0 || job.OperatorID <= 0 || len(accountIDs) == 0 {
s.logAutoPublishWarn("schedule auto publish skipped because configuration is incomplete", nil,
zap.Int64("generation_task_id", job.TaskID),
zap.Int64("article_id", job.ArticleID),
zap.Int64("workspace_id", workspaceID),
zap.Int("account_count", len(accountIDs)),
zap.Bool("has_cover", coverURL != ""),
)
return
}
accounts := make([]CreatePublishJobAccountRequest, 0, len(accountIDs))
for _, accountID := range accountIDs {
accountID = strings.TrimSpace(accountID)
if accountID == "" {
continue
}
accounts = append(accounts, CreatePublishJobAccountRequest{AccountID: accountID})
}
if len(accounts) == 0 {
return
}
publishTitle := strings.TrimSpace(title)
if publishTitle == "" {
publishTitle = "定时生成文章"
}
if _, err := s.publishJobs.Create(ctx, auth.Actor{
TenantID: job.TenantID,
UserID: job.OperatorID,
PrimaryWorkspaceID: workspaceID,
}, CreatePublishJobRequest{
Title: publishTitle,
ContentRef: map[string]any{
"article_id": job.ArticleID,
},
Accounts: accounts,
}); err != nil {
s.logAutoPublishWarn("schedule auto publish enqueue failed", err,
zap.Int64("generation_task_id", job.TaskID),
zap.Int64("article_id", job.ArticleID),
zap.Int64("workspace_id", workspaceID),
zap.Int("account_count", len(accounts)),
)
}
}
func (s *PromptRuleGenerationService) logAutoPublishWarn(message string, err error, fields ...zap.Field) {
if s == nil || s.logger == nil {
return
}
if err != nil {
fields = append(fields, zap.Error(err))
}
s.logger.Warn(message, fields...)
}
func (s *PromptRuleGenerationService) failGeneration(ctx context.Context, job promptRuleGenerationJob, title, stage string, genErr error) {
@@ -632,9 +742,6 @@ func buildPromptRuleGenerationPrompt(rule *promptRuleGenerationRecord, params ma
if rule.DefaultWordCount != nil && *rule.DefaultWordCount > 0 {
supplements = append(supplements, prompts.PromptRuleWordCountSupplement(*rule.DefaultWordCount))
}
if target := strings.TrimSpace(extractString(params, "target_platform")); target != "" {
supplements = append(supplements, prompts.PromptRuleTargetPlatformSupplement(target))
}
if len(supplements) > 0 {
sections = append(sections, prompts.PromptRuleSupplementSection(supplements))
@@ -678,9 +785,6 @@ func buildPromptRuleKnowledgeQuery(rule *promptRuleGenerationRecord, params map[
if keywords := extractStringList(params["keywords"], 16); len(keywords) > 0 {
parts = append(parts, strings.Join(keywords, "\n"))
}
if target := strings.TrimSpace(extractString(params, "target_platform")); target != "" {
parts = append(parts, target)
}
if rule != nil {
if text := strings.TrimSpace(rule.PromptContent); text != "" {
parts = append(parts, text)
@@ -5,8 +5,10 @@ import (
"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"
@@ -37,34 +39,41 @@ func (s *ScheduleTaskService) WithCache(c sharedcache.Cache) *ScheduleTaskServic
}
type ScheduleTaskRequest struct {
PromptRuleID int64 `json:"prompt_rule_id" binding:"required"`
BrandID *int64 `json:"brand_id"`
Name string `json:"name" binding:"required"`
CronExpr string `json:"cron_expr" binding:"required"`
TargetPlatform *string `json:"target_platform"`
EnableWebSearch *bool `json:"enable_web_search"`
GenerateCount *int `json:"generate_count"`
StartAt *string `json:"start_at"`
EndAt *string `json:"end_at"`
PromptRuleID int64 `json:"prompt_rule_id" binding:"required"`
BrandID *int64 `json:"brand_id"`
Name string `json:"name" binding:"required"`
CronExpr string `json:"cron_expr" binding:"required"`
AutoPublish *bool `json:"auto_publish"`
PublishAccountIDs []string `json:"publish_account_ids"`
CoverAssetURL *string `json:"cover_asset_url"`
CoverImageAssetID *int64 `json:"cover_image_asset_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"`
PromptRuleID int64 `json:"prompt_rule_id"`
PromptRuleName *string `json:"prompt_rule_name"`
BrandID *int64 `json:"brand_id"`
BrandName *string `json:"brand_name"`
Name string `json:"name"`
CronExpr string `json:"cron_expr"`
TargetPlatform *string `json:"target_platform"`
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"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
ID int64 `json:"id"`
WorkspaceID *int64 `json:"workspace_id"`
PromptRuleID int64 `json:"prompt_rule_id"`
PromptRuleName *string `json:"prompt_rule_name"`
BrandID *int64 `json:"brand_id"`
BrandName *string `json:"brand_name"`
Name string `json:"name"`
CronExpr string `json:"cron_expr"`
AutoPublish bool `json:"auto_publish"`
PublishAccountIDs []string `json:"publish_account_ids"`
CoverAssetURL *string `json:"cover_asset_url"`
CoverImageAssetID *int64 `json:"cover_image_asset_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"`
CreatedAt string `json:"created_at"`
UpdatedAt string `json:"updated_at"`
}
type ScheduleTaskListParams struct {
@@ -121,6 +130,10 @@ func (s *ScheduleTaskService) Create(ctx context.Context, req ScheduleTaskReques
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 {
@@ -135,12 +148,13 @@ func (s *ScheduleTaskService) Create(ctx context.Context, req ScheduleTaskReques
var status string
err = tx.QueryRow(ctx, `
INSERT INTO schedule_tasks (
tenant_id, operator_id, prompt_rule_id, brand_id, name, cron_expr, target_platform,
enable_web_search, generate_count, start_at, end_at
tenant_id, workspace_id, operator_id, prompt_rule_id, brand_id, name, cron_expr,
enable_web_search, generate_count, auto_publish, publish_account_ids, cover_asset_url,
cover_image_asset_id, start_at, end_at
)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10::timestamptz, $11::timestamptz)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11::jsonb, $12, $13, $14::timestamptz, $15::timestamptz)
RETURNING id, created_at, start_at, end_at, status
`, actor.TenantID, actor.UserID, req.PromptRuleID, req.BrandID, req.Name, req.CronExpr, req.TargetPlatform, enableWebSearch, generateCount, req.StartAt, req.EndAt).
`, actor.TenantID, actor.PrimaryWorkspaceID, actor.UserID, req.PromptRuleID, req.BrandID, req.Name, req.CronExpr, enableWebSearch, generateCount, publishConfig.AutoPublish, publishConfig.AccountIDsJSON, publishConfig.CoverAssetURL, publishConfig.CoverImageAssetID, 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")
@@ -170,6 +184,7 @@ func (s *ScheduleTaskService) Create(ctx context.Context, req ScheduleTaskReques
"cron_expr": req.CronExpr,
"enable_web_search": enableWebSearch,
"generate_count": generateCount,
"auto_publish": publishConfig.AutoPublish,
})
result := "success"
resourceType := "schedule_task"
@@ -187,11 +202,14 @@ func (s *ScheduleTaskService) Create(ctx context.Context, req ScheduleTaskReques
})
invalidateScheduleTaskCaches(ctx, s.cache, actor.TenantID, &id)
workspaceID := actor.PrimaryWorkspaceID
return &ScheduleTaskResponse{
ID: id, PromptRuleID: req.PromptRuleID, BrandID: req.BrandID,
Name: req.Name, CronExpr: req.CronExpr, TargetPlatform: req.TargetPlatform,
EnableWebSearch: enableWebSearch, GenerateCount: generateCount,
Status: status, CreatedAt: fmt.Sprintf("%v", createdAt),
ID: id, WorkspaceID: &workspaceID, PromptRuleID: req.PromptRuleID, BrandID: req.BrandID,
Name: req.Name, CronExpr: req.CronExpr, AutoPublish: publishConfig.AutoPublish,
PublishAccountIDs: publishConfig.AccountIDs, CoverAssetURL: publishConfig.CoverAssetURL,
CoverImageAssetID: publishConfig.CoverImageAssetID, EnableWebSearch: enableWebSearch,
GenerateCount: generateCount,
Status: status, CreatedAt: fmt.Sprintf("%v", createdAt),
NextRunAt: timeStringPtr(nextRunAt),
}, nil
}
@@ -209,6 +227,10 @@ func (s *ScheduleTaskService) Update(ctx context.Context, id int64, req Schedule
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 {
@@ -221,11 +243,13 @@ func (s *ScheduleTaskService) Update(ctx context.Context, id int64, req Schedule
var endAt pgtype.Timestamptz
err = tx.QueryRow(ctx, `
UPDATE schedule_tasks SET prompt_rule_id = $1, brand_id = $2, name = $3,
cron_expr = $4, target_platform = $5, enable_web_search = $6, generate_count = $7,
start_at = $8::timestamptz, end_at = $9::timestamptz, operator_id = $10, updated_at = NOW()
WHERE id = $11 AND tenant_id = $12 AND deleted_at IS NULL
cron_expr = $4, enable_web_search = $5, generate_count = $6,
workspace_id = $7, auto_publish = $8, publish_account_ids = $9::jsonb,
cover_asset_url = $10, cover_image_asset_id = $11,
start_at = $12::timestamptz, end_at = $13::timestamptz, operator_id = $14, updated_at = NOW()
WHERE id = $15 AND tenant_id = $16 AND deleted_at IS NULL
RETURNING status, start_at, end_at
`, req.PromptRuleID, req.BrandID, req.Name, req.CronExpr, req.TargetPlatform, enableWebSearch, generateCount, req.StartAt, req.EndAt, actor.UserID, id, actor.TenantID).
`, req.PromptRuleID, req.BrandID, req.Name, req.CronExpr, enableWebSearch, generateCount, actor.PrimaryWorkspaceID, publishConfig.AutoPublish, publishConfig.AccountIDsJSON, publishConfig.CoverAssetURL, publishConfig.CoverImageAssetID, req.StartAt, req.EndAt, actor.UserID, id, actor.TenantID).
Scan(&status, &startAt, &endAt)
if err != nil {
return response.ErrNotFound(40432, "schedule_not_found", "schedule task not found")
@@ -347,8 +371,9 @@ func (s *ScheduleTaskService) loadScheduleTasks(ctx context.Context, tenantID in
}
rows, err := s.pool.Query(ctx, `
SELECT st.id, st.prompt_rule_id, st.brand_id, st.name,
st.cron_expr, st.target_platform, st.enable_web_search, st.generate_count, st.start_at, st.end_at,
SELECT st.id, st.workspace_id, st.prompt_rule_id, st.brand_id, st.name,
st.cron_expr, st.auto_publish, st.publish_account_ids, st.cover_asset_url,
st.cover_image_asset_id, st.enable_web_search, st.generate_count, st.start_at, st.end_at,
st.next_run_at, st.status, st.created_at, st.updated_at,
pr.name AS prompt_rule_name,
b.name AS brand_name
@@ -382,8 +407,9 @@ func (s *ScheduleTaskService) loadScheduleTasks(ctx context.Context, tenantID in
func (s *ScheduleTaskService) loadScheduleTaskDetail(ctx context.Context, tenantID, taskID int64) (*ScheduleTaskResponse, bool, error) {
row := s.pool.QueryRow(ctx, `
SELECT st.id, st.prompt_rule_id, st.brand_id, st.name,
st.cron_expr, st.target_platform, st.enable_web_search, st.generate_count, st.start_at, st.end_at,
SELECT st.id, st.workspace_id, st.prompt_rule_id, st.brand_id, st.name,
st.cron_expr, st.auto_publish, st.publish_account_ids, st.cover_asset_url,
st.cover_image_asset_id, st.enable_web_search, st.generate_count, st.start_at, st.end_at,
st.next_run_at, st.status, st.created_at, st.updated_at,
pr.name AS prompt_rule_name,
b.name AS brand_name
@@ -411,8 +437,10 @@ func scanScheduleTaskResponse(scanner interface {
var startAt interface{}
var endAt interface{}
var nextRunAt interface{}
if err := scanner.Scan(&item.ID, &item.PromptRuleID, &item.BrandID, &item.Name,
&item.CronExpr, &item.TargetPlatform, &item.EnableWebSearch, &item.GenerateCount, &startAt, &endAt,
var publishAccountIDsJSON []byte
if err := scanner.Scan(&item.ID, &item.WorkspaceID, &item.PromptRuleID, &item.BrandID, &item.Name,
&item.CronExpr, &item.AutoPublish, &publishAccountIDsJSON,
&item.CoverAssetURL, &item.CoverImageAssetID, &item.EnableWebSearch, &item.GenerateCount, &startAt, &endAt,
&nextRunAt, &item.Status, &createdAt, &updatedAt,
&item.PromptRuleName, &item.BrandName); err != nil {
if errors.Is(err, pgx.ErrNoRows) {
@@ -420,6 +448,7 @@ func scanScheduleTaskResponse(scanner interface {
}
return ScheduleTaskResponse{}, response.ErrInternal(50010, "scan_failed", err.Error())
}
item.PublishAccountIDs = decodeSchedulePublishAccountIDs(publishAccountIDsJSON)
item.CreatedAt = fmt.Sprintf("%v", createdAt)
item.UpdatedAt = fmt.Sprintf("%v", updatedAt)
if startAt != nil {
@@ -448,6 +477,101 @@ func (s *ScheduleTaskService) ensurePromptRuleExists(ctx context.Context, tenant
return nil
}
type scheduleAutoPublishConfig struct {
AutoPublish bool
AccountIDs []string
AccountIDsJSON []byte
CoverAssetURL *string
CoverImageAssetID *int64
}
func (s *ScheduleTaskService) normalizeAutoPublishConfig(ctx context.Context, actor auth.Actor, req ScheduleTaskRequest) (scheduleAutoPublishConfig, error) {
autoPublish := boolValue(req.AutoPublish)
accountIDs := normalizeSchedulePublishAccountIDs(req.PublishAccountIDs)
config := scheduleAutoPublishConfig{
AutoPublish: autoPublish,
AccountIDs: accountIDs,
}
if !autoPublish {
config.AccountIDs = []string{}
config.AccountIDsJSON = []byte("[]")
return config, nil
}
if actor.PrimaryWorkspaceID <= 0 {
return config, response.ErrBadRequest(40023, "workspace_required", "workspace context is required for automatic publishing")
}
if len(accountIDs) == 0 {
return config, response.ErrBadRequest(40024, "publish_accounts_required", "publish_account_ids is required when auto_publish is enabled")
}
if err := validateOptionalPositiveInt64(req.CoverImageAssetID, "cover_image_asset_id"); err != nil {
return config, err
}
coverURL := strings.TrimSpace(stringPointerValue(req.CoverAssetURL))
platformIDs, err := s.loadPublishAccountPlatformIDs(ctx, actor.TenantID, actor.PrimaryWorkspaceID, accountIDs)
if err != nil {
return config, err
}
if schedulePublishPlatformsRequireCover(platformIDs) && coverURL == "" {
return config, response.ErrBadRequest(40025, "cover_required", "selected publish accounts require cover_asset_url")
}
accountIDsJSON, err := json.Marshal(accountIDs)
if err != nil {
return config, response.ErrBadRequest(40026, "invalid_publish_account_ids", "publish_account_ids must be serializable")
}
config.AccountIDsJSON = accountIDsJSON
if coverURL != "" {
config.CoverAssetURL = &coverURL
config.CoverImageAssetID = req.CoverImageAssetID
}
return config, 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 {
switch strings.TrimSpace(platformID) {
case "baijiahao", "dongchedi":
return true
}
}
return false
}
func resolveScheduleNextRunForStatus(status, cronExpr string, startAt, endAt *time.Time, now time.Time) (*time.Time, error) {
if status != "enabled" {
return nil, nil
@@ -476,6 +600,46 @@ 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
+20 -16
View File
@@ -3,20 +3,24 @@ package domain
import "time"
type ScheduleTask struct {
ID int64
TenantID int64
OperatorID *int64
PromptRuleID int64
BrandID *int64
Name string
CronExpr string
TargetPlatform *string
EnableWebSearch bool
GenerateCount int
StartAt *time.Time
EndAt *time.Time
NextRunAt *time.Time
Status string
CreatedAt time.Time
UpdatedAt time.Time
ID int64
TenantID int64
WorkspaceID *int64
OperatorID *int64
PromptRuleID int64
BrandID *int64
Name string
CronExpr string
AutoPublish bool
PublishAccountIDs []string
CoverAssetURL *string
CoverImageAssetID *int64
EnableWebSearch bool
GenerateCount int
StartAt *time.Time
EndAt *time.Time
NextRunAt *time.Time
Status string
CreatedAt time.Time
UpdatedAt time.Time
}
@@ -620,23 +620,27 @@ type QuotaReservation struct {
}
type ScheduleTask struct {
ID int64 `json:"id"`
TenantID int64 `json:"tenant_id"`
PromptRuleID int64 `json:"prompt_rule_id"`
BrandID pgtype.Int8 `json:"brand_id"`
Name string `json:"name"`
CronExpr string `json:"cron_expr"`
TargetPlatform pgtype.Text `json:"target_platform"`
StartAt pgtype.Timestamptz `json:"start_at"`
EndAt pgtype.Timestamptz `json:"end_at"`
NextRunAt pgtype.Timestamptz `json:"next_run_at"`
Status string `json:"status"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
DeletedAt pgtype.Timestamptz `json:"deleted_at"`
OperatorID pgtype.Int8 `json:"operator_id"`
EnableWebSearch bool `json:"enable_web_search"`
GenerateCount int32 `json:"generate_count"`
ID int64 `json:"id"`
TenantID int64 `json:"tenant_id"`
PromptRuleID int64 `json:"prompt_rule_id"`
BrandID pgtype.Int8 `json:"brand_id"`
Name string `json:"name"`
CronExpr string `json:"cron_expr"`
StartAt pgtype.Timestamptz `json:"start_at"`
EndAt pgtype.Timestamptz `json:"end_at"`
NextRunAt pgtype.Timestamptz `json:"next_run_at"`
Status string `json:"status"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
DeletedAt pgtype.Timestamptz `json:"deleted_at"`
OperatorID pgtype.Int8 `json:"operator_id"`
EnableWebSearch bool `json:"enable_web_search"`
GenerateCount int32 `json:"generate_count"`
WorkspaceID pgtype.Int8 `json:"workspace_id"`
AutoPublish bool `json:"auto_publish"`
PublishAccountIds []byte `json:"publish_account_ids"`
CoverAssetUrl pgtype.Text `json:"cover_asset_url"`
CoverImageAssetID pgtype.Int8 `json:"cover_image_asset_id"`
}
type TaskRecord struct {
@@ -34,24 +34,30 @@ func (q *Queries) CountScheduleTasks(ctx context.Context, arg CountScheduleTasks
}
const createScheduleTask = `-- name: CreateScheduleTask :one
INSERT INTO schedule_tasks (tenant_id, prompt_rule_id, brand_id, name, cron_expr,
target_platform, start_at, end_at, next_run_at)
VALUES ($1, $2, $3, $4,
$5, $6, $7, $8,
$9)
INSERT INTO schedule_tasks (tenant_id, workspace_id, prompt_rule_id, brand_id, name, cron_expr,
auto_publish, publish_account_ids, cover_asset_url, cover_image_asset_id,
start_at, end_at, next_run_at)
VALUES ($1, $2, $3, $4, $5,
$6, $7, $8, $9,
$10, $11, $12,
$13)
RETURNING id, created_at
`
type CreateScheduleTaskParams struct {
TenantID int64 `json:"tenant_id"`
PromptRuleID int64 `json:"prompt_rule_id"`
BrandID pgtype.Int8 `json:"brand_id"`
Name string `json:"name"`
CronExpr string `json:"cron_expr"`
TargetPlatform pgtype.Text `json:"target_platform"`
StartAt pgtype.Timestamptz `json:"start_at"`
EndAt pgtype.Timestamptz `json:"end_at"`
NextRunAt pgtype.Timestamptz `json:"next_run_at"`
TenantID int64 `json:"tenant_id"`
WorkspaceID pgtype.Int8 `json:"workspace_id"`
PromptRuleID int64 `json:"prompt_rule_id"`
BrandID pgtype.Int8 `json:"brand_id"`
Name string `json:"name"`
CronExpr string `json:"cron_expr"`
AutoPublish bool `json:"auto_publish"`
PublishAccountIds []byte `json:"publish_account_ids"`
CoverAssetUrl pgtype.Text `json:"cover_asset_url"`
CoverImageAssetID pgtype.Int8 `json:"cover_image_asset_id"`
StartAt pgtype.Timestamptz `json:"start_at"`
EndAt pgtype.Timestamptz `json:"end_at"`
NextRunAt pgtype.Timestamptz `json:"next_run_at"`
}
type CreateScheduleTaskRow struct {
@@ -62,11 +68,15 @@ type CreateScheduleTaskRow struct {
func (q *Queries) CreateScheduleTask(ctx context.Context, arg CreateScheduleTaskParams) (CreateScheduleTaskRow, error) {
row := q.db.QueryRow(ctx, createScheduleTask,
arg.TenantID,
arg.WorkspaceID,
arg.PromptRuleID,
arg.BrandID,
arg.Name,
arg.CronExpr,
arg.TargetPlatform,
arg.AutoPublish,
arg.PublishAccountIds,
arg.CoverAssetUrl,
arg.CoverImageAssetID,
arg.StartAt,
arg.EndAt,
arg.NextRunAt,
@@ -77,8 +87,9 @@ func (q *Queries) CreateScheduleTask(ctx context.Context, arg CreateScheduleTask
}
const getScheduleTaskByID = `-- name: GetScheduleTaskByID :one
SELECT st.id, st.tenant_id, st.prompt_rule_id, st.brand_id, st.name,
st.cron_expr, st.target_platform, st.start_at, st.end_at,
SELECT st.id, st.tenant_id, st.workspace_id, st.prompt_rule_id, st.brand_id, st.name,
st.cron_expr, st.auto_publish, st.publish_account_ids, st.cover_asset_url, st.cover_image_asset_id,
st.start_at, st.end_at,
st.next_run_at, st.status, st.created_at, st.updated_at,
pr.name AS prompt_rule_name,
b.name AS brand_name
@@ -94,21 +105,25 @@ type GetScheduleTaskByIDParams struct {
}
type GetScheduleTaskByIDRow struct {
ID int64 `json:"id"`
TenantID int64 `json:"tenant_id"`
PromptRuleID int64 `json:"prompt_rule_id"`
BrandID pgtype.Int8 `json:"brand_id"`
Name string `json:"name"`
CronExpr string `json:"cron_expr"`
TargetPlatform pgtype.Text `json:"target_platform"`
StartAt pgtype.Timestamptz `json:"start_at"`
EndAt pgtype.Timestamptz `json:"end_at"`
NextRunAt pgtype.Timestamptz `json:"next_run_at"`
Status string `json:"status"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
PromptRuleName pgtype.Text `json:"prompt_rule_name"`
BrandName pgtype.Text `json:"brand_name"`
ID int64 `json:"id"`
TenantID int64 `json:"tenant_id"`
WorkspaceID pgtype.Int8 `json:"workspace_id"`
PromptRuleID int64 `json:"prompt_rule_id"`
BrandID pgtype.Int8 `json:"brand_id"`
Name string `json:"name"`
CronExpr string `json:"cron_expr"`
AutoPublish bool `json:"auto_publish"`
PublishAccountIds []byte `json:"publish_account_ids"`
CoverAssetUrl pgtype.Text `json:"cover_asset_url"`
CoverImageAssetID pgtype.Int8 `json:"cover_image_asset_id"`
StartAt pgtype.Timestamptz `json:"start_at"`
EndAt pgtype.Timestamptz `json:"end_at"`
NextRunAt pgtype.Timestamptz `json:"next_run_at"`
Status string `json:"status"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
PromptRuleName pgtype.Text `json:"prompt_rule_name"`
BrandName pgtype.Text `json:"brand_name"`
}
func (q *Queries) GetScheduleTaskByID(ctx context.Context, arg GetScheduleTaskByIDParams) (GetScheduleTaskByIDRow, error) {
@@ -117,11 +132,15 @@ func (q *Queries) GetScheduleTaskByID(ctx context.Context, arg GetScheduleTaskBy
err := row.Scan(
&i.ID,
&i.TenantID,
&i.WorkspaceID,
&i.PromptRuleID,
&i.BrandID,
&i.Name,
&i.CronExpr,
&i.TargetPlatform,
&i.AutoPublish,
&i.PublishAccountIds,
&i.CoverAssetUrl,
&i.CoverImageAssetID,
&i.StartAt,
&i.EndAt,
&i.NextRunAt,
@@ -135,8 +154,9 @@ func (q *Queries) GetScheduleTaskByID(ctx context.Context, arg GetScheduleTaskBy
}
const listScheduleTasks = `-- name: ListScheduleTasks :many
SELECT st.id, st.tenant_id, st.prompt_rule_id, st.brand_id, st.name,
st.cron_expr, st.target_platform, st.start_at, st.end_at,
SELECT st.id, st.tenant_id, st.workspace_id, st.prompt_rule_id, st.brand_id, st.name,
st.cron_expr, st.auto_publish, st.publish_account_ids, st.cover_asset_url, st.cover_image_asset_id,
st.start_at, st.end_at,
st.next_run_at, st.status, st.created_at, st.updated_at,
pr.name AS prompt_rule_name,
b.name AS brand_name
@@ -160,21 +180,25 @@ type ListScheduleTasksParams struct {
}
type ListScheduleTasksRow struct {
ID int64 `json:"id"`
TenantID int64 `json:"tenant_id"`
PromptRuleID int64 `json:"prompt_rule_id"`
BrandID pgtype.Int8 `json:"brand_id"`
Name string `json:"name"`
CronExpr string `json:"cron_expr"`
TargetPlatform pgtype.Text `json:"target_platform"`
StartAt pgtype.Timestamptz `json:"start_at"`
EndAt pgtype.Timestamptz `json:"end_at"`
NextRunAt pgtype.Timestamptz `json:"next_run_at"`
Status string `json:"status"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
PromptRuleName pgtype.Text `json:"prompt_rule_name"`
BrandName pgtype.Text `json:"brand_name"`
ID int64 `json:"id"`
TenantID int64 `json:"tenant_id"`
WorkspaceID pgtype.Int8 `json:"workspace_id"`
PromptRuleID int64 `json:"prompt_rule_id"`
BrandID pgtype.Int8 `json:"brand_id"`
Name string `json:"name"`
CronExpr string `json:"cron_expr"`
AutoPublish bool `json:"auto_publish"`
PublishAccountIds []byte `json:"publish_account_ids"`
CoverAssetUrl pgtype.Text `json:"cover_asset_url"`
CoverImageAssetID pgtype.Int8 `json:"cover_image_asset_id"`
StartAt pgtype.Timestamptz `json:"start_at"`
EndAt pgtype.Timestamptz `json:"end_at"`
NextRunAt pgtype.Timestamptz `json:"next_run_at"`
Status string `json:"status"`
CreatedAt pgtype.Timestamptz `json:"created_at"`
UpdatedAt pgtype.Timestamptz `json:"updated_at"`
PromptRuleName pgtype.Text `json:"prompt_rule_name"`
BrandName pgtype.Text `json:"brand_name"`
}
func (q *Queries) ListScheduleTasks(ctx context.Context, arg ListScheduleTasksParams) ([]ListScheduleTasksRow, error) {
@@ -195,11 +219,15 @@ func (q *Queries) ListScheduleTasks(ctx context.Context, arg ListScheduleTasksPa
if err := rows.Scan(
&i.ID,
&i.TenantID,
&i.WorkspaceID,
&i.PromptRuleID,
&i.BrandID,
&i.Name,
&i.CronExpr,
&i.TargetPlatform,
&i.AutoPublish,
&i.PublishAccountIds,
&i.CoverAssetUrl,
&i.CoverImageAssetID,
&i.StartAt,
&i.EndAt,
&i.NextRunAt,
@@ -238,23 +266,31 @@ const updateScheduleTask = `-- name: UpdateScheduleTask :exec
UPDATE schedule_tasks
SET prompt_rule_id = $1, brand_id = $2,
name = $3, cron_expr = $4,
target_platform = $5,
start_at = $6, end_at = $7,
next_run_at = $8, updated_at = NOW()
WHERE id = $9 AND tenant_id = $10 AND deleted_at IS NULL
workspace_id = $5,
auto_publish = $6,
publish_account_ids = $7,
cover_asset_url = $8,
cover_image_asset_id = $9,
start_at = $10, end_at = $11,
next_run_at = $12, updated_at = NOW()
WHERE id = $13 AND tenant_id = $14 AND deleted_at IS NULL
`
type UpdateScheduleTaskParams struct {
PromptRuleID int64 `json:"prompt_rule_id"`
BrandID pgtype.Int8 `json:"brand_id"`
Name string `json:"name"`
CronExpr string `json:"cron_expr"`
TargetPlatform pgtype.Text `json:"target_platform"`
StartAt pgtype.Timestamptz `json:"start_at"`
EndAt pgtype.Timestamptz `json:"end_at"`
NextRunAt pgtype.Timestamptz `json:"next_run_at"`
ID int64 `json:"id"`
TenantID int64 `json:"tenant_id"`
PromptRuleID int64 `json:"prompt_rule_id"`
BrandID pgtype.Int8 `json:"brand_id"`
Name string `json:"name"`
CronExpr string `json:"cron_expr"`
WorkspaceID pgtype.Int8 `json:"workspace_id"`
AutoPublish bool `json:"auto_publish"`
PublishAccountIds []byte `json:"publish_account_ids"`
CoverAssetUrl pgtype.Text `json:"cover_asset_url"`
CoverImageAssetID pgtype.Int8 `json:"cover_image_asset_id"`
StartAt pgtype.Timestamptz `json:"start_at"`
EndAt pgtype.Timestamptz `json:"end_at"`
NextRunAt pgtype.Timestamptz `json:"next_run_at"`
ID int64 `json:"id"`
TenantID int64 `json:"tenant_id"`
}
func (q *Queries) UpdateScheduleTask(ctx context.Context, arg UpdateScheduleTaskParams) error {
@@ -263,7 +299,11 @@ func (q *Queries) UpdateScheduleTask(ctx context.Context, arg UpdateScheduleTask
arg.BrandID,
arg.Name,
arg.CronExpr,
arg.TargetPlatform,
arg.WorkspaceID,
arg.AutoPublish,
arg.PublishAccountIds,
arg.CoverAssetUrl,
arg.CoverImageAssetID,
arg.StartAt,
arg.EndAt,
arg.NextRunAt,
@@ -1,6 +1,7 @@
-- name: ListScheduleTasks :many
SELECT st.id, st.tenant_id, st.prompt_rule_id, st.brand_id, st.name,
st.cron_expr, st.target_platform, st.start_at, st.end_at,
SELECT st.id, st.tenant_id, st.workspace_id, st.prompt_rule_id, st.brand_id, st.name,
st.cron_expr, st.auto_publish, st.publish_account_ids, st.cover_asset_url, st.cover_image_asset_id,
st.start_at, st.end_at,
st.next_run_at, st.status, st.created_at, st.updated_at,
pr.name AS prompt_rule_name,
b.name AS brand_name
@@ -23,8 +24,9 @@ WHERE tenant_id = sqlc.arg(tenant_id)
AND (sqlc.narg(prompt_rule_id)::bigint IS NULL OR prompt_rule_id = sqlc.narg(prompt_rule_id));
-- name: GetScheduleTaskByID :one
SELECT st.id, st.tenant_id, st.prompt_rule_id, st.brand_id, st.name,
st.cron_expr, st.target_platform, st.start_at, st.end_at,
SELECT st.id, st.tenant_id, st.workspace_id, st.prompt_rule_id, st.brand_id, st.name,
st.cron_expr, st.auto_publish, st.publish_account_ids, st.cover_asset_url, st.cover_image_asset_id,
st.start_at, st.end_at,
st.next_run_at, st.status, st.created_at, st.updated_at,
pr.name AS prompt_rule_name,
b.name AS brand_name
@@ -34,10 +36,12 @@ LEFT JOIN brands b ON b.id = st.brand_id
WHERE st.id = sqlc.arg(id) AND st.tenant_id = sqlc.arg(tenant_id) AND st.deleted_at IS NULL;
-- name: CreateScheduleTask :one
INSERT INTO schedule_tasks (tenant_id, prompt_rule_id, brand_id, name, cron_expr,
target_platform, start_at, end_at, next_run_at)
VALUES (sqlc.arg(tenant_id), sqlc.arg(prompt_rule_id), sqlc.narg(brand_id), sqlc.arg(name),
sqlc.arg(cron_expr), sqlc.narg(target_platform), sqlc.narg(start_at), sqlc.narg(end_at),
INSERT INTO schedule_tasks (tenant_id, workspace_id, prompt_rule_id, brand_id, name, cron_expr,
auto_publish, publish_account_ids, cover_asset_url, cover_image_asset_id,
start_at, end_at, next_run_at)
VALUES (sqlc.arg(tenant_id), sqlc.narg(workspace_id), sqlc.arg(prompt_rule_id), sqlc.narg(brand_id), sqlc.arg(name),
sqlc.arg(cron_expr), sqlc.arg(auto_publish), sqlc.arg(publish_account_ids), sqlc.narg(cover_asset_url),
sqlc.narg(cover_image_asset_id), sqlc.narg(start_at), sqlc.narg(end_at),
sqlc.narg(next_run_at))
RETURNING id, created_at;
@@ -45,7 +49,11 @@ RETURNING id, created_at;
UPDATE schedule_tasks
SET prompt_rule_id = sqlc.arg(prompt_rule_id), brand_id = sqlc.narg(brand_id),
name = sqlc.arg(name), cron_expr = sqlc.arg(cron_expr),
target_platform = sqlc.narg(target_platform),
workspace_id = sqlc.narg(workspace_id),
auto_publish = sqlc.arg(auto_publish),
publish_account_ids = sqlc.arg(publish_account_ids),
cover_asset_url = sqlc.narg(cover_asset_url),
cover_image_asset_id = sqlc.narg(cover_image_asset_id),
start_at = sqlc.narg(start_at), end_at = sqlc.narg(end_at),
next_run_at = sqlc.narg(next_run_at), updated_at = NOW()
WHERE id = sqlc.arg(id) AND tenant_id = sqlc.arg(tenant_id) AND deleted_at IS NULL;
@@ -57,7 +57,7 @@ func NewArticleHandler(a *bootstrap.App) *ArticleHandler {
a.GenerationStreams,
a.Config.Generation,
a.Config.LLM.MaxOutputTokens,
).WithCache(a.Cache),
).WithCache(a.Cache).WithLogger(a.Logger),
imitationSvc: app.NewArticleImitationService(
a.DB,
a.LLM,