feat(jd): 上架必填参数 AI 补值服务端——/api/jd-publish/fill-values(2026-11-21 拍板「必填项一定要填,采集没有的用 AI 生成」)

- JdPublishFillAiService:标题/SKU 京东价/库存三档缺口生成,与尺码表补值同族;龙抬头密钥不出服务端,取钥走 UserApiSecretService.findLongtaitouPlainValue 单一出口(外观专利→货源查询模块顺序);无密钥/上游故障返回空映射不抛错,客户端按原缺失真实原因拒绝该行
- JdPublishController /fill-values 端点:会话归属校验同族,生成的值不落库
- JdSizeChartAiService:取钥改委托同一单一出口(消除逐字重复的第二份模块顺序)
- 判据:JdPublishFillAiServiceTest 177 行钉缺口三档/平移继承不进请求/200 SKU 截断;JdSizeChartAiServiceTest 取钥委托化
This commit is contained in:
2026-11-23 08:24:19 +08:00
parent a51f94c2cb
commit 7aa87bd06a
6 changed files with 578 additions and 34 deletions
@@ -4,6 +4,7 @@ import com.nanri.aiimage.common.api.ApiResponse;
import com.nanri.aiimage.common.api.PageDefaults; import com.nanri.aiimage.common.api.PageDefaults;
import com.nanri.aiimage.common.security.AdminAuthSupport; import com.nanri.aiimage.common.security.AdminAuthSupport;
import com.nanri.aiimage.modules.jd.model.dto.JdPublishChunkRequest; import com.nanri.aiimage.modules.jd.model.dto.JdPublishChunkRequest;
import com.nanri.aiimage.modules.jd.model.dto.JdPublishFillValuesRequest;
import com.nanri.aiimage.modules.jd.model.dto.JdPublishTaskBatchRequest; import com.nanri.aiimage.modules.jd.model.dto.JdPublishTaskBatchRequest;
import com.nanri.aiimage.modules.jd.model.dto.JdPublishTaskCreateRequest; import com.nanri.aiimage.modules.jd.model.dto.JdPublishTaskCreateRequest;
import com.nanri.aiimage.modules.jd.model.dto.JdSizeChartValuesRequest; import com.nanri.aiimage.modules.jd.model.dto.JdSizeChartValuesRequest;
@@ -17,6 +18,7 @@ import com.nanri.aiimage.modules.jd.model.vo.JdPublishTaskBatchVo;
import com.nanri.aiimage.modules.jd.model.vo.JdPublishTaskVo; import com.nanri.aiimage.modules.jd.model.vo.JdPublishTaskVo;
import com.nanri.aiimage.modules.jd.service.JdProductQueryService; 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.JdPublishIngestService; import com.nanri.aiimage.modules.jd.service.JdPublishIngestService;
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;
@@ -65,6 +67,7 @@ public class JdPublishController {
private final TaskProgressOwnershipSupport progressOwnershipSupport; private final TaskProgressOwnershipSupport progressOwnershipSupport;
private final AdminAuthSupport adminAuthSupport; private final AdminAuthSupport adminAuthSupport;
private final JdSizeChartAiService sizeChartAiService; private final JdSizeChartAiService sizeChartAiService;
private final JdPublishFillAiService fillAiService;
@PostMapping({"/tasks", "/tasks/target-brand"}) @PostMapping({"/tasks", "/tasks/target-brand"})
@Operation(summary = "创建京东商品上架任务", description = "勾选京东数据库商品(归属校验)+可选统一改价规则建单;" @Operation(summary = "创建京东商品上架任务", description = "勾选京东数据库商品(归属校验)+可选统一改价规则建单;"
@@ -166,6 +169,18 @@ public class JdPublishController {
adminAuthSupport.requireSessionOwnerUserId(httpRequest, null), request)); adminAuthSupport.requireSessionOwnerUserId(httpRequest, null), request));
} }
@PostMapping("/fill-values")
@Operation(summary = "上架必填参数 AI 补值", description = "2026-11-21 拍板「必填项一定要填,采集没有的用 AI 生成」,"
+ "与尺码表补值同族:客户端扫出快照缺失(标题空、SKU 京东价缺失/非法、库存缺失/非法,与执行侧拒绝语义"
+ "同口径)后到本端点要值。密钥不出服务端——取钥走 UserApiSecretService.findLongtaitouPlainValue 单一出口"
+ "(外观专利 → 货源查询 模块顺序);无密钥/上游故障返回空映射(不抛错),客户端按原缺失真实原因拒绝该行,"
+ "其余商品继续。同款有价的缺口由客户端先平移继承,只有全缺才把定价交给模型。生成的值不落库。")
public ApiResponse<Map<String, Object>> fillValues(
@Valid @RequestBody JdPublishFillValuesRequest request, HttpServletRequest httpRequest) {
return ApiResponse.success(fillAiService.generate(
adminAuthSupport.requireSessionOwnerUserId(httpRequest, null), request));
}
// ------------------------------------------------------------------ // ------------------------------------------------------------------
// v1.5 Phase 4:用户端「商品上架」页读侧(选品分页+任务面板四端点)。 // v1.5 Phase 4:用户端「商品上架」页读侧(选品分页+任务面板四端点)。
// 形状照 JdCollectController 面板段同族:dashboard/history/delete 走 resolve, // 形状照 JdCollectController 面板段同族:dashboard/history/delete 走 resolve,
@@ -0,0 +1,69 @@
package com.nanri.aiimage.modules.jd.model.dto;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.Data;
import java.math.BigDecimal;
import java.util.List;
/**
* 京东上架必填参数 AI 补值请求(2026-11-21 用户拍板「必填项一定要填,采集没有的用 AI 生成」,
* 与 B184-05 尺码表补值同族)。
*
* <p>采集的商品数据(biz_jd_product/biz_jd_sku)缺标题、SKU 京东价或库存时,客户端按
* 与 {@code _validate_product} 同口径的缺失探测扫出缺口,到本端点要值。密钥不出服务端:
* 按 外观专利 → 货源查询 的模块顺序取用户登记为龙抬头渠道的 LLM 密钥代调;服务端拿不到值
* (无密钥/上游故障/值形状非法)返回空映射,客户端按原缺失真实原因拒绝,发布链路不被卡死。</p>
*
* <p>价格不在这里凭空定:客户端对「同商品仍有合法价」的缺口先做同款平移继承,只有
* 全部 SKU 无价时才把定价交给模型(参考已有库存量级与类目上下文)。</p>
*/
@Data
public class JdPublishFillValuesRequest {
/** 商品 id(可选):只作日志与排查锚点,生成不依赖它。 */
private Long productId;
/** 品类路径文本(如「女装/连衣裙」),给模型上下文用,可选。 */
@Size(max = 200)
private String categoryPath;
/** 是否缺标题。 */
@NotNull
private Boolean needTitle;
/** SKU 摘要(按下发顺序 index 对齐):销售属性与已有合法价/库存供模型参考。 */
@NotEmpty
@Size(max = 200, message = "单次补值请求不能超过 200 个 SKU 摘要")
@Valid
private List<SkuSummary> skus;
/** 缺京东价的 SKU 下标(可为空列表:只缺标题/库存时)。 */
@Size(max = 200, message = "单次补值请求不能超过 200 个缺价 SKU")
private List<Integer> priceIndexes = List.of();
/** 缺库存的 SKU 下标(可为空列表)。 */
@Size(max = 200, message = "单次补值请求不能超过 200 个缺库存 SKU")
private List<Integer> stockIndexes = List.of();
@Data
public static class SkuSummary {
/** 在客户端 SKU 快照列表中的下标(回填映射的键)。 */
@NotNull
private Integer index;
/** 销售属性摘要(「颜色:红;尺码:M」),可选。 */
@Size(max = 120)
private String attrs;
/** 已有合法京东价(参考,缺价 SKU 不带)。 */
private BigDecimal price;
/** 已有合法库存(参考,缺库存 SKU 不带)。 */
private Integer stock;
}
}
@@ -0,0 +1,309 @@
package com.nanri.aiimage.modules.jd.service;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.config.HttpClientPool;
import com.nanri.aiimage.modules.jd.model.dto.JdPublishFillValuesRequest;
import com.nanri.aiimage.modules.usersecret.service.UserApiSecretService;
import com.nanri.aiimage.modules.usersecret.support.LlmChannel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClient;
import java.io.InputStream;
import java.math.BigDecimal;
import java.time.Duration;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* 京东上架必填参数 AI 补值服务(2026-11-21 用户拍板「必填项一定要填,采集没有的
* 用 AI 生成」,与 B184-05 尺码表补值 {@link JdSizeChartAiService} 同族)。
*
* <p>取数链路:客户端扫出快照缺失(标题空、SKU 京东价缺失/非法、库存缺失/非法——与
* {@code _validate_product} 的拒绝语义同口径)→ 本端点按用户密钥调龙抬头
* chat/completions 生成 → 返回 标题/SKU下标→价/SKU下标→库存。密钥不出服务端:
* 取钥走 {@link UserApiSecretService#findLongtaitouPlainValue} 单一出口,没有就不打
* 上游、直接返回空映射(客户端按原缺失真实原因拒绝该行,其余商品继续)。</p>
*
* <p>降级纪律与 {@link JdSizeChartAiService} 同形:上游任何故障(未配密钥、超时、
* 响应不可解析、值形状非法)一律 WARN + 空映射,绝不抛出中断发布链路。生成的值
* 不是永久资产,不落库不缓存。</p>
*/
@Service
@Slf4j
public class JdPublishFillAiService {
private static final int CHAT_TIMEOUT_MILLIS = 20_000;
private static final int MAX_RESPONSE_BYTES = 1 << 20;
private static final int MAX_SKUS_PER_CALL = 200;
/** 京麦标题框单行输入:超长标题整条丢弃,宁缺勿错。 */
private static final int MAX_TITLE_CHARS = 45;
private static final BigDecimal MAX_PRICE = new BigDecimal("999999");
private static final int MAX_STOCK = 999999;
private final UserApiSecretService userApiSecretService;
private final ObjectMapper objectMapper;
private volatile RestClient sharedClient;
public JdPublishFillAiService(UserApiSecretService userApiSecretService, ObjectMapper objectMapper) {
this.userApiSecretService = userApiSecretService;
this.objectMapper = objectMapper;
}
/**
* 为客户端请求生成缺失必填参数的值。返回 {"title": …, "prices": {下标: 值},
* "stocks": {下标: 值}},仅含命中的键;拿不到值的缺口不出现(客户端按原缺失
* 拒绝)。任何故障返回空映射,绝不抛出。
*/
public Map<String, Object> generate(Long userId, JdPublishFillValuesRequest request) {
Map<String, Object> empty = new LinkedHashMap<>();
if (userId == null || userId <= 0 || request == null || !hasAnyGap(request)) {
return empty;
}
String apiKey = userApiSecretService.findLongtaitouPlainValue(userId);
if (apiKey.isEmpty()) {
log.info("[jd-publish][fill-values] 用户 {} 未配置龙抬头密钥,上架必填参数按原缺失拒绝", userId);
return empty;
}
try {
String content = chatCompletion(apiKey, buildPrompt(request));
Map<String, Object> parsed = parseValues(content, request);
log.info("[jd-publish][fill-values] 用户 {} 商品 {} AI 补值完成 请求 {} 缺口 命中 {} 项",
userId, request.getProductId(), gapCount(request), filledCount(parsed));
return parsed;
} catch (Exception ex) {
log.warn("[jd-publish][fill-values] AI 补值失败,客户端按原缺失拒绝 userId={} productId={} err={}",
userId, request.getProductId(), ex.getMessage());
return empty;
}
}
static boolean hasAnyGap(JdPublishFillValuesRequest request) {
return Boolean.TRUE.equals(request.getNeedTitle())
|| (request.getPriceIndexes() != null && !request.getPriceIndexes().isEmpty())
|| (request.getStockIndexes() != null && !request.getStockIndexes().isEmpty());
}
static int gapCount(JdPublishFillValuesRequest request) {
int count = 0;
if (Boolean.TRUE.equals(request.getNeedTitle())) {
count++;
}
count += request.getPriceIndexes() == null ? 0 : request.getPriceIndexes().size();
count += request.getStockIndexes() == null ? 0 : request.getStockIndexes().size();
return count;
}
private static int filledCount(Map<String, Object> parsed) {
int count = parsed.containsKey("title") ? 1 : 0;
for (String key : List.of("prices", "stocks")) {
if (parsed.get(key) instanceof Map<?, ?> values) {
count += values.size();
}
}
return count;
}
String buildPrompt(JdPublishFillValuesRequest request) {
StringBuilder skus = new StringBuilder();
List<JdPublishFillValuesRequest.SkuSummary> list = request.getSkus();
if (list != null && list.size() > MAX_SKUS_PER_CALL) {
list = list.subList(0, MAX_SKUS_PER_CALL);
}
if (list != null) {
for (JdPublishFillValuesRequest.SkuSummary sku : list) {
skus.append("#").append(sku.getIndex()).append(' ')
.append(sku.getAttrs() == null ? "" : sku.getAttrs());
if (sku.getPrice() != null) {
skus.append(" 价=").append(sku.getPrice().toPlainString());
}
if (sku.getStock() != null) {
skus.append(" 库存=").append(sku.getStock());
}
skus.append('\n');
}
}
StringBuilder gaps = new StringBuilder();
if (Boolean.TRUE.equals(request.getNeedTitle())) {
gaps.append("标题\n");
}
if (request.getPriceIndexes() != null) {
for (Integer index : request.getPriceIndexes()) {
gaps.append("SKU #").append(index).append(" 京东价\n");
}
}
if (request.getStockIndexes() != null) {
for (Integer index : request.getStockIndexes()) {
gaps.append("SKU #").append(index).append(" 库存\n");
}
}
return "你是京东商品上架助手。下面这个商品的部分必填字段在采集数据里缺失,"
+ "请根据类目与 SKU 销售属性生成合理值补齐。规则:"
+ "1) 标题:不超过 30 个汉字的单行文本,不带品牌名,"
+ "不使用「最」「第一」「国家级」等广告法极限词;"
+ "2) 京东价:单位元,大于 0、最多 2 位小数,符合该类目中国电商常规定价,"
+ "参考已有 SKU 价格保持同款一致;"
+ "3) 库存:非负整数,常规备货量级,可参考已有 SKU 库存。"
+ (request.getCategoryPath() == null || request.getCategoryPath().isBlank()
? "" : "商品类目:" + request.getCategoryPath() + "。")
+ "\n只需要输出 JSON 对象,不要解释、不要 markdown 围栏,形状:"
+ "{\"title\": \"标题\", \"prices\": {\"<SKU下标>\": 价格}, \"stocks\": {\"<SKU下标>\": 库存}},"
+ "只包含下面点名的缺口。\nSKU 清单:\n" + skus + "需要补值的缺口:\n" + gaps;
}
/** 调龙抬头 chat/completions;该渠道需要显式思考参数(LlmChannel 登记)。 */
String chatCompletion(String apiKey, String prompt) {
Map<String, Object> body = new LinkedHashMap<>();
body.put("model", LlmChannel.LONGTAITOU.modelFor(null));
body.put("messages", List.of(Map.of("role", "user", "content", prompt)));
body.put("temperature", 0.2);
LlmChannel.LONGTAITOU.applyThinking(body);
String response = restClient().post()
.uri(LlmChannel.LONGTAITOU.host() + "/v1/chat/completions")
.headers(headers -> headers.setBearerAuth(apiKey))
.body(body)
.exchange((request, res) -> {
try (InputStream in = res.getBody()) {
return HttpClientPool.readBodyBounded(in,
Duration.ofMillis(CHAT_TIMEOUT_MILLIS), MAX_RESPONSE_BYTES);
}
});
JsonNode root = parse(response);
JsonNode content = root == null ? null
: root.path("choices").path(0).path("message").path("content");
return content == null || content.isNull() ? "" : content.asText();
}
/**
* 模型输出 → 归一映射:标题只收非空单行且 ≤45 字;价/库存按下标点名收,非法值
* (非数值、≤0、超上限、价超 2 位小数、库存非整数)整格丢弃——生成值要直接进
* 京麦输入框,宁缺勿错。未点名的下标不收。
*/
Map<String, Object> parseValues(String content, JdPublishFillValuesRequest request) {
Map<String, Object> out = new LinkedHashMap<>();
if (content == null || content.isBlank()) {
return out;
}
String json = content.trim();
if (json.startsWith("```")) {
int start = json.indexOf('\n');
int end = json.lastIndexOf("```");
json = start >= 0 && end > start ? json.substring(start + 1, end) : json.replaceAll("```", "");
}
JsonNode root = parse(json);
if (root == null || !root.isObject()) {
return out;
}
if (Boolean.TRUE.equals(request.getNeedTitle())) {
String title = asTitle(root.path("title"));
if (title != null) {
out.put("title", title);
}
}
Map<String, String> prices = numericByIndex(root.path("prices"), request.getPriceIndexes(), false);
if (!prices.isEmpty()) {
out.put("prices", prices);
}
Map<String, String> stocks = numericByIndex(root.path("stocks"), request.getStockIndexes(), true);
if (!stocks.isEmpty()) {
out.put("stocks", stocks);
}
return out;
}
private static String asTitle(JsonNode value) {
if (value == null || !value.isTextual()) {
return null;
}
String text = value.asText().trim();
if (text.isEmpty() || text.length() > MAX_TITLE_CHARS
|| text.indexOf('\n') >= 0 || text.indexOf('\r') >= 0) {
return null;
}
return text;
}
private static Map<String, String> numericByIndex(JsonNode node, List<Integer> indexes, boolean stock) {
Map<String, String> out = new LinkedHashMap<>();
if (node == null || !node.isObject() || indexes == null) {
return out;
}
for (Integer index : indexes) {
if (index == null || index < 0) {
continue;
}
JsonNode value = node.path(String.valueOf(index));
String parsed = stock ? asStock(value) : asPrice(value);
if (parsed != null) {
out.put(String.valueOf(index), parsed);
}
}
return out;
}
private static String asPrice(JsonNode value) {
BigDecimal number = asDecimal(value);
if (number == null || number.signum() <= 0 || number.compareTo(MAX_PRICE) > 0
|| number.stripTrailingZeros().scale() > 2) {
return null;
}
return number.toPlainString();
}
private static String asStock(JsonNode value) {
BigDecimal number = asDecimal(value);
if (number == null || number.signum() < 0 || number.compareTo(BigDecimal.valueOf(MAX_STOCK)) > 0
|| number.stripTrailingZeros().scale() > 0) {
return null;
}
return String.valueOf(number.intValueExact());
}
/** 模型常把数值输出成字符串("47.2"),两种形状都认;其余一律不合格。 */
private static BigDecimal asDecimal(JsonNode value) {
if (value == null || value.isNull()) {
return null;
}
if (value.isNumber()) {
return value.decimalValue();
}
if (value.isTextual()) {
String text = value.asText().trim();
if (text.isEmpty() || !text.matches("\\d+(\\.\\d+)?")) {
return null;
}
try {
return new BigDecimal(text);
} catch (NumberFormatException ex) {
return null;
}
}
return null;
}
private JsonNode parse(String body) {
try {
return body == null || body.isBlank() ? null : objectMapper.readTree(body);
} catch (Exception ex) {
return null;
}
}
private RestClient restClient() {
RestClient client = sharedClient;
if (client != null) {
return client;
}
synchronized (this) {
if (sharedClient == null) {
sharedClient = RestClient.builder()
.requestFactory(HttpClientPool.requestFactory(CHAT_TIMEOUT_MILLIS))
.build();
}
return sharedClient;
}
}
}
@@ -6,7 +6,6 @@ import com.nanri.aiimage.config.HttpClientPool;
import com.nanri.aiimage.modules.jd.model.dto.JdSizeChartValuesRequest; import com.nanri.aiimage.modules.jd.model.dto.JdSizeChartValuesRequest;
import com.nanri.aiimage.modules.usersecret.service.UserApiSecretService; import com.nanri.aiimage.modules.usersecret.service.UserApiSecretService;
import com.nanri.aiimage.modules.usersecret.support.LlmChannel; import com.nanri.aiimage.modules.usersecret.support.LlmChannel;
import com.nanri.aiimage.modules.usersecret.support.UserSecretModule;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClient; import org.springframework.web.client.RestClient;
@@ -83,14 +82,8 @@ public class JdSizeChartAiService {
/** 按模块顺序找「渠道登记为龙抬头且已存明文」的用户 LLM 密钥;没有返回空串。 */ /** 按模块顺序找「渠道登记为龙抬头且已存明文」的用户 LLM 密钥;没有返回空串。 */
String findLongtaitouKey(Long userId) { String findLongtaitouKey(Long userId) {
for (UserSecretModule module : List.of(UserSecretModule.APPEARANCE_PATENT, UserSecretModule.SIMILAR_ASIN)) { // 单一出口在 UserApiSecretService(京东上架必填参数补值同用一份模块顺序)。
String channel = userApiSecretService.findChannel(userId, module.key()); return userApiSecretService.findLongtaitouPlainValue(userId);
String key = userApiSecretService.findPlainValue(userId, module.key());
if (LlmChannel.LONGTAITOU.key().equals(channel) && key != null && !key.isBlank()) {
return key;
}
}
return "";
} }
String buildPrompt(JdSizeChartValuesRequest request, List<JdSizeChartValuesRequest.Gap> gaps) { String buildPrompt(JdSizeChartValuesRequest request, List<JdSizeChartValuesRequest.Gap> gaps) {
@@ -0,0 +1,177 @@
package com.nanri.aiimage.modules.jd.service;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nanri.aiimage.modules.jd.model.dto.JdPublishFillValuesRequest;
import com.nanri.aiimage.modules.usersecret.service.UserApiSecretService;
import org.junit.jupiter.api.Test;
import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* 京东上架必填参数 AI 补值的口径判据(2026-11-21 拍板「必填项一定要填,采集没有的
* 用 AI 生成」,与 {@link JdSizeChartAiServiceTest} 同族)。
*
* <p>上游 HTTP 不 mock(抽包可见解析方法直测)。这一格要守的是:模型输出可以直接
* 落进京麦标题框与 SKU 价格/库存输入框——<b>宁缺勿错</b>,超长/换行标题、非法价格、
* 非整数库存的格整格丢弃(客户端按原缺失真实原因拒绝该行),绝不给用户一张
* 「看着补齐了但值离谱」的商品。</p>
*/
class JdPublishFillAiServiceTest {
private final UserApiSecretService secretService = mock(UserApiSecretService.class);
private final JdPublishFillAiService service =
new JdPublishFillAiService(secretService, new ObjectMapper());
private static JdPublishFillValuesRequest.SkuSummary sku(int index, String attrs, String price, Integer stock) {
JdPublishFillValuesRequest.SkuSummary summary = new JdPublishFillValuesRequest.SkuSummary();
summary.setIndex(index);
summary.setAttrs(attrs);
summary.setPrice(price == null ? null : new BigDecimal(price));
summary.setStock(stock);
return summary;
}
private static JdPublishFillValuesRequest request(boolean needTitle, List<Integer> prices,
List<Integer> stocks) {
JdPublishFillValuesRequest request = new JdPublishFillValuesRequest();
request.setProductId(42L);
request.setCategoryPath("女装/连衣裙");
request.setNeedTitle(needTitle);
request.setPriceIndexes(prices);
request.setStockIndexes(stocks);
request.setSkus(List.of(
sku(0, "颜色:红;尺码:M", "21.30", 5),
sku(1, "颜色:蓝;尺码:L", null, null)));
return request;
}
@Test
void 模型输出解析成标题与下标价格库存() {
String content = "{\"title\": \"法式碎花雪纺连衣裙\", \"prices\": {\"1\": 59.9}, \"stocks\": {\"1\": \"100\"}}";
Map<String, Object> values = service.parseValues(content,
request(true, List.of(1), List.of(1)));
assertThat(values.get("title")).isEqualTo("法式碎花雪纺连衣裙");
assertThat(values.get("prices")).isEqualTo(Map.of("1", "59.9"));
assertThat(values.get("stocks")).isEqualTo(Map.of("1", "100"));
}
@Test
void 字符串数值与markdown围栏照常解析() {
String content = "```json\n{\"title\": \"宽松直筒牛仔裤\", \"prices\": {\"1\": \"128.00\"},"
+ " \"stocks\": {\"1\": 80}}\n```";
Map<String, Object> values = service.parseValues(content,
request(true, List.of(1), List.of(1)));
assertThat(values.get("title")).isEqualTo("宽松直筒牛仔裤");
assertThat(values.get("prices")).isEqualTo(Map.of("1", "128.00"));
assertThat(values.get("stocks")).isEqualTo(Map.of("1", "80"));
}
@Test
void 超长与换行标题整条丢弃() {
String longTitle = "好".repeat(46);
String content = "{\"title\": \"第一行\\n第二行\"}";
assertThat(service.parseValues(content, request(true, List.of(), List.of())))
.doesNotContainKey("title");
Map<String, Object> values = service.parseValues(
"{\"title\": \"" + longTitle + "\"}", request(true, List.of(), List.of()));
assertThat(values).doesNotContainKey("title");
Map<String, Object> atLimit = service.parseValues(
"{\"title\": \"" + "好".repeat(45) + "\"}", request(true, List.of(), List.of()));
assertThat(atLimit).containsKey("title");
}
@Test
void 非法价格格丢弃不给半截值() {
String content = "{\"prices\": {\"1\": 0, \"2\": -3, \"3\": \"59.999\", \"4\": \"abc\", \"5\": 9999999}}";
Map<String, Object> values = service.parseValues(content,
request(false, List.of(1, 2, 3, 4, 5), List.of()));
assertThat(values).doesNotContainKey("prices");
}
@Test
void 非法库存格丢弃() {
String content = "{\"stocks\": {\"1\": -1, \"2\": 80.5, \"3\": \"件\", \"4\": 9999999}}";
Map<String, Object> values = service.parseValues(content,
request(false, List.of(), List.of(1, 2, 3, 4)));
assertThat(values).doesNotContainKey("stocks");
Map<String, Object> zeroKept = service.parseValues(
"{\"stocks\": {\"1\": 0}}", request(false, List.of(), List.of(1)));
assertThat(zeroKept.get("stocks")).isEqualTo(Map.of("1", "0"));
}
@Test
void 未点名的下标不收() {
String content = "{\"prices\": {\"0\": 10}, \"stocks\": {\"0\": 5}}";
Map<String, Object> values = service.parseValues(content,
request(false, List.of(1), List.of(1)));
assertThat(values).doesNotContainKeys("prices", "stocks");
}
@Test
void 垃圾输出返回空映射不抛异常() {
assertThat(service.parseValues("", request(true, List.of(), List.of()))).isEmpty();
assertThat(service.parseValues("这是一句话", request(true, List.of(), List.of()))).isEmpty();
assertThat(service.parseValues("[1,2,3]", request(true, List.of(), List.of()))).isEmpty();
}
@Test
void prompt带类目SKU摘要与缺口清单() {
String prompt = service.buildPrompt(request(true, List.of(1), List.of(1)));
assertThat(prompt).contains("女装/连衣裙")
.contains("#0 颜色:红;尺码:M 价=21.30 库存=5")
.contains("#1 颜色:蓝;尺码:L")
.contains("标题\n").contains("SKU #1 京东价").contains("SKU #1 库存")
.contains("广告法极限词").contains("JSON");
}
@Test
void 无categoryPath的prompt照常构造() {
JdPublishFillValuesRequest request = request(false, List.of(), List.of(1));
request.setCategoryPath(null);
assertThat(service.buildPrompt(request)).contains("SKU #1 库存").doesNotContain("null");
}
@Test
void 取钥走服务单一出口且无密钥不打上游() {
when(secretService.findLongtaitouPlainValue(any())).thenReturn("");
assertThat(service.generate(11L, request(true, List.of(1), List.of())))
.isEmpty();
verify(secretService).findLongtaitouPlainValue(11L);
}
@Test
void generate对脏入参与无缺口一律空映射() {
assertThat(service.generate(null, request(true, List.of(), List.of()))).isEmpty();
assertThat(service.generate(1L, null)).isEmpty();
// 无缺口(needTitle 未点名、价/库下标都空)直接空映射,连密钥都不查。
assertThat(service.generate(1L, request(false, List.of(), List.of()))).isEmpty();
verify(secretService, never()).findLongtaitouPlainValue(any());
}
}
@@ -10,9 +10,9 @@ import java.util.Map;
import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock; import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when; import static org.mockito.Mockito.when;
/** /**
@@ -120,31 +120,12 @@ class JdSizeChartAiServiceTest {
} }
@Test @Test
void 龙抬头密钥按模块顺序取用() { void 龙抬头密钥走服务单一出口() {
when(secretService.findChannel(eq(7L), eq("appearance-patent"))).thenReturn("longtaitou"); when(secretService.findLongtaitouPlainValue(eq(7L))).thenReturn("sk-ltt-1");
when(secretService.findPlainValue(eq(7L), eq("appearance-patent"))).thenReturn("sk-ltt-1");
assertThat(service.findLongtaitouKey(7L)).isEqualTo("sk-ltt-1"); assertThat(service.findLongtaitouKey(7L)).isEqualTo("sk-ltt-1");
} // 模块顺序与兜底口径统一收口在 UserApiSecretServiceTest 验证。
verify(secretService).findLongtaitouPlainValue(eq(7L));
@Test
void 外观专利渠道不匹配时回落货源查询模块() {
when(secretService.findChannel(eq(8L), eq("appearance-patent"))).thenReturn("t8star");
when(secretService.findPlainValue(eq(8L), eq("appearance-patent"))).thenReturn("sk-t8");
when(secretService.findChannel(eq(8L), eq("similar-asin"))).thenReturn("longtaitou");
when(secretService.findPlainValue(eq(8L), eq("similar-asin"))).thenReturn("sk-ltt-2");
assertThat(service.findLongtaitouKey(8L)).isEqualTo("sk-ltt-2");
}
@Test
void 密钥登记为空或无龙抬头时降级公式回退() {
when(secretService.findChannel(eq(9L), anyString())).thenReturn(null);
assertThat(service.findLongtaitouKey(9L)).isEmpty();
when(secretService.findChannel(eq(10L), eq("appearance-patent"))).thenReturn("longtaitou");
when(secretService.findPlainValue(eq(10L), eq("appearance-patent"))).thenReturn("");
assertThat(service.findLongtaitouKey(10L)).isEmpty();
} }
@Test @Test
@@ -156,7 +137,7 @@ class JdSizeChartAiServiceTest {
assertThat(service.generate(1L, null)).isEmpty(); assertThat(service.generate(1L, null)).isEmpty();
assertThat(service.generate(1L, new JdSizeChartValuesRequest())).isEmpty(); assertThat(service.generate(1L, new JdSizeChartValuesRequest())).isEmpty();
when(secretService.findChannel(any(), anyString())).thenReturn(null); when(secretService.findLongtaitouPlainValue(any())).thenReturn("");
assertThat(service.generate(11L, request)).isEmpty(); assertThat(service.generate(11L, request)).isEmpty();
} }
} }