feat(jd): 上架按账号授权 + 建单钉来源店铺 + 店铺不匹配整单判死

2026-11-24 客户(心向大海)两条口径:
「如果没有店铺登入情况 软件怎么知道我们要上架是哪一个店铺?」
「上架的账户 我是这个权限不开给他的」

后端半边(用户端页头与会话核对见 frontend-vue 同笔;客户端发布前核对见 app_client 0f8bcdf)。

一、按账号授权(拒绝型能力,quiet fail 全靠本类判据)
- JdPublishPermissionSupport:V209 app 菜单组键 jd_tools 或子键 jd-publish 命中即放行,
  超管直放;有效键集按 AdminMenuPlatformScope 过滤到账号平台(与登录分发同源)。
  无权限抛 403 + 中文动作句(告诉管理员去哪儿勾)。
- JdPublishController:建单/改品牌重试/选品/面板/历史/批量进度六个用户面入口一律先判;
  客户端执行面(items/chunk/activate/heartbeat/补值/删除)不判——执行器本来就只跑
  已建的任务,判在这里会让进行中的任务断在半路。

二、建单钉来源店铺(一次上架只发一家店)
- resolveSingleShop:按勾选商品快照判店铺,跨店勾选建单即拒并点名两家店;
  同店两种形状(有 id / 只有店名)归一到 id 再比。
- JdPublishTaskCreateRequest 落 shopId/shopName → 队列载荷两键 → 明细页
  JdPublishItemsPageVo.shopId/shopName 下发;旧任务载荷没这两键时回落明细行
  shop_name(V210 就有),保证老任务至少能按店名核对。

三、店铺不匹配整单判死
- JdPublishStaleTaskService.SHOP_MISMATCH_MARK/terminalizeOnJdShopMismatch:
  CAS RUNNING→FAILED、0/1 计数、原文追加动作句;不按累计行数收窄(确定性失败)。
- JdPublishIngestService.fail:命中标记排在凭据致命档之后、页面结构变更之前接线,
  回 accept=true 让客户端收口。

