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

1092 lines
43 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 { loadCategoryCache, saveCategoryCache } from './jd-category-cache'
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);可选多选采集
* 分类(京麦「店内分类」,`shopCategoryNames`/`shopCategoryIds` 双键)——空=全店
* 采集,选中值随建单进 request_json、随推送/兜底拉取进客户端,客户端按行
* shopCategorys/shopCategoryPath/groupId 等值过滤、任一键命中即命中(三处同键契约;
* 2026-11-16 类目级联按客户口径「类目不需要只要分类」下线,categoryPaths 仅历史行兼容);
* 2. 建单成功把 `jd-shop-collect-run` 载荷推进本机客户端队列——只建单不推送会让任务
* 卡在 PENDING 等兜底拉取(v1.4 Phase 6.1 P0-1 的教训);推送失败不回滚建单;
* 3. 进度只读服务端:任务状态 + 合并写游标里的 itemsReceived/total。`total` 缺失时
* 卡片只显示已采集行数,不编造百分比;
* 4. 失败/中断任务「重试/继续」走通用原位复位(铁律 26,保留已收分片与断点游标),
* 复位后页面重新激活并推队列——同一份输入不再多出好几行结果。
*
* 2026-11-19 客户口径「每一家店铺的分类都会不一样」:选项集正本从冻结快照
* (2026-11-16 对花屿巷一家店的抓包,对第二家店必错)改为**按店实时拉取**——
* 「同步分类」按钮 → 桥 `get_jd_shop_categories` → 客户端用本机已登录京麦的
* profile 现拉 getShopCategoryList(执行体 amazon/jd/shop_categories.py)。
* 店内分类是商家在京麦后台自维护的,选项集永远等于「本机已登录那家店」的现值;
* 老客户端没有该桥方法 ⇒ 按钮置灰并提示升级。
*
* 2026-11-20 客户口径「加个状态勾选,采集售卖中或已下架的,多选」:采集状态从写死的
* DEFAULT_TABS 改为页面勾选(默认两项都勾=与旧行为一致),选中值成为建单 listTabs 与
* 推送载荷的同一真源;空选不建单(服务端 JdCollectTaskService 同样要求至少一个 Tab)。
* DEFAULT_TABS 只保留给历史行缺 listTabs 时的重试/继续兜底。
*/
/** 页面不再让用户填店铺名:店铺名称由客户端从京麦后台读,建单先按此占位记录。 */
const DEFAULT_SHOP_NAME = '京麦后台'
/** 兜底词表:历史行没带 listTabs 时,重试/继续重建推送载荷按两项都采处理。 */
const DEFAULT_TABS: JdListTab[] = ['ONSALE', 'OFFSALE']
/** 采集状态多选(2026-11-20 客户口径「加个状态勾选,采集售卖中或已下架的,多选」):
* 默认两项都勾=与旧行为一致;只勾一项就只采那一档;空选不允许建单(服务端同样要求
* 至少一个 Tab)。词表与京麦列表页签同源:ONSALE 售卖中 / OFFSALE 已下架。 */
const TAB_OPTIONS: ReadonlyArray<{ value: JdListTab; label: string }> = [
{ value: 'ONSALE', label: '售卖中' },
{ value: 'OFFSALE', label: '已下架' },
]
const selectedTabs = ref<JdListTab[]>([...DEFAULT_TABS])
const noTabSelected = computed(() => selectedTabs.value.length === 0)
const selectedTabLabels = computed(() =>
TAB_OPTIONS.filter((option) => selectedTabs.value.includes(option.value)).map((option) => option.label),
)
const tabHint = computed(() => (
selectedTabLabels.value.length
? `本次采集「${selectedTabLabels.value.join('、')}」的商品。`
: '至少勾选一个采集状态才能开始采集。'
))
/** 勾选/取消一个状态:默认两项都选是旧行为,用户可只留一项(例如店里只剩已下架商品)。 */
function toggleTab(tab: JdListTab) {
selectedTabs.value = selectedTabs.value.includes(tab)
? selectedTabs.value.filter((item) => item !== tab)
: [...selectedTabs.value, tab]
}
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('')
/** 推送失败等「设计内慢路径」提示:amber 展示,不占红色 error(2026-11-19 用户反馈红条吓人)。 */
const noticeMessage = ref('')
// ---- 采集分类(可选,下拉多选;空=全店采集)----
/** 京麦「店内分类」项:label=分类名(行级等值词),value=分类 id。形状与旧快照同形。 */
interface ShopCategoryOption {
label: string
value: string
}
/** 选项集=「同步分类」从本机已登录京麦店铺现拉的实时结果(2026-11-19 起;
* 旧冻结快照已退役——每家店的店内分类名字与 id 都不同,写死必错)。 */
const shopCategoryOptions = ref<ShopCategoryOption[]>([])
const selectedShopCategoryValues = ref<string[]>([])
/** 同步中/可用态:可用性按桥上有没有 get_jd_shop_categories 方法判(老客户端置灰)。 */
const syncingCategories = ref(false)
const canSyncCategories = ref(false)
/** 「登录京麦」(2026-11-20):起采集专用浏览器等人工登录;可用态同口径按桥判。 */
const loggingIn = ref(false)
const canLoginJd = ref(false)
/** 最近一次同步到的店铺名(空=尚未同步或京麦页面没返回店铺名)。 */
const syncedShopName = ref('')
/** 本页选项集来自上次缓存的时间(空=本次没回填缓存;只作提示,不参与建单)。 */
const cachedFetchedAt = ref('')
/** localStorage 访问包一层:隐私模式/配额异常时退回「不缓存」,不影响建单。 */
function localStore(): Storage | null {
try {
return window.localStorage
} catch {
return null
}
}
/** 挂载即回填上次成功同步的选项集(2026-11-19 客户口径「同步后就记住呀 别每次都同步」)。
* 只回填**选项集**,不回填选中值——选中值是「这一单采哪些分类」,跨次沿用它等于
* 静默改采集范围;要刷新就点「同步分类」,现拉会覆盖缓存。 */
function restoreCategoryCache() {
const cache = loadCategoryCache(localStore())
if (!cache) return
shopCategoryOptions.value = cache.categories
syncedShopName.value = cache.shopName
cachedFetchedAt.value = cache.fetchedAt
}
/** 无桥(浏览器打开)或老客户端(桥没有该方法)时点同步的提示。 */
const SYNC_UNAVAILABLE_NOTE =
'当前在浏览器中打开或客户端版本较旧,无法同步店内分类。请在本机客户端中打开本页;仍不可用请把客户端升级到最新版'
/** 同上口径的「登录京麦」不可用提示(2026-11-20)。 */
const LOGIN_UNAVAILABLE_NOTE =
'当前在浏览器中打开或客户端版本较旧,无法打开京麦登录窗口。请在本机客户端中打开本页;仍不可用请把客户端升级到最新版'
function refreshSyncAvailability() {
const api = getPywebviewApi()
canSyncCategories.value = typeof api?.get_jd_shop_categories === 'function'
canLoginJd.value = typeof api?.open_jd_login === 'function'
}
/** 分类块底部说明:同步状态 + 选中口径 + 「先挂分类才有命中」的边界,一行讲完。 */
const categoryHint = computed(() => {
const parts: string[] = []
if (syncedShopName.value) {
const suffix = cachedFetchedAt.value
? `(${formatDateTime(cachedFetchedAt.value)} 同步,点「同步分类」可刷新)`
: ''
parts.push(`已同步店铺「${syncedShopName.value}」:${shopCategoryOptions.value.length} 个分类${suffix}`)
} else {
parts.push('分类来自本机客户端已登录的京麦店铺,点「同步分类」拉取;未同步或空选=全店采集')
}
if (selectedShopCategoryValues.value.length) {
parts.push(`只采选中 ${selectedShopCategoryValues.value.length} 个分类的商品`)
}
parts.push('商品要先在京麦挂上分类才会被选中')
return `${parts.join(';')}。`
})
/** 点「同步分类」:桥 → 客户端现拉 getShopCategoryList。成功刷新选项集并清理
* 不属于当前店铺的已选 id(id 是店铺自有,跨店必错);失败按 code 分档——
* jd_busy(京东任务在跑)走 amber notice,jd_login/jd_page/未知走红色 error。 */
async function syncShopCategories() {
if (syncingCategories.value) return
errorMessage.value = ''
noticeMessage.value = ''
const api = getPywebviewApi()
const bridge = api?.get_jd_shop_categories
if (typeof bridge !== 'function') {
errorMessage.value = SYNC_UNAVAILABLE_NOTE
return
}
syncingCategories.value = true
try {
const result = await bridge()
if (result?.success && Array.isArray(result.categories)) {
const options = result.categories.filter((item) => item && item.label && item.value)
const optionIds = new Set(options.map((item) => item.value))
const staleCount =
selectedShopCategoryValues.value.filter((value) => !optionIds.has(value)).length
selectedShopCategoryValues.value =
selectedShopCategoryValues.value.filter((value) => optionIds.has(value))
shopCategoryOptions.value = options
syncedShopName.value = result.shopName || ''
cachedFetchedAt.value = ''
saveCategoryCache(localStore(), {
shopName: syncedShopName.value,
shopId: String(result.shopId || ''),
categories: options,
fetchedAt: new Date().toISOString(),
})
if (staleCount > 0) {
noticeMessage.value = `已按当前店铺刷新分类,清除了 ${staleCount} 个不属于当前店铺的已选项`
}
} else if (result?.code === 'jd_busy') {
noticeMessage.value = result.error || '京东任务正在运行,请等任务结束后再同步分类'
} else if (result?.code === 'jd_login') {
errorMessage.value = result.error || '京麦未登录(登录态失效)'
if (canLoginJd.value) {
noticeMessage.value = '点上方「登录京麦」按钮打开登录窗口,登录完成后重新点「同步分类」'
}
} else {
errorMessage.value = result?.error || '同步分类未返回结果,请稍后重试'
}
} catch (error) {
errorMessage.value = error instanceof Error ? `同步分类失败:${error.message}` : '同步分类失败,请稍后重试'
} finally {
syncingCategories.value = false
}
}
function clearShopCategories() {
selectedShopCategoryValues.value = []
}
/** 点「登录京麦」(2026-11-20 装机实录后的独立登录入口):桥 → 客户端起采集专用
* 浏览器停在京麦登录页等人工登录,登录成功即关窗、登录态常驻本机 profile。
* 分档口径:busy/重入/超时/用户关窗都是「设计内等待或可恢复」走 amber notice
* (超时档客户端**不关窗口**,用户可继续登),只有 jd_page/未知才是红色 error。 */
async function openJdLogin() {
if (loggingIn.value) return
errorMessage.value = ''
noticeMessage.value = ''
successMessage.value = ''
const api = getPywebviewApi()
const bridge = api?.open_jd_login
if (typeof bridge !== 'function') {
errorMessage.value = LOGIN_UNAVAILABLE_NOTE
return
}
loggingIn.value = true
try {
const result = await bridge()
if (result?.success) {
successMessage.value = result.message || '京麦登录完成,可重跑采集或点「同步分类」'
} else if (result?.code === 'jd_busy' || result?.code === 'jd_login_running'
|| result?.code === 'timeout' || result?.code === 'window_closed') {
noticeMessage.value = result.error || '京麦登录未完成,请按提示重试'
} else {
errorMessage.value = result?.error || '打开登录窗口失败,请稍后重试'
}
} catch (error) {
errorMessage.value = error instanceof Error ? `登录京麦失败:${error.message}` : '登录京麦失败,请稍后重试'
} finally {
loggingIn.value = false
}
}
/** 选中项按选项集原序反查回对象(下拉里点选的先后不进请求体——双键顺序恒等于同步序)。 */
const selectedShopCategories = computed(() =>
shopCategoryOptions.value.filter((item) => selectedShopCategoryValues.value.includes(item.value)),
)
/** 建单/推送载荷的选中值:label 与 id 双键同发(行级填充形状未取证,任一键命中即命中)。 */
const selectedShopCategoryNames = computed(() => selectedShopCategories.value.map((item) => item.label))
const selectedShopCategoryIds = computed(() => selectedShopCategories.value.map((item) => item.value))
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: async (taskId) => {
// 先叫停本机这一单的独立 worker,再让服务端物理删除:任务行一删,子进程只能等
// 下一批分片/60 秒心跳才发现「任务不存在」,期间仍占着京麦浏览器锁(登录/下一单被挡)。
await stopLocalJdWorker(taskId)
return deleteJdCollectTask(taskId)
},
deleteHistory: async () => undefined,
onTaskDeleted: (item) => board.removePollingTask(item.taskId as number),
},
})
/** 删除前停止本机 worker(尽力而为):桥不可用/旧包都不得阻断删除,删除后 worker 下一批
* 分片或心跳仍会按「任务不存在」自行收手。stop_task 自 4.0.12 起就在 expose 名单里。 */
async function stopLocalJdWorker(taskId: number) {
try {
await getPywebviewApi()?.stop_task?.(taskId)
} catch (error) {
// 尽力而为档:异常原文留控制台;服务端「任务不存在」兜底对用户可见,不吞删除失败。
const detail = error instanceof Error ? error.message : String(error)
console.warn('[jd-collect] 停止本机 worker 失败:%s,回退服务端「任务不存在」兜底', detail)
}
}
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
}
/** 历史行 Tab 词 → 界面词;旧行没有 listTabs 时整行不显示,不拿兜底两项冒充事实。 */
function tabLabel(tab: string) {
return TAB_OPTIONS.find((option) => option.value === tab)?.label ?? tab
}
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.listTabs?.length ? [`采集状态:${item.listTabs.map(tabLabel).join('、')}`] : []),
...(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'
}
/** 已采计数口径:``rowCount`` 是「已落京东数据库」的真值,``itemsReceived`` 只是服务端
* 已收下的分片行数——分片被拒/回传失败时后者低估(34959 实录:8 行已落库、分片回传
* 500 ⇒ itemsReceived=0,卡片 extraLines 显示「已采集 8 个商品」而进度行显示 0,
* 同屏自相矛盾)。进度取两者大者。 */
function collectedCount(item: JdCollectHistoryItemVo) {
return Math.max(item.itemsReceived ?? 0, item.rowCount ?? 0)
}
/** 百分比:有 total 按已落库商品数算(封顶 99 直到服务端落 SUCCESS);没有 total 不编造分母。
* 分母来自服务端游标 cursor.total——客户端在页面级店内分类筛选生效时会写真分母
* (2026-11-19 起),行级过滤兜底时仍记 0 ⇒ 走无分母口径只报行数。 */
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(collectedCount(item), total)
return Math.max(0, Math.min(99, Math.round((done * 100) / total)))
}
/** 计数文案:有 total 带分母和百分比「已采集 30/100 个商品(30%)」——TaskItemCard 的
* countLabel 会顶掉「总进度 X%」那行字,百分比只能随 countLabel 一起出;
* 没有 total 保持只报行数,不编造分母(与本页 progressPercent 同一口径)。
* 2026-11-21 35089 实录补进行时档:首批分片被服务端收下前 itemsReceived 恒 0(页内
* 详情采集要 1-3 分钟)、「已采集 0 个商品」像卡死,用户误以为失败点了删除(35088/
* 35089/35090 三单都被这样删掉,数据采集成功但随删除清库)。0 行时改报进行时文案。 */
function progressCountLabel(item: JdCollectHistoryItemVo) {
const received = collectedCount(item)
const total = typeof item.total === 'number' && item.total > 0 ? item.total : null
if (!received && normalizeTaskStatus(item) !== 'SUCCESS') {
return total ? `已采 0/${total} 个商品(正在采集中…)` : '正在采集,首批数据确认后开始计数…'
}
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[],
item?.shopCategoryNames ?? [], item?.shopCategoryIds ?? [])
}
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 '任务激活失败,本机客户端领不到这一单,请稍后重试'
}
}
/** 推送失败 ≠ 建单失败:任务已在服务端落库,客户端兜底拉取线程(60 秒一轮)会自动认领。
* 2026-11-19 用户反馈红色「推送失败」横幅吓人(实为设计内慢路径,最多晚约 1 分钟)——
* 文案改中性动作句,展示走 amber notice 通道,红色 error 只留给真失败(建单/激活失败)。 */
const PUSH_FALLBACK_NOTE =
'任务已创建,但未能即时推送到本机队列。请保持本机客户端在线,客户端会在约 1 分钟内自动领取并执行'
/** 建单成功后推送本机队列;返回 null 表示已推送成功,返回 string 表示要展示的提示文案
* (含浏览器无桥环境——任务仍会由在线客户端兜底认领,不是失败)。
* shopCategoryNames/Ids 是建单时选的京麦店内分类(重试/继续从历史行同源带回)——推送载荷
* 与建单请求体、客户端兜底拉取(request_json)三处同键,缺一处客户端就按全店采集跑。 */
async function pushToClientQueue(
id: number,
shop: string,
tabs: JdListTab[],
shopCategoryNames: string[] = [],
shopCategoryIds: string[] = [],
): 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, shopCategoryNames, shopCategoryIds },
}
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 PUSH_FALLBACK_NOTE
}
const isRunning = computed(() => Boolean(board.dashboard.value.pendingTaskCount) || submitting.value)
async function startCollect() {
if (submitting.value) return
errorMessage.value = ''
successMessage.value = ''
noticeMessage.value = ''
// 只认勾选的状态、按固定顺序(ONSALE→OFFSALE)下发:用户点选的先后不影响请求体。
const tabs = TAB_OPTIONS
.map((option) => option.value)
.filter((tab) => selectedTabs.value.includes(tab))
if (!tabs.length) {
errorMessage.value = '请至少勾选一个采集状态(售卖中 / 已下架)'
return
}
submitting.value = true
const shop = DEFAULT_SHOP_NAME
const shopNames = [...selectedShopCategoryNames.value]
const shopIds = [...selectedShopCategoryIds.value]
try {
const vo = await createJdCollectTask(shop, tabs, 0, [], shopNames, shopIds)
board.addPollingTask(vo.taskId)
const activateError = await activateTask(vo.taskId)
if (activateError) {
// 没激活成功就不推队列:推了也是白跑一轮(分片全被拒)。任务留在 PENDING,
// 由客户端兜底拉取认领后照样会跑,所以这里只提示、不回滚建单。
// 激活失败是服务端原因,留在红色 error 档提醒用户可重试。
errorMessage.value = activateError
} else {
try {
const pushError = await pushToClientQueue(vo.taskId, shop, tabs, shopNames, shopIds)
// 推送失败只是慢路径(兜底拉取约 1 分钟内认领),走 amber notice,不占红色 error。
if (pushError) noticeMessage.value = pushError
} catch (pushErr) {
// 推送自身异常不回滚建单:任务可由客户端兜底拉取认领。
noticeMessage.value = PUSH_FALLBACK_NOTE
console.error('[jd-collect] 推送本机队列失败', pushErr)
}
}
if (!errorMessage.value && !noticeMessage.value) {
const tabLabels = TAB_OPTIONS
.filter((option) => tabs.includes(option.value))
.map((option) => option.label)
.join('、')
const scopeNote = [
`采集 ${tabLabels}`,
...(shopNames.length ? [`只采 ${shopNames.length} 个分类`] : []),
].join(',')
successMessage.value = `任务已创建(${scopeNote})并推送给本机客户端,进度显示在右侧任务区`
}
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()
// 同步按钮可用性:桥晚到(pywebviewready 在挂载之后)也要能翻成可用。
refreshSyncAvailability()
// 上次成功同步的分类直接回填:分类是现拉(起 Chrome 十几秒),不该每次重开都空着。
restoreCategoryCache()
window.addEventListener('pywebviewready', refreshSyncAvailability)
await Promise.all([
board.loadDashboard().catch(() => undefined),
board.loadHistory().catch(() => undefined),
])
board.seedRunningTasksFromHistory()
board.seedPendingFileTasksFromHistory()
board.ensurePollingIfAny()
})
onUnmounted(() => {
window.removeEventListener('pywebviewready', refreshSyncAvailability)
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">
<div class="category-block">
<span class="category-label">采集状态(多选)</span>
<div class="tab-checks">
<label v-for="option in TAB_OPTIONS" :key="option.value" class="tab-check">
<input type="checkbox" :value="option.value"
:checked="selectedTabs.includes(option.value)" @change="toggleTab(option.value)" />
<span>{{ option.label }}</span>
</label>
</div>
<p class="category-hint">{{ tabHint }}</p>
</div>
<div class="category-block">
<div class="category-head">
<span class="category-label">采集分类(可选,多选)</span>
<button class="shop-cat-sync" type="button" :disabled="!canLoginJd || loggingIn"
title="打开京东采集专用浏览器,停在京麦登录页人工登录(登录态失效时需要;登录一次即常驻本机)"
@click="openJdLogin">
{{ loggingIn ? '等待登录中…' : '登录京麦' }}
</button>
<button class="shop-cat-sync" type="button" :disabled="!canSyncCategories || syncingCategories"
title="从本机已登录的京麦店铺拉取店内分类(每家店不一样)" @click="syncShopCategories">
{{ syncingCategories ? '同步中…' : '同步分类' }}
</button>
</div>
<el-select v-model="selectedShopCategoryValues" multiple collapse-tags collapse-tags-tooltip
:max-collapse-tags="1" placeholder="全店采集(点击选择分类)" class="shop-cat-select">
<el-option v-for="category in shopCategoryOptions" :key="category.value"
:label="category.label" :value="category.value" />
</el-select>
<p class="category-hint">{{ categoryHint }}
<button v-if="selectedShopCategoryValues.length" class="shop-cat-clear" type="button"
@click="clearShopCategories">清空</button>
</p>
</div>
<button class="collect-btn" type="button" :disabled="isRunning || noTabSelected" @click="startCollect">
{{ isRunning ? '获取中…' : (noTabSelected ? '请先勾选采集状态' : (selectedShopCategories.length ? `获取选中分类数据` : '一键获取店铺数据')) }}
</button>
<p class="collect-hint">
点击后本机客户端会自动打开已登录的京麦后台采集商品,请保持客户端在线且京麦已登录;
采集到的数据会实时回传并导入后台「京东数据库」。进度显示在右侧任务区。
</p>
<p v-if="successMessage" class="feedback success">{{ successMessage }}</p>
<p v-if="noticeMessage" class="feedback notice">{{ noticeMessage }}</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,
.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;
}
.home-back:hover,
.tool-head__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__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;
}
/* 类目选择块:与按钮同宽,label 用面板小字口径。 */
.category-block {
margin-bottom: 16px;
}
/* label 与「同步分类」按钮同一行(2026-11-19 用户口径:店内分类旁边加个同步按钮)。 */
.category-head {
display: flex;
align-items: center;
justify-content: space-between;
gap: 10px;
margin-bottom: 8px;
}
.category-label {
display: block;
color: #c8d2e2;
font-size: 13px;
font-weight: 600;
}
/* 采集状态勾选(2026-11-20):只两档,直接平铺两个复选框,不用下拉。 */
.tab-checks {
display: flex;
gap: 20px;
margin-top: 8px;
}
.tab-check {
display: inline-flex;
align-items: center;
gap: 6px;
color: #c8d2e2;
font-size: 13px;
cursor: pointer;
user-select: none;
}
.tab-check input {
width: 14px;
height: 14px;
margin: 0;
accent-color: #e1251b;
cursor: pointer;
}
.shop-cat-sync {
flex-shrink: 0;
padding: 4px 12px;
border: 1px solid #3e4a62;
border-radius: 6px;
background: #232b3d;
color: #6ea8ff;
font-size: 12px;
font-family: inherit;
cursor: pointer;
transition: all 0.2s;
}
.shop-cat-sync:hover:not(:disabled) {
background: #2b3447;
border-color: #6ea8ff;
}
.shop-cat-sync:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.category-hint {
margin: 8px 0 0;
color: #7f8ca3;
font-size: 12px;
line-height: 1.6;
}
/* 采集分类下拉多选(2026-11-17 客户口径「别全展示,弄下拉式多选」):
* 暗色主题套品牌页 el-select 同款壳(wrapper 底色/描边/文字色),
* 面板内弹层由 Element Plus 自带样式,不再逐条铺 9 行复选框。 */
.shop-cat-select {
width: 100%;
}
.shop-cat-select :deep(.el-select__wrapper) {
background-color: #232b3d;
box-shadow: 0 0 0 1px #3e4a62 inset;
}
.shop-cat-select :deep(.el-select__placeholder),
.shop-cat-select :deep(.el-select__selected-item) {
color: #c8d2e2;
}
.shop-cat-clear {
margin-left: 6px;
padding: 0;
border: none;
background: none;
color: #6ea8ff;
font-size: 12px;
cursor: pointer;
font-family: inherit;
}
.shop-cat-clear:hover {
text-decoration: underline;
}
.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;
}
/* amber notice:设计内慢路径(推送失败走兜底拉取)专用,不是错误——与 success/error 同族配色 */
.feedback.notice {
background: rgba(245, 158, 11, 0.14);
color: #fcd34d;
}
/* 行内动作按钮:与外观专利 Tab 同色系(中断琥珀/重试绿/删除红),钉死 12px 字号 */
.btn-delete, .btn-retry, .btn-interrupt { border: none; cursor: pointer; border-radius: 6px; font-size: 12px; }
.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>