Compare commits

..

9 Commits

Author SHA1 Message Date
huangzd1997 40f280d261 docs(跟价多状态): 状态目录注释改口——页面取值已由真机证实为 OfferMissing
上一笔写的「MissingOffer 取值未证实、先按文案兜底」已被 2026-10-17 黄建新·英国站·新版
管理商品页探针推翻:页面取值是 OfferMissing(照 PascalCase 规律推反了),映射在客户端
LISTING_STATUS_CATALOG。补一句 value 是我们的标识、不是页面取值,防止有人"顺手对齐"改键名
把载荷兼容与存量循环任务的落库值打断。
2026-10-17 00:13:41 +08:00
huangzd1997 8a20f85ca6 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 黄建新
  英国站真机实锤),两者不同形是有意的:改键名会断载荷兼容。
2026-10-17 00:07:31 +08:00
huangzd1997 6b1105f841 feat(phase-5 后管): 业务下拉恢复 删除ASIN 与 巡店删除 两项,反向钉改正向钉
- task-center-model.ts MODULE_OPTIONS 12→14:DELETE_BRAND 紧跟 PUBLISH、PATROL_DELETE 紧跟
  SHOP_MATCH(与 e1e38420~1 的历史位置一致),注释改为记录恢复口径
- task-center-board.test.ts:撤掉 e1e38420 那条「这两值再现即判红」的反向钉,改正向钉——
  两项必须以正确 value+label 单列,再消失就是判红;length>=12 上调 14
- 自证:npm test 1819/1819 绿、npm run test:mount 21/21 绿
- 部署(Phase 7)另行执行:本笔只改源码与用例,未动主机 B
2026-10-16 20:04:45 +08:00
huangzd1997 11ad68eea4 feat(phase-4/5 用户端): 恢复巡店删除与指定删除ASIN两个功能页与全部表件
用户口径:这两个功能是随 fdaae3c5 连带删错(该退役的只有紫鸟新版/旧版选项控件),
本次按历史逐字找回并摘掉紫鸟引用。

- 页面:BrandDeleteBrandTab.vue(1740行) / BrandPatrolDeleteTab.vue(1370行) 从 fdaae3c5~1 找回,
  两页各摘 5 处 ZiniaoVersionSetting/useZiniaoVersion 引用与 1 个 ziniao_version 载荷字段
  (checkQueuePayload 只钉 taskId,摘掉不触闸;全树其余读点 0 处)
- 表件:router 两条路由、tool-catalog 18→20 工具与四条图标/详情、BrandTopBar 导航两条、
  endpoints 两块(deleteBrand 10 键 / patrolDelete 16 键)、progress-light 10→12、
  java-modules re-export、module-templates 联合、withdraw.ts 巡店段整文件找回(513 行,
  含两个 ProductRisk*Vo import)
- 测试面:9 支退役时改过的用例从 fdaae3c5~1 逐字找回(含 modules-delete-brand.test.ts 167 行/11 例)
- 自证:npm test 854/854 绿(基线 840+找回 14 例)、vue-tsc --noEmit 与 vite build 通过
- 未触碰他人在飞件:BrandSimilarAsinTab.vue / task-status-text.ts / similar-asin-fake-completed.test.ts

注:恢复后的三支大文件将顶破 ops 侧 readability 棘轮,基线随本轮在 ops 仓重锚并登记。
2026-10-16 20:04:40 +08:00
huangzd1997 ffeb777c38 task-7: 递归语义 8 例落地(RED 实录:隐藏目录/链接重复计入/遍历失败三格真红);实测证伪 plan 假设——Files.walk 会钻进 Windows junction 读出 [One.java,One.java],且公开 NIO 无 isReparsePoint,改按 toRealPath 折叠 2026-10-16 16:44:20 +08:00
huangzd1997 77b4f49f55 task-6: moduleSources 目录聚合入口落地 8 例(RED 实录 8 格全红);实测发现 plan 原文「相对 src/main/java 解析」与本仓布局不符——模块目录实相对包基址 com/nanri/aiimage,只按字面解析读回 0 支,正是要防的死法 2026-10-16 16:22:43 +08:00
huangzd1997 d4107ca904 task-5: 同名面普查落地 8 例(RED 实录 8 格全红);实测 3 组同名与点名 10 裸名交集为 0、主源码 973 支/970 唯一名,N20 收紧的前提得证 2026-10-16 16:04:57 +08:00
huangzd1997 5c3668fc2e task-4: SourceScan 点名普查落地 8 例(RED 实录 1 Failure+7 Errors);台账 15 调用点/8 调用方/10 裸名,plan 原文「9 支文件」经核为把 SourceScan.java:22 声明行算进分母 2026-10-16 15:46:30 +08:00
huangzd1997 e1e3842045 后管业务下拉摘掉退役两项:删除ASIN 与 巡店删除(14→12),并反向钉住不许回流
随旧版亚马逊界面退役的收尾:用户定案这两项功能入口不要再出现。
- src/pages/task-center/task-center-model.ts:MODULE_OPTIONS 摘掉 DELETE_BRAND / PATROL_DELETE;
  注释写明这是**有意少列**——后端 TaskModuleRegistry 的枚举与历史行都还在(按 module_type 存),
  只是 UI 不再单列筛选,要查这两类历史单只能从「全部业务」里看。
- tests/task-center-board.test.ts:原 `>= 13` 随实况收到 `>= 12`,并补一条反向钉——
  这两值一旦重新出现在下拉里就判红(放宽必须有理由,理由写在注释里)。