判据:JdPublishPermissionSupportTest 5 支(新)+TaskService +3/Stale +2/Ingest +2,
后端 JdPublish 九类 77 支全绿;四支既有护栏(catch 静默/请求身份/超管单出口/SQL 分层)绿。
This commit is contained in:
2026-11-24 15:21:27 +08:00
parent cf06872cb6
commit 1b10db4bf9
20 changed files with 1156 additions and 6 deletions
@@ -20,6 +20,7 @@ import com.nanri.aiimage.modules.jd.service.JdProductQueryService;
import com.nanri.aiimage.modules.jd.service.JdPublishBoardService; import com.nanri.aiimage.modules.jd.service.JdPublishBoardService;
import com.nanri.aiimage.modules.jd.service.JdPublishFillAiService; import com.nanri.aiimage.modules.jd.service.JdPublishFillAiService;
import com.nanri.aiimage.modules.jd.service.JdPublishIngestService; import com.nanri.aiimage.modules.jd.service.JdPublishIngestService;
import com.nanri.aiimage.modules.jd.service.JdPublishPermissionSupport;
import com.nanri.aiimage.modules.jd.service.JdPublishTaskService; import com.nanri.aiimage.modules.jd.service.JdPublishTaskService;
import com.nanri.aiimage.modules.jd.service.JdSizeChartAiService; import com.nanri.aiimage.modules.jd.service.JdSizeChartAiService;
import com.nanri.aiimage.modules.task.model.dto.TaskHeartbeatRequest; import com.nanri.aiimage.modules.task.model.dto.TaskHeartbeatRequest;
@@ -68,6 +69,7 @@ public class JdPublishController {
private final AdminAuthSupport adminAuthSupport; private final AdminAuthSupport adminAuthSupport;
private final JdSizeChartAiService sizeChartAiService; private final JdSizeChartAiService sizeChartAiService;
private final JdPublishFillAiService fillAiService; private final JdPublishFillAiService fillAiService;
private final JdPublishPermissionSupport publishPermissionSupport;
@PostMapping({"/tasks", "/tasks/target-brand"}) @PostMapping({"/tasks", "/tasks/target-brand"})
@Operation(summary = "创建京东商品上架任务", description = "勾选京东数据库商品(归属校验)+可选统一改价规则建单;" @Operation(summary = "创建京东商品上架任务", description = "勾选京东数据库商品(归属校验)+可选统一改价规则建单;"
@@ -77,6 +79,8 @@ public class JdPublishController {
HttpServletRequest httpRequest) { HttpServletRequest httpRequest) {
// uid 不由请求体说了算:解析不出会话身份就 401(fail-closed,与采集建单同口径)。 // uid 不由请求体说了算:解析不出会话身份就 401(fail-closed,与采集建单同口径)。
request.setUserId(adminAuthSupport.requireSessionOwnerUserId(httpRequest, request.getUserId())); request.setUserId(adminAuthSupport.requireSessionOwnerUserId(httpRequest, request.getUserId()));
// 菜单权限闸(V209 jd_tools/jd-publish):直连 URL/接口也不能绕过卡片显隐。
publishPermissionSupport.assertCanPublish(request.getUserId());
return ApiResponse.success(publishTaskService.createTask(request, return ApiResponse.success(publishTaskService.createTask(request,
adminAuthSupport.currentDeviceId(httpRequest))); adminAuthSupport.currentDeviceId(httpRequest)));
} }
@@ -84,9 +88,10 @@ public class JdPublishController {
@PostMapping("/tasks/{taskId}/retry-brand") @PostMapping("/tasks/{taskId}/retry-brand")
public ApiResponse<JdPublishTaskVo> retryBrand(@PathVariable Long taskId, public ApiResponse<JdPublishTaskVo> retryBrand(@PathVariable Long taskId,
@Valid @RequestBody BrandRetryRequest request, HttpServletRequest httpRequest) { @Valid @RequestBody BrandRetryRequest request, HttpServletRequest httpRequest) {
Long userId = adminAuthSupport.requireSessionOwnerUserId(httpRequest, null);
publishPermissionSupport.assertCanPublish(userId);
return ApiResponse.success(publishTaskService.retryWithBrand(taskId, return ApiResponse.success(publishTaskService.retryWithBrand(taskId,
adminAuthSupport.requireSessionOwnerUserId(httpRequest, null), userId, request.resumeAttempt(), request.targetBrandName()));
request.resumeAttempt(), request.targetBrandName()));
} }
public record BrandRetryRequest(@jakarta.validation.constraints.NotNull Integer resumeAttempt, String targetBrandName) {} public record BrandRetryRequest(@jakarta.validation.constraints.NotNull Integer resumeAttempt, String targetBrandName) {}
@@ -201,6 +206,7 @@ public class JdPublishController {
@RequestParam(value = "user_id", required = false) Long userId, @RequestParam(value = "user_id", required = false) Long userId,
HttpServletRequest httpRequest) { HttpServletRequest httpRequest) {
userId = adminAuthSupport.requireSessionOwnerUserId(httpRequest, userId); userId = adminAuthSupport.requireSessionOwnerUserId(httpRequest, userId);
publishPermissionSupport.assertCanPublish(userId);
return ApiResponse.success(jdProductQueryService.pageForUser(userId, categoryId, page, pageSize)); return ApiResponse.success(jdProductQueryService.pageForUser(userId, categoryId, page, pageSize));
} }
@@ -212,6 +218,7 @@ public class JdPublishController {
@RequestParam("user_id") Long userId, @RequestParam("user_id") Long userId,
HttpServletRequest httpRequest) { HttpServletRequest httpRequest) {
userId = adminAuthSupport.requireSessionOwnerUserId(httpRequest, userId); userId = adminAuthSupport.requireSessionOwnerUserId(httpRequest, userId);
publishPermissionSupport.assertCanPublish(userId);
return ApiResponse.success(boardService.dashboard(userId)); return ApiResponse.success(boardService.dashboard(userId));
} }
@@ -225,6 +232,7 @@ public class JdPublishController {
@RequestParam(value = "limit", required = false, defaultValue = PageDefaults.DEFAULT_RESULT_LIMIT) Integer limit, @RequestParam(value = "limit", required = false, defaultValue = PageDefaults.DEFAULT_RESULT_LIMIT) Integer limit,
HttpServletRequest httpRequest) { HttpServletRequest httpRequest) {
userId = adminAuthSupport.requireSessionOwnerUserId(httpRequest, userId); userId = adminAuthSupport.requireSessionOwnerUserId(httpRequest, userId);
publishPermissionSupport.assertCanPublish(userId);
return ApiResponse.success(boardService.history(userId, limit)); return ApiResponse.success(boardService.history(userId, limit));
} }
@@ -233,9 +241,10 @@ public class JdPublishController {
+ "归属先由公共出口按会话身份过滤,返回任务头 + 行级四档计数。") + "归属先由公共出口按会话身份过滤,返回任务头 + 行级四档计数。")
public ApiResponse<JdPublishTaskBatchVo> progressBatch(@Valid @RequestBody JdPublishTaskBatchRequest request, public ApiResponse<JdPublishTaskBatchVo> progressBatch(@Valid @RequestBody JdPublishTaskBatchRequest request,
HttpServletRequest httpRequest) { HttpServletRequest httpRequest) {
Long userId = adminAuthSupport.requireSessionOwnerUserId(httpRequest, request.getUserId());
publishPermissionSupport.assertCanPublish(userId);
return ApiResponse.success(boardService.progressBatch(progressOwnershipSupport return ApiResponse.success(boardService.progressBatch(progressOwnershipSupport
.filterOwnedTaskIds(request.getTaskIds(), .filterOwnedTaskIds(request.getTaskIds(), userId)));
adminAuthSupport.requireSessionOwnerUserId(httpRequest, request.getUserId()))));
} }
@DeleteMapping("/tasks/{taskId}") @DeleteMapping("/tasks/{taskId}")
@@ -30,6 +30,19 @@ public class JdPublishTaskCreateRequest {
/** 本次任务统一使用的目标品牌名,不回写商品库。 */ /** 本次任务统一使用的目标品牌名,不回写商品库。 */
private String targetBrandName; private String targetBrandName;
/**
* 本次建单商品的来源店铺 ID(京麦 venderId,服务端按勾选商品回填,**不采信请求体**)。
*
* <p>2026-11-24 客户口径「上架时候要获取店铺登入情况,软件才知道要发到哪家店」:
* 建单时把勾选商品快照里的店铺钉进载荷,客户端发布前拿本机京麦实际登录店铺对撞,
* 不一致整单中止(见 {@code JdPublishPage.verify_shop})。旧任务载荷没有这两个键 ⇒
* 客户端按「无法核对」明确告警,不冒充已核对。</p>
*/
private String shopId;
/** 本次建单商品的来源店铺名(服务端回填,供失败文案与界面展示点名)。 */
private String shopName;
/** 统一改价规则:none 原价 / percent 加价百分比(value=百分数) / fixed 固定加价(value=金额)。 */ /** 统一改价规则:none 原价 / percent 加价百分比(value=百分数) / fixed 固定加价(value=金额)。 */
@Data @Data
public static class PriceRule { public static class PriceRule {
@@ -20,6 +20,16 @@ public class JdPublishItemsPageVo {
private String targetBrandName; private String targetBrandName;
private int resumeAttempt; private int resumeAttempt;
/**
* 期望店铺(2026-11-24):本任务的商品来源店铺 venderId。客户端发布前用本机京麦
* 实际登录店铺与它对比,不一致整单中止——空值=旧任务/旧数据没有可核对锚点,
* 客户端必须明确告警而不是当作已核对。
*/
private String shopId;
/** 期望店铺名(与 shopId 配对;ID 缺失时按店名核对,失败文案点名用)。 */
private String shopName;
/** 本页明细行。 */ /** 本页明细行。 */
private List<JdPublishItemPayloadVo> items; private List<JdPublishItemPayloadVo> items;
@@ -92,8 +92,13 @@ public class JdPublishIngestService {
vo.setPendingCount(counts.getOrDefault(ITEM_PENDING, 0L)); vo.setPendingCount(counts.getOrDefault(ITEM_PENDING, 0L));
vo.setPublishingCount(counts.getOrDefault(ITEM_PUBLISHING, 0L)); vo.setPublishingCount(counts.getOrDefault(ITEM_PUBLISHING, 0L));
vo.setNeedsReview(Boolean.TRUE.equals(request.getIsEnd()) && vo.getPublishingCount() > 0); vo.setNeedsReview(Boolean.TRUE.equals(request.getIsEnd()) && vo.getPublishingCount() > 0);
String shopMismatch = shopMismatchMessage(request.getError());
if (terminal) { if (terminal) {
vo.setTaskStatus(task.getStatus()); vo.setTaskStatus(task.getStatus());
} else if (shopMismatch != null
&& staleTaskService.terminalizeOnJdShopMismatch(task, shopMismatch)) {
// 店铺不匹配是确定性失败(打开任何商品页之前就中止),不按累计行数收窄。
vo.setTaskStatus(TaskStatuses.FileTask.FAILED);
} else if (preflightMessage != null && accepted == 1) { } else if (preflightMessage != null && accepted == 1) {
vo.setTaskStatus(finish(task, counts, TaskStatuses.FileTask.FAILED, preflightMessage)); vo.setTaskStatus(finish(task, counts, TaskStatuses.FileTask.FAILED, preflightMessage));
} else if (newlyFailedReason != null && staleTaskService.terminalizeOnJdLoginFatal(task, newlyFailedReason)) { } else if (newlyFailedReason != null && staleTaskService.terminalizeOnJdLoginFatal(task, newlyFailedReason)) {
@@ -104,6 +109,12 @@ public class JdPublishIngestService {
return vo; return vo;
} }
/** 失败上报里含店铺不匹配标记才认这一档;其他 error 文本仍走原有汇总/心跳线。 */
private static String shopMismatchMessage(String error) {
String raw = error == null ? "" : error.strip();
return raw.contains(JdPublishStaleTaskService.SHOP_MISMATCH_MARK) ? raw : null;
}
private RowOutcome applyRow(Long taskId, Long userId, int attempt, String batchId, ItemResult item, private RowOutcome applyRow(Long taskId, Long userId, int attempt, String batchId, ItemResult item,
String status, boolean terminal) { String status, boolean terminal) {
String wareId = ITEM_SUCCESS.equals(status) ? item.getJdWareId() : null; String wareId = ITEM_SUCCESS.equals(status) ? item.getJdWareId() : null;
@@ -0,0 +1,77 @@
package com.nanri.aiimage.modules.jd.service;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.mapper.AdminUserMapper;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.common.security.DeviceSessionPolicy;
import com.nanri.aiimage.common.service.AdminMenuPlatformScope;
import com.nanri.aiimage.modules.permission.model.vo.PermissionMenuItemVo;
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Locale;
import java.util.Set;
import java.util.stream.Collectors;
/**
* 用户端「商品上架」菜单权限闸(2026-11-24 客户口径「上架的账户,我是这个权限不开给他的」)。
*
* <p>权限键沿用 V209 的 app 菜单树,不新增表:组键 {@code jd_tools}(京东工具台)或子键
* {@code jd-publish}(商品上架)任一命中即放行;两者都没有就一律 403。判定走
* {@link PermissionMenuService#getUserColumnPermissions} 的**有效权限**(直授+组行展开后代),
* 与登录下发/前端卡片显隐同一口径——后管授权树里取消「商品上架」后,组行会退成半选、
* 保存的直授集只剩 {@code jd-collect},展开后 {@code jd-publish} 自然不在集合里。</p>
*
* <p>平台过滤与 {@code AuthService} 登录下发逐字同源({@link AdminMenuPlatformScope}):
* 不给京东档账号多算一行亚马逊/视频菜单,也不让平台过滤前后判据分叉。</p>
*/
@Service
@RequiredArgsConstructor
public class JdPublishPermissionSupport {
/** app 菜单组键:京东运营工具台(V209,组行命中=两个工具都放行)。 */
public static final String GROUP_KEY = "jd_tools";
/** app 菜单子键:商品上架(与前端 tool-catalog.ts 的 permissionKeys 逐字一致)。 */
public static final String PUBLISH_KEY = "jd-publish";
/** 拒绝文案:点名去哪儿开通,不写「稍后重试」。 */
public static final String DENIED_MESSAGE =
"当前账号没有「商品上架」权限,请联系管理员在后台「用户管理 → 菜单权限 → 桌面端」中开通";
private final AdminUserMapper adminUserMapper;
private final PermissionMenuService permissionMenuService;
/** 该账号能否使用商品上架(站点超管始终放行;查不到账号按无权限处理)。 */
public boolean canPublish(Long userId) {
if (userId == null) {
return false;
}
AdminUserEntity user = adminUserMapper.selectById(userId);
if (user == null) {
return false;
}
if (DeviceSessionPolicy.isSuperAdmin(user.getRole(), user.getIsAdmin(), user.getCreatedById())) {
return true;
}
List<PermissionMenuItemVo> columns = permissionMenuService.getUserColumnPermissions(
userId, PermissionMenuService.MENU_TYPE_APP);
List<PermissionMenuItemVo> scoped = AdminMenuPlatformScope.filterMenuVosByPlatform(
columns, user.getPlatform());
Set<String> keys = scoped.stream()
.map(PermissionMenuItemVo::getColumnKey)
.filter(key -> key != null && !key.isBlank())
.map(key -> key.trim().toLowerCase(Locale.ROOT))
.collect(Collectors.toSet());
return keys.contains(GROUP_KEY) || keys.contains(PUBLISH_KEY);
}
/** 建单/选品/面板入口统一闸:无权限直接 403(fail-closed,不让直连 URL 绕过卡片显隐)。 */
public void assertCanPublish(Long userId) {
if (!canPublish(userId)) {
throw new BusinessException(403, DENIED_MESSAGE);
}
}
}
@@ -155,4 +155,57 @@ public class JdPublishStaleTaskService {
message.append("京麦未登录(登录态失效),请在客户端重新登录京麦后重试"); message.append("京麦未登录(登录态失效),请在客户端重新登录京麦后重试");
return message.toString(); return message.toString();
} }
/**
* 店铺不匹配整单判死(2026-11-24 客户口径「软件怎么知道要上架哪一家店」)。
*
* <p>客户端发布前用本机京麦实际登录店铺对撞任务记录的来源店铺,不一致就在**打开任何
* 商品页之前**中止并上报本标记——这是确定性失败,重试同一登录态只会再错一次,所以
* 不按累计行数收窄、不等 60 分钟心跳线。CAS RUNNING→FAILED 可重入,已终态自然不命中。</p>
*
* @return true=本次真的把任务写成了终态
*/
public boolean terminalizeOnJdShopMismatch(FileTaskEntity task, String rawError) {
if (task == null || task.getId() == null) {
return false;
}
String message = terminalShopMismatchMessage(rawError);
int updated = fileTaskMapper.update(null, new LambdaUpdateWrapper<FileTaskEntity>()
.eq(FileTaskEntity::getId, task.getId())
.eq(FileTaskEntity::getModuleType, MODULE_TYPE)
.eq(FileTaskEntity::getStatus, STATUS_RUNNING)
.set(FileTaskEntity::getStatus, STATUS_FAILED)
.set(FileTaskEntity::getSuccessFileCount, 0)
.set(FileTaskEntity::getFailedFileCount, 1)
.set(FileTaskEntity::getErrorMessage, message)
.set(FileTaskEntity::getFailureCategory, TaskFailureLedger.categoryOf(message))
.set(FileTaskEntity::getUpdatedAt, LocalDateTime.now())
.set(FileTaskEntity::getFinishedAt, LocalDateTime.now()));
if (updated > 0) {
taskProgressSnapshotService.markTerminal(task.getId(), MODULE_TYPE, STATUS_FAILED, message);
log.warn("[{}] 京麦当前登录店铺与任务来源店铺不一致,任务落终态 FAILED taskId={} err={}",
LOG_TAG, task.getId(), message);
}
return updated > 0;
}
/** 判据标记:客户端失败文案必须含它(前缀即本串),服务端只按它认档,不做模糊匹配。 */
public static final String SHOP_MISMATCH_MARK = "京东店铺不匹配";
/** 终态文案:生产者原文(含两家店名)+ 动作句;缺标记时补上,保证界面与后台同一句话。 */
static String terminalShopMismatchMessage(String rawError) {
String raw = rawError == null ? "" : rawError.trim();
StringBuilder message = new StringBuilder();
if (!raw.isEmpty()) {
message.append(raw);
if (!raw.contains(SHOP_MISMATCH_MARK)) {
message.append(";").append(SHOP_MISMATCH_MARK);
}
message.append(";");
} else {
message.append(SHOP_MISMATCH_MARK).append(";");
}
message.append("请在京麦切换到任务记录的那家店后重新上架;本次未发布任何商品");
return message.toString();
}
} }
@@ -136,6 +136,12 @@ public class JdPublishTaskService {
throw new BusinessException(403, "勾选的商品不属于当前账号,不能上架他人数据库的商品"); throw new BusinessException(403, "勾选的商品不属于当前账号,不能上架他人数据库的商品");
} }
} }
// 来源店铺闸(2026-11-24 客户口径「软件怎么知道要上架哪一家店」):一次任务只允许
// 单店商品——客户端发布前只核对「本机京麦登录店铺」这一家,跨店勾选没法用一家店的
// 登录态发对两家店,属建单即错,当场拒并点名店铺(fail-closed,不静默挑第一家)。
ShopIdentity shop = resolveSingleShop(products);
request.setShopId(shop.id());
request.setShopName(shop.name());
LocalDateTime now = LocalDateTime.now(); LocalDateTime now = LocalDateTime.now();
FileTaskEntity task = new FileTaskEntity(); FileTaskEntity task = new FileTaskEntity();
@@ -219,6 +225,15 @@ public class JdPublishTaskService {
vo.setTaskId(taskId); vo.setTaskId(taskId);
vo.setResumeAttempt(attempt); vo.setResumeAttempt(attempt);
vo.setTargetBrandName(targetBrand); vo.setTargetBrandName(targetBrand);
// 期望店铺(2026-11-24):建单载荷优先;旧任务载荷没有这两个键 ⇒ 回落明细快照里的
// shop_name(V210 落库时就有),至少能按店名核对,绝不静默跳过核对。
JdPublishTaskCreateRequest create = readCreateRequest(task);
vo.setShopId(trimToNull(create.getShopId()));
String expectedShopName = trimToNull(create.getShopName());
if (expectedShopName == null && !rows.isEmpty()) {
expectedShopName = trimToNull(rows.get(0).getShopName());
}
vo.setShopName(expectedShopName);
vo.setItems(rows.isEmpty() ? List.of() : rows.stream() vo.setItems(rows.isEmpty() ? List.of() : rows.stream()
.map(row -> buildItemPayload(row, productsByPid.get(row.getProductId()))) .map(row -> buildItemPayload(row, productsByPid.get(row.getProductId())))
.toList()); .toList());
@@ -271,6 +286,13 @@ public class JdPublishTaskService {
if (create.getTargetBrandName() != null) { if (create.getTargetBrandName() != null) {
data.put("targetBrandRequired", true); data.put("targetBrandRequired", true);
} }
// 期望店铺随载荷下发:客户端在建单推送这条路上就不必先拉明细也能核对店铺。
if (trimToNull(create.getShopId()) != null) {
data.put("shopId", create.getShopId().strip());
}
if (trimToNull(create.getShopName()) != null) {
data.put("shopName", create.getShopName().strip());
}
data.put("priceRule", create.getPriceRule() == null ? Map.of("mode", "none") : create.getPriceRule()); data.put("priceRule", create.getPriceRule() == null ? Map.of("mode", "none") : create.getPriceRule());
return Map.of("type", JdPublishTaskPullSpiImpl.QUEUE_TYPE, "data", data); return Map.of("type", JdPublishTaskPullSpiImpl.QUEUE_TYPE, "data", data);
} }
@@ -358,6 +380,64 @@ public class JdPublishTaskService {
return brand; return brand;
} }
/** 建单勾选集的来源店铺(服务端按商品快照判定;请求体里的同名字段一律被覆盖)。 */
record ShopIdentity(String id, String name) {
}
/**
* 一次上架只允许单店商品:客户端发布前只核对「本机京麦当前登录店铺」这一家,跨店勾选
* 没有任何一家登录态能同时发对两家店 ⇒ 建单即拒并点名店铺(fail-closed)。
*
* <p>判定按「商品行实际带什么」分三档:有 venderId 用 ID 当键;只有店名且该店名在本次
* 勾选里出现过对应 ID 的(同一家店的两种形状)归一到 ID;只剩店名的按名字当键。
* 完全没有店铺标识的旧行不参与判定——那种行本来就没有可核对的锚点,客户端会明确
* 告警「任务未记录来源店铺」,不在这里冒充已核对。</p>
*/
private static ShopIdentity resolveSingleShop(List<JdProductEntity> products) {
Map<String, String> nameToId = new LinkedHashMap<>();
for (JdProductEntity product : products) {
String id = trimToNull(product.getShopId());
String name = trimToNull(product.getShopName());
if (id != null && name != null) {
nameToId.putIfAbsent(name, id);
}
}
Set<String> keys = new java.util.LinkedHashSet<>();
Map<String, String> labelByKey = new LinkedHashMap<>();
for (JdProductEntity product : products) {
String id = trimToNull(product.getShopId());
String name = trimToNull(product.getShopName());
String key;
if (id != null) {
key = "id:" + id;
} else if (name != null && nameToId.containsKey(name)) {
key = "id:" + nameToId.get(name);
} else if (name != null) {
key = "name:" + name;
} else {
continue;
}
keys.add(key);
labelByKey.putIfAbsent(key, name != null ? name : id);
}
if (keys.size() > 1) {
throw new BusinessException(400, "本次勾选的商品来自多个店铺("
+ String.join("、", labelByKey.values())
+ "),一次上架只能发到一家店,请按店铺分开勾选");
}
if (keys.isEmpty()) {
return new ShopIdentity(null, null);
}
String key = keys.iterator().next();
String id = key.startsWith("id:") ? key.substring(3) : null;
return new ShopIdentity(id, labelByKey.get(key));
}
private static String trimToNull(String value) {
String trimmed = value == null ? "" : value.strip();
return trimmed.isEmpty() ? null : trimmed;
}
private String writeCreateRequest(JdPublishTaskCreateRequest request) { private String writeCreateRequest(JdPublishTaskCreateRequest request) {
try { try {
return objectMapper.writeValueAsString(request); return objectMapper.writeValueAsString(request);
@@ -210,4 +210,27 @@ class JdPublishIngestServiceTest {
when(staleTaskService.terminalizeOnJdLoginFatal(task, "京麦未登录")).thenReturn(true); when(staleTaskService.terminalizeOnJdLoginFatal(task, "京麦未登录")).thenReturn(true);
assertThat(service.submitChunk(TASK_ID, request(1, "batchA", "FAILED", "京麦未登录"), UID).getTaskStatus()).isEqualTo("FAILED"); assertThat(service.submitChunk(TASK_ID, request(1, "batchA", "FAILED", "京麦未登录"), UID).getTaskStatus()).isEqualTo("FAILED");
} }
@Test
void 店铺不匹配上报即整单判死不按行数收窄() {
FileTaskEntity task = task("RUNNING", 1, 2);
JdPublishChunkRequest request = request(1, "batchA", null, null);
request.setError("京东店铺不匹配:任务记录「家居日用数据库店」,当前京麦登录「花屿巷旗舰店」");
when(staleTaskService.terminalizeOnJdShopMismatch(task, request.getError())).thenReturn(true);
// 零行回传也要判死:这是打开商品页之前的确定性失败,重试同一登录态只会再错一次。
assertThat(service.submitChunk(TASK_ID, request, UID).getTaskStatus()).isEqualTo("FAILED");
verify(staleTaskService).terminalizeOnJdShopMismatch(task, request.getError());
verify(staleTaskService, never()).terminalizeOnJdLoginFatal(any(), any());
}
@Test
void 其他失败上报文本不触发店铺判死() {
task("RUNNING", 1, 2);
JdPublishChunkRequest request = request(1, "batchA", null, null);
request.setError("页面结构变更,未确认提交");
assertThat(service.submitChunk(TASK_ID, request, UID).getTaskStatus()).isNull();
verifyNoInteractions(staleTaskService);
}
} }
@@ -0,0 +1,110 @@
package com.nanri.aiimage.modules.jd.service;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.common.mapper.AdminUserMapper;
import com.nanri.aiimage.common.model.entity.AdminUserEntity;
import com.nanri.aiimage.modules.permission.model.vo.PermissionMenuItemVo;
import com.nanri.aiimage.modules.permission.service.PermissionMenuService;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.when;
/**
* 商品上架菜单权限闸(2026-11-24 客户口径「上架的账户,我是这个权限不开给他的」)。
*
* <p>判据四件:组键 jd_tools 命中整组放行;子键 jd-publish 单独命中放行;只有 jd-collect
* 一律 403;平台过滤与登录下发同源(亚马逊档账号拿到 jd 键也不放行)。</p>
*/
@ExtendWith(MockitoExtension.class)
class JdPublishPermissionSupportTest {
@Mock
private AdminUserMapper adminUserMapper;
@Mock
private PermissionMenuService permissionMenuService;
@InjectMocks
private JdPublishPermissionSupport support;
private AdminUserEntity jdUser() {
AdminUserEntity user = new AdminUserEntity();
user.setId(7L);
user.setCompanyId(2L);
user.setPlatform("jd");
user.setCreatedById(1L);
return user;
}
private PermissionMenuItemVo column(long id, String key) {
PermissionMenuItemVo vo = new PermissionMenuItemVo();
vo.setId(id);
vo.setColumnKey(key);
vo.setMenuType(PermissionMenuService.MENU_TYPE_APP);
return vo;
}
@Test
void 组键命中整组放行() {
when(adminUserMapper.selectById(7L)).thenReturn(jdUser());
when(permissionMenuService.getUserColumnPermissions(7L, PermissionMenuService.MENU_TYPE_APP))
.thenReturn(List.of(column(1L, "jd_tools"), column(2L, "jd-collect"), column(3L, "jd-publish")));
assertThat(support.canPublish(7L)).isTrue();
support.assertCanPublish(7L);
}
@Test
void 只授商品上架子键也放行() {
when(adminUserMapper.selectById(7L)).thenReturn(jdUser());
when(permissionMenuService.getUserColumnPermissions(7L, PermissionMenuService.MENU_TYPE_APP))
.thenReturn(List.of(column(3L, "jd-publish")));
assertThat(support.canPublish(7L)).isTrue();
}
@Test
void 只授采集不授上架一律403并点名开通入口() {
when(adminUserMapper.selectById(7L)).thenReturn(jdUser());
when(permissionMenuService.getUserColumnPermissions(7L, PermissionMenuService.MENU_TYPE_APP))
.thenReturn(List.of(column(2L, "jd-collect")));
assertThat(support.canPublish(7L)).isFalse();
assertThatThrownBy(() -> support.assertCanPublish(7L))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("没有「商品上架」权限")
.hasMessageContaining("菜单权限")
.extracting("code")
.isEqualTo(403);
}
@Test
void 平台过滤与登录下发同源_亚马逊档即便拿到京东键也不放行() {
AdminUserEntity amazon = jdUser();
amazon.setPlatform("amazon");
when(adminUserMapper.selectById(7L)).thenReturn(amazon);
when(permissionMenuService.getUserColumnPermissions(7L, PermissionMenuService.MENU_TYPE_APP))
.thenReturn(List.of(column(1L, "jd_tools"), column(3L, "jd-publish")));
assertThat(support.canPublish(7L)).as("京东菜单只下发京东档账号,判据不得比下发松").isFalse();
}
@Test
void 站点超管与查不到账号的边界() {
AdminUserEntity superAdmin = jdUser();
superAdmin.setRole("super_admin");
when(adminUserMapper.selectById(7L)).thenReturn(superAdmin);
assertThat(support.canPublish(7L)).isTrue();
when(adminUserMapper.selectById(8L)).thenReturn(null);
assertThat(support.canPublish(8L)).isFalse();
assertThat(support.canPublish(null)).isFalse();
}
}
@@ -103,4 +103,35 @@ class JdPublishStaleTaskServiceTest {
assertThat(JdStaleTaskService.isJdLoginStateFailure("页面结构变更")).isFalse(); assertThat(JdStaleTaskService.isJdLoginStateFailure("页面结构变更")).isFalse();
assertThat(JdStaleTaskService.isJdLoginStateFailure(" ")).isFalse(); assertThat(JdStaleTaskService.isJdLoginStateFailure(" ")).isFalse();
} }
@Test
void 店铺不匹配判死CAS成功并点名两家店() {
FileTaskEntity task = task(34420L);
when(fileTaskMapper.update(any(), any(LambdaUpdateWrapper.class))).thenReturn(1);
boolean terminalized = service.terminalizeOnJdShopMismatch(task,
"京东店铺不匹配:任务记录「家居日用数据库店」(shopId=228346061),"
+ "当前京麦登录「花屿巷旗舰店」(shopId=165515933),请先切换店铺");
assertThat(terminalized).isTrue();
ArgumentCaptor<LambdaUpdateWrapper> captor = ArgumentCaptor.forClass(LambdaUpdateWrapper.class);
verify(fileTaskMapper).update(any(), captor.capture());
String joined = java.util.Arrays.toString(captor.getValue().getParamNameValuePairs().values().toArray());
assertThat(joined)
.contains("家居日用数据库店")
.contains("花屿巷旗舰店")
.contains("京麦切换到任务记录的那家店")
.doesNotContain("稍后重试");
verify(taskProgressSnapshotService).markTerminal(eq(34420L), eq("JD_PUBLISH"), eq("FAILED"), any());
}
@Test
void 店铺不匹配已终态不命中可重入() {
FileTaskEntity task = task(34421L);
when(fileTaskMapper.update(any(), any(LambdaUpdateWrapper.class))).thenReturn(0);
assertThat(service.terminalizeOnJdShopMismatch(task, "京东店铺不匹配")).isFalse();
verify(taskProgressSnapshotService, org.mockito.Mockito.never())
.markTerminal(any(), any(), any(), any());
}
} }
@@ -416,4 +416,76 @@ class JdPublishTaskServiceTest {
assertThat(vo.isAlive()).isTrue(); assertThat(vo.isAlive()).isTrue();
verify(taskHeartbeatPositionService).record(eq(34400L), any()); verify(taskHeartbeatPositionService).record(eq(34400L), any());
} }
// ---- 来源店铺闸(2026-11-24 客户口径「软件怎么知道要上架哪一家店」)----
@Test
void 跨店勾选建单被拒并点名两家店() {
when(adminUserMapper.selectById(7L)).thenReturn(new AdminUserEntity());
JdProductEntity first = product(101L, 7L, "连衣裙A");
first.setShopId("1001");
first.setShopName("花屿巷旗舰店");
JdProductEntity second = product(102L, 7L, "连衣裙B");
second.setShopId("2002");
second.setShopName("家居日用数据库店");
when(jdProductMapper.selectBatchIds(List.of(101L, 102L))).thenReturn(List.of(first, second));
assertThatThrownBy(() -> service.createTask(validRequest(7L), null))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("多个店铺")
.hasMessageContaining("花屿巷旗舰店")
.hasMessageContaining("家居日用数据库店");
verify(fileTaskMapper, never()).insert(any(FileTaskEntity.class));
}
@Test
void 建单把来源店铺钉进载荷与推送载荷() {
when(adminUserMapper.selectById(7L)).thenReturn(new AdminUserEntity());
JdProductEntity first = product(101L, 7L, "连衣裙A");
first.setShopId("228346061");
first.setShopName("家居日用数据库店");
JdProductEntity second = product(102L, 7L, "连衣裙B");
second.setShopId("228346061");
second.setShopName("家居日用数据库店");
when(jdProductMapper.selectBatchIds(List.of(101L, 102L))).thenReturn(List.of(first, second));
when(fileTaskMapper.insert(any(FileTaskEntity.class))).thenAnswer(invocation -> {
invocation.getArgument(0, FileTaskEntity.class).setId(34410L);
return 1;
});
when(jdPublishItemMapper.insert(any(JdPublishItemEntity.class))).thenReturn(1);
JdPublishTaskVo vo = service.createTask(validRequest(7L), null);
ArgumentCaptor<FileTaskEntity> taskCaptor = ArgumentCaptor.forClass(FileTaskEntity.class);
verify(fileTaskMapper).insert(taskCaptor.capture());
assertThat(taskCaptor.getValue().getRequestJson())
.as("期望店铺随建单载荷固化,客户端兜底拉取也能核对")
.contains("\"shopId\":\"228346061\"")
.contains("\"shopName\":\"家居日用数据库店\"");
assertThat(String.valueOf(vo.getQueuePayload())).contains("228346061").contains("家居日用数据库店");
}
@Test
void 同店两种形状归一后放行() {
when(adminUserMapper.selectById(7L)).thenReturn(new AdminUserEntity());
JdProductEntity withId = product(101L, 7L, "连衣裙A");
withId.setShopId("228346061");
withId.setShopName("家居日用数据库店");
JdProductEntity nameOnly = product(102L, 7L, "连衣裙B");
nameOnly.setShopId(null);
nameOnly.setShopName("家居日用数据库店");
when(jdProductMapper.selectBatchIds(List.of(101L, 102L))).thenReturn(List.of(withId, nameOnly));
when(fileTaskMapper.insert(any(FileTaskEntity.class))).thenAnswer(invocation -> {
invocation.getArgument(0, FileTaskEntity.class).setId(34411L);
return 1;
});
when(jdPublishItemMapper.insert(any(JdPublishItemEntity.class))).thenReturn(1);
JdPublishTaskVo vo = service.createTask(validRequest(7L), null);
assertThat(vo.getTaskId()).isEqualTo(34411L);
assertThat(String.valueOf(vo.getQueuePayload()))
.as("只带店名的行按同名归一到同一家店的 venderId")
.contains("228346061");
}
} }
+155
View File
@@ -22,6 +22,13 @@ import {
} from '@/shared/api/types/modules/jd-publish' } from '@/shared/api/types/modules/jd-publish'
import { retryClientTask } from '@/shared/api/task-retry' import { retryClientTask } from '@/shared/api/task-retry'
import { getPywebviewApi } from '@/shared/bridges/pywebview' import { getPywebviewApi } from '@/shared/bridges/pywebview'
import { ensureJdLogin, markJdLoginExpired } from '@/shared/stores/jd-login-autoflow'
import {
evaluateShopGuard,
shopGuardBlocks,
shopLabel,
type JdShopRef,
} from '@/pages/jd/jd-publish-shop'
import { resolvePageHref } from '@/shared/page-prefix' import { resolvePageHref } from '@/shared/page-prefix'
import { userNotice } from '@/shared/utils/user-notice' import { userNotice } from '@/shared/utils/user-notice'
import { formatDateTime } from '@/shared/utils/datetime' import { formatDateTime } from '@/shared/utils/datetime'
@@ -166,8 +173,109 @@ function isValidBrand(name: string) {
const priceValueMissing = computed(() => priceMode.value !== 'none' && (priceValue.value == null || priceValue.value < 0)) const priceValueMissing = computed(() => priceMode.value !== 'none' && (priceValue.value == null || priceValue.value < 0))
// ---- 本次上架到哪家店(2026-11-24 客户口径「软件怎么知道要上架哪一家店铺」)----
/** 来源店铺=勾选商品行的快照店铺;京麦当前店铺=桥现拉(不缓存、不猜、不自动探测)。 */
const selectedProductRows = computed(() => Array.from(selectedProducts.value.values()))
const currentShop = ref<JdShopRef | null>(null)
const detectingShop = ref(false)
const canDetectShop = ref(false)
const shopNote = ref('')
const shopError = ref('')
const SHOP_DETECT_UNAVAILABLE =
'当前在本机客户端之外打开或客户端版本较旧,无法检测京麦店铺。请在本机客户端中打开本页;'
+ '本机客户端发布前仍会核对任务记录的店铺,不一致整单拦下、一条都不发'
const shopGuard = computed(() => evaluateShopGuard(selectedProductRows.value, currentShop.value))
/** 来源店铺文案:没取到/多家店/单店三档(多店由 shopGuard 直接拦)。 */
const sourceShopText = computed(() => {
const guard = shopGuard.value
if (guard.state === 'unknown') return '未取到(旧商品数据没有店铺信息)'
if (guard.state === 'multi') return guard.shops.map((shop) => shopLabel(shop)).join('、')
return shopLabel(guard.expected)
})
const currentShopText = computed(() => (currentShop.value ? shopLabel(currentShop.value) : '未检测'))
/** 挂载时判可用性:老客户端没有 get_jd_shop_info ⇒ 检测按钮置灰(同「同步分类」口径)。 */
function refreshShopDetectability() {
canDetectShop.value = typeof getPywebviewApi()?.get_jd_shop_info === 'function'
}
/**
* 点「检测当前京麦店铺」:桥现拉京麦首屏(会起客户端专用浏览器,秒级)。
* 失败按 code 分档——jd_busy 走 amber 说明、jd_login 走自动登录链路(登录成功后自动重测一次)、
* jd_page/未知走红色错误。返回值只作 `startPublish` 的判断输入,展示通道由本函数自理。
*/
async function detectShop(options?: { fromAutoLogin?: boolean }) {
if (detectingShop.value && !options?.fromAutoLogin) return
shopError.value = ''
shopNote.value = ''
const api = getPywebviewApi()
const bridge = api?.get_jd_shop_info
if (typeof bridge !== 'function') {
canDetectShop.value = false
shopNote.value = SHOP_DETECT_UNAVAILABLE
return
}
detectingShop.value = true
try {
const result = await bridge()
if (result?.success && (result.shopName || result.shopId)) {
currentShop.value = { shopId: result.shopId, shopName: result.shopName }
return
}
if (result?.code === 'jd_busy') {
shopNote.value = result.error || '京东任务正在运行,等任务结束后再检测京麦店铺'
return
}
if (result?.code === 'jd_login') {
if (options?.fromAutoLogin) {
shopError.value = result.error || '京麦未登录(登录态失效)'
return
}
markJdLoginExpired()
shopNote.value = '检测到京麦未登录,已自动打开京麦登录窗口,请在弹出的浏览器里完成登录'
const gate = await ensureJdLogin(api)
if (gate.status === 'ok') {
shopNote.value = ''
detectingShop.value = false
await detectShop({ fromAutoLogin: true })
return
}
if (gate.severity === 'error') {
shopNote.value = ''
shopError.value = gate.hint || result.error || '打开京麦登录窗口失败,请稍后重试'
} else {
shopNote.value = gate.hint || shopNote.value
}
return
}
shopError.value = result?.error || '检测京麦店铺失败,请稍后重试'
} finally {
detectingShop.value = false
}
}
/**
* 建单前把店铺核一次:已检测且一致就不再开浏览器;命中不匹配/跨店直接给拦截文案。
* 检测失败(页面结构变更、老客户端、京麦任务在跑)**不**拦创建——最终强拦截在客户端
* 执行器(先上报标记再中止)与服务端(命中即整单判死),页面这层只负责提前告知。
*/
async function ensureShopChecked(): Promise<string> {
const guard = shopGuard.value
if (shopGuardBlocks(guard)) return guard.message
if (guard.state !== 'undetected') return ''
await detectShop()
const next = shopGuard.value
return shopGuardBlocks(next) ? next.message : ''
}
const submitDisabled = computed(() => const submitDisabled = computed(() =>
submitting.value submitting.value
|| detectingShop.value
|| shopGuardBlocks(shopGuard.value)
|| !selectedGroupId.value || !selectedGroupId.value
|| !selectedProducts.value.size || !selectedProducts.value.size
|| !isValidBrand(targetBrandName.value) || !isValidBrand(targetBrandName.value)
@@ -603,6 +711,12 @@ async function startPublish() {
errorMessage.value = JD_UPGRADE_NOTICE errorMessage.value = JD_UPGRADE_NOTICE
return return
} }
// 店铺核对在建单之前:京麦登录的不是勾选商品那家店时一条都不发(客户口径「强拦截」)。
const shopIssue = await ensureShopChecked()
if (shopIssue) {
errorMessage.value = shopIssue
return
}
const vo = await createJdPublishTask(categoryId, productIds, priceRule, brand) const vo = await createJdPublishTask(categoryId, productIds, priceRule, brand)
board.addPollingTask(vo.taskId) board.addPollingTask(vo.taskId)
const pushNote = await pushToClientQueue(vo.queuePayload) const pushNote = await pushToClientQueue(vo.queuePayload)
@@ -620,6 +734,7 @@ async function startPublish() {
onMounted(async () => { onMounted(async () => {
const localName = (window.localStorage.getItem('username') || '').trim() const localName = (window.localStorage.getItem('username') || '').trim()
if (localName) username.value = localName if (localName) username.value = localName
refreshShopDetectability()
board.loadPollingIds() board.loadPollingIds()
await Promise.all([ await Promise.all([
loadGroups().catch(() => undefined), loadGroups().catch(() => undefined),
@@ -666,6 +781,35 @@ onUnmounted(() => {
<main class="jd-body"> <main class="jd-body">
<aside class="left-panel"> <aside class="left-panel">
<!-- 本次上架到哪家店:来源店铺(勾选商品快照)vs 京麦当前登录店铺(现检测) -->
<div class="category-block shop-guard">
<span class="category-label">本次上架到哪家店</span>
<p class="shop-line">
<span class="shop-line__key">商品来源店铺</span>
<span class="shop-line__value">{{ sourceShopText }}</span>
</p>
<p class="shop-line">
<span class="shop-line__key">京麦当前登录</span>
<span class="shop-line__value" :class="{ 'shop-line__value--muted': !currentShop }">{{ currentShopText }}</span>
<button class="shop-detect-btn" type="button" :disabled="detectingShop || !canDetectShop" @click="detectShop()">
{{ detectingShop ? '检测中…' : (currentShop ? '重新检测' : '检测京麦店铺') }}
</button>
</p>
<p v-if="shopError" class="shop-alert">{{ shopError }}</p>
<p v-else-if="shopGuard.state === 'mismatch' || shopGuard.state === 'multi'" class="shop-alert">
{{ shopGuard.message }}
</p>
<p v-else-if="shopGuard.state === 'match'" class="shop-ok">
店铺一致:商品会发布到「{{ shopLabel(shopGuard.expected) }}」。
</p>
<p v-else-if="shopNote" class="category-hint">{{ shopNote }}</p>
<p v-else-if="!canDetectShop" class="category-hint">{{ SHOP_DETECT_UNAVAILABLE }}</p>
<p v-else class="category-hint">
勾选商品后点「检测京麦店铺」可确认京麦当前登录的是不是同一家店;不一致时本页不让建单,
客户端发布前还会再核对一次,一条都不会发出去。
</p>
</div>
<div class="category-block"> <div class="category-block">
<span class="category-label">自定义分类</span> <span class="category-label">自定义分类</span>
<el-select v-model="selectedGroupId" placeholder="选择分类" class="shop-cat-select" <el-select v-model="selectedGroupId" placeholder="选择分类" class="shop-cat-select"
@@ -700,6 +844,7 @@ onUnmounted(() => {
<span class="product-info"> <span class="product-info">
<span class="product-title">{{ product.title }}</span> <span class="product-title">{{ product.title }}</span>
<span class="product-meta"> <span class="product-meta">
<template v-if="product.shopName">店铺 {{ product.shopName }} · </template>
¥{{ product.priceMin ?? '-' }}<template v-if="product.priceMax && product.priceMax !== product.priceMin">~{{ product.priceMax }}</template> ¥{{ 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> · 库存 {{ product.stockTotal ?? '-' }}<template v-if="product.skuCount"> · {{ product.skuCount }}个SKU</template>
</span> </span>
@@ -797,6 +942,16 @@ onUnmounted(() => {
.category-block { margin-bottom: 16px; } .category-block { margin-bottom: 16px; }
.category-label { display: block; margin-bottom: 8px; color: #c8d2e2; font-size: 13px; font-weight: 600; } .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; } .category-hint { margin: 8px 0 0; color: #7f8ca3; font-size: 12px; line-height: 1.6; }
.shop-guard { padding: 10px 12px; border: 1px solid #2c3547; border-radius: 8px; background: #20283a; }
.shop-line { display: flex; align-items: center; gap: 8px; margin: 0 0 6px; font-size: 12px; line-height: 1.5; }
.shop-line__key { flex-shrink: 0; color: #7f8ca3; }
.shop-line__value { min-width: 0; overflow: hidden; color: #d9e1ef; text-overflow: ellipsis; white-space: nowrap; }
.shop-line__value--muted { color: #7f8ca3; }
.shop-detect-btn { flex-shrink: 0; margin-left: auto; padding: 3px 10px; border: 1px solid #3e4a62; border-radius: 6px; background: #232b3d; color: #c8d2e2; font-family: inherit; font-size: 12px; cursor: pointer; }
.shop-detect-btn:hover:not(:disabled) { border-color: #6ea8ff; color: #f5f8fc; }
.shop-detect-btn:disabled { opacity: 0.55; cursor: not-allowed; }
.shop-alert { margin: 6px 0 0; padding: 8px 10px; border-radius: 6px; background: rgba(248, 113, 113, 0.12); color: #fca5a5; font-size: 12px; line-height: 1.6; }
.shop-ok { margin: 6px 0 0; color: #6ee7b7; font-size: 12px; }
.shop-cat-select { width: 100%; } .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__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-select :deep(.el-select__placeholder), .shop-cat-select :deep(.el-select__selected-item) { color: #c8d2e2; }
@@ -0,0 +1,44 @@
/**
* 「商品上架」按账号授权(2026-11-24 客户口径:「上架的账户 我是这个权限不开给他的」)。
*
* 三层,口径同一份、判据逐字相同:
* 1. **入口**:京东工作台的卡片由 `filterJdToolsByPermission` 过滤(V209 app 菜单:
* 组键 `jd_tools` 或子键 `jd-publish`);
* 2. **直达路由**:`/jd-publish` 的 `beforeEnter` 用本文件的 `resolveJdPublishAccess`,
* 没权限的用户手敲地址也进不来(正常入口被隐藏后,直达是唯一绕过口);
* 3. **服务端**:`JdPublishPermissionSupport.assertCanPublish`(建单/选品/面板一律 403),
* 这是唯一权威判据——前端两层只为用户体验,不承担安全职责。
*
* 收回权限的实操(后管「用户管理 → 菜单权限 → 桌面端」):把「商品上架」子项取消勾选后
* 保存,直接授权集合只剩 `{jd-collect}`,读侧不再展开 `jd_tools` 组 ⇒ 本文件判为无权限。
*
* 权限接口异常(`null`)按「未知」放行:后管账号体系里「读不到权限」与「没有权限」必须分开,
* 抖一下把有权限的人锁在门外比放进去后被 403 更难解释;后端 403 仍是硬边界。
*/
/** app 菜单组键(V209 columns.column_key='jd_tools') */
export const JD_PUBLISH_GROUP_KEY = 'jd_tools'
/** 商品上架子键(V209 columns.column_key='jd-publish') */
export const JD_PUBLISH_COLUMN_KEY = 'jd-publish'
export const JD_PUBLISH_DENIED_TEXT =
'当前账号没有「商品上架」权限,请联系管理员在后台「用户管理 → 菜单权限 → 桌面端」里勾上「商品上架」'
export type JdPublishAccess = 'allowed' | 'denied' | 'unknown'
/** 权限键是否覆盖「商品上架」:组键命中(预授权授的是组行)或子键命中都算。 */
export function canUseJdPublish(keys: ReadonlyArray<string> | null | undefined): boolean {
const allowed = new Set(
(keys ?? []).map((key) => String(key ?? '').trim().toLowerCase()).filter(Boolean),
)
return allowed.has(JD_PUBLISH_GROUP_KEY) || allowed.has(JD_PUBLISH_COLUMN_KEY)
}
/**
* 路由判据:拿到键集(可能为空数组=真没权限)⇒ allowed/denied;
* 拿不到键集(接口失败/超时,调用方传 null)⇒ unknown(放行,服务端 403 兜底)。
*/
export function resolveJdPublishAccess(keys: ReadonlyArray<string> | null): JdPublishAccess {
if (keys === null) return 'unknown'
return canUseJdPublish(keys) ? 'allowed' : 'denied'
}
@@ -0,0 +1,127 @@
/**
* 京东上架「发到哪一家店」(2026-11-24 客户口径:「如果没有店铺登入情况 软件怎么知道我们要上架
* 是哪一个店铺?」)。
*
* 三份身份,各有唯一出处,三层同一标记:
* 1. **来源店铺**=所勾商品行的 `shopName/shopId`(京东数据库快照)。服务端建单时按它做
* 「一单只能发到一家店」校验(`JdPublishTaskService.resolveSingleShop`),并把它钉进
* 任务载荷与明细下发(`JdPublishItemsPageVo.shopId/shopName`);
* 2. **京麦当前登录店铺**=桥 `get_jd_shop_info` 现拉(客户端起有头浏览器读京麦首屏),
* 不是页面缓存、也不是上次「同步分类」的残留;本页只拿它做提前告知;
* 3. **最终强拦截**=客户端发布前用任务记录的店铺再核一次(`JdPublishPage.verify_shop`),
* 不一致先上报标记再中止,服务端 `JdPublishStaleTaskService` 命中即整单判死——一条都不发。
*
* 本文件是纯函数(node --test 直测):只产状态与中文文案,复选框禁用/错误条/提示色由调用方选。
*/
/** 判据标记:客户端 `SHOP_MISMATCH_MARK`、服务端 `JdPublishStaleTaskService.SHOP_MISMATCH_MARK` 同值。 */
export const SHOP_MISMATCH_MARK = '京东店铺不匹配'
export interface JdShopRef {
shopId?: string
shopName?: string
}
/** 来源店铺的最小子集(只要这两个字段,页面传 `JdPublishProductVo[]` 进来即可)。 */
export interface JdShopSource {
shopId?: string
shopName?: string
}
export type JdShopGuard =
/** 勾选的商品没带店铺信息(旧数据/未勾选)⇒ 页面不拦,交给客户端与服务端兜底 */
| { state: 'unknown' }
/** 有来源店铺、还没检测京麦 ⇒ 提示可检测(不拦) */
| { state: 'undetected'; expected: JdShopRef }
| { state: 'match'; expected: JdShopRef; actual: JdShopRef }
| { state: 'mismatch'; expected: JdShopRef; actual: JdShopRef; message: string }
/** 勾选的商品来自多家店 ⇒ 服务端也会拒(按店分开勾) */
| { state: 'multi'; shops: JdShopRef[]; message: string }
function text(value: unknown): string {
return String(value ?? '').trim()
}
/** 归一化店铺身份:两名皆空返回 null(把「没记录」和「记录了空串」当同一件事)。 */
export function normalizeShopRef(raw: JdShopRef | null | undefined): JdShopRef | null {
const shopId = text(raw?.shopId)
const shopName = text(raw?.shopName)
if (!shopId && !shopName) return null
return { ...(shopId ? { shopId } : {}), ...(shopName ? { shopName } : {}) }
}
/** 人读标签:`家居日用数据库店(shopId=228346061)`,缺一半只报有的那半。 */
export function shopLabel(raw: JdShopRef | null | undefined): string {
const shop = normalizeShopRef(raw)
if (!shop) return '未记录店铺'
if (shop.shopName && shop.shopId) return `${shop.shopName}(shopId=${shop.shopId})`
if (shop.shopName) return shop.shopName
return `shopId=${shop.shopId}`
}
/**
* 勾选商品的来源店铺去重(id 优先、回退店名):同一家店的不同行只算一家,
* 顺序按勾选先后稳定输出(页面文案不会因 Map 重排跳字)。
*
* 跨形状归一:库存里有行带 id、有行只带店名(快照字段缺失),both 指同一家店时
* 必须并成一条并补齐缺的字段——否则页面对同店勾选误报「来自多个店铺」。
*/
export function sourceShopRefs(products: ReadonlyArray<JdShopSource> | null | undefined): JdShopRef[] {
const refs: JdShopRef[] = []
for (const product of products ?? []) {
const shop = normalizeShopRef(product)
if (!shop) continue
const existing = refs.find((ref) => (shop.shopId && ref.shopId === shop.shopId)
|| (shop.shopName && ref.shopName === shop.shopName))
if (existing) {
if (shop.shopId && !existing.shopId) existing.shopId = shop.shopId
if (shop.shopName && !existing.shopName) existing.shopName = shop.shopName
continue
}
refs.push({ ...shop })
}
return refs
}
/** 不匹配整句:开头即标记,点名「勾选的店」与「京麦现在登的店」,给动作句(不写「稍后重试」)。 */
export function shopMismatchMessage(expected: JdShopRef | null | undefined, actual: JdShopRef | null | undefined): string {
const expectedLabel = shopLabel(expected)
return (`${SHOP_MISMATCH_MARK}:本次勾选的商品来自「${expectedLabel}」,`
+ `当前京麦登录「${shopLabel(actual)}」;请先在京麦切换到「${expectedLabel}」再上架。`)
}
/** 跨店勾选整句(与服务端建单拒绝文案同口径:按店分开勾)。 */
export function multiShopMessage(shops: ReadonlyArray<JdShopRef>): string {
const labels = shops.map((shop) => shopLabel(shop)).join('、')
return `本次勾选的商品来自多个店铺(${labels}),一次上架只能发到一家店,请按店铺分开勾选。`
}
/** true/false=能比;null=两边都缺可比字段(只认同一维度:id 对 id、名对名)。 */
function sameShop(expected: JdShopRef, actual: JdShopRef): boolean | null {
if (expected.shopId && actual.shopId) return expected.shopId === actual.shopId
if (expected.shopName && actual.shopName) return expected.shopName === actual.shopName
return null
}
/** 页面判据:来源店铺(勾选集) vs 京麦当前登录店铺(检测结果,null=没检测/没读到)。 */
export function evaluateShopGuard(
products: ReadonlyArray<JdShopSource> | null | undefined,
detected: JdShopRef | null | undefined,
): JdShopGuard {
const refs = sourceShopRefs(products)
if (refs.length > 1) return { state: 'multi', shops: refs, message: multiShopMessage(refs) }
const expected = refs[0]
if (!expected) return { state: 'unknown' }
const actual = normalizeShopRef(detected)
if (!actual) return { state: 'undetected', expected }
const same = sameShop(expected, actual)
// 比不了(一边只有店名、另一边只有 id)不判不匹配:宁可留给客户端强拦截,也不误拦真实任务。
if (same === null) return { state: 'undetected', expected }
if (same) return { state: 'match', expected, actual }
return { state: 'mismatch', expected, actual, message: shopMismatchMessage(expected, actual) }
}
/** UI 唯一处断:命中这两档才禁「上架」按钮(unknown/undetected 不拦)。 */
export function shopGuardBlocks(guard: JdShopGuard): guard is Extract<JdShopGuard, { state: 'mismatch' | 'multi' }> {
return guard.state === 'mismatch' || guard.state === 'multi'
}
+30
View File
@@ -1,4 +1,32 @@
import { createRouter, createWebHistory } from 'vue-router' import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getCurrentUserAppColumnKeys } from '@/shared/api/permission'
import { JD_PUBLISH_DENIED_TEXT, resolveJdPublishAccess } from '@/pages/jd/jd-publish-access'
/**
* `/jd-publish` 直达守卫(2026-11-24 客户口径「上架的账户 我是这个权限不开给他的」)。
*
* 正常入口(京东工作台卡片)已由 filterJdToolsByPermission 隐藏,手敲地址是唯一绕过口;
* 服务端 `JdPublishPermissionSupport` 仍是一律 403 的硬边界,这里只把「进得去但处处报错」
* 换成一句可执行的中文提示 + 回工作台。
*
* 权限接口失败(拿不到键集)⇒ unknown 放行:后管账号体系里「读不到」不等于「没权限」,
* 抖一下把人锁住比让它落到后端 403 更难解释(与 JdConsolePage 的 permissionUnavailable 同口径)。
*/
export async function guardJdPublishRoute(): Promise<true | { path: string }> {
let keys: string[] | null = null
try {
keys = await getCurrentUserAppColumnKeys()
} catch (error) {
keys = null
console.error('[router] 读取菜单权限失败,/jd-publish 按放行处理:%s',
error instanceof Error ? error.message : String(error))
}
if (resolveJdPublishAccess(keys) !== 'denied') return true
ElMessage.warning(JD_PUBLISH_DENIED_TEXT)
return { path: '/jd-console' }
}
/** /**
* 数富AI 桌面前端 SPA 路由(无 .html 后缀) * 数富AI 桌面前端 SPA 路由(无 .html 后缀)
@@ -82,6 +110,8 @@ const routes = [
path: '/jd-publish', path: '/jd-publish',
name: 'jd-publish', name: 'jd-publish',
component: () => import('@/pages/jd/JdPublishTab.vue'), component: () => import('@/pages/jd/JdPublishTab.vue'),
// 菜单权限未开通「商品上架」的账号手敲地址也进不来(详见 guardJdPublishRoute)
beforeEnter: guardJdPublishRoute,
}, },
{ {
path: '/split', path: '/split',
@@ -221,6 +221,22 @@ export interface PywebviewApi {
code?: string; code?: string;
error?: string; error?: string;
}>; }>;
/**
* 京麦当前登录店铺(2026-11-24 客户口径「软件怎么知道我们要上架是哪一个店铺?」):
* 执行体 `amazon/jd/shop_categories.py::fetch_shop_info` 与「同步分类」共用同一个首屏
* 窗口,但**不等分类包**——店名/ID 到手即返回(分类档才等分类)。成功带
* `shopName/shopId`;失败 code 分档 jd_busy(京东任务在跑)/ jd_login(京麦未登录)/
* jd_page(读不到店铺信息:页面结构变更或落登录页)。
* 老客户端没有这个方法 ⇒ 页面置灰检测按钮并提示升级(发布前的强拦截在客户端执行器里,
* 不依赖本页检测)。
*/
get_jd_shop_info?: () => Promise<{
success: boolean;
shopName?: string;
shopId?: string;
code?: string;
error?: string;
}>;
/** /**
* 京麦登录窗自动触发链路(2026-11-23「登录京麦」按钮退役,原 2026-11-20 独立登录 * 京麦登录窗自动触发链路(2026-11-23「登录京麦」按钮退役,原 2026-11-20 独立登录
* 入口):起本机京东采集专用浏览器、停在京麦登录页等人工登录(执行体在客户端 * 入口):起本机京东采集专用浏览器、停在京麦登录页等人工登录(执行体在客户端
@@ -113,7 +113,12 @@ const BASELINE = {
// resubmitTask 包住重新提交请求——失败 ElMessage.error 当场把服务端文案报给用户、 // resubmitTask 包住重新提交请求——失败 ElMessage.error 当场把服务端文案报给用户、
// 成功 ElMessage.success 并刷新看板;确认框的取消走 `error === 'cancel'` 直接 return。 // 成功 ElMessage.success 并刷新看板;确认框的取消走 `error === 'cancel'` 直接 return。
// 非静默(块内有用户可见出口),silent 一格没涨、perFile 无新增条目,只进 blocks。 // 非静默(块内有用户可见出口),silent 一格没涨、perFile 无新增条目,只进 blocks。
blocks: 335, // 336 = 335 + 1(2026-11-24 京东上架「发到哪一家店」+按账号授权):router/index.ts 的
// guardJdPublishRoute 包住 app 菜单权限读取——接口失败/超时按 unknown 放行(keys=null),
// 原文只进 console;「读不到权限」不等于「没权限」,把有权限的人锁在门外比放进去后被
// 服务端 403 更难解释(与 JdConsolePage 的 permissionUnavailable 同口径)。非静默:
// 首条语句是状态写入、不是 console.*,silent 一格没涨、perFile 无新增条目,只进 blocks。
blocks: 336,
// 2026-10-30(ops Phase 6/可读棘轮):ApiSecretSettingsPanel.vue 1113→775 行,面板里那处 // 2026-10-30(ops Phase 6/可读棘轮):ApiSecretSettingsPanel.vue 1113→775 行,面板里那处
// 静默 catch(余额查询失败只 console.warn、界面留空)随 loadBalance 整块搬进 // 静默 catch(余额查询失败只 console.warn、界面留空)随 loadBalance 整块搬进
// useProxyPlan.ts。不是新增静默:面板 1→0、新文件记 1,silent 总数与 blocks 都一格没动, // useProxyPlan.ts。不是新增静默:面板 1→0、新文件记 1,silent 总数与 blocks 都一格没动,
+162
View File
@@ -0,0 +1,162 @@
import assert from 'node:assert/strict'
import { existsSync, readFileSync } from 'node:fs'
import { join } from 'node:path'
import test from 'node:test'
import {
canUseJdPublish,
JD_PUBLISH_DENIED_TEXT,
resolveJdPublishAccess,
} from '../src/pages/jd/jd-publish-access.ts'
import {
evaluateShopGuard,
normalizeShopRef,
shopGuardBlocks,
shopLabel,
shopMismatchMessage,
SHOP_MISMATCH_MARK,
sourceShopRefs,
} from '../src/pages/jd/jd-publish-shop.ts'
/**
* 2026-11-24 客户口径两件(京东「商品上架」):
* 1. 「如果没有店铺登入情况 软件怎么知道我们要上架是哪一个店铺?」——页面必须显形
* 来源店铺与京麦当前登录店铺,不一致强拦截;
* 2. 「上架的账户 我是这个权限不开给他的」——按账号授权:入口隐藏(卡片过滤)+
* 直达路由守卫+服务端 403 三层。
*
* 本文件管纯判据与源码绊线;页面接线由 tests/mount/jd-publish-dispatch.mount.test.ts 覆盖。
*/
const ROOT = process.cwd()
function read(relativePath: string, what: string): string {
const path = join(ROOT, relativePath)
assert.ok(existsSync(path), `${what} 尚未落地:${path}`)
return readFileSync(path, 'utf8')
}
// ---------------------------------------------------------------- 店铺身份判据
test('来源店铺按 id 去重、同名单店归一、空值全部丢弃', () => {
const refs = sourceShopRefs([
{ shopId: ' 228346061 ', shopName: ' 家居日用数据库店 ' },
{ shopId: '228346061', shopName: '家居日用数据库店' },
{ shopId: '', shopName: '家居日用数据库店' },
{ shopName: '花屿巷旗舰店' },
{ shopId: null, shopName: ' ' },
{},
])
assert.deepEqual(refs, [
{ shopId: '228346061', shopName: '家居日用数据库店' },
{ shopName: '花屿巷旗舰店' },
], '同一家店不同行只算一家;店名回退 id 时不能把空 id 当身份')
})
test('同一家店两种形状(只有 id / 只有店名)在来源集里能归一', () => {
// id 口径优先:一行有 id 一行只有名字时,页面无法确定同店,按两家报出来让用户分开勾
const refs = sourceShopRefs([{ shopId: '1' }, { shopName: '某店' }])
assert.equal(refs.length, 2)
})
test('店铺标签:名+id 全显示,缺一半只报有的那半,全空=未记录店铺', () => {
assert.equal(shopLabel({ shopId: '1', shopName: '某店' }), '某店(shopId=1)')
assert.equal(shopLabel({ shopName: '某店' }), '某店')
assert.equal(shopLabel({ shopId: '1' }), 'shopId=1')
assert.equal(shopLabel(null), '未记录店铺')
assert.equal(normalizeShopRef({ shopId: ' ' }), null)
})
test('不匹配文案:标记开头、点名两家店、给动作句且不写「稍后重试」', () => {
const message = shopMismatchMessage(
{ shopId: '228346061', shopName: '家居日用数据库店' },
{ shopId: '165515933', shopName: '花屿巷旗舰店' },
)
assert.ok(message.startsWith(SHOP_MISMATCH_MARK))
assert.ok(message.includes('家居日用数据库店') && message.includes('228346061'))
assert.ok(message.includes('花屿巷旗舰店') && message.includes('165515933'))
assert.ok(message.includes('切换'))
assert.ok(!message.includes('稍后重试'), '确定性失败不允许写「稍后重试」')
})
test('判据四态:未勾选 unknown / 未检测 undetected / 同店 match / 异店 mismatch', () => {
assert.equal(evaluateShopGuard([], { shopId: '1' }).state, 'unknown')
assert.equal(evaluateShopGuard([{ shopId: '1' }], null).state, 'undetected')
const match = evaluateShopGuard([{ shopId: '1', shopName: '某店' }], { shopId: '1', shopName: '某店' })
assert.equal(match.state, 'match')
const mismatch = evaluateShopGuard([{ shopId: '1', shopName: '某店' }], { shopId: '2', shopName: '别店' })
assert.equal(mismatch.state, 'mismatch')
assert.ok(shopGuardBlocks(mismatch))
assert.ok(!shopGuardBlocks(match) && !shopGuardBlocks(evaluateShopGuard([], null)))
})
test('id 优先于店名:id 不同但同名也不放行', () => {
const guard = evaluateShopGuard([{ shopId: '1', shopName: '同名店' }], { shopId: '2', shopName: '同名店' })
assert.equal(guard.state, 'mismatch')
})
test('只有店名时按店名比对;比不了(一边只有 id)按未检测处理,不误拦', () => {
assert.equal(evaluateShopGuard([{ shopName: '某店' }], { shopName: '某店' }).state, 'match')
assert.equal(evaluateShopGuard([{ shopName: '某店' }], { shopName: '别店' }).state, 'mismatch')
assert.equal(evaluateShopGuard([{ shopId: '1' }], { shopName: '某店' }).state, 'undetected')
})
test('跨店勾选直接拦,文案与服务端建单拒绝同口径(按店分开勾)', () => {
const guard = evaluateShopGuard([{ shopId: '1', shopName: '甲店' }, { shopId: '2', shopName: '乙店' }], null)
assert.equal(guard.state, 'multi')
assert.ok(shopGuardBlocks(guard))
if (guard.state === 'multi') {
assert.ok(guard.message.includes('甲店') && guard.message.includes('乙店'))
assert.ok(guard.message.includes('分开勾选'))
}
})
// ---------------------------------------------------------------- 菜单权限判据
test('权限判据:组键 jd_tools 或子键 jd-publish 命中即放行(大小写/空白归一)', () => {
assert.ok(canUseJdPublish(['jd_tools']))
assert.ok(canUseJdPublish([' JD-PUBLISH ']))
assert.ok(!canUseJdPublish(['jd-collect']), '只授「获取店铺数据」不包含「商品上架」')
assert.ok(!canUseJdPublish([]))
assert.ok(!canUseJdPublish(['jd_tools_extra']), '前缀相近不算命中')
})
test('路由判据三态:拿到空键集=denied,拿不到键集(接口失败)=unknown 放行', () => {
assert.equal(resolveJdPublishAccess(['jd-collect']), 'denied')
assert.equal(resolveJdPublishAccess(null), 'unknown')
assert.equal(resolveJdPublishAccess(['jd-publish']), 'allowed')
assert.ok(JD_PUBLISH_DENIED_TEXT.includes('菜单权限'))
assert.ok(JD_PUBLISH_DENIED_TEXT.includes('商品上架'))
})
// ---------------------------------------------------------------- 源码绊线(接线不许漏)
test('上架页显形来源店铺与京麦当前店铺,并在建单前核对', () => {
const tab = read('src/pages/jd/JdPublishTab.vue', '商品上架页')
assert.ok(tab.includes('get_jd_shop_info'), '页面必须调桥 get_jd_shop_info 现拉京麦当前店铺')
assert.ok(tab.includes('ensureShopChecked'), '建单前必须走店铺核对(strong block)')
assert.ok(tab.includes('shopGuardBlocks'), '不匹配/跨店必须禁掉上架按钮')
assert.ok(tab.includes('product.shopName'), '商品行要显形自己的来源店铺')
const createAt = tab.indexOf('createJdPublishTask(')
const checkAt = tab.indexOf('await ensureShopChecked()')
assert.ok(checkAt > 0 && createAt > checkAt, '核对必须早于建单')
})
test('上架页不得自己拼店铺身份(只用勾选商品快照 + 桥结果)', () => {
const tab = read('src/pages/jd/JdPublishTab.vue', '商品上架页')
assert.ok(!/shopId\s*=\s*['"]\d+/.test(tab), '页面不得写死任何 shopId')
assert.ok(!tab.includes('jd-shop-info'), '页面不得自拼店铺读取 URL(唯一口是桥)')
})
test('/jd-publish 直达路由挂权限守卫,权限接口失败按放行处理', () => {
const router = read('src/router/index.ts', 'router/index.ts')
assert.ok(router.includes('resolveJdPublishAccess'), '路由必须用统一判据模块')
assert.ok(/path: '\/jd-publish'[\s\S]{0,200}?beforeEnter:/.test(router), '/jd-publish 缺 beforeEnter 守卫')
assert.ok(router.includes('getCurrentUserAppColumnKeys'), '守卫必须读当前用户 app 列权限')
assert.ok(router.includes("path: '/jd-console'"), '没权限时回工作台(那里只显示有权限的卡片)')
})
test('桥类型声明 get_jd_shop_info(老客户端按缺方法置灰)', () => {
const bridge = read('src/shared/bridges/pywebview.ts', 'pywebview.ts')
assert.ok(bridge.includes('get_jd_shop_info?:'), 'PywebviewApi 缺 get_jd_shop_info 声明')
})
@@ -10,7 +10,7 @@ import {
const api = vi.hoisted(() => ({ const api = vi.hoisted(() => ({
create: vi.fn(), activate: vi.fn(), products: vi.fn(), groups: vi.fn(), create: vi.fn(), activate: vi.fn(), products: vi.fn(), groups: vi.fn(),
history: vi.fn(), progress: vi.fn(), dashboard: vi.fn(), retry: vi.fn(), enqueue: vi.fn(), bridge: vi.fn(), history: vi.fn(), progress: vi.fn(), dashboard: vi.fn(), retry: vi.fn(), enqueue: vi.fn(), bridge: vi.fn(),
protocol: vi.fn(), retryBrand: vi.fn(), alert: vi.fn(), prompt: vi.fn(), protocol: vi.fn(), retryBrand: vi.fn(), alert: vi.fn(), prompt: vi.fn(), shop: vi.fn(),
})) }))
vi.mock('@/shared/api/types/modules/jd-collect', () => ({ fetchJdCollectGroups: api.groups })) vi.mock('@/shared/api/types/modules/jd-collect', () => ({ fetchJdCollectGroups: api.groups }))
@@ -357,3 +357,78 @@ it('源商品身份缺失形状已被客户端放行,提示维持换店或重
await page.get('.history-btn').trigger('click') await page.get('.history-btn').trigger('click')
expect(page.text()).not.toContain('非在售商品') expect(page.text()).not.toContain('非在售商品')
}) })
// ---- 店铺核对(2026-11-24 客户口径「软件怎么知道要上架哪一家店铺」)----
// 桥 get_jd_shop_info 现拉京麦当前登录店铺;与勾选商品的来源店铺不一致 ⇒ 页面强拦截,一条都不建单。
// 老客户端没有这个方法(默认替身就不带)⇒ 不拦,最终拦截由客户端执行器与服务端完成。
type ShopBridgeResult = {
success: boolean; shopId?: string; shopName?: string; code?: string; error?: string
}
function withShopBridge(result: ShopBridgeResult) {
api.bridge.mockReturnValue({
jd_publish_protocol: api.protocol, enqueue_json: api.enqueue, get_jd_shop_info: api.shop,
})
api.shop.mockResolvedValue(result)
}
it('京麦登录的不是勾选商品的店铺时不建单,并点名两家店', async () => {
api.products.mockResolvedValue({
items: [{ id: 23, title: '示例商品', shopId: '228346061', shopName: '家居日用数据库店' }], total: 1,
})
withShopBridge({ success: true, shopId: '165515933', shopName: '花屿巷旗舰店' })
const page = await mountPage()
await page.get('.target-brand-input').setValue('示例品牌')
await page.get<HTMLInputElement>('.product-check').setValue(true)
// 勾选后不检测:按钮仍可点(未检测不拦),点下去才开始核对
expect(page.get<HTMLButtonElement>('.collect-btn').element.disabled).toBe(false)
await page.get('.collect-btn').trigger('click')
await flushPromises()
expect(api.shop).toHaveBeenCalledOnce()
expect(api.create).not.toHaveBeenCalled()
expect(api.enqueue).not.toHaveBeenCalled()
expect(page.text()).toContain('京东店铺不匹配')
expect(page.text()).toContain('家居日用数据库店')
expect(page.text()).toContain('花屿巷旗舰店')
expect(page.get<HTMLButtonElement>('.collect-btn').element.disabled).toBe(true)
})
it('京麦与来源店铺一致时照常建单', async () => {
api.products.mockResolvedValue({
items: [{ id: 23, title: '示例商品', shopId: '228346061', shopName: '家居日用数据库店' }], total: 1,
})
withShopBridge({ success: true, shopId: '228346061', shopName: '家居日用数据库店' })
const page = await mountPage()
await startPublish(page)
expect(api.shop).toHaveBeenCalledOnce()
expect(api.create).toHaveBeenCalledExactlyOnceWith(12, [23], { mode: 'none' }, '示例品牌')
expect(page.text()).toContain('店铺一致')
})
it('检测过且一致后不再重复起浏览器', async () => {
api.products.mockResolvedValue({
items: [{ id: 23, title: '示例商品', shopId: '228346061', shopName: '家居日用数据库店' }], total: 1,
})
withShopBridge({ success: true, shopId: '228346061', shopName: '家居日用数据库店' })
const page = await mountPage()
await page.get<HTMLInputElement>('.product-check').setValue(true)
await page.get('.shop-detect-btn').trigger('click')
await flushPromises()
expect(api.shop).toHaveBeenCalledOnce()
await startPublish(page)
expect(api.shop).toHaveBeenCalledOnce()
expect(api.create).toHaveBeenCalledOnce()
})
it('京麦未登录时给登录指引,不静默建单', async () => {
api.products.mockResolvedValue({
items: [{ id: 23, title: '示例商品', shopId: '228346061', shopName: '家居日用数据库店' }], total: 1,
})
withShopBridge({ success: false, code: 'jd_busy', error: '京东任务正在运行,请稍后再试' })
const page = await mountPage()
await startPublish(page)
// jd_busy 档:不硬拦(任务可能在收尾),页面给 amber 说明;建单继续,最终拦截在客户端
expect(api.create).toHaveBeenCalledOnce()
expect(page.text()).toContain('京东任务正在运行')
})
@@ -0,0 +1,47 @@
import { beforeEach, expect, it, vi } from 'vitest'
/**
* `/jd-publish` 直达权限守卫(2026-11-24 客户口径「上架的账户 我是这个权限不开给他的」)。
*
* 正常入口(京东工作台卡片)已被 `filterJdToolsByPermission` 隐藏,手敲地址是唯一绕过口;
* 这里直测守卫本体,不导航(导航会顺带拉起页面组件、发一堆真实请求)。
* 三层口径:入口隐藏 + 本守卫 + 服务端 `JdPublishPermissionSupport` 403(唯一权威判据)。
*/
const api = vi.hoisted(() => ({ columnKeys: vi.fn() }))
vi.mock('@/shared/api/permission', () => ({ getCurrentUserAppColumnKeys: api.columnKeys }))
vi.mock('element-plus', async (importOriginal) => ({
...await importOriginal<typeof import('element-plus')>(),
ElMessage: { warning: vi.fn(), error: vi.fn(), success: vi.fn() },
}))
const { guardJdPublishRoute } = await import('@/router/index')
const { ElMessage } = await import('element-plus')
beforeEach(() => {
api.columnKeys.mockReset()
vi.mocked(ElMessage.warning).mockClear()
vi.spyOn(console, 'error').mockImplementation(() => undefined)
})
it('没开通「商品上架」的账号手敲 /jd-publish 被挡回京东工作台并给中文提示', async () => {
api.columnKeys.mockResolvedValue(['jd-collect'])
expect(await guardJdPublishRoute()).toEqual({ path: '/jd-console' })
expect(ElMessage.warning).toHaveBeenCalledOnce()
expect(String(vi.mocked(ElMessage.warning).mock.calls[0][0])).toContain('商品上架')
})
it('组键 jd_tools 或子键 jd-publish 命中都放行', async () => {
api.columnKeys.mockResolvedValue(['jd_tools'])
expect(await guardJdPublishRoute()).toBe(true)
api.columnKeys.mockResolvedValue(['jd-collect', 'jd-publish'])
expect(await guardJdPublishRoute()).toBe(true)
expect(ElMessage.warning).not.toHaveBeenCalled()
})
it('权限接口失败按放行处理(读不到 ≠ 没权限,后端 403 仍是硬边界)', async () => {
api.columnKeys.mockRejectedValue(new Error('timeout'))
expect(await guardJdPublishRoute()).toBe(true)
expect(ElMessage.warning).not.toHaveBeenCalled()
})