96b090dfd5
同类问题一起修:这两个模块与外观专利共用同一条自动重试(原先也克隆重试)。
- 新增通用端点 POST /api/tasks/{taskId}/retry(模块无关,从任务行取 moduleType)
- 两页失败任务在「删除」前显示「重试」,调用后在原任务上复位续跑
- catch 棘轮 308→310,两处均 ElMessage 可见出口
1028 lines
33 KiB
Vue
1028 lines
33 KiB
Vue
<template>
|
||
<div class="page-shell module-page">
|
||
<AmazonToolPageShell tool-id="source">
|
||
|
||
<div class="main-content">
|
||
<aside class="left-panel left-panel--with-template">
|
||
<div class="section-title">上传文件</div>
|
||
<FileUploadZone
|
||
hint="选择 Excel 后点击解析,系统会识别表格里的 ID、ASIN、国家、价格,每一行都会自动检测。"
|
||
:names="selectedFileNames"
|
||
@select-files="selectFiles"
|
||
@select-folder="selectFolder"
|
||
/>
|
||
|
||
<div class="condition-card">
|
||
<div class="section-title">检测条件</div>
|
||
<label class="switch-row">
|
||
<span>
|
||
<strong>图片检测</strong>
|
||
</span>
|
||
<input v-model="imgSwitch" type="checkbox" />
|
||
<i></i>
|
||
</label>
|
||
<label class="switch-row">
|
||
<span>
|
||
<strong>类目检测</strong>
|
||
</span>
|
||
<input v-model="categorySwitch" type="checkbox" />
|
||
<i></i>
|
||
</label>
|
||
</div>
|
||
|
||
<div class="aliprice-card">
|
||
<div class="section-title">货源账号</div>
|
||
<label class="aliprice-field">
|
||
<span>账号</span>
|
||
<input
|
||
v-model="alipriceUsername"
|
||
type="text"
|
||
autocomplete="username"
|
||
placeholder="请输入 Aliprice 账号"
|
||
required
|
||
/>
|
||
</label>
|
||
<label class="aliprice-field">
|
||
<span>密码</span>
|
||
<input
|
||
v-model="alipricePassword"
|
||
type="password"
|
||
autocomplete="current-password"
|
||
placeholder="请输入 Aliprice 密码"
|
||
required
|
||
/>
|
||
</label>
|
||
</div>
|
||
|
||
<div class="channel-row">
|
||
<span class="channel-title">本单采集方式</span>
|
||
<label class="channel-opt">
|
||
<input v-model="collectChannel" type="radio" value="LOCAL" :disabled="channelLocked" /> 本机采集
|
||
</label>
|
||
<label class="channel-opt">
|
||
<input v-model="collectChannel" type="radio" value="ONLINE" :disabled="channelLocked" /> 线上采集
|
||
</label>
|
||
</div>
|
||
|
||
<div class="run-row">
|
||
<button type="button" class="btn-run" :disabled="parsing || !uploadedFiles.length" @click="parseFiles">
|
||
{{ parsing ? '解析中...' : '解析并创建任务' }}
|
||
</button>
|
||
<button type="button" class="btn-run btn-queue" :disabled="pushing || !parseResult?.taskId"
|
||
@click="pushToPythonQueue">
|
||
{{ pushing ? (localCollectEnabled ? '启动中...' : '提交中...') : (localCollectEnabled ? '启动任务' : '提交后台执行') }}
|
||
</button>
|
||
</div>
|
||
<p class="loading-msg">
|
||
{{ channelLocked
|
||
? '本单通道已随任务登记,改方式请重新解析创建。'
|
||
: (localCollectEnabled
|
||
? '启动后任务推送到本机客户端采集,进度显示在右侧任务区,完成后可下载结果。'
|
||
: '提交后由后台自动分批检测,进度显示在右侧任务区,完成后可下载结果。') }}
|
||
</p>
|
||
|
||
<div v-if="visibleTaskSummary" class="parse-card">
|
||
<div>任务 ID:{{ visibleTaskSummary.taskId }}</div>
|
||
<div>总行数:{{ visibleTaskSummary.totalRows }},有效:{{ visibleTaskSummary.acceptedRows }},过滤:{{
|
||
visibleTaskSummary.droppedRows }}</div>
|
||
</div>
|
||
<pre v-if="queuePayloadText" class="queue-payload">{{ queuePayloadText }}</pre>
|
||
<ModuleTemplateDownload module-code="similar-asin" filename="货源查询 文档格式.xlsx" />
|
||
</aside>
|
||
|
||
<section class="right-panel">
|
||
<TaskCenterPanel
|
||
:on-batch-delete="batchDeleteHistory"
|
||
:on-refresh="refreshBoard"
|
||
title="货源查询"
|
||
:cards="asinCards"
|
||
:current-items="currentTaskViews"
|
||
:history-items="historyTaskViews"
|
||
current-title="当前任务"
|
||
current-empty-text="暂无当前任务"
|
||
history-empty-text="暂无历史记录"
|
||
>
|
||
<template #item-extra="{ item }">
|
||
<div v-if="pendingResultHint(itemSource(item))" class="files result-hint">{{ pendingResultHint(itemSource(item)) }}</div>
|
||
</template>
|
||
<template #history-item-extra="{ item }">
|
||
<div v-if="pendingResultHint(itemSource(item))" class="files result-hint">{{ pendingResultHint(itemSource(item)) }}</div>
|
||
</template>
|
||
<template #item-actions="{ item }">
|
||
<button v-if="canRetryTask(itemSource(item))" type="button" class="btn-retry"
|
||
@click="retryTaskRecord(itemSource(item))">重试</button>
|
||
<button type="button" class="btn-delete" @click="deleteTaskRecord(itemSource(item))">删除</button>
|
||
</template>
|
||
<template #history-item-actions="{ item }">
|
||
<button v-if="canDownload(itemSource(item))" type="button" class="download"
|
||
@click="downloadResult(itemSource(item))">下载</button>
|
||
<button v-if="canRetryTask(itemSource(item))" type="button" class="btn-retry"
|
||
@click="retryTaskRecord(itemSource(item))">重试</button>
|
||
<button v-if="itemSource(item).resultId" type="button" class="btn-delete"
|
||
@click="deleteTaskRecord(itemSource(item))">删除</button>
|
||
</template>
|
||
</TaskCenterPanel>
|
||
</section>
|
||
</div>
|
||
|
||
</AmazonToolPageShell>
|
||
</div>
|
||
</template>
|
||
|
||
<script setup lang="ts">
|
||
import { computed, onMounted, onUnmounted, ref } from 'vue'
|
||
import { userNotice } from '@/shared/utils/user-notice'
|
||
import { ElMessage } from 'element-plus'
|
||
import { retryClientTask } from '@/shared/api/task-retry'
|
||
import AmazonToolPageShell from '@/pages/amazon/components/AmazonToolPageShell.vue';
|
||
import FileUploadZone from '@/shared/components/FileUploadZone.vue'
|
||
import ModuleTemplateDownload from '@/shared/components/ModuleTemplateDownload.vue'
|
||
import TaskCenterPanel from '@/shared/components/tasks/TaskCenterPanel.vue'
|
||
import type { TaskItemView, TaskStatCard } from '@/shared/components/tasks/types'
|
||
import {
|
||
activateSimilarAsinTask,
|
||
deleteSimilarAsinHistory,
|
||
deleteSimilarAsinTask,
|
||
getSimilarAsinDashboard,
|
||
getSimilarAsinHistory,
|
||
getSimilarAsinResultDownloadUrl,
|
||
getSimilarAsinTaskProgressBatch,
|
||
parseSimilarAsin,
|
||
type SimilarAsinHistoryItem,
|
||
type SimilarAsinParseVo,
|
||
type UploadedFileRef,
|
||
} from '@/shared/api/java-modules'
|
||
import { getPywebviewApi, type ProxyMode } from '@/shared/bridges/pywebview'
|
||
import { useExcelFileUpload } from '@/shared/composables/useExcelFileUpload'
|
||
import {
|
||
useLiveTaskBoard,
|
||
activeFileJobStatus,
|
||
hasFileProgressCount,
|
||
shouldShowFallbackJobProgress,
|
||
} from '@/shared/composables/useLiveTaskBoard'
|
||
import { createAsinForceThrottle } from '@/shared/asin-force-throttle'
|
||
import { toParsePreview, type ParsePreviewOptions } from '@/shared/parse-preview'
|
||
import {
|
||
checkParseResult,
|
||
checkQueuePayload,
|
||
} from '@/shared/dispatch-guard'
|
||
import { passGuard } from '@/shared/dispatch-guard-ui'
|
||
import { getCollectRouting, type CollectChannel } from '@/shared/api/types/modules/collect-routing'
|
||
import { formatDateTime } from '@/shared/utils/datetime'
|
||
import { isCompletedTask, resultBuildFailed, taskStatusClass, taskStatusText } from '@/shared/utils/task-status-text'
|
||
import { getStoredApiSecret } from '@/shared/utils/api-secret-store'
|
||
|
||
// ---- 文件选择 / 上传(公共组合式函数)----
|
||
const {
|
||
files: uploadedFiles,
|
||
selectedPaths: selectedFileNames,
|
||
selectFiles,
|
||
selectFolder,
|
||
} = useExcelFileUpload({
|
||
requireUploadCapability: true,
|
||
folderRequireUploadCapability: true,
|
||
pickFilesUnavailableWarning: '当前桌面端未提供文件选择或上传能力',
|
||
folderUnavailableWarning: '当前桌面端未提供文件夹选择或上传能力',
|
||
errorFallbackMessage: (action) => (action === 'files' ? '文件上传失败' : '选择失败'),
|
||
onUploaded: () => {
|
||
parseResult.value = null
|
||
queuedTaskSummary.value = null
|
||
queuePayloadText.value = ''
|
||
},
|
||
onFailed: (action) => {
|
||
// 与原实现一致:文件选择失败清空 queuedTaskSummary/queuePayloadText,文件夹失败只清 parseResult
|
||
parseResult.value = null
|
||
if (action === 'files') {
|
||
queuedTaskSummary.value = null
|
||
queuePayloadText.value = ''
|
||
}
|
||
},
|
||
})
|
||
|
||
const parseResult = ref<SimilarAsinParseVo | null>(null)
|
||
type TaskSummary = Pick<SimilarAsinParseVo, 'taskId' | 'totalRows' | 'acceptedRows' | 'groupCount' | 'droppedRows'>
|
||
const queuedTaskSummary = ref<TaskSummary | null>(null)
|
||
const parsing = ref(false)
|
||
const pushing = ref(false)
|
||
/**
|
||
* 这一单的采集执行通道(V183 建单时单选,随 /parse 交服务端落 biz_file_task.collect_channel)。
|
||
* 默认值取服务端「模块默认」(getCollectRouting),取不到就按本机渲染:
|
||
* 服务端 activate 在通道不是本机时会明确拒绝,不会把任务推给不该跑本地的机器。
|
||
*/
|
||
const collectChannel = ref<CollectChannel>('LOCAL')
|
||
/** 派生量:模板与启动分支沿用「本机通道」这一读法,避免两处各判各的。 */
|
||
const localCollectEnabled = computed(() => collectChannel.value === 'LOCAL')
|
||
/**
|
||
* 通道在「解析建单」那一刻就写进任务行了,之后再改单选框只会被建单值覆盖,
|
||
* 界面就会出现「选着线上、点启动却推本机」的假象——所以建完单即锁定。
|
||
*/
|
||
const channelLocked = computed(() => parsing.value || pushing.value || Boolean(parseResult.value?.taskId))
|
||
const imgSwitch = ref(false)
|
||
const categorySwitch = ref(false)
|
||
const alipriceUsername = ref('')
|
||
const alipricePassword = ref('')
|
||
const queuePayloadText = ref('')
|
||
// force 请求节流:文件生成中不重复 force(TTL 窗口内只发一次),终态后 clear 释放
|
||
const forceThrottle = createAsinForceThrottle({ ttlMs: 30_000 })
|
||
let disposed = false
|
||
let pywebviewReadyHandler: (() => void) | null = null
|
||
|
||
function uidForStorage() {
|
||
return typeof window !== 'undefined' ? window.localStorage.getItem('uid') || '0' : '0'
|
||
}
|
||
|
||
function currentUserId() {
|
||
return Number(uidForStorage()) || 0
|
||
}
|
||
|
||
// ---- 实时任务面板(与外观专利 Tab 的公共骨架抽到 useLiveTaskBoard)----
|
||
const board = useLiveTaskBoard<SimilarAsinHistoryItem>({
|
||
scope: 'similar-asin',
|
||
pollingStorageKey: () => `similar-asin:tasks:${uidForStorage()}`,
|
||
fetchHistory: getSimilarAsinHistory,
|
||
fetchProgressBatch: getSimilarAsinTaskProgressBatch,
|
||
fetchDashboard: getSimilarAsinDashboard,
|
||
normalizeTaskStatus,
|
||
isResultPreparing,
|
||
addPendingAfterFinalStatus: (task) => task.status === 'SUCCESS',
|
||
keepPendingFileTask: (_item, taskStatus) => taskStatus === 'SUCCESS',
|
||
settleOnTaskStatuses: ['SUCCESS'],
|
||
beforeBatch: (_taskIds, pendingIds) => ({
|
||
taskIds: _taskIds,
|
||
force: pendingIds.some((taskId) => forceThrottle.shouldForce(taskId)),
|
||
}),
|
||
afterBatch: (_taskIds, pendingIds, forced) => {
|
||
if (forced) {
|
||
// force 请求已发出,进入冷却窗口;TTL 内不再重复 force,避免重复触发文件生成
|
||
pendingIds.forEach((taskId) => forceThrottle.markForce(taskId))
|
||
}
|
||
},
|
||
onPendingFileTaskRemoved: (taskId) => forceThrottle.clear(taskId),
|
||
getPendingParseItem: () => pendingParseItem.value,
|
||
download: {
|
||
buildUrl: (resultId) => getSimilarAsinResultDownloadUrl(resultId),
|
||
fallbackFilename: 'similar-asin',
|
||
progressKeyPrefix: 'similar-asin',
|
||
},
|
||
deleteTask: {
|
||
shouldDeleteTask: (item, status) =>
|
||
item.taskId != null && (status === 'RUNNING' || status === 'PENDING' || !item.resultId),
|
||
deleteTask: (taskId) => deleteSimilarAsinTask(taskId),
|
||
deleteHistory: (resultId) => deleteSimilarAsinHistory(resultId),
|
||
onTaskDeleted: (item) => removeTaskFromLocalState(item.taskId),
|
||
onHistoryDeleted: (item) => {
|
||
if (item.taskId) {
|
||
board.historyItems.value = board.historyItems.value.filter((row) => row.taskId !== item.taskId)
|
||
}
|
||
},
|
||
},
|
||
})
|
||
|
||
const visibleTaskSummary = computed(() => parseResult.value || queuedTaskSummary.value)
|
||
const pendingParseItem = computed<SimilarAsinHistoryItem | null>(() => {
|
||
const result = parseResult.value
|
||
if (!result?.taskId) return null
|
||
const exists = board.historyItems.value.some((item) => item.taskId === result.taskId)
|
||
if (exists) return null
|
||
return {
|
||
taskId: result.taskId,
|
||
sourceFilename: result.sourceFilename,
|
||
rowCount: result.acceptedRows,
|
||
taskStatus: 'PENDING',
|
||
success: false,
|
||
}
|
||
})
|
||
|
||
const asinCards = computed<TaskStatCard[]>(() => [
|
||
{ label: '运行中任务', value: board.dashboard.value.pendingTaskCount },
|
||
{ label: '已结束任务', value: board.dashboard.value.processedTaskCount },
|
||
{ label: '成功任务', value: board.dashboard.value.successTaskCount },
|
||
{ label: '失败任务', value: board.dashboard.value.failedTaskCount },
|
||
])
|
||
|
||
const currentTaskViews = computed<TaskItemView[]>(() => board.currentItems.value.map(toAsinTaskView))
|
||
|
||
const historyTaskViews = computed<TaskItemView[]>(() => board.historyOnlyItems.value.map(toAsinTaskView))
|
||
|
||
/** 手动刷新:强拉历史 + 统计 + 当前轮询任务进度(轮询意外中断后的自救出口) */
|
||
async function refreshBoard() {
|
||
await Promise.all([
|
||
board.loadDashboard(),
|
||
board.loadHistory({ force: true }),
|
||
board.refreshTaskProgress(),
|
||
])
|
||
}
|
||
|
||
function itemSource(item: TaskItemView): SimilarAsinHistoryItem {
|
||
return item.source as SimilarAsinHistoryItem
|
||
}
|
||
|
||
function toAsinTaskView(item: SimilarAsinHistoryItem): TaskItemView {
|
||
const showProgress = board.showFileProgress(item)
|
||
const isRunning = normalizeTaskStatus(item) === 'RUNNING'
|
||
return {
|
||
key: `asin-${item.taskId ?? item.resultId ?? item.sourceFilename}`,
|
||
title: item.sourceFilename || '货源查询',
|
||
taskId: item.taskId ?? '-',
|
||
startedAt: formatDateTime(item.startedAt || item.createdAt),
|
||
finishedAt: formatDateTime(item.finishedAt),
|
||
statusText: statusText(item),
|
||
statusClass: statusClass(item),
|
||
extraLines: [
|
||
...(item.rowCount != null ? [`行数:${item.rowCount}`] : []),
|
||
...(item.resultFilename && !showProgress ? [item.resultFilename] : []),
|
||
...(item.error ? [`错误:${userNotice(item.error)}`] : []),
|
||
],
|
||
progress: showProgress
|
||
? {
|
||
percent: fileProgressPercent(item),
|
||
stage: displayFileProgressStage(item, isRunning ? '处理中' : '结果生成中'),
|
||
countLabel: hasFileProgressCount(item) ? fileProgressCountLabel(item) : undefined,
|
||
}
|
||
: null,
|
||
source: item,
|
||
}
|
||
}
|
||
|
||
// ---- 本模块的状态语义(与外观专利 Tab 不同,保留在 Tab 内)----
|
||
|
||
function statusText(item: SimilarAsinHistoryItem) {
|
||
const status = normalizeTaskStatus(item)
|
||
if (status === 'FAILED') return taskStatusText('FAILED')
|
||
if (status === 'RUNNING') return taskStatusText(status)
|
||
if (status === 'PENDING') return taskStatusText(status, { text: { PENDING: '已解析待启动' } })
|
||
if (isResultPreparing(item)) return '结果生成中'
|
||
if (isResultBuildFailed(item)) return '结果生成失败'
|
||
if (isCompletedTask(status)) return taskStatusText('SUCCESS')
|
||
return '等待中'
|
||
}
|
||
|
||
function statusClass(item: SimilarAsinHistoryItem) {
|
||
const status = normalizeTaskStatus(item)
|
||
if (status === 'FAILED' || isResultBuildFailed(item)) return taskStatusClass('FAILED')
|
||
if (status === 'RUNNING' || isResultPreparing(item)) return taskStatusClass('RUNNING')
|
||
if (isCompletedTask(status)) return taskStatusClass('SUCCESS')
|
||
return 'pending'
|
||
}
|
||
|
||
function isResultPreparing(item: SimilarAsinHistoryItem) {
|
||
const status = normalizeTaskStatus(item)
|
||
const fileStatus = (item.fileStatus || '').toUpperCase()
|
||
if (status !== 'SUCCESS') return false
|
||
if (canDownload(item)) return false
|
||
if (fileStatus === 'FAILED' || fileStatus === 'SUCCESS') return false
|
||
return true
|
||
}
|
||
|
||
/**
|
||
* 失败任务重试:在**原任务**上复位续跑(不新建任务),与外观专利同口径。
|
||
* 只有 FAILED 才出按钮——成功/进行中的任务重试没有语义。
|
||
*/
|
||
function canRetryTask(item: SimilarAsinHistoryItem | null | undefined): boolean {
|
||
return Boolean(item?.taskId) && normalizeTaskStatus(item as SimilarAsinHistoryItem) === 'FAILED'
|
||
}
|
||
|
||
async function retryTaskRecord(item: SimilarAsinHistoryItem | null | undefined) {
|
||
const taskId = item?.taskId
|
||
if (!taskId) return
|
||
try {
|
||
await retryClientTask(taskId)
|
||
ElMessage.success('已提交重试:在这条任务上继续跑(不新建任务)')
|
||
await refreshBoard()
|
||
} catch (error) {
|
||
ElMessage.error(error instanceof Error ? error.message : '重试失败')
|
||
}
|
||
}
|
||
|
||
function normalizeTaskStatus(item: SimilarAsinHistoryItem) {
|
||
const taskStatus = (item.taskStatus || '').toUpperCase()
|
||
if (taskStatus !== 'FAILED' && isResultFileComplete(item)) return 'SUCCESS'
|
||
return taskStatus
|
||
}
|
||
|
||
function isResultBuildFailed(item: SimilarAsinHistoryItem) {
|
||
return resultBuildFailed(item.fileStatus, canDownload(item))
|
||
}
|
||
|
||
function pendingResultHint(item: SimilarAsinHistoryItem) {
|
||
if (isResultBuildFailed(item)) {
|
||
return userNotice(item.fileError, '结果文件生成失败,请稍后重试或检查后端日志')
|
||
}
|
||
if (board.showFileProgress(item)) {
|
||
return ''
|
||
}
|
||
if (!isResultPreparing(item)) return ''
|
||
const fileStatus = (item.fileStatus || '').toUpperCase()
|
||
if (fileStatus === 'RUNNING') {
|
||
return '任务已完成,正在生成结果文件,下载按钮稍后出现'
|
||
}
|
||
if (fileStatus === 'PENDING') {
|
||
return '任务已完成,结果文件排队中,请稍候'
|
||
}
|
||
return '任务已完成,正在生成结果文件,下载按钮稍后出现'
|
||
}
|
||
|
||
function canDownload(item: SimilarAsinHistoryItem) {
|
||
return Boolean(item.resultId && (item.fileReady || item.downloadUrl))
|
||
}
|
||
|
||
function isResultFileComplete(item: SimilarAsinHistoryItem) {
|
||
return Boolean(
|
||
item.fileReady
|
||
|| item.downloadUrl
|
||
|| (item.fileStatus || '').toUpperCase() === 'SUCCESS',
|
||
)
|
||
}
|
||
|
||
function fileProgressPercent(item: SimilarAsinHistoryItem) {
|
||
if (isResultFileComplete(item)) return 100
|
||
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 displayFileProgressStage(item: SimilarAsinHistoryItem, fallback: string) {
|
||
const message = (item.fileProgressMessage || '').trim()
|
||
if (!message) return fallback
|
||
if (/llm/i.test(message) || /LLM|回流/.test(message)) {
|
||
if (/submitting/i.test(message) || /提交/.test(message)) return '正在提交检测批次'
|
||
if (/生成结果|结果文件|组装/i.test(message)) return '检测结果已返回,正在生成结果文件'
|
||
if (/waiting/i.test(message) || /等待/.test(message) || /\d+\s*\/\s*\d+/.test(message)) {
|
||
return '检测中,等待结果返回'
|
||
}
|
||
return '检测中'
|
||
}
|
||
if (/assembling|xlsx|组装|生成结果/i.test(message)) return '正在生成结果文件'
|
||
return message
|
||
}
|
||
|
||
function fileProgressCountLabel(item: SimilarAsinHistoryItem) {
|
||
const message = (item.fileProgressMessage || '').trim()
|
||
const parsed = parseProgressCountFromMessage(message)
|
||
const current = parsed?.current ?? item.fileProgressCurrent ?? 0
|
||
const total = parsed?.total ?? item.fileProgressTotal ?? 0
|
||
if (/llm/i.test(message) || /LLM|回流/.test(message)) {
|
||
if (/submitting/i.test(message) || /提交/.test(message)) {
|
||
return `检测批次 ${current}/${total}`
|
||
}
|
||
return `检测完成批次 ${current}/${total}`
|
||
}
|
||
return `当前阶段 ${current}/${total}`
|
||
}
|
||
|
||
function parseProgressCountFromMessage(message: string) {
|
||
const match = message.match(/(\d+)\s*\/\s*(\d+)/)
|
||
if (!match) return null
|
||
const current = Number(match[1])
|
||
const total = Number(match[2])
|
||
if (!Number.isFinite(current) || !Number.isFinite(total)) return null
|
||
return { current, total }
|
||
}
|
||
|
||
// ---- 解析与启动(本模块特有)----
|
||
|
||
function effectiveLlmApiKey() {
|
||
return getStoredApiSecret('similar-asin').trim()
|
||
}
|
||
|
||
function getRequiredAlipriceCredentials() {
|
||
const username = alipriceUsername.value.trim()
|
||
const password = alipricePassword.value
|
||
if (!username || !password.trim()) {
|
||
ElMessage.warning('请填写 Aliprice 账号和密码')
|
||
return null
|
||
}
|
||
return { username, password }
|
||
}
|
||
|
||
function maskSecret(secret: string) {
|
||
if (!secret) return ''
|
||
if (secret.length <= 10) return '***'
|
||
return `${secret.slice(0, 6)}***${secret.slice(-4)}`
|
||
}
|
||
|
||
function payloadForDisplay<T extends { data?: Record<string, unknown> }>(payload: T) {
|
||
return {
|
||
...payload,
|
||
data: payload.data
|
||
? {
|
||
...payload.data,
|
||
api_key: maskSecret(String(payload.data.api_key || '')),
|
||
aliprice_pwd: maskSecret(String(payload.data.aliprice_pwd || '')),
|
||
}
|
||
: payload.data,
|
||
}
|
||
}
|
||
|
||
function toTaskSummary(result: SimilarAsinParseVo): TaskSummary {
|
||
return {
|
||
taskId: result.taskId,
|
||
totalRows: result.totalRows,
|
||
acceptedRows: result.acceptedRows,
|
||
groupCount: result.groupCount,
|
||
droppedRows: result.droppedRows,
|
||
}
|
||
}
|
||
|
||
async function parseFiles() {
|
||
if (!uploadedFiles.value.length) {
|
||
ElMessage.warning('请先选择 Excel')
|
||
return
|
||
}
|
||
if (!effectiveLlmApiKey()) {
|
||
// 本地无明文不再阻断:密钥已服务端化,任务执行按用户 uid 兜底读取
|
||
console.log('[similar-asin] 本地无密钥明文,提交时由服务端按用户密钥兜底')
|
||
}
|
||
if (!getRequiredAlipriceCredentials()) return
|
||
parsing.value = true
|
||
try {
|
||
const files: UploadedFileRef[] = uploadedFiles.value.map((f) => ({
|
||
fileKey: f.fileKey,
|
||
originalFilename: f.originalFilename,
|
||
relativePath: f.relativePath,
|
||
}))
|
||
const res = await parseSimilarAsin(files, effectiveLlmApiKey(), imgSwitch.value, categorySwitch.value, collectChannel.value)
|
||
// 0 有效行的任务推给 Python 只会一直停在 RUNNING,这里拦下来不写入 parseResult
|
||
const guard = checkParseResult(res, { requiredColumnsHint: 'id / ASIN / 国家' })
|
||
if (!(await passGuard(guard))) {
|
||
parseResult.value = null
|
||
queuedTaskSummary.value = null
|
||
queuePayloadText.value = ''
|
||
return
|
||
}
|
||
// 只保留摘要字段与有界预览行,避免数千行 items/groups 进入响应式对象
|
||
const previewOptions: ParsePreviewOptions = { previewRowLimit: 200 }
|
||
parseResult.value = toParsePreview(res, previewOptions) as unknown as SimilarAsinParseVo
|
||
categorySwitch.value = Boolean(res.categorySwitch)
|
||
queuedTaskSummary.value = null
|
||
queuePayloadText.value = ''
|
||
ElMessage.success(`解析完成,共 ${res.acceptedRows} 条`)
|
||
} catch (e) {
|
||
ElMessage.error(e instanceof Error ? e.message : '解析失败')
|
||
} finally {
|
||
parsing.value = false
|
||
}
|
||
}
|
||
|
||
async function pushToPythonQueue() {
|
||
const api = getPywebviewApi()
|
||
const currentParseResult = parseResult.value
|
||
const taskId = currentParseResult?.taskId
|
||
if (!taskId) {
|
||
ElMessage.warning('请先解析文件')
|
||
return
|
||
}
|
||
if (!localCollectEnabled.value) {
|
||
// 本地采集关闭:只建单,任务保持 PENDING 由 Linux 后台认领
|
||
pushing.value = true
|
||
try {
|
||
queuedTaskSummary.value = toTaskSummary(currentParseResult)
|
||
board.addPollingTask(taskId)
|
||
clearParsedTask()
|
||
await board.loadDashboard()
|
||
await board.loadHistory({ force: true })
|
||
ElMessage.success('已提交,后台自动执行中')
|
||
} finally {
|
||
pushing.value = false
|
||
}
|
||
return
|
||
}
|
||
if (!api?.enqueue_json) {
|
||
ElMessage.error('当前环境未启用 pywebview enqueue_json')
|
||
return
|
||
}
|
||
if (!effectiveLlmApiKey()) {
|
||
// 本地无明文不再阻断:服务端已保存该用户密钥,任务执行时按 uid 兜底读取
|
||
console.log('[similar-asin] 本地无密钥明文,启动任务由服务端兜底')
|
||
}
|
||
const alipriceCredentials = getRequiredAlipriceCredentials()
|
||
if (!alipriceCredentials) return
|
||
const alipriceUsename = alipriceCredentials.username
|
||
const alipricePwd = alipriceCredentials.password
|
||
pushing.value = true
|
||
try {
|
||
let proxyData: { proxy_url: string; proxy_mode: ProxyMode } | undefined
|
||
if (api.read_config) {
|
||
try {
|
||
const config = await api.read_config()
|
||
const proxyUrl = typeof config?.proxy_url === 'string' ? config.proxy_url.trim() : ''
|
||
if (proxyUrl) {
|
||
proxyData = {
|
||
proxy_url: proxyUrl,
|
||
proxy_mode: Number(config?.proxy_mode) === 2 ? 2 : 1,
|
||
}
|
||
}
|
||
} catch {
|
||
// Keep the existing queue behavior when proxy configuration is unavailable.
|
||
}
|
||
}
|
||
if (api.save_config) {
|
||
try {
|
||
await api.save_config({
|
||
aliprice_usename: alipriceUsename,
|
||
aliprice_pwd: alipricePwd,
|
||
})
|
||
} catch {
|
||
ElMessage.warning('Aliprice 账号配置保存失败,本次任务仍会继续')
|
||
}
|
||
}
|
||
const payload = {
|
||
type: 'similar-asin-run',
|
||
ts: Date.now(),
|
||
data: {
|
||
taskId,
|
||
user_id: currentUserId(),
|
||
api_key: effectiveLlmApiKey(),
|
||
sourceFileCount: currentParseResult.sourceFileCount || 0,
|
||
totalRows: currentParseResult.totalRows || 0,
|
||
acceptedRows: currentParseResult.acceptedRows || 0,
|
||
groupCount: currentParseResult.groupCount || 0,
|
||
aliprice_usename: alipriceUsename,
|
||
aliprice_pwd: alipricePwd,
|
||
...proxyData,
|
||
},
|
||
}
|
||
queuePayloadText.value = JSON.stringify(payloadForDisplay(payload), null, 2)
|
||
// 入队前最后一道闸:缺字段或含 NaN 的 payload 到 Python 侧会变成 None,任务卡住
|
||
const guard = checkQueuePayload(payload, {
|
||
expectedType: 'similar-asin-run',
|
||
// api_key 不列为必填:密钥已服务端化,本地无明文时由服务端按 uid 兜底
|
||
// (Java SimilarAsinPayloadSupport.readApiKey),列必填会把这类用户全部拦下
|
||
requiredDataKeys: ['taskId', 'aliprice_usename', 'aliprice_pwd'],
|
||
})
|
||
if (!(await passGuard(guard))) return
|
||
// 任务可能已被客户端「兜底拉取」领走(页面长时间没点启动):服务端会拒绝 activate,
|
||
// 此时必须直接返回,不能再入队,否则同一任务会被执行两次
|
||
try {
|
||
await activateSimilarAsinTask(taskId)
|
||
} catch (activateError) {
|
||
ElMessage.warning(activateError instanceof Error ? activateError.message : '任务已在执行中,无需重复启动')
|
||
await Promise.all([board.loadDashboard(), board.loadHistory({ force: true })])
|
||
return
|
||
}
|
||
const result = await api.enqueue_json(payload)
|
||
if (!result?.success) {
|
||
ElMessage.error(userNotice(result?.error, '启动失败'))
|
||
return
|
||
}
|
||
queuedTaskSummary.value = toTaskSummary(currentParseResult)
|
||
board.addPollingTask(taskId)
|
||
clearParsedTask()
|
||
await board.loadDashboard()
|
||
await board.loadHistory({ force: true })
|
||
ElMessage.success('已启动任务')
|
||
} finally {
|
||
pushing.value = false
|
||
}
|
||
}
|
||
|
||
async function loadAlipriceConfig() {
|
||
const api = getPywebviewApi()
|
||
if (!api?.read_config) return
|
||
try {
|
||
const config = await api.read_config()
|
||
if (disposed) return
|
||
alipriceUsername.value = typeof config?.aliprice_usename === 'string' ? config.aliprice_usename : ''
|
||
alipricePassword.value = typeof config?.aliprice_pwd === 'string' ? config.aliprice_pwd : ''
|
||
} catch {
|
||
ElMessage.warning('Aliprice 账号配置读取失败')
|
||
}
|
||
}
|
||
|
||
function clearParsedTask() {
|
||
parseResult.value = null
|
||
queuePayloadText.value = ''
|
||
}
|
||
|
||
function removeTaskFromLocalState(taskId?: number) {
|
||
if (!taskId) return
|
||
board.removePollingTask(taskId)
|
||
board.removePendingFileTask(taskId)
|
||
if (parseResult.value?.taskId === taskId) {
|
||
clearParsedTask()
|
||
}
|
||
if (queuedTaskSummary.value?.taskId === taskId) {
|
||
queuedTaskSummary.value = null
|
||
}
|
||
board.historyItems.value = board.historyItems.value.filter((row) => row.taskId !== taskId)
|
||
if (board.liveProgressItems.value[taskId]) {
|
||
const next = { ...board.liveProgressItems.value }
|
||
delete next[taskId]
|
||
board.liveProgressItems.value = next
|
||
}
|
||
}
|
||
|
||
const { batchDeleteHistory, deleteTaskRecord, downloadResult } = board
|
||
|
||
onMounted(async () => {
|
||
board.loadPollingIds()
|
||
if (typeof window !== 'undefined') {
|
||
pywebviewReadyHandler = () => {
|
||
void loadAlipriceConfig()
|
||
}
|
||
window.addEventListener('pywebviewready', pywebviewReadyHandler)
|
||
}
|
||
// 单选框默认选中项取服务端模块默认;读不到就按本机,服务端 activate 会兜底拒绝
|
||
getCollectRouting()
|
||
.then((routing) => {
|
||
collectChannel.value = routing.similarAsinLocal !== false ? 'LOCAL' : 'ONLINE'
|
||
})
|
||
.catch((error) => {
|
||
console.warn('[similar-asin] 读取采集通道默认值失败,按本机采集处理', error)
|
||
})
|
||
await Promise.all([
|
||
board.loadDashboard().catch(() => undefined),
|
||
board.loadHistory().catch(() => undefined),
|
||
loadAlipriceConfig(),
|
||
])
|
||
board.seedPendingFileTasksFromHistory()
|
||
board.seedRunningTasksFromHistory()
|
||
board.ensurePollingIfAny()
|
||
})
|
||
|
||
onUnmounted(() => {
|
||
disposed = true
|
||
if (typeof window !== 'undefined' && pywebviewReadyHandler) {
|
||
window.removeEventListener('pywebviewready', pywebviewReadyHandler)
|
||
pywebviewReadyHandler = null
|
||
}
|
||
board.dispose()
|
||
})
|
||
</script>
|
||
|
||
<style scoped>
|
||
.module-page {
|
||
min-height: 100vh;
|
||
background: #242424;
|
||
}
|
||
|
||
.main-content {
|
||
display: flex;
|
||
height: calc(100vh - 56px);
|
||
min-height: calc(100vh - 56px);
|
||
}
|
||
|
||
.left-panel {
|
||
width: 400px;
|
||
background: #242424;
|
||
padding: 20px;
|
||
overflow-y: auto;
|
||
border-right: 1px solid #2e3a52;
|
||
}
|
||
|
||
.right-panel {
|
||
flex: 1;
|
||
min-width: 0;
|
||
background: #242424;
|
||
display: flex;
|
||
flex-direction: column;
|
||
}
|
||
|
||
.section-title {
|
||
font-size: 13px;
|
||
color: #a0acbe;
|
||
margin-bottom: 10px;
|
||
}
|
||
|
||
.condition-card {
|
||
margin-bottom: 18px;
|
||
padding: 14px 16px;
|
||
border: 1px solid #2f3a34;
|
||
border-radius: 10px;
|
||
background: linear-gradient(135deg, #222a25, #222b3d);
|
||
}
|
||
|
||
.aliprice-card {
|
||
margin-bottom: 18px;
|
||
padding: 14px 16px;
|
||
border: 1px solid #343434;
|
||
border-radius: 8px;
|
||
background: #232323;
|
||
}
|
||
|
||
.aliprice-field {
|
||
display: grid;
|
||
grid-template-columns: 44px minmax(0, 1fr);
|
||
align-items: center;
|
||
gap: 10px;
|
||
color: #a0acbe;
|
||
font-size: 13px;
|
||
}
|
||
|
||
.aliprice-field + .aliprice-field {
|
||
margin-top: 10px;
|
||
}
|
||
|
||
.aliprice-field input {
|
||
width: 100%;
|
||
min-width: 0;
|
||
height: 34px;
|
||
padding: 0 10px;
|
||
border: 1px solid #3b3b3b;
|
||
border-radius: 6px;
|
||
outline: none;
|
||
background: #1b1b1b;
|
||
color: #c8d2e2;
|
||
font: inherit;
|
||
}
|
||
|
||
.aliprice-field input:focus {
|
||
border-color: #4f91c7;
|
||
}
|
||
|
||
.switch-row {
|
||
display: flex;
|
||
align-items: center;
|
||
justify-content: space-between;
|
||
gap: 14px;
|
||
color: #d8e4dc;
|
||
cursor: pointer;
|
||
user-select: none;
|
||
}
|
||
|
||
.switch-row span {
|
||
display: flex;
|
||
flex-direction: column;
|
||
gap: 4px;
|
||
min-width: 0;
|
||
}
|
||
|
||
.switch-row strong {
|
||
font-size: 13px;
|
||
font-weight: 600;
|
||
}
|
||
|
||
.switch-row em {
|
||
color: #8d9a91;
|
||
font-size: 12px;
|
||
font-style: normal;
|
||
line-height: 1.4;
|
||
}
|
||
|
||
.switch-row input {
|
||
position: absolute;
|
||
opacity: 0;
|
||
pointer-events: none;
|
||
}
|
||
|
||
.switch-row i {
|
||
position: relative;
|
||
width: 46px;
|
||
height: 24px;
|
||
flex: 0 0 auto;
|
||
border-radius: 999px;
|
||
background: #3e4a62;
|
||
box-shadow: inset 0 0 0 1px #4b4b4b;
|
||
transition: background .2s ease, box-shadow .2s ease;
|
||
}
|
||
|
||
.switch-row i::after {
|
||
content: '';
|
||
position: absolute;
|
||
top: 3px;
|
||
left: 3px;
|
||
width: 18px;
|
||
height: 18px;
|
||
border-radius: 50%;
|
||
background: #c7c7c7;
|
||
transition: transform .2s ease, background .2s ease;
|
||
}
|
||
|
||
.switch-row input:checked+i {
|
||
background: #27ae60;
|
||
box-shadow: inset 0 0 0 1px #42d17a;
|
||
}
|
||
|
||
.switch-row input:checked+i::after {
|
||
transform: translateX(22px);
|
||
background: #fff;
|
||
}
|
||
|
||
.hint,
|
||
.loading-msg,
|
||
.files,
|
||
.muted {
|
||
color: #5e6878;
|
||
font-size: 12px;
|
||
line-height: 1.5;
|
||
}
|
||
|
||
.link {
|
||
color: #6ea8fe;
|
||
text-decoration: none;
|
||
}
|
||
|
||
.link:hover {
|
||
color: #9fc5ff;
|
||
}
|
||
|
||
.run-row {
|
||
display: flex;
|
||
gap: 10px;
|
||
flex-wrap: wrap;
|
||
}
|
||
|
||
.channel-row {
|
||
display: flex;
|
||
align-items: center;
|
||
gap: 14px;
|
||
flex-wrap: wrap;
|
||
margin-bottom: 12px;
|
||
color: #a0acbe;
|
||
font-size: 12px;
|
||
}
|
||
|
||
.channel-title {
|
||
color: #5e6878;
|
||
}
|
||
|
||
.channel-opt {
|
||
display: inline-flex;
|
||
align-items: center;
|
||
gap: 6px;
|
||
cursor: pointer;
|
||
}
|
||
|
||
.channel-opt:has(input:disabled) {
|
||
opacity: .55;
|
||
cursor: not-allowed;
|
||
}
|
||
|
||
.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;
|
||
}
|
||
|
||
.parse-card,
|
||
.queue-payload {
|
||
margin-top: 14px;
|
||
padding: 12px;
|
||
border: 1px solid #2e3a52;
|
||
border-radius: 8px;
|
||
background: #222b3d;
|
||
color: #a0acbe;
|
||
font-size: 12px;
|
||
}
|
||
|
||
.queue-payload {
|
||
max-height: 220px;
|
||
overflow: auto;
|
||
color: #8fd3ff;
|
||
white-space: pre-wrap;
|
||
}
|
||
|
||
.result-hint {
|
||
margin-top: 6px;
|
||
color: #e0b96d;
|
||
}
|
||
|
||
.download {
|
||
padding: 6px 10px;
|
||
color: #c8d2e2;
|
||
background: rgba(52, 152, 219, .18);
|
||
}
|
||
|
||
.btn-delete {
|
||
padding: 6px 10px;
|
||
color: #ff8f8f;
|
||
background: rgba(231, 76, 60, .12);
|
||
}
|
||
|
||
@media (max-width: 1100px) {
|
||
.main-content {
|
||
flex-direction: column;
|
||
height: auto;
|
||
}
|
||
|
||
.left-panel {
|
||
width: 100%;
|
||
border-right: none;
|
||
border-bottom: 1px solid #2e3a52;
|
||
}
|
||
}
|
||
</style>
|