Files
crawler-plugin/frontend-vue/src/pages/brand/components/BrandConvertTab.vue
T
huangzd1997 aa7e17f95c feat(task-board): 手动刷新铺满全部 16 个任务面板页
用户点名「只要是任务的功能都要加上」:TaskCenterPanel 的 on-refresh 按各自骨架接线
——useLiveTaskBoard 两页强拉 history+dashboard+进度;手写 fetch 五页 allSettled
(history+dashboard+refreshTaskBatch);useHistoryPolling 三页 refreshTaskViews+活跃进度;
useTaskProgressLoop 两页加 progressLoop.refreshOnce;一次性拉取三页直挂各自 load 函数;
品牌检测复用既有 syncTasksAndResumePolling。接线守卫测试扩到 16 页。
2026-10-22 15:48:44 +08:00

637 lines
17 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="convert">
<div class="main-content">
<aside class="left-panel">
<div class="section-title">选择文件</div>
<FileUploadZone
hint="选择需要转换的 Excel 文件或文件夹,将按所选模板生成 txt 文件。"
:names="convertSelectedPaths"
:max-display="8"
files-label="选择 Excel 文件"
empty-text="暂未选择待转换文件"
files-class="clean-placeholder"
@select-files="selectConvertFiles"
@select-folder="selectConvertFolder"
/>
<div class="section-title">模板选择</div>
<div class="option-group">
<label v-for="template in convertTemplates" :key="template.id" class="radio-item"
:class="{ active: convertTemplateId === template.id }">
<input v-model="convertTemplateId" type="radio" :value="template.id" name="convert-template" />
<div class="template-item-content">
<div>
<span class="label">
{{ template.templateName }}
<span v-if="template.isDefault" class="template-tag">默认</span>
<span v-else-if="template.builtIn" class="template-tag muted">内置</span>
<span v-else class="template-tag custom">自定义</span>
</span>
<div class="desc">输出文件:{{ template.outputFilename }}</div>
</div>
</div>
</label>
<div v-if="!convertTemplates.length" class="empty-option">暂无可用模板</div>
</div>
<div class="section-title">转换说明</div>
<div class="option-group">
<label class="radio-item active">
<input type="checkbox" checked disabled />
<div>
<span class="label">按当前模板输出</span>
<div class="desc">当前模板:{{ currentConvertTemplate?.templateName || '未加载模板' }}</div>
</div>
</label>
<label class="radio-item active">
<input type="checkbox" checked disabled />
<div>
<span class="label">SKU 使用雪花ID-序号</span>
<div class="desc">例如 1773816146796-1</div>
</div>
</label>
</div>
<div class="run-row">
<button type="button" class="btn-run" :disabled="convertRunning" @click="submitConvertRun">
{{ convertRunning ? '转换中...' : '开始转换' }}
</button>
<span class="loading-msg">
{{ convertRunning ? '正在生成并上传结果,请稍候…' : '选择文件后即可执行格式转换,结果会显示在右侧供下载' }}
</span>
</div>
</aside>
<section class="right-panel">
<TaskCenterPanel
:on-batch-delete="batchDeleteHistory"
:on-refresh="loadConvertHistory"
title="转换结果"
:cards="convertCards"
:current-items="currentTaskViews"
:history-items="historyTaskViews"
current-title="当前任务"
current-empty-text="暂无当前任务,完成格式转换后会在这里展示"
history-empty-text="暂无历史记录"
>
<template #history-item-actions="{ item }">
<template v-if="itemSource(item)">
<button
v-if="itemSource(item).success && (itemSource(item).downloadUrl || itemSource(item).resultId)"
type="button"
class="download"
@click="downloadConvertResult(itemSource(item))"
>
下载压缩包
</button>
<button
v-if="itemSource(item).resultId"
type="button"
class="btn-delete"
@click="deleteConvertHistoryRecord(itemSource(item).resultId!)"
>
删除
</button>
</template>
</template>
</TaskCenterPanel>
</section>
</div>
</AmazonToolPageShell>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { userNotice } from '@/shared/utils/user-notice'
import { ElMessage } from 'element-plus'
import AmazonToolPageShell from '@/pages/amazon/components/AmazonToolPageShell.vue';
import FileUploadZone from '@/shared/components/FileUploadZone.vue'
import TaskCenterPanel from '@/shared/components/tasks/TaskCenterPanel.vue'
import type { TaskItemView, TaskStatCard } from '@/shared/components/tasks/types'
import {
deleteConvertHistory,
getConvertHistory,
getConvertResultDownloadUrl,
getConvertTemplates,
runConvert,
type ConvertResultItem,
type ConvertTemplateVo,
} from '@/shared/api/java-modules'
import { saveUrlWithProgress } from '@/shared/utils/download-progress'
import { collectDistinctErrors, guardBlocked } from '@/shared/dispatch-guard'
import { passGuard } from '@/shared/dispatch-guard-ui'
import { useExcelFileUpload } from '@/shared/composables/useExcelFileUpload'
import { formatDateTime } from '@/shared/utils/datetime'
import { runBatchDelete } from '@/shared/utils/batch-delete'
const {
files: convertUploadedFiles,
selectedPaths: convertSelectedPaths,
selectFiles: selectConvertFiles,
selectFolder: selectConvertFolder,
} = useExcelFileUpload({
// 展示原始本机路径;文件夹展开后只展示相对路径(与原实现一致)
filePathsMode: 'raw',
folderPathsMode: 'relative',
filesSuccessMessage: (_files, paths) => `已选择 ${paths.length} 个待转换文件`,
folderSuccessMessage: (_files, items) => `已选择文件夹内 ${items.length} 个 xlsx 文件`,
folderEmptyWarning: (error) => error || '该文件夹下没有 xlsx 文件',
onFolderPicked: (folder) => {
convertArchiveName.value = folder.split(/[/\\]/).filter(Boolean).pop() || ''
},
onUploaded: (info) => {
if (info.action === 'files') convertArchiveName.value = ''
},
})
const convertArchiveName = ref('')
const convertRunning = ref(false)
const convertResultItems = ref<ConvertResultItem[]>([])
const convertTemplates = ref<ConvertTemplateVo[]>([])
const convertTemplateId = ref('')
const currentConvertTemplate = computed(
() => convertTemplates.value.find((item) => item.id === convertTemplateId.value) || null,
)
// ---- 右侧任务面板统一视图(TaskCenterPanel)----
const convertCards = computed<TaskStatCard[]>(() => [
{ label: '运行中任务', value: currentTaskViews.value.length },
{ label: '已结束任务', value: historyTaskViews.value.length },
{ label: '成功任务', value: historyTaskViews.value.filter((view) => view.statusClass === 'success').length },
{ label: '失败任务', value: historyTaskViews.value.filter((view) => view.statusClass === 'failed').length },
])
function isConvertTaskBusy(item: ConvertResultItem) {
const status = (item.taskStatus || '').toUpperCase()
return status === 'RUNNING' || status === 'PENDING'
}
/** 当前任务:运行中/待执行项(转换接口通常同步完成即出结果,正常为空) */
const currentTaskViews = computed<TaskItemView[]>(() =>
convertResultItems.value.filter(isConvertTaskBusy).map(toConvertTaskView),
)
/** 历史任务:全部已结束的结果项 */
const historyTaskViews = computed<TaskItemView[]>(() =>
convertResultItems.value.filter((item) => !isConvertTaskBusy(item)).map(toConvertTaskView),
)
function itemSource(item: TaskItemView): ConvertResultItem {
return item.source as ConvertResultItem
}
function convertTaskStatusText(item: ConvertResultItem) {
const status = (item.taskStatus || '').toUpperCase()
if (status === 'RUNNING') return '执行中'
if (status === 'PENDING') return '等待中'
return item.success ? '已完成' : '失败'
}
function convertTaskStatusClass(item: ConvertResultItem) {
const status = (item.taskStatus || '').toUpperCase()
if (status === 'RUNNING') return 'running'
if (status === 'PENDING') return 'pending'
return item.success ? 'success' : 'failed'
}
function toConvertTaskView(item: ConvertResultItem): TaskItemView {
return {
key: `convert-${item.resultId ?? item.sourceFilename}`,
title: item.sourceFilename || '格式转换',
taskId: item.taskId ?? '-',
startedAt: formatDateTime(item.startedAt || item.createdAt),
finishedAt: formatDateTime(item.finishedAt),
statusText: convertTaskStatusText(item),
statusClass: convertTaskStatusClass(item),
extraLines: [
...(item.outputFilename ? [`压缩包文件:${item.outputFilename}`] : []),
...(item.error ? [`错误信息:${userNotice(item.error)}`] : []),
],
// 显式给 null:这一类是点了就跑完的一次性操作,卡片列的是完成记录,没有可数的分母。写死 null 而不是省略字段,是为了让「没得画」和「忘了接」在代码里长得不一样(守卫:tests/task-progress-view-wiring.test.ts)。
progress: null,
source: item,
}
}
async function loadConvertTemplates(preferredTemplateId?: string) {
const templates = await getConvertTemplates()
convertTemplates.value = templates || []
if (preferredTemplateId && convertTemplates.value.some((item) => item.id === preferredTemplateId)) {
convertTemplateId.value = preferredTemplateId
return
}
const existing = convertTemplates.value.find((item) => item.id === convertTemplateId.value)
if (existing) {
convertTemplateId.value = existing.id
return
}
const defaultTemplate = convertTemplates.value.find((item) => item.isDefault)
if (defaultTemplate) {
convertTemplateId.value = defaultTemplate.id
return
}
convertTemplateId.value = convertTemplates.value[0]?.id || ''
}
async function submitConvertRun() {
if (!convertUploadedFiles.value.length) {
ElMessage.warning('请先选择待转换 Excel 文件或文件夹')
return
}
if (!convertTemplateId.value) {
ElMessage.warning('请先选择模板')
return
}
try {
convertRunning.value = true
const result = await runConvert({
files: convertUploadedFiles.value.map((item) => ({
fileKey: item.fileKey,
originalFilename: item.originalFilename,
relativePath: item.relativePath,
})),
templateId: convertTemplateId.value,
archiveName:
convertUploadedFiles.value.some((item) => !!item.relativePath) && convertArchiveName.value
? convertArchiveName.value
: undefined,
})
convertResultItems.value = result.items || []
await loadConvertHistory()
if (result.total > 0 && result.successCount === 0) {
// 逐文件原因就在 items[].error 里,优先直接列出,不再让用户对着「常见原因」猜
const details = collectDistinctErrors((result.items || []).map((item) => item.error)).slice(0, 5)
await passGuard(
guardBlocked(
'格式转换未成功',
`本次提交的 ${result.total} 个文件全部转换失败。\n` +
(details.length
? `失败原因:\n${details.map((message) => `· ${message}`).join('\n')}\n`
: '常见原因是源文件表头与所选模板不匹配,或文件内没有数据行。\n') +
'请在右侧结果列表查看每个文件的失败原因,或换一个模板后重试。',
'convert.all-failed',
),
)
return
}
ElMessage.success('格式转换完成')
} catch (error) {
ElMessage.error(error instanceof Error ? error.message : '格式转换失败')
} finally {
convertRunning.value = false
}
}
async function loadConvertHistory() {
try {
const response = await getConvertHistory()
convertResultItems.value = response.items || []
} catch {
// ignore history load errors
}
}
async function deleteConvertHistoryRecord(resultId: number) {
try {
await deleteConvertHistory(resultId)
await loadConvertHistory()
ElMessage.success('已删除')
} catch (error) {
ElMessage.error(error instanceof Error ? error.message : '删除失败')
}
}
async function downloadConvertResult(item: ConvertResultItem) {
const url = item.downloadUrl || (item.resultId ? getConvertResultDownloadUrl(item.resultId) : '')
if (!url) {
ElMessage.warning('当前结果没有下载地址')
return
}
const filename = item.outputFilename || `${new Date().toISOString().slice(0, 10).replace(/-/g, '')}.txt`
const result = await saveUrlWithProgress(url, filename, item.resultId ? `convert:${item.resultId}` : undefined)
if (result.success) {
ElMessage.success(`已保存:${result.path || filename}`)
} else if (result.error && result.error !== '用户取消') {
ElMessage.error(userNotice(result.error))
}
}
onMounted(() => {
loadConvertTemplates().catch(() => undefined)
loadConvertHistory().catch(() => undefined)
})
/**
* 历史记录批量删除:复用单条删除逻辑(删除后原函数各自刷新列表)
*/
async function batchDeleteHistory(views: TaskItemView[]) {
const { total, failed } = await runBatchDelete(views, (view) => deleteConvertHistoryRecord(itemSource(view).resultId!))
if (!total) return
if (failed > 0) {
ElMessage.warning(`删除完成,${failed} 条失败`)
} else {
ElMessage.success(`已删除 ${total} 条历史记录`)
}
}
</script>
<style scoped>
.module-page {
min-height: 100vh;
background: #242424;
}
.main-content {
display: flex;
min-height: calc(100vh - 56px);
height: calc(100vh - 56px);
}
.left-panel {
width: 380px;
background: #242424;
padding: 20px;
overflow-y: auto;
border-right: 1px solid #2e3a52;
}
.right-panel {
flex: 1;
display: flex;
flex-direction: column;
min-width: 0;
background: #242424;
}
.section-title {
font-size: 13px;
color: #a0acbe;
margin-bottom: 10px;
}
/* upload-zone 已抽到 FileUploadZone 组件;这里保留本 Tab 的差异样式 */
:deep(.upload-zone) {
padding: 24px;
text-align: center;
margin-bottom: 20px;
transition: all 0.2s ease;
}
:deep(.upload-zone:hover) {
border-color: #3498db;
background: #242424;
}
.hint {
color: #5e6878;
font-size: 13px;
margin-bottom: 12px;
line-height: 1.5;
}
:deep(.upload-zone .hint) {
font-size: 13px;
margin-bottom: 12px;
}
:deep(.upload-zone .btns) {
justify-content: center;
}
:deep(.upload-zone .opt-btn) {
padding: 8px 16px;
font-size: 13px;
border-radius: 6px;
}
:deep(.upload-zone .opt-btn:hover) {
color: #3498db;
background: #333;
border-color: #3498db;
}
:deep(.upload-zone .opt-btn:disabled) {
cursor: not-allowed;
opacity: 0.55;
}
:deep(.selected-files) {
font-size: 12px;
color: #5e6878;
max-height: 112px;
overflow-y: auto;
text-align: left;
}
:deep(.more-line) {
color: #a0acbe;
}
.opt-btn,
.btn-run,
.download,
.btn-delete {
border: none;
cursor: pointer;
transition: all 0.2s ease;
}
.opt-btn {
padding: 8px 16px;
font-size: 13px;
color: #c8d2e2;
background: #242424;
border: 1px solid #3e4a62;
border-radius: 6px;
}
.opt-btn.small {
padding: 6px 10px;
font-size: 12px;
}
.opt-btn:hover {
color: #3498db;
background: #333;
border-color: #3498db;
}
.opt-btn.danger:hover {
color: #ff9f9f;
border-color: rgba(231, 76, 60, 0.5);
}
.opt-btn:disabled {
cursor: not-allowed;
opacity: 0.55;
}
.option-group {
margin-bottom: 20px;
}
.radio-item {
display: flex;
align-items: flex-start;
gap: 10px;
cursor: pointer;
padding: 10px 12px;
border-radius: 8px;
background: #242424;
border: 1px solid #2e3a52;
margin-bottom: 8px;
transition: all 0.2s ease;
}
.template-item-content {
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
width: 100%;
}
.radio-item:hover,
.radio-item.active {
background: #242424;
border-color: #3e4a62;
}
.radio-item input {
margin-top: 3px;
}
.label {
font-weight: 500;
color: #f5f8fc;
font-size: 13px;
}
.desc {
font-size: 12px;
color: #5e6878;
margin-top: 2px;
line-height: 1.5;
font-weight: 400;
}
.template-tag {
margin-left: 8px;
padding: 2px 8px;
border-radius: 999px;
font-size: 11px;
color: #8fd0ff;
background: rgba(52, 152, 219, 0.14);
}
.template-tag.muted {
color: #b8b8b8;
background: rgba(255, 255, 255, 0.08);
}
.template-tag.custom {
color: #90f0b3;
background: rgba(46, 204, 113, 0.14);
}
.empty-option {
padding: 12px;
border: 1px dashed #3e4a62;
border-radius: 8px;
color: #5e6878;
font-size: 12px;
}
.run-row {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 10px 12px;
margin-top: 16px;
}
.btn-run {
padding: 10px 22px;
background: #3498db;
color: #f5f8fc;
border-radius: 8px;
font-size: 14px;
}
.btn-run:hover {
background: #2980b9;
}
.btn-run:disabled {
background: #555;
color: #a0acbe;
cursor: not-allowed;
}
.loading-msg {
color: #3498db;
font-size: 13px;
}
.download {
padding: 6px 10px;
border-radius: 6px;
font-size: 12px;
background: rgba(52, 152, 219, 0.18);
color: #69b6ff;
}
.download:hover {
background: rgba(52, 152, 219, 0.28);
}
.btn-delete {
padding: 6px 10px;
border-radius: 6px;
font-size: 12px;
background: rgba(231, 76, 60, 0.12);
color: #ff8f8f;
}
.btn-delete:hover {
background: rgba(231, 76, 60, 0.22);
}
.files {
font-size: 12px;
color: #5e6878;
margin-top: 4px;
}
.clean-placeholder {
max-height: none;
}
@media (max-width: 1100px) {
.main-content {
flex-direction: column;
height: auto;
}
.left-panel {
width: 100%;
border-right: none;
border-bottom: 1px solid #2e3a52;
}
.right-panel {
min-height: 420px;
}
}
</style>