refactor: 第二批收敛——公共 Excel 写出器 + 任务收尾零件下沉 + 前端上传区/任务面板抽取

This commit is contained in:
2026-10-01 15:00:52 +08:00
parent 4b29a150f3
commit fa4bd57016
32 changed files with 2467 additions and 2826 deletions
@@ -5,17 +5,12 @@
<div class="main-content">
<aside class="left-panel left-panel--with-template">
<div class="section-title">上传文件</div>
<div class="upload-zone">
<div class="hint">选择 Excel 后点击解析,系统会识别表格里的 ID、ASIN、国家信息;同一 ID 有多行时只保留第一行。</div>
<div class="btns">
<button type="button" class="opt-btn" @click="selectFiles">选择 Excel</button>
<button type="button" class="opt-btn" @click="selectFolder">选择文件夹</button>
</div>
<div class="selected-files">
<span v-if="!selectedFileNames.length">暂未选择文件</span>
<span v-for="name in selectedFileNames" v-else :key="name">{{ name }}</span>
</div>
</div>
<FileUploadZone
hint="选择 Excel 后点击解析,系统会识别表格里的 ID、ASIN、国家信息;同一 ID 有多行时只保留第一行。"
:names="selectedFileNames"
@select-files="selectFiles"
@select-folder="selectFolder"
/>
<div class="prompt-card">
<div class="section-title">新增条件要求</div>
@@ -76,6 +71,7 @@
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'
@@ -87,34 +83,47 @@ import {
getAppearancePatentResultDownloadUrl,
getAppearancePatentTaskProgressBatch,
parseAppearancePatent,
type AppearancePatentDashboardVo,
type AppearancePatentHistoryItem,
type AppearancePatentParseVo,
type UploadedFileRef,
type UploadFileVo,
} from '@/shared/api/java-modules'
import { expandBrandFolderRecursive } from '@/shared/api/brand'
import { getPywebviewApi } from '@/shared/bridges/pywebview'
import { getTaskPollIntervalMs } from '@/shared/task-progress-config'
import { getStoredApiSecret } from '@/shared/utils/api-secret-store'
import { createCategorizedTimers } from '@/shared/utils/categorized-timers'
import { saveUrlWithProgress } from '@/shared/utils/download-progress'
import { useExcelFileUpload } from '@/shared/composables/useExcelFileUpload'
import {
EXCEL_EXTENSIONS,
checkParseResult,
checkSelectedFiles,
} from '@/shared/dispatch-guard'
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 { taskStatusClass, taskStatusText } from '@/shared/utils/task-status-text'
import { uploadPathsToJava } from '@/shared/utils/upload-to-java'
import { runBatchDelete } from '@/shared/utils/batch-delete'
import { getModuleProgressLight } from '@/shared/api/progress-light.ts'
import { createRowsVersionTracker } from '@/shared/api/task-progress-polling.ts'
import { confirmTaskDeletion } from '@/shared/task-delete-confirm'
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 selectedFileNames = ref<string[]>([])
const uploadedFiles = ref<UploadFileVo[]>([])
const parseResult = ref<AppearancePatentParseVo | null>(null)
type TaskSummary = Pick<AppearancePatentParseVo, 'taskId' | 'totalRows' | 'acceptedRows' | 'groupCount' | 'droppedRows'>
const queuedTaskSummary = ref<TaskSummary | null>(null)
@@ -122,30 +131,66 @@ const queuedTaskSummary = ref<TaskSummary | null>(null)
const aiPrompt = ref('')
const parsing = ref(false)
const pushing = ref(false)
const pollingTaskIds = ref<number[]>([])
const pendingFileTaskIds = ref<number[]>([])
const pollTimer = ref<number | null>(null)
const pollingInFlight = ref(false)
const HISTORY_CACHE_TTL_MS = 3000
let historyInFlight: Promise<void> | null = null
let lastHistoryLoadedAt = 0
let disposed = false
const timers = createCategorizedTimers('appearance-patent')
const dashboard = ref<AppearancePatentDashboardVo>({
pendingTaskCount: 0,
processedTaskCount: 0,
successTaskCount: 0,
failedTaskCount: 0,
/** 结果行版本跟踪(审查 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 historyItems = ref<AppearancePatentHistoryItem[]>([])
const liveProgressItems = ref<Record<number, AppearancePatentHistoryItem>>({})
const visibleTaskSummary = computed(() => parseResult.value || queuedTaskSummary.value)
const pendingParseItem = computed<AppearancePatentHistoryItem | null>(() => {
const result = parseResult.value
if (!result?.taskId) return null
const exists = historyItems.value.some((item) => item.taskId === result.taskId)
const exists = board.historyItems.value.some((item) => item.taskId === result.taskId)
if (exists) return null
return {
taskId: result.taskId,
@@ -155,47 +200,20 @@ const pendingParseItem = computed<AppearancePatentHistoryItem | null>(() => {
success: false,
}
})
const currentItems = computed(() => {
const activeIds = new Set([...pollingTaskIds.value, ...pendingFileTaskIds.value])
const activeItems = historyItems.value
.filter((item) => {
const status = normalizeTaskStatus(item)
return item.taskId != null && (activeIds.has(item.taskId) || status === 'RUNNING' || status === 'PENDING')
})
.map((item) => mergeCurrentTaskItem(item))
for (const [taskIdText, liveItem] of Object.entries(liveProgressItems.value)) {
const taskId = Number(taskIdText)
if (!Number.isFinite(taskId) || taskId <= 0) continue
if (!activeIds.has(taskId) && normalizeTaskStatus(liveItem) !== 'RUNNING' && normalizeTaskStatus(liveItem) !== 'PENDING') {
continue
}
if (activeItems.some((item) => item.taskId === taskId)) continue
activeItems.push(mergeCurrentTaskItem(liveItem))
}
if (!pendingParseItem.value) return activeItems
const exists = activeItems.some((item) => item.taskId === pendingParseItem.value?.taskId)
return exists ? activeItems : [pendingParseItem.value, ...activeItems]
})
const historyOnlyItems = computed(() =>
historyItems.value.filter((i) => {
const status = normalizeTaskStatus(i)
return status !== 'RUNNING' && status !== 'PENDING'
}),
)
const patentCards = computed<TaskStatCard[]>(() => [
{ label: '运行中任务', value: dashboard.value.pendingTaskCount },
{ label: '已结束任务', value: dashboard.value.processedTaskCount },
{ label: '成功任务', value: dashboard.value.successTaskCount },
{ label: '失败任务', value: dashboard.value.failedTaskCount },
{ 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[]>(() =>
currentItems.value.map(toPatentTaskView),
board.currentItems.value.map(toPatentTaskView),
)
const historyTaskViews = computed<TaskItemView[]>(() =>
historyOnlyItems.value.map(toPatentTaskView),
board.historyOnlyItems.value.map(toPatentTaskView),
)
function itemSource(item: TaskItemView) {
@@ -203,7 +221,7 @@ function itemSource(item: TaskItemView) {
}
function toPatentTaskView(item: AppearancePatentHistoryItem): TaskItemView {
const showProgress = showFileProgress(item)
const showProgress = board.showFileProgress(item)
const progressPercent = fileProgressPercent(item)
return {
key: `patent-${item.taskId ?? item.resultId ?? item.sourceFilename}`,
@@ -228,20 +246,113 @@ function toPatentTaskView(item: AppearancePatentHistoryItem): TaskItemView {
}
}
function mergeCurrentTaskItem(item: AppearancePatentHistoryItem) {
if (item.taskId == null) return item
const liveItem = liveProgressItems.value[item.taskId]
if (!liveItem) return item
return {
...item,
...liveItem,
sourceFilename: liveItem.sourceFilename || item.sourceFilename,
resultFilename: liveItem.resultFilename || item.resultFilename,
rowCount: liveItem.rowCount ?? item.rowCount,
createdAt: liveItem.createdAt || item.createdAt,
}
// ---- 本模块的状态语义(与货源查询 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 (item.fileStatus || '').toUpperCase() === 'FAILED'
}
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()
@@ -251,15 +362,6 @@ function effectiveLlmApiKey() {
return getStoredApiSecret('appearance-patent').trim()
}
function uidForStorage() {
return typeof window !== 'undefined' ? window.localStorage.getItem('uid') || '0' : '0'
}
function pollingKey() {
return `appearance-patent:tasks:${uidForStorage()}`
}
function toTaskSummary(result: AppearancePatentParseVo): TaskSummary {
return {
taskId: result.taskId,
@@ -270,80 +372,6 @@ function toTaskSummary(result: AppearancePatentParseVo): TaskSummary {
}
}
function savePollingIds() {
if (typeof window === 'undefined') return
const ids = Array.from(new Set([...pollingTaskIds.value, ...pendingFileTaskIds.value]))
if (!ids.length) window.localStorage.removeItem(pollingKey())
else window.localStorage.setItem(pollingKey(), JSON.stringify(ids))
}
function loadPollingIds() {
if (typeof window === 'undefined') return
try {
const raw = window.localStorage.getItem(pollingKey())
const ids = raw ? JSON.parse(raw) : []
pollingTaskIds.value = Array.isArray(ids)
? ids.filter((id): id is number => typeof id === 'number' && id > 0)
: []
} catch {
pollingTaskIds.value = []
}
}
async function selectFiles() {
const api = getPywebviewApi()
if (!api?.select_brand_xlsx_files || !api.upload_file_to_java) {
ElMessage.warning('当前环境不支持文件选择或上传')
return
}
const paths = await api.select_brand_xlsx_files()
if (!paths?.length) return
if (!(await passGuard(checkSelectedFiles(paths, { allowedExtensions: EXCEL_EXTENSIONS })))) return
try {
const files = await uploadPathsToJava(getPywebviewApi(), paths)
uploadedFiles.value = files
selectedFileNames.value = files.map((f) => f.relativePath || f.originalFilename || f.fileKey)
parseResult.value = null
queuedTaskSummary.value = null
} catch (error) {
// 上传失败时清空选择,避免残留上一批文件让用户误以为新文件已就绪
uploadedFiles.value = []
selectedFileNames.value = []
parseResult.value = null
queuedTaskSummary.value = null
ElMessage.error(error instanceof Error ? error.message : '文件上传失败')
}
}
async function selectFolder() {
const api = getPywebviewApi()
if (!api?.select_brand_folder) {
ElMessage.warning('当前环境不支持文件夹选择,请在本地客户端中打开')
return
}
try {
const folder = await api.select_brand_folder()
if (!folder) return
const result = await expandBrandFolderRecursive(folder)
if (!result.success || !result.items?.length) {
ElMessage.warning(result.error || '该文件夹下没有可用的 xlsx 文件')
return
}
if (!(await passGuard(checkSelectedFiles(result.items, { allowedExtensions: EXCEL_EXTENSIONS })))) return
const files = await uploadPathsToJava(getPywebviewApi(), result.items)
uploadedFiles.value = files
selectedFileNames.value = result.items.map((item) => item.relativePath || item.absolutePath)
parseResult.value = null
queuedTaskSummary.value = null
ElMessage.success(`已选择文件夹内 ${result.items.length} 个 Excel 文件`)
} catch (error) {
uploadedFiles.value = []
selectedFileNames.value = []
parseResult.value = null
ElMessage.error(error instanceof Error ? error.message : '选择失败')
}
}
/**
* 本模块按 id 列分组,同组只检测 1 次并把结论复制给组内其它行。
* 生产事故(任务 28805):源表 id 列 904 行全填 "1",整表塌成 1 组,105 秒就"完成"了。
@@ -424,10 +452,10 @@ async function pushToPythonQueue() {
pushing.value = true
try {
queuedTaskSummary.value = toTaskSummary(currentParseResult)
addPollingTask(taskId)
board.addPollingTask(taskId)
clearParsedTask()
await loadDashboard()
await loadHistory({ force: true })
await board.loadDashboard()
await board.loadHistory({ force: true })
ElMessage.success('已提交,后台自动执行中(无需打开浏览器)')
} finally {
pushing.value = false
@@ -438,476 +466,22 @@ function clearParsedTask() {
parseResult.value = null
}
function addPollingTask(taskId: number) {
if (!pollingTaskIds.value.includes(taskId)) {
pollingTaskIds.value = [...pollingTaskIds.value, taskId]
savePollingIds()
}
ensurePolling()
}
function removePollingTask(taskId: number) {
pollingTaskIds.value = pollingTaskIds.value.filter((id) => id !== taskId)
if (!pendingFileTaskIds.value.includes(taskId)) {
const next = { ...liveProgressItems.value }
delete next[taskId]
liveProgressItems.value = next
}
savePollingIds()
}
function addPendingFileTask(taskId: number) {
if (!pendingFileTaskIds.value.includes(taskId)) {
pendingFileTaskIds.value = [...pendingFileTaskIds.value, taskId]
savePollingIds()
}
ensurePolling()
}
function removePendingFileTask(taskId: number) {
pendingFileTaskIds.value = pendingFileTaskIds.value.filter((id) => id !== taskId)
if (!pollingTaskIds.value.includes(taskId)) {
const next = { ...liveProgressItems.value }
delete next[taskId]
liveProgressItems.value = next
}
savePollingIds()
}
function ensurePolling() {
if (disposed) return
if (pollTimer.value != null) return
scheduleNextPoll(true)
}
function stopPolling() {
if (pollTimer.value != null) {
timers.clearTimer('task-poll', pollTimer.value)
pollTimer.value = null
}
}
function scheduleNextPoll(immediate = false) {
if (disposed) return
if (pollTimer.value != null) {
if (!immediate) return
timers.clearTimer('task-poll', pollTimer.value)
pollTimer.value = null
}
const run = async () => {
pollTimer.value = null
if (disposed) return
if (!pollingTaskIds.value.length && !pendingFileTaskIds.value.length) return
await refreshTaskProgress()
if (!disposed && pollTimer.value == null && (pollingTaskIds.value.length || pendingFileTaskIds.value.length)) {
pollTimer.value = timers.setTimeout('task-poll', run, getTaskPollIntervalMs())
}
}
if (immediate) void run()
else pollTimer.value = timers.setTimeout('task-poll', run, getTaskPollIntervalMs())
}
/** 结果行版本跟踪(审查 F5 后续):版本未变的任务跳过行明细拉取 */
const rowsVersionTracker = createRowsVersionTracker()
async function refreshTaskProgress() {
if (pollingInFlight.value || (!pollingTaskIds.value.length && !pendingFileTaskIds.value.length)) {
if (!pollingTaskIds.value.length && !pendingFileTaskIds.value.length) stopPolling()
return
}
pollingInFlight.value = true
try {
let shouldRefreshDashboard = false
let shouldRefreshHistory = false
const taskIds = Array.from(new Set([...pollingTaskIds.value, ...pendingFileTaskIds.value]))
if (taskIds.length) {
// 行数据按需拉取(审查 F5 后续):等结果文件(pending)时必须强刷;其余情况版本未变的任务跳过
let heavyIds = taskIds
const mustForce = pendingFileTaskIds.value.length > 0
if (!mustForce) {
try {
const light = await getModuleProgressLight('appearancePatent', taskIds)
heavyIds = rowsVersionTracker.selectTasksNeedingRows(light.items || [], taskIds)
if (!heavyIds.length && !(light.missingTaskIds || []).length) {
// 行数据与状态都没变:本轮不拉行明细,直接结束
return
}
} catch {
// 轻量端点不可用(老后端/网络)→ 照旧全量拉取,行为与原来一致
heavyIds = taskIds
}
}
const batch = await getAppearancePatentTaskProgressBatch(heavyIds, { force: mustForce })
for (const detail of batch.items || []) {
const task = detail.task
if (!task?.id) continue
const item = detail.items?.[0]
if (item) {
liveProgressItems.value = {
...liveProgressItems.value,
[task.id]: item,
}
mergeHistoryItem(item)
}
if (task.status === 'SUCCESS' || task.status === 'FAILED') {
removePollingTask(task.id)
shouldRefreshDashboard = true
if (item && isResultPreparing(item)) addPendingFileTask(task.id)
else removePendingFileTask(task.id)
}
if (item && (task.status === 'SUCCESS' || task.status === 'FAILED') && pendingFileTaskIds.value.includes(task.id)) {
const fileStatus = (item.fileStatus || '').toUpperCase()
if (item.fileReady || fileStatus === 'SUCCESS' || fileStatus === 'FAILED') {
removePendingFileTask(task.id)
shouldRefreshDashboard = true
shouldRefreshHistory = true
}
}
}
if (batch.missingTaskIds?.length) {
batch.missingTaskIds.forEach((taskId) => {
removePollingTask(taskId)
removePendingFileTask(taskId)
})
shouldRefreshHistory = true
shouldRefreshDashboard = true
}
}
if (shouldRefreshDashboard) {
await loadDashboard()
}
if (shouldRefreshHistory) {
await loadHistory()
}
settlePendingFileTasks()
} finally {
pollingInFlight.value = false
}
}
function mergeHistoryItem(item: AppearancePatentHistoryItem) {
if (!item.taskId && !item.resultId) return
const index = historyItems.value.findIndex((row) =>
(item.resultId != null && row.resultId === item.resultId)
|| (item.taskId != null && row.taskId === item.taskId),
)
if (index >= 0) {
historyItems.value[index] = { ...historyItems.value[index], ...item }
} else {
historyItems.value = [item, ...historyItems.value]
}
}
function settlePendingFileTasks() {
if (!pendingFileTaskIds.value.length) return
const remaining: number[] = []
for (const taskId of pendingFileTaskIds.value) {
const item = historyItems.value.find((row) => row.taskId === taskId)
if (!item) {
remaining.push(taskId)
continue
}
const taskStatus = (item.taskStatus || '').toUpperCase()
const fileStatus = (item.fileStatus || '').toUpperCase()
if (item.fileReady || fileStatus === 'SUCCESS' || fileStatus === 'FAILED') {
continue
}
if (taskStatus === 'SUCCESS' || taskStatus === 'FAILED') {
remaining.push(taskId)
}
}
pendingFileTaskIds.value = remaining
savePollingIds()
if (pendingFileTaskIds.value.length) ensurePolling()
}
function seedPendingFileTasksFromHistory() {
const ids = historyItems.value
.filter((item) => item.taskId != null && isResultPreparing(item))
.map((item) => item.taskId as number)
pendingFileTaskIds.value = Array.from(new Set(ids))
savePollingIds()
if (pendingFileTaskIds.value.length) ensurePolling()
}
function seedRunningTasksFromHistory() {
const ids = historyItems.value
.filter((item) => item.taskId != null && normalizeTaskStatus(item) === 'RUNNING')
.map((item) => item.taskId as number)
if (!ids.length) return
pollingTaskIds.value = Array.from(new Set([...pollingTaskIds.value, ...ids]))
savePollingIds()
ensurePolling()
}
async function loadDashboard() {
dashboard.value = await getAppearancePatentDashboard()
}
async function loadHistory(options: { force?: boolean } = {}) {
const now = Date.now()
if (!options.force && historyItems.value.length && now - lastHistoryLoadedAt < HISTORY_CACHE_TTL_MS) return
if (historyInFlight) return historyInFlight
historyInFlight = getAppearancePatentHistory()
.then((res) => {
historyItems.value = mergeHistoryItemsPreservingLiveProgress(historyItems.value, res.items || [])
lastHistoryLoadedAt = Date.now()
})
.finally(() => {
historyInFlight = null
})
return historyInFlight
}
function mergeHistoryItemsPreservingLiveProgress(
previousItems: AppearancePatentHistoryItem[],
incomingItems: AppearancePatentHistoryItem[],
) {
const previousByTaskId = new Map<number, AppearancePatentHistoryItem>()
const previousByResultId = new Map<number, AppearancePatentHistoryItem>()
for (const item of previousItems || []) {
if (item.taskId != null) previousByTaskId.set(item.taskId, item)
if (item.resultId != null) previousByResultId.set(item.resultId, item)
}
return (incomingItems || []).map((incoming) => {
const previous = incoming.resultId != null
? previousByResultId.get(incoming.resultId)
: incoming.taskId != null
? previousByTaskId.get(incoming.taskId)
: undefined
return mergeHistoryItemPreservingLiveProgress(previous, incoming)
})
}
function mergeHistoryItemPreservingLiveProgress(
previous: AppearancePatentHistoryItem | undefined,
incoming: AppearancePatentHistoryItem,
) {
if (!previous) return incoming
const shouldPreserveLiveProgress =
(normalizeTaskStatus(previous) === 'RUNNING' || isResultPreparing(previous) || showFileProgress(previous))
&& !showFileProgress(incoming)
&& !canDownload(incoming)
if (!shouldPreserveLiveProgress) {
return incoming
}
return {
...incoming,
fileJobId: incoming.fileJobId ?? previous.fileJobId,
fileStatus: incoming.fileStatus || previous.fileStatus,
fileError: incoming.fileError || previous.fileError,
fileReady: incoming.fileReady || previous.fileReady,
fileProgressPercent: hasMeaningfulProgressValue(incoming.fileProgressPercent)
? incoming.fileProgressPercent
: previous.fileProgressPercent,
fileProgressCurrent: hasMeaningfulProgressValue(incoming.fileProgressCurrent)
? incoming.fileProgressCurrent
: previous.fileProgressCurrent,
fileProgressTotal: hasMeaningfulProgressValue(incoming.fileProgressTotal)
? incoming.fileProgressTotal
: previous.fileProgressTotal,
fileProgressMessage: (incoming.fileProgressMessage || '').trim()
? incoming.fileProgressMessage
: previous.fileProgressMessage,
}
}
function hasMeaningfulProgressValue(value: unknown) {
const num = Number(value)
return Number.isFinite(num) && num > 0
}
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 (item.fileStatus || '').toUpperCase() === 'FAILED'
}
function pendingResultHint(item: AppearancePatentHistoryItem) {
if (isResultBuildFailed(item)) {
return item.fileError || '结果文件生成失败,请稍后重试或检查后端日志'
}
if (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 showFileProgress(item: AppearancePatentHistoryItem) {
const status = normalizeTaskStatus(item)
return (status === 'RUNNING' || isResultPreparing(item)) && (hasExplicitFileProgress(item) || shouldShowFallbackJobProgress(item))
}
function hasExplicitFileProgress(item: AppearancePatentHistoryItem) {
return hasFileProgressCount(item)
|| Number(item.fileProgressPercent || 0) > 0
|| Boolean((item.fileProgressMessage || '').trim())
}
function hasFileProgressCount(item: AppearancePatentHistoryItem) {
return (item.fileProgressTotal || 0) > 0
}
function activeFileJobStatus(item: AppearancePatentHistoryItem) {
return (item.fileStatus || '').toUpperCase()
}
function hasActiveFileJob(item: AppearancePatentHistoryItem) {
const fileStatus = activeFileJobStatus(item)
return item.fileJobId != null || fileStatus === 'PENDING' || fileStatus === 'RUNNING'
}
function shouldShowFallbackJobProgress(item: AppearancePatentHistoryItem) {
return hasActiveFileJob(item) && !hasExplicitFileProgress(item)
}
async function downloadResult(item: AppearancePatentHistoryItem) {
if (!item.resultId) return
const url = item.downloadUrl || getAppearancePatentResultDownloadUrl(item.resultId)
const filename = item.resultFilename || `${item.sourceFilename || 'appearance-patent'}.xlsx`
const result = await saveUrlWithProgress(url, filename, `appearance-patent:${item.resultId}`)
if (result.success) {
ElMessage.success(`已保存: ${result.path || filename}`)
} else if (result.error && result.error !== '用户取消') {
ElMessage.error(result.error)
}
}
async function deleteTaskRecord(item: AppearancePatentHistoryItem) {
if (!(await confirmTaskDeletion(item))) return
try {
if (item.taskStatus === 'RUNNING' && item.taskId) {
await deleteAppearancePatentTask(item.taskId)
removePollingTask(item.taskId)
} else if (item.resultId) {
await deleteAppearancePatentHistory(item.resultId)
}
await loadDashboard()
await loadHistory({ force: true })
ElMessage.success('已删除')
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : '删除失败')
}
}
const { batchDeleteHistory, deleteTaskRecord, downloadResult } = board
onMounted(async () => {
loadPollingIds()
board.loadPollingIds()
await Promise.all([
loadDashboard().catch(() => undefined),
loadHistory().catch(() => undefined),
board.loadDashboard().catch(() => undefined),
board.loadHistory().catch(() => undefined),
])
seedRunningTasksFromHistory()
seedPendingFileTasksFromHistory()
if (pollingTaskIds.value.length || pendingFileTaskIds.value.length) ensurePolling()
board.seedRunningTasksFromHistory()
board.seedPendingFileTasksFromHistory()
board.ensurePollingIfAny()
})
onUnmounted(() => {
disposed = true
stopPolling()
timers.clearScope()
board.dispose()
})
/**
* 历史记录批量删除:复用单条删除逻辑(删除后原函数各自刷新列表)
*/
async function batchDeleteHistory(views: TaskItemView[]) {
const { total, failed } = await runBatchDelete(views, (view) => deleteTaskRecord(itemSource(view)))
if (!total) return
if (failed > 0) {
ElMessage.warning(`删除完成,${failed} 条失败`)
} else {
ElMessage.success(`已删除 ${total} 条历史记录`)
}
}
</script>
<style scoped>
@@ -916,18 +490,14 @@ async function batchDeleteHistory(views: TaskItemView[]) {
.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; }
.upload-zone { border: 1px dashed #3e4a62; border-radius: 10px; padding: 18px; background: #242424; margin-bottom: 18px; }
.hint, .loading-msg, .files, .muted { color: #5e6878; font-size: 12px; line-height: 1.5; }
.link { color: #6ea8fe; text-decoration: none; }
.link:hover { color: #9fc5ff; }
.btns, .run-row { display: flex; gap: 10px; flex-wrap: wrap; }
.opt-btn, .btn-run, .btn-delete, .download { border: none; cursor: pointer; border-radius: 7px; }
.opt-btn { padding: 8px 14px; color: #c8d2e2; background: #242424; border: 1px solid #3e4a62; }
.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; }
.selected-files { margin-top: 14px; color: #a0acbe; font-size: 12px; word-break: break-all; }
.selected-files span { display: block; margin: 4px 0; }
.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; }