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
@@ -7,6 +7,8 @@ export interface UploadedJavaFile {
localPath: string;
size: number;
relativePath?: string;
/** OSS 上传模式下返回的跨节点访问地址(uploadOss=true 时桌面桥可能附带) */
url?: string;
}
export type ProxyMode = 1 | 2;
@@ -0,0 +1,142 @@
<template>
<div class="upload-zone">
<div class="hint">{{ hint }}</div>
<div class="btns">
<button type="button" class="opt-btn" :disabled="disabled" @click="emit('select-files')">
{{ uploading && uploadingLabel ? uploadingLabel : filesLabel }}
</button>
<button v-if="showFolderButton" type="button" class="opt-btn" :disabled="disabled" @click="emit('select-folder')">
{{ folderLabel }}
</button>
</div>
<div class="selected-files" :class="filesClass">
<template v-if="names.length">
<span v-for="name in visibleNames" :key="name" :title="nameTitle ? name : undefined">{{ name }}</span>
<span v-if="names.length > visibleNames.length" class="more-line">
还有 {{ names.length - visibleNames.length }} 个文件未展开显示
</span>
</template>
<span v-else :class="{ 'text-muted': mutedEmpty }">{{ emptyText }}</span>
</div>
<div v-if="footerTip" class="bridge-tip">{{ footerTip }}</div>
</div>
</template>
<script setup lang="ts">
import { computed } from 'vue'
/**
* 「上传文件」区块:选择 Excel / 文件夹按钮 + 已选文件列表。
*
* 抽自各品牌 Tab 逐字重复的 upload-zone 模板与样式;差异点全部 props 化。
* Tab 保留自己的业务状态与 selectFiles / selectFolder 实现(通常来自
* useExcelFileUpload),组件只负责展示与点击事件。
*/
const props = withDefaults(
defineProps<{
/** 区块顶部提示文案 */
hint: string
/** 已选文件展示列表(完整列表,超出 maxDisplay 时折叠) */
names: string[]
/** 未选择时的占位文案 */
emptyText?: string
/** 「选择 Excel」按钮文案 */
filesLabel?: string
/** 上传中时「选择 Excel」按钮的文案(配合 uploading) */
uploadingLabel?: string
/** 「选择文件夹」按钮文案 */
folderLabel?: string
/** 是否显示「选择文件夹」按钮 */
showFolderButton?: boolean
/** 两个按钮是否禁用 */
disabled?: boolean
/** 上传中状态(配合 uploadingLabel) */
uploading?: boolean
/** 超过该数量折叠展示;不传则全量展示 */
maxDisplay?: number
/** selected-files 容器的附加 class(如 clean-placeholder) */
filesClass?: string
/** 空态文案是否加 text-muted */
mutedEmpty?: boolean
/** 文件名 span 是否带 title 提示完整路径 */
nameTitle?: boolean
/** 区块底部的附加提示(如浏览器环境的桥接提示),空串不显示 */
footerTip?: string
}>(),
{
emptyText: '暂未选择文件',
filesLabel: '选择 Excel',
folderLabel: '选择文件夹',
showFolderButton: true,
disabled: false,
uploading: false,
mutedEmpty: false,
nameTitle: false,
footerTip: '',
},
)
const emit = defineEmits<{
(event: 'select-files'): void
(event: 'select-folder'): void
}>()
const visibleNames = computed(() =>
props.maxDisplay && props.maxDisplay > 0 ? props.names.slice(0, props.maxDisplay) : props.names,
)
</script>
<style scoped>
/* 与多数品牌 Tab 原有的 upload-zone 写法保持一致;个别 Tab 的差异样式由
Tab 自身用 :deep(.upload-zone) 等覆写 */
.upload-zone {
border: 1px dashed #3e4a62;
border-radius: 10px;
padding: 18px;
background: #242424;
margin-bottom: 18px;
}
.hint {
color: #5e6878;
font-size: 12px;
line-height: 1.5;
}
.btns {
display: flex;
gap: 10px;
flex-wrap: wrap;
}
.opt-btn {
border: none;
cursor: pointer;
border-radius: 7px;
padding: 8px 14px;
color: #c8d2e2;
background: #242424;
border: 1px solid #3e4a62;
}
.selected-files {
margin-top: 14px;
color: #a0acbe;
font-size: 12px;
word-break: break-all;
}
.selected-files span {
display: block;
margin: 4px 0;
}
.selected-files .more-line {
color: #5e6878;
}
.selected-files .text-muted {
color: #5e6878;
font-style: italic;
}
</style>
@@ -0,0 +1,210 @@
import { ref, type Ref } from 'vue'
import { ElMessage } from 'element-plus'
import { getPywebviewApi, type UploadedJavaFile } from '../bridges/pywebview.ts'
import { expandBrandFolderRecursive, type BrandExpandFolderItem } from '../api/types/modules/brand.ts'
import { EXCEL_EXTENSIONS, checkSelectedFiles } from '../dispatch-guard.ts'
import { passGuard } from '../dispatch-guard-ui.ts'
import { uploadPathsToJava, type UploadPathsToJavaOptions } from '../utils/upload-to-java.ts'
/**
* 「选文件 / 选文件夹 → 校验 → 上传 → 重置状态」组合式函数。
*
* 抽自各品牌 Tab 逐字重复的 selectFiles / selectFolder:能力检查 → 桥选路径 →
* passGuard(checkSelectedFiles(...)) → uploadPathsToJava(...) → 回填展示列表 →
* 成功 / 失败提示。各 Tab 的差异点(提示文案、展示路径来源、上传参数、成功后
* 的本地状态重置)全部参数化,保持每个 Tab 的既有行为与文案不变。
*
* 使用方式:
* const upload = useExcelFileUpload({
* onUploaded: () => { parseResult.value = null },
* })
* upload.selectFiles() / upload.selectFolder()
* upload.files / upload.selectedPaths / upload.uploading
*/
/** 选文件动作:成功回填的展示路径来源 */
export type ExcelFilePathsMode = 'uploaded' | 'raw'
/** 选文件夹动作:成功回填的展示路径来源 */
export type ExcelFolderPathsMode = 'items' | 'relative' | 'uploaded'
export interface ExcelFileUploadSuccessInfo {
action: 'files' | 'folder'
/** 上传结果列表 */
files: UploadedJavaFile[]
/** 展示用路径列表(与 selectedPaths ref 一致) */
displayPaths: string[]
/** 选文件动作的原始本机路径 */
paths?: string[]
/** 选文件夹动作的文件夹路径 */
folder?: string
/** 选文件夹动作展开出的条目 */
items?: BrandExpandFolderItem[]
}
export interface UseExcelFileUploadOptions {
/** 允许的扩展名;默认 EXCEL_EXTENSIONS */
allowedExtensions?: readonly string[]
/** 透传给 uploadPathsToJava 的参数(uploadOss / returnEmptyWhenUnavailable) */
uploadOptions?: UploadPathsToJavaOptions
/**
* 自定义「选择文件」实现(默认走桥的 select_brand_xlsx_files)。
* 返回 null / undefined / 空数组一律视为取消。
*/
pickFiles?: () => Promise<string[] | null | undefined>
/** 自定义「展开文件夹」实现(默认 expandBrandFolderRecursive) */
expandFolder?: (folder: string) => Promise<{ success: boolean; items?: BrandExpandFolderItem[]; error?: string }>
/** 选文件能力检查是否同时要求 upload_file_to_java;默认 false */
requireUploadCapability?: boolean
/** 选文件夹能力检查是否同时要求 upload_file_to_java;默认 false */
folderRequireUploadCapability?: boolean
/** 选文件能力缺失时的 warning 文案 */
pickFilesUnavailableWarning?: string
/** 选文件夹能力缺失时的 warning 文案 */
folderUnavailableWarning?: string
/** 文件夹下没有可用文件时的 warning 文案;默认 (error) => error || '该文件夹下没有可用的 xlsx 文件' */
folderEmptyWarning?: (error?: string) => string
/** 选文件成功提示;返回空串则不提示(默认不提示) */
filesSuccessMessage?: (files: UploadedJavaFile[], paths: string[]) => string
/** 选文件夹成功提示;返回空串则不提示 */
folderSuccessMessage?: (files: UploadedJavaFile[], items: BrandExpandFolderItem[]) => string
/** 失败时 ElMessage.error 的兜底文案;默认 '选择失败' */
errorFallbackMessage?: string | ((action: 'files' | 'folder') => string)
/** 选文件成功后回填展示列表的方式;默认 'uploaded'(取上传结果相对路径/文件名) */
filePathsMode?: ExcelFilePathsMode
/** 选文件夹成功后回填展示列表的方式;默认 'items'(relativePath || absolutePath) */
folderPathsMode?: ExcelFolderPathsMode
/** 上传成功回调(重置 Tab 本地解析状态等);可为 async,成功提示会等它完成 */
onUploaded?: (info: ExcelFileUploadSuccessInfo) => void | Promise<void>
/** 上传失败回调(清理 Tab 本地状态);失败时组件自身已清空 files/selectedPaths(除非 clearOnError=false) */
onFailed?: (action: 'files' | 'folder') => void
/** 选到文件夹后(展开前)回调;用于记录文件夹名等 Tab 本地状态 */
onFolderPicked?: (folder: string) => void
/** 上传失败时是否清空 files/selectedPaths;默认 true(品牌检测 Tab 上传失败保留旧文件) */
clearOnError?: boolean
}
export interface UseExcelFileUploadReturn {
/** 上传成功的结果列表 */
files: Ref<UploadedJavaFile[]>
/** 展示用路径列表(文件动作为原始路径或上传名,文件夹动作为展开条目路径) */
selectedPaths: Ref<string[]>
/** 上传进行中(仅覆盖 uploadPathsToJava 调用窗口) */
uploading: Ref<boolean>
selectFiles: () => Promise<void>
selectFolder: () => Promise<void>
/** 清空已选 / 已上传(不触发 onFailed) */
clear: () => void
}
function defaultErrorMessage(error: unknown, action: 'files' | 'folder', fallback: string | ((a: 'files' | 'folder') => string)) {
if (error instanceof Error && error.message) return error.message
return typeof fallback === 'function' ? fallback(action) : fallback
}
export function useExcelFileUpload(options: UseExcelFileUploadOptions = {}): UseExcelFileUploadReturn {
const allowedExtensions = options.allowedExtensions ?? EXCEL_EXTENSIONS
const requireUploadCapability = options.requireUploadCapability ?? false
const folderRequireUploadCapability = options.folderRequireUploadCapability ?? false
const pickWarning = options.pickFilesUnavailableWarning ?? '当前环境不支持文件选择,请在本机客户端中打开'
const folderWarning = options.folderUnavailableWarning ?? '当前环境不支持文件夹选择,请在本机客户端中打开'
const emptyWarning = options.folderEmptyWarning ?? ((error?: string) => error || '该文件夹下没有可用的 xlsx 文件')
const fallbackMessage = options.errorFallbackMessage ?? '选择失败'
const filePathsMode = options.filePathsMode ?? 'uploaded'
const folderPathsMode = options.folderPathsMode ?? 'items'
const clearOnError = options.clearOnError ?? true
const files = ref<UploadedJavaFile[]>([])
const selectedPaths = ref<string[]>([])
const uploading = ref(false)
function resetLocal() {
files.value = []
selectedPaths.value = []
}
function fail(action: 'files' | 'folder', error: unknown) {
if (clearOnError) resetLocal()
options.onFailed?.(action)
ElMessage.error(defaultErrorMessage(error, action, fallbackMessage))
}
async function selectFiles() {
try {
let paths: string[] | null | undefined
if (options.pickFiles) {
paths = await options.pickFiles()
} else {
const api = getPywebviewApi()
if (!api?.select_brand_xlsx_files || (requireUploadCapability && !api.upload_file_to_java)) {
ElMessage.warning(pickWarning)
return
}
paths = await api.select_brand_xlsx_files()
}
if (!paths?.length) return
if (!(await passGuard(checkSelectedFiles(paths, { allowedExtensions })))) return
uploading.value = true
const uploaded = await uploadPathsToJava(getPywebviewApi(), paths, options.uploadOptions)
files.value = uploaded
selectedPaths.value = filePathsMode === 'raw'
? [...paths]
: uploaded.map((f) => f.relativePath || f.originalFilename || f.fileKey)
await options.onUploaded?.({ action: 'files', files: uploaded, displayPaths: selectedPaths.value, paths: [...paths] })
const message = options.filesSuccessMessage?.(uploaded, paths)
if (message) ElMessage.success(message)
} catch (error) {
fail('files', error)
} finally {
uploading.value = false
}
}
async function selectFolder() {
try {
const api = getPywebviewApi()
if (!api?.select_brand_folder || (folderRequireUploadCapability && !api.upload_file_to_java)) {
ElMessage.warning(folderWarning)
return
}
const folder = await api.select_brand_folder()
if (!folder) return
options.onFolderPicked?.(folder)
const result = options.expandFolder
? await options.expandFolder(folder)
: await expandBrandFolderRecursive(folder)
if (!result.success || !result.items?.length) {
ElMessage.warning(emptyWarning(result.error))
return
}
if (!(await passGuard(checkSelectedFiles(result.items, { allowedExtensions })))) return
uploading.value = true
const uploaded = await uploadPathsToJava(getPywebviewApi(), result.items, options.uploadOptions)
files.value = uploaded
selectedPaths.value = resolveFolderPaths(folderPathsMode, uploaded, result.items)
await options.onUploaded?.({ action: 'folder', files: uploaded, displayPaths: selectedPaths.value, folder, items: result.items })
const message = options.folderSuccessMessage?.(uploaded, result.items)
if (message) ElMessage.success(message)
} catch (error) {
fail('folder', error)
} finally {
uploading.value = false
}
}
function clear() {
resetLocal()
}
return { files, selectedPaths, uploading, selectFiles, selectFolder, clear }
}
function resolveFolderPaths(
mode: ExcelFolderPathsMode,
uploaded: UploadedJavaFile[],
items: BrandExpandFolderItem[],
): string[] {
if (mode === 'relative') return items.map((item) => item.relativePath)
if (mode === 'uploaded') return uploaded.map((f) => f.relativePath || f.originalFilename || f.fileKey)
return items.map((item) => item.relativePath || item.absolutePath)
}
@@ -0,0 +1,713 @@
import { computed, ref, type ComputedRef, type Ref } from 'vue'
import { ElMessage } from 'element-plus'
import { getTaskPollIntervalMs } from '../task-progress-config.ts'
import { createCategorizedTimers } from '../utils/categorized-timers.ts'
import { saveUrlWithProgress } from '../utils/download-progress.ts'
import { runBatchDelete } from '../utils/batch-delete.ts'
import { confirmTaskDeletion } from '../task-delete-confirm.ts'
import type { TaskItemView } from '../components/tasks/types'
/**
* 「实时任务面板」组合式函数(BrandSimilarAsinTab / BrandAppearancePatentTab 的公共骨架)。
*
* 封装两个 Tab 逐字克隆的那部分:轮询 ID 持久化(localStorage,含 uid 后缀)、
* 双队列轮询(任务队列 + 结果文件生成队列)、live 进度合并兜底、history 去重合并、
* pending 文件任务结算、seed(从历史恢复)、下载 / 删除 / 批量删除胶水。
*
* 两 Tab 的真实差异全部参数化(见 UseLiveTaskBoardOptions):
* - 状态归一化 normalizeTaskStatus / isResultPreparing(两 Tab 语义不同)
* - 终态后是否登记 pending 文件任务、哪些任务状态参与文件结算
* - 进度批量请求的预/后处理(SimilarAsin 的 force 节流、Patent 的 light 行版本检查)
* - 轮询回调抛错时是否打断轮询(SimilarAsin 吞掉、Patent 上抛——保持原行为)
* - 下载 URL / 文件名兜底 / 进度 key 前缀、删除判定与本地清理
*
* 其余手写轮询的 Tab(DeleteBrand/PatrolDelete/QueryAsin/Withdraw 等)后续可渐进接入。
*/
/** 两个模块 history/progress item 的公共字段(SimilarAsinHistoryItem / AppearancePatentHistoryItem 结构一致) */
export interface LiveTaskHistoryItem {
resultId?: number
taskId?: number
sourceFilename?: string
resultFilename?: string
downloadUrl?: string
fileJobId?: number
fileStatus?: string
fileError?: string
fileReady?: boolean
fileProgressPercent?: number
fileProgressCurrent?: number
fileProgressTotal?: number
fileProgressMessage?: string
taskStatus?: string
success?: boolean
error?: string
rowCount?: number
createdAt?: string
startedAt?: string
finishedAt?: string
}
/** 批量进度响应的公共形状 */
export interface LiveTaskProgressDetail<TItem extends LiveTaskHistoryItem> {
task?: { id?: number; status?: string }
items?: TItem[]
}
export interface LiveTaskProgressBatch<TItem extends LiveTaskHistoryItem> {
items?: LiveTaskProgressDetail<TItem>[]
missingTaskIds?: number[]
}
export interface TaskBoardDashboardCounts {
pendingTaskCount: number
processedTaskCount: number
successTaskCount: number
failedTaskCount: number
}
export interface UseLiveTaskBoardOptions<T extends LiveTaskHistoryItem> {
/** categorized-timers 命名空间,例如 'similar-asin' */
scope: string
/** 轮询 ID 的 localStorage key(含 uid 后缀),如 () => `similar-asin:tasks:${uid}` */
pollingStorageKey: () => string
/** 历史记录接口 */
fetchHistory: () => Promise<{ items?: T[] }>
/** 批量进度接口 */
fetchProgressBatch: (taskIds: number[], options: { force: boolean }) => Promise<LiveTaskProgressBatch<T>>
/** 统计卡片接口 */
fetchDashboard: () => Promise<TaskBoardDashboardCounts>
/** 状态归一化(两 Tab 实现不同,必传) */
normalizeTaskStatus: (item: T) => string
/** 结果文件是否在生成中(两 Tab 实现不同,必传) */
isResultPreparing: (item: T) => boolean
/**
* 任务到达终态(SUCCESS/FAILED)后是否登记为「结果生成中」待跟踪任务。
* SimilarAsin: status === 'SUCCESS';Patent: item 存在且 isResultPreparing(item)。
*/
addPendingAfterFinalStatus: (task: { id?: number; status?: string }, item: T | undefined) => boolean
/**
* settlePendingFileTasks:对已找到 history 条目、文件未完成的任务,是否继续保留跟踪。
* SimilarAsin: taskStatus === 'SUCCESS';Patent: SUCCESS || FAILED。
*/
keepPendingFileTask: (item: T, taskStatus: string) => boolean
/** 终态后进行文件状态结算检查的任务状态集合。SimilarAsin: ['SUCCESS'];Patent: ['SUCCESS','FAILED'] */
settleOnTaskStatuses: string[]
/**
* 批量进度请求预处理:可裁剪 taskIds / 决定 force;返回 null 表示本轮直接跳过
* (Patent 的 light 行版本检查)。缺省为全量拉取、force=false。
*/
beforeBatch?: (
taskIds: number[],
pendingFileTaskIds: number[],
) => Promise<{ taskIds: number[]; force: boolean } | null> | { taskIds: number[]; force: boolean } | null
/** 批量进度请求后处理(SimilarAsin 的 force 节流登记)。 */
afterBatch?: (taskIds: number[], pendingFileTaskIds: number[], forced: boolean) => void
/**
* 轮询回调抛错时的处理:
* - 'swallow'(SimilarAsin):瞬时失败不打断轮询;
* - 'propagate'(Patent):异常上抛,轮询停止(与原实现一致)。
*/
pollErrorMode?: 'swallow' | 'propagate'
/** pending 文件任务被移除时的回调(SimilarAsin 的 forceThrottle.clear) */
onPendingFileTaskRemoved?: (taskId: number) => void
/** 当前任务区顶部的「解析待启动」占位条目;返回 null 表示没有 */
getPendingParseItem?: () => T | null
/** 下载胶水的模块差异 */
download?: {
/** resultId -> 下载地址(item.downloadUrl 优先) */
buildUrl: (resultId: number, item: T) => string
/** 文件名兜底前缀(item.sourceFilename 缺失时) */
fallbackFilename: string
/** 下载进度 key 前缀,如 'similar-asin' */
progressKeyPrefix: string
}
/** 删除胶水的模块差异 */
deleteTask?: {
/** 是否按「删除整个任务」处理(两 Tab 判定不同) */
shouldDeleteTask: (item: T, normalizedStatus: string) => boolean
deleteTask: (taskId: number) => Promise<unknown>
deleteHistory: (resultId: number) => Promise<unknown>
/** 任务删除成功后的本地清理 */
onTaskDeleted?: (item: T) => void
/** 结果记录删除成功后的本地清理 */
onHistoryDeleted?: (item: T) => void
}
}
export interface UseLiveTaskBoardReturn<T extends LiveTaskHistoryItem> {
/** 轮询中的任务队列(任务执行中) */
pollingTaskIds: Ref<number[]>
/** 结果文件生成中待跟踪队列(任务终态后文件仍未就绪) */
pendingFileTaskIds: Ref<number[]>
/** 最近一次 progress/batch 的实时进度缓存(history 兜底) */
liveProgressItems: Ref<Record<number, T>>
/** 历史记录(含进行中的;展示时经 historyOnlyItems 过滤) */
historyItems: Ref<T[]>
/** 统计卡片数据 */
dashboard: Ref<TaskBoardDashboardCounts>
/** 当前任务区条目(轮询/进行中 + live 兜底 + 解析占位) */
currentItems: ComputedRef<T[]>
/** 纯历史条目(排除 RUNNING/PENDING) */
historyOnlyItems: ComputedRef<T[]>
/** 从 localStorage 恢复轮询 ID */
loadPollingIds: () => void
/** 挂载后恢复种子:从历史回填 pending 文件任务与进行中任务 */
seedPendingFileTasksFromHistory: () => void
seedRunningTasksFromHistory: () => void
/** 有任何待轮询任务时启动轮询(与原 Tab 的 onMounted 守卫一致) */
ensurePollingIfAny: () => void
ensurePolling: () => void
stopPolling: () => void
/** 卸载清理(停止轮询 + 清空 timers) */
dispose: () => void
addPollingTask: (taskId: number) => void
removePollingTask: (taskId: number) => void
addPendingFileTask: (taskId: number) => void
removePendingFileTask: (taskId: number) => void
loadDashboard: () => Promise<void>
loadHistory: (options?: { force?: boolean }) => Promise<void>
refreshTaskProgress: () => Promise<void>
/** 状态判定(透出传入的实现与公共实现,供 Tab 的视图层函数复用) */
normalizeTaskStatus: (item: T) => string
isResultPreparing: (item: T) => boolean
canDownload: (item: T) => boolean
showFileProgress: (item: T) => boolean
downloadResult: (item: T) => Promise<void>
deleteTaskRecord: (item: T) => Promise<void>
/** 历史记录批量删除(复用单条删除逻辑) */
batchDeleteHistory: (views: TaskItemView[]) => Promise<void>
}
/** 模块无关的文件进度字段判定(两 Tab 逐字相同,抽为纯函数) */
export function hasMeaningfulProgressValue(value: unknown) {
const num = Number(value)
return Number.isFinite(num) && num > 0
}
export function activeFileJobStatus(item: LiveTaskHistoryItem) {
return (item.fileStatus || '').toUpperCase()
}
export function hasActiveFileJob(item: LiveTaskHistoryItem) {
const fileStatus = activeFileJobStatus(item)
return item.fileJobId != null || fileStatus === 'PENDING' || fileStatus === 'RUNNING'
}
export function hasFileProgressCount(item: LiveTaskHistoryItem) {
return (item.fileProgressTotal || 0) > 0
}
export function hasExplicitFileProgress(item: LiveTaskHistoryItem) {
return hasFileProgressCount(item)
|| Number(item.fileProgressPercent || 0) > 0
|| Boolean((item.fileProgressMessage || '').trim())
}
export function shouldShowFallbackJobProgress(item: LiveTaskHistoryItem) {
return hasActiveFileJob(item) && !hasExplicitFileProgress(item)
}
/** 两个 Tab 的 canDownload 实现逐字相同 */
export function defaultCanDownload(item: LiveTaskHistoryItem) {
return Boolean(item.resultId && (item.fileReady || item.downloadUrl))
}
const HISTORY_CACHE_TTL_MS = 3000
export function useLiveTaskBoard<T extends LiveTaskHistoryItem>(
options: UseLiveTaskBoardOptions<T>,
): UseLiveTaskBoardReturn<T> {
const timers = createCategorizedTimers(options.scope)
const pollErrorMode = options.pollErrorMode ?? 'swallow'
const pollingTaskIds = ref<number[]>([])
const pendingFileTaskIds = ref<number[]>([])
const liveProgressItems = ref({}) as Ref<Record<number, T>>
const historyItems = ref([]) as Ref<T[]>
const dashboard = ref<TaskBoardDashboardCounts>({
pendingTaskCount: 0,
processedTaskCount: 0,
successTaskCount: 0,
failedTaskCount: 0,
})
const pollTimer = ref<number | null>(null)
const pollingInFlight = ref(false)
let historyInFlight: Promise<void> | null = null
let lastHistoryLoadedAt = 0
let disposed = false
const { normalizeTaskStatus, isResultPreparing } = options
const canDownload = defaultCanDownload
function showFileProgress(item: T) {
const status = normalizeTaskStatus(item)
return (status === 'RUNNING' || isResultPreparing(item)) && (hasExplicitFileProgress(item) || shouldShowFallbackJobProgress(item))
}
// ---- 当前任务 / 纯历史(两 Tab 逐字相同)----
const currentItems = computed<T[]>(() => {
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))
// 兜底:history 暂未返回该任务,但实时缓存里仍在跑,保留它在当前任务区
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))
}
const pendingParseItem = options.getPendingParseItem?.() ?? null
if (!pendingParseItem) return activeItems
const exists = activeItems.some((item) => item.taskId === pendingParseItem.taskId)
return exists ? activeItems : [pendingParseItem, ...activeItems]
})
const historyOnlyItems = computed<T[]>(() =>
historyItems.value.filter((i) => {
const status = normalizeTaskStatus(i)
return status !== 'RUNNING' && status !== 'PENDING'
}),
)
// ---- 轮询 ID 持久化(两 Tab 逐字相同,仅 key 不同)----
function pollingKey() {
return options.pollingStorageKey()
}
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 = []
}
}
// ---- 双队列维护(两 Tab 逐字相同;removePendingFileTask 多一个回调钩子)----
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)
options.onPendingFileTaskRemoved?.(taskId)
if (!pollingTaskIds.value.includes(taskId)) {
const next = { ...liveProgressItems.value }
delete next[taskId]
liveProgressItems.value = next
}
savePollingIds()
}
// ---- 轮询循环(两 Tab 逐字相同;抛错处理按 pollErrorMode 参数化)----
function ensurePolling() {
if (disposed) return
if (pollTimer.value != null) return
scheduleNextPoll(true)
}
function ensurePollingIfAny() {
if (pollingTaskIds.value.length || pendingFileTaskIds.value.length) ensurePolling()
}
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
}
if (immediate) void runPollCycle()
else pollTimer.value = timers.setTimeout('task-poll', runPollCycle, getTaskPollIntervalMs())
}
async function runPollCycle() {
pollTimer.value = null
if (disposed) return
if (!pollingTaskIds.value.length && !pendingFileTaskIds.value.length) return
if (pollErrorMode === 'propagate') {
await refreshTaskProgress()
scheduleFollowUp()
} else {
try {
await refreshTaskProgress()
} catch {
// A transient request failure must not stop progress polling permanently.
} finally {
scheduleFollowUp()
}
}
}
function scheduleFollowUp() {
if (!disposed && pollTimer.value == null && (pollingTaskIds.value.length || pendingFileTaskIds.value.length)) {
pollTimer.value = timers.setTimeout('task-poll', runPollCycle, getTaskPollIntervalMs())
}
}
// ---- 进度批量刷新(差异点经 beforeBatch / afterBatch / 钩子参数化)----
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) {
let batchIds = taskIds
let force = false
const prepared = options.beforeBatch
? await options.beforeBatch(taskIds, pendingFileTaskIds.value)
: { taskIds, force: false }
if (!prepared) {
// 预处理判断本轮无需拉取(Patent 的行版本未变路径):直接结束,不做结算
return
}
batchIds = prepared.taskIds
force = prepared.force
const batch = await options.fetchProgressBatch(batchIds, { force })
if (options.afterBatch) options.afterBatch(taskIds, pendingFileTaskIds.value, force)
for (const detail of batch.items || []) {
const task = detail.task
if (!task?.id) continue
const item = detail.items?.[0]
if (item) {
// 实时缓存:以最新一次 progress 为准,避免 history 接口字段缺失/延迟时丢失进度
liveProgressItems.value = {
...liveProgressItems.value,
[task.id]: item,
}
mergeHistoryItem(item)
}
if (task.status === 'SUCCESS' || task.status === 'FAILED') {
removePollingTask(task.id)
shouldRefreshDashboard = true
if (options.addPendingAfterFinalStatus(task, item)) addPendingFileTask(task.id)
else removePendingFileTask(task.id)
}
if (item && options.settleOnTaskStatuses.includes(task.status || '') && 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
}
}
// ---- history 合并(两 Tab 逐字相同)----
function mergeHistoryItem(item: T) {
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 mergeCurrentTaskItem(item: T) {
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,
}
}
function mergeHistoryItemsPreservingLiveProgress(
previousItems: T[],
incomingItems: T[],
) {
const previousByTaskId = new Map<number, T>()
const previousByResultId = new Map<number, T>()
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: T | undefined,
incoming: T,
) {
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,
}
}
// ---- pending 文件任务结算与种子恢复(差异点经 keepPendingFileTask 参数化)----
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 (options.keepPendingFileTask(item, taskStatus)) {
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()
}
// ---- 数据加载(两 Tab 逐字相同,仅接口不同)----
async function loadDashboard() {
dashboard.value = await options.fetchDashboard()
}
async function loadHistory(opts: { force?: boolean } = {}) {
const now = Date.now()
if (!opts.force && historyItems.value.length && now - lastHistoryLoadedAt < HISTORY_CACHE_TTL_MS) return
if (historyInFlight) return historyInFlight
historyInFlight = options
.fetchHistory()
.then((res) => {
historyItems.value = mergeHistoryItemsPreservingLiveProgress(historyItems.value, res.items || [])
lastHistoryLoadedAt = Date.now()
})
.finally(() => {
historyInFlight = null
})
return historyInFlight
}
// ---- 下载 / 删除 / 批量删除胶水(差异点经 options 参数化)----
async function downloadResult(item: T) {
if (!item.resultId || !options.download) return
const url = item.downloadUrl || options.download.buildUrl(item.resultId, item)
const filename = item.resultFilename || `${item.sourceFilename || options.download.fallbackFilename}.xlsx`
const result = await saveUrlWithProgress(url, filename, `${options.download.progressKeyPrefix}:${item.resultId}`)
if (result.success) {
ElMessage.success(`已保存: ${result.path || filename}`)
} else if (result.error && result.error !== '用户取消') {
ElMessage.error(result.error)
}
}
async function deleteTaskRecord(item: T) {
if (!(await confirmTaskDeletion(item))) return
try {
const status = normalizeTaskStatus(item)
const deleteOptions = options.deleteTask
if (deleteOptions && deleteOptions.shouldDeleteTask(item, status)) {
await deleteOptions.deleteTask(item.taskId as number)
deleteOptions.onTaskDeleted?.(item)
} else if (item.resultId && deleteOptions) {
await deleteOptions.deleteHistory(item.resultId)
deleteOptions.onHistoryDeleted?.(item)
}
await loadDashboard()
await loadHistory({ force: true })
ElMessage.success('已删除')
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : '删除失败')
}
}
/**
* 历史记录批量删除:复用单条删除逻辑(删除后原函数各自刷新列表)
*/
async function batchDeleteHistory(views: TaskItemView[]) {
const { total, failed } = await runBatchDelete(views, (view) => deleteTaskRecord(view.source as T))
if (!total) return
if (failed > 0) {
ElMessage.warning(`删除完成,${failed} 条失败`)
} else {
ElMessage.success(`已删除 ${total} 条历史记录`)
}
}
function dispose() {
disposed = true
stopPolling()
timers.clearScope()
}
return {
pollingTaskIds,
pendingFileTaskIds,
liveProgressItems,
historyItems,
dashboard,
currentItems,
historyOnlyItems,
loadPollingIds,
seedPendingFileTasksFromHistory,
seedRunningTasksFromHistory,
ensurePollingIfAny,
ensurePolling,
stopPolling,
dispose,
addPollingTask,
removePollingTask,
addPendingFileTask,
removePendingFileTask,
loadDashboard,
loadHistory,
refreshTaskProgress,
normalizeTaskStatus,
isResultPreparing,
canDownload,
showFileProgress,
downloadResult,
deleteTaskRecord,
batchDeleteHistory,
}
}