feat(jd-publish): 目标品牌建单+校验失败整单判死+改品牌原位重试(桌面协议 v3 服务端半边)

- 建单必填目标品牌(1–120 字符单行),走 /tasks/target-brand 独占路径,旧后端不会静默丢参数

- 激活与明细下发带 jdPublishProtocol,协议 <3 直接 409 要求升级客户端;明细 VO 下发 targetBrandName

- 预检失败回执(SOURCE/BRAND)必须带一条失败明细,整单判 FAILED 并落分类前缀;通用重试/继续对品牌失败任务拒绝

- 新增 /tasks/{taskId}/retry-brand:只允许无成功、无待确认记录的品牌失败任务改品牌后原位重试(世代+1、明细复位、回执直推本机队列)

- 兜底拉取按协议过滤带 targetBrandName 的 JD 上架任务,认领 CAS 带 resumeAttempt 防跨代误领

- 用户端:目标品牌必填输入、协议探测挡旧客户端、品牌失败弹窗与「修改品牌并重试」按钮
This commit is contained in:
2026-11-20 21:48:59 +08:00
parent acd61aa1d2
commit 9b23b4934d
24 changed files with 653 additions and 82 deletions
@@ -0,0 +1,20 @@
package com.nanri.aiimage.common.task;
/** Desktop contract shared by the JD publisher and the generic pull/retry routes. */
public final class JdPublishProtocol {
public static final int LEGACY = 2;
public static final int TARGET_BRAND = 3;
public static final String BRAND_FAILURE = "目标品牌校验失败:";
public static final String SOURCE_FAILURE = "本店源商品校验失败:";
private JdPublishProtocol() {
}
public static boolean supportsTargetBrand(Integer protocol) {
return Integer.valueOf(TARGET_BRAND).equals(protocol);
}
public static boolean needsBrandCorrection(String message) {
return message != null && message.startsWith(BRAND_FAILURE);
}
}
@@ -60,7 +60,7 @@ public class JdPublishController {
private final TaskProgressOwnershipSupport progressOwnershipSupport; private final TaskProgressOwnershipSupport progressOwnershipSupport;
private final AdminAuthSupport adminAuthSupport; private final AdminAuthSupport adminAuthSupport;
@PostMapping("/tasks") @PostMapping({"/tasks", "/tasks/target-brand"})
@Operation(summary = "创建京东商品上架任务", description = "勾选京东数据库商品(归属校验)+可选统一改价规则建单;" @Operation(summary = "创建京东商品上架任务", description = "勾选京东数据库商品(归属校验)+可选统一改价规则建单;"
+ "任务落 PENDING、执行通道显式 LOCAL(本机已登录京麦的 Chrome 执行)、明细快照行随建单落库。" + "任务落 PENDING、执行通道显式 LOCAL(本机已登录京麦的 Chrome 执行)、明细快照行随建单落库。"
+ "响应体带 queuePayload(type=jd-product-publish-run),页面原样投 api.enqueue_json。") + "响应体带 queuePayload(type=jd-product-publish-run),页面原样投 api.enqueue_json。")
@@ -72,13 +72,25 @@ public class JdPublishController {
adminAuthSupport.currentDeviceId(httpRequest))); adminAuthSupport.currentDeviceId(httpRequest)));
} }
@PostMapping("/tasks/{taskId}/retry-brand")
public ApiResponse<JdPublishTaskVo> retryBrand(@PathVariable Long taskId,
@Valid @RequestBody BrandRetryRequest request, HttpServletRequest httpRequest) {
return ApiResponse.success(publishTaskService.retryWithBrand(taskId,
adminAuthSupport.requireSessionOwnerUserId(httpRequest, null),
request.resumeAttempt(), request.targetBrandName()));
}
public record BrandRetryRequest(@jakarta.validation.constraints.NotNull Integer resumeAttempt, String targetBrandName) {}
@PostMapping("/tasks/{taskId}/activate") @PostMapping("/tasks/{taskId}/activate")
@Operation(summary = "认领当前代次的京东上架任务") @Operation(summary = "认领当前代次的京东上架任务")
public ApiResponse<Void> activate(@PathVariable Long taskId, public ApiResponse<Void> activate(@PathVariable Long taskId,
@RequestParam("resumeAttempt") int resumeAttempt, @RequestParam("resumeAttempt") int resumeAttempt,
@RequestParam(value = "jdPublishProtocol", required = false) Integer protocol,
@RequestParam(value = "user_id", required = false) Long userId, @RequestParam(value = "user_id", required = false) Long userId,
HttpServletRequest httpRequest) { HttpServletRequest httpRequest) {
publishTaskService.activateTask(taskId, adminAuthSupport.requireSessionOwnerUserId(httpRequest, userId), resumeAttempt); publishTaskService.activateTask(taskId, adminAuthSupport.requireSessionOwnerUserId(httpRequest, userId),
resumeAttempt, protocol);
return ApiResponse.success(null); return ApiResponse.success(null);
} }
@@ -96,9 +108,10 @@ public class JdPublishController {
@Parameter(description = "任务所属用户 ID;省略时取当前登录身份", required = false, example = "1") @Parameter(description = "任务所属用户 ID;省略时取当前登录身份", required = false, example = "1")
@RequestParam(value = "user_id", required = false) Long userId, @RequestParam(value = "user_id", required = false) Long userId,
@RequestParam("resumeAttempt") int resumeAttempt, @RequestParam("resumeAttempt") int resumeAttempt,
@RequestParam(value = "jdPublishProtocol", required = false) Integer protocol,
HttpServletRequest httpRequest) { HttpServletRequest httpRequest) {
return ApiResponse.success(publishTaskService.pullItems(taskId, return ApiResponse.success(publishTaskService.pullItems(taskId,
adminAuthSupport.requireSessionOwnerUserId(httpRequest, userId), resumeAttempt, cursor, limit)); adminAuthSupport.requireSessionOwnerUserId(httpRequest, userId), resumeAttempt, cursor, limit, protocol));
} }
@GetMapping("/tasks/{taskId}/progress") @GetMapping("/tasks/{taskId}/progress")
@@ -35,6 +35,11 @@ public class JdPublishChunkRequest {
*/ */
private String error; private String error;
/** 提交前明确阻断:SOURCE(源商品/店铺)或 BRAND(目标品牌)。 */
private PreflightFailure preflightFailure;
public enum PreflightFailure { SOURCE, BRAND }
/** 单行回传结果。 */ /** 单行回传结果。 */
@Data @Data
@JsonIgnoreProperties(ignoreUnknown = true) @JsonIgnoreProperties(ignoreUnknown = true)
@@ -27,6 +27,9 @@ public class JdPublishTaskCreateRequest {
/** 统一改价规则(可选;null=按原价,mode=none)。 */ /** 统一改价规则(可选;null=按原价,mode=none)。 */
private PriceRule priceRule; private PriceRule priceRule;
/** 本次任务统一使用的目标品牌名,不回写商品库。 */
private String targetBrandName;
/** 统一改价规则:none 原价 / percent 加价百分比(value=百分数) / fixed 固定加价(value=金额)。 */ /** 统一改价规则:none 原价 / percent 加价百分比(value=百分数) / fixed 固定加价(value=金额)。 */
@Data @Data
public static class PriceRule { public static class PriceRule {
@@ -15,6 +15,9 @@ import java.util.List;
public class JdPublishItemsPageVo { public class JdPublishItemsPageVo {
private Long taskId; private Long taskId;
/** 旧任务为空,沿用京麦预填。 */
private String targetBrandName;
private int resumeAttempt; private int resumeAttempt;
/** 本页明细行。 */ /** 本页明细行。 */
@@ -3,10 +3,12 @@ package com.nanri.aiimage.modules.jd.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.nanri.aiimage.common.exception.BusinessException; import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.task.JdPublishProtocol;
import com.nanri.aiimage.common.task.TaskStatuses; import com.nanri.aiimage.common.task.TaskStatuses;
import com.nanri.aiimage.modules.jd.mapper.JdPublishItemMapper; import com.nanri.aiimage.modules.jd.mapper.JdPublishItemMapper;
import com.nanri.aiimage.modules.jd.model.dto.JdPublishChunkRequest; import com.nanri.aiimage.modules.jd.model.dto.JdPublishChunkRequest;
import com.nanri.aiimage.modules.jd.model.dto.JdPublishChunkRequest.ItemResult; import com.nanri.aiimage.modules.jd.model.dto.JdPublishChunkRequest.ItemResult;
import com.nanri.aiimage.modules.jd.model.dto.JdPublishChunkRequest.PreflightFailure;
import com.nanri.aiimage.modules.jd.model.entity.JdPublishItemEntity; import com.nanri.aiimage.modules.jd.model.entity.JdPublishItemEntity;
import com.nanri.aiimage.modules.jd.model.vo.JdPublishChunkVo; import com.nanri.aiimage.modules.jd.model.vo.JdPublishChunkVo;
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper; import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
@@ -66,6 +68,7 @@ public class JdPublishIngestService {
throw new BusinessException(409, "任务不在运行中,请先激活任务再回传"); throw new BusinessException(409, "任务不在运行中,请先激活任务再回传");
} }
String preflightMessage = preflightMessage(request, items);
int accepted = 0; int accepted = 0;
String newlyFailedReason = null; String newlyFailedReason = null;
Set<Long> seen = new HashSet<>(); Set<Long> seen = new HashSet<>();
@@ -91,6 +94,8 @@ public class JdPublishIngestService {
vo.setNeedsReview(Boolean.TRUE.equals(request.getIsEnd()) && vo.getPublishingCount() > 0); vo.setNeedsReview(Boolean.TRUE.equals(request.getIsEnd()) && vo.getPublishingCount() > 0);
if (terminal) { if (terminal) {
vo.setTaskStatus(task.getStatus()); vo.setTaskStatus(task.getStatus());
} else if (preflightMessage != null && accepted == 1) {
vo.setTaskStatus(finish(task, counts, TaskStatuses.FileTask.FAILED, preflightMessage));
} else if (newlyFailedReason != null && staleTaskService.terminalizeOnJdLoginFatal(task, newlyFailedReason)) { } else if (newlyFailedReason != null && staleTaskService.terminalizeOnJdLoginFatal(task, newlyFailedReason)) {
vo.setTaskStatus(TaskStatuses.FileTask.FAILED); vo.setTaskStatus(TaskStatuses.FileTask.FAILED);
} else if (Boolean.TRUE.equals(request.getIsEnd())) { } else if (Boolean.TRUE.equals(request.getIsEnd())) {
@@ -149,6 +154,12 @@ public class JdPublishIngestService {
} }
String status = failed > 0 ? TaskStatuses.FileTask.FAILED : TaskStatuses.FileTask.SUCCESS; String status = failed > 0 ? TaskStatuses.FileTask.FAILED : TaskStatuses.FileTask.SUCCESS;
String message = failed > 0 ? "发布完成:成功 " + success + " 行,失败 " + failed + " 行" : null; String message = failed > 0 ? "发布完成:成功 " + success + " 行,失败 " + failed + " 行" : null;
return finish(task, counts, status, message);
}
private String finish(FileTaskEntity task, Map<String, Long> counts, String status, String message) {
long success = counts.getOrDefault(ITEM_SUCCESS, 0L);
long failed = counts.getOrDefault(ITEM_FAILED, 0L);
LocalDateTime now = LocalDateTime.now(); LocalDateTime now = LocalDateTime.now();
int updated = fileTaskMapper.update(null, new LambdaUpdateWrapper<FileTaskEntity>() int updated = fileTaskMapper.update(null, new LambdaUpdateWrapper<FileTaskEntity>()
.eq(FileTaskEntity::getId, task.getId()) .eq(FileTaskEntity::getId, task.getId())
@@ -169,6 +180,26 @@ public class JdPublishIngestService {
return RUNNING; return RUNNING;
} }
private static String preflightMessage(JdPublishChunkRequest request, List<ItemResult> items) {
if (request.getPreflightFailure() == null) {
return null;
}
if (items.size() != 1 || items.getFirst() == null
|| !ITEM_FAILED.equals(normalizeStatus(items.getFirst().getPublishStatus()))) {
throw new BusinessException(400, "上架校验阻断须同时回传一条失败明细");
}
String error = truncate(items.getFirst().getPublishError());
if (error == null || error.isEmpty()) {
throw new BusinessException(400, "上架校验阻断须同时回传失败原因");
}
String prefix = request.getPreflightFailure() == PreflightFailure.BRAND
? JdPublishProtocol.BRAND_FAILURE : JdPublishProtocol.SOURCE_FAILURE;
String message = prefix + error;
// biz_file_task.error_message 比发布明细的 publish_error 短。
int end = message.offsetByCodePoints(0, Math.min(1000, message.codePointCount(0, message.length())));
return message.substring(0, end);
}
private Map<String, Long> statusCounts(Long taskId) { private Map<String, Long> statusCounts(Long taskId) {
Map<String, Long> counts = new HashMap<>(); Map<String, Long> counts = new HashMap<>();
for (Map<String, Object> row : jdPublishItemMapper.countByPublishStatus(taskId)) { for (Map<String, Object> row : jdPublishItemMapper.countByPublishStatus(taskId)) {
@@ -8,7 +8,9 @@ import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.mapper.AdminUserMapper; import com.nanri.aiimage.common.mapper.AdminUserMapper;
import com.nanri.aiimage.common.model.entity.AdminUserEntity; import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.common.security.AdminAuthSupport; import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.common.task.JdPublishProtocol;
import com.nanri.aiimage.common.task.TaskStatuses; import com.nanri.aiimage.common.task.TaskStatuses;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.nanri.aiimage.config.CollectRoutingProperties; import com.nanri.aiimage.config.CollectRoutingProperties;
import com.nanri.aiimage.modules.file.service.oss.OssStorageService; import com.nanri.aiimage.modules.file.service.oss.OssStorageService;
import com.nanri.aiimage.modules.jd.mapper.JdProductImageMapper; import com.nanri.aiimage.modules.jd.mapper.JdProductImageMapper;
@@ -106,6 +108,7 @@ public class JdPublishTaskService {
private final ObjectMapper objectMapper; private final ObjectMapper objectMapper;
private final TaskHeartbeatService taskHeartbeatService; private final TaskHeartbeatService taskHeartbeatService;
private final TaskHeartbeatPositionService taskHeartbeatPositionService; private final TaskHeartbeatPositionService taskHeartbeatPositionService;
private final JdPublishTaskItemsResetSpiImpl itemsReset;
/** 下发批大小出厂值(aiimage.jd.publish.items-batch-size,服务侧钳制上限 100)。 */ /** 下发批大小出厂值(aiimage.jd.publish.items-batch-size,服务侧钳制上限 100)。 */
@Value("${aiimage.jd.publish.items-batch-size:20}") @Value("${aiimage.jd.publish.items-batch-size:20}")
@@ -150,12 +153,8 @@ public class JdPublishTaskService {
task.setDeviceId(AdminAuthSupport.normalizeDeviceId(deviceId)); task.setDeviceId(AdminAuthSupport.normalizeDeviceId(deviceId));
task.setCreatedAt(now); task.setCreatedAt(now);
task.setUpdatedAt(now); task.setUpdatedAt(now);
try { task.setRequestJson(writeCreateRequest(request));
task.setRequestJson(objectMapper.writeValueAsString(request)); task.setResultJson("{}");
task.setResultJson("{}");
} catch (Exception ex) {
throw new BusinessException("序列化建单载荷失败", ex);
}
fileTaskMapper.insert(task); fileTaskMapper.insert(task);
// 建单即落明细快照行(蓝图 §3):标题/类目/价格折算/库存/店铺/编码随行固化, // 建单即落明细快照行(蓝图 §3):标题/类目/价格折算/库存/店铺/编码随行固化,
@@ -178,9 +177,10 @@ public class JdPublishTaskService {
} }
/** 仅当前代次的 PENDING 任务能被页面队列中的桌面执行器认领。 */ /** 仅当前代次的 PENDING 任务能被页面队列中的桌面执行器认领。 */
public void activateTask(Long taskId, Long userId, int attempt) { public void activateTask(Long taskId, Long userId, int attempt, Integer protocol) {
FileTaskEntity task = requireOwnedTask(taskId, userId); FileTaskEntity task = requireOwnedTask(taskId, userId);
requireAttempt(task, attempt); requireAttempt(task, attempt);
targetBrandForClient(task, protocol);
int updated = fileTaskMapper.update(null, new LambdaUpdateWrapper<FileTaskEntity>() int updated = fileTaskMapper.update(null, new LambdaUpdateWrapper<FileTaskEntity>()
.eq(FileTaskEntity::getId, taskId) .eq(FileTaskEntity::getId, taskId)
.eq(FileTaskEntity::getUserId, userId) .eq(FileTaskEntity::getUserId, userId)
@@ -198,9 +198,11 @@ public class JdPublishTaskService {
* 重连 cursor 归零也不会重发已发布商品,AC-4 服务端半边);SKU 价按改价规则折算; * 重连 cursor 归零也不会重发已发布商品,AC-4 服务端半边);SKU 价按改价规则折算;
* 图片发 jd-products 桶预签名 GET URL(蓝图 §3)。 * 图片发 jd-products 桶预签名 GET URL(蓝图 §3)。
*/ */
public JdPublishItemsPageVo pullItems(Long taskId, Long userId, int attempt, Long cursor, Integer limit) { public JdPublishItemsPageVo pullItems(Long taskId, Long userId, int attempt, Long cursor, Integer limit,
Integer protocol) {
FileTaskEntity task = requireOwnedTask(taskId, userId); FileTaskEntity task = requireOwnedTask(taskId, userId);
requireAttempt(task, attempt); requireAttempt(task, attempt);
String targetBrand = targetBrandForClient(task, protocol);
if (!STATUS_RUNNING.equals(task.getStatus())) { if (!STATUS_RUNNING.equals(task.getStatus())) {
throw new BusinessException(409, "任务未在运行,不能下发发布明细"); throw new BusinessException(409, "任务未在运行,不能下发发布明细");
} }
@@ -216,6 +218,7 @@ public class JdPublishTaskService {
JdPublishItemsPageVo vo = new JdPublishItemsPageVo(); JdPublishItemsPageVo vo = new JdPublishItemsPageVo();
vo.setTaskId(taskId); vo.setTaskId(taskId);
vo.setResumeAttempt(attempt); vo.setResumeAttempt(attempt);
vo.setTargetBrandName(targetBrand);
vo.setItems(rows.isEmpty() ? List.of() : rows.stream() vo.setItems(rows.isEmpty() ? List.of() : rows.stream()
.map(row -> buildItemPayload(row, productsByPid.get(row.getProductId()))) .map(row -> buildItemPayload(row, productsByPid.get(row.getProductId())))
.toList()); .toList());
@@ -265,6 +268,9 @@ public class JdPublishTaskService {
Map<String, Object> data = new LinkedHashMap<>(); Map<String, Object> data = new LinkedHashMap<>();
data.put("taskId", task.getId()); data.put("taskId", task.getId());
data.put("resumeAttempt", resumeAttempt(task)); data.put("resumeAttempt", resumeAttempt(task));
if (create.getTargetBrandName() != null) {
data.put("targetBrandRequired", true);
}
data.put("priceRule", create.getPriceRule() == null ? Map.of("mode", "none") : create.getPriceRule()); data.put("priceRule", create.getPriceRule() == null ? Map.of("mode", "none") : create.getPriceRule());
return Map.of("type", JdPublishTaskPullSpiImpl.QUEUE_TYPE, "data", data); return Map.of("type", JdPublishTaskPullSpiImpl.QUEUE_TYPE, "data", data);
} }
@@ -337,9 +343,84 @@ public class JdPublishTaskService {
throw new BusinessException("单次上架最多选 " + MAX_PRODUCT_IDS + " 个商品,当前 " throw new BusinessException("单次上架最多选 " + MAX_PRODUCT_IDS + " 个商品,当前 "
+ request.getProductIds().size() + " 个"); + request.getProductIds().size() + " 个");
} }
request.setTargetBrandName(requireTargetBrand(request.getTargetBrandName()));
normalizePriceRule(request); normalizePriceRule(request);
} }
private static String requireTargetBrand(String value) {
String brand = value == null ? "" : value.strip();
if (brand.isEmpty()) {
throw new BusinessException(400, "请填写目标品牌");
}
if (brand.length() > 120 || brand.codePoints().anyMatch(Character::isISOControl)) {
throw new BusinessException(400, "目标品牌须为不超过 120 个字符的单行名称");
}
return brand;
}
private String writeCreateRequest(JdPublishTaskCreateRequest request) {
try {
return objectMapper.writeValueAsString(request);
} catch (JsonProcessingException ex) {
throw new BusinessException("序列化建单载荷失败", ex);
}
}
private String targetBrandForClient(FileTaskEntity task, Integer protocol) {
String brand = readCreateRequest(task).getTargetBrandName();
if (brand != null && !JdPublishProtocol.supportsTargetBrand(protocol)) {
throw new BusinessException(409, "请升级数富客户端后再执行目标品牌上架任务");
}
return brand;
}
/** 与发布回执锁同一条父任务,品牌修正和换代必须一起提交。 */
@Transactional
public JdPublishTaskVo retryWithBrand(Long taskId, Long userId, int attempt, String rawBrand) {
String brand = requireTargetBrand(rawBrand);
FileTaskEntity task = assertOwnedTask(fileTaskMapper.selectByIdForUpdate(taskId), userId);
requireAttempt(task, attempt);
if (!TaskStatuses.FileTask.FAILED.equals(task.getStatus())
|| !JdPublishProtocol.needsBrandCorrection(task.getErrorMessage())) {
throw new BusinessException(409, "只有目标品牌校验失败的任务才能修改品牌后重试");
}
Map<String, Long> counts = aggregateStatusCounts(taskId);
if (counts.getOrDefault(ITEM_SUCCESS, 0L) > 0 || counts.getOrDefault(ITEM_PUBLISHING, 0L) > 0) {
throw new BusinessException(409, "已有发布成功或待确认记录,不能修改本任务品牌;请先在京麦核对");
}
JdPublishTaskCreateRequest create = readCreateRequest(task);
if (Objects.equals(brand, create.getTargetBrandName())) {
throw new BusinessException(400, "请输入正确的目标品牌,不能原样重试");
}
create.setTargetBrandName(brand);
String requestJson = writeCreateRequest(create);
int updated = fileTaskMapper.update(null, new LambdaUpdateWrapper<FileTaskEntity>()
.eq(FileTaskEntity::getId, taskId)
.eq(FileTaskEntity::getStatus, TaskStatuses.FileTask.FAILED)
.eq(FileTaskEntity::getResumeAttempt, attempt)
.set(FileTaskEntity::getRequestJson, requestJson)
.set(FileTaskEntity::getResumeAttempt, attempt + 1)
.set(FileTaskEntity::getStatus, STATUS_PENDING)
.set(FileTaskEntity::getSuccessFileCount, 0)
.set(FileTaskEntity::getFailedFileCount, 0)
.set(FileTaskEntity::getErrorMessage, null)
.set(FileTaskEntity::getFailureCategory, null)
.set(FileTaskEntity::getFinishedAt, null)
.set(FileTaskEntity::getUpdatedAt, LocalDateTime.now()));
if (updated != 1) {
throw new BusinessException(409, "任务状态已变化,请刷新后再试");
}
itemsReset.resetForRetry(taskId);
task.setRequestJson(requestJson);
task.setResumeAttempt(attempt + 1);
JdPublishTaskVo vo = new JdPublishTaskVo();
vo.setTaskId(taskId);
vo.setTaskNo(task.getTaskNo());
vo.setCollectChannel(task.getCollectChannel());
vo.setQueuePayload(buildQueuePayload(task));
return vo;
}
/** 改价规则归一化写回请求体:request_json 里的值必须就是闸门认可的值(铁律 27a 同源)。 */ /** 改价规则归一化写回请求体:request_json 里的值必须就是闸门认可的值(铁律 27a 同源)。 */
private void normalizePriceRule(JdPublishTaskCreateRequest request) { private void normalizePriceRule(JdPublishTaskCreateRequest request) {
PriceRule rule = request.getPriceRule(); PriceRule rule = request.getPriceRule();
@@ -28,8 +28,6 @@ import java.util.List;
@Tag(name = "任务兜底拉取", description = "供桌面客户端领取页面未推送成功的待执行任务") @Tag(name = "任务兜底拉取", description = "供桌面客户端领取页面未推送成功的待执行任务")
public class TaskClientPullController { public class TaskClientPullController {
private static final Integer JD_PUBLISH_PROTOCOL = 2;
private final TaskClientPullService taskClientPullService; private final TaskClientPullService taskClientPullService;
private final AdminAuthSupport adminAuthSupport; private final AdminAuthSupport adminAuthSupport;
@@ -41,7 +39,6 @@ public class TaskClientPullController {
public ApiResponse<List<TaskClientPullVo>> pullPending(HttpServletRequest request, public ApiResponse<List<TaskClientPullVo>> pullPending(HttpServletRequest request,
@RequestParam(name = "jdPublishProtocol", required = false) Integer jdPublishProtocol) { @RequestParam(name = "jdPublishProtocol", required = false) Integer jdPublishProtocol) {
AdminUserEntity me = adminAuthSupport.requireUser(request); AdminUserEntity me = adminAuthSupport.requireUser(request);
return ApiResponse.success(taskClientPullService.pullPendingTasks(me.getId(), return ApiResponse.success(taskClientPullService.pullPendingTasks(me.getId(), jdPublishProtocol));
JD_PUBLISH_PROTOCOL.equals(jdPublishProtocol)));
} }
} }
@@ -44,7 +44,8 @@ public interface FileTaskMapper extends BaseMapper<FileTaskEntity> {
@Param("moduleTypes") List<String> moduleTypes, @Param("moduleTypes") List<String> moduleTypes,
@Param("localDefaultModules") List<String> localDefaultModules, @Param("localDefaultModules") List<String> localDefaultModules,
@Param("cutoff") LocalDateTime cutoff, @Param("cutoff") LocalDateTime cutoff,
@Param("limit") int limit); @Param("limit") int limit,
@Param("supportsTargetBrand") boolean supportsTargetBrand);
/** /**
* 服务端内部认领候选(Linux 后台 worker):指定状态 + 白名单模块 + 创建早于 cutoff, * 服务端内部认领候选(Linux 后台 worker):指定状态 + 白名单模块 + 创建早于 cutoff,
@@ -1,6 +1,7 @@
package com.nanri.aiimage.modules.task.service; package com.nanri.aiimage.modules.task.service;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.nanri.aiimage.common.task.JdPublishProtocol;
import com.nanri.aiimage.config.CollectRoutingProperties; import com.nanri.aiimage.config.CollectRoutingProperties;
import com.nanri.aiimage.config.InstanceMetadata; import com.nanri.aiimage.config.InstanceMetadata;
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper; import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
@@ -128,10 +129,10 @@ public class TaskClientPullService {
/** 拉取并认领该用户"长期未被领取"的任务,按创建时间升序返回,最多 limit 条。 */ /** 拉取并认领该用户"长期未被领取"的任务,按创建时间升序返回,最多 limit 条。 */
public List<TaskClientPullVo> pullPendingTasks(Long userId) { public List<TaskClientPullVo> pullPendingTasks(Long userId) {
return pullPendingTasks(userId, false); return pullPendingTasks(userId, null);
} }
public List<TaskClientPullVo> pullPendingTasks(Long userId, boolean jdPublishV2) { public List<TaskClientPullVo> pullPendingTasks(Long userId, Integer jdPublishProtocol) {
if (!enabled) { if (!enabled) {
return List.of(); return List.of();
} }
@@ -139,7 +140,8 @@ public class TaskClientPullService {
return List.of(); return List.of();
} }
List<String> types = resolveModuleTypes(); List<String> types = resolveModuleTypes();
if (!jdPublishV2) { boolean supportsTargetBrand = JdPublishProtocol.supportsTargetBrand(jdPublishProtocol);
if (!supportsTargetBrand && !Integer.valueOf(JdPublishProtocol.LEGACY).equals(jdPublishProtocol)) {
types = withoutJdPublish(types); types = withoutJdPublish(types);
} }
if (types.isEmpty()) { if (types.isEmpty()) {
@@ -153,7 +155,7 @@ public class TaskClientPullService {
LocalDateTime cutoff = LocalDateTime.now(DB_ZONE).minusMinutes(Math.max(1L, minPendingMinutes)); LocalDateTime cutoff = LocalDateTime.now(DB_ZONE).minusMinutes(Math.max(1L, minPendingMinutes));
int safeLimit = Math.max(1, Math.min(limit, MAX_LIMIT)); int safeLimit = Math.max(1, Math.min(limit, MAX_LIMIT));
List<FileTaskEntity> candidates = fileTaskMapper.selectLocalChannelPendingTasks( List<FileTaskEntity> candidates = fileTaskMapper.selectLocalChannelPendingTasks(
userId, STATUS_PENDING, types, CollectChannel.localDefaultModuleTypes(), cutoff, safeLimit); userId, STATUS_PENDING, types, CollectChannel.localDefaultModuleTypes(), cutoff, safeLimit, supportsTargetBrand);
if (candidates.isEmpty() && !types.isEmpty()) { if (candidates.isEmpty() && !types.isEmpty()) {
log.info("[client-task-pull] 白名单内没有本机通道的排队任务,本次不拉取 userId={} moduleTypes={}", log.info("[client-task-pull] 白名单内没有本机通道的排队任务,本次不拉取 userId={} moduleTypes={}",
userId, moduleTypes); userId, moduleTypes);
@@ -218,7 +220,7 @@ public class TaskClientPullService {
candidate.getId(), candidate.getModuleType()); candidate.getId(), candidate.getModuleType());
continue; continue;
} }
if (!claim(candidate.getId())) { if (!claim(candidate)) {
log.info("[client-task-pull] 任务已被页面领取或状态已变化,跳过 taskId={}", candidate.getId()); log.info("[client-task-pull] 任务已被页面领取或状态已变化,跳过 taskId={}", candidate.getId());
continue; continue;
} }
@@ -279,10 +281,12 @@ public class TaskClientPullService {
* (ensureTaskOwnedByCurrentInstance)会拒绝(2026-09-30 内部认领上线实测: * (ensureTaskOwnedByCurrentInstance)会拒绝(2026-09-30 内部认领上线实测:
* 任务 parse 落 server-110、认领在 server-121,组装载荷被拒并误标失败)。 * 任务 parse 落 server-110、认领在 server-121,组装载荷被拒并误标失败)。
*/ */
private boolean claim(Long taskId) { private boolean claim(FileTaskEntity candidate) {
return fileTaskMapper.update(null, new LambdaUpdateWrapper<FileTaskEntity>() return fileTaskMapper.update(null, new LambdaUpdateWrapper<FileTaskEntity>()
.eq(FileTaskEntity::getId, taskId) .eq(FileTaskEntity::getId, candidate.getId())
.eq(FileTaskEntity::getStatus, STATUS_PENDING) .eq(FileTaskEntity::getStatus, STATUS_PENDING)
.eq(CollectRoutingProperties.MODULE_JD_PUBLISH.equals(candidate.getModuleType()),
FileTaskEntity::getResumeAttempt, candidate.getResumeAttempt())
.set(FileTaskEntity::getStatus, STATUS_RUNNING) .set(FileTaskEntity::getStatus, STATUS_RUNNING)
.set(FileTaskEntity::getUpdatedAt, LocalDateTime.now()) .set(FileTaskEntity::getUpdatedAt, LocalDateTime.now())
.set(FileTaskEntity::getOwnerInstanceId, currentInstanceId())) > 0; .set(FileTaskEntity::getOwnerInstanceId, currentInstanceId())) > 0;
@@ -2,6 +2,7 @@ package com.nanri.aiimage.modules.task.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.nanri.aiimage.common.task.JdPublishProtocol;
import com.nanri.aiimage.common.task.TaskStatuses; import com.nanri.aiimage.common.task.TaskStatuses;
import com.nanri.aiimage.modules.task.mapper.FileResultMapper; import com.nanri.aiimage.modules.task.mapper.FileResultMapper;
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper; import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
@@ -80,6 +81,9 @@ public class TaskInPlaceRetryService {
if (task == null || task.getId() == null) { if (task == null || task.getId() == null) {
return false; return false;
} }
if (requiresBrandCorrection(task)) {
return false;
}
if (STATUS_CANCELLED.equals(task.getStatus())) { if (STATUS_CANCELLED.equals(task.getStatus())) {
// 「继续」前先清模块补检预算:失败即中止(此刻任务一行未动,用户重按即可)。 // 「继续」前先清模块补检预算:失败即中止(此刻任务一行未动,用户重按即可)。
// 刻意不包 try/catch——本仓静默 catch 台账只许减,且放在 CAS 之前不会留下 // 刻意不包 try/catch——本仓静默 catch 台账只许减,且放在 CAS 之前不会留下
@@ -222,11 +226,18 @@ public class TaskInPlaceRetryService {
if (!STATUS_FAILED.equals(task.getStatus()) && !STATUS_CANCELLED.equals(task.getStatus())) { if (!STATUS_FAILED.equals(task.getStatus()) && !STATUS_CANCELLED.equals(task.getStatus())) {
throw new com.nanri.aiimage.common.exception.BusinessException("只有失败或已中断的任务可以继续"); throw new com.nanri.aiimage.common.exception.BusinessException("只有失败或已中断的任务可以继续");
} }
if (requiresBrandCorrection(task)) {
throw new com.nanri.aiimage.common.exception.BusinessException("请先修改目标品牌,再重试上架任务");
}
if (!retryInPlace(task)) { if (!retryInPlace(task)) {
throw new com.nanri.aiimage.common.exception.BusinessException("任务状态已变化,请刷新后再试"); throw new com.nanri.aiimage.common.exception.BusinessException("任务状态已变化,请刷新后再试");
} }
} }
private static boolean requiresBrandCorrection(FileTaskEntity task) {
return "JD_PUBLISH".equals(task.getModuleType()) && JdPublishProtocol.needsBrandCorrection(task.getErrorMessage());
}
/** /**
* 模块侧明细行复位(AC-7 服务端半边):京东上架的行级真源在 biz_jd_publish_item, * 模块侧明细行复位(AC-7 服务端半边):京东上架的行级真源在 biz_jd_publish_item,
* 上一代的 FAILED/PUBLISHING 行不复位,重试后的明细分批下发(只出 PENDING 行)就是 * 上一代的 FAILED/PUBLISHING 行不复位,重试后的明细分批下发(只出 PENDING 行)就是
@@ -30,7 +30,7 @@
<!-- 客户端兜底拉取候选(P1-1):通道谓词与 status/模块/时间窗口同在 WHERE 里,LIMIT 之后不再有 Java 过滤。 --> <!-- 客户端兜底拉取候选(P1-1):通道谓词与 status/模块/时间窗口同在 WHERE 里,LIMIT 之后不再有 Java 过滤。 -->
<select id="selectLocalChannelPendingTasks" <select id="selectLocalChannelPendingTasks"
resultType="com.nanri.aiimage.modules.task.model.entity.FileTaskEntity"> resultType="com.nanri.aiimage.modules.task.model.entity.FileTaskEntity">
SELECT id, module_type, collect_channel, created_at SELECT id, module_type, collect_channel, created_at, resume_attempt
FROM biz_file_task FROM biz_file_task
WHERE user_id = #{userId} WHERE user_id = #{userId}
AND status = #{status} AND status = #{status}
@@ -38,6 +38,10 @@
<foreach collection="moduleTypes" item="module" open="(" separator="," close=")">#{module}</foreach> <foreach collection="moduleTypes" item="module" open="(" separator="," close=")">#{module}</foreach>
AND created_at &lt; #{cutoff} AND created_at &lt; #{cutoff}
AND <include refid="resolvedChannelCase"/> = 'LOCAL' AND <include refid="resolvedChannelCase"/> = 'LOCAL'
<if test="supportsTargetBrand == false">
AND (module_type != 'JD_PUBLISH'
OR COALESCE(JSON_TYPE(JSON_EXTRACT(request_json, '$.targetBrandName')), 'NULL') = 'NULL')
</if>
ORDER BY created_at ASC ORDER BY created_at ASC
LIMIT #{limit} LIMIT #{limit}
</select> </select>
@@ -120,8 +120,8 @@ class JdPublishContractPendingTest {
String source = Files.readString(PUBLISH_CONTROLLER); String source = Files.readString(PUBLISH_CONTROLLER);
// 类级 @RequestMapping 与方法级 @PostMapping 分开写,拼接串搜不到(照 AC-9 格同一口径)。 // 类级 @RequestMapping 与方法级 @PostMapping 分开写,拼接串搜不到(照 AC-9 格同一口径)。
assertTrue(source.contains("/api/jd-publish"), "缺类级 @RequestMapping /api/jd-publish"); assertTrue(source.contains("/api/jd-publish"), "缺类级 @RequestMapping /api/jd-publish");
assertTrue(source.contains("@PostMapping(\"/tasks\")"), "缺建单端点 POST /tasks"); assertTrue(source.contains("@PostMapping({\"/tasks\", \"/tasks/target-brand\"})"),
assertTrue(source.contains("@PostMapping"), "建单必须是 POST 端点"); "保留原建单入口,新页面必须用独立品牌入口,避免旧服务静默忽略品牌");
// AC-9 归属半边:选了他人商品要业务码拒绝(照 JdCollectController 的 fail-closed 鉴权形状) // AC-9 归属半边:选了他人商品要业务码拒绝(照 JdCollectController 的 fail-closed 鉴权形状)
assertTrue(source.contains("adminAuthSupport.requireSessionOwnerUserId(httpRequest"), assertTrue(source.contains("adminAuthSupport.requireSessionOwnerUserId(httpRequest"),
"京东发布必须使用真实会话绑定所有者"); "京东发布必须使用真实会话绑定所有者");
@@ -168,6 +168,36 @@ class JdPublishIngestServiceTest {
verify(taskProgressSnapshotService).markTerminal(TASK_ID, "JD_PUBLISH", "FAILED", "发布完成:成功 0 行,失败 1 行"); verify(taskProgressSnapshotService).markTerminal(TASK_ID, "JD_PUBLISH", "FAILED", "发布完成:成功 0 行,失败 1 行");
} }
@Test
void 品牌预检阻断整单但保留既有成功与待确认行() {
task("RUNNING", 1, 3);
row("PENDING", null, null);
when(jdPublishItemMapper.update(isNull(), any())).thenReturn(1);
when(fileTaskMapper.update(isNull(), any())).thenReturn(1);
when(jdPublishItemMapper.countByPublishStatus(TASK_ID)).thenReturn(List.of(
Map.of("publishStatus", "FAILED", "cnt", 1),
Map.of("publishStatus", "SUCCESS", "cnt", 1),
Map.of("publishStatus", "PUBLISHING", "cnt", 1)));
JdPublishChunkRequest request = request(1, "batchA", "FAILED", "商品 101 无法选择品牌 B");
request.setPreflightFailure(JdPublishChunkRequest.PreflightFailure.BRAND);
var result = service.submitChunk(TASK_ID, request, UID);
assertThat(result.getTaskStatus()).isEqualTo("FAILED");
assertThat(result.getPublishingCount()).isOne();
verify(taskProgressSnapshotService).markTerminal(TASK_ID, "JD_PUBLISH", "FAILED",
"目标品牌校验失败:商品 101 无法选择品牌 B");
verifyNoInteractions(staleTaskService);
}
@Test
void 预检没有关联有效失败行不能终止任务() {
task("RUNNING", 1, 2);
JdPublishChunkRequest request = request(1, "batchA", null, null);
request.setPreflightFailure(JdPublishChunkRequest.PreflightFailure.SOURCE);
assertThatThrownBy(() -> service.submitChunk(TASK_ID, request, UID))
.isInstanceOf(BusinessException.class).extracting("code").isEqualTo(400);
verifyNoInteractions(jdPublishItemMapper, taskProgressSnapshotService);
}
@Test @Test
void 登录失效必须先写真实失败行才可判死() { void 登录失效必须先写真实失败行才可判死() {
FileTaskEntity task = task("RUNNING", 1, 2); FileTaskEntity task = task("RUNNING", 1, 2);
@@ -69,6 +69,8 @@ class JdPublishTaskServiceTest {
private TaskHeartbeatService taskHeartbeatService; private TaskHeartbeatService taskHeartbeatService;
@Mock @Mock
private TaskHeartbeatPositionService taskHeartbeatPositionService; private TaskHeartbeatPositionService taskHeartbeatPositionService;
@Mock
private JdPublishTaskItemsResetSpiImpl itemsReset;
@InjectMocks @InjectMocks
private JdPublishTaskService service; private JdPublishTaskService service;
@@ -92,6 +94,7 @@ class JdPublishTaskServiceTest {
request.setUserId(userId); request.setUserId(userId);
request.setCategoryId(11L); request.setCategoryId(11L);
request.setProductIds(List.of(101L, 102L)); request.setProductIds(List.of(101L, 102L));
request.setTargetBrandName(" 目标品牌B ");
return request; return request;
} }
@@ -119,7 +122,8 @@ class JdPublishTaskServiceTest {
assertThat(task.getStatus()).isEqualTo("PENDING"); assertThat(task.getStatus()).isEqualTo("PENDING");
assertThat(task.getUserId()).isEqualTo(7L); assertThat(task.getUserId()).isEqualTo(7L);
assertThat(task.getSourceFileCount()).isEqualTo(2); assertThat(task.getSourceFileCount()).isEqualTo(2);
assertThat(task.getRequestJson()).contains("101").contains("102"); assertThat(task.getRequestJson()).contains("101").contains("102")
.contains("\"targetBrandName\":\"目标品牌B\"");
// AC-1 明细快照行:每勾选商品一行 // AC-1 明细快照行:每勾选商品一行
verify(jdPublishItemMapper, org.mockito.Mockito.times(2)).insert(any(JdPublishItemEntity.class)); verify(jdPublishItemMapper, org.mockito.Mockito.times(2)).insert(any(JdPublishItemEntity.class));
// AC-8 配额闸:前置且按勾选数计 // AC-8 配额闸:前置且按勾选数计
@@ -243,6 +247,74 @@ class JdPublishTaskServiceTest {
.hasMessageContaining("必须填写加价值"); .hasMessageContaining("必须填写加价值");
} }
@Test
void 空白目标品牌建单不查配额不落库() {
var request = validRequest(7L);
request.setTargetBrandName("  ");
assertThatThrownBy(() -> service.createTask(request, null))
.isInstanceOf(BusinessException.class).hasMessageContaining("请填写目标品牌");
verify(adminUserMapper, never()).selectById(any());
}
@Test
void 品牌任务旧版不激活也不下发明细() {
FileTaskEntity task = new FileTaskEntity();
task.setModuleType("JD_PUBLISH");
task.setUserId(7L);
task.setRequestJson("{\"productIds\":[101],\"targetBrandName\":\"品牌B\"}");
when(fileTaskMapper.selectById(34400L)).thenReturn(task);
assertThatThrownBy(() -> service.activateTask(34400L, 7L, 0, 2))
.isInstanceOf(BusinessException.class).hasMessageContaining("升级");
task.setStatus("RUNNING");
assertThatThrownBy(() -> service.pullItems(34400L, 7L, 0, 0L, null, null))
.isInstanceOf(BusinessException.class).hasMessageContaining("升级");
when(jdPublishItemMapper.selectPublishableItems(34400L, 0L, 20)).thenReturn(List.of());
when(jdPublishItemMapper.countByPublishStatus(34400L)).thenReturn(List.of());
assertThat(service.pullItems(34400L, 7L, 0, 0L, null, 3).getTargetBrandName()).isEqualTo("品牌B");
}
@Test
void 修正品牌在原任务换代并经同一快照下发() {
FileTaskEntity task = rejectedBrandTask();
when(jdPublishItemMapper.countByPublishStatus(34400L)).thenReturn(List.of());
when(fileTaskMapper.update(any(), any())).thenReturn(1);
var result = service.retryWithBrand(34400L, 7L, 4, " 品牌C ");
assertThat(result.getTaskId()).isEqualTo(34400L);
assertThat(result.getQueuePayload().get("data").toString()).contains("resumeAttempt=5", "targetBrandRequired=true");
assertThat(service.readCreateRequest(task).getTargetBrandName()).isEqualTo("品牌C");
assertThat(service.readCreateRequest(task).getProductIds()).containsExactly(101L);
verify(itemsReset).resetForRetry(34400L);
}
@Test
void 品牌纠错不接受旧代相同品牌或已有提交许可() {
rejectedBrandTask();
assertThatThrownBy(() -> service.retryWithBrand(34400L, 7L, 3, "品牌C"))
.isInstanceOf(BusinessException.class).hasMessageContaining("代次");
when(jdPublishItemMapper.countByPublishStatus(34400L)).thenReturn(List.of());
assertThatThrownBy(() -> service.retryWithBrand(34400L, 7L, 4, "品牌B"))
.isInstanceOf(BusinessException.class).hasMessageContaining("不能原样重试");
when(jdPublishItemMapper.countByPublishStatus(34400L)).thenReturn(List.of(
java.util.Map.of("publishStatus", "PUBLISHING", "cnt", 1)));
assertThatThrownBy(() -> service.retryWithBrand(34400L, 7L, 4, "品牌C"))
.isInstanceOf(BusinessException.class).hasMessageContaining("待确认");
verify(fileTaskMapper, never()).update(any(), any());
verify(itemsReset, never()).resetForRetry(any());
}
private FileTaskEntity rejectedBrandTask() {
FileTaskEntity task = new FileTaskEntity();
task.setId(34400L);
task.setUserId(7L);
task.setModuleType("JD_PUBLISH");
task.setStatus("FAILED");
task.setResumeAttempt(4);
task.setErrorMessage("目标品牌校验失败:目标店铺中不存在品牌B");
task.setRequestJson("{\"productIds\":[101],\"targetBrandName\":\"品牌B\"}");
when(fileTaskMapper.selectByIdForUpdate(34400L)).thenReturn(task);
return task;
}
@Test @Test
void 统一改价折算口径() { void 统一改价折算口径() {
PriceRule percent = new PriceRule(); PriceRule percent = new PriceRule();
@@ -267,6 +339,7 @@ class JdPublishTaskServiceTest {
task.setModuleType("JD_PUBLISH"); task.setModuleType("JD_PUBLISH");
task.setUserId(7L); task.setUserId(7L);
task.setStatus("RUNNING"); task.setStatus("RUNNING");
task.setRequestJson("{\"productIds\":[101]}");
when(fileTaskMapper.selectById(34400L)).thenReturn(task); when(fileTaskMapper.selectById(34400L)).thenReturn(task);
JdPublishItemEntity row = new JdPublishItemEntity(); JdPublishItemEntity row = new JdPublishItemEntity();
@@ -286,7 +359,8 @@ class JdPublishTaskServiceTest {
when(jdProductSkuMapper.selectList(any())).thenReturn(List.of()); when(jdProductSkuMapper.selectList(any())).thenReturn(List.of());
when(jdProductImageMapper.selectList(any())).thenReturn(List.of()); when(jdProductImageMapper.selectList(any())).thenReturn(List.of());
var vo = service.pullItems(34400L, 7L, 0, 0L, null); var vo = service.pullItems(34400L, 7L, 0, 0L, null, null);
assertThat(vo.getTargetBrandName()).isNull();
assertThat(vo.getTaskId()).isEqualTo(34400L); assertThat(vo.getTaskId()).isEqualTo(34400L);
assertThat(vo.getItems()).hasSize(1); assertThat(vo.getItems()).hasSize(1);
@@ -304,7 +378,7 @@ class JdPublishTaskServiceTest {
task.setUserId(8L); task.setUserId(8L);
task.setStatus("RUNNING"); task.setStatus("RUNNING");
when(fileTaskMapper.selectById(34400L)).thenReturn(task); when(fileTaskMapper.selectById(34400L)).thenReturn(task);
assertThatThrownBy(() -> service.pullItems(34400L, 7L, 0, 0L, null)) assertThatThrownBy(() -> service.pullItems(34400L, 7L, 0, 0L, null, null))
.isInstanceOf(BusinessException.class) .isInstanceOf(BusinessException.class)
.extracting("code") .extracting("code")
.isEqualTo(403); .isEqualTo(403);
@@ -50,7 +50,7 @@ class FileTaskMapperChannelSqlTest {
assertTrue(limit > at, () -> "通道谓词必须出现在 LIMIT 之前,否则取到的那一页里没有本机单: " + sql); assertTrue(limit > at, () -> "通道谓词必须出现在 LIMIT 之前,否则取到的那一页里没有本机单: " + sql);
assertTrue(sql.indexOf("ORDER BY created_at ASC") < limit, assertTrue(sql.indexOf("ORDER BY created_at ASC") < limit,
() -> "排序必须在 LIMIT 之前,否则取页不是「最早创建的本机单」: " + sql); () -> "排序必须在 LIMIT 之前,否则取页不是「最早创建的本机单」: " + sql);
assertEquals("SELECT id, module_type, collect_channel, created_at FROM biz_file_task" assertEquals("SELECT id, module_type, collect_channel, created_at, resume_attempt FROM biz_file_task"
+ " WHERE user_id = ? AND status = ? AND module_type IN (?, ?) AND created_at < ?" + " WHERE user_id = ? AND status = ? AND module_type IN (?, ?) AND created_at < ?"
+ " AND CASE WHEN collect_channel IN ('LOCAL', 'ONLINE') THEN collect_channel" + " AND CASE WHEN collect_channel IN ('LOCAL', 'ONLINE') THEN collect_channel"
+ " WHEN module_type IN (?, ?) THEN 'LOCAL' ELSE 'ONLINE' END = 'LOCAL'" + " WHEN module_type IN (?, ?) THEN 'LOCAL' ELSE 'ONLINE' END = 'LOCAL'"
@@ -83,9 +83,19 @@ class FileTaskMapperChannelSqlTest {
} }
@Test @Test
void 取页投影只有认领需要的四列() throws Exception { void 旧版排除品牌任务且版本筛选在取页以前() throws Exception {
var params = new java.util.HashMap<>(clientParams(2));
params.put("supportsTargetBrand", false);
String sql = render("selectLocalChannelPendingTasks", params);
int predicate = sql.indexOf("JSON_EXTRACT(request_json, '$.targetBrandName')");
assertTrue(predicate > 0 && predicate < sql.indexOf("LIMIT ?"), sql);
assertFalse(render("selectLocalChannelPendingTasks", clientParams(2)).contains("JSON_EXTRACT"));
}
@Test
void 取页只投影认领所需的窄列和代次() throws Exception {
String sql = render("selectLocalChannelPendingTasks", clientParams(2)); String sql = render("selectLocalChannelPendingTasks", clientParams(2));
assertTrue(sql.startsWith("SELECT id, module_type, collect_channel, created_at FROM biz_file_task"), assertTrue(sql.startsWith("SELECT id, module_type, collect_channel, created_at, resume_attempt FROM biz_file_task"),
() -> "投影列清单变了(整行拉回来会把 result_json 这类大列带进兜底轮询): " + sql); () -> "投影列清单变了(整行拉回来会把 result_json 这类大列带进兜底轮询): " + sql);
} }
@@ -95,7 +95,7 @@ class TaskClientPullServiceTest {
// 这里钉「调用的是哪条具名查询、传了什么」,两者合起来才挡住 P1-1 复发。 // 这里钉「调用的是哪条具名查询、传了什么」,两者合起来才挡住 P1-1 复发。
verify(fileTaskMapper).selectLocalChannelPendingTasks(eq(USER_ID), eq("PENDING"), verify(fileTaskMapper).selectLocalChannelPendingTasks(eq(USER_ID), eq("PENDING"),
eq(List.of("SIMILAR_ASIN", "COLLECT_DATA")), eq(CollectChannel.localDefaultModuleTypes()), eq(List.of("SIMILAR_ASIN", "COLLECT_DATA")), eq(CollectChannel.localDefaultModuleTypes()),
any(LocalDateTime.class), eq(5)); any(LocalDateTime.class), eq(5), eq(false));
} }
@Test @Test
@@ -103,12 +103,15 @@ class TaskClientPullServiceTest {
TaskClientPullService service = service(new StubHandler("SIMILAR_ASIN", payload("similar-asin-run"))); TaskClientPullService service = service(new StubHandler("SIMILAR_ASIN", payload("similar-asin-run")));
ReflectionTestUtils.setField(service, "moduleTypes", "JD_PUBLISH,SIMILAR_ASIN"); ReflectionTestUtils.setField(service, "moduleTypes", "JD_PUBLISH,SIMILAR_ASIN");
service.pullPendingTasks(USER_ID); service.pullPendingTasks(USER_ID);
service.pullPendingTasks(USER_ID, true); service.pullPendingTasks(USER_ID, 2);
service.pullPendingTasks(USER_ID, 3);
verify(fileTaskMapper).selectLocalChannelPendingTasks(eq(USER_ID), eq("PENDING"), verify(fileTaskMapper).selectLocalChannelPendingTasks(eq(USER_ID), eq("PENDING"),
eq(List.of("SIMILAR_ASIN")), eq(CollectChannel.localDefaultModuleTypes()), any(), eq(5)); eq(List.of("SIMILAR_ASIN")), eq(CollectChannel.localDefaultModuleTypes()), any(), eq(5), eq(false));
verify(fileTaskMapper).selectLocalChannelPendingTasks(eq(USER_ID), eq("PENDING"), verify(fileTaskMapper).selectLocalChannelPendingTasks(eq(USER_ID), eq("PENDING"),
eq(List.of("JD_PUBLISH", "SIMILAR_ASIN")), eq(CollectChannel.localDefaultModuleTypes()), any(), eq(5)); eq(List.of("JD_PUBLISH", "SIMILAR_ASIN")), eq(CollectChannel.localDefaultModuleTypes()), any(), eq(5), eq(false));
verify(fileTaskMapper).selectLocalChannelPendingTasks(eq(USER_ID), eq("PENDING"),
eq(List.of("JD_PUBLISH", "SIMILAR_ASIN")), eq(CollectChannel.localDefaultModuleTypes()), any(), eq(5), eq(true));
} }
@Test @Test
@@ -289,7 +292,8 @@ class TaskClientPullServiceTest {
} }
private void stubPullCandidates(FileTaskEntity... rows) { private void stubPullCandidates(FileTaskEntity... rows) {
when(fileTaskMapper.selectLocalChannelPendingTasks(any(), any(), any(), any(), any(), anyInt())) when(fileTaskMapper.selectLocalChannelPendingTasks(any(), any(), any(), any(), any(), anyInt(),
org.mockito.ArgumentMatchers.anyBoolean()))
.thenReturn(List.of(rows)); .thenReturn(List.of(rows));
} }
@@ -130,6 +130,17 @@ class TaskInPlaceRetryServiceTest {
} }
// ---- AC-7 服务端半边(v1.5 Phase 5):模块侧明细行随任务头一并复位 ---- // ---- AC-7 服务端半边(v1.5 Phase 5):模块侧明细行随任务头一并复位 ----
@Test
void 京东上架品牌校验失败不能原样重试() {
FileTaskMapper mapper = mock(FileTaskMapper.class);
FileTaskEntity task = failedTask();
task.setModuleType("JD_PUBLISH");
task.setErrorMessage("目标品牌校验失败:店铺中没有品牌B");
var retry = service(mapper, mock(FileResultMapper.class), mock(TaskFileJobService.class));
assertFalse(retry.retryInPlace(task));
verify(mapper, never()).update(any(), any());
}
@Test @Test
void 京东上架重试必须复位模块侧明细行() { void 京东上架重试必须复位模块侧明细行() {
FileTaskMapper mapper = mock(FileTaskMapper.class); FileTaskMapper mapper = mock(FileTaskMapper.class);
+171 -35
View File
@@ -1,5 +1,5 @@
<script setup lang="ts"> <script setup lang="ts">
import { computed, onMounted, onUnmounted, ref } from 'vue' import { computed, onMounted, onUnmounted, ref, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus' import { ElMessage, ElMessageBox } from 'element-plus'
import TaskCenterPanel from '@/shared/components/tasks/TaskCenterPanel.vue' import TaskCenterPanel from '@/shared/components/tasks/TaskCenterPanel.vue'
import type { TaskItemView, TaskStatCard } from '@/shared/components/tasks/types' import type { TaskItemView, TaskStatCard } from '@/shared/components/tasks/types'
@@ -15,6 +15,7 @@ import {
fetchJdPublishProducts, fetchJdPublishProducts,
fetchJdPublishTaskProgressBatch, fetchJdPublishTaskProgressBatch,
interruptJdPublishTask, interruptJdPublishTask,
retryJdPublishBrand,
type JdPublishHistoryItemVo, type JdPublishHistoryItemVo,
type JdPublishProductVo, type JdPublishProductVo,
} from '@/shared/api/types/modules/jd-publish' } from '@/shared/api/types/modules/jd-publish'
@@ -36,7 +37,7 @@ import NotificationBell from '@/shared/components/NotificationBell.vue'
* 同一规则折算 SKU 价(铁律 27a 改价同源); * 同一规则折算 SKU 价(铁律 27a 改价同源);
* 3. 网页原样转交建单响应的 queuePayload;认领只由客户端与后端完成,投递失败仍可由客户端拉取; * 3. 网页原样转交建单响应的 queuePayload;认领只由客户端与后端完成,投递失败仍可由客户端拉取;
* 4. 进度只读服务端:行级四档计数来自发布明细表聚合,total 缺失时只报已发布行数,不编造百分比; * 4. 进度只读服务端:行级四档计数来自发布明细表聚合,total 缺失时只报已发布行数,不编造百分比;
* 5. 失败/中断「重试/继续」走通用原位复位(铁律 26,不克隆),新一轮由客户端拉取认领; * 5. 失败/中断在原任务上重试,目标品牌校验失败时只允许符合条件的任务改品牌后重试;
* 6. 京麦未登录等凭据致命失败(铁律 31):服务端整单判死后 useLiveTaskBoard 经 * 6. 京麦未登录等凭据致命失败(铁律 31):服务端整单判死后 useLiveTaskBoard 经
* reportCredentialFatal 弹一次窗(credential-fatal 同形接入,AC-5 用户端半边;弹窗组件 * reportCredentialFatal 弹一次窗(credential-fatal 同形接入,AC-5 用户端半边;弹窗组件
* 挂 App.vue,本页无需重复挂)。 * 挂 App.vue,本页无需重复挂)。
@@ -152,6 +153,14 @@ const PRICE_RULE_MODES = [
] as const ] as const
const priceMode = ref<'none' | 'percent' | 'fixed'>('none') const priceMode = ref<'none' | 'percent' | 'fixed'>('none')
const priceValue = ref<number | null>(null) const priceValue = ref<number | null>(null)
const targetBrandInput = ref('')
const TARGET_BRAND_MAX = 120
const TARGET_BRAND_ERROR = '请输入目标品牌名称,去掉首尾空格后须为 1–120 个字符。'
const targetBrandName = computed(() => targetBrandInput.value.trim())
function isValidBrand(name: string) {
return name.length > 0 && name.length <= TARGET_BRAND_MAX
}
const priceValueMissing = computed(() => priceMode.value !== 'none' && (priceValue.value == null || priceValue.value < 0)) const priceValueMissing = computed(() => priceMode.value !== 'none' && (priceValue.value == null || priceValue.value < 0))
@@ -159,9 +168,23 @@ const submitDisabled = computed(() =>
submitting.value submitting.value
|| !selectedGroupId.value || !selectedGroupId.value
|| !selectedProducts.value.size || !selectedProducts.value.size
|| !isValidBrand(targetBrandName.value)
|| priceValueMissing.value) || priceValueMissing.value)
// 重试回执不带代数:旧代 + 1 只用作读侧下限,不生成任务或队列数据。 // 此闸只约束京东品牌发布,不改变客户端其他功能的全局版本门槛。
const JD_PUBLISH_PROTOCOL = 3
const JD_UPGRADE_NOTICE = '请升级到支持目标品牌发布的数富AI客户端,并在客户端内打开本页。'
async function supportsBrandPublishing() {
try {
return await getPywebviewApi()?.jd_publish_protocol?.() === JD_PUBLISH_PROTOCOL
} catch (error) {
console.error('[jd-publish] 读取本机发布协议失败', error)
return false
}
}
// 通用重试回执不带代数:旧代 + 1 只用作读侧下限,不生成任务或队列数据。
const retryAttemptFloor = new Map<number, number>() const retryAttemptFloor = new Map<number, number>()
const awaitingRetryProgress = new Set<number>() const awaitingRetryProgress = new Set<number>()
const retryingTaskIds = ref(new Set<number>()) const retryingTaskIds = ref(new Set<number>())
@@ -192,12 +215,22 @@ async function fetchCurrentProgress(taskIds: number[], { force }: { force: boole
}) })
return { return {
...batch, ...batch,
items: batch.items.filter(({ task, items }) => { items: batch.items.flatMap((detail) => {
if (task?.id == null || !unchanged(task.id) || !acceptsAttempt(task.id, task.resumeAttempt)) return false const { task, items } = detail
if (task?.id == null || !unchanged(task.id) || !acceptsAttempt(task.id, task.resumeAttempt)) return []
const row = items?.[0] const row = items?.[0]
if (row && !acceptsAttempt(task.id, row.resumeAttempt)) return false if (row && !acceptsAttempt(task.id, row.resumeAttempt)) return []
awaitingRetryProgress.delete(task.id) awaitingRetryProgress.delete(task.id)
return true // 稳定分档来自任务头,而非商品行错误;缺行时仍显示失败,但不猜商品计数。
if (task.status?.toUpperCase() !== 'FAILED' || !validationFailureKind(task.errorMessage)) return [detail]
// 京东校验提示由本页处理,不把原文交给通用凭据分类器。
return [{ ...detail, task: { ...task, errorMessage: undefined }, items: [{
...row,
taskId: task.id,
taskStatus: task.status,
resumeAttempt: task.resumeAttempt,
errorMessage: task.errorMessage,
}] }]
}), }),
missingTaskIds: batch.missingTaskIds.filter(unchanged), missingTaskIds: batch.missingTaskIds.filter(unchanged),
} }
@@ -249,6 +282,7 @@ function toJdPublishTaskView(item: JdPublishHistoryItemVo): TaskItemView {
const showProgress = isActiveTask(item) const showProgress = isActiveTask(item)
const total = typeof item.productTotal === 'number' && item.productTotal > 0 ? item.productTotal : null const total = typeof item.productTotal === 'number' && item.productTotal > 0 ? item.productTotal : null
const published = (item.successCount ?? 0) + (item.failedCount ?? 0) const published = (item.successCount ?? 0) + (item.failedCount ?? 0)
const failureNotice = validationFailureNotice(item)
return { return {
key: `jd-publish-${item.taskId ?? item.taskNo ?? item.updatedAt ?? ''}`, key: `jd-publish-${item.taskId ?? item.taskNo ?? item.updatedAt ?? ''}`,
title: `商品上架 · ${total ?? '—'} 个商品`, title: `商品上架 · ${total ?? '—'} 个商品`,
@@ -261,7 +295,8 @@ function toJdPublishTaskView(item: JdPublishHistoryItemVo): TaskItemView {
`成功 ${item.successCount ?? 0} / 失败 ${item.failedCount ?? 0}` `成功 ${item.successCount ?? 0} / 失败 ${item.failedCount ?? 0}`
+ (item.publishingCount ? ` / 发布中 ${item.publishingCount}` : ''), + (item.publishingCount ? ` / 发布中 ${item.publishingCount}` : ''),
...(showProgress && total ? [`已发布 ${Math.min(published, total)}/${total} 个商品`] : []), ...(showProgress && total ? [`已发布 ${Math.min(published, total)}/${total} 个商品`] : []),
...(item.errorMessage ? [`错误:${userNotice(item.errorMessage)}`] : []), ...(failureNotice ? [`错误:${failureNotice.title}:${failureNotice.body}`]
: item.errorMessage ? [`错误:${userNotice(item.errorMessage)}`] : []),
], ],
progress: showProgress ? { percent: progressPercent(item), countLabel: progressCountLabel(item) } : null, progress: showProgress ? { percent: progressPercent(item), countLabel: progressCountLabel(item) } : null,
source: item, source: item,
@@ -317,15 +352,73 @@ function progressCountLabel(item: JdPublishHistoryItemVo) {
return `已发布 ${published}/${total} 个商品(${progressPercent(item)}%)` return `已发布 ${published}/${total} 个商品(${progressPercent(item)}%)`
} }
/** 失败/已中断的任务能续跑:在原任务上复位(不新建任务)。 */ function validationFailureKind(message: string | undefined) {
if (message?.startsWith('目标品牌校验失败:')) return 'brand'
if (message?.startsWith('本店源商品校验失败:')) return 'source'
return null
}
function canChangeBrand(item: JdPublishHistoryItemVo) {
return item.successCount === 0 && item.publishingCount === 0
}
function validationFailureDetail(message: string) {
// 只去掉发布校验机器码,不把商品编码或英文品牌名误当错误码。
const detail = message.slice(message.indexOf(':') + 1)
.replace(/[((]\s*JD_(?:BRAND|SOURCE)_[A-Z0-9_]+\s*[))]|\bJD_(?:BRAND|SOURCE)_[A-Z0-9_]+\b/g, '')
.trim()
return /\p{Script=Han}/u.test(detail) ? detail : ''
}
function validationFailureNotice(item: JdPublishHistoryItemVo) {
if (normalizeTaskStatus(item) !== 'FAILED') return null
const kind = validationFailureKind(item.errorMessage)
if (!kind || !item.errorMessage) return null
const detail = validationFailureDetail(item.errorMessage)
const addAction = (action: string) => detail ? `${detail}\n${action}` : action
if (kind === 'brand') {
return {
title: '目标品牌校验失败',
body: addAction(canChangeBrand(item)
? '请核对当前京麦店铺可用的品牌名称,然后选择「修改品牌并重试」。'
: '请保留已发布结果,核对京麦中的发布状态,然后重新选择未发布商品建单。'),
}
}
return {
title: '本店源商品校验失败',
body: addAction('请切换到正确店铺后重试,或重新选择本店商品建单。'),
}
}
const shownValidationFailures = new Set<string>()
watch(
() => board.historyItems.value.map((item) => ({
taskId: item.taskId, attempt: item.resumeAttempt ?? 0, notice: validationFailureNotice(item),
})),
(items) => {
for (const { taskId, attempt, notice } of items) {
if (!taskId || !notice) continue
const key = `${taskId}:${attempt}`
if (shownValidationFailures.has(key)) continue
shownValidationFailures.add(key)
void ElMessageBox.alert(notice.body, notice.title, {
type: 'warning', confirmButtonText: '知道了', dangerouslyUseHTMLString: false,
})
.then(() => undefined, () => undefined)
}
},
)
/** 失败/已中断的任务能续跑;品牌失败仅在既无成功也无待确认商品时允许改品牌。 */
function canRetryTask(item: JdPublishHistoryItemVo | null | undefined): boolean { function canRetryTask(item: JdPublishHistoryItemVo | null | undefined): boolean {
if (!item?.taskId) return false if (!item?.taskId) return false
const status = normalizeTaskStatus(item) const status = normalizeTaskStatus(item)
if (status === 'FAILED' && validationFailureKind(item.errorMessage) === 'brand') return canChangeBrand(item)
return status === 'FAILED' || status === 'CANCELLED' return status === 'FAILED' || status === 'CANCELLED'
} }
/** 按钮文案:已中断的任务显示「继续」(从断点接着跑),失败任务仍是「重试」。 */
function retryLabel(item: JdPublishHistoryItemVo | null | undefined): string { function retryLabel(item: JdPublishHistoryItemVo | null | undefined): string {
if (normalizeTaskStatus(item) === 'FAILED' && validationFailureKind(item?.errorMessage) === 'brand') return '修改品牌并重试'
return normalizeTaskStatus(item) === 'CANCELLED' ? '继续' : '重试' return normalizeTaskStatus(item) === 'CANCELLED' ? '继续' : '重试'
} }
@@ -358,24 +451,53 @@ async function interruptTaskRecord(item: JdPublishHistoryItemVo | null | undefin
} }
} }
async function retryTaskRecord(item: JdPublishHistoryItemVo | null | undefined) { async function promptRetryBrand(): Promise<string | null> {
const taskId = item?.taskId if (!await supportsBrandPublishing()) {
if (!taskId || retryingTaskIds.value.has(taskId)) return ElMessage.error(JD_UPGRADE_NOTICE)
const isResume = normalizeTaskStatus(item) === 'CANCELLED' return null
retryingTaskIds.value.add(taskId) }
const retried = await retryClientTask(taskId).then(() => true, (error: unknown) => { const name = await ElMessageBox.prompt('请输入当前京麦店铺可用的目标品牌名称。', '修改品牌并重试', {
ElMessage.error(error instanceof Error ? error.message : '重试失败') confirmButtonText: '重试',
return false cancelButtonText: '取消',
}) inputValidator: (value: string) => isValidBrand(value.trim()) || TARGET_BRAND_ERROR,
retryingTaskIds.value.delete(taskId) }).then(({ value }) => value.trim(), () => null)
if (!retried) return return name && isValidBrand(name) ? name : null
}
async function retryTaskRecord(item: JdPublishHistoryItemVo | null | undefined) {
if (!item?.taskId || !canRetryTask(item) || retryingTaskIds.value.has(item.taskId)) return
const { taskId, resumeAttempt = 0 } = item
const changeBrand = normalizeTaskStatus(item) === 'FAILED' && validationFailureKind(item.errorMessage) === 'brand'
const isResume = normalizeTaskStatus(item) === 'CANCELLED'
let nextPayload: Record<string, unknown> | undefined
retryingTaskIds.value.add(taskId)
try {
if (changeBrand) {
const brand = await promptRetryBrand()
if (!brand) return
const vo = await retryJdPublishBrand(taskId, brand, resumeAttempt)
nextPayload = vo.queuePayload
} else {
await retryClientTask(taskId)
}
retryAttemptFloor.set(taskId, resumeAttempt + 1)
} catch (error) {
ElMessage.error(error instanceof Error ? userNotice(error.message) : '重试失败')
return
} finally {
retryingTaskIds.value.delete(taskId)
}
retryAttemptFloor.set(taskId, (item.resumeAttempt ?? 0) + 1)
awaitingRetryProgress.add(taskId) awaitingRetryProgress.add(taskId)
board.removePollingTask(taskId) board.removePollingTask(taskId)
board.historyItems.value = board.historyItems.value.filter((row) => row.taskId !== taskId) board.historyItems.value = board.historyItems.value.filter((row) => row.taskId !== taskId)
board.addPollingTask(taskId) board.addPollingTask(taskId)
ElMessage.success(isResume ? '已提交继续,等待本机客户端领取' : '已提交原任务重试,等待本机客户端领取') if (changeBrand) {
const pushNote = await pushToClientQueue(nextPayload, '已修改品牌并重试')
ElMessage.success(pushNote ?? '已修改品牌并重试,任务已送入本机队列')
} else {
ElMessage.success(isResume ? '已提交继续,等待本机客户端领取' : '已提交原任务重试,等待本机客户端领取')
}
await refreshBoard().catch((error) => console.error('[jd-publish] 重试后刷新任务失败', error)) await refreshBoard().catch((error) => console.error('[jd-publish] 重试后刷新任务失败', error))
} }
@@ -388,21 +510,20 @@ async function refreshBoard() {
]) ])
} }
const WAIT_FOR_CLIENT = '任务已创建,等待本机客户端领取。请保持客户端在线。' async function pushToClientQueue(payload: Record<string, unknown> | undefined, action = '任务已创建'): Promise<string | null> {
if (!payload) return `${action},等待本机客户端领取。请保持客户端在线。`
async function pushToClientQueue(payload: Record<string, unknown> | undefined): Promise<string | null> {
if (!payload) return WAIT_FOR_CLIENT
const api = getPywebviewApi() const api = getPywebviewApi()
if (!api?.enqueue_json) { if (!api?.enqueue_json) {
return '任务已创建,等待本机客户端领取。请打开本机客户端并登录同一账号。' return `${action},等待本机客户端领取。请打开本机客户端并登录同一账号。`
} }
const result = await api.enqueue_json(payload).catch((error) => { try {
const result = await api.enqueue_json(payload)
if (result?.success) return null
if (result?.error) console.error('[jd-publish] enqueue_json 被拒', result.error)
} catch (error) {
console.error('[jd-publish] 推送本机队列失败', error) console.error('[jd-publish] 推送本机队列失败', error)
return null }
}) return `${action},但未能推送到本机队列。请保持客户端在线,客户端会自动领取。`
if (result?.success) return null
if (result?.error) console.error('[jd-publish] enqueue_json 被拒', result.error)
return '任务已创建,但未能推送到本机队列。请保持客户端在线,客户端会自动领取。'
} }
const isRunning = computed(() => Boolean(board.dashboard.value.pendingTaskCount) || submitting.value) const isRunning = computed(() => Boolean(board.dashboard.value.pendingTaskCount) || submitting.value)
@@ -426,7 +547,12 @@ async function startPublish() {
// (服务端按 owner 校验,选了他人商品当场拒,AC-9)。 // (服务端按 owner 校验,选了他人商品当场拒,AC-9)。
const categoryId = selectedGroupId.value const categoryId = selectedGroupId.value
const productIds = selectedProductIds.value const productIds = selectedProductIds.value
const vo = await createJdPublishTask(categoryId, productIds, priceRule) const brand = targetBrandName.value
if (!await supportsBrandPublishing()) {
errorMessage.value = JD_UPGRADE_NOTICE
return
}
const vo = await createJdPublishTask(categoryId, productIds, priceRule, brand)
board.addPollingTask(vo.taskId) board.addPollingTask(vo.taskId)
const pushNote = await pushToClientQueue(vo.queuePayload) const pushNote = await pushToClientQueue(vo.queuePayload)
successMessage.value = pushNote successMessage.value = pushNote
@@ -542,6 +668,14 @@ onUnmounted(() => {
<p class="category-hint">{{ priceRuleHint }}</p> <p class="category-hint">{{ priceRuleHint }}</p>
</div> </div>
<div class="category-block">
<label class="category-label" for="jd-publish-target-brand">目标品牌名称(必填)</label>
<input id="jd-publish-target-brand" v-model="targetBrandInput" class="target-brand-input" type="text"
required :aria-invalid="Boolean(targetBrandInput && !isValidBrand(targetBrandName))"
aria-describedby="jd-publish-brand-hint" placeholder="输入当前京麦店铺可用的品牌名称" />
<p id="jd-publish-brand-hint" class="category-hint">本次选中的商品统一使用此品牌,不会修改京东数据库中的原品牌。</p>
</div>
<button class="collect-btn" type="button" :disabled="submitDisabled" @click="startPublish"> <button class="collect-btn" type="button" :disabled="submitDisabled" @click="startPublish">
{{ submitting ? '创建中…' : `上架已选 ${selectedProducts.size} 个商品` }} {{ submitting ? '创建中…' : `上架已选 ${selectedProducts.size} 个商品` }}
</button> </button>
@@ -630,6 +764,8 @@ onUnmounted(() => {
.product-pager { margin-top: 8px; justify-content: center; } .product-pager { margin-top: 8px; justify-content: center; }
.product-pager :deep(.el-pager li), .product-pager :deep(.btn-prev), .product-pager :deep(.btn-next) { background: transparent; color: #c8d2e2; } .product-pager :deep(.el-pager li), .product-pager :deep(.btn-prev), .product-pager :deep(.btn-next) { background: transparent; color: #c8d2e2; }
.product-pager :deep(.el-pager li.is-active) { color: #6ea8ff; } .product-pager :deep(.el-pager li.is-active) { color: #6ea8ff; }
.target-brand-input { box-sizing: border-box; width: 100%; padding: 8px 10px; border: 1px solid #3e4a62; border-radius: 6px; background: #232b3d; color: #c8d2e2; font: inherit; }
.target-brand-input[aria-invalid="true"] { border-color: #fca5a5; }
.price-input { width: 100%; margin-top: 8px; } .price-input { width: 100%; margin-top: 8px; }
.price-input :deep(.el-input__wrapper) { background-color: #232b3d; box-shadow: 0 0 0 1px #3e4a62 inset; } .price-input :deep(.el-input__wrapper) { background-color: #232b3d; box-shadow: 0 0 0 1px #3e4a62 inset; }
.price-input :deep(.el-input__inner) { color: #c8d2e2; } .price-input :deep(.el-input__inner) { color: #c8d2e2; }
+4 -1
View File
@@ -228,8 +228,11 @@ export const API_ENDPOINTS = {
}, },
/** 京东商品上架:用户端建单/选品/面板;派发载荷由服务端下发,认领只由客户端和后端完成。 */ /** 京东商品上架:用户端建单/选品/面板;派发载荷由服务端下发,认领只由客户端和后端完成。 */
jdPublish: { jdPublish: {
/** 建单(请求体 categoryId+productIds+priceRule,响应带 queuePayload 页面直推) */ /** 后端兼容建单入口;新版页面用独占路径,避免旧后端忽略品牌参数。 */
create: '/api/jd-publish/tasks', create: '/api/jd-publish/tasks',
createWithTargetBrand: '/api/jd-publish/tasks/target-brand',
/** 修改目标品牌后原位重试;沿用建单回执以直推本机队列。 */
retryBrand: '/api/jd-publish/tasks/{taskId}/retry-brand',
/** 用户端选品分页(AC-9 owner 过滤:只回归属当前用户的京东数据库商品行) */ /** 用户端选品分页(AC-9 owner 过滤:只回归属当前用户的京东数据库商品行) */
products: '/api/jd-publish/products', products: '/api/jd-publish/products',
/** 任务面板总览(运行中/成功/失败计数统计卡) */ /** 任务面板总览(运行中/成功/失败计数统计卡) */
@@ -39,19 +39,28 @@ export function createJdPublishTask(
categoryId: number | null, categoryId: number | null,
productIds: number[], productIds: number[],
priceRule: JdPublishPriceRule, priceRule: JdPublishPriceRule,
targetBrandName: string,
) { ) {
return unwrapJavaResponse(post<JavaApiResponse<JdPublishTaskVo>, Record<string, unknown>>( return unwrapJavaResponse(post<JavaApiResponse<JdPublishTaskVo>, Record<string, unknown>>(
buildJavaUrl(API_ENDPOINTS.jdPublish.create), buildJavaUrl(API_ENDPOINTS.jdPublish.createWithTargetBrand),
{ {
userId: getCurrentUserId(), userId: getCurrentUserId(),
categoryId, categoryId,
productIds, productIds,
// mode=none 时不带 value(后端 normalizePriceRule 对 none 忽略 value) // mode=none 时不带 value(后端 normalizePriceRule 对 none 忽略 value)
priceRule: priceRule.mode === 'none' ? { mode: 'none' } : priceRule, priceRule: priceRule.mode === 'none' ? { mode: 'none' } : priceRule,
targetBrandName,
}, },
)) ))
} }
export function retryJdPublishBrand(taskId: number, targetBrandName: string, resumeAttempt: number) {
return unwrapJavaResponse(post<JavaApiResponse<JdPublishTaskVo>, { targetBrandName: string; resumeAttempt: number }>(
buildJavaUrl(API_ENDPOINTS.jdPublish.retryBrand.replace('{taskId}', String(taskId))),
{ targetBrandName, resumeAttempt },
))
}
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
// 选品分页(AC-9 owner 过滤):服务端只回归属当前用户的京东数据库商品行。 // 选品分页(AC-9 owner 过滤):服务端只回归属当前用户的京东数据库商品行。
// 形状照后管京东数据库列表行裁剪(选品面板只需要主字段,attr/detail 不下发)。 // 形状照后管京东数据库列表行裁剪(选品面板只需要主字段,attr/detail 不下发)。
@@ -201,6 +201,8 @@ export interface PywebviewApi {
error?: string; error?: string;
alreadyRunning?: boolean; alreadyRunning?: boolean;
}>; }>;
/** 京东发布独立协议:品牌单仅允许明确支持该协议的客户端创建或修改品牌重试。 */
jd_publish_protocol?: () => Promise<number>;
enqueue_json?: ( enqueue_json?: (
data: unknown, data: unknown,
) => Promise<{ success: boolean; queue_size?: number; error?: string; code?: string }>; ) => Promise<{ success: boolean; queue_size?: number; error?: string; code?: string }>;
+2
View File
@@ -342,6 +342,8 @@ test('test_endpoints_frozen_snapshot', () => {
// 京东商品上架:网页建单后只原样投递 queuePayload,客户端与后端负责认领。 // 京东商品上架:网页建单后只原样投递 queuePayload,客户端与后端负责认领。
"jdPublish": { "jdPublish": {
"create": "/api/jd-publish/tasks", "create": "/api/jd-publish/tasks",
"createWithTargetBrand": "/api/jd-publish/tasks/target-brand",
"retryBrand": "/api/jd-publish/tasks/{taskId}/retry-brand",
"products": "/api/jd-publish/products", "products": "/api/jd-publish/products",
"dashboard": "/api/jd-publish/dashboard", "dashboard": "/api/jd-publish/dashboard",
"history": "/api/jd-publish/history", "history": "/api/jd-publish/history",
@@ -10,11 +10,13 @@ import {
const api = vi.hoisted(() => ({ const api = vi.hoisted(() => ({
create: vi.fn(), activate: vi.fn(), products: vi.fn(), groups: vi.fn(), create: vi.fn(), activate: vi.fn(), products: vi.fn(), groups: vi.fn(),
history: vi.fn(), progress: vi.fn(), dashboard: vi.fn(), retry: vi.fn(), enqueue: vi.fn(), bridge: vi.fn(), history: vi.fn(), progress: vi.fn(), dashboard: vi.fn(), retry: vi.fn(), enqueue: vi.fn(), bridge: vi.fn(),
protocol: vi.fn(), retryBrand: vi.fn(), alert: vi.fn(), prompt: vi.fn(),
})) }))
vi.mock('@/shared/api/types/modules/jd-collect', () => ({ fetchJdCollectGroups: api.groups })) vi.mock('@/shared/api/types/modules/jd-collect', () => ({ fetchJdCollectGroups: api.groups }))
vi.mock('@/shared/api/types/modules/jd-publish', () => ({ vi.mock('@/shared/api/types/modules/jd-publish', () => ({
createJdPublishTask: api.create, createJdPublishTask: api.create,
retryJdPublishBrand: api.retryBrand,
activateJdPublishTask: api.activate, activateJdPublishTask: api.activate,
fetchJdPublishDashboard: api.dashboard, fetchJdPublishDashboard: api.dashboard,
fetchJdPublishHistory: api.history, fetchJdPublishHistory: api.history,
@@ -29,15 +31,18 @@ vi.mock('@/shared/utils/categorized-timers.ts', () => ({
vi.mock('element-plus', async (importOriginal) => ({ vi.mock('element-plus', async (importOriginal) => ({
...await importOriginal<typeof import('element-plus')>(), ...await importOriginal<typeof import('element-plus')>(),
ElMessage: { success: vi.fn(), error: vi.fn() }, ElMessage: { success: vi.fn(), error: vi.fn() },
ElMessageBox: { alert: api.alert, prompt: api.prompt },
})) }))
vi.mock('@/shared/api/task-retry', () => ({ retryClientTask: api.retry })) vi.mock('@/shared/api/task-retry', () => ({ retryClientTask: api.retry }))
vi.mock('@/shared/bridges/pywebview', () => ({ getPywebviewApi: api.bridge })) vi.mock('@/shared/bridges/pywebview', () => ({ getPywebviewApi: api.bridge }))
const queuePayload = { type: 'jd-product-publish-run', data: { taskId: 88, resumeAttempt: 0, serverOnly: true } } const queuePayload = { type: 'jd-product-publish-run', data: { taskId: 88, resumeAttempt: 0, serverOnly: true } }
const loginError = '京麦未登录(登录态失效),请在客户端重新登录京麦后重试' const loginError = '京麦未登录(登录态失效),请在客户端重新登录京麦后重试'
const brandError = '目标品牌校验失败:商品「蓝牙音箱」的目标品牌「Blue-Sound」在京麦不可选(JD_BRAND_UNAVAILABLE)'
const sourceError = '本店源商品校验失败:当前店铺找不到源商品「蓝牙音箱」,编码 SKU_12345(JD_SOURCE_NOT_FOUND)'
function row(taskStatus: string, resumeAttempt: number, errorMessage?: string) { function row(taskStatus: string, resumeAttempt: number, errorMessage?: string) {
return { taskId: 88, taskStatus, resumeAttempt, productTotal: 2, errorMessage } return { taskId: 88, taskStatus, resumeAttempt, productTotal: 2, successCount: 0, publishingCount: 0, errorMessage }
} }
function batch(item: ReturnType<typeof row>) { function batch(item: ReturnType<typeof row>) {
@@ -67,7 +72,8 @@ async function mountPage() {
return wrapper return wrapper
} }
async function startPublish(page: VueWrapper) { async function startPublish(page: VueWrapper, brand = ' 示例品牌 ') {
await page.get('.target-brand-input').setValue(brand)
await page.get<HTMLInputElement>('.product-check').setValue(true) await page.get<HTMLInputElement>('.product-check').setValue(true)
await page.get('.collect-btn').trigger('click') await page.get('.collect-btn').trigger('click')
await flushPromises() await flushPromises()
@@ -82,7 +88,9 @@ beforeEach(() => {
api.dashboard.mockResolvedValue({ pendingTaskCount: 0, processedTaskCount: 0, successTaskCount: 0, failedTaskCount: 0 }) api.dashboard.mockResolvedValue({ pendingTaskCount: 0, processedTaskCount: 0, successTaskCount: 0, failedTaskCount: 0 })
api.history.mockResolvedValue({ items: [] }) api.history.mockResolvedValue({ items: [] })
api.progress.mockResolvedValue(batch(row('PENDING', 0))) api.progress.mockResolvedValue(batch(row('PENDING', 0)))
api.bridge.mockReturnValue({ enqueue_json: api.enqueue }) api.bridge.mockReturnValue({ jd_publish_protocol: api.protocol, enqueue_json: api.enqueue })
api.protocol.mockResolvedValue(3)
api.alert.mockResolvedValue(undefined)
api.enqueue.mockResolvedValue({ success: true }) api.enqueue.mockResolvedValue({ success: true })
api.retry.mockResolvedValue(null) api.retry.mockResolvedValue(null)
vi.spyOn(console, 'error').mockImplementation(() => undefined) vi.spyOn(console, 'error').mockImplementation(() => undefined)
@@ -99,21 +107,44 @@ afterEach(() => {
it('建单只原样投递服务端载荷,网页不激活任务', async () => { it('建单只原样投递服务端载荷,网页不激活任务', async () => {
const page = await mountPage() const page = await mountPage()
await startPublish(page) await startPublish(page)
expect(api.create).toHaveBeenCalledOnce() expect(page.get('#jd-publish-brand-hint').text()).toContain('本次选中的商品统一使用此品牌,不会修改京东数据库')
expect(api.protocol).toHaveBeenCalled()
expect(api.create).toHaveBeenCalledExactlyOnceWith(12, [23], { mode: 'none' }, '示例品牌')
expect(api.enqueue).toHaveBeenCalledOnce() expect(api.enqueue).toHaveBeenCalledOnce()
expect(api.enqueue.mock.calls[0][0]).toBe(queuePayload) expect(api.enqueue.mock.calls[0][0]).toBe(queuePayload)
expect(api.activate).not.toHaveBeenCalled() expect(api.activate).not.toHaveBeenCalled()
}) })
it.each(['没有桥', '队列拒绝', '桥异常', '没有服务端载荷'])('%s时保留待认领,不拼载荷也不误报建单失败', async (failure) => { it.each(['没有桥', '旧桥', '旧协议', '字符串协议', '未知协议', '协议异常'])('%s不允许建品牌单', async (failure) => {
if (failure === '没有桥') api.bridge.mockReturnValue(undefined) if (failure === '没有桥') api.bridge.mockReturnValue(undefined)
if (failure === '旧桥') api.bridge.mockReturnValue({ enqueue_json: api.enqueue })
if (failure === '旧协议') api.protocol.mockResolvedValue(2)
if (failure === '字符串协议') api.protocol.mockResolvedValue('3')
if (failure === '未知协议') api.protocol.mockResolvedValue(4)
if (failure === '协议异常') api.protocol.mockRejectedValue(new Error('bridge unavailable'))
const page = await mountPage()
await startPublish(page)
expect(api.create).not.toHaveBeenCalled()
expect(api.enqueue).not.toHaveBeenCalled()
expect(page.text()).toContain('升级')
})
it.each([' ', '品'.repeat(121)])('目标品牌名空白或超长时不建单', async (brand) => {
const page = await mountPage()
await startPublish(page, brand)
expect(page.get<HTMLButtonElement>('.collect-btn').element.disabled).toBe(true)
expect(api.create).not.toHaveBeenCalled()
})
it.each(['没有入队方法', '队列拒绝', '桥异常', '没有服务端载荷'])('%s时保留待认领,不拼载荷也不误报建单失败', async (failure) => {
if (failure === '没有入队方法') api.bridge.mockReturnValue({ jd_publish_protocol: api.protocol })
if (failure === '队列拒绝') api.enqueue.mockResolvedValue({ success: false, error: 'queue rejected' }) if (failure === '队列拒绝') api.enqueue.mockResolvedValue({ success: false, error: 'queue rejected' })
if (failure === '桥异常') api.enqueue.mockRejectedValue(new Error('bridge unavailable')) if (failure === '桥异常') api.enqueue.mockRejectedValue(new Error('bridge unavailable'))
if (failure === '没有服务端载荷') api.create.mockResolvedValue({ taskId: 88 }) if (failure === '没有服务端载荷') api.create.mockResolvedValue({ taskId: 88 })
const page = await mountPage() const page = await mountPage()
await startPublish(page) await startPublish(page)
expect(api.activate).not.toHaveBeenCalled() expect(api.activate).not.toHaveBeenCalled()
if (failure === '没有桥' || failure === '没有服务端载荷') expect(api.enqueue).not.toHaveBeenCalled() if (failure === '没有入队方法' || failure === '没有服务端载荷') expect(api.enqueue).not.toHaveBeenCalled()
expect(page.get('.feedback').text()).toContain('任务已创建') expect(page.get('.feedback').text()).toContain('任务已创建')
expect(page.get('.feedback').text()).toContain('客户端') expect(page.get('.feedback').text()).toContain('客户端')
expect(page.get('.status').text()).toContain('等待本机客户端领取') expect(page.get('.status').text()).toContain('等待本机客户端领取')
@@ -134,7 +165,7 @@ it('切换分类后迟到的旧商品列表不能再参与勾选', async () => {
await flushPromises() await flushPromises()
expect(page.get('.product-title').text()).toBe('新分类商品') expect(page.get('.product-title').text()).toBe('新分类商品')
await startPublish(page) await startPublish(page)
expect(api.create).toHaveBeenCalledExactlyOnceWith(13, [24], { mode: 'none' }) expect(api.create).toHaveBeenCalledExactlyOnceWith(13, [24], { mode: 'none' }, '示例品牌')
}) })
it('全选和取消只影响本页,其他页勾选保留', async () => { it('全选和取消只影响本页,其他页勾选保留', async () => {
@@ -147,9 +178,10 @@ it('全选和取消只影响本页,其他页勾选保留', async () => {
await page.get('.product-select-page').setValue(true) await page.get('.product-select-page').setValue(true)
expect(page.get('.collect-btn').text()).toContain('2 个商品') expect(page.get('.collect-btn').text()).toContain('2 个商品')
await page.get('.product-select-page').setValue(false) await page.get('.product-select-page').setValue(false)
await page.get('.target-brand-input').setValue('示例品牌')
await page.get('.collect-btn').trigger('click') await page.get('.collect-btn').trigger('click')
await flushPromises() await flushPromises()
expect(api.create).toHaveBeenCalledExactlyOnceWith(12, [23], { mode: 'none' }) expect(api.create).toHaveBeenCalledExactlyOnceWith(12, [23], { mode: 'none' }, '示例品牌')
}) })
it('原位重试只由兜底认领,迟到的旧代终态不能停掉轮询或弹窗', async () => { it('原位重试只由兜底认领,迟到的旧代终态不能停掉轮询或弹窗', async () => {
@@ -189,3 +221,88 @@ it('原位重试只由兜底认领,迟到的旧代终态不能停掉轮询或
expect(takeCredentialFatal()?.notice.body).toContain('请在客户端重新登录京麦') expect(takeCredentialFatal()?.notice.body).toContain('请在客户端重新登录京麦')
expect(localStorage.getItem('jd-publish:tasks:0')).toBeNull() expect(localStorage.getItem('jd-publish:tasks:0')).toBeNull()
}) })
it('轮询只凭任务头识别失败,历史和重复轮询不重弹,新代可再弹', async () => {
localStorage.setItem('jd-publish:tasks:0', '[88]')
api.history.mockResolvedValue({ items: [row('RUNNING', 3)] })
const progress = batch(row('FAILED', 3, brandError))
progress.items[0].items[0].errorMessage = undefined
api.progress.mockResolvedValue(progress)
const page = await mountPage()
expect(api.alert).toHaveBeenCalledTimes(1)
expect(api.alert.mock.calls[0].join(' ')).toContain('商品「蓝牙音箱」的目标品牌「Blue-Sound」在京麦不可选')
expect(api.alert.mock.calls[0].join(' ')).not.toContain('JD_BRAND_UNAVAILABLE')
await page.get('.history-btn').trigger('click')
expect(page.get('.btn-retry').text()).toBe('修改品牌并重试')
expect(page.text()).toContain('商品「蓝牙音箱」的目标品牌「Blue-Sound」在京麦不可选')
expect(page.text()).not.toContain('JD_BRAND_UNAVAILABLE')
api.history.mockResolvedValue({ items: [row('FAILED', 3, brandError)] })
await page.get('.panel-refresh').trigger('click')
await flushPromises()
expect(api.alert).toHaveBeenCalledTimes(1)
api.history.mockResolvedValue({ items: [row('FAILED', 4, brandError)] })
await page.get('.panel-refresh').trigger('click')
await flushPromises()
expect(api.alert).toHaveBeenCalledTimes(2)
})
it('修改品牌走专用原位重试,原样投递新载荷并拒绝旧代进度', async () => {
api.history.mockResolvedValue({ items: [row('FAILED', 3, brandError)] })
api.progress.mockResolvedValue(batch(row('FAILED', 3, brandError)))
api.prompt.mockResolvedValue({ value: ' 新品牌 ' })
const retryPayload = { ...queuePayload, data: { taskId: 88, resumeAttempt: 4, serverOnly: true } }
api.retryBrand.mockResolvedValue({ taskId: 88, queuePayload: retryPayload })
const page = await mountPage()
await page.get('.history-btn').trigger('click')
await page.get('.btn-retry').trigger('click')
await flushPromises()
expect(api.prompt).toHaveBeenCalledOnce()
expect(api.retryBrand).toHaveBeenCalledExactlyOnceWith(88, '新品牌', 3)
expect(api.enqueue.mock.calls[0][0]).toBe(retryPayload)
expect(api.retry).not.toHaveBeenCalled()
expect(api.create).not.toHaveBeenCalled()
expect(api.alert).toHaveBeenCalledTimes(1)
expect(localStorage.getItem('jd-publish:tasks:0')).toBe('[88]')
})
it('旧桥不允许修改品牌并重试', async () => {
api.bridge.mockReturnValue({ enqueue_json: api.enqueue })
api.history.mockResolvedValue({ items: [row('FAILED', 0, brandError)] })
const page = await mountPage()
await page.get('.history-btn').trigger('click')
await page.get('.btn-retry').trigger('click')
await flushPromises()
expect(api.prompt).not.toHaveBeenCalled()
expect(api.retryBrand).not.toHaveBeenCalled()
expect(api.retry).not.toHaveBeenCalled()
})
it.each([{ successCount: 1 }, { publishingCount: 1 }])('已有成功或待确认时禁止品牌重试:%o', async (counts) => {
api.history.mockResolvedValue({ items: [{ ...row('FAILED', 3, brandError), ...counts }] })
const page = await mountPage()
await page.get('.history-btn').trigger('click')
expect(page.find('.btn-retry').exists()).toBe(false)
expect(page.text()).toContain('核对京麦')
expect(page.text()).toContain('未发布商品')
expect(page.text()).not.toContain('JD_BRAND_UNAVAILABLE')
})
it('源商品失败提示换店或重选,并保留普通原位重试', async () => {
api.history.mockResolvedValue({ items: [row('FAILED', 0, sourceError)] })
const page = await mountPage()
await page.get('.history-btn').trigger('click')
expect(page.text()).toContain('正确店铺')
expect(page.text()).toContain('重新选择')
expect(page.text()).toContain('当前店铺找不到源商品「蓝牙音箱」,编码 SKU_12345')
expect(page.text()).not.toContain('JD_SOURCE_NOT_FOUND')
expect(api.alert).toHaveBeenCalledOnce()
expect(api.alert.mock.calls[0].join(' ')).toContain('当前店铺找不到源商品「蓝牙音箱」,编码 SKU_12345')
expect(api.alert.mock.calls[0].join(' ')).not.toContain('JD_SOURCE_NOT_FOUND')
expect(page.get('.btn-retry').text()).toBe('重试')
await page.get('.btn-retry').trigger('click')
await flushPromises()
expect(api.retry).toHaveBeenCalledExactlyOnceWith(88)
expect(api.retryBrand).not.toHaveBeenCalled()
})