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
@@ -69,7 +69,7 @@
<div class="section-title">备选店铺</div>
<div v-if="!candidates.length" class="empty-candidates">暂无备选店铺,请先输入并确认</div>
<div v-else class="candidate-table-scroll">
<el-table :data="pagedCandidates" row-key="id" height="160" class="candidate-table"
<el-table ref="candidateTableRef" :data="pagedCandidates" row-key="id" height="160" class="candidate-table"
@selection-change="onSelectionChange">
<el-table-column type="selection" width="42" />
<el-table-column prop="shopName" label="店铺名" min-width="120" show-overflow-tooltip />
@@ -83,6 +83,11 @@
<el-pagination v-if="candidateTotal > candidatePageSize" class="candidate-pagination"
layout="total, prev, pager, next" :total="candidateTotal" :page-size="candidatePageSize"
v-model:current-page="candidatePage" />
<div v-if="candidateSelectionNotice || rememberedCandidates.length" class="hint">
<span v-if="candidateSelectionNotice">{{ candidateSelectionNotice }}</span>
<button v-if="rememberedCandidates.length" type="button" class="link-danger"
@click="clearCandidateSelectionMemory">清除勾选记忆(共 {{ rememberedCandidates.length }} 家)</button>
</div>
</div>
<template v-if="!asinModeEnabled">
@@ -214,8 +219,9 @@
</template>
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref, shallowRef, triggerRef } from 'vue'
import { computed, nextTick, onMounted, onUnmounted, ref, shallowRef, triggerRef, watch } from 'vue'
import { ElMessage } from 'element-plus'
import type { TableInstance } from 'element-plus'
import AmazonToolPageShell from '@/pages/amazon/components/AmazonToolPageShell.vue';
import ModuleTemplateDownload from '@/shared/components/ModuleTemplateDownload.vue'
import ZiniaoVersionSetting from '@/shared/components/ZiniaoVersionSetting.vue'
@@ -272,6 +278,13 @@ import { runBatchDelete } from '@/shared/utils/batch-delete'
import { isRecordMissingError } from '@/shared/utils/task-queue-state.ts'
import { useTablePaging } from '@/shared/composables/useTablePaging.ts'
import { confirmTaskDeletion } from '@/shared/task-delete-confirm'
import {
parseRememberedNames,
reconcileRememberedNames,
selectableRows,
selectionMemoryKey,
selectionNotice,
} from '@/shared/utils/candidate-selection-memory'
const ziniaoVersion = useZiniaoVersion()
@@ -304,11 +317,14 @@ const {
total: candidateTotal,
paged: pagedCandidates,
} = useTablePaging(candidates)
// 勾选记忆:按 uid + 页签存店铺名,翻页与重载后自动恢复,不发任何请求
const candidateTableRef = ref<TableInstance | null>(null)
const rememberedCandidates = ref<string[]>([])
const candidateSelectionNotice = ref('')
let restoringSelection = false
const adding = ref(false)
const matching = ref(false)
const pushing = ref(false)
const queueWorkerRunning = ref(false)
const autoQueueEnabled = ref(false)
const queuePushResult = ref('')
const queuePayloadText = ref('')
const matchAsinRowsByCountry = ref<Record<string, PriceTrackAsinParsedRow[]>>({})
@@ -437,6 +453,10 @@ function activeLoopStorageKey() {
return `price-track:active-loop:${uidForStorage()}`
}
function selectionMemoryStorageKey() {
return selectionMemoryKey(uidForStorage(), 'price-track')
}
function setStorageJson(key: string, value: unknown, shouldRemove: boolean) {
if (typeof window === 'undefined') return
try {
@@ -724,10 +744,64 @@ function syncPollingIdsWithHistory() {
}
}
function candidateNameOf(row: PriceTrackCandidateVo) {
return row.shopName || ''
}
function loadSelectionMemory() {
try {
const raw = typeof window !== 'undefined' ? window.localStorage.getItem(selectionMemoryStorageKey()) : null
rememberedCandidates.value = parseRememberedNames(raw ? JSON.parse(raw) : [])
} catch {
rememberedCandidates.value = []
}
}
function saveSelectionMemory() {
setStorageJson(selectionMemoryStorageKey(), rememberedCandidates.value, rememberedCandidates.value.length === 0)
}
async function restoreCandidateSelection() {
await nextTick()
const table = candidateTableRef.value
if (!table) return
const rows = selectableRows(pagedCandidates.value, rememberedCandidates.value, candidateNameOf)
if (!rows.length) {
candidateSelectionNotice.value = ''
return
}
// 恢复期间的 selection-change 不回写记忆:半程重算会把还没勾上的名字抹掉
restoringSelection = true
try {
for (const row of rows) table.toggleRowSelection(row, true)
} finally {
restoringSelection = false
}
candidateSelectionNotice.value = selectionNotice(rows.length)
}
function clearCandidateSelectionMemory() {
rememberedCandidates.value = []
candidateSelectionNotice.value = ''
saveSelectionMemory()
candidateTableRef.value?.clearSelection()
}
function onSelectionChange(rows: PriceTrackCandidateVo[]) {
selectedCandidates.value = rows || []
if (restoringSelection) return
rememberedCandidates.value = reconcileRememberedNames(
rememberedCandidates.value,
pagedCandidates.value.map(candidateNameOf),
(rows || []).map(candidateNameOf),
)
saveSelectionMemory()
}
watch(pagedCandidates, () => {
void restoreCandidateSelection()
})
async function confirmAdd() {
const name = shopInput.value.trim()
if (!name) {
@@ -807,9 +881,6 @@ async function runMatch() {
}
matchedItems.value = [...nextByShop.values()]
saveMatchedItemsToStorage()
if (autoQueueEnabled.value) {
void processMatchedQueue()
}
ElMessage.success(`匹配 ${batch.length} 个店铺`)
} catch (e) {
ElMessage.error(e instanceof Error ? e.message : '匹配失败')
@@ -1083,122 +1154,6 @@ async function waitForTaskTerminal(taskId: number) {
}
}
function nextMatchedQueueItem() {
return matchedItems.value.find((item) => item.matched)
}
async function processMatchedQueue() {
if (disposed) return
if (queueWorkerRunning.value) {
return
}
if (!hasValidMode.value) {
ElMessage.warning('请至少选择一个跟价模式')
return
}
if (asinModeEnabled.value && !asinFiles.value.length) {
ElMessage.warning('请先选择 ASIN 文件')
return
}
const api = getPywebviewApi()
if (!api?.enqueue_json) {
ElMessage.error('当前环境未启用 pywebview enqueue_json')
return
}
const matchedRows = matchedItems.value.filter((i) => i.matched)
if (!matchedRows.length) {
ElMessage.warning('无可用匹配店铺')
return
}
queueWorkerRunning.value = true
pushing.value = true
queuePayloadText.value = ''
let successCount = 0
let failedCount = 0
try {
let index = 0
while (!disposed && autoQueueEnabled.value) {
const row = nextMatchedQueueItem()
if (!row) {
break
}
index += 1
try {
let attempt = 0
const taskVo = await (async () => {
while (true) {
if (disposed) throw new Error('component disposed')
try {
return await createPriceTrackTask({
userId: 0,
statusMode: statusModeEnabled.value,
asinMode: asinModeEnabled.value,
items: [row] as unknown as Record<string, unknown>[],
asinFiles: resolveAsinRequestPaths(),
countryCodes: resolveCountryCodesForRequest(),
})
} catch (error) {
const message = (error instanceof Error ? error.message : String(error || '')).toLowerCase()
const transient = ['无法连接到服务', 'bad gateway', 'gateway timeout', 'network error', 'timeout', '502', '503', '504'].some((pattern) => message.includes(pattern.toLowerCase()))
attempt += 1
if (!transient || attempt >= 10) throw error
queuePushResult.value = '服务暂时不可用,正在重试创建任务(' + attempt + '/10)...'
await sleep(getPollIntervalMs())
}
}
})()
taskSnapshots.value = {
...taskSnapshots.value,
[taskVo.taskId]: {
task: { id: taskVo.taskId, status: 'RUNNING' },
items: taskVo.items,
},
}
triggerRef(taskSnapshots)
taskDetails.value = {
...taskDetails.value,
[taskVo.taskId]: 'RUNNING',
}
saveTaskSnapshotsToStorage(true)
saveTaskDetailsToStorage()
const queuePayload = await buildQueuePayload(taskVo, row)
queuePayloadText.value = JSON.stringify(queuePayload, null, 2)
await enqueueCreatedTask(api, taskVo.taskId, queuePayload)
addPollingTask(taskVo.taskId)
scheduleNextPoll(true)
removeMatchedRowsLocally([row])
queuePushResult.value = '任务 ' + taskVo.taskId + ' 已提交,等待执行完成'
const finalStatus = await waitForTaskTerminal(taskVo.taskId)
if (finalStatus !== 'SUCCESS') {
failedCount += 1
queuePushResult.value = '任务 ' + taskVo.taskId + ' 执行失败,已自动继续下一条'
ElMessage.error(queuePushResult.value)
continue
}
successCount += 1
queuePushResult.value = '任务 ' + taskVo.taskId + ' 已完成'
} catch (error) {
if (disposed) break
failedCount += 1
queuePushResult.value = '第 ' + index + ' 条任务处理失败,已自动继续下一条:' + (error instanceof Error ? error.message : '未知错误')
ElMessage.error(queuePushResult.value)
removeMatchedRowsLocally([row])
continue
}
}
if (successCount > 0 || failedCount > 0) {
ElMessage.success('店铺任务启动已完成:成功 ' + successCount + ' 条,失败 ' + failedCount + ' 条')
}
} catch (e) {
if (disposed) return
queuePushResult.value = e instanceof Error ? e.message : '启动异常'
ElMessage.error(queuePushResult.value)
} finally {
queueWorkerRunning.value = false
pushing.value = false
}
}
function setLoopRun(next: PriceTrackLoopRunVo | null) {
activeLoopRun.value = next
activeLoopRunId.value = next?.id ?? null
@@ -1699,6 +1654,7 @@ onMounted(() => {
loadTaskSnapshotsFromStorage()
loadMatchedItemsFromStorage()
loadActiveLoopRunIdFromStorage()
loadSelectionMemory()
loadCandidates().catch(() => undefined)
loadCountryPreference().catch(() => undefined)
loadHistory().catch(() => undefined)
@@ -33,6 +33,7 @@
</div>
<div v-else class="candidate-table-scroll">
<el-table
ref="candidateTableRef"
:data="pagedCandidates"
row-key="id"
height="260"
@@ -67,6 +68,17 @@
:page-size="candidatePageSize"
v-model:current-page="candidatePage"
/>
<div v-if="candidateSelectionNotice || rememberedCandidates.length" class="loading-msg">
<span v-if="candidateSelectionNotice">{{ candidateSelectionNotice }}</span>
<button
v-if="rememberedCandidates.length"
type="button"
class="link-danger"
@click="clearCandidateSelectionMemory"
>
清除勾选记忆(共 {{ rememberedCandidates.length }} 家)
</button>
</div>
<ZiniaoVersionSetting v-model="ziniaoVersion" />
@@ -197,8 +209,9 @@
</template>
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from "vue";
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from "vue";
import { ElMessage } from "element-plus";
import type { TableInstance } 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";
@@ -239,6 +252,14 @@ import { useTablePaging } from '@/shared/composables/useTablePaging.ts'
import { getModuleProgressLight } from '@/shared/api/progress-light.ts'
import { createRowsVersionTracker } from '@/shared/api/task-progress-polling.ts'
import { confirmTaskDeletion } from '@/shared/task-delete-confirm';
import { dispatchedPruneNotice, mergeDispatchedArchive, pruneRows } from '@/shared/utils/dispatch-row-prune';
import {
parseRememberedNames,
reconcileRememberedNames,
selectableRows,
selectionMemoryKey,
selectionNotice,
} from '@/shared/utils/candidate-selection-memory';
const MAX_TRANSIENT_ERRORS = 30;
const ziniaoVersion = useZiniaoVersion();
@@ -262,6 +283,11 @@ const {
total: candidateTotal,
paged: pagedCandidates,
} = useTablePaging(candidates)
// 勾选记忆:按 uid + 页签存店铺名,翻页与重载后自动恢复,不发任何请求
const candidateTableRef = ref<TableInstance | null>(null);
const rememberedCandidates = ref<string[]>([]);
const candidateSelectionNotice = ref("");
let restoringSelection = false;
const historyItems = ref<QueryAsinHistoryItem[]>([]);
const dashboard = ref<QueryAsinDashboardVo>({
candidateCount: 0,
@@ -275,6 +301,8 @@ const pushing = ref(false);
const queuePushResult = ref("");
const queuePayloadText = ref("");
const pendingQueue = ref<QueryAsinShopQueueItem[]>([]);
// 已派发但历史卡片的 ASIN 明细仍要靠它回退(见 fallbackQueryAsinsForShop),所以只裁匹配表、不删数据
const dispatchedArchive = ref<QueryAsinShopQueueItem[]>([]);
const activeTaskId = ref<number | null>(null);
const activeQueueItem = ref<QueryAsinShopQueueItem | null>(null);
const queueWorkerRunning = ref(false);
@@ -492,6 +520,7 @@ function fallbackQueryAsinsForShop(shopName?: string) {
activeQueueItem.value,
...pendingQueue.value,
...matchedItems.value,
...dispatchedArchive.value,
];
const exact = candidates.find((item) => (item?.shopName || "").trim() === normalizedShopName && hasQueryAsins(item));
return readQueryAsins(exact);
@@ -554,6 +583,7 @@ function saveQueueState() {
if (typeof window === "undefined") return;
const payload = {
pendingQueue: pendingQueue.value,
dispatchedArchive: dispatchedArchive.value,
activeTaskId: activeTaskId.value,
activeQueueItem: activeQueueItem.value,
};
@@ -578,14 +608,19 @@ function loadQueueState() {
if (!raw) return;
const parsed = JSON.parse(raw) as {
pendingQueue?: QueryAsinShopQueueItem[];
dispatchedArchive?: QueryAsinShopQueueItem[];
activeTaskId?: number | null;
activeQueueItem?: QueryAsinShopQueueItem | null;
};
pendingQueue.value = parsed.pendingQueue || [];
dispatchedArchive.value = Array.isArray(parsed.dispatchedArchive)
? parsed.dispatchedArchive
: [];
activeTaskId.value = parsed.activeTaskId ?? null;
activeQueueItem.value = parsed.activeQueueItem ?? null;
} catch {
pendingQueue.value = [];
dispatchedArchive.value = [];
activeTaskId.value = null;
activeQueueItem.value = null;
}
@@ -766,10 +801,79 @@ async function refreshActiveTaskProgress(taskIds?: number[]) {
}
}
function candidateNameOf(row: QueryAsinCandidateVo) {
return row.shop_name || "";
}
function selectionMemoryStorageKey() {
return selectionMemoryKey(uidForStorage(), "query-asin");
}
function loadSelectionMemory() {
try {
const raw =
typeof window === "undefined"
? null
: window.localStorage.getItem(selectionMemoryStorageKey());
rememberedCandidates.value = parseRememberedNames(raw ? JSON.parse(raw) : []);
} catch {
rememberedCandidates.value = [];
}
}
function saveSelectionMemory() {
if (typeof window === "undefined") return;
try {
window.localStorage.setItem(
selectionMemoryStorageKey(),
JSON.stringify(rememberedCandidates.value),
);
} catch {
/* 配额满:记忆丢了不影响任务 */
}
}
async function restoreCandidateSelection() {
await nextTick();
const table = candidateTableRef.value;
if (!table) return;
const rows = selectableRows(pagedCandidates.value, rememberedCandidates.value, candidateNameOf);
if (!rows.length) {
candidateSelectionNotice.value = "";
return;
}
// 恢复期间的 selection-change 不回写记忆:半程重算会把还没勾上的名字抹掉
restoringSelection = true;
try {
for (const row of rows) table.toggleRowSelection(row, true);
} finally {
restoringSelection = false;
}
candidateSelectionNotice.value = selectionNotice(rows.length);
}
function clearCandidateSelectionMemory() {
rememberedCandidates.value = [];
candidateSelectionNotice.value = "";
saveSelectionMemory();
candidateTableRef.value?.clearSelection();
}
function onSelectionChange(rows: QueryAsinCandidateVo[]) {
selectedCandidates.value = rows;
if (restoringSelection) return;
rememberedCandidates.value = reconcileRememberedNames(
rememberedCandidates.value,
pagedCandidates.value.map(candidateNameOf),
rows.map(candidateNameOf),
);
saveSelectionMemory();
}
watch(pagedCandidates, () => {
void restoreCandidateSelection();
});
async function confirmAdd() {
const name = shopInput.value.trim();
if (!name) {
@@ -1052,9 +1156,13 @@ async function pushToPythonQueue() {
ElMessage.warning("请先匹配可用店铺");
return;
}
const { remaining, removed } = pruneRows(matchedItems.value, runnable, rowKeyForMatch);
matchedItems.value = remaining;
saveMatchedItems();
dispatchedArchive.value = mergeDispatchedArchive(dispatchedArchive.value, removed, rowKeyForMatch);
pendingQueue.value = mergeQueueItems(pendingQueue.value, runnable);
saveQueueState();
queuePushResult.value = `已加入 ${runnable.length} 条店铺,开始按顺序执行`;
queuePushResult.value = dispatchedPruneNotice(runnable.length, remaining.length);
await processQueue();
}
@@ -1105,6 +1213,7 @@ async function deleteTaskRecord(item: QueryAsinHistoryItem) {
}
onMounted(async () => {
loadSelectionMemory();
loadMatchedItems();
loadQueueState();
loadTaskStartTimes();
@@ -0,0 +1,64 @@
/**
* 候选区「勾选记忆」的纯逻辑(2026-10-04 C 档,不加任何请求)。
*
* 备选店铺每天重新拉一次,勾选状态原本跟着一起清零,于是同一批店铺要重勾一遍。
* 记住的是店铺名而不是行 id —— 候选行会被删了再加、id 会变,店铺名才是人眼认的那个身份。
* 三个会静默出错的点抽在这里钉住:
* 1. 键必须按 uid + 页签隔离,否则换账号 / 换页签会串勾选;
* 2. 候选区分页,selection-change 只带当前渲染窗口里的行。直接整份覆盖会把别的页
* 刚记住的勾选一起抹掉 ⇒ 只按「本窗口的可见行」重算;
* 3. 店铺已被删除时不得恢复勾选(否则匹配的是不存在的店)。
*/
/** 记忆上限:按店铺名存,超出丢最旧的,留最近勾的 */
export const SELECTION_MEMORY_LIMIT = 200
export function selectionMemoryKey(uid: string, tab: string): string {
return `candidate-selection:${tab}:${uid}`
}
/** localStorage 读回来的可能是脏值(手改、旧结构),入口先收干净 */
export function parseRememberedNames(raw: unknown): string[] {
if (!Array.isArray(raw)) return []
const seen = new Set<string>()
const names: string[] = []
for (const item of raw) {
if (typeof item !== 'string') continue
const name = item.trim()
if (!name || seen.has(name)) continue
seen.add(name)
names.push(name)
}
return names.length > SELECTION_MEMORY_LIMIT
? names.slice(names.length - SELECTION_MEMORY_LIMIT)
: names
}
/** 当前候选里仍然存在的、且被记住的行(名字两端空格按同一口径对齐) */
export function selectableRows<T>(
rows: readonly T[],
remembered: readonly string[],
nameOf: (row: T) => string,
): T[] {
const names = new Set(remembered.map((name) => name.trim()))
return rows.filter((row) => names.has(nameOf(row).trim()))
}
/**
* 本窗口(visibleNames)的勾选由 selectedNames 说了算,窗口外的名字原样保留。
* 顺序:先窗口外的旧记忆,再本窗口勾上的。
*/
export function reconcileRememberedNames(
remembered: readonly string[],
visibleNames: readonly string[],
selectedNames: readonly string[],
): string[] {
const visible = new Set(visibleNames.map((name) => name.trim()))
const kept = remembered.map((name) => name.trim()).filter((name) => name && !visible.has(name))
return parseRememberedNames([...kept, ...selectedNames.map((name) => name.trim())])
}
export function selectionNotice(restoredCount: number): string {
if (restoredCount <= 0) return ''
return `已恢复上次勾选的 ${restoredCount} 家店铺`
}
@@ -0,0 +1,72 @@
/**
* 「派发即移除」的纯逻辑(查 ASIN 页用;跟价页在循环体里逐行裁剪,语义相同)。
*
* 匹配好的店铺交给后台执行后不从「匹配结果表」里删掉,用户再点一次启动就把同一批店铺
* 再派发一遍 —— 代理按提取次数计费,多点这一次是真花钱。删行本身只是一句 filter,
* 但两个坑要抽出来钉住:
* 1. 行键口径必须与该页 `rowKeyForMatch` 一致(店铺名 trim + shopId)。名字带两端空格
* 的行删不掉,就会留着下次再买一轮;
* 2. 查 ASIN 的历史行明细靠本地匹配表回退(`withQueryAsinFallback` 读 matchedItems),
* 直接删行等于把已派发店铺的历史明细一起删掉 ⇒ 移除的行要进一份有上限的归档,
* 继续当回退数据源。
*/
/** 归档上限。整份归档会随队列状态同步写 localStorage,行里带 ASIN 明细,压到 50 行以内 */
export const DISPATCH_ARCHIVE_LIMIT = 50
export interface PruneResult<T> {
remaining: T[]
removed: T[]
}
/**
* 把已派发的行从列表里裁掉,返回新数组(不改入参:页面直接把结果赋回 ref,
* 原地改会让 Vue 的引用比较看不到变化)。
*/
export function pruneRows<T>(
rows: readonly T[],
dispatched: readonly T[],
keyOf: (row: T) => string,
): PruneResult<T> {
const keys = new Set(dispatched.map((row) => keyOf(row)))
const remaining: T[] = []
const removed: T[] = []
for (const row of rows) {
if (keys.has(keyOf(row))) {
removed.push(row)
} else {
remaining.push(row)
}
}
return { remaining, removed }
}
/**
* 已派发行的归档:按行键覆盖(重新匹配过 ASIN 时以最新一份为准),并按上限截断。
*/
export function mergeDispatchedArchive<T>(
archive: readonly T[],
removed: readonly T[],
keyOf: (row: T) => string,
): T[] {
const byKey = new Map<string, T>()
for (const row of archive) {
byKey.set(keyOf(row), row)
}
for (const row of removed) {
byKey.set(keyOf(row), row)
}
const merged = [...byKey.values()]
return merged.length > DISPATCH_ARCHIVE_LIMIT
? merged.slice(merged.length - DISPATCH_ARCHIVE_LIMIT)
: merged
}
/** 派发后的提示:把「再点启动只跑剩余」说在前面,免得用户以为按一次跑一批。 */
export function dispatchedPruneNotice(dispatchedCount: number, remainingCount: number): string {
const head = `已派发 ${dispatchedCount} 家店铺`
if (remainingCount <= 0) {
return `${head},匹配表已清空(再点启动不会重复提取)`
}
return `${head},匹配表还剩 ${remainingCount} 家未派发(再点启动只跑剩余,不会重复提取)`
}
@@ -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\]\)/,
'跟价循环体不再裁剪已派发行',
)
})