diff --git a/frontend-vue/src/pages/brand/components/BrandShopMatchTab.vue b/frontend-vue/src/pages/brand/components/BrandShopMatchTab.vue index aa72771c4..f30db06c4 100644 --- a/frontend-vue/src/pages/brand/components/BrandShopMatchTab.vue +++ b/frontend-vue/src/pages/brand/components/BrandShopMatchTab.vue @@ -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 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(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() }) diff --git a/frontend-vue/src/pages/brand/components/listingFilters.ts b/frontend-vue/src/pages/brand/components/listingFilters.ts index a1a03c943..8bea86b67 100644 --- a/frontend-vue/src/pages/brand/components/listingFilters.ts +++ b/frontend-vue/src/pages/brand/components/listingFilters.ts @@ -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', diff --git a/frontend-vue/tests/shop-match-payload-guard.test.ts b/frontend-vue/tests/shop-match-payload-guard.test.ts new file mode 100644 index 000000000..eb1679ca4 --- /dev/null +++ b/frontend-vue/tests/shop-match-payload-guard.test.ts @@ -0,0 +1,144 @@ +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { readFileSync } from 'node:fs' +import { fileURLToPath } from 'node:url' +import { resolve, dirname } from 'node:path' +import { + RISK_LISTING_FILTER_KEY, + productRiskFilterIssues, + shopMatchFilterIssues, +} from '../src/pages/brand/components/listingFilters.ts' +import { checkQueuePayload, type GuardResult } from '../src/shared/dispatch-guard.ts' + +/** + * 定时匹配(shop-match-run)入队前的闸。 + * + * 2026-10-19 给产品风险补那道闸时,这一支被记在"同源没改"的欠账里。复算后拆开处理: + * - 缺筛选值这一半确实同源:match_action.py 拿到 '' 会去页面上找 value='' 的选项, + * 必然 0 行,而它判空的写法与 approve.py 逐字同形(`len(sku_ls) == 0` 直接 return), + * 整单看着跑完、实际一行没匹配 ⇒ 照样拦。 + * - 「在售要签字」这一半不成立:shopMatchListingFilter 的默认值就是 Active, + * 这一支的主用途正是给在售商品匹配价格。给它套产品风险那份判据,等于每天默认 + * 发起都要签一次字——只会教会用户闭眼点。所以这里只接缺键那道。 + * + * .vue 组件无法在本套里挂载,接线按源码形状钉(同 enqueue-rejection-wiring 的约定)。 + */ +const here = dirname(fileURLToPath(import.meta.url)) +const shopMatchTab = readFileSync( + resolve(here, '../src/pages/brand/components/BrandShopMatchTab.vue'), 'utf8', +) + +function codes(result: GuardResult) { + return result.issues.map((issue) => issue.code) +} + +/** 与组件里 shopMatchPayloadGuard 同一份选项,改了组件不改这里 ⇒ 下面的用例判红 */ +function guard(payload: unknown) { + return checkQueuePayload(payload, { + expectedType: 'shop-match-run', + requiredDataKeys: ['taskId'], + nonEmptyArrayKeys: ['items', 'country_codes'], + extraIssues: (data) => shopMatchFilterIssues(data[RISK_LISTING_FILTER_KEY]), + }) +} + +function runPayload(data: Record) { + return { + type: 'shop-match-run', + ts: 1, + data: { + taskId: 31500, + items: [{ shopName: '蔡建芳' }], + country_codes: ['DE'], + [RISK_LISTING_FILTER_KEY]: 'Active', + ...data, + }, + } +} + +test('test_定时匹配_缺筛选值必须拦住', () => { + const issues = shopMatchFilterIssues(undefined) + assert.equal(issues.length, 1) + assert.equal(issues[0].severity, 'block', "空值到了 Python 端会 0 行假成功,不能放行") + assert.equal(issues[0].code, 'shop-match.filter-missing') + assert.match(issues[0].message, /risk_listing_filter/) + + for (const bad of ['', ' ', null, 7]) { + assert.equal(shopMatchFilterIssues(bad)[0].severity, 'block', `空值 ${String(bad)} 同样要拦`) + } +}) + +test('test_定时匹配_在售是默认值不许弹窗', () => { + assert.deepEqual(shopMatchFilterIssues('Active'), [], + '这一支的默认与主用途就是在售;套上产品风险那份 confirm 会让每次发起都弹一次字') + const result = guard(runPayload({})) + assert.equal(result.ok, true) + assert.equal(result.needsConfirm, false) + assert.deepEqual(result.issues, []) +}) + +test('test_定时匹配_整条载荷缺键时结构校验也救不回来', () => { + const withoutFilter = runPayload({}) + delete (withoutFilter.data as Record)[RISK_LISTING_FILTER_KEY] + const result = guard(withoutFilter) + assert.equal(result.ok, false, '只查 taskId/items 的结构校验拦不住缺筛选值,必须靠 extraIssues') + assert.ok(codes(result).includes('shop-match.filter-missing')) + + for (const blank of ['', ' ']) { + assert.equal(guard(runPayload({ [RISK_LISTING_FILTER_KEY]: blank })).ok, false, + `空串 ${JSON.stringify(blank)} 与缺键同形:键在但值为空,Python 端照样拿它去 search('')`) + } +}) + +test('test_定时匹配_空店铺与空国家照样拦下', () => { + assert.equal(guard(runPayload({ items: [] })).ok, false) + assert.equal(guard(runPayload({ country_codes: [] })).ok, false) + assert.ok(codes(guard(runPayload({ items: [], country_codes: [] }))).includes('payload.empty-array')) +}) + +test('test_定时匹配_任务号缺失与NaN都拦下', () => { + const noTaskId = runPayload({}) + delete (noTaskId.data as Record).taskId + assert.equal(guard(noTaskId).ok, false) + assert.equal(guard(runPayload({ taskId: Number.NaN })).ok, false, + 'NaN 序列化后是 null,Python 端拿到空任务号会一直卡在执行中') +}) + +test('test_两支共用的缺键判据各认各的出处', () => { + assert.equal(shopMatchFilterIssues('')[0].code, 'shop-match.filter-missing') + assert.equal(productRiskFilterIssues('')[0].code, 'product-risk.filter-missing', + '文案与问题码按支分开:产品风险那条被日志/用例认过,不能因为复用而改名') + // 产品风险仍然对在售要签字,定时匹配不签——这份差异就是本次复算的结论 + assert.equal(productRiskFilterIssues('Active')[0].severity, 'confirm') + assert.deepEqual(shopMatchFilterIssues('Active'), []) +}) + +function bodyOf(source: string, startMarker: string, endMarker: string) { + const start = source.indexOf(startMarker) + assert.notEqual(start, -1, `组件里找不到 ${startMarker}`) + const end = source.indexOf(endMarker, start) + assert.notEqual(end, -1, `组件里找不到 ${endMarker}`) + return source.slice(start, end) +} + +test('test_定时匹配_手动启动口先过闸再入队', () => { + const fn = bodyOf(shopMatchTab, 'async function processMatchedQueue', 'async function batchDeleteHistory') + const guardAt = fn.indexOf('passGuard(shopMatchPayloadGuard(payload))') + assert.notEqual(guardAt, -1, '手动启动口没过闸') + const enqueueAt = fn.indexOf('api.enqueue_json(payload)') + assert.notEqual(enqueueAt, -1, '找不到推送语句') + assert.ok(guardAt < enqueueAt, '闸必须跑在推送之前') + assert.match(fn.slice(guardAt, enqueueAt), /break/, + '店铺列表共用同一份筛选值与国家,拦下一条就该整批停手,不该逐店再弹一次') +}) + +test('test_定时匹配_定时口无人签字只认阻断项', () => { + const fn = bodyOf(shopMatchTab, 'async function dispatchScheduledTask', 'function scheduledTimestamp') + const guardAt = fn.indexOf('shopMatchPayloadGuard(payload)') + assert.notEqual(guardAt, -1, '定时执行口没过闸') + const enqueueAt = fn.indexOf('api.enqueue_json(payload)') + assert.ok(guardAt < enqueueAt, '闸必须跑在推送之前') + assert.doesNotMatch(fn, /passGuard\(/, + '定时口没有人在屏幕前,弹窗会把这一轮卡住;只按 guard.ok 抛错,交给外层如实报错') + assert.match(fn, /if \(!guard\.ok\) throw/, '不通过要抛错,让这一轮留下失败原因而不是静默跳过') +})