feat(采集页省钱线): 派发即裁剪已匹配行、候选勾选记忆、摘掉跟价旧逐行派发

代理按「提取次数」计费而不是按流量,所以把同一批店铺重复派发一次就是真花钱。三处改动的
共同口径是「用户多点一次启动,不再多买一轮」。纯逻辑各抽成一个可单测的模块,页面只接线。

- dispatch-row-prune:查 ASIN 页匹配好的店铺交给后台执行后从结果表里移除。删行本身一句 filter,
  两个坑要钉住——行键口径必须与该页 rowKeyForMatch 一致(名字带两端空格的行删不掉,就留着
  下次再买一轮);历史行明细靠本地匹配表回退(withQueryAsinFallback 读 matchedItems),直接删行
  等于把已派发店铺的历史明细一起删掉 ⇒ 移除的行进一份上限 50 的归档,继续当回退数据源。
- candidate-selection-memory:候选店铺每天重拉时保住勾选。记的是店铺名不是行 id(候选行会被
  删了再加、id 会变,店铺名才是人眼认的那个身份);键按 uid + 页签隔离;selection-change 只带
  当前渲染窗口里的行,整份覆盖会把别的页刚记住的勾选一起抹掉 ⇒ 只按本窗口可见行重算;
  店铺已被删除时不得恢复勾选(否则匹配的是不存在的店)。
- 跟价页摘掉 processMatchedQueue 这条旧逐行派发路径:入口只有 if (autoQueueEnabled),而本页
  从来没把它置 true ⇒ 永远进不去。留着不是无害死代码——它是一套能重复买提取的并行派发路径,
  谁接错一次就再花钱。用例反向钉「不得回流」,不给死代码补测试。

