feat(京东跨店上架): 协议 v4 + 目标店/发布模式 + V218 + 必填属性 AI 补值

客户口径「要跨店」:客户端走京麦「新增商品」路径(publishType=1),服务端要能把
「发到哪家店、走哪条链」一路下发,并让旧客户端领不到 NEW 明细。

- JdPublishProtocol:CROSS_SHOP=4;supportsTargetBrand/supportsCrossShop 均改区间判定
  (v4 是 v3 的超集,等值比较会让协议 4 客户端被剔出 v3 能力集)
- 建单:JdPublishTaskCreateRequest 加 targetShopId/targetShopName;来源店仍须唯一;
  给了目标店即算 publishMode(同 ID=CLONE,否则 NEW);两者都空校验失败
- V218:biz_jd_publish_item 加 shop_id/target_shop_id/target_shop_name/publish_mode
  (四列可空,NULL=旧行按来源店克隆,历史行为逐字不变)
- 载荷/明细/队列:JdPublishItemsPageVo 与 buildQueuePayload 带目标店与模式
- 兜底拉取:FileTaskMapper 增 supportsCrossShop 参数,SQL 闸不向旧客户端投递 NEW
- fill-values:JdPublishFillValuesRequest 加 missingAttrs(name+候选 options),
  回包 attrValues 必须命中候选否则丢弃(复用 JdLlmChatSupport)

