feat(phase-4): 京东商品上架用户端页(v1.5 蓝图 docs/ITERATION_PLAN.md §4 Phase 4)——JdPublishTab(分类 jdCollect.groups 唯一源→选品分页 owner 过滤→跨页勾选→改价三档→建单 queuePayload 直推→useLiveTaskBoard 行级面板+credential-fatal 同形接入)+tool-catalog 占位卡转正式+router 注册;后端面板读侧 JdCollectController 同形五端点(products/dashboard/history/progressBatch/delete)+JdPublishBoardService(无 scope_state,进度真源=明细行级四档)+JdProductQueryService.pageForUser(归属表两步下推不夹原生 SQL);激活 Phase 0 预置 5 支 Pending 契约;判据:JdPublishBoardServiceTest 5+JdProductQueryServiceUserPageTest 4+outlet 分母 138/72(写+2 读+3 随面板端点)、endpoints 冻结快照+progress/batch 清单+1、终态窄集合台账+JdPublishTab 1、catch 块 319→324 全非静默、占位 mount 锁翻转两条断言;vue-tsc rc0、用户端 node --test 1078/1078+vitest mount 90/90、后端点名 6 类 41 例 BUILD SUCCESS、快检四面格(后端 9.5/客户端 10.0/用户端 9.6)绿,唯一红格=后管 mount 组件挂载格,甄别=他窗在飞 admin 件输出含 failed 子串触发 ruler vfail 脆弱判据(实跑 cmd /c npx vitest run RC=0、188/188 全过,本笔零后管文件)

