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:
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user