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:
@@ -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(
|
||||
|
||||
+84
@@ -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);
|
||||
}
|
||||
}
|
||||
|
||||
+24
@@ -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;
|
||||
}
|
||||
+27
@@ -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;
|
||||
}
|
||||
+67
@@ -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;
|
||||
}
|
||||
+16
@@ -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<>();
|
||||
}
|
||||
+19
@@ -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<>();
|
||||
}
|
||||
+19
@@ -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<>();
|
||||
}
|
||||
+25
@@ -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;
|
||||
}
|
||||
+47
@@ -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)
|
||||
|
||||
+254
@@ -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();
|
||||
}
|
||||
}
|
||||
+10
-2
@@ -113,7 +113,11 @@ class RequestSuppliedIdentityOutletTest {
|
||||
// + POST /api/jd-publish/tasks/{taskId}/heartbeat(都是 @RequestParam("user_id") 先过
|
||||
// requireOwnershipUserId);chunk 回传不走身份出口(判死口凭据化 isTrustedInternalToken,
|
||||
// JdPublishChunkRequest 不带 userId 字段),不计入——覆盖面变大,不是放宽分母。
|
||||
assertThat(scan.boundWrite()).as("取请求身份且已接出口的写类 handler 数").isEqualTo(136);
|
||||
// 138 而不是 136:2026-11-18 v1.5 Phase 4 京东上架用户端读侧新增两支写类端点——
|
||||
// POST /api/jd-publish/tasks/progress/batch(request.userId 先过 requireOwnershipUserId 再
|
||||
// filterOwnedTaskIds 过滤归属)+ DELETE /api/jd-publish/tasks/{taskId}(@RequestParam("user_id")
|
||||
// 先过 resolveOwnershipUserId,删除任务行连带发布明细快照行)——覆盖面变大,不是放宽分母。
|
||||
assertThat(scan.boundWrite()).as("取请求身份且已接出口的写类 handler 数").isEqualTo(138);
|
||||
// 64 而不是 63:2026-10-29 随本地采集开关恢复 GET /tasks/{taskId}/queue-payload,
|
||||
// 该 handler 同时接上 resolveOwnershipUserId(不是放宽分母)。
|
||||
// 65 而不是 64:2026-11-14 v1.4 新增 JdCollectController GET /api/jd-collect/tasks/{taskId}/progress
|
||||
@@ -125,7 +129,11 @@ class RequestSuppliedIdentityOutletTest {
|
||||
// 69 而不是 67:2026-11-18 v1.5 Phase 2 新增两支读类端点——GET /api/jd-publish/tasks/{taskId}/items
|
||||
// + GET /api/jd-publish/tasks/{taskId}/progress,都是 @RequestParam("user_id") 先过
|
||||
// requireOwnershipUserId——覆盖面变大,不是放宽分母。
|
||||
assertThat(scan.boundRead()).as("取请求身份且已接出口的读类 handler 数").isEqualTo(69);
|
||||
// 72 而不是 69:2026-11-18 v1.5 Phase 4 京东上架用户端读侧新增三支读类端点——
|
||||
// GET /api/jd-publish/products(选品分页,AC-9 owner 过滤)+ GET /api/jd-publish/dashboard
|
||||
// + GET /api/jd-publish/history(面板统计卡+历史层),都是 @RequestParam("user_id") 先过
|
||||
// resolveOwnershipUserId——覆盖面变大,不是放宽分母。
|
||||
assertThat(scan.boundRead()).as("取请求身份且已接出口的读类 handler 数").isEqualTo(72);
|
||||
assertThat(scan.unbound()).as("取请求身份但未接出口的 handler:只剩豁免那一条")
|
||||
.containsExactlyElementsOf(ALLOWED_WITHOUT_OUTLET);
|
||||
}
|
||||
|
||||
+150
@@ -0,0 +1,150 @@
|
||||
package com.nanri.aiimage.modules.jd.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.nanri.aiimage.modules.jd.mapper.JdProductGroupAssignMapper;
|
||||
import com.nanri.aiimage.modules.jd.mapper.JdProductGroupMapper;
|
||||
import com.nanri.aiimage.modules.jd.mapper.JdProductImageMapper;
|
||||
import com.nanri.aiimage.modules.jd.mapper.JdProductMapper;
|
||||
import com.nanri.aiimage.modules.jd.mapper.JdProductSkuMapper;
|
||||
import com.nanri.aiimage.modules.jd.model.entity.JdProductEntity;
|
||||
import com.nanri.aiimage.modules.jd.model.vo.JdProductPageVo;
|
||||
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;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.mockito.ArgumentMatchers.any;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* 用户端「商品上架」选品分页(v1.5 Phase 4,AC-9 owner 过滤的服务端半边)。
|
||||
*
|
||||
* <p>判据四件:① 归属条件恒带(user_id 来自会话出口,跨用户商品 0 返回);② 分类过滤走
|
||||
* V203 归属表两步下推(先取 product_id 集再 in 主键,不往 wrapper 夹原生 SQL);③ 分类空集
|
||||
* 直接回空页不查主表;④ 页码/页宽钳制照管理面同出口(MAX_PAGE/MAX_PAGE_SIZE,铁律 15)。</p>
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class JdProductQueryServiceUserPageTest {
|
||||
|
||||
@Mock
|
||||
private JdProductMapper jdProductMapper;
|
||||
@Mock
|
||||
private JdProductImageMapper jdProductImageMapper;
|
||||
@Mock
|
||||
private JdProductSkuMapper jdProductSkuMapper;
|
||||
@Mock
|
||||
private JdProductGroupMapper jdProductGroupMapper;
|
||||
@Mock
|
||||
private JdProductGroupAssignMapper jdProductGroupAssignMapper;
|
||||
|
||||
@InjectMocks
|
||||
private JdProductQueryService service;
|
||||
|
||||
@BeforeAll
|
||||
static void initMybatisPlusTableInfo() {
|
||||
// LambdaQueryWrapper 需要 MP 的 lambda cache(ProgressQueryOwnershipOutletTest 同款初始化)。
|
||||
com.baomidou.mybatisplus.core.MybatisConfiguration configuration =
|
||||
new com.baomidou.mybatisplus.core.MybatisConfiguration();
|
||||
org.apache.ibatis.builder.MapperBuilderAssistant assistant =
|
||||
new org.apache.ibatis.builder.MapperBuilderAssistant(configuration, "");
|
||||
com.baomidou.mybatisplus.core.metadata.TableInfoHelper.initTableInfo(assistant,
|
||||
JdProductEntity.class);
|
||||
com.baomidou.mybatisplus.core.metadata.TableInfoHelper.initTableInfo(assistant,
|
||||
com.nanri.aiimage.modules.jd.model.entity.JdProductGroupAssignEntity.class);
|
||||
}
|
||||
|
||||
private JdProductEntity product(long id) {
|
||||
JdProductEntity row = new JdProductEntity();
|
||||
row.setId(id);
|
||||
row.setUserId(7L);
|
||||
row.setTitle("测试商品 " + id);
|
||||
row.setProductCode("P" + id);
|
||||
row.setPriceMin(new BigDecimal("10.50"));
|
||||
row.setStockTotal(3);
|
||||
return row;
|
||||
}
|
||||
|
||||
private com.nanri.aiimage.modules.jd.model.entity.JdProductGroupAssignEntity assign(long productId) {
|
||||
com.nanri.aiimage.modules.jd.model.entity.JdProductGroupAssignEntity row =
|
||||
new com.nanri.aiimage.modules.jd.model.entity.JdProductGroupAssignEntity();
|
||||
row.setProductId(productId);
|
||||
row.setCategoryId(3L);
|
||||
row.setOwnerGroupId(2L);
|
||||
return row;
|
||||
}
|
||||
|
||||
@Test
|
||||
void 选品分页只回归属当前用户的行() {
|
||||
when(jdProductMapper.selectCount(any())).thenReturn(1L);
|
||||
when(jdProductMapper.selectList(any())).thenReturn(List.of(product(11L)));
|
||||
|
||||
JdProductPageVo vo = service.pageForUser(7L, null, 1L, 20L);
|
||||
|
||||
ArgumentCaptor<LambdaQueryWrapper<JdProductEntity>> captor =
|
||||
ArgumentCaptor.forClass(LambdaQueryWrapper.class);
|
||||
verify(jdProductMapper).selectCount(captor.capture());
|
||||
captor.getValue().getSqlSegment(); // MP 惯例:先求值一次才铺出参数
|
||||
assertThat(captor.getValue().getSqlSegment()).as("归属条件恒在主查询里").contains("user_id");
|
||||
assertThat(captor.getValue().getParamNameValuePairs().values()).contains(7L);
|
||||
assertThat(vo.getTotal()).isEqualTo(1L);
|
||||
assertThat(vo.getItems()).hasSize(1);
|
||||
assertThat(vo.getItems().get(0).getTitle()).isEqualTo("测试商品 11");
|
||||
// 没选分类不查归属表
|
||||
verify(jdProductGroupAssignMapper, never()).selectList(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void 分类过滤_先取归属表产品集再进主查询() {
|
||||
when(jdProductGroupAssignMapper.selectList(any()))
|
||||
.thenReturn(List.of(assign(11L), assign(12L), assign(11L)));
|
||||
when(jdProductMapper.selectCount(any())).thenReturn(1L);
|
||||
when(jdProductMapper.selectList(any())).thenReturn(List.of(product(12L)));
|
||||
|
||||
JdProductPageVo vo = service.pageForUser(7L, 3L, 1L, 20L);
|
||||
|
||||
ArgumentCaptor<LambdaQueryWrapper<JdProductEntity>> captor =
|
||||
ArgumentCaptor.forClass(LambdaQueryWrapper.class);
|
||||
verify(jdProductMapper).selectCount(captor.capture());
|
||||
captor.getValue().getSqlSegment();
|
||||
assertThat(captor.getValue().getSqlSegment())
|
||||
.as("分类集以 IN 下推进主查询(owner 条件仍然恒在)")
|
||||
.contains("user_id").contains("IN");
|
||||
assertThat(captor.getValue().getParamNameValuePairs().values())
|
||||
.contains(7L, 11L, 12L);
|
||||
assertThat(vo.getItems()).hasSize(1);
|
||||
}
|
||||
|
||||
@Test
|
||||
void 分类空集直接回空页不查主表() {
|
||||
when(jdProductGroupAssignMapper.selectList(any())).thenReturn(List.of());
|
||||
|
||||
JdProductPageVo vo = service.pageForUser(7L, 3L, 1L, 20L);
|
||||
|
||||
assertThat(vo.getTotal()).isZero();
|
||||
assertThat(vo.getItems()).isEmpty();
|
||||
verify(jdProductMapper, never()).selectCount(any());
|
||||
verify(jdProductMapper, never()).selectList(any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void 页码页宽钳制_离谱页码不喂负下标() {
|
||||
when(jdProductMapper.selectCount(any())).thenReturn(0L);
|
||||
|
||||
JdProductPageVo zero = service.pageForUser(7L, null, 0L, 5000L);
|
||||
assertThat(zero.getPage()).as("页码下限钳到 1").isEqualTo(1L);
|
||||
assertThat(zero.getPageSize()).as("页宽上限钳到 100").isEqualTo(100L);
|
||||
|
||||
JdProductPageVo huge = service.pageForUser(7L, null, Long.MAX_VALUE, 20L);
|
||||
assertThat(huge.getPage()).as("页码上限钳到 10000(乘积不溢出,铁律 15 同形)").isEqualTo(10000L);
|
||||
verify(jdProductMapper, never()).selectList(any());
|
||||
}
|
||||
}
|
||||
+167
@@ -0,0 +1,167 @@
|
||||
package com.nanri.aiimage.modules.jd.service;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.nanri.aiimage.common.exception.BusinessException;
|
||||
import com.nanri.aiimage.modules.jd.mapper.JdPublishItemMapper;
|
||||
import com.nanri.aiimage.modules.task.mapper.FileTaskMapper;
|
||||
import com.nanri.aiimage.modules.task.model.entity.FileTaskEntity;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.mockito.InOrder;
|
||||
import org.mockito.InjectMocks;
|
||||
import org.mockito.Mock;
|
||||
import org.mockito.Spy;
|
||||
import org.mockito.junit.jupiter.MockitoExtension;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
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.Mockito.inOrder;
|
||||
import static org.mockito.Mockito.never;
|
||||
import static org.mockito.Mockito.verify;
|
||||
import static org.mockito.Mockito.when;
|
||||
|
||||
/**
|
||||
* 京东商品上架任务面板服务(v1.5 Phase 4 面板四端点)。
|
||||
*
|
||||
* <p>判据四件:① 总览三档计数(已结束=成功+失败);② 历史行读真源(行级四档计数来自
|
||||
* {@code biz_jd_publish_item} GROUP BY 聚合,分类 id/改价规则从建单载荷带回);③ 批量进度
|
||||
* 按模块过滤,非本模块任务进 missingTaskIds 不冒充面板条目;④ 删除面校验归属后才清明细行
|
||||
* +任务主行(发布不落商品行,无京东数据库清理语义)。</p>
|
||||
*/
|
||||
@ExtendWith(MockitoExtension.class)
|
||||
class JdPublishBoardServiceTest {
|
||||
|
||||
@Mock
|
||||
private FileTaskMapper fileTaskMapper;
|
||||
@Mock
|
||||
private JdPublishItemMapper jdPublishItemMapper;
|
||||
@Spy
|
||||
private ObjectMapper objectMapper = new ObjectMapper();
|
||||
|
||||
@InjectMocks
|
||||
private JdPublishBoardService service;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
// LambdaQueryWrapper 需要 MP 的 lambda cache(JdCollectBoardServiceTest 同款初始化)。
|
||||
com.baomidou.mybatisplus.core.MybatisConfiguration configuration =
|
||||
new com.baomidou.mybatisplus.core.MybatisConfiguration();
|
||||
org.apache.ibatis.builder.MapperBuilderAssistant assistant =
|
||||
new org.apache.ibatis.builder.MapperBuilderAssistant(configuration, "");
|
||||
com.baomidou.mybatisplus.core.metadata.TableInfoHelper.initTableInfo(assistant,
|
||||
com.nanri.aiimage.modules.jd.model.entity.JdPublishItemEntity.class);
|
||||
com.baomidou.mybatisplus.core.metadata.TableInfoHelper.initTableInfo(assistant,
|
||||
com.nanri.aiimage.modules.task.model.entity.FileTaskEntity.class);
|
||||
}
|
||||
|
||||
private FileTaskEntity task(long id, long userId, String status) {
|
||||
FileTaskEntity task = new FileTaskEntity();
|
||||
task.setId(id);
|
||||
task.setModuleType(JdPublishTaskService.MODULE_TYPE);
|
||||
task.setUserId(userId);
|
||||
task.setTaskNo("JD_PUBLISH-" + id);
|
||||
task.setStatus(status);
|
||||
task.setRequestJson("{\"userId\":" + userId + ",\"categoryId\":3,\"productIds\":[11,12],"
|
||||
+ "\"priceRule\":{\"mode\":\"percent\",\"value\":10}}");
|
||||
task.setCreatedAt(LocalDateTime.of(2026, 11, 18, 10, 0));
|
||||
task.setUpdatedAt(LocalDateTime.of(2026, 11, 18, 10, 1));
|
||||
return task;
|
||||
}
|
||||
|
||||
@Test
|
||||
void 总览三档计数与已结束数() {
|
||||
when(fileTaskMapper.selectCount(any())).thenReturn(2L, 3L, 1L);
|
||||
|
||||
var vo = service.dashboard(7L);
|
||||
|
||||
assertThat(vo.getPendingTaskCount()).isEqualTo(2L);
|
||||
assertThat(vo.getSuccessTaskCount()).isEqualTo(3L);
|
||||
assertThat(vo.getFailedTaskCount()).isEqualTo(1L);
|
||||
assertThat(vo.getProcessedTaskCount()).as("已结束=成功+失败").isEqualTo(4L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void 历史行读真源_行级四档计数与建单载荷带回() {
|
||||
FileTaskEntity running = task(34400L, 7L, "RUNNING");
|
||||
FileTaskEntity failed = task(34399L, 7L, "FAILED");
|
||||
// selectList 先出 history 主查询(按 createdAt 倒序 limit),乱序返回验证排序
|
||||
when(fileTaskMapper.selectList(any())).thenReturn(new ArrayList<>(List.of(failed, running)));
|
||||
// 一条 GROUP BY(task_id, publish_status)出全部任务的四档计数
|
||||
when(jdPublishItemMapper.selectMaps(any())).thenReturn(List.of(
|
||||
Map.of("task_id", 34400L, "publish_status", "SUCCESS", "cnt", 5L),
|
||||
Map.of("task_id", 34400L, "publish_status", "PUBLISHING", "cnt", 2L),
|
||||
Map.of("task_id", 34399L, "publish_status", "SUCCESS", "cnt", 3L),
|
||||
Map.of("task_id", 34399L, "publish_status", "FAILED", "cnt", 1L)));
|
||||
|
||||
var vo = service.history(7L, 50);
|
||||
|
||||
assertThat(vo.getItems()).hasSize(2);
|
||||
// 活跃(RUNNING)排前:失败任务往后靠
|
||||
assertThat(vo.getItems().get(0).getTaskId()).isEqualTo(34400L);
|
||||
var first = vo.getItems().get(0);
|
||||
assertThat(first.getCategoryId()).as("分类 id 随建单载荷带回").isEqualTo(3L);
|
||||
assertThat(first.getPriceRule())
|
||||
.as("改价规则随建单载荷带回(重试重建推送载荷与建单响应 queuePayload 同键)")
|
||||
.containsEntry("mode", "percent").containsEntry("value", java.math.BigDecimal.TEN);
|
||||
assertThat(first.getProductTotal()).as("总行数=四档计数之和(SUCCESS5+PUBLISHING2)").isEqualTo(7L);
|
||||
assertThat(first.getSuccessCount()).isEqualTo(5L);
|
||||
assertThat(first.getPublishingCount()).isEqualTo(2L);
|
||||
assertThat(first.getPendingCount()).isEqualTo(0L);
|
||||
assertThat(first.getFailedCount()).isEqualTo(0L);
|
||||
var second = vo.getItems().get(1);
|
||||
assertThat(second.getTaskStatus()).isEqualTo("FAILED");
|
||||
assertThat(second.getFailedCount()).as("失败行单独计数").isEqualTo(1L);
|
||||
assertThat(second.getSuccessCount()).isEqualTo(3L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void 批量进度按模块过滤_非本模块任务进missingTaskIds() {
|
||||
FileTaskEntity publish = task(88L, 7L, "RUNNING");
|
||||
FileTaskEntity collect = task(89L, 7L, "RUNNING");
|
||||
collect.setModuleType("JD_SHOP_COLLECT");
|
||||
when(fileTaskMapper.selectList(any())).thenReturn(List.of(publish, collect));
|
||||
when(jdPublishItemMapper.selectMaps(any())).thenReturn(
|
||||
List.of(Map.of("task_id", 88L, "publish_status", "SUCCESS", "cnt", 2L)));
|
||||
|
||||
var vo = service.progressBatch(List.of(88L, 89L, 0L, 88L));
|
||||
|
||||
assertThat(vo.getItems()).hasSize(1);
|
||||
assertThat(vo.getItems().get(0).getTask().getId()).isEqualTo(88L);
|
||||
assertThat(vo.getItems().get(0).getItems().get(0).getSuccessCount()).isEqualTo(2L);
|
||||
assertThat(vo.getMissingTaskIds())
|
||||
.as("非本模块任务不冒充面板条目;非法/重复 id 归一化后不影响")
|
||||
.containsExactly(89L);
|
||||
}
|
||||
|
||||
@Test
|
||||
void 删除任务_归属不符一律拒_不碰明细表() {
|
||||
FileTaskEntity other = task(88L, 9L, "FAILED");
|
||||
when(fileTaskMapper.selectById(88L)).thenReturn(other);
|
||||
|
||||
assertThatThrownBy(() -> service.deleteTask(88L, 7L))
|
||||
.isInstanceOf(BusinessException.class)
|
||||
.hasMessageContaining("任务不存在");
|
||||
verify(jdPublishItemMapper, never()).delete(any());
|
||||
verify(fileTaskMapper, never()).deleteById(any(java.io.Serializable.class));
|
||||
}
|
||||
|
||||
@Test
|
||||
void 删除任务_先清明细快照行再清任务行() {
|
||||
FileTaskEntity mine = task(88L, 7L, "FAILED");
|
||||
when(fileTaskMapper.selectById(88L)).thenReturn(mine);
|
||||
when(jdPublishItemMapper.delete(any())).thenReturn(2);
|
||||
|
||||
service.deleteTask(88L, 7L);
|
||||
|
||||
InOrder order = inOrder(jdPublishItemMapper, fileTaskMapper);
|
||||
order.verify(jdPublishItemMapper).delete(any());
|
||||
order.verify(fileTaskMapper).deleteById(any(java.io.Serializable.class));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,615 @@
|
||||
<script setup lang="ts">
|
||||
import { computed, onMounted, onUnmounted, ref } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import TaskCenterPanel from '@/shared/components/tasks/TaskCenterPanel.vue'
|
||||
import type { TaskItemView, TaskStatCard } from '@/shared/components/tasks/types'
|
||||
import {
|
||||
fetchJdCollectGroups,
|
||||
type JdCollectGroupVo,
|
||||
} from '@/shared/api/types/modules/jd-collect'
|
||||
import {
|
||||
activateJdPublishTask,
|
||||
createJdPublishTask,
|
||||
deleteJdPublishTask,
|
||||
fetchJdPublishDashboard,
|
||||
fetchJdPublishHistory,
|
||||
fetchJdPublishProducts,
|
||||
fetchJdPublishTaskProgressBatch,
|
||||
interruptJdPublishTask,
|
||||
type JdPublishHistoryItemVo,
|
||||
type JdPublishProductVo,
|
||||
} from '@/shared/api/types/modules/jd-publish'
|
||||
import { retryClientTask } from '@/shared/api/task-retry'
|
||||
import { getPywebviewApi } from '@/shared/bridges/pywebview'
|
||||
import { resolvePageHref } from '@/shared/page-prefix'
|
||||
import { userNotice } from '@/shared/utils/user-notice'
|
||||
import { formatDateTime } from '@/shared/utils/datetime'
|
||||
import { useLiveTaskBoard } from '@/shared/composables/useLiveTaskBoard'
|
||||
import NotificationBell from '@/shared/components/NotificationBell.vue'
|
||||
|
||||
/** 京东「商品上架」(v1.5 蓝图 §4 Phase 4):选分类 → 勾商品 → 改价规则 → 建单 → 右侧任务面板实时行级进度。
|
||||
*
|
||||
* 六条边界(照 v1.4/v1.5 已落地的采集契约与外观专利任务面板骨架,不另造流程):
|
||||
* 1. 分类选项唯一来源=jdCollect.groups 既有出口(B113-01,AC-9 源码绊线钉死:本页不得自拼
|
||||
* 分类 URL);分组下的商品列表走 jdPublish.products(AC-9 owner 过滤:服务端只回归属
|
||||
* 当前登录用户的行),页内翻页、勾选跨页累计;
|
||||
* 2. 改价规则三档(none/percent/fixed,蓝图 §3 死契约),与勾选集一起进建单体;服务端按
|
||||
* 同一规则折算 SKU 价(铁律 27a 改价同源);
|
||||
* 3. 建单成功把服务端下发的 queuePayload(type=jd-product-publish-run,铁律 32 第三件)原样
|
||||
* 推进本机客户端队列;激活(PENDING→RUNNING)必须在推队列之前(2026-11-14 采集链真机
|
||||
* 实录同因);推送失败不回滚建单(兜底拉取认领);
|
||||
* 4. 进度只读服务端:行级四档计数来自发布明细表聚合,total 缺失时只报已发布行数,不编造百分比;
|
||||
* 5. 失败/中断「重试/继续」走通用原位复位(铁律 26,不克隆),推送载荷从历史行的建单载荷
|
||||
* (分类 id+改价规则)同源重建——与建单响应 queuePayload 同键同形状;
|
||||
* 6. 京麦未登录等凭据致命失败(铁律 31):服务端整单判死后 useLiveTaskBoard 经
|
||||
* reportCredentialFatal 弹一次窗(credential-fatal 同形接入,AC-5 用户端半边;弹窗组件
|
||||
* 挂 App.vue,本页无需重复挂)。
|
||||
*/
|
||||
|
||||
const homeHref = resolvePageHref('/new_web_source/home.html')
|
||||
const backHref = resolvePageHref('/new_web_source/jd-console.html')
|
||||
|
||||
const username = ref('admin')
|
||||
const submitting = ref(false)
|
||||
const errorMessage = ref('')
|
||||
const successMessage = ref('')
|
||||
|
||||
function uidForStorage() {
|
||||
return typeof window !== 'undefined' ? window.localStorage.getItem('uid') || '0' : '0'
|
||||
}
|
||||
|
||||
// ---- 分类选择(AC-9:唯一来源是 jdCollect 组的既有 fetch 函数,不自拼 URL)----
|
||||
const jdCollectGroupLoader = fetchJdCollectGroups
|
||||
const groupOptions = ref<JdCollectGroupVo[]>([])
|
||||
const groupsLoading = ref(false)
|
||||
const selectedGroupId = ref<number | null>(null)
|
||||
|
||||
async function loadGroups() {
|
||||
groupsLoading.value = true
|
||||
try {
|
||||
const vo = await jdCollectGroupLoader()
|
||||
groupOptions.value = vo ?? []
|
||||
// 默认选中第一个分类:分类是建单的展示维度,缺省选中省一次点击;商品列表随之拉取。
|
||||
if (!selectedGroupId.value && groupOptions.value.length) {
|
||||
selectedGroupId.value = groupOptions.value[0].id
|
||||
}
|
||||
} finally {
|
||||
groupsLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 选品分页(owner 过滤在服务端;勾选跨页累计在本地 Map,翻页不清空)----
|
||||
const PRODUCT_PAGE_SIZE = 12
|
||||
const products = ref<JdPublishProductVo[]>([])
|
||||
const productTotal = ref(0)
|
||||
const productPage = ref(1)
|
||||
const productsLoading = ref(false)
|
||||
const selectedProducts = ref(new Map<number, JdPublishProductVo>())
|
||||
|
||||
const selectedProductIds = computed(() => Array.from(selectedProducts.value.keys()))
|
||||
|
||||
function toggleProduct(row: JdPublishProductVo, checked: boolean) {
|
||||
const next = new Map(selectedProducts.value)
|
||||
if (checked) next.set(row.id, row)
|
||||
else next.delete(row.id)
|
||||
selectedProducts.value = next
|
||||
}
|
||||
|
||||
function clearSelection() {
|
||||
selectedProducts.value = new Map()
|
||||
}
|
||||
|
||||
async function loadProducts() {
|
||||
productsLoading.value = true
|
||||
try {
|
||||
const vo = await fetchJdPublishProducts(selectedGroupId.value, productPage.value, PRODUCT_PAGE_SIZE)
|
||||
products.value = vo.items ?? []
|
||||
productTotal.value = vo.total ?? 0
|
||||
} catch (err) {
|
||||
errorMessage.value = err instanceof Error ? err.message : '商品列表拉取失败,请稍后重试'
|
||||
} finally {
|
||||
productsLoading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function changePage(page: number) {
|
||||
productPage.value = page
|
||||
void loadProducts()
|
||||
}
|
||||
|
||||
// ---- 改价规则(蓝图 §3:none/percent/fixed 三档;percent=百分数,fixed=加价金额)----
|
||||
const PRICE_RULE_MODES = [
|
||||
{ value: 'none', label: '按原价上架' },
|
||||
{ value: 'percent', label: '按比例加价(%)' },
|
||||
{ value: 'fixed', label: '固定加价(元)' },
|
||||
] as const
|
||||
const priceMode = ref<'none' | 'percent' | 'fixed'>('none')
|
||||
const priceValue = ref<number | null>(null)
|
||||
|
||||
const priceValueMissing = computed(() => priceMode.value !== 'none' && (priceValue.value == null || priceValue.value < 0))
|
||||
|
||||
const submitDisabled = computed(() =>
|
||||
submitting.value
|
||||
|| !selectedGroupId.value
|
||||
|| !selectedProducts.value.size
|
||||
|| priceValueMissing.value)
|
||||
|
||||
// ---- 实时任务面板(照 JdCollectTab 的 useLiveTaskBoard 形状;京东发布无结果文件,无下载层)----
|
||||
const board = useLiveTaskBoard<JdPublishHistoryItemVo>({
|
||||
scope: 'jd-publish',
|
||||
pollingStorageKey: () => `jd-publish:tasks:${uidForStorage()}`,
|
||||
fetchHistory: fetchJdPublishHistory,
|
||||
fetchProgressBatch: fetchJdPublishTaskProgressBatch,
|
||||
fetchDashboard: fetchJdPublishDashboard,
|
||||
normalizeTaskStatus,
|
||||
// 京东发布没有结果文件:状态到终态即结束,没有「等文件」那一层
|
||||
isResultPreparing: () => false,
|
||||
addPendingAfterFinalStatus: () => false,
|
||||
keepPendingFileTask: () => false,
|
||||
// CANCELLED 也是终态:中断的任务出「继续」按钮并停止轮询
|
||||
settleOnTaskStatuses: ['SUCCESS', 'FAILED', 'CANCELLED'],
|
||||
deleteTask: {
|
||||
shouldDeleteTask: (item) => item.taskId != null,
|
||||
deleteTask: (taskId) => deleteJdPublishTask(taskId),
|
||||
deleteHistory: async () => undefined,
|
||||
onTaskDeleted: (item) => board.removePollingTask(item.taskId as number),
|
||||
},
|
||||
})
|
||||
|
||||
const { batchDeleteHistory, deleteTaskRecord } = board
|
||||
|
||||
const jdCards = computed<TaskStatCard[]>(() => [
|
||||
{ label: '运行中任务', value: board.dashboard.value.pendingTaskCount },
|
||||
{ label: '已结束任务', value: board.dashboard.value.processedTaskCount },
|
||||
{ label: '成功任务', value: board.dashboard.value.successTaskCount },
|
||||
{ label: '失败任务', value: board.dashboard.value.failedTaskCount },
|
||||
])
|
||||
|
||||
const currentTaskViews = computed<TaskItemView[]>(() =>
|
||||
board.currentItems.value.map(toJdPublishTaskView),
|
||||
)
|
||||
const historyTaskViews = computed<TaskItemView[]>(() =>
|
||||
board.historyOnlyItems.value.map(toJdPublishTaskView),
|
||||
)
|
||||
|
||||
function itemSource(item: TaskItemView) {
|
||||
return item.source as JdPublishHistoryItemVo
|
||||
}
|
||||
|
||||
function toJdPublishTaskView(item: JdPublishHistoryItemVo): TaskItemView {
|
||||
const showProgress = isActiveTask(item)
|
||||
const total = typeof item.productTotal === 'number' && item.productTotal > 0 ? item.productTotal : null
|
||||
const published = (item.successCount ?? 0) + (item.failedCount ?? 0)
|
||||
return {
|
||||
key: `jd-publish-${item.taskId ?? item.taskNo ?? item.updatedAt ?? ''}`,
|
||||
title: `商品上架 · ${total ?? '—'} 个商品`,
|
||||
taskId: item.taskId ?? '-',
|
||||
startedAt: formatDateTime(item.createdAt),
|
||||
finishedAt: formatDateTime(item.finishedAt),
|
||||
statusText: statusText(item),
|
||||
statusClass: statusClass(item),
|
||||
extraLines: [
|
||||
`成功 ${item.successCount ?? 0} / 失败 ${item.failedCount ?? 0}`
|
||||
+ (item.publishingCount ? ` / 发布中 ${item.publishingCount}` : ''),
|
||||
...(showProgress && total ? [`已发布 ${Math.min(published, total)}/${total} 个商品`] : []),
|
||||
...(item.errorMessage ? [`错误:${userNotice(item.errorMessage)}`] : []),
|
||||
],
|
||||
progress: showProgress ? { percent: progressPercent(item), countLabel: progressCountLabel(item) } : null,
|
||||
source: item,
|
||||
}
|
||||
}
|
||||
|
||||
// ---- 本模块的状态语义(京东发布:无结果文件,状态即终态)----
|
||||
|
||||
function normalizeTaskStatus(item: JdPublishHistoryItemVo | null | undefined) {
|
||||
return (item?.taskStatus || '').toUpperCase()
|
||||
}
|
||||
|
||||
function isActiveTask(item: JdPublishHistoryItemVo) {
|
||||
const status = normalizeTaskStatus(item)
|
||||
return status === 'PENDING' || status === 'RUNNING' || status === 'SCHEDULED'
|
||||
}
|
||||
|
||||
function statusText(item: JdPublishHistoryItemVo) {
|
||||
const status = normalizeTaskStatus(item)
|
||||
if (status === 'RUNNING') return '正在发布到京麦…'
|
||||
if (status === 'PENDING') return '等待本机客户端领取任务…'
|
||||
if (status === 'SCHEDULED') return '已排队,等待执行'
|
||||
if (status === 'CANCELLED') return '已中断'
|
||||
if (status === 'FAILED') return '发布失败'
|
||||
if (status === 'SUCCESS' || item.success) return '发布完成'
|
||||
return '等待中'
|
||||
}
|
||||
|
||||
function statusClass(item: JdPublishHistoryItemVo) {
|
||||
const status = normalizeTaskStatus(item)
|
||||
if (status === 'FAILED') return 'failed'
|
||||
if (status === 'RUNNING' || status === 'SCHEDULED') return 'running'
|
||||
if (status === 'CANCELLED') return 'pending'
|
||||
if (status === 'SUCCESS' || item.success) return 'success'
|
||||
return 'pending'
|
||||
}
|
||||
|
||||
/** 百分比:有 total 按已发布行数算(封顶 99 直到服务端落 SUCCESS);没有 total 不编造分母。 */
|
||||
function progressPercent(item: JdPublishHistoryItemVo) {
|
||||
const status = normalizeTaskStatus(item)
|
||||
if (status === 'SUCCESS') return 100
|
||||
const total = typeof item.productTotal === 'number' && item.productTotal > 0 ? item.productTotal : null
|
||||
if (!total) return 0
|
||||
const done = Math.min((item.successCount ?? 0) + (item.failedCount ?? 0), total)
|
||||
return Math.max(0, Math.min(99, Math.round((done * 100) / total)))
|
||||
}
|
||||
|
||||
/** 计数文案:有 total 带分母和百分比;没有 total 只报行数,不编造分母。 */
|
||||
function progressCountLabel(item: JdPublishHistoryItemVo) {
|
||||
const published = (item.successCount ?? 0) + (item.failedCount ?? 0)
|
||||
const total = typeof item.productTotal === 'number' && item.productTotal > 0 ? item.productTotal : null
|
||||
if (!total) return `已发布 ${published} 个商品`
|
||||
return `已发布 ${published}/${total} 个商品(${progressPercent(item)}%)`
|
||||
}
|
||||
|
||||
/** 失败/已中断的任务能续跑:在原任务上复位(不新建任务)。 */
|
||||
function canRetryTask(item: JdPublishHistoryItemVo | null | undefined): boolean {
|
||||
if (!item?.taskId) return false
|
||||
const status = normalizeTaskStatus(item)
|
||||
return status === 'FAILED' || status === 'CANCELLED'
|
||||
}
|
||||
|
||||
/** 按钮文案:已中断的任务显示「继续」(从断点接着跑),失败任务仍是「重试」。 */
|
||||
function retryLabel(item: JdPublishHistoryItemVo | null | undefined): string {
|
||||
return normalizeTaskStatus(item) === 'CANCELLED' ? '继续' : '重试'
|
||||
}
|
||||
|
||||
/** 在跑/待跑的任务可中断:PENDING/RUNNING/SCHEDULED 是服务端 CAS 的同一 ACTIVE 集合。 */
|
||||
function canInterruptTask(item: JdPublishHistoryItemVo | null | undefined): boolean {
|
||||
if (!item?.taskId) return false
|
||||
const status = normalizeTaskStatus(item)
|
||||
return status === 'PENDING' || status === 'RUNNING' || status === 'SCHEDULED'
|
||||
}
|
||||
|
||||
async function interruptTaskRecord(item: JdPublishHistoryItemVo | null | undefined) {
|
||||
const taskId = item?.taskId
|
||||
if (!taskId) return
|
||||
// 确认框取消走 reject 两臂(与采集页同口径,不新增 catch 块)
|
||||
const confirmed = await ElMessageBox.confirm(
|
||||
'中断后:本机客户端会停止发布,已发布的商品保留在京麦与发布明细里。确定中断吗?',
|
||||
'中断任务',
|
||||
{ type: 'warning', confirmButtonText: '中断', cancelButtonText: '先不中断' },
|
||||
).then(
|
||||
() => true,
|
||||
() => false,
|
||||
)
|
||||
if (!confirmed) return
|
||||
try {
|
||||
await interruptJdPublishTask(taskId)
|
||||
ElMessage.success('已中断:客户端下一跳心跳后收手,之后可点「继续」接着跑')
|
||||
await refreshBoard()
|
||||
} catch (error) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '中断失败')
|
||||
}
|
||||
}
|
||||
|
||||
async function retryTaskRecord(item: JdPublishHistoryItemVo | null | undefined) {
|
||||
const taskId = item?.taskId
|
||||
if (!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) {
|
||||
ElMessage.error(error instanceof Error ? error.message : '重试失败')
|
||||
}
|
||||
}
|
||||
|
||||
/** 手动刷新:强拉历史 + 统计 + 当前轮询任务进度 */
|
||||
async function refreshBoard() {
|
||||
await Promise.all([
|
||||
board.loadDashboard(),
|
||||
board.loadHistory({ force: true }),
|
||||
board.refreshTaskProgress(),
|
||||
])
|
||||
}
|
||||
|
||||
/** 激活任务(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 '任务激活失败,本机客户端领不到这一单,请稍后重试'
|
||||
}
|
||||
}
|
||||
|
||||
/** 推送本机队列:建单路径传服务端下发的 queuePayload(页面不拼载荷),重试路径按同键形状重建后传入。 */
|
||||
async function pushToClientQueue(payload: Record<string, unknown>): Promise<string | null> {
|
||||
const api = getPywebviewApi()
|
||||
if (!api?.enqueue_json) {
|
||||
return '当前环境未启用任务队列能力(浏览器预览环境不会启动),请在本机客户端中打开本页'
|
||||
}
|
||||
const pushResult = await api.enqueue_json(payload)
|
||||
if (pushResult?.success) {
|
||||
return null
|
||||
}
|
||||
// 桥返回的 error 原文(系统/英文)不透传进界面:console 留链,界面固定中文动作句
|
||||
if (pushResult?.error) {
|
||||
console.error('[jd-publish] enqueue_json 被拒', pushResult.error)
|
||||
}
|
||||
return '推送本机队列失败,任务将由客户端兜底拉取认领'
|
||||
}
|
||||
|
||||
const isRunning = computed(() => Boolean(board.dashboard.value.pendingTaskCount) || submitting.value)
|
||||
|
||||
const priceRuleHint = computed(() => {
|
||||
if (priceMode.value === 'none') return '按京东数据库里的采集原价上架。'
|
||||
if (priceMode.value === 'percent') return '按采集价上浮 N%(填 10 表示加价 10%)。'
|
||||
return '每个商品统一加固定金额(填 5 表示加 5 元)。'
|
||||
})
|
||||
|
||||
async function startPublish() {
|
||||
if (submitDisabled.value) return
|
||||
errorMessage.value = ''
|
||||
successMessage.value = ''
|
||||
submitting.value = true
|
||||
try {
|
||||
const priceRule = priceMode.value === 'none'
|
||||
? { mode: 'none' as const }
|
||||
: { mode: priceMode.value, value: priceValue.value as number }
|
||||
// 勾选集即建单 productIds;selectedGroupId 即建单体 categoryId
|
||||
// (服务端按 owner 校验,选了他人商品当场拒,AC-9)。
|
||||
const categoryId = selectedGroupId.value
|
||||
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} 个商品)并推送给本机客户端,进度显示在右侧任务区`
|
||||
}
|
||||
await Promise.all([board.loadDashboard(), board.loadHistory({ force: true })])
|
||||
} catch (err) {
|
||||
errorMessage.value = err instanceof Error ? err.message : '建单失败,请稍后重试'
|
||||
} finally {
|
||||
submitting.value = false
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
const localName = (window.localStorage.getItem('username') || '').trim()
|
||||
if (localName) username.value = localName
|
||||
board.loadPollingIds()
|
||||
await Promise.all([
|
||||
loadGroups().catch(() => undefined),
|
||||
board.loadDashboard().catch(() => undefined),
|
||||
board.loadHistory().catch(() => undefined),
|
||||
])
|
||||
board.seedRunningTasksFromHistory()
|
||||
board.seedPendingFileTasksFromHistory()
|
||||
board.ensurePollingIfAny()
|
||||
void loadProducts()
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
board.dispose()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="page-shell module-page jd-publish-page">
|
||||
<header class="jd-top">
|
||||
<router-link class="home-back" :to="homeHref" title="返回首页">← 返回首页</router-link>
|
||||
<div class="brand">
|
||||
<span class="brand-logo">富</span>
|
||||
<span class="brand-text">
|
||||
<span class="brand-name">数富AI</span>
|
||||
<span class="brand-sub">京东运营工具台</span>
|
||||
</span>
|
||||
</div>
|
||||
<div class="top-right">
|
||||
<NotificationBell />
|
||||
<span class="admin-name">{{ username }}</span>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div class="tool-head">
|
||||
<router-link class="tool-head__back" :to="backHref">← 返回京东工具台</router-link>
|
||||
<span class="tool-head__title">商品上架</span>
|
||||
<span class="tool-head__desc">
|
||||
把京东数据库里你自己的商品批量上架到京麦店铺:选分类、勾商品、可选统一改价,本机已登录京麦的客户端逐个发布。
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<main class="jd-body">
|
||||
<aside class="left-panel">
|
||||
<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() }">
|
||||
<el-option v-for="group in groupOptions" :key="group.id"
|
||||
:label="`${group.name}(${group.productCount ?? 0} 个商品)`" :value="group.id" />
|
||||
</el-select>
|
||||
<p class="category-hint">分类由管理员在后台「京东数据库」维护;列表只显示归属你账号的商品。</p>
|
||||
</div>
|
||||
|
||||
<div class="product-block" v-loading="productsLoading">
|
||||
<div class="product-head">
|
||||
<span class="category-label">选择商品(已选 {{ selectedProducts.size }} 个,跨页累计)</span>
|
||||
<button v-if="selectedProducts.size" class="shop-cat-clear" type="button"
|
||||
@click="clearSelection">清空勾选</button>
|
||||
</div>
|
||||
<div v-if="!products.length && !productsLoading" class="product-empty">
|
||||
{{ selectedGroupId ? '该分类下暂无归属你账号的商品' : '请先选择分类' }}
|
||||
</div>
|
||||
<label v-for="product in products" :key="product.id" class="product-row">
|
||||
<input type="checkbox" class="product-check"
|
||||
:checked="selectedProducts.has(product.id)"
|
||||
@change="toggleProduct(product, ($event.target as HTMLInputElement).checked)" />
|
||||
<img v-if="product.mainImageUrl" class="product-thumb" :src="product.mainImageUrl" alt="" loading="lazy" />
|
||||
<span v-else class="product-thumb product-thumb--empty">无图</span>
|
||||
<span class="product-info">
|
||||
<span class="product-title">{{ product.title }}</span>
|
||||
<span class="product-meta">
|
||||
¥{{ product.priceMin ?? '-' }}<template v-if="product.priceMax && product.priceMax !== product.priceMin">~{{ product.priceMax }}</template>
|
||||
· 库存 {{ product.stockTotal ?? '-' }}<template v-if="product.skuCount"> · {{ product.skuCount }}个SKU</template>
|
||||
</span>
|
||||
</span>
|
||||
</label>
|
||||
<el-pagination v-if="productTotal > PRODUCT_PAGE_SIZE" class="product-pager" layout="prev, pager, next"
|
||||
:total="productTotal" :page-size="PRODUCT_PAGE_SIZE" :current-page="productPage"
|
||||
@current-change="changePage" />
|
||||
</div>
|
||||
|
||||
<div class="category-block">
|
||||
<span class="category-label">改价规则(可选)</span>
|
||||
<el-select v-model="priceMode" class="shop-cat-select">
|
||||
<el-option v-for="mode in PRICE_RULE_MODES" :key="mode.value" :label="mode.label" :value="mode.value" />
|
||||
</el-select>
|
||||
<el-input-number v-if="priceMode !== 'none'" v-model="priceValue" :min="0" :precision="2"
|
||||
:step="priceMode === 'percent' ? 1 : 0.5" class="price-input" controls-position="right"
|
||||
:placeholder="priceMode === 'percent' ? '加价百分比' : '加价金额'" />
|
||||
<p class="category-hint">{{ priceRuleHint }}</p>
|
||||
</div>
|
||||
|
||||
<button class="collect-btn" type="button" :disabled="submitDisabled" @click="startPublish">
|
||||
{{ submitting ? '创建中…' : `上架已选 ${selectedProducts.size} 个商品` }}
|
||||
</button>
|
||||
|
||||
<p class="collect-hint">
|
||||
点击后本机客户端会逐个把商品发布到已登录的京麦店铺,请保持客户端在线且京麦已登录;发布进度逐行显示在右侧任务区。
|
||||
</p>
|
||||
|
||||
<p v-if="successMessage" class="feedback success">{{ successMessage }}</p>
|
||||
<p v-if="errorMessage" class="feedback error">{{ errorMessage }}</p>
|
||||
</aside>
|
||||
|
||||
<section class="right-panel">
|
||||
<TaskCenterPanel
|
||||
:on-batch-delete="batchDeleteHistory"
|
||||
:on-refresh="refreshBoard"
|
||||
title="商品上架"
|
||||
:cards="jdCards"
|
||||
:current-items="currentTaskViews"
|
||||
:history-items="historyTaskViews"
|
||||
current-title="当前任务"
|
||||
current-empty-text="暂无当前任务"
|
||||
history-empty-text="暂无历史记录"
|
||||
>
|
||||
<template #item-actions="{ item }">
|
||||
<button v-if="canInterruptTask(itemSource(item))" type="button" class="btn-interrupt"
|
||||
@click="interruptTaskRecord(itemSource(item))">中断</button>
|
||||
<button v-if="canRetryTask(itemSource(item))" type="button" class="btn-retry"
|
||||
@click="retryTaskRecord(itemSource(item))">{{ retryLabel(itemSource(item)) }}</button>
|
||||
<button type="button" class="btn-delete" @click="deleteTaskRecord(itemSource(item))">删除</button>
|
||||
</template>
|
||||
<template #history-item-actions="{ item }">
|
||||
<button v-if="canInterruptTask(itemSource(item))" type="button" class="btn-interrupt"
|
||||
@click="interruptTaskRecord(itemSource(item))">中断</button>
|
||||
<button v-if="canRetryTask(itemSource(item))" type="button" class="btn-retry"
|
||||
@click="retryTaskRecord(itemSource(item))">{{ retryLabel(itemSource(item)) }}</button>
|
||||
<button v-if="itemSource(item).taskId" type="button" class="btn-delete"
|
||||
@click="deleteTaskRecord(itemSource(item))">删除</button>
|
||||
</template>
|
||||
</TaskCenterPanel>
|
||||
</section>
|
||||
</main>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<!-- 样式与采集页同族暗色主题(header/brand/工具头为两页共通形状,各自 scoped 不共享);
|
||||
逐规则单行压缩只为过可读棘轮 800 行线,不改任何选择器与声明。 -->
|
||||
<style scoped>
|
||||
.jd-publish-page { display: flex; flex-direction: column; min-height: 100vh; background-color: #1a1f2e; background-image: radial-gradient(rgba(45, 212, 191, 0.08) 1px, transparent 1px); background-size: 48px 48px; font-family: "PingFang SC", "Microsoft YaHei UI", "Microsoft YaHei", "微软雅黑", sans-serif; }
|
||||
.jd-top { flex: 0 0 auto; min-height: 64px; display: flex; align-items: center; justify-content: space-between; gap: 20px; padding: 0 28px; background: #1a1f2e; border-bottom: 1px solid #3e4a62; }
|
||||
.home-back, .tool-head__back { flex-shrink: 0; display: inline-flex; align-items: center; gap: 6px; padding: 6px 14px; border: 1px solid #3e4a62; border-radius: 6px; color: #c8d2e2; font-size: 13px; text-decoration: none; white-space: nowrap; transition: all 0.2s; }
|
||||
.home-back:hover, .tool-head__back:hover { background: #2b3447; color: #f5f8fc; }
|
||||
.brand { display: flex; align-items: center; gap: 12px; flex-shrink: 0; }
|
||||
.brand-logo { display: flex; align-items: center; justify-content: center; width: 38px; height: 38px; border-radius: 8px; background: #e1251b; color: #fff; font-size: 20px; font-weight: 700; box-shadow: 0 2px 8px rgba(225, 37, 27, 0.32); }
|
||||
.brand-text { display: flex; flex-direction: column; line-height: 1.35; }
|
||||
.brand-name { color: #f5f8fc; font-size: 17px; font-weight: 700; white-space: nowrap; }
|
||||
.brand-sub { color: #a0acbe; font-size: 10px; white-space: nowrap; }
|
||||
.top-right { display: flex; align-items: center; gap: 14px; flex-shrink: 0; }
|
||||
.admin-name { color: #c8d2e2; font-size: 13px; font-weight: 700; white-space: nowrap; }
|
||||
.tool-head { flex: 0 0 auto; display: flex; align-items: center; flex-wrap: wrap; gap: 20px; min-height: 62px; padding: 10px 34px; background: #1a1f2e; }
|
||||
.tool-head__title { flex-shrink: 0; color: #f5f8fc; font-size: 22px; font-weight: 700; white-space: nowrap; }
|
||||
.tool-head__desc { min-width: 0; max-width: 760px; color: #a0acbe; font-size: 14px; line-height: 1.5; }
|
||||
.jd-body { flex: 1 1 auto; min-height: 0; display: flex; align-items: stretch; overflow: hidden; }
|
||||
.left-panel { width: 440px; flex-shrink: 0; padding: 20px; overflow-y: auto; border-right: 1px solid #3e4a62; }
|
||||
.right-panel { flex: 1; min-width: 0; display: flex; flex-direction: column; overflow-y: auto; padding: 20px; }
|
||||
.category-block { margin-bottom: 16px; }
|
||||
.category-label { display: block; margin-bottom: 8px; color: #c8d2e2; font-size: 13px; font-weight: 600; }
|
||||
.category-hint { margin: 8px 0 0; color: #7f8ca3; font-size: 12px; line-height: 1.6; }
|
||||
.shop-cat-select { width: 100%; }
|
||||
.shop-cat-select :deep(.el-select__wrapper) { background-color: #232b3d; box-shadow: 0 0 0 1px #3e4a62 inset; }
|
||||
.shop-cat-select :deep(.el-select__placeholder), .shop-cat-select :deep(.el-select__selected-item) { color: #c8d2e2; }
|
||||
.shop-cat-clear { margin-left: 6px; padding: 0; border: none; background: none; color: #6ea8ff; font-size: 12px; cursor: pointer; font-family: inherit; }
|
||||
.shop-cat-clear:hover { text-decoration: underline; }
|
||||
.product-block { margin-bottom: 16px; }
|
||||
.product-head { display: flex; align-items: center; justify-content: space-between; }
|
||||
.product-head .category-label { margin-bottom: 8px; }
|
||||
.product-row { display: flex; align-items: center; gap: 10px; padding: 8px 10px; margin-bottom: 6px; border: 1px solid #2c3547; border-radius: 8px; background: #20283a; cursor: pointer; }
|
||||
.product-row:hover { border-color: #3e4a62; }
|
||||
.product-check { flex-shrink: 0; width: 15px; height: 15px; accent-color: #e1251b; cursor: pointer; }
|
||||
.product-thumb { flex-shrink: 0; width: 44px; height: 44px; border-radius: 6px; object-fit: cover; background: #232b3d; }
|
||||
.product-thumb--empty { display: inline-flex; align-items: center; justify-content: center; color: #5f6c85; font-size: 11px; }
|
||||
.product-info { min-width: 0; display: flex; flex-direction: column; gap: 3px; }
|
||||
.product-title { color: #d9e1ef; font-size: 12px; line-height: 1.4; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden; }
|
||||
.product-meta { color: #8a97ad; font-size: 11px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.product-empty { padding: 18px 0; color: #5f6c85; font-size: 12px; text-align: center; }
|
||||
.product-pager { margin-top: 8px; justify-content: center; }
|
||||
.product-pager :deep(.el-pager li), .product-pager :deep(.btn-prev), .product-pager :deep(.btn-next) { background: transparent; color: #c8d2e2; }
|
||||
.product-pager :deep(.el-pager li.is-active) { color: #6ea8ff; }
|
||||
.price-input { width: 100%; margin-top: 8px; }
|
||||
.price-input :deep(.el-input__wrapper) { background-color: #232b3d; box-shadow: 0 0 0 1px #3e4a62 inset; }
|
||||
.price-input :deep(.el-input__inner) { color: #c8d2e2; }
|
||||
.collect-btn { width: 100%; padding: 13px 0; border: none; border-radius: 8px; background: linear-gradient(135deg, #ff5a4f, #e1251b); color: #ffffff; font-size: 16px; font-weight: 700; font-family: inherit; cursor: pointer; box-shadow: 0 4px 16px rgba(225, 37, 27, 0.32); transition: all 0.2s; }
|
||||
.collect-btn:hover:not(:disabled) { filter: brightness(1.1); transform: translateY(-1px); }
|
||||
.collect-btn:disabled { opacity: 0.6; cursor: not-allowed; }
|
||||
.collect-hint { margin: 12px 0 0; color: #a0acbe; font-size: 12px; line-height: 1.7; }
|
||||
.feedback { margin: 16px 0 0; padding: 10px 12px; border-radius: 8px; font-size: 13px; line-height: 1.6; }
|
||||
.feedback.success { background: rgba(16, 185, 129, 0.12); color: #6ee7b7; }
|
||||
.feedback.error { background: rgba(248, 113, 113, 0.12); color: #fca5a5; }
|
||||
.btn-delete, .btn-retry, .btn-interrupt { border: none; cursor: pointer; border-radius: 6px; font-size: 12px; }
|
||||
.btn-delete { padding: 6px 10px; color: #ff8f8f; background: rgba(231, 76, 60, .12); }
|
||||
.btn-retry { padding: 6px 10px; color: #7fd1a0; background: rgba(39, 174, 96, .14); }
|
||||
.btn-interrupt { padding: 6px 10px; color: #f0b35e; background: rgba(240, 179, 94, .12); }
|
||||
@media (max-width: 1100px) {
|
||||
.tool-head { padding: 10px 16px; gap: 10px; }
|
||||
.jd-body { flex-direction: column; overflow-y: auto; }
|
||||
.left-panel { width: 100%; border-right: none; border-bottom: 1px solid #3e4a62; }
|
||||
.right-panel { padding: 16px; }
|
||||
}
|
||||
</style>
|
||||
@@ -3,7 +3,7 @@
|
||||
*
|
||||
* 一级入口在桌面首页(与「亚马逊 / 视频」并列,见 DesktopHomePage),进来后是这两个菜单:
|
||||
* 1. 获取店铺数据:一键抓已登录京麦后台的店铺商品(列表 + 详情 + 图片),落后台「京东数据库」;
|
||||
* 2. 商品上架:功能未落地,先按"假菜单"占位(点击提示暂未开通),不发 href。
|
||||
* 2. 商品上架(v1.5 Phase 4 转正式):选自定义分类勾商品建单,本机已登录京麦的客户端逐个发布;
|
||||
*
|
||||
* 卡片形状照亚马逊工具台(tool-catalog.ts)的 ToolInfo,样式复用同一套深色卡片墙。
|
||||
*
|
||||
@@ -44,8 +44,9 @@ export const JD_TOOLS: ReadonlyArray<JdToolInfo> = [
|
||||
{
|
||||
id: 'jd-publish',
|
||||
name: '商品上架',
|
||||
desc: '把京东数据库里的商品批量上架到京麦店铺(建设中,敬请期待)',
|
||||
tag: '规划中',
|
||||
desc: '把京东数据库里你自己的商品批量上架到京麦店铺:选分类、勾商品、可选统一改价,本机客户端逐个发布',
|
||||
tag: '核心',
|
||||
href: '/jd-publish',
|
||||
permissionKeys: ['jd-publish'],
|
||||
},
|
||||
]
|
||||
|
||||
@@ -78,6 +78,11 @@ const routes = [
|
||||
name: 'jd-collect',
|
||||
component: () => import('@/pages/jd/JdCollectTab.vue'),
|
||||
},
|
||||
{
|
||||
path: '/jd-publish',
|
||||
name: 'jd-publish',
|
||||
component: () => import('@/pages/jd/JdPublishTab.vue'),
|
||||
},
|
||||
{
|
||||
path: '/split',
|
||||
name: 'split',
|
||||
|
||||
@@ -226,6 +226,25 @@ 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',
|
||||
/** 任务面板总览(运行中/成功/失败计数统计卡) */
|
||||
dashboard: '/api/jd-publish/dashboard',
|
||||
/** 任务历史(活跃任务排前,含行级四档计数与建单载荷带回) */
|
||||
history: '/api/jd-publish/history',
|
||||
/** 批量任务进度(面板轮询专用,归属先经公共出口过滤) */
|
||||
progressBatch: '/api/jd-publish/tasks/progress/batch',
|
||||
/** 单任务行级进度(行级四档计数;面板批量口覆盖不到的兜底) */
|
||||
progress: '/api/jd-publish/tasks/{taskId}/progress',
|
||||
/** 删除任务(连带清理该任务的发布明细快照行) */
|
||||
deleteTask: '/api/jd-publish/tasks/{taskId}',
|
||||
},
|
||||
userSecret: {
|
||||
bundle: '/api/user-secrets',
|
||||
save: '/api/user-secrets/{moduleKey}',
|
||||
|
||||
@@ -0,0 +1,283 @@
|
||||
import { get, post, del, type JavaApiResponse, unwrapJavaResponse } from '../../http.ts'
|
||||
import { buildJavaUrl, JAVA_API_PREFIX } from '../../url.ts'
|
||||
import { getCurrentUserId } from '../../user.ts'
|
||||
import { API_ENDPOINTS } from '../../endpoints.ts'
|
||||
import { getTaskProgressCacheTtlMs, getTaskProgressTimeoutMs } from '../../../task-progress-config.ts'
|
||||
import { createTaskProgressRequestCache } from '../../../task-progress-request-cache.ts'
|
||||
|
||||
/**
|
||||
* 京东商品上架(v1.5 蓝图 docs/ITERATION_PLAN.md §3/§4 Phase 4):用户端「京东工具台 →
|
||||
* 商品上架」选自定义分类 → 勾选归属自己的商品(AC-9 owner 过滤)→ 可选统一改价规则 →
|
||||
* 建单(服务端落 PENDING、执行通道显式 LOCAL)→ 建单响应 queuePayload 原样投
|
||||
* api.enqueue_json 推本机客户端(铁律 32 第三件,type 与 SPI QUEUE_TYPE 同值)。
|
||||
*
|
||||
* 面板三件(dashboard/history/progressBatch)与删除/中断照 jd-collect 同族形状;
|
||||
* 分类读取唯一来源仍是 jdCollect.groups 既有出口(B113-01,AC-9 源码绊线钉死)。
|
||||
*/
|
||||
|
||||
/** 建单回执:任务落 PENDING;queuePayload 页面直推本机队列(服务端组装,页面不拼载荷)。 */
|
||||
export interface JdPublishTaskVo {
|
||||
taskId: number;
|
||||
taskNo?: string;
|
||||
collectChannel?: string;
|
||||
/** {type:'jd-product-publish-run', data:{taskId, priceRule}}(铁律 32 第三件) */
|
||||
queuePayload?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
/** 建单统一改价规则:none 原价 / percent 加价百分比(value=百分数) / fixed 固定加价(value=金额)。 */
|
||||
export interface JdPublishPriceRule {
|
||||
mode: 'none' | 'percent' | 'fixed';
|
||||
value?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* 建单(AC-1/AC-8/AC-9):categoryId=所选自定义分类;productIds=勾选的商品行 id 集
|
||||
* (服务端按 owner 校验,选了他人商品/超配额当场业务码拒绝并点名文案)。
|
||||
* 请求体是 JSON(@RequestBody + JdPublishTaskCreateRequest),字段名 camelCase 与采集建单同口径。
|
||||
*/
|
||||
export function createJdPublishTask(
|
||||
categoryId: number | null,
|
||||
productIds: number[],
|
||||
priceRule: JdPublishPriceRule,
|
||||
) {
|
||||
return unwrapJavaResponse(post<JavaApiResponse<JdPublishTaskVo>, Record<string, unknown>>(
|
||||
buildJavaUrl(API_ENDPOINTS.jdPublish.create),
|
||||
{
|
||||
userId: getCurrentUserId(),
|
||||
categoryId,
|
||||
productIds,
|
||||
// mode=none 时不带 value(后端 normalizePriceRule 对 none 忽略 value)
|
||||
priceRule: priceRule.mode === 'none' ? { mode: 'none' } : priceRule,
|
||||
},
|
||||
))
|
||||
}
|
||||
|
||||
/** 激活任务(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 不下发)。
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export interface JdPublishProductVo {
|
||||
id: number;
|
||||
shopName?: string;
|
||||
productCode?: string;
|
||||
skuCount?: number;
|
||||
title?: string;
|
||||
categoryPath?: string;
|
||||
priceMin?: number;
|
||||
priceMax?: number;
|
||||
stockTotal?: number;
|
||||
saleStatus?: string;
|
||||
mainImageUrl?: string;
|
||||
imageCount?: number;
|
||||
syncedAt?: string;
|
||||
}
|
||||
|
||||
export interface JdPublishProductPageVo {
|
||||
items: JdPublishProductVo[];
|
||||
total: number;
|
||||
page: number;
|
||||
pageSize: number;
|
||||
}
|
||||
|
||||
/** 选品分页:categoryId 缺省=全部归属商品(分类下拉唯一来源是 jdCollect.groups 既有出口,AC-9)。 */
|
||||
export function fetchJdPublishProducts(categoryId: number | null, page: number, pageSize: number) {
|
||||
const params: Record<string, unknown> = {
|
||||
user_id: getCurrentUserId(),
|
||||
page,
|
||||
page_size: pageSize,
|
||||
}
|
||||
if (categoryId != null && categoryId > 0) {
|
||||
params.category_id = categoryId
|
||||
}
|
||||
return unwrapJavaResponse(
|
||||
get<JavaApiResponse<JdPublishProductPageVo>>(
|
||||
buildJavaUrl(API_ENDPOINTS.jdPublish.products),
|
||||
{ params },
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// 任务面板(v1.5 Phase 4):总览统计卡 / 历史层(行级四档计数)/ 活跃任务批量进度 / 删除。
|
||||
// 形状照 jd-collect 同族;京东发布没有结果文件,没有 downloadUrl / fileStatus 那一层。
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
/** 任务面板总览(运行中/已结束/成功/失败任务数)。 */
|
||||
export interface JdPublishDashboardVo {
|
||||
pendingTaskCount: number;
|
||||
processedTaskCount: number;
|
||||
successTaskCount: number;
|
||||
failedTaskCount: number;
|
||||
}
|
||||
|
||||
/** 历史行(任务卡片数据源)。行级四档计数来自发布明细表聚合(服务端真源,不编造分母)。 */
|
||||
export interface JdPublishHistoryItemVo {
|
||||
taskId?: number;
|
||||
taskNo?: string;
|
||||
/** biz_file_task.status 原值:PENDING/RUNNING/SUCCESS/FAILED */
|
||||
taskStatus?: string;
|
||||
success?: boolean;
|
||||
errorMessage?: string;
|
||||
/** 建单所选自定义分类 id;重试重建推送载荷时同源带回 */
|
||||
categoryId?: number;
|
||||
/** 建单统一改价规则(原样带回;重试重建推送载荷与建单响应 queuePayload 同键) */
|
||||
priceRule?: { mode?: string; value?: number };
|
||||
/** 商品明细总行数 */
|
||||
productTotal?: number;
|
||||
pendingCount?: number;
|
||||
publishingCount?: number;
|
||||
successCount?: number;
|
||||
failedCount?: number;
|
||||
createdAt?: string;
|
||||
finishedAt?: string;
|
||||
updatedAt?: string;
|
||||
}
|
||||
|
||||
export interface JdPublishHistoryVo {
|
||||
items: JdPublishHistoryItemVo[];
|
||||
}
|
||||
|
||||
/** 批量进度条目:任务头 + 单元素进度行(与 jd-collect TaskDetailVo 同形)。 */
|
||||
export interface JdPublishTaskDetailVo {
|
||||
task?: {
|
||||
id?: number;
|
||||
taskNo?: string;
|
||||
status?: string;
|
||||
errorMessage?: string;
|
||||
updatedAt?: string;
|
||||
};
|
||||
items?: JdPublishHistoryItemVo[];
|
||||
}
|
||||
|
||||
export interface JdPublishTaskBatchVo {
|
||||
items: JdPublishTaskDetailVo[];
|
||||
missingTaskIds: number[];
|
||||
}
|
||||
|
||||
export function fetchJdPublishDashboard() {
|
||||
return unwrapJavaResponse(
|
||||
get<JavaApiResponse<JdPublishDashboardVo>>(
|
||||
buildJavaUrl(API_ENDPOINTS.jdPublish.dashboard),
|
||||
{ params: { user_id: getCurrentUserId() } },
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
export function fetchJdPublishHistory() {
|
||||
return unwrapJavaResponse(
|
||||
get<JavaApiResponse<JdPublishHistoryVo>>(
|
||||
buildJavaUrl(API_ENDPOINTS.jdPublish.history),
|
||||
{ params: { user_id: getCurrentUserId(), limit: 50 } },
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
interface JdProgressBatchOptions {
|
||||
force?: boolean;
|
||||
}
|
||||
|
||||
const taskProgressResponseCache = createTaskProgressRequestCache<unknown>({
|
||||
ttlMs: () => getTaskProgressCacheTtlMs(),
|
||||
maxEntries: 100,
|
||||
maxInflight: 16,
|
||||
});
|
||||
|
||||
function normalizeTaskIds(taskIds: number[]) {
|
||||
return Array.from(
|
||||
new Set(
|
||||
(taskIds || [])
|
||||
.map((taskId) => Number(taskId))
|
||||
.filter((taskId) => Number.isFinite(taskId) && taskId > 0),
|
||||
),
|
||||
).sort((left, right) => left - right);
|
||||
}
|
||||
|
||||
function buildTaskProgressRequestKey(path: string, taskIds: number[]) {
|
||||
return `${path}::${taskIds.join(',')}`;
|
||||
}
|
||||
|
||||
/** 批量进度请求缓存(与 jd-collect 同一形状:TTL 缓存 + 在飞合并 + force 旁路)。 */
|
||||
async function postTaskProgressBatch<T>(
|
||||
path: string,
|
||||
taskIds: number[],
|
||||
options: JdProgressBatchOptions = {},
|
||||
) {
|
||||
const normalizedTaskIds = normalizeTaskIds(taskIds);
|
||||
if (!normalizedTaskIds.length) {
|
||||
return { items: [], missingTaskIds: [] } as T;
|
||||
}
|
||||
|
||||
const cacheKey = buildTaskProgressRequestKey(path, normalizedTaskIds);
|
||||
const cached = taskProgressResponseCache.get(cacheKey);
|
||||
if (!options.force && cached !== undefined) {
|
||||
return cached as T;
|
||||
}
|
||||
|
||||
const inflight = taskProgressResponseCache.getInflight(cacheKey);
|
||||
if (!options.force && inflight) {
|
||||
return (await inflight) as T;
|
||||
}
|
||||
|
||||
const requestPromise = unwrapJavaResponse(
|
||||
post<JavaApiResponse<T>, { taskIds: number[]; userId?: number }>(path, {
|
||||
taskIds: normalizedTaskIds,
|
||||
userId: Number(window.localStorage.getItem('uid')) || undefined,
|
||||
}, {
|
||||
timeout: getTaskProgressTimeoutMs(),
|
||||
}),
|
||||
)
|
||||
.then((data) => {
|
||||
taskProgressResponseCache.set(cacheKey, data);
|
||||
return data;
|
||||
})
|
||||
.finally(() => {
|
||||
taskProgressResponseCache.endInflight(cacheKey);
|
||||
});
|
||||
|
||||
taskProgressResponseCache.startInflight(cacheKey, requestPromise);
|
||||
return await requestPromise;
|
||||
}
|
||||
|
||||
export function fetchJdPublishTaskProgressBatch(
|
||||
taskIds: number[],
|
||||
options: JdProgressBatchOptions = {},
|
||||
) {
|
||||
return postTaskProgressBatch<JdPublishTaskBatchVo>(
|
||||
buildJavaUrl(API_ENDPOINTS.jdPublish.progressBatch),
|
||||
taskIds,
|
||||
options,
|
||||
);
|
||||
}
|
||||
|
||||
/** 删除任务:服务端连带清理该任务的发布明细快照行。 */
|
||||
export function deleteJdPublishTask(taskId: number) {
|
||||
return unwrapJavaResponse(
|
||||
del<JavaApiResponse<null>>(
|
||||
buildJavaUrl(API_ENDPOINTS.jdPublish.deleteTask.replace('{taskId}', String(taskId))),
|
||||
{ params: { user_id: getCurrentUserId() } },
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 用户中断任务:在跑/待跑的任务落 CANCELLED——客户端心跳拿到 notAlive 后协作停止,
|
||||
* 已发布的行保留在发布明细里,之后可「继续」接着跑(断点游标服务端按 PENDING 行下发)。
|
||||
* 通用任务中断端点(TaskHeartbeatController),与采集中断同形。
|
||||
*/
|
||||
export function interruptJdPublishTask(taskId: number) {
|
||||
return unwrapJavaResponse(
|
||||
post<JavaApiResponse<null>>(
|
||||
`${JAVA_API_PREFIX}/tasks/${taskId}/interrupt`,
|
||||
undefined,
|
||||
{ params: { user_id: getCurrentUserId() } },
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -91,7 +91,11 @@ const BASELINE = {
|
||||
// 都能看到」):JdCollectTab.vue 的 loadGroups catch——分类只是展示项,拉取失败
|
||||
// ElMessage.warning 当场说给用户、原文只进 console,采集主路照常;非静默,
|
||||
// silent 一格没涨,只进 blocks。
|
||||
blocks: 319,
|
||||
// 324 = 319 + 5(2026-11-18 v1.5 Phase 4 京东商品上架用户端):JdPublishTab.vue +
|
||||
// jd-publish.ts 新增 5 支 try/catch(分类/商品列表拉取失败落到界面反馈、激活失败
|
||||
// 降级为提示由客户端兜底拉取认领、重试/建单入口异常 ElMessage),全部非静默
|
||||
// ("新增静默文件"断言未触发),silent 一格没涨,只进 blocks。
|
||||
blocks: 324,
|
||||
// 2026-10-30(ops Phase 6/可读棘轮):ApiSecretSettingsPanel.vue 1113→775 行,面板里那处
|
||||
// 静默 catch(余额查询失败只 console.warn、界面留空)随 loadBalance 整块搬进
|
||||
// useProxyPlan.ts。不是新增静默:面板 1→0、新文件记 1,silent 总数与 blocks 都一格没动,
|
||||
|
||||
@@ -90,6 +90,7 @@ test('test_progress_batch_paths_match_controllers', () => {
|
||||
'/api/shop-data-crawl/tasks/progress/batch',
|
||||
'/api/withdraw/tasks/progress/batch',
|
||||
'/api/jd-collect/tasks/progress/batch',
|
||||
'/api/jd-publish/tasks/progress/batch',
|
||||
].sort(),
|
||||
'progress/batch 端点应与 Java controller 路由一一对应',
|
||||
)
|
||||
@@ -338,6 +339,19 @@ 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 源码绊线钉死)。
|
||||
"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",
|
||||
"progressBatch": "/api/jd-publish/tasks/progress/batch",
|
||||
"progress": "/api/jd-publish/tasks/{taskId}/progress",
|
||||
"deleteTask": "/api/jd-publish/tasks/{taskId}"
|
||||
},
|
||||
"userSecret": {
|
||||
"bundle": "/api/user-secrets",
|
||||
"save": "/api/user-secrets/{moduleKey}",
|
||||
|
||||
@@ -28,11 +28,11 @@ test('京东工作台只有两个菜单:获取店铺数据 + 商品上架', ()
|
||||
assert.ok(JD_TOOL_MAP.get('jd-collect'), 'JD_TOOL_MAP 应按 id 命中获取店铺数据')
|
||||
})
|
||||
|
||||
test('获取店铺数据指向采集页,商品上架先做占位菜单', () => {
|
||||
test('获取店铺数据指向采集页,商品上架已转正式挂 /jd-publish(v1.5 Phase 4)', () => {
|
||||
const collect = JD_TOOLS.find((tool) => tool.id === 'jd-collect')
|
||||
const publish = JD_TOOLS.find((tool) => tool.id === 'jd-publish')
|
||||
assert.equal(collect?.href, '/jd-collect', '获取店铺数据应指向 /jd-collect')
|
||||
assert.equal(publish?.href, undefined, '商品上架先做假菜单:不得挂路由')
|
||||
assert.equal(publish?.href, '/jd-publish', '商品上架已转正式:指向 /jd-publish(占位态已随 v1.5 Phase 4 下线)')
|
||||
})
|
||||
|
||||
test('路由器注册京东工作台与采集页', () => {
|
||||
@@ -40,6 +40,7 @@ test('路由器注册京东工作台与采集页', () => {
|
||||
assert.ok(router.includes("path: '/jd-console'"), 'router 缺 /jd-console')
|
||||
assert.ok(router.includes('JdConsolePage.vue'), 'router 未指向 JdConsolePage')
|
||||
assert.ok(router.includes("path: '/jd-collect'"), 'router 缺 /jd-collect')
|
||||
assert.ok(router.includes("path: '/jd-publish'"), 'router 缺 /jd-publish(v1.5 Phase 4 转正式)')
|
||||
})
|
||||
|
||||
test('首页京东入口与亚马逊/视频并列', () => {
|
||||
|
||||
@@ -9,8 +9,8 @@ import { join } from 'node:path'
|
||||
* 1. **立即生效**(AC-9 前端绊线,B113-01):`/api/jd-collect/groups` 是京东分类的
|
||||
* 唯一读取口——全 src 不得出现第三个裸 URL 消费点;发布页要分类数据必须走
|
||||
* endpoints.jdCollect.groups 的既有 fetch 函数(出现第二个分类口即红)。
|
||||
* 2. **Pending Phase 4**(每支带 skip):JdPublishTab(分类→商品→改价→建单→实时面板)
|
||||
* 落地后移除对应 skip 跑绿——蓝图 §4 Phase 4【待激活验收测试】登记的就是这份清单。
|
||||
* 2. **Phase 4 契约**(2026-11-18 随 Phase 4 落地移除 skip 正式激活):JdPublishTab
|
||||
* (分类→商品→改价→建单→实时面板)的 5 支验收契约,蓝图 §4 Phase 4【待激活验收测试】清单。
|
||||
*/
|
||||
|
||||
const ROOT = process.cwd()
|
||||
@@ -45,19 +45,19 @@ test('AC-9: 京东分类读取口全 src 唯一(B113-01 绊线)', () => {
|
||||
|
||||
// ---------------------------------------------------------- Pending Phase 4
|
||||
|
||||
test('AC-9: JdPublishTab 分类选择消费唯一 groups 出口', { skip: 'Pending Phase 4: JdPublishTab 落地后移除 skip' }, () => {
|
||||
test('AC-9: JdPublishTab 分类选择消费唯一 groups 出口', () => {
|
||||
const tab = read('src/pages/jd/JdPublishTab.vue', '商品上架页')
|
||||
assert.ok(tab.includes('jdCollect'), 'JdPublishTab 的分类数据必须走 endpoints.jdCollect/groups 既有 fetch(AC-9),不得自拼 URL')
|
||||
assert.ok(!tab.includes('jd-collect/groups'), 'JdPublishTab 不得裸写分类 URL(B113-01 绊线)')
|
||||
})
|
||||
|
||||
test('AC-9: 商品列表只拉归属当前用户的行(owner 过滤)', { skip: 'Pending Phase 4: JdPublishTab 落地后移除 skip' }, () => {
|
||||
test('AC-9: 商品列表只拉归属当前用户的行(owner 过滤)', () => {
|
||||
const tab = read('src/pages/jd/JdPublishTab.vue', '商品上架页')
|
||||
assert.ok(tab.includes('productIds') || tab.includes('productId'),
|
||||
'JdPublishTab 建单提交必须携带勾选的商品 id 集合(服务端按 owner 校验,跨用户商品 0 返回)')
|
||||
})
|
||||
|
||||
test('建单请求体形状:categoryId + productIds + priceRule{mode,value}', { skip: 'Pending Phase 4: JdPublishTab 落地后移除 skip' }, () => {
|
||||
test('建单请求体形状:categoryId + productIds + priceRule{mode,value}', () => {
|
||||
const tab = read('src/pages/jd/JdPublishTab.vue', '商品上架页')
|
||||
// 蓝图 §3 死契约:POST /api/jd-publish/tasks 请求体 {categoryId, productIds[], priceRule:{mode,value?}}
|
||||
assert.ok(tab.includes('categoryId'), '建单体缺 categoryId(所选自定义分类)')
|
||||
@@ -66,13 +66,13 @@ test('建单请求体形状:categoryId + productIds + priceRule{mode,value}',
|
||||
'priceRule.mode 三档(none/percent/fixed)必须与蓝图 §3 同值')
|
||||
})
|
||||
|
||||
test('endpoints 注册 jdPublish 端点组(建单/items/chunk 三件)', { skip: 'Pending Phase 4: endpoints 扩组后移除 skip' }, () => {
|
||||
test('endpoints 注册 jdPublish 端点组(建单/items/chunk 三件)', () => {
|
||||
const endpoints = read('src/shared/api/endpoints.ts', 'endpoints.ts')
|
||||
assert.ok(endpoints.includes('jdPublish'), 'endpoints.ts 缺 jdPublish 端点组')
|
||||
assert.ok(endpoints.includes('/api/jd-publish/tasks'), 'jdPublish 组缺建单端点 /api/jd-publish/tasks')
|
||||
})
|
||||
|
||||
test('商品上架占位卡转正式:jd-publish 卡挂 /jd-publish 路由', { skip: 'Pending Phase 4: 占位卡转正式时移除 skip(须同步改 jd-console-tool-catalog.test.ts 的占位锁)' }, () => {
|
||||
test('商品上架占位卡转正式:jd-publish 卡挂 /jd-publish 路由', () => {
|
||||
const catalog = read('src/pages/jd/tool-catalog.ts', 'jd/tool-catalog.ts')
|
||||
const router = read('src/router/index.ts', 'router/index.ts')
|
||||
assert.ok(/id:\s*'jd-publish'[\s\S]*?href:\s*'\/jd-publish'/.test(catalog),
|
||||
|
||||
@@ -3,8 +3,12 @@
|
||||
*
|
||||
* 三件事一起判,缺一条就是假绿:
|
||||
* ① 两个菜单名都在 DOM 里(获取店铺数据 / 商品上架);
|
||||
* ② 获取店铺数据是「可用」卡片(有 href → router-link 分支,文案是「打开工具」);
|
||||
* ③ 商品上架是「假菜单」:没有 href,点开只弹一句「暂未开通」,不发任何请求。
|
||||
* ② 两张卡都是「可用」卡片(有 href → router-link 分支,文案是「打开工具」);
|
||||
* ③ 商品上架卡(v1.5 Phase 4 由占位转正式)的 router-link 指向 /jd-publish。
|
||||
*
|
||||
* 历史锁(2026-11-17):本文件原本钉「商品上架是假菜单(tool-card--pending,点开只弹
|
||||
* 暂未开通)」;占位随 Phase 4 转正式后这两条断言翻转为可用卡形状,假菜单分支在
|
||||
* JdConsolePage 保留为通用防御(后续新工具再用)。
|
||||
*
|
||||
* 跑法:cd frontend-vue && npx vitest run(tests/mount/** 由 vitest.config.ts 收)。
|
||||
*/
|
||||
@@ -20,8 +24,8 @@ function mountConsole() {
|
||||
global: {
|
||||
stubs: {
|
||||
NotificationBell: true,
|
||||
RouterLink: { template: '<a class="router-link-stub"><slot /></a>' },
|
||||
'router-link': { template: '<a class="router-link-stub"><slot /></a>' },
|
||||
RouterLink: { props: ['to'], template: '<a class="router-link-stub" :data-to="to"><slot /></a>' },
|
||||
'router-link': { props: ['to'], template: '<a class="router-link-stub" :data-to="to"><slot /></a>' },
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -47,21 +51,19 @@ describe('京东工作台两个菜单', () => {
|
||||
expect(w.findAll('.tool-card').length).toBe(2)
|
||||
})
|
||||
|
||||
it('获取店铺数据是可用卡片,商品上架是占位(暂未开通)', () => {
|
||||
it('两张卡都是可用卡片(转正式后无占位态)', () => {
|
||||
const w = mountConsole()
|
||||
const cards = w.findAll('.tool-card')
|
||||
expect(cards[0].classes()).not.toContain('tool-card--pending')
|
||||
expect(cards[0].text()).toContain('打开工具')
|
||||
expect(cards[1].classes()).toContain('tool-card--pending')
|
||||
expect(cards[1].text()).toContain('暂未开通')
|
||||
expect(cards[1].classes()).not.toContain('tool-card--pending')
|
||||
expect(cards[1].text()).toContain('打开工具')
|
||||
})
|
||||
|
||||
it('点假菜单只弹提示,不跳转', async () => {
|
||||
it('商品上架卡的 router-link 指向 /jd-publish(占位已转正式)', () => {
|
||||
const w = mountConsole()
|
||||
const pending = w.findAll('.tool-card')[1]
|
||||
await pending.trigger('click')
|
||||
const toast = w.find('.toast')
|
||||
expect(toast.text()).toContain('商品上架暂未开通')
|
||||
expect(toast.classes()).toContain('show')
|
||||
const links = w.findAll('a.router-link-stub').map((a) => a.attributes('data-to'))
|
||||
expect(links).toContain('/jd-collect')
|
||||
expect(links).toContain('/jd-publish')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -46,6 +46,8 @@ const NARROW_LEDGER: Record<string, number> = {
|
||||
'src/pages/brand/components/BrandProductRiskTab.vue': 2,
|
||||
'src/pages/brand/components/BrandSimilarAsinTab.vue': 1,
|
||||
'src/pages/jd/JdCollectTab.vue': 1,
|
||||
// v1.5 Phase 4:商品上架页同形(settleOnTaskStatuses 需含 CANCELLED,与采集页同因不入共用词表)
|
||||
'src/pages/jd/JdPublishTab.vue': 1,
|
||||
'src/shared/composables/useLiveTaskBoard.ts': 2,
|
||||
}
|
||||
const NARROW_BASELINE_TOTAL = Object.values(NARROW_LEDGER).reduce((a, b) => a + b, 0)
|
||||
|
||||
Reference in New Issue
Block a user