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();