Java 侧 /api/delete-brand/** 与 /api/patrol-delete/** 端点本轮不动:它们仍服务历史单的
读取/下载/进度面,摘掉会让管理员查不到已发生的事。

已发布:npm run build(16.77s)→ scripts/_deploy_admin_vue.py → 主机B
/var/www/admin-vue-20261016-100735(64 文件远程 md5 逐份等值,回滚点 20261014-100845)。
现网回读三条:入口 assets/index-DN6qtjkF.js;现网目录内 DELETE_BRAND / PATROL_DELETE /
巡店删除 命中 0;回滚点里两者各剩 1 处(证明这把尺子量的不是恒零)。
npm test:1819/1819 绿。
2026-10-16 10:52:35 +08:00
39 changed files with 5214 additions and 39 deletions
@@ -27,7 +27,12 @@ export function createVariantFilter(): TaskCenterVariantFilter {
return { status: '' }
}
/** 业务下拉:与后端 TaskModuleRegistry 的客户端模块(biz_file_task 12 个 + 品牌检测)对齐。 */
/**
* 业务下拉:与后端 TaskModuleRegistry 的客户端模块(biz_file_task 10 个 + 品牌检测)对齐。
* 2026-10-16 恢复两项:删除ASIN(DELETE_BRAND) 与 巡店删除(PATROL_DELETE) 按用户口径随功能
* 一起回到下拉(此前随旧版亚马逊界面退役属连带删错;该退役的只有紫鸟新版/旧版选项控件)。
* 用例侧已把原先的反向钉改成正向钉,这两项再消失就是判红。
*/
export const MODULE_OPTIONS: Array<{ value: string; label: string }> = [
{ value: '', label: '全部业务' },
{ value: 'PUBLISH', label: '上架' },
@@ -106,7 +106,15 @@ test('task_center_status_labels_cover_backend_states', () => {
assert.equal(TASK_STATUS_OPTIONS[0].value, '')
assert.equal(MODULE_OPTIONS[0].value, '', '首项为「全部业务」')
assert.equal(MODULE_OPTIONS.slice(1).every((o) => o.value && o.label), true)
assert.ok(MODULE_OPTIONS.length >= 13, '业务下拉覆盖客户端模块')
assert.ok(MODULE_OPTIONS.length >= 14, '业务下拉覆盖客户端模块(2026-10-16 删除ASIN/巡店删除恢复后 12→14)')
// 正向钉:2026-10-16 用户口径恢复这两项。此前那条「退役不许回流」的反向钉随功能恢复一并作废——
// 后端 TaskModuleRegistry 的枚举一直在,前端下拉与它对齐;这两值再消失就是判红。
assert.equal(
MODULE_OPTIONS.some((o) => o.value === 'DELETE_BRAND' && o.label === '删除ASIN'),
true, '删除ASIN 必须单列在下拉里(恢复后不许再消失)')
assert.equal(
MODULE_OPTIONS.some((o) => o.value === 'PATROL_DELETE' && o.label === '巡店删除'),
true, '巡店删除 必须单列在下拉里(恢复后不许再消失)')
})
test('task_center_variant_status_map_follows_maixiang_semantics', () => {
@@ -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);
@@ -2,9 +2,15 @@ package com.nanri.aiimage.testutil;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileVisitOption;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import java.util.stream.Stream;
@@ -16,6 +22,234 @@ public final class SourceScan {
private SourceScan() {
}
/** 一处 {@code sourceText("<裸名>")} 字面量点名。 */
public record CallSite(String bareName, String relativeFile, int line) {
}
/** 本仓主源码的包基址:模块目录实际相对的是它,不是 src/main/java 本身。 */
private static final String PACKAGE_BASE = "com/nanri/aiimage";
private static final Pattern CALL_SITE = Pattern.compile("sourceText\\(\\s*\"([^\"]+)\"\\s*\\)");
/** {@code src/test/java} 的绝对根,与 {@link #mainSources()} 同一条定位分支。 */
public static Path testSourcesRoot() {
Path root = moduleRoot().resolve("src/test/java");
if (!Files.isDirectory(root)) {
throw new IllegalStateException("语料根不存在: " + root + "(cwd=" + Path.of("").toAbsolutePath() + ")");
}
return root;
}
/** 点名普查:列出 {@code src/test/java} 里每一处 {@code sourceText("<裸名>")} 字面量调用。 */
public static List<CallSite> censusSourceTextCallSites() {
return censusSourceTextCallSites(testSourcesRoot());
}
/**
* 点名普查(可指定语料根)。三条设计决定都是被坑逼出来的:
* <ol>
* <li><b>数的是代码不是文字</b>:判据打在 {@link #withoutComments} 上,注释里提一句
* {@code sourceText("Fake.java")} 不计入——否则台账的 15 会被 javadoc 喂成任意大的数。</li>
* <li><b>只配字面量</b>:正则要求紧跟一对引号,所以 {@code SourceScan.java:22} 那行
* 被调方自己的声明(参数是 {@code String fileName})天然不算调用点。plan 原文的「9 支文件」
* 正是 {@code grep -rl 'sourceText('} 把声明也算了进去;真实调用点是 15 处/8 支文件。</li>
* <li><b>语料根不存在必须抛</b>,不许返回空表:空表会被读成「已经没人用裸名口径了」。
* 目录存在且确实没有 {@code .java} 才返回空——那是"语料真的没了",与"尺子架错地方"是两回事。</li>
* </ol>
*/
public static List<CallSite> censusSourceTextCallSites(Path corpusRoot) {
Path root = corpusRoot.toAbsolutePath();
if (!Files.isDirectory(root)) {
throw new IllegalStateException("语料根不存在: " + root + "(cwd=" + Path.of("").toAbsolutePath() + ")");
}
Path base = moduleRoot();
List<CallSite> sites = new java.util.ArrayList<>();
// N7 之后普查与聚合共用同一条遍历(含隐藏目录/重解析点排除),免得两套口径读出不一样多的文件
for (Path file : collectJavaFiles(root)) {
String code = withoutComments(read(file));
String relative = relativizeForCensus(file, root, base).replace('\\', '/');
Matcher matcher = CALL_SITE.matcher(code);
while (matcher.find()) {
sites.add(new CallSite(matcher.group(1), relative, lineAt(code, matcher.start())));
}
}
return List.copyOf(sites);
}
private static String relativizeForCensus(Path file, Path corpusRoot, Path moduleRoot) {
Path absolute = file.toAbsolutePath();
if (absolute.startsWith(moduleRoot)) {
return moduleRoot.relativize(absolute).toString();
}
return corpusRoot.relativize(absolute).toString();
}
/** 偏移不变的 {@link #withoutComments} 保证:剥完再数换行,行号仍等于原文件行号。 */
private static int lineAt(String code, int offset) {
int line = 1;
for (int i = 0; i < offset; i++) {
if (code.charAt(i) == '\n') {
line++;
}
}
return line;
}
/** {@code src/main/java} 的绝对根。定位不到必须抛——理由与 {@link #mainSources()} 同一条。 */
public static Path mainSourcesRoot() {
Path root = moduleRoot().resolve("src/main/java");
if (!Files.isDirectory(root)) {
throw new IllegalStateException("源码根不存在: " + root + "(cwd=" + Path.of("").toAbsolutePath() + ")");
}
return root;
}
/** 主源码面全部 {@code .java},按相对路径字典序(与 {@link #censusSourceTextCallSites} 同一条排序键)。 */
public static List<Path> mainSourceFiles() {
return collectJavaFiles(mainSourcesRoot());
}
/** 同名面普查:{@code src/main/java} 下裸文件名出现 >1 次的那些。 */
public static java.util.Map<String, List<String>> duplicateMainSourceNames() {
return duplicateSourceNames(mainSourcesRoot());
}
/**
* 分组键是<b>裸文件名</b>——因为 {@link #sourceText(String)} 就是按裸名找文件的,
* 两个包下放同名件,那个助手就会命中 >1(N20 要把它改成歧义即抛)。
* 只算 {@code .java}:{@code Foo.md} 与 {@code Foo.java} 不同名,把文档也算进来会让聚合面多吃一支。
*/
public static java.util.Map<String, List<String>> duplicateSourceNames(Path treeRoot) {
Path root = treeRoot.toAbsolutePath();
if (!Files.isDirectory(root)) {
throw new IllegalStateException("同名面普查的树根不是目录: " + root + "(cwd="
+ Path.of("").toAbsolutePath() + ")");
}
java.util.Map<String, List<String>> grouped = new java.util.TreeMap<>();
for (Path file : collectJavaFiles(root)) {
grouped.computeIfAbsent(file.getFileName().toString(), k -> new java.util.ArrayList<>())
.add(root.relativize(file).toString().replace('\\', '/'));
}
grouped.entrySet().removeIf(entry -> entry.getValue().size() < 2);
return java.util.Map.copyOf(grouped);
}
/**
* 模块聚合入口(N6 定「正常返回」):列出 {@code src/main/java} 下该模块目录里所有 {@code .java}。
*
* <p>为什么需要它:归属类护栏此前只能 {@code sourceText("XxxService.java")} 逐文件点,而一座上帝类拆成
* {@code service/} + {@code service/support/} 之后,被禁写法只要搬进 support 文件,旧格子<b>照样绿</b>。
* 目录口径才是这条护栏的成立前提,所以这里按目录求值,且递归任意深度(N7)。</p>
*
* <p>本格只定「目录存在 ⇒ 返回不可变、按相对路径字典序的 {@code List<Path>}」。
* 「目录不存在 ⇒ 抛」由 N10 定义、「0 支 .java ⇒ 抛」由 N11 定义(零文件绝不许读成零违规)。</p>
*/
public static List<Path> moduleSources(String moduleRelDir) {
return moduleSources(mainSourcesRoot(), moduleRelDir);
}
/** 可注入语料根的同义重载:合成树场景(中文目录、越界、空目录)必须在不动业务树的前提下被测。 */
public static List<Path> moduleSources(Path javaRoot, String moduleRelDir) {
Path root = javaRoot.toAbsolutePath();
if (!Files.isDirectory(root)) {
throw new IllegalStateException("源码根不存在: " + root + "(cwd=" + Path.of("").toAbsolutePath() + ")");
}
String normalized = moduleRelDir == null ? "" : moduleRelDir.replace('\\', '/');
while (normalized.startsWith("/")) {
normalized = normalized.substring(1);
}
while (normalized.endsWith("/")) {
normalized = normalized.substring(0, normalized.length() - 1);
}
Path module = root.resolve(normalized).normalize();
if (!Files.isDirectory(module)) {
/*
* ⚠ plan N6 原文写「相对 {@code src/main/java} 解析目录」,但本仓的模块目录实际相对的是
* <b>包基址</b>:真实路径是 {@code src/main/java/com/nanri/aiimage/modules/appearancepatent}。
* 只按 plan 字面解析会得到 0 支文件——而那正是 N11 要防的死法(读不到被当成没违规)。
* 所以这里先按字面试、再按包基址试;两条都不存在时保留字面路径,交给 N10 的「目录不存在 ⇒ 抛」。
*/
Path underBase = root.resolve(PACKAGE_BASE).resolve(normalized).normalize();
if (Files.isDirectory(underBase)) {
module = underBase;
}
}
if (!normalized.isEmpty() && !module.startsWith(root)) {
throw new IllegalArgumentException("模块目录越界出 src/main/java: 请求「" + moduleRelDir
+ "」解析为 " + module + "(根=" + root + ",cwd=" + Path.of("").toAbsolutePath() + ")"
+ " —— 聚合面只许吃主源码树,越界就等于把整台机器读进来");
}
if (!Files.isDirectory(module)) {
return List.of(); // N10 会把它改成抛;N6 只定正常返回
}
return List.copyOf(collectJavaFiles(module));
}
/**
* 收集 {@code root} 下任意深度的 {@code .java}(N7 定递归语义)。用 {@code walkFileTree} 而不是
* {@code Files.walk},因为三种失败模式必须在<b>进入之前</b>决定,事后 filter 来不及:
* <ol>
* <li><b>隐藏目录不进面</b>:{@code .git/}、{@code .idea/} 里的 {@code .java} 是工具生成的副本,
* 进面等于同一份代码被数两遍,精确计数格(publish 恰 1)当场失真。</li>
* <li><b>重解析点不进面</b>:本机实测 {@code Files.walk} <b>会</b>钻进 Windows 的 junction
* (用例读出 {@code [One.java, One.java]}),"默认不 FOLLOW_LINKS 所以安全"这条假设已被证伪。
* {@code dos:ReparsePoint} 属性是公开 API 里唯一的识别手段({@code DosFileAttributes} 接口上没有 isReparsePoint())。</li>
* <li><b>遍历失败必须抛</b>:{@code visitFileFailed} 与"根本不存在"两条道都包成
* {@code IllegalStateException} 并点名路径——吞成空表就是「读不到 = 没违规」。</li>
* </ol>
*/
static List<Path> collectJavaFiles(Path root) {
Path start = root.toAbsolutePath();
java.util.Map<Path, Path> deduped = new java.util.LinkedHashMap<>();
try {
Files.walkFileTree(start, java.util.EnumSet.noneOf(FileVisitOption.class), Integer.MAX_VALUE,
new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) {
return !dir.equals(start) && isExcludedDirectory(dir)
? FileVisitResult.SKIP_SUBTREE
: FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
String name = file.getFileName().toString();
if (name.endsWith(".java") && !name.startsWith(".")) {
deduped.putIfAbsent(realPathOf(file), file);
}
return FileVisitResult.CONTINUE;
}
@Override
public FileVisitResult visitFileFailed(Path file, IOException exc) {
throw new IllegalStateException("遍历 " + start + " 时在 " + file + " 失败: "
+ exc.getMessage(), exc);
}
});
} catch (IOException e) {
throw new IllegalStateException("遍历 " + start + " 失败: " + e.getMessage(), e);
}
List<Path> found = new java.util.ArrayList<>(deduped.values());
found.sort(java.util.Comparator.comparing(p -> start.relativize(p).toString().replace('\\', '/')));
return List.copyOf(found);
}
/** 链接折叠用的键;拿不到实路径(并发被删等)就退回绝对路径,宁可少折一次也不吞异常。 */
private static Path realPathOf(Path file) {
try {
return file.toRealPath();
} catch (IOException e) {
return file.toAbsolutePath().normalize();
}
}
private static boolean isExcludedDirectory(Path dir) {
if (dir.getFileName().toString().startsWith(".") || Files.isSymbolicLink(dir)) {
return true;
}
return false;
}
/** 按文件名(不含目录)取 {@code src/main/java} 下那份源码的<b>全文字符串</b>。
* ⚠️ 返回 String,与 InternalTokenSingleOutletTest 里那个返回 Path 的私有 {@code sourceOf} 不是一回事,
* 别指望复用它的——那个是 private。 */
@@ -0,0 +1,490 @@
package com.nanri.aiimage.testutil;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
/**
* {@link SourceScan} 自己的护栏(2026-10-16,plan 01 N4 起)。
*
* <p><b>N4 点名普查台账</b>(由 {@code census_sourceText调用点总数不少于10} 那格机器复算,不是手抄):</p>
* <pre>
* 被点名裸名(10 个唯一) 字面量调用点 出处
* ---------------------------------------------------------------------------
* PublishController.java 3 PublishOwnershipGuardrailTest:42 :82 :96
* AdminApiGuardFilter.java 2 AdminGuardSwitchConfigTest:107 :254
* AdminDeviceLogController.java 2 DeviceLogServiceTest:412 :428
* LockSkipWitness.java 2 LockSkipWitnessTest:178 + LockSkipSilentExitGuardrailTest:153
* AppearancePatentTaskService.java 1 PublishOwnershipGuardrailTest:111
* PublishTaskService.java 1 PublishOwnershipGuardrailTest:109
* SimilarAsinTaskService.java 1 PublishOwnershipGuardrailTest:112
* ClientVersionGuardFilter.java 1 ClientVersionFloorConfigTest:249
* PermissionMenuService.java 1 MenuWriteOutletOperatorTest:30
* ShopManageController.java 1 ShopManageServiceTest:185
* ---------------------------------------------------------------------------
* 合计 15 落在 <b>8</b> 支调用方文件里
* </pre>
*
* <p><b>一处与 plan 原文不符的读数,按"先怀疑尺子"的流程处理并留在脸上</b>:plan/AGENTS §1 记的是「9 支文件」,
* 那条数是 {@code grep -rl 'sourceText('} 数出来的,而第 9 支是 {@code SourceScan.java:22} 里
* {@code public static String sourceText(String fileName)} 这行<b>被调方自己的声明</b>——它不是调用点。
* 所以真实形状是 <b>15 个调用点/8 支调用方/9 支引用方文件</b>。下面第 3 格把这三个数同时钉住,
* 免得下一个人拿 {@code grep} 再数一遍又把声明算进去。</p>
*/
class SourceScanTest {
/** 台账里登记过的 10 个被点名裸名,逐字对撞用。 */
private static final Set<String> REGISTERED_BARE_NAMES = Set.of(
"PublishController.java",
"PublishTaskService.java",
"AppearancePatentTaskService.java",
"SimilarAsinTaskService.java",
"AdminApiGuardFilter.java",
"AdminDeviceLogController.java",
"ClientVersionGuardFilter.java",
"LockSkipWitness.java",
"PermissionMenuService.java",
"ShopManageController.java");
@TempDir
Path tmp;
@Test
void census_sourceText调用点总数不少于10() {
List<SourceScan.CallSite> sites = SourceScan.censusSourceTextCallSites();
assertThat(sites)
.as("普查扫到的字面量调用点总数——下限判据:扫到 0 会被误读成「已经没人点名单文件了」,"
+ "而真相往往是语料根没找对")
.hasSizeGreaterThanOrEqualTo(10);
}
@Test
void census_唯一裸名恰为10且与已登记集合相等() {
Set<String> found = SourceScan.censusSourceTextCallSites().stream()
.map(SourceScan.CallSite::bareName)
.collect(Collectors.toSet());
assertThat(found)
.as("唯一裸名集合必须与类头台账逐字相等——多一个说明有人新引了单文件口径,少一个说明尺子漏扫")
.isEqualTo(REGISTERED_BARE_NAMES)
.hasSize(10);
}
@Test
void census_涉及文件恰为9() {
List<SourceScan.CallSite> sites = SourceScan.censusSourceTextCallSites();
Set<String> callerFiles = sites.stream()
.map(SourceScan.CallSite::relativeFile)
.collect(Collectors.toSet());
String declarationFile = "src/test/java/com/nanri/aiimage/testutil/SourceScan.java";
assertThat(callerFiles)
.as("真实字面量调用点落在 8 支调用方文件里")
.hasSize(8);
assertThat(callerFiles)
.as("plan 原文记的「9 支」= grep -rl 'sourceText(' 的条数,第 9 支是被调方自己的声明行"
+ "(SourceScan.java:22 的 `public static String sourceText(String fileName)`),"
+ "它不是调用点。这里把「声明件必须落在调用方集合之外」钉成机器判,"
+ "免得下一个人再拿 grep 数一遍把声明算进分母")
.doesNotContain(declarationFile);
assertThat(Path.of(declarationFile)).exists();
}
@Test
void census_空语料目录返回空而非抛() throws IOException {
Path empty = Files.createDirectories(tmp.resolve("empty_corpus"));
assertThat(SourceScan.censusSourceTextCallSites(empty))
.as("目录存在且确实是空的 ⇒ 返回空表。这与「目录不存在必须抛」是两回事,"
+ "前者是语料真的没了,后者是尺子架错了地方")
.isEmpty();
}
@Test
void census_中文路径文件被计入不丢失() throws IOException {
Path corpus = Files.createDirectories(tmp.resolve("语料根"));
Path chineseDir = Files.createDirectories(corpus.resolve("中文语料"));
Files.writeString(chineseDir.resolve("点名中文件.java"),
"class A { void x() { SourceScan.sourceText(\"PublishController.java\"); } }",
StandardCharsets.UTF_8);
List<SourceScan.CallSite> sites = SourceScan.censusSourceTextCallSites(corpus);
assertThat(sites)
.as("本仓有几百支中文名的测试件;遍历若按非 UTF-8 出口处理就会静默漏掉它们")
.singleElement()
.satisfies(site -> {
assertThat(site.bareName()).isEqualTo("PublishController.java");
assertThat(site.relativeFile()).contains("中文语料");
});
}
@Test
void census_同名多次调用逐条计数不合并() {
List<SourceScan.CallSite> publishController = SourceScan.censusSourceTextCallSites().stream()
.filter(site -> site.bareName().equals("PublishController.java"))
.toList();
assertThat(publishController)
.as("同一个裸名被点 3 次就必须是 3 条,按名去重会把「三格钉同一方法」这族形状抹平")
.hasSize(3)
.extracting(SourceScan.CallSite::line)
.containsExactlyInAnyOrder(42, 82, 96);
}
@Test
void census_非法正则模式不影响解析() throws IOException {
Path corpus = Files.createDirectories(tmp.resolve("混淆语料"));
Files.writeString(corpus.resolve("Mixed.java"), String.join("\n",
"class Mixed {",
" // 有人在注释里写 SourceScan.sourceText(\"CommentFake.java\") —— 这不算点名",
" static final String DOC = \"别学这个 sourceText(\\\"LiteralFake.java\\\") 的写法\";",
" void real() { SourceScan.sourceText(\"RealOne.java\"); }",
"}",
""),
StandardCharsets.UTF_8);
List<SourceScan.CallSite> sites = SourceScan.censusSourceTextCallSites(corpus);
assertThat(sites)
.as("真点名 1 条:注释里的那条要被判掉(护栏数的是代码不是文字),"
+ "字符串字面量里那条带转义引号,正则不该配上")
.singleElement()
.satisfies(site -> assertThat(site.bareName()).isEqualTo("RealOne.java"));
}
@Test
void census_扫不到源码根时抛并回显cwd() {
Path wrong = tmp.resolve("少爬了一层");
assertThatThrownBy(() -> SourceScan.censusSourceTextCallSites(wrong))
.as("根目录不存在时必须炸,不许返回空表——「扫不到」被读成「没人在用」是本族护栏的标准死法")
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("cwd=")
.hasMessageContaining(wrong.toAbsolutePath().toString());
}
// ---------------------------------------------------------------- N5 同名面普查
@Test
void duplicateNames_实测三组且不多不少() {
assertThat(SourceScan.duplicateMainSourceNames().keySet())
.as("src/main/java 下同名 >1 的裸文件名——实测就这三组,多一组说明有新落点,少一组说明有人搬走了")
.containsExactlyInAnyOrder(
"BoundedImageCache.java",
"GroupDeletionGuard.java",
"SkipPriceAsinPageVo.java");
}
@Test
void duplicateNames_与点名单交集为空() {
Set<String> duplicates = SourceScan.duplicateMainSourceNames().keySet();
assertThat(duplicates)
.as("这是 N20 把 sourceText 收紧成「歧义即抛」的前提证明:今天被点名的 10 个裸名"
+ "全部单命中,所以当场不会打红。若未来第 11 个点名撞上这三组之一,"
+ "N20 会当场红——那是正确行为,不是回归")
.doesNotContainAnyElementsOf(REGISTERED_BARE_NAMES);
}
@Test
void duplicateNames_全树java数不少于900() {
assertThat(SourceScan.mainSourceFiles())
.as("分母下限:扫到 0 支必须被读成尺子坏了,而不是「主源码空了」")
.hasSizeGreaterThanOrEqualTo(900);
}
@Test
void duplicateNames_唯一名数小于总文件数() {
List<Path> all = SourceScan.mainSourceFiles();
long uniqueNames = all.stream()
.map(p -> p.getFileName().toString())
.distinct()
.count();
assertThat(uniqueNames)
.as("973 支文件 / 970 个唯一名 ⇒ 确有 3 组同名。相等就说明同名面被搬空了,N5 的台账要同步改")
.isLessThan((long) all.size());
}
@Test
void duplicateNames_空目录返回空集合() throws IOException {
Path empty = Files.createDirectories(tmp.resolve("空树"));
assertThat(SourceScan.duplicateSourceNames(empty))
.as("目录存在且没有 .java ⇒ 空 Map(与 N4 的「语料真空」同一条口径)")
.isEmpty();
}
@Test
void duplicateNames_同名恰好三支时计数为3() throws IOException {
for (String dir : new String[] {"a", "b/c", "d/e/f"}) {
Path sub = Files.createDirectories(tmp.resolve("三支").resolve(dir));
Files.writeString(sub.resolve("Trio.java"), "class Trio {}", StandardCharsets.UTF_8);
}
assertThat(SourceScan.duplicateSourceNames(tmp.resolve("三支")))
.as("三支同名必须聚成一组、值为 3 条路径;分组写成「每对相邻比较」就会数出 3 组")
.containsEntry("Trio.java", List.of(
"a/Trio.java", "b/c/Trio.java", "d/e/f/Trio.java"));
}
@Test
void duplicateNames_忽略非java文件同名() throws IOException {
Path tree = Files.createDirectories(tmp.resolve("混放树"));
Files.createDirectories(tree.resolve("docs"));
Files.writeString(tree.resolve("Foo.java"), "class Foo {}", StandardCharsets.UTF_8);
Files.writeString(tree.resolve("docs").resolve("Foo.md"), "# Foo", StandardCharsets.UTF_8);
assertThat(SourceScan.duplicateSourceNames(tree))
.as("`Foo.md` 与 `Foo.java` 不同名——只按裸名分组会把文档也算成同名,聚合面就多吃一支")
.isEmpty();
}
@Test
void duplicateNames_路径不可读时抛不静默跳过() throws IOException {
Path notADirectory = Files.writeString(tmp.resolve("我是文件不是目录"), "x", StandardCharsets.UTF_8);
assertThatThrownBy(() -> SourceScan.duplicateSourceNames(notADirectory))
.as("传进来的是文件而非目录 ⇒ 必须抛。静默返回空 Map 会被读成「主源码没有同名件」")
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("cwd=");
}
// ---------------------------------------------------------------- N6 moduleSources
@Test
void moduleSources_appearancepatent返回28支含既有support件() {
List<Path> files = SourceScan.moduleSources("modules/appearancepatent");
assertThat(files)
.as("真实集成:对真仓目录求值。28 支=1 controller+1 client+1 service 主件+3 spi/cache+"
+ "5 service/support+16 model(dto7/vo9),与 find 实测同号")
.hasSize(28);
assertThat(files.stream().map(p -> p.toString().replace('\\', '/')).toList())
.as("support 目录里的既有件必须在面里——聚合入口存在的理由就是拆分后的新文件要自动被看到")
.anyMatch(rel -> rel.endsWith("service/support/AppearancePatentRowNormalizer.java"));
}
@Test
void moduleSources_返回列表不可变() {
List<Path> files = SourceScan.moduleSources("modules/appearancepatent");
assertThatThrownBy(() -> files.add(Path.of("塞一支进去.java")))
.as("调用方改坏面 ⇒ 同一轮里后一格读到的就不是真面了")
.isInstanceOf(UnsupportedOperationException.class);
}
@Test
void moduleSources_相对路径与绝对路径两种写法都接受() {
List<Path> plain = SourceScan.moduleSources("modules/appearancepatent");
assertThat(SourceScan.moduleSources("/modules/appearancepatent"))
.as("前导斜杠写法与裸相对写法必须同面,否则同一个模块会有两种口径")
.isEqualTo(plain);
assertThat(SourceScan.moduleSources("modules/appearancepatent/"))
.as("尾斜杠同理")
.isEqualTo(plain);
assertThat(SourceScan.moduleSources("modules\\appearancepatent"))
.as("Windows 反斜杠写法")
.isEqualTo(plain);
}
@Test
void moduleSources_空目录场景留给N11本task先返回空() throws IOException {
Path javaRoot = Files.createDirectories(tmp.resolve("N6空场景树/src/main/java"));
Files.createDirectories(javaRoot.resolve("modules/zzz_empty"));
assertThat(SourceScan.moduleSources(javaRoot, "modules/zzz_empty"))
.as("N6 只定「正常返回」:目录存在且为空 ⇒ 先返回空表不抛。"
+ "N11 会把这条改成抛(零文件绝不许读成零违规),届时更新本例")
.isEmpty();
}
@Test
void moduleSources_深层相对路径越界到src外时拒绝() {
assertThatThrownBy(() -> SourceScan.moduleSources("modules/../../../Windows"))
.as("`..` 逃逸出 src/main/java ⇒ 必须挡。挡不住就等于聚合面能把整台机器读进来")
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("越界");
}
@Test
void moduleSources_路径含中文时正确解析() throws IOException {
Path javaRoot = Files.createDirectories(tmp.resolve("N6中文树/src/main/java"));
Path module = Files.createDirectories(javaRoot.resolve("modules/模块中文"));
Files.writeString(module.resolve("中文件.java"), "class A {}", StandardCharsets.UTF_8);
List<Path> chinese = SourceScan.moduleSources(javaRoot, "modules/模块中文");
assertThat(chinese)
.as("主源码树今天没有中文名件,但语料根与相对目录都得过 UTF-8 这条道:这里用合成树把它钉住")
.hasSize(1);
assertThat(chinese.get(0).getFileName().toString()).isEqualTo("中文件.java");
}
@Test
void moduleSources_返回类型是Path不是字符串() {
List<Path> files = SourceScan.moduleSources("modules/appearancepatent");
assertThat(files).allSatisfy(p -> assertThat(p).isInstanceOf(Path.class));
assertThat(files).allSatisfy(p -> assertThat(p.isAbsolute()).isTrue());
assertThat(files).allSatisfy(p -> assertThat(Files.isRegularFile(p)).isTrue());
}
@Test
void moduleSources_找不到源码根时抛并回显cwd() {
Path wrong = tmp.resolve("少爬了一层/src/main/java");
assertThatThrownBy(() -> SourceScan.moduleSources(wrong, "modules/appearancepatent"))
.as("根目录不存在必须抛并回显 cwd——静默返回空表会让整条聚合护栏恒绿")
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("cwd=")
.hasMessageContaining(Path.of("").toAbsolutePath().toString());
}
// ---------------------------------------------------------------- N7 递归语义
@Test
void recursive_包含service下的直接件() {
assertThat(SourceScan.moduleSources("modules/appearancepatent"))
.as("模块根下第一层的 service/ 直接件必须在面里")
.anyMatch(p -> p.toString().replace('\\', '/').endsWith(
"service/AppearancePatentTaskService.java"));
}
@Test
void recursive_包含service_support下的既有5件() {
List<String> support = SourceScan.moduleSources("modules/appearancepatent").stream()
.map(p -> p.toString().replace('\\', '/'))
.filter(rel -> rel.contains("/service/support/"))
.toList();
assertThat(support)
.as("真实集成:对真仓 modules/appearancepatent/service/support 求值,实测 5 支。"
+ "这一格就是聚合入口存在的理由——拆分出去的新文件必须自动进面")
.hasSize(5);
}
@Test
void recursive_包含model下两层dto与vo() {
List<String> rel = SourceScan.moduleSources("modules/appearancepatent").stream()
.map(p -> p.toString().replace('\\', '/'))
.toList();
assertThat(rel.stream().filter(p -> p.contains("/model/dto/")).count())
.as("model/dto 一层嵌套")
.isEqualTo(7);
assertThat(rel.stream().filter(p -> p.contains("/model/vo/")).count())
.as("model/vo 一层嵌套")
.isEqualTo(9);
}
@Test
void recursive_深度为1的目录不出现在面里() throws IOException {
Path module = Files.createDirectories(tmp.resolve("N7深度树/src/main/java/modules/deep"));
Path deep = Files.createDirectories(module.resolve("a/b/c"));
Files.writeString(deep.resolve("D.java"), "class D {}", StandardCharsets.UTF_8);
Files.writeString(module.resolve("Root.java"), "class Root {}", StandardCharsets.UTF_8);
List<Path> files = SourceScan.moduleSources(tmp.resolve("N7深度树/src/main/java"), "modules/deep");
assertThat(files)
.as("三层嵌套里的 a/b/c/D.java 必须被计入:只爬一层的实现会静默漏掉它,"
+ "而 support/ 恰恰就是这一层以下的位置")
.extracting(p -> p.getFileName().toString())
.containsExactlyInAnyOrder("D.java", "Root.java");
assertThat(files)
.as("面里只许有文件——目录本身不是元素,否则聚合文本会多出无内容条目")
.allMatch(Files::isRegularFile);
}
@Test
void recursive_隐藏目录件被排除() throws IOException {
Path module = Files.createDirectories(tmp.resolve("N7隐藏树/src/main/java/modules/vis"));
Path hidden = Files.createDirectories(module.resolve(".git"));
Files.writeString(hidden.resolve("Ghost.java"), "class Ghost {}", StandardCharsets.UTF_8);
Files.writeString(module.resolve("Real.java"), "class Real {}", StandardCharsets.UTF_8);
assertThat(SourceScan.moduleSources(tmp.resolve("N7隐藏树/src/main/java"), "modules/vis"))
.as(".git / .idea 这类目录里的 .java(IDE 与工具生成的副本)不许进面——"
+ "否则同一份代码会被算两遍,精确计数格(publish 恰 1)当场失真")
.extracting(p -> p.getFileName().toString())
.containsExactly("Real.java");
}
@Test
void recursive_符号链接目录不被重复计入() throws IOException, InterruptedException {
Path javaRoot = Files.createDirectories(tmp.resolve("N7链树/src/main/java"));
Path real = Files.createDirectories(javaRoot.resolve("modules/linkreal"));
Files.writeString(real.resolve("One.java"), "class One {}", StandardCharsets.UTF_8);
// Windows 上建符号链接要特权,junction 不用:mklink /J 是本机的可复现路径。
// ⚠ 这里刻意不用 Assumptions 跳过——跳过会新增一格 Skipped,直接违反 N99「一个新 skip 都不许有」,
// 那是拿跳过换绿。建不出来就判红并点名环境缺口(plan N3 第 9 例同一条口径)。
Process mk = new ProcessBuilder("cmd.exe", "/c", "mklink", "/J",
javaRoot.resolve("modules").resolve("linkalias").toString(), real.toString())
.redirectErrorStream(true).start();
String out;
try (var in = mk.getInputStream()) {
out = new String(in.readAllBytes(), StandardCharsets.UTF_8);
}
int mklink = mk.waitFor();
assertThat(mklink)
.as("junction 建不出来 ⇒ 本机环境不支持,这格判红而不是跳过(跳过会新增 Skipped,"
+ "违反 N99「一个新 skip 都不许有」)。cmd 输出:%s", out)
.isZero();
List<Path> files = SourceScan.moduleSources(javaRoot, "modules");
assertThat(files)
.as("目录联接指回同一棵树:本机实测 Files.walk 会照钻 junction(改之前读出 [One.java, One.java]),"
+ "所以「默认不 FOLLOW_LINKS 就安全」这条假设已被证伪。实现按 toRealPath() 折叠同一份文件"
+ "(公开 NIO 读不到重解析点标志);重复计入会让精确计数格(publish 恰 1)假绿")
.extracting(p -> p.getFileName().toString())
.containsExactly("One.java");
}
@Test
void recursive_目录内全是非java时命中为空() throws IOException {
Path module = Files.createDirectories(tmp.resolve("N7非java树/src/main/java/modules/docs"));
Files.writeString(module.resolve("README.md"), "# 迁移说明", StandardCharsets.UTF_8);
Files.createDirectories(module.resolve("sub"));
Files.writeString(module.resolve("sub").resolve("notes.txt"), "x", StandardCharsets.UTF_8);
assertThat(SourceScan.moduleSources(tmp.resolve("N7非java树/src/main/java"), "modules/docs"))
.as("整棵树没有 .java ⇒ 空表(N11 会把这条改成抛;本格先钉「非 java 不进面」)")
.isEmpty();
}
@Test
void recursive_遍历失败抛IllegalStateException不吞() throws IOException {
Path vanished = tmp.resolve("N7消失树"); // 刻意不创建:walk 必须在第一步就抛 IOException
// 正对照:先证明这里真的会抛 IOException —— 否则「没吞」这条断言是空的
try (var raw = java.nio.file.Files.walk(vanished)) {
raw.toList();
org.junit.jupiter.api.Assertions.fail("JDK 的 Files.walk 在这条路径上没抛,正对照失效");
} catch (java.io.IOException expected) {
assertThat(expected).isInstanceOf(java.nio.file.NoSuchFileException.class);
}
assertThatThrownBy(() -> SourceScan.collectJavaFiles(vanished))
.as("遍历抛 IOException 时必须包成 IllegalStateException 并点名路径,不许吞成空表——"
+ "「扫不到」被读成「没违规」是本族护栏的标准死法(10-15 §12 第一条)")
.isInstanceOf(IllegalStateException.class)
.hasMessageContaining("遍历")
.hasMessageContaining(vanished.getFileName().toString());
}
}
@@ -146,9 +146,11 @@ export const TOOL_GROUPS: ReadonlyArray<ToolGroup> = [
workflowHint: '10步工作流 · 从上架到复盘,环环相扣',
workflow: [
{ name: '上架', desc: '安全数据批量上架', toolId: 'list' },
{ name: '指定删除ASIN', desc: '批量清理无效ASIN', toolId: 'delasin' },
{ name: '商品风险解决', desc: '3类风险一键处理', toolId: 'risk' },
{ name: '定时匹配', desc: '定时价格匹配', toolId: 'time' },
{ name: '跟价', desc: '跟价规则配置', toolId: 'follow' },
{ name: '巡店删除', desc: '巡检店铺状态', toolId: 'patrol' },
{ name: '查询ASIN', desc: '排查ASIN在售状态', toolId: 'qasin' },
{ name: '店铺数据抓取', desc: '抓取运营数据', toolId: 'scrape' },
{ name: '取款', desc: '留足平台扣款费用', toolId: 'cash' },
@@ -162,6 +164,13 @@ export const TOOL_GROUPS: ReadonlyArray<ToolGroup> = [
href: '/publish',
permissionKeys: ['publish'],
},
{
id: 'delasin',
name: '指定删除ASIN',
desc: '批量删除需清理的 ASIN(风险 / 优化 / 邮箱汇总)',
href: '/delete-brand',
permissionKeys: ['delete-brand'],
},
{
id: 'risk',
name: '商品风险解决',
@@ -187,6 +196,13 @@ export const TOOL_GROUPS: ReadonlyArray<ToolGroup> = [
href: '/price-track',
permissionKeys: ['pricing', 'price-track'],
},
{
id: 'patrol',
name: '巡店删除',
desc: '按商品状态巡店清理,摸清店铺商品全貌',
href: '/patrol-delete',
permissionKeys: ['patrol-delete'],
},
{
id: 'qasin',
name: '查询ASIN',
@@ -253,9 +269,11 @@ export const TOOL_ICON_GRADIENTS: Record<string, string> = {
split: 'linear-gradient(180deg, #86EFAC, #22C55E)',
convert: 'linear-gradient(180deg, #FCA5A5, #EF4444)',
list: 'linear-gradient(180deg, #5EEAD4, #14B8A6)',
delasin: 'linear-gradient(180deg, #93C5FD, #3B82F6)',
risk: 'linear-gradient(180deg, #C4B5FD, #8B5CF6)',
time: 'linear-gradient(180deg, #F9A8D4, #EC4899)',
follow: 'linear-gradient(180deg, #FDBA74, #F97316)',
patrol: 'linear-gradient(180deg, #FDE047, #EAB308)',
qasin: 'linear-gradient(180deg, #86EFAC, #22C55E)',
scrape: 'linear-gradient(180deg, #FCA5A5, #EF4444)',
cash: 'linear-gradient(180deg, #5EEAD4, #14B8A6)',
@@ -287,12 +305,16 @@ export const TOOL_ICON_SHAPES: Record<string, string> = {
convert: '<path d="M11.88 31 A 14 14 0 0 1 36.12 17"/><path d="M36.12 17 A 14 14 0 0 1 11.88 31"/><path class="fill" d="M32 18 L40 18 L36 14 Z"/><path class="fill" d="M8 30 L16 30 L12 34 Z"/>',
// 上架:方框+向上箭头
list: '<rect x="10" y="16" width="28" height="24"/><line x1="24" y1="34" x2="24" y2="12"/><path class="fill" d="M19 15 L29 15 L24 10 Z"/>',
// 删除ASIN:垃圾桶
delasin: '<rect x="10" y="10" width="28" height="6"/><path d="M13 18 L35 18 L33 40 L15 40 Z"/><line x1="20" y1="22" x2="20" y2="36"/><line x1="28" y1="22" x2="28" y2="36"/>',
// 商品风险解决:三角+感叹号
risk: '<path d="M24 8 L40 38 L8 38 Z"/><line x1="24" y1="18" x2="24" y2="28" stroke-width="3"/><circle class="fill" cx="24" cy="33" r="2"/>',
// 定时匹配:时钟
time: '<circle cx="24" cy="24" r="16"/><line x1="24" y1="14" x2="24" y2="24"/><line x1="24" y1="24" x2="32" y2="28"/>',
// 跟价:标签
follow: '<path d="M10 12 L32 12 L40 24 L32 36 L10 36 Z"/><circle cx="32" cy="23" r="2" stroke-width="2"/>',
// 巡店删除:眼睛
patrol: '<ellipse cx="24" cy="24" rx="16" ry="8"/><circle class="fill" cx="24" cy="24" r="4"/>',
// 查询ASIN:放大镜
qasin: '<circle cx="20" cy="20" r="12"/><line x1="28" y1="28" x2="40" y2="40" stroke-width="4"/>',
// 店铺数据抓取:立方体
@@ -318,8 +340,10 @@ export const TOOL_DETAILS: Readonly<Record<string, string>> = {
collect: '默认勾选有排名和FBM这两个选择',
dedupe: '去重之后,切记一定上传到数富后台去重数据库',
brand: '核查上架数据品牌风险,先跑精确匹配,后跑嵌入式',
delasin: '收集统一要删除的ASIN,批量删除清理',
risk:
'A 搜索结果中禁止显示;B 需要批准(最通用、使用频率最高);C 详情页面已删除。',
patrol: '巡店删除是按商品状态删除,如审核多次不通过的商品。不放任何状态跑一遍,可清楚掌握店铺数据情况。',
follow:
'一个虚拟桌面跟一个国家,错开跑即可时时跟价抢购物车。指定 ASIN 文档跟价:用后台有利润数据快速跟价,下班前跑一下,确保出单数据及时是我们的购物车。',
qasin: '通过店小蜜导出出单 ASIN,上传后台,时不时排查是否还在店铺售卖,确保优质数据时刻在店。',
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -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(),
@@ -50,9 +50,11 @@ type ActiveNavKey =
| 'dedupe'
| 'convert'
| 'split'
| 'delete-brand'
| 'product-risk'
| 'shop-match'
| 'pricing'
| 'patrol-delete'
| 'query-asin'
| 'shop-data-crawl'
| 'withdraw'
@@ -112,9 +114,11 @@ const navGroups: ReadonlyArray<NavGroup> = [
label: '运营工具',
items: [
{ key: 'publish', label: '上架', href: '/publish' },
{ key: 'delete-brand', label: '删除ASIN', href: '/delete-brand' },
{ key: 'product-risk', label: '商品风险解决', href: '/product-risk' },
{ key: 'shop-match', label: '定时匹配', href: '/shop-match' },
{ key: 'pricing', label: '跟价', href: '/price-track', aliases: ['price-track'] },
{ key: 'patrol-delete', label: '巡店删除', href: '/patrol-delete' },
{ key: 'query-asin', label: '查询ASIN', href: '/query-asin' },
{ key: 'shop-data-crawl', label: '店铺数据抓取', href: '/shop-data-crawl', columnKey: 'shop_data_crawl', aliases: ['shop-data-crawl'] },
{ key: 'withdraw', label: '取款', href: '/withdraw' },
@@ -6,3 +6,25 @@ 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 精确命中页面选项,命中不到
* 再按中文文案兜底。顺序即客户端逐状态跑的顺序(在售 → 缺少的报价 → 定价问题)。
*
* 这里的 value 是我们自己的标识,不等于亚马逊页面上的取值:2026-10-17 黄建新·英国站·新版
* 「管理商品」页真机实锤,「缺少的报价」的页面取值是 OfferMissing(不是照命名规律推的
* MissingOffer),映射表在客户端目录里;改这两个 value 会断载荷兼容与存量循环任务的落库值。
*/
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']
+10
View File
@@ -82,6 +82,11 @@ const routes = [
name: 'publish',
component: () => import('@/pages/brand/components/BrandPublishTab.vue'),
},
{
path: '/delete-brand',
name: 'delete-brand',
component: () => import('@/pages/brand/components/BrandDeleteBrandTab.vue'),
},
{
path: '/product-risk',
name: 'product-risk',
@@ -97,6 +102,11 @@ const routes = [
name: 'price-track',
component: () => import('@/pages/brand/components/BrandPriceTrackTab.vue'),
},
{
path: '/patrol-delete',
name: 'patrol-delete',
component: () => import('@/pages/brand/components/BrandPatrolDeleteTab.vue'),
},
{
path: '/query-asin',
name: 'query-asin',
+30
View File
@@ -40,6 +40,18 @@ export const API_ENDPOINTS = {
history: '/api/publish/history',
taskDelete: '/api/publish/tasks/{taskId}',
},
deleteBrand: {
run: '/api/delete-brand/run',
history: '/api/delete-brand/history',
historyDelete: '/api/delete-brand/history/{resultId}',
taskDetail: '/api/delete-brand/tasks/{taskId}',
taskDetails: '/api/delete-brand/tasks/batch',
taskDownload: '/api/delete-brand/tasks/{taskId}/download',
resultDownload: '/api/delete-brand/results/{resultId}/download',
resultSubmit: '/api/delete-brand/tasks/{taskId}/result',
progressBatch: '/api/delete-brand/tasks/progress/batch',
progressLight: '/api/delete-brand/tasks/progress/light',
},
productRisk: {
candidates: '/api/product-risk-resolve/candidates',
candidateAdd: '/api/product-risk-resolve/candidates',
@@ -76,6 +88,24 @@ export const API_ENDPOINTS = {
skipAsins: '/api/shop-match/tasks/{taskId}/skip-asins/paginated',
resultDownload: '/api/shop-match/results/{resultId}/download',
},
patrolDelete: {
candidates: '/api/patrol-delete/candidates',
candidateAdd: '/api/patrol-delete/candidates',
candidateDelete: '/api/patrol-delete/candidates/{id}',
conditions: '/api/patrol-delete/conditions',
conditionAdd: '/api/patrol-delete/conditions',
conditionDelete: '/api/patrol-delete/conditions/{id}',
matchShops: '/api/patrol-delete/match-shops',
dashboard: '/api/patrol-delete/dashboard',
history: '/api/patrol-delete/history',
historyDelete: '/api/patrol-delete/history/{resultId}',
progressBatch: '/api/patrol-delete/tasks/progress/batch',
progressLight: '/api/patrol-delete/tasks/progress/light',
taskCreate: '/api/patrol-delete/tasks',
taskDelete: '/api/patrol-delete/tasks/{taskId}',
taskResult: '/api/patrol-delete/tasks/{taskId}/result',
resultDownload: '/api/patrol-delete/results/{resultId}/download',
},
queryAsin: {
candidates: '/api/query-asin/candidates',
candidateAdd: '/api/query-asin/candidates',
@@ -1,6 +1,7 @@
export * from "./types/modules/dedupe.ts";
export * from "./types/modules/split.ts";
export * from "./types/modules/convert.ts";
export * from "./types/modules/delete-brand.ts";
export * from "./types/modules/publish.ts";
export * from "./types/modules/similar-asin.ts";
export * from "./types/modules/appearance-patent.ts";
@@ -6,6 +6,7 @@ export type ModuleTemplateCode =
| 'price-track'
| 'collect-data'
| 'similar-asin'
| 'delete-brand'
export function getModuleTemplateDownloadUrl(moduleCode: ModuleTemplateCode) {
return getJavaDownloadUrl(`/module-templates/${encodeURIComponent(moduleCode)}/download`)
@@ -19,8 +19,10 @@ import type { TaskProgressBatchVo } from './types/task.ts'
*/
export const PROGRESS_LIGHT_MODULES = [
'publish',
'deleteBrand',
'productRisk',
'shopMatch',
'patrolDelete',
'queryAsin',
'shopDataCrawl',
'withdraw',
@@ -0,0 +1,315 @@
import { get, post, del, type JavaApiResponse, unwrapJavaResponse } from '../../http.ts'
import { buildJavaUrl, JAVA_API_PREFIX } from '../../url.ts'
import { getCurrentUserId } from '../../user.ts'
import { getJavaDownloadUrl } from '../../download-url.ts'
import { getTaskProgressCacheTtlMs, getTaskProgressTimeoutMs } from '../../../task-progress-config.ts'
import { createTaskProgressRequestCache } from '../../../task-progress-request-cache.ts'
import type { UploadedFileRef } from '../upload.ts'
import { API_ENDPOINTS } from '../../endpoints.ts'
export interface DeleteBrandPreviewRow {
rowIndex: number;
country: string;
asin: string;
status: string;
}
export interface DeleteBrandCountryAsinItem {
rowIndex: number;
asin: string;
status: string;
}
export interface DeleteBrandCountryGroup {
country: string;
asinCount: number;
items: DeleteBrandCountryAsinItem[];
}
export interface DeleteBrandCountryResultItem {
asin: string;
status?: string;
}
export interface DeleteBrandProcessedCountry {
country: string;
items: DeleteBrandCountryResultItem[];
}
export interface DeleteBrandResultFile {
fileKey?: string;
sourceFilename: string;
fileIndex?: number;
fileTotal?: number;
chunkIndex?: number;
chunkTotal?: number;
processedRows?: number;
totalRows?: number;
currentCountry?: string;
currentAsin?: string;
countries: DeleteBrandProcessedCountry[];
}
export interface DeleteBrandSubmitResultRequest {
submissionId?: string;
files: DeleteBrandResultFile[];
}
export interface DeleteBrandLineProgressInfo {
file_index?: number;
file_total?: number;
file_name?: string;
current_line?: number;
total_lines?: number;
current_country?: string;
current_asin?: string;
finished_files?: number;
phase?: string;
}
export interface DeleteBrandLineProgress {
has_progress: boolean;
info?: DeleteBrandLineProgressInfo;
}
export interface DeleteBrandTaskItem {
id: number;
taskNo?: string;
status?: string;
sourceFileCount?: number;
successFileCount?: number;
failedFileCount?: number;
errorMessage?: string;
createdAt?: string;
updatedAt?: string;
finishedAt?: string;
downloadUrl?: string;
downloadFilename?: string;
}
export interface DeleteBrandTaskFileProgress {
fileKey?: string;
sourceFilename?: string;
processedRows?: number;
totalRows?: number;
percent?: number;
status?: "PENDING" | "RUNNING" | "COMPLETED" | "FAILED";
}
export interface DeleteBrandTaskDetailVo {
task: DeleteBrandTaskItem;
line_progress: DeleteBrandLineProgress;
items?: DeleteBrandResultItem[];
fileProgress?: DeleteBrandTaskFileProgress[];
}
export interface DeleteBrandTaskBatchVo {
items: DeleteBrandTaskDetailVo[];
missingTaskIds: number[];
}
export type DeleteBrandMatchStatus =
| "MATCHED"
| "PENDING"
| "CONFLICT"
| "INDEX_STALE";
export interface DeleteBrandResultItem {
resultId?: number;
fileKey?: string;
sourceFilename: string;
shopName?: string;
companyName?: string;
matched?: boolean;
matchStatus?: DeleteBrandMatchStatus;
matchMessage?: string;
shopId?: string;
platform?: string;
openStoreUrl?: string;
outputFilename?: string;
downloadUrl?: string;
fileJobId?: number;
fileStatus?: string;
fileError?: string;
fileReady?: boolean;
taskId?: number;
countryCount?: number;
countries?: DeleteBrandCountryGroup[];
totalRows?: number;
truncated?: boolean;
previewRows?: DeleteBrandPreviewRow[];
success: boolean;
error?: string;
taskStatus?: string;
}
export interface DeleteBrandRunVo {
total: number;
successCount: number;
failedCount: number;
items: DeleteBrandResultItem[];
}
export interface DeleteBrandHistoryVo {
items: DeleteBrandResultItem[];
}
export interface DeleteBrandRunRequest {
files: UploadedFileRef[];
user_id: number;
}
interface TaskProgressBatchOptions {
force?: boolean;
}
const taskProgressResponseCache = createTaskProgressRequestCache<unknown>({
ttlMs: () => getTaskProgressCacheTtlMs(),
maxEntries: 100,
maxInflight: 16,
});
function normalizeTaskIds(taskIds: number[]) {
return Array.from(
new Set(
(taskIds || [])
.map((taskId) => Number(taskId))
.filter((taskId) => Number.isFinite(taskId) && taskId > 0),
),
).sort((left, right) => left - right);
}
function buildTaskProgressRequestKey(path: string, taskIds: number[]) {
return `${path}::${taskIds.join(",")}`;
}
async function postTaskProgressBatch<T>(
path: string,
taskIds: number[],
options: TaskProgressBatchOptions = {},
) {
const normalizedTaskIds = normalizeTaskIds(taskIds);
if (!normalizedTaskIds.length) {
return { items: [], missingTaskIds: [] } as T;
}
const cacheKey = buildTaskProgressRequestKey(path, normalizedTaskIds);
const cached = taskProgressResponseCache.get(cacheKey);
if (!options.force && cached !== undefined) {
return cached as T;
}
const inflight = taskProgressResponseCache.getInflight(cacheKey);
if (!options.force && inflight) {
return (await inflight) as T;
}
const requestPromise = unwrapJavaResponse(
post<JavaApiResponse<T>, { taskIds: number[]; userId?: number }>(path, {
taskIds: normalizedTaskIds,
// 传当前用户 id:后端据此过滤非归属任务(未传时后端不过滤,保持向后兼容)
userId: Number(window.localStorage.getItem('uid')) || undefined,
}, {
timeout: getTaskProgressTimeoutMs(),
}),
)
.then((data) => {
taskProgressResponseCache.set(cacheKey, data);
return data;
})
.finally(() => {
taskProgressResponseCache.endInflight(cacheKey);
});
taskProgressResponseCache.startInflight(cacheKey, requestPromise);
return requestPromise;
}
export function runDeleteBrand(
request: Omit<DeleteBrandRunRequest, "user_id"> | DeleteBrandRunRequest,
) {
return unwrapJavaResponse(
post<JavaApiResponse<DeleteBrandRunVo>, DeleteBrandRunRequest>(
buildJavaUrl(API_ENDPOINTS.deleteBrand.run),
{
...request,
user_id: getCurrentUserId(),
},
{ timeout: 180000 },
),
);
}
export function getDeleteBrandHistory() {
return unwrapJavaResponse(
get<JavaApiResponse<DeleteBrandHistoryVo>>(
buildJavaUrl(API_ENDPOINTS.deleteBrand.history),
{
params: { user_id: getCurrentUserId() },
},
),
);
}
export function deleteDeleteBrandHistory(resultId: number) {
return unwrapJavaResponse(
del<JavaApiResponse<null>>(
buildJavaUrl(API_ENDPOINTS.deleteBrand.historyDelete.replace('{resultId}', String(resultId))),
{
params: { user_id: getCurrentUserId() },
},
),
);
}
export function getDeleteBrandTaskDetail(taskId: number) {
return unwrapJavaResponse(
get<JavaApiResponse<DeleteBrandTaskDetailVo>>(
buildJavaUrl(API_ENDPOINTS.deleteBrand.taskDetail.replace('{taskId}', String(taskId))),
),
);
}
export function getDeleteBrandTaskDetails(taskIds: number[]) {
return unwrapJavaResponse(
post<JavaApiResponse<DeleteBrandTaskBatchVo>, { taskIds: number[]; userId?: number }>(
buildJavaUrl(API_ENDPOINTS.deleteBrand.taskDetails),
{
taskIds,
// 传当前用户 id:后端据此过滤非归属任务(未传时后端不过滤,保持向后兼容)
userId: Number(window.localStorage.getItem('uid')) || undefined,
},
),
);
}
export function getDeleteBrandTaskDownloadUrl(taskId: number) {
return getJavaDownloadUrl(
API_ENDPOINTS.deleteBrand.taskDownload.replace('{taskId}', String(taskId)),
);
}
export function getDeleteBrandResultDownloadUrl(resultId: number) {
return getJavaDownloadUrl(
API_ENDPOINTS.deleteBrand.resultDownload.replace('{resultId}', String(resultId)),
);
}
export function submitDeleteBrandResult(
taskId: number,
request: DeleteBrandSubmitResultRequest,
) {
return unwrapJavaResponse(
post<JavaApiResponse<null>, DeleteBrandSubmitResultRequest>(
buildJavaUrl(API_ENDPOINTS.deleteBrand.resultSubmit.replace('{taskId}', String(taskId))),
request,
),
);
}
export function getDeleteBrandTaskProgress(taskIds: number[]) {
return postTaskProgressBatch<DeleteBrandTaskBatchVo>(
`${JAVA_API_PREFIX}/delete-brand/tasks/progress/batch`,
taskIds,
);
}
@@ -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[];
@@ -5,6 +5,8 @@ import { getJavaDownloadUrl } from '../../download-url.ts'
import { getTaskProgressCacheTtlMs, getTaskProgressTimeoutMs } from '../../../task-progress-config.ts'
import { createTaskProgressRequestCache } from '../../../task-progress-request-cache.ts'
import type {
ProductRiskCandidateVo,
ProductRiskDashboardVo,
ProductRiskMatchShopsVo,
ProductRiskShopQueueItem,
} from './shop-match.ts'
@@ -74,6 +76,94 @@ export interface WithdrawCreateTaskVo {
items: WithdrawHistoryItem[];
}
export type PatrolDeleteCandidateVo = ProductRiskCandidateVo;
export type PatrolDeleteDashboardVo = ProductRiskDashboardVo;
export type PatrolDeleteShopQueueItem = ProductRiskShopQueueItem;
export interface PatrolDeleteConditionVo {
id: number;
conditionText: string;
createdAt?: string;
}
export interface PatrolDeleteCountryMetricRow {
status: string;
quantity: string;
deleteQuantity: string;
processStatus: string;
}
export interface PatrolDeleteCountrySection {
country: string;
rows: PatrolDeleteCountryMetricRow[];
}
export interface PatrolDeleteCartRatio {
country: string;
ratio: string;
}
export interface PatrolDeleteTaskItem {
shopName?: string;
matched?: boolean;
shopId?: string;
platform?: string;
companyName?: string;
matchStatus?: string;
matchMessage?: string;
countrySections: PatrolDeleteCountrySection[];
cartRatios: PatrolDeleteCartRatio[];
}
export interface PatrolDeleteHistoryItem {
resultId?: number;
taskId?: number;
shopName?: string;
shopId?: string;
platform?: string;
companyName?: string;
matched?: boolean;
matchStatus?: string;
matchMessage?: string;
taskStatus?: string;
success?: boolean;
error?: string;
createdAt?: string;
finishedAt?: string;
outputFilename?: string;
downloadUrl?: string;
fileJobId?: number;
fileStatus?: string;
fileError?: string;
fileReady?: boolean;
countrySections: PatrolDeleteCountrySection[];
cartRatios: PatrolDeleteCartRatio[];
}
export interface PatrolDeleteHistoryVo {
items: PatrolDeleteHistoryItem[];
}
export interface PatrolDeleteTaskBatchVo {
items: PatrolDeleteHistoryItem[];
missingTaskIds: number[];
}
export interface PatrolDeleteCreateTaskVo {
taskId: number;
items: PatrolDeleteHistoryItem[];
}
export interface PatrolDeleteSubmitShopPayload {
shopName: string;
error?: string;
countrySections: PatrolDeleteCountrySection[];
cartRatios: PatrolDeleteCartRatio[];
shopDone?: boolean;
submissionId?: string;
chunkIndex?: number;
chunkTotal?: number;
}
const taskProgressResponseCache = createTaskProgressRequestCache<unknown>({
ttlMs: () => getTaskProgressCacheTtlMs(),
@@ -254,3 +344,170 @@ export function deleteWithdrawHistory(resultId: number) {
);
}
export function listPatrolDeleteCandidates() {
return unwrapJavaResponse(
get<JavaApiResponse<PatrolDeleteCandidateVo[]>>(
`${JAVA_API_PREFIX}/patrol-delete/candidates`,
{
params: { user_id: getCurrentUserId() },
},
),
);
}
export function addPatrolDeleteCandidate(shopName: string) {
return unwrapJavaResponse(
post<
JavaApiResponse<PatrolDeleteCandidateVo>,
{ user_id: number; shop_name: string }
>(`${JAVA_API_PREFIX}/patrol-delete/candidates`, {
user_id: getCurrentUserId(),
shop_name: shopName,
}),
);
}
export function deletePatrolDeleteCandidate(id: number) {
return unwrapJavaResponse(
del<JavaApiResponse<null>>(
`${JAVA_API_PREFIX}/patrol-delete/candidates/${id}`,
{
params: { user_id: getCurrentUserId() },
},
),
);
}
export function listPatrolDeleteConditions() {
return unwrapJavaResponse(
get<JavaApiResponse<PatrolDeleteConditionVo[]>>(
`${JAVA_API_PREFIX}/patrol-delete/conditions`,
{
params: { user_id: getCurrentUserId() },
},
),
);
}
export function addPatrolDeleteCondition(conditionText: string) {
return unwrapJavaResponse(
post<
JavaApiResponse<PatrolDeleteConditionVo>,
{ user_id: number; conditionText: string }
>(`${JAVA_API_PREFIX}/patrol-delete/conditions`, {
user_id: getCurrentUserId(),
conditionText,
}),
);
}
export function deletePatrolDeleteCondition(id: number) {
return unwrapJavaResponse(
del<JavaApiResponse<null>>(
`${JAVA_API_PREFIX}/patrol-delete/conditions/${id}`,
{
params: { user_id: getCurrentUserId() },
},
),
);
}
export function matchPatrolDeleteShops(shopNames: string[]) {
return unwrapJavaResponse(
post<
JavaApiResponse<ProductRiskMatchShopsVo>,
{ user_id: number; shop_names: string[] }
>(`${JAVA_API_PREFIX}/patrol-delete/match-shops`, {
user_id: getCurrentUserId(),
shop_names: shopNames,
}),
);
}
export function getPatrolDeleteDashboard() {
return unwrapJavaResponse(
get<JavaApiResponse<PatrolDeleteDashboardVo>>(
`${JAVA_API_PREFIX}/patrol-delete/dashboard`,
{
params: { user_id: getCurrentUserId() },
},
),
);
}
export function getPatrolDeleteHistory() {
return unwrapJavaResponse(
get<JavaApiResponse<PatrolDeleteHistoryVo>>(
`${JAVA_API_PREFIX}/patrol-delete/history`,
{
params: { user_id: getCurrentUserId() },
},
),
);
}
export function getPatrolDeleteTaskProgressBatch(taskIds: number[]) {
return postTaskProgressBatch<PatrolDeleteTaskBatchVo>(
`${JAVA_API_PREFIX}/patrol-delete/tasks/progress/batch`,
taskIds,
);
}
export function createPatrolDeleteTask(
items: PatrolDeleteTaskItem[],
deleteConditions: unknown[] = [],
) {
return unwrapJavaResponse(
post<
JavaApiResponse<PatrolDeleteCreateTaskVo>,
{ user_id: number; items: PatrolDeleteTaskItem[]; delete_conditions: unknown[] }
>(`${JAVA_API_PREFIX}/patrol-delete/tasks`, {
user_id: getCurrentUserId(),
items,
// 服务端校验删除条件非空(创建即 RUNNING,空条件的任务 Python 端无内容可执行)
delete_conditions: deleteConditions,
}),
);
}
export function submitPatrolDeleteTaskResult(
taskId: number,
payload: {
shops: PatrolDeleteSubmitShopPayload[];
},
) {
return unwrapJavaResponse(
post<
JavaApiResponse<null>,
{ shops: PatrolDeleteSubmitShopPayload[] }
>(`${JAVA_API_PREFIX}/patrol-delete/tasks/${taskId}/result`, payload),
);
}
export function getPatrolDeleteResultDownloadUrl(resultId: number) {
return getJavaDownloadUrl(
API_ENDPOINTS.patrolDelete.resultDownload.replace('{resultId}', String(resultId)),
);
}
export function deletePatrolDeleteTask(taskId: number) {
return unwrapJavaResponse(
del<JavaApiResponse<null>>(
`${JAVA_API_PREFIX}/patrol-delete/tasks/${taskId}`,
{
params: { user_id: getCurrentUserId() },
},
),
);
}
export function deletePatrolDeleteHistory(resultId: number) {
return unwrapJavaResponse(
del<JavaApiResponse<null>>(
`${JAVA_API_PREFIX}/patrol-delete/history/${resultId}`,
{
params: { user_id: getCurrentUserId() },
},
),
);
}
@@ -11,11 +11,9 @@ import {
TOOL_MAP,
} from '../src/pages/amazon/tool-catalog.ts'
test('工具目录:18 个工具 id 唯一且每个都有图标与渐变配色', () => {
test('工具目录:20 个工具 id 唯一且每个都有图标与渐变配色', () => {
const ids = TOOL_GROUPS.flatMap((g) => g.tools.map((t) => t.id))
// 2026-10-15 旧版界面退役:删除品牌(delasin)与巡店删除(patrol)两条目随功能摘除,
// 工具总数 20→18(前端8 + 运营8 + 后勤2)。
assert.equal(ids.length, 18, '工具总数应为 18(前端8 + 运营8 + 后勤2)')
assert.equal(ids.length, 20, '工具总数应为 20(前端8 + 运营10 + 后勤2)')
assert.equal(new Set(ids).size, ids.length, '工具 id 不应重复')
for (const id of ids) {
assert.ok(TOOL_ICON_SHAPES[id], `图标形状缺失: ${id}`)
@@ -6,17 +6,16 @@ import { dirname, join } from 'node:path'
/**
* 「行数据按需拉取」接线守卫(审查 F5 后续):
* 品牌工具页用轻量端点的结果行版本跳过重型 batch;这里守住两件最容易写错的事
* 5 个品牌工具页用轻量端点的结果行版本跳过重型 batch;这里守住两件最容易写错的事
* ——①接线没被误删;②跳过分支的返回值必须符合调用方契约(曾经把 shopDataCrawl 写成裸 return,
* 而调用方 waitForTerminal 把 falsy 当「任务已消失 → FAILED」,会误杀正在跑的任务)。
*/
const PAGES_DIR = join(dirname(fileURLToPath(import.meta.url)), '../src/pages/brand/components')
// 2026-10-15 旧版界面退役:原第 3 个页签 BrandPatrolDeleteTab.vue(巡店删除)随功能
// 一并退役删除,接线名单 5→4;其余四页一字未动。
const WIRED_PAGES = [
'BrandQueryAsinTab.vue',
'BrandWithdrawTab.vue',
'BrandPatrolDeleteTab.vue',
'BrandShopDataCrawlTab.vue',
'BrandAppearancePatentTab.vue',
]
@@ -38,7 +37,7 @@ test('轻量请求失败必须回退为全量拉取(不得因此少拉任务
// 多任务页:catch 里把 heavyIds 还原成全部任务
// 回退必须写在 catch 体内:用 [^}] 锁住,否则窗口会跨过 catch 的右花括号,
// 把后面正常分支的 return(如 { taskIds, force: true })当成回退,断言恒真。
for (const page of ['BrandQueryAsinTab.vue', 'BrandWithdrawTab.vue']) {
for (const page of ['BrandQueryAsinTab.vue', 'BrandWithdrawTab.vue', 'BrandPatrolDeleteTab.vue']) {
assert.match(sourceOf(page), /catch\s*\{[^}]{0,200}?heavyIds = ids/, `${page} 缺少轻量失败回退`)
}
assert.match(sourceOf('BrandAppearancePatentTab.vue'),
@@ -58,4 +57,8 @@ test('跳过分支的返回值符合调用方契约', () => {
assert.match(shopDataCrawl, /selectTasksNeedingRows\([\s\S]{0,200}?return true/,
'BrandShopDataCrawlTab 跳过分支必须 return true(false/undefined 会被当成任务已消失)')
const patrolDelete = sourceOf('BrandPatrolDeleteTab.vue')
// waitForTaskTerminal: `missingTaskIds.includes(taskId)` —— 未消失时返回空数组
assert.match(patrolDelete, /selectTasksNeedingRows\([\s\S]{0,300}?return \[\]/,
'BrandPatrolDeleteTab 跳过分支必须返回空 missingTaskIds 数组')
})
+34
View File
@@ -8,8 +8,10 @@ const MODULE_KEYS = [
'split',
'convert',
'publish',
'deleteBrand',
'productRisk',
'shopMatch',
'patrolDelete',
'queryAsin',
'shopDataCrawl',
'withdraw',
@@ -78,6 +80,8 @@ test('test_progress_batch_paths_match_controllers', () => {
'/api/appearance-patent/tasks/progress/batch',
'/api/collect-data/tasks/progress/batch',
'/api/publish/tasks/progress/batch',
'/api/delete-brand/tasks/progress/batch',
'/api/patrol-delete/tasks/progress/batch',
'/api/price-track/tasks/progress/batch',
'/api/product-risk-resolve/tasks/progress/batch',
'/api/shop-match/tasks/progress/batch',
@@ -144,6 +148,18 @@ test('test_endpoints_frozen_snapshot', () => {
"history": "/api/publish/history",
"taskDelete": "/api/publish/tasks/{taskId}"
},
"deleteBrand": {
"run": "/api/delete-brand/run",
"history": "/api/delete-brand/history",
"historyDelete": "/api/delete-brand/history/{resultId}",
"taskDetail": "/api/delete-brand/tasks/{taskId}",
"taskDetails": "/api/delete-brand/tasks/batch",
"taskDownload": "/api/delete-brand/tasks/{taskId}/download",
"resultDownload": "/api/delete-brand/results/{resultId}/download",
"resultSubmit": "/api/delete-brand/tasks/{taskId}/result",
"progressBatch": "/api/delete-brand/tasks/progress/batch",
"progressLight": "/api/delete-brand/tasks/progress/light"
},
"productRisk": {
"candidates": "/api/product-risk-resolve/candidates",
"candidateAdd": "/api/product-risk-resolve/candidates",
@@ -180,6 +196,24 @@ test('test_endpoints_frozen_snapshot', () => {
"skipAsins": "/api/shop-match/tasks/{taskId}/skip-asins/paginated",
"resultDownload": "/api/shop-match/results/{resultId}/download"
},
"patrolDelete": {
"candidates": "/api/patrol-delete/candidates",
"candidateAdd": "/api/patrol-delete/candidates",
"candidateDelete": "/api/patrol-delete/candidates/{id}",
"conditions": "/api/patrol-delete/conditions",
"conditionAdd": "/api/patrol-delete/conditions",
"conditionDelete": "/api/patrol-delete/conditions/{id}",
"matchShops": "/api/patrol-delete/match-shops",
"dashboard": "/api/patrol-delete/dashboard",
"history": "/api/patrol-delete/history",
"historyDelete": "/api/patrol-delete/history/{resultId}",
"progressBatch": "/api/patrol-delete/tasks/progress/batch",
"progressLight": "/api/patrol-delete/tasks/progress/light",
"taskCreate": "/api/patrol-delete/tasks",
"taskDelete": "/api/patrol-delete/tasks/{taskId}",
"taskResult": "/api/patrol-delete/tasks/{taskId}/result",
"resultDownload": "/api/patrol-delete/results/{resultId}/download"
},
"queryAsin": {
"candidates": "/api/query-asin/candidates",
"candidateAdd": "/api/query-asin/candidates",
@@ -14,6 +14,7 @@ import { resolve, dirname } from 'node:path'
*/
const here = dirname(fileURLToPath(import.meta.url))
const priceTrack = readFileSync(resolve(here, '../src/pages/brand/components/BrandPriceTrackTab.vue'), 'utf8')
const deleteBrand = readFileSync(resolve(here, '../src/pages/brand/components/BrandDeleteBrandTab.vue'), 'utf8')
function bodyOf(source: string, startMarker: string, endMarker: string, label: string) {
const start = source.indexOf(startMarker)
@@ -57,10 +58,17 @@ test('price_track_still_compensates_hard_failures', () => {
'三处收尾:数据闸 / 桥异常 / 拒绝且不可等待')
})
// 2026-10-15 旧版界面退役:原「两页都引分类器」的 BrandDeleteBrandTab.vue 随功能删除,
// 只剩跟价这一页(钉形状不变)。
test('price_track_tab_imports_the_classifier', () => {
assert.match(priceTrack, /classifyQueueRejection/, 'BrandPriceTrackTab.vue 未引用分类器')
assert.match(priceTrack, /from '@\/shared\/dispatch-guard'/, 'BrandPriceTrackTab.vue 未从 dispatch-guard 导入')
test('delete_brand_tab_uses_the_shared_classifier', () => {
// 旧写法 includes('当前店铺正在执行中') 匹配不到带店名的文案(客户端两个互斥出口都带名),
// 自动续跑的"重试"闸因此从未生效过。
assert.doesNotMatch(deleteBrand, /includes\('当前店铺正在执行中'\)/, '仍在用匹配不到的中文串判互斥')
assert.doesNotMatch(deleteBrand, /function isQueueBusyError/, '旧判定函数应随之删除,别留死代码')
assert.match(deleteBrand, /classifyQueueRejection\(pushResult\)/, '没有改用共享分类器')
})
test('both_tabs_import_the_classifier', () => {
for (const [name, src] of [['BrandPriceTrackTab.vue', priceTrack], ['BrandDeleteBrandTab.vue', deleteBrand]] as const) {
assert.match(src, /classifyQueueRejection/, `${name} 未引用分类器`)
assert.match(src, /from '@\/shared\/dispatch-guard'/, `${name} 未从 dispatch-guard 导入`)
}
})
@@ -6,17 +6,16 @@ import { resolve, dirname } from 'node:path'
import { http } from '../src/shared/api/http.ts'
import { http as httpAgain } from '../src/shared/api/http.ts'
// 2026-10-15 旧版界面退役:'delete-brand' 模块随删除品牌功能删除,名单同步摘除。
const moduleFiles = [
'dedupe', 'split', 'convert', 'publish', 'similar-asin', 'appearance-patent',
'price-track', 'shop-match', 'query-asin', 'withdraw',
'delete-brand', 'price-track', 'shop-match', 'query-asin', 'withdraw',
'collect-data', 'image-video', 'brand', 'permission', 'digital-human',
]
const functionNames = [
'runDedupe', 'getSplitHistory', 'runConvert', 'parsePublish',
'parseSimilarAsin', 'parseAppearancePatent',
'listPriceTrackCandidates', 'listProductRiskCandidates',
'runDeleteBrand', 'listPriceTrackCandidates', 'listProductRiskCandidates',
'listShopMatchCandidates', 'listQueryAsinCandidates', 'listWithdrawCandidates',
'listShopDataCrawlCandidates', 'parseCollectData', 'getImageVideoSecretStatus',
'expandBrandFolderRecursive', 'getCurrentUserAppColumnKeys',
@@ -0,0 +1,167 @@
import { test } from 'node:test'
import assert from 'node:assert/strict'
import { http } from '../src/shared/api/http.ts'
import {
runDeleteBrand,
getDeleteBrandHistory,
deleteDeleteBrandHistory,
getDeleteBrandTaskDetail,
getDeleteBrandTaskDetails,
getDeleteBrandTaskDownloadUrl,
getDeleteBrandResultDownloadUrl,
submitDeleteBrandResult,
getDeleteBrandTaskProgress,
type DeleteBrandRunRequest,
type DeleteBrandSubmitResultRequest,
} from '../src/shared/api/types/modules/delete-brand.ts'
function setupWindow() {
;(globalThis as Record<string, unknown>).window = {
localStorage: { getItem: () => '42' },
location: { origin: 'http://localhost' },
}
}
function mockRequest(
t: Parameters<typeof test>[1] extends (t: infer T) => unknown ? T : never,
impl: (config: { url?: string; method?: string; params?: Record<string, unknown>; data?: unknown; timeout?: number }) => Promise<unknown>,
) {
t.mock.method(http, 'request', impl as never)
}
const okResponse = (data: unknown) => Promise.resolve({ data: { success: true, message: 'ok', data } })
const runRequest: Omit<DeleteBrandRunRequest, 'user_id'> = {
files: [{ fileKey: 'k1' }],
}
test('test_delete_brand_run_url_payload', async (t) => {
setupWindow()
let captured: { url?: string; method?: string; data?: unknown; timeout?: number } = {}
mockRequest(t, (config) => {
captured = config
return okResponse({ total: 1, successCount: 0, failedCount: 1, items: [] })
})
await runDeleteBrand(runRequest)
assert.equal(captured.url, '/newApi/api/delete-brand/run')
assert.equal(captured.method, 'POST')
assert.deepEqual(captured.data, { ...runRequest, user_id: 42 })
assert.equal(captured.timeout, 180000)
})
test('test_delete_brand_history', async (t) => {
setupWindow()
let captured: { url?: string; params?: Record<string, unknown> } = {}
mockRequest(t, (config) => {
captured = config
return okResponse({ items: [] })
})
await getDeleteBrandHistory()
assert.equal(captured.url, '/newApi/api/delete-brand/history')
assert.deepEqual(captured.params, { user_id: 42 })
})
test('test_delete_brand_delete_history', async (t) => {
setupWindow()
let captured: { url?: string; method?: string; params?: Record<string, unknown> } = {}
mockRequest(t, (config) => {
captured = config
return okResponse(null)
})
await deleteDeleteBrandHistory(7)
assert.equal(captured.url, '/newApi/api/delete-brand/history/7')
assert.equal(captured.method, 'DELETE')
assert.deepEqual(captured.params, { user_id: 42 })
})
test('test_delete_brand_task_detail', async (t) => {
setupWindow()
let captured: { url?: string } = {}
mockRequest(t, (config) => {
captured = config
return okResponse({ task: { id: 7 }, line_progress: { has_progress: true }, items: [] })
})
const result = await getDeleteBrandTaskDetail(7)
assert.equal(captured.url, '/newApi/api/delete-brand/tasks/7')
assert.equal(result.task.id, 7)
assert.equal(result.line_progress.has_progress, true)
})
test('test_delete_brand_task_details', async (t) => {
setupWindow()
let captured: { url?: string; method?: string; data?: unknown } = {}
mockRequest(t, (config) => {
captured = config
return okResponse({ items: [], missingTaskIds: [] })
})
await getDeleteBrandTaskDetails([5, 3])
assert.equal(captured.url, '/newApi/api/delete-brand/tasks/batch')
assert.equal(captured.method, 'POST')
assert.deepEqual(captured.data, { taskIds: [5, 3], userId: 42 })
})
test('test_delete_brand_task_download_url', async (t) => {
setupWindow()
assert.equal(
getDeleteBrandTaskDownloadUrl(7),
'http://localhost/newApi/api/delete-brand/tasks/7/download?user_id=42',
)
})
test('test_delete_brand_result_download_url', async (t) => {
setupWindow()
assert.equal(
getDeleteBrandResultDownloadUrl(9),
'http://localhost/newApi/api/delete-brand/results/9/download?user_id=42',
)
})
test('test_delete_brand_submit_result_body', async (t) => {
setupWindow()
let captured: { url?: string; method?: string; data?: unknown } = {}
mockRequest(t, (config) => {
captured = config
return okResponse(null)
})
const body: DeleteBrandSubmitResultRequest = {
submissionId: 'sub-1',
files: [{ sourceFilename: 'a.xlsx', countries: [] }],
}
await submitDeleteBrandResult(7, body)
assert.equal(captured.url, '/newApi/api/delete-brand/tasks/7/result')
assert.equal(captured.method, 'POST')
assert.deepEqual(captured.data, body)
})
test('test_delete_brand_progress_batch', async (t) => {
setupWindow()
let captured: { url?: string; method?: string; data?: unknown; timeout?: number } = {}
mockRequest(t, (config) => {
captured = config
return okResponse({ items: [], missingTaskIds: [] })
})
const result = await getDeleteBrandTaskProgress([5, 3])
assert.equal(captured.url, '/newApi/api/delete-brand/tasks/progress/batch')
assert.equal(captured.method, 'POST')
assert.deepEqual(captured.data, { taskIds: [3, 5], userId: 42 })
assert.equal(captured.timeout, 10000)
assert.deepEqual(result, { items: [], missingTaskIds: [] })
})
test('test_delete_brand_export_compat', async (t) => {
setupWindow()
const fromJavaModules = await import('../src/shared/api/java-modules.ts')
const fromDeleteBrand = await import('../src/shared/api/types/modules/delete-brand.ts')
const names = [
'runDeleteBrand', 'getDeleteBrandHistory', 'deleteDeleteBrandHistory',
'getDeleteBrandTaskDetail', 'getDeleteBrandTaskDetails', 'getDeleteBrandTaskDownloadUrl',
'getDeleteBrandResultDownloadUrl', 'submitDeleteBrandResult', 'getDeleteBrandTaskProgress',
]
for (const name of names) {
assert.equal(fromJavaModules[name], fromDeleteBrand[name], `${name} 应为同一引用`)
}
const item = { id: 1, taskNo: 'T1', status: 'RUNNING' }
assert.equal(item.taskNo, 'T1')
const status: 'MATCHED' | 'PENDING' = 'MATCHED'
assert.equal(status, 'MATCHED')
})
@@ -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'],
'勾选的状态清单必须原样提交给后端——循环每一轮子任务的载荷都从后端记录回读,不吃界面当下勾选',
)
})
+103 -3
View File
@@ -15,6 +15,21 @@ import {
getWithdrawResultDownloadUrl,
deleteWithdrawTask,
deleteWithdrawHistory,
listPatrolDeleteCandidates,
addPatrolDeleteCandidate,
deletePatrolDeleteCandidate,
listPatrolDeleteConditions,
addPatrolDeleteCondition,
deletePatrolDeleteCondition,
matchPatrolDeleteShops,
getPatrolDeleteDashboard,
getPatrolDeleteHistory,
getPatrolDeleteTaskProgressBatch,
createPatrolDeleteTask,
submitPatrolDeleteTaskResult,
getPatrolDeleteResultDownloadUrl,
deletePatrolDeleteTask,
deletePatrolDeleteHistory,
} from '../src/shared/api/types/modules/withdraw.ts'
function setupWindow() {
@@ -126,12 +141,91 @@ test('test_withdraw_match', async (t) => {
assert.deepEqual(calls[0].data, { user_id: 42, shop_names: ['店铺A'] })
})
test('test_patrol_delete_candidates_conditions', async (t) => {
setupWindow()
const calls: { url?: string; method?: string; params?: Record<string, unknown>; data?: unknown }[] = []
mockRequest(t, (config) => {
calls.push(config)
return okResponse({ id: 1, shop_name: 's1' })
})
await listPatrolDeleteCandidates()
await addPatrolDeleteCandidate('店铺A')
await deletePatrolDeleteCandidate(3)
await listPatrolDeleteConditions()
await addPatrolDeleteCondition('条件X')
await deletePatrolDeleteCondition(5)
assert.equal(calls[0].url, '/newApi/api/patrol-delete/candidates')
assert.deepEqual(calls[0].params, { user_id: 42 })
assert.equal(calls[1].url, '/newApi/api/patrol-delete/candidates')
assert.equal(calls[1].method, 'POST')
assert.deepEqual(calls[1].data, { user_id: 42, shop_name: '店铺A' })
assert.equal(calls[2].url, '/newApi/api/patrol-delete/candidates/3')
assert.equal(calls[2].method, 'DELETE')
assert.equal(calls[3].url, '/newApi/api/patrol-delete/conditions')
assert.deepEqual(calls[3].params, { user_id: 42 })
assert.equal(calls[4].url, '/newApi/api/patrol-delete/conditions')
assert.equal(calls[4].method, 'POST')
assert.deepEqual(calls[4].data, { user_id: 42, conditionText: '条件X' })
assert.equal(calls[5].url, '/newApi/api/patrol-delete/conditions/5')
assert.equal(calls[5].method, 'DELETE')
})
test('test_patrol_delete_create_submit', async (t) => {
setupWindow()
const calls: { url?: string; method?: string; data?: unknown }[] = []
mockRequest(t, (config) => {
calls.push(config)
return okResponse({ taskId: 1, items: [] })
})
const item = {
shopName: '店铺A',
matched: true,
countrySections: [{ country: 'US', rows: [{ status: 'ok', quantity: '1', deleteQuantity: '0', processStatus: 'done' }] }],
cartRatios: [{ country: 'US', ratio: '0.5' }],
}
await createPatrolDeleteTask([item])
assert.equal(calls[0].url, '/newApi/api/patrol-delete/tasks')
assert.equal(calls[0].method, 'POST')
assert.deepEqual(calls[0].data, { user_id: 42, items: [item], delete_conditions: [] })
const payload = { shops: [{ shopName: '店铺A', countrySections: item.countrySections, cartRatios: item.cartRatios, shopDone: true, chunkIndex: 0, chunkTotal: 1 }] }
await submitPatrolDeleteTaskResult(7, payload)
assert.equal(calls[1].url, '/newApi/api/patrol-delete/tasks/7/result')
assert.deepEqual(calls[1].data, payload)
})
test('test_patrol_delete_progress_dashboard_download', async (t) => {
setupWindow()
const calls: { url?: string; method?: string; data?: unknown; timeout?: number; params?: Record<string, unknown> }[] = []
mockRequest(t, (config) => {
calls.push(config)
return okResponse({ items: [], missingTaskIds: [] })
})
await getPatrolDeleteTaskProgressBatch([5, 3])
await getPatrolDeleteDashboard()
await getPatrolDeleteHistory()
await matchPatrolDeleteShops(['店铺A'])
await deletePatrolDeleteTask(7)
await deletePatrolDeleteHistory(9)
assert.equal(calls[0].url, '/newApi/api/patrol-delete/tasks/progress/batch')
assert.equal(calls[0].method, 'POST')
assert.deepEqual(calls[0].data, { taskIds: [3, 5], userId: 42 })
assert.equal(calls[0].timeout, 10000)
assert.equal(calls[1].url, '/newApi/api/patrol-delete/dashboard')
assert.deepEqual(calls[1].params, { user_id: 42 })
assert.equal(calls[2].url, '/newApi/api/patrol-delete/history')
assert.equal(calls[3].url, '/newApi/api/patrol-delete/match-shops')
assert.deepEqual(calls[3].data, { user_id: 42, shop_names: ['店铺A'] })
assert.equal(calls[4].url, '/newApi/api/patrol-delete/tasks/7')
assert.equal(calls[4].method, 'DELETE')
assert.equal(calls[5].url, '/newApi/api/patrol-delete/history/9')
assert.equal(calls[5].method, 'DELETE')
assert.equal(
getPatrolDeleteResultDownloadUrl(7),
'http://localhost/newApi/api/patrol-delete/results/7/download?user_id=42',
)
})
// 2026-10-15 旧版界面退役:巡店删除的 15 个 API 函数随功能从 withdraw.ts 切掉,
// 本格只剩提款一组(原 test_withdraw_patrol_export_compat)。
test('test_withdraw_export_compat', async (t) => {
test('test_withdraw_patrol_export_compat', async (t) => {
setupWindow()
const fromJavaModules = await import('../src/shared/api/java-modules.ts')
const fromWithdraw = await import('../src/shared/api/types/modules/withdraw.ts')
@@ -141,6 +235,12 @@ test('test_withdraw_export_compat', async (t) => {
'getWithdrawHistory', 'getWithdrawTaskProgressBatch', 'createWithdrawTask',
'submitWithdrawTaskResult', 'getWithdrawResultDownloadUrl',
'deleteWithdrawTask', 'deleteWithdrawHistory',
'listPatrolDeleteCandidates', 'addPatrolDeleteCandidate', 'deletePatrolDeleteCandidate',
'listPatrolDeleteConditions', 'addPatrolDeleteCondition', 'deletePatrolDeleteCondition',
'matchPatrolDeleteShops', 'getPatrolDeleteDashboard', 'getPatrolDeleteHistory',
'getPatrolDeleteTaskProgressBatch', 'createPatrolDeleteTask',
'submitPatrolDeleteTaskResult', 'getPatrolDeleteResultDownloadUrl',
'deletePatrolDeleteTask', 'deletePatrolDeleteHistory',
]
for (const name of names) {
assert.equal(fromJavaModules[name], fromWithdraw[name], `${name} 应为同一引用`)
@@ -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\] : \[\]/)
})
+3 -4
View File
@@ -29,9 +29,8 @@ function mockRequest(
const okResponse = (data: unknown) => Promise.resolve({ data: { success: true, message: 'ok', data } })
// 2026-10-15 旧版界面退役:deleteBrand 与 patrolDelete 两模块随功能摘除(12→10)。
const LIGHT_MODULES: ProgressLightModule[] = [
'publish', 'productRisk', 'shopMatch',
'publish', 'deleteBrand', 'productRisk', 'shopMatch', 'patrolDelete',
'queryAsin', 'shopDataCrawl', 'withdraw', 'priceTrack', 'similarAsin',
'appearancePatent', 'collectData',
]
@@ -154,11 +153,11 @@ test('test_light_snapshot', async (t) => {
return okResponse({ items: [{ taskId: 1, status: 'RUNNING', fileReady: false }], missingTaskIds: [] })
})
await getModuleProgressLight('appearancePatent', [1], { force: true })
await getModuleProgressLight('queryAsin', [2], { force: true })
await getModuleProgressLight('deleteBrand', [2], { force: true })
assert.equal(calls[0].url, '/newApi/api/appearance-patent/tasks/progress/light')
assert.equal(calls[0].method, 'POST')
assert.deepEqual(calls[0].data, { taskIds: [1] })
assert.equal(calls[1].url, '/newApi/api/query-asin/tasks/progress/light')
assert.equal(calls[1].url, '/newApi/api/delete-brand/tasks/progress/light')
assert.deepEqual(calls[1].data, { taskIds: [2] })
})
@@ -7,7 +7,7 @@ import { join } from 'node:path'
* 任务卡片的「进度条接线」普查。
*
* 为什么要它:TaskItemView.progress 是可空字段,页面少写一行不会报错、不会红,
* 界面上就是安静地没有进度条。每个任务页各写一处,漏哪一处全靠这条出声。
* 界面上就是安静地没有进度条。11 个任务页各写一处,漏哪一处全靠这条出声。
*
* 分母不手抄:扫 src/pages/brand/components 下所有写了 `to*TaskView(...): TaskItemView`
* 适配器的页面,清单由文件系统给出;再把总数硬钉住——新增页面没接进度、或有人把
@@ -41,9 +41,7 @@ const pages = readdirSync(COMPONENTS).filter((name) => name.endsWith('.vue'))
const seen = pages.flatMap((file) => adaptersOf(file).map((a) => ({ file, ...a })))
test('被扫描的任务卡适配器数量必须硬钉(少扫或多扫都说明扫描面变了)', () => {
// 2026-10-15 旧版界面退役:BrandDeleteBrandTab 与 BrandPatrolDeleteTab 两页删除,
// 适配器 16→14(少扫或多扫都说明扫描面变了)。
assert.equal(seen.length, 14, `扫到 ${seen.length} 个 to*TaskView 适配器:${seen.map((s) => `${s.file}#${s.name}`).join(', ')}`)
assert.equal(seen.length, 16, `扫到 ${seen.length} 个 to*TaskView 适配器:${seen.map((s) => `${s.file}#${s.name}`).join(', ')}`)
})
test('每个任务卡适配器都必须给出进度读数,或明确给出 null', () => {
@@ -18,8 +18,8 @@ const root = resolve(here, '..')
const rel = (p: string) => relative(root, p).split(sep).join('/')
const SRC_FILES = listSourceFiles(resolve(root, 'src')).map(rel)
// 2026-10-15 旧版界面退役:BrandPatrolDeleteTab.vue(巡店删除)随功能删除,六页→五页。
const TABS = [
'BrandPatrolDeleteTab.vue',
'BrandPriceTrackTab.vue',
'BrandProductRiskTab.vue',
'BrandQueryAsinTab.vue',
@@ -40,6 +40,8 @@ const TABS = [
const NARROW_LEDGER: Record<string, number> = {
'src/pages/brand/components/BrandAppearancePatentTab.vue': 3,
'src/pages/brand/components/BrandCollectDataTab.vue': 2,
'src/pages/brand/components/BrandDeleteBrandTab.vue': 2,
'src/pages/brand/components/BrandPatrolDeleteTab.vue': 1,
'src/pages/brand/components/BrandPriceTrackTab.vue': 6,
'src/pages/brand/components/BrandProductRiskTab.vue': 2,
'src/pages/brand/components/BrandSimilarAsinTab.vue': 1,
@@ -175,7 +177,7 @@ test('全 src 窄集合只许减:逐文件台账 + 分母自证', () => {
}
})
test('五个 Tab 的每条等待函数都真的走骨架(按 AST 认函数,不靠签名切字符串)', () => {
test('六个 Tab 的每条等待函数都真的走骨架(按 AST 认函数,不靠签名切字符串)', () => {
const offenders: string[] = []
const seen: string[] = []
for (const tab of TABS) {