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
@@ -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,
}
}