fix(定时匹配): 入队前接上 dispatch-guard——只补缺键那道,在售不弹窗
上一轮给产品风险补闸时把这支记成「同源没改」。复算后拆成两半: - 缺筛选值确实同源。match_action.py:371 判空那三行与 approve.py 逐字同形, 拿到 '' 会去页面上找 value='' 的选项、必然 0 行、再以「没有需要审批的商品」 正常收尾;这一支的两个推送口(手动启动、定时泵)过去一个闸都没接, 缺 taskId/空店铺/NaN 也是原样推过去让任务卡在執行中。现在都过 checkQueuePayload。 - 「在售要签字」不成立:shopMatchListingFilter 的默认值就是 Active,这一支的主用途 正是给在售商品匹配价格。套过去等于每天默认发起签一次字,只会教会用户闭眼点。 所以缺键判据收进 listingFilters 共用,confirm 仍只归产品风险,问题码按支分开。 定时泵没人签字,只认 guard.ok 并抛错交外层如实报错,绝不弹窗。 新增 8 例(含两枚接线钉),并做过反例自证:把两处闸摘掉,接线钉当场判红。
This commit is contained in:
@@ -124,7 +124,9 @@ import { ElMessage } from 'element-plus'
|
||||
import AmazonToolPageShell from '@/pages/amazon/components/AmazonToolPageShell.vue';
|
||||
import TaskCenterPanel from '@/shared/components/tasks/TaskCenterPanel.vue'
|
||||
import type { TaskItemView, TaskStatCard } from '@/shared/components/tasks/types'
|
||||
import { LISTING_FILTER_OPTIONS, type ListingFilterValue } from '@/pages/brand/components/listingFilters'
|
||||
import { LISTING_FILTER_OPTIONS, RISK_LISTING_FILTER_KEY, shopMatchFilterIssues, type ListingFilterValue } from '@/pages/brand/components/listingFilters'
|
||||
import { checkQueuePayload } from '@/shared/dispatch-guard'
|
||||
import { passGuard } from '@/shared/dispatch-guard-ui'
|
||||
import { activateShopMatchTask, addShopMatchCandidate, createShopMatchTask, deleteShopMatchCandidate, deleteShopMatchHistory, deleteShopMatchTask, getShopMatchCountryPreference, getShopMatchDashboard, getShopMatchHistory, getShopMatchResultDownloadUrl, getShopMatchTaskProgressBatch, listShopMatchCandidates, matchShopMatchShops, putShopMatchCountryPreference, type ShopMatchCandidateVo, type ShopMatchCreateTaskItem, type ShopMatchDashboardVo, type ShopMatchHistoryItem, type ShopMatchShopQueueItem, type ShopMatchTaskDetailVo } from '@/shared/api/java-modules'
|
||||
import { getPollingProgressBatch } from '@/shared/api/task-progress-polling.ts'
|
||||
import { liveProgress } from '@/shared/api/task-progress-live.ts'
|
||||
@@ -433,8 +435,27 @@ function buildQueuePayload(taskId: number, item: Pick<ShopMatchHistoryItem, 'sho
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 入队前的最后一道闸。这一支过去两个推送口都没接 dispatch-guard:payload 缺 taskId、
|
||||
* 店铺/国家列表为空、或混进 NaN(序列化后静默变 null)都会原样推给 Python,
|
||||
* 任务停在执行中且不报错。
|
||||
*
|
||||
* 「商品列表筛选」为空的后果更具体:match_action 拿到 '' 会去页面上找一个 value='' 的
|
||||
* 选项,必然 0 行,而 0 行在它那儿算正常收尾(`len(sku_ls) == 0` 直接 return),
|
||||
* 于是整单看着跑完了、实际一行都没匹配。
|
||||
* 在售不弹窗:那是这一支的默认值,也是它的主用途——天天要签字的弹窗只会教会用户闭眼点。
|
||||
*/
|
||||
function shopMatchPayloadGuard(payload: unknown) {
|
||||
return checkQueuePayload(payload, {
|
||||
expectedType: 'shop-match-run',
|
||||
requiredDataKeys: ['taskId'],
|
||||
nonEmptyArrayKeys: ['items', 'country_codes'],
|
||||
extraIssues: (data) => shopMatchFilterIssues(data[RISK_LISTING_FILTER_KEY]),
|
||||
})
|
||||
}
|
||||
function nextScheduleStage(taskId: number) { const task = taskSnapshots.value[taskId]?.task; const stages = task?.scheduleStages || []; const currentStageIndex = task?.currentStageIndex; if (typeof currentStageIndex !== 'number') return null; const stage = stages.find((item) => item.stageIndex === currentStageIndex); if (!stage?.scheduledAt) return null; return { stageIndex: currentStageIndex, scheduledAt: stage.scheduledAt, finalStage: currentStageIndex === stages.length - 1 } }
|
||||
async function dispatchScheduledTask(taskId: number, item: ShopMatchHistoryItem) { const api = getPywebviewApi(); if (!api?.enqueue_json) throw new Error('当前客户端未提供 enqueue_json'); const stage = nextScheduleStage(taskId); const snapshot = taskSnapshots.value[taskId]; const countryCodes = snapshot?.task?.countryCodes || orderedCountryCodes.value; if (!stage) throw new Error(`任务 ${taskId} 缺少待执行阶段`); clearDispatchTimer(taskId); await withTransientRetry(() => activateShopMatchTask(taskId, stage.stageIndex), (attempt, maxAttempts) => { queuePushResult.value = `任务 ${taskId} 等待服务恢复后再激活执行(${attempt}/${maxAttempts})...` }); taskDetails.value = { ...taskDetails.value, [taskId]: 'RUNNING' }; if (snapshot?.task) taskSnapshots.value = { ...taskSnapshots.value, [taskId]: { ...snapshot, task: { ...snapshot.task, status: 'RUNNING', activeStageIndex: stage.stageIndex } } }; triggerRef(taskSnapshots); saveTaskSnapshotsToStorage(); saveTaskDetailsToStorage(); const payload = buildQueuePayload(taskId, item, countryCodes, stage.stageIndex, stage.finalStage); queuePayloadText.value = JSON.stringify(payload, null, 2); const result = await api.enqueue_json(payload); if (!result?.success) throw new Error(result?.error || `任务 ${taskId} 启动失败`); addPollingTask(taskId); queuePushResult.value = `任务 ${taskId} 已启动第 ${stage.stageIndex + 1} 轮`; ensurePolling(true) }
|
||||
async function dispatchScheduledTask(taskId: number, item: ShopMatchHistoryItem) { const api = getPywebviewApi(); if (!api?.enqueue_json) throw new Error('当前客户端未提供 enqueue_json'); const stage = nextScheduleStage(taskId); const snapshot = taskSnapshots.value[taskId]; const countryCodes = snapshot?.task?.countryCodes || orderedCountryCodes.value; if (!stage) throw new Error(`任务 ${taskId} 缺少待执行阶段`); clearDispatchTimer(taskId); await withTransientRetry(() => activateShopMatchTask(taskId, stage.stageIndex), (attempt, maxAttempts) => { queuePushResult.value = `任务 ${taskId} 等待服务恢复后再激活执行(${attempt}/${maxAttempts})...` }); taskDetails.value = { ...taskDetails.value, [taskId]: 'RUNNING' }; if (snapshot?.task) taskSnapshots.value = { ...taskSnapshots.value, [taskId]: { ...snapshot, task: { ...snapshot.task, status: 'RUNNING', activeStageIndex: stage.stageIndex } } }; triggerRef(taskSnapshots); saveTaskSnapshotsToStorage(); saveTaskDetailsToStorage(); const payload = buildQueuePayload(taskId, item, countryCodes, stage.stageIndex, stage.finalStage); queuePayloadText.value = JSON.stringify(payload, null, 2); const guard = shopMatchPayloadGuard(payload); if (!guard.ok) throw new Error(`任务 ${taskId} 数据校验未通过,已阻止启动:${guard.message}`); const result = await api.enqueue_json(payload); if (!result?.success) throw new Error(result?.error || `任务 ${taskId} 启动失败`); addPollingTask(taskId); queuePushResult.value = `任务 ${taskId} 已启动第 ${stage.stageIndex + 1} 轮`; ensurePolling(true) }
|
||||
function scheduledTimestamp(value?: string) { const date = parseScheduleDateTime(value); return date ? date.getTime() : Number.NaN }
|
||||
function findReadyScheduledTasks() { const taskIds = new Set<number>(pollingTaskIds.value); for (const key of Object.keys(taskSnapshots.value)) { const id = normalizeTaskId(key); if (id > 0) taskIds.add(id) } for (const item of historyItems.value) { const id = normalizeTaskId(item.taskId); if (id > 0) taskIds.add(id) } const ready = Array.from(taskIds).map((taskId) => { const snapshot = taskSnapshots.value[taskId]; const taskStatus = taskDetails.value[taskId] || snapshot?.task?.status; const item = snapshot?.items?.[0] || historyItems.value.find((row) => normalizeTaskId(row.taskId) === taskId); const stage = nextScheduleStage(taskId); if (taskStatus !== 'SCHEDULED' || !item || !stage?.scheduledAt) return null; const scheduledTime = scheduledTimestamp(stage.scheduledAt); if (!Number.isFinite(scheduledTime) || scheduledTime > Date.now()) return null; return { taskId, item, scheduledTime } }).filter((item): item is { taskId: number; item: ShopMatchHistoryItem; scheduledTime: number } => !!item); ready.sort((a, b) => a.scheduledTime - b.scheduledTime || a.taskId - b.taskId); return ready }
|
||||
async function pumpScheduledQueue() {
|
||||
@@ -644,7 +665,7 @@ function formatMatchStatus(status?: string) { const value = (status || '').trim(
|
||||
function formatMatchRemark(row: ShopMatchShopQueueItem) { const message = (row.matchMessage || '').trim(); if (message) return message; if (row.matched && row.matchStatus === 'MATCHED') return '已匹配成功,可启动任务'; if (row.matched) return '已关联店铺,请查看状态确认'; if (row.matchStatus === 'CONFLICT') return '存在多个同名店铺,请人工确认'; if (row.matchStatus === 'PENDING') return '店铺尚未匹配完成,请稍后查看'; return '未匹配成功,请检查店铺名' }
|
||||
async function pushToPythonQueue() { autoQueueEnabled.value = true; await processMatchedQueue() }
|
||||
function nextMatchedQueueItem() { return matchedItems.value.find((item) => item.matched) }
|
||||
async function processMatchedQueue() { if (disposed || queueWorkerRunning.value) return; const api = getPywebviewApi(); if (!api?.enqueue_json) { ElMessage.error('当前客户端未提供 enqueue_json'); return } const matched = matchedItems.value.filter((item) => item.matched); if (!matched.length) { ElMessage.warning('请先匹配可用店铺'); return } if (!orderedCountryCodes.value.length) { ElMessage.warning('请至少勾选一个国家'); return } let scheduleValues: string[] | undefined; try { scheduleValues = parseScheduleValues() } catch (error) { ElMessage.error(error instanceof Error ? error.message : '定时配置无效'); return } queueWorkerRunning.value = true; pushing.value = true; queuePayloadText.value = ''; let successCount = 0; let failedCount = 0; let index = 0; try { while (!disposed && autoQueueEnabled.value) { const item = nextMatchedQueueItem(); if (!item) break; index += 1; try { const created = await withTransientRetry(() => createShopMatchTask([buildTaskCreateItem(item)], orderedCountryCodes.value, scheduleValues), (attempt, maxAttempts) => { queuePushResult.value = `服务暂时不可用,正在重试创建任务(${attempt}/${maxAttempts})...` }); const taskId = created.taskId; const initialStatus = scheduleValues?.length ? 'SCHEDULED' : 'RUNNING'; const snapshot: ShopMatchTaskDetailVo = { task: { id: taskId, status: initialStatus, scheduledAt: scheduleValues?.[0], countryCodes: [...orderedCountryCodes.value], currentStageIndex: scheduleValues?.length ? 0 : undefined, activeStageIndex: undefined, scheduleStages: (scheduleValues || []).map((value, stageIndex) => ({ stageIndex, scheduledAt: value, status: stageIndex === 0 ? 'SCHEDULED' : 'PENDING' })) }, items: created.items }; taskSnapshots.value = { ...taskSnapshots.value, [taskId]: snapshot }; triggerRef(taskSnapshots); taskDetails.value = { ...taskDetails.value, [taskId]: initialStatus }; saveTaskSnapshotsToStorage(); saveTaskDetailsToStorage(); const createdItem = created.items?.[0]; if (!createdItem) { removeMatchedRowsLocally([item]); continue } if (scheduleValues?.length) { successCount += 1; restoreScheduledDispatches(); queuePushResult.value = `任务 ${taskId} 已创建,共 ${scheduleValues.length} 个执行时间点`; removeMatchedRowsLocally([item]); continue } const payload = buildQueuePayload(taskId, item, orderedCountryCodes.value); queuePayloadText.value = JSON.stringify(payload, null, 2); const result = await api.enqueue_json(payload); if (!result?.success) { failedCount += 1; queuePushResult.value = `任务 ${taskId} 启动失败,已自动继续下一条:${userNotice(result?.error || '未知错误')}`; ElMessage.error(queuePushResult.value); removeMatchedRowsLocally([item]); continue } addPollingTask(taskId); ensurePolling(true); removeMatchedRowsLocally([item]); queuePushResult.value = `任务 ${taskId} 已提交,等待执行完成`; const finalStatus = await waitForTaskTerminal(taskId); if (finalStatus !== 'SUCCESS') { failedCount += 1; queuePushResult.value = `任务 ${taskId} 执行失败,已自动继续下一条`; ElMessage.error(queuePushResult.value); continue } successCount += 1; queuePushResult.value = `任务 ${taskId} 已完成` } catch (error) { if (disposed) break; failedCount += 1; queuePushResult.value = `第 ${index} 条任务处理失败,已自动继续下一条:${userNotice(error instanceof Error ? error.message : '未知错误')}`; ElMessage.error(queuePushResult.value); removeMatchedRowsLocally([item]); continue } } restoreScheduledDispatches(); if (!scheduleValues?.length) ensurePolling(true); if (!disposed && (successCount > 0 || failedCount > 0)) ElMessage.success(scheduleValues?.length ? `定时任务已创建:成功 ${successCount} 条,失败 ${failedCount} 条` : `店铺启动已完成:成功 ${successCount} 条,失败 ${failedCount} 条`) } catch (error) { if (disposed) return; const message = error instanceof Error ? error.message : '启动失败'; queuePushResult.value = message; ElMessage.error(message) } finally { queueWorkerRunning.value = false; pushing.value = false } }
|
||||
async function processMatchedQueue() { if (disposed || queueWorkerRunning.value) return; const api = getPywebviewApi(); if (!api?.enqueue_json) { ElMessage.error('当前客户端未提供 enqueue_json'); return } const matched = matchedItems.value.filter((item) => item.matched); if (!matched.length) { ElMessage.warning('请先匹配可用店铺'); return } if (!orderedCountryCodes.value.length) { ElMessage.warning('请至少勾选一个国家'); return } let scheduleValues: string[] | undefined; try { scheduleValues = parseScheduleValues() } catch (error) { ElMessage.error(error instanceof Error ? error.message : '定时配置无效'); return } queueWorkerRunning.value = true; pushing.value = true; queuePayloadText.value = ''; let successCount = 0; let failedCount = 0; let index = 0; try { while (!disposed && autoQueueEnabled.value) { const item = nextMatchedQueueItem(); if (!item) break; index += 1; try { const created = await withTransientRetry(() => createShopMatchTask([buildTaskCreateItem(item)], orderedCountryCodes.value, scheduleValues), (attempt, maxAttempts) => { queuePushResult.value = `服务暂时不可用,正在重试创建任务(${attempt}/${maxAttempts})...` }); const taskId = created.taskId; const initialStatus = scheduleValues?.length ? 'SCHEDULED' : 'RUNNING'; const snapshot: ShopMatchTaskDetailVo = { task: { id: taskId, status: initialStatus, scheduledAt: scheduleValues?.[0], countryCodes: [...orderedCountryCodes.value], currentStageIndex: scheduleValues?.length ? 0 : undefined, activeStageIndex: undefined, scheduleStages: (scheduleValues || []).map((value, stageIndex) => ({ stageIndex, scheduledAt: value, status: stageIndex === 0 ? 'SCHEDULED' : 'PENDING' })) }, items: created.items }; taskSnapshots.value = { ...taskSnapshots.value, [taskId]: snapshot }; triggerRef(taskSnapshots); taskDetails.value = { ...taskDetails.value, [taskId]: initialStatus }; saveTaskSnapshotsToStorage(); saveTaskDetailsToStorage(); const createdItem = created.items?.[0]; if (!createdItem) { removeMatchedRowsLocally([item]); continue } if (scheduleValues?.length) { successCount += 1; restoreScheduledDispatches(); queuePushResult.value = `任务 ${taskId} 已创建,共 ${scheduleValues.length} 个执行时间点`; removeMatchedRowsLocally([item]); continue } const payload = buildQueuePayload(taskId, item, orderedCountryCodes.value); queuePayloadText.value = JSON.stringify(payload, null, 2); if (!(await passGuard(shopMatchPayloadGuard(payload)))) { failedCount += 1; queuePushResult.value = `任务 ${taskId} 数据校验未通过,已阻止启动`; ElMessage.error(queuePushResult.value); break } const result = await api.enqueue_json(payload); if (!result?.success) { failedCount += 1; queuePushResult.value = `任务 ${taskId} 启动失败,已自动继续下一条:${userNotice(result?.error || '未知错误')}`; ElMessage.error(queuePushResult.value); removeMatchedRowsLocally([item]); continue } addPollingTask(taskId); ensurePolling(true); removeMatchedRowsLocally([item]); queuePushResult.value = `任务 ${taskId} 已提交,等待执行完成`; const finalStatus = await waitForTaskTerminal(taskId); if (finalStatus !== 'SUCCESS') { failedCount += 1; queuePushResult.value = `任务 ${taskId} 执行失败,已自动继续下一条`; ElMessage.error(queuePushResult.value); continue } successCount += 1; queuePushResult.value = `任务 ${taskId} 已完成` } catch (error) { if (disposed) break; failedCount += 1; queuePushResult.value = `第 ${index} 条任务处理失败,已自动继续下一条:${userNotice(error instanceof Error ? error.message : '未知错误')}`; ElMessage.error(queuePushResult.value); removeMatchedRowsLocally([item]); continue } } restoreScheduledDispatches(); if (!scheduleValues?.length) ensurePolling(true); if (!disposed && (successCount > 0 || failedCount > 0)) ElMessage.success(scheduleValues?.length ? `定时任务已创建:成功 ${successCount} 条,失败 ${failedCount} 条` : `店铺启动已完成:成功 ${successCount} 条,失败 ${failedCount} 条`) } catch (error) { if (disposed) return; const message = error instanceof Error ? error.message : '启动失败'; queuePushResult.value = message; ElMessage.error(message) } finally { queueWorkerRunning.value = false; pushing.value = false } }
|
||||
onMounted(async () => { loadPollingIdsFromStorage(); loadTaskDetailsFromStorage(); loadTaskSnapshotsFromStorage(); loadMatchedItemsFromStorage(); schedulePickerValues.value = sanitizeSchedulePickerValues(schedulePickerValues.value, scheduleEnabled.value); syncPollingIdsWithTaskState(); await Promise.allSettled([loadCandidates(), loadCountryPreference(), loadHistory(), loadDashboard()]); window.addEventListener('focus', handleScheduleRecovery); document.addEventListener('visibilitychange', handleScheduleRecovery); restoreScheduledDispatches(); if (pollingTaskIds.value.length) ensurePolling(true) })
|
||||
onUnmounted(() => { disposed = true; stopPolling(); stopScheduleHeartbeat(); clearSleepTimers(); window.removeEventListener('focus', handleScheduleRecovery); document.removeEventListener('visibilitychange', handleScheduleRecovery); if (countryPrefSaveTimer) timers.clearTimer('preference-save', countryPrefSaveTimer); for (const timer of dispatchTimers.values()) timers.clearTimer('scheduled-dispatch', timer); dispatchTimers.clear(); timers.clearScope() })
|
||||
|
||||
|
||||
@@ -24,24 +24,45 @@ function listingFilterLabel(value: string): string {
|
||||
return LISTING_FILTER_OPTIONS.find((opt) => opt.value === value)?.label || value
|
||||
}
|
||||
|
||||
function filterValue(filter: unknown): string {
|
||||
return typeof filter === 'string' ? filter.trim() : ''
|
||||
}
|
||||
|
||||
/**
|
||||
* 产品风险审批的筛选值判据:缺键/空串 = block(Python 端会拿它去页面上找一个 value="" 的
|
||||
* 选项,必然落空并以「没有需要审批的商品」假成功收尾);非风险状态 = confirm。
|
||||
* 缺键/空串 = block:客户端拿到空值会去页面上找一个 value="" 的筛选选项,必然落空,
|
||||
* 返回 0 行却把 search_success 置真 ⇒ 整国以「没有需要审批的商品」正常收尾(假成功)。
|
||||
* 这一条产品风险与定时匹配共用:两边的 process_country 判空写法逐字同形
|
||||
* (app_client/amazon/approve.py 与 match_action.py 里那句 `len(sku_ls) == 0` 直接 return)。
|
||||
* 文案按各支自己的空跑说法分开写,共用一句会把其中一支的说辞安到另一支头上。
|
||||
*/
|
||||
function missingFilterIssue(scope: string, emptyRunPhrase: string): GuardIssue[] {
|
||||
return [{
|
||||
code: `${scope}.filter-missing`,
|
||||
severity: 'block',
|
||||
message:
|
||||
`任务数据缺少「商品列表筛选」(${RISK_LISTING_FILTER_KEY}),已阻止启动。\n` +
|
||||
`Python 端拿到空值会去页面上找一个不存在的筛选选项,整国以「${emptyRunPhrase}」空跑收尾。\n` +
|
||||
'请先在「商品列表筛选」里选择状态,再点启动任务。',
|
||||
}]
|
||||
}
|
||||
|
||||
/**
|
||||
* 跟价/定时匹配那一支的「在售」是默认值也是主用途(给在售商品匹配价格),
|
||||
* 所以这一支只在缺键时拦下,不该为在售弹窗——默认值天天要签字,用户只会学会闭眼点。
|
||||
*/
|
||||
export function shopMatchFilterIssues(filter: unknown): GuardIssue[] {
|
||||
if (filterValue(filter)) return []
|
||||
return missingFilterIssue('shop-match', '没有需要审批的商品')
|
||||
}
|
||||
|
||||
/**
|
||||
* 产品风险审批的筛选值判据:缺键/空串 = block;非风险状态 = confirm。
|
||||
* 返回的是 dispatch-guard 的 GuardIssue 形状,由 checkQueuePayload 的 extraIssues 承接,
|
||||
* ok/needsConfirm 与「有 block 就不展示 confirm」那条规则不在这里重复解释。
|
||||
*/
|
||||
export function productRiskFilterIssues(filter: unknown): GuardIssue[] {
|
||||
const value = typeof filter === 'string' ? filter.trim() : ''
|
||||
if (!value) {
|
||||
return [{
|
||||
code: 'product-risk.filter-missing',
|
||||
severity: 'block',
|
||||
message:
|
||||
`任务数据缺少「商品列表筛选」(${RISK_LISTING_FILTER_KEY}),已阻止启动。\n` +
|
||||
'Python 端拿到空值会去页面上找一个不存在的筛选选项,整国以「没有需要审批的商品」空跑收尾。\n' +
|
||||
'请先在「商品列表筛选」里选择状态,再点启动任务。',
|
||||
}]
|
||||
}
|
||||
const value = filterValue(filter)
|
||||
if (!value) return missingFilterIssue('product-risk', '没有需要审批的商品')
|
||||
if ((NON_RISK_LISTING_FILTERS as readonly string[]).includes(value)) {
|
||||
return [{
|
||||
code: 'product-risk.filter-not-risk',
|
||||
|
||||
Reference in New Issue
Block a user