Files
crawler-plugin/frontend-vue/src/pages/brand/components/BrandAppearancePatentTab.vue
T
huangzd1997 d98b1dc1dd fix(结果文件): 文件可下载就不判"结果生成失败"——两页共用一条判据
货源查询任务 30456 结果文件已生成、下载按钮可用,但徽标仍按 fileStatus=FAILED
判红。前端加一条:能下载就不算生成失败。判据抽到 task-status-text.resultBuildFailed,
货源查询与外观专利两个 tab 同用一个出口,外观专利 statusText 里"整体失败优先于
生成失败"的 carve-out 由用例盯住不得回流。
2026-10-09 17:52:08 +08:00

516 lines
22 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="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 ? '提交中...' : '提交后台执行' }}
</button>
</div>
<p class="loading-msg">提交后系统自动分批检测,进度显示在右侧任务区,完成后可下载结果。</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"
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 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="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 { 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 {
deleteAppearancePatentHistory,
deleteAppearancePatentTask,
getAppearancePatentDashboard,
getAppearancePatentHistory,
getAppearancePatentResultDownloadUrl,
getAppearancePatentTaskProgressBatch,
parseAppearancePatent,
type AppearancePatentHistoryItem,
type AppearancePatentParseVo,
type UploadedFileRef,
} from '@/shared/api/java-modules'
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 } 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 { 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)
/** 结果行版本跟踪(审查 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 }
},
// 轮询回调抛错时上抛、轮询停止(与原实现一致)
pollErrorMode: 'propagate',
getPendingParseItem: () => pendingParseItem.value,
download: {
buildUrl: (resultId) => getAppearancePatentResultDownloadUrl(resultId),
fallbackFilename: 'appearance-patent',
progressKeyPrefix: 'appearance-patent',
},
deleteTask: {
shouldDeleteTask: (item) => item.taskStatus === 'RUNNING' && item.taskId != null,
deleteTask: (taskId) => deleteAppearancePatentTask(taskId),
deleteHistory: (resultId) => deleteAppearancePatentHistory(resultId),
onTaskDeleted: (item) => board.removePollingTask(item.taskId as number),
},
})
const visibleTaskSummary = computed(() => parseResult.value || queuedTaskSummary.value)
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 ? [`错误:${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 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,
}
}
/**
* 本模块按 id 列分组,同组只检测 1 次并把结论复制给组内其它行。
* 生产事故(任务 28805):源表 id 列 904 行全填 "1",整表塌成 1 组,105 秒就"完成"了。
* 这里在解析后按组/行比例提醒用户确认,返回 true 表示用户选择回去改表。
*/
async function abortOnCollapsedGroups(res: { acceptedRows?: number; groupCount?: number }): Promise<boolean> {
const rows = res.acceptedRows || 0
const groups = res.groupCount || 0
if (rows < 20 || groups * 3 >= rows) {
return false
}
try {
await ElMessageBox.confirm(
`本次共 ${rows} 行,只识别出 ${groups} 个检测分组(平均每组 ${(rows / Math.max(groups, 1)).toFixed(1)} 行)。`
+ '同组只会检测 1 次,结论复制到组内其它行。若 id 列是整表同一个值,请改为每个商品一个 id 后重新上传。',
'分组数异常',
{ confirmButtonText: '按当前分组继续', cancelButtonText: '返回改表', type: 'warning', distinguishCancelAndClose: true },
)
return false
} catch {
return true
}
}
async function parseFiles() {
if (!uploadedFiles.value.length) {
ElMessage.warning('请先选择 Excel')
return
}
if (!effectiveLlmApiKey()) {
// 本地无明文不再阻断:密钥已服务端化,任务执行按用户 uid 兜底读取
console.log('[appearance-patent] 本地无密钥明文,提交时由服务端按用户密钥兜底')
}
parsing.value = true
try {
const files: UploadedFileRef[] = uploadedFiles.value.map((f) => ({
fileKey: f.fileKey,
originalFilename: f.originalFilename,
relativePath: f.relativePath,
}))
const res = await parseAppearancePatent(files, effectiveAiPrompt(), effectiveLlmApiKey())
// 本模块按主 ID 分组执行,没有分组就没有可跑的批次,一并拦下
const guard = checkParseResult(res, {
requireGroups: true,
requiredColumnsHint: 'id / ASIN / 国家',
})
if (!(await passGuard(guard))) {
parseResult.value = null
queuedTaskSummary.value = null
return
}
if (await abortOnCollapsedGroups(res)) {
parseResult.value = null
queuedTaskSummary.value = null
ElMessage.info('已取消,修正 id 列后重新解析')
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
}
// 2026-09-30 外观专利已迁移 Linux 后台执行(无浏览器抓取):
// 「启动」不再推送客户端队列,任务保持 PENDING,由服务端内部认领
// (/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
}
}
function clearParsedTask() {
parseResult.value = null
}
const { batchDeleteHistory, deleteTaskRecord, downloadResult } = board
onMounted(async () => {
board.loadPollingIds()
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; }
.btn-run, .btn-delete, .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); }
@media (max-width: 1100px) {
.main-content { flex-direction: column; height: auto; }
.left-panel { width: 100%; border-right: none; border-bottom: 1px solid #2e3a52; }
}
</style>