Files
crawler-plugin/frontend-vue/src/pages/jd/JdCollectTab.vue
T

670 lines
22 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.
<script setup lang="ts">
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,
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 { 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.4 已落地的采集契约与外观专利任务面板骨架,不另造流程):
* 1. 建单走后端 `/api/jd-collect/tasks`(通道恒 LOCAL,服务端落 PENDING);
* 2. 建单成功把 `jd-shop-collect-run` 载荷推进本机客户端队列——只建单不推送会让任务
* 卡在 PENDING 等兜底拉取(v1.4 Phase 6.1 P0-1 的教训);推送失败不回滚建单;
* 3. 进度只读服务端:任务状态 + 合并写游标里的 itemsReceived/total。`total` 缺失时
* 卡片只显示已采集行数,不编造百分比;
* 4. 失败/中断任务「重试/继续」走通用原位复位(铁律 26,保留已收分片与断点游标),
* 复位后页面重新激活并推队列——同一份输入不再多出好几行结果。
*/
/** 页面不再让用户填店铺名:店铺名称由客户端从京麦后台读,建单先按此占位记录。 */
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 errorMessage = ref('')
const successMessage = ref('')
function uidForStorage() {
return typeof window !== 'undefined' ? window.localStorage.getItem('uid') || '0' : '0'
}
// ---- 实时任务面板(与外观专利共用 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: progressCountLabel(item) } : null,
source: item,
}
}
// ---- 本模块的状态语义(京东采集:无结果文件,状态即终态)----
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)))
}
/** 计数文案:有 total 带分母和百分比「已采集 30/100 个商品(30%)」——TaskItemCard 的
* countLabel 会顶掉「总进度 X%」那行字,百分比只能随 countLabel 一起出;
* 没有 total 保持只报行数,不编造分母(与本页 progressPercent 同一口径)。 */
function progressCountLabel(item: JdCollectHistoryItemVo) {
const received = item.itemsReceived ?? item.rowCount ?? 0
const total = typeof item.total === 'number' && item.total > 0 ? item.total : null
if (!total) return `已采集 ${received} 个商品`
return `已采集 ${received}/${total} 个商品(${progressPercent(item)}%)`
}
/** 失败/已中断的任务能续跑:在原任务上复位(不新建任务),成功/进行中的任务不该出现这个按钮。 */
function canRetryTask(item: JdCollectHistoryItemVo | null | undefined): boolean {
if (!item?.taskId) return false
const status = normalizeTaskStatus(item)
return status === 'FAILED' || status === 'CANCELLED'
}
/** 按钮文案:已中断的任务显示「继续」(从断点接着跑),失败任务仍是「重试」。 */
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 {
await interruptJdCollectTask(taskId)
ElMessage.success('已中断:客户端下一跳心跳后收手,之后可点「继续」接着跑')
await refreshBoard()
} catch (error) {
ElMessage.error(error instanceof Error ? error.message : '中断失败')
}
}
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 : '重试失败')
}
}
/** 手动刷新:强拉历史 + 统计 + 当前轮询任务进度(轮询意外中断后的自救出口) */
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 要求客户端收手,采集白跑一轮。
*/
async function activateTask(id: number): Promise<string | null> {
try {
await activateJdCollectTask(id)
return null
} catch (err) {
const text = err instanceof Error ? err.message : ''
// 客户端兜底拉取已原子认领(PENDING→RUNNING)时后端回这句:等同激活成功,不当失败展示。
if (text.includes('已在执行中')) {
return null
}
console.error('[jd-collect] 激活任务失败', err)
return '任务激活失败,本机客户端领不到这一单,请稍后重试'
}
}
/** 建单成功后推送本机队列;返回 null 表示环境无队列能力(浏览器预览),返回 string 表示失败原因。 */
async function pushToClientQueue(
id: number,
shop: string,
tabs: JdListTab[],
): Promise<string | null> {
const api = getPywebviewApi()
if (!api?.enqueue_json) {
return '当前环境未启用任务队列能力(浏览器预览环境不会启动),请在本机客户端中打开本页'
}
const payload = {
type: 'jd-shop-collect-run',
ts: Date.now(),
data: { taskId: id, shopName: shop, listTabs: tabs, maxProducts: 0 },
}
const pushResult = await api.enqueue_json(payload)
if (pushResult?.success) {
return null
}
// 桥返回的 error 原文(系统/英文)不透传进界面:console 留链,界面固定中文动作句
if (pushResult?.error) {
console.error('[jd-collect] enqueue_json 被拒', pushResult.error)
}
return '推送本机队列失败,任务将由客户端兜底拉取认领'
}
const isRunning = computed(() => Boolean(board.dashboard.value.pendingTaskCount) || submitting.value)
async function startCollect() {
if (submitting.value) return
errorMessage.value = ''
successMessage.value = ''
submitting.value = true
const shop = DEFAULT_SHOP_NAME
const tabs = DEFAULT_TABS
try {
const vo = await createJdCollectTask(shop, tabs, 0)
board.addPollingTask(vo.taskId)
let pushNote = ''
const activateError = await activateTask(vo.taskId)
if (activateError) {
// 没激活成功就不推队列:推了也是白跑一轮(分片全被拒)。任务留在 PENDING,
// 由服务端兜底拉取认领后照样会跑,所以这里只提示、不回滚建单。
pushNote = activateError
} else {
try {
const pushError = await pushToClientQueue(vo.taskId, shop, tabs)
if (pushError) pushNote = pushError
} catch (pushErr) {
// 推送自身异常不回滚建单:任务可由服务端兜底拉取认领。
pushNote = '推送本机队列失败,任务将由服务端兜底派发给本机客户端执行'
console.error('[jd-collect] 推送本机队列失败', pushErr)
}
}
if (pushNote) {
errorMessage.value = pushNote
} else {
successMessage.value = '任务已创建并推送给本机客户端,进度显示在右侧任务区'
}
await Promise.all([board.loadDashboard(), board.loadHistory({ force: true })])
} catch (err) {
errorMessage.value = err instanceof Error ? err.message : '建单失败,请稍后重试'
} finally {
submitting.value = false
}
}
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()
})
onUnmounted(() => {
board.dispose()
})
</script>
<template>
<div class="page-shell module-page jd-collect-page">
<header class="jd-top">
<router-link class="home-back" :to="homeHref" title="返回首页">← 返回首页</router-link>
<div class="brand">
<span class="brand-logo">富</span>
<span class="brand-text">
<span class="brand-name">数富AI</span>
<span class="brand-sub">京东运营工具台</span>
</span>
</div>
<div class="top-right">
<NotificationBell />
<span class="admin-name">{{ username }}</span>
</div>
</header>
<div class="tool-head">
<router-link class="tool-head__back" :to="backHref">← 返回京东工具台</router-link>
<span class="tool-head__title">获取店铺数据</span>
<span class="tool-head__desc">
一键抓取已登录京麦后台的店铺商品(列表 + 详情全部属性 + 图片),导入后台「京东数据库」。
</span>
</div>
<main class="jd-body">
<aside class="left-panel">
<button class="collect-btn" type="button" :disabled="isRunning" @click="startCollect">
{{ isRunning ? '获取中…' : '一键获取店铺数据' }}
</button>
<p class="collect-hint">
点击后本机客户端会自动打开已登录的京麦后台采集商品,请保持客户端在线且京麦已登录;
采集到的数据会实时回传并导入后台「京东数据库」。进度显示在右侧任务区。
</p>
<p v-if="successMessage" class="feedback success">{{ successMessage }}</p>
<p v-if="errorMessage" class="feedback error">{{ errorMessage }}</p>
</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>
<style scoped>
.jd-collect-page {
display: flex;
flex-direction: column;
min-height: 100vh;
background-color: #1a1f2e;
background-image: radial-gradient(rgba(45, 212, 191, 0.08) 1px, transparent 1px);
background-size: 48px 48px;
font-family: "PingFang SC", "Microsoft YaHei UI", "Microsoft YaHei", "微软雅黑", sans-serif;
}
.jd-top {
flex: 0 0 auto;
min-height: 64px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
padding: 0 28px;
background: #1a1f2e;
border-bottom: 1px solid #3e4a62;
}
.home-back {
flex-shrink: 0;
display: inline-flex;
align-items: center;
gap: 6px;
padding: 6px 14px;
border: 1px solid #3e4a62;
border-radius: 6px;
color: #c8d2e2;
font-size: 13px;
text-decoration: none;
white-space: nowrap;
transition: all 0.2s;
}
.home-back:hover {
background: #2b3447;
color: #f5f8fc;
}
.brand {
display: flex;
align-items: center;
gap: 12px;
flex-shrink: 0;
}
.brand-logo {
display: flex;
align-items: center;
justify-content: center;
width: 38px;
height: 38px;
border-radius: 8px;
background: #e1251b;
color: #fff;
font-size: 20px;
font-weight: 700;
box-shadow: 0 2px 8px rgba(225, 37, 27, 0.32);
}
.brand-text {
display: flex;
flex-direction: column;
line-height: 1.35;
}
.brand-name {
color: #f5f8fc;
font-size: 17px;
font-weight: 700;
white-space: nowrap;
}
.brand-sub {
color: #a0acbe;
font-size: 10px;
white-space: nowrap;
}
.top-right {
display: flex;
align-items: center;
gap: 14px;
flex-shrink: 0;
}
.admin-name {
color: #c8d2e2;
font-size: 13px;
font-weight: 700;
white-space: nowrap;
}
.tool-head {
flex: 0 0 auto;
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 20px;
min-height: 62px;
padding: 10px 34px;
background: #1a1f2e;
}
.tool-head__back {
flex-shrink: 0;
display: inline-flex;
align-items: center;
gap: 6px;
padding: 6px 14px;
border: 1px solid #3e4a62;
border-radius: 6px;
color: #c8d2e2;
font-size: 13px;
text-decoration: none;
white-space: nowrap;
transition: all 0.2s;
}
.tool-head__back:hover {
background: #2b3447;
color: #f5f8fc;
}
.tool-head__title {
flex-shrink: 0;
color: #f5f8fc;
font-size: 22px;
font-weight: 700;
white-space: nowrap;
}
.tool-head__desc {
min-width: 0;
max-width: 760px;
color: #a0acbe;
font-size: 14px;
line-height: 1.5;
}
/* ===== 左按钮 + 右任务面板(照外观专利 Tab 布局)===== */
.jd-body {
flex: 1 1 auto;
min-height: 0;
display: flex;
align-items: stretch;
overflow: hidden;
}
.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 {
width: 100%;
padding: 13px 0;
border: none;
border-radius: 8px;
background: linear-gradient(135deg, #ff5a4f, #e1251b);
color: #ffffff;
font-size: 16px;
font-weight: 700;
font-family: inherit;
cursor: pointer;
box-shadow: 0 4px 16px rgba(225, 37, 27, 0.32);
transition: all 0.2s;
}
.collect-btn:hover:not(:disabled) {
filter: brightness(1.1);
transform: translateY(-1px);
}
.collect-btn:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.collect-hint {
margin: 12px 0 0;
color: #a0acbe;
font-size: 12px;
line-height: 1.7;
}
.feedback {
margin: 16px 0 0;
padding: 10px 12px;
border-radius: 8px;
font-size: 13px;
line-height: 1.6;
}
.feedback.success {
background: rgba(16, 185, 129, 0.12);
color: #6ee7b7;
}
.feedback.error {
background: rgba(248, 113, 113, 0.12);
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;
gap: 10px;
}
.jd-body {
flex-direction: column;
overflow-y: auto;
}
.left-panel {
width: 100%;
border-right: none;
border-bottom: 1px solid #3e4a62;
}
.right-panel {
padding: 16px;
}
}
</style>