Files
crawler-plugin/frontend-vue/src/pages/brand/components/BrandAppearancePatentTab.vue
T
huangzd1997 10dec12ec0 refactor(前端): 前后台界面小字全面精简——删技术ID括号/页头操作提示条/机制解释句(2026-11-28 客户口径「这些小字都不需要多余,还有shopId啥的…除了必须要的比如任务ID密钥,其他精简一些」)
用户端 frontend-vue:
- jd-publish-shop.ts:shopLabel 只出店名(缺名兜底「店铺 N」),跨店/多店琥珀文案压成一两句,判据逻辑零改动
- JdPublishTab:删工具头/分类解释/品牌句后半,默认店铺/选品/collect-hint/中断回执/加价规则各压一句
- JdCollectTab:删工具头 desc、分类机制句、断点游标行,「页面筛选未生效兜底翻页中」从任务卡撤下
- jd-on-shelf 空态一句、JdConsolePage hero-sub 整段删(含过时的「正在建设中」)
- 品牌 10 个 tab:输入/筛选/加载长句压一句或删,任务卡删「结果ID/店铺ID/平台」技术行(店名已显形)
- 保留:错误出口、额度「当前在架X/Y」、GROUPS_EMPTY 空态动作句、检测按钮与店铺显形

后管 admin-frontend-vue:
- 每页顶部「当前页面操作提示」条整条下线(删 OperationGuide.vue+operation-guides.ts)
- 撞款/任务中心/关键词用量/密钥用量/客户端包/教程/软件版本/数字人/菜单/店铺密钥/登录页逐页删说明小字(保留:踢线警示、「留空=永不过期」、「不要带v前缀」、「仅支持.zip」、草稿需手动发布、已授权人数、安全提示)
- 编辑/建号弹窗 label 括号收短;代理弹窗/设备日志(删 pywebview/kk-browser 进程名)/密钥 pill title/授权弹窗 dim/品牌门控空态收短

测试同步(16 支改反钉或同步断言,全部当场绿):
- align-operation-guide 整份重写为反钉(组件与文案表不得回流)
- source-pin 台账 task-center-board 条目手工点名 7/3/5→24/14/28:旧值是切分器把正则字面量内裸引号当字符串开关吞掉 18 支用例的误量(stripNonCode 不识别 regex literal),本次改写恰好移除该文件最后两处带引号正则后测出真值;真实用例数反而 25→24(删 1 支 guide 用例),非真实增长

门禁:后管 node --test 1965/1965+vitest 253/253+vue-tsc rc=0;用户端 node 1150/mount 149/vue-tsc rc=0;ops 快检 --fast overall=pass(后端9.5/后管8.8/客户端9.8/用户端9.6)。本窗不发版;app_client/jar/后端零改动。
2026-11-28 01:14:51 +08:00