判据:JdPublishTaskServiceTest(跨店建单落 target/mode、协议 4 白名单、同店仍 CLONE)、
JdPublishFillAiServiceTest(属性补值解析与候选过滤)、JdSchemaContractTest(V218 四列)、
FileTaskMapperChannelSqlTest(NEW 闸)、TaskClientPullServiceTest(协议闸),77 支绿;
协议等值刀已反向验证当场红并还原。后端整量 mvn -o test 5878 例/0 失败/19 skip。
This commit is contained in:
2026-11-26 11:51:26 +08:00
parent 934091b3d5
commit 1307caf5e5
16 changed files with 571 additions and 13 deletions
@@ -4,14 +4,25 @@ package com.nanri.aiimage.common.task;
public final class JdPublishProtocol { public final class JdPublishProtocol {
public static final int LEGACY = 2; public static final int LEGACY = 2;
public static final int TARGET_BRAND = 3; public static final int TARGET_BRAND = 3;
/** v4(2026-11-26):跨店上架——源店 A 采集的商品发到目标店 B,走京麦「新增商品」路径。 */
public static final int CROSS_SHOP = 4;
public static final String BRAND_FAILURE = "目标品牌校验失败:"; public static final String BRAND_FAILURE = "目标品牌校验失败:";
public static final String SOURCE_FAILURE = "本店源商品校验失败:"; public static final String SOURCE_FAILURE = "本店源商品校验失败:";
private JdPublishProtocol() { private JdPublishProtocol() {
} }
/**
* 协议能力按「最低档」判定:v4 是 v3 的超集(新增商品路径同样支持目标品牌),
* 用 {@code >=} 而不是 {@code ==},否则每次升版都要把上一档整体复制一遍。
*/
public static boolean supportsTargetBrand(Integer protocol) { public static boolean supportsTargetBrand(Integer protocol) {
return Integer.valueOf(TARGET_BRAND).equals(protocol); return protocol != null && protocol >= TARGET_BRAND;
}
/** 跨店(新增商品路径)只有 v4 及以上客户端会做,旧客户端必须被明确拒绝而不是按同店跑。 */
public static boolean supportsCrossShop(Integer protocol) {
return protocol != null && protocol >= CROSS_SHOP;
} }
public static boolean needsBrandCorrection(String message) { public static boolean needsBrandCorrection(String message) {
@@ -1,6 +1,7 @@
package com.nanri.aiimage.modules.jd.model.dto; package com.nanri.aiimage.modules.jd.model.dto;
import jakarta.validation.Valid; import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty; import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size; import jakarta.validation.constraints.Size;
@@ -49,6 +50,31 @@ public class JdPublishFillValuesRequest {
@Size(max = 200, message = "单次补值请求不能超过 200 个缺库存 SKU") @Size(max = 200, message = "单次补值请求不能超过 200 个缺库存 SKU")
private List<Integer> stockIndexes = List.of(); private List<Integer> stockIndexes = List.of();
/**
* 目标类目的必填属性缺口(2026-11-26 跨店上架「新增商品」路径)。
*
* <p>新增路径的必填属性由**目标类目**的模板下发(`productAttrComponentList` 里
* `validate[].required`),采集数据里通常没有这些属性 ⇒ 客户端把属性名与候选值一起
* 报上来,服务端让模型从候选项里挑一个(不许自造,值不在候选内整格丢弃)。</p>
*/
@Size(max = 40, message = "单次补值请求不能超过 40 个缺失属性")
@Valid
private List<MissingAttr> missingAttrs = List.of();
/** 一个缺失属性的缺口描述:名字+京麦模板下发的候选值(空=自由文本属性)。 */
@Data
public static class MissingAttr {
/** 京麦属性名(模板 `title`,如「安装方式」「材质」)。 */
@NotBlank
@Size(max = 60)
private String name;
/** 候选值(模板 `options[].label`);空列表=该属性是自由文本,模型可自行生成短语。 */
@Size(max = 200, message = "单个属性的候选值不能超过 200 个")
private List<@Size(max = 120) String> options = List.of();
}
@Data @Data
public static class SkuSummary { public static class SkuSummary {
@@ -45,6 +45,25 @@ public class JdPublishTaskCreateRequest {
/** 本次建单商品的来源店铺名(服务端回填,供失败文案与界面展示点名)。 */ /** 本次建单商品的来源店铺名(服务端回填,供失败文案与界面展示点名)。 */
private String shopName; private String shopName;
/**
* 目标店铺 ID(京麦 venderId)——2026-11-26 跨店上架:源店 A 采集的商品发到目标店 B。
*
* <p>目标店由用户端从「本机京麦当前登录店」读出后随建单下发(空=旧页面/旧客户端,
* 语义仍是同店克隆)。服务端只做形状校验与模式判定,不采信它当授权依据:
* 目标店能不能用取决于它有没有该类目的授权,那是客户端读授权树的运行时事实。</p>
*/
private String targetShopId;
/** 目标店铺名(与 {@link #targetShopId} 配对;ID 缺失时按店名核对,失败文案点名用)。 */
private String targetShopName;
/**
* 发布模式(服务端按来源店/目标店判定后回填,请求体自带值一律被覆盖):
* {@code CLONE}=同店克隆(京麦 publishType=8,带本店源 productId);
* {@code NEW}=跨店新增(京麦 publishType=1,无 productId,须目标店已授权该类目)。
*/
private String publishMode;
/** 统一改价规则:none 原价 / percent 加价百分比(value=百分数) / fixed 固定加价(value=金额)。 */ /** 统一改价规则:none 原价 / percent 加价百分比(value=百分数) / fixed 固定加价(value=金额)。 */
@Data @Data
public static class PriceRule { public static class PriceRule {
@@ -39,6 +39,14 @@ public class JdPublishItemEntity {
private String title; private String title;
/** 京麦类目路径快照(A &gt; B &gt; C)。 */ /** 京麦类目路径快照(A &gt; B &gt; C)。 */
private String categoryPath; private String categoryPath;
/** 来源店铺 venderId 快照(V218:与 shopName 配对,跨店时用来判同店/异店)。 */
private String shopId;
/** 目标店铺 venderId(V218,2026-11-26 跨店上架);NULL=旧行,按来源店克隆处理。 */
private String targetShopId;
/** 目标店铺名(V218;与目标店铺 ID 配对,失败文案点名用)。 */
private String targetShopName;
/** 发布模式(V218):CLONE 同店克隆 / NEW 跨店新增;NULL=旧行按 CLONE。 */
private String publishMode;
/** 改价快照 JSON({"mode","value","sourcePrice","finalPrice"},finalPrice=主档价按规则折算)。 */ /** 改价快照 JSON({"mode","value","sourcePrice","finalPrice"},finalPrice=主档价按规则折算)。 */
private String priceRuleJson; private String priceRuleJson;
/** 库存快照 JSON({"total":n})。 */ /** 库存快照 JSON({"total":n})。 */
@@ -30,6 +30,22 @@ public class JdPublishItemsPageVo {
/** 期望店铺名(与 shopId 配对;ID 缺失时按店名核对,失败文案点名用)。 */ /** 期望店铺名(与 shopId 配对;ID 缺失时按店名核对,失败文案点名用)。 */
private String shopName; private String shopName;
/**
* 目标店铺(2026-11-26 跨店上架):本次要发到哪家店。旧任务为空 ⇒ 客户端按
* {@link #shopName}/{@link #publishMode} 的 CLONE 语义只核对来源店。
*/
private String targetShopId;
/** 目标店铺名(与 targetShopId 配对;跨店失败文案点名用)。 */
private String targetShopName;
/**
* 发布模式:{@code CLONE}=同店克隆(publishType=8,带本店源 productId);
* {@code NEW}=跨店新增(publishType=1,无 productId,先在目标店授权树里匹配类目)。
* 空值按 CLONE 处理(旧任务)。
*/
private String publishMode;
/** 本页明细行。 */ /** 本页明细行。 */
private List<JdPublishItemPayloadVo> items; private List<JdPublishItemPayloadVo> items;
@@ -33,6 +33,9 @@ public class JdPublishFillAiService {
private static final int MAX_SKUS_PER_CALL = 200; private static final int MAX_SKUS_PER_CALL = 200;
/** 京麦标题框单行输入:超长标题整条丢弃,宁缺勿错。 */ /** 京麦标题框单行输入:超长标题整条丢弃,宁缺勿错。 */
private static final int MAX_TITLE_CHARS = 45; private static final int MAX_TITLE_CHARS = 45;
/** 必填属性单次上限(跨店新增路径,目标类目模板里的必填属性通常个位数)。 */
private static final int MAX_ATTRS_PER_CALL = 40;
private static final int MAX_ATTR_VALUE_CHARS = 120;
private static final BigDecimal MAX_PRICE = new BigDecimal("999999"); private static final BigDecimal MAX_PRICE = new BigDecimal("999999");
private static final int MAX_STOCK = 999999; private static final int MAX_STOCK = 999999;
@@ -75,7 +78,8 @@ public class JdPublishFillAiService {
static boolean hasAnyGap(JdPublishFillValuesRequest request) { static boolean hasAnyGap(JdPublishFillValuesRequest request) {
return Boolean.TRUE.equals(request.getNeedTitle()) return Boolean.TRUE.equals(request.getNeedTitle())
|| (request.getPriceIndexes() != null && !request.getPriceIndexes().isEmpty()) || (request.getPriceIndexes() != null && !request.getPriceIndexes().isEmpty())
|| (request.getStockIndexes() != null && !request.getStockIndexes().isEmpty()); || (request.getStockIndexes() != null && !request.getStockIndexes().isEmpty())
|| (request.getMissingAttrs() != null && !request.getMissingAttrs().isEmpty());
} }
static int gapCount(JdPublishFillValuesRequest request) { static int gapCount(JdPublishFillValuesRequest request) {
@@ -85,12 +89,13 @@ public class JdPublishFillAiService {
} }
count += request.getPriceIndexes() == null ? 0 : request.getPriceIndexes().size(); count += request.getPriceIndexes() == null ? 0 : request.getPriceIndexes().size();
count += request.getStockIndexes() == null ? 0 : request.getStockIndexes().size(); count += request.getStockIndexes() == null ? 0 : request.getStockIndexes().size();
count += request.getMissingAttrs() == null ? 0 : request.getMissingAttrs().size();
return count; return count;
} }
private static int filledCount(Map<String, Object> parsed) { private static int filledCount(Map<String, Object> parsed) {
int count = parsed.containsKey("title") ? 1 : 0; int count = parsed.containsKey("title") ? 1 : 0;
for (String key : List.of("prices", "stocks")) { for (String key : List.of("prices", "stocks", "attrValues")) {
if (parsed.get(key) instanceof Map<?, ?> values) { if (parsed.get(key) instanceof Map<?, ?> values) {
count += values.size(); count += values.size();
} }
@@ -131,6 +136,30 @@ public class JdPublishFillAiService {
gaps.append("SKU #").append(index).append(" 库存\n"); gaps.append("SKU #").append(index).append(" 库存\n");
} }
} }
StringBuilder attrs = new StringBuilder();
List<JdPublishFillValuesRequest.MissingAttr> missingAttrs = request.getMissingAttrs();
if (missingAttrs != null && !missingAttrs.isEmpty()) {
int limit = Math.min(missingAttrs.size(), MAX_ATTRS_PER_CALL);
for (JdPublishFillValuesRequest.MissingAttr attr : missingAttrs.subList(0, limit)) {
if (attr == null || attr.getName() == null || attr.getName().isBlank()) {
continue;
}
attrs.append("- ").append(attr.getName());
List<String> options = attr.getOptions();
if (options != null && !options.isEmpty()) {
attrs.append(",只能从这个列表里原样选一个:").append(String.join(" / ", options));
} else {
attrs.append("(自由文本,给一个简短常见值)");
}
attrs.append('\n');
gaps.append("属性「").append(attr.getName()).append("」\n");
}
}
String attrRule = attrs.isEmpty() ? ""
: "4) 商品属性:有候选列表的必须原样选列表里的一项(不得改写、不得自造),"
+ "没有候选的给一个简短常见值;"
+ "输出到 \"attrValues\",键是属性名原文。";
String attrExample = attrs.isEmpty() ? "" : ", \"attrValues\": {\"<属性名>\": \"<值>\"}";
return "你是京东商品上架助手。下面这个商品的部分必填字段在采集数据里缺失," return "你是京东商品上架助手。下面这个商品的部分必填字段在采集数据里缺失,"
+ "请根据类目与 SKU 销售属性生成合理值补齐。规则:" + "请根据类目与 SKU 销售属性生成合理值补齐。规则:"
+ "1) 标题:不超过 30 个汉字的单行文本,不带品牌名," + "1) 标题:不超过 30 个汉字的单行文本,不带品牌名,"
@@ -138,11 +167,14 @@ public class JdPublishFillAiService {
+ "2) 京东价:单位元,大于 0、最多 2 位小数,符合该类目中国电商常规定价," + "2) 京东价:单位元,大于 0、最多 2 位小数,符合该类目中国电商常规定价,"
+ "参考已有 SKU 价格保持同款一致;" + "参考已有 SKU 价格保持同款一致;"
+ "3) 库存:非负整数,常规备货量级,可参考已有 SKU 库存。" + "3) 库存:非负整数,常规备货量级,可参考已有 SKU 库存。"
+ attrRule
+ (request.getCategoryPath() == null || request.getCategoryPath().isBlank() + (request.getCategoryPath() == null || request.getCategoryPath().isBlank()
? "" : "商品类目:" + request.getCategoryPath() + "。") ? "" : "商品类目:" + request.getCategoryPath() + "。")
+ "\n只需要输出 JSON 对象,不要解释、不要 markdown 围栏,形状:" + "\n只需要输出 JSON 对象,不要解释、不要 markdown 围栏,形状:"
+ "{\"title\": \"标题\", \"prices\": {\"<SKU下标>\": 价格}, \"stocks\": {\"<SKU下标>\": 库存}}," + "{\"title\": \"标题\", \"prices\": {\"<SKU下标>\": 价格}, \"stocks\": {\"<SKU下标>\": 库存}"
+ "只包含下面点名的缺口。\nSKU 清单:\n" + skus + "需要补值的缺口:\n" + gaps; + attrExample + "},"
+ "只包含下面点名的缺口。\nSKU 清单:\n" + skus + "需要补值的缺口:\n" + gaps
+ (attrs.isEmpty() ? "" : "必填属性(按属性名取值):\n" + attrs);
} }
/** 调龙抬头 chat/completions(请求组装与响应解析收口在 {@link JdLlmChatSupport} 同一份里)。 */ /** 调龙抬头 chat/completions(请求组装与响应解析收口在 {@link JdLlmChatSupport} 同一份里)。 */
@@ -154,6 +186,10 @@ public class JdPublishFillAiService {
* 模型输出 → 归一映射:标题只收非空单行且 ≤45 字;价/库存按下标点名收,非法值 * 模型输出 → 归一映射:标题只收非空单行且 ≤45 字;价/库存按下标点名收,非法值
* (非数值、≤0、超上限、价超 2 位小数、库存非整数)整格丢弃——生成值要直接进 * (非数值、≤0、超上限、价超 2 位小数、库存非整数)整格丢弃——生成值要直接进
* 京麦输入框,宁缺勿错。未点名的下标不收。 * 京麦输入框,宁缺勿错。未点名的下标不收。
*
* <p>属性补值(2026-11-26 跨店新增路径)多一道硬闸:**值必须在京麦模板的候选项里
* 原样命中**(有候选时),否则整格丢弃——京麦下拉是枚举,自造的值填不进去,
* 悄悄放行只会让客户端在填表阶段失败、还看不出是补值给的坏值。</p>
*/ */
Map<String, Object> parseValues(String content, JdPublishFillValuesRequest request) { Map<String, Object> parseValues(String content, JdPublishFillValuesRequest request) {
Map<String, Object> out = new LinkedHashMap<>(); Map<String, Object> out = new LinkedHashMap<>();
@@ -184,6 +220,41 @@ public class JdPublishFillAiService {
if (!stocks.isEmpty()) { if (!stocks.isEmpty()) {
out.put("stocks", stocks); out.put("stocks", stocks);
} }
Map<String, String> attrValues = attrValues(root.path("attrValues"), request.getMissingAttrs());
if (!attrValues.isEmpty()) {
out.put("attrValues", attrValues);
}
return out;
}
/** 属性值只收「点名的属性名」+非空单行 ≤120 字+(有候选时)原样命中候选列表。 */
private static Map<String, String> attrValues(JsonNode node,
List<JdPublishFillValuesRequest.MissingAttr> attrs) {
Map<String, String> out = new LinkedHashMap<>();
if (node == null || !node.isObject() || attrs == null || attrs.isEmpty()) {
return out;
}
for (JdPublishFillValuesRequest.MissingAttr attr : attrs) {
if (attr == null || attr.getName() == null || attr.getName().isBlank()) {
continue;
}
JsonNode value = node.path(attr.getName());
if (!value.isTextual()) {
continue;
}
String text = value.asText().trim();
if (text.isEmpty() || text.length() > MAX_ATTR_VALUE_CHARS
|| text.indexOf('\n') >= 0 || text.indexOf('\r') >= 0) {
continue;
}
List<String> options = attr.getOptions();
if (options != null && !options.isEmpty()
&& options.stream().noneMatch(option -> option != null && option.trim().equals(text))) {
continue;
}
out.put(attr.getName(), text);
}
return out; return out;
} }
@@ -91,6 +91,14 @@ public class JdPublishTaskService {
public static final String ITEM_SUCCESS = "SUCCESS"; public static final String ITEM_SUCCESS = "SUCCESS";
public static final String ITEM_FAILED = "FAILED"; public static final String ITEM_FAILED = "FAILED";
/**
* 发布模式词表(V218 publish_mode 列,客户端按它分派两条发布链):
* {@code CLONE}=京麦「克隆本店商品」(publishType=8,带源 productId);
* {@code NEW}=京麦「新增商品」(publishType=1,无 productId,跨店的唯一可行路径)。
*/
public static final String PUBLISH_MODE_CLONE = "CLONE";
public static final String PUBLISH_MODE_NEW = "NEW";
/** 单任务商品勾选上限(防 request_json/明细行膨胀;建单口拦注定失败的输入)。 */ /** 单任务商品勾选上限(防 request_json/明细行膨胀;建单口拦注定失败的输入)。 */
private static final int MAX_PRODUCT_IDS = 500; private static final int MAX_PRODUCT_IDS = 500;
@@ -156,6 +164,10 @@ public class JdPublishTaskService {
ShopIdentity shop = resolveSingleShop(products); ShopIdentity shop = resolveSingleShop(products);
request.setShopId(shop.id()); request.setShopId(shop.id());
request.setShopName(shop.name()); request.setShopName(shop.name());
// 跨店上架(2026-11-26 客户口径「要跨店」):目标店由用户端从「本机京麦当前登录店」
// 读出后随建单下发。没给=旧语义(同店克隆,行为与 V218 之前逐字一致);给了就按
// 店铺身份判模式——同店仍走克隆(京麦带 productId 更稳),异店只能走「新增商品」。
applyTargetShop(request, shop, products);
LocalDateTime now = LocalDateTime.now(); LocalDateTime now = LocalDateTime.now();
FileTaskEntity task = new FileTaskEntity(); FileTaskEntity task = new FileTaskEntity();
@@ -233,6 +245,7 @@ public class JdPublishTaskService {
FileTaskEntity task = requireOwnedTask(taskId, userId); FileTaskEntity task = requireOwnedTask(taskId, userId);
requireAttempt(task, attempt); requireAttempt(task, attempt);
targetBrandForClient(task, protocol); targetBrandForClient(task, protocol);
publishModeForClient(task, protocol);
int updated = fileTaskMapper.update(null, new LambdaUpdateWrapper<FileTaskEntity>() int updated = fileTaskMapper.update(null, new LambdaUpdateWrapper<FileTaskEntity>()
.eq(FileTaskEntity::getId, taskId) .eq(FileTaskEntity::getId, taskId)
.eq(FileTaskEntity::getUserId, userId) .eq(FileTaskEntity::getUserId, userId)
@@ -255,6 +268,7 @@ public class JdPublishTaskService {
FileTaskEntity task = requireOwnedTask(taskId, userId); FileTaskEntity task = requireOwnedTask(taskId, userId);
requireAttempt(task, attempt); requireAttempt(task, attempt);
String targetBrand = targetBrandForClient(task, protocol); String targetBrand = targetBrandForClient(task, protocol);
publishModeForClient(task, protocol);
if (!STATUS_RUNNING.equals(task.getStatus())) { if (!STATUS_RUNNING.equals(task.getStatus())) {
throw new BusinessException(409, "任务未在运行,不能下发发布明细"); throw new BusinessException(409, "任务未在运行,不能下发发布明细");
} }
@@ -280,6 +294,15 @@ public class JdPublishTaskService {
expectedShopName = trimToNull(rows.get(0).getShopName()); expectedShopName = trimToNull(rows.get(0).getShopName());
} }
vo.setShopName(expectedShopName); vo.setShopName(expectedShopName);
// 目标店与发布模式(2026-11-26):旧任务两项都缺 ⇒ 目标店回落来源店、模式 CLONE,
// 客户端按 v3 语义只核对来源店(逐字不变);NEW 档客户端改核对目标店。
String targetShopName = targetShopNameOf(create);
if (targetShopName == null && !rows.isEmpty()) {
targetShopName = trimToNull(rows.get(0).getShopName());
}
vo.setTargetShopId(targetShopIdOf(create));
vo.setTargetShopName(targetShopName);
vo.setPublishMode(publishModeOf(create));
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());
@@ -339,6 +362,15 @@ public class JdPublishTaskService {
if (trimToNull(create.getShopName()) != null) { if (trimToNull(create.getShopName()) != null) {
data.put("shopName", create.getShopName().strip()); data.put("shopName", create.getShopName().strip());
} }
// 目标店与发布模式随载荷下发:建单推送这条路不必先拉明细,客户端也能立刻
// 决定核对哪家店、走克隆还是新增(2026-11-26 跨店上架)。
if (targetShopIdOf(create) != null) {
data.put("targetShopId", targetShopIdOf(create));
}
if (targetShopNameOf(create) != null) {
data.put("targetShopName", targetShopNameOf(create));
}
data.put("publishMode", publishModeOf(create));
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);
} }
@@ -484,6 +516,56 @@ public class JdPublishTaskService {
return trimmed.isEmpty() ? null : trimmed; return trimmed.isEmpty() ? null : trimmed;
} }
/**
* 目标店与发布模式归一化写回请求体(铁律 27a 同源:request_json 里存的就是闸门认可的值)。
*
* <p>三档:① 请求没带目标店 ⇒ 旧语义,目标店=来源店、模式 CLONE(V218 之前建的任务
* 与老页面提交逐字不变,客户端仍按来源店核对);② 带的店铺与来源店同一家 ⇒ CLONE
* (有 venderId 按 ID 比,只剩店名的按店名比——同一家店的两种形状);③ 异店 ⇒ NEW,
* 且勾选商品必须有类目路径:新增路径靠末级类目名在目标店授权树里定位 {@code cateList},
* 没有类目路径的商品必然行级失败,建单即点名拒绝(脏输入不进任务)。</p>
*/
private static void applyTargetShop(JdPublishTaskCreateRequest request, ShopIdentity source,
List<JdProductEntity> products) {
String targetId = requireShopToken(request.getTargetShopId(), 128, "目标店铺 ID");
String targetName = requireShopToken(request.getTargetShopName(), 255, "目标店铺名");
request.setTargetShopId(targetId);
request.setTargetShopName(targetName);
if (targetId == null && targetName == null) {
request.setTargetShopId(source.id());
request.setTargetShopName(source.name());
request.setPublishMode(PUBLISH_MODE_CLONE);
return;
}
boolean sameShop = targetId != null && source.id() != null
? targetId.equals(source.id())
: targetName != null && source.name() != null && targetName.equals(source.name());
if (sameShop) {
request.setPublishMode(PUBLISH_MODE_CLONE);
return;
}
long missingCategory = products.stream()
.filter(product -> trimToNull(product.getCategoryPath()) == null)
.count();
if (missingCategory > 0) {
throw new BusinessException(400, "跨店上架需要商品类目路径:勾选里有 " + missingCategory
+ " 个商品没有类目信息,无法在目标店匹配类目,请重新采集后再上架");
}
request.setPublishMode(PUBLISH_MODE_NEW);
}
/** 店铺标识列的形状校验(空串按缺省;超长/控制字符当场 400 点名)。 */
private static String requireShopToken(String value, int maxLength, String label) {
String token = trimToNull(value);
if (token == null) {
return null;
}
if (token.length() > maxLength || token.codePoints().anyMatch(Character::isISOControl)) {
throw new BusinessException(400, label + "须为不超过 " + maxLength + " 个字符的单行文本");
}
return token;
}
private String writeCreateRequest(JdPublishTaskCreateRequest request) { private String writeCreateRequest(JdPublishTaskCreateRequest request) {
try { try {
return objectMapper.writeValueAsString(request); return objectMapper.writeValueAsString(request);
@@ -500,6 +582,35 @@ public class JdPublishTaskService {
return brand; return brand;
} }
/**
* 发布模式与协议闸:跨店任务(NEW)只能交给 v4 及以上客户端——旧客户端没有「新增商品」
* 路径,会按同店克隆去撞来源店 productId,白跑一轮还留个假失败。同店(CLONE)不限协议。
*/
private String publishModeForClient(FileTaskEntity task, Integer protocol) {
String mode = publishModeOf(readCreateRequest(task));
if (PUBLISH_MODE_NEW.equals(mode) && !JdPublishProtocol.supportsCrossShop(protocol)) {
throw new BusinessException(409, "请升级数富客户端后再执行跨店上架任务");
}
return mode;
}
/** 目标店(下发口径):V218 之前建的任务没有这两个键 ⇒ 回落来源店(同店语义逐字不变)。 */
static String targetShopIdOf(JdPublishTaskCreateRequest create) {
String id = trimToNull(create.getTargetShopId());
return id != null ? id : trimToNull(create.getShopId());
}
static String targetShopNameOf(JdPublishTaskCreateRequest create) {
String name = trimToNull(create.getTargetShopName());
return name != null ? name : trimToNull(create.getShopName());
}
/** 发布模式:空/未知值=旧任务按克隆处理(与 V218 之前的行为一致,不猜新路径)。 */
static String publishModeOf(JdPublishTaskCreateRequest create) {
String mode = trimToNull(create.getPublishMode());
return PUBLISH_MODE_NEW.equalsIgnoreCase(mode) ? PUBLISH_MODE_NEW : PUBLISH_MODE_CLONE;
}
/** 与发布回执锁同一条父任务,品牌修正和换代必须一起提交。 */ /** 与发布回执锁同一条父任务,品牌修正和换代必须一起提交。 */
@Transactional @Transactional
public JdPublishTaskVo retryWithBrand(Long taskId, Long userId, int attempt, String rawBrand) { public JdPublishTaskVo retryWithBrand(Long taskId, Long userId, int attempt, String rawBrand) {
@@ -596,6 +707,12 @@ public class JdPublishTaskService {
item.setProductId(product.getId()); item.setProductId(product.getId());
item.setProductCode(product.getProductCode()); item.setProductCode(product.getProductCode());
item.setShopName(product.getShopName()); item.setShopName(product.getShopName());
item.setShopId(trimToNull(product.getShopId()));
// 目标店/模式随行快照(V218):断点续跑与失败重试按行读得到「发到哪家店、走哪条路径」,
// 不依赖任务载荷还能被解析(载荷是任务级,行级留档才是溯源正本)。
item.setTargetShopId(trimToNull(request.getTargetShopId()));
item.setTargetShopName(trimToNull(request.getTargetShopName()));
item.setPublishMode(publishModeOf(request));
item.setTitle(product.getTitle()); item.setTitle(product.getTitle());
item.setCategoryPath(product.getCategoryPath()); item.setCategoryPath(product.getCategoryPath());
PriceRule rule = request.getPriceRule(); PriceRule rule = request.getPriceRule();
@@ -45,7 +45,8 @@ public interface FileTaskMapper extends BaseMapper<FileTaskEntity> {
@Param("localDefaultModules") List<String> localDefaultModules, @Param("localDefaultModules") List<String> localDefaultModules,
@Param("cutoff") LocalDateTime cutoff, @Param("cutoff") LocalDateTime cutoff,
@Param("limit") int limit, @Param("limit") int limit,
@Param("supportsTargetBrand") boolean supportsTargetBrand); @Param("supportsTargetBrand") boolean supportsTargetBrand,
@Param("supportsCrossShop") boolean supportsCrossShop);
/** /**
* 服务端内部认领候选(Linux 后台 worker):指定状态 + 白名单模块 + 创建早于 cutoff, * 服务端内部认领候选(Linux 后台 worker):指定状态 + 白名单模块 + 创建早于 cutoff,
@@ -141,6 +141,7 @@ public class TaskClientPullService {
} }
List<String> types = resolveModuleTypes(); List<String> types = resolveModuleTypes();
boolean supportsTargetBrand = JdPublishProtocol.supportsTargetBrand(jdPublishProtocol); boolean supportsTargetBrand = JdPublishProtocol.supportsTargetBrand(jdPublishProtocol);
boolean supportsCrossShop = JdPublishProtocol.supportsCrossShop(jdPublishProtocol);
if (!supportsTargetBrand && !Integer.valueOf(JdPublishProtocol.LEGACY).equals(jdPublishProtocol)) { if (!supportsTargetBrand && !Integer.valueOf(JdPublishProtocol.LEGACY).equals(jdPublishProtocol)) {
types = withoutJdPublish(types); types = withoutJdPublish(types);
} }
@@ -155,7 +156,8 @@ public class TaskClientPullService {
LocalDateTime cutoff = LocalDateTime.now(DB_ZONE).minusMinutes(Math.max(1L, minPendingMinutes)); LocalDateTime cutoff = LocalDateTime.now(DB_ZONE).minusMinutes(Math.max(1L, minPendingMinutes));
int safeLimit = Math.max(1, Math.min(limit, MAX_LIMIT)); int safeLimit = Math.max(1, Math.min(limit, MAX_LIMIT));
List<FileTaskEntity> candidates = fileTaskMapper.selectLocalChannelPendingTasks( List<FileTaskEntity> candidates = fileTaskMapper.selectLocalChannelPendingTasks(
userId, STATUS_PENDING, types, CollectChannel.localDefaultModuleTypes(), cutoff, safeLimit, supportsTargetBrand); userId, STATUS_PENDING, types, CollectChannel.localDefaultModuleTypes(), cutoff, safeLimit,
supportsTargetBrand, supportsCrossShop);
if (candidates.isEmpty() && !types.isEmpty()) { if (candidates.isEmpty() && !types.isEmpty()) {
log.info("[client-task-pull] 白名单内没有本机通道的排队任务,本次不拉取 userId={} moduleTypes={}", log.info("[client-task-pull] 白名单内没有本机通道的排队任务,本次不拉取 userId={} moduleTypes={}",
userId, moduleTypes); userId, moduleTypes);
@@ -0,0 +1,31 @@
-- 迁移 V218:发布明细表加「来源店 ID / 目标店 / 发布模式」三列(2026-11-26 跨店上架)。
-- =============================================================
-- 1. 号段协调:V217=users_normal_quota_reset(934091b3)已占用,本窗取 V218;
-- 契约正则 V208~V229(JdPublishContractPendingTest)天然覆盖。
--
-- 2. 业务背景:客户要「源店 A 采集的商品 → 目标店 B 上架」(跨店)。京麦两条发布路径:
-- 同店克隆 publishType=8(必须带本店源 productId)/ 新增商品 publishType=1(无 productId)。
-- 跨店的唯一可行路径是新增商品 ⇒ 明细行要记「这次发到哪家店、走哪条路径」,
-- 否则断点续跑与失败重试无法区分配置,运营也无法从一个任务看出目标店。
--
-- 3. 列口径:
-- * shop_id 来源店铺 venderId(V210 只有 shop_name,同店/异店判定需要 ID 对撞);
-- * target_shop_id 目标店铺 venderId;target_shop_name 目标店铺名(失败文案点名用);
-- * publish_mode CLONE=同店克隆 / NEW=跨店新增;NULL 一律按 CLONE(旧任务语义)。
-- 存量行三列全 NULL(来源店 ID 不猜;目标店=来源店;模式=克隆),与上线前逐字一致。
--
-- 4. 可重跑性:plain ALTER(V207/V216 同形先例),Flyway 按版本记账只执行一次。
-- 应用侧:MigrationInventoryTest 自动清点;JdSchemaContractTest 钉 V218 列。
--
-- 5. 回滚(patch,不当期执行):
-- ALTER TABLE biz_jd_publish_item
-- DROP COLUMN shop_id, DROP COLUMN target_shop_id,
-- DROP COLUMN target_shop_name, DROP COLUMN publish_mode;
-- DELETE FROM flyway_schema_history WHERE version='218';
-- =============================================================
ALTER TABLE `biz_jd_publish_item`
ADD COLUMN `shop_id` VARCHAR(128) NULL COMMENT '来源店铺 venderId 快照(跨店同/异店判定用)' AFTER `shop_name`,
ADD COLUMN `target_shop_id` VARCHAR(128) NULL COMMENT '目标店铺 venderId(NULL=旧行,按来源店克隆)' AFTER `shop_id`,
ADD COLUMN `target_shop_name` VARCHAR(255) NULL COMMENT '目标店铺名(失败文案点名用)' AFTER `target_shop_id`,
ADD COLUMN `publish_mode` VARCHAR(16) NULL COMMENT 'CLONE 同店克隆 / NEW 跨店新增(NULL=CLONE)' AFTER `target_shop_name`;
@@ -42,6 +42,12 @@
AND (module_type != 'JD_PUBLISH' AND (module_type != 'JD_PUBLISH'
OR COALESCE(JSON_TYPE(JSON_EXTRACT(request_json, '$.targetBrandName')), 'NULL') = 'NULL') OR COALESCE(JSON_TYPE(JSON_EXTRACT(request_json, '$.targetBrandName')), 'NULL') = 'NULL')
</if> </if>
<!-- 跨店上架(2026-11-26):NEW 模式只有 v4 客户端会做(京麦「新增商品」路径)。旧客户端领了
也只会按同店克隆去撞来源店 productId,白跑一轮还留个假失败 ⇒ 不投递,等升级后自然领到。 -->
<if test="supportsCrossShop == false">
AND (module_type != 'JD_PUBLISH'
OR COALESCE(JSON_UNQUOTE(JSON_EXTRACT(request_json, '$.publishMode')), '') != 'NEW')
</if>
ORDER BY created_at ASC ORDER BY created_at ASC
LIMIT #{limit} LIMIT #{limit}
</select> </select>
@@ -178,6 +178,25 @@ class JdSchemaContractTest {
assertTrue(reset.contains("`jd_publish_quota` = 5000"), "只清默认值 5000,重跑幂等"); assertTrue(reset.contains("`jd_publish_quota` = 5000"), "只清默认值 5000,重跑幂等");
} }
@Test
void V218_跨店上架的目标店与发布模式列() {
// 2026-11-26 跨店上架:明细行要记「发到哪家店、走哪条路径」,否则断点续跑/重试
// 无法区分同店克隆(publishType=8)与新增商品(publishType=1)。
String sql = read(DB_DIR.resolve("V218__jd_publish_item_target_shop.sql"));
assertTrue(sql.contains("迁移 V218"), "头注释必须是 `-- 迁移 V218…`(MigrationInventoryTest 口径)");
assertTrue(sql.contains("biz_jd_publish_item"), "必须落在发布明细表");
assertTrue(linesContaining(sql, "`shop_id`").stream().anyMatch(line -> line.contains("VARCHAR(128)")),
"shop_id 必须是 VARCHAR(128):V210 只有 shop_name,同店/异店判定要 ID 对撞");
assertTrue(linesContaining(sql, "`target_shop_id`").stream().anyMatch(line -> line.contains("VARCHAR(128)")),
"target_shop_id 缺失:跨店任务看不出目标店");
assertTrue(linesContaining(sql, "`target_shop_name`").stream().anyMatch(line -> line.contains("VARCHAR(255)")),
"target_shop_name 缺失:失败文案点名不了目标店");
assertTrue(linesContaining(sql, "`publish_mode`").stream().anyMatch(line -> line.contains("VARCHAR(16)")),
"publish_mode 缺失:客户端无法分派克隆/新增两条链");
// 四列全可空:NULL=旧行,按来源店克隆处理(上线前建的任务行为逐字不变,不猜历史)。
assertTrue(linesContaining(sql, "NULL").size() >= 4, "四列必须允许 NULL(旧行语义=CLONE)");
}
@Test @Test
void V214_分类店铺名单_同分类唯一键形状() { void V214_分类店铺名单_同分类唯一键形状() {
String sql = read(DB_DIR.resolve("V214__jd_group_shop.sql")); String sql = read(DB_DIR.resolve("V214__jd_group_shop.sql"));
@@ -170,8 +170,72 @@ class JdPublishFillAiServiceTest {
assertThat(service.generate(null, request(true, List.of(), List.of()))).isEmpty(); assertThat(service.generate(null, request(true, List.of(), List.of()))).isEmpty();
assertThat(service.generate(1L, null)).isEmpty(); assertThat(service.generate(1L, null)).isEmpty();
// 无缺口(needTitle 未点名、价/库下标都空)直接空映射,连密钥都不查。 // 无缺口(needTitle 未点名、价/库下标都空、无缺失属性)直接空映射,连密钥都不查。
assertThat(service.generate(1L, request(false, List.of(), List.of()))).isEmpty(); assertThat(service.generate(1L, request(false, List.of(), List.of()))).isEmpty();
verify(secretService, never()).findLongtaitouPlainValue(any()); verify(secretService, never()).findLongtaitouPlainValue(any());
} }
// ---- 必填属性补值(2026-11-26 跨店「新增商品」路径:属性由目标类目模板下发)----
private static JdPublishFillValuesRequest.MissingAttr attr(String name, List<String> options) {
JdPublishFillValuesRequest.MissingAttr attr = new JdPublishFillValuesRequest.MissingAttr();
attr.setName(name);
attr.setOptions(options);
return attr;
}
private static JdPublishFillValuesRequest attrRequest(JdPublishFillValuesRequest.MissingAttr... attrs) {
JdPublishFillValuesRequest request = request(false, List.of(), List.of());
request.setMissingAttrs(List.of(attrs));
return request;
}
@Test
void 属性补值必须命中京麦候选项() {
var attrs = attrRequest(
attr("安装方式", List.of("螺钉壁挂式", "免打孔粘贴")),
attr("材质", List.of("塑料", "不锈钢")));
Map<String, Object> values = service.parseValues(
"{\"attrValues\": {\"安装方式\": \"免打孔粘贴\", \"材质\": \"铝合金自造\"}}", attrs);
assertThat(values.get("attrValues"))
.as("候选内原样命中才收;自造值填不进京麦下拉,整格丢弃(客户端按缺属性失败并点名)")
.isEqualTo(Map.of("安装方式", "免打孔粘贴"));
}
@Test
void 自由文本属性可生成短语且未点名的属性不收() {
var attrs = attrRequest(attr("安装方式", List.of()));
Map<String, Object> values = service.parseValues(
"{\"attrValues\": {\"安装方式\": \" 壁挂 \", \"品牌\": \"自造\"}}", attrs);
assertThat(values.get("attrValues")).isEqualTo(Map.of("安装方式", "壁挂"));
}
@Test
void 属性值空串换行超长一律丢弃() {
var attrs = attrRequest(attr("安装方式", List.of()), attr("材质", List.of()), attr("款式", List.of()));
assertThat(service.parseValues("{\"attrValues\": {\"安装方式\": \" \"}}", attrs))
.doesNotContainKey("attrValues");
assertThat(service.parseValues("{\"attrValues\": {\"材质\": \"第一行\\n第二行\"}}", attrs))
.doesNotContainKey("attrValues");
assertThat(service.parseValues("{\"attrValues\": {\"款式\": \"" + "好".repeat(121) + "\"}}", attrs))
.doesNotContainKey("attrValues");
}
@Test
void 只有属性缺口也算缺口并进prompt() {
var attrs = attrRequest(attr("安装方式", List.of("螺钉壁挂式", "免打孔粘贴")));
assertThat(JdPublishFillAiService.hasAnyGap(attrs)).isTrue();
assertThat(JdPublishFillAiService.gapCount(attrs)).isEqualTo(1);
assertThat(service.buildPrompt(attrs))
.contains("属性「安装方式」")
.contains("螺钉壁挂式 / 免打孔粘贴")
.contains("attrValues")
.contains("原样选列表里的一项");
}
} }
@@ -582,4 +582,153 @@ class JdPublishTaskServiceTest {
.as("只带店名的行按同名归一到同一家店的 venderId") .as("只带店名的行按同名归一到同一家店的 venderId")
.contains("228346061"); .contains("228346061");
} }
// ---- 跨店上架(2026-11-26 客户口径「要跨店」:源店 A 采集 → 目标店 B 新增商品)----
/** 来源店固定家居日用数据库店(228346061),目标店固定服装数据库店(21248199)。 */
private void stubCrossShopProducts() {
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));
stubVisibleGroups(7L, 2L, 11L);
stubAssign(11L, 101L, 102L);
}
private JdPublishTaskCreateRequest crossRequest() {
JdPublishTaskCreateRequest request = validRequest(7L);
request.setTargetShopId(" 21248199 ");
request.setTargetShopName("服装数据库店");
return request;
}
@Test
void 跨店建单落目标店与NEW模式() {
when(adminUserMapper.selectById(7L)).thenReturn(new AdminUserEntity());
stubCrossShopProducts();
when(fileTaskMapper.insert(any(FileTaskEntity.class))).thenAnswer(invocation -> {
invocation.getArgument(0, FileTaskEntity.class).setId(34420L);
return 1;
});
when(jdPublishItemMapper.insert(any(JdPublishItemEntity.class))).thenReturn(1);
ArgumentCaptor<JdPublishItemEntity> itemCaptor = ArgumentCaptor.forClass(JdPublishItemEntity.class);
JdPublishTaskVo vo = service.createTask(crossRequest(), null);
ArgumentCaptor<FileTaskEntity> taskCaptor = ArgumentCaptor.forClass(FileTaskEntity.class);
verify(fileTaskMapper).insert(taskCaptor.capture());
String requestJson = taskCaptor.getValue().getRequestJson();
assertThat(requestJson)
.as("来源店仍按勾选商品回填,目标店按请求归一(含 strip),模式服务端判定")
.contains("\"shopId\":\"228346061\"")
.contains("\"targetShopId\":\"21248199\"")
.contains("\"targetShopName\":\"服装数据库店\"")
.contains("\"publishMode\":\"NEW\"");
assertThat(String.valueOf(vo.getQueuePayload()))
.as("页面直推载荷也要带目标店与模式:建单推送这条路不必先拉明细")
.contains("21248199").contains("服装数据库店").contains("NEW");
verify(jdPublishItemMapper, org.mockito.Mockito.times(2)).insert(itemCaptor.capture());
assertThat(itemCaptor.getAllValues()).allSatisfy(item -> {
assertThat(item.getShopId()).isEqualTo("228346061");
assertThat(item.getTargetShopId()).isEqualTo("21248199");
assertThat(item.getTargetShopName()).isEqualTo("服装数据库店");
assertThat(item.getPublishMode()).isEqualTo("NEW");
});
}
@Test
void 目标店与来源店同ID仍走克隆() {
when(adminUserMapper.selectById(7L)).thenReturn(new AdminUserEntity());
stubCrossShopProducts();
when(fileTaskMapper.insert(any(FileTaskEntity.class))).thenAnswer(invocation -> {
invocation.getArgument(0, FileTaskEntity.class).setId(34421L);
return 1;
});
when(jdPublishItemMapper.insert(any(JdPublishItemEntity.class))).thenReturn(1);
JdPublishTaskCreateRequest request = crossRequest();
request.setTargetShopId("228346061");
request.setTargetShopName("家居日用数据库店");
service.createTask(request, null);
ArgumentCaptor<FileTaskEntity> taskCaptor = ArgumentCaptor.forClass(FileTaskEntity.class);
verify(fileTaskMapper).insert(taskCaptor.capture());
assertThat(taskCaptor.getValue().getRequestJson())
.as("同一家店走克隆路径(京麦 publishType=8 带源 productId 更稳),不当跨店")
.contains("\"publishMode\":\"CLONE\"");
}
@Test
void 不带目标店按旧语义克隆且目标店回落来源店() {
when(adminUserMapper.selectById(7L)).thenReturn(new AdminUserEntity());
stubCrossShopProducts();
when(fileTaskMapper.insert(any(FileTaskEntity.class))).thenAnswer(invocation -> {
invocation.getArgument(0, FileTaskEntity.class).setId(34422L);
return 1;
});
when(jdPublishItemMapper.insert(any(JdPublishItemEntity.class))).thenReturn(1);
service.createTask(validRequest(7L), null);
ArgumentCaptor<FileTaskEntity> taskCaptor = ArgumentCaptor.forClass(FileTaskEntity.class);
verify(fileTaskMapper).insert(taskCaptor.capture());
assertThat(taskCaptor.getValue().getRequestJson())
.as("旧页面/旧客户端不带目标店:目标店=来源店、模式 CLONE,行为与 V218 之前逐字一致")
.contains("\"publishMode\":\"CLONE\"")
.contains("\"targetShopId\":\"228346061\"");
}
@Test
void 跨店商品缺类目路径建单被拒并点名() {
when(adminUserMapper.selectById(7L)).thenReturn(new AdminUserEntity());
JdProductEntity noCategory = product(101L, 7L, "收纳盒A");
noCategory.setShopId("228346061");
noCategory.setShopName("家居日用数据库店");
noCategory.setCategoryPath(null);
JdProductEntity ok = product(102L, 7L, "收纳盒B");
ok.setShopId("228346061");
ok.setShopName("家居日用数据库店");
when(jdProductMapper.selectBatchIds(List.of(101L, 102L))).thenReturn(List.of(noCategory, ok));
stubVisibleGroups(7L, 2L, 11L);
stubAssign(11L, 101L, 102L);
assertThatThrownBy(() -> service.createTask(crossRequest(), null))
.isInstanceOf(BusinessException.class)
.hasMessageContaining("类目")
.hasMessageContaining("1 个");
verify(fileTaskMapper, never()).insert(any(FileTaskEntity.class));
}
@Test
void 跨店任务旧版协议不激活也不下发明细() {
FileTaskEntity task = new FileTaskEntity();
task.setModuleType("JD_PUBLISH");
task.setUserId(7L);
task.setResumeAttempt(0);
task.setRequestJson("{\"productIds\":[101],\"targetBrandName\":\"品牌B\","
+ "\"shopId\":\"228346061\",\"shopName\":\"家居日用数据库店\","
+ "\"targetShopId\":\"21248199\",\"targetShopName\":\"服装数据库店\","
+ "\"publishMode\":\"NEW\"}");
when(fileTaskMapper.selectById(34430L)).thenReturn(task);
assertThatThrownBy(() -> service.activateTask(34430L, 7L, 0, 3))
.as("v3 客户端没有新增商品路径,领了只会按同店克隆白跑一轮")
.isInstanceOf(BusinessException.class).hasMessageContaining("跨店");
task.setStatus("RUNNING");
assertThatThrownBy(() -> service.pullItems(34430L, 7L, 0, 0L, null, 3))
.isInstanceOf(BusinessException.class).hasMessageContaining("跨店");
// v4 起同一条任务正常下发,明细带目标店与模式(客户端据此核对目标店、走新路径)
when(jdPublishItemMapper.selectPublishableItems(34430L, 0L, 20)).thenReturn(List.of());
when(jdPublishItemMapper.countByPublishStatus(34430L)).thenReturn(List.of());
var page = service.pullItems(34430L, 7L, 0, 0L, null, 4);
assertThat(page.getPublishMode()).isEqualTo("NEW");
assertThat(page.getTargetShopId()).isEqualTo("21248199");
assertThat(page.getTargetShopName()).isEqualTo("服装数据库店");
assertThat(page.getShopId()).as("来源店仍在,客户端失败文案要同时点名两边").isEqualTo("228346061");
}
} }
@@ -92,6 +92,20 @@ class FileTaskMapperChannelSqlTest {
assertFalse(render("selectLocalChannelPendingTasks", clientParams(2)).contains("JSON_EXTRACT")); assertFalse(render("selectLocalChannelPendingTasks", clientParams(2)).contains("JSON_EXTRACT"));
} }
@Test
void 旧版客户端不投递跨店新增任务() throws Exception {
// 2026-11-26 跨店上架:NEW 模式只有 v4 客户端能执行(京麦新增商品路径),旧客户端领了
// 只会按同店克隆去撞来源店 productId ⇒ 白跑一轮 + 假失败。与品牌档同一形状:在 SQL 里、
// 在 LIMIT 之前排除,升级后同一行自然被领到(不写状态、不丢任务)。
var params = new java.util.HashMap<>(clientParams(2));
params.put("supportsCrossShop", false);
String sql = render("selectLocalChannelPendingTasks", params);
int predicate = sql.indexOf("JSON_EXTRACT(request_json, '$.publishMode')");
assertTrue(predicate > 0 && predicate < sql.indexOf("LIMIT ?"), sql);
assertFalse(render("selectLocalChannelPendingTasks", clientParams(2)).contains("publishMode"),
"v4 客户端(能力位为 true)不该被这条谓词过滤");
}
@Test @Test
void 取页只投影认领所需的窄列和代次() throws Exception { void 取页只投影认领所需的窄列和代次() throws Exception {
String sql = render("selectLocalChannelPendingTasks", clientParams(2)); String sql = render("selectLocalChannelPendingTasks", clientParams(2));
@@ -96,7 +96,7 @@ class TaskClientPullServiceTest {
// 这里钉「调用的是哪条具名查询、传了什么」,两者合起来才挡住 P1-1 复发。 // 这里钉「调用的是哪条具名查询、传了什么」,两者合起来才挡住 P1-1 复发。
verify(fileTaskMapper).selectLocalChannelPendingTasks(eq(USER_ID), eq("PENDING"), verify(fileTaskMapper).selectLocalChannelPendingTasks(eq(USER_ID), eq("PENDING"),
eq(List.of("SIMILAR_ASIN", "COLLECT_DATA")), eq(CollectChannel.localDefaultModuleTypes()), eq(List.of("SIMILAR_ASIN", "COLLECT_DATA")), eq(CollectChannel.localDefaultModuleTypes()),
any(LocalDateTime.class), eq(5), eq(false)); any(LocalDateTime.class), eq(5), eq(false), eq(false));
} }
@Test @Test
@@ -106,13 +106,17 @@ class TaskClientPullServiceTest {
service.pullPendingTasks(USER_ID); service.pullPendingTasks(USER_ID);
service.pullPendingTasks(USER_ID, 2); service.pullPendingTasks(USER_ID, 2);
service.pullPendingTasks(USER_ID, 3); service.pullPendingTasks(USER_ID, 3);
service.pullPendingTasks(USER_ID, 4);
verify(fileTaskMapper).selectLocalChannelPendingTasks(eq(USER_ID), eq("PENDING"), verify(fileTaskMapper).selectLocalChannelPendingTasks(eq(USER_ID), eq("PENDING"),
eq(List.of("SIMILAR_ASIN")), eq(CollectChannel.localDefaultModuleTypes()), any(), eq(5), eq(false)); eq(List.of("SIMILAR_ASIN")), eq(CollectChannel.localDefaultModuleTypes()), any(), eq(5), eq(false), eq(false));
verify(fileTaskMapper).selectLocalChannelPendingTasks(eq(USER_ID), eq("PENDING"), verify(fileTaskMapper).selectLocalChannelPendingTasks(eq(USER_ID), eq("PENDING"),
eq(List.of("JD_PUBLISH", "SIMILAR_ASIN")), eq(CollectChannel.localDefaultModuleTypes()), any(), eq(5), eq(false)); eq(List.of("JD_PUBLISH", "SIMILAR_ASIN")), eq(CollectChannel.localDefaultModuleTypes()), any(), eq(5), eq(false), eq(false));
verify(fileTaskMapper).selectLocalChannelPendingTasks(eq(USER_ID), eq("PENDING"), verify(fileTaskMapper).selectLocalChannelPendingTasks(eq(USER_ID), eq("PENDING"),
eq(List.of("JD_PUBLISH", "SIMILAR_ASIN")), eq(CollectChannel.localDefaultModuleTypes()), any(), eq(5), eq(true)); eq(List.of("JD_PUBLISH", "SIMILAR_ASIN")), eq(CollectChannel.localDefaultModuleTypes()), any(), eq(5), eq(true), eq(false));
// v4(2026-11-26 跨店上架):品牌档是它的子集(>= 判定),跨店档单独放开 NEW 行投递。
verify(fileTaskMapper).selectLocalChannelPendingTasks(eq(USER_ID), eq("PENDING"),
eq(List.of("JD_PUBLISH", "SIMILAR_ASIN")), eq(CollectChannel.localDefaultModuleTypes()), any(), eq(5), eq(true), eq(true));
} }
@Test @Test
@@ -328,7 +332,7 @@ class TaskClientPullServiceTest {
private void stubPullCandidates(FileTaskEntity... rows) { private void stubPullCandidates(FileTaskEntity... rows) {
when(fileTaskMapper.selectLocalChannelPendingTasks(any(), any(), any(), any(), any(), anyInt(), when(fileTaskMapper.selectLocalChannelPendingTasks(any(), any(), any(), any(), any(), anyInt(),
org.mockito.ArgumentMatchers.anyBoolean())) org.mockito.ArgumentMatchers.anyBoolean(), org.mockito.ArgumentMatchers.anyBoolean()))
.thenReturn(List.of(rows)); .thenReturn(List.of(rows));
} }