验证:frontend-vue 定向 29/0(dispatch-row-prune 7、candidate-selection-memory 5、
wiring 10、query-asin-dispatch-prune 5、price-track-dead-queue-removed 反向钉 2),
全量 710/0(含本会话另加的到期弹窗 9 支,那 9 支随上一笔走)。接线由 wiring 用例钉住
"纯模块真被这两个页面 import",不是只测纯函数。
This commit is contained in:
2026-10-05 11:51:53 +08:00
parent 95e2318c42
commit eea617b3e6
9 changed files with 719 additions and 125 deletions
@@ -0,0 +1,90 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, join } from 'node:path'
/**
* 候选区「勾选记忆」接线守卫(2026-10-04 C 档)。
* 纯逻辑在 candidate-selection-memory.test.ts 里钉;这里只守两件"接错就完全不生效"的事:
* ①el-table 上真有 ref、恢复真的由分页变化驱动(只挂 onMounted 的话翻页不恢复、重新加载不恢复);
* ②写入记忆的入口是 selection-change,且恢复期间不重算(半程写入会把还没勾上的名字抹掉)。
*/
const PAGES_DIR = join(dirname(fileURLToPath(import.meta.url)), '../src/pages/brand/components')
const PAGES = [
{ file: 'BrandQueryAsinTab.vue', tab: 'query-asin', nameField: 'shop_name' },
{ file: 'BrandPriceTrackTab.vue', tab: 'price-track', nameField: 'shopName' },
]
function blockBetween(source: string, from: string, to: string) {
const start = source.indexOf(from)
assert.ok(start >= 0, `未找到 ${from}`)
const end = source.indexOf(to, start)
assert.ok(end > start, `${from} 之后没找到 ${to}`)
return source.slice(start, end)
}
function functionBody(source: string, header: string) {
const start = source.indexOf(header)
assert.ok(start >= 0, `未找到 ${header}`)
const rest = source.slice(start + header.length)
const next = rest.search(/\n(?:async )?function /)
return next < 0 ? rest : rest.slice(0, next)
}
for (const { file, tab, nameField } of PAGES) {
const source = readFileSync(join(PAGES_DIR, file), 'utf8')
test(`${file} 勾选记忆接线到位`, () => {
assert.match(source, /ref="candidateTableRef"/, '候选表没有 ref,恢复勾选无处可调')
assert.ok(source.includes('toggleRowSelection'), '没有调用 toggleRowSelection 恢复勾选')
assert.ok(source.includes('selectionMemoryKey'), '没有用共享的记忆键')
assert.match(
source,
new RegExp(`selectionMemoryKey\\(\\s*uidForStorage\\(\\)\\s*,\\s*["']${tab}["']\\s*\\)`),
`记忆键没带本页第 ${tab} 的 tab`,
)
assert.match(
source,
new RegExp(`function candidateNameOf[\\s\\S]{0,90}?row\\.${nameField}`),
`店铺名取值口径不对(应为 row.${nameField})`,
)
})
test(`${file} 恢复由分页变化驱动,且 onMounted 先读记忆`, () => {
assert.match(source, /watch\(\s*\n?\s*pagedCandidates/, '翻页后不重新恢复勾选')
const mount = blockBetween(source, 'onMounted(', 'onUnmounted(')
const memIdx = mount.indexOf('loadSelectionMemory()')
const candIdx = mount.search(/loadCandidates\(/)
assert.ok(memIdx >= 0, 'onMounted 没有读记忆')
assert.ok(candIdx < 0 || memIdx < candIdx, '读记忆晚于加载候选,首屏恢复不出来')
})
test(`${file} 勾选变化写记忆:按本窗口重算,恢复期间不重算`, () => {
const body = functionBody(source, 'function onSelectionChange(')
assert.ok(body.includes('reconcileRememberedNames('), 'selection-change 没有把勾选写进记忆')
assert.match(body, /if \(\s*restoringSelection\s*\)\s*return/, '恢复过程中仍在重写记忆,半程会抹掉未恢复的名字')
assert.match(body, /reconcileRememberedNames\([\s\S]{0,260}?saveSelectionMemory\(\)/, '记忆没落盘')
})
test(`${file} 记忆的读写真的落到 localStorage`, () => {
const save = functionBody(source, 'function saveSelectionMemory(')
assert.match(
save,
/(setStorageJson|localStorage\.setItem)\(\s*\n?\s*selectionMemoryStorageKey\(\)/,
'saveSelectionMemory 只改了内存,重启就忘',
)
const load = functionBody(source, 'function loadSelectionMemory(')
assert.match(load, /getItem\(\s*\n?\s*selectionMemoryStorageKey\(\)/, 'loadSelectionMemory 没读盘')
assert.match(load, /parseRememberedNames\(/, '读回来的没经脏数据收口')
})
test(`${file} 有清除入口,且清的是记忆本身`, () => {
const clear = functionBody(source, 'function clearCandidateSelectionMemory(')
assert.match(clear, /rememberedCandidates\.value = \[\]/, '没清内存里的名单')
assert.ok(clear.includes('saveSelectionMemory()'), '没写回 localStorage,下次启动又恢复')
assert.match(source, /@click="clearCandidateSelectionMemory/, '界面上没有清除勾选记忆入口')
})
}
@@ -0,0 +1,80 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import {
SELECTION_MEMORY_LIMIT,
parseRememberedNames,
reconcileRememberedNames,
selectionMemoryKey,
selectionNotice,
selectableRows,
} from '../src/shared/utils/candidate-selection-memory.ts'
/**
* 候选区「勾选记忆」的纯逻辑(2026-10-04 C 档,不加任何请求)。
* 每天开工都要重勾同一批店铺 ⇒ 把勾选按店铺名记住,加载完候选后恢复。
* 这里钉住四件会静默出错的事:键按页隔离、脏数据入口、分页互相覆盖、店铺删除后复活。
*/
interface Row {
id: number
shopName?: string
}
const nameOf = (row: Row) => row.shopName || ''
test('勾选记忆按 uid + 页签隔离,两个页签不得互相污染', () => {
const asin = selectionMemoryKey('1146', 'query-asin')
const track = selectionMemoryKey('1146', 'price-track')
assert.notEqual(asin, track, '同 uid 不同页签共用了键')
assert.ok(asin.includes('1146'), '键里没有 uid,换账号会串勾选')
assert.ok(selectionMemoryKey('1147', 'query-asin').includes('1147'))
})
test('脏数据一律丢弃:非数组、非字符串、空白名去重后保留最近 N 条', () => {
assert.deepEqual(parseRememberedNames(undefined), [])
assert.deepEqual(parseRememberedNames('{"a":1}'), [])
assert.deepEqual(parseRememberedNames([null, 1, {}, '', ' ']), [])
assert.deepEqual(parseRememberedNames([' A店 ', 'A店', 'B店']), ['A店', 'B店'])
const many = Array.from({ length: SELECTION_MEMORY_LIMIT + 30 }, (_, i) => `店${i}`)
const trimmed = parseRememberedNames(many)
assert.equal(trimmed.length, SELECTION_MEMORY_LIMIT, '未按上限截断,localStorage 会一直涨')
assert.equal(trimmed[trimmed.length - 1], `店${many.length - 1}`, '截断丢了最新的勾选')
assert.ok(!trimmed.includes('店0'), '截断保留了最旧的')
})
test('只恢复当前候选里仍然存在的店铺,已删除的不得复活', () => {
const rows: Row[] = [
{ id: 1, shopName: 'A店' },
{ id: 2, shopName: 'B店' },
{ id: 9, shopName: '这次没勾的店' },
]
// 记忆里有「已删除的店」但候选里没有 ⇒ 不恢复;候选里有但记忆里没有 ⇒ 也不许勾上
assert.deepEqual(selectableRows(rows, ['A店', '已删除的店', 'B店'], nameOf).map((r) => r.id), [1, 2])
// 名字两端空格:记忆与候选行必须按同一口径对齐
assert.deepEqual(selectableRows([{ id: 3, shopName: ' C店 ' }], ['C店'], nameOf).map((r) => r.id), [3])
assert.deepEqual(selectableRows([{ id: 4 }], ['undefined'], nameOf), [])
})
test('分页不得互相覆盖:切页时本窗口的勾选说了算,其他页的原样保留', () => {
const page1Selected = ['A店', 'B店']
const page2Visible = ['C店', 'D店']
// 在第二页勾了 C,取消 D
const afterPage2 = reconcileRememberedNames(page1Selected, page2Visible, ['C店'])
assert.deepEqual(afterPage2.sort(), ['A店', 'B店', 'C店'].sort())
// 回到第一页取消 B
const backToPage1 = reconcileRememberedNames(afterPage2, ['A店', 'B店'], ['A店'])
assert.deepEqual(backToPage1.sort(), ['A店', 'C店'].sort())
// 全窗口取消 ⇒ 该窗口的名字全部消失,其他页不受牵连
const cleared = reconcileRememberedNames(['A店', 'C店'], ['A店'], [])
assert.deepEqual(cleared, ['C店'])
})
test('恢复提示报出真实条数,0 家时不得谎报', () => {
assert.match(selectionNotice(3), /已恢复/)
assert.ok(selectionNotice(3).includes('3'))
assert.equal(selectionNotice(0), '')
})
@@ -0,0 +1,100 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import {
DISPATCH_ARCHIVE_LIMIT,
dispatchedPruneNotice,
mergeDispatchedArchive,
pruneRows,
} from '../src/shared/utils/dispatch-row-prune.ts'
interface Row {
shopName: string
shopId?: number
asins?: string[]
}
const keyOf = (row: Row) => `${(row.shopName || '').trim()}::${row.shopId || ''}`
/** 三行 A/B/C(A 与 B 各带 ASIN,用来验归档后仍查得到明细) */
function rows(): Row[] {
return [
{ shopName: ' 店铺A ', shopId: 1, asins: ['B0A'] },
{ shopName: '店铺B', shopId: 2, asins: ['B0B'] },
{ shopName: '店铺C', shopId: 3, asins: [] },
]
}
test('裁剪按行键移除,保留原顺序与未派发的行', () => {
const base = rows()
const { remaining, removed } = pruneRows(base, [base[0]], keyOf)
assert.deepEqual(remaining.map(keyOf), ['店铺B::2', '店铺C::3'])
assert.deepEqual(removed.map(keyOf), ['店铺A::1'])
assert.deepEqual(removed.map((r) => r.shopName), [' 店铺A '], '返回的应是原始行对象本体,不是重写过的')
})
test('裁剪不修改入参数组(页面 ref 直接赋值时要能安全比较)', () => {
const base = rows()
const snapshot = base.map(keyOf)
pruneRows(base, [base[0], base[1]], keyOf)
assert.deepEqual(base.map(keyOf), snapshot, 'pruneRows 原地改了入参:Vue 的引用比较会失效')
})
test('派发键含空白时按 trim 匹配:同一店铺不因两端空格漏掉而留双行', () => {
const base: Row[] = [{ shopName: '店铺A', shopId: 1 }]
const dispatched: Row[] = [{ shopName: ' 店铺A ', shopId: 1 }]
const { remaining } = pruneRows(base, dispatched, keyOf)
assert.deepEqual(remaining, [], 'trim 口径不一致 ⇒ 再点启动会把这家店再派发一次(再买一轮提取)')
})
test('派发清单为空时不动任何行', () => {
const base = rows()
const { remaining, removed } = pruneRows(base, [], keyOf)
assert.deepEqual(remaining.map(keyOf), base.map(keyOf))
assert.deepEqual(removed, [])
})
test('归档按行键去重并按上限截断(localStorage 不能被历史 ASIN 撑爆)', () => {
const base = rows()
const first = mergeDispatchedArchive([], base, keyOf)
assert.deepEqual(first.map(keyOf), ['店铺A::1', '店铺B::2', '店铺C::3'])
assert.equal(first.length, 3)
// 重复派发同一行不累积
const again = mergeDispatchedArchive(first, [base[0]], keyOf)
assert.equal(again.length, 3, '同一店铺重复派发应在归档里覆盖而不是追加')
const many: Row[] = Array.from({ length: DISPATCH_ARCHIVE_LIMIT + 20 }, (_, i) => ({
shopName: `店${i}`,
shopId: i,
asins: [`B0${i}`],
}))
const capped = mergeDispatchedArchive([], many, keyOf)
assert.equal(capped.length, DISPATCH_ARCHIVE_LIMIT, '归档必须有上限')
// 保留最近的:最后一条一定在
assert.equal(capped[capped.length - 1].shopName, `店${many.length - 1}`)
})
test('归档覆盖同一行时保留最新明细(ASIN 可能被重新匹配改过)', () => {
const oldRow: Row = { shopName: '店铺A', shopId: 1, asins: ['旧ASIN'] }
const newRow: Row = { shopName: '店铺A', shopId: 1, asins: ['新ASIN'] }
const merged = mergeDispatchedArchive([oldRow], [newRow], keyOf)
assert.deepEqual(merged.map((r) => r.asins), [['新ASIN']])
})
test('派发提示要说清"再点启动只跑剩余",且剩余为 0 时不谎称还有', () => {
// 数字必须真从入参来:写成 /剩余|5/ 这类或关系,把剩余数硬编码成 0 也照样绿
assert.match(dispatchedPruneNotice(3, 5), /已派发 3 家/)
assert.match(dispatchedPruneNotice(3, 5), /还剩 5 家/)
assert.match(dispatchedPruneNotice(3, 5), /只跑剩余/)
assert.doesNotMatch(dispatchedPruneNotice(3, 0), /\d 家未派发|还剩 \d 家/)
assert.match(dispatchedPruneNotice(3, 0), /已清空/)
})
@@ -0,0 +1,36 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, join } from 'node:path'
/**
* 跟价页「旧逐行派发」死代码守卫(2026-10-04 C 档收尾)。
*
* processMatchedQueue 是循环派发(pushToPythonLoopQueue → runLoopExecution)之前的实现,
* 入口只有 `if (autoQueueEnabled.value)`,而 autoQueueEnabled 在本页从来没被置 true ⇒ 永远进不去。
* 留着它不是无害死代码:它是一套能重复买提取的并行派发路径,谁接错一次就再花钱。
* 所以这里反向钉住"不得回流",而不是给死代码补测试。
*/
const PAGE = join(
dirname(fileURLToPath(import.meta.url)),
'../src/pages/brand/components/BrandPriceTrackTab.vue',
)
const source = readFileSync(PAGE, 'utf8')
test('跟价页不再保留旧逐行派发队列及其开关', () => {
for (const symbol of [
'processMatchedQueue',
'nextMatchedQueueItem',
'autoQueueEnabled',
'queueWorkerRunning',
]) {
assert.ok(!source.includes(symbol), `${symbol} 仍在跟价页:旧的重复派发路径没清干净`)
}
})
test('跟价页启动仍只接循环派发一条路径', () => {
assert.match(source, /@click="pushToPythonLoopQueue"/, '启动按钮没接循环派发')
assert.ok(source.includes('async function runLoopExecution('), '循环派发实现不见了')
})
@@ -0,0 +1,87 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { fileURLToPath } from 'node:url'
import { dirname, join } from 'node:path'
/**
* 「派发即移除」接线守卫(2026-10-04 A2)。
*
* 代理按提取次数计费:点两次启动就把同一批店铺跑两遍是真花钱。查 ASIN 页把整批匹配行
* 合进 pendingQueue 后从不清空匹配表,第二次点击会再合一遍;跟价页则是在循环体里
* 逐行裁剪(这里把它钉成对照组,谁删了谁报错)。
*
* 删行还有一个反向坑:查 ASIN 的历史卡片 ASIN 明细靠本地匹配表回退
* (fallbackQueryAsinsForShop 读 matchedItems),只删行不加归档等于把已派发店铺的历史
* 明细静默删掉 ⇒ 守卫同时要求归档进回退候选源 + 进持久化。
*/
const PAGES_DIR = join(dirname(fileURLToPath(import.meta.url)), '../src/pages/brand/components')
function sourceOf(page: string) {
return readFileSync(join(PAGES_DIR, page), 'utf8')
}
const QUERY_ASIN = sourceOf('BrandQueryAsinTab.vue')
const PRICE_TRACK = sourceOf('BrandPriceTrackTab.vue')
/** 取函数体:从声明行到下一个顶层 function/async function 之前 */
function functionBody(source: string, header: string) {
const start = source.indexOf(header)
assert.ok(start >= 0, `未找到 ${header}`)
const rest = source.slice(start + header.length)
const next = rest.search(/\n(?:async )?function /)
return next < 0 ? rest : rest.slice(0, next)
}
test('查ASIN 派发时必须把已交出的行从匹配表裁掉', () => {
const body = functionBody(QUERY_ASIN, 'async function pushToPythonQueue()')
assert.ok(body.includes('pruneRows('), 'pushToPythonQueue 未调用 pruneRows')
// 必须把匹配表换成 pruneRows 算出来的 remaining(写成 matchedItems.value = matchedItems.value
// 也算「有赋值」,所以要把变量名钉住),且发生在 processQueue 之前
assert.match(
body,
/const \{ remaining, removed \} = pruneRows\([\s\S]{0,160}?matchedItems\.value = remaining\b[\s\S]{0,400}?await processQueue\(\)/,
'匹配表必须被替换成 pruneRows 的 remaining,且在 processQueue 之前',
)
assert.ok(/saveMatchedItems\(\)/.test(body), '裁剪后未持久化匹配表')
})
test('查ASIN 被裁掉的行要进归档并继续当 ASIN 回退数据源', () => {
const body = functionBody(QUERY_ASIN, 'async function pushToPythonQueue()')
assert.ok(body.includes('mergeDispatchedArchive('), '未把移除行并入已派发归档')
const fallback = functionBody(QUERY_ASIN, 'function fallbackQueryAsinsForShop(')
assert.match(
fallback,
/\.\.\.matchedItems\.value[\s\S]{0,80}?\.\.\.dispatchedArchive\.value/,
'回退候选源里没有归档,隐藏=静默删除历史 ASIN 明细',
)
})
test('查ASIN 归档必须随队列状态一起持久化并在重载后恢复', () => {
const save = functionBody(QUERY_ASIN, 'function saveQueueState()')
assert.ok(save.includes('dispatchedArchive'), 'saveQueueState 未写入归档')
const load = functionBody(QUERY_ASIN, 'function loadQueueState()')
// 只写「= 什么东西 ;」不够:类型注解 QueryAsinShopQueueItem[] 里就有 [],
// 断言必须抓到 Array.isArray 这条兜底分支本身
assert.match(
load,
/dispatchedArchive\.value = Array\.isArray\(parsed\.dispatchedArchive\)[\s\S]{0,120}?:\s*\[\];/,
'loadQueueState 未对归档做类型兜底',
)
})
test('查ASIN 派发后的提示要说清「再点启动只跑剩余」', () => {
const body = functionBody(QUERY_ASIN, 'async function pushToPythonQueue()')
assert.ok(body.includes('dispatchedPruneNotice('), '未使用统一提示语')
})
test('对照组:跟价循环每派发一行就裁一行', () => {
// 这条是现状钉桩,不是新增要求:runLoopExecution 已实现派发即移除,
// 一旦有人把它删了,跟价会立刻退化成「再点启动再买一轮」。
assert.match(
PRICE_TRACK,
/enqueueCreatedTask\(api,[\s\S]{0,200}?removeMatchedRowsLocally\(\[row\]\)/,
'跟价循环体不再裁剪已派发行',
)
})