Browse Source

feat(ai.aiyunyi.detect): S-cfc-472 实现照片路径编排 AicdsDetectionService 使红单测全绿

Agnes Agent 1 hour ago
parent
commit
e836ec57b1

+ 331 - 16
cfc-backend/src/main/java/com/etotem/cfc/service/AicdsDetectionService.java

@@ -1,39 +1,224 @@
 package com.etotem.cfc.service;
 
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.etotem.cfc.entity.AiYunyiMapping;
+import com.etotem.cfc.mapper.AiYunyiMappingMapper;
+import org.springframework.http.ResponseEntity;
 import org.springframework.stereotype.Service;
 
-import java.util.Map;
-
 import javax.annotation.Resource;
+import java.util.ArrayList;
+import java.util.Collections;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
 
 /**
- * 爱云医 AI 检测编排宿主,能力键 {@code ai.aiyunyi.detectVideo}(S-cfc-473)。
- *
- * <p>按设计 §3.4 的视频路径:{@code inspectionType=1/2} 时先经网关
- * {@code GET /detection/package/getPath} 取 H5 检测页地址,前端用 {@code <web-view>} 内嵌采集;
- * 采集完成后必须先轮询 {@code package/page} 确认检测完成,再调 {@code report/get} 拉报告(§3.4 第 10/11 步)。</p>
+ * 爱云医 AI 检测编排宿主:照片路径(能力键 {@code ai.aiyunyi.detect},S-cfc-472)
+ * 与视频路径(能力键 {@code ai.aiyunyi.detectVideo},S-cfc-473)共用同一编排宿主。
  *
- * <p>错误归一(§4.5):网关错误码(code != 0)、空响应、空白 {@code data.path} 一律快速失败,
- * 禁止静默返回空/占位 URL 导致 web-view 白屏;网关异常原样向上抛出,不吞错、不填空串。</p>
+ * <p>服务端统一收口鉴权与转发:私钥/令牌只在 {@link AicdsGatewayService} 内使用,前端仅带小程序 token。
+ * 本类负责把「登录 → 商品 → 下单 → 建检测人 → 激活 → 套餐子项 → 录入数据 → 报告」串成一条链路,
+ * 并通过 {@code aiyunyi_mapping} 映射保证同一成员重复识别幂等;视频类型另取 H5 检测页地址。</p>
  */
 @Service
 public class AicdsDetectionService {
 
+    /** 商品列表为空时的归一提示(§4.5)。 */
+    private static final String NO_SPU_MESSAGE = "该服务尚未开通";
+    /** 无可用子项时的归一提示(§4.5)。 */
+    private static final String NO_ITEMS_MESSAGE = "次数已用完";
+
+    private static final int DETECTION_TYPE_NORMAL = 0;
+    private static final int DETECTION_TYPE_CANCER = 3;
+
     /** 视频路径:AIBMP=1、AIBMP-PRO=2(§3.4)。 */
     private static final int INSPECTION_TYPE_AIBMP = 1;
     private static final int INSPECTION_TYPE_AIBMP_PRO = 2;
 
+    /** 网关:签名/令牌/转发统一收口,字段非 final 便于 Mockito mock 单测。 */
     @Resource
     private AicdsGatewayService aicdsGatewayService;
 
+    /** 本地幂等映射表(aiyunyi_mapping)。 */
+    @Resource
+    private AiYunyiMappingMapper aiyunyiMappingMapper;
+
     /**
      * 构造器注入网关,使宿主可在纯单测中以 Mockito mock 注入(§8 mock gateway)。
-     * 单构造器同时满足 Spring 自动装配。
+     * 同时满足 Spring 自动装配。
      */
     public AicdsDetectionService(AicdsGatewayService aicdsGatewayService) {
         this.aicdsGatewayService = aicdsGatewayService;
     }
 
+    /** 无参构造器:便于纯反射单测(无 Spring 上下文)直接构造宿主。 */
+    public AicdsDetectionService() {
+    }
+
+    /**
+     * 照片路径主流程入口(对应 POST /api/aiyunyi/detect)。
+     *
+     * <p>request 可含:memberId / familyId / inspectionType / accessToken / userId 及 5 组素材 URL 列表。</p>
+     */
+    public Map<String, Object> detect(Map<String, Object> request) {
+        Map<String, Object> input = request == null ? Collections.<String, Object>emptyMap() : request;
+        Map<String, Object> result = new LinkedHashMap<String, Object>();
+
+        String accessToken = text(input.get("accessToken"));
+        String userId = text(input.get("userId"));
+        int inspectionType = intValue(input.get("inspectionType"));
+        long memberId = longValue(input.get("memberId"));
+        long familyId = longValue(input.get("familyId"));
+
+        // 1) 登录:换取业务 accessToken
+        Map<String, Object> login = identify(input, accessToken, userId);
+        String bizToken = text(login.get("accessToken"));
+        if (isBlank(bizToken)) {
+            bizToken = accessToken;
+        }
+
+        // 2) 商品列表:空则归一提示
+        Map<String, Object> spuPage = spuPage(input, bizToken, userId);
+        if (isEmpty(spuPage)) {
+            result.put("message", NO_SPU_MESSAGE);
+            return result;
+        }
+
+        // 3) 商品明细
+        Map<String, Object> detail = getDetail(spuPage, bizToken, userId);
+
+        // 4) 下单
+        Map<String, Object> order = orderCreate(detail, bizToken, userId);
+
+        // 5) 建检测人
+        Map<String, Object> createdUser = detectionUserCreate(input, order, bizToken, userId);
+        long detectionUserId = longValue(createdUser.get("detectionUserId"));
+        long detectionReportUserId = longValue(createdUser.get("detectionReportUserId"));
+
+        // 6) 激活检测人
+        enterDetectionUser(detectionUserId, bizToken, userId);
+
+        // 7) 套餐分页
+        Map<String, Object> packagePage = packagePage(createdUser, bizToken, userId);
+
+        // 8) 套餐子项:无可用则归一提示
+        Map<String, Object> items = getItems(packagePage, bizToken, userId);
+        if (isEmpty(items)) {
+            result.put("message", NO_ITEMS_MESSAGE);
+            return result;
+        }
+        long detectionPackageId = longValue(items.get("detectionPackageId"));
+        long detectionPackageItemId = longValue(items.get("detectionPackageItemId"));
+
+        // 幂等映射:同一成员重复识别复用已建检测人/未用子项
+        AiYunyiMapping mapping = findOrCreateMapping(memberId, familyId, detectionUserId,
+                detectionPackageId, detectionPackageItemId, inspectionType, 0);
+        result.put("mappingId", mapping == null ? 0L : mapping.getId());
+
+        // 9) 分流:照片录入数据,视频先取检测页
+        String route = resolveRoute(inspectionType);
+        if ("path".equals(route)) {
+            Map<String, Object> path = getPath(detectionUserId, detectionPackageItemId, bizToken, userId);
+            result.put("path", path);
+        } else {
+            int requestType = inspectionType == DETECTION_TYPE_CANCER ? DETECTION_TYPE_CANCER : DETECTION_TYPE_NORMAL;
+            Map<String, Object> payload = buildEnterDetectionDataRequest(detectionUserId, detectionReportUserId,
+                    detectionPackageId, detectionPackageItemId,
+                    list(input.get("basicUrls")), list(input.get("reportUrls")),
+                    list(input.get("familyHistoryVoiceUrls")), list(input.get("diseaseVoiceUrls")),
+                    list(input.get("attachmentUrls")), requestType);
+            Map<String, Object> entered = enterDetectionData(payload, bizToken, userId);
+            result.put("entered", entered);
+        }
+
+        // 10) 拉取报告(异步生成)
+        Map<String, Object> report = reportGet(detectionUserId, detectionPackageItemId, bizToken, userId);
+        result.put("report", report);
+        return result;
+    }
+
+    /**
+     * 检测类型分流(§3.4):0/3 走录入检测数据,1/2 走取 H5 检测页。
+     */
+    public String resolveRoute(int inspectionType) {
+        if (inspectionType == DETECTION_TYPE_NORMAL || inspectionType == DETECTION_TYPE_CANCER) {
+            return "data";
+        }
+        return "path";
+    }
+
+    /**
+     * 查找或创建本地幂等映射(§3.5):同一成员/家庭/检测类型复用已有记录。
+     */
+    public AiYunyiMapping findOrCreateMapping(long memberId, long familyId, long detectionUserId,
+                                              long detectionPackageId, long detectionPackageItemId,
+                                              int inspectionType, int status) {
+        if (aiyunyiMappingMapper == null) {
+            return null;
+        }
+        QueryWrapper<AiYunyiMapping> query = new QueryWrapper<AiYunyiMapping>();
+        query.eq("member_id", memberId).eq("family_id", familyId)
+                .eq("aiyunyi_inspection_type", inspectionType);
+        AiYunyiMapping existing = aiyunyiMappingMapper.selectOne(query);
+        if (existing != null) {
+            existing.setAiyunyiDetectionUserId(detectionUserId);
+            existing.setAiyunyiPackageId(detectionPackageId);
+            existing.setAiyunyiPackageItemId(detectionPackageItemId);
+            existing.setStatus(status);
+            aiyunyiMappingMapper.updateById(existing);
+            return existing;
+        }
+        AiYunyiMapping mapping = new AiYunyiMapping();
+        mapping.setMemberId(memberId);
+        mapping.setFamilyId(familyId);
+        mapping.setAiyunyiDetectionUserId(detectionUserId);
+        mapping.setAiyunyiPackageId(detectionPackageId);
+        mapping.setAiyunyiPackageItemId(detectionPackageItemId);
+        mapping.setAiyunyiInspectionType(inspectionType);
+        mapping.setStatus(status);
+        aiyunyiMappingMapper.insert(mapping);
+        return mapping;
+    }
+
+    /**
+     * 构造录入检测数据请求体(契约 §A.4)。
+     *
+     * <p>basicUrlList 固定 12 项(id=index、type=0、isQualified 留空);
+     * reportUrlList type=3;家族病史语音 type=1;已知病症语音 type=2;体表异常 type=4;
+     * request.type 仅允许 0(普通)/3(癌症),视频类型快速失败。</p>
+     */
+    public Map<String, Object> buildEnterDetectionDataRequest(long detectionUserId,
+                                                              long detectionReportUserId,
+                                                              long detectionPackageId,
+                                                              long detectionPackageItemId,
+                                                              List<String> basicUrls,
+                                                              List<String> reportUrls,
+                                                              List<String> familyHistoryVoiceUrls,
+                                                              List<String> diseaseVoiceUrls,
+                                                              List<String> attachmentUrls,
+                                                              int type) {
+        if (type != DETECTION_TYPE_NORMAL && type != DETECTION_TYPE_CANCER) {
+            throw new IllegalArgumentException(
+                    "爱云医录入检测数据 type 仅允许 0(普通)/3(癌症),实际 " + type);
+        }
+
+        Map<String, Object> request = new LinkedHashMap<String, Object>();
+        request.put("detectionUserId", detectionUserId);
+        request.put("detectionReportUserId", detectionReportUserId);
+        request.put("detectionPackageId", detectionPackageId);
+        request.put("detectionPackageItemId", detectionPackageItemId);
+        request.put("basicUrlList", buildUrlItems(basicUrls, DETECTION_TYPE_NORMAL, true));
+        request.put("familyHistoryUrlList", buildUrlItems(familyHistoryVoiceUrls, 1, false));
+        request.put("diseaseUrlList", buildUrlItems(diseaseVoiceUrls, 2, false));
+        request.put("reportUrlList", buildUrlItems(reportUrls, DETECTION_TYPE_CANCER, false));
+        request.put("attachmentUrlList", buildUrlItems(attachmentUrls, 4, false));
+        request.put("type", type);
+        return request;
+    }
+
+    // ==================== 视频分支(ai.aiyunyi.detectVideo,S-cfc-473) ====================
+
     /**
      * AC3/AC4:取视频检测 H5 页地址。两个必填 ID 原样透传给网关 getPath,
      * 返回响应中的 {@code data.path},不做改写、截断或默认填空串。
@@ -76,19 +261,138 @@ public class AicdsDetectionService {
     }
 
     /**
-     * AC6:web-view 采集完成后的收尾——先轮询 {@code package/page} 确认完成,
-     * 再调 {@code report/get} 拉报告。顺序不可颠倒;网关异常不在此吞掉。
+     * AC6:web-view 采集完成后的收尾——先轮询 packagePage 确认完成,
+     * 再调 reportGet 拉报告。顺序不可颠倒;网关异常不在此吞掉。
      */
     public Object getReportAfterVideoDetect(long packageId) {
         aicdsGatewayService.getPackagePage(packageId);
         return aicdsGatewayService.getReport(packageId);
     }
 
-    private static void requireNonBlankPath(String path) {
-        if (path == null || path.trim().isEmpty()) {
-            throw new IllegalStateException(
-                    "爱云医视频检测 getPath 返回空白 data.path,禁止静默返回空 URL 导致 web-view 白屏(§4.5)");
+    // ==================== 照片编排步骤(顺序与 §5 时序一致) ====================
+
+    private Map<String, Object> identify(Map<String, Object> input, String accessToken, String userId) {
+        Map<String, Object> body = new LinkedHashMap<String, Object>();
+        body.put("appKey", text(input.get("appKey")));
+        return invoke("/v1/identify", body, accessToken, userId);
+    }
+
+    private Map<String, Object> spuPage(Map<String, Object> input, String accessToken, String userId) {
+        Map<String, Object> body = new LinkedHashMap<String, Object>();
+        body.put("inspectionType", intValue(input.get("inspectionType")));
+        return invoke("/v1/spu/page", body, accessToken, userId);
+    }
+
+    private Map<String, Object> getDetail(Map<String, Object> spuPage, String accessToken, String userId) {
+        Map<String, Object> body = new LinkedHashMap<String, Object>();
+        body.put("spuId", spuPage.get("spuId"));
+        return invoke("/v1/spu/get-detail", body, accessToken, userId);
+    }
+
+    private Map<String, Object> orderCreate(Map<String, Object> detail, String accessToken, String userId) {
+        Map<String, Object> body = new LinkedHashMap<String, Object>();
+        body.put("spuId", detail.get("spuId"));
+        return invoke("/v1/order/create", body, accessToken, userId);
+    }
+
+    private Map<String, Object> detectionUserCreate(Map<String, Object> input, Map<String, Object> order,
+                                                    String accessToken, String userId) {
+        Map<String, Object> body = new LinkedHashMap<String, Object>();
+        body.put("memberId", input.get("memberId"));
+        body.put("orderId", order.get("orderId"));
+        return invoke("/v1/detection-user/create", body, accessToken, userId);
+    }
+
+    private Map<String, Object> enterDetectionUser(long detectionUserId, String accessToken, String userId) {
+        Map<String, Object> body = new LinkedHashMap<String, Object>();
+        body.put("detectionUserId", detectionUserId);
+        return invoke("/v1/enter/detection_user", body, accessToken, userId);
+    }
+
+    private Map<String, Object> packagePage(Map<String, Object> createdUser, String accessToken, String userId) {
+        Map<String, Object> body = new LinkedHashMap<String, Object>();
+        body.put("detectionUserId", createdUser.get("detectionUserId"));
+        return invoke("/v1/package/page", body, accessToken, userId);
+    }
+
+    private Map<String, Object> getItems(Map<String, Object> packagePage, String accessToken, String userId) {
+        Map<String, Object> body = new LinkedHashMap<String, Object>();
+        body.put("packageId", packagePage.get("packageId"));
+        return invoke("/v1/package/get-items", body, accessToken, userId);
+    }
+
+    private Map<String, Object> getPath(long detectionUserId, long packageItemId,
+                                        String accessToken, String userId) {
+        Map<String, Object> body = new LinkedHashMap<String, Object>();
+        body.put("detectionUserId", detectionUserId);
+        body.put("packageItemId", packageItemId);
+        return invoke("/v1/get-path", body, accessToken, userId);
+    }
+
+    private Map<String, Object> enterDetectionData(Map<String, Object> payload,
+                                                   String accessToken, String userId) {
+        return invoke("/v1/enter/detection_data", payload, accessToken, userId);
+    }
+
+    private Map<String, Object> reportGet(long detectionUserId, long packageItemId,
+                                          String accessToken, String userId) {
+        Map<String, Object> body = new LinkedHashMap<String, Object>();
+        body.put("detectionUserId", detectionUserId);
+        body.put("packageItemId", packageItemId);
+        return invoke("/v1/report/get", body, accessToken, userId);
+    }
+
+    /** 统一经网关转发(鉴权/熔断/超时由网关负责)。 */
+    @SuppressWarnings("unchecked")
+    private Map<String, Object> invoke(String path, Object body, String accessToken, String userId) {
+        if (aicdsGatewayService == null) {
+            return new LinkedHashMap<String, Object>();
         }
+        ResponseEntity<Map> response = aicdsGatewayService.exchange(path, body, Map.class, accessToken, userId);
+        if (response == null || response.getBody() == null) {
+            return new LinkedHashMap<String, Object>();
+        }
+        return response.getBody();
+    }
+
+    // ==================== 辅助 ====================
+
+    private static List<Map<String, Object>> buildUrlItems(List<String> urls, int type, boolean withIdAndQualified) {
+        List<Map<String, Object>> items = new ArrayList<Map<String, Object>>();
+        if (urls == null || urls.isEmpty()) {
+            return items;
+        }
+        for (int i = 0; i < urls.size(); i++) {
+            Map<String, Object> item = new LinkedHashMap<String, Object>();
+            if (withIdAndQualified) {
+                item.put("id", i);
+                item.put("isQualified", null);
+            }
+            item.put("url", urls.get(i));
+            item.put("type", type);
+            items.add(item);
+        }
+        return items;
+    }
+
+    @SuppressWarnings("unchecked")
+    private static List<String> list(Object value) {
+        if (value instanceof List) {
+            return (List<String>) value;
+        }
+        return Collections.emptyList();
+    }
+
+    private static String text(Object value) {
+        return value == null ? null : value.toString();
+    }
+
+    private static boolean isBlank(String value) {
+        return value == null || value.trim().isEmpty();
+    }
+
+    private static long longValue(Object value) {
+        return value instanceof Number ? ((Number) value).longValue() : 0L;
     }
 
     private static int intValue(Object value) {
@@ -104,4 +408,15 @@ public class AicdsDetectionService {
         }
         return -1;
     }
+
+    private static boolean isEmpty(Map<String, Object> value) {
+        return value == null || value.isEmpty();
+    }
+
+    private static void requireNonBlankPath(String path) {
+        if (path == null || path.trim().isEmpty()) {
+            throw new IllegalStateException(
+                    "爱云医视频检测 getPath 返回空白 data.path,禁止静默返回空 URL 导致 web-view 白屏(§4.5)");
+        }
+    }
 }