fix task article link drawer
This commit is contained in:
@@ -31,16 +31,25 @@ type InstantTaskListParams struct {
|
||||
}
|
||||
|
||||
type InstantTaskResponse struct {
|
||||
ID int64 `json:"id"`
|
||||
ArticleID *int64 `json:"article_id"`
|
||||
PromptRuleID *int64 `json:"prompt_rule_id"`
|
||||
PromptRuleName *string `json:"prompt_rule_name"`
|
||||
Name string `json:"name"`
|
||||
Status string `json:"status"`
|
||||
ExecutionTime *string `json:"execution_time"`
|
||||
AutoPublishPlatforms []string `json:"auto_publish_platforms"`
|
||||
GenerateCount int `json:"generate_count"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
ID int64 `json:"id"`
|
||||
ArticleID *int64 `json:"article_id"`
|
||||
TaskBatchID *string `json:"task_batch_id"`
|
||||
PromptRuleID *int64 `json:"prompt_rule_id"`
|
||||
PromptRuleName *string `json:"prompt_rule_name"`
|
||||
Name string `json:"name"`
|
||||
Status string `json:"status"`
|
||||
ExecutionTime *string `json:"execution_time"`
|
||||
AutoPublishPlatforms []string `json:"auto_publish_platforms"`
|
||||
GenerateCount int `json:"generate_count"`
|
||||
Articles []InstantTaskArticleLink `json:"articles"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
type InstantTaskArticleLink struct {
|
||||
ArticleID int64 `json:"article_id"`
|
||||
Title *string `json:"title"`
|
||||
GenerateStatus string `json:"generate_status"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
type InstantTaskListResponse struct {
|
||||
@@ -58,42 +67,104 @@ func (s *InstantTaskService) List(ctx context.Context, params InstantTaskListPar
|
||||
}
|
||||
offset := (params.Page - 1) * params.PageSize
|
||||
|
||||
const instantTaskBatchCTE = `
|
||||
WITH base AS (
|
||||
SELECT gt.id, gt.article_id, gt.task_batch_id, gt.operator_id,
|
||||
pr.id AS prompt_rule_id, pr.name AS prompt_rule_name,
|
||||
COALESCE(NULLIF(gt.input_params_json ->> 'task_name', ''), pr.name, '即时任务') AS task_name,
|
||||
gt.status,
|
||||
COALESCE(gt.started_at, gt.completed_at, gt.created_at) AS execution_time,
|
||||
gt.input_params_json,
|
||||
gt.created_at,
|
||||
CASE
|
||||
WHEN (gt.input_params_json ->> 'generate_count') ~ '^[0-9]+$'
|
||||
THEN GREATEST(1, LEAST(20, (gt.input_params_json ->> 'generate_count')::int))
|
||||
ELSE 1
|
||||
END AS generate_count,
|
||||
a.id AS active_article_id,
|
||||
COALESCE(av.title, NULLIF(a.wizard_state_json ->> 'title', ''), NULLIF(gt.input_params_json ->> 'title', '')) AS article_title,
|
||||
COALESCE(a.generate_status, gt.status) AS article_generate_status,
|
||||
COALESCE(a.created_at, gt.created_at) AS article_created_at
|
||||
FROM generation_tasks gt
|
||||
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
|
||||
LEFT JOIN prompt_rules pr ON pr.id = COALESCE(a.prompt_rule_id, NULLIF(gt.input_params_json ->> 'prompt_rule_id', '')::bigint)
|
||||
WHERE gt.tenant_id = $1
|
||||
AND gt.task_type = 'custom_generation'
|
||||
AND COALESCE(NULLIF(gt.input_params_json ->> 'generation_mode', ''), 'instant') = 'instant'
|
||||
AND ($2::bigint IS NULL OR pr.id = $2)
|
||||
AND ($4::text IS NULL OR COALESCE(NULLIF(gt.input_params_json ->> 'task_name', ''), pr.name, '') ILIKE '%' || $4 || '%')
|
||||
AND ($5::timestamptz IS NULL OR gt.created_at >= $5)
|
||||
AND ($6::timestamptz IS NULL OR gt.created_at <= $6)
|
||||
),
|
||||
keyed AS (
|
||||
SELECT *,
|
||||
COALESCE(
|
||||
NULLIF(task_batch_id, ''),
|
||||
NULLIF(input_params_json ->> 'task_batch_id', ''),
|
||||
CASE
|
||||
WHEN generate_count > 1 THEN CONCAT(
|
||||
'legacy:', COALESCE(operator_id, 0), ':', COALESCE(prompt_rule_id, 0), ':',
|
||||
task_name, ':', generate_count, ':', to_char(date_trunc('second', created_at), 'YYYY-MM-DD"T"HH24:MI:SS')
|
||||
)
|
||||
ELSE CONCAT('task:', id)
|
||||
END
|
||||
) AS batch_key
|
||||
FROM base
|
||||
),
|
||||
aggregated AS (
|
||||
SELECT MIN(id) AS id,
|
||||
MIN(batch_key) AS batch_key,
|
||||
MIN(NULLIF(task_batch_id, '')) AS task_batch_id,
|
||||
(ARRAY_AGG(active_article_id ORDER BY created_at, id) FILTER (WHERE active_article_id IS NOT NULL))[1] AS article_id,
|
||||
(ARRAY_AGG(prompt_rule_id ORDER BY created_at, id) FILTER (WHERE prompt_rule_id IS NOT NULL))[1] AS prompt_rule_id,
|
||||
(ARRAY_AGG(prompt_rule_name ORDER BY created_at, id) FILTER (WHERE prompt_rule_name IS NOT NULL))[1] AS prompt_rule_name,
|
||||
(ARRAY_AGG(task_name ORDER BY created_at, id))[1] AS task_name,
|
||||
CASE
|
||||
WHEN COUNT(*) FILTER (WHERE article_generate_status IN ('generating', 'running')) > 0 THEN 'running'
|
||||
WHEN COUNT(*) FILTER (WHERE article_generate_status IN ('queued', 'pending')) > 0 THEN 'queued'
|
||||
WHEN COUNT(*) FILTER (WHERE article_generate_status = 'completed') > 0
|
||||
AND COUNT(*) FILTER (WHERE article_generate_status = 'failed') > 0 THEN 'partial_success'
|
||||
WHEN COUNT(*) FILTER (WHERE article_generate_status = 'failed') = COUNT(*) THEN 'failed'
|
||||
WHEN COUNT(*) FILTER (WHERE article_generate_status = 'completed') = COUNT(*) THEN 'completed'
|
||||
ELSE (ARRAY_AGG(article_generate_status ORDER BY created_at DESC, id DESC))[1]
|
||||
END AS status,
|
||||
MIN(execution_time) AS execution_time,
|
||||
(ARRAY_AGG(input_params_json ORDER BY created_at, id))[1] AS input_params_json,
|
||||
MAX(generate_count) AS generate_count,
|
||||
MIN(created_at) AS created_at,
|
||||
COALESCE(
|
||||
JSONB_AGG(
|
||||
JSONB_BUILD_OBJECT(
|
||||
'article_id', active_article_id,
|
||||
'title', article_title,
|
||||
'generate_status', article_generate_status,
|
||||
'created_at', article_created_at
|
||||
)
|
||||
ORDER BY created_at, id
|
||||
) FILTER (WHERE active_article_id IS NOT NULL),
|
||||
'[]'::jsonb
|
||||
) AS articles
|
||||
FROM keyed
|
||||
GROUP BY batch_key
|
||||
)`
|
||||
|
||||
var total int64
|
||||
err := s.pool.QueryRow(ctx, `
|
||||
err := s.pool.QueryRow(ctx, instantTaskBatchCTE+`
|
||||
SELECT COUNT(*)
|
||||
FROM generation_tasks gt
|
||||
LEFT JOIN articles a ON a.id = gt.article_id
|
||||
LEFT JOIN prompt_rules pr ON pr.id = COALESCE(a.prompt_rule_id, NULLIF(gt.input_params_json ->> 'prompt_rule_id', '')::bigint)
|
||||
WHERE gt.tenant_id = $1
|
||||
AND gt.task_type = 'custom_generation'
|
||||
AND ($2::bigint IS NULL OR pr.id = $2)
|
||||
AND ($3::text IS NULL OR gt.status = $3)
|
||||
AND ($4::text IS NULL OR COALESCE(NULLIF(gt.input_params_json ->> 'task_name', ''), pr.name, '') ILIKE '%' || $4 || '%')
|
||||
AND ($5::timestamptz IS NULL OR gt.created_at >= $5)
|
||||
AND ($6::timestamptz IS NULL OR gt.created_at <= $6)
|
||||
FROM aggregated
|
||||
WHERE ($3::text IS NULL OR status = $3)
|
||||
`, actor.TenantID, params.PromptRuleID, params.Status, params.Keyword, params.CreatedFrom, params.CreatedTo).Scan(&total)
|
||||
if err != nil {
|
||||
return nil, response.ErrInternal(50010, "count_failed", "failed to count instant tasks")
|
||||
}
|
||||
|
||||
rows, err := s.pool.Query(ctx, `
|
||||
SELECT gt.id, gt.article_id, pr.id, pr.name,
|
||||
COALESCE(NULLIF(gt.input_params_json ->> 'task_name', ''), pr.name, '即时任务') AS task_name,
|
||||
gt.status,
|
||||
COALESCE(gt.started_at, gt.completed_at, gt.created_at) AS execution_time,
|
||||
gt.input_params_json,
|
||||
gt.created_at
|
||||
FROM generation_tasks gt
|
||||
LEFT JOIN articles a ON a.id = gt.article_id
|
||||
LEFT JOIN prompt_rules pr ON pr.id = COALESCE(a.prompt_rule_id, NULLIF(gt.input_params_json ->> 'prompt_rule_id', '')::bigint)
|
||||
WHERE gt.tenant_id = $1
|
||||
AND gt.task_type = 'custom_generation'
|
||||
AND ($2::bigint IS NULL OR pr.id = $2)
|
||||
AND ($3::text IS NULL OR gt.status = $3)
|
||||
AND ($4::text IS NULL OR COALESCE(NULLIF(gt.input_params_json ->> 'task_name', ''), pr.name, '') ILIKE '%' || $4 || '%')
|
||||
AND ($5::timestamptz IS NULL OR gt.created_at >= $5)
|
||||
AND ($6::timestamptz IS NULL OR gt.created_at <= $6)
|
||||
ORDER BY gt.created_at DESC
|
||||
rows, err := s.pool.Query(ctx, instantTaskBatchCTE+`
|
||||
SELECT id, article_id, task_batch_id, prompt_rule_id, prompt_rule_name, task_name,
|
||||
status, execution_time, input_params_json, generate_count, articles, created_at
|
||||
FROM aggregated
|
||||
WHERE ($3::text IS NULL OR status = $3)
|
||||
ORDER BY created_at DESC, id DESC
|
||||
LIMIT $7 OFFSET $8
|
||||
`, actor.TenantID, params.PromptRuleID, params.Status, params.Keyword, params.CreatedFrom, params.CreatedTo, params.PageSize, offset)
|
||||
if err != nil {
|
||||
@@ -107,15 +178,19 @@ func (s *InstantTaskService) List(ctx context.Context, params InstantTaskListPar
|
||||
var executionAt interface{}
|
||||
var createdAt interface{}
|
||||
var inputParamsJSON []byte
|
||||
var articlesJSON []byte
|
||||
if err := rows.Scan(
|
||||
&item.ID,
|
||||
&item.ArticleID,
|
||||
&item.TaskBatchID,
|
||||
&item.PromptRuleID,
|
||||
&item.PromptRuleName,
|
||||
&item.Name,
|
||||
&item.Status,
|
||||
&executionAt,
|
||||
&inputParamsJSON,
|
||||
&item.GenerateCount,
|
||||
&articlesJSON,
|
||||
&createdAt,
|
||||
); err != nil {
|
||||
return nil, response.ErrInternal(50010, "scan_failed", err.Error())
|
||||
@@ -123,24 +198,24 @@ func (s *InstantTaskService) List(ctx context.Context, params InstantTaskListPar
|
||||
|
||||
item.ExecutionTime = stringPtrFromDBValue(executionAt)
|
||||
item.CreatedAt = fmt.Sprintf("%v", createdAt)
|
||||
item.Articles = parseInstantTaskArticleLinks(articlesJSON)
|
||||
autoPublishPlatforms, err := loadScheduleAutoPublishPlatforms(ctx, s.pool, actor.TenantID, inputParamsJSON)
|
||||
if err != nil {
|
||||
return nil, response.ErrInternal(50010, "query_failed", "failed to resolve instant task auto publish platforms")
|
||||
}
|
||||
item.AutoPublishPlatforms = autoPublishPlatforms
|
||||
item.GenerateCount = 1
|
||||
|
||||
if len(inputParamsJSON) > 0 {
|
||||
payload, err := parseJSONMap(inputParamsJSON)
|
||||
if err == nil {
|
||||
if count := extractInt(payload, "generate_count"); count > 0 {
|
||||
item.GenerateCount = count
|
||||
}
|
||||
}
|
||||
if item.GenerateCount <= 0 {
|
||||
item.GenerateCount = len(item.Articles)
|
||||
}
|
||||
if item.GenerateCount <= 0 {
|
||||
item.GenerateCount = 1
|
||||
}
|
||||
|
||||
items = append(items, item)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, response.ErrInternal(50010, "scan_failed", "failed to iterate instant tasks")
|
||||
}
|
||||
|
||||
return &InstantTaskListResponse{
|
||||
Items: items,
|
||||
@@ -167,3 +242,18 @@ func parseJSONMap(raw []byte) (map[string]interface{}, error) {
|
||||
}
|
||||
return payload, nil
|
||||
}
|
||||
|
||||
func parseInstantTaskArticleLinks(raw []byte) []InstantTaskArticleLink {
|
||||
if len(raw) == 0 {
|
||||
return []InstantTaskArticleLink{}
|
||||
}
|
||||
|
||||
var links []InstantTaskArticleLink
|
||||
if err := json.Unmarshal(raw, &links); err != nil {
|
||||
return []InstantTaskArticleLink{}
|
||||
}
|
||||
if links == nil {
|
||||
return []InstantTaskArticleLink{}
|
||||
}
|
||||
return links
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"go.uber.org/zap"
|
||||
|
||||
@@ -108,6 +109,7 @@ type enqueuePromptRuleGenerationInput struct {
|
||||
BrandID *int64
|
||||
ExtraParams map[string]interface{}
|
||||
FallbackName string
|
||||
TaskBatchID *string
|
||||
}
|
||||
|
||||
func NewPromptRuleGenerationService(
|
||||
@@ -181,6 +183,7 @@ func (s *PromptRuleGenerationService) GenerateFromRule(ctx context.Context, req
|
||||
}
|
||||
|
||||
results := make([]GenerateFromRuleItem, 0, generateCount)
|
||||
taskBatchID := "instant-" + uuid.NewString()
|
||||
var lastErr error
|
||||
for idx := 0; idx < generateCount; idx++ {
|
||||
result, enqueueErr := s.enqueuePromptRuleGeneration(ctx, enqueuePromptRuleGenerationInput{
|
||||
@@ -190,6 +193,7 @@ func (s *PromptRuleGenerationService) GenerateFromRule(ctx context.Context, req
|
||||
BrandID: req.BrandID,
|
||||
ExtraParams: clonePromptRuleExtraParams(extra),
|
||||
FallbackName: "即时任务",
|
||||
TaskBatchID: &taskBatchID,
|
||||
})
|
||||
if enqueueErr != nil {
|
||||
lastErr = enqueueErr
|
||||
@@ -293,6 +297,9 @@ func (s *PromptRuleGenerationService) enqueuePromptRuleGeneration(ctx context.Co
|
||||
"enable_web_search": extractBool(extra, "enable_web_search"),
|
||||
"generate_count": generateCount,
|
||||
}
|
||||
if input.TaskBatchID != nil && strings.TrimSpace(*input.TaskBatchID) != "" {
|
||||
inputParams["task_batch_id"] = strings.TrimSpace(*input.TaskBatchID)
|
||||
}
|
||||
if workspaceID := extractInt(extra, "workspace_id"); workspaceID > 0 {
|
||||
inputParams["workspace_id"] = workspaceID
|
||||
}
|
||||
@@ -417,6 +424,7 @@ func (s *PromptRuleGenerationService) enqueuePromptRuleGeneration(ctx context.Co
|
||||
OperatorID: operatorID,
|
||||
TenantID: input.TenantID,
|
||||
ArticleID: &articleID,
|
||||
TaskBatchID: input.TaskBatchID,
|
||||
QuotaReservationID: &reservationID,
|
||||
TaskType: "custom_generation",
|
||||
InputParamsJSON: inputJSON,
|
||||
@@ -429,6 +437,7 @@ func (s *PromptRuleGenerationService) enqueuePromptRuleGeneration(ctx context.Co
|
||||
return nil, response.ErrInternal(50012, "create_failed", "failed to commit generation task")
|
||||
}
|
||||
invalidateArticleCaches(ctx, s.cache, input.TenantID, &articleID)
|
||||
s.invalidateScheduleTaskCacheForGeneration(ctx, input.TenantID, inputParams)
|
||||
|
||||
job := promptRuleGenerationJob{
|
||||
OperatorID: operatorID,
|
||||
@@ -612,6 +621,7 @@ func (s *PromptRuleGenerationService) executeGeneration(ctx context.Context, job
|
||||
cleanupCtx, cancel := newGenerationCleanupContext()
|
||||
defer cancel()
|
||||
invalidateArticleCaches(cleanupCtx, s.cache, job.TenantID, &job.ArticleID)
|
||||
s.invalidateScheduleTaskCacheForGeneration(cleanupCtx, job.TenantID, job.InputParams)
|
||||
|
||||
if runtimeCfg.StreamEnabled && s.streams != nil {
|
||||
s.streams.Complete(job.ArticleID, job.TaskID, title, content)
|
||||
@@ -764,6 +774,7 @@ func (s *PromptRuleGenerationService) failGeneration(ctx context.Context, job pr
|
||||
}
|
||||
}
|
||||
invalidateArticleCaches(cleanupCtx, s.cache, job.TenantID, &job.ArticleID)
|
||||
s.invalidateScheduleTaskCacheForGeneration(cleanupCtx, job.TenantID, job.InputParams)
|
||||
if cleanupErr != nil {
|
||||
RecordGenerationTaskEvent(GenerationTaskEventCleanupFailure, logCtx)
|
||||
LogGenerationTaskError(s.logger, "prompt rule generation failure cleanup failed", logCtx, zap.Error(cleanupErr))
|
||||
@@ -775,6 +786,18 @@ func (s *PromptRuleGenerationService) failGeneration(ctx context.Context, job pr
|
||||
}
|
||||
}
|
||||
|
||||
func (s *PromptRuleGenerationService) invalidateScheduleTaskCacheForGeneration(ctx context.Context, tenantID int64, inputParams map[string]interface{}) {
|
||||
if s == nil || s.cache == nil || strings.TrimSpace(extractString(inputParams, "generation_mode")) != "schedule" {
|
||||
return
|
||||
}
|
||||
scheduleTaskID := int64(extractInt(inputParams, "schedule_task_id"))
|
||||
if scheduleTaskID <= 0 {
|
||||
invalidateScheduleTaskCaches(ctx, s.cache, tenantID, nil)
|
||||
return
|
||||
}
|
||||
invalidateScheduleTaskCaches(ctx, s.cache, tenantID, &scheduleTaskID)
|
||||
}
|
||||
|
||||
func promptRuleGenerationJobLogContext(job promptRuleGenerationJob, stage, statusBefore, statusAfter, result string) GenerationTaskLogContext {
|
||||
return GenerationTaskLogContext{
|
||||
TaskID: job.TaskID,
|
||||
|
||||
@@ -54,27 +54,30 @@ type ScheduleTaskRequest struct {
|
||||
}
|
||||
|
||||
type ScheduleTaskResponse struct {
|
||||
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"`
|
||||
AutoPublishPlatforms []string `json:"auto_publish_platforms"`
|
||||
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"`
|
||||
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"`
|
||||
AutoPublishPlatforms []string `json:"auto_publish_platforms"`
|
||||
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"`
|
||||
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 {
|
||||
@@ -404,6 +407,9 @@ func (s *ScheduleTaskService) loadScheduleTasks(ctx context.Context, tenantID in
|
||||
if err := s.populateScheduleAutoPublishPlatforms(ctx, tenantID, &item); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := s.populateScheduleLatestGeneratedArticles(ctx, tenantID, &item); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items = append(items, item)
|
||||
}
|
||||
return &ScheduleTaskListResponse{Items: items, Total: total}, nil
|
||||
@@ -432,6 +438,9 @@ func (s *ScheduleTaskService) loadScheduleTaskDetail(ctx context.Context, tenant
|
||||
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
|
||||
}
|
||||
|
||||
@@ -447,6 +456,122 @@ func (s *ScheduleTaskService) populateScheduleAutoPublishPlatforms(ctx context.C
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *ScheduleTaskService) populateScheduleLatestGeneratedArticles(ctx context.Context, tenantID int64, item *ScheduleTaskResponse) error {
|
||||
if item == nil || item.ID <= 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
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 = 'custom_generation'
|
||||
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 = 'custom_generation'
|
||||
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)
|
||||
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 = stringPtrFromDBValue(executionAt)
|
||||
}
|
||||
statuses = append(statuses, generateStatus)
|
||||
if articleID != nil && *articleID > 0 {
|
||||
articles = append(articles, InstantTaskArticleLink{
|
||||
ArticleID: *articleID,
|
||||
Title: title,
|
||||
GenerateStatus: generateStatus,
|
||||
CreatedAt: fmt.Sprintf("%v", 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 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) {
|
||||
|
||||
@@ -25,6 +25,7 @@ type GenerationTaskInput struct {
|
||||
OperatorID int64
|
||||
TenantID int64
|
||||
ArticleID *int64
|
||||
TaskBatchID *string
|
||||
QuotaReservationID *int64
|
||||
TaskType string
|
||||
RequestHash *string
|
||||
@@ -91,6 +92,7 @@ func (r *auditRepository) CreateGenerationTask(ctx context.Context, input Genera
|
||||
OperatorID: pgInt8(operatorID),
|
||||
TenantID: input.TenantID,
|
||||
ArticleID: pgInt8(input.ArticleID),
|
||||
TaskBatchID: pgText(input.TaskBatchID),
|
||||
QuotaReservationID: pgInt8(input.QuotaReservationID),
|
||||
TaskType: input.TaskType,
|
||||
RequestHash: pgText(input.RequestHash),
|
||||
|
||||
@@ -62,9 +62,9 @@ func (q *Queries) CreateAuditLog(ctx context.Context, arg CreateAuditLogParams)
|
||||
}
|
||||
|
||||
const createGenerationTask = `-- name: CreateGenerationTask :one
|
||||
INSERT INTO generation_tasks (tenant_id, operator_id, article_id, quota_reservation_id, task_type, request_hash, input_params_json, status)
|
||||
INSERT INTO generation_tasks (tenant_id, operator_id, article_id, task_batch_id, quota_reservation_id, task_type, request_hash, input_params_json, status)
|
||||
VALUES ($1, $2, $3, $4,
|
||||
$5, $6, $7, 'queued')
|
||||
$5, $6, $7, $8, 'queued')
|
||||
RETURNING id
|
||||
`
|
||||
|
||||
@@ -72,6 +72,7 @@ type CreateGenerationTaskParams struct {
|
||||
TenantID int64 `json:"tenant_id"`
|
||||
OperatorID pgtype.Int8 `json:"operator_id"`
|
||||
ArticleID pgtype.Int8 `json:"article_id"`
|
||||
TaskBatchID pgtype.Text `json:"task_batch_id"`
|
||||
QuotaReservationID pgtype.Int8 `json:"quota_reservation_id"`
|
||||
TaskType string `json:"task_type"`
|
||||
RequestHash pgtype.Text `json:"request_hash"`
|
||||
@@ -83,6 +84,7 @@ func (q *Queries) CreateGenerationTask(ctx context.Context, arg CreateGeneration
|
||||
arg.TenantID,
|
||||
arg.OperatorID,
|
||||
arg.ArticleID,
|
||||
arg.TaskBatchID,
|
||||
arg.QuotaReservationID,
|
||||
arg.TaskType,
|
||||
arg.RequestHash,
|
||||
|
||||
@@ -17,9 +17,9 @@ VALUES (sqlc.arg(operator_id), sqlc.arg(tenant_id), sqlc.arg(module), sqlc.arg(a
|
||||
sqlc.arg(before_json), sqlc.arg(after_json), sqlc.arg(result), sqlc.arg(error_message));
|
||||
|
||||
-- name: CreateGenerationTask :one
|
||||
INSERT INTO generation_tasks (tenant_id, operator_id, article_id, quota_reservation_id, task_type, request_hash, input_params_json, status)
|
||||
VALUES (sqlc.arg(tenant_id), sqlc.arg(operator_id), sqlc.arg(article_id), sqlc.arg(quota_reservation_id),
|
||||
sqlc.arg(task_type), sqlc.arg(request_hash), sqlc.arg(input_params_json), 'queued')
|
||||
INSERT INTO generation_tasks (tenant_id, operator_id, article_id, task_batch_id, quota_reservation_id, task_type, request_hash, input_params_json, status)
|
||||
VALUES (sqlc.arg(tenant_id), sqlc.arg(operator_id), sqlc.arg(article_id), sqlc.arg(task_batch_id),
|
||||
sqlc.arg(quota_reservation_id), sqlc.arg(task_type), sqlc.arg(request_hash), sqlc.arg(input_params_json), 'queued')
|
||||
RETURNING id;
|
||||
|
||||
-- name: CreateTaskRecord :one
|
||||
|
||||
Reference in New Issue
Block a user