diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/jd/controller/JdPublishController.java b/backend-java/src/main/java/com/nanri/aiimage/modules/jd/controller/JdPublishController.java index 81da66d31..aa5496175 100644 --- a/backend-java/src/main/java/com/nanri/aiimage/modules/jd/controller/JdPublishController.java +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/jd/controller/JdPublishController.java @@ -6,6 +6,7 @@ import com.nanri.aiimage.common.security.AdminAuthSupport; import com.nanri.aiimage.modules.jd.model.dto.JdPublishChunkRequest; import com.nanri.aiimage.modules.jd.model.dto.JdPublishTaskBatchRequest; import com.nanri.aiimage.modules.jd.model.dto.JdPublishTaskCreateRequest; +import com.nanri.aiimage.modules.jd.model.dto.JdSizeChartValuesRequest; import com.nanri.aiimage.modules.jd.model.vo.JdProductPageVo; import com.nanri.aiimage.modules.jd.model.vo.JdPublishChunkVo; import com.nanri.aiimage.modules.jd.model.vo.JdPublishDashboardVo; @@ -18,6 +19,7 @@ import com.nanri.aiimage.modules.jd.service.JdProductQueryService; import com.nanri.aiimage.modules.jd.service.JdPublishBoardService; import com.nanri.aiimage.modules.jd.service.JdPublishIngestService; import com.nanri.aiimage.modules.jd.service.JdPublishTaskService; +import com.nanri.aiimage.modules.jd.service.JdSizeChartAiService; import com.nanri.aiimage.modules.task.model.dto.TaskHeartbeatRequest; import com.nanri.aiimage.modules.task.model.vo.TaskHeartbeatVo; import com.nanri.aiimage.modules.task.service.TaskProgressOwnershipSupport; @@ -37,6 +39,9 @@ import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; +import java.util.List; +import java.util.Map; + /** * 京东商品上架任务面(v1.5 Phase 2,蓝图 docs/ITERATION_PLAN.md §3)。 * @@ -59,6 +64,7 @@ public class JdPublishController { private final JdProductQueryService jdProductQueryService; private final TaskProgressOwnershipSupport progressOwnershipSupport; private final AdminAuthSupport adminAuthSupport; + private final JdSizeChartAiService sizeChartAiService; @PostMapping({"/tasks", "/tasks/target-brand"}) @Operation(summary = "创建京东商品上架任务", description = "勾选京东数据库商品(归属校验)+可选统一改价规则建单;" @@ -149,6 +155,17 @@ public class JdPublishController { adminAuthSupport.requireSessionOwnerUserId(httpRequest, userId), request)); } + @PostMapping("/size-values") + @Operation(summary = "尺码表空格 AI 补值", description = "B184-05(2026-11-21 拍板「必填项一定要填,采集没有的用 AI 生成」):" + + "客户端扫出京麦服装类目尺码表强制列空格后到本端点要值。密钥不出服务端——按 外观专利 → 货源查询 " + + "的模块顺序取用户登记为龙抬头渠道的 LLM 密钥代调;无密钥/上游故障返回空映射(不抛错)," + + "客户端按身高比例公式回退填表,发布链路不被卡死。生成的值不落库。") + public ApiResponse>>> sizeChartValues( + @Valid @RequestBody JdSizeChartValuesRequest request, HttpServletRequest httpRequest) { + return ApiResponse.success(sizeChartAiService.generate( + adminAuthSupport.requireSessionOwnerUserId(httpRequest, null), request)); + } + // ------------------------------------------------------------------ // v1.5 Phase 4:用户端「商品上架」页读侧(选品分页+任务面板四端点)。 // 形状照 JdCollectController 面板段同族:dashboard/history/delete 走 resolve, diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/jd/model/dto/JdSizeChartValuesRequest.java b/backend-java/src/main/java/com/nanri/aiimage/modules/jd/model/dto/JdSizeChartValuesRequest.java new file mode 100644 index 000000000..e86f8495f --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/jd/model/dto/JdSizeChartValuesRequest.java @@ -0,0 +1,49 @@ +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.Pattern; +import jakarta.validation.constraints.Size; +import lombok.Data; + +import java.util.List; + +/** + * 尺码表空格补值请求(B184-05,2026-11-21 用户拍板「必填项一定要填,采集没有的用 AI 生成」)。 + * + *

京麦服装类目尺码表 6 个强制维度列 × 每个尺码行全部必填(真机取证:「空着」无通过形态), + * 克隆预填只带出源商品已填的身高/体重,其余空格由客户端扫出后到服务端请求 AI 生成; + * 服务端拿不到值(无龙抬头密钥/上游故障)时返回空映射,客户端按身高比例公式回退。

+ */ +@Data +public class JdSizeChartValuesRequest { + + @NotEmpty + @Size(max = 200, message = "单次补值请求不能超过 200 个空格") + @Valid + private List gaps; + + /** 品类文本(如「男士套头毛衣/针织衫」),给模型上下文用,可选。 */ + @Size(max = 120) + private String categoryPath; + + @Data + public static class Gap { + + /** 尺码行名(S / M / XL / 2XL …)。 */ + @NotEmpty + @Size(max = 20) + private String row; + + /** 补值口径列 key:height / weight / shoulder / bust / length / sleeve。 */ + @NotEmpty + @Pattern(regexp = "height|weight|shoulder|bust|length|sleeve", + message = "column 必须是登记过的尺码表列 key") + private String column; + + /** 该格输入框数(区间格 2、单值格 1),决定要回几个值。 */ + @NotNull + private Integer inputCount; + } +} diff --git a/backend-java/src/main/java/com/nanri/aiimage/modules/jd/service/JdSizeChartAiService.java b/backend-java/src/main/java/com/nanri/aiimage/modules/jd/service/JdSizeChartAiService.java new file mode 100644 index 000000000..a647ae59b --- /dev/null +++ b/backend-java/src/main/java/com/nanri/aiimage/modules/jd/service/JdSizeChartAiService.java @@ -0,0 +1,231 @@ +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.JdSizeChartValuesRequest; +import com.nanri.aiimage.modules.usersecret.service.UserApiSecretService; +import com.nanri.aiimage.modules.usersecret.support.LlmChannel; +import com.nanri.aiimage.modules.usersecret.support.UserSecretModule; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Service; +import org.springframework.web.client.RestClient; + +import java.io.InputStream; +import java.time.Duration; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * 尺码表空格的 AI 补值服务(B184-05,2026-11-21 用户拍板「必填项一定要填, + * 采集没有的用 AI 生成」)。 + * + *

