Files
crawler-plugin/frontend-vue/src/pages/brand/components/BrandAppearancePatentTab.vue
T
huangzd1997 0a467793ac feat(task-retry): 失败任务改为原任务上重试 + 重试按钮(用户拍板)
用户口径(2026-11-01):失败不再自动克隆(一单失败几次就多几行结果),
改成「删除」旁边的「重试」按钮,在原任务上断点续传;自动重试也只复位原任务。

- 新增 TaskInPlaceRetryService:FAILED→PENDING,清错误/终态时间,代数+1,
  保留分片/解析载荷/已检测标记;结果行清错误、组装作业复位(含卡死重排计数清零)
- TaskResumeService 自动重试改为调用原地复位(不再 cloneForRetry)
- TaskRetryEligibility 新增 DELIVERY(结果文件生成多次失败/卡死重排不重试)
- 新端点 POST /api/appearance-patent/tasks/{id}/retry;前端失败任务显示重试按钮
- ⚠ 本笔的 BrandAppearancePatentTab.vue 里另含他路在飞的「删除失败任务时一并删任务行」
  两小段(同一文件无法分块提交),随本笔一并入库
- 用例:TaskInPlaceRetryServiceTest 2、TaskResumeServiceTest 19、Eligibility 9、
  契约 8、前端 catch 棘轮 4,均绿
2026-11-01 00:30:51 +08:00

