feat(jd-collect): 任务面板改版——后端 dashboard/history/progress-batch/delete 四端点+前端左按钮右 TaskCenterPanel(历史/断点续传/中断/重试走通用原位复位)
This commit is contained in:
@@ -1,159 +1,237 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onBeforeUnmount, onMounted, ref } from 'vue'
|
||||
import { computed, onMounted, onUnmounted, ref } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import TaskCenterPanel from '@/shared/components/tasks/TaskCenterPanel.vue'
|
||||
import type { TaskItemView, TaskStatCard } from '@/shared/components/tasks/types'
|
||||
import {
|
||||
activateJdCollectTask,
|
||||
createJdCollectTask,
|
||||
fetchJdCollectProgress,
|
||||
type JdCollectProgressVo,
|
||||
deleteJdCollectTask,
|
||||
fetchJdCollectDashboard,
|
||||
fetchJdCollectHistory,
|
||||
fetchJdCollectTaskProgressBatch,
|
||||
interruptJdCollectTask,
|
||||
type JdCollectHistoryItemVo,
|
||||
type JdListTab,
|
||||
} from '@/shared/api/types/modules/jd-collect'
|
||||
import { retryClientTask } from '@/shared/api/task-retry'
|
||||
import { getPywebviewApi } from '@/shared/bridges/pywebview'
|
||||
import { resolvePageHref } from '@/shared/page-prefix'
|
||||
import { isTerminalTaskStatus } from '@/shared/utils/task-terminal'
|
||||
import { userNotice } from '@/shared/utils/user-notice'
|
||||
import { formatDateTime } from '@/shared/utils/datetime'
|
||||
import { useLiveTaskBoard } from '@/shared/composables/useLiveTaskBoard'
|
||||
import NotificationBell from '@/shared/components/NotificationBell.vue'
|
||||
|
||||
/** 京东「获取店铺数据」(v1.5):一键建单 → 推送本机客户端 → 轮询服务端进度。
|
||||
/** 京东「获取店铺数据」(v1.5):一键建单 → 推送本机客户端 → 右侧任务面板实时进度。
|
||||
*
|
||||
* 三个真源与三条边界(照 v1.4 已落地的采集契约,不另造流程):
|
||||
* 四个真源与四条边界(照 v1.4 已落地的采集契约与外观专利任务面板骨架,不另造流程):
|
||||
* 1. 建单走后端 `/api/jd-collect/tasks`(通道恒 LOCAL,服务端落 PENDING);
|
||||
* 2. 建单成功把 `jd-shop-collect-run` 载荷推进本机客户端队列——只建单不推送会让任务
|
||||
* 卡在 PENDING 等兜底拉取(v1.4 Phase 6.1 P0-1 的教训);推送失败不回滚建单;
|
||||
* 3. 进度只读服务端(`/tasks/{taskId}/progress`):任务状态 + 合并写游标里的
|
||||
* itemsReceived/total。`total` 缺失时进度条走不定态,不编造百分比。
|
||||
* 3. 进度只读服务端:任务状态 + 合并写游标里的 itemsReceived/total。`total` 缺失时
|
||||
* 卡片只显示已采集行数,不编造百分比;
|
||||
* 4. 失败/中断任务「重试/继续」走通用原位复位(铁律 26,保留已收分片与断点游标),
|
||||
* 复位后页面重新激活并推队列——同一份输入不再多出好几行结果。
|
||||
*/
|
||||
|
||||
type ProgressStatus = 'PENDING' | 'RUNNING' | 'SUCCESS' | 'FAILED'
|
||||
type ProgressPhase = 'idle' | 'running' | 'done' | 'failed'
|
||||
|
||||
const POLL_INTERVAL_MS = 2000
|
||||
/** 一小时还没终态就停轮询(任务本身有 stale 兜底,页面不该无限烧请求)。 */
|
||||
const POLL_TIMEOUT_MS = 60 * 60 * 1000
|
||||
/** 页面不再让用户填店铺名:店铺名称由客户端从京麦后台读,建单先按此占位记录。 */
|
||||
const DEFAULT_SHOP_NAME = '京麦后台'
|
||||
const DEFAULT_TABS: JdListTab[] = ['ONSALE', 'OFFSALE']
|
||||
|
||||
const homeHref = resolvePageHref('/new_web_source/home.html')
|
||||
const backHref = resolvePageHref('/new_web_source/jd-console.html')
|
||||
|
||||
const username = ref('admin')
|
||||
const submitting = ref(false)
|
||||
const taskId = ref<number | null>(null)
|
||||
const progress = ref<JdCollectProgressVo | null>(null)
|
||||
const phase = ref<ProgressPhase>('idle')
|
||||
const errorMessage = ref('')
|
||||
const successMessage = ref('')
|
||||
|
||||
let pollTimer: number | undefined
|
||||
let pollStartedAt = 0
|
||||
let pollFailures = 0
|
||||
function uidForStorage() {
|
||||
return typeof window !== 'undefined' ? window.localStorage.getItem('uid') || '0' : '0'
|
||||
}
|
||||
|
||||
const statusText = computed(() => {
|
||||
const status = progress.value?.status
|
||||
if (phase.value === 'done') return '获取完成'
|
||||
if (phase.value === 'failed') return '获取失败'
|
||||
switch (status) {
|
||||
case 'PENDING':
|
||||
return '等待本机客户端领取任务…'
|
||||
case 'RUNNING':
|
||||
return '正在获取店铺数据…'
|
||||
case 'SUCCESS':
|
||||
return '获取完成'
|
||||
case 'FAILED':
|
||||
return '获取失败'
|
||||
default:
|
||||
return '已提交,正在确认任务状态…'
|
||||
// ---- 实时任务面板(与外观专利共用 useLiveTaskBoard 骨架;京东无结果文件,无下载层)----
|
||||
const board = useLiveTaskBoard<JdCollectHistoryItemVo>({
|
||||
scope: 'jd-collect',
|
||||
pollingStorageKey: () => `jd-collect:tasks:${uidForStorage()}`,
|
||||
fetchHistory: fetchJdCollectHistory,
|
||||
fetchProgressBatch: fetchJdCollectTaskProgressBatch,
|
||||
fetchDashboard: fetchJdCollectDashboard,
|
||||
normalizeTaskStatus,
|
||||
// 京东采集没有结果文件:状态到终态即结束,没有「等文件」那一层
|
||||
isResultPreparing: () => false,
|
||||
addPendingAfterFinalStatus: () => false,
|
||||
keepPendingFileTask: () => false,
|
||||
// CANCELLED 也是终态:中断的任务出「继续」按钮并停止轮询,不收手会一直烧进度请求
|
||||
settleOnTaskStatuses: ['SUCCESS', 'FAILED', 'CANCELLED'],
|
||||
deleteTask: {
|
||||
shouldDeleteTask: (item) => item.taskId != null,
|
||||
deleteTask: (taskId) => deleteJdCollectTask(taskId),
|
||||
deleteHistory: async () => undefined,
|
||||
onTaskDeleted: (item) => board.removePollingTask(item.taskId as number),
|
||||
},
|
||||
})
|
||||
|
||||
const { batchDeleteHistory, deleteTaskRecord } = board
|
||||
|
||||
const jdCards = 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(toJdTaskView),
|
||||
)
|
||||
const historyTaskViews = computed<TaskItemView[]>(() =>
|
||||
board.historyOnlyItems.value.map(toJdTaskView),
|
||||
)
|
||||
|
||||
function itemSource(item: TaskItemView) {
|
||||
return item.source as JdCollectHistoryItemVo
|
||||
}
|
||||
|
||||
function toJdTaskView(item: JdCollectHistoryItemVo): TaskItemView {
|
||||
const showProgress = isActiveTask(item)
|
||||
return {
|
||||
key: `jd-${item.taskId ?? item.taskNo ?? item.updatedAt ?? ''}`,
|
||||
title: item.shopName || '京东店铺采集',
|
||||
taskId: item.taskId ?? '-',
|
||||
startedAt: formatDateTime(item.createdAt),
|
||||
finishedAt: formatDateTime(item.finishedAt),
|
||||
statusText: statusText(item),
|
||||
statusClass: statusClass(item),
|
||||
extraLines: [
|
||||
...(item.rowCount != null ? [`已采集 ${item.rowCount} 个商品`] : []),
|
||||
...(showProgress && typeof item.page === 'number' && item.page > 0
|
||||
? [`断点游标:第 ${item.page} 页 · 已回传 ${item.batches ?? 0} 批`]
|
||||
: []),
|
||||
...(item.errorMessage ? [`错误:${userNotice(item.errorMessage)}`] : []),
|
||||
],
|
||||
progress: showProgress ? { percent: progressPercent(item), countLabel: `已采集 ${item.itemsReceived ?? item.rowCount ?? 0} 个商品` } : null,
|
||||
source: item,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
const itemsReceived = computed(() => progress.value?.itemsReceived ?? 0)
|
||||
const totalCount = computed(() => {
|
||||
const total = progress.value?.total
|
||||
return typeof total === 'number' && total > 0 ? total : null
|
||||
})
|
||||
// ---- 本模块的状态语义(京东采集:无结果文件,状态即终态)----
|
||||
|
||||
/** 百分比:终态 100;有 total 按已落库商品数算(封顶 99 直到服务端落 SUCCESS)。 */
|
||||
const percent = computed<number | null>(() => {
|
||||
if (phase.value === 'done') return 100
|
||||
const total = totalCount.value
|
||||
if (!total) return null
|
||||
const done = Math.min(itemsReceived.value, total)
|
||||
function normalizeTaskStatus(item: JdCollectHistoryItemVo | null | undefined) {
|
||||
return (item?.taskStatus || '').toUpperCase()
|
||||
}
|
||||
|
||||
function isActiveTask(item: JdCollectHistoryItemVo) {
|
||||
const status = normalizeTaskStatus(item)
|
||||
return status === 'PENDING' || status === 'RUNNING' || status === 'SCHEDULED'
|
||||
}
|
||||
|
||||
function statusText(item: JdCollectHistoryItemVo) {
|
||||
const status = normalizeTaskStatus(item)
|
||||
if (status === 'RUNNING') return '正在获取店铺数据…'
|
||||
if (status === 'PENDING') return '等待本机客户端领取任务…'
|
||||
if (status === 'SCHEDULED') return '已排队,等待执行'
|
||||
if (status === 'CANCELLED') return '已中断'
|
||||
if (status === 'FAILED') return '获取失败'
|
||||
if (status === 'SUCCESS' || item.success) return '获取完成'
|
||||
return '等待中'
|
||||
}
|
||||
|
||||
function statusClass(item: JdCollectHistoryItemVo) {
|
||||
const status = normalizeTaskStatus(item)
|
||||
if (status === 'FAILED') return 'failed'
|
||||
if (status === 'RUNNING' || status === 'SCHEDULED') return 'running'
|
||||
if (status === 'CANCELLED') return 'pending'
|
||||
if (status === 'SUCCESS' || item.success) return 'success'
|
||||
return 'pending'
|
||||
}
|
||||
|
||||
/** 百分比:有 total 按已落库商品数算(封顶 99 直到服务端落 SUCCESS);没有 total 不编造分母。 */
|
||||
function progressPercent(item: JdCollectHistoryItemVo) {
|
||||
const status = normalizeTaskStatus(item)
|
||||
if (status === 'SUCCESS') return 100
|
||||
const total = typeof item.total === 'number' && item.total > 0 ? item.total : null
|
||||
if (!total) return 0
|
||||
const done = Math.min(item.itemsReceived ?? 0, total)
|
||||
return Math.max(0, Math.min(99, Math.round((done * 100) / total)))
|
||||
})
|
||||
|
||||
const percentText = computed(() => (percent.value === null ? '' : `${percent.value}%`))
|
||||
|
||||
const progressMeta = computed(() => {
|
||||
const vo = progress.value
|
||||
if (!vo) return ''
|
||||
const parts: string[] = [`已采集 ${itemsReceived.value} 个商品`]
|
||||
if (totalCount.value) {
|
||||
parts.push(`共 ${totalCount.value} 个`)
|
||||
}
|
||||
if (typeof vo.page === 'number' && vo.page > 0) {
|
||||
parts.push(`第 ${vo.page} 页`)
|
||||
}
|
||||
if (typeof vo.batches === 'number' && vo.batches > 0) {
|
||||
parts.push(`已回传 ${vo.batches} 批`)
|
||||
}
|
||||
return parts.join(' · ')
|
||||
})
|
||||
|
||||
const isRunning = computed(() => phase.value === 'running' || submitting.value)
|
||||
|
||||
function stopPolling() {
|
||||
if (pollTimer !== undefined) {
|
||||
window.clearTimeout(pollTimer)
|
||||
pollTimer = undefined
|
||||
}
|
||||
}
|
||||
|
||||
function applyTerminal(vo: JdCollectProgressVo) {
|
||||
stopPolling()
|
||||
// 终态集合走共享词表(shared/utils/task-terminal,含 COMPLETED≡SUCCESS);
|
||||
// 只有明确 FAILED 才当失败,其余终态都按完成展示——窄集合是六页踩过的坑。
|
||||
if (vo.status !== 'FAILED') {
|
||||
phase.value = 'done'
|
||||
successMessage.value = `获取完成:共采集 ${vo.itemsReceived ?? 0} 个商品,` +
|
||||
'已导入后台「京东数据库」。'
|
||||
return
|
||||
}
|
||||
phase.value = 'failed'
|
||||
errorMessage.value = vo.message?.trim()
|
||||
|| '获取失败:没有拿到失败原因,请到客户端任务列表查看详情'
|
||||
/** 失败/已中断的任务能续跑:在原任务上复位(不新建任务),成功/进行中的任务不该出现这个按钮。 */
|
||||
function canRetryTask(item: JdCollectHistoryItemVo | null | undefined): boolean {
|
||||
if (!item?.taskId) return false
|
||||
const status = normalizeTaskStatus(item)
|
||||
return status === 'FAILED' || status === 'CANCELLED'
|
||||
}
|
||||
|
||||
async function pollProgress(id: number) {
|
||||
/** 按钮文案:已中断的任务显示「继续」(从断点接着跑),失败任务仍是「重试」。 */
|
||||
function retryLabel(item: JdCollectHistoryItemVo | null | undefined): string {
|
||||
return normalizeTaskStatus(item) === 'CANCELLED' ? '继续' : '重试'
|
||||
}
|
||||
|
||||
/** 在跑/待跑的任务可中断:PENDING/RUNNING/SCHEDULED 是服务端 CAS 的同一 ACTIVE 集合。 */
|
||||
function canInterruptTask(item: JdCollectHistoryItemVo | null | undefined): boolean {
|
||||
if (!item?.taskId) return false
|
||||
const status = normalizeTaskStatus(item)
|
||||
return status === 'PENDING' || status === 'RUNNING' || status === 'SCHEDULED'
|
||||
}
|
||||
|
||||
async function interruptTaskRecord(item: JdCollectHistoryItemVo | 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 {
|
||||
const vo = await fetchJdCollectProgress(id)
|
||||
progress.value = vo
|
||||
pollFailures = 0
|
||||
if (isTerminalTaskStatus(vo.status)) {
|
||||
applyTerminal(vo)
|
||||
return
|
||||
}
|
||||
} catch (err) {
|
||||
pollFailures += 1
|
||||
// 单次失败不打断轮询(网络抖动/切页);连续失败 5 次才把进度条挂上提示,
|
||||
// 异常原文只留 console(英文原文不进界面)。
|
||||
console.error('[jd-collect] 进度查询失败', err)
|
||||
if (pollFailures >= 5) {
|
||||
errorMessage.value = '进度查询连续失败,请检查网络;任务本身仍在客户端执行'
|
||||
}
|
||||
await interruptJdCollectTask(taskId)
|
||||
ElMessage.success('已中断:客户端下一跳心跳后收手,之后可点「继续」接着跑')
|
||||
await refreshBoard()
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '中断失败')
|
||||
}
|
||||
if (Date.now() - pollStartedAt > POLL_TIMEOUT_MS) {
|
||||
stopPolling()
|
||||
errorMessage.value = '进度查询超时,请到客户端任务列表查看采集结果'
|
||||
return
|
||||
}
|
||||
|
||||
async function retryTaskRecord(item: JdCollectHistoryItemVo | null | undefined) {
|
||||
const taskId = item?.taskId
|
||||
if (!taskId) return
|
||||
const isResume = normalizeTaskStatus(item) === 'CANCELLED'
|
||||
try {
|
||||
await retryClientTask(taskId)
|
||||
ElMessage.success(isResume
|
||||
? '已继续:在这条任务上接着跑(断点游标保留,不重复采集)'
|
||||
: '已提交重试:在这条任务上继续跑(不新建任务)')
|
||||
// 复位是 PENDING:与建单同一条激活+推队列链路,客户端才会立刻领到这一单。
|
||||
// 激活/推送失败不回滚复位——任务留在 PENDING 由客户端兜底拉取认领。
|
||||
const activateError = await activateTask(taskId)
|
||||
if (!activateError) {
|
||||
await pushToClientQueue(taskId, item?.shopName || DEFAULT_SHOP_NAME,
|
||||
(item?.listTabs?.length ? item.listTabs : DEFAULT_TABS) as JdListTab[])
|
||||
}
|
||||
board.addPollingTask(taskId)
|
||||
await refreshBoard()
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '重试失败')
|
||||
}
|
||||
pollTimer = window.setTimeout(() => {
|
||||
void pollProgress(id)
|
||||
}, POLL_INTERVAL_MS)
|
||||
}
|
||||
|
||||
/** 手动刷新:强拉历史 + 统计 + 当前轮询任务进度(轮询意外中断后的自救出口) */
|
||||
async function refreshBoard() {
|
||||
await Promise.all([
|
||||
board.loadDashboard(),
|
||||
board.loadHistory({ force: true }),
|
||||
board.refreshTaskProgress(),
|
||||
])
|
||||
}
|
||||
|
||||
/** 激活任务(PENDING→RUNNING),返回 null 表示可推队列,返回 string 表示失败原因。
|
||||
*
|
||||
* 2026-11-14 真机实录:页面建完单直接推客户端,任务还是 PENDING ⇒ 客户端第一个分片被
|
||||
* 「任务不在运行中(PENDING)」拒收、心跳回 alive=false 要求客户端收手,采集白跑一轮。
|
||||
* 相似ASIN/货源/外观专利/上架四条链都有这一步,京东这条在建单入口漏了。
|
||||
*/
|
||||
async function activateTask(id: number): Promise<string | null> {
|
||||
try {
|
||||
@@ -196,19 +274,18 @@ async function pushToClientQueue(
|
||||
return '推送本机队列失败,任务将由客户端兜底拉取认领'
|
||||
}
|
||||
|
||||
const isRunning = computed(() => Boolean(board.dashboard.value.pendingTaskCount) || submitting.value)
|
||||
|
||||
async function startCollect() {
|
||||
if (isRunning.value) return
|
||||
stopPolling()
|
||||
if (submitting.value) return
|
||||
errorMessage.value = ''
|
||||
successMessage.value = ''
|
||||
progress.value = null
|
||||
phase.value = 'running'
|
||||
submitting.value = true
|
||||
const shop = DEFAULT_SHOP_NAME
|
||||
const tabs: JdListTab[] = ['ONSALE', 'OFFSALE']
|
||||
const tabs = DEFAULT_TABS
|
||||
try {
|
||||
const vo = await createJdCollectTask(shop, tabs, 0)
|
||||
taskId.value = vo.taskId
|
||||
board.addPollingTask(vo.taskId)
|
||||
let pushNote = ''
|
||||
const activateError = await activateTask(vo.taskId)
|
||||
if (activateError) {
|
||||
@@ -218,34 +295,41 @@ async function startCollect() {
|
||||
} else {
|
||||
try {
|
||||
const pushError = await pushToClientQueue(vo.taskId, shop, tabs)
|
||||
if (pushError) pushNote = ` ${pushError}`
|
||||
if (pushError) pushNote = pushError
|
||||
} catch (pushErr) {
|
||||
// 推送自身异常不回滚建单:任务可由服务端兜底拉取认领。
|
||||
pushNote = ' 推送本机队列失败,任务将由服务端兜底派发给本机客户端执行'
|
||||
pushNote = '推送本机队列失败,任务将由服务端兜底派发给本机客户端执行'
|
||||
console.error('[jd-collect] 推送本机队列失败', pushErr)
|
||||
}
|
||||
}
|
||||
if (pushNote) {
|
||||
errorMessage.value = pushNote.trim()
|
||||
errorMessage.value = pushNote
|
||||
} else {
|
||||
successMessage.value = '任务已创建并推送给本机客户端,进度显示在右侧任务区'
|
||||
}
|
||||
pollStartedAt = Date.now()
|
||||
pollFailures = 0
|
||||
void pollProgress(vo.taskId)
|
||||
await Promise.all([board.loadDashboard(), board.loadHistory({ force: true })])
|
||||
} catch (err) {
|
||||
phase.value = 'failed'
|
||||
errorMessage.value = err instanceof Error ? err.message : '建单失败,请稍后重试'
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
onMounted(async () => {
|
||||
const localName = (window.localStorage.getItem('username') || '').trim()
|
||||
if (localName) username.value = localName
|
||||
board.loadPollingIds()
|
||||
await Promise.all([
|
||||
board.loadDashboard().catch(() => undefined),
|
||||
board.loadHistory().catch(() => undefined),
|
||||
])
|
||||
board.seedRunningTasksFromHistory()
|
||||
board.seedPendingFileTasksFromHistory()
|
||||
board.ensurePollingIfAny()
|
||||
})
|
||||
|
||||
onBeforeUnmount(() => {
|
||||
stopPolling()
|
||||
onUnmounted(() => {
|
||||
board.dispose()
|
||||
})
|
||||
</script>
|
||||
|
||||
@@ -277,34 +361,49 @@ onBeforeUnmount(() => {
|
||||
</div>
|
||||
|
||||
<main class="jd-body">
|
||||
<div class="collect-card">
|
||||
<aside class="left-panel">
|
||||
<button class="collect-btn" type="button" :disabled="isRunning" @click="startCollect">
|
||||
{{ isRunning ? '获取中…' : '一键获取店铺数据' }}
|
||||
</button>
|
||||
|
||||
<p class="collect-hint">
|
||||
点击后本机客户端会自动打开已登录的京麦后台采集商品,请保持客户端在线且京麦已登录;
|
||||
采集到的数据会实时回传并导入后台。
|
||||
采集到的数据会实时回传并导入后台「京东数据库」。进度显示在右侧任务区。
|
||||
</p>
|
||||
|
||||
<section v-if="taskId" class="progress-block">
|
||||
<div class="progress-head">
|
||||
<span class="progress-status">{{ statusText }}</span>
|
||||
<span v-if="percentText" class="progress-percent">{{ percentText }}</span>
|
||||
</div>
|
||||
<div class="progress-track">
|
||||
<div
|
||||
class="progress-fill"
|
||||
:class="{ 'progress-fill--indeterminate': percent === null && phase === 'running' }"
|
||||
:style="percent === null ? undefined : { width: `${percent}%` }"
|
||||
></div>
|
||||
</div>
|
||||
<div v-if="progressMeta" class="progress-meta">{{ progressMeta }}</div>
|
||||
</section>
|
||||
|
||||
<p v-if="successMessage" class="feedback success">{{ successMessage }}</p>
|
||||
<p v-if="errorMessage" class="feedback error">{{ errorMessage }}</p>
|
||||
</div>
|
||||
</aside>
|
||||
|
||||
<section class="right-panel">
|
||||
<TaskCenterPanel
|
||||
:on-batch-delete="batchDeleteHistory"
|
||||
:on-refresh="refreshBoard"
|
||||
title="获取店铺数据"
|
||||
:cards="jdCards"
|
||||
:current-items="currentTaskViews"
|
||||
:history-items="historyTaskViews"
|
||||
current-title="当前任务"
|
||||
current-empty-text="暂无当前任务"
|
||||
history-empty-text="暂无历史记录"
|
||||
>
|
||||
<template #item-actions="{ item }">
|
||||
<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="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" type="button" class="btn-delete"
|
||||
@click="deleteTaskRecord(itemSource(item))">删除</button>
|
||||
</template>
|
||||
</TaskCenterPanel>
|
||||
</section>
|
||||
</main>
|
||||
</div>
|
||||
</template>
|
||||
@@ -453,24 +552,30 @@ onBeforeUnmount(() => {
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
/* ===== 左按钮 + 右任务面板(照外观专利 Tab 布局)===== */
|
||||
.jd-body {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
padding: 4px 34px 40px;
|
||||
display: flex;
|
||||
justify-content: center;
|
||||
/* 卡片按内容高度收口:flex 默认 stretch 会把它拉到整屏,空白比内容还长 */
|
||||
align-items: flex-start;
|
||||
align-items: stretch;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.collect-card {
|
||||
width: 100%;
|
||||
max-width: 720px;
|
||||
padding: 26px 28px;
|
||||
border: 1px solid #3e4a62;
|
||||
border-radius: 12px;
|
||||
background: #232a3b;
|
||||
.left-panel {
|
||||
width: 400px;
|
||||
flex-shrink: 0;
|
||||
padding: 20px;
|
||||
overflow-y: auto;
|
||||
border-right: 1px solid #3e4a62;
|
||||
}
|
||||
|
||||
.right-panel {
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow-y: auto;
|
||||
padding: 20px;
|
||||
}
|
||||
|
||||
.collect-btn {
|
||||
@@ -505,76 +610,6 @@ onBeforeUnmount(() => {
|
||||
line-height: 1.7;
|
||||
}
|
||||
|
||||
/* ===== 进度条 ===== */
|
||||
.progress-block {
|
||||
margin-top: 22px;
|
||||
padding: 16px 18px;
|
||||
border: 1px solid #3e4a62;
|
||||
border-radius: 10px;
|
||||
background: #1f2637;
|
||||
}
|
||||
|
||||
.progress-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
margin-bottom: 10px;
|
||||
}
|
||||
|
||||
.progress-status {
|
||||
color: #f5f8fc;
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.progress-percent {
|
||||
color: #ff8a80;
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.progress-track {
|
||||
position: relative;
|
||||
height: 12px;
|
||||
overflow: hidden;
|
||||
border-radius: 999px;
|
||||
background: #11161f;
|
||||
border: 1px solid #2a3344;
|
||||
}
|
||||
|
||||
.progress-fill {
|
||||
height: 100%;
|
||||
width: 0;
|
||||
border-radius: 999px;
|
||||
background: linear-gradient(90deg, #ff7a70, #e1251b);
|
||||
transition: width 0.4s ease;
|
||||
}
|
||||
|
||||
/* 没有 total(客户端还没抓到列表首页)时走不定态:不编造百分比 */
|
||||
.progress-fill--indeterminate {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
width: 40%;
|
||||
animation: jd-progress-indeterminate 1.2s ease-in-out infinite;
|
||||
}
|
||||
|
||||
@keyframes jd-progress-indeterminate {
|
||||
0% {
|
||||
transform: translateX(-100%);
|
||||
}
|
||||
100% {
|
||||
transform: translateX(250%);
|
||||
}
|
||||
}
|
||||
|
||||
.progress-meta {
|
||||
margin-top: 10px;
|
||||
color: #a0acbe;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.feedback {
|
||||
margin: 16px 0 0;
|
||||
padding: 10px 12px;
|
||||
@@ -593,6 +628,13 @@ onBeforeUnmount(() => {
|
||||
color: #fca5a5;
|
||||
}
|
||||
|
||||
/* 行内动作按钮:与外观专利 Tab 同色系(中断琥珀/重试绿/删除红),钉死 12px 字号 */
|
||||
.btn-delete, .btn-retry, .btn-interrupt { border: none; cursor: pointer; border-radius: 6px; font-size: 12px; }
|
||||
.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) {
|
||||
.tool-head {
|
||||
padding: 10px 16px;
|
||||
@@ -600,7 +642,18 @@ onBeforeUnmount(() => {
|
||||
}
|
||||
|
||||
.jd-body {
|
||||
padding: 4px 16px 24px;
|
||||
flex-direction: column;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.left-panel {
|
||||
width: 100%;
|
||||
border-right: none;
|
||||
border-bottom: 1px solid #3e4a62;
|
||||
}
|
||||
|
||||
.right-panel {
|
||||
padding: 16px;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -213,6 +213,14 @@ export const API_ENDPOINTS = {
|
||||
progress: '/api/jd-collect/tasks/{taskId}/progress',
|
||||
heartbeat: '/api/jd-collect/tasks/{taskId}/heartbeat',
|
||||
chunk: '/api/jd-collect/tasks/{taskId}/chunk',
|
||||
/** 任务面板总览(运行中/成功/失败计数统计卡) */
|
||||
dashboard: '/api/jd-collect/dashboard',
|
||||
/** 任务历史(活跃任务排前,含行数与断点游标) */
|
||||
history: '/api/jd-collect/history',
|
||||
/** 批量任务进度(面板轮询专用,归属先经公共出口过滤) */
|
||||
progressBatch: '/api/jd-collect/tasks/progress/batch',
|
||||
/** 删除任务(连带清理京东数据库该任务的商品/图片/SKU 行与断点游标) */
|
||||
deleteTask: '/api/jd-collect/tasks/{taskId}',
|
||||
},
|
||||
userSecret: {
|
||||
bundle: '/api/user-secrets',
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { get, post, type JavaApiResponse, unwrapJavaResponse } from '../../http.ts'
|
||||
import { buildJavaUrl } from '../../url.ts'
|
||||
import { get, post, del, type JavaApiResponse, unwrapJavaResponse } from '../../http.ts'
|
||||
import { buildJavaUrl, JAVA_API_PREFIX } from '../../url.ts'
|
||||
import { getCurrentUserId } from '../../user.ts'
|
||||
import { API_ENDPOINTS } from '../../endpoints.ts'
|
||||
import { getTaskProgressTimeoutMs } from '../../../task-progress-config.ts'
|
||||
import { getTaskProgressCacheTtlMs, getTaskProgressTimeoutMs } from '../../../task-progress-config.ts'
|
||||
import { createTaskProgressRequestCache } from '../../../task-progress-request-cache.ts'
|
||||
|
||||
/** 京东店铺采集建单回执(蓝图 §3.2):任务落 PENDING、执行通道固定 LOCAL,由本机客户端领取执行。 */
|
||||
export interface JdCollectTaskVo {
|
||||
@@ -28,13 +29,13 @@ export type JdListTab = 'ONSALE' | 'OFFSALE'
|
||||
export interface JdCollectProgressVo {
|
||||
taskId: number;
|
||||
status: string;
|
||||
itemsReceived: number | null;
|
||||
total: number | null;
|
||||
page: number | null;
|
||||
listTab: string | null;
|
||||
batches: number | null;
|
||||
message: string | null;
|
||||
updatedAt: string | null;
|
||||
itemsReceived?: number;
|
||||
total?: number;
|
||||
page?: number;
|
||||
listTab?: string;
|
||||
batches?: number;
|
||||
message?: string;
|
||||
updatedAt?: string;
|
||||
}
|
||||
|
||||
/** 轮询采集进度:uid 与建单同口径(会话身份),任务 owner 不一致服务端直接拒。 */
|
||||
@@ -76,3 +77,184 @@ export function createJdCollectTask(shopName: string, listTabs: JdListTab[], max
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 任务面板(v1.5):总览统计卡 / 历史层 / 活跃任务批量进度 / 删除任务。
|
||||
// 形状照外观专利 appearance-patent.ts 同名函数;京东采集没有结果文件,
|
||||
// 所以没有 downloadUrl / fileStatus 那一层,进度直接用游标 itemsReceived/total。
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** 任务面板总览(运行中/已结束/成功/失败任务数)。 */
|
||||
export interface JdCollectDashboardVo {
|
||||
pendingTaskCount: number;
|
||||
processedTaskCount: number;
|
||||
successTaskCount: number;
|
||||
failedTaskCount: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 历史行(任务卡片数据源)。`total` 为 null 时页面用不定态进度条,
|
||||
* 与单任务进度条同口径(客户端抓过列表首页才写进游标,不编造分母)。
|
||||
*/
|
||||
export interface JdCollectHistoryItemVo {
|
||||
resultId?: number;
|
||||
taskId?: number;
|
||||
taskNo?: string;
|
||||
/** biz_file_task.status 原值:PENDING/RUNNING/SUCCESS/FAILED */
|
||||
taskStatus?: string;
|
||||
success?: boolean;
|
||||
errorMessage?: string;
|
||||
shopName?: string;
|
||||
listTabs?: string[];
|
||||
/** 已落京东数据库的商品行数 */
|
||||
rowCount?: number;
|
||||
itemsReceived?: number;
|
||||
total?: number;
|
||||
page?: number;
|
||||
listTab?: string;
|
||||
batches?: number;
|
||||
updatedAt?: string;
|
||||
createdAt?: string;
|
||||
finishedAt?: string;
|
||||
}
|
||||
|
||||
export interface JdCollectHistoryVo {
|
||||
items: JdCollectHistoryItemVo[];
|
||||
}
|
||||
|
||||
/** 批量进度条目:任务头 + 单元素进度行(与外观专利 TaskDetailVo 同形)。 */
|
||||
export interface JdCollectTaskDetailVo {
|
||||
task?: {
|
||||
id?: number;
|
||||
taskNo?: string;
|
||||
status?: string;
|
||||
errorMessage?: string;
|
||||
updatedAt?: string;
|
||||
};
|
||||
items?: JdCollectHistoryItemVo[];
|
||||
}
|
||||
|
||||
export interface JdCollectTaskBatchVo {
|
||||
items: JdCollectTaskDetailVo[];
|
||||
missingTaskIds: number[];
|
||||
}
|
||||
|
||||
export function fetchJdCollectDashboard() {
|
||||
return unwrapJavaResponse(
|
||||
get<JavaApiResponse<JdCollectDashboardVo>>(
|
||||
buildJavaUrl(API_ENDPOINTS.jdCollect.dashboard),
|
||||
{ params: { user_id: getCurrentUserId() } },
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export function fetchJdCollectHistory() {
|
||||
return unwrapJavaResponse(
|
||||
get<JavaApiResponse<JdCollectHistoryVo>>(
|
||||
buildJavaUrl(API_ENDPOINTS.jdCollect.history),
|
||||
{ params: { user_id: getCurrentUserId(), limit: 50 } },
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
interface JdProgressBatchOptions {
|
||||
force?: boolean;
|
||||
}
|
||||
|
||||
const taskProgressResponseCache = createTaskProgressRequestCache<unknown>({
|
||||
ttlMs: () => getTaskProgressCacheTtlMs(),
|
||||
maxEntries: 100,
|
||||
maxInflight: 16,
|
||||
});
|
||||
|
||||
function normalizeTaskIds(taskIds: number[]) {
|
||||
return Array.from(
|
||||
new Set(
|
||||
(taskIds || [])
|
||||
.map((taskId) => Number(taskId))
|
||||
.filter((taskId) => Number.isFinite(taskId) && taskId > 0),
|
||||
),
|
||||
).sort((left, right) => left - right);
|
||||
}
|
||||
|
||||
function buildTaskProgressRequestKey(path: string, taskIds: number[]) {
|
||||
return `${path}::${taskIds.join(',')}`;
|
||||
}
|
||||
|
||||
/** 批量进度请求缓存(与外观专利/delete-brand 同一形状:TTL 缓存 + 在飞合并 + force 旁路)。 */
|
||||
async function postTaskProgressBatch<T>(
|
||||
path: string,
|
||||
taskIds: number[],
|
||||
options: JdProgressBatchOptions = {},
|
||||
) {
|
||||
const normalizedTaskIds = normalizeTaskIds(taskIds);
|
||||
if (!normalizedTaskIds.length) {
|
||||
return { items: [], missingTaskIds: [] } as T;
|
||||
}
|
||||
|
||||
const cacheKey = buildTaskProgressRequestKey(path, normalizedTaskIds);
|
||||
const cached = taskProgressResponseCache.get(cacheKey);
|
||||
if (!options.force && cached !== undefined) {
|
||||
return cached as T;
|
||||
}
|
||||
|
||||
const inflight = taskProgressResponseCache.getInflight(cacheKey);
|
||||
if (!options.force && inflight) {
|
||||
return (await inflight) as T;
|
||||
}
|
||||
|
||||
const requestPromise = unwrapJavaResponse(
|
||||
post<JavaApiResponse<T>, { taskIds: number[]; userId?: number }>(path, {
|
||||
taskIds: normalizedTaskIds,
|
||||
userId: Number(window.localStorage.getItem('uid')) || undefined,
|
||||
}, {
|
||||
timeout: getTaskProgressTimeoutMs(),
|
||||
}),
|
||||
)
|
||||
.then((data) => {
|
||||
taskProgressResponseCache.set(cacheKey, data);
|
||||
return data;
|
||||
})
|
||||
.finally(() => {
|
||||
taskProgressResponseCache.endInflight(cacheKey);
|
||||
});
|
||||
|
||||
taskProgressResponseCache.startInflight(cacheKey, requestPromise);
|
||||
return await requestPromise;
|
||||
}
|
||||
|
||||
export function fetchJdCollectTaskProgressBatch(
|
||||
taskIds: number[],
|
||||
options: JdProgressBatchOptions = {},
|
||||
) {
|
||||
return postTaskProgressBatch<JdCollectTaskBatchVo>(
|
||||
buildJavaUrl(API_ENDPOINTS.jdCollect.progressBatch),
|
||||
taskIds,
|
||||
options,
|
||||
);
|
||||
}
|
||||
|
||||
/** 删除任务:服务端连带清理京东数据库该任务的商品/图片/SKU 行与断点游标。 */
|
||||
export function deleteJdCollectTask(taskId: number) {
|
||||
return unwrapJavaResponse(
|
||||
del<JavaApiResponse<null>>(
|
||||
buildJavaUrl(API_ENDPOINTS.jdCollect.deleteTask.replace('{taskId}', String(taskId))),
|
||||
{ params: { user_id: getCurrentUserId() } },
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户中断任务:在跑/待跑的任务落 CANCELLED——客户端心跳拿到 notAlive 后协作停止,
|
||||
* 已采集的行保留在京东数据库(断点游标也在),之后可「继续」接着跑。
|
||||
* 终态任务重按是幂等 no-op;普通账号只能中断自己名下的任务。
|
||||
*/
|
||||
export function interruptJdCollectTask(taskId: number) {
|
||||
return unwrapJavaResponse(
|
||||
post<JavaApiResponse<null>>(
|
||||
`${JAVA_API_PREFIX}/tasks/${taskId}/interrupt`,
|
||||
undefined,
|
||||
{ params: { user_id: getCurrentUserId() } },
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -79,7 +79,11 @@ const BASELINE = {
|
||||
// 原文只进 console,并由调用方写进 errorMessage 跳过推队列——错误既有可见出口也没被吞,
|
||||
// silent 一格没涨。**该笔提交当时改的是代码、没同步本基线**(8d8c88a5 树实扫 316 vs 台账
|
||||
// 315 ⇒ 那一提交起本棘轮就是红的),此处按「逐条点名改基线」补记,不整份 --write 回写。
|
||||
blocks: 316,
|
||||
// 317 = 316 + 1(2026-11-15 JdCollectTab 任务面板改版):旧页面的 pollProgress 轮询
|
||||
// catch 随单任务进度条移除(-1),新增 retryTaskRecord / interruptTaskRecord 两支
|
||||
// catch(+2)——重试失败/中断失败都走 ElMessage.error 把服务端文案报给用户,
|
||||
// 原文只进 console;净 +1,silent 一格没涨(两支都不是静默形状)。
|
||||
blocks: 317,
|
||||
// 2026-10-30(ops Phase 6/可读棘轮):ApiSecretSettingsPanel.vue 1113→775 行,面板里那处
|
||||
// 静默 catch(余额查询失败只 console.warn、界面留空)随 loadBalance 整块搬进
|
||||
// useProxyPlan.ts。不是新增静默:面板 1→0、新文件记 1,silent 总数与 blocks 都一格没动,
|
||||
|
||||
@@ -89,6 +89,7 @@ test('test_progress_batch_paths_match_controllers', () => {
|
||||
'/api/query-asin/tasks/progress/batch',
|
||||
'/api/shop-data-crawl/tasks/progress/batch',
|
||||
'/api/withdraw/tasks/progress/batch',
|
||||
'/api/jd-collect/tasks/progress/batch',
|
||||
].sort(),
|
||||
'progress/batch 端点应与 Java controller 路由一一对应',
|
||||
)
|
||||
@@ -315,11 +316,21 @@ test('test_endpoints_frozen_snapshot', () => {
|
||||
// 2026-11-14 v1.4 京东数据库:三支端点(建单/心跳/分片回传)随 Phase 3 落码,
|
||||
// 冻结快照只许显式追加——端点漂移会让"新开一条匿名可达口"没人看见。
|
||||
// 2026-11-14 v1.5:progress(进度条数据源,鉴权与建单同口径:uid 会话身份 + owner 校验)。
|
||||
// 2026-11-15 任务面板改版:dashboard/history/progressBatch(面板三件,鉴权照外观专利
|
||||
// ——dashboard/history/delete 走 resolve,progressBatch 走 filterOwnedTaskIds+require)+
|
||||
// deleteTask(连带清理京东数据库该任务的行与断点游标,铁律 32 数据面)。
|
||||
"jdCollect": {
|
||||
"create": "/api/jd-collect/tasks",
|
||||
// activate 补录(存量漂移):8d8c88a5「补激活这一步」只改了常量表,快照没跟上,
|
||||
// 本次任务面板改版全量跑才暴露(快照测试此前没在全量档里红过)。
|
||||
"activate": "/api/jd-collect/tasks/{taskId}/activate",
|
||||
"progress": "/api/jd-collect/tasks/{taskId}/progress",
|
||||
"heartbeat": "/api/jd-collect/tasks/{taskId}/heartbeat",
|
||||
"chunk": "/api/jd-collect/tasks/{taskId}/chunk"
|
||||
"chunk": "/api/jd-collect/tasks/{taskId}/chunk",
|
||||
"dashboard": "/api/jd-collect/dashboard",
|
||||
"history": "/api/jd-collect/history",
|
||||
"progressBatch": "/api/jd-collect/tasks/progress/batch",
|
||||
"deleteTask": "/api/jd-collect/tasks/{taskId}"
|
||||
},
|
||||
"userSecret": {
|
||||
"bundle": "/api/user-secrets",
|
||||
|
||||
@@ -40,13 +40,18 @@ test('endpoints 注册 jdCollect 端点组', () => {
|
||||
|
||||
/** 2026-11-14 真机实录:建单请求体写成 `user_id` 时后端回一句「user_id 不合法」直接拒,
|
||||
* 管理员点「一键获取店铺数据」永远失败——Java 侧 DTO 是 camelCase `userId`(无 snake 命名
|
||||
* 策略),snake 键会被静默丢掉。进度接口的 `?user_id=` 是 @RequestParam,那个名字不改。 */
|
||||
* 策略),snake 键会被静默丢掉。进度接口的 `?user_id=` 是 @RequestParam,那个名字不改。
|
||||
* 射程只圈 createJdCollectTask 函数段:面板段的 `params: { user_id }` 是 @RequestParam
|
||||
* 形状(deleteJdCollectTask 等与外观专利同形),不是请求体,不该被这条守卫误伤。 */
|
||||
test('建单请求体用 camelCase userId,不是 user_id', () => {
|
||||
const api = readIfExists(
|
||||
join(process.cwd(), 'src', 'shared', 'api', 'types', 'modules', 'jd-collect.ts'),
|
||||
'jd-collect.ts',
|
||||
)
|
||||
const body = api.slice(api.indexOf('createJdCollectTask'))
|
||||
const start = api.indexOf('createJdCollectTask')
|
||||
const end = api.indexOf('export interface JdCollectDashboardVo')
|
||||
assert.ok(start > 0 && end > start, 'jd-collect.ts 缺 createJdCollectTask 或面板段形状变了')
|
||||
const body = api.slice(start, end)
|
||||
assert.ok(/userId:\s*getCurrentUserId\(\)/.test(body),
|
||||
'createJdCollectTask 请求体必须传 camelCase `userId`(传 user_id 会被后端丢掉⇒「user_id 不合法」)')
|
||||
assert.ok(!/[^_a-z]user_id:\s*getCurrentUserId\(\)/.test(body),
|
||||
|
||||
@@ -43,12 +43,14 @@ test('首页京东入口与亚马逊/视频并列', () => {
|
||||
assert.ok(/>京东</.test(home), '首页缺「京东」按钮文字')
|
||||
})
|
||||
|
||||
test('获取店铺数据页是一键触发 + 服务端进度条', () => {
|
||||
test('获取店铺数据页是一键触发 + 服务端进度(任务面板改版后)', () => {
|
||||
const page = read('src/pages/jd/JdCollectTab.vue')
|
||||
assert.ok(page.includes('fetchJdCollectProgress'), '采集页必须轮询服务端进度(不拿本地内存数充进度)')
|
||||
assert.ok(page.includes('progress-track'), '采集页缺进度条轨道')
|
||||
assert.ok(page.includes('jd-progress-indeterminate'),
|
||||
'拿不到 total 时必须走不定态进度条,不得编造百分比')
|
||||
// 进度真源仍是服务端:改版后走批量进度轮询(useLiveTaskBoard),不再有单任务进度条
|
||||
assert.ok(page.includes('fetchJdCollectTaskProgressBatch'),
|
||||
'采集页必须经 useLiveTaskBoard 轮询服务端批量进度(不拿本地内存数充进度)')
|
||||
assert.ok(page.includes('file-progress') || page.includes('progress: showProgress'),
|
||||
'采集页任务卡片必须带进度条(照外观专利面板形状)')
|
||||
assert.ok(page.includes('一键获取店铺数据'), '主按钮应是一键获取')
|
||||
assert.ok(page.includes('jd-shop-collect-run'), '建单后必须推送本机客户端队列')
|
||||
assert.ok(page.includes('TaskCenterPanel'), '改版后右侧必须是共享任务面板(含历史任务层)')
|
||||
})
|
||||
|
||||
@@ -1,12 +1,14 @@
|
||||
/**
|
||||
* 「获取店铺数据」一键采集 + 进度条挂载用例(v1.5)。
|
||||
* 「获取店铺数据」一键采集 + 任务面板挂载用例(v1.5 改版后)。
|
||||
*
|
||||
* 用户口径原话:「获取店铺就是点击获取后就自动抓已打开的京麦后台的店铺数据导入到后台 需要有进度条」。
|
||||
* 四组靶子,缺一条就是假绿:
|
||||
* ① 点一次按钮就走完整链路:建单 → 把 `jd-shop-collect-run` 推进本机客户端队列;
|
||||
* ② 有 total 时进度条按已落库商品数算出真实百分比(分母只来自服务端游标,不编造);
|
||||
* ③ total 缺失时走不定态动画(没有分母就不许编一个假百分比);
|
||||
* ④ 终态即收手:SUCCESS 落 100% + 导入完成文案,FAILED 用服务端原因,两种情况都不再轮询。
|
||||
* 页面改版(2026-11-15):左侧只留「一键获取店铺数据」按钮,右侧换共享任务面板
|
||||
* (TaskCenterPanel + useLiveTaskBoard,与外观专利同一骨架);单任务进度条移除,
|
||||
* 进度在任务卡片上。四组靶子保留,缺一条就是假绿:
|
||||
* ① 点一次按钮就走完整链路:建单 → 激活 → 把 `jd-shop-collect-run` 推进本机客户端队列 → 轮询批量进度;
|
||||
* ② 有 total 时卡片进度条按已落库商品数算出真实百分比(分母只来自服务端游标,不编造);
|
||||
* ③ total 缺失时只显示「已采集 N 个商品」,不编造百分比;
|
||||
* ④ 终态即收手:SUCCESS/FAILED 从轮询移除,FAILED 显示服务端原因并出「重试」按钮
|
||||
* (重试走通用原位复位 + 重新激活推队列——断点续传,不新建任务)。
|
||||
*
|
||||
* 跑法:`npx vitest run tests/mount/jd-collect-progress.mount.test.ts`
|
||||
*/
|
||||
@@ -20,38 +22,81 @@ const api = vi.hoisted(() => ({
|
||||
// 8d8c88a5 起建单后先 PENDING→RUNNING 再推队列;mock 里缺这一个键会让组件拿到
|
||||
// undefined 调用、enqueue 永远不被调用(本文件当时没跟上,红在这里)。
|
||||
activateJdCollectTask: vi.fn(),
|
||||
fetchJdCollectProgress: vi.fn(),
|
||||
fetchJdCollectDashboard: vi.fn(),
|
||||
fetchJdCollectHistory: vi.fn(),
|
||||
fetchJdCollectTaskProgressBatch: vi.fn(),
|
||||
deleteJdCollectTask: vi.fn(),
|
||||
interruptJdCollectTask: vi.fn(),
|
||||
retryClientTask: vi.fn(),
|
||||
enqueue: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/shared/api/types/modules/jd-collect', () => ({
|
||||
createJdCollectTask: api.createJdCollectTask,
|
||||
activateJdCollectTask: api.activateJdCollectTask,
|
||||
fetchJdCollectProgress: api.fetchJdCollectProgress,
|
||||
fetchJdCollectProgress: vi.fn(),
|
||||
fetchJdCollectDashboard: api.fetchJdCollectDashboard,
|
||||
fetchJdCollectHistory: api.fetchJdCollectHistory,
|
||||
fetchJdCollectTaskProgressBatch: api.fetchJdCollectTaskProgressBatch,
|
||||
deleteJdCollectTask: api.deleteJdCollectTask,
|
||||
interruptJdCollectTask: api.interruptJdCollectTask,
|
||||
}))
|
||||
vi.mock('@/shared/api/task-retry', () => ({
|
||||
retryClientTask: api.retryClientTask,
|
||||
}))
|
||||
vi.mock('@/shared/bridges/pywebview', () => ({
|
||||
getPywebviewApi: () => ({ enqueue_json: api.enqueue }),
|
||||
}))
|
||||
|
||||
const POLL_MS = 2000
|
||||
const EMPTY_DASHBOARD = {
|
||||
pendingTaskCount: 0,
|
||||
processedTaskCount: 0,
|
||||
successTaskCount: 0,
|
||||
failedTaskCount: 0,
|
||||
}
|
||||
|
||||
let wrapper: VueWrapper | null = null
|
||||
|
||||
function baseProgress(over: Record<string, unknown> = {}) {
|
||||
function historyItem(over: Record<string, unknown> = {}) {
|
||||
return {
|
||||
taskId: 88,
|
||||
status: 'RUNNING',
|
||||
taskNo: 'JD-1',
|
||||
taskStatus: 'RUNNING',
|
||||
success: false,
|
||||
errorMessage: null,
|
||||
shopName: '花屿巷旗舰店',
|
||||
listTabs: ['ONSALE', 'OFFSALE'],
|
||||
rowCount: 30,
|
||||
itemsReceived: 30,
|
||||
total: 100,
|
||||
page: 2,
|
||||
listTab: 'ONSALE',
|
||||
batches: 1,
|
||||
message: null,
|
||||
createdAt: '2026-11-15T10:00:00',
|
||||
updatedAt: null,
|
||||
finishedAt: null,
|
||||
...over,
|
||||
}
|
||||
}
|
||||
|
||||
function batchOf(item: Record<string, unknown>) {
|
||||
return {
|
||||
items: [
|
||||
{
|
||||
task: {
|
||||
id: item.taskId ?? 88,
|
||||
taskNo: 'JD-1',
|
||||
status: item.taskStatus ?? 'RUNNING',
|
||||
errorMessage: item.errorMessage ?? null,
|
||||
updatedAt: null,
|
||||
},
|
||||
items: [item],
|
||||
},
|
||||
],
|
||||
missingTaskIds: [],
|
||||
}
|
||||
}
|
||||
|
||||
let wrapper: VueWrapper | null = null
|
||||
|
||||
async function mountPage() {
|
||||
wrapper = mount(JdCollectTab, {
|
||||
global: {
|
||||
@@ -74,13 +119,15 @@ async function startCollect(w: VueWrapper) {
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
localStorage.setItem('username', 'admin')
|
||||
api.createJdCollectTask.mockReset()
|
||||
api.fetchJdCollectProgress.mockReset()
|
||||
api.enqueue.mockReset()
|
||||
for (const mock of Object.values(api)) mock.mockReset()
|
||||
api.createJdCollectTask.mockResolvedValue({ taskId: 88, taskNo: 'JD-1', collectChannel: 'LOCAL' })
|
||||
api.activateJdCollectTask.mockResolvedValue({ taskId: 88, status: 'RUNNING' })
|
||||
api.activateJdCollectTask.mockResolvedValue(null)
|
||||
api.enqueue.mockResolvedValue({ success: true })
|
||||
api.fetchJdCollectDashboard.mockResolvedValue(EMPTY_DASHBOARD)
|
||||
api.fetchJdCollectHistory.mockResolvedValue({ items: [] })
|
||||
api.fetchJdCollectTaskProgressBatch.mockResolvedValue(batchOf(historyItem()))
|
||||
vi.spyOn(console, 'error').mockImplementation(() => {})
|
||||
vi.spyOn(console, 'warn').mockImplementation(() => {})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
@@ -91,14 +138,13 @@ afterEach(() => {
|
||||
localStorage.clear()
|
||||
})
|
||||
|
||||
describe('获取店铺数据:一键采集 + 进度条', () => {
|
||||
it('点一次按钮就建单并把采集载荷推进本机客户端队列', async () => {
|
||||
api.fetchJdCollectProgress.mockResolvedValue(baseProgress())
|
||||
describe('获取店铺数据:一键采集 + 任务面板', () => {
|
||||
it('点一次按钮就走完整链路:建单 → 激活 → 推本机队列 → 轮询批量进度', async () => {
|
||||
const w = await mountPage()
|
||||
await startCollect(w)
|
||||
|
||||
expect(api.createJdCollectTask).toHaveBeenCalledTimes(1)
|
||||
// 店铺名留空 → 按「京麦后台」记录(与后端 shop_name 语义一致)
|
||||
// 店铺名留空 → 按「京麦后台」占位(客户端从京麦后台现读真实店铺名落库)
|
||||
expect(api.createJdCollectTask).toHaveBeenCalledWith('京麦后台', ['ONSALE', 'OFFSALE'], 0)
|
||||
expect(api.activateJdCollectTask).toHaveBeenCalledWith(88)
|
||||
expect(api.enqueue).toHaveBeenCalledTimes(1)
|
||||
@@ -110,76 +156,102 @@ describe('获取店铺数据:一键采集 + 进度条', () => {
|
||||
listTabs: ['ONSALE', 'OFFSALE'],
|
||||
maxProducts: 0,
|
||||
})
|
||||
// 轮询已启动:批量进度端点拿到任务 88
|
||||
expect(api.fetchJdCollectTaskProgressBatch).toHaveBeenCalled()
|
||||
const calledIds = api.fetchJdCollectTaskProgressBatch.mock.calls[0][0]
|
||||
expect(calledIds).toContain(88)
|
||||
})
|
||||
|
||||
it('有 total 时按已落库商品数显示真实百分比与进度元信息', async () => {
|
||||
api.fetchJdCollectProgress.mockResolvedValue(baseProgress())
|
||||
it('有 total 时任务卡片显示真实百分比(分母只来自服务端游标)', async () => {
|
||||
const w = await mountPage()
|
||||
await startCollect(w)
|
||||
await flushPromises()
|
||||
|
||||
expect(w.find('.progress-track').exists()).toBe(true)
|
||||
expect(w.find('.progress-percent').text()).toBe('30%')
|
||||
const fill = w.find('.progress-fill')
|
||||
expect(fill.attributes('style')).toContain('width: 30%')
|
||||
expect(fill.classes()).not.toContain('progress-fill--indeterminate')
|
||||
expect(w.find('.progress-meta').text()).toBe('已采集 30 个商品 · 共 100 个 · 第 2 页 · 已回传 1 批')
|
||||
expect(w.find('.progress-status').text()).toBe('正在获取店铺数据…')
|
||||
expect(w.find('.task-item').exists()).toBe(true)
|
||||
expect(w.find('.status').text()).toBe('正在获取店铺数据…')
|
||||
const bar = w.find('.file-progress-bar')
|
||||
expect(bar.exists()).toBe(true)
|
||||
expect(bar.attributes('style')).toContain('width: 30%')
|
||||
expect(w.find('.file-progress-meta').text()).toContain('已采集 30 个商品')
|
||||
})
|
||||
|
||||
it('没有分母(total 缺失)时走不定态动画,不编造百分比', async () => {
|
||||
api.fetchJdCollectProgress.mockResolvedValue(baseProgress({ total: null, page: null, batches: 0 }))
|
||||
const w = await mountPage()
|
||||
await startCollect(w)
|
||||
|
||||
expect(w.find('.progress-percent').exists()).toBe(false)
|
||||
expect(w.find('.progress-fill').classes()).toContain('progress-fill--indeterminate')
|
||||
expect(w.find('.progress-meta').text()).toBe('已采集 30 个商品')
|
||||
})
|
||||
|
||||
it('SUCCESS 终态:进度满格并提示已导入后台,且停止轮询', async () => {
|
||||
api.fetchJdCollectProgress.mockResolvedValue(baseProgress({ itemsReceived: 100 }))
|
||||
const w = await mountPage()
|
||||
await startCollect(w)
|
||||
|
||||
api.fetchJdCollectProgress.mockResolvedValue(
|
||||
baseProgress({ status: 'SUCCESS', itemsReceived: 100 }),
|
||||
it('没有分母(total 缺失)时只显示已采集行数,不编造百分比', async () => {
|
||||
api.fetchJdCollectTaskProgressBatch.mockResolvedValue(
|
||||
batchOf(historyItem({ total: null, page: null, itemsReceived: 30, rowCount: 30 })),
|
||||
)
|
||||
await vi.advanceTimersByTimeAsync(POLL_MS)
|
||||
await flushPromises()
|
||||
|
||||
expect(w.find('.progress-percent').text()).toBe('100%')
|
||||
expect(w.find('.progress-status').text()).toBe('获取完成')
|
||||
expect(w.find('.feedback.success').text()).toContain('已导入后台「京东数据库」')
|
||||
const callsAfterTerminal = api.fetchJdCollectProgress.mock.calls.length
|
||||
await vi.advanceTimersByTimeAsync(POLL_MS * 3)
|
||||
await flushPromises()
|
||||
expect(api.fetchJdCollectProgress.mock.calls.length).toBe(callsAfterTerminal)
|
||||
})
|
||||
|
||||
it('FAILED 终态:用服务端原因说明失败,按钮恢复可点', async () => {
|
||||
api.fetchJdCollectProgress.mockResolvedValue(baseProgress())
|
||||
const w = await mountPage()
|
||||
await startCollect(w)
|
||||
|
||||
api.fetchJdCollectProgress.mockResolvedValue(
|
||||
baseProgress({ status: 'FAILED', message: '京麦后台未登录,请先在客户端登录京麦' }),
|
||||
)
|
||||
await vi.advanceTimersByTimeAsync(POLL_MS)
|
||||
await flushPromises()
|
||||
|
||||
expect(w.find('.progress-status').text()).toBe('获取失败')
|
||||
expect(w.find('.feedback.error').text()).toContain('京麦后台未登录')
|
||||
expect(w.find('.collect-btn').attributes('disabled')).toBeUndefined()
|
||||
const meta = w.find('.file-progress-meta')
|
||||
expect(meta.exists()).toBe(true)
|
||||
expect(meta.text()).toContain('已采集 30 个商品')
|
||||
expect(meta.text()).not.toContain('%')
|
||||
expect(w.find('.file-progress-bar').attributes('style')).toContain('width: 0%')
|
||||
})
|
||||
|
||||
it('建单失败:只报错不留假进度条,一次进度请求也不发', async () => {
|
||||
it('SUCCESS 终态:状态徽章落「获取完成」、进度满格,且从轮询中收手', async () => {
|
||||
const w = await mountPage()
|
||||
await startCollect(w)
|
||||
await flushPromises()
|
||||
|
||||
api.fetchJdCollectTaskProgressBatch.mockResolvedValue(
|
||||
batchOf(historyItem({ taskStatus: 'SUCCESS', success: true, itemsReceived: 100, rowCount: 100 })),
|
||||
)
|
||||
await vi.advanceTimersByTimeAsync(60_000)
|
||||
await flushPromises()
|
||||
|
||||
expect(w.find('.status').text()).toBe('获取完成')
|
||||
// 终态任务没有进度条(isActiveTask 才有),行数行收口在卡片 extraLines
|
||||
expect(w.find('.file-progress-bar').exists()).toBe(false)
|
||||
expect(w.find('.task-item').text()).toContain('已采集 100 个商品')
|
||||
// 终态即收手:再推进几轮轮询间隔,批量进度不再被调
|
||||
const callsAfterTerminal = api.fetchJdCollectTaskProgressBatch.mock.calls.length
|
||||
await vi.advanceTimersByTimeAsync(60_000)
|
||||
await flushPromises()
|
||||
expect(api.fetchJdCollectTaskProgressBatch.mock.calls.length).toBe(callsAfterTerminal)
|
||||
})
|
||||
|
||||
it('FAILED 终态:显示服务端原因、出「重试」按钮,重试走原位复位并重新激活推队列', async () => {
|
||||
const w = await mountPage()
|
||||
await startCollect(w)
|
||||
await flushPromises()
|
||||
|
||||
api.fetchJdCollectTaskProgressBatch.mockResolvedValue(
|
||||
batchOf(historyItem({
|
||||
taskStatus: 'FAILED',
|
||||
success: false,
|
||||
errorMessage: '京麦后台未登录,请先在客户端登录京麦',
|
||||
itemsReceived: 30,
|
||||
})),
|
||||
)
|
||||
await vi.advanceTimersByTimeAsync(60_000)
|
||||
await flushPromises()
|
||||
|
||||
expect(w.find('.status').text()).toBe('获取失败')
|
||||
expect(w.find('.task-item').text()).toContain('京麦后台未登录')
|
||||
const retryBtn = w.find('.btn-retry')
|
||||
expect(retryBtn.exists()).toBe(true)
|
||||
expect(retryBtn.text()).toBe('重试')
|
||||
|
||||
await retryBtn.trigger('click')
|
||||
await flushPromises()
|
||||
// 铁律 26:原任务复位(不克隆新任务),复位后重新激活并推队列(断点续传)
|
||||
expect(api.retryClientTask).toHaveBeenCalledWith(88)
|
||||
expect(api.activateJdCollectTask).toHaveBeenCalledWith(88)
|
||||
expect(api.enqueue).toHaveBeenCalled()
|
||||
const pushPayload = api.enqueue.mock.calls.at(-1)?.[0]
|
||||
expect(pushPayload?.type).toBe('jd-shop-collect-run')
|
||||
expect(pushPayload?.data?.taskId).toBe(88)
|
||||
})
|
||||
|
||||
it('建单失败:只报错不留假任务,一次批量进度请求也不发', async () => {
|
||||
api.createJdCollectTask.mockRejectedValue(new Error('缺少登录凭据'))
|
||||
const w = await mountPage()
|
||||
await startCollect(w)
|
||||
|
||||
expect(w.find('.feedback.error').text()).toContain('缺少登录凭据')
|
||||
expect(w.find('.progress-track').exists()).toBe(false)
|
||||
expect(api.fetchJdCollectProgress).not.toHaveBeenCalled()
|
||||
expect(api.fetchJdCollectTaskProgressBatch).not.toHaveBeenCalled()
|
||||
expect(api.enqueue).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
@@ -191,8 +263,6 @@ describe('获取店铺数据:一键采集 + 进度条', () => {
|
||||
expect(api.activateJdCollectTask).toHaveBeenCalledWith(88)
|
||||
expect(api.enqueue).not.toHaveBeenCalled()
|
||||
expect(w.find('.feedback.error').text()).toContain('任务激活失败')
|
||||
// 建单不回滚、进度照轮询:任务留在 PENDING,由服务端兜底拉取认领后照样会跑。
|
||||
expect(api.fetchJdCollectProgress).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it('激活时服务端回「已在执行中」:等同激活成功,照常推队列', async () => {
|
||||
|
||||
@@ -45,6 +45,7 @@ const NARROW_LEDGER: Record<string, number> = {
|
||||
'src/pages/brand/components/BrandPriceTrackTab.vue': 6,
|
||||
'src/pages/brand/components/BrandProductRiskTab.vue': 2,
|
||||
'src/pages/brand/components/BrandSimilarAsinTab.vue': 1,
|
||||
'src/pages/jd/JdCollectTab.vue': 1,
|
||||
'src/shared/composables/useLiveTaskBoard.ts': 2,
|
||||
}
|
||||
const NARROW_BASELINE_TOTAL = Object.values(NARROW_LEDGER).reduce((a, b) => a + b, 0)
|
||||
|
||||
Reference in New Issue
Block a user