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:
@@ -3,20 +3,20 @@ import { PlusOutlined } from "@ant-design/icons-vue";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/vue-query";
|
||||
import { message } from "ant-design-vue";
|
||||
import type { PromptRuleSimple, ScheduleTask } from "@geo/shared-types";
|
||||
import { computed, onBeforeUnmount, reactive, ref, watch } from "vue";
|
||||
import { computed, reactive, ref, watch } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
|
||||
import CoverPickerModal from "@/components/CoverPickerModal.vue";
|
||||
import PromptRuleModal from "@/components/PromptRuleModal.vue";
|
||||
import PublishPlatformSelector from "@/components/PublishPlatformSelector.vue";
|
||||
import { generateApi, mediaApi, promptRulesApi, schedulesApi, tenantAccountsApi } from "@/lib/api";
|
||||
import { generateApi, imagesApi, mediaApi, promptRulesApi, resolveApiURL, schedulesApi, tenantAccountsApi } from "@/lib/api";
|
||||
import { coverUploadRequired, deriveCoverFileName } from "@/lib/cover-requirements";
|
||||
import { formatError } from "@/lib/errors";
|
||||
import { IMAGE_UPLOAD_ACCEPT, useImageUploadProgress, validateImageUploadFile } from "@/lib/image-webp";
|
||||
import {
|
||||
buildPublishPlatformOptions,
|
||||
normalizePublishPlatformIds,
|
||||
parseTargetPlatforms,
|
||||
serializeTargetPlatforms,
|
||||
} from "@/lib/publish-platforms";
|
||||
buildPublishAccountCards,
|
||||
buildPublishPlatformMap,
|
||||
publishStatusShortLabel,
|
||||
type PublishAccountCard,
|
||||
} from "@/lib/publish-account-cards";
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean;
|
||||
@@ -30,17 +30,19 @@ const emit = defineEmits<{
|
||||
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useI18n();
|
||||
const imageUploadProgress = useImageUploadProgress();
|
||||
|
||||
const promptDrawerOpen = ref(false);
|
||||
const coverPreviewUrl = ref("");
|
||||
const coverFileName = ref("");
|
||||
const coverPickerOpen = ref(false);
|
||||
|
||||
const form = reactive({
|
||||
name: "",
|
||||
promptRuleId: undefined as number | undefined,
|
||||
platformIds: [] as string[],
|
||||
coverEnabled: true,
|
||||
autoPublish: false,
|
||||
publishAccountIds: [] as string[],
|
||||
coverEnabled: false,
|
||||
coverAssetUrl: "",
|
||||
coverFileName: "",
|
||||
coverImageAssetId: null as number | null,
|
||||
enableWebSearch: false,
|
||||
generateCount: 1,
|
||||
scheduleTime: "08:00:00",
|
||||
@@ -48,31 +50,25 @@ const form = reactive({
|
||||
|
||||
const isSchedule = computed(() => props.mode === "schedule");
|
||||
|
||||
const rulesQuery = useQuery({
|
||||
queryKey: ["promptRules", "simple"],
|
||||
queryFn: () => promptRulesApi.listSimple(),
|
||||
});
|
||||
|
||||
const schedulePublishQueryEnabled = computed(() => props.open && isSchedule.value);
|
||||
|
||||
const platformsQuery = useQuery({
|
||||
queryKey: ["media", "platforms", "task-drawer"],
|
||||
enabled: computed(() => props.open),
|
||||
queryKey: ["media", "platforms", "schedule-task-drawer"],
|
||||
enabled: schedulePublishQueryEnabled,
|
||||
queryFn: () => mediaApi.platforms(),
|
||||
});
|
||||
|
||||
const accountsQuery = useQuery({
|
||||
queryKey: ["tenant", "desktop-accounts", "task-drawer"],
|
||||
enabled: computed(() => props.open),
|
||||
queryKey: ["tenant", "desktop-accounts", "schedule-task-drawer"],
|
||||
enabled: schedulePublishQueryEnabled,
|
||||
queryFn: () => tenantAccountsApi.list(),
|
||||
});
|
||||
|
||||
const allPlatforms = computed(() =>
|
||||
buildPublishPlatformOptions(platformsQuery.data.value ?? [], accountsQuery.data.value),
|
||||
);
|
||||
|
||||
const platformsLoading = computed(
|
||||
() => platformsQuery.isPending.value || accountsQuery.isPending.value,
|
||||
);
|
||||
|
||||
const rulesQuery = useQuery({
|
||||
queryKey: ["promptRules", "simple"],
|
||||
queryFn: () => promptRulesApi.listSimple(),
|
||||
});
|
||||
|
||||
const promptOptions = computed(() =>
|
||||
(rulesQuery.data.value ?? []).map((rule: PromptRuleSimple) => ({
|
||||
label: rule.name,
|
||||
@@ -80,6 +76,40 @@ const promptOptions = computed(() =>
|
||||
})),
|
||||
);
|
||||
|
||||
const platformMap = computed(() => buildPublishPlatformMap(platformsQuery.data.value ?? []));
|
||||
|
||||
const schedulePublishAccounts = computed<PublishAccountCard[]>(() =>
|
||||
buildPublishAccountCards(accountsQuery.data.value ?? [], platformMap.value),
|
||||
);
|
||||
|
||||
const schedulePublishLoading = computed(
|
||||
() => platformsQuery.isPending.value || accountsQuery.isPending.value,
|
||||
);
|
||||
|
||||
const selectedSchedulePublishPlatformIds = computed(() => {
|
||||
const selected = new Set(form.publishAccountIds);
|
||||
return Array.from(
|
||||
new Set(
|
||||
schedulePublishAccounts.value
|
||||
.filter((account) => selected.has(account.id))
|
||||
.map((account) => account.platformId),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
const scheduleCoverRequired = computed(() => coverUploadRequired(selectedSchedulePublishPlatformIds.value));
|
||||
const effectiveScheduleCoverEnabled = computed(() => scheduleCoverRequired.value || form.coverEnabled);
|
||||
|
||||
watch(
|
||||
scheduleCoverRequired,
|
||||
(required) => {
|
||||
if (required) {
|
||||
form.coverEnabled = true;
|
||||
}
|
||||
},
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
const drawerTitle = computed(() => {
|
||||
if (isSchedule.value) {
|
||||
return props.task?.id ? t("custom.schedule.editTitle") : t("custom.schedule.createTitle");
|
||||
@@ -99,16 +129,10 @@ watch(
|
||||
(open) => {
|
||||
if (open) {
|
||||
hydrateForm();
|
||||
return;
|
||||
}
|
||||
resetCoverState();
|
||||
},
|
||||
);
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
resetCoverState();
|
||||
});
|
||||
|
||||
const createScheduleMutation = useMutation({
|
||||
mutationFn: () =>
|
||||
schedulesApi.create(buildSchedulePayload()),
|
||||
@@ -151,94 +175,101 @@ const submitLoading = computed(
|
||||
updateScheduleMutation.isPending.value ||
|
||||
instantGenerateMutation.isPending.value,
|
||||
);
|
||||
const imageUploadBusy = computed(() => imageUploadProgress.visible);
|
||||
|
||||
function hydrateForm(): void {
|
||||
form.name = props.task?.name ?? "";
|
||||
form.promptRuleId = props.task?.prompt_rule_id ?? undefined;
|
||||
form.platformIds = parseTargetPlatforms(props.task?.target_platform);
|
||||
form.coverEnabled = true;
|
||||
form.autoPublish = isSchedule.value ? Boolean(props.task?.auto_publish) : false;
|
||||
form.publishAccountIds = isSchedule.value ? [...(props.task?.publish_account_ids ?? [])] : [];
|
||||
form.coverAssetUrl = isSchedule.value ? resolveApiURL(props.task?.cover_asset_url) : "";
|
||||
form.coverFileName = deriveCoverFileName(form.coverAssetUrl);
|
||||
form.coverImageAssetId = isSchedule.value ? props.task?.cover_image_asset_id ?? null : null;
|
||||
form.coverEnabled = Boolean(form.coverAssetUrl);
|
||||
form.enableWebSearch = props.task?.enable_web_search ?? false;
|
||||
form.generateCount = props.task?.generate_count ?? 1;
|
||||
form.scheduleTime = parseCronToDailyTime(props.task?.cron_expr);
|
||||
resetCoverState();
|
||||
}
|
||||
|
||||
function getSelectedPlatformIds(): string[] {
|
||||
return normalizePublishPlatformIds(form.platformIds);
|
||||
}
|
||||
|
||||
function buildSchedulePayload() {
|
||||
const coverEnabled = form.autoPublish && effectiveScheduleCoverEnabled.value;
|
||||
const coverAssetUrl = coverEnabled ? form.coverAssetUrl.trim() : "";
|
||||
|
||||
return {
|
||||
name: form.name.trim(),
|
||||
prompt_rule_id: form.promptRuleId!,
|
||||
cron_expr: buildDailyCron(form.scheduleTime),
|
||||
target_platform: serializeTargetPlatforms(getSelectedPlatformIds()),
|
||||
auto_publish: form.autoPublish,
|
||||
publish_account_ids: form.autoPublish ? form.publishAccountIds : [],
|
||||
cover_asset_url: coverAssetUrl || null,
|
||||
cover_image_asset_id: coverAssetUrl ? form.coverImageAssetId : null,
|
||||
enable_web_search: form.enableWebSearch,
|
||||
generate_count: form.generateCount,
|
||||
};
|
||||
}
|
||||
|
||||
function buildInstantPayload() {
|
||||
const platformIds = getSelectedPlatformIds();
|
||||
|
||||
return {
|
||||
prompt_rule_id: form.promptRuleId!,
|
||||
target_platform: serializeTargetPlatforms(platformIds),
|
||||
extra_params: {
|
||||
task_name: form.name.trim(),
|
||||
generation_mode: "instant",
|
||||
enable_web_search: form.enableWebSearch,
|
||||
generate_count: form.generateCount,
|
||||
target_platforms: platformIds,
|
||||
cover_file_name: coverFileName.value || null,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function resetCoverState(): void {
|
||||
if (coverPreviewUrl.value) {
|
||||
URL.revokeObjectURL(coverPreviewUrl.value);
|
||||
}
|
||||
coverPreviewUrl.value = "";
|
||||
coverFileName.value = "";
|
||||
}
|
||||
|
||||
function handleCoverChange(event: Event): void {
|
||||
if (imageUploadBusy.value) {
|
||||
(event.target as HTMLInputElement).value = "";
|
||||
return;
|
||||
}
|
||||
|
||||
const input = event.target as HTMLInputElement;
|
||||
const file = input.files?.[0];
|
||||
input.value = "";
|
||||
|
||||
if (!file) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
validateImageUploadFile(file);
|
||||
} catch (error) {
|
||||
message.warning(formatError(error));
|
||||
return;
|
||||
}
|
||||
|
||||
if (coverPreviewUrl.value) {
|
||||
URL.revokeObjectURL(coverPreviewUrl.value);
|
||||
}
|
||||
|
||||
coverFileName.value = file.name;
|
||||
coverPreviewUrl.value = URL.createObjectURL(file);
|
||||
}
|
||||
|
||||
function handlePromptSaved(ruleId: number): void {
|
||||
form.promptRuleId = ruleId;
|
||||
promptDrawerOpen.value = false;
|
||||
void queryClient.invalidateQueries({ queryKey: ["promptRules", "simple"] });
|
||||
}
|
||||
|
||||
function toggleSchedulePublishAccount(account: PublishAccountCard): void {
|
||||
if (!account.selectable) {
|
||||
return;
|
||||
}
|
||||
if (form.publishAccountIds.includes(account.id)) {
|
||||
form.publishAccountIds = form.publishAccountIds.filter((id) => id !== account.id);
|
||||
return;
|
||||
}
|
||||
form.publishAccountIds = [...form.publishAccountIds, account.id];
|
||||
}
|
||||
|
||||
function isSchedulePublishAccountSelected(accountId: string): boolean {
|
||||
return form.publishAccountIds.includes(accountId);
|
||||
}
|
||||
|
||||
async function uploadScheduleCover(file: File): Promise<{ url: string; fileName: string; assetId?: number | null }> {
|
||||
const uploaded = await imagesApi.upload(file);
|
||||
return {
|
||||
url: uploaded.url,
|
||||
fileName: uploaded.name,
|
||||
assetId: uploaded.id,
|
||||
};
|
||||
}
|
||||
|
||||
function handleScheduleCoverPicked(payload: { url: string; fileName: string; assetId?: number | null }): void {
|
||||
form.coverAssetUrl = payload.url;
|
||||
form.coverFileName = payload.fileName;
|
||||
form.coverImageAssetId = payload.assetId ?? null;
|
||||
form.coverEnabled = true;
|
||||
}
|
||||
|
||||
function handleRemoveScheduleCover(): void {
|
||||
form.coverAssetUrl = "";
|
||||
form.coverFileName = "";
|
||||
form.coverImageAssetId = null;
|
||||
}
|
||||
|
||||
function handleScheduleCoverToggle(checked: boolean): void {
|
||||
if (scheduleCoverRequired.value) {
|
||||
form.coverEnabled = true;
|
||||
return;
|
||||
}
|
||||
form.coverEnabled = checked;
|
||||
}
|
||||
|
||||
function validateForm(): boolean {
|
||||
if (!form.name.trim()) {
|
||||
message.warning(t("custom.messages.missingTaskName"));
|
||||
@@ -260,6 +291,17 @@ function validateForm(): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (isSchedule.value && form.autoPublish) {
|
||||
if (form.publishAccountIds.length === 0) {
|
||||
message.warning(t("custom.messages.missingPublishAccounts"));
|
||||
return false;
|
||||
}
|
||||
if (scheduleCoverRequired.value && !form.coverAssetUrl.trim()) {
|
||||
message.warning(t("custom.messages.missingScheduleCover"));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -368,48 +410,123 @@ function padTime(value: string): string {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="generate-task-drawer__field">
|
||||
<label class="generate-task-drawer__label">{{ t("custom.task.platforms") }}:</label>
|
||||
<p class="generate-task-drawer__hint">{{ t("custom.task.platformsHint") }}</p>
|
||||
<a-skeleton
|
||||
v-if="platformsLoading"
|
||||
active
|
||||
:title="false"
|
||||
:paragraph="{ rows: 4 }"
|
||||
/>
|
||||
<PublishPlatformSelector
|
||||
v-else
|
||||
v-model="form.platformIds"
|
||||
:platforms="allPlatforms"
|
||||
/>
|
||||
</section>
|
||||
|
||||
<section v-if="isSchedule" class="generate-task-drawer__panel generate-task-drawer__panel--bordered">
|
||||
<div class="generate-task-drawer__section-head">
|
||||
<div class="generate-task-drawer__section-marker"></div>
|
||||
<h3>{{ t("custom.task.publishSection") }}</h3>
|
||||
</div>
|
||||
|
||||
<div class="generate-task-drawer__field">
|
||||
<label class="generate-task-drawer__label">{{ t("custom.task.cover") }}:</label>
|
||||
<p class="generate-task-drawer__hint">{{ t("custom.task.coverHint") }}</p>
|
||||
<div class="generate-task-drawer__field generate-task-drawer__field--inline">
|
||||
<div>
|
||||
<label class="generate-task-drawer__label">{{ t("custom.task.autoPublish") }}:</label>
|
||||
<p class="generate-task-drawer__hint generate-task-drawer__hint--compact">
|
||||
{{ t("custom.task.autoPublishHint") }}
|
||||
</p>
|
||||
</div>
|
||||
<a-switch v-model:checked="form.autoPublish" />
|
||||
</div>
|
||||
|
||||
<label
|
||||
class="generate-task-drawer__cover"
|
||||
:class="{ 'generate-task-drawer__cover--disabled': !form.coverEnabled || imageUploadBusy }"
|
||||
>
|
||||
<input
|
||||
type="file"
|
||||
:accept="IMAGE_UPLOAD_ACCEPT"
|
||||
hidden
|
||||
:disabled="!form.coverEnabled || imageUploadBusy"
|
||||
@change="handleCoverChange"
|
||||
<template v-if="form.autoPublish">
|
||||
<div class="generate-task-drawer__field">
|
||||
<label class="generate-task-drawer__label generate-task-drawer__label--required">
|
||||
{{ t("custom.task.publishAccounts") }}:
|
||||
</label>
|
||||
<p class="generate-task-drawer__hint">{{ t("custom.task.publishAccountsHint") }}</p>
|
||||
|
||||
<a-skeleton
|
||||
v-if="schedulePublishLoading"
|
||||
active
|
||||
:title="false"
|
||||
:paragraph="{ rows: 4 }"
|
||||
/>
|
||||
<div v-else-if="schedulePublishAccounts.length" class="generate-task-drawer__account-grid">
|
||||
<button
|
||||
v-for="account in schedulePublishAccounts"
|
||||
:key="account.id"
|
||||
type="button"
|
||||
class="generate-task-drawer__account"
|
||||
:class="{
|
||||
'generate-task-drawer__account--active': isSchedulePublishAccountSelected(account.id),
|
||||
'generate-task-drawer__account--disabled': !account.selectable,
|
||||
}"
|
||||
@click="toggleSchedulePublishAccount(account)"
|
||||
>
|
||||
<span class="generate-task-drawer__account-check">
|
||||
<span v-if="isSchedulePublishAccountSelected(account.id)"></span>
|
||||
</span>
|
||||
<span class="generate-task-drawer__account-logo" :style="{ '--account-accent': account.platformAccent }">
|
||||
<img
|
||||
v-if="account.platformLogoUrl"
|
||||
:src="account.platformLogoUrl"
|
||||
:alt="account.platformName"
|
||||
referrerpolicy="no-referrer"
|
||||
/>
|
||||
<span v-else>{{ account.platformShortName }}</span>
|
||||
</span>
|
||||
<span class="generate-task-drawer__account-copy">
|
||||
<strong>{{ account.displayName }}</strong>
|
||||
<small>{{ account.platformName }} · {{ account.platformUid }}</small>
|
||||
</span>
|
||||
<a-tooltip :title="account.statusText" placement="top">
|
||||
<span
|
||||
class="generate-task-drawer__account-status"
|
||||
:class="`generate-task-drawer__account-status--${account.publishState}`"
|
||||
>
|
||||
{{ publishStatusShortLabel(account.publishState) }}
|
||||
</span>
|
||||
</a-tooltip>
|
||||
</button>
|
||||
</div>
|
||||
<div v-else class="generate-task-drawer__empty">
|
||||
<strong>{{ t("custom.task.publishAccountEmptyTitle") }}</strong>
|
||||
<p>{{ t("custom.task.publishAccountEmptyHint") }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<template v-if="coverPreviewUrl">
|
||||
<img :src="coverPreviewUrl" alt="cover preview" />
|
||||
</template>
|
||||
<template v-else>
|
||||
<span class="generate-task-drawer__cover-plus">+</span>
|
||||
<strong>{{ t("custom.task.coverUpload") }}</strong>
|
||||
<small>{{ coverFileName || t("custom.task.coverUploadHint") }}</small>
|
||||
</template>
|
||||
</label>
|
||||
</div>
|
||||
<div class="generate-task-drawer__field">
|
||||
<div class="generate-task-drawer__cover-head">
|
||||
<label
|
||||
class="generate-task-drawer__label"
|
||||
:class="{ 'generate-task-drawer__label--required': scheduleCoverRequired }"
|
||||
>
|
||||
{{ t("custom.task.cover") }}:
|
||||
</label>
|
||||
<a-switch
|
||||
:checked="effectiveScheduleCoverEnabled"
|
||||
:disabled="scheduleCoverRequired"
|
||||
@change="handleScheduleCoverToggle"
|
||||
/>
|
||||
</div>
|
||||
<p class="generate-task-drawer__hint">
|
||||
{{ scheduleCoverRequired ? t("custom.task.scheduleCoverRequiredHint") : t("custom.task.scheduleCoverHint") }}
|
||||
</p>
|
||||
|
||||
<div v-if="effectiveScheduleCoverEnabled" class="generate-task-drawer__cover-row">
|
||||
<button type="button" class="generate-task-drawer__cover" @click="coverPickerOpen = true">
|
||||
<template v-if="form.coverAssetUrl">
|
||||
<img :src="form.coverAssetUrl" alt="cover preview" />
|
||||
</template>
|
||||
<template v-else>
|
||||
<span class="generate-task-drawer__cover-plus">+</span>
|
||||
<strong>{{ t("custom.task.coverUpload") }}</strong>
|
||||
<small>{{ t("custom.task.scheduleCoverUploadHint") }}</small>
|
||||
</template>
|
||||
</button>
|
||||
|
||||
<div v-if="form.coverAssetUrl" class="generate-task-drawer__cover-meta">
|
||||
<strong>{{ form.coverFileName || t("custom.task.cover") }}</strong>
|
||||
<a-button size="small" @click="coverPickerOpen = true">
|
||||
{{ t("article.editor.coverReplace") }}
|
||||
</a-button>
|
||||
<a-button size="small" danger @click="handleRemoveScheduleCover">
|
||||
{{ t("article.editor.coverRemove") }}
|
||||
</a-button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
</section>
|
||||
|
||||
<section class="generate-task-drawer__panel generate-task-drawer__panel--bordered">
|
||||
@@ -462,6 +579,17 @@ function padTime(value: string): string {
|
||||
</template>
|
||||
|
||||
<PromptRuleModal v-model:open="promptDrawerOpen" @saved="handlePromptSaved" />
|
||||
|
||||
<CoverPickerModal
|
||||
v-model:open="coverPickerOpen"
|
||||
:article-id="null"
|
||||
:platform-ids="selectedSchedulePublishPlatformIds"
|
||||
:current-url="form.coverAssetUrl"
|
||||
:current-file-name="form.coverFileName"
|
||||
:current-asset-id="form.coverImageAssetId"
|
||||
:upload-handler="uploadScheduleCover"
|
||||
@confirmed="handleScheduleCoverPicked"
|
||||
/>
|
||||
</a-drawer>
|
||||
</template>
|
||||
|
||||
@@ -581,6 +709,179 @@ function padTime(value: string): string {
|
||||
color: #355dff;
|
||||
}
|
||||
|
||||
.generate-task-drawer__account-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.generate-task-drawer__account {
|
||||
display: grid;
|
||||
grid-template-columns: 20px 36px minmax(0, 1fr);
|
||||
gap: 12px;
|
||||
align-items: center;
|
||||
min-height: 76px;
|
||||
padding: 12px 14px;
|
||||
border: 1px solid #e1e8f2;
|
||||
border-radius: 8px;
|
||||
background: #fff;
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
transition: border-color 0.2s ease, background 0.2s ease, box-shadow 0.2s ease;
|
||||
}
|
||||
|
||||
.generate-task-drawer__account:hover {
|
||||
border-color: #b7c7ec;
|
||||
background: #fbfdff;
|
||||
}
|
||||
|
||||
.generate-task-drawer__account--active {
|
||||
border-color: #355dff;
|
||||
background: #f4f7ff;
|
||||
box-shadow: 0 4px 12px rgba(53, 93, 255, 0.08);
|
||||
}
|
||||
|
||||
.generate-task-drawer__account--disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.55;
|
||||
}
|
||||
|
||||
.generate-task-drawer__account-check {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 18px;
|
||||
height: 18px;
|
||||
border: 1px solid #d0d7e5;
|
||||
border-radius: 4px;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.generate-task-drawer__account--active .generate-task-drawer__account-check {
|
||||
border-color: #355dff;
|
||||
background: #355dff;
|
||||
}
|
||||
|
||||
.generate-task-drawer__account-check span {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
border-radius: 1px;
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.generate-task-drawer__account-logo {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
border-radius: 8px;
|
||||
border: 1px solid #e4e9f2;
|
||||
background: #fff;
|
||||
color: var(--account-accent);
|
||||
font-size: 12px;
|
||||
font-weight: 800;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.generate-task-drawer__account-logo img {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
.generate-task-drawer__account-logo span {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
background: color-mix(in srgb, var(--account-accent) 10%, #ffffff);
|
||||
}
|
||||
|
||||
.generate-task-drawer__account-copy {
|
||||
display: flex;
|
||||
min-width: 0;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.generate-task-drawer__account-copy strong,
|
||||
.generate-task-drawer__cover-meta strong {
|
||||
overflow: hidden;
|
||||
color: #1f2937;
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.generate-task-drawer__account-copy small,
|
||||
.generate-task-drawer__account-status {
|
||||
overflow: hidden;
|
||||
color: #667085;
|
||||
font-size: 12px;
|
||||
line-height: 1.4;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.generate-task-drawer__account-status {
|
||||
grid-column: 3;
|
||||
color: #355dff;
|
||||
}
|
||||
|
||||
.generate-task-drawer__account-status--immediate {
|
||||
color: #039855;
|
||||
}
|
||||
|
||||
.generate-task-drawer__account-status--queued {
|
||||
color: #dc6803;
|
||||
}
|
||||
|
||||
.generate-task-drawer__account-status--unavailable {
|
||||
color: #d92d20;
|
||||
}
|
||||
|
||||
.generate-task-drawer__cover-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.generate-task-drawer__cover-head .generate-task-drawer__label {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.generate-task-drawer__empty {
|
||||
padding: 18px 20px;
|
||||
border: 1px dashed #cfd9e8;
|
||||
border-radius: 8px;
|
||||
background: #fbfcff;
|
||||
}
|
||||
|
||||
.generate-task-drawer__empty strong {
|
||||
display: block;
|
||||
color: #1f2937;
|
||||
font-size: 15px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.generate-task-drawer__empty p {
|
||||
margin: 6px 0 0;
|
||||
color: #667085;
|
||||
font-size: 13px;
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
.generate-task-drawer__cover-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 16px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.generate-task-drawer__cover {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
@@ -589,16 +890,20 @@ function padTime(value: string): string {
|
||||
gap: 8px;
|
||||
width: 228px;
|
||||
min-height: 172px;
|
||||
padding: 0;
|
||||
border: 1px dashed #cfd9e8;
|
||||
border-radius: 20px;
|
||||
background:
|
||||
radial-gradient(circle at top, rgba(53, 93, 255, 0.08), transparent 48%),
|
||||
#fbfcff;
|
||||
border-radius: 8px;
|
||||
background: #fbfcff;
|
||||
color: #1f2937;
|
||||
cursor: pointer;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.generate-task-drawer__cover:hover {
|
||||
border-color: #9db7ff;
|
||||
background: #f7faff;
|
||||
}
|
||||
|
||||
.generate-task-drawer__cover img {
|
||||
width: 100%;
|
||||
height: 172px;
|
||||
@@ -615,11 +920,6 @@ function padTime(value: string): string {
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.generate-task-drawer__cover--disabled {
|
||||
opacity: 0.55;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.generate-task-drawer__cover-plus {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
@@ -633,6 +933,15 @@ function padTime(value: string): string {
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.generate-task-drawer__cover-meta {
|
||||
display: flex;
|
||||
min-width: 220px;
|
||||
max-width: 360px;
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.generate-task-drawer__time-wrapper {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
@@ -2,61 +2,29 @@
|
||||
import { MinusCircleFilled } from "@ant-design/icons-vue";
|
||||
import { useMutation, useQuery, useQueryClient } from "@tanstack/vue-query";
|
||||
import { message, notification } from "ant-design-vue";
|
||||
import type { ArticleDetail, DesktopAccountInfo, MediaPlatform } from "@geo/shared-types";
|
||||
import type { ArticleDetail } from "@geo/shared-types";
|
||||
import { computed, ref, watch, watchEffect } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
|
||||
import CoverPickerModal from "@/components/CoverPickerModal.vue";
|
||||
import { articlesApi, mediaApi, publishJobsApi, resolveApiURL, tenantAccountsApi } from "@/lib/api";
|
||||
import { coverUploadRequired, deriveCoverFileName } from "@/lib/cover-requirements";
|
||||
import { resolveAccountCheckedAt, resolveAccountHealth } from "@/lib/desktop-account-runtime";
|
||||
import { formatError } from "@/lib/errors";
|
||||
import {
|
||||
getPublishPlatformMeta,
|
||||
isPublishPlatformId,
|
||||
normalizePublishPlatformId,
|
||||
accountInitial,
|
||||
buildPublishAccountCards,
|
||||
buildPublishPlatformMap,
|
||||
clientStatusColor,
|
||||
clientStatusLabel,
|
||||
healthColor,
|
||||
healthLabel,
|
||||
publishStateLabel,
|
||||
type PublishAccountCard,
|
||||
} from "@/lib/publish-account-cards";
|
||||
import {
|
||||
normalizePublishPlatformIds,
|
||||
} from "@/lib/publish-platforms";
|
||||
|
||||
type PublishState = "immediate" | "queued" | "unavailable";
|
||||
|
||||
const platformLogoCatalog: Record<string, string> = {
|
||||
toutiaohao: "/logos/logo_toutiao.png",
|
||||
baijiahao: "/logos/logo_baijiahao.png",
|
||||
sohuhao: "/logos/logo_souhu.png",
|
||||
qiehao: "/logos/logo_qiehao.png",
|
||||
zhihu: "/logos/logo_zhihu.png",
|
||||
wangyihao: "/logos/logo_wangyihao.png",
|
||||
jianshu: "/logos/logo_jianshu.svg",
|
||||
bilibili: "/logos/logo_bilibili.png",
|
||||
juejin: "/logos/logo_juejin.png",
|
||||
smzdm: "/logos/logo_smzdm.svg",
|
||||
weixin_gzh: "/logos/logo_weixin_gzh.svg",
|
||||
zol: "/logos/logo_zol.png",
|
||||
dongchedi: "/logos/logo_dongchedi.svg",
|
||||
};
|
||||
|
||||
interface PublishAccountCard {
|
||||
id: string;
|
||||
platformId: string;
|
||||
platformName: string;
|
||||
platformShortName: string;
|
||||
platformAccent: string;
|
||||
platformLogoUrl: string | null;
|
||||
displayName: string;
|
||||
platformUid: string;
|
||||
avatarUrl: string | null;
|
||||
health: DesktopAccountInfo["health"];
|
||||
verifiedAt: string | null;
|
||||
clientId: string | null;
|
||||
clientOnline: boolean | null;
|
||||
clientDeviceName: string | null;
|
||||
clientLastSeenAt: string | null;
|
||||
publishState: PublishState;
|
||||
selectable: boolean;
|
||||
statusText: string;
|
||||
}
|
||||
|
||||
const props = defineProps<{
|
||||
open: boolean;
|
||||
articleId: number | null;
|
||||
@@ -123,77 +91,13 @@ watch(
|
||||
{ immediate: true },
|
||||
);
|
||||
|
||||
const platformMap = computed<Map<string, MediaPlatform>>(() => {
|
||||
return new Map(
|
||||
(platformsQuery.data.value ?? []).map((platform: MediaPlatform) => [
|
||||
normalizePublishPlatformId(platform.platform_id),
|
||||
platform,
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
const publishAccounts = computed(() => {
|
||||
return (accountsQuery.data.value ?? []).filter((account) => {
|
||||
if (account.deleted_at) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const platformId = normalizePublishPlatformId(account.platform);
|
||||
return platformMap.value.has(platformId) || isPublishPlatformId(platformId);
|
||||
});
|
||||
});
|
||||
const platformMap = computed(() => buildPublishPlatformMap(platformsQuery.data.value ?? []));
|
||||
|
||||
const articlePlatformIds = computed(() => normalizePublishPlatformIds(detailQuery.data.value?.platforms ?? []));
|
||||
|
||||
const accountCards = computed<PublishAccountCard[]>(() => {
|
||||
const preferredPlatforms = new Set(articlePlatformIds.value);
|
||||
|
||||
return [...publishAccounts.value]
|
||||
.map((account) => {
|
||||
const platformId = normalizePublishPlatformId(account.platform);
|
||||
const platform = platformMap.value.get(platformId);
|
||||
const fallback = getPublishPlatformMeta(platformId);
|
||||
const publishState = resolvePublishState(account);
|
||||
const health = resolveAccountHealth(account);
|
||||
|
||||
return {
|
||||
id: account.id,
|
||||
platformId,
|
||||
platformName: platform?.name || fallback.name,
|
||||
platformShortName: platform?.short_name || fallback.shortName,
|
||||
platformAccent: platform?.accent_color || fallback.accent,
|
||||
platformLogoUrl: resolvePlatformLogoUrl(platformId, platform?.logo_url),
|
||||
displayName: account.display_name,
|
||||
platformUid: normalizePlatformUid(account.platform_uid),
|
||||
avatarUrl: resolveApiURL(account.avatar_url),
|
||||
health,
|
||||
verifiedAt: resolveAccountCheckedAt(account),
|
||||
clientId: account.client_id,
|
||||
clientOnline: account.client_online,
|
||||
clientDeviceName: account.client_device_name,
|
||||
clientLastSeenAt: account.client_last_seen_at,
|
||||
publishState,
|
||||
selectable: publishState !== "unavailable",
|
||||
statusText: resolveStatusText(account, publishState),
|
||||
};
|
||||
})
|
||||
.sort((left, right) => {
|
||||
const preferredGap =
|
||||
Number(preferredPlatforms.has(right.platformId)) - Number(preferredPlatforms.has(left.platformId));
|
||||
if (preferredGap !== 0) {
|
||||
return preferredGap;
|
||||
}
|
||||
|
||||
const publishGap = publishRank(left.publishState) - publishRank(right.publishState);
|
||||
if (publishGap !== 0) {
|
||||
return publishGap;
|
||||
}
|
||||
|
||||
const leftVerifiedAt = Date.parse(left.verifiedAt ?? "") || 0;
|
||||
const rightVerifiedAt = Date.parse(right.verifiedAt ?? "") || 0;
|
||||
return rightVerifiedAt - leftVerifiedAt;
|
||||
});
|
||||
});
|
||||
const accountCards = computed<PublishAccountCard[]>(() =>
|
||||
buildPublishAccountCards(accountsQuery.data.value ?? [], platformMap.value, articlePlatformIds.value),
|
||||
);
|
||||
|
||||
watch(
|
||||
accountCards,
|
||||
@@ -391,112 +295,6 @@ function handleRemoveCover(): void {
|
||||
coverImageAssetId.value = null;
|
||||
}
|
||||
|
||||
function resolvePublishState(account: DesktopAccountInfo): PublishState {
|
||||
if (resolveAccountHealth(account) !== "live") {
|
||||
return "unavailable";
|
||||
}
|
||||
if (!account.client_id) {
|
||||
return "unavailable";
|
||||
}
|
||||
return account.client_online === true ? "immediate" : "queued";
|
||||
}
|
||||
|
||||
function resolveStatusText(account: DesktopAccountInfo, publishState: PublishState): string {
|
||||
if (publishState === "immediate") {
|
||||
return "客户端在线,RabbitMQ 会立即唤醒桌面端开始发布。";
|
||||
}
|
||||
if (publishState === "queued") {
|
||||
return "客户端当前离线,任务会先落库排队,等桌面端上线后自动继续发布。";
|
||||
}
|
||||
if (resolveAccountHealth(account) !== "live") {
|
||||
return "该账号授权状态异常,请先在桌面端重新校验或重新授权。";
|
||||
}
|
||||
return "该账号还没有绑定桌面客户端,当前不能进入发布队列。";
|
||||
}
|
||||
|
||||
function publishRank(state: PublishState): number {
|
||||
switch (state) {
|
||||
case "immediate":
|
||||
return 0;
|
||||
case "queued":
|
||||
return 1;
|
||||
default:
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
|
||||
function publishStateLabel(state: PublishState): string {
|
||||
switch (state) {
|
||||
case "immediate":
|
||||
return "立即发布";
|
||||
case "queued":
|
||||
return "离线排队";
|
||||
default:
|
||||
return "不可发布";
|
||||
}
|
||||
}
|
||||
|
||||
function healthLabel(health: DesktopAccountInfo["health"]): string {
|
||||
switch (health) {
|
||||
case "live":
|
||||
return "授权正常";
|
||||
case "captcha":
|
||||
return "待处理";
|
||||
case "risk":
|
||||
return "风险观察";
|
||||
default:
|
||||
return "授权异常";
|
||||
}
|
||||
}
|
||||
|
||||
function healthColor(health: DesktopAccountInfo["health"]): string {
|
||||
switch (health) {
|
||||
case "live":
|
||||
return "green";
|
||||
case "captcha":
|
||||
return "orange";
|
||||
case "risk":
|
||||
return "gold";
|
||||
default:
|
||||
return "red";
|
||||
}
|
||||
}
|
||||
|
||||
function clientStatusLabel(card: PublishAccountCard): string {
|
||||
if (!card.clientId) {
|
||||
return "未绑定客户端";
|
||||
}
|
||||
return card.clientOnline ? "客户端在线" : "客户端离线";
|
||||
}
|
||||
|
||||
function clientStatusColor(card: PublishAccountCard): string {
|
||||
if (!card.clientId) {
|
||||
return "default";
|
||||
}
|
||||
return card.clientOnline ? "green" : "gold";
|
||||
}
|
||||
|
||||
function accountInitial(card: PublishAccountCard): string {
|
||||
const trimmed = card.displayName.trim();
|
||||
return trimmed ? trimmed.slice(0, 1).toUpperCase() : card.platformShortName;
|
||||
}
|
||||
|
||||
function resolvePlatformLogoUrl(platformId: string, remoteLogoUrl?: string | null): string | null {
|
||||
const localLogoUrl = platformLogoCatalog[platformId];
|
||||
if (localLogoUrl) {
|
||||
return localLogoUrl;
|
||||
}
|
||||
const resolvedRemoteLogoUrl = resolveApiURL(remoteLogoUrl);
|
||||
return resolvedRemoteLogoUrl || null;
|
||||
}
|
||||
|
||||
function normalizePlatformUid(value?: string | null): string {
|
||||
let normalized = String(value ?? "").trim();
|
||||
while (normalized.toLowerCase().startsWith("platform:")) {
|
||||
normalized = normalized.slice("platform:".length).trim();
|
||||
}
|
||||
return normalized || "--";
|
||||
}
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -16,7 +16,6 @@ import ScheduleTaskModal from "@/components/ScheduleTaskModal.vue";
|
||||
import { promptRulesApi, schedulesApi } from "@/lib/api";
|
||||
import { formatCronExecutionTime, formatDateTime } from "@/lib/display";
|
||||
import { formatError } from "@/lib/errors";
|
||||
import { formatPublishPlatformSummary } from "@/lib/publish-platforms";
|
||||
|
||||
const queryClient = useQueryClient();
|
||||
const { t } = useI18n();
|
||||
@@ -85,7 +84,7 @@ const columns = computed<TableColumnsType<ScheduleTask>>(() => [
|
||||
{ title: t("custom.schedule.rule"), dataIndex: "prompt_rule_name", key: "prompt_rule_name", width: 180 },
|
||||
{ title: t("custom.instant.executionStatus"), dataIndex: "status", key: "status", width: 140 },
|
||||
{ title: t("custom.instant.executionTime"), dataIndex: "cron_expr", key: "cron_expr", width: 170 },
|
||||
{ title: t("custom.schedule.platform"), dataIndex: "target_platform", key: "target_platform", width: 220 },
|
||||
{ title: t("custom.schedule.autoPublish"), dataIndex: "auto_publish", key: "auto_publish", width: 160 },
|
||||
{ title: t("custom.task.generateCount"), dataIndex: "generate_count", key: "generate_count", width: 120 },
|
||||
{ title: t("custom.instant.createdTime"), dataIndex: "created_at", key: "created_at", width: 170 },
|
||||
{ title: t("common.actions"), key: "actions", width: 140, fixed: "right", align: "right" },
|
||||
@@ -223,8 +222,14 @@ function handleTableChange(nextPage: number, nextPageSize: number): void {
|
||||
<template v-else-if="column.key === 'cron_expr'">
|
||||
{{ formatCronExecutionTime(record.cron_expr) }}
|
||||
</template>
|
||||
<template v-else-if="column.key === 'target_platform'">
|
||||
{{ formatPublishPlatformSummary(record.target_platform) }}
|
||||
<template v-else-if="column.key === 'auto_publish'">
|
||||
<a-tag :color="record.auto_publish ? 'blue' : 'default'">
|
||||
{{
|
||||
record.auto_publish
|
||||
? t("custom.schedule.autoPublishAccountCount", { count: record.publish_account_ids?.length ?? 0 })
|
||||
: t("custom.schedule.manualPublish")
|
||||
}}
|
||||
</a-tag>
|
||||
</template>
|
||||
<template v-else-if="column.key === 'generate_count'">
|
||||
{{ record.generate_count || 1 }}
|
||||
|
||||
@@ -1254,10 +1254,20 @@ const enUS = {
|
||||
platformUnauthorized: "Unauthorized",
|
||||
platformEmptyTitle: "No publish platforms",
|
||||
platformEmptyHint: "No platform data is available yet. Please verify the Media Management setup first.",
|
||||
publishSection: "Publish Settings",
|
||||
autoPublish: "Auto publish",
|
||||
autoPublishHint: "When enabled, scheduled articles enter the publish queue after generation.",
|
||||
publishAccounts: "Media accounts",
|
||||
publishAccountsHint: "Choose specific accounts. Offline clients queue first and continue after reconnecting.",
|
||||
publishAccountEmptyTitle: "No media accounts",
|
||||
publishAccountEmptyHint: "Bind media accounts in the desktop client before configuring auto publish.",
|
||||
cover: "Cover image",
|
||||
coverHint: "Keep the cover clear, complete, and visually polished.",
|
||||
scheduleCoverHint: "Cover is off by default. Enable it to save a cover to generated articles for publishing.",
|
||||
scheduleCoverRequiredHint: "A selected account platform requires a cover image before publishing.",
|
||||
coverUpload: "Upload cover image",
|
||||
coverUploadHint: "Local preview only for now",
|
||||
scheduleCoverUploadHint: "Choose from local files or the asset library",
|
||||
scheduleTime: "Schedule article generation",
|
||||
scheduleEveryDay: "Every day",
|
||||
enableWebSearch: "Enable web search for generation",
|
||||
@@ -1276,7 +1286,9 @@ const enUS = {
|
||||
name: "Task name",
|
||||
rule: "Prompt rule",
|
||||
cron: "Frequency",
|
||||
platform: "Target platform",
|
||||
autoPublish: "Auto publish",
|
||||
manualPublish: "Manual publish",
|
||||
autoPublishAccountCount: "Auto · {count} accounts",
|
||||
nextRun: "Next run",
|
||||
startAt: "Start time",
|
||||
endAt: "End time",
|
||||
@@ -1341,6 +1353,8 @@ const enUS = {
|
||||
missingPromptRule: "Choose a prompt first.",
|
||||
invalidGenerateCount: "Article count must be at least 1.",
|
||||
invalidScheduleTime: "Choose a valid schedule time.",
|
||||
missingPublishAccounts: "Choose at least one media account when auto publish is enabled.",
|
||||
missingScheduleCover: "A selected media account platform requires a cover image.",
|
||||
missingPromptName: "Enter a prompt name first.",
|
||||
missingPromptContent: "Enter prompt content first.",
|
||||
},
|
||||
|
||||
@@ -91,6 +91,7 @@ const zhCN = {
|
||||
},
|
||||
auth: {
|
||||
welcomeBack: "欢迎回来",
|
||||
tenantAdminLogin: "租户后台登录",
|
||||
loginAndEnter: "登录并进入工作台",
|
||||
email: "邮箱",
|
||||
loginIdentifier: "手机号 / 邮箱",
|
||||
@@ -597,7 +598,7 @@ const zhCN = {
|
||||
publishing: "发布中",
|
||||
success: "发布成功",
|
||||
failed: "发布失败",
|
||||
partial_success: "部分成功",
|
||||
partial_success: "部分发布",
|
||||
published: "发布成功",
|
||||
publish_success: "发布成功",
|
||||
publish_failed: "发布失败",
|
||||
@@ -1263,10 +1264,20 @@ const zhCN = {
|
||||
platformUnauthorized: "未授权",
|
||||
platformEmptyTitle: "暂无发布平台",
|
||||
platformEmptyHint: "当前还没有可用的平台数据,请先检查媒体管理配置。",
|
||||
publishSection: "发布设置",
|
||||
autoPublish: "是否自动发布",
|
||||
autoPublishHint: "开启后,定时生成完成的文章会使用指定媒体账号自动进入发布队列。",
|
||||
publishAccounts: "媒体账号",
|
||||
publishAccountsHint: "请选择具体账号。客户端离线时会先排队,上线后继续发布。",
|
||||
publishAccountEmptyTitle: "暂无可选媒体账号",
|
||||
publishAccountEmptyHint: "请先在桌面端绑定媒体账号,再回到这里配置自动发布。",
|
||||
cover: "封面图",
|
||||
coverHint: "请保证封面清晰、美观和完整",
|
||||
scheduleCoverHint: "默认不设置封面。需要时可单独指定,生成完成后会写入文章并用于发布。",
|
||||
scheduleCoverRequiredHint: "已选账号的平台要求发布封面,请先选择封面图。",
|
||||
coverUpload: "上传封面图",
|
||||
coverUploadHint: "当前仅做本地预览",
|
||||
scheduleCoverUploadHint: "从本地或素材库选择",
|
||||
scheduleTime: "定时生成文章",
|
||||
scheduleEveryDay: "每天",
|
||||
enableWebSearch: "生成文章联网搜索",
|
||||
@@ -1285,7 +1296,9 @@ const zhCN = {
|
||||
name: "任务名称",
|
||||
rule: "关联规则",
|
||||
cron: "执行频率",
|
||||
platform: "目标平台",
|
||||
autoPublish: "自动发布",
|
||||
manualPublish: "手动发布",
|
||||
autoPublishAccountCount: "自动 · {count} 个账号",
|
||||
nextRun: "下次执行",
|
||||
startAt: "开始时间",
|
||||
endAt: "结束时间",
|
||||
@@ -1350,6 +1363,8 @@ const zhCN = {
|
||||
missingPromptRule: "请先选择 Prompt",
|
||||
invalidGenerateCount: "生成篇数至少为 1",
|
||||
invalidScheduleTime: "请选择有效的定时时间",
|
||||
missingPublishAccounts: "开启自动发布后,请至少选择一个媒体账号",
|
||||
missingScheduleCover: "已选媒体账号的平台要求封面图,请先设置封面",
|
||||
missingPromptName: "请先填写 Prompt 名称",
|
||||
missingPromptContent: "请先填写 Prompt 内容",
|
||||
},
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
import type { DesktopAccountInfo, MediaPlatform } from "@geo/shared-types";
|
||||
|
||||
import { resolveApiURL } from "@/lib/api";
|
||||
import { resolveAccountCheckedAt, resolveAccountHealth } from "@/lib/desktop-account-runtime";
|
||||
import {
|
||||
getPublishPlatformMeta,
|
||||
isPublishPlatformId,
|
||||
normalizePublishPlatformId,
|
||||
} from "@/lib/publish-platforms";
|
||||
|
||||
export type PublishState = "immediate" | "queued" | "unavailable";
|
||||
|
||||
export interface PublishAccountCard {
|
||||
id: string;
|
||||
platformId: string;
|
||||
platformName: string;
|
||||
platformShortName: string;
|
||||
platformAccent: string;
|
||||
platformLogoUrl: string | null;
|
||||
displayName: string;
|
||||
platformUid: string;
|
||||
avatarUrl: string | null;
|
||||
health: DesktopAccountInfo["health"];
|
||||
verifiedAt: string | null;
|
||||
clientId: string | null;
|
||||
clientOnline: boolean | null;
|
||||
clientDeviceName: string | null;
|
||||
clientLastSeenAt: string | null;
|
||||
publishState: PublishState;
|
||||
selectable: boolean;
|
||||
statusText: string;
|
||||
}
|
||||
|
||||
const platformLogoCatalog: Record<string, string> = {
|
||||
toutiaohao: "/logos/logo_toutiao.png",
|
||||
baijiahao: "/logos/logo_baijiahao.png",
|
||||
sohuhao: "/logos/logo_souhu.png",
|
||||
qiehao: "/logos/logo_qiehao.png",
|
||||
zhihu: "/logos/logo_zhihu.png",
|
||||
wangyihao: "/logos/logo_wangyihao.png",
|
||||
jianshu: "/logos/logo_jianshu.svg",
|
||||
bilibili: "/logos/logo_bilibili.png",
|
||||
juejin: "/logos/logo_juejin.png",
|
||||
smzdm: "/logos/logo_smzdm.svg",
|
||||
weixin_gzh: "/logos/logo_weixin_gzh.svg",
|
||||
zol: "/logos/logo_zol.png",
|
||||
dongchedi: "/logos/logo_dongchedi.svg",
|
||||
};
|
||||
|
||||
export function buildPublishPlatformMap(platforms: MediaPlatform[]): Map<string, MediaPlatform> {
|
||||
return new Map(
|
||||
platforms.map((platform) => [
|
||||
normalizePublishPlatformId(platform.platform_id),
|
||||
platform,
|
||||
]),
|
||||
);
|
||||
}
|
||||
|
||||
export function buildPublishAccountCards(
|
||||
accounts: DesktopAccountInfo[],
|
||||
platformMap: Map<string, MediaPlatform>,
|
||||
preferredPlatformIds: string[] = [],
|
||||
): PublishAccountCard[] {
|
||||
const preferredPlatforms = new Set(preferredPlatformIds.map(normalizePublishPlatformId));
|
||||
|
||||
return accounts
|
||||
.filter((account) => {
|
||||
if (account.deleted_at) {
|
||||
return false;
|
||||
}
|
||||
const platformId = normalizePublishPlatformId(account.platform);
|
||||
return platformMap.has(platformId) || isPublishPlatformId(platformId);
|
||||
})
|
||||
.map((account) => buildPublishAccountCard(account, platformMap))
|
||||
.sort((left, right) => {
|
||||
const preferredGap =
|
||||
Number(preferredPlatforms.has(right.platformId)) - Number(preferredPlatforms.has(left.platformId));
|
||||
if (preferredGap !== 0) {
|
||||
return preferredGap;
|
||||
}
|
||||
|
||||
const publishGap = publishRank(left.publishState) - publishRank(right.publishState);
|
||||
if (publishGap !== 0) {
|
||||
return publishGap;
|
||||
}
|
||||
|
||||
const leftVerifiedAt = Date.parse(left.verifiedAt ?? "") || 0;
|
||||
const rightVerifiedAt = Date.parse(right.verifiedAt ?? "") || 0;
|
||||
return rightVerifiedAt - leftVerifiedAt;
|
||||
});
|
||||
}
|
||||
|
||||
export function buildPublishAccountCard(
|
||||
account: DesktopAccountInfo,
|
||||
platformMap: Map<string, MediaPlatform>,
|
||||
): PublishAccountCard {
|
||||
const platformId = normalizePublishPlatformId(account.platform);
|
||||
const platform = platformMap.get(platformId);
|
||||
const fallback = getPublishPlatformMeta(platformId);
|
||||
const publishState = resolvePublishState(account);
|
||||
const health = resolveAccountHealth(account);
|
||||
|
||||
return {
|
||||
id: account.id,
|
||||
platformId,
|
||||
platformName: platform?.name || fallback.name,
|
||||
platformShortName: platform?.short_name || fallback.shortName,
|
||||
platformAccent: platform?.accent_color || fallback.accent,
|
||||
platformLogoUrl: resolvePlatformLogoUrl(platformId, platform?.logo_url),
|
||||
displayName: account.display_name,
|
||||
platformUid: normalizePlatformUid(account.platform_uid),
|
||||
avatarUrl: resolveApiURL(account.avatar_url),
|
||||
health,
|
||||
verifiedAt: resolveAccountCheckedAt(account),
|
||||
clientId: account.client_id,
|
||||
clientOnline: account.client_online,
|
||||
clientDeviceName: account.client_device_name,
|
||||
clientLastSeenAt: account.client_last_seen_at,
|
||||
publishState,
|
||||
selectable: publishState !== "unavailable",
|
||||
statusText: resolvePublishStatusText(account, publishState),
|
||||
};
|
||||
}
|
||||
|
||||
export function resolvePublishState(account: DesktopAccountInfo): PublishState {
|
||||
if (resolveAccountHealth(account) !== "live") {
|
||||
return "unavailable";
|
||||
}
|
||||
if (!account.client_id) {
|
||||
return "unavailable";
|
||||
}
|
||||
return account.client_online === true ? "immediate" : "queued";
|
||||
}
|
||||
|
||||
export function publishRank(state: PublishState): number {
|
||||
switch (state) {
|
||||
case "immediate":
|
||||
return 0;
|
||||
case "queued":
|
||||
return 1;
|
||||
default:
|
||||
return 2;
|
||||
}
|
||||
}
|
||||
|
||||
export function publishStateLabel(state: PublishState): string {
|
||||
switch (state) {
|
||||
case "immediate":
|
||||
return "立即发布";
|
||||
case "queued":
|
||||
return "离线排队";
|
||||
default:
|
||||
return "不可发布";
|
||||
}
|
||||
}
|
||||
|
||||
export function publishStatusShortLabel(state: PublishState): string {
|
||||
switch (state) {
|
||||
case "immediate":
|
||||
return "客户端在线";
|
||||
case "queued":
|
||||
return "离线可排队";
|
||||
default:
|
||||
return "不可发布";
|
||||
}
|
||||
}
|
||||
|
||||
export function healthLabel(health: DesktopAccountInfo["health"]): string {
|
||||
switch (health) {
|
||||
case "live":
|
||||
return "授权正常";
|
||||
case "captcha":
|
||||
return "待处理";
|
||||
case "risk":
|
||||
return "风险观察";
|
||||
default:
|
||||
return "授权异常";
|
||||
}
|
||||
}
|
||||
|
||||
export function healthColor(health: DesktopAccountInfo["health"]): string {
|
||||
switch (health) {
|
||||
case "live":
|
||||
return "green";
|
||||
case "captcha":
|
||||
return "orange";
|
||||
case "risk":
|
||||
return "gold";
|
||||
default:
|
||||
return "red";
|
||||
}
|
||||
}
|
||||
|
||||
export function clientStatusLabel(card: PublishAccountCard): string {
|
||||
if (!card.clientId) {
|
||||
return "未绑定客户端";
|
||||
}
|
||||
return card.clientOnline ? "客户端在线" : "客户端离线";
|
||||
}
|
||||
|
||||
export function clientStatusColor(card: PublishAccountCard): string {
|
||||
if (!card.clientId) {
|
||||
return "default";
|
||||
}
|
||||
return card.clientOnline ? "green" : "gold";
|
||||
}
|
||||
|
||||
export function accountInitial(card: Pick<PublishAccountCard, "displayName" | "platformShortName">): string {
|
||||
const trimmed = card.displayName.trim();
|
||||
return trimmed ? trimmed.slice(0, 1).toUpperCase() : card.platformShortName;
|
||||
}
|
||||
|
||||
export function resolvePlatformLogoUrl(platformId: string, remoteLogoUrl?: string | null): string | null {
|
||||
const localLogoUrl = platformLogoCatalog[platformId];
|
||||
if (localLogoUrl) {
|
||||
return localLogoUrl;
|
||||
}
|
||||
const resolvedRemoteLogoUrl = resolveApiURL(remoteLogoUrl);
|
||||
return resolvedRemoteLogoUrl || null;
|
||||
}
|
||||
|
||||
function resolvePublishStatusText(account: DesktopAccountInfo, publishState: PublishState): string {
|
||||
if (publishState === "immediate") {
|
||||
return "客户端在线,RabbitMQ 会立即唤醒桌面端开始发布。";
|
||||
}
|
||||
if (publishState === "queued") {
|
||||
return "客户端当前离线,任务会先落库排队,等桌面端上线后自动继续发布。";
|
||||
}
|
||||
if (resolveAccountHealth(account) !== "live") {
|
||||
return "该账号授权状态异常,请先在桌面端重新校验或重新授权。";
|
||||
}
|
||||
return "该账号还没有绑定桌面客户端,当前不能进入发布队列。";
|
||||
}
|
||||
|
||||
function normalizePlatformUid(value?: string | null): string {
|
||||
let normalized = String(value ?? "").trim();
|
||||
while (normalized.toLowerCase().startsWith("platform:")) {
|
||||
normalized = normalized.slice("platform:".length).trim();
|
||||
}
|
||||
return normalized || "--";
|
||||
}
|
||||
@@ -1422,13 +1422,17 @@ export interface PromptRuleStatusRequest {
|
||||
|
||||
export interface ScheduleTask {
|
||||
id: number;
|
||||
workspace_id: number | null;
|
||||
prompt_rule_id: number;
|
||||
prompt_rule_name: string | null;
|
||||
brand_id: number | null;
|
||||
brand_name: string | null;
|
||||
name: string;
|
||||
cron_expr: string;
|
||||
target_platform: string | null;
|
||||
auto_publish: boolean;
|
||||
publish_account_ids: string[];
|
||||
cover_asset_url: string | null;
|
||||
cover_image_asset_id: number | null;
|
||||
enable_web_search: boolean;
|
||||
generate_count: number;
|
||||
start_at: string | null;
|
||||
@@ -1444,7 +1448,10 @@ export interface ScheduleTaskRequest {
|
||||
brand_id?: number | null;
|
||||
name: string;
|
||||
cron_expr: string;
|
||||
target_platform?: string;
|
||||
auto_publish?: boolean;
|
||||
publish_account_ids?: string[];
|
||||
cover_asset_url?: string | null;
|
||||
cover_image_asset_id?: number | null;
|
||||
enable_web_search?: boolean;
|
||||
generate_count?: number;
|
||||
start_at?: string;
|
||||
@@ -1475,7 +1482,6 @@ export interface ScheduleTaskStatusRequest {
|
||||
export interface GenerateFromRuleRequest {
|
||||
prompt_rule_id: number;
|
||||
brand_id?: number;
|
||||
target_platform?: string;
|
||||
extra_params?: Record<string, JsonValue>;
|
||||
}
|
||||
|
||||
|
||||
@@ -60,7 +60,7 @@ func main() {
|
||||
app.GenerationStreams,
|
||||
generationCfg,
|
||||
app.Config.LLM.MaxOutputTokens,
|
||||
).WithCache(app.Cache)
|
||||
).WithCache(app.Cache).WithLogger(app.Logger)
|
||||
|
||||
monitoringCallbackService := tenantapp.NewMonitoringCallbackService(
|
||||
app.DB,
|
||||
|
||||
@@ -63,7 +63,15 @@ func main() {
|
||||
app.GenerationStreams,
|
||||
generationCfg,
|
||||
app.Config.LLM.MaxOutputTokens,
|
||||
).WithCache(app.Cache).WithLogger(app.Logger)
|
||||
|
||||
publishJobSvc := tenantapp.NewPublishJobService(
|
||||
app.DB,
|
||||
app.RabbitMQ,
|
||||
app.Redis,
|
||||
app.Logger,
|
||||
).WithCache(app.Cache)
|
||||
promptRuleSvc.WithPublishJobService(publishJobSvc)
|
||||
|
||||
imitationSvc := tenantapp.NewArticleImitationService(
|
||||
app.DB,
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -5,7 +5,6 @@ CREATE TABLE schedule_tasks (
|
||||
brand_id BIGINT REFERENCES brands(id),
|
||||
name VARCHAR(100) NOT NULL,
|
||||
cron_expr VARCHAR(100) NOT NULL,
|
||||
target_platform VARCHAR(50),
|
||||
start_at TIMESTAMPTZ,
|
||||
end_at TIMESTAMPTZ,
|
||||
next_run_at TIMESTAMPTZ,
|
||||
|
||||
@@ -7,10 +7,3 @@ ALTER TABLE schedule_tasks
|
||||
DROP COLUMN IF EXISTS generate_count,
|
||||
DROP COLUMN IF EXISTS enable_web_search,
|
||||
DROP COLUMN IF EXISTS operator_id;
|
||||
|
||||
ALTER TABLE schedule_tasks
|
||||
ALTER COLUMN target_platform TYPE VARCHAR(50)
|
||||
USING CASE
|
||||
WHEN target_platform IS NULL THEN NULL
|
||||
ELSE LEFT(target_platform, 50)
|
||||
END;
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
ALTER TABLE schedule_tasks
|
||||
ALTER COLUMN target_platform TYPE TEXT;
|
||||
|
||||
ALTER TABLE schedule_tasks
|
||||
ADD COLUMN operator_id BIGINT REFERENCES users(id),
|
||||
ADD COLUMN enable_web_search BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
DROP INDEX IF EXISTS idx_schedule_task_workspace;
|
||||
|
||||
ALTER TABLE schedule_tasks
|
||||
DROP CONSTRAINT IF EXISTS chk_schedule_tasks_publish_account_ids_json;
|
||||
|
||||
ALTER TABLE schedule_tasks
|
||||
DROP COLUMN IF EXISTS cover_image_asset_id,
|
||||
DROP COLUMN IF EXISTS cover_asset_url,
|
||||
DROP COLUMN IF EXISTS publish_account_ids,
|
||||
DROP COLUMN IF EXISTS auto_publish,
|
||||
DROP COLUMN IF EXISTS workspace_id;
|
||||
@@ -0,0 +1,14 @@
|
||||
ALTER TABLE schedule_tasks
|
||||
ADD COLUMN workspace_id BIGINT REFERENCES workspaces(id),
|
||||
ADD COLUMN auto_publish BOOLEAN NOT NULL DEFAULT FALSE,
|
||||
ADD COLUMN publish_account_ids JSONB NOT NULL DEFAULT '[]'::jsonb,
|
||||
ADD COLUMN cover_asset_url TEXT,
|
||||
ADD COLUMN cover_image_asset_id BIGINT;
|
||||
|
||||
ALTER TABLE schedule_tasks
|
||||
ADD CONSTRAINT chk_schedule_tasks_publish_account_ids_json
|
||||
CHECK (jsonb_typeof(publish_account_ids) = 'array');
|
||||
|
||||
CREATE INDEX idx_schedule_task_workspace
|
||||
ON schedule_tasks(tenant_id, workspace_id, created_at DESC)
|
||||
WHERE deleted_at IS NULL;
|
||||
Reference in New Issue
Block a user