This commit is contained in:
zwork
2026-11-18 12:23:27 +08:00
parent b5578561df
commit 917884aa6d
25 changed files with 1888 additions and 33 deletions
@@ -118,11 +118,13 @@ 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 京东商品上架任务面(建单/activate/items/progress/chunk/
* heartbeat):与 /api/jd-collect 逐形状同族——建单等五端点方法体已有 requireOwnershipUserId
* (fail-closed 401,B98-07 同形债预防),chunk 判死口凭据化(isTrustedInternalToken,
* 匿名一律拒绝判死),行级落库与 jd-collect 同形状(本机桌面执行器不带凭据,行归属以
* 任务 owner 投影);判死口凭据化后随统一批进名单</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>
* </ul>
*/
static final Set<String> PENDING_CONVERGENCE = Set.of(
@@ -1,17 +1,26 @@
package com.nanri.aiimage.modules.jd.controller;
import com.nanri.aiimage.common.api.ApiResponse;
import com.nanri.aiimage.common.api.PageDefaults;
import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.modules.jd.model.dto.JdPublishChunkRequest;
import com.nanri.aiimage.modules.jd.model.dto.JdPublishTaskBatchRequest;
import com.nanri.aiimage.modules.jd.model.dto.JdPublishTaskCreateRequest;
import com.nanri.aiimage.modules.jd.model.vo.JdProductPageVo;
import com.nanri.aiimage.modules.jd.model.vo.JdPublishChunkVo;
import com.nanri.aiimage.modules.jd.model.vo.JdPublishDashboardVo;
import com.nanri.aiimage.modules.jd.model.vo.JdPublishHistoryVo;
import com.nanri.aiimage.modules.jd.model.vo.JdPublishItemsPageVo;
import com.nanri.aiimage.modules.jd.model.vo.JdPublishProgressVo;
import com.nanri.aiimage.modules.jd.model.vo.JdPublishTaskBatchVo;
import com.nanri.aiimage.modules.jd.model.vo.JdPublishTaskVo;
import com.nanri.aiimage.modules.jd.service.JdProductQueryService;
import com.nanri.aiimage.modules.jd.service.JdPublishBoardService;
import com.nanri.aiimage.modules.jd.service.JdPublishIngestService;
import com.nanri.aiimage.modules.jd.service.JdPublishTaskService;
import com.nanri.aiimage.modules.task.model.dto.TaskHeartbeatRequest;
import com.nanri.aiimage.modules.task.model.vo.TaskHeartbeatVo;
import com.nanri.aiimage.modules.task.service.TaskProgressOwnershipSupport;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
@@ -19,6 +28,7 @@ import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
@@ -45,6 +55,9 @@ public class JdPublishController {
private final JdPublishTaskService publishTaskService;
private final JdPublishIngestService ingestService;
private final JdPublishBoardService boardService;
private final JdProductQueryService jdProductQueryService;
private final TaskProgressOwnershipSupport progressOwnershipSupport;
private final AdminAuthSupport adminAuthSupport;
@PostMapping("/tasks")
@@ -134,4 +147,75 @@ public class JdPublishController {
return ApiResponse.success(publishTaskService.heartbeat(taskId,
adminAuthSupport.requireOwnershipUserId(httpRequest, userId), request));
}
// ------------------------------------------------------------------
// v1.5 Phase 4:用户端「商品上架」页读侧(选品分页+任务面板四端点)。
// 形状照 JdCollectController 面板段同族:dashboard/history/delete 走 resolve,
// progressBatch 走 requireOwnershipUserId+filterOwnedTaskIds;products 按会话
// 身份只回归属当前用户的商品行(AC-9 owner 过滤,跨用户商品 0 返回)。
// ------------------------------------------------------------------
@GetMapping("/products")
@Operation(summary = "用户端选品分页(归属过滤)", description = "「商品上架」页选品列表:只回归属当前"
+ "登录用户的京东数据库商品行(AC-9 owner 过滤,跨用户商品 0 返回),可按自定义分类过滤"
+ "(分类 id 经 V203 归属表两步下推:先取 product_id 集,再 in 主键)。")
public ApiResponse<JdProductPageVo> products(
@Parameter(description = "自定义分类 id(不传=全部归属商品)")
@RequestParam(name = "category_id", required = false) Long categoryId,
@Parameter(description = "页码") @RequestParam(name = "page", defaultValue = PageDefaults.FIRST_PAGE) Long page,
@Parameter(description = "每页数量") @RequestParam(name = "page_size", defaultValue = PageDefaults.JD_PRODUCTS_PAGE_SIZE) Long pageSize,
@Parameter(description = "当前用户 ID;省略时取当前登录身份", required = false)
@RequestParam(value = "user_id", required = false) Long userId,
HttpServletRequest httpRequest) {
userId = adminAuthSupport.resolveOwnershipUserId(httpRequest, userId);
return ApiResponse.success(jdProductQueryService.pageForUser(userId, categoryId, page, pageSize));
}
@GetMapping("/dashboard")
@Operation(summary = "查询京东上架任务总览", description = "当前用户的运行中、成功、失败任务数。"
+ "任务面板统计卡数据源,页面进入时请求一次即可,不需要持续轮询。")
public ApiResponse<JdPublishDashboardVo> dashboard(
@Parameter(description = "当前用户 ID", required = true, example = "1")
@RequestParam("user_id") Long userId,
HttpServletRequest httpRequest) {
userId = adminAuthSupport.resolveOwnershipUserId(httpRequest, userId);
return ApiResponse.success(boardService.dashboard(userId));
}
@GetMapping("/history")
@Operation(summary = "查询京东上架任务历史", description = "当前用户最近的上架任务历史(活跃任务排前),"
+ "含行级四档计数(待发布/发布中/成功/失败)与建单载荷带回(分类 id/改价规则,重试重建推送载荷用)。")
public ApiResponse<JdPublishHistoryVo> history(
@Parameter(description = "当前用户 ID", required = true, example = "1")
@RequestParam("user_id") Long userId,
@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);
return ApiResponse.success(boardService.history(userId, limit));
}
@PostMapping("/tasks/progress/batch")
@Operation(summary = "批量查询上架任务进度", description = "任务面板只对活跃任务调用该接口,建议 6 秒一次。"
+ "归属先由公共出口按会话身份过滤,返回任务头 + 行级四档计数。")
public ApiResponse<JdPublishTaskBatchVo> progressBatch(@Valid @RequestBody JdPublishTaskBatchRequest request,
HttpServletRequest httpRequest) {
return ApiResponse.success(boardService.progressBatch(progressOwnershipSupport
.filterOwnedTaskIds(request.getTaskIds(),
adminAuthSupport.requireOwnershipUserId(httpRequest, request.getUserId()))));
}
@DeleteMapping("/tasks/{taskId}")
@Operation(summary = "删除上架任务", description = "删除当前用户的一条京东商品上架任务,"
+ "连带清理该任务的发布明细快照行(发布不落商品行,无京东数据库清理语义)。")
public ApiResponse<Void> deleteTask(
@Parameter(description = "任务 ID", required = true, example = "34400")
@PathVariable Long taskId,
@Parameter(description = "当前用户 ID,必须与创建任务的用户一致", required = true, example = "1")
@RequestParam("user_id") Long userId,
HttpServletRequest httpRequest) {
userId = adminAuthSupport.resolveOwnershipUserId(httpRequest, userId);
boardService.deleteTask(taskId, userId);
return ApiResponse.success(null);
}
}
@@ -0,0 +1,24 @@
package com.nanri.aiimage.modules.jd.model.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotEmpty;
import lombok.Data;
import java.util.List;
/**
* 京东商品上架批量进度请求(形状照 {@code JdCollectTaskBatchRequest} 同族)。
* {@code userId} 可省略:归属过滤主体是 {@code TaskProgressOwnershipSupport.filterOwnedTaskIds}
* 按会话身份判定,请求体里的 userId 只作 admin 代客的归属提示。
*/
@Data
@Schema(description = "京东商品上架批量进度请求")
public class JdPublishTaskBatchRequest {
@Schema(description = "要查询的任务 ID 列表(只查活跃任务,建议 6 秒一批)", required = true)
@NotEmpty(message = "taskIds 不能为空")
private List<Long> taskIds;
@Schema(description = "当前用户 ID(归属过滤用,可省略)")
private Long userId;
}
@@ -0,0 +1,27 @@
package com.nanri.aiimage.modules.jd.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/**
* 京东商品上架任务面板总览(v1.5 Phase 4,用户端「商品上架」统计卡数据源)。
*
* <p>形状照 {@code JdCollectDashboardVo} 同族:当前用户的运行中/成功/失败任务数,
* 已结束=成功+失败。页面进入时请求一次,不参与轮询。</p>
*/
@Data
@Schema(description = "京东商品上架任务总览")
public class JdPublishDashboardVo {
@Schema(description = "运行中任务数(含排队)")
private long pendingTaskCount;
@Schema(description = "已结束任务数(成功+失败)")
private long processedTaskCount;
@Schema(description = "成功任务数")
private long successTaskCount;
@Schema(description = "失败任务数")
private long failedTaskCount;
}
@@ -0,0 +1,67 @@
package com.nanri.aiimage.modules.jd.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.math.BigDecimal;
import java.util.Map;
/**
* 京东商品上架任务历史行(v1.5 Phase 4,任务面板历史层数据源)。
*
* <p>行级计数(待发布/发布中/成功/失败)来自 {@code biz_jd_publish_item} 按任务聚合;
* 建单载荷(分类 id + 改价规则)随行带回——失败任务「重试」时页面用它重建推送载荷
* (铁律 26 原任务复位 + 铁律 32 第三件同键:重建的载荷与建单响应 queuePayload 同形状)。</p>
*/
@Data
@Schema(description = "京东商品上架任务历史行")
public class JdPublishHistoryItemVo {
@Schema(description = "任务 ID")
private Long taskId;
@Schema(description = "任务编号")
private String taskNo;
@Schema(description = "biz_file_task.status 原值:PENDING/RUNNING/SUCCESS/FAILED")
private String taskStatus;
@Schema(description = "任务是否成功")
private boolean success;
@Schema(description = "终态原因(非终态为 null)")
private String errorMessage;
@Schema(description = "建单所选自定义分类 id(biz_jd_product_group.id)")
private Long categoryId;
@Schema(description = "建单统一改价规则(原样带回,重试重建推送载荷用;空=原价)")
private Map<String, Object> priceRule;
@Schema(description = "商品明细总行数")
private long productTotal;
@Schema(description = "待发布行数")
private long pendingCount;
@Schema(description = "发布中行数")
private long publishingCount;
@Schema(description = "成功行数")
private long successCount;
@Schema(description = "失败行数")
private long failedCount;
@Schema(description = "任务创建时刻")
private String createdAt;
@Schema(description = "任务结束时刻")
private String finishedAt;
@Schema(description = "最近更新时刻")
private String updatedAt;
@Schema(description = "改价规则里的加价值(percent 百分数 / fixed 金额;仅展示用)")
private BigDecimal priceRuleValue;
}
@@ -0,0 +1,16 @@
package com.nanri.aiimage.modules.jd.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
/** 京东商品上架任务历史(活跃任务排前,形状照 {@code JdCollectHistoryVo} 同族)。 */
@Data
@Schema(description = "京东商品上架任务历史")
public class JdPublishHistoryVo {
@Schema(description = "历史行")
private List<JdPublishHistoryItemVo> items = new ArrayList<>();
}
@@ -0,0 +1,19 @@
package com.nanri.aiimage.modules.jd.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
/** 批量进度响应(形状照 {@code JdCollectTaskBatchVo} 同族;查不到的任务进 missingTaskIds)。 */
@Data
@Schema(description = "京东商品上架批量进度")
public class JdPublishTaskBatchVo {
@Schema(description = "命中的任务条目")
private List<JdPublishTaskDetailVo> items = new ArrayList<>();
@Schema(description = "没查到的任务 ID(已删除/非本模块,前端停止轮询)")
private List<Long> missingTaskIds = new ArrayList<>();
}
@@ -0,0 +1,19 @@
package com.nanri.aiimage.modules.jd.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
/** 批量进度条目:任务头 + 最新历史行(形状照 {@code JdCollectTaskDetailVo} 同族)。 */
@Data
@Schema(description = "京东商品上架任务进度条目")
public class JdPublishTaskDetailVo {
@Schema(description = "任务头")
private JdPublishTaskItemVo task;
@Schema(description = "最新进度行(单元素)")
private List<JdPublishHistoryItemVo> items = new ArrayList<>();
}
@@ -0,0 +1,25 @@
package com.nanri.aiimage.modules.jd.model.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
/** 批量进度条目里的任务头(形状照 {@code JdCollectTaskItemVo} 同族)。 */
@Data
@Schema(description = "京东商品上架任务头")
public class JdPublishTaskItemVo {
@Schema(description = "任务 ID")
private Long id;
@Schema(description = "任务编号")
private String taskNo;
@Schema(description = "任务状态")
private String status;
@Schema(description = "终态原因")
private String errorMessage;
@Schema(description = "最近更新时刻")
private String updatedAt;
}
@@ -117,6 +117,53 @@ public class JdProductQueryService {
return vo;
}
/**
* 用户端「商品上架」选品分页(v1.5 Phase 4,AC-9 owner 过滤):只回归属当前用户的行,
* 可按自定义分类过滤。分类过滤不走 wrapper 原生 EXISTS(SqlLayeringConventionTest
* rawSqlInsideWrappersDoesNotGrow 钉死不涨):先从 V203 归属表取该分类的 product_id 集,
* 再 in 主键——分类规模=组内商品数,量级可控;分类空集直接回空页不查主表。
* 页码钳制与 {@link #page} 同出口(MAX_PAGE/MAX_PAGE_SIZE,铁律 15)。
*/
public JdProductPageVo pageForUser(Long userId, Long categoryId, Long page, Long pageSize) {
long safePage = page == null || page < 1 ? 1 : Math.min(page, MAX_PAGE);
long safeSize = pageSize == null ? PageDefaults.JD_PRODUCTS_PAGE_SIZE_INT
: Math.min(Math.max(pageSize, 1), MAX_PAGE_SIZE);
LambdaQueryWrapper<JdProductEntity> query = new LambdaQueryWrapper<JdProductEntity>()
.eq(JdProductEntity::getUserId, userId);
if (categoryId != null && categoryId > 0) {
List<Long> productIds = jdProductGroupAssignMapper.selectList(
new LambdaQueryWrapper<JdProductGroupAssignEntity>()
.select(JdProductGroupAssignEntity::getProductId)
.eq(JdProductGroupAssignEntity::getCategoryId, categoryId))
.stream().map(JdProductGroupAssignEntity::getProductId).distinct().toList();
if (productIds.isEmpty()) {
return emptyPage(safePage, safeSize);
}
query.in(JdProductEntity::getId, productIds);
}
long total = jdProductMapper.selectCount(query);
List<JdProductListItemVo> items = total <= 0 ? List.of()
: jdProductMapper.selectList(query
.orderByDesc(JdProductEntity::getSyncedAt, JdProductEntity::getId)
.last("limit " + (safePage - 1) * safeSize + ", " + safeSize))
.stream().map(this::toListItem).toList();
JdProductPageVo vo = new JdProductPageVo();
vo.setItems(items);
vo.setTotal(total);
vo.setPage(safePage);
vo.setPageSize(safeSize);
return vo;
}
private static JdProductPageVo emptyPage(long page, long pageSize) {
JdProductPageVo vo = new JdProductPageVo();
vo.setItems(List.of());
vo.setTotal(0L);
vo.setPage(page);
vo.setPageSize(pageSize);
return vo;
}
/**
* 类目筛选下拉数据源(2026-11-15 用户口径「京麦的类目也要同步过来后台」):
* 已落库行 distinct 的 {@code category_path}(=京麦末级类目名,契约 §2.3 E3)
@@ -0,0 +1,254 @@
package com.nanri.aiimage.modules.jd.service;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.task.TaskStatuses;
import com.nanri.aiimage.modules.jd.mapper.JdPublishItemMapper;
import com.nanri.aiimage.modules.jd.model.dto.JdPublishTaskCreateRequest;
import com.nanri.aiimage.modules.jd.model.entity.JdPublishItemEntity;
import com.nanri.aiimage.modules.jd.model.vo.JdPublishDashboardVo;
import com.nanri.aiimage.modules.jd.model.vo.JdPublishHistoryItemVo;
import com.nanri.aiimage.modules.jd.model.vo.JdPublishHistoryVo;
import com.nanri.aiimage.modules.jd.model.vo.JdPublishTaskBatchVo;
import com.nanri.aiimage.modules.jd.model.vo.JdPublishTaskDetailVo;
import com.nanri.aiimage.modules.jd.model.vo.JdPublishTaskItemVo;
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
/**
* 京东商品上架任务面板服务(v1.5 Phase 4,用户端「商品上架」实时任务面板四端点)。
*
* <p>形状照 {@code JdCollectBoardService} 同族裁剪:京东发布<b>没有</b>
* {@code biz_task_scope_state} 游标(进度真源是 {@code biz_jd_publish_item} 的行级状态,
* {@code JdPublishTaskService#queryProgress} 同口径),历史行的「行级计数」改从明细表
* GROUP BY 聚合;删除面只清明细行+任务主行(发布不落商品行,无京东数据库清理语义)。</p>
*/
@Service
@RequiredArgsConstructor
@Slf4j
public class JdPublishBoardService {
private static final int MAX_HISTORY_LIMIT = 100;
private final FileTaskMapper fileTaskMapper;
private final JdPublishItemMapper jdPublishItemMapper;
private final ObjectMapper objectMapper;
/** 查询当前用户的面板总览(运行中/成功/失败三档计数,已结束=成功+失败)。 */
public JdPublishDashboardVo dashboard(Long userId) {
JdPublishDashboardVo vo = new JdPublishDashboardVo();
long running = countTask(userId, TaskStatuses.FileTask.RUNNING);
long success = countTask(userId, TaskStatuses.FileTask.SUCCESS);
long failed = countTask(userId, TaskStatuses.FileTask.FAILED);
vo.setPendingTaskCount(running);
vo.setSuccessTaskCount(success);
vo.setFailedTaskCount(failed);
vo.setProcessedTaskCount(success + failed);
return vo;
}
private long countTask(Long userId, String status) {
return fileTaskMapper.selectCount(new LambdaQueryWrapper<FileTaskEntity>()
.eq(FileTaskEntity::getModuleType, JdPublishTaskService.MODULE_TYPE)
.eq(FileTaskEntity::getUserId, userId)
.eq(FileTaskEntity::getStatus, status));
}
/**
* 查询当前用户最近的任务历史(活跃任务排前,其余按最近更新时间倒序)。
* 行级计数批量回查:一条 GROUP BY(task_id, publish_status)出全部任务的四档计数,
* 不逐任务一条聚合查询(100 行上限打爆面板的同族教训)。
*/
public JdPublishHistoryVo history(Long userId, Integer limit) {
int safeLimit = Math.max(1, Math.min(limit == null ? 50 : limit, MAX_HISTORY_LIMIT));
List<FileTaskEntity> tasks = fileTaskMapper.selectList(new LambdaQueryWrapper<FileTaskEntity>()
.eq(FileTaskEntity::getModuleType, JdPublishTaskService.MODULE_TYPE)
.eq(FileTaskEntity::getUserId, userId)
.orderByDesc(FileTaskEntity::getCreatedAt)
.last("limit " + safeLimit));
tasks.sort(Comparator
.comparing((FileTaskEntity task) -> !isActive(task))
.thenComparing(FileTaskEntity::getUpdatedAt,
Comparator.nullsLast(Comparator.reverseOrder()))
.thenComparing(FileTaskEntity::getId, Comparator.reverseOrder()));
Map<Long, Map<String, Long>> countsByTask = countItemsByTask(
tasks.stream().map(FileTaskEntity::getId).toList());
JdPublishHistoryVo vo = new JdPublishHistoryVo();
for (FileTaskEntity task : tasks) {
vo.getItems().add(toHistoryItem(task,
countsByTask.getOrDefault(task.getId(), Map.of())));
}
return vo;
}
private static boolean isActive(FileTaskEntity task) {
return TaskStatuses.FileTask.ACTIVE.contains(task.getStatus());
}
/** 批量行级计数:一条 GROUP BY 出全部任务的 PENDING/PUBLISHING/SUCCESS/FAILED 行数。 */
private Map<Long, Map<String, Long>> countItemsByTask(List<Long> taskIds) {
Map<Long, Map<String, Long>> counts = new HashMap<>();
if (taskIds.isEmpty()) {
return counts;
}
List<Map<String, Object>> rows = jdPublishItemMapper.selectMaps(new QueryWrapper<JdPublishItemEntity>()
.select("task_id", "publish_status", "count(*) as cnt")
.in("task_id", taskIds)
.groupBy("task_id", "publish_status"));
for (Map<String, Object> row : rows) {
Long taskId = row.get("task_id") == null ? null : Long.valueOf(String.valueOf(row.get("task_id")));
Object status = row.get("publish_status");
Object cnt = row.get("cnt");
if (taskId == null || status == null || !(cnt instanceof Number number)) {
continue;
}
counts.computeIfAbsent(taskId, key -> new LinkedHashMap<>())
.put(String.valueOf(status), number.longValue());
}
return counts;
}
/** 组装历史行:任务头 + 建单载荷(分类 id/改价规则,宽松读) + 行级四档计数。 */
private JdPublishHistoryItemVo toHistoryItem(FileTaskEntity task, Map<String, Long> counts) {
JdPublishHistoryItemVo item = new JdPublishHistoryItemVo();
item.setTaskId(task.getId());
item.setTaskNo(task.getTaskNo());
item.setTaskStatus(task.getStatus());
item.setSuccess(TaskStatuses.FileTask.SUCCESS.equals(task.getStatus()));
item.setErrorMessage(task.getErrorMessage());
JdPublishTaskCreateRequest request = readCreateRequestQuiet(task);
if (request != null) {
item.setCategoryId(request.getCategoryId());
if (request.getPriceRule() != null) {
Map<String, Object> rule = new LinkedHashMap<>();
rule.put("mode", request.getPriceRule().getMode());
rule.put("value", request.getPriceRule().getValue());
item.setPriceRule(rule);
item.setPriceRuleValue(request.getPriceRule().getValue());
}
}
item.setProductTotal(counts.values().stream().mapToLong(Long::longValue).sum());
item.setPendingCount(counts.getOrDefault(JdPublishTaskService.ITEM_PENDING, 0L));
item.setPublishingCount(counts.getOrDefault(JdPublishTaskService.ITEM_PUBLISHING, 0L));
item.setSuccessCount(counts.getOrDefault(JdPublishTaskService.ITEM_SUCCESS, 0L));
item.setFailedCount(counts.getOrDefault(JdPublishTaskService.ITEM_FAILED, 0L));
if (task.getCreatedAt() != null) {
item.setCreatedAt(task.getCreatedAt().toString());
}
if (task.getFinishedAt() != null) {
item.setFinishedAt(task.getFinishedAt().toString());
}
if (task.getUpdatedAt() != null) {
item.setUpdatedAt(task.getUpdatedAt().toString());
}
return item;
}
/** 历史行宽松读建单载荷:载荷缺失/损坏时只少分类 id 与改价规则,不把历史面板打成红条。 */
private JdPublishTaskCreateRequest readCreateRequestQuiet(FileTaskEntity task) {
if (task.getRequestJson() == null || task.getRequestJson().isBlank()) {
return null;
}
try {
return objectMapper.readValue(task.getRequestJson(), JdPublishTaskCreateRequest.class);
} catch (Exception ex) {
log.warn("[jd-publish] 建单载荷解析失败,历史行少分类/改价 taskId={} err={}",
task.getId(), ex.getMessage());
return null;
}
}
/**
* 批量查任务进度(前端轮询专用,归属已由 {@code TaskProgressOwnershipSupport} 过滤)。
* 形状照采集面板:每任务一条 {@code {task, items:[最新进度行]}},查不到的进 missingTaskIds。
*/
public JdPublishTaskBatchVo progressBatch(List<Long> taskIds) {
Set<Long> normalized = new LinkedHashSet<>();
if (taskIds != null) {
for (Long id : taskIds) {
if (id != null && id > 0) {
normalized.add(id);
}
}
}
JdPublishTaskBatchVo vo = new JdPublishTaskBatchVo();
if (normalized.isEmpty()) {
return vo;
}
List<FileTaskEntity> tasks = fileTaskMapper.selectList(
new LambdaQueryWrapper<FileTaskEntity>().in(FileTaskEntity::getId, normalized));
List<Long> hitIds = new ArrayList<>();
Map<Long, Map<String, Long>> countsByTask = countItemsByTask(
tasks.stream().map(FileTaskEntity::getId).toList());
for (FileTaskEntity task : tasks) {
if (!JdPublishTaskService.MODULE_TYPE.equals(task.getModuleType())) {
continue;
}
hitIds.add(task.getId());
JdPublishTaskItemVo taskItem = new JdPublishTaskItemVo();
taskItem.setId(task.getId());
taskItem.setTaskNo(task.getTaskNo());
taskItem.setStatus(task.getStatus());
taskItem.setErrorMessage(task.getErrorMessage());
taskItem.setUpdatedAt(task.getUpdatedAt() == null ? null : task.getUpdatedAt().toString());
JdPublishTaskDetailVo detail = new JdPublishTaskDetailVo();
detail.setTask(taskItem);
detail.getItems().add(toHistoryItem(task,
countsByTask.getOrDefault(task.getId(), Map.of())));
vo.getItems().add(detail);
}
for (Long id : normalized) {
if (!hitIds.contains(id)) {
vo.getMissingTaskIds().add(id);
}
}
return vo;
}
/**
* 删除任务:明细快照行按 {@code task_id} 清 + 任务主行。事务内只做 DB 删除——
* 发布不落商品行/图片行(京东数据库是采集面的数据),没有额外清理语义。
*/
@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("任务不存在");
}
int items = jdPublishItemMapper.delete(new LambdaQueryWrapper<JdPublishItemEntity>()
.eq(JdPublishItemEntity::getTaskId, taskId));
fileTaskMapper.deleteById(taskId);
log.info("[jd-publish] 删除任务 taskId={} userId={} 明细行={}", taskId, userId, items);
}
/** 供测试确认行级计数口径(BigDecimal 展示值从 priceRule 原样带回)。 */
static BigDecimal priceRuleValueOf(JdPublishTaskCreateRequest request) {
return request.getPriceRule() == null ? null : request.getPriceRule().getValue();
}
/** 时间列统一字符串(LocalDateTime.toString;空值原样 null,与采集面板同口径)。 */
static String timeText(LocalDateTime value) {
return value == null ? null : value.toString();
}
}