fix task article link drawer
Frontend CI / Frontend (push) Successful in 5m6s
Backend CI / Backend (push) Successful in 16m45s

This commit is contained in:
2026-05-14 21:14:27 +08:00
parent 34dda524d7
commit 765dae4bf1
15 changed files with 735 additions and 104 deletions
@@ -0,0 +1,236 @@
<script setup lang="ts">
import { FileTextOutlined, RightOutlined } from '@ant-design/icons-vue'
import type { GeneratedArticleLink } from '@geo/shared-types'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRoute, useRouter } from 'vue-router'
import { formatDateTime, getGenerateStatusMeta } from '@/lib/display'
const props = defineProps<{
open: boolean
articles: GeneratedArticleLink[]
}>()
const emit = defineEmits<{
'update:open': [value: boolean]
}>()
const { t } = useI18n()
const route = useRoute()
const router = useRouter()
const drawerOpen = computed({
get: () => props.open,
set: (value: boolean) => emit('update:open', value),
})
function canOpenArticle(article: GeneratedArticleLink): boolean {
return article.generate_status === 'completed'
}
function articleTitle(article: GeneratedArticleLink, index: number): string {
return article.title || `${t('article.untitled')} ${index + 1}`
}
function openArticle(article: GeneratedArticleLink): void {
if (!canOpenArticle(article)) {
return
}
emit('update:open', false)
const returnTo = router.resolve({
name: route.name ?? undefined,
params: route.params,
query: route.query,
})
void router.push({
name: 'article-editor',
params: { id: String(article.article_id) },
query: { return_to: returnTo.fullPath },
})
}
</script>
<template>
<a-drawer
v-model:open="drawerOpen"
:title="t('custom.instant.generatedArticles')"
width="560px"
placement="right"
:body-style="{ padding: '16px 24px', background: '#f7f8fa' }"
>
<div class="generated-article-links">
<template v-if="articles.length > 0">
<div
v-for="(item, index) in articles"
:key="item.article_id || index"
class="generated-article-links__item"
:class="{ 'generated-article-links__item--clickable': canOpenArticle(item) }"
@click="openArticle(item)"
>
<div
class="generated-article-links__icon"
:class="`generated-article-links__icon--${item.generate_status}`"
>
<FileTextOutlined />
</div>
<div class="generated-article-links__content">
<div class="generated-article-links__header">
<a-tooltip :title="articleTitle(item, index)">
<div class="generated-article-links__title">
{{ articleTitle(item, index) }}
</div>
</a-tooltip>
<a-tag
class="generated-article-links__status"
:color="getGenerateStatusMeta(item.generate_status).color"
:bordered="false"
>
{{ getGenerateStatusMeta(item.generate_status).label }}
</a-tag>
</div>
<div class="generated-article-links__meta">
{{ formatDateTime(item.created_at) }}
</div>
</div>
<div v-if="canOpenArticle(item)" class="generated-article-links__action">
<a-button type="link" size="small" @click.stop="openArticle(item)">
{{ t('custom.instant.openArticle') }}
<RightOutlined />
</a-button>
</div>
</div>
</template>
<a-empty
v-else
:description="t('custom.instant.articleLinksEmpty')"
class="generated-article-links__empty"
/>
</div>
</a-drawer>
</template>
<style scoped>
.generated-article-links {
display: flex;
flex-direction: column;
gap: 12px;
}
.generated-article-links__item {
display: flex;
align-items: center;
gap: 16px;
min-height: 74px;
padding: 16px;
background-color: #ffffff;
border: 1px solid #e5e6eb;
border-radius: 8px;
transition:
border-color 0.2s,
box-shadow 0.2s,
transform 0.2s;
}
.generated-article-links__item--clickable {
cursor: pointer;
}
.generated-article-links__item--clickable:hover {
border-color: #1677ff;
box-shadow: 0 4px 12px rgba(22, 119, 255, 0.08);
transform: translateY(-1px);
}
.generated-article-links__icon {
display: flex;
flex: 0 0 40px;
align-items: center;
justify-content: center;
width: 40px;
height: 40px;
color: #1677ff;
font-size: 20px;
background-color: #f0f5ff;
border-radius: 8px;
}
.generated-article-links__icon--failed {
color: #ff4d4f;
background-color: #fff1f0;
}
.generated-article-links__icon--completed {
color: #52c41a;
background-color: #f6ffed;
}
.generated-article-links__icon--running,
.generated-article-links__icon--generating,
.generated-article-links__icon--queued {
color: #1677ff;
background-color: #e6f4ff;
}
.generated-article-links__content {
display: flex;
flex: 1;
flex-direction: column;
gap: 6px;
min-width: 0;
}
.generated-article-links__header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}
.generated-article-links__title {
flex: 1;
min-width: 0;
overflow: hidden;
color: #1d2129;
font-weight: 500;
font-size: 15px;
line-height: 1.4;
white-space: nowrap;
text-overflow: ellipsis;
}
.generated-article-links__item--clickable .generated-article-links__title {
transition: color 0.2s;
}
.generated-article-links__item--clickable:hover .generated-article-links__title {
color: #1677ff;
}
.generated-article-links__status {
margin-inline-end: 0;
border-radius: 4px;
}
.generated-article-links__meta {
color: #86909c;
font-size: 13px;
}
.generated-article-links__action {
flex-shrink: 0;
}
.generated-article-links__action :deep(.ant-btn) {
display: inline-flex;
align-items: center;
gap: 2px;
height: 28px;
padding: 0;
font-size: 13px;
}
.generated-article-links__empty {
margin-top: 60px;
}
</style>
@@ -7,7 +7,7 @@ import type { Dayjs } from 'dayjs'
import { computed, onBeforeUnmount, reactive, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import ArticleDetailDrawer from '@/components/ArticleDetailDrawer.vue'
import GeneratedArticleLinksDrawer from '@/components/GeneratedArticleLinksDrawer.vue'
import { instantTasksApi, promptRulesApi } from '@/lib/api'
import { formatDateTime, getGenerateStatusMeta } from '@/lib/display'
import { formatPublishPlatformList } from '@/lib/publish-platforms'
@@ -17,8 +17,8 @@ const { t } = useI18n()
const page = ref(1)
const pageSize = ref(20)
const createdRange = ref<[Dayjs, Dayjs] | null>(null)
const detailOpen = ref(false)
const selectedArticleId = ref<number | null>(null)
const articleLinksOpen = ref(false)
const selectedTask = ref<InstantTaskItem | null>(null)
const draftFilters = reactive<{
prompt_rule_id?: number
@@ -54,6 +54,7 @@ const statusOptions = computed(() => [
{ label: getGenerateStatusMeta('queued').label, value: 'queued' },
{ label: getGenerateStatusMeta('running').label, value: 'running' },
{ label: getGenerateStatusMeta('completed').label, value: 'completed' },
{ label: getGenerateStatusMeta('partial_success').label, value: 'partial_success' },
{ label: getGenerateStatusMeta('failed').label, value: 'failed' },
])
@@ -135,12 +136,14 @@ function handleTableChange(nextPage: number, nextPageSize: number): void {
pageSize.value = nextPageSize
}
function openArticle(task: InstantTaskItem): void {
if (!task.article_id) {
const selectedTaskArticles = computed(() => selectedTask.value?.articles ?? [])
function openTaskArticles(task: InstantTaskItem): void {
if (!task.articles?.length) {
return
}
selectedArticleId.value = task.article_id
detailOpen.value = true
selectedTask.value = task
articleLinksOpen.value = true
}
function startPolling(): void {
@@ -281,8 +284,8 @@ onBeforeUnmount(() => {
shape="circle"
size="small"
class="action-btn action-eye"
:disabled="!record.article_id"
@click="openArticle(record)"
:disabled="!record.articles?.length"
@click="openTaskArticles(record)"
>
<EyeOutlined />
</a-button>
@@ -293,10 +296,9 @@ onBeforeUnmount(() => {
</template>
</a-table>
<ArticleDetailDrawer
:open="detailOpen"
:article-id="selectedArticleId"
@close="detailOpen = false"
<GeneratedArticleLinksDrawer
v-model:open="articleLinksOpen"
:articles="selectedTaskArticles"
/>
</div>
</template>
@@ -2,6 +2,8 @@
import {
DeleteOutlined,
EditOutlined,
EyeOutlined,
LoadingOutlined,
PauseCircleOutlined,
PlayCircleOutlined,
} from '@ant-design/icons-vue'
@@ -9,12 +11,13 @@ import type { ScheduleTask, ScheduleTaskListParams } from '@geo/shared-types'
import { useMutation, useQuery, useQueryClient } from '@tanstack/vue-query'
import { message, type TableColumnsType } from 'ant-design-vue'
import type { Dayjs } from 'dayjs'
import { computed, reactive, ref } from 'vue'
import { computed, onBeforeUnmount, reactive, ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import GeneratedArticleLinksDrawer from '@/components/GeneratedArticleLinksDrawer.vue'
import ScheduleTaskModal from '@/components/ScheduleTaskModal.vue'
import { promptRulesApi, schedulesApi } from '@/lib/api'
import { formatCronExecutionTime, formatDateTime } from '@/lib/display'
import { formatDateTime, getGenerateStatusMeta, hasActiveGenerationStatus } from '@/lib/display'
import { formatError } from '@/lib/errors'
import { formatPublishPlatformList } from '@/lib/publish-platforms'
@@ -26,6 +29,8 @@ const editingTask = ref<ScheduleTask | null>(null)
const page = ref(1)
const pageSize = ref(20)
const createdRange = ref<[Dayjs, Dayjs] | null>(null)
const articleLinksOpen = ref(false)
const selectedTask = ref<ScheduleTask | null>(null)
const draftFilters = reactive<{
prompt_rule_id?: number
@@ -88,11 +93,16 @@ const columns = computed<TableColumnsType<ScheduleTask>>(() => [
key: 'prompt_rule_name',
width: 180,
},
{ title: t('custom.instant.executionStatus'), dataIndex: 'status', key: 'status', width: 140 },
{
title: t('custom.instant.executionStatus'),
dataIndex: 'generation_status',
key: 'generation_status',
width: 140,
},
{
title: t('custom.instant.executionTime'),
dataIndex: 'cron_expr',
key: 'cron_expr',
dataIndex: 'execution_time',
key: 'execution_time',
width: 170,
},
{
@@ -113,7 +123,7 @@ const columns = computed<TableColumnsType<ScheduleTask>>(() => [
key: 'created_at',
width: 170,
},
{ title: t('common.actions'), key: 'actions', width: 140, fixed: 'right', align: 'right' },
{ title: t('common.actions'), key: 'actions', width: 176, fixed: 'right', align: 'right' },
])
const removeMutation = useMutation({
@@ -165,6 +175,45 @@ function handleTableChange(nextPage: number, nextPageSize: number): void {
page.value = nextPage
pageSize.value = nextPageSize
}
const selectedTaskArticles = computed(() => selectedTask.value?.generated_articles ?? [])
function openTaskArticles(task: ScheduleTask): void {
selectedTask.value = task
articleLinksOpen.value = true
}
let pollingTimer: number | null = null
function startPolling(): void {
if (pollingTimer !== null) return
pollingTimer = window.setInterval(() => {
void listQuery.refetch()
}, 3000)
}
function stopPolling(): void {
if (pollingTimer === null) return
window.clearInterval(pollingTimer)
pollingTimer = null
}
watch(
() => listQuery.data.value?.items ?? [],
(items) => {
const hasActive = items.some((item) => hasActiveGenerationStatus(item.generation_status))
if (hasActive) {
startPolling()
} else {
stopPolling()
}
},
{ immediate: true },
)
onBeforeUnmount(() => {
stopPolling()
})
</script>
<template>
@@ -240,17 +289,16 @@ function handleTableChange(nextPage: number, nextPageSize: number): void {
<template v-if="column.key === 'prompt_rule_name'">
{{ record.prompt_rule_name || '--' }}
</template>
<template v-else-if="column.key === 'status'">
<a-tag :color="record.status === 'enabled' ? 'green' : 'default'">
{{
record.status === 'enabled'
? t('custom.schedule.enabled')
: t('custom.schedule.disabled')
}}
<template v-else-if="column.key === 'generation_status'">
<a-tag :color="getGenerateStatusMeta(record.generation_status).color">
<span class="task-tab__status">
<LoadingOutlined v-if="hasActiveGenerationStatus(record.generation_status)" spin />
<span>{{ getGenerateStatusMeta(record.generation_status).label }}</span>
</span>
</a-tag>
</template>
<template v-else-if="column.key === 'cron_expr'">
{{ formatCronExecutionTime(record.cron_expr) }}
<template v-else-if="column.key === 'execution_time'">
{{ formatDateTime(record.execution_time) }}
</template>
<template v-else-if="column.key === 'auto_publish_platforms'">
<a-tag :color="record.auto_publish ? 'blue' : 'default'">
@@ -269,6 +317,19 @@ function handleTableChange(nextPage: number, nextPageSize: number): void {
</template>
<template v-else-if="column.key === 'actions'">
<div class="table-actions-row">
<a-tooltip :title="t('common.preview')">
<span>
<a-button
type="text"
shape="circle"
size="small"
class="action-btn action-eye"
@click="openTaskArticles(record)"
>
<EyeOutlined />
</a-button>
</span>
</a-tooltip>
<a-tooltip :title="t('common.edit')">
<a-button
type="text"
@@ -326,6 +387,10 @@ function handleTableChange(nextPage: number, nextPageSize: number): void {
</a-table>
<ScheduleTaskModal v-model:open="modalOpen" :task="editingTask" />
<GeneratedArticleLinksDrawer
v-model:open="articleLinksOpen"
:articles="selectedTaskArticles"
/>
</div>
</template>
@@ -362,6 +427,12 @@ function handleTableChange(nextPage: number, nextPageSize: number): void {
justify-content: flex-end;
}
.task-tab__status {
display: inline-flex;
align-items: center;
gap: 4px;
}
@media (max-width: 1400px) {
.task-tab__filters {
grid-template-columns: repeat(2, minmax(260px, 1fr));
@@ -664,6 +664,8 @@ const enUS = {
generating: 'Generating',
running: 'Running',
completed: 'Completed',
partial_success: 'Partially successful',
partial_completed: 'Partially successful',
failed: 'Failed',
},
publish: {
@@ -1589,6 +1591,9 @@ const enUS = {
executionStatus: 'Execution status',
executionTime: 'Execution time',
createdTime: 'Created time',
generatedArticles: 'Generated article links',
articleLinksEmpty: 'No generated articles',
openArticle: 'Open article',
empty: 'No instant tasks yet.',
},
filters: {
@@ -634,6 +634,8 @@ const zhCN = {
generating: "生成中",
running: "运行中",
completed: "已完成",
partial_success: "部分成功",
partial_completed: "部分成功",
failed: "生成失败",
},
publish: {
@@ -1508,6 +1510,9 @@ const zhCN = {
executionStatus: "执行状态",
executionTime: "执行时间",
createdTime: "创建时间",
generatedArticles: "生成文章链接",
articleLinksEmpty: "暂无生成文章",
openArticle: "打开文章",
empty: "还未创建即时任务,暂无相关数据~",
},
filters: {
+2
View File
@@ -8,6 +8,8 @@ const generateStatusMap: Record<string, { label: string; color: string }> = {
generating: { label: 'status.generate.generating', color: 'processing' },
running: { label: 'status.generate.running', color: 'processing' },
completed: { label: 'status.generate.completed', color: 'success' },
partial_success: { label: 'status.generate.partial_success', color: 'warning' },
partial_completed: { label: 'status.generate.partial_completed', color: 'warning' },
failed: { label: 'status.generate.failed', color: 'error' },
}
@@ -344,6 +344,12 @@ async function cleanupEmptyFreeCreate(): Promise<void> {
}
function navigateBack(): void {
const returnTo = normalizeReturnTo(route.query.return_to)
if (returnTo) {
void router.push(returnTo)
return
}
if (window.history.length > 1) {
void router.back()
return
@@ -352,6 +358,18 @@ function navigateBack(): void {
void router.push('/articles/templates')
}
function normalizeReturnTo(value: unknown): string | null {
const raw = Array.isArray(value) ? value[0] : value
if (typeof raw !== 'string') {
return null
}
const trimmed = raw.trim()
if (!trimmed || !trimmed.startsWith('/') || trimmed.startsWith('//')) {
return null
}
return trimmed
}
function handleStay(): void {
leaveModalOpen.value = false
}
@@ -1,7 +1,8 @@
<script setup lang="ts">
import { ClockCircleOutlined, ThunderboltOutlined } from '@ant-design/icons-vue'
import { ref } from 'vue'
import { ref, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRoute, useRouter } from 'vue-router'
import CustomArticleTab from '@/components/CustomArticleTab.vue'
import InstantGenerateModal from '@/components/InstantGenerateModal.vue'
@@ -11,11 +12,48 @@ import ScheduleTaskModal from '@/components/ScheduleTaskModal.vue'
import ScheduleTaskTab from '@/components/ScheduleTaskTab.vue'
const { t } = useI18n()
const route = useRoute()
const router = useRouter()
const activeTab = ref('articles')
const customTabs = ['articles', 'instantTasks', 'scheduleTasks', 'promptRules'] as const
type CustomTab = (typeof customTabs)[number]
const activeTab = ref<CustomTab>(normalizeCustomTab(route.query.tab))
const instantModalOpen = ref(false)
const scheduleModalOpen = ref(false)
function normalizeCustomTab(value: unknown): CustomTab {
const tab = Array.isArray(value) ? value[0] : value
return customTabs.includes(tab as CustomTab) ? (tab as CustomTab) : 'articles'
}
watch(
() => route.query.tab,
(tab) => {
const normalized = normalizeCustomTab(tab)
if (activeTab.value !== normalized) {
activeTab.value = normalized
}
},
)
watch(
activeTab,
(tab) => {
if (route.query.tab === tab) {
return
}
void router.replace({
name: 'articles-custom',
query: {
...route.query,
tab,
},
})
},
{ immediate: true },
)
function openInstantModal(): void {
instantModalOpen.value = true
}
+12
View File
@@ -1689,6 +1689,9 @@ export interface ScheduleTask {
end_at: string | null
next_run_at: string | null
status: 'enabled' | 'disabled'
generation_status?: string | null
execution_time?: string | null
generated_articles?: GeneratedArticleLink[] | null
created_at: string
updated_at: string
}
@@ -1759,9 +1762,17 @@ export interface InstantTaskListParams {
created_to?: string
}
export interface GeneratedArticleLink {
article_id: number
title: string | null
generate_status: string
created_at: string
}
export interface InstantTaskItem {
id: number
article_id: number | null
task_batch_id?: string | null
prompt_rule_id: number | null
prompt_rule_name: string | null
name: string
@@ -1769,6 +1780,7 @@ export interface InstantTaskItem {
execution_time: string | null
auto_publish_platforms: string[]
generate_count: number
articles: GeneratedArticleLink[]
created_at: string
}
@@ -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