取数链路:客户端扫出克隆页尺码表强制列空格 → 本端点按用户密钥调龙抬头 + * chat/completions 生成 → 返回 行→列→值序列 映射。密钥不出服务端:按 + * 外观专利 → 货源查询的模块顺序找「渠道登记为龙抬头且已存明文」的用户密钥, + * 没有就不打上游、直接返回空映射(客户端按身高比例公式回退,发布不被卡死)。

+ * + *

降级纪律与 {@code LongtaitouBalanceClient} 同形:上游任何故障(未配密钥、 + * 超时、响应不可解析、值形状非法)一律 WARN + 空映射,绝不抛出中断发布链路; + * 生成的值也不是永久资产,不落库不缓存。

+ */ +@Service +@Slf4j +public class JdSizeChartAiService { + + private static final int CHAT_TIMEOUT_MILLIS = 20_000; + private static final int MAX_RESPONSE_BYTES = 1 << 20; + private static final int MAX_ITEMS_PER_CALL = 200; + + private final UserApiSecretService userApiSecretService; + private final ObjectMapper objectMapper; + + private volatile RestClient sharedClient; + + public JdSizeChartAiService(UserApiSecretService userApiSecretService, ObjectMapper objectMapper) { + this.userApiSecretService = userApiSecretService; + this.objectMapper = objectMapper; + } + + /** + * 为客户端请求生成空格补值。返回 行→列→值序列;拿不到值的格不出现(客户端按 + * 公式回退)。任何故障返回空映射,绝不抛出。 + */ + public Map>> generate(Long userId, JdSizeChartValuesRequest request) { + Map>> empty = new LinkedHashMap<>(); + if (userId == null || userId <= 0 || request == null + || request.getGaps() == null || request.getGaps().isEmpty()) { + return empty; + } + List gaps = request.getGaps(); + if (gaps.size() > MAX_ITEMS_PER_CALL) { + gaps = gaps.subList(0, MAX_ITEMS_PER_CALL); + } + String apiKey = findLongtaitouKey(userId); + if (apiKey.isEmpty()) { + log.info("[jd-publish][size-chart] 用户 {} 未配置龙抬头密钥,尺码表补值走客户端公式回退", userId); + return empty; + } + try { + String content = chatCompletion(apiKey, buildPrompt(request, gaps)); + Map>> parsed = parseValues(content, gaps); + log.info("[jd-publish][size-chart] 用户 {} AI 补值完成 请求 {} 格 命中 {} 格", + userId, gaps.size(), parsed.values().stream().mapToInt(Map::size).sum()); + return parsed; + } catch (Exception ex) { + log.warn("[jd-publish][size-chart] AI 补值失败,客户端将回退比例公式 userId={} err={}", + userId, ex.getMessage()); + return empty; + } + } + + /** 按模块顺序找「渠道登记为龙抬头且已存明文」的用户 LLM 密钥;没有返回空串。 */ + String findLongtaitouKey(Long userId) { + for (UserSecretModule module : List.of(UserSecretModule.APPEARANCE_PATENT, UserSecretModule.SIMILAR_ASIN)) { + String channel = userApiSecretService.findChannel(userId, module.key()); + 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 gaps) { + StringBuilder rows = new StringBuilder(); + Map> byRow = new LinkedHashMap<>(); + for (JdSizeChartValuesRequest.Gap gap : gaps) { + byRow.computeIfAbsent(gap.getRow(), k -> new ArrayList<>()) + .add(gap.getColumn() + "(要" + gap.getInputCount() + "个值)"); + } + byRow.forEach((row, cols) -> rows.append(row).append(": ").append(String.join("、", cols)).append("\n")); + return "你是服装商品上架的尺码顾问。请为下面的服装类目尺码表空格给出合理的数值:" + + "单位 cm(体重 kg),数值保留 1 位小数,区间左值必须小于右值," + + "同一列数值随尺码变大单调不减,数值要符合中国成人男/女装常规版型。" + + (request.getCategoryPath() == null || request.getCategoryPath().isBlank() + ? "" : "商品类目:" + request.getCategoryPath() + "。") + + "\n只需要输出 JSON 对象,不要解释、不要 markdown 围栏,形状:" + + "{\"尺码行名\": {\"列key\": [值1, 值2]}}。\n需要补值的格子:\n" + rows; + } + + /** 调龙抬头 chat/completions;该渠道需要显式思考参数(LlmChannel 登记)。 */ + String chatCompletion(String apiKey, String prompt) { + Map 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(); + } + + /** + * 模型输出 → 归一映射:行/列 key 归一大写与登记 key,值转字符串、按 inputCount + * 截断/丢弃;非法值(非数值、区间倒挂、负数)整格丢弃——生成值要直接进京麦 + * 数值输入框,宁缺勿错。 + */ + Map>> parseValues(String content, List gaps) { + Map>> 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; + } + for (JdSizeChartValuesRequest.Gap gap : gaps) { + JsonNode values = root.path(gap.getRow()).path(gap.getColumn()); + if (!values.isArray() || values.size() < gap.getInputCount()) { + continue; + } + List seq = new ArrayList<>(); + boolean ok = true; + for (int i = 0; i < gap.getInputCount(); i++) { + Double num = asNumber(values.get(i)); + if (num == null || num <= 0 || num > 500) { + ok = false; + break; + } + seq.add(String.valueOf(round1(num))); + } + if (ok && gap.getInputCount() == 2 + && Double.parseDouble(seq.get(0)) >= Double.parseDouble(seq.get(1))) { + ok = false; + } + if (ok) { + out.computeIfAbsent(gap.getRow(), k -> new LinkedHashMap<>()) + .put(gap.getColumn(), seq); + } + } + return out; + } + + /** 模型常把数值输出成字符串("47.2"),两种形状都认;其余一律不合格。 */ + private static Double asNumber(JsonNode v) { + if (v == null || v.isNull()) { + return null; + } + if (v.isNumber()) { + return v.asDouble(); + } + if (v.isTextual()) { + String text = v.asText().trim(); + if (!text.matches("\\d+(\\.\\d+)?")) { + return null; + } + try { + return Double.parseDouble(text); + } catch (NumberFormatException ex) { + return null; + } + } + return null; + } + + private static double round1(double value) { + return Math.round(value * 10.0) / 10.0; + } + + 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; + } + } +} diff --git a/backend-java/src/test/java/com/nanri/aiimage/modules/jd/service/JdSizeChartAiServiceTest.java b/backend-java/src/test/java/com/nanri/aiimage/modules/jd/service/JdSizeChartAiServiceTest.java new file mode 100644 index 000000000..9cfbab59d --- /dev/null +++ b/backend-java/src/test/java/com/nanri/aiimage/modules/jd/service/JdSizeChartAiServiceTest.java @@ -0,0 +1,162 @@ +package com.nanri.aiimage.modules.jd.service; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.nanri.aiimage.modules.jd.model.dto.JdSizeChartValuesRequest; +import com.nanri.aiimage.modules.usersecret.service.UserApiSecretService; +import org.junit.jupiter.api.Test; + +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.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * 尺码表空格 AI 补值的口径判据(B184-05,2026-11-21 拍板「必填项一定要填, + * 采集没有的用 AI 生成」)。 + * + *

