feat(跟价多状态): 全量跟价支持勾选多个商品状态,取值以派发落库值为准

原来「按商品状态(全量)」写死在售。现在用户端可勾选 在售/缺少的报价/定价问题
(默认只勾在售),勾几个跑几个,状态清单随循环任务落库并在每次派发子任务时下发。

- 载荷的 mode 与状态清单都取派发上下文(childTaskRequest),不再读界面当前勾选:
  循环跑到第 N 轮时用户可能已经改过勾选,用界面值会把没勾的状态跑出去。
- listingStatuses 白名单 Active/PricingIssue/MissingOffer 三值,校验放在 try 之外——
  try 里的 catch 会把「不支持的商品状态」改写成「循环任务序列化失败」,那是句假话。
- V159 给 biz_price_track_loop_run 加 listing_statuses_json(可空=本特性之前的行=在售)。
- 状态标识用我们自己的键 MissingOffer,页面真实取值是 OfferMissing(2026-10-17 黄建新
  英国站真机实锤),两者不同形是有意的:改键名会断载荷兼容。
This commit is contained in:
2026-10-17 00:07:31 +08:00
parent 6b1105f841
commit 8a20f85ca6
14 changed files with 384 additions and 7 deletions
@@ -19,6 +19,11 @@ public class PriceTrackCreateTaskRequest {
@Schema(description = "是否启用按商品状态处理模式")
private boolean statusMode;
@Schema(description = "statusMode 下要跑的商品状态清单(Active/PricingIssue/MissingOffer);"
+ "为空时客户端按在售执行,与未升级的存量载荷等价",
example = "[\"Active\",\"PricingIssue\"]")
private List<String> listingStatuses;
@Schema(description = "是否启用按指定 ASIN 文件处理模式")
private boolean asinMode;
@@ -20,6 +20,8 @@ public class PriceTrackLoopRunCreateRequest {
private boolean statusMode;
private List<String> listingStatuses = new ArrayList<>();
private boolean asinMode;
@NotEmpty(message = "items不能为空")
@@ -22,6 +22,8 @@ public class PriceTrackLoopRunEntity {
private Integer currentRound;
private Integer currentShopIndex;
private Boolean statusMode;
/** 建单时勾选的商品状态清单(JSON 数组,V159)。NULL=这条记录早于多状态功能,按在售跑。 */
private String listingStatusesJson;
private Boolean asinMode;
private String asinFilesJson;
private String countryCodesJson;
@@ -9,6 +9,7 @@ import java.util.List;
public class PriceTrackCreateTaskRequestVo {
private Long userId;
private boolean statusMode;
private List<String> listingStatuses = new ArrayList<>();
private boolean asinMode;
private List<PriceTrackMatchShopsVo.PriceTrackShopQueueItem> items = new ArrayList<>();
private List<String> asinFiles = new ArrayList<>();
@@ -22,6 +22,7 @@ public class PriceTrackLoopRunVo {
private Boolean stopRequested;
private String errorMessage;
private Boolean statusMode;
private List<String> listingStatuses = new ArrayList<>();
private Boolean asinMode;
private List<String> asinFiles = new ArrayList<>();
private List<String> countryCodes = new ArrayList<>();
@@ -38,6 +38,13 @@ public class PriceTrackLoopRunService {
private static final String STATUS_FAILED = "FAILED";
private static final String STATUS_STOPPED = "STOPPED";
private static final String EXECUTION_MODE_FINITE = "FINITE";
/**
* 跟价界面上可勾选的商品状态(2026-10-16 多状态立项)。取值以客户端
* {@code amazon_base_v2.LISTING_STATUS_CATALOG} 为准,这里只挡清单外的 junk——
* 不让它存进循环记录、再派发给客户端去猜页面。
*/
private static final List<String> ALLOWED_LISTING_STATUSES =
List.of("Active", "PricingIssue", "MissingOffer");
private static final String EXECUTION_MODE_INFINITE = "INFINITE";
/** 客户端异常中断的任务 errorMessage 前缀(TaskHeartbeatService.markInterrupted 写入)。 */
private static final String CLIENT_INTERRUPT_ERROR_PREFIX = "客户端异常中断";
@@ -60,6 +67,9 @@ public class PriceTrackLoopRunService {
if (items.isEmpty()) {
throw new BusinessException("items不能为空");
}
// 状态清单的校验必须在下面那个 try 之外:try 里的 catch 会把任何异常改写成
// 「循环任务序列化失败」,那等于对人说"勾了个不支持的状态"是 Jackson 的锅。
List<String> listingStatuses = normalizeListingStatuses(request);
PriceTrackLoopRunEntity entity = new PriceTrackLoopRunEntity();
entity.setUserId(request.getUserId());
entity.setStatus(STATUS_RUNNING);
@@ -77,6 +87,7 @@ public class PriceTrackLoopRunService {
try {
entity.setAsinFilesJson(objectMapper.writeValueAsString(request.getAsinFiles() == null ? List.of() : request.getAsinFiles()));
entity.setCountryCodesJson(objectMapper.writeValueAsString(request.getCountryCodes()));
entity.setListingStatusesJson(objectMapper.writeValueAsString(listingStatuses));
entity.setShopsJson(objectMapper.writeValueAsString(items));
} catch (Exception ex) {
throw new BusinessException("循环任务序列化失败");
@@ -129,6 +140,9 @@ public class PriceTrackLoopRunService {
PriceTrackCreateTaskRequestVo childRequest = new PriceTrackCreateTaskRequestVo();
childRequest.setUserId(entity.getUserId());
childRequest.setStatusMode(Boolean.TRUE.equals(entity.getStatusMode()));
// 逐轮派发的子任务必须吃循环建单时勾的状态,不能吃界面当下的勾选态——
// 页面刷新后本地勾选会回到默认(只有在售),INFINITE 循环的后续轮就会少跑状态。
childRequest.setListingStatuses(parseStringList(entity.getListingStatusesJson()));
childRequest.setAsinMode(Boolean.TRUE.equals(entity.getAsinMode()));
childRequest.setAsinFiles(parseStringList(entity.getAsinFilesJson()));
childRequest.setCountryCodes(parseStringList(entity.getCountryCodesJson()));
@@ -485,6 +499,30 @@ public class PriceTrackLoopRunService {
return entity;
}
/**
* 清洗并校验勾选的商品状态。
*
* <p>空清单**不判错**:未升级的用户端不会带这个字段,那时按在售跑(客户端默认值),
* 后端先于前端发布也不会把建单打挂。"至少要勾一个"由界面保证,服务端只守取值白名单。
*/
private List<String> normalizeListingStatuses(PriceTrackLoopRunCreateRequest request) {
List<String> picked = request.getListingStatuses() == null ? List.of() : request.getListingStatuses();
List<String> cleaned = new ArrayList<>();
for (String status : picked) {
String key = status == null ? "" : status.trim();
if (key.isEmpty()) {
continue;
}
if (!ALLOWED_LISTING_STATUSES.contains(key)) {
throw new BusinessException("不支持的商品状态:" + key);
}
if (!cleaned.contains(key)) {
cleaned.add(key);
}
}
return cleaned;
}
private void validateCreateRequest(PriceTrackLoopRunCreateRequest request) {
if (request == null) {
throw new BusinessException("请求不能为空");
@@ -539,6 +577,7 @@ public class PriceTrackLoopRunService {
vo.setStopRequested(Boolean.TRUE.equals(entity.getStopRequested()));
vo.setErrorMessage(entity.getErrorMessage());
vo.setStatusMode(Boolean.TRUE.equals(entity.getStatusMode()));
vo.setListingStatuses(parseStringList(entity.getListingStatusesJson()));
vo.setAsinMode(Boolean.TRUE.equals(entity.getAsinMode()));
vo.setAsinFiles(parseStringList(entity.getAsinFilesJson()));
vo.setCountryCodes(parseStringList(entity.getCountryCodesJson()));
@@ -548,6 +548,9 @@ public class PriceTrackTaskService {
Map<String, Object> ctx = new LinkedHashMap<>();
ctx.put("userId", request.getUserId());
ctx.put("statusMode", request.isStatusMode());
// 勾选的商品状态原样进快照:Python 侧按它逐状态筛,排查时也看得到这单跑的是哪些状态
ctx.put("listingStatuses", request.getListingStatuses() == null
? List.of() : request.getListingStatuses());
ctx.put("asinMode", request.isAsinMode());
ctx.put("countryCodes", request.getCountryCodes());
// 不再保存全量 ASIN 数据到 requestJson
@@ -0,0 +1,24 @@
-- 跟价「按商品状态(全量)」多状态(2026-10-16 立项):循环任务落库建单时勾选的状态清单。
--
-- 为什么必须落库、不能让界面现取:每一轮子任务的 Python 载荷由用户端现场拼,而页面刷新后
-- 本地勾选态会回到默认(只有在售)。INFINITE 循环跑几小时期间用户刷新一次页面,后续轮就会
-- 静默少跑「缺少的报价 / 定价问题」——用户以为还在跑,实际只跟在售。所以派发必须回读这里。
--
-- NULL=这条记录早于本功能(含所有存量循环),语义=按在售跑,与客户端默认值一致,不回填。
SET @db_name = DATABASE();
SET @col_exists := (
SELECT COUNT(*)
FROM information_schema.COLUMNS
WHERE TABLE_SCHEMA = @db_name
AND TABLE_NAME = 'biz_price_track_loop_run'
AND COLUMN_NAME = 'listing_statuses_json'
);
SET @sql := IF(@col_exists = 0,
'ALTER TABLE biz_price_track_loop_run ADD COLUMN listing_statuses_json VARCHAR(512) NULL COMMENT ''json array of listing statuses: Active/PricingIssue/MissingOffer; NULL = pre-feature row, means Active'' AFTER status_mode',
'SELECT 1'
);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
@@ -1,13 +1,18 @@
package com.nanri.aiimage.modules.pricetrack.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.modules.pricetrack.mapper.PriceTrackLoopRunMapper;
import com.nanri.aiimage.modules.pricetrack.model.dto.PriceTrackLoopRunCreateRequest;
import com.nanri.aiimage.modules.pricetrack.model.entity.PriceTrackLoopRunEntity;
import com.nanri.aiimage.modules.pricetrack.model.vo.PriceTrackLoopRunDispatchVo;
import com.nanri.aiimage.modules.pricetrack.model.vo.PriceTrackLoopRunVo;
import com.nanri.aiimage.modules.pricetrack.model.vo.PriceTrackMatchShopsVo;
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import com.nanri.aiimage.modules.ziniao.service.ZiniaoShopSwitchService;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import java.util.List;
import java.util.Map;
@@ -16,6 +21,8 @@ import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
@@ -315,6 +322,101 @@ class PriceTrackLoopRunServiceTest {
assertEquals(0, loop.getResumeAttempt());
}
// ---------- 跟价多状态(2026-10-16):勾选的状态必须落在循环记录上 ----------
private PriceTrackLoopRunService newLoopService(PriceTrackLoopRunMapper loopRunMapper,
FileTaskMapper fileTaskMapper,
ObjectMapper objectMapper) {
ZiniaoShopSwitchService ziniao = mock(ZiniaoShopSwitchService.class);
when(ziniao.normalizeShopName(any())).thenAnswer(call -> call.getArgument(0));
return new PriceTrackLoopRunService(loopRunMapper, fileTaskMapper, objectMapper, ziniao);
}
private PriceTrackLoopRunCreateRequest statusModeRequest(List<String> statuses) {
PriceTrackLoopRunCreateRequest request = new PriceTrackLoopRunCreateRequest();
request.setUserId(1L);
request.setStatusMode(true);
request.setAsinMode(false);
request.setItems(new java.util.ArrayList<>(List.of(shop("魏振峰"))));
request.setCountryCodes(new java.util.ArrayList<>(List.of("DE")));
request.setExecutionMode("FINITE");
request.setTargetRounds(1);
request.setListingStatuses(statuses == null ? null : new java.util.ArrayList<>(statuses));
return request;
}
@Test
void createLoopRunPersistsCheckedListingStatusesTrimmedAndDeduped() {
PriceTrackLoopRunMapper loopRunMapper = mock(PriceTrackLoopRunMapper.class);
ObjectMapper objectMapper = new ObjectMapper();
PriceTrackLoopRunService service = newLoopService(loopRunMapper, mock(FileTaskMapper.class), objectMapper);
service.createLoopRun(statusModeRequest(List.of("Active", " PricingIssue ", "Active", "")));
ArgumentCaptor<PriceTrackLoopRunEntity> captor = ArgumentCaptor.forClass(PriceTrackLoopRunEntity.class);
verify(loopRunMapper).insert(captor.capture());
assertEquals("[\"Active\",\"PricingIssue\"]", captor.getValue().getListingStatusesJson(),
"勾选清单要去空白、去重后落库——派发每一轮都从这里回读");
}
@Test
void createLoopRunRejectsStatusOutsideTheCatalog() {
PriceTrackLoopRunMapper loopRunMapper = mock(PriceTrackLoopRunMapper.class);
PriceTrackLoopRunService service = newLoopService(loopRunMapper, mock(FileTaskMapper.class), new ObjectMapper());
BusinessException error = assertThrows(BusinessException.class,
() -> service.createLoopRun(statusModeRequest(List.of("NotAStatus"))));
assertTrue(error.getMessage().contains("NotAStatus"), "报错要点名被拒的取值:" + error.getMessage());
verify(loopRunMapper, never()).insert(any(PriceTrackLoopRunEntity.class));
}
@Test
void createLoopRunWithoutListingStatusesStillSucceedsForOlderWebBundle() {
// 后端先于用户端发布时,老界面不会带这个字段:空=按在售跑(客户端默认),不能把建单打挂
PriceTrackLoopRunMapper loopRunMapper = mock(PriceTrackLoopRunMapper.class);
PriceTrackLoopRunService service = newLoopService(loopRunMapper, mock(FileTaskMapper.class), new ObjectMapper());
PriceTrackLoopRunVo vo = service.createLoopRun(statusModeRequest(null));
ArgumentCaptor<PriceTrackLoopRunEntity> captor = ArgumentCaptor.forClass(PriceTrackLoopRunEntity.class);
verify(loopRunMapper).insert(captor.capture());
assertEquals("[]", captor.getValue().getListingStatusesJson());
assertTrue(vo.getListingStatuses().isEmpty());
}
@Test
void dispatchNextCarriesPersistedStatusesInsteadOfUiState() throws Exception {
// 这一条是"必须落库"的全部理由:载荷由用户端现场拼,页面刷新后本地勾选回到默认
// (只有在售),INFINITE 循环的后续轮就会静默少跑「缺少的报价 / 定价问题」。
ObjectMapper objectMapper = new ObjectMapper();
PriceTrackLoopRunMapper loopRunMapper = mock(PriceTrackLoopRunMapper.class);
PriceTrackLoopRunService service = newLoopService(loopRunMapper, mock(FileTaskMapper.class), objectMapper);
PriceTrackLoopRunEntity loop = new PriceTrackLoopRunEntity();
loop.setId(900L);
loop.setUserId(1L);
loop.setStatus("RUNNING");
loop.setExecutionMode("FINITE");
loop.setTargetRounds(2);
loop.setCurrentRound(1);
loop.setCurrentShopIndex(0);
loop.setStatusMode(true);
loop.setAsinMode(false);
loop.setStopRequested(false);
loop.setActiveTaskId(null);
loop.setCountryCodesJson(objectMapper.writeValueAsString(List.of("DE")));
loop.setListingStatusesJson(objectMapper.writeValueAsString(List.of("Active", "MissingOffer")));
loop.setShopsJson(objectMapper.writeValueAsString(List.of(shop("魏振峰"))));
when(loopRunMapper.selectById(900L)).thenReturn(loop);
PriceTrackLoopRunDispatchVo dispatched = service.dispatchNext(900L, 1L);
assertEquals(List.of("Active", "MissingOffer"), dispatched.getChildTaskRequest().getListingStatuses(),
"子任务派发必须回读循环记录上的状态清单");
assertEquals(List.of("Active", "MissingOffer"), dispatched.getLoopRun().getListingStatuses(),
"循环 VO 也要回显,界面才显示得出这单在跑哪些状态");
}
private PriceTrackMatchShopsVo.PriceTrackShopQueueItem shop(String name) {
PriceTrackMatchShopsVo.PriceTrackShopQueueItem item = new PriceTrackMatchShopsVo.PriceTrackShopQueueItem();
item.setShopName(name);
@@ -10,7 +10,7 @@
<label class="mode-check-row">
<input type="radio" name="price-track-mode" class="mode-check-input" :checked="statusModeEnabled" @change="selectMode('status')" />
<span class="mode-check-text">按商品状态(全量)</span>
<span class="mode-hint-inline">— 获取店铺所有在售ASIN跑跟价</span>
<span class="mode-hint-inline">— 按下方勾选的商品状态跑跟价</span>
</label>
<label class="mode-check-row">
<input type="radio" name="price-track-mode" class="mode-check-input" :checked="asinModeEnabled" @change="selectMode('asin')" />
@@ -19,6 +19,22 @@
</label>
</div>
<!-- 商品状态多选(仅全量模式):勾几个状态就跑几个状态 -->
<template v-if="statusModeEnabled">
<div class="section-title">商品状态 <span class="tag-badge">可多选</span></div>
<div class="country-pref-checks">
<label v-for="row in listingStatusRows" :key="row.value" class="country-check-row">
<input type="checkbox" class="country-check-input" :checked="isListingStatusSelected(row.value)"
:disabled="pushing" @change="onListingStatusToggle(row.value, $event)" />
<span class="country-check-text">{{ row.label }}</span>
</label>
</div>
<p class="hint">
勾选的状态在同一国家内各筛一遍、各跑一遍整店列表;同一 ASIN 命中多个状态只跟一次价。
某状态在该店铺没有商品时会被跳过并记进任务日志。
</p>
</template>
<!-- 按指定ASIN文档:上传 -->
<div class="section-title">执行配置</div>
<div class="mode-zone">
@@ -122,7 +138,7 @@
<!-- 状态指示 -->
<div v-if="statusModeEnabled" class="mode-status-bar">
<span class="mode-status-dot active"></span>
<span class="mode-status-text">商品状态模式:将在售(Active)ASIN纳入跟价,跳过ASIN由后台配置的店铺维度数据提供</span>
<span class="mode-status-text">商品状态模式:将{{ listingStatusSummaryText }}ASIN纳入跟价,跳过ASIN由后台配置的店铺维度数据提供</span>
</div>
<div class="run-row">
@@ -223,6 +239,10 @@ import { userNotice } from '@/shared/utils/user-notice'
import { ElMessage } from 'element-plus'
import type { TableInstance } from 'element-plus'
import AmazonToolPageShell from '@/pages/amazon/components/AmazonToolPageShell.vue';
import {
PRICE_TRACK_DEFAULT_LISTING_STATUSES,
PRICE_TRACK_LISTING_STATUSES,
} from './listingFilters'
import ModuleTemplateDownload from '@/shared/components/ModuleTemplateDownload.vue'
import FileUploadZone from '@/shared/components/FileUploadZone.vue'
import TaskCenterPanel from '@/shared/components/tasks/TaskCenterPanel.vue'
@@ -265,6 +285,7 @@ import {
stopPriceTrackLoopRun,
type PriceTrackAsinParsedRow,
type PriceTrackCandidateVo,
type PriceTrackCreateTaskRequest,
type PriceTrackCreateTaskVo,
type PriceTrackDashboardVo,
type PriceTrackExecutionMode,
@@ -342,6 +363,30 @@ const stopLoopPending = ref(false)
const statusModeEnabled = ref(true) // 按商品状态(全量)
const asinModeEnabled = ref(false) // 按指定ASIN文档(自定义)
// 商品状态多选(只在全量模式生效)。默认只勾在售=本功能上线前的行为,存量用户不勾不多跑状态。
const listingStatusRows = PRICE_TRACK_LISTING_STATUSES
const selectedListingStatuses = ref<string[]>([...PRICE_TRACK_DEFAULT_LISTING_STATUSES])
function isListingStatusSelected(value: string) {
return selectedListingStatuses.value.includes(value)
}
function onListingStatusToggle(value: string, event: Event) {
const checked = (event.target as HTMLInputElement).checked
const next = new Set(selectedListingStatuses.value)
if (checked) next.add(value)
else next.delete(value)
// 按目录顺序回写:这个顺序就是客户端逐状态筛选、逐页跑的顺序,不能跟着点击次序漂
selectedListingStatuses.value = listingStatusRows.filter((row) => next.has(row.value)).map((row) => row.value)
}
const hasValidListingStatuses = computed(() => selectedListingStatuses.value.length > 0)
const listingStatusSummaryText = computed(() => {
const labels = listingStatusRows.filter((row) => isListingStatusSelected(row.value)).map((row) => row.label)
return labels.length ? `「${labels.join(' / ')}」的` : '(一个状态都没勾,无法启动)'
})
// 上传文件
const {
files: asinUploadedFiles,
@@ -912,10 +957,21 @@ function rowKeyForMatch(row: { shopName?: string; shopId?: number | string | nul
return `${(row.shopName || '').trim()}\u0001${row.shopId ?? ''}`
}
function priceTrackModeForAppClient() {
function priceTrackModeForAppClient(child?: PriceTrackCreateTaskRequest | null) {
// 载荷的 mode 以派发回来的子任务为准,本地勾选只作兜底:onMounted 会自动续跑未完成的循环,
// 而页面刷新后本地勾选态回到默认(全量)——那时按本地态拼载荷,指定ASIN的循环会被拼成
// "全量在售跟价",等于对整店真实改价。
if (child) return child.statusMode ? 'status' : 'asin'
return statusModeEnabled.value ? 'status' : 'asin'
}
function listingStatusesForPayload(child?: PriceTrackCreateTaskRequest | null) {
const fromDispatch = (child?.listingStatuses || []).filter((item) => !!item)
// 派发值优先(循环建单时勾的那几个状态要一路跑到最后一轮,不随界面中途改勾选而变);
// 老循环没存这个字段(后端加列前的记录)时退回本地勾选。
return fromDispatch.length ? fromDispatch : [...selectedListingStatuses.value]
}
function buildMinimumPriceByCountryAndAsin(rowsByCountry: Record<string, PriceTrackAsinParsedRow[]>) {
const out: Record<string, Record<string, string>> = {}
for (const [country, rows] of Object.entries(rowsByCountry || {})) {
@@ -1023,10 +1079,12 @@ async function removeMatchedRow(row: PriceTrackShopQueueItem) {
}
// ========== 任务状态轮询 ==========
async function buildQueuePayload(taskVo: PriceTrackCreateTaskVo, row: PriceTrackShopQueueItem) {
async function buildQueuePayload(taskVo: PriceTrackCreateTaskVo, row: PriceTrackShopQueueItem,
child?: PriceTrackCreateTaskRequest | null) {
const shopName = (row.shopName || '').trim()
const asinRowsByCountry = await loadAsinRowsForAppClient(taskVo)
const minimumPriceByCountryAndAsin = buildMinimumPriceMapForAppClient(taskVo, asinRowsByCountry)
const mode = priceTrackModeForAppClient(child)
return {
type: 'price-track-run',
@@ -1035,7 +1093,10 @@ async function buildQueuePayload(taskVo: PriceTrackCreateTaskVo, row: PriceTrack
task_id: taskVo.taskId,
shop_name: shopName,
country_codes: resolveCountryCodesForRequest(),
mode: priceTrackModeForAppClient(),
mode,
// 只在状态模式下带这份清单:指定ASIN模式不发这个键,客户端就按今天的默认(在售)预筛,
// 逐字保持原行为——那一模式的搜索目标是文档里的 ASIN,不是某个状态的整店列表。
...(mode === 'status' ? { listing_statuses: listingStatusesForPayload(child) } : {}),
shopName,
companyName: row.companyName || '',
shopMallName: row.shopMallName || '',
@@ -1051,11 +1112,13 @@ async function enqueueCreatedTask(api: PywebviewApi, taskId: number, queuePayloa
// 空 country_codes 会让 Python 端没有可遍历的站点,任务永远停在 RUNNING。
// asin_rows_by_country 只在 asin 模式下要求非空——status 模式下
// loadAsinRowsForAppClient 本就返回 {},那是正常的。
// listing_statuses 只在 status 模式下要求非空:空清单到了客户端会退回"在售",
// 用户勾的其它状态就静默不跑——宁可不投也不投一个语义不对的任务。
const mode = (queuePayload as { data?: { mode?: unknown } } | null)?.data?.mode
const guard = checkQueuePayload(queuePayload, {
expectedType: 'price-track-run',
requiredDataKeys: ['task_id', 'shop_name'],
nonEmptyArrayKeys: ['country_codes'],
nonEmptyArrayKeys: mode === 'status' ? ['country_codes', 'listing_statuses'] : ['country_codes'],
nonEmptyObjectKeys: mode === 'asin' ? ['asin_rows_by_country'] : [],
})
if (!(await passGuard(guard))) {
@@ -1320,7 +1383,7 @@ async function runLoopExecution(loopId?: number) {
}
})()
recordCreatedTask(taskVo)
const queuePayload = await buildQueuePayload(taskVo, row)
const queuePayload = await buildQueuePayload(taskVo, row, childTaskRequest)
queuePayloadText.value = JSON.stringify(queuePayload, null, 2)
await enqueueCreatedTask(api, taskVo.taskId, queuePayload)
addPollingTask(taskVo.taskId)
@@ -1353,6 +1416,11 @@ async function pushToPythonLoopQueue() {
ElMessage.warning('请至少选择一个跟价模式')
return
}
if (statusModeEnabled.value && !hasValidListingStatuses.value) {
// 空清单投出去会被客户端退回"在售",用户勾的其它状态就静默不跑,所以在这里就拦住
ElMessage.warning('按商品状态跟价时请至少勾选一个商品状态')
return
}
if (asinModeEnabled.value && !asinFiles.value.length) {
ElMessage.warning('请先选择 ASIN 文件')
return
@@ -1368,6 +1436,8 @@ async function pushToPythonLoopQueue() {
const loop = await createPriceTrackLoopRun({
userId: 0,
statusMode: statusModeEnabled.value,
// 勾了哪些状态随循环落库:每一轮子任务都从这里回读,界面中途改勾选不影响已启动的循环
listingStatuses: statusModeEnabled.value ? [...selectedListingStatuses.value] : [],
asinMode: asinModeEnabled.value,
items: matchedRows,
asinFiles: resolveAsinRequestPaths(),
@@ -6,3 +6,24 @@ export const LISTING_FILTER_OPTIONS = [
] as const
export type ListingFilterValue = (typeof LISTING_FILTER_OPTIONS)[number]['value']
/**
* 跟价「按商品状态(全量)」可勾选的状态(2026-10-16 多状态立项)。
*
* value 是发给客户端的标识,必须与 app_client/amazon/amazon_base_v2.py 的
* LISTING_STATUS_CATALOG 的键逐字一致——那边按 value 精确命中页面选项,命中不到
* 再按中文文案兜底。顺序即客户端逐状态跑的顺序(在售 → 缺少的报价 → 定价问题)。
*
* MissingOffer 的页面真实取值未经真机证实(唯一可测的测试店该状态没有商品、选项不渲染),
* 所以客户端先按文案命中并把回显的取值写进日志,届时再补进目录升为第一路。
*/
export const PRICE_TRACK_LISTING_STATUSES = [
{ value: 'Active', label: '在售' },
{ value: 'MissingOffer', label: '缺少的报价' },
{ value: 'PricingIssue', label: '定价问题' },
] as const
export type PriceTrackListingStatusValue = (typeof PRICE_TRACK_LISTING_STATUSES)[number]['value']
/** 默认只勾在售=本功能上线前的行为,存量用户不勾也不会多跑状态。 */
export const PRICE_TRACK_DEFAULT_LISTING_STATUSES: PriceTrackListingStatusValue[] = ['Active']
@@ -134,6 +134,8 @@ export type PriceTrackCreateTaskPayload = Omit<
export interface PriceTrackCreateTaskRequest {
userId: number;
statusMode: boolean;
/** 状态模式下要跑的商品状态清单(Active/PricingIssue/MissingOffer);空=客户端按在售跑 */
listingStatuses?: string[];
asinMode: boolean;
items: PriceTrackShopQueueItem[];
asinFiles: string[];
@@ -148,6 +150,7 @@ export type PriceTrackExecutionMode = "FINITE" | "INFINITE";
export interface PriceTrackLoopRunCreateRequest {
userId: number;
statusMode: boolean;
listingStatuses?: string[];
asinMode: boolean;
items: PriceTrackShopQueueItem[];
asinFiles: string[];
@@ -169,6 +172,7 @@ export interface PriceTrackLoopRunVo {
stopRequested?: boolean;
errorMessage?: string;
statusMode?: boolean;
listingStatuses?: string[];
asinMode?: boolean;
asinFiles?: string[];
countryCodes?: string[];
@@ -250,3 +250,28 @@ test('test_price_track_unwrap_and_error', async (t) => {
mockRequest(t, () => Promise.resolve({ data: { success: false, message: '店铺不存在' } }))
await assert.rejects(addPriceTrackCandidate('x'), /店铺不存在/)
})
test('test_price_track_loop_run_listing_statuses_passthrough', async (t) => {
setupWindow()
let captured: { url?: string; data?: unknown } = {}
mockRequest(t, (config) => {
captured = config
return okResponse({ id: 1, status: 'RUNNING' })
})
const request: Omit<PriceTrackLoopRunCreateRequest, 'userId'> = {
statusMode: true,
listingStatuses: ['Active', 'MissingOffer', 'PricingIssue'],
asinMode: false,
items: [],
asinFiles: [],
countryCodes: ['US'],
executionMode: 'FINITE',
targetRounds: 1,
}
await createPriceTrackLoopRun(request)
assert.deepEqual(
(captured.data as Record<string, unknown>).listingStatuses,
['Active', 'MissingOffer', 'PricingIssue'],
'勾选的状态清单必须原样提交给后端——循环每一轮子任务的载荷都从后端记录回读,不吃界面当下勾选',
)
})
@@ -0,0 +1,78 @@
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'
import {
PRICE_TRACK_DEFAULT_LISTING_STATUSES,
PRICE_TRACK_LISTING_STATUSES,
} from '../src/pages/brand/components/listingFilters.ts'
/**
* 跟价「按商品状态(全量)」多状态(2026-10-16 立项)。
*
* 钉三件事:
* 1. 状态目录本身——取值必须与客户端 amazon_base_v2.LISTING_STATUS_CATALOG 的键逐字一致,
* 顺序就是客户端逐状态跑的顺序,默认只勾在售(=本功能上线前的行为);
* 2. 载荷接线——listing_statuses 只在状态模式下发、以派发值为准、空清单不入队;
* 3. mode 不再单吃本地勾选态(页面刷新后本地态回默认=全量,会把指定ASIN循环跑成全量改价)。
*/
const PAGE = join(
dirname(fileURLToPath(import.meta.url)),
'../src/pages/brand/components/BrandPriceTrackTab.vue',
)
const source = readFileSync(PAGE, 'utf8')
test('状态目录:三项、顺序稳定、取值与客户端目录同名', () => {
assert.deepEqual(
PRICE_TRACK_LISTING_STATUSES.map((row) => row.value),
['Active', 'MissingOffer', 'PricingIssue'],
'顺序即客户端逐状态筛选执行的顺序,改动要同步 app_client 的 LISTING_STATUS_CATALOG',
)
assert.deepEqual(
PRICE_TRACK_LISTING_STATUSES.map((row) => row.label),
['在售', '缺少的报价', '定价问题'],
)
assert.equal(new Set(PRICE_TRACK_LISTING_STATUSES.map((row) => row.label)).size, 3, '文案不许重复')
})
test('默认只勾在售=上线前行为,且必须是目录里的项', () => {
assert.deepEqual([...PRICE_TRACK_DEFAULT_LISTING_STATUSES], ['Active'])
const known = new Set<string>(PRICE_TRACK_LISTING_STATUSES.map((row) => row.value))
for (const value of PRICE_TRACK_DEFAULT_LISTING_STATUSES) {
assert.ok(known.has(value), `默认勾了目录外的状态 ${value}`)
}
})
test('载荷只在状态模式下带 listing_statuses', () => {
assert.match(
source,
/\.\.\.\(mode === 'status' \? \{ listing_statuses: listingStatusesForPayload\(child\) \}\s*:\s*\{\}\)/,
'指定ASIN模式不该发这个键(发了客户端会拿清单首项做预筛,改掉今天"按在售预筛"的形状)',
)
})
test('listing_statuses 为空不许入队', () => {
assert.match(source, /\['country_codes', 'listing_statuses'\]/,
'队列闸没把 listing_statuses 圈进非空数组——空清单会被客户端静默退回在售')
assert.match(source, /请至少勾选一个商品状态/, '启动前没有"至少勾一个"的拦截')
})
test('mode 与状态清单都以派发回来的子任务为准,本地勾选只作兜底', () => {
assert.match(source, /if \(child\) return child\.statusMode \? 'status' : 'asin'/,
'mode 又变成只读本地勾选态:刷新页面后指定ASIN循环会被拼成全量跟价(对整店真实改价)')
assert.match(source, /fromDispatch\.length \? fromDispatch : \[\.\.\.selectedListingStatuses\.value\]/,
'状态清单不再优先取派发值:INFINITE 循环的后续轮会随界面改勾选而漂')
assert.match(source, /buildQueuePayload\(taskVo, row, childTaskRequest\)/,
'派发链路没把 childTaskRequest 传进载荷')
})
test('勾选回写按目录顺序,不随点击次序漂', () => {
assert.match(source, /listingStatusRows\.filter\(\(row\) => next\.has\(row\.value\)\)\.map\(\(row\) => row\.value\)/,
'逐状态执行顺序变成了点击顺序,同一份勾选两次跑出的任务形状不同')
})
test('循环建单把勾选清单一起提交(后端逐轮回读的就是它)', () => {
assert.match(source, /listingStatuses: statusModeEnabled\.value \? \[\.\.\.selectedListingStatuses\.value\] : \[\]/)
})