fix(phase-5): v1.5 CR 消项 JD-PUB-01~07 服务端半边(蓝图 docs/ITERATION_PLAN.md Phase 5)——①JD-PUB-01 发布端点收有效用户会话+任务归属闸(AdminAuthSupport 身份源收口,outlet 分母随行,RequestSuppliedIdentityOutletTest +1);②JD-PUB-02 建单/原位重试补事务边界防半截状态;③JD-PUB-03 回传校验执行代次与许可批次(V213__jd_publish_item_permit 两列 nullable 扩展,Expand-and-Contract;旧代不写新代、重复回执幂等、未处理明细不产 SUCCESS);④JD-PUB-04 入队不再等于认领(激活与桌面推送顺序,兜底保留);⑤JD-PUB-05 未知提交不自动重发;⑥JD-PUB-06 旧代终态不触发新代收尾或弹窗(credential-fatal 旧代隔离+京麦登录失效识别);⑦JD-PUB-07 选品切分类丢弃迟到响应、全选只影响本页;新增 mount 测试 jd-publish-dispatch。判据:后端点名 11 类 88 例+整量 mvn -o test 5,716 例 0 失败 0 错误 19 skip BUILD SUCCESS(00:07,7:12min);用户端 vue-tsc rc0+node --test 31+vitest mount 8 全绿;full 闸门 overall=pass 四面绿(2026-11-18 23:59:16);真机 AC-1~AC-9 联验与发版未做,Phase 5 保持未勾
This commit is contained in:
@@ -315,6 +315,18 @@ public class AdminAuthSupport {
|
||||
return bindOwnershipUserId(requireUserOrInternal(request), requestedUserId);
|
||||
}
|
||||
|
||||
/** 用户自助接口:只接受真实会话,不允许内部令牌或管理角色代用户。 */
|
||||
public Long requireSessionOwnerUserId(HttpServletRequest request, Long requestedUserId) {
|
||||
Long userId = requireUser(request).getId();
|
||||
if (userId == null || userId <= 0) {
|
||||
throw new BusinessException(401, "登录身份无效");
|
||||
}
|
||||
if (requestedUserId != null && !userId.equals(requestedUserId)) {
|
||||
throw new BusinessException(403, "请求用户与登录用户不一致");
|
||||
}
|
||||
return userId;
|
||||
}
|
||||
|
||||
private Long bindOwnershipUserId(AdminUserEntity identity, Long requestedUserId) {
|
||||
if (mayActForOtherUsers(identity)) {
|
||||
return requestedUserId;
|
||||
|
||||
@@ -118,13 +118,8 @@ public class ApiGuardCoverageAuditor implements SmartInitializingSingleton {
|
||||
* requireOwnershipUserId(fail-closed 401),chunk 与 heartbeat 和 collect-data/delete-brand
|
||||
* 同形状(本机桌面执行器不带凭据,行归属以任务 owner 投影);chunk 的 error 上报已接整单
|
||||
* 判死,其 owner 对撞收口随 v1.4 Phase 6.1 落,判死口凭据化后随统一批进名单</li>
|
||||
* <li>{@code /api/jd-publish} —— v1.5 京东商品上架任务面(建单/products/activate/items/progress/
|
||||
* dashboard/history/progress-batch/delete/chunk/heartbeat):与 /api/jd-collect 逐形状同族——建单等
|
||||
* 写类端点方法体已有 requireOwnershipUserId
|
||||
* (fail-closed 401,B98-07 同形债预防),products/dashboard/history/delete 走 resolveOwnershipUserId
|
||||
* (Phase 4 面板读侧),progressBatch 走 require+filterOwnedTaskIds,chunk 判死口凭据化
|
||||
* (isTrustedInternalToken,匿名一律拒绝判死),行级落库与 jd-collect 同形状(本机桌面执行器不带凭据,
|
||||
* 行归属以任务 owner 投影);判死口凭据化后随统一批进名单</li>
|
||||
* <li>{@code /api/jd-publish} —— 所有入口在控制器绑定真实会话;执行器沿用桌面 JWT,
|
||||
* 单独内部令牌不授权。回传再在事务内校验归属、代次与发布许可。</li>
|
||||
* </ul>
|
||||
*/
|
||||
static final Set<String> PENDING_CONVERGENCE = Set.of(
|
||||
|
||||
+18
-30
@@ -67,23 +67,18 @@ public class JdPublishController {
|
||||
public ApiResponse<JdPublishTaskVo> createTask(@Valid @RequestBody JdPublishTaskCreateRequest request,
|
||||
HttpServletRequest httpRequest) {
|
||||
// uid 不由请求体说了算:解析不出会话身份就 401(fail-closed,与采集建单同口径)。
|
||||
request.setUserId(adminAuthSupport.requireOwnershipUserId(httpRequest, request.getUserId()));
|
||||
request.setUserId(adminAuthSupport.requireSessionOwnerUserId(httpRequest, request.getUserId()));
|
||||
return ApiResponse.success(publishTaskService.createTask(request,
|
||||
adminAuthSupport.currentDeviceId(httpRequest)));
|
||||
}
|
||||
|
||||
@PostMapping("/tasks/{taskId}/activate")
|
||||
@Operation(summary = "激活京东上架任务", description = "页面把 jd-product-publish-run 载荷推给本机客户端前调用:"
|
||||
+ "PENDING→RUNNING 条件更新。漏掉这一步,客户端第一个回传会被「任务不在运行中(PENDING)」拒收"
|
||||
+ "(2026-11-14 采集链真机实录同形)。")
|
||||
public ApiResponse<Void> activate(
|
||||
@Parameter(description = "任务 ID", required = true, example = "34400")
|
||||
@PathVariable Long taskId,
|
||||
@Parameter(description = "任务所属用户 ID;省略时取当前登录身份", required = false, example = "1")
|
||||
@Operation(summary = "认领当前代次的京东上架任务")
|
||||
public ApiResponse<Void> activate(@PathVariable Long taskId,
|
||||
@RequestParam("resumeAttempt") int resumeAttempt,
|
||||
@RequestParam(value = "user_id", required = false) Long userId,
|
||||
HttpServletRequest httpRequest) {
|
||||
publishTaskService.activateTask(taskId,
|
||||
adminAuthSupport.requireOwnershipUserId(httpRequest, userId));
|
||||
publishTaskService.activateTask(taskId, adminAuthSupport.requireSessionOwnerUserId(httpRequest, userId), resumeAttempt);
|
||||
return ApiResponse.success(null);
|
||||
}
|
||||
|
||||
@@ -100,9 +95,10 @@ public class JdPublishController {
|
||||
@RequestParam(value = "limit", required = false) Integer limit,
|
||||
@Parameter(description = "任务所属用户 ID;省略时取当前登录身份", required = false, example = "1")
|
||||
@RequestParam(value = "user_id", required = false) Long userId,
|
||||
@RequestParam("resumeAttempt") int resumeAttempt,
|
||||
HttpServletRequest httpRequest) {
|
||||
return ApiResponse.success(publishTaskService.pullItems(taskId,
|
||||
adminAuthSupport.requireOwnershipUserId(httpRequest, userId), cursor, limit));
|
||||
adminAuthSupport.requireSessionOwnerUserId(httpRequest, userId), resumeAttempt, cursor, limit));
|
||||
}
|
||||
|
||||
@GetMapping("/tasks/{taskId}/progress")
|
||||
@@ -115,22 +111,14 @@ public class JdPublishController {
|
||||
@RequestParam(value = "user_id", required = false) Long userId,
|
||||
HttpServletRequest httpRequest) {
|
||||
return ApiResponse.success(publishTaskService.queryProgress(taskId,
|
||||
adminAuthSupport.requireOwnershipUserId(httpRequest, userId)));
|
||||
adminAuthSupport.requireSessionOwnerUserId(httpRequest, userId)));
|
||||
}
|
||||
|
||||
@PostMapping("/tasks/{taskId}/chunk")
|
||||
@Operation(summary = "提交行级发布结果回传", description = "执行器按批次回传行级状态(PUBLISHING/SUCCESS/FAILED"
|
||||
+ " +真实失败原因 + wareId);isEnd=true 任务按行级状态汇总落终态。error 字段按铁律 31 分档"
|
||||
+ "(京麦登录态失效整单 FAILED;非致命只记录)——判定只信 X-Internal-Token,匿名一律拒绝判死。")
|
||||
public ApiResponse<JdPublishChunkVo> submitChunk(
|
||||
@Parameter(description = "任务 ID", required = true, example = "34400")
|
||||
@PathVariable Long taskId,
|
||||
@RequestBody JdPublishChunkRequest request,
|
||||
HttpServletRequest httpRequest) {
|
||||
// 判死口凭据化(JdCollectController.submitChunk 同口径):error 上报是唯一能触发整单
|
||||
// 判死的入口,匿名一律拒绝判死;行级结果落库不要求内部令牌(采集端按任务拉单)。
|
||||
boolean trustedErrorReporter = adminAuthSupport.isTrustedInternalToken(httpRequest);
|
||||
return ApiResponse.success(ingestService.submitChunk(taskId, request, trustedErrorReporter));
|
||||
@Operation(summary = "申请发布许可或提交京麦发布回执")
|
||||
public ApiResponse<JdPublishChunkVo> submitChunk(@PathVariable Long taskId,
|
||||
@Valid @RequestBody JdPublishChunkRequest request, HttpServletRequest httpRequest) {
|
||||
return ApiResponse.success(ingestService.submitChunk(taskId, request, adminAuthSupport.requireSessionOwnerUserId(httpRequest, null)));
|
||||
}
|
||||
|
||||
@PostMapping("/tasks/{taskId}/heartbeat")
|
||||
@@ -145,7 +133,7 @@ public class JdPublishController {
|
||||
@RequestBody(required = false) TaskHeartbeatRequest request,
|
||||
HttpServletRequest httpRequest) {
|
||||
return ApiResponse.success(publishTaskService.heartbeat(taskId,
|
||||
adminAuthSupport.requireOwnershipUserId(httpRequest, userId), request));
|
||||
adminAuthSupport.requireSessionOwnerUserId(httpRequest, userId), request));
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------
|
||||
@@ -167,7 +155,7 @@ public class JdPublishController {
|
||||
@Parameter(description = "当前用户 ID;省略时取当前登录身份", required = false)
|
||||
@RequestParam(value = "user_id", required = false) Long userId,
|
||||
HttpServletRequest httpRequest) {
|
||||
userId = adminAuthSupport.resolveOwnershipUserId(httpRequest, userId);
|
||||
userId = adminAuthSupport.requireSessionOwnerUserId(httpRequest, userId);
|
||||
return ApiResponse.success(jdProductQueryService.pageForUser(userId, categoryId, page, pageSize));
|
||||
}
|
||||
|
||||
@@ -178,7 +166,7 @@ public class JdPublishController {
|
||||
@Parameter(description = "当前用户 ID", required = true, example = "1")
|
||||
@RequestParam("user_id") Long userId,
|
||||
HttpServletRequest httpRequest) {
|
||||
userId = adminAuthSupport.resolveOwnershipUserId(httpRequest, userId);
|
||||
userId = adminAuthSupport.requireSessionOwnerUserId(httpRequest, userId);
|
||||
return ApiResponse.success(boardService.dashboard(userId));
|
||||
}
|
||||
|
||||
@@ -191,7 +179,7 @@ public class JdPublishController {
|
||||
@Parameter(description = "历史记录条数,默认 50,最大 100", example = "50")
|
||||
@RequestParam(value = "limit", required = false, defaultValue = PageDefaults.DEFAULT_RESULT_LIMIT) Integer limit,
|
||||
HttpServletRequest httpRequest) {
|
||||
userId = adminAuthSupport.resolveOwnershipUserId(httpRequest, userId);
|
||||
userId = adminAuthSupport.requireSessionOwnerUserId(httpRequest, userId);
|
||||
return ApiResponse.success(boardService.history(userId, limit));
|
||||
}
|
||||
|
||||
@@ -202,7 +190,7 @@ public class JdPublishController {
|
||||
HttpServletRequest httpRequest) {
|
||||
return ApiResponse.success(boardService.progressBatch(progressOwnershipSupport
|
||||
.filterOwnedTaskIds(request.getTaskIds(),
|
||||
adminAuthSupport.requireOwnershipUserId(httpRequest, request.getUserId()))));
|
||||
adminAuthSupport.requireSessionOwnerUserId(httpRequest, request.getUserId()))));
|
||||
}
|
||||
|
||||
@DeleteMapping("/tasks/{taskId}")
|
||||
@@ -214,7 +202,7 @@ public class JdPublishController {
|
||||
@Parameter(description = "当前用户 ID,必须与创建任务的用户一致", required = true, example = "1")
|
||||
@RequestParam("user_id") Long userId,
|
||||
HttpServletRequest httpRequest) {
|
||||
userId = adminAuthSupport.resolveOwnershipUserId(httpRequest, userId);
|
||||
userId = adminAuthSupport.requireSessionOwnerUserId(httpRequest, userId);
|
||||
boardService.deleteTask(taskId, userId);
|
||||
return ApiResponse.success(null);
|
||||
}
|
||||
|
||||
+10
-8
@@ -1,6 +1,9 @@
|
||||
package com.nanri.aiimage.modules.jd.model.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.PositiveOrZero;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
@@ -8,21 +11,20 @@ import java.util.List;
|
||||
/**
|
||||
* 京东发布行级回传请求(v1.5 蓝图 §3:POST /api/jd-publish/tasks/{taskId}/chunk)。
|
||||
*
|
||||
* <p>顶层键集 {@code batchId / items / isEnd}(外加 {@code error} 失败上报);行内键集
|
||||
* {@code itemId / productId / publishStatus / publishError / jdWareId}。行状态是唯一
|
||||
* 行级真源({@code biz_jd_publish_item.publish_status});{@code error} 按铁律 31 分档
|
||||
* (京麦登录态失效→整单 FAILED,代理/LLM 凭据致命词→{@code CredentialFatalClassifier},
|
||||
* 其余技术性故障只记录不判死)——判定只信 X-Internal-Token(匿名 error 一律拒绝判死,
|
||||
* 照 JdCollectController.submitChunk 同口径)。</p>
|
||||
* <p>发布许可属于当前 {@code resumeAttempt} 和本执行者 {@code batchId};成功/失败回执沿用该批次。</p>
|
||||
*/
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class JdPublishChunkRequest {
|
||||
|
||||
/** 批次号(客户端生成,溯源用)。 */
|
||||
@NotNull
|
||||
@PositiveOrZero
|
||||
private Integer resumeAttempt;
|
||||
|
||||
/** Stable execution identity, not a per-request identifier. */
|
||||
private String batchId;
|
||||
|
||||
/** 本批行级结果。 */
|
||||
@Size(max = 500)
|
||||
private List<ItemResult> items;
|
||||
|
||||
/** true=本任务全部行已回传,任务按行级状态汇总落终态。 */
|
||||
|
||||
+4
-2
@@ -13,8 +13,8 @@ import java.time.LocalDateTime;
|
||||
* <p>每任务每商品一行(唯一键 {@code uk_task_product}):建单即按 {@code biz_jd_product}
|
||||
* 快照落行(商品库有 ageCleanup 清理语义,发布记录不随商品删除丢失溯源);行级状态机
|
||||
* {@code PENDING → PUBLISHING → SUCCESS/FAILED} 由客户端 chunk 回传逐行推进——服务端
|
||||
* 不预测发布结果,行状态的唯一写入口是 {@code JdPublishIngestService}(单客户端串行
|
||||
* 回传,无并发竞争)。任务级行为复用 {@code biz_file_task}(module_type=JD_PUBLISH),
|
||||
* 不预测发布结果。回传持任务行锁,发布许可按代次和执行批次绑定。任务级行为复用
|
||||
* {@code biz_file_task}(module_type=JD_PUBLISH),
|
||||
* 本表只承载行级明细与快照。</p>
|
||||
*/
|
||||
@Data
|
||||
@@ -45,6 +45,8 @@ public class JdPublishItemEntity {
|
||||
private String stockJson;
|
||||
/** 行级状态机:PENDING/PUBLISHING/SUCCESS/FAILED(客户端 chunk 回传推进)。 */
|
||||
private String publishStatus;
|
||||
private String publishBatchId;
|
||||
private Integer publishResumeAttempt;
|
||||
/** 行级失败真实原因(客户端回传原文,R6 单行失败隔离)。 */
|
||||
private String publishError;
|
||||
/** 京麦发布成功回执的商品 id(wareId,AC-3 真机核对锚点)。 */
|
||||
|
||||
@@ -13,6 +13,8 @@ public class JdPublishChunkVo {
|
||||
|
||||
/** 该任务剩余未发布(PENDING)行数。 */
|
||||
private long pendingCount;
|
||||
private long publishingCount;
|
||||
private boolean needsReview;
|
||||
|
||||
/** 任务终态状态(isEnd=true 且落了终态时回填;非终态回 null)。 */
|
||||
private String taskStatus;
|
||||
|
||||
+1
@@ -19,6 +19,7 @@ public class JdPublishHistoryItemVo {
|
||||
|
||||
@Schema(description = "任务 ID")
|
||||
private Long taskId;
|
||||
private int resumeAttempt;
|
||||
|
||||
@Schema(description = "任务编号")
|
||||
private String taskNo;
|
||||
|
||||
+1
@@ -15,6 +15,7 @@ import java.util.List;
|
||||
public class JdPublishItemsPageVo {
|
||||
|
||||
private Long taskId;
|
||||
private int resumeAttempt;
|
||||
|
||||
/** 本页明细行。 */
|
||||
private List<JdPublishItemPayloadVo> items;
|
||||
|
||||
+1
@@ -15,6 +15,7 @@ import java.time.LocalDateTime;
|
||||
public class JdPublishProgressVo {
|
||||
|
||||
private Long taskId;
|
||||
private int resumeAttempt;
|
||||
|
||||
/** 任务状态(biz_file_task.status)。 */
|
||||
private String status;
|
||||
|
||||
+1
@@ -10,6 +10,7 @@ public class JdPublishTaskItemVo {
|
||||
|
||||
@Schema(description = "任务 ID")
|
||||
private Long id;
|
||||
private int resumeAttempt;
|
||||
|
||||
@Schema(description = "任务编号")
|
||||
private String taskNo;
|
||||
|
||||
+5
-5
@@ -30,7 +30,6 @@ import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
@@ -134,6 +133,7 @@ public class JdPublishBoardService {
|
||||
item.setTaskId(task.getId());
|
||||
item.setTaskNo(task.getTaskNo());
|
||||
item.setTaskStatus(task.getStatus());
|
||||
item.setResumeAttempt(JdPublishTaskService.resumeAttempt(task));
|
||||
item.setSuccess(TaskStatuses.FileTask.SUCCESS.equals(task.getStatus()));
|
||||
item.setErrorMessage(task.getErrorMessage());
|
||||
JdPublishTaskCreateRequest request = readCreateRequestQuiet(task);
|
||||
@@ -209,6 +209,7 @@ public class JdPublishBoardService {
|
||||
taskItem.setId(task.getId());
|
||||
taskItem.setTaskNo(task.getTaskNo());
|
||||
taskItem.setStatus(task.getStatus());
|
||||
taskItem.setResumeAttempt(JdPublishTaskService.resumeAttempt(task));
|
||||
taskItem.setErrorMessage(task.getErrorMessage());
|
||||
taskItem.setUpdatedAt(task.getUpdatedAt() == null ? null : task.getUpdatedAt().toString());
|
||||
JdPublishTaskDetailVo detail = new JdPublishTaskDetailVo();
|
||||
@@ -231,10 +232,9 @@ public class JdPublishBoardService {
|
||||
*/
|
||||
@Transactional
|
||||
public void deleteTask(Long taskId, Long userId) {
|
||||
FileTaskEntity task = fileTaskMapper.selectById(taskId);
|
||||
if (task == null || !JdPublishTaskService.MODULE_TYPE.equals(task.getModuleType())
|
||||
|| (userId != null && task.getUserId() != null && !Objects.equals(userId, task.getUserId()))) {
|
||||
throw new BusinessException("任务不存在");
|
||||
FileTaskEntity task = JdPublishTaskService.assertOwnedTask(fileTaskMapper.selectByIdForUpdate(taskId), userId);
|
||||
if (TaskStatuses.FileTask.RUNNING.equals(task.getStatus())) {
|
||||
throw new BusinessException(409, "运行中的发布任务不能删除");
|
||||
}
|
||||
int items = jdPublishItemMapper.delete(new LambdaQueryWrapper<JdPublishItemEntity>()
|
||||
.eq(JdPublishItemEntity::getTaskId, taskId));
|
||||
|
||||
+124
-150
@@ -11,219 +11,193 @@ import com.nanri.aiimage.modules.jd.model.entity.JdPublishItemEntity;
|
||||
import com.nanri.aiimage.modules.jd.model.vo.JdPublishChunkVo;
|
||||
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
|
||||
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
|
||||
import com.nanri.aiimage.modules.task.service.CredentialFatalTaskCloser;
|
||||
import com.nanri.aiimage.modules.task.service.TaskFinalizeSupport;
|
||||
import com.nanri.aiimage.modules.task.service.TaskProgressSnapshotService;
|
||||
import com.nanri.aiimage.modules.task.service.support.TaskFailureLedger;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import static com.nanri.aiimage.modules.jd.service.JdPublishTaskService.ITEM_FAILED;
|
||||
import static com.nanri.aiimage.modules.jd.service.JdPublishTaskService.ITEM_PENDING;
|
||||
import static com.nanri.aiimage.modules.jd.service.JdPublishTaskService.ITEM_PUBLISHING;
|
||||
import static com.nanri.aiimage.modules.jd.service.JdPublishTaskService.ITEM_SUCCESS;
|
||||
import static com.nanri.aiimage.modules.jd.service.JdPublishTaskService.MODULE_TYPE;
|
||||
|
||||
/**
|
||||
* 京东发布行级回传(v1.5 蓝图 §3 chunk 通道:POST /api/jd-publish/tasks/{taskId}/chunk)。
|
||||
*
|
||||
* <p>行状态是唯一行级真源({@code biz_jd_publish_item.publish_status},uk_task_product 定位);
|
||||
* {@code isEnd=true} 时按行级状态汇总任务终态(失败行 > 0 ⇒ 任务 FAILED、其余 SUCCESS,
|
||||
* successFileCount/failedFileCount 落真实行数——R6 单行失败隔离、任务终态汇总成败数)。
|
||||
* CAS 只认 RUNNING(铁律 14:已终态的任务不改写;可重入)。</p>
|
||||
*
|
||||
* <p>{@code error} 上报按铁律 31 分档(判死口凭据化,匿名一律拒绝判死——照
|
||||
* {@code JdCollectController#submitChunk} 同口径):京麦登录态失效 →
|
||||
* {@link JdPublishStaleTaskService#terminalizeOnJdLoginFatal}(词表复用
|
||||
* {@code JdStaleTaskService#isJdLoginStateFailure},京东域两链同一族);代理/LLM 凭据
|
||||
* 致命词 → {@code CredentialFatalTaskCloser};其余技术性故障只记录不判死。</p>
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
@Slf4j
|
||||
public class JdPublishIngestService {
|
||||
|
||||
private static final String LOG_TAG = "jd-publish";
|
||||
|
||||
private static final String STATUS_RUNNING = TaskStatuses.FileTask.RUNNING;
|
||||
|
||||
/** chunk 可写回的行级状态(PENDING 是建单初值,不接受回传写回)。 */
|
||||
private static final Set<String> WRITABLE_STATUSES =
|
||||
Set.of(JdPublishTaskService.ITEM_PUBLISHING, JdPublishTaskService.ITEM_SUCCESS,
|
||||
JdPublishTaskService.ITEM_FAILED);
|
||||
|
||||
/** publish_error 列宽(V210 VARCHAR(1024)),超长截断不炸批。 */
|
||||
private static final int MAX_ERROR_LENGTH = 1024;
|
||||
private static final String RUNNING = TaskStatuses.FileTask.RUNNING;
|
||||
private static final Pattern BATCH_ID = Pattern.compile("[A-Za-z0-9_-]{1,128}");
|
||||
|
||||
private final FileTaskMapper fileTaskMapper;
|
||||
private final JdPublishItemMapper jdPublishItemMapper;
|
||||
private final JdPublishStaleTaskService staleTaskService;
|
||||
private final TaskProgressSnapshotService taskProgressSnapshotService;
|
||||
|
||||
public JdPublishChunkVo submitChunk(Long taskId, JdPublishChunkRequest request, boolean trustedErrorReporter) {
|
||||
if (taskId == null || taskId <= 0) {
|
||||
throw new BusinessException("任务 ID 不合法");
|
||||
@Transactional
|
||||
public JdPublishChunkVo submitChunk(Long taskId, JdPublishChunkRequest request, Long userId) {
|
||||
if (taskId == null || taskId <= 0 || request == null || request.getResumeAttempt() == null
|
||||
|| request.getResumeAttempt() < 0 || request.getBatchId() == null
|
||||
|| !BATCH_ID.matcher(request.getBatchId()).matches()) {
|
||||
throw new BusinessException(400, "回传必须提供有效的任务、代次和批次号");
|
||||
}
|
||||
if (request == null) {
|
||||
throw new BusinessException("回传体为空");
|
||||
List<ItemResult> items = request.getItems() == null ? List.of() : request.getItems();
|
||||
if (items.size() > 500) {
|
||||
throw new BusinessException(400, "回传明细过多");
|
||||
}
|
||||
FileTaskEntity task = fileTaskMapper.selectById(taskId);
|
||||
if (task == null || !TaskFinalizeSupport.belongsToModule(JdPublishTaskService.MODULE_TYPE, task.getModuleType())) {
|
||||
throw new BusinessException("任务不存在: " + taskId);
|
||||
FileTaskEntity task = JdPublishTaskService.assertOwnedTask(fileTaskMapper.selectByIdForUpdate(taskId), userId);
|
||||
int attempt = JdPublishTaskService.resumeAttempt(task);
|
||||
if (attempt != request.getResumeAttempt()) {
|
||||
throw new BusinessException(409, "回传代次已失效");
|
||||
}
|
||||
if (TaskStatuses.FileTask.TERMINAL.contains(task.getStatus())) {
|
||||
throw new BusinessException("任务已结束(" + task.getStatus() + "),不再接受回传");
|
||||
}
|
||||
if (request.getError() != null && !request.getError().isBlank()) {
|
||||
return handleErrorReport(task, request.getError(), trustedErrorReporter);
|
||||
}
|
||||
if (!STATUS_RUNNING.equals(task.getStatus())) {
|
||||
// PENDING 拒收(页面推送漏 activate 时客户端第一个回传在此被拒,2026-11-14 同形实录)。
|
||||
throw new BusinessException("任务不在运行中(" + task.getStatus() + "),请先激活任务再回传");
|
||||
boolean terminal = TaskStatuses.FileTask.TERMINAL.contains(task.getStatus());
|
||||
if (!terminal && !RUNNING.equals(task.getStatus())) {
|
||||
throw new BusinessException(409, "任务不在运行中,请先激活任务再回传");
|
||||
}
|
||||
|
||||
int accepted = 0;
|
||||
if (request.getItems() != null) {
|
||||
for (ItemResult item : request.getItems()) {
|
||||
accepted += applyRowResult(taskId, item);
|
||||
String newlyFailedReason = null;
|
||||
Set<Long> seen = new HashSet<>();
|
||||
for (ItemResult item : items) {
|
||||
if (item == null || item.getProductId() == null || !seen.add(item.getProductId())) {
|
||||
continue;
|
||||
}
|
||||
String status = normalizeStatus(item.getPublishStatus());
|
||||
RowOutcome outcome = applyRow(taskId, userId, attempt, request.getBatchId(), item, status, terminal);
|
||||
if (outcome != RowOutcome.REJECTED) {
|
||||
accepted++;
|
||||
}
|
||||
if (outcome == RowOutcome.CHANGED && ITEM_FAILED.equals(status)
|
||||
&& JdStaleTaskService.isJdLoginStateFailure(item.getPublishError())) {
|
||||
newlyFailedReason = item.getPublishError();
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, Long> counts = statusCounts(taskId);
|
||||
JdPublishChunkVo vo = new JdPublishChunkVo();
|
||||
vo.setAcceptedCount(accepted);
|
||||
vo.setPendingCount(statusCounts(taskId).getOrDefault(JdPublishTaskService.ITEM_PENDING, 0L));
|
||||
if (Boolean.TRUE.equals(request.getIsEnd())) {
|
||||
vo.setTaskStatus(summarizeTerminal(taskId));
|
||||
vo.setPendingCount(counts.getOrDefault(ITEM_PENDING, 0L));
|
||||
vo.setPublishingCount(counts.getOrDefault(ITEM_PUBLISHING, 0L));
|
||||
vo.setNeedsReview(Boolean.TRUE.equals(request.getIsEnd()) && vo.getPublishingCount() > 0);
|
||||
if (terminal) {
|
||||
vo.setTaskStatus(task.getStatus());
|
||||
} else if (newlyFailedReason != null && staleTaskService.terminalizeOnJdLoginFatal(task, newlyFailedReason)) {
|
||||
vo.setTaskStatus(TaskStatuses.FileTask.FAILED);
|
||||
} else if (Boolean.TRUE.equals(request.getIsEnd())) {
|
||||
vo.setTaskStatus(summarizeTerminal(task, counts));
|
||||
}
|
||||
log.info("[{}] chunk 回传 taskId={} batchId={} accepted={} pending={} isEnd={}",
|
||||
LOG_TAG, taskId, request.getBatchId(), accepted, vo.getPendingCount(),
|
||||
Boolean.TRUE.equals(request.getIsEnd()));
|
||||
return vo;
|
||||
}
|
||||
|
||||
/** 行级结果落库:按 uk_task_product(task_id + product_id)定位,单行失败不炸批。 */
|
||||
private int applyRowResult(Long taskId, ItemResult item) {
|
||||
if (item == null || item.getProductId() == null) {
|
||||
return 0;
|
||||
private RowOutcome applyRow(Long taskId, Long userId, int attempt, String batchId, ItemResult item,
|
||||
String status, boolean terminal) {
|
||||
String wareId = ITEM_SUCCESS.equals(status) ? item.getJdWareId() : null;
|
||||
String error = ITEM_FAILED.equals(status) ? truncate(item.getPublishError()) : null;
|
||||
if (status == null || (ITEM_SUCCESS.equals(status) && (wareId == null || wareId.isBlank() || wareId.length() > 64))
|
||||
|| (ITEM_FAILED.equals(status) && (error == null || error.isBlank()))) {
|
||||
return RowOutcome.REJECTED;
|
||||
}
|
||||
String status = item.getPublishStatus() == null ? null : item.getPublishStatus().trim().toUpperCase();
|
||||
if (status == null || !WRITABLE_STATUSES.contains(status)) {
|
||||
log.warn("[{}] 回传行状态不识别,跳过 taskId={} productId={} status={}",
|
||||
LOG_TAG, taskId, item.getProductId(), item.getPublishStatus());
|
||||
return 0;
|
||||
}
|
||||
LambdaUpdateWrapper<JdPublishItemEntity> wrapper = new LambdaUpdateWrapper<JdPublishItemEntity>()
|
||||
JdPublishItemEntity row = jdPublishItemMapper.selectOne(new LambdaQueryWrapper<JdPublishItemEntity>()
|
||||
.eq(JdPublishItemEntity::getTaskId, taskId)
|
||||
.eq(JdPublishItemEntity::getProductId, item.getProductId())
|
||||
.eq(JdPublishItemEntity::getUserId, userId));
|
||||
if (row == null || (item.getItemId() != null && !item.getItemId().equals(row.getId()))) {
|
||||
return RowOutcome.REJECTED;
|
||||
}
|
||||
String previous = row.getPublishStatus();
|
||||
boolean samePermit = batchId.equals(row.getPublishBatchId()) && Objects.equals(attempt, row.getPublishResumeAttempt());
|
||||
if (samePermit && status.equals(previous) && (!terminal || !ITEM_PUBLISHING.equals(status))
|
||||
&& Objects.equals(wareId, row.getJdWareId()) && Objects.equals(error, row.getPublishError())) {
|
||||
return RowOutcome.REPLAY;
|
||||
}
|
||||
boolean fromPending = ITEM_PENDING.equals(previous) && !ITEM_SUCCESS.equals(status);
|
||||
boolean fromPublishing = ITEM_PUBLISHING.equals(previous) && samePermit && !ITEM_PUBLISHING.equals(status);
|
||||
if (terminal || (!fromPending && !fromPublishing)) {
|
||||
return RowOutcome.REJECTED;
|
||||
}
|
||||
int updated = jdPublishItemMapper.update(null, new LambdaUpdateWrapper<JdPublishItemEntity>()
|
||||
.eq(JdPublishItemEntity::getId, row.getId())
|
||||
.eq(JdPublishItemEntity::getTaskId, taskId)
|
||||
.eq(JdPublishItemEntity::getPublishStatus, previous)
|
||||
.eq(fromPublishing, JdPublishItemEntity::getPublishBatchId, batchId)
|
||||
.eq(fromPublishing, JdPublishItemEntity::getPublishResumeAttempt, attempt)
|
||||
.set(JdPublishItemEntity::getPublishStatus, status)
|
||||
.set(JdPublishItemEntity::getPublishError,
|
||||
JdPublishTaskService.ITEM_FAILED.equals(status)
|
||||
? truncate(item.getPublishError()) : null)
|
||||
.set(JdPublishItemEntity::getJdWareId, item.getJdWareId())
|
||||
.set(JdPublishItemEntity::getUpdatedAt, LocalDateTime.now());
|
||||
int updated = jdPublishItemMapper.update(null, wrapper);
|
||||
if (updated == 0) {
|
||||
log.warn("[{}] 回传行未命中明细行(商品不在本任务?)taskId={} productId={}",
|
||||
LOG_TAG, taskId, item.getProductId());
|
||||
}
|
||||
return updated;
|
||||
.set(JdPublishItemEntity::getPublishError, error)
|
||||
.set(JdPublishItemEntity::getJdWareId, wareId)
|
||||
.set(JdPublishItemEntity::getPublishBatchId, batchId)
|
||||
.set(JdPublishItemEntity::getPublishResumeAttempt, attempt)
|
||||
.set(JdPublishItemEntity::getUpdatedAt, LocalDateTime.now()));
|
||||
return updated == 1 ? RowOutcome.CHANGED : RowOutcome.REJECTED;
|
||||
}
|
||||
|
||||
/** 铁律 31 分档判死口:只信 X-Internal-Token,匿名 error 一律拒绝判死(不碰状态)。 */
|
||||
private JdPublishChunkVo handleErrorReport(FileTaskEntity task, String error, boolean trustedErrorReporter) {
|
||||
JdPublishChunkVo vo = new JdPublishChunkVo();
|
||||
vo.setAcceptedCount(0);
|
||||
vo.setPendingCount(statusCounts(task.getId()).getOrDefault(JdPublishTaskService.ITEM_PENDING, 0L));
|
||||
if (!trustedErrorReporter) {
|
||||
log.warn("[{}] 匿名 error 上报拒绝判死 taskId={} err={}", LOG_TAG, task.getId(), abbreviate(error));
|
||||
return vo;
|
||||
}
|
||||
// 京东域凭据词(京麦登录态)先判——采集/发布共用 19899 同一 profile,同一族同一判据。
|
||||
if (JdStaleTaskService.isJdLoginStateFailure(error)) {
|
||||
staleTaskService.terminalizeOnJdLoginFatal(task, error);
|
||||
vo.setTaskStatus(TaskStatuses.FileTask.FAILED);
|
||||
return vo;
|
||||
}
|
||||
// 代理/LLM 凭据致命词 → 公共判定档(发布面无代理无 LLM 消费,客户端报什么分什么档)。
|
||||
boolean closed = new CredentialFatalTaskCloser(LOG_TAG, fileTaskMapper, null)
|
||||
.closeIfFatal(task, error);
|
||||
if (closed) {
|
||||
vo.setTaskStatus(TaskStatuses.FileTask.FAILED);
|
||||
return vo;
|
||||
}
|
||||
log.warn("[{}] 非致命失败上报,只记录不判死 taskId={} err={}", LOG_TAG, task.getId(), abbreviate(error));
|
||||
return vo;
|
||||
}
|
||||
|
||||
/** isEnd 终态汇总:按行级真源聚合落任务终态(R6),CAS 只认 RUNNING(铁律 14)。 */
|
||||
private String summarizeTerminal(Long taskId) {
|
||||
Map<String, Long> counts = statusCounts(taskId);
|
||||
long success = counts.getOrDefault(JdPublishTaskService.ITEM_SUCCESS, 0L);
|
||||
long failed = counts.getOrDefault(JdPublishTaskService.ITEM_FAILED, 0L);
|
||||
long unpublished = counts.getOrDefault(JdPublishTaskService.ITEM_PENDING, 0L)
|
||||
+ counts.getOrDefault(JdPublishTaskService.ITEM_PUBLISHING, 0L);
|
||||
boolean anyFailed = failed > 0;
|
||||
String status = anyFailed ? TaskStatuses.FileTask.FAILED : TaskStatuses.FileTask.SUCCESS;
|
||||
StringBuilder reason = new StringBuilder("发布完成:成功 ").append(success).append(" 行,失败 ")
|
||||
.append(failed).append(" 行");
|
||||
if (unpublished > 0) {
|
||||
reason.append(",未发布 ").append(unpublished).append(" 行");
|
||||
private String summarizeTerminal(FileTaskEntity task, Map<String, Long> counts) {
|
||||
long success = counts.getOrDefault(ITEM_SUCCESS, 0L);
|
||||
long failed = counts.getOrDefault(ITEM_FAILED, 0L);
|
||||
long total = counts.values().stream().mapToLong(Long::longValue).sum();
|
||||
if (total == 0 || success + failed != total || !Objects.equals(task.getSourceFileCount(), (int) total)) {
|
||||
return RUNNING;
|
||||
}
|
||||
String status = failed > 0 ? TaskStatuses.FileTask.FAILED : TaskStatuses.FileTask.SUCCESS;
|
||||
String message = failed > 0 ? "发布完成:成功 " + success + " 行,失败 " + failed + " 行" : null;
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
// 文案先落局部变量再配对写列(B51-R1 守卫「写的列与文案同一个来源」:列由同一句文案派生,
|
||||
// 三元里各写各的表达式会被 TaskFailureCategoryGuardrailTest 判为不同源即红)。
|
||||
String message = anyFailed ? reason.toString() : null;
|
||||
int updated = fileTaskMapper.update(null, new LambdaUpdateWrapper<FileTaskEntity>()
|
||||
.eq(FileTaskEntity::getId, taskId)
|
||||
.eq(FileTaskEntity::getModuleType, JdPublishTaskService.MODULE_TYPE)
|
||||
.eq(FileTaskEntity::getStatus, STATUS_RUNNING)
|
||||
.eq(FileTaskEntity::getId, task.getId())
|
||||
.eq(FileTaskEntity::getModuleType, MODULE_TYPE)
|
||||
.eq(FileTaskEntity::getStatus, RUNNING)
|
||||
.eq(FileTaskEntity::getResumeAttempt, JdPublishTaskService.resumeAttempt(task))
|
||||
.set(FileTaskEntity::getStatus, status)
|
||||
.set(FileTaskEntity::getSuccessFileCount, success)
|
||||
.set(FileTaskEntity::getFailedFileCount, failed)
|
||||
.set(FileTaskEntity::getErrorMessage, message)
|
||||
.set(FileTaskEntity::getFailureCategory, message == null ? null : TaskFailureLedger.categoryOf(message))
|
||||
.set(FileTaskEntity::getFailureCategory, TaskFailureLedger.categoryOf(message))
|
||||
.set(FileTaskEntity::getUpdatedAt, now)
|
||||
.set(FileTaskEntity::getFinishedAt, now));
|
||||
if (updated > 0) {
|
||||
taskProgressSnapshotService.markTerminal(taskId, JdPublishTaskService.MODULE_TYPE, status,
|
||||
anyFailed ? reason.toString() : null);
|
||||
log.info("[{}] 任务落终态 {} taskId={}", LOG_TAG, status, taskId);
|
||||
taskProgressSnapshotService.markTerminal(task.getId(), MODULE_TYPE, status, message);
|
||||
return status;
|
||||
}
|
||||
return status;
|
||||
return RUNNING;
|
||||
}
|
||||
|
||||
/** 行级状态聚合(XML 具名 SQL):status → 行数。 */
|
||||
private Map<String, Long> statusCounts(Long taskId) {
|
||||
Map<String, Long> counts = new LinkedHashMap<>();
|
||||
Map<String, Long> counts = new HashMap<>();
|
||||
for (Map<String, Object> row : jdPublishItemMapper.countByPublishStatus(taskId)) {
|
||||
Object status = row.get("publishStatus");
|
||||
Object cnt = row.get("cnt");
|
||||
if (status != null && cnt instanceof Number number) {
|
||||
counts.put(String.valueOf(status), number.longValue());
|
||||
if (row.get("publishStatus") != null && row.get("cnt") instanceof Number number) {
|
||||
counts.put(String.valueOf(row.get("publishStatus")), number.longValue());
|
||||
}
|
||||
}
|
||||
return counts;
|
||||
}
|
||||
|
||||
private String truncate(String value) {
|
||||
private static String normalizeStatus(String raw) {
|
||||
if (raw == null) {
|
||||
return null;
|
||||
}
|
||||
return switch (raw.trim().toUpperCase(Locale.ROOT)) {
|
||||
case ITEM_PUBLISHING -> ITEM_PUBLISHING;
|
||||
case ITEM_SUCCESS -> ITEM_SUCCESS;
|
||||
case ITEM_FAILED -> ITEM_FAILED;
|
||||
default -> null;
|
||||
};
|
||||
}
|
||||
|
||||
private static String truncate(String value) {
|
||||
if (value == null) {
|
||||
return null;
|
||||
}
|
||||
String trimmed = value.trim();
|
||||
return trimmed.length() <= MAX_ERROR_LENGTH ? trimmed : trimmed.substring(0, MAX_ERROR_LENGTH);
|
||||
return trimmed.length() <= 1024 ? trimmed : trimmed.substring(0, 1024);
|
||||
}
|
||||
|
||||
private String abbreviate(String value) {
|
||||
if (value == null) {
|
||||
return "";
|
||||
}
|
||||
return value.length() <= 200 ? value : value.substring(0, 200) + "…";
|
||||
}
|
||||
|
||||
/** 供测试确认行级形状(按任务取全部明细行)。 */
|
||||
public java.util.List<JdPublishItemEntity> findItemRows(Long taskId) {
|
||||
return jdPublishItemMapper.selectList(new LambdaQueryWrapper<JdPublishItemEntity>()
|
||||
.eq(JdPublishItemEntity::getTaskId, taskId)
|
||||
.orderByAsc(JdPublishItemEntity::getId));
|
||||
}
|
||||
private enum RowOutcome { REJECTED, REPLAY, CHANGED }
|
||||
}
|
||||
|
||||
+2
@@ -102,6 +102,8 @@ public class JdPublishStaleTaskService {
|
||||
.eq(FileTaskEntity::getId, task.getId())
|
||||
.eq(FileTaskEntity::getModuleType, MODULE_TYPE)
|
||||
.eq(FileTaskEntity::getStatus, STATUS_RUNNING)
|
||||
.eq(FileTaskEntity::getResumeAttempt, JdPublishTaskService.resumeAttempt(task))
|
||||
.lt(FileTaskEntity::getUpdatedAt, LocalDateTime.now().minusMinutes(minutes))
|
||||
.set(FileTaskEntity::getStatus, STATUS_FAILED)
|
||||
.set(FileTaskEntity::getErrorMessage, reason)
|
||||
.set(FileTaskEntity::getFailureCategory, TaskFailureLedger.categoryOf(reason))
|
||||
|
||||
+6
-11
@@ -13,15 +13,8 @@ import java.time.LocalDateTime;
|
||||
/**
|
||||
* 京东商品上架的失败重试明细行复位(AC-7 服务端半边,v1.5 Phase 5 消欠账)。
|
||||
*
|
||||
* <p>任务头被 {@code TaskInPlaceRetryService} 原地复位成 PENDING 后,明细分批下发
|
||||
* {@code JdPublishItemMapper.selectPublishableItems} 只出 PENDING 行——上一代留下的
|
||||
* FAILED/PUBLISHING 行不复位,重试就是空页空跑(蓝图 Phase 2 变更记录登记的欠账)。
|
||||
* 本实现把 FAILED/PUBLISHING 行复位回 PENDING 并清旧错误文案,让剩余商品重新进入
|
||||
* 下发候选;SUCCESS 行不动:已发布商品不重发(AC-4),客户端断点 done 集合同口径。
|
||||
*
|
||||
* <p>{@code jd_ware_id} 不清:只有 SUCCESS 行才有值,本条不碰 SUCCESS 行;
|
||||
* 旧 {@code publish_error} 必须清——留着会让用户端面板把「上一代的失败原因」
|
||||
* 显示在「待发布」行上(进度真源是行级状态聚合,JdPublishBoardService 同源)。
|
||||
* <p>只复位已经确认失败的 FAILED 行。SUCCESS 已经发布,PUBLISHING 的外部提交结果未知,
|
||||
* 两者都不能重发。已发出的许可保留用于识别旧批次,但不能跨代确认。</p>
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@@ -40,10 +33,12 @@ public class JdPublishTaskItemsResetSpiImpl implements TaskItemsResetSpi {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
int updated = jdPublishItemMapper.update(null, new LambdaUpdateWrapper<JdPublishItemEntity>()
|
||||
.eq(JdPublishItemEntity::getTaskId, taskId)
|
||||
.in(JdPublishItemEntity::getPublishStatus,
|
||||
JdPublishTaskService.ITEM_FAILED, JdPublishTaskService.ITEM_PUBLISHING)
|
||||
.eq(JdPublishItemEntity::getPublishStatus, JdPublishTaskService.ITEM_FAILED)
|
||||
.set(JdPublishItemEntity::getPublishStatus, JdPublishTaskService.ITEM_PENDING)
|
||||
.set(JdPublishItemEntity::getPublishError, null)
|
||||
.set(JdPublishItemEntity::getPublishBatchId, null)
|
||||
.set(JdPublishItemEntity::getPublishResumeAttempt, null)
|
||||
.set(JdPublishItemEntity::getJdWareId, null)
|
||||
.set(JdPublishItemEntity::getUpdatedAt, now));
|
||||
log.info("[jd-publish][retry] 明细行已复位可续跑 taskId={} reset={}", taskId, updated);
|
||||
}
|
||||
|
||||
+5
@@ -40,6 +40,11 @@ public class JdPublishTaskPullSpiImpl implements ClientTaskPullSpi {
|
||||
public Map<String, Object> buildQueuePayload(FileTaskEntity task) {
|
||||
// 载荷组装单一出处:与建单响应的 queuePayload 同源(铁律 32 三件同值判据)。
|
||||
Map<String, Object> payload = publishTaskService.buildQueuePayload(task);
|
||||
if (payload.get("data") instanceof Map<?, ?> data) {
|
||||
Map<Object, Object> claimed = new java.util.LinkedHashMap<>(data);
|
||||
claimed.put("claimed", true);
|
||||
payload = Map.of("type", QUEUE_TYPE, "data", claimed);
|
||||
}
|
||||
log.info("[jd-publish] 兜底载荷已组装 taskId={}", task.getId());
|
||||
return payload;
|
||||
}
|
||||
|
||||
+36
-27
@@ -37,6 +37,7 @@ import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
@@ -114,6 +115,7 @@ public class JdPublishTaskService {
|
||||
@Value("${aiimage.jd.oss.bucket:jd-products}")
|
||||
private String bucket;
|
||||
|
||||
@Transactional
|
||||
public JdPublishTaskVo createTask(JdPublishTaskCreateRequest request, String deviceId) {
|
||||
validate(request);
|
||||
// AC-8 配额闸:前置在一切昂贵动作前(铁律 27b),超配额当场业务码拒绝并点名额度文案。
|
||||
@@ -175,33 +177,20 @@ public class JdPublishTaskService {
|
||||
return vo;
|
||||
}
|
||||
|
||||
/**
|
||||
* 激活任务(PENDING→RUNNING)——页面把载荷推给本机客户端<b>之前</b>调用。
|
||||
*
|
||||
* <p>形状照 {@code JdCollectTaskService#activateTask} 同形(2026-11-14 真机实录:漏掉
|
||||
* 这一步,客户端第一个回传会被「任务不在运行中(PENDING)」拒收)。只允许
|
||||
* PENDING→RUNNING 条件更新:与客户端兜底拉取的原子认领互斥,谁先翻转谁执行。
|
||||
*/
|
||||
public void activateTask(Long taskId, Long userId) {
|
||||
FileTaskEntity task = fileTaskMapper.selectById(taskId);
|
||||
// 归属谓词走公共出口(TaskLifecycleDebtRatchetTest 棘轮只许降:新增手写遍数即红)。
|
||||
if (task == null || !TaskFinalizeSupport.belongsToModule(MODULE_TYPE, task.getModuleType())
|
||||
|| (userId != null && task.getUserId() != null && !Objects.equals(userId, task.getUserId()))) {
|
||||
throw new BusinessException("任务不存在");
|
||||
}
|
||||
/** 仅当前代次的 PENDING 任务能被页面队列中的桌面执行器认领。 */
|
||||
public void activateTask(Long taskId, Long userId, int attempt) {
|
||||
FileTaskEntity task = requireOwnedTask(taskId, userId);
|
||||
requireAttempt(task, attempt);
|
||||
int updated = fileTaskMapper.update(null, new LambdaUpdateWrapper<FileTaskEntity>()
|
||||
.eq(FileTaskEntity::getId, taskId)
|
||||
.eq(FileTaskEntity::getUserId, userId)
|
||||
.eq(FileTaskEntity::getStatus, STATUS_PENDING)
|
||||
.eq(FileTaskEntity::getResumeAttempt, attempt)
|
||||
.set(FileTaskEntity::getStatus, STATUS_RUNNING)
|
||||
.set(FileTaskEntity::getUpdatedAt, LocalDateTime.now()));
|
||||
if (updated == 0) {
|
||||
FileTaskEntity latest = fileTaskMapper.selectById(taskId);
|
||||
if (latest != null && STATUS_RUNNING.equals(latest.getStatus())) {
|
||||
throw new BusinessException("任务已在执行中(可能已由客户端自动接管),无需重复启动");
|
||||
}
|
||||
throw new BusinessException("任务已结束");
|
||||
if (updated != 1) {
|
||||
throw new BusinessException(409, "任务已被认领、已结束或代次已变化");
|
||||
}
|
||||
log.info("[jd-publish] 已激活(PENDING→RUNNING) taskId={} userId={}", taskId, task.getUserId());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -209,8 +198,12 @@ public class JdPublishTaskService {
|
||||
* 重连 cursor 归零也不会重发已发布商品,AC-4 服务端半边);SKU 价按改价规则折算;
|
||||
* 图片发 jd-products 桶预签名 GET URL(蓝图 §3)。
|
||||
*/
|
||||
public JdPublishItemsPageVo pullItems(Long taskId, Long userId, Long cursor, Integer limit) {
|
||||
requireOwnedTask(taskId, userId);
|
||||
public JdPublishItemsPageVo pullItems(Long taskId, Long userId, int attempt, Long cursor, Integer limit) {
|
||||
FileTaskEntity task = requireOwnedTask(taskId, userId);
|
||||
requireAttempt(task, attempt);
|
||||
if (!STATUS_RUNNING.equals(task.getStatus())) {
|
||||
throw new BusinessException(409, "任务未在运行,不能下发发布明细");
|
||||
}
|
||||
int safeLimit = Math.min(Math.max(limit == null ? itemsBatchSize : limit, 1), MAX_ITEMS_BATCH);
|
||||
long safeCursor = cursor == null ? 0L : Math.max(0L, cursor);
|
||||
|
||||
@@ -222,6 +215,7 @@ public class JdPublishTaskService {
|
||||
|
||||
JdPublishItemsPageVo vo = new JdPublishItemsPageVo();
|
||||
vo.setTaskId(taskId);
|
||||
vo.setResumeAttempt(attempt);
|
||||
vo.setItems(rows.isEmpty() ? List.of() : rows.stream()
|
||||
.map(row -> buildItemPayload(row, productsByPid.get(row.getProductId())))
|
||||
.toList());
|
||||
@@ -237,6 +231,7 @@ public class JdPublishTaskService {
|
||||
JdPublishProgressVo vo = new JdPublishProgressVo();
|
||||
vo.setTaskId(task.getId());
|
||||
vo.setStatus(task.getStatus());
|
||||
vo.setResumeAttempt(resumeAttempt(task));
|
||||
vo.setMessage(task.getErrorMessage());
|
||||
vo.setUpdatedAt(task.getUpdatedAt());
|
||||
Map<String, Long> counts = aggregateStatusCounts(taskId);
|
||||
@@ -269,6 +264,7 @@ public class JdPublishTaskService {
|
||||
JdPublishTaskCreateRequest create = readCreateRequest(task);
|
||||
Map<String, Object> data = new LinkedHashMap<>();
|
||||
data.put("taskId", task.getId());
|
||||
data.put("resumeAttempt", resumeAttempt(task));
|
||||
data.put("priceRule", create.getPriceRule() == null ? Map.of("mode", "none") : create.getPriceRule());
|
||||
return Map.of("type", JdPublishTaskPullSpiImpl.QUEUE_TYPE, "data", data);
|
||||
}
|
||||
@@ -298,16 +294,29 @@ public class JdPublishTaskService {
|
||||
if (taskId == null || taskId <= 0) {
|
||||
throw new BusinessException("任务 ID 不合法");
|
||||
}
|
||||
FileTaskEntity task = fileTaskMapper.selectById(taskId);
|
||||
return assertOwnedTask(fileTaskMapper.selectById(taskId), userId);
|
||||
}
|
||||
|
||||
static FileTaskEntity assertOwnedTask(FileTaskEntity task, Long userId) {
|
||||
if (task == null || !TaskFinalizeSupport.belongsToModule(MODULE_TYPE, task.getModuleType())) {
|
||||
throw new BusinessException("任务不存在: " + taskId);
|
||||
throw new BusinessException(404, "任务不存在");
|
||||
}
|
||||
if (userId != null && task.getUserId() != null && !Objects.equals(userId, task.getUserId())) {
|
||||
throw new BusinessException(403, "无权查看该任务");
|
||||
if (userId == null || userId <= 0 || !userId.equals(task.getUserId())) {
|
||||
throw new BusinessException(403, "无权访问该任务");
|
||||
}
|
||||
return task;
|
||||
}
|
||||
|
||||
static int resumeAttempt(FileTaskEntity task) {
|
||||
return task.getResumeAttempt() == null ? 0 : task.getResumeAttempt();
|
||||
}
|
||||
|
||||
private static void requireAttempt(FileTaskEntity task, int attempt) {
|
||||
if (attempt < 0 || attempt != resumeAttempt(task)) {
|
||||
throw new BusinessException(409, "任务代次已变化");
|
||||
}
|
||||
}
|
||||
|
||||
private void validate(JdPublishTaskCreateRequest request) {
|
||||
if (request.getUserId() == null || request.getUserId() <= 0) {
|
||||
throw new BusinessException("user_id 不合法");
|
||||
|
||||
+7
-2
@@ -11,6 +11,7 @@ import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import java.util.List;
|
||||
@@ -27,6 +28,8 @@ import java.util.List;
|
||||
@Tag(name = "任务兜底拉取", description = "供桌面客户端领取页面未推送成功的待执行任务")
|
||||
public class TaskClientPullController {
|
||||
|
||||
private static final Integer JD_PUBLISH_PROTOCOL = 2;
|
||||
|
||||
private final TaskClientPullService taskClientPullService;
|
||||
private final AdminAuthSupport adminAuthSupport;
|
||||
|
||||
@@ -35,8 +38,10 @@ public class TaskClientPullController {
|
||||
summary = "拉取并认领长期未推送的任务",
|
||||
description = "只返回当前登录用户、创建超过 N 分钟仍为 PENDING 的任务;服务端原子认领(PENDING→RUNNING),"
|
||||
+ "与页面推送互斥,不会重复执行。开关关闭时返回空列表。")
|
||||
public ApiResponse<List<TaskClientPullVo>> pullPending(HttpServletRequest request) {
|
||||
public ApiResponse<List<TaskClientPullVo>> pullPending(HttpServletRequest request,
|
||||
@RequestParam(name = "jdPublishProtocol", required = false) Integer jdPublishProtocol) {
|
||||
AdminUserEntity me = adminAuthSupport.requireUser(request);
|
||||
return ApiResponse.success(taskClientPullService.pullPendingTasks(me.getId()));
|
||||
return ApiResponse.success(taskClientPullService.pullPendingTasks(me.getId(),
|
||||
JD_PUBLISH_PROTOCOL.equals(jdPublishProtocol)));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,6 +11,9 @@ import java.util.List;
|
||||
@Mapper
|
||||
public interface FileTaskMapper extends BaseMapper<FileTaskEntity> {
|
||||
|
||||
/** 回传、重试与删除按任务主键串行,调用方必须持有数据库事务。 */
|
||||
FileTaskEntity selectByIdForUpdate(@Param("taskId") Long taskId);
|
||||
|
||||
/**
|
||||
* 查询某模块下超过保留期的终态任务 id(保留期清理用,只取 id 不拉整行)。
|
||||
*
|
||||
|
||||
+12
-1
@@ -128,6 +128,10 @@ public class TaskClientPullService {
|
||||
|
||||
/** 拉取并认领该用户"长期未被领取"的任务,按创建时间升序返回,最多 limit 条。 */
|
||||
public List<TaskClientPullVo> pullPendingTasks(Long userId) {
|
||||
return pullPendingTasks(userId, false);
|
||||
}
|
||||
|
||||
public List<TaskClientPullVo> pullPendingTasks(Long userId, boolean jdPublishV2) {
|
||||
if (!enabled) {
|
||||
return List.of();
|
||||
}
|
||||
@@ -135,6 +139,9 @@ public class TaskClientPullService {
|
||||
return List.of();
|
||||
}
|
||||
List<String> types = resolveModuleTypes();
|
||||
if (!jdPublishV2) {
|
||||
types = withoutJdPublish(types);
|
||||
}
|
||||
if (types.isEmpty()) {
|
||||
log.warn("[client-task-pull] 模块白名单为空,本次不拉取 userId={}", userId);
|
||||
return List.of();
|
||||
@@ -174,7 +181,7 @@ public class TaskClientPullService {
|
||||
log.info("[client-task-pull] 内部认领端点被调用但开关关闭 types={}", moduleTypes);
|
||||
return List.of();
|
||||
}
|
||||
List<String> types = normalizeModuleTypes(moduleTypes);
|
||||
List<String> types = withoutJdPublish(normalizeModuleTypes(moduleTypes));
|
||||
if (types.isEmpty()) {
|
||||
log.warn("[client-task-pull] 内部认领:模块白名单为空,本次不拉取");
|
||||
return List.of();
|
||||
@@ -250,6 +257,10 @@ public class TaskClientPullService {
|
||||
}
|
||||
|
||||
/** 归一化模块类型列表:去空白、转大写、去重;空输入返回空列表。 */
|
||||
private static List<String> withoutJdPublish(List<String> types) {
|
||||
return types.stream().filter(type -> !CollectRoutingProperties.MODULE_JD_PUBLISH.equals(type)).toList();
|
||||
}
|
||||
|
||||
private List<String> normalizeModuleTypes(List<String> moduleTypes) {
|
||||
List<String> types = new ArrayList<>();
|
||||
for (String raw : (moduleTypes == null ? List.<String>of() : moduleTypes)) {
|
||||
|
||||
+5
@@ -15,6 +15,7 @@ import com.nanri.aiimage.modules.task.spi.TaskItemsResetSpi;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
@@ -74,6 +75,7 @@ public class TaskInPlaceRetryService {
|
||||
* @return true=已复位(「活已经干完了」那一形状返回的是「已补终态」,见 {@link #settleAlreadyDelivered});
|
||||
* false=状态已不是 FAILED/CANCELLED(并发或已重试过)
|
||||
*/
|
||||
@Transactional
|
||||
public boolean retryInPlace(FileTaskEntity task) {
|
||||
if (task == null || task.getId() == null) {
|
||||
return false;
|
||||
@@ -98,6 +100,7 @@ public class TaskInPlaceRetryService {
|
||||
int updated = fileTaskMapper.update(null, new LambdaUpdateWrapper<FileTaskEntity>()
|
||||
.eq(FileTaskEntity::getId, task.getId())
|
||||
.in(FileTaskEntity::getStatus, STATUS_FAILED, STATUS_CANCELLED)
|
||||
.eq(FileTaskEntity::getResumeAttempt, attempt)
|
||||
.set(FileTaskEntity::getStatus, STATUS_PENDING)
|
||||
.set(FileTaskEntity::getErrorMessage, null)
|
||||
.set(FileTaskEntity::getFailureCategory, null)
|
||||
@@ -195,6 +198,7 @@ public class TaskInPlaceRetryService {
|
||||
* <p>外观专利/相似ASIN/采集数据三个模块的失败任务走同一条路——它们原先都会被
|
||||
* {@code TaskResumeService} 克隆重试,同一份输入在界面上多出好几行。
|
||||
*/
|
||||
@Transactional
|
||||
public void retryFailedTask(Long taskId, Long userId) {
|
||||
FileTaskEntity task = fileTaskMapper.selectById(taskId);
|
||||
if (task == null || !java.util.Objects.equals(userId, task.getUserId())) {
|
||||
@@ -208,6 +212,7 @@ public class TaskInPlaceRetryService {
|
||||
*
|
||||
* @throws com.nanri.aiimage.common.exception.BusinessException 任务不存在 / 不是可续跑态 / 状态已变
|
||||
*/
|
||||
@Transactional
|
||||
public void retryFailedTask(Long taskId, Long userId, String moduleType) {
|
||||
FileTaskEntity task = fileTaskMapper.selectById(taskId);
|
||||
if (task == null || !moduleType.equals(task.getModuleType())
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
-- V213: bind a publish permit to its originating execution batch and generation.
|
||||
-- Nullable expansion: legacy PUBLISHING rows remain protected, not automatically reissued.
|
||||
ALTER TABLE biz_jd_publish_item
|
||||
ADD COLUMN publish_batch_id VARCHAR(128) CHARACTER SET ascii COLLATE ascii_bin NULL,
|
||||
ADD COLUMN publish_resume_attempt INT NULL;
|
||||
@@ -55,4 +55,7 @@
|
||||
ORDER BY created_at ASC
|
||||
LIMIT #{limit}
|
||||
</select>
|
||||
<select id="selectByIdForUpdate" resultType="com.nanri.aiimage.modules.task.model.entity.FileTaskEntity" useCache="false" flushCache="true">
|
||||
SELECT * FROM biz_file_task WHERE id = #{taskId} FOR UPDATE
|
||||
</select>
|
||||
</mapper>
|
||||
|
||||
@@ -109,7 +109,8 @@ class MigratedSqlEquivalenceTest {
|
||||
// 103 → 105:2026-11-18 整量补记 v1.5 Phase 2(24272a91)JdPublishItemMapper 新写 2 条
|
||||
// 只读 select(selectPublishableItems + countByPublishStatus),逐条点名进 NOT_MIGRATED
|
||||
//(SqlLayeringConventionTest.XML_STATEMENT_TOTAL 同轮 147 → 149)。
|
||||
private static final int XML_SELECT_TOTAL = 105;
|
||||
// 105 → 106:Phase 5 京东上架回传的任务行锁在 FileTaskMapper 新写一条 select。
|
||||
private static final int XML_SELECT_TOTAL = 106;
|
||||
|
||||
/**
|
||||
* 不是「从注解搬过来」的语句:注解时代没有原文可对撞,等价性这支只能跳过它们。
|
||||
@@ -227,7 +228,9 @@ class MigratedSqlEquivalenceTest {
|
||||
// 该笔点名 12 类 87 例没跑整量、两处账本漏记,2026-11-18 发版前整量抓到补记
|
||||
//(XML_SELECT_TOTAL 103 → 105,SqlLayeringConventionTest.XML_STATEMENT_TOTAL 同轮 147 → 149)。
|
||||
"JdPublishItemMapper#selectPublishableItems",
|
||||
"JdPublishItemMapper#countByPublishStatus");
|
||||
"JdPublishItemMapper#countByPublishStatus",
|
||||
// Phase 5 原生 XML 行锁,不存在注解时代原文。
|
||||
"FileTaskMapper#selectByIdForUpdate");
|
||||
|
||||
/** 账本 5 列:接口 / 方法 / @Select 种类 / 是否含常量插值 / 注解原文(Java 反转义后那条串)。 */
|
||||
private static final int LEDGER_COLUMNS = 5;
|
||||
|
||||
@@ -135,7 +135,8 @@ class SqlLayeringConventionTest {
|
||||
// 落 2 条只读 select(selectPublishableItems 明细分批下发页 + countByPublishStatus 行级聚合),
|
||||
// 全部新写,非迁移语句;同轮登记进 MigratedSqlEquivalenceTest.NOT_MIGRATED
|
||||
//(该文件 XML_SELECT_TOTAL 同轮 103 → 105)。
|
||||
private static final int XML_STATEMENT_TOTAL = 149;
|
||||
// 149 → 150:Phase 5 京东上架的任务行锁查询(FileTaskMapper.selectByIdForUpdate)。
|
||||
private static final int XML_STATEMENT_TOTAL = 150;
|
||||
|
||||
/**
|
||||
* wrapper 里夹带函数级 SQL 的现状("这不是简单单表"的证据),文件名 → 条数:
|
||||
|
||||
+1
@@ -48,6 +48,7 @@ class RequestSuppliedIdentityOutletTest {
|
||||
private static final List<String> OUTLETS = List.of(
|
||||
"resolveOwnershipUserId(httpRequest",
|
||||
"requireOwnershipUserId(httpRequest",
|
||||
"adminAuthSupport.requireSessionOwnerUserId(httpRequest",
|
||||
"currentUserId(httpRequest");
|
||||
|
||||
private static final Pattern MAPPING =
|
||||
|
||||
@@ -97,9 +97,12 @@ class MigrationInventoryTest {
|
||||
* 2026-11-17 已改号 {@code V207__users_jd_publish_quota.sql} 入库(V206 被同窗
|
||||
* admin_account_platform 三表平台列占用,account-platform 提交);202 号自此彻底空置。</p>
|
||||
*
|
||||
* <p><b>211</b>:京东商品发布许可迁移尚未入库时,生产已随品牌双通道发版应用 V212
|
||||
* (2026-11-18 17:1x)。Flyway 未开 out-of-order,故许可迁移改为 V213,211 永久留空。</p>
|
||||
*
|
||||
* <p>共同后果:新迁移只能取当前最大值之上的号(详见 docs/migration-inventory.md)。</p>
|
||||
*/
|
||||
private static final Set<Integer> RETIRED_HOLES = Set.of(132, 133, 148, 168, 169, 202);
|
||||
private static final Set<Integer> RETIRED_HOLES = Set.of(132, 133, 148, 168, 169, 202, 211);
|
||||
|
||||
/**
|
||||
* 文件名版本与头注释版本不一致的历史件。V170 的头注释误写成 V168;它已应用到生产,
|
||||
|
||||
+2
-2
@@ -123,8 +123,8 @@ class JdPublishContractPendingTest {
|
||||
assertTrue(source.contains("@PostMapping(\"/tasks\")"), "缺建单端点 POST /tasks");
|
||||
assertTrue(source.contains("@PostMapping"), "建单必须是 POST 端点");
|
||||
// AC-9 归属半边:选了他人商品要业务码拒绝(照 JdCollectController 的 fail-closed 鉴权形状)
|
||||
assertTrue(source.contains("requireOwnershipUserId"),
|
||||
"建单/items 下发必须走 adminAuthSupport.requireOwnershipUserId(选他人商品要业务码拒绝)");
|
||||
assertTrue(source.contains("adminAuthSupport.requireSessionOwnerUserId(httpRequest"),
|
||||
"京东发布必须使用真实会话绑定所有者");
|
||||
}
|
||||
|
||||
@Test
|
||||
|
||||
+3
-3
@@ -143,11 +143,11 @@ class JdPublishBoardServiceTest {
|
||||
@Test
|
||||
void 删除任务_归属不符一律拒_不碰明细表() {
|
||||
FileTaskEntity other = task(88L, 9L, "FAILED");
|
||||
when(fileTaskMapper.selectById(88L)).thenReturn(other);
|
||||
when(fileTaskMapper.selectByIdForUpdate(88L)).thenReturn(other);
|
||||
|
||||
assertThatThrownBy(() -> service.deleteTask(88L, 7L))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("任务不存在");
|
||||
.extracting("code").isEqualTo(403);
|
||||
verify(jdPublishItemMapper, never()).delete(any());
|
||||
verify(fileTaskMapper, never()).deleteById(any(java.io.Serializable.class));
|
||||
}
|
||||
@@ -155,7 +155,7 @@ class JdPublishBoardServiceTest {
|
||||
@Test
|
||||
void 删除任务_先清明细快照行再清任务行() {
|
||||
FileTaskEntity mine = task(88L, 7L, "FAILED");
|
||||
when(fileTaskMapper.selectById(88L)).thenReturn(mine);
|
||||
when(fileTaskMapper.selectByIdForUpdate(88L)).thenReturn(mine);
|
||||
when(jdPublishItemMapper.delete(any())).thenReturn(2);
|
||||
|
||||
service.deleteTask(88L, 7L);
|
||||
|
||||
+112
-195
@@ -1,14 +1,12 @@
|
||||
package com.nanri.aiimage.modules.jd.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.MybatisConfiguration;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.baomidou.mybatisplus.core.metadata.TableInfoHelper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
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.ItemResult;
|
||||
import com.nanri.aiimage.modules.jd.model.entity.JdPublishItemEntity;
|
||||
import com.nanri.aiimage.modules.jd.model.vo.JdPublishChunkVo;
|
||||
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
|
||||
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
|
||||
import com.nanri.aiimage.modules.task.service.TaskProgressSnapshotService;
|
||||
@@ -16,7 +14,6 @@ import org.apache.ibatis.builder.MapperBuilderAssistant;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.ArgumentCaptor;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
@@ -27,240 +24,160 @@ import java.util.Map;
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.ArgumentMatchers.anyString;
|
||||
import static org.mockito.ArgumentMatchers.eq;
|
||||
import static org.mockito.Mockito.lenient;
|
||||
import static org.mockito.ArgumentMatchers.isNull;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* v1.5 Phase 2 行级回传测试:R6 单行失败隔离/终态汇总、铁律 31 判死分档(京麦登录态致命、
|
||||
* 匿名拒判死、非致命只记录)、PENDING/终态任务拒收回传。
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class JdPublishIngestServiceTest {
|
||||
private static final long TASK_ID = 34400L;
|
||||
private static final long UID = 7L;
|
||||
|
||||
@Mock
|
||||
private FileTaskMapper fileTaskMapper;
|
||||
@Mock
|
||||
private JdPublishItemMapper jdPublishItemMapper;
|
||||
@Mock
|
||||
private JdPublishStaleTaskService staleTaskService;
|
||||
@Mock
|
||||
private TaskProgressSnapshotService taskProgressSnapshotService;
|
||||
@Mock FileTaskMapper fileTaskMapper;
|
||||
@Mock JdPublishItemMapper jdPublishItemMapper;
|
||||
@Mock JdPublishStaleTaskService staleTaskService;
|
||||
@Mock TaskProgressSnapshotService taskProgressSnapshotService;
|
||||
@InjectMocks JdPublishIngestService service;
|
||||
|
||||
@InjectMocks
|
||||
private JdPublishIngestService service;
|
||||
|
||||
/** Mockito 纯单测无 Spring 环境:LambdaUpdateWrapper 解析 SFunction 需要 TableInfo 缓存(先例 ProgressQueryOwnershipOutletTest)。 */
|
||||
@BeforeAll
|
||||
static void initMybatisPlusTableInfo() {
|
||||
static void initTableInfo() {
|
||||
MapperBuilderAssistant assistant = new MapperBuilderAssistant(new MybatisConfiguration(), "");
|
||||
TableInfoHelper.initTableInfo(assistant, FileTaskEntity.class);
|
||||
TableInfoHelper.initTableInfo(assistant, JdPublishItemEntity.class);
|
||||
}
|
||||
|
||||
private FileTaskEntity runningTask(long taskId) {
|
||||
private FileTaskEntity task(String status, int attempt, int total) {
|
||||
FileTaskEntity task = new FileTaskEntity();
|
||||
task.setId(taskId);
|
||||
task.setId(TASK_ID);
|
||||
task.setUserId(UID);
|
||||
task.setModuleType("JD_PUBLISH");
|
||||
task.setStatus("RUNNING");
|
||||
task.setStatus(status);
|
||||
task.setResumeAttempt(attempt);
|
||||
task.setSourceFileCount(total);
|
||||
when(fileTaskMapper.selectByIdForUpdate(TASK_ID)).thenReturn(task);
|
||||
return task;
|
||||
}
|
||||
|
||||
private ItemResult row(long productId, String status, String error, String wareId) {
|
||||
ItemResult item = new ItemResult();
|
||||
item.setProductId(productId);
|
||||
item.setPublishStatus(status);
|
||||
item.setPublishError(error);
|
||||
item.setJdWareId(wareId);
|
||||
return item;
|
||||
private JdPublishItemEntity row(String status, String batch, Integer attempt) {
|
||||
JdPublishItemEntity row = new JdPublishItemEntity();
|
||||
row.setId(1L);
|
||||
row.setPublishStatus(status);
|
||||
row.setPublishBatchId(batch);
|
||||
row.setPublishResumeAttempt(attempt);
|
||||
when(jdPublishItemMapper.selectOne(any())).thenReturn(row);
|
||||
return row;
|
||||
}
|
||||
|
||||
private void stubCounts(long success, long failed, long pending, long publishing) {
|
||||
when(jdPublishItemMapper.countByPublishStatus(34400L)).thenReturn(List.of(
|
||||
Map.of("publishStatus", "SUCCESS", "cnt", success),
|
||||
Map.of("publishStatus", "FAILED", "cnt", failed),
|
||||
Map.of("publishStatus", "PENDING", "cnt", pending),
|
||||
Map.of("publishStatus", "PUBLISHING", "cnt", publishing)));
|
||||
private static JdPublishChunkRequest request(int attempt, String batch, String status, String evidence) {
|
||||
JdPublishChunkRequest request = new JdPublishChunkRequest();
|
||||
request.setResumeAttempt(attempt);
|
||||
request.setBatchId(batch);
|
||||
if (status != null) {
|
||||
ItemResult item = new ItemResult();
|
||||
item.setItemId(1L);
|
||||
item.setProductId(101L);
|
||||
item.setPublishStatus(status);
|
||||
if ("SUCCESS".equals(status)) {
|
||||
item.setJdWareId(evidence);
|
||||
} else {
|
||||
item.setPublishError(evidence);
|
||||
}
|
||||
request.setItems(List.of(item));
|
||||
}
|
||||
return request;
|
||||
}
|
||||
|
||||
private void counts(String status, long count) {
|
||||
when(jdPublishItemMapper.countByPublishStatus(TASK_ID)).thenReturn(
|
||||
List.of(Map.of("publishStatus", status, "cnt", count)));
|
||||
}
|
||||
|
||||
@Test
|
||||
void 行级回传SUCCESS落库并带wareId() {
|
||||
when(fileTaskMapper.selectById(34400L)).thenReturn(runningTask(34400L));
|
||||
stubCounts(0, 0, 1, 0);
|
||||
when(jdPublishItemMapper.update(any(), any(LambdaUpdateWrapper.class))).thenReturn(1);
|
||||
|
||||
JdPublishChunkRequest request = new JdPublishChunkRequest();
|
||||
request.setBatchId("PUB-0001");
|
||||
request.setItems(List.of(row(101L, "SUCCESS", null, "10036498117800")));
|
||||
|
||||
JdPublishChunkVo vo = service.submitChunk(34400L, request, true);
|
||||
|
||||
assertThat(vo.getAcceptedCount()).isEqualTo(1);
|
||||
ArgumentCaptor<LambdaUpdateWrapper> captor = ArgumentCaptor.forClass(LambdaUpdateWrapper.class);
|
||||
verify(jdPublishItemMapper).update(any(), captor.capture());
|
||||
String sqlSet = captor.getValue().getSqlSet();
|
||||
assertThat(sqlSet).as("行级状态与 wareId 两列一起落库")
|
||||
.contains("publish_status").contains("jd_ware_id");
|
||||
assertThat(captor.getValue().getParamNameValuePairs().values())
|
||||
.extracting(String::valueOf)
|
||||
.as("行级值:状态 + wareId").contains("SUCCESS", "10036498117800");
|
||||
assertThat(vo.getTaskStatus()).as("未带 isEnd 不落终态").isNull();
|
||||
void 旧代回执及异主请求都不接触明细() {
|
||||
task("RUNNING", 1, 1);
|
||||
assertThatThrownBy(() -> service.submitChunk(TASK_ID, request(0, "old", "FAILED", "失败"), UID))
|
||||
.isInstanceOf(BusinessException.class).extracting("code").isEqualTo(409);
|
||||
assertThatThrownBy(() -> service.submitChunk(TASK_ID, request(1, "other", null, null), 8L))
|
||||
.isInstanceOf(BusinessException.class).extracting("code").isEqualTo(403);
|
||||
verifyNoInteractions(jdPublishItemMapper, staleTaskService);
|
||||
}
|
||||
|
||||
@Test
|
||||
void 行级FAILED带真实原因落库() {
|
||||
when(fileTaskMapper.selectById(34400L)).thenReturn(runningTask(34400L));
|
||||
stubCounts(0, 0, 1, 0);
|
||||
when(jdPublishItemMapper.update(any(), any(LambdaUpdateWrapper.class))).thenReturn(1);
|
||||
|
||||
JdPublishChunkRequest request = new JdPublishChunkRequest();
|
||||
request.setItems(List.of(row(101L, "FAILED", "类目不在授权树内", null)));
|
||||
|
||||
JdPublishChunkVo vo = service.submitChunk(34400L, request, true);
|
||||
|
||||
assertThat(vo.getAcceptedCount()).isEqualTo(1);
|
||||
ArgumentCaptor<LambdaUpdateWrapper> captor = ArgumentCaptor.forClass(LambdaUpdateWrapper.class);
|
||||
verify(jdPublishItemMapper).update(any(), captor.capture());
|
||||
assertThat(captor.getValue().getParamNameValuePairs().values())
|
||||
.extracting(String::valueOf)
|
||||
.as("R6:失败行落真实原因,不伪造成功").contains("FAILED", "类目不在授权树内");
|
||||
void 已领取发布许可仅原代原批可重复确认() {
|
||||
task("RUNNING", 1, 1);
|
||||
row("PUBLISHING", "batchA", 1);
|
||||
assertThat(service.submitChunk(TASK_ID, request(1, "batchB", "PUBLISHING", null), UID).getAcceptedCount()).isZero();
|
||||
assertThat(service.submitChunk(TASK_ID, request(1, "batchA", "PUBLISHING", null), UID).getAcceptedCount()).isOne();
|
||||
verify(jdPublishItemMapper, never()).update(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void 不识别的行状态跳过不炸批() {
|
||||
when(fileTaskMapper.selectById(34400L)).thenReturn(runningTask(34400L));
|
||||
stubCounts(0, 0, 2, 0);
|
||||
when(jdPublishItemMapper.update(any(), any(LambdaUpdateWrapper.class))).thenReturn(1);
|
||||
|
||||
JdPublishChunkRequest request = new JdPublishChunkRequest();
|
||||
request.setItems(List.of(row(101L, "PENDING", null, null), row(102L, "SUCCESS", null, "w1")));
|
||||
|
||||
JdPublishChunkVo vo = service.submitChunk(34400L, request, true);
|
||||
|
||||
assertThat(vo.getAcceptedCount()).as("PENDING 不可回传写回,只有 SUCCESS 行被接受").isEqualTo(1);
|
||||
void 首次许可及持有者的确定失败分别写库() {
|
||||
task("RUNNING", 1, 1);
|
||||
JdPublishItemEntity row = row("PENDING", null, null);
|
||||
when(jdPublishItemMapper.update(isNull(), any())).thenReturn(1);
|
||||
assertThat(service.submitChunk(TASK_ID, request(1, "batchA", "PUBLISHING", null), UID).getAcceptedCount()).isOne();
|
||||
row.setPublishStatus("PUBLISHING");
|
||||
row.setPublishBatchId("batchA");
|
||||
row.setPublishResumeAttempt(1);
|
||||
assertThat(service.submitChunk(TASK_ID, request(1, "batchA", "FAILED", "京麦明确拒绝"), UID).getAcceptedCount()).isOne();
|
||||
}
|
||||
|
||||
@Test
|
||||
void isEnd全成功任务落SUCCESS() {
|
||||
when(fileTaskMapper.selectById(34400L)).thenReturn(runningTask(34400L));
|
||||
stubCounts(3, 0, 0, 0);
|
||||
when(jdPublishItemMapper.update(any(), any(LambdaUpdateWrapper.class))).thenReturn(1);
|
||||
when(fileTaskMapper.update(any(), any(LambdaUpdateWrapper.class))).thenReturn(1);
|
||||
void 旧代许可不能在新代被同一批次重新确认或转失败() {
|
||||
task("RUNNING", 2, 1);
|
||||
row("PUBLISHING", "batchA", 1);
|
||||
assertThat(service.submitChunk(TASK_ID, request(2, "batchA", "PUBLISHING", null), UID).getAcceptedCount()).isZero();
|
||||
assertThat(service.submitChunk(TASK_ID, request(2, "batchA", "FAILED", "京麦明确拒绝"), UID).getAcceptedCount()).isZero();
|
||||
verify(jdPublishItemMapper, never()).update(any(), any());
|
||||
}
|
||||
|
||||
JdPublishChunkRequest request = new JdPublishChunkRequest();
|
||||
@Test
|
||||
void SUCCESS仅允许精确重放而不可覆盖() {
|
||||
task("SUCCESS", 1, 1);
|
||||
row("SUCCESS", "batchA", 1).setJdWareId("w1");
|
||||
assertThat(service.submitChunk(TASK_ID, request(1, "batchA", "SUCCESS", "w1"), UID).getAcceptedCount()).isOne();
|
||||
assertThat(service.submitChunk(TASK_ID, request(1, "batchA", "SUCCESS", "w2"), UID).getAcceptedCount()).isZero();
|
||||
verify(jdPublishItemMapper, never()).update(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void 未决或零行不得收尾() {
|
||||
task("RUNNING", 1, 1);
|
||||
JdPublishChunkRequest request = request(1, "batchA", null, null);
|
||||
request.setIsEnd(true);
|
||||
request.setItems(List.of(row(103L, "SUCCESS", null, "w3")));
|
||||
|
||||
JdPublishChunkVo vo = service.submitChunk(34400L, request, true);
|
||||
|
||||
assertThat(vo.getTaskStatus()).isEqualTo("SUCCESS");
|
||||
ArgumentCaptor<LambdaUpdateWrapper> captor = ArgumentCaptor.forClass(LambdaUpdateWrapper.class);
|
||||
verify(fileTaskMapper).update(any(), captor.capture());
|
||||
String sqlSet = captor.getValue().getSqlSet();
|
||||
assertThat(sqlSet).as("任务终态列:状态 + 真实行数两列")
|
||||
.contains("status").contains("success_file_count");
|
||||
assertThat(captor.getValue().getParamNameValuePairs().values())
|
||||
.extracting(String::valueOf)
|
||||
.as("AC-6:任务终态汇总真实行数").contains("SUCCESS");
|
||||
verify(taskProgressSnapshotService).markTerminal(eq(34400L), eq("JD_PUBLISH"), eq("SUCCESS"), any());
|
||||
assertThat(service.submitChunk(TASK_ID, request, UID).getTaskStatus()).isEqualTo("RUNNING");
|
||||
counts("PUBLISHING", 1);
|
||||
var pending = service.submitChunk(TASK_ID, request, UID);
|
||||
assertThat(pending.getTaskStatus()).isEqualTo("RUNNING");
|
||||
assertThat(pending.isNeedsReview()).isTrue();
|
||||
assertThat(pending.getPublishingCount()).isOne();
|
||||
verify(fileTaskMapper, never()).update(any(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void isEnd有失败行任务落FAILED并汇总() {
|
||||
when(fileTaskMapper.selectById(34400L)).thenReturn(runningTask(34400L));
|
||||
stubCounts(2, 1, 0, 0);
|
||||
when(fileTaskMapper.update(any(), any(LambdaUpdateWrapper.class))).thenReturn(1);
|
||||
|
||||
JdPublishChunkRequest request = new JdPublishChunkRequest();
|
||||
void 非零且全部已处理才汇总失败() {
|
||||
task("RUNNING", 1, 1);
|
||||
counts("FAILED", 1);
|
||||
when(fileTaskMapper.update(isNull(), any())).thenReturn(1);
|
||||
JdPublishChunkRequest request = request(1, "batchA", null, null);
|
||||
request.setIsEnd(true);
|
||||
request.setItems(List.of());
|
||||
|
||||
JdPublishChunkVo vo = service.submitChunk(34400L, request, true);
|
||||
|
||||
assertThat(vo.getTaskStatus()).isEqualTo("FAILED");
|
||||
ArgumentCaptor<LambdaUpdateWrapper> captor = ArgumentCaptor.forClass(LambdaUpdateWrapper.class);
|
||||
verify(fileTaskMapper).update(any(), captor.capture());
|
||||
assertThat(captor.getValue().getParamNameValuePairs().values())
|
||||
.extracting(String::valueOf)
|
||||
.as("R6:任务终态汇总成败数(文案带真实行数)")
|
||||
.contains("FAILED", "发布完成:成功 2 行,失败 1 行");
|
||||
assertThat(service.submitChunk(TASK_ID, request, UID).getTaskStatus()).isEqualTo("FAILED");
|
||||
verify(taskProgressSnapshotService).markTerminal(TASK_ID, "JD_PUBLISH", "FAILED", "发布完成:成功 0 行,失败 1 行");
|
||||
}
|
||||
|
||||
@Test
|
||||
void PENDING任务拒收回传点名激活() {
|
||||
FileTaskEntity task = runningTask(34400L);
|
||||
task.setStatus("PENDING");
|
||||
when(fileTaskMapper.selectById(34400L)).thenReturn(task);
|
||||
assertThatThrownBy(() -> service.submitChunk(34400L, new JdPublishChunkRequest(), true))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("任务不在运行中");
|
||||
verify(jdPublishItemMapper, never()).update(any(), any(LambdaUpdateWrapper.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void 终态任务拒收回传() {
|
||||
FileTaskEntity task = runningTask(34400L);
|
||||
task.setStatus("SUCCESS");
|
||||
when(fileTaskMapper.selectById(34400L)).thenReturn(task);
|
||||
assertThatThrownBy(() -> service.submitChunk(34400L, new JdPublishChunkRequest(), true))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("任务已结束");
|
||||
}
|
||||
|
||||
@Test
|
||||
void 京麦登录态致命可信上报判死() {
|
||||
when(fileTaskMapper.selectById(34400L)).thenReturn(runningTask(34400L));
|
||||
stubCounts(0, 0, 1, 0);
|
||||
when(staleTaskService.terminalizeOnJdLoginFatal(any(), anyString())).thenReturn(true);
|
||||
|
||||
JdPublishChunkRequest request = new JdPublishChunkRequest();
|
||||
request.setError("发布页跳回登录页,京麦未登录");
|
||||
|
||||
JdPublishChunkVo vo = service.submitChunk(34400L, request, true);
|
||||
|
||||
assertThat(vo.getTaskStatus()).as("铁律 31:凭据不可自愈 ⇒ 整单 FAILED").isEqualTo("FAILED");
|
||||
verify(staleTaskService).terminalizeOnJdLoginFatal(any(), eq("发布页跳回登录页,京麦未登录"));
|
||||
verify(jdPublishItemMapper, never()).update(any(), any(LambdaUpdateWrapper.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void 匿名error上报拒绝判死() {
|
||||
when(fileTaskMapper.selectById(34400L)).thenReturn(runningTask(34400L));
|
||||
stubCounts(0, 0, 1, 0);
|
||||
|
||||
JdPublishChunkRequest request = new JdPublishChunkRequest();
|
||||
void 登录失效必须先写真实失败行才可判死() {
|
||||
FileTaskEntity task = task("RUNNING", 1, 2);
|
||||
JdPublishChunkRequest request = request(1, "batchA", null, null);
|
||||
request.setError("京麦未登录");
|
||||
|
||||
JdPublishChunkVo vo = service.submitChunk(34400L, request, false);
|
||||
|
||||
assertThat(vo.getTaskStatus()).as("判死口凭据化:匿名一律拒绝判死").isNull();
|
||||
verify(staleTaskService, never()).terminalizeOnJdLoginFatal(any(), anyString());
|
||||
verify(fileTaskMapper, never()).update(any(), any(LambdaUpdateWrapper.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void 非致命技术故障只记录不判死() {
|
||||
when(fileTaskMapper.selectById(34400L)).thenReturn(runningTask(34400L));
|
||||
stubCounts(0, 0, 1, 0);
|
||||
|
||||
JdPublishChunkRequest request = new JdPublishChunkRequest();
|
||||
request.setError("页面结构变更,发布按钮定位失败");
|
||||
|
||||
JdPublishChunkVo vo = service.submitChunk(34400L, request, true);
|
||||
|
||||
assertThat(vo.getTaskStatus()).as("技术性故障只补测不判死(R5 分档)").isNull();
|
||||
verify(staleTaskService, never()).terminalizeOnJdLoginFatal(any(), anyString());
|
||||
verify(fileTaskMapper, never()).update(any(), any(LambdaUpdateWrapper.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void 任务不存在拒收回传() {
|
||||
when(fileTaskMapper.selectById(99999L)).thenReturn(null);
|
||||
assertThatThrownBy(() -> service.submitChunk(99999L, new JdPublishChunkRequest(), true))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("任务不存在");
|
||||
assertThat(service.submitChunk(TASK_ID, request, UID).getTaskStatus()).isNull();
|
||||
verifyNoInteractions(staleTaskService);
|
||||
row("PENDING", null, null);
|
||||
when(jdPublishItemMapper.update(isNull(), any())).thenReturn(1);
|
||||
when(staleTaskService.terminalizeOnJdLoginFatal(task, "京麦未登录")).thenReturn(true);
|
||||
assertThat(service.submitChunk(TASK_ID, request(1, "batchA", "FAILED", "京麦未登录"), UID).getTaskStatus()).isEqualTo("FAILED");
|
||||
}
|
||||
}
|
||||
|
||||
+3
-2
@@ -45,7 +45,7 @@ class JdPublishTaskItemsResetSpiImplTest {
|
||||
}
|
||||
|
||||
@Test
|
||||
void 复位只圈FAILED与PUBLISHING行_清旧错误文案_不碰SUCCESS() {
|
||||
void 复位只圈确定FAILED行_不碰SUCCESS或结果未知的PUBLISHING() {
|
||||
JdPublishItemMapper mapper = mock(JdPublishItemMapper.class);
|
||||
when(mapper.update(isNull(), any())).thenReturn(3);
|
||||
|
||||
@@ -67,7 +67,8 @@ class JdPublishTaskItemsResetSpiImplTest {
|
||||
assertEquals(34567L, UpdateWrapperProbe.whereEq(wrapper).get("task_id"));
|
||||
Map<String, Object> params = UpdateWrapperProbe.paramNameValuePairs(wrapper);
|
||||
assertTrue(params.containsValue("FAILED"), "行状态谓词必须含 FAILED");
|
||||
assertTrue(params.containsValue("PUBLISHING"), "行状态谓词必须含 PUBLISHING(中断遗留行)");
|
||||
assertTrue(!params.containsValue("PUBLISHING"), "结果未知的 PUBLISHING 绝不能重新发布");
|
||||
assertTrue(!params.containsValue("SUCCESS"), "已发布商品绝不能重新发布");
|
||||
assertTrue(params.containsValue("PENDING"), "复位目标值在参数册");
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -286,7 +286,7 @@ class JdPublishTaskServiceTest {
|
||||
when(jdProductSkuMapper.selectList(any())).thenReturn(List.of());
|
||||
when(jdProductImageMapper.selectList(any())).thenReturn(List.of());
|
||||
|
||||
var vo = service.pullItems(34400L, 7L, 0L, null);
|
||||
var vo = service.pullItems(34400L, 7L, 0, 0L, null);
|
||||
|
||||
assertThat(vo.getTaskId()).isEqualTo(34400L);
|
||||
assertThat(vo.getItems()).hasSize(1);
|
||||
@@ -304,7 +304,7 @@ class JdPublishTaskServiceTest {
|
||||
task.setUserId(8L);
|
||||
task.setStatus("RUNNING");
|
||||
when(fileTaskMapper.selectById(34400L)).thenReturn(task);
|
||||
assertThatThrownBy(() -> service.pullItems(34400L, 7L, 0L, null))
|
||||
assertThatThrownBy(() -> service.pullItems(34400L, 7L, 0, 0L, null))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.extracting("code")
|
||||
.isEqualTo(403);
|
||||
|
||||
+13
@@ -98,6 +98,19 @@ class TaskClientPullServiceTest {
|
||||
any(LocalDateTime.class), eq(5));
|
||||
}
|
||||
|
||||
@Test
|
||||
void 京东发布能力在SQL取页以前生效且不影响其他任务() {
|
||||
TaskClientPullService service = service(new StubHandler("SIMILAR_ASIN", payload("similar-asin-run")));
|
||||
ReflectionTestUtils.setField(service, "moduleTypes", "JD_PUBLISH,SIMILAR_ASIN");
|
||||
service.pullPendingTasks(USER_ID);
|
||||
service.pullPendingTasks(USER_ID, true);
|
||||
|
||||
verify(fileTaskMapper).selectLocalChannelPendingTasks(eq(USER_ID), eq("PENDING"),
|
||||
eq(List.of("SIMILAR_ASIN")), eq(CollectChannel.localDefaultModuleTypes()), any(), eq(5));
|
||||
verify(fileTaskMapper).selectLocalChannelPendingTasks(eq(USER_ID), eq("PENDING"),
|
||||
eq(List.of("JD_PUBLISH", "SIMILAR_ASIN")), eq(CollectChannel.localDefaultModuleTypes()), any(), eq(5));
|
||||
}
|
||||
|
||||
@Test
|
||||
void 页面抢先认领后不再返回任务() {
|
||||
stubPullCandidates(task(11L, "SIMILAR_ASIN"));
|
||||
|
||||
@@ -8,7 +8,6 @@ import {
|
||||
type JdCollectGroupVo,
|
||||
} from '@/shared/api/types/modules/jd-collect'
|
||||
import {
|
||||
activateJdPublishTask,
|
||||
createJdPublishTask,
|
||||
deleteJdPublishTask,
|
||||
fetchJdPublishDashboard,
|
||||
@@ -35,12 +34,9 @@ import NotificationBell from '@/shared/components/NotificationBell.vue'
|
||||
* 当前登录用户的行),页内翻页、勾选跨页累计;
|
||||
* 2. 改价规则三档(none/percent/fixed,蓝图 §3 死契约),与勾选集一起进建单体;服务端按
|
||||
* 同一规则折算 SKU 价(铁律 27a 改价同源);
|
||||
* 3. 建单成功把服务端下发的 queuePayload(type=jd-product-publish-run,铁律 32 第三件)原样
|
||||
* 推进本机客户端队列;激活(PENDING→RUNNING)必须在推队列之前(2026-11-14 采集链真机
|
||||
* 实录同因);推送失败不回滚建单(兜底拉取认领);
|
||||
* 3. 网页原样转交建单响应的 queuePayload;认领只由客户端与后端完成,投递失败仍可由客户端拉取;
|
||||
* 4. 进度只读服务端:行级四档计数来自发布明细表聚合,total 缺失时只报已发布行数,不编造百分比;
|
||||
* 5. 失败/中断「重试/继续」走通用原位复位(铁律 26,不克隆),推送载荷从历史行的建单载荷
|
||||
* (分类 id+改价规则)同源重建——与建单响应 queuePayload 同键同形状;
|
||||
* 5. 失败/中断「重试/继续」走通用原位复位(铁律 26,不克隆),新一轮由客户端拉取认领;
|
||||
* 6. 京麦未登录等凭据致命失败(铁律 31):服务端整单判死后 useLiveTaskBoard 经
|
||||
* reportCredentialFatal 弹一次窗(credential-fatal 同形接入,AC-5 用户端半边;弹窗组件
|
||||
* 挂 App.vue,本页无需重复挂)。
|
||||
@@ -85,8 +81,22 @@ const productTotal = ref(0)
|
||||
const productPage = ref(1)
|
||||
const productsLoading = ref(false)
|
||||
const selectedProducts = ref(new Map<number, JdPublishProductVo>())
|
||||
let productRequest = 0
|
||||
|
||||
const selectedProductIds = computed(() => Array.from(selectedProducts.value.keys()))
|
||||
const wholePageSelected = computed(() => products.value.length > 0
|
||||
&& products.value.every((row) => selectedProducts.value.has(row.id)))
|
||||
const partOfPageSelected = computed(() => !wholePageSelected.value
|
||||
&& products.value.some((row) => selectedProducts.value.has(row.id)))
|
||||
|
||||
function togglePage(checked: boolean) {
|
||||
const next = new Map(selectedProducts.value)
|
||||
for (const row of products.value) {
|
||||
if (checked) next.set(row.id, row)
|
||||
else next.delete(row.id)
|
||||
}
|
||||
selectedProducts.value = next
|
||||
}
|
||||
|
||||
function toggleProduct(row: JdPublishProductVo, checked: boolean) {
|
||||
const next = new Map(selectedProducts.value)
|
||||
@@ -100,18 +110,35 @@ function clearSelection() {
|
||||
}
|
||||
|
||||
async function loadProducts() {
|
||||
const request = ++productRequest
|
||||
products.value = []
|
||||
if (selectedGroupId.value == null) {
|
||||
productTotal.value = 0
|
||||
productsLoading.value = false
|
||||
return
|
||||
}
|
||||
productsLoading.value = true
|
||||
try {
|
||||
const vo = await fetchJdPublishProducts(selectedGroupId.value, productPage.value, PRODUCT_PAGE_SIZE)
|
||||
if (request !== productRequest) return
|
||||
products.value = vo.items ?? []
|
||||
productTotal.value = vo.total ?? 0
|
||||
} catch (err) {
|
||||
errorMessage.value = err instanceof Error ? err.message : '商品列表拉取失败,请稍后重试'
|
||||
if (request === productRequest) {
|
||||
errorMessage.value = err instanceof Error ? err.message : '商品列表拉取失败,请稍后重试'
|
||||
}
|
||||
} finally {
|
||||
productsLoading.value = false
|
||||
if (request === productRequest) productsLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function changeGroup() {
|
||||
productPage.value = 1
|
||||
productTotal.value = 0
|
||||
clearSelection()
|
||||
void loadProducts()
|
||||
}
|
||||
|
||||
function changePage(page: number) {
|
||||
productPage.value = page
|
||||
void loadProducts()
|
||||
@@ -134,12 +161,54 @@ const submitDisabled = computed(() =>
|
||||
|| !selectedProducts.value.size
|
||||
|| priceValueMissing.value)
|
||||
|
||||
// 重试回执不带代数:旧代 + 1 只用作读侧下限,不生成任务或队列数据。
|
||||
const retryAttemptFloor = new Map<number, number>()
|
||||
const awaitingRetryProgress = new Set<number>()
|
||||
const retryingTaskIds = ref(new Set<number>())
|
||||
|
||||
function acceptsAttempt(taskId: number | undefined, attempt: number | undefined) {
|
||||
const floor = taskId == null ? undefined : retryAttemptFloor.get(taskId)
|
||||
return floor == null || (attempt != null && attempt >= floor)
|
||||
}
|
||||
|
||||
async function fetchCurrentHistory(): ReturnType<typeof fetchJdPublishHistory> {
|
||||
const history = await fetchJdPublishHistory()
|
||||
return {
|
||||
...history,
|
||||
items: history.items.flatMap((item): JdPublishHistoryItemVo[] => {
|
||||
if (acceptsAttempt(item.taskId, item.resumeAttempt)) return [item]
|
||||
const current = board.historyItems.value.find((row) => row.taskId === item.taskId)
|
||||
return current && acceptsAttempt(current.taskId, current.resumeAttempt) ? [current] : []
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchCurrentProgress(taskIds: number[], { force }: { force: boolean }) {
|
||||
const floorsAtRequest = new Map(taskIds.map((id) => [id, retryAttemptFloor.get(id)]))
|
||||
const unchanged = (id: number) => !retryingTaskIds.value.has(id)
|
||||
&& retryAttemptFloor.get(id) === floorsAtRequest.get(id)
|
||||
const batch = await fetchJdPublishTaskProgressBatch(taskIds, {
|
||||
force: force || taskIds.some((id) => awaitingRetryProgress.has(id)),
|
||||
})
|
||||
return {
|
||||
...batch,
|
||||
items: batch.items.filter(({ task, items }) => {
|
||||
if (task?.id == null || !unchanged(task.id) || !acceptsAttempt(task.id, task.resumeAttempt)) return false
|
||||
const row = items?.[0]
|
||||
if (row && !acceptsAttempt(task.id, row.resumeAttempt)) return false
|
||||
awaitingRetryProgress.delete(task.id)
|
||||
return true
|
||||
}),
|
||||
missingTaskIds: batch.missingTaskIds.filter(unchanged),
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 实时任务面板(照 JdCollectTab 的 useLiveTaskBoard 形状;京东发布无结果文件,无下载层)----
|
||||
const board = useLiveTaskBoard<JdPublishHistoryItemVo>({
|
||||
scope: 'jd-publish',
|
||||
pollingStorageKey: () => `jd-publish:tasks:${uidForStorage()}`,
|
||||
fetchHistory: fetchJdPublishHistory,
|
||||
fetchProgressBatch: fetchJdPublishTaskProgressBatch,
|
||||
fetchHistory: fetchCurrentHistory,
|
||||
fetchProgressBatch: fetchCurrentProgress,
|
||||
fetchDashboard: fetchJdPublishDashboard,
|
||||
normalizeTaskStatus,
|
||||
// 京东发布没有结果文件:状态到终态即结束,没有「等文件」那一层
|
||||
@@ -291,25 +360,23 @@ async function interruptTaskRecord(item: JdPublishHistoryItemVo | null | undefin
|
||||
|
||||
async function retryTaskRecord(item: JdPublishHistoryItemVo | null | undefined) {
|
||||
const taskId = item?.taskId
|
||||
if (!taskId) return
|
||||
if (!taskId || retryingTaskIds.value.has(taskId)) return
|
||||
const isResume = normalizeTaskStatus(item) === 'CANCELLED'
|
||||
try {
|
||||
await retryClientTask(taskId)
|
||||
ElMessage.success(isResume
|
||||
? '已继续:在这条任务上接着跑(已成功的商品不会重复发布)'
|
||||
: '已提交重试:在这条任务上继续跑(不新建任务)')
|
||||
// 复位是 PENDING:与建单同一条激活+推队列链路,客户端才会立刻领到这一单。
|
||||
const activateError = await activateTask(taskId)
|
||||
if (!activateError) {
|
||||
const priceRule = item?.priceRule && item.priceRule.mode ? item.priceRule : { mode: 'none' }
|
||||
// 推送载荷从历史行的建单载荷同源重建(与建单响应 queuePayload 同键:type/taskId/priceRule)。
|
||||
await pushToClientQueue({ type: 'jd-product-publish-run', data: { taskId, priceRule } })
|
||||
}
|
||||
board.addPollingTask(taskId)
|
||||
await refreshBoard()
|
||||
} catch (error) {
|
||||
retryingTaskIds.value.add(taskId)
|
||||
const retried = await retryClientTask(taskId).then(() => true, (error: unknown) => {
|
||||
ElMessage.error(error instanceof Error ? error.message : '重试失败')
|
||||
}
|
||||
return false
|
||||
})
|
||||
retryingTaskIds.value.delete(taskId)
|
||||
if (!retried) return
|
||||
|
||||
retryAttemptFloor.set(taskId, (item.resumeAttempt ?? 0) + 1)
|
||||
awaitingRetryProgress.add(taskId)
|
||||
board.removePollingTask(taskId)
|
||||
board.historyItems.value = board.historyItems.value.filter((row) => row.taskId !== taskId)
|
||||
board.addPollingTask(taskId)
|
||||
ElMessage.success(isResume ? '已提交继续,等待本机客户端领取' : '已提交原任务重试,等待本机客户端领取')
|
||||
await refreshBoard().catch((error) => console.error('[jd-publish] 重试后刷新任务失败', error))
|
||||
}
|
||||
|
||||
/** 手动刷新:强拉历史 + 统计 + 当前轮询任务进度 */
|
||||
@@ -321,38 +388,21 @@ async function refreshBoard() {
|
||||
])
|
||||
}
|
||||
|
||||
/** 激活任务(PENDING→RUNNING),返回 null 表示可推队列,返回 string 表示失败原因。
|
||||
* 漏掉这一步,客户端第一个回传会被「任务不在运行中(PENDING)」拒收(采集链真机实录同因)。 */
|
||||
async function activateTask(id: number): Promise<string | null> {
|
||||
try {
|
||||
await activateJdPublishTask(id)
|
||||
return null
|
||||
} catch (err) {
|
||||
const text = err instanceof Error ? err.message : ''
|
||||
// 客户端兜底拉取已原子认领(PENDING→RUNNING)时后端回这句:等同激活成功,不当失败展示。
|
||||
if (text.includes('已在执行中')) {
|
||||
return null
|
||||
}
|
||||
console.error('[jd-publish] 激活任务失败', err)
|
||||
return '任务激活失败,本机客户端领不到这一单,请稍后重试'
|
||||
}
|
||||
}
|
||||
const WAIT_FOR_CLIENT = '任务已创建,等待本机客户端领取。请保持客户端在线。'
|
||||
|
||||
/** 推送本机队列:建单路径传服务端下发的 queuePayload(页面不拼载荷),重试路径按同键形状重建后传入。 */
|
||||
async function pushToClientQueue(payload: Record<string, unknown>): Promise<string | null> {
|
||||
async function pushToClientQueue(payload: Record<string, unknown> | undefined): Promise<string | null> {
|
||||
if (!payload) return WAIT_FOR_CLIENT
|
||||
const api = getPywebviewApi()
|
||||
if (!api?.enqueue_json) {
|
||||
return '当前环境未启用任务队列能力(浏览器预览环境不会启动),请在本机客户端中打开本页'
|
||||
return '任务已创建,等待本机客户端领取。请打开本机客户端并登录同一账号。'
|
||||
}
|
||||
const pushResult = await api.enqueue_json(payload)
|
||||
if (pushResult?.success) {
|
||||
const result = await api.enqueue_json(payload).catch((error) => {
|
||||
console.error('[jd-publish] 推送本机队列失败', error)
|
||||
return null
|
||||
}
|
||||
// 桥返回的 error 原文(系统/英文)不透传进界面:console 留链,界面固定中文动作句
|
||||
if (pushResult?.error) {
|
||||
console.error('[jd-publish] enqueue_json 被拒', pushResult.error)
|
||||
}
|
||||
return '推送本机队列失败,任务将由客户端兜底拉取认领'
|
||||
})
|
||||
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)
|
||||
@@ -378,29 +428,11 @@ async function startPublish() {
|
||||
const productIds = selectedProductIds.value
|
||||
const vo = await createJdPublishTask(categoryId, productIds, priceRule)
|
||||
board.addPollingTask(vo.taskId)
|
||||
let pushNote = ''
|
||||
const activateError = await activateTask(vo.taskId)
|
||||
if (activateError) {
|
||||
// 没激活成功就不推队列:推了也是白跑一轮。任务留在 PENDING,
|
||||
// 由服务端兜底拉取认领后照样会跑,所以这里只提示、不回滚建单。
|
||||
pushNote = activateError
|
||||
} else {
|
||||
try {
|
||||
// 建单响应自带 queuePayload(服务端组装,铁律 32 第三件),页面原样投递。
|
||||
const pushError = await pushToClientQueue(vo.queuePayload
|
||||
?? { type: 'jd-product-publish-run', data: { taskId: vo.taskId, priceRule } })
|
||||
if (pushError) pushNote = pushError
|
||||
} catch (pushErr) {
|
||||
pushNote = '推送本机队列失败,任务将由服务端兜底派发给本机客户端执行'
|
||||
console.error('[jd-publish] 推送本机队列失败', pushErr)
|
||||
}
|
||||
}
|
||||
if (pushNote) {
|
||||
errorMessage.value = pushNote
|
||||
} else {
|
||||
successMessage.value = `任务已创建(${productIds.length} 个商品)并推送给本机客户端,进度显示在右侧任务区`
|
||||
}
|
||||
const pushNote = await pushToClientQueue(vo.queuePayload)
|
||||
successMessage.value = pushNote
|
||||
?? `任务已创建(${productIds.length} 个商品)并送入本机队列,等待客户端领取。`
|
||||
await Promise.all([board.loadDashboard(), board.loadHistory({ force: true })])
|
||||
.catch((error) => console.error('[jd-publish] 建单后刷新任务失败', error))
|
||||
} catch (err) {
|
||||
errorMessage.value = err instanceof Error ? err.message : '建单失败,请稍后重试'
|
||||
} finally {
|
||||
@@ -458,7 +490,7 @@ onUnmounted(() => {
|
||||
<div class="category-block">
|
||||
<span class="category-label">自定义分类</span>
|
||||
<el-select v-model="selectedGroupId" placeholder="选择分类" class="shop-cat-select"
|
||||
:loading="groupsLoading" @change="() => { productPage = 1; clearSelection(); void loadProducts() }">
|
||||
:loading="groupsLoading" @change="changeGroup">
|
||||
<el-option v-for="group in groupOptions" :key="group.id"
|
||||
:label="`${group.name}(${group.productCount ?? 0} 个商品)`" :value="group.id" />
|
||||
</el-select>
|
||||
@@ -468,6 +500,12 @@ onUnmounted(() => {
|
||||
<div class="product-block" v-loading="productsLoading">
|
||||
<div class="product-head">
|
||||
<span class="category-label">选择商品(已选 {{ selectedProducts.size }} 个,跨页累计)</span>
|
||||
<label v-if="products.length" class="category-hint">
|
||||
<input type="checkbox" class="product-select-page" :checked="wholePageSelected"
|
||||
:indeterminate.prop="partOfPageSelected"
|
||||
@change="togglePage(($event.target as HTMLInputElement).checked)" />
|
||||
全选本页
|
||||
</label>
|
||||
<button v-if="selectedProducts.size" class="shop-cat-clear" type="button"
|
||||
@click="clearSelection">清空勾选</button>
|
||||
</div>
|
||||
|
||||
@@ -226,12 +226,10 @@ export const API_ENDPOINTS = {
|
||||
/** 删除任务(连带清理京东数据库该任务的商品/图片/SKU 行与断点游标) */
|
||||
deleteTask: '/api/jd-collect/tasks/{taskId}',
|
||||
},
|
||||
/** 京东商品上架(v1.5 Phase 4):用户端建单/激活/选品/面板;派发载荷 type=jd-product-publish-run 由服务端下发 */
|
||||
/** 京东商品上架:用户端建单/选品/面板;派发载荷由服务端下发,认领只由客户端和后端完成。 */
|
||||
jdPublish: {
|
||||
/** 建单(请求体 categoryId+productIds+priceRule,响应带 queuePayload 页面直推) */
|
||||
create: '/api/jd-publish/tasks',
|
||||
/** 激活(PENDING→RUNNING):推客户端队列之前必须调用(2026-11-14 采集链真机实录同因) */
|
||||
activate: '/api/jd-publish/tasks/{taskId}/activate',
|
||||
/** 用户端选品分页(AC-9 owner 过滤:只回归属当前用户的京东数据库商品行) */
|
||||
products: '/api/jd-publish/products',
|
||||
/** 任务面板总览(运行中/成功/失败计数统计卡) */
|
||||
|
||||
@@ -20,7 +20,7 @@ export interface JdPublishTaskVo {
|
||||
taskId: number;
|
||||
taskNo?: string;
|
||||
collectChannel?: string;
|
||||
/** {type:'jd-product-publish-run', data:{taskId, priceRule}}(铁律 32 第三件) */
|
||||
/** 服务端完整载荷,包含任务代数;网页只转交,不读取或重建 data。 */
|
||||
queuePayload?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
@@ -52,13 +52,6 @@ export function createJdPublishTask(
|
||||
))
|
||||
}
|
||||
|
||||
/** 激活任务(PENDING→RUNNING):推客户端队列之前必须调用(漏掉=分片全被拒,采集链真机实录同因)。 */
|
||||
export function activateJdPublishTask(taskId: number) {
|
||||
const path = buildJavaUrl(API_ENDPOINTS.jdPublish.activate.replace('{taskId}', String(taskId)))
|
||||
const query = `?user_id=${encodeURIComponent(String(getCurrentUserId()))}`
|
||||
return unwrapJavaResponse(post<JavaApiResponse<null>, Record<string, unknown>>(path + query, {}))
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 选品分页(AC-9 owner 过滤):服务端只回归属当前用户的京东数据库商品行。
|
||||
// 形状照后管京东数据库列表行裁剪(选品面板只需要主字段,attr/detail 不下发)。
|
||||
@@ -126,9 +119,11 @@ export interface JdPublishHistoryItemVo {
|
||||
taskStatus?: string;
|
||||
success?: boolean;
|
||||
errorMessage?: string;
|
||||
/** 建单所选自定义分类 id;重试重建推送载荷时同源带回 */
|
||||
/** 由后端递增的原位重试代数;首轮为 0。 */
|
||||
resumeAttempt?: number;
|
||||
/** 建单所选自定义分类 id。 */
|
||||
categoryId?: number;
|
||||
/** 建单统一改价规则(原样带回;重试重建推送载荷与建单响应 queuePayload 同键) */
|
||||
/** 建单统一改价规则。 */
|
||||
priceRule?: { mode?: string; value?: number };
|
||||
/** 商品明细总行数 */
|
||||
productTotal?: number;
|
||||
@@ -151,6 +146,7 @@ export interface JdPublishTaskDetailVo {
|
||||
id?: number;
|
||||
taskNo?: string;
|
||||
status?: string;
|
||||
resumeAttempt?: number;
|
||||
errorMessage?: string;
|
||||
updatedAt?: string;
|
||||
};
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
* (用户只看到一行消失)或「界面弹了但其实还在跑」(拿抖动陪葬)的错位。
|
||||
*/
|
||||
|
||||
export type CredentialFatalKind = 'llm_balance' | 'proxy' | 'key_invalid'
|
||||
export type CredentialFatalKind = 'llm_balance' | 'proxy' | 'key_invalid' | 'jd_login'
|
||||
|
||||
export interface CredentialFatalNotice {
|
||||
kind: CredentialFatalKind
|
||||
@@ -120,6 +120,12 @@ export function credentialFatalNotice(message: string | null | undefined): Crede
|
||||
if (!raw) return null
|
||||
const text = raw.toLowerCase()
|
||||
|
||||
// 京麦专属判据优先于通用终止句与 HTTP 401;仅探测登录态超时不是登录凭据失效。
|
||||
if (/京麦未登录|未登录京麦|京麦登录态(?:已)?失效/.test(raw)
|
||||
|| (raw.includes('京麦') && raw.includes('登录态失效') && !hit(text, SELF_HEALING_MARKERS))) {
|
||||
return jdLoginNotice()
|
||||
}
|
||||
|
||||
// 后端已经判死并写了指引句:这句话本身就足够定性,先认它(比逐词猜稳)
|
||||
if (raw.includes(TERMINAL_SENTENCE)) {
|
||||
return raw.includes(PROXY_TERMINAL_HINT) ? proxyNotice() : llmBalanceNotice()
|
||||
@@ -137,6 +143,14 @@ export function credentialFatalNotice(message: string | null | undefined): Crede
|
||||
return null
|
||||
}
|
||||
|
||||
function jdLoginNotice(): CredentialFatalNotice {
|
||||
return {
|
||||
kind: 'jd_login',
|
||||
title: '任务已中断:京麦未登录',
|
||||
body: '请在客户端重新登录京麦,再回到任务面板重试。',
|
||||
}
|
||||
}
|
||||
|
||||
export function proxyNotice(): CredentialFatalNotice {
|
||||
return {
|
||||
kind: 'proxy',
|
||||
|
||||
@@ -26,6 +26,15 @@ test('同一任务同一档只入队一次(重复轮询/重进页面都吃掉
|
||||
assert.equal(credentialFatalQueueLength(), 1)
|
||||
})
|
||||
|
||||
test('同一京麦任务的未登录提示出队后也不重复弹', () => {
|
||||
__resetCredentialFatalAlertForTest()
|
||||
assert.equal(reportCredentialFatal(88, '京麦接口限流'), false)
|
||||
assert.equal(reportCredentialFatal(88, '京麦未登录'), true)
|
||||
assert.equal(takeCredentialFatal()?.notice.kind, 'jd_login')
|
||||
assert.equal(reportCredentialFatal(88, '京麦登录态已失效,请重新登录'), false)
|
||||
assert.equal(credentialFatalQueueLength(), 0)
|
||||
})
|
||||
|
||||
test('同一任务换了一档要再弹(要去改的是另一处)', () => {
|
||||
__resetCredentialFatalAlertForTest()
|
||||
assert.equal(reportCredentialFatal(32901, '用户未配置代理'), true)
|
||||
|
||||
@@ -68,6 +68,26 @@ test('可自愈的供应商状态一律不弹', () => {
|
||||
}
|
||||
})
|
||||
|
||||
test('京麦未登录和登录态失效提示去客户端重新登录', () => {
|
||||
for (const message of [
|
||||
'京麦未登录(登录态失效),请在客户端重新登录京麦后重试',
|
||||
'京麦登录态失效,任务已终止,请在客户端重新登录京麦',
|
||||
'未登录京麦',
|
||||
'京麦登录态已失效(HTTP 401)',
|
||||
]) {
|
||||
const notice = credentialFatalNotice(message)
|
||||
assert.equal(notice?.kind, 'jd_login')
|
||||
assert.equal(notice?.title, '任务已中断:京麦未登录')
|
||||
assert.match(notice?.body ?? '', /请在客户端重新登录京麦/)
|
||||
}
|
||||
})
|
||||
|
||||
test('京麦限流、页面结构变化和未注明京麦的登录错误不弹京麦提示', () => {
|
||||
for (const message of ['京麦接口限流', '京麦登录态检查超时', '京麦发布页面结构变更', '登录态失效']) {
|
||||
assert.equal(kindOf(message), null, `误弹: ${message}`)
|
||||
}
|
||||
})
|
||||
|
||||
test('没有凭据字样的失败不弹(抖动不是凭据问题)', () => {
|
||||
assert.equal(kindOf('LLM 网关无应答'), null)
|
||||
assert.equal(kindOf('扩展注入失败'), null)
|
||||
|
||||
@@ -339,12 +339,9 @@ test('test_endpoints_frozen_snapshot', () => {
|
||||
"progressBatch": "/api/jd-collect/tasks/progress/batch",
|
||||
"deleteTask": "/api/jd-collect/tasks/{taskId}"
|
||||
},
|
||||
// 2026-11-18 v1.5 Phase 4:京东商品上架(建单/激活/选品/面板七件)。建单响应 queuePayload
|
||||
// 由服务端组装(type=jd-product-publish-run 与 SPI 同值,铁律 32 第三件),页面原样投
|
||||
// api.enqueue_json;分类读取唯一来源仍是 jdCollect.groups(B113-01,AC-9 源码绊线钉死)。
|
||||
// 京东商品上架:网页建单后只原样投递 queuePayload,客户端与后端负责认领。
|
||||
"jdPublish": {
|
||||
"create": "/api/jd-publish/tasks",
|
||||
"activate": "/api/jd-publish/tasks/{taskId}/activate",
|
||||
"products": "/api/jd-publish/products",
|
||||
"dashboard": "/api/jd-publish/dashboard",
|
||||
"history": "/api/jd-publish/history",
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
import { afterEach, beforeEach, expect, it, vi } from 'vitest'
|
||||
import { flushPromises, mount, type VueWrapper } from '@vue/test-utils'
|
||||
import JdPublishTab from '@/pages/jd/JdPublishTab.vue'
|
||||
import {
|
||||
__resetCredentialFatalAlertForTest,
|
||||
credentialFatalQueueLength,
|
||||
takeCredentialFatal,
|
||||
} from '@/shared/stores/credential-fatal-alert'
|
||||
|
||||
const api = vi.hoisted(() => ({
|
||||
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(),
|
||||
}))
|
||||
|
||||
vi.mock('@/shared/api/types/modules/jd-collect', () => ({ fetchJdCollectGroups: api.groups }))
|
||||
vi.mock('@/shared/api/types/modules/jd-publish', () => ({
|
||||
createJdPublishTask: api.create,
|
||||
activateJdPublishTask: api.activate,
|
||||
fetchJdPublishDashboard: api.dashboard,
|
||||
fetchJdPublishHistory: api.history,
|
||||
fetchJdPublishProducts: api.products,
|
||||
fetchJdPublishTaskProgressBatch: api.progress,
|
||||
deleteJdPublishTask: vi.fn(),
|
||||
interruptJdPublishTask: vi.fn(),
|
||||
}))
|
||||
vi.mock('@/shared/utils/categorized-timers.ts', () => ({
|
||||
createCategorizedTimers: () => ({ setTimeout: () => 1, clearTimer: vi.fn(), clearScope: vi.fn() }),
|
||||
}))
|
||||
vi.mock('element-plus', async (importOriginal) => ({
|
||||
...await importOriginal<typeof import('element-plus')>(),
|
||||
ElMessage: { success: vi.fn(), error: vi.fn() },
|
||||
}))
|
||||
vi.mock('@/shared/api/task-retry', () => ({ retryClientTask: api.retry }))
|
||||
vi.mock('@/shared/bridges/pywebview', () => ({ getPywebviewApi: api.bridge }))
|
||||
|
||||
const queuePayload = { type: 'jd-product-publish-run', data: { taskId: 88, resumeAttempt: 0, serverOnly: true } }
|
||||
const loginError = '京麦未登录(登录态失效),请在客户端重新登录京麦后重试'
|
||||
|
||||
function row(taskStatus: string, resumeAttempt: number, errorMessage?: string) {
|
||||
return { taskId: 88, taskStatus, resumeAttempt, productTotal: 2, errorMessage }
|
||||
}
|
||||
|
||||
function batch(item: ReturnType<typeof row>) {
|
||||
return {
|
||||
items: [{ task: {
|
||||
id: item.taskId, status: item.taskStatus, resumeAttempt: item.resumeAttempt, errorMessage: item.errorMessage,
|
||||
}, items: [item] }],
|
||||
missingTaskIds: [],
|
||||
}
|
||||
}
|
||||
|
||||
let wrapper: VueWrapper | undefined
|
||||
|
||||
async function mountPage() {
|
||||
wrapper = mount(JdPublishTab, {
|
||||
global: {
|
||||
stubs: {
|
||||
NotificationBell: true, RouterLink: true, ElOption: true,
|
||||
ElSelect: { props: ['modelValue'], emits: ['update:modelValue', 'change'], template: '<div><slot /></div>' },
|
||||
ElPagination: { emits: ['current-change'], template: '<div />' }, ElInputNumber: true,
|
||||
ElDrawer: { props: ['modelValue'], template: '<div v-if="modelValue"><slot /></div>' },
|
||||
},
|
||||
directives: { loading: () => undefined },
|
||||
},
|
||||
})
|
||||
await flushPromises()
|
||||
return wrapper
|
||||
}
|
||||
|
||||
async function startPublish(page: VueWrapper) {
|
||||
await page.get<HTMLInputElement>('.product-check').setValue(true)
|
||||
await page.get('.collect-btn').trigger('click')
|
||||
await flushPromises()
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
for (const mock of Object.values(api)) mock.mockReset()
|
||||
api.groups.mockResolvedValue([{ id: 12, name: '共享类目' }])
|
||||
api.products.mockResolvedValue({ items: [{ id: 23, title: '示例商品' }], total: 1 })
|
||||
api.create.mockResolvedValue({ taskId: 88, queuePayload })
|
||||
api.activate.mockResolvedValue(null)
|
||||
api.dashboard.mockResolvedValue({ pendingTaskCount: 0, processedTaskCount: 0, successTaskCount: 0, failedTaskCount: 0 })
|
||||
api.history.mockResolvedValue({ items: [] })
|
||||
api.progress.mockResolvedValue(batch(row('PENDING', 0)))
|
||||
api.bridge.mockReturnValue({ enqueue_json: api.enqueue })
|
||||
api.enqueue.mockResolvedValue({ success: true })
|
||||
api.retry.mockResolvedValue(null)
|
||||
vi.spyOn(console, 'error').mockImplementation(() => undefined)
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
wrapper?.unmount()
|
||||
wrapper = undefined
|
||||
__resetCredentialFatalAlertForTest()
|
||||
localStorage.clear()
|
||||
vi.restoreAllMocks()
|
||||
})
|
||||
|
||||
it('建单只原样投递服务端载荷,网页不激活任务', async () => {
|
||||
const page = await mountPage()
|
||||
await startPublish(page)
|
||||
expect(api.create).toHaveBeenCalledOnce()
|
||||
expect(api.enqueue).toHaveBeenCalledOnce()
|
||||
expect(api.enqueue.mock.calls[0][0]).toBe(queuePayload)
|
||||
expect(api.activate).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it.each(['没有桥', '队列拒绝', '桥异常', '没有服务端载荷'])('%s时保留待认领,不拼载荷也不误报建单失败', async (failure) => {
|
||||
if (failure === '没有桥') api.bridge.mockReturnValue(undefined)
|
||||
if (failure === '队列拒绝') api.enqueue.mockResolvedValue({ success: false, error: 'queue rejected' })
|
||||
if (failure === '桥异常') api.enqueue.mockRejectedValue(new Error('bridge unavailable'))
|
||||
if (failure === '没有服务端载荷') api.create.mockResolvedValue({ taskId: 88 })
|
||||
const page = await mountPage()
|
||||
await startPublish(page)
|
||||
expect(api.activate).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('.status').text()).toContain('等待本机客户端领取')
|
||||
expect(page.text()).not.toContain('queue rejected')
|
||||
})
|
||||
|
||||
it('切换分类后迟到的旧商品列表不能再参与勾选', async () => {
|
||||
api.groups.mockResolvedValue([{ id: 12, name: '原分类' }, { id: 13, name: '新分类' }])
|
||||
let resolveOld!: (data: { items: { id: number, title: string }[], total: number }) => void
|
||||
api.products.mockImplementationOnce(() => new Promise((resolve) => { resolveOld = resolve }))
|
||||
api.products.mockResolvedValueOnce({ items: [{ id: 24, title: '新分类商品' }], total: 1 })
|
||||
const page = await mountPage()
|
||||
const select = page.getComponent('.shop-cat-select')
|
||||
select.vm.$emit('update:modelValue', 13)
|
||||
select.vm.$emit('change', 13)
|
||||
await flushPromises()
|
||||
resolveOld({ items: [{ id: 23, title: '旧分类商品' }], total: 1 })
|
||||
await flushPromises()
|
||||
expect(page.get('.product-title').text()).toBe('新分类商品')
|
||||
await startPublish(page)
|
||||
expect(api.create).toHaveBeenCalledExactlyOnceWith(13, [24], { mode: 'none' })
|
||||
})
|
||||
|
||||
it('全选和取消只影响本页,其他页勾选保留', async () => {
|
||||
api.products.mockResolvedValueOnce({ items: [{ id: 23, title: '第一页商品' }], total: 13 })
|
||||
api.products.mockResolvedValueOnce({ items: [{ id: 24, title: '第二页商品' }], total: 13 })
|
||||
const page = await mountPage()
|
||||
await page.get('.product-select-page').setValue(true)
|
||||
page.getComponent('.product-pager').vm.$emit('current-change', 2)
|
||||
await flushPromises()
|
||||
await page.get('.product-select-page').setValue(true)
|
||||
expect(page.get('.collect-btn').text()).toContain('2 个商品')
|
||||
await page.get('.product-select-page').setValue(false)
|
||||
await page.get('.collect-btn').trigger('click')
|
||||
await flushPromises()
|
||||
expect(api.create).toHaveBeenCalledExactlyOnceWith(12, [23], { mode: 'none' })
|
||||
})
|
||||
|
||||
it('原位重试只由兜底认领,迟到的旧代终态不能停掉轮询或弹窗', async () => {
|
||||
api.history.mockResolvedValue({ items: [row('FAILED', 3, loginError)] })
|
||||
api.progress.mockResolvedValue(batch(row('FAILED', 3, loginError)))
|
||||
const page = await mountPage()
|
||||
await page.get('.history-btn').trigger('click')
|
||||
await page.get('.btn-retry').trigger('click')
|
||||
await flushPromises()
|
||||
expect(api.retry).toHaveBeenCalledExactlyOnceWith(88)
|
||||
expect(api.activate).not.toHaveBeenCalled()
|
||||
expect(api.enqueue).not.toHaveBeenCalled()
|
||||
expect(credentialFatalQueueLength()).toBe(0)
|
||||
expect(page.find('.btn-retry').exists()).toBe(false)
|
||||
expect(localStorage.getItem('jd-publish:tasks:0')).toBe('[88]')
|
||||
|
||||
api.history.mockResolvedValue({ items: [row('RUNNING', 4)] })
|
||||
api.progress.mockResolvedValue(batch(row('RUNNING', 4)))
|
||||
await page.get('.panel-refresh').trigger('click')
|
||||
await flushPromises()
|
||||
await flushPromises()
|
||||
expect(page.get('.status').text()).toBe('正在发布到京麦…')
|
||||
expect(page.text()).not.toContain(loginError)
|
||||
|
||||
// 新代已进入 RUNNING,此时再晚到一条旧代终态也不能结算。
|
||||
api.progress.mockResolvedValue(batch(row('FAILED', 3, loginError)))
|
||||
await page.get('.panel-refresh').trigger('click')
|
||||
await flushPromises()
|
||||
expect(credentialFatalQueueLength()).toBe(0)
|
||||
expect(localStorage.getItem('jd-publish:tasks:0')).toBe('[88]')
|
||||
|
||||
api.progress.mockResolvedValue(batch(row('FAILED', 4, loginError)))
|
||||
await page.get('.panel-refresh').trigger('click')
|
||||
await flushPromises()
|
||||
await flushPromises()
|
||||
expect(credentialFatalQueueLength()).toBe(1)
|
||||
expect(takeCredentialFatal()?.notice.body).toContain('请在客户端重新登录京麦')
|
||||
expect(localStorage.getItem('jd-publish:tasks:0')).toBeNull()
|
||||
})
|
||||
Reference in New Issue
Block a user