feat(jd-publish): 目标品牌建单+校验失败整单判死+改品牌原位重试(桌面协议 v3 服务端半边)
- 建单必填目标品牌(1–120 字符单行),走 /tasks/target-brand 独占路径,旧后端不会静默丢参数
- 激活与明细下发带 jdPublishProtocol,协议 <3 直接 409 要求升级客户端;明细 VO 下发 targetBrandName
- 预检失败回执(SOURCE/BRAND)必须带一条失败明细,整单判 FAILED 并落分类前缀;通用重试/继续对品牌失败任务拒绝
- 新增 /tasks/{taskId}/retry-brand:只允许无成功、无待确认记录的品牌失败任务改品牌后原位重试(世代+1、明细复位、回执直推本机队列)
- 兜底拉取按协议过滤带 targetBrandName 的 JD 上架任务,认领 CAS 带 resumeAttempt 防跨代误领
- 用户端:目标品牌必填输入、协议探测挡旧客户端、品牌失败弹窗与「修改品牌并重试」按钮
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onUnmounted, ref } from 'vue'
|
||||
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'
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
fetchJdPublishProducts,
|
||||
fetchJdPublishTaskProgressBatch,
|
||||
interruptJdPublishTask,
|
||||
retryJdPublishBrand,
|
||||
type JdPublishHistoryItemVo,
|
||||
type JdPublishProductVo,
|
||||
} from '@/shared/api/types/modules/jd-publish'
|
||||
@@ -36,7 +37,7 @@ import NotificationBell from '@/shared/components/NotificationBell.vue'
|
||||
* 同一规则折算 SKU 价(铁律 27a 改价同源);
|
||||
* 3. 网页原样转交建单响应的 queuePayload;认领只由客户端与后端完成,投递失败仍可由客户端拉取;
|
||||
* 4. 进度只读服务端:行级四档计数来自发布明细表聚合,total 缺失时只报已发布行数,不编造百分比;
|
||||
* 5. 失败/中断「重试/继续」走通用原位复位(铁律 26,不克隆),新一轮由客户端拉取认领;
|
||||
* 5. 失败/中断在原任务上重试,目标品牌校验失败时只允许符合条件的任务改品牌后重试;
|
||||
* 6. 京麦未登录等凭据致命失败(铁律 31):服务端整单判死后 useLiveTaskBoard 经
|
||||
* reportCredentialFatal 弹一次窗(credential-fatal 同形接入,AC-5 用户端半边;弹窗组件
|
||||
* 挂 App.vue,本页无需重复挂)。
|
||||
@@ -152,6 +153,14 @@ const PRICE_RULE_MODES = [
|
||||
] 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))
|
||||
|
||||
@@ -159,9 +168,23 @@ const submitDisabled = computed(() =>
|
||||
submitting.value
|
||||
|| !selectedGroupId.value
|
||||
|| !selectedProducts.value.size
|
||||
|| !isValidBrand(targetBrandName.value)
|
||||
|| priceValueMissing.value)
|
||||
|
||||
// 重试回执不带代数:旧代 + 1 只用作读侧下限,不生成任务或队列数据。
|
||||
// 此闸只约束京东品牌发布,不改变客户端其他功能的全局版本门槛。
|
||||
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) {
|
||||
console.error('[jd-publish] 读取本机发布协议失败', error)
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// 通用重试回执不带代数:旧代 + 1 只用作读侧下限,不生成任务或队列数据。
|
||||
const retryAttemptFloor = new Map<number, number>()
|
||||
const awaitingRetryProgress = new Set<number>()
|
||||
const retryingTaskIds = ref(new Set<number>())
|
||||
@@ -192,12 +215,22 @@ async function fetchCurrentProgress(taskIds: number[], { force }: { force: boole
|
||||
})
|
||||
return {
|
||||
...batch,
|
||||
items: batch.items.filter(({ task, items }) => {
|
||||
if (task?.id == null || !unchanged(task.id) || !acceptsAttempt(task.id, task.resumeAttempt)) return false
|
||||
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 false
|
||||
if (row && !acceptsAttempt(task.id, row.resumeAttempt)) return []
|
||||
awaitingRetryProgress.delete(task.id)
|
||||
return true
|
||||
// 稳定分档来自任务头,而非商品行错误;缺行时仍显示失败,但不猜商品计数。
|
||||
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),
|
||||
}
|
||||
@@ -249,6 +282,7 @@ 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 ?? '—'} 个商品`,
|
||||
@@ -261,7 +295,8 @@ function toJdPublishTaskView(item: JdPublishHistoryItemVo): TaskItemView {
|
||||
`成功 ${item.successCount ?? 0} / 失败 ${item.failedCount ?? 0}`
|
||||
+ (item.publishingCount ? ` / 发布中 ${item.publishingCount}` : ''),
|
||||
...(showProgress && total ? [`已发布 ${Math.min(published, total)}/${total} 个商品`] : []),
|
||||
...(item.errorMessage ? [`错误:${userNotice(item.errorMessage)}`] : []),
|
||||
...(failureNotice ? [`错误:${failureNotice.title}:${failureNotice.body}`]
|
||||
: item.errorMessage ? [`错误:${userNotice(item.errorMessage)}`] : []),
|
||||
],
|
||||
progress: showProgress ? { percent: progressPercent(item), countLabel: progressCountLabel(item) } : null,
|
||||
source: item,
|
||||
@@ -317,15 +352,73 @@ function progressCountLabel(item: JdPublishHistoryItemVo) {
|
||||
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)
|
||||
? '请核对当前京麦店铺可用的品牌名称,然后选择「修改品牌并重试」。'
|
||||
: '请保留已发布结果,核对京麦中的发布状态,然后重新选择未发布商品建单。'),
|
||||
}
|
||||
}
|
||||
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' ? '继续' : '重试'
|
||||
}
|
||||
|
||||
@@ -358,24 +451,53 @@ async function interruptTaskRecord(item: JdPublishHistoryItemVo | null | undefin
|
||||
}
|
||||
}
|
||||
|
||||
async function retryTaskRecord(item: JdPublishHistoryItemVo | null | undefined) {
|
||||
const taskId = item?.taskId
|
||||
if (!taskId || retryingTaskIds.value.has(taskId)) return
|
||||
const isResume = normalizeTaskStatus(item) === 'CANCELLED'
|
||||
retryingTaskIds.value.add(taskId)
|
||||
const retried = await retryClientTask(taskId).then(() => true, (error: unknown) => {
|
||||
ElMessage.error(error instanceof Error ? error.message : '重试失败')
|
||||
return false
|
||||
})
|
||||
retryingTaskIds.value.delete(taskId)
|
||||
if (!retried) return
|
||||
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 {
|
||||
await retryClientTask(taskId)
|
||||
}
|
||||
retryAttemptFloor.set(taskId, resumeAttempt + 1)
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? userNotice(error.message) : '重试失败')
|
||||
return
|
||||
} finally {
|
||||
retryingTaskIds.value.delete(taskId)
|
||||
}
|
||||
|
||||
retryAttemptFloor.set(taskId, (item.resumeAttempt ?? 0) + 1)
|
||||
awaitingRetryProgress.add(taskId)
|
||||
board.removePollingTask(taskId)
|
||||
board.historyItems.value = board.historyItems.value.filter((row) => row.taskId !== taskId)
|
||||
board.addPollingTask(taskId)
|
||||
ElMessage.success(isResume ? '已提交继续,等待本机客户端领取' : '已提交原任务重试,等待本机客户端领取')
|
||||
if (changeBrand) {
|
||||
const pushNote = await pushToClientQueue(nextPayload, '已修改品牌并重试')
|
||||
ElMessage.success(pushNote ?? '已修改品牌并重试,任务已送入本机队列')
|
||||
} else {
|
||||
ElMessage.success(isResume ? '已提交继续,等待本机客户端领取' : '已提交原任务重试,等待本机客户端领取')
|
||||
}
|
||||
await refreshBoard().catch((error) => console.error('[jd-publish] 重试后刷新任务失败', error))
|
||||
}
|
||||
|
||||
@@ -388,21 +510,20 @@ async function refreshBoard() {
|
||||
])
|
||||
}
|
||||
|
||||
const WAIT_FOR_CLIENT = '任务已创建,等待本机客户端领取。请保持客户端在线。'
|
||||
|
||||
async function pushToClientQueue(payload: Record<string, unknown> | undefined): Promise<string | null> {
|
||||
if (!payload) return WAIT_FOR_CLIENT
|
||||
async function pushToClientQueue(payload: Record<string, unknown> | undefined, action = '任务已创建'): Promise<string | null> {
|
||||
if (!payload) return `${action},等待本机客户端领取。请保持客户端在线。`
|
||||
const api = getPywebviewApi()
|
||||
if (!api?.enqueue_json) {
|
||||
return '任务已创建,等待本机客户端领取。请打开本机客户端并登录同一账号。'
|
||||
return `${action},等待本机客户端领取。请打开本机客户端并登录同一账号。`
|
||||
}
|
||||
const result = await api.enqueue_json(payload).catch((error) => {
|
||||
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) {
|
||||
console.error('[jd-publish] 推送本机队列失败', error)
|
||||
return null
|
||||
})
|
||||
if (result?.success) return null
|
||||
if (result?.error) console.error('[jd-publish] enqueue_json 被拒', result.error)
|
||||
return '任务已创建,但未能推送到本机队列。请保持客户端在线,客户端会自动领取。'
|
||||
}
|
||||
return `${action},但未能推送到本机队列。请保持客户端在线,客户端会自动领取。`
|
||||
}
|
||||
|
||||
const isRunning = computed(() => Boolean(board.dashboard.value.pendingTaskCount) || submitting.value)
|
||||
@@ -426,7 +547,12 @@ async function startPublish() {
|
||||
// (服务端按 owner 校验,选了他人商品当场拒,AC-9)。
|
||||
const categoryId = selectedGroupId.value
|
||||
const productIds = selectedProductIds.value
|
||||
const vo = await createJdPublishTask(categoryId, productIds, priceRule)
|
||||
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
|
||||
@@ -542,6 +668,14 @@ onUnmounted(() => {
|
||||
<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>
|
||||
@@ -630,6 +764,8 @@ onUnmounted(() => {
|
||||
.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; }
|
||||
|
||||
@@ -228,8 +228,11 @@ export const API_ENDPOINTS = {
|
||||
},
|
||||
/** 京东商品上架:用户端建单/选品/面板;派发载荷由服务端下发,认领只由客户端和后端完成。 */
|
||||
jdPublish: {
|
||||
/** 建单(请求体 categoryId+productIds+priceRule,响应带 queuePayload 页面直推) */
|
||||
/** 后端兼容建单入口;新版页面用独占路径,避免旧后端忽略品牌参数。 */
|
||||
create: '/api/jd-publish/tasks',
|
||||
createWithTargetBrand: '/api/jd-publish/tasks/target-brand',
|
||||
/** 修改目标品牌后原位重试;沿用建单回执以直推本机队列。 */
|
||||
retryBrand: '/api/jd-publish/tasks/{taskId}/retry-brand',
|
||||
/** 用户端选品分页(AC-9 owner 过滤:只回归属当前用户的京东数据库商品行) */
|
||||
products: '/api/jd-publish/products',
|
||||
/** 任务面板总览(运行中/成功/失败计数统计卡) */
|
||||
|
||||
@@ -39,19 +39,28 @@ export function createJdPublishTask(
|
||||
categoryId: number | null,
|
||||
productIds: number[],
|
||||
priceRule: JdPublishPriceRule,
|
||||
targetBrandName: string,
|
||||
) {
|
||||
return unwrapJavaResponse(post<JavaApiResponse<JdPublishTaskVo>, Record<string, unknown>>(
|
||||
buildJavaUrl(API_ENDPOINTS.jdPublish.create),
|
||||
buildJavaUrl(API_ENDPOINTS.jdPublish.createWithTargetBrand),
|
||||
{
|
||||
userId: getCurrentUserId(),
|
||||
categoryId,
|
||||
productIds,
|
||||
// mode=none 时不带 value(后端 normalizePriceRule 对 none 忽略 value)
|
||||
priceRule: priceRule.mode === 'none' ? { mode: 'none' } : priceRule,
|
||||
targetBrandName,
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
export function retryJdPublishBrand(taskId: number, targetBrandName: string, resumeAttempt: number) {
|
||||
return unwrapJavaResponse(post<JavaApiResponse<JdPublishTaskVo>, { targetBrandName: string; resumeAttempt: number }>(
|
||||
buildJavaUrl(API_ENDPOINTS.jdPublish.retryBrand.replace('{taskId}', String(taskId))),
|
||||
{ targetBrandName, resumeAttempt },
|
||||
))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 选品分页(AC-9 owner 过滤):服务端只回归属当前用户的京东数据库商品行。
|
||||
// 形状照后管京东数据库列表行裁剪(选品面板只需要主字段,attr/detail 不下发)。
|
||||
|
||||
@@ -201,6 +201,8 @@ export interface PywebviewApi {
|
||||
error?: string;
|
||||
alreadyRunning?: boolean;
|
||||
}>;
|
||||
/** 京东发布独立协议:品牌单仅允许明确支持该协议的客户端创建或修改品牌重试。 */
|
||||
jd_publish_protocol?: () => Promise<number>;
|
||||
enqueue_json?: (
|
||||
data: unknown,
|
||||
) => Promise<{ success: boolean; queue_size?: number; error?: string; code?: string }>;
|
||||
|
||||
@@ -342,6 +342,8 @@ test('test_endpoints_frozen_snapshot', () => {
|
||||
// 京东商品上架:网页建单后只原样投递 queuePayload,客户端与后端负责认领。
|
||||
"jdPublish": {
|
||||
"create": "/api/jd-publish/tasks",
|
||||
"createWithTargetBrand": "/api/jd-publish/tasks/target-brand",
|
||||
"retryBrand": "/api/jd-publish/tasks/{taskId}/retry-brand",
|
||||
"products": "/api/jd-publish/products",
|
||||
"dashboard": "/api/jd-publish/dashboard",
|
||||
"history": "/api/jd-publish/history",
|
||||
|
||||
@@ -10,11 +10,13 @@ import {
|
||||
const api = vi.hoisted(() => ({
|
||||
create: vi.fn(), activate: vi.fn(), products: vi.fn(), groups: vi.fn(),
|
||||
history: vi.fn(), progress: vi.fn(), dashboard: vi.fn(), retry: vi.fn(), enqueue: vi.fn(), bridge: vi.fn(),
|
||||
protocol: vi.fn(), retryBrand: vi.fn(), alert: vi.fn(), prompt: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/shared/api/types/modules/jd-collect', () => ({ fetchJdCollectGroups: api.groups }))
|
||||
vi.mock('@/shared/api/types/modules/jd-publish', () => ({
|
||||
createJdPublishTask: api.create,
|
||||
retryJdPublishBrand: api.retryBrand,
|
||||
activateJdPublishTask: api.activate,
|
||||
fetchJdPublishDashboard: api.dashboard,
|
||||
fetchJdPublishHistory: api.history,
|
||||
@@ -29,15 +31,18 @@ vi.mock('@/shared/utils/categorized-timers.ts', () => ({
|
||||
vi.mock('element-plus', async (importOriginal) => ({
|
||||
...await importOriginal<typeof import('element-plus')>(),
|
||||
ElMessage: { success: vi.fn(), error: vi.fn() },
|
||||
ElMessageBox: { alert: api.alert, prompt: api.prompt },
|
||||
}))
|
||||
vi.mock('@/shared/api/task-retry', () => ({ retryClientTask: api.retry }))
|
||||
vi.mock('@/shared/bridges/pywebview', () => ({ getPywebviewApi: api.bridge }))
|
||||
|
||||
const queuePayload = { type: 'jd-product-publish-run', data: { taskId: 88, resumeAttempt: 0, serverOnly: true } }
|
||||
const loginError = '京麦未登录(登录态失效),请在客户端重新登录京麦后重试'
|
||||
const brandError = '目标品牌校验失败:商品「蓝牙音箱」的目标品牌「Blue-Sound」在京麦不可选(JD_BRAND_UNAVAILABLE)'
|
||||
const sourceError = '本店源商品校验失败:当前店铺找不到源商品「蓝牙音箱」,编码 SKU_12345(JD_SOURCE_NOT_FOUND)'
|
||||
|
||||
function row(taskStatus: string, resumeAttempt: number, errorMessage?: string) {
|
||||
return { taskId: 88, taskStatus, resumeAttempt, productTotal: 2, errorMessage }
|
||||
return { taskId: 88, taskStatus, resumeAttempt, productTotal: 2, successCount: 0, publishingCount: 0, errorMessage }
|
||||
}
|
||||
|
||||
function batch(item: ReturnType<typeof row>) {
|
||||
@@ -67,7 +72,8 @@ async function mountPage() {
|
||||
return wrapper
|
||||
}
|
||||
|
||||
async function startPublish(page: VueWrapper) {
|
||||
async function startPublish(page: VueWrapper, brand = ' 示例品牌 ') {
|
||||
await page.get('.target-brand-input').setValue(brand)
|
||||
await page.get<HTMLInputElement>('.product-check').setValue(true)
|
||||
await page.get('.collect-btn').trigger('click')
|
||||
await flushPromises()
|
||||
@@ -82,7 +88,9 @@ beforeEach(() => {
|
||||
api.dashboard.mockResolvedValue({ pendingTaskCount: 0, processedTaskCount: 0, successTaskCount: 0, failedTaskCount: 0 })
|
||||
api.history.mockResolvedValue({ items: [] })
|
||||
api.progress.mockResolvedValue(batch(row('PENDING', 0)))
|
||||
api.bridge.mockReturnValue({ enqueue_json: api.enqueue })
|
||||
api.bridge.mockReturnValue({ jd_publish_protocol: api.protocol, enqueue_json: api.enqueue })
|
||||
api.protocol.mockResolvedValue(3)
|
||||
api.alert.mockResolvedValue(undefined)
|
||||
api.enqueue.mockResolvedValue({ success: true })
|
||||
api.retry.mockResolvedValue(null)
|
||||
vi.spyOn(console, 'error').mockImplementation(() => undefined)
|
||||
@@ -99,21 +107,44 @@ afterEach(() => {
|
||||
it('建单只原样投递服务端载荷,网页不激活任务', async () => {
|
||||
const page = await mountPage()
|
||||
await startPublish(page)
|
||||
expect(api.create).toHaveBeenCalledOnce()
|
||||
expect(page.get('#jd-publish-brand-hint').text()).toContain('本次选中的商品统一使用此品牌,不会修改京东数据库')
|
||||
expect(api.protocol).toHaveBeenCalled()
|
||||
expect(api.create).toHaveBeenCalledExactlyOnceWith(12, [23], { mode: 'none' }, '示例品牌')
|
||||
expect(api.enqueue).toHaveBeenCalledOnce()
|
||||
expect(api.enqueue.mock.calls[0][0]).toBe(queuePayload)
|
||||
expect(api.activate).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it.each(['没有桥', '队列拒绝', '桥异常', '没有服务端载荷'])('%s时保留待认领,不拼载荷也不误报建单失败', async (failure) => {
|
||||
it.each(['没有桥', '旧桥', '旧协议', '字符串协议', '未知协议', '协议异常'])('%s不允许建品牌单', async (failure) => {
|
||||
if (failure === '没有桥') api.bridge.mockReturnValue(undefined)
|
||||
if (failure === '旧桥') api.bridge.mockReturnValue({ enqueue_json: api.enqueue })
|
||||
if (failure === '旧协议') api.protocol.mockResolvedValue(2)
|
||||
if (failure === '字符串协议') api.protocol.mockResolvedValue('3')
|
||||
if (failure === '未知协议') api.protocol.mockResolvedValue(4)
|
||||
if (failure === '协议异常') api.protocol.mockRejectedValue(new Error('bridge unavailable'))
|
||||
const page = await mountPage()
|
||||
await startPublish(page)
|
||||
expect(api.create).not.toHaveBeenCalled()
|
||||
expect(api.enqueue).not.toHaveBeenCalled()
|
||||
expect(page.text()).toContain('升级')
|
||||
})
|
||||
|
||||
it.each([' ', '品'.repeat(121)])('目标品牌名空白或超长时不建单', async (brand) => {
|
||||
const page = await mountPage()
|
||||
await startPublish(page, brand)
|
||||
expect(page.get<HTMLButtonElement>('.collect-btn').element.disabled).toBe(true)
|
||||
expect(api.create).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it.each(['没有入队方法', '队列拒绝', '桥异常', '没有服务端载荷'])('%s时保留待认领,不拼载荷也不误报建单失败', async (failure) => {
|
||||
if (failure === '没有入队方法') api.bridge.mockReturnValue({ jd_publish_protocol: api.protocol })
|
||||
if (failure === '队列拒绝') api.enqueue.mockResolvedValue({ success: false, error: 'queue rejected' })
|
||||
if (failure === '桥异常') api.enqueue.mockRejectedValue(new Error('bridge unavailable'))
|
||||
if (failure === '没有服务端载荷') api.create.mockResolvedValue({ taskId: 88 })
|
||||
const page = await mountPage()
|
||||
await startPublish(page)
|
||||
expect(api.activate).not.toHaveBeenCalled()
|
||||
if (failure === '没有桥' || failure === '没有服务端载荷') expect(api.enqueue).not.toHaveBeenCalled()
|
||||
if (failure === '没有入队方法' || failure === '没有服务端载荷') expect(api.enqueue).not.toHaveBeenCalled()
|
||||
expect(page.get('.feedback').text()).toContain('任务已创建')
|
||||
expect(page.get('.feedback').text()).toContain('客户端')
|
||||
expect(page.get('.status').text()).toContain('等待本机客户端领取')
|
||||
@@ -134,7 +165,7 @@ it('切换分类后迟到的旧商品列表不能再参与勾选', async () => {
|
||||
await flushPromises()
|
||||
expect(page.get('.product-title').text()).toBe('新分类商品')
|
||||
await startPublish(page)
|
||||
expect(api.create).toHaveBeenCalledExactlyOnceWith(13, [24], { mode: 'none' })
|
||||
expect(api.create).toHaveBeenCalledExactlyOnceWith(13, [24], { mode: 'none' }, '示例品牌')
|
||||
})
|
||||
|
||||
it('全选和取消只影响本页,其他页勾选保留', async () => {
|
||||
@@ -147,9 +178,10 @@ it('全选和取消只影响本页,其他页勾选保留', async () => {
|
||||
await page.get('.product-select-page').setValue(true)
|
||||
expect(page.get('.collect-btn').text()).toContain('2 个商品')
|
||||
await page.get('.product-select-page').setValue(false)
|
||||
await page.get('.target-brand-input').setValue('示例品牌')
|
||||
await page.get('.collect-btn').trigger('click')
|
||||
await flushPromises()
|
||||
expect(api.create).toHaveBeenCalledExactlyOnceWith(12, [23], { mode: 'none' })
|
||||
expect(api.create).toHaveBeenCalledExactlyOnceWith(12, [23], { mode: 'none' }, '示例品牌')
|
||||
})
|
||||
|
||||
it('原位重试只由兜底认领,迟到的旧代终态不能停掉轮询或弹窗', async () => {
|
||||
@@ -189,3 +221,88 @@ it('原位重试只由兜底认领,迟到的旧代终态不能停掉轮询或
|
||||
expect(takeCredentialFatal()?.notice.body).toContain('请在客户端重新登录京麦')
|
||||
expect(localStorage.getItem('jd-publish:tasks:0')).toBeNull()
|
||||
})
|
||||
|
||||
it('轮询只凭任务头识别失败,历史和重复轮询不重弹,新代可再弹', async () => {
|
||||
localStorage.setItem('jd-publish:tasks:0', '[88]')
|
||||
api.history.mockResolvedValue({ items: [row('RUNNING', 3)] })
|
||||
const progress = batch(row('FAILED', 3, brandError))
|
||||
progress.items[0].items[0].errorMessage = undefined
|
||||
api.progress.mockResolvedValue(progress)
|
||||
const page = await mountPage()
|
||||
expect(api.alert).toHaveBeenCalledTimes(1)
|
||||
expect(api.alert.mock.calls[0].join(' ')).toContain('商品「蓝牙音箱」的目标品牌「Blue-Sound」在京麦不可选')
|
||||
expect(api.alert.mock.calls[0].join(' ')).not.toContain('JD_BRAND_UNAVAILABLE')
|
||||
await page.get('.history-btn').trigger('click')
|
||||
expect(page.get('.btn-retry').text()).toBe('修改品牌并重试')
|
||||
expect(page.text()).toContain('商品「蓝牙音箱」的目标品牌「Blue-Sound」在京麦不可选')
|
||||
expect(page.text()).not.toContain('JD_BRAND_UNAVAILABLE')
|
||||
|
||||
api.history.mockResolvedValue({ items: [row('FAILED', 3, brandError)] })
|
||||
await page.get('.panel-refresh').trigger('click')
|
||||
await flushPromises()
|
||||
expect(api.alert).toHaveBeenCalledTimes(1)
|
||||
|
||||
api.history.mockResolvedValue({ items: [row('FAILED', 4, brandError)] })
|
||||
await page.get('.panel-refresh').trigger('click')
|
||||
await flushPromises()
|
||||
expect(api.alert).toHaveBeenCalledTimes(2)
|
||||
})
|
||||
|
||||
it('修改品牌走专用原位重试,原样投递新载荷并拒绝旧代进度', async () => {
|
||||
api.history.mockResolvedValue({ items: [row('FAILED', 3, brandError)] })
|
||||
api.progress.mockResolvedValue(batch(row('FAILED', 3, brandError)))
|
||||
api.prompt.mockResolvedValue({ value: ' 新品牌 ' })
|
||||
const retryPayload = { ...queuePayload, data: { taskId: 88, resumeAttempt: 4, serverOnly: true } }
|
||||
api.retryBrand.mockResolvedValue({ taskId: 88, queuePayload: retryPayload })
|
||||
const page = await mountPage()
|
||||
await page.get('.history-btn').trigger('click')
|
||||
await page.get('.btn-retry').trigger('click')
|
||||
await flushPromises()
|
||||
expect(api.prompt).toHaveBeenCalledOnce()
|
||||
expect(api.retryBrand).toHaveBeenCalledExactlyOnceWith(88, '新品牌', 3)
|
||||
expect(api.enqueue.mock.calls[0][0]).toBe(retryPayload)
|
||||
expect(api.retry).not.toHaveBeenCalled()
|
||||
expect(api.create).not.toHaveBeenCalled()
|
||||
expect(api.alert).toHaveBeenCalledTimes(1)
|
||||
expect(localStorage.getItem('jd-publish:tasks:0')).toBe('[88]')
|
||||
})
|
||||
|
||||
it('旧桥不允许修改品牌并重试', async () => {
|
||||
api.bridge.mockReturnValue({ enqueue_json: api.enqueue })
|
||||
api.history.mockResolvedValue({ items: [row('FAILED', 0, brandError)] })
|
||||
const page = await mountPage()
|
||||
await page.get('.history-btn').trigger('click')
|
||||
await page.get('.btn-retry').trigger('click')
|
||||
await flushPromises()
|
||||
expect(api.prompt).not.toHaveBeenCalled()
|
||||
expect(api.retryBrand).not.toHaveBeenCalled()
|
||||
expect(api.retry).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it.each([{ successCount: 1 }, { publishingCount: 1 }])('已有成功或待确认时禁止品牌重试:%o', async (counts) => {
|
||||
api.history.mockResolvedValue({ items: [{ ...row('FAILED', 3, brandError), ...counts }] })
|
||||
const page = await mountPage()
|
||||
await page.get('.history-btn').trigger('click')
|
||||
expect(page.find('.btn-retry').exists()).toBe(false)
|
||||
expect(page.text()).toContain('核对京麦')
|
||||
expect(page.text()).toContain('未发布商品')
|
||||
expect(page.text()).not.toContain('JD_BRAND_UNAVAILABLE')
|
||||
})
|
||||
|
||||
it('源商品失败提示换店或重选,并保留普通原位重试', async () => {
|
||||
api.history.mockResolvedValue({ items: [row('FAILED', 0, sourceError)] })
|
||||
const page = await mountPage()
|
||||
await page.get('.history-btn').trigger('click')
|
||||
expect(page.text()).toContain('正确店铺')
|
||||
expect(page.text()).toContain('重新选择')
|
||||
expect(page.text()).toContain('当前店铺找不到源商品「蓝牙音箱」,编码 SKU_12345')
|
||||
expect(page.text()).not.toContain('JD_SOURCE_NOT_FOUND')
|
||||
expect(api.alert).toHaveBeenCalledOnce()
|
||||
expect(api.alert.mock.calls[0].join(' ')).toContain('当前店铺找不到源商品「蓝牙音箱」,编码 SKU_12345')
|
||||
expect(api.alert.mock.calls[0].join(' ')).not.toContain('JD_SOURCE_NOT_FOUND')
|
||||
expect(page.get('.btn-retry').text()).toBe('重试')
|
||||
await page.get('.btn-retry').trigger('click')
|
||||
await flushPromises()
|
||||
expect(api.retry).toHaveBeenCalledExactlyOnceWith(88)
|
||||
expect(api.retryBrand).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user