| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438 |
- 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 org.springframework.web.multipart.MultipartFile;
- 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.detect},S-cfc-472)
- * 与视频路径(能力键 {@code ai.aiyunyi.detectVideo},S-cfc-473)共用同一编排宿主。
- *
- * <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 自动装配。
- */
- 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},不做改写、截断或默认填空串。
- */
- public String detectVideo(long detectionPackageItemId, long detectionReportUserId) {
- Object response = aicdsGatewayService.getPath(detectionPackageItemId, detectionReportUserId);
- // 兼容网关直接返回 path 字符串的调用形态(code 缺省视为 0)。
- if (response instanceof CharSequence) {
- String directPath = response.toString();
- requireNonBlankPath(directPath);
- return directPath;
- }
- if (!(response instanceof Map)) {
- throw new IllegalStateException(
- "爱云医视频检测 getPath 响应为空或格式非法,无法取得检测页面地址(§4.5)");
- }
- Map<?, ?> body = (Map<?, ?>) response;
- int code = intValue(body.get("code"));
- if (code != 0) {
- throw new IllegalStateException(
- "爱云医视频检测 getPath 失败,code=" + code + "(§4.5 错误归一)");
- }
- Object data = body.get("data");
- Object path = (data instanceof Map) ? ((Map<?, ?>) data).get("path") : null;
- if (path == null) {
- throw new IllegalStateException(
- "爱云医视频检测 getPath 响应缺少 data.path,禁止返回空 URL(§A.5)");
- }
- String h5Path = path.toString();
- requireNonBlankPath(h5Path);
- return h5Path;
- }
- /** AC5:仅 1(AIBMP)/2(AIBMP-PRO) 走视频 getPath 路径;0/3 及非法值均返回 false。 */
- public boolean isVideoInspectionType(int inspectionType) {
- return inspectionType == INSPECTION_TYPE_AIBMP
- || inspectionType == INSPECTION_TYPE_AIBMP_PRO;
- }
- /**
- * AC6:web-view 采集完成后的收尾——先轮询 packagePage 确认完成,
- * 再调 reportGet 拉报告。顺序不可颠倒;网关异常不在此吞掉。
- */
- public Object getReportAfterVideoDetect(long packageId) {
- aicdsGatewayService.getPackagePage(packageId);
- return aicdsGatewayService.getReport(packageId);
- }
- // ==================== 照片编排步骤(顺序与 §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) {
- if (value instanceof Number) {
- return ((Number) value).intValue();
- }
- if (value instanceof CharSequence) {
- try {
- return Integer.parseInt(value.toString().trim());
- } catch (NumberFormatException ignored) {
- return -1;
- }
- }
- 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)");
- }
- }
- /**
- * 照片上传(能力键 {@code ai.aiyunyi.upload},S-cfc-496):经网关转发到平台 uploadFile
- * 拿图片 URL,供前端「AI 快速识别」在提交检测数据前使用(§3.3 / §4.1)。
- *
- * @param file 待上传照片(必填)
- * @param path 存储路径/文件名(选填)
- * @return 平台返回的图片 URL
- */
- public String uploadFile(MultipartFile file, String path) {
- if (aicdsGatewayService == null) {
- throw new IllegalStateException("爱云医网关未注入,无法上传照片(B.7)");
- }
- return aicdsGatewayService.uploadFile(file, path);
- }
- }
|