上游 HTTP 不 mock(与 {@code LongtaitouBalanceClientTest} 同形:抽包可见解析 + * 方法直测)。这一格要守的是:模型输出可以直接落进京麦数值输入框——宁缺勿错, + * 数量不够/区间倒挂/非数值的格整格丢弃(客户端按比例公式回退),绝不给用户一张 + * 「看着填满了但数值离谱」的尺码表。

+ */ +class JdSizeChartAiServiceTest { + + private final UserApiSecretService secretService = mock(UserApiSecretService.class); + private final JdSizeChartAiService service = + new JdSizeChartAiService(secretService, new ObjectMapper()); + + private static JdSizeChartValuesRequest.Gap gap(String row, String column, int inputCount) { + JdSizeChartValuesRequest.Gap gap = new JdSizeChartValuesRequest.Gap(); + gap.setRow(row); + gap.setColumn(column); + gap.setInputCount(inputCount); + return gap; + } + + @Test + void 模型数值输出解析成行列值序列() { + String content = "{\"S\": {\"shoulder\": [47.2], \"bust\": [80.3, 81.5]}," + + " \"M\": {\"length\": [68.5]}}"; + + Map>> values = service.parseValues(content, List.of( + gap("S", "shoulder", 1), gap("S", "bust", 2), gap("M", "length", 1))); + + assertThat(values.get("S").get("shoulder")).containsExactly("47.2"); + assertThat(values.get("S").get("bust")).containsExactly("80.3", "81.5"); + assertThat(values.get("M").get("length")).containsExactly("68.5"); + } + + @Test + void 字符串数值与markdown围栏照常解析() { + String content = "```json\n{\"XL\": {\"sleeve\": [\"57.1\"], \"weight\": [\"62.5\", \"70\"]}}\n```"; + + Map>> values = service.parseValues(content, List.of( + gap("XL", "sleeve", 1), gap("XL", "weight", 2))); + + assertThat(values.get("XL").get("sleeve")).containsExactly("57.1"); + assertThat(values.get("XL").get("weight")).containsExactly("62.5", "70.0"); + } + + @Test + void 值数量不足inputCount的格整格丢弃() { + String content = "{\"S\": {\"bust\": [80.3]}}"; + + assertThat(service.parseValues(content, + List.of(gap("S", "bust", 2)))).isEmpty(); + } + + @Test + void 区间倒挂的格丢弃不给半截值() { + String content = "{\"M\": {\"bust\": [81.5, 80.3]}}"; + + assertThat(service.parseValues(content, + List.of(gap("M", "bust", 2)))).isEmpty(); + } + + @Test + void 非数值超范围与零值格丢弃() { + String content = "{\"S\": {\"shoulder\": [\"肩宽\"]}, \"M\": {\"shoulder\": [-3]}," + + " \"L\": {\"shoulder\": [0]}, \"XL\": {\"shoulder\": [900]}}"; + + Map>> values = service.parseValues(content, List.of( + gap("S", "shoulder", 1), gap("M", "shoulder", 1), + gap("L", "shoulder", 1), gap("XL", "shoulder", 1))); + + assertThat(values).isEmpty(); + } + + @Test + void 垃圾输出返回空映射不抛异常() { + assertThat(service.parseValues("", List.of(gap("S", "bust", 1)))).isEmpty(); + assertThat(service.parseValues("这是一句话", List.of(gap("S", "bust", 1)))).isEmpty(); + assertThat(service.parseValues("[1,2,3]", List.of(gap("S", "bust", 1)))).isEmpty(); + } + + @Test + void prompt带类目上下文与格清单() { + JdSizeChartValuesRequest request = new JdSizeChartValuesRequest(); + request.setGaps(List.of(gap("S", "shoulder", 1), gap("S", "bust", 2))); + request.setCategoryPath("男士套头毛衣"); + + String prompt = service.buildPrompt(request, request.getGaps()); + + assertThat(prompt).contains("男士套头毛衣").contains("S: ") + .contains("shoulder(要1个值)").contains("bust(要2个值)") + .contains("区间左值必须小于右值").contains("JSON"); + } + + @Test + void 无categoryPath的prompt照常构造() { + JdSizeChartValuesRequest request = new JdSizeChartValuesRequest(); + request.setGaps(List.of(gap("M", "length", 1))); + + assertThat(service.buildPrompt(request, request.getGaps())) + .contains("M: ").doesNotContain("null"); + } + + @Test + void 龙抬头密钥按模块顺序取用() { + when(secretService.findChannel(eq(7L), eq("appearance-patent"))).thenReturn("longtaitou"); + when(secretService.findPlainValue(eq(7L), eq("appearance-patent"))).thenReturn("sk-ltt-1"); + + assertThat(service.findLongtaitouKey(7L)).isEqualTo("sk-ltt-1"); + } + + @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 + void generate对脏入参与无密钥一律空映射() { + JdSizeChartValuesRequest request = new JdSizeChartValuesRequest(); + request.setGaps(List.of(gap("S", "bust", 1))); + + assertThat(service.generate(null, request)).isEmpty(); + assertThat(service.generate(1L, null)).isEmpty(); + assertThat(service.generate(1L, new JdSizeChartValuesRequest())).isEmpty(); + + when(secretService.findChannel(any(), anyString())).thenReturn(null); + assertThat(service.generate(11L, request)).isEmpty(); + } +}