783 lines
35 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="patent">
<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="prompt-card">
<div class="section-title">新增条件要求</div>
<textarea v-model="aiPrompt" class="prompt-input" rows="8" placeholder="选填:填写后会作为额外要求一并提交给检测" />
</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.groupCount || 0 }},过滤:{{ visibleTaskSummary.droppedRows }}</div>
</div>
<ModuleTemplateDownload module-code="appearance-patent" filename="外观专利检测 文档格式.xlsx" />
</aside>
<section class="right-panel">
<TaskCenterPanel
:on-batch-delete="batchDeleteHistory"
:on-refresh="refreshBoard"
title="外观专利检测"
:cards="patentCards"
: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="canDownload(itemSource(item))" type="button" class="download"
@click="downloadResult(itemSource(item))">下载</button>
<button v-if="canInterruptTask(itemSource(item))" type="button" class="btn-interrupt"
@click="interruptTaskRecord(itemSource(item))">中断</button>
<button v-if="canRetryTask(itemSource(item))" type="button" class="btn-retry"
@click="retryTaskRecord(itemSource(item))">{{ retryLabel(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="canInterruptTask(itemSource(item))" type="button" class="btn-interrupt"
@click="interruptTaskRecord(itemSource(item))">中断</button>
<button v-if="canRetryTask(itemSource(item))" type="button" class="btn-retry"
@click="retryTaskRecord(itemSource(item))">{{ retryLabel(itemSource(item)) }}</button>
<button v-if="itemSource(item).taskId || 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, ElMessageBox } from 'element-plus'
import AmazonToolPageShell from '@/pages/amazon/components/AmazonToolPageShell.vue';
import FileUploadZone from '@/shared/components/FileUploadZone.vue'
import ModuleTemplateDownload from '@/shared/components/ModuleTemplateDownload.vue'
import TaskCenterPanel from '@/shared/components/tasks/TaskCenterPanel.vue'
import type { TaskItemView, TaskStatCard } from '@/shared/components/tasks/types'
import {
activateAppearancePatentTask,
deleteAppearancePatentHistory,
deleteAppearancePatentTask,
interruptAppearancePatentTask,
retryAppearancePatentTask,
getAppearancePatentDashboard,
getAppearancePatentHistory,
getAppearancePatentQueuePayload,
getAppearancePatentResultDownloadUrl,
getAppearancePatentTaskProgressBatch,
parseAppearancePatent,
type AppearancePatentHistoryItem,
type AppearancePatentParseVo,
type AppearancePatentParsedPayloadDto,
type UploadedFileRef,
} from '@/shared/api/java-modules'
import { getCollectRouting, type CollectChannel } from '@/shared/api/types/modules/collect-routing'
import { getPywebviewApi } from '@/shared/bridges/pywebview'
import { useExcelFileUpload } from '@/shared/composables/useExcelFileUpload'
import {
useLiveTaskBoard,
activeFileJobStatus,
hasActiveFileJob,
shouldShowFallbackJobProgress,
} from '@/shared/composables/useLiveTaskBoard'
import { getModuleProgressLight } from '@/shared/api/progress-light.ts'
import { createRowsVersionTracker } from '@/shared/api/task-progress-polling.ts'
import { checkParseResult, checkQueuePayload } from '@/shared/dispatch-guard'
import { passGuard } from '@/shared/dispatch-guard-ui'
import { formatDateTime } from '@/shared/utils/datetime'
import { resultBuildFailed, taskStatusClass, taskStatusText } from '@/shared/utils/task-status-text'
import {
ensureBrandCheckProxy,
getApiSecretGateState,
getStoredApiSecret,
getStoredApiSecretSnapshot,
listApiSecretModules,
} from '@/shared/utils/api-secret-store'
// ---- 文件选择 / 上传(公共组合式函数)----
const {
files: uploadedFiles,
selectedPaths: selectedFileNames,
selectFiles,
selectFolder,
} = useExcelFileUpload({
requireUploadCapability: true,
pickFilesUnavailableWarning: '当前环境不支持文件选择或上传',
folderUnavailableWarning: '当前环境不支持文件夹选择,请在本地客户端中打开',
errorFallbackMessage: (action) => (action === 'files' ? '文件上传失败' : '选择失败'),
onUploaded: () => {
parseResult.value = null
queuedTaskSummary.value = null
},
onFailed: () => {
parseResult.value = null
queuedTaskSummary.value = null
},
})
const parseResult = ref<AppearancePatentParseVo | null>(null)
type TaskSummary = Pick<AppearancePatentParseVo, 'taskId' | 'totalRows' | 'acceptedRows' | 'groupCount' | 'droppedRows'>
const queuedTaskSummary = ref<TaskSummary | null>(null)
// 不再注入默认 prompt:用户未填则一律空字符串,由后端决定是否给 LLM 透传 prompt 字段。
const aiPrompt = ref('')
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))
/** 结果行版本跟踪(审查 F5 后续):版本未变的任务跳过行明细拉取 */
const rowsVersionTracker = createRowsVersionTracker()
function uidForStorage() {
return typeof window !== 'undefined' ? window.localStorage.getItem('uid') || '0' : '0'
}
// ---- 实时任务面板(与货源查询 Tab 的公共骨架抽到 useLiveTaskBoard)----
const board = useLiveTaskBoard<AppearancePatentHistoryItem>({
scope: 'appearance-patent',
pollingStorageKey: () => `appearance-patent:tasks:${uidForStorage()}`,
fetchHistory: getAppearancePatentHistory,
fetchProgressBatch: getAppearancePatentTaskProgressBatch,
fetchDashboard: getAppearancePatentDashboard,
normalizeTaskStatus,
isResultPreparing,
addPendingAfterFinalStatus: (_task, item) => Boolean(item && isResultPreparing(item)),
keepPendingFileTask: (_item, taskStatus) =>
taskStatus === 'SUCCESS' || taskStatus === 'FAILED' || taskStatus === 'CANCELLED',
settleOnTaskStatuses: ['SUCCESS', 'FAILED', 'CANCELLED'],
beforeBatch: async (taskIds, pendingIds) => {
// 行数据按需拉取(审查 F5 后续):等结果文件(pending)时必须强刷;其余情况版本未变的任务跳过
const mustForce = pendingIds.length > 0
if (!mustForce) {
try {
const light = await getModuleProgressLight('appearancePatent', taskIds)
const heavyIds = rowsVersionTracker.selectTasksNeedingRows(light.items || [], taskIds)
if (!heavyIds.length && !(light.missingTaskIds || []).length) {
// 行数据与状态都没变:本轮不拉行明细,直接结束
return null
}
return { taskIds: heavyIds, force: false }
} catch {
// 轻量端点不可用(老后端/网络)→ 照旧全量拉取,行为与原来一致
return { taskIds, force: false }
}
}
return { taskIds, force: true }
},
getPendingParseItem: () => pendingParseItem.value,
download: {
buildUrl: (resultId) => getAppearancePatentResultDownloadUrl(resultId),
fallbackFilename: 'appearance-patent',
progressKeyPrefix: 'appearance-patent',
},
deleteTask: {
// 有任务就删任务:失败任务常被自动克隆重试(克隆件没有结果行),只删结果行等于
// 删不掉那条任务——统计不降、任务还会被再克隆一次,用户看到的就是「删了又回来」。
shouldDeleteTask: (item) => item.taskId != null,
deleteTask: (taskId) => deleteAppearancePatentTask(taskId),
deleteHistory: (resultId) => deleteAppearancePatentHistory(resultId),
onTaskDeleted: (item) => board.removePollingTask(item.taskId as number),
},
})
/** 失败/已中断的任务能续跑:在原任务上复位(不新建任务),成功/进行中的任务不该出现这个按钮。 */
function canRetryTask(item: AppearancePatentHistoryItem | null | undefined): boolean {
if (!item?.taskId) return false
const status = String(item?.taskStatus || '').toUpperCase()
return status === 'FAILED' || status === 'CANCELLED'
}
/** 按钮文案:已中断的任务显示「继续」(从中断点接着跑),失败任务仍是「重试」。 */
function retryLabel(item: AppearancePatentHistoryItem | null | undefined): string {
return String(item?.taskStatus || '').toUpperCase() === 'CANCELLED' ? '继续' : '重试'
}
/**
* 在跑/待跑的任务可中断(2026-11-03):PENDING/RUNNING/SCHEDULED 是服务端 CAS 的同一
* ACTIVE 集合;终态任务重按是幂等 no-op,不显示按钮让用户少猜一次。
*/
function canInterruptTask(item: AppearancePatentHistoryItem | null | undefined): boolean {
if (!item?.taskId) return false
const status = normalizeTaskStatus(item)
return status === 'PENDING' || status === 'RUNNING' || status === 'SCHEDULED'
}
async function retryTaskRecord(item: AppearancePatentHistoryItem | null | undefined) {
const taskId = item?.taskId
if (!taskId) return
const isResume = String(item?.taskStatus || '').toUpperCase() === 'CANCELLED'
if (isResume && canDownload(item)) {
// 确认框以 reject 收尾属正常交互而不是错误(与 ensureBrandCheckProxyReady 同一口径,
// 不新增 catch 块):.then 两臂分别接「确认/取消」。
const confirmed = await ElMessageBox.confirm(
'继续将重新检测剩余行并生成新的完整结果:当前已生成的部分结果文件会被替换,请先下载留存。确定继续吗?',
'继续任务',
{ type: 'warning', confirmButtonText: '继续', cancelButtonText: '先不继续' },
).then(
() => true,
() => false,
)
if (!confirmed) return
}
try {
await retryAppearancePatentTask(taskId)
ElMessage.success(isResume
? '已继续:在这条任务上接着跑(已检测的行不会重检)'
: '已提交重试:在这条任务上继续跑(不新建任务)')
await refreshBoard()
} catch (error) {
ElMessage.error(error instanceof Error ? error.message : '重试失败')
}
}
async function interruptTaskRecord(item: AppearancePatentHistoryItem | null | undefined) {
const taskId = item?.taskId
if (!taskId) return
// 同上:确认框取消走 reject 两臂,不新增 catch 块
const confirmed = await ElMessageBox.confirm(
'中断后:未完成的行不再检测,已完成检测的数据会生成结果文件供下载。确定中断吗?',
'中断任务',
{ type: 'warning', confirmButtonText: '中断', cancelButtonText: '先不中断' },
).then(
() => true,
() => false,
)
if (!confirmed) return
try {
await interruptAppearancePatentTask(taskId)
ElMessage.success('已中断:已完成部分正在生成结果文件,下载按钮稍后出现')
await refreshBoard()
} catch (error) {
ElMessage.error(error instanceof Error ? error.message : '中断失败')
}
}
const visibleTaskSummary = computed(() => parseResult.value || queuedTaskSummary.value)
/** 手动刷新:强拉历史 + 统计 + 当前轮询任务进度(轮询意外中断后的自救出口) */
async function refreshBoard() {
await Promise.all([
board.loadDashboard(),
board.loadHistory({ force: true }),
board.refreshTaskProgress(),
])
}
const pendingParseItem = computed<AppearancePatentHistoryItem | 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 patentCards = computed<TaskStatCard[]>(() => [
{ label: '运行中任务', value: board.dashboard.value.pendingTaskCount },
{ label: '已完成任务', value: board.dashboard.value.successTaskCount },
{ label: '失败任务', value: board.dashboard.value.failedTaskCount },
])
const currentTaskViews = computed<TaskItemView[]>(() =>
board.currentItems.value.map(toPatentTaskView),
)
const historyTaskViews = computed<TaskItemView[]>(() =>
board.historyOnlyItems.value.map(toPatentTaskView),
)
function itemSource(item: TaskItemView) {
return item.source as AppearancePatentHistoryItem
}
function toPatentTaskView(item: AppearancePatentHistoryItem): TaskItemView {
const showProgress = board.showFileProgress(item)
const progressPercent = fileProgressPercent(item)
return {
key: `patent-${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: progressPercent,
stage: displayFileProgressMessage(item, '处理中'),
}
: null,
source: item,
}
}
// ---- 本模块的状态语义(与货源查询 Tab 不同,保留在 Tab 内)----
function statusText(item: AppearancePatentHistoryItem) {
const status = normalizeTaskStatus(item)
if (status === 'RUNNING') return taskStatusText(status)
if (status === 'PENDING') return taskStatusText(status, { text: { PENDING: '已解析,等待后台执行' } })
if (status === 'CANCELLED') {
// 已中断:检测/采集已停,部分结果文件生成后下载按钮会自动出现。
// 不能掉进函数末尾的「等待中」兜底——那是 task-status-text.ts 点名过的取消态误显形状。
return '已中断'
}
// 已判死(含心跳超时)的任务始终显示失败:后台检测可能仍在跑、文件生成后下载按钮会自动出现,
// 但状态文案不能是"结果生成中",否则用户会以为任务还在执行(2026-09-28 29473/29479)
if (status === 'FAILED') return isResultBuildFailed(item) ? '结果生成失败' : taskStatusText('FAILED')
if (isResultPreparing(item)) return '结果生成中'
if (isResultBuildFailed(item)) return '结果生成失败'
if (hasDownloadableResult(item)) return taskStatusText('SUCCESS')
if (status === 'SUCCESS' || item.success) return taskStatusText('SUCCESS')
return '等待中'
}
function statusClass(item: AppearancePatentHistoryItem) {
const status = normalizeTaskStatus(item)
if (status === 'CANCELLED') return taskStatusClass('CANCELLED')
if (status === 'FAILED' || isResultBuildFailed(item)) return taskStatusClass('FAILED')
if (status === 'RUNNING' || isResultPreparing(item)) return taskStatusClass('RUNNING')
if (hasDownloadableResult(item)) return taskStatusClass('SUCCESS')
if (status === 'SUCCESS' || item.success) return taskStatusClass('SUCCESS')
return 'pending'
}
function isResultPreparing(item: AppearancePatentHistoryItem) {
const status = normalizeTaskStatus(item)
const fileStatus = (item.fileStatus || '').toUpperCase()
if (status !== 'SUCCESS' && status !== 'FAILED') return false
if (canDownload(item)) return false
if (fileStatus === 'FAILED' || fileStatus === 'SUCCESS') return false
return status === 'SUCCESS' || hasActiveFileJob(item)
}
function normalizeTaskStatus(item: AppearancePatentHistoryItem) {
return (item.taskStatus || '').toUpperCase()
}
function isResultBuildFailed(item: AppearancePatentHistoryItem) {
return resultBuildFailed(item.fileStatus, canDownload(item))
}
function pendingResultHint(item: AppearancePatentHistoryItem) {
if (isResultBuildFailed(item)) {
return userNotice(item.fileError, '结果文件生成失败,请稍后重试或检查后端日志')
}
if (board.showFileProgress(item)) {
return ''
}
if (!isResultPreparing(item)) return ''
const doneLabel = normalizeTaskStatus(item) === 'FAILED' ? '任务已失败' : '任务已完成'
const fileStatus = (item.fileStatus || '').toUpperCase()
if (fileStatus === 'PENDING') {
return `${doneLabel},结果文件排队中,请稍候`
}
return `${doneLabel},正在生成结果文件,下载按钮稍后出现`
}
function canDownload(item: AppearancePatentHistoryItem) {
return Boolean(item.resultId && (item.fileReady || item.downloadUrl))
}
function hasDownloadableResult(item: AppearancePatentHistoryItem) {
return canDownload(item)
}
function fileProgressPercent(item: AppearancePatentHistoryItem) {
const percent = Number(item.fileProgressPercent || 0)
if (Number.isFinite(percent) && percent > 0) {
return Math.max(0, Math.min(100, Math.round(percent)))
}
if (shouldShowFallbackJobProgress(item)) {
return activeFileJobStatus(item) === 'PENDING' ? 6 : 10
}
return 0
}
function displayFileProgressMessage(item: AppearancePatentHistoryItem, fallback: string) {
const message = (item.fileProgressMessage || '').trim()
if (!message) return fallback
return translateFileProgressMessage(message)
}
function translateFileProgressMessage(message: string) {
const submittedMatch = message.match(/^LLM submitted (\d+) batches, completed (\d+), waiting for results$/)
if (submittedMatch) {
return `已提交 ${submittedMatch[1]} 批,已完成 ${submittedMatch[2]} 批,等待结果`
}
const completedMatch = message.match(/^LLM completed (\d+) batches, waiting for remaining Python data$/)
if (completedMatch) {
return `已完成 ${completedMatch[1]} 批,等待后续数据`
}
const translations: Record<string, string> = {
'Receiving Python data, waiting for 50 rows before LLM': '正在接收检测数据,累计 50 条后提交检测',
'Submitting LLM': '正在提交检测',
'LLM submitted, waiting for result': '已提交检测,等待结果',
'Waiting for Python upload': '等待后续数据',
'LLM results ready, assembling xlsx': '检测结果已返回,正在生成结果文件',
'Assembling xlsx': '正在生成结果文件',
'Uploading result file': '正在上传结果文件',
'Result file generated': '结果文件已生成',
}
return translations[message] || message
}
// ---- 解析与提交(本模块特有)----
function effectiveAiPrompt() {
// 用户没在文本框填东西就送空字符串,后端会跳过 prompt 字段。
return aiPrompt.value.trim()
}
function effectiveLlmApiKey() {
return getStoredApiSecret('appearance-patent').trim()
}
function toTaskSummary(result: AppearancePatentParseVo): TaskSummary {
return {
taskId: result.taskId,
totalRows: result.totalRows,
acceptedRows: result.acceptedRows,
groupCount: result.groupCount,
droppedRows: result.droppedRows,
}
}
/**
* 本模块自 2026-10-15 起逐行抓取、逐行送检:解析阶段仍按 id 前缀分组,但分组只是
* 回传攒片的单位,不再决定检测覆盖,所以原先这里有一个「分组数异常」确认框
* (组数 < 行数/3 就拦一道,源自任务 28805 的 id 塌陷事故)—— 它的前提已经不存在,
* 且会在用户正常填变体 id(12_1…12_98)时误报,故摘除。检测覆盖由 ap_worker 的
* 逐行抓取用例钉住:maixiang_run_task/test/maixiang_ops/test_proxy_cost_leaks.py。
*/
/**
* 创建任务前确认服务端有代理:商标维度依赖服务端代理,缺代理时整批都会落成
* 「商标查询失败」且状态为失败。服务端读不到(unknown)不拦,避免网络抖动误伤。
*/
async function ensureBrandCheckProxyReady(): Promise<boolean> {
const check = await ensureBrandCheckProxy()
if (check.ok) return true
await ElMessageBox.alert(
'当前账号未在服务端配置代理,商标维度将无法查询,整批结果会显示「商标查询失败」。'
+ '请先点击右上角「密钥设置」,在「代理地址」中保存代理后再创建任务。',
'未配置代理,无法检测商标',
{ type: 'warning', confirmButtonText: '知道了' },
).then(
// 关闭弹窗会以 reject 收尾,属正常交互而不是错误,不新增 catch 块
() => undefined,
() => undefined,
)
return false
}
/** 模块名取服务端下发的 label,前端不再另起一份叫法;默认清单里必有本模块,兜底句只为满足类型。 */
function llmKeyModuleLabel(): string {
return listApiSecretModules().find((info) => info.moduleKey === 'appearance-patent')?.moduleLabel || '对应模块密钥'
}
/**
* 创建任务前确认这个模块的 LLM 密钥已配置:服务端建单口(UserApiSecretService#requireSubmitSecret)
* 也会拒,但那时 Excel 已上传、单已建一半,用户白等一趟,所以把同一句话提到提交前说。
* 门禁状态 unknown(从未成功拉到服务端数据)不拦——网络抖动不等于未配置,与 ensureBrandCheckProxy 同口径。
*/
async function ensureLlmApiKeyReady(): Promise<boolean> {
if (getApiSecretGateState() === 'unknown') return true
const snapshot = getStoredApiSecretSnapshot('appearance-patent')
// exists + 检测通过才算配好;error(上游无法判定)按放行,与 computeApiSecretsComplete 同一判据
const configured = (snapshot.exists && (snapshot.checkStatus === 'passed' || snapshot.checkStatus === 'error'))
|| Boolean(effectiveLlmApiKey())
if (configured) return true
await ElMessageBox.alert(
`该账号还没有配置${llmKeyModuleLabel()}:这一单要用它跑 LLM 检测,`
+ '缺了只会得到一张没有检测结论的结果表。请先在「密钥设置」里填好并保存。',
'未配置密钥,无法创建任务',
{ type: 'warning', confirmButtonText: '知道了' },
).then(
// 关闭弹窗会以 reject 收尾,属正常交互而不是错误,不新增 catch 块
() => undefined,
() => undefined,
)
return false
}
async function parseFiles() {
if (!uploadedFiles.value.length) {
ElMessage.warning('请先选择 Excel')
return
}
if (!(await ensureLlmApiKeyReady())) return
parsing.value = true
try {
if (!(await ensureBrandCheckProxyReady())) {
return
}
const files: UploadedFileRef[] = uploadedFiles.value.map((f) => ({
fileKey: f.fileKey,
originalFilename: f.originalFilename,
relativePath: f.relativePath,
}))
const res = await parseAppearancePatent(files, effectiveAiPrompt(), effectiveLlmApiKey(), collectChannel.value)
// 本模块按主 ID 分组执行,没有分组就没有可跑的批次,一并拦下
const guard = checkParseResult(res, {
requireGroups: true,
requiredColumnsHint: 'id / ASIN / 国家',
})
if (!(await passGuard(guard))) {
parseResult.value = null
queuedTaskSummary.value = null
return
}
parseResult.value = res
queuedTaskSummary.value = null
ElMessage.success(`解析完成,共 ${res.groupCount || 0} 组 / ${res.acceptedRows} 条`)
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : '解析失败')
} finally {
parsing.value = false
}
}
async function pushToPythonQueue() {
const currentParseResult = parseResult.value
const taskId = currentParseResult?.taskId
if (!taskId) {
ElMessage.warning('请先解析文件')
return
}
if (!localCollectEnabled.value) {
// 本地采集关闭:只建单,任务保持 PENDING 由 Linux 后台认领
// (/api/internal/tasks/pull-pending + 主机B maixiang-ap worker)在等待窗口后自动接管。
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
}
const api = getPywebviewApi()
if (!api?.enqueue_json) {
ElMessage.error('当前环境未启用 pywebview enqueue_json,请在本地客户端中打开本页后再启动')
return
}
if (!effectiveLlmApiKey()) {
// 本地无明文不再阻断:服务端已保存该用户密钥,任务执行时按 uid 兜底读取
console.log('[appearance-patent] 本地无密钥明文,启动任务由服务端兜底')
}
pushing.value = true
try {
const parsedPayload: AppearancePatentParsedPayloadDto = await getAppearancePatentQueuePayload(taskId)
const groups = parsedPayload.groups || []
const payload = {
type: 'appearance-patent-run',
ts: Date.now(),
data: {
taskId,
prompt: aiPrompt.value.trim(),
api_key: effectiveLlmApiKey(),
sourceFileCount: currentParseResult.sourceFileCount || 0,
totalRows: currentParseResult.totalRows || 0,
acceptedRows: currentParseResult.acceptedRows || 0,
groupCount: currentParseResult.groupCount || 0,
groups: groups.map((group) => ({
sourceFileKey: group.sourceFileKey || '',
sourceFilename: group.sourceFilename || '',
groupKey: group.groupKey || '',
baseId: group.baseId || '',
displayId: group.displayId || '',
items: (group.items || []).map((row) => ({
sourceFileKey: row.sourceFileKey || '',
sourceFilename: row.sourceFilename || '',
rowToken: row.rowToken || '',
groupKey: row.groupKey || '',
id: row.displayId,
asin: row.asin,
country: row.country,
sku: row.sku || '',
url: row.url || '',
title: row.title || '',
})),
})),
},
}
// 后端返回的 groups 为空时推送出去,Python 端没有可执行批次会一直停在执行中
const guard = checkQueuePayload(payload, {
expectedType: 'appearance-patent-run',
// api_key 不列为必填:密钥已服务端化,本地无明文时由服务端按 uid 兜底
requiredDataKeys: ['taskId'],
nonEmptyArrayKeys: ['groups'],
})
if (!(await passGuard(guard))) return
// 任务可能已被客户端「兜底拉取」/Linux 兜底领走:服务端会拒绝 activate,
// 此时必须直接返回,不能再入队,否则同一任务会被执行两次
try {
await activateAppearancePatentTask(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('已启动任务')
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : '启动失败')
} finally {
pushing.value = false
}
}
function clearParsedTask() {
parseResult.value = null
}
const { batchDeleteHistory, deleteTaskRecord, downloadResult } = board
onMounted(async () => {
board.loadPollingIds()
// 单选框默认选中项取服务端模块默认;读不到就按本机,服务端 activate 会兜底拒绝
getCollectRouting()
.then((routing) => {
collectChannel.value = routing.appearancePatentLocal !== false ? 'LOCAL' : 'ONLINE'
})
.catch((error) => {
console.warn('[appearance-patent] 读取采集通道默认值失败,按本机采集处理', error)
})
await Promise.all([
board.loadDashboard().catch(() => undefined),
board.loadHistory().catch(() => undefined),
])
board.seedRunningTasksFromHistory()
board.seedPendingFileTasksFromHistory()
board.ensurePollingIfAny()
})
onUnmounted(() => {
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, .subsection-title { font-size: 13px; color: #a0acbe; margin-bottom: 10px; }
.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, .btn-retry, .btn-interrupt, .download { border: none; cursor: pointer; }
/* 行内动作按钮钉死 12px 字号 + 6px 圆角:reset.css 里 button 是 font: inherit,
不写就继承到 16px,比状态徽章高出一截、字也大一号(2026-11-12 实测徽章 38px / 按钮 54px) */
.btn-delete, .btn-retry, .btn-interrupt, .download { border-radius: 6px; font-size: 12px; }
.btn-run { padding: 10px 18px; border-radius: 7px; color: #f5f8fc; background: #3498db; font-weight: 600; }
.btn-queue { background: #27ae60; }
.btn-run:disabled { opacity: .55; cursor: not-allowed; }
.prompt-card, .secret-card { margin-bottom: 18px; }
.secret-card { display: none; }
.prompt-input { width: 100%; box-sizing: border-box; resize: vertical; min-height: 180px; padding: 10px 12px; border: 1px solid #333; border-radius: 8px; background: #222b3d; color: #c8d2e2; font-size: 12px; line-height: 1.6; outline: none; }
.secret-input { width: 100%; box-sizing: border-box; height: 38px; padding: 0 12px; border: 1px solid #333; border-radius: 8px; background: #222b3d; color: #c8d2e2; font-size: 12px; outline: none; }
.prompt-input:focus, .secret-input:focus { border-color: #3498db; }
.parse-card { margin-top: 14px; padding: 12px; border: 1px solid #2e3a52; border-radius: 8px; background: #222b3d; color: #a0acbe; font-size: 12px; }
.result-table { --el-table-bg-color: #242424; --el-table-tr-bg-color: #242424; --el-table-header-bg-color: #2e3a52; --el-table-text-color: #c8d2e2; --el-table-border-color: #333; }
.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); }
.btn-retry { padding: 6px 10px; color: #7fd1a0; background: rgba(39, 174, 96, .14); }
/* 中断是带后果的警示动作(未完成行不再检测):琥珀色区别于「重试」的绿与「删除」的红 */
.btn-interrupt { padding: 6px 10px; color: #f0b35e; background: rgba(240, 179, 94, .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>