809 lines
40 KiB
Vue
809 lines
40 KiB
Vue
<script setup lang="ts">
|
||
import { computed, onMounted, onUnmounted, ref, watch } 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 {
|
||
fetchJdCollectGroups,
|
||
type JdCollectGroupVo,
|
||
} from '@/shared/api/types/modules/jd-collect'
|
||
import {
|
||
createJdPublishTask,
|
||
deleteJdPublishTask,
|
||
fetchJdPublishDashboard,
|
||
fetchJdPublishHistory,
|
||
fetchJdPublishProducts,
|
||
fetchJdPublishTaskProgressBatch,
|
||
interruptJdPublishTask,
|
||
retryJdPublishBrand,
|
||
type JdPublishHistoryItemVo,
|
||
type JdPublishProductVo,
|
||
} from '@/shared/api/types/modules/jd-publish'
|
||
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 蓝图 §4 Phase 4):选分类 → 勾商品 → 改价规则 → 建单 → 右侧任务面板实时行级进度。
|
||
*
|
||
* 六条边界(照 v1.4/v1.5 已落地的采集契约与外观专利任务面板骨架,不另造流程):
|
||
* 1. 分类选项唯一来源=jdCollect.groups 既有出口(B113-01,AC-9 源码绊线钉死:本页不得自拼
|
||
* 分类 URL);分组下的商品列表走 jdPublish.products(AC-9 owner 过滤:服务端只回归属
|
||
* 当前登录用户的行),页内翻页、勾选跨页累计;
|
||
* 2. 改价规则三档(none/percent/fixed,蓝图 §3 死契约),与勾选集一起进建单体;服务端按
|
||
* 同一规则折算 SKU 价(铁律 27a 改价同源);
|
||
* 3. 网页原样转交建单响应的 queuePayload;认领只由客户端与后端完成,投递失败仍可由客户端拉取;
|
||
* 4. 进度只读服务端:行级四档计数来自发布明细表聚合,total 缺失时只报已发布行数,不编造百分比;
|
||
* 5. 失败/中断在原任务上重试,目标品牌校验失败时只允许符合条件的任务改品牌后重试;
|
||
* 6. 京麦未登录等凭据致命失败(铁律 31):服务端整单判死后 useLiveTaskBoard 经
|
||
* reportCredentialFatal 弹一次窗(credential-fatal 同形接入,AC-5 用户端半边;弹窗组件
|
||
* 挂 App.vue,本页无需重复挂)。
|
||
*/
|
||
|
||
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'
|
||
}
|
||
|
||
// ---- 分类选择(AC-9:唯一来源是 jdCollect 组的既有 fetch 函数,不自拼 URL)----
|
||
const jdCollectGroupLoader = fetchJdCollectGroups
|
||
const groupOptions = ref<JdCollectGroupVo[]>([])
|
||
const groupsLoading = ref(false)
|
||
const selectedGroupId = ref<number | null>(null)
|
||
|
||
async function loadGroups() {
|
||
groupsLoading.value = true
|
||
try {
|
||
const vo = await jdCollectGroupLoader()
|
||
groupOptions.value = vo ?? []
|
||
// 默认选中第一个分类:分类是建单的展示维度,缺省选中省一次点击;商品列表随之拉取。
|
||
if (!selectedGroupId.value && groupOptions.value.length) {
|
||
selectedGroupId.value = groupOptions.value[0].id
|
||
}
|
||
} finally {
|
||
groupsLoading.value = false
|
||
}
|
||
}
|
||
|
||
// ---- 选品分页(owner 过滤在服务端;勾选跨页累计在本地 Map,翻页不清空)----
|
||
const PRODUCT_PAGE_SIZE = 12
|
||
const products = ref<JdPublishProductVo[]>([])
|
||
const productTotal = ref(0)
|
||
const productPage = ref(1)
|
||
const productsLoading = ref(false)
|
||
const selectedProducts = ref(new Map<number, JdPublishProductVo>())
|
||
let productRequest = 0
|
||
|
||
const selectedProductIds = computed(() => Array.from(selectedProducts.value.keys()))
|
||
const wholePageSelected = computed(() => products.value.length > 0
|
||
&& products.value.every((row) => selectedProducts.value.has(row.id)))
|
||
const partOfPageSelected = computed(() => !wholePageSelected.value
|
||
&& products.value.some((row) => selectedProducts.value.has(row.id)))
|
||
|
||
function togglePage(checked: boolean) {
|
||
const next = new Map(selectedProducts.value)
|
||
for (const row of products.value) {
|
||
if (checked) next.set(row.id, row)
|
||
else next.delete(row.id)
|
||
}
|
||
selectedProducts.value = next
|
||
}
|
||
|
||
function toggleProduct(row: JdPublishProductVo, checked: boolean) {
|
||
const next = new Map(selectedProducts.value)
|
||
if (checked) next.set(row.id, row)
|
||
else next.delete(row.id)
|
||
selectedProducts.value = next
|
||
}
|
||
|
||
function clearSelection() {
|
||
selectedProducts.value = new Map()
|
||
}
|
||
|
||
async function loadProducts() {
|
||
const request = ++productRequest
|
||
products.value = []
|
||
if (selectedGroupId.value == null) {
|
||
productTotal.value = 0
|
||
productsLoading.value = false
|
||
return
|
||
}
|
||
productsLoading.value = true
|
||
try {
|
||
const vo = await fetchJdPublishProducts(selectedGroupId.value, productPage.value, PRODUCT_PAGE_SIZE)
|
||
if (request !== productRequest) return
|
||
products.value = vo.items ?? []
|
||
productTotal.value = vo.total ?? 0
|
||
} catch (err) {
|
||
if (request === productRequest) {
|
||
errorMessage.value = err instanceof Error ? err.message : '商品列表拉取失败,请稍后重试'
|
||
}
|
||
} finally {
|
||
if (request === productRequest) productsLoading.value = false
|
||
}
|
||
}
|
||
|
||
function changeGroup() {
|
||
productPage.value = 1
|
||
productTotal.value = 0
|
||
clearSelection()
|
||
void loadProducts()
|
||
}
|
||
|
||
function changePage(page: number) {
|
||
productPage.value = page
|
||
void loadProducts()
|
||
}
|
||
|
||
// ---- 改价规则(蓝图 §3:none/percent/fixed 三档;percent=百分数,fixed=加价金额)----
|
||
const PRICE_RULE_MODES = [
|
||
{ value: 'none', label: '按原价上架' },
|
||
{ value: 'percent', label: '按比例加价(%)' },
|
||
{ value: 'fixed', label: '固定加价(元)' },
|
||
] as const
|
||
const priceMode = ref<'none' | 'percent' | 'fixed'>('none')
|
||
const priceValue = ref<number | null>(null)
|
||
const targetBrandInput = ref('')
|
||
const TARGET_BRAND_MAX = 120
|
||
const TARGET_BRAND_ERROR = '请输入目标品牌名称,去掉首尾空格后须为 1–120 个字符。'
|
||
const targetBrandName = computed(() => targetBrandInput.value.trim())
|
||
|
||
function isValidBrand(name: string) {
|
||
return name.length > 0 && name.length <= TARGET_BRAND_MAX
|
||
}
|
||
|
||
const priceValueMissing = computed(() => priceMode.value !== 'none' && (priceValue.value == null || priceValue.value < 0))
|
||
|
||
const submitDisabled = computed(() =>
|
||
submitting.value
|
||
|| !selectedGroupId.value
|
||
|| !selectedProducts.value.size
|
||
|| !isValidBrand(targetBrandName.value)
|
||
|| priceValueMissing.value)
|
||
|
||
// 此闸只约束京东品牌发布,不改变客户端其他功能的全局版本门槛。
|
||
const JD_PUBLISH_PROTOCOL = 3
|
||
const JD_UPGRADE_NOTICE = '请升级到支持目标品牌发布的数富AI客户端,并在客户端内打开本页。'
|
||
|
||
async function supportsBrandPublishing() {
|
||
try {
|
||
return await getPywebviewApi()?.jd_publish_protocol?.() === JD_PUBLISH_PROTOCOL
|
||
} catch (error) {
|
||
// 桥拒绝/异常按「本机不支持目标品牌」处理,false 会让两个调用方弹升级提示(用户可见出口)。
|
||
const detail = error instanceof Error ? error.message : String(error)
|
||
console.error('[jd-publish] 读取本机发布协议失败:%s', detail)
|
||
return false
|
||
}
|
||
}
|
||
|
||
// 通用重试回执不带代数:旧代 + 1 只用作读侧下限,不生成任务或队列数据。
|
||
const retryAttemptFloor = new Map<number, number>()
|
||
const awaitingRetryProgress = new Set<number>()
|
||
const retryingTaskIds = ref(new Set<number>())
|
||
|
||
function acceptsAttempt(taskId: number | undefined, attempt: number | undefined) {
|
||
const floor = taskId == null ? undefined : retryAttemptFloor.get(taskId)
|
||
return floor == null || (attempt != null && attempt >= floor)
|
||
}
|
||
|
||
async function fetchCurrentHistory(): ReturnType<typeof fetchJdPublishHistory> {
|
||
const history = await fetchJdPublishHistory()
|
||
return {
|
||
...history,
|
||
items: history.items.flatMap((item): JdPublishHistoryItemVo[] => {
|
||
if (acceptsAttempt(item.taskId, item.resumeAttempt)) return [item]
|
||
const current = board.historyItems.value.find((row) => row.taskId === item.taskId)
|
||
return current && acceptsAttempt(current.taskId, current.resumeAttempt) ? [current] : []
|
||
}),
|
||
}
|
||
}
|
||
|
||
async function fetchCurrentProgress(taskIds: number[], { force }: { force: boolean }) {
|
||
const floorsAtRequest = new Map(taskIds.map((id) => [id, retryAttemptFloor.get(id)]))
|
||
const unchanged = (id: number) => !retryingTaskIds.value.has(id)
|
||
&& retryAttemptFloor.get(id) === floorsAtRequest.get(id)
|
||
const batch = await fetchJdPublishTaskProgressBatch(taskIds, {
|
||
force: force || taskIds.some((id) => awaitingRetryProgress.has(id)),
|
||
})
|
||
return {
|
||
...batch,
|
||
items: batch.items.flatMap((detail) => {
|
||
const { task, items } = detail
|
||
if (task?.id == null || !unchanged(task.id) || !acceptsAttempt(task.id, task.resumeAttempt)) return []
|
||
const row = items?.[0]
|
||
if (row && !acceptsAttempt(task.id, row.resumeAttempt)) return []
|
||
awaitingRetryProgress.delete(task.id)
|
||
// 稳定分档来自任务头,而非商品行错误;缺行时仍显示失败,但不猜商品计数。
|
||
if (task.status?.toUpperCase() !== 'FAILED' || !validationFailureKind(task.errorMessage)) return [detail]
|
||
// 京东校验提示由本页处理,不把原文交给通用凭据分类器。
|
||
return [{ ...detail, task: { ...task, errorMessage: undefined }, items: [{
|
||
...row,
|
||
taskId: task.id,
|
||
taskStatus: task.status,
|
||
resumeAttempt: task.resumeAttempt,
|
||
errorMessage: task.errorMessage,
|
||
}] }]
|
||
}),
|
||
missingTaskIds: batch.missingTaskIds.filter(unchanged),
|
||
}
|
||
}
|
||
|
||
// ---- 实时任务面板(照 JdCollectTab 的 useLiveTaskBoard 形状;京东发布无结果文件,无下载层)----
|
||
const board = useLiveTaskBoard<JdPublishHistoryItemVo>({
|
||
scope: 'jd-publish',
|
||
pollingStorageKey: () => `jd-publish:tasks:${uidForStorage()}`,
|
||
fetchHistory: fetchCurrentHistory,
|
||
fetchProgressBatch: fetchCurrentProgress,
|
||
fetchDashboard: fetchJdPublishDashboard,
|
||
normalizeTaskStatus,
|
||
// 京东发布没有结果文件:状态到终态即结束,没有「等文件」那一层
|
||
isResultPreparing: () => false,
|
||
addPendingAfterFinalStatus: () => false,
|
||
keepPendingFileTask: () => false,
|
||
// CANCELLED 也是终态:中断的任务出「继续」按钮并停止轮询
|
||
settleOnTaskStatuses: ['SUCCESS', 'FAILED', 'CANCELLED'],
|
||
deleteTask: {
|
||
shouldDeleteTask: (item) => item.taskId != null,
|
||
deleteTask: (taskId) => deleteJdPublishTask(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(toJdPublishTaskView),
|
||
)
|
||
const historyTaskViews = computed<TaskItemView[]>(() =>
|
||
board.historyOnlyItems.value.map(toJdPublishTaskView),
|
||
)
|
||
|
||
function itemSource(item: TaskItemView) {
|
||
return item.source as JdPublishHistoryItemVo
|
||
}
|
||
|
||
function toJdPublishTaskView(item: JdPublishHistoryItemVo): TaskItemView {
|
||
const showProgress = isActiveTask(item)
|
||
const total = typeof item.productTotal === 'number' && item.productTotal > 0 ? item.productTotal : null
|
||
const published = (item.successCount ?? 0) + (item.failedCount ?? 0)
|
||
const failureNotice = validationFailureNotice(item)
|
||
return {
|
||
key: `jd-publish-${item.taskId ?? item.taskNo ?? item.updatedAt ?? ''}`,
|
||
title: `商品上架 · ${total ?? '—'} 个商品`,
|
||
taskId: item.taskId ?? '-',
|
||
startedAt: formatDateTime(item.createdAt),
|
||
finishedAt: formatDateTime(item.finishedAt),
|
||
statusText: statusText(item),
|
||
statusClass: statusClass(item),
|
||
extraLines: [
|
||
`成功 ${item.successCount ?? 0} / 失败 ${item.failedCount ?? 0}`
|
||
+ (item.publishingCount ? ` / 发布中 ${item.publishingCount}` : ''),
|
||
...(showProgress && total ? [`已发布 ${Math.min(published, total)}/${total} 个商品`] : []),
|
||
...(failureNotice ? [`错误:${failureNotice.title}:${failureNotice.body}`]
|
||
: item.errorMessage ? [`错误:${userNotice(item.errorMessage)}`] : []),
|
||
],
|
||
progress: showProgress ? { percent: progressPercent(item), countLabel: progressCountLabel(item) } : null,
|
||
source: item,
|
||
}
|
||
}
|
||
|
||
// ---- 本模块的状态语义(京东发布:无结果文件,状态即终态)----
|
||
|
||
function normalizeTaskStatus(item: JdPublishHistoryItemVo | null | undefined) {
|
||
return (item?.taskStatus || '').toUpperCase()
|
||
}
|
||
|
||
function isActiveTask(item: JdPublishHistoryItemVo) {
|
||
const status = normalizeTaskStatus(item)
|
||
return status === 'PENDING' || status === 'RUNNING' || status === 'SCHEDULED'
|
||
}
|
||
|
||
function statusText(item: JdPublishHistoryItemVo) {
|
||
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: JdPublishHistoryItemVo) {
|
||
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: JdPublishHistoryItemVo) {
|
||
const status = normalizeTaskStatus(item)
|
||
if (status === 'SUCCESS') return 100
|
||
const total = typeof item.productTotal === 'number' && item.productTotal > 0 ? item.productTotal : null
|
||
if (!total) return 0
|
||
const done = Math.min((item.successCount ?? 0) + (item.failedCount ?? 0), total)
|
||
return Math.max(0, Math.min(99, Math.round((done * 100) / total)))
|
||
}
|
||
|
||
/** 计数文案:有 total 带分母和百分比;没有 total 只报行数,不编造分母。 */
|
||
function progressCountLabel(item: JdPublishHistoryItemVo) {
|
||
const published = (item.successCount ?? 0) + (item.failedCount ?? 0)
|
||
const total = typeof item.productTotal === 'number' && item.productTotal > 0 ? item.productTotal : null
|
||
if (!total) return `已发布 ${published} 个商品`
|
||
return `已发布 ${published}/${total} 个商品(${progressPercent(item)}%)`
|
||
}
|
||
|
||
function validationFailureKind(message: string | undefined) {
|
||
if (message?.startsWith('目标品牌校验失败:')) return 'brand'
|
||
if (message?.startsWith('本店源商品校验失败:')) return 'source'
|
||
return null
|
||
}
|
||
|
||
function canChangeBrand(item: JdPublishHistoryItemVo) {
|
||
return item.successCount === 0 && item.publishingCount === 0
|
||
}
|
||
|
||
function validationFailureDetail(message: string) {
|
||
// 只去掉发布校验机器码,不把商品编码或英文品牌名误当错误码。
|
||
const detail = message.slice(message.indexOf(':') + 1)
|
||
.replace(/[((]\s*JD_(?:BRAND|SOURCE)_[A-Z0-9_]+\s*[))]|\bJD_(?:BRAND|SOURCE)_[A-Z0-9_]+\b/g, '')
|
||
.trim()
|
||
return /\p{Script=Han}/u.test(detail) ? detail : ''
|
||
}
|
||
|
||
function validationFailureNotice(item: JdPublishHistoryItemVo) {
|
||
if (normalizeTaskStatus(item) !== 'FAILED') return null
|
||
const kind = validationFailureKind(item.errorMessage)
|
||
if (!kind || !item.errorMessage) return null
|
||
const detail = validationFailureDetail(item.errorMessage)
|
||
const addAction = (action: string) => detail ? `${detail}\n${action}` : action
|
||
if (kind === 'brand') {
|
||
return {
|
||
title: '目标品牌校验失败',
|
||
body: addAction(canChangeBrand(item)
|
||
? '请核对当前京麦店铺可用的品牌名称,然后选择「修改品牌并重试」。'
|
||
: '请保留已发布结果,核对京麦中的发布状态,然后重新选择未发布商品建单。'),
|
||
}
|
||
}
|
||
// 2026-11-21 四商品实测:京麦对「上架中」源商品的克隆页响应字段齐全但 productId/spuId
|
||
// 恒为 0——不是店铺归属问题,别把用户引去切店铺(切了也一样);只有其余形状才是换店信号。
|
||
if (detail.includes('未携带源商品身份')) {
|
||
return {
|
||
title: '本店源商品校验失败',
|
||
body: addAction('京麦未把该商品当作本店可克隆源(实测「上架中」商品如此),请改用「已下架」等非在售商品建单。'),
|
||
}
|
||
}
|
||
return {
|
||
title: '本店源商品校验失败',
|
||
body: addAction('请切换到正确店铺后重试,或重新选择本店商品建单。'),
|
||
}
|
||
}
|
||
|
||
const shownValidationFailures = new Set<string>()
|
||
watch(
|
||
() => board.historyItems.value.map((item) => ({
|
||
taskId: item.taskId, attempt: item.resumeAttempt ?? 0, notice: validationFailureNotice(item),
|
||
})),
|
||
(items) => {
|
||
for (const { taskId, attempt, notice } of items) {
|
||
if (!taskId || !notice) continue
|
||
const key = `${taskId}:${attempt}`
|
||
if (shownValidationFailures.has(key)) continue
|
||
shownValidationFailures.add(key)
|
||
void ElMessageBox.alert(notice.body, notice.title, {
|
||
type: 'warning', confirmButtonText: '知道了', dangerouslyUseHTMLString: false,
|
||
})
|
||
.then(() => undefined, () => undefined)
|
||
}
|
||
},
|
||
)
|
||
|
||
/** 失败/已中断的任务能续跑;品牌失败仅在既无成功也无待确认商品时允许改品牌。 */
|
||
function canRetryTask(item: JdPublishHistoryItemVo | null | undefined): boolean {
|
||
if (!item?.taskId) return false
|
||
const status = normalizeTaskStatus(item)
|
||
if (status === 'FAILED' && validationFailureKind(item.errorMessage) === 'brand') return canChangeBrand(item)
|
||
return status === 'FAILED' || status === 'CANCELLED'
|
||
}
|
||
|
||
function retryLabel(item: JdPublishHistoryItemVo | null | undefined): string {
|
||
if (normalizeTaskStatus(item) === 'FAILED' && validationFailureKind(item?.errorMessage) === 'brand') return '修改品牌并重试'
|
||
return normalizeTaskStatus(item) === 'CANCELLED' ? '继续' : '重试'
|
||
}
|
||
|
||
/** 在跑/待跑的任务可中断:PENDING/RUNNING/SCHEDULED 是服务端 CAS 的同一 ACTIVE 集合。 */
|
||
function canInterruptTask(item: JdPublishHistoryItemVo | null | undefined): boolean {
|
||
if (!item?.taskId) return false
|
||
const status = normalizeTaskStatus(item)
|
||
return status === 'PENDING' || status === 'RUNNING' || status === 'SCHEDULED'
|
||
}
|
||
|
||
async function interruptTaskRecord(item: JdPublishHistoryItemVo | 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 interruptJdPublishTask(taskId)
|
||
ElMessage.success('已中断:客户端下一跳心跳后收手,之后可点「继续」接着跑')
|
||
await refreshBoard()
|
||
} catch (error) {
|
||
ElMessage.error(error instanceof Error ? error.message : '中断失败')
|
||
}
|
||
}
|
||
|
||
async function promptRetryBrand(): Promise<string | null> {
|
||
if (!await supportsBrandPublishing()) {
|
||
ElMessage.error(JD_UPGRADE_NOTICE)
|
||
return null
|
||
}
|
||
const name = await ElMessageBox.prompt('请输入当前京麦店铺可用的目标品牌名称。', '修改品牌并重试', {
|
||
confirmButtonText: '重试',
|
||
cancelButtonText: '取消',
|
||
inputValidator: (value: string) => isValidBrand(value.trim()) || TARGET_BRAND_ERROR,
|
||
}).then(({ value }) => value.trim(), () => null)
|
||
return name && isValidBrand(name) ? name : null
|
||
}
|
||
|
||
async function retryTaskRecord(item: JdPublishHistoryItemVo | null | undefined) {
|
||
if (!item?.taskId || !canRetryTask(item) || retryingTaskIds.value.has(item.taskId)) return
|
||
const { taskId, resumeAttempt = 0 } = item
|
||
const changeBrand = normalizeTaskStatus(item) === 'FAILED' && validationFailureKind(item.errorMessage) === 'brand'
|
||
const isResume = normalizeTaskStatus(item) === 'CANCELLED'
|
||
let nextPayload: Record<string, unknown> | undefined
|
||
retryingTaskIds.value.add(taskId)
|
||
try {
|
||
if (changeBrand) {
|
||
const brand = await promptRetryBrand()
|
||
if (!brand) return
|
||
const vo = await retryJdPublishBrand(taskId, brand, resumeAttempt)
|
||
nextPayload = vo.queuePayload
|
||
} else {
|
||
// 2026-11-21:复位是 PENDING,服务端兜底拉取默认关闭——不把响应带回的直推载荷
|
||
// 推回本机队列,任务会停在 PENDING 直到有人手动干预(35147 重试实录)。
|
||
const result = await retryClientTask(taskId)
|
||
nextPayload = result?.queuePayload ?? undefined
|
||
}
|
||
retryAttemptFloor.set(taskId, resumeAttempt + 1)
|
||
} catch (error) {
|
||
ElMessage.error(error instanceof Error ? userNotice(error.message) : '重试失败')
|
||
return
|
||
} finally {
|
||
retryingTaskIds.value.delete(taskId)
|
||
}
|
||
|
||
awaitingRetryProgress.add(taskId)
|
||
board.removePollingTask(taskId)
|
||
board.historyItems.value = board.historyItems.value.filter((row) => row.taskId !== taskId)
|
||
board.addPollingTask(taskId)
|
||
if (changeBrand) {
|
||
const pushNote = await pushToClientQueue(nextPayload, '已修改品牌并重试')
|
||
ElMessage.success(pushNote ?? '已修改品牌并重试,任务已送入本机队列')
|
||
} else {
|
||
// 服务端带回直推载荷时推回本机队列并立即提示;拿不到(非本机执行模块/服务端未升级)
|
||
// 才退回「等待领取」的旧口径——文案与实际去向一致,不再让用户空等。
|
||
const pushNote = await pushToClientQueue(nextPayload, isResume ? '已提交继续' : '已提交原任务重试')
|
||
ElMessage.success(pushNote ?? `${isResume ? '已提交继续' : '已提交原任务重试'},任务已送入本机队列`)
|
||
}
|
||
await refreshBoard().catch((error) => console.error('[jd-publish] 重试后刷新任务失败', error))
|
||
}
|
||
|
||
/** 手动刷新:强拉历史 + 统计 + 当前轮询任务进度 + 分组(计数是服务端聚合,归类后旧值过时) */
|
||
async function refreshBoard() {
|
||
await Promise.all([
|
||
board.loadDashboard(),
|
||
board.loadHistory({ force: true }),
|
||
board.refreshTaskProgress(),
|
||
loadGroups().catch(() => undefined),
|
||
])
|
||
}
|
||
|
||
async function pushToClientQueue(payload: Record<string, unknown> | undefined, action = '任务已创建'): Promise<string | null> {
|
||
if (!payload) return `${action},等待本机客户端领取。请保持客户端在线。`
|
||
const api = getPywebviewApi()
|
||
if (!api?.enqueue_json) {
|
||
return `${action},等待本机客户端领取。请打开本机客户端并登录同一账号。`
|
||
}
|
||
try {
|
||
const result = await api.enqueue_json(payload)
|
||
if (result?.success) return null
|
||
if (result?.error) console.error('[jd-publish] enqueue_json 被拒', result.error)
|
||
} catch (error) {
|
||
// 异常原文留控制台;用户可见出口是下方返回的兜底提示(调用方弹给用户)。
|
||
const detail = error instanceof Error ? error.message : String(error)
|
||
console.error('[jd-publish] 推送本机队列失败:%s', detail)
|
||
}
|
||
return `${action},但未能推送到本机队列。请保持客户端在线,客户端会自动领取。`
|
||
}
|
||
|
||
const isRunning = computed(() => Boolean(board.dashboard.value.pendingTaskCount) || submitting.value)
|
||
|
||
const priceRuleHint = computed(() => {
|
||
if (priceMode.value === 'none') return '按京东数据库里的采集原价上架。'
|
||
if (priceMode.value === 'percent') return '按采集价上浮 N%(填 10 表示加价 10%)。'
|
||
return '每个商品统一加固定金额(填 5 表示加 5 元)。'
|
||
})
|
||
|
||
async function startPublish() {
|
||
if (submitDisabled.value) return
|
||
errorMessage.value = ''
|
||
successMessage.value = ''
|
||
submitting.value = true
|
||
try {
|
||
const priceRule = priceMode.value === 'none'
|
||
? { mode: 'none' as const }
|
||
: { mode: priceMode.value, value: priceValue.value as number }
|
||
// 勾选集即建单 productIds;selectedGroupId 即建单体 categoryId
|
||
// (服务端按 owner 校验,选了他人商品当场拒,AC-9)。
|
||
const categoryId = selectedGroupId.value
|
||
const productIds = selectedProductIds.value
|
||
const brand = targetBrandName.value
|
||
if (!await supportsBrandPublishing()) {
|
||
errorMessage.value = JD_UPGRADE_NOTICE
|
||
return
|
||
}
|
||
const vo = await createJdPublishTask(categoryId, productIds, priceRule, brand)
|
||
board.addPollingTask(vo.taskId)
|
||
const pushNote = await pushToClientQueue(vo.queuePayload)
|
||
successMessage.value = pushNote
|
||
?? `任务已创建(${productIds.length} 个商品)并送入本机队列,等待客户端领取。`
|
||
await Promise.all([board.loadDashboard(), board.loadHistory({ force: true })])
|
||
.catch((error) => console.error('[jd-publish] 建单后刷新任务失败', error))
|
||
} 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([
|
||
loadGroups().catch(() => undefined),
|
||
board.loadDashboard().catch(() => undefined),
|
||
board.loadHistory().catch(() => undefined),
|
||
])
|
||
board.seedRunningTasksFromHistory()
|
||
board.seedPendingFileTasksFromHistory()
|
||
board.ensurePollingIfAny()
|
||
void loadProducts()
|
||
})
|
||
|
||
onUnmounted(() => {
|
||
board.dispose()
|
||
})
|
||
</script>
|
||
|
||
<template>
|
||
<div class="page-shell module-page jd-publish-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>
|
||
<el-select v-model="selectedGroupId" placeholder="选择分类" class="shop-cat-select"
|
||
:loading="groupsLoading" @change="changeGroup">
|
||
<el-option v-for="group in groupOptions" :key="group.id"
|
||
:label="`${group.name}(${group.productCount ?? 0} 个商品)`" :value="group.id" />
|
||
</el-select>
|
||
<p class="category-hint">分类由管理员在后台「京东数据库」维护;列表只显示归属你账号的商品。</p>
|
||
</div>
|
||
|
||
<div class="product-block" v-loading="productsLoading">
|
||
<div class="product-head">
|
||
<span class="category-label">选择商品(已选 {{ selectedProducts.size }} 个,跨页累计)</span>
|
||
<label v-if="products.length" class="category-hint">
|
||
<input type="checkbox" class="product-select-page" :checked="wholePageSelected"
|
||
:indeterminate.prop="partOfPageSelected"
|
||
@change="togglePage(($event.target as HTMLInputElement).checked)" />
|
||
全选本页
|
||
</label>
|
||
<button v-if="selectedProducts.size" class="shop-cat-clear" type="button"
|
||
@click="clearSelection">清空勾选</button>
|
||
</div>
|
||
<div v-if="!products.length && !productsLoading" class="product-empty">
|
||
{{ selectedGroupId ? '该分类下暂无归属你账号的商品' : '请先选择分类' }}
|
||
</div>
|
||
<label v-for="product in products" :key="product.id" class="product-row">
|
||
<input type="checkbox" class="product-check"
|
||
:checked="selectedProducts.has(product.id)"
|
||
@change="toggleProduct(product, ($event.target as HTMLInputElement).checked)" />
|
||
<img v-if="product.mainImageUrl" class="product-thumb" :src="product.mainImageUrl" alt="" loading="lazy" />
|
||
<span v-else class="product-thumb product-thumb--empty">无图</span>
|
||
<span class="product-info">
|
||
<span class="product-title">{{ product.title }}</span>
|
||
<span class="product-meta">
|
||
¥{{ product.priceMin ?? '-' }}<template v-if="product.priceMax && product.priceMax !== product.priceMin">~{{ product.priceMax }}</template>
|
||
· 库存 {{ product.stockTotal ?? '-' }}<template v-if="product.skuCount"> · {{ product.skuCount }}个SKU</template>
|
||
</span>
|
||
</span>
|
||
</label>
|
||
<el-pagination v-if="productTotal > PRODUCT_PAGE_SIZE" class="product-pager" layout="prev, pager, next"
|
||
:total="productTotal" :page-size="PRODUCT_PAGE_SIZE" :current-page="productPage"
|
||
@current-change="changePage" />
|
||
</div>
|
||
|
||
<div class="category-block">
|
||
<span class="category-label">改价规则(可选)</span>
|
||
<el-select v-model="priceMode" class="shop-cat-select">
|
||
<el-option v-for="mode in PRICE_RULE_MODES" :key="mode.value" :label="mode.label" :value="mode.value" />
|
||
</el-select>
|
||
<el-input-number v-if="priceMode !== 'none'" v-model="priceValue" :min="0" :precision="2"
|
||
:step="priceMode === 'percent' ? 1 : 0.5" class="price-input" controls-position="right"
|
||
:placeholder="priceMode === 'percent' ? '加价百分比' : '加价金额'" />
|
||
<p class="category-hint">{{ priceRuleHint }}</p>
|
||
</div>
|
||
|
||
<div class="category-block">
|
||
<label class="category-label" for="jd-publish-target-brand">目标品牌名称(必填)</label>
|
||
<input id="jd-publish-target-brand" v-model="targetBrandInput" class="target-brand-input" type="text"
|
||
required :aria-invalid="Boolean(targetBrandInput && !isValidBrand(targetBrandName))"
|
||
aria-describedby="jd-publish-brand-hint" placeholder="输入当前京麦店铺可用的品牌名称" />
|
||
<p id="jd-publish-brand-hint" class="category-hint">本次选中的商品统一使用此品牌,不会修改京东数据库中的原品牌。</p>
|
||
</div>
|
||
|
||
<button class="collect-btn" type="button" :disabled="submitDisabled" @click="startPublish">
|
||
{{ submitting ? '创建中…' : `上架已选 ${selectedProducts.size} 个商品` }}
|
||
</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>
|
||
|
||
<!-- 样式与采集页同族暗色主题(header/brand/工具头为两页共通形状,各自 scoped 不共享);
|
||
逐规则单行压缩只为过可读棘轮 800 行线,不改任何选择器与声明。 -->
|
||
<style scoped>
|
||
.jd-publish-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; }
|
||
.jd-body { flex: 1 1 auto; min-height: 0; display: flex; align-items: stretch; overflow: hidden; }
|
||
.left-panel { width: 440px; 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; }
|
||
.category-block { margin-bottom: 16px; }
|
||
.category-label { display: block; margin-bottom: 8px; color: #c8d2e2; font-size: 13px; font-weight: 600; }
|
||
.category-hint { margin: 8px 0 0; color: #7f8ca3; font-size: 12px; line-height: 1.6; }
|
||
.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; }
|
||
.product-block { margin-bottom: 16px; }
|
||
.product-head { display: flex; align-items: center; justify-content: space-between; }
|
||
.product-head .category-label { margin-bottom: 8px; }
|
||
.product-row { display: flex; align-items: center; gap: 10px; padding: 8px 10px; margin-bottom: 6px; border: 1px solid #2c3547; border-radius: 8px; background: #20283a; cursor: pointer; }
|
||
.product-row:hover { border-color: #3e4a62; }
|
||
.product-check { flex-shrink: 0; width: 15px; height: 15px; accent-color: #e1251b; cursor: pointer; }
|
||
.product-thumb { flex-shrink: 0; width: 44px; height: 44px; border-radius: 6px; object-fit: cover; background: #232b3d; }
|
||
.product-thumb--empty { display: inline-flex; align-items: center; justify-content: center; color: #5f6c85; font-size: 11px; }
|
||
.product-info { min-width: 0; display: flex; flex-direction: column; gap: 3px; }
|
||
.product-title { color: #d9e1ef; font-size: 12px; line-height: 1.4; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
|
||
.product-meta { color: #8a97ad; font-size: 11px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||
.product-empty { padding: 18px 0; color: #5f6c85; font-size: 12px; text-align: center; }
|
||
.product-pager { margin-top: 8px; justify-content: center; }
|
||
.product-pager :deep(.el-pager li), .product-pager :deep(.btn-prev), .product-pager :deep(.btn-next) { background: transparent; color: #c8d2e2; }
|
||
.product-pager :deep(.el-pager li.is-active) { color: #6ea8ff; }
|
||
.target-brand-input { box-sizing: border-box; width: 100%; padding: 8px 10px; border: 1px solid #3e4a62; border-radius: 6px; background: #232b3d; color: #c8d2e2; font: inherit; }
|
||
.target-brand-input[aria-invalid="true"] { border-color: #fca5a5; }
|
||
.price-input { width: 100%; margin-top: 8px; }
|
||
.price-input :deep(.el-input__wrapper) { background-color: #232b3d; box-shadow: 0 0 0 1px #3e4a62 inset; }
|
||
.price-input :deep(.el-input__inner) { color: #c8d2e2; }
|
||
.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; }
|
||
.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>
|