679 lines
30 KiB
Vue
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<template>
<div class="page-shell module-page">
<AmazonToolPageShell tool-id="patent">
<div class="main-content">
<aside class="left-panel left-panel--with-template">
<div class="section-title">上传文件</div>
<FileUploadZone
hint="选择 Excel 后点击解析,系统会识别表格里的 ID、ASIN、国家信息;每一行都会各自抓取商品页、各自送检,同一 ID 有多行也不会少检。"
:names="selectedFileNames"
@select-files="selectFiles"
@select-folder="selectFolder"
/>
<div class="prompt-card">
<div class="section-title">新增条件要求</div>
<textarea v-model="aiPrompt" class="prompt-input" rows="8" placeholder="选填:填写后会作为额外要求一并提交给检测" />
</div>
<div class="channel-row">
<span class="channel-title">本单采集方式</span>
<label class="channel-opt">
<input v-model="collectChannel" type="radio" value="LOCAL" :disabled="channelLocked" /> 本机采集
</label>
<label class="channel-opt">
<input v-model="collectChannel" type="radio" value="ONLINE" :disabled="channelLocked" /> 线上采集
</label>
</div>
<div class="run-row">
<button type="button" class="btn-run" :disabled="parsing || !uploadedFiles.length" @click="parseFiles">
{{ parsing ? '解析中...' : '解析并创建任务' }}
</button>
<button type="button" class="btn-run btn-queue" :disabled="pushing || !parseResult?.taskId" @click="pushToPythonQueue">
{{ pushing ? (localCollectEnabled ? '启动中...' : '提交中...') : (localCollectEnabled ? '启动任务' : '提交后台执行') }}
</button>
</div>
<p class="loading-msg">
{{ channelLocked
? '本单通道已随任务登记,改方式请重新解析创建。'
: (localCollectEnabled
? '启动后任务推送到本机客户端采集,进度显示在右侧任务区,完成后可下载结果。'
: '提交后系统自动分批检测,进度显示在右侧任务区,完成后可下载结果。') }}
</p>
<div v-if="visibleTaskSummary" class="parse-card">
<div>任务 ID:{{ visibleTaskSummary.taskId }}</div>
<div>总行数:{{ visibleTaskSummary.totalRows }},有效:{{ visibleTaskSummary.acceptedRows }},分组:{{ visibleTaskSummary.groupCount || 0 }},过滤:{{ visibleTaskSummary.droppedRows }}</div>
</div>
<ModuleTemplateDownload module-code="appearance-patent" filename="外观专利检测 文档格式.xlsx" />
</aside>
<section class="right-panel">
<TaskCenterPanel
:on-batch-delete="batchDeleteHistory"
:on-refresh="refreshBoard"
title="外观专利检测"
:cards="patentCards"
:current-items="currentTaskViews"
:history-items="historyTaskViews"
current-title="当前任务"
current-empty-text="暂无当前任务"
history-empty-text="暂无历史记录"
>
<template #item-extra="{ item }">
<div v-if="pendingResultHint(itemSource(item))" class="files result-hint">{{ pendingResultHint(itemSource(item)) }}</div>
</template>
<template #history-item-extra="{ item }">
<div v-if="pendingResultHint(itemSource(item))" class="files result-hint">{{ pendingResultHint(itemSource(item)) }}</div>
</template>
<template #item-actions="{ item }">
<button v-if="canDownload(itemSource(item))" type="button" class="download"
@click="downloadResult(itemSource(item))">下载</button>
<button v-if="canRetryTask(itemSource(item))" type="button" class="btn-retry"
@click="retryTaskRecord(itemSource(item))">重试</button>
<button type="button" class="btn-delete" @click="deleteTaskRecord(itemSource(item))">删除</button>
</template>
<template #history-item-actions="{ item }">
<button v-if="canDownload(itemSource(item))" type="button" class="download"
@click="downloadResult(itemSource(item))">下载</button>
<button v-if="canRetryTask(itemSource(item))" type="button" class="btn-retry"
@click="retryTaskRecord(itemSource(item))">重试</button>
<button v-if="itemSource(item).taskId || itemSource(item).resultId" type="button" class="btn-delete"
@click="deleteTaskRecord(itemSource(item))">删除</button>
</template>
</TaskCenterPanel>
</section>
</div>
</AmazonToolPageShell>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from 'vue'
import { userNotice } from '@/shared/utils/user-notice'
import { ElMessage, ElMessageBox } from 'element-plus'
import AmazonToolPageShell from '@/pages/amazon/components/AmazonToolPageShell.vue';
import FileUploadZone from '@/shared/components/FileUploadZone.vue'
import ModuleTemplateDownload from '@/shared/components/ModuleTemplateDownload.vue'
import TaskCenterPanel from '@/shared/components/tasks/TaskCenterPanel.vue'
import type { TaskItemView, TaskStatCard } from '@/shared/components/tasks/types'
import {
activateAppearancePatentTask,
deleteAppearancePatentHistory,
deleteAppearancePatentTask,
retryAppearancePatentTask,
getAppearancePatentDashboard,
getAppearancePatentHistory,
getAppearancePatentQueuePayload,
getAppearancePatentResultDownloadUrl,
getAppearancePatentTaskProgressBatch,
parseAppearancePatent,
type AppearancePatentHistoryItem,
type AppearancePatentParseVo,
type AppearancePatentParsedPayloadDto,
type UploadedFileRef,
} from '@/shared/api/java-modules'
import { getCollectRouting, type CollectChannel } from '@/shared/api/types/modules/collect-routing'
import { getPywebviewApi } from '@/shared/bridges/pywebview'
import { useExcelFileUpload } from '@/shared/composables/useExcelFileUpload'
import {
useLiveTaskBoard,
activeFileJobStatus,
hasActiveFileJob,
shouldShowFallbackJobProgress,
} from '@/shared/composables/useLiveTaskBoard'
import { getModuleProgressLight } from '@/shared/api/progress-light.ts'
import { createRowsVersionTracker } from '@/shared/api/task-progress-polling.ts'
import { checkParseResult, checkQueuePayload } from '@/shared/dispatch-guard'
import { passGuard } from '@/shared/dispatch-guard-ui'
import { formatDateTime } from '@/shared/utils/datetime'
import { resultBuildFailed, taskStatusClass, taskStatusText } from '@/shared/utils/task-status-text'
import { ensureBrandCheckProxy, getStoredApiSecret } from '@/shared/utils/api-secret-store'
// ---- 文件选择 / 上传(公共组合式函数)----
const {
files: uploadedFiles,
selectedPaths: selectedFileNames,
selectFiles,
selectFolder,
} = useExcelFileUpload({
requireUploadCapability: true,
pickFilesUnavailableWarning: '当前环境不支持文件选择或上传',
folderUnavailableWarning: '当前环境不支持文件夹选择,请在本地客户端中打开',
errorFallbackMessage: (action) => (action === 'files' ? '文件上传失败' : '选择失败'),
onUploaded: () => {
parseResult.value = null
queuedTaskSummary.value = null
},
onFailed: () => {
parseResult.value = null
queuedTaskSummary.value = null
},
})
const parseResult = ref<AppearancePatentParseVo | null>(null)
type TaskSummary = Pick<AppearancePatentParseVo, 'taskId' | 'totalRows' | 'acceptedRows' | 'groupCount' | 'droppedRows'>
const queuedTaskSummary = ref<TaskSummary | null>(null)
// 不再注入默认 prompt:用户未填则一律空字符串,由后端决定是否给 LLM 透传 prompt 字段。
const aiPrompt = ref('')
const parsing = ref(false)
const pushing = ref(false)
/**
* 这一单的采集执行通道(V183 建单时单选,随 /parse 交服务端落 biz_file_task.collect_channel)。
* 默认值取服务端「模块默认」(getCollectRouting),取不到就按本机渲染:真正兜底在服务端——
* 选了线上的单子 activate 会明确拒绝,页面最多多报一次错,不会把任务推给不该跑本地的机器。
*/
const collectChannel = ref<CollectChannel>('LOCAL')
/** 派生量:模板与启动分支沿用「本机通道」这一读法,避免两处各判各的。 */
const localCollectEnabled = computed(() => collectChannel.value === 'LOCAL')
/**
* 通道在「解析建单」那一刻就写进任务行了,之后再改单选框只会被建单值覆盖,
* 界面就会出现「选着线上、点启动却推本机」的假象——所以建完单即锁定。
*/
const channelLocked = computed(() => parsing.value || pushing.value || Boolean(parseResult.value?.taskId))
/** 结果行版本跟踪(审查 F5 后续):版本未变的任务跳过行明细拉取 */
const rowsVersionTracker = createRowsVersionTracker()
function uidForStorage() {
return typeof window !== 'undefined' ? window.localStorage.getItem('uid') || '0' : '0'
}
// ---- 实时任务面板(与货源查询 Tab 的公共骨架抽到 useLiveTaskBoard)----
const board = useLiveTaskBoard<AppearancePatentHistoryItem>({
scope: 'appearance-patent',
pollingStorageKey: () => `appearance-patent:tasks:${uidForStorage()}`,
fetchHistory: getAppearancePatentHistory,
fetchProgressBatch: getAppearancePatentTaskProgressBatch,
fetchDashboard: getAppearancePatentDashboard,
normalizeTaskStatus,
isResultPreparing,
addPendingAfterFinalStatus: (_task, item) => Boolean(item && isResultPreparing(item)),
keepPendingFileTask: (_item, taskStatus) => taskStatus === 'SUCCESS' || taskStatus === 'FAILED',
settleOnTaskStatuses: ['SUCCESS', 'FAILED'],
beforeBatch: async (taskIds, pendingIds) => {
// 行数据按需拉取(审查 F5 后续):等结果文件(pending)时必须强刷;其余情况版本未变的任务跳过
const mustForce = pendingIds.length > 0
if (!mustForce) {
try {
const light = await getModuleProgressLight('appearancePatent', taskIds)
const heavyIds = rowsVersionTracker.selectTasksNeedingRows(light.items || [], taskIds)
if (!heavyIds.length && !(light.missingTaskIds || []).length) {
// 行数据与状态都没变:本轮不拉行明细,直接结束
return null
}
return { taskIds: heavyIds, force: false }
} catch {
// 轻量端点不可用(老后端/网络)→ 照旧全量拉取,行为与原来一致
return { taskIds, force: false }
}
}
return { taskIds, force: true }
},
getPendingParseItem: () => pendingParseItem.value,
download: {
buildUrl: (resultId) => getAppearancePatentResultDownloadUrl(resultId),
fallbackFilename: 'appearance-patent',
progressKeyPrefix: 'appearance-patent',
},
deleteTask: {
// 有任务就删任务:失败任务常被自动克隆重试(克隆件没有结果行),只删结果行等于
// 删不掉那条任务——统计不降、任务还会被再克隆一次,用户看到的就是「删了又回来」。
shouldDeleteTask: (item) => item.taskId != null,
deleteTask: (taskId) => deleteAppearancePatentTask(taskId),
deleteHistory: (resultId) => deleteAppearancePatentHistory(resultId),
onTaskDeleted: (item) => board.removePollingTask(item.taskId as number),
},
})
/** 只有失败的任务能重试:在原任务上复位续跑(不新建任务),成功/进行中的任务不该出现这个按钮。 */
function canRetryTask(item: AppearancePatentHistoryItem | null | undefined): boolean {
return Boolean(item?.taskId) && String(item?.taskStatus || '').toUpperCase() === 'FAILED'
}
async function retryTaskRecord(item: AppearancePatentHistoryItem | null | undefined) {
const taskId = item?.taskId
if (!taskId) return
try {
await retryAppearancePatentTask(taskId)
ElMessage.success('已提交重试:在这条任务上继续跑(不新建任务)')
await refreshBoard()
} catch (error) {
ElMessage.error(error instanceof Error ? error.message : '重试失败')
}
}
const visibleTaskSummary = computed(() => parseResult.value || queuedTaskSummary.value)
/** 手动刷新:强拉历史 + 统计 + 当前轮询任务进度(轮询意外中断后的自救出口) */
async function refreshBoard() {
await Promise.all([
board.loadDashboard(),
board.loadHistory({ force: true }),
board.refreshTaskProgress(),
])
}
const pendingParseItem = computed<AppearancePatentHistoryItem | null>(() => {
const result = parseResult.value
if (!result?.taskId) return null
const exists = board.historyItems.value.some((item) => item.taskId === result.taskId)
if (exists) return null
return {
taskId: result.taskId,
sourceFilename: result.sourceFilename,
rowCount: result.acceptedRows,
taskStatus: 'PENDING',
success: false,
}
})
const patentCards = computed<TaskStatCard[]>(() => [
{ label: '运行中任务', value: board.dashboard.value.pendingTaskCount },
{ label: '已结束任务', value: board.dashboard.value.processedTaskCount },
{ label: '成功任务', value: board.dashboard.value.successTaskCount },
{ label: '失败任务', value: board.dashboard.value.failedTaskCount },
])
const currentTaskViews = computed<TaskItemView[]>(() =>
board.currentItems.value.map(toPatentTaskView),
)
const historyTaskViews = computed<TaskItemView[]>(() =>
board.historyOnlyItems.value.map(toPatentTaskView),
)
function itemSource(item: TaskItemView) {
return item.source as AppearancePatentHistoryItem
}
function toPatentTaskView(item: AppearancePatentHistoryItem): TaskItemView {
const showProgress = board.showFileProgress(item)
const progressPercent = fileProgressPercent(item)
return {
key: `patent-${item.taskId ?? item.resultId ?? item.sourceFilename}`,
title: item.sourceFilename || '外观专利检测',
taskId: item.taskId ?? '-',
startedAt: formatDateTime(item.startedAt || item.createdAt),
finishedAt: formatDateTime(item.finishedAt),
statusText: statusText(item),
statusClass: statusClass(item),
extraLines: [
...(item.rowCount != null ? [`行数:${item.rowCount}`] : []),
...(item.resultFilename && !showProgress ? [item.resultFilename] : []),
...(item.error ? [`错误:${userNotice(item.error)}`] : []),
],
progress: showProgress
? {
percent: progressPercent,
stage: displayFileProgressMessage(item, '处理中'),
}
: null,
source: item,
}
}
// ---- 本模块的状态语义(与货源查询 Tab 不同,保留在 Tab 内)----
function statusText(item: AppearancePatentHistoryItem) {
const status = normalizeTaskStatus(item)
if (status === 'RUNNING') return taskStatusText(status)
if (status === 'PENDING') return taskStatusText(status, { text: { PENDING: '已解析,等待后台执行' } })
// 已判死(含心跳超时)的任务始终显示失败:后台检测可能仍在跑、文件生成后下载按钮会自动出现,
// 但状态文案不能是"结果生成中",否则用户会以为任务还在执行(2026-09-28 29473/29479)
if (status === 'FAILED') return isResultBuildFailed(item) ? '结果生成失败' : taskStatusText('FAILED')
if (isResultPreparing(item)) return '结果生成中'
if (isResultBuildFailed(item)) return '结果生成失败'
if (hasDownloadableResult(item)) return taskStatusText('SUCCESS')
if (status === 'SUCCESS' || item.success) return taskStatusText('SUCCESS')
return '等待中'
}
function statusClass(item: AppearancePatentHistoryItem) {
const status = normalizeTaskStatus(item)
if (status === 'FAILED' || isResultBuildFailed(item)) return taskStatusClass('FAILED')
if (status === 'RUNNING' || isResultPreparing(item)) return taskStatusClass('RUNNING')
if (hasDownloadableResult(item)) return taskStatusClass('SUCCESS')
if (status === 'SUCCESS' || item.success) return taskStatusClass('SUCCESS')
return 'pending'
}
function isResultPreparing(item: AppearancePatentHistoryItem) {
const status = normalizeTaskStatus(item)
const fileStatus = (item.fileStatus || '').toUpperCase()
if (status !== 'SUCCESS' && status !== 'FAILED') return false
if (canDownload(item)) return false
if (fileStatus === 'FAILED' || fileStatus === 'SUCCESS') return false
return status === 'SUCCESS' || hasActiveFileJob(item)
}
function normalizeTaskStatus(item: AppearancePatentHistoryItem) {
return (item.taskStatus || '').toUpperCase()
}
function isResultBuildFailed(item: AppearancePatentHistoryItem) {
return resultBuildFailed(item.fileStatus, canDownload(item))
}
function pendingResultHint(item: AppearancePatentHistoryItem) {
if (isResultBuildFailed(item)) {
return userNotice(item.fileError, '结果文件生成失败,请稍后重试或检查后端日志')
}
if (board.showFileProgress(item)) {
return ''
}
if (!isResultPreparing(item)) return ''
const doneLabel = normalizeTaskStatus(item) === 'FAILED' ? '任务已失败' : '任务已完成'
const fileStatus = (item.fileStatus || '').toUpperCase()
if (fileStatus === 'PENDING') {
return `${doneLabel},结果文件排队中,请稍候`
}
return `${doneLabel},正在生成结果文件,下载按钮稍后出现`
}
function canDownload(item: AppearancePatentHistoryItem) {
return Boolean(item.resultId && (item.fileReady || item.downloadUrl))
}
function hasDownloadableResult(item: AppearancePatentHistoryItem) {
return canDownload(item)
}
function fileProgressPercent(item: AppearancePatentHistoryItem) {
const percent = Number(item.fileProgressPercent || 0)
if (Number.isFinite(percent) && percent > 0) {
return Math.max(0, Math.min(100, Math.round(percent)))
}
if (shouldShowFallbackJobProgress(item)) {
return activeFileJobStatus(item) === 'PENDING' ? 6 : 10
}
return 0
}
function displayFileProgressMessage(item: AppearancePatentHistoryItem, fallback: string) {
const message = (item.fileProgressMessage || '').trim()
if (!message) return fallback
return translateFileProgressMessage(message)
}
function translateFileProgressMessage(message: string) {
const submittedMatch = message.match(/^LLM submitted (\d+) batches, completed (\d+), waiting for results$/)
if (submittedMatch) {
return `已提交 ${submittedMatch[1]} 批,已完成 ${submittedMatch[2]} 批,等待结果`
}
const completedMatch = message.match(/^LLM completed (\d+) batches, waiting for remaining Python data$/)
if (completedMatch) {
return `已完成 ${completedMatch[1]} 批,等待后续数据`
}
const translations: Record<string, string> = {
'Receiving Python data, waiting for 50 rows before LLM': '正在接收检测数据,累计 50 条后提交检测',
'Submitting LLM': '正在提交检测',
'LLM submitted, waiting for result': '已提交检测,等待结果',
'Waiting for Python upload': '等待后续数据',
'LLM results ready, assembling xlsx': '检测结果已返回,正在生成结果文件',
'Assembling xlsx': '正在生成结果文件',
'Uploading result file': '正在上传结果文件',
'Result file generated': '结果文件已生成',
}
return translations[message] || message
}
// ---- 解析与提交(本模块特有)----
function effectiveAiPrompt() {
// 用户没在文本框填东西就送空字符串,后端会跳过 prompt 字段。
return aiPrompt.value.trim()
}
function effectiveLlmApiKey() {
return getStoredApiSecret('appearance-patent').trim()
}
function toTaskSummary(result: AppearancePatentParseVo): TaskSummary {
return {
taskId: result.taskId,
totalRows: result.totalRows,
acceptedRows: result.acceptedRows,
groupCount: result.groupCount,
droppedRows: result.droppedRows,
}
}
/**
* 本模块自 2026-10-15 起逐行抓取、逐行送检:解析阶段仍按 id 前缀分组,但分组只是
* 回传攒片的单位,不再决定检测覆盖,所以原先这里有一个「分组数异常」确认框
* (组数 < 行数/3 就拦一道,源自任务 28805 的 id 塌陷事故)—— 它的前提已经不存在,
* 且会在用户正常填变体 id(12_1…12_98)时误报,故摘除。检测覆盖由 ap_worker 的
* 逐行抓取用例钉住:maixiang_run_task/test/maixiang_ops/test_proxy_cost_leaks.py。
*/
/**
* 创建任务前确认服务端有代理:商标维度依赖服务端代理,缺代理时整批都会落成
* 「商标查询失败」且状态为失败。服务端读不到(unknown)不拦,避免网络抖动误伤。
*/
async function ensureBrandCheckProxyReady(): Promise<boolean> {
const check = await ensureBrandCheckProxy()
if (check.ok) return true
await ElMessageBox.alert(
'当前账号未在服务端配置代理,商标维度将无法查询,整批结果会显示「商标查询失败」。'
+ '请先点击右上角「密钥设置」,在「代理地址」中保存代理后再创建任务。',
'未配置代理,无法检测商标',
{ type: 'warning', confirmButtonText: '知道了' },
).then(
// 关闭弹窗会以 reject 收尾,属正常交互而不是错误,不新增 catch 块
() => undefined,
() => undefined,
)
return false
}
async function parseFiles() {
if (!uploadedFiles.value.length) {
ElMessage.warning('请先选择 Excel')
return
}
if (!effectiveLlmApiKey()) {
// 本地无明文不再阻断:密钥已服务端化,任务执行按用户 uid 兜底读取
console.log('[appearance-patent] 本地无密钥明文,提交时由服务端按用户密钥兜底')
}
parsing.value = true
try {
if (!(await ensureBrandCheckProxyReady())) {
return
}
const files: UploadedFileRef[] = uploadedFiles.value.map((f) => ({
fileKey: f.fileKey,
originalFilename: f.originalFilename,
relativePath: f.relativePath,
}))
const res = await parseAppearancePatent(files, effectiveAiPrompt(), effectiveLlmApiKey(), collectChannel.value)
// 本模块按主 ID 分组执行,没有分组就没有可跑的批次,一并拦下
const guard = checkParseResult(res, {
requireGroups: true,
requiredColumnsHint: 'id / ASIN / 国家',
})
if (!(await passGuard(guard))) {
parseResult.value = null
queuedTaskSummary.value = null
return
}
parseResult.value = res
queuedTaskSummary.value = null
ElMessage.success(`解析完成,共 ${res.groupCount || 0} 组 / ${res.acceptedRows} 条`)
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : '解析失败')
} finally {
parsing.value = false
}
}
async function pushToPythonQueue() {
const currentParseResult = parseResult.value
const taskId = currentParseResult?.taskId
if (!taskId) {
ElMessage.warning('请先解析文件')
return
}
if (!localCollectEnabled.value) {
// 本地采集关闭:只建单,任务保持 PENDING 由 Linux 后台认领
// (/api/internal/tasks/pull-pending + 主机B maixiang-ap worker)在等待窗口后自动接管。
pushing.value = true
try {
queuedTaskSummary.value = toTaskSummary(currentParseResult)
board.addPollingTask(taskId)
clearParsedTask()
await board.loadDashboard()
await board.loadHistory({ force: true })
ElMessage.success('已提交,后台自动执行中(无需打开浏览器)')
} finally {
pushing.value = false
}
return
}
const api = getPywebviewApi()
if (!api?.enqueue_json) {
ElMessage.error('当前环境未启用 pywebview enqueue_json,请在本地客户端中打开本页后再启动')
return
}
if (!effectiveLlmApiKey()) {
// 本地无明文不再阻断:服务端已保存该用户密钥,任务执行时按 uid 兜底读取
console.log('[appearance-patent] 本地无密钥明文,启动任务由服务端兜底')
}
pushing.value = true
try {
const parsedPayload: AppearancePatentParsedPayloadDto = await getAppearancePatentQueuePayload(taskId)
const groups = parsedPayload.groups || []
const payload = {
type: 'appearance-patent-run',
ts: Date.now(),
data: {
taskId,
prompt: aiPrompt.value.trim(),
api_key: effectiveLlmApiKey(),
sourceFileCount: currentParseResult.sourceFileCount || 0,
totalRows: currentParseResult.totalRows || 0,
acceptedRows: currentParseResult.acceptedRows || 0,
groupCount: currentParseResult.groupCount || 0,
groups: groups.map((group) => ({
sourceFileKey: group.sourceFileKey || '',
sourceFilename: group.sourceFilename || '',
groupKey: group.groupKey || '',
baseId: group.baseId || '',
displayId: group.displayId || '',
items: (group.items || []).map((row) => ({
sourceFileKey: row.sourceFileKey || '',
sourceFilename: row.sourceFilename || '',
rowToken: row.rowToken || '',
groupKey: row.groupKey || '',
id: row.displayId,
asin: row.asin,
country: row.country,
sku: row.sku || '',
url: row.url || '',
title: row.title || '',
})),
})),
},
}
// 后端返回的 groups 为空时推送出去,Python 端没有可执行批次会一直停在执行中
const guard = checkQueuePayload(payload, {
expectedType: 'appearance-patent-run',
// api_key 不列为必填:密钥已服务端化,本地无明文时由服务端按 uid 兜底
requiredDataKeys: ['taskId'],
nonEmptyArrayKeys: ['groups'],
})
if (!(await passGuard(guard))) return
// 任务可能已被客户端「兜底拉取」/Linux 兜底领走:服务端会拒绝 activate,
// 此时必须直接返回,不能再入队,否则同一任务会被执行两次
try {
await activateAppearancePatentTask(taskId)
} catch (activateError) {
ElMessage.warning(activateError instanceof Error ? activateError.message : '任务已在执行中,无需重复启动')
await Promise.all([board.loadDashboard(), board.loadHistory({ force: true })])
return
}
const result = await api.enqueue_json(payload)
if (!result?.success) {
ElMessage.error(userNotice(result?.error, '启动失败'))
return
}
queuedTaskSummary.value = toTaskSummary(currentParseResult)
board.addPollingTask(taskId)
clearParsedTask()
await board.loadDashboard()
await board.loadHistory({ force: true })
ElMessage.success('已启动任务')
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : '启动失败')
} finally {
pushing.value = false
}
}
function clearParsedTask() {
parseResult.value = null
}
const { batchDeleteHistory, deleteTaskRecord, downloadResult } = board
onMounted(async () => {
board.loadPollingIds()
// 单选框默认选中项取服务端模块默认;读不到就按本机,服务端 activate 会兜底拒绝
getCollectRouting()
.then((routing) => {
collectChannel.value = routing.appearancePatentLocal !== false ? 'LOCAL' : 'ONLINE'
})
.catch((error) => {
console.warn('[appearance-patent] 读取采集通道默认值失败,按本机采集处理', error)
})
await Promise.all([
board.loadDashboard().catch(() => undefined),
board.loadHistory().catch(() => undefined),
])
board.seedRunningTasksFromHistory()
board.seedPendingFileTasksFromHistory()
board.ensurePollingIfAny()
})
onUnmounted(() => {
board.dispose()
})
</script>
<style scoped>
.module-page { min-height: 100vh; background: #242424; }
.main-content { display: flex; height: calc(100vh - 56px); min-height: calc(100vh - 56px); }
.left-panel { width: 400px; background: #242424; padding: 20px; overflow-y: auto; border-right: 1px solid #2e3a52; }
.right-panel { flex: 1; min-width: 0; background: #242424; display: flex; flex-direction: column; }
.section-title, .subsection-title { font-size: 13px; color: #a0acbe; margin-bottom: 10px; }
.hint, .loading-msg, .files, .muted { color: #5e6878; font-size: 12px; line-height: 1.5; }
.link { color: #6ea8fe; text-decoration: none; }
.link:hover { color: #9fc5ff; }
.run-row { display: flex; gap: 10px; flex-wrap: wrap; }
.channel-row { display: flex; align-items: center; gap: 14px; flex-wrap: wrap; margin-bottom: 12px; color: #a0acbe; font-size: 12px; }
.channel-title { color: #5e6878; }
.channel-opt { display: inline-flex; align-items: center; gap: 6px; cursor: pointer; }
.channel-opt:has(input:disabled) { opacity: .55; cursor: not-allowed; }
.btn-run, .btn-delete, .btn-retry, .download { border: none; cursor: pointer; border-radius: 7px; }
.btn-run { padding: 10px 18px; color: #f5f8fc; background: #3498db; font-weight: 600; }
.btn-queue { background: #27ae60; }
.btn-run:disabled { opacity: .55; cursor: not-allowed; }
.prompt-card, .secret-card { margin-bottom: 18px; }
.secret-card { display: none; }
.prompt-input { width: 100%; box-sizing: border-box; resize: vertical; min-height: 180px; padding: 10px 12px; border: 1px solid #333; border-radius: 8px; background: #222b3d; color: #c8d2e2; font-size: 12px; line-height: 1.6; outline: none; }
.secret-input { width: 100%; box-sizing: border-box; height: 38px; padding: 0 12px; border: 1px solid #333; border-radius: 8px; background: #222b3d; color: #c8d2e2; font-size: 12px; outline: none; }
.prompt-input:focus, .secret-input:focus { border-color: #3498db; }
.parse-card { margin-top: 14px; padding: 12px; border: 1px solid #2e3a52; border-radius: 8px; background: #222b3d; color: #a0acbe; font-size: 12px; }
.result-table { --el-table-bg-color: #242424; --el-table-tr-bg-color: #242424; --el-table-header-bg-color: #2e3a52; --el-table-text-color: #c8d2e2; --el-table-border-color: #333; }
.result-hint { margin-top: 6px; color: #e0b96d; }
.download { padding: 6px 10px; color: #c8d2e2; background: rgba(52, 152, 219, .18); }
.btn-delete { padding: 6px 10px; color: #ff8f8f; background: rgba(231, 76, 60, .12); }
.btn-retry { padding: 6px 10px; color: #7fd1a0; background: rgba(39, 174, 96, .14); }
@media (max-width: 1100px) {
.main-content { flex-direction: column; height: auto; }
.left-panel { width: 100%; border-right: none; border-bottom: 1px solid #2e3a52; }
}
</style>