AicdsDetectionService.java 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438
  1. package com.etotem.cfc.service;
  2. import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
  3. import com.etotem.cfc.entity.AiYunyiMapping;
  4. import com.etotem.cfc.mapper.AiYunyiMappingMapper;
  5. import org.springframework.http.ResponseEntity;
  6. import org.springframework.stereotype.Service;
  7. import org.springframework.web.multipart.MultipartFile;
  8. import javax.annotation.Resource;
  9. import java.util.ArrayList;
  10. import java.util.Collections;
  11. import java.util.LinkedHashMap;
  12. import java.util.List;
  13. import java.util.Map;
  14. /**
  15. * 爱云医 AI 检测编排宿主:照片路径(能力键 {@code ai.aiyunyi.detect},S-cfc-472)
  16. * 与视频路径(能力键 {@code ai.aiyunyi.detectVideo},S-cfc-473)共用同一编排宿主。
  17. *
  18. * <p>服务端统一收口鉴权与转发:私钥/令牌只在 {@link AicdsGatewayService} 内使用,前端仅带小程序 token。
  19. * 本类负责把「登录 → 商品 → 下单 → 建检测人 → 激活 → 套餐子项 → 录入数据 → 报告」串成一条链路,
  20. * 并通过 {@code aiyunyi_mapping} 映射保证同一成员重复识别幂等;视频类型另取 H5 检测页地址。</p>
  21. */
  22. @Service
  23. public class AicdsDetectionService {
  24. /** 商品列表为空时的归一提示(§4.5)。 */
  25. private static final String NO_SPU_MESSAGE = "该服务尚未开通";
  26. /** 无可用子项时的归一提示(§4.5)。 */
  27. private static final String NO_ITEMS_MESSAGE = "次数已用完";
  28. private static final int DETECTION_TYPE_NORMAL = 0;
  29. private static final int DETECTION_TYPE_CANCER = 3;
  30. /** 视频路径:AIBMP=1、AIBMP-PRO=2(§3.4)。 */
  31. private static final int INSPECTION_TYPE_AIBMP = 1;
  32. private static final int INSPECTION_TYPE_AIBMP_PRO = 2;
  33. /** 网关:签名/令牌/转发统一收口,字段非 final 便于 Mockito mock 单测。 */
  34. @Resource
  35. private AicdsGatewayService aicdsGatewayService;
  36. /** 本地幂等映射表(aiyunyi_mapping)。 */
  37. @Resource
  38. private AiYunyiMappingMapper aiyunyiMappingMapper;
  39. /**
  40. * 构造器注入网关,使宿主可在纯单测中以 Mockito mock 注入(§8 mock gateway)。
  41. * 同时满足 Spring 自动装配。
  42. */
  43. public AicdsDetectionService(AicdsGatewayService aicdsGatewayService) {
  44. this.aicdsGatewayService = aicdsGatewayService;
  45. }
  46. /** 无参构造器:便于纯反射单测(无 Spring 上下文)直接构造宿主。 */
  47. public AicdsDetectionService() {
  48. }
  49. /**
  50. * 照片路径主流程入口(对应 POST /api/aiyunyi/detect)。
  51. *
  52. * <p>request 可含:memberId / familyId / inspectionType / accessToken / userId 及 5 组素材 URL 列表。</p>
  53. */
  54. public Map<String, Object> detect(Map<String, Object> request) {
  55. Map<String, Object> input = request == null ? Collections.<String, Object>emptyMap() : request;
  56. Map<String, Object> result = new LinkedHashMap<String, Object>();
  57. String accessToken = text(input.get("accessToken"));
  58. String userId = text(input.get("userId"));
  59. int inspectionType = intValue(input.get("inspectionType"));
  60. long memberId = longValue(input.get("memberId"));
  61. long familyId = longValue(input.get("familyId"));
  62. // 1) 登录:换取业务 accessToken
  63. Map<String, Object> login = identify(input, accessToken, userId);
  64. String bizToken = text(login.get("accessToken"));
  65. if (isBlank(bizToken)) {
  66. bizToken = accessToken;
  67. }
  68. // 2) 商品列表:空则归一提示
  69. Map<String, Object> spuPage = spuPage(input, bizToken, userId);
  70. if (isEmpty(spuPage)) {
  71. result.put("message", NO_SPU_MESSAGE);
  72. return result;
  73. }
  74. // 3) 商品明细
  75. Map<String, Object> detail = getDetail(spuPage, bizToken, userId);
  76. // 4) 下单
  77. Map<String, Object> order = orderCreate(detail, bizToken, userId);
  78. // 5) 建检测人
  79. Map<String, Object> createdUser = detectionUserCreate(input, order, bizToken, userId);
  80. long detectionUserId = longValue(createdUser.get("detectionUserId"));
  81. long detectionReportUserId = longValue(createdUser.get("detectionReportUserId"));
  82. // 6) 激活检测人
  83. enterDetectionUser(detectionUserId, bizToken, userId);
  84. // 7) 套餐分页
  85. Map<String, Object> packagePage = packagePage(createdUser, bizToken, userId);
  86. // 8) 套餐子项:无可用则归一提示
  87. Map<String, Object> items = getItems(packagePage, bizToken, userId);
  88. if (isEmpty(items)) {
  89. result.put("message", NO_ITEMS_MESSAGE);
  90. return result;
  91. }
  92. long detectionPackageId = longValue(items.get("detectionPackageId"));
  93. long detectionPackageItemId = longValue(items.get("detectionPackageItemId"));
  94. // 幂等映射:同一成员重复识别复用已建检测人/未用子项
  95. AiYunyiMapping mapping = findOrCreateMapping(memberId, familyId, detectionUserId,
  96. detectionPackageId, detectionPackageItemId, inspectionType, 0);
  97. result.put("mappingId", mapping == null ? 0L : mapping.getId());
  98. // 9) 分流:照片录入数据,视频先取检测页
  99. String route = resolveRoute(inspectionType);
  100. if ("path".equals(route)) {
  101. Map<String, Object> path = getPath(detectionUserId, detectionPackageItemId, bizToken, userId);
  102. result.put("path", path);
  103. } else {
  104. int requestType = inspectionType == DETECTION_TYPE_CANCER ? DETECTION_TYPE_CANCER : DETECTION_TYPE_NORMAL;
  105. Map<String, Object> payload = buildEnterDetectionDataRequest(detectionUserId, detectionReportUserId,
  106. detectionPackageId, detectionPackageItemId,
  107. list(input.get("basicUrls")), list(input.get("reportUrls")),
  108. list(input.get("familyHistoryVoiceUrls")), list(input.get("diseaseVoiceUrls")),
  109. list(input.get("attachmentUrls")), requestType);
  110. Map<String, Object> entered = enterDetectionData(payload, bizToken, userId);
  111. result.put("entered", entered);
  112. }
  113. // 10) 拉取报告(异步生成)
  114. Map<String, Object> report = reportGet(detectionUserId, detectionPackageItemId, bizToken, userId);
  115. result.put("report", report);
  116. return result;
  117. }
  118. /**
  119. * 检测类型分流(§3.4):0/3 走录入检测数据,1/2 走取 H5 检测页。
  120. */
  121. public String resolveRoute(int inspectionType) {
  122. if (inspectionType == DETECTION_TYPE_NORMAL || inspectionType == DETECTION_TYPE_CANCER) {
  123. return "data";
  124. }
  125. return "path";
  126. }
  127. /**
  128. * 查找或创建本地幂等映射(§3.5):同一成员/家庭/检测类型复用已有记录。
  129. */
  130. public AiYunyiMapping findOrCreateMapping(long memberId, long familyId, long detectionUserId,
  131. long detectionPackageId, long detectionPackageItemId,
  132. int inspectionType, int status) {
  133. if (aiyunyiMappingMapper == null) {
  134. return null;
  135. }
  136. QueryWrapper<AiYunyiMapping> query = new QueryWrapper<AiYunyiMapping>();
  137. query.eq("member_id", memberId).eq("family_id", familyId)
  138. .eq("aiyunyi_inspection_type", inspectionType);
  139. AiYunyiMapping existing = aiyunyiMappingMapper.selectOne(query);
  140. if (existing != null) {
  141. existing.setAiyunyiDetectionUserId(detectionUserId);
  142. existing.setAiyunyiPackageId(detectionPackageId);
  143. existing.setAiyunyiPackageItemId(detectionPackageItemId);
  144. existing.setStatus(status);
  145. aiyunyiMappingMapper.updateById(existing);
  146. return existing;
  147. }
  148. AiYunyiMapping mapping = new AiYunyiMapping();
  149. mapping.setMemberId(memberId);
  150. mapping.setFamilyId(familyId);
  151. mapping.setAiyunyiDetectionUserId(detectionUserId);
  152. mapping.setAiyunyiPackageId(detectionPackageId);
  153. mapping.setAiyunyiPackageItemId(detectionPackageItemId);
  154. mapping.setAiyunyiInspectionType(inspectionType);
  155. mapping.setStatus(status);
  156. aiyunyiMappingMapper.insert(mapping);
  157. return mapping;
  158. }
  159. /**
  160. * 构造录入检测数据请求体(契约 §A.4)。
  161. *
  162. * <p>basicUrlList 固定 12 项(id=index、type=0、isQualified 留空);
  163. * reportUrlList type=3;家族病史语音 type=1;已知病症语音 type=2;体表异常 type=4;
  164. * request.type 仅允许 0(普通)/3(癌症),视频类型快速失败。</p>
  165. */
  166. public Map<String, Object> buildEnterDetectionDataRequest(long detectionUserId,
  167. long detectionReportUserId,
  168. long detectionPackageId,
  169. long detectionPackageItemId,
  170. List<String> basicUrls,
  171. List<String> reportUrls,
  172. List<String> familyHistoryVoiceUrls,
  173. List<String> diseaseVoiceUrls,
  174. List<String> attachmentUrls,
  175. int type) {
  176. if (type != DETECTION_TYPE_NORMAL && type != DETECTION_TYPE_CANCER) {
  177. throw new IllegalArgumentException(
  178. "爱云医录入检测数据 type 仅允许 0(普通)/3(癌症),实际 " + type);
  179. }
  180. Map<String, Object> request = new LinkedHashMap<String, Object>();
  181. request.put("detectionUserId", detectionUserId);
  182. request.put("detectionReportUserId", detectionReportUserId);
  183. request.put("detectionPackageId", detectionPackageId);
  184. request.put("detectionPackageItemId", detectionPackageItemId);
  185. request.put("basicUrlList", buildUrlItems(basicUrls, DETECTION_TYPE_NORMAL, true));
  186. request.put("familyHistoryUrlList", buildUrlItems(familyHistoryVoiceUrls, 1, false));
  187. request.put("diseaseUrlList", buildUrlItems(diseaseVoiceUrls, 2, false));
  188. request.put("reportUrlList", buildUrlItems(reportUrls, DETECTION_TYPE_CANCER, false));
  189. request.put("attachmentUrlList", buildUrlItems(attachmentUrls, 4, false));
  190. request.put("type", type);
  191. return request;
  192. }
  193. // ==================== 视频分支(ai.aiyunyi.detectVideo,S-cfc-473) ====================
  194. /**
  195. * AC3/AC4:取视频检测 H5 页地址。两个必填 ID 原样透传给网关 getPath,
  196. * 返回响应中的 {@code data.path},不做改写、截断或默认填空串。
  197. */
  198. public String detectVideo(long detectionPackageItemId, long detectionReportUserId) {
  199. Object response = aicdsGatewayService.getPath(detectionPackageItemId, detectionReportUserId);
  200. // 兼容网关直接返回 path 字符串的调用形态(code 缺省视为 0)。
  201. if (response instanceof CharSequence) {
  202. String directPath = response.toString();
  203. requireNonBlankPath(directPath);
  204. return directPath;
  205. }
  206. if (!(response instanceof Map)) {
  207. throw new IllegalStateException(
  208. "爱云医视频检测 getPath 响应为空或格式非法,无法取得检测页面地址(§4.5)");
  209. }
  210. Map<?, ?> body = (Map<?, ?>) response;
  211. int code = intValue(body.get("code"));
  212. if (code != 0) {
  213. throw new IllegalStateException(
  214. "爱云医视频检测 getPath 失败,code=" + code + "(§4.5 错误归一)");
  215. }
  216. Object data = body.get("data");
  217. Object path = (data instanceof Map) ? ((Map<?, ?>) data).get("path") : null;
  218. if (path == null) {
  219. throw new IllegalStateException(
  220. "爱云医视频检测 getPath 响应缺少 data.path,禁止返回空 URL(§A.5)");
  221. }
  222. String h5Path = path.toString();
  223. requireNonBlankPath(h5Path);
  224. return h5Path;
  225. }
  226. /** AC5:仅 1(AIBMP)/2(AIBMP-PRO) 走视频 getPath 路径;0/3 及非法值均返回 false。 */
  227. public boolean isVideoInspectionType(int inspectionType) {
  228. return inspectionType == INSPECTION_TYPE_AIBMP
  229. || inspectionType == INSPECTION_TYPE_AIBMP_PRO;
  230. }
  231. /**
  232. * AC6:web-view 采集完成后的收尾——先轮询 packagePage 确认完成,
  233. * 再调 reportGet 拉报告。顺序不可颠倒;网关异常不在此吞掉。
  234. */
  235. public Object getReportAfterVideoDetect(long packageId) {
  236. aicdsGatewayService.getPackagePage(packageId);
  237. return aicdsGatewayService.getReport(packageId);
  238. }
  239. // ==================== 照片编排步骤(顺序与 §5 时序一致) ====================
  240. private Map<String, Object> identify(Map<String, Object> input, String accessToken, String userId) {
  241. Map<String, Object> body = new LinkedHashMap<String, Object>();
  242. body.put("appKey", text(input.get("appKey")));
  243. return invoke("/v1/identify", body, accessToken, userId);
  244. }
  245. private Map<String, Object> spuPage(Map<String, Object> input, String accessToken, String userId) {
  246. Map<String, Object> body = new LinkedHashMap<String, Object>();
  247. body.put("inspectionType", intValue(input.get("inspectionType")));
  248. return invoke("/v1/spu/page", body, accessToken, userId);
  249. }
  250. private Map<String, Object> getDetail(Map<String, Object> spuPage, String accessToken, String userId) {
  251. Map<String, Object> body = new LinkedHashMap<String, Object>();
  252. body.put("spuId", spuPage.get("spuId"));
  253. return invoke("/v1/spu/get-detail", body, accessToken, userId);
  254. }
  255. private Map<String, Object> orderCreate(Map<String, Object> detail, String accessToken, String userId) {
  256. Map<String, Object> body = new LinkedHashMap<String, Object>();
  257. body.put("spuId", detail.get("spuId"));
  258. return invoke("/v1/order/create", body, accessToken, userId);
  259. }
  260. private Map<String, Object> detectionUserCreate(Map<String, Object> input, Map<String, Object> order,
  261. String accessToken, String userId) {
  262. Map<String, Object> body = new LinkedHashMap<String, Object>();
  263. body.put("memberId", input.get("memberId"));
  264. body.put("orderId", order.get("orderId"));
  265. return invoke("/v1/detection-user/create", body, accessToken, userId);
  266. }
  267. private Map<String, Object> enterDetectionUser(long detectionUserId, String accessToken, String userId) {
  268. Map<String, Object> body = new LinkedHashMap<String, Object>();
  269. body.put("detectionUserId", detectionUserId);
  270. return invoke("/v1/enter/detection_user", body, accessToken, userId);
  271. }
  272. private Map<String, Object> packagePage(Map<String, Object> createdUser, String accessToken, String userId) {
  273. Map<String, Object> body = new LinkedHashMap<String, Object>();
  274. body.put("detectionUserId", createdUser.get("detectionUserId"));
  275. return invoke("/v1/package/page", body, accessToken, userId);
  276. }
  277. private Map<String, Object> getItems(Map<String, Object> packagePage, String accessToken, String userId) {
  278. Map<String, Object> body = new LinkedHashMap<String, Object>();
  279. body.put("packageId", packagePage.get("packageId"));
  280. return invoke("/v1/package/get-items", body, accessToken, userId);
  281. }
  282. private Map<String, Object> getPath(long detectionUserId, long packageItemId,
  283. String accessToken, String userId) {
  284. Map<String, Object> body = new LinkedHashMap<String, Object>();
  285. body.put("detectionUserId", detectionUserId);
  286. body.put("packageItemId", packageItemId);
  287. return invoke("/v1/get-path", body, accessToken, userId);
  288. }
  289. private Map<String, Object> enterDetectionData(Map<String, Object> payload,
  290. String accessToken, String userId) {
  291. return invoke("/v1/enter/detection_data", payload, accessToken, userId);
  292. }
  293. private Map<String, Object> reportGet(long detectionUserId, long packageItemId,
  294. String accessToken, String userId) {
  295. Map<String, Object> body = new LinkedHashMap<String, Object>();
  296. body.put("detectionUserId", detectionUserId);
  297. body.put("packageItemId", packageItemId);
  298. return invoke("/v1/report/get", body, accessToken, userId);
  299. }
  300. /** 统一经网关转发(鉴权/熔断/超时由网关负责)。 */
  301. @SuppressWarnings("unchecked")
  302. private Map<String, Object> invoke(String path, Object body, String accessToken, String userId) {
  303. if (aicdsGatewayService == null) {
  304. return new LinkedHashMap<String, Object>();
  305. }
  306. ResponseEntity<Map> response = aicdsGatewayService.exchange(path, body, Map.class, accessToken, userId);
  307. if (response == null || response.getBody() == null) {
  308. return new LinkedHashMap<String, Object>();
  309. }
  310. return response.getBody();
  311. }
  312. // ==================== 辅助 ====================
  313. private static List<Map<String, Object>> buildUrlItems(List<String> urls, int type, boolean withIdAndQualified) {
  314. List<Map<String, Object>> items = new ArrayList<Map<String, Object>>();
  315. if (urls == null || urls.isEmpty()) {
  316. return items;
  317. }
  318. for (int i = 0; i < urls.size(); i++) {
  319. Map<String, Object> item = new LinkedHashMap<String, Object>();
  320. if (withIdAndQualified) {
  321. item.put("id", i);
  322. item.put("isQualified", null);
  323. }
  324. item.put("url", urls.get(i));
  325. item.put("type", type);
  326. items.add(item);
  327. }
  328. return items;
  329. }
  330. @SuppressWarnings("unchecked")
  331. private static List<String> list(Object value) {
  332. if (value instanceof List) {
  333. return (List<String>) value;
  334. }
  335. return Collections.emptyList();
  336. }
  337. private static String text(Object value) {
  338. return value == null ? null : value.toString();
  339. }
  340. private static boolean isBlank(String value) {
  341. return value == null || value.trim().isEmpty();
  342. }
  343. private static long longValue(Object value) {
  344. return value instanceof Number ? ((Number) value).longValue() : 0L;
  345. }
  346. private static int intValue(Object value) {
  347. if (value instanceof Number) {
  348. return ((Number) value).intValue();
  349. }
  350. if (value instanceof CharSequence) {
  351. try {
  352. return Integer.parseInt(value.toString().trim());
  353. } catch (NumberFormatException ignored) {
  354. return -1;
  355. }
  356. }
  357. return -1;
  358. }
  359. private static boolean isEmpty(Map<String, Object> value) {
  360. return value == null || value.isEmpty();
  361. }
  362. private static void requireNonBlankPath(String path) {
  363. if (path == null || path.trim().isEmpty()) {
  364. throw new IllegalStateException(
  365. "爱云医视频检测 getPath 返回空白 data.path,禁止静默返回空 URL 导致 web-view 白屏(§4.5)");
  366. }
  367. }
  368. /**
  369. * 照片上传(能力键 {@code ai.aiyunyi.upload},S-cfc-496):经网关转发到平台 uploadFile
  370. * 拿图片 URL,供前端「AI 快速识别」在提交检测数据前使用(§3.3 / §4.1)。
  371. *
  372. * @param file 待上传照片(必填)
  373. * @param path 存储路径/文件名(选填)
  374. * @return 平台返回的图片 URL
  375. */
  376. public String uploadFile(MultipartFile file, String path) {
  377. if (aicdsGatewayService == null) {
  378. throw new IllegalStateException("爱云医网关未注入,无法上传照片(B.7)");
  379. }
  380. return aicdsGatewayService.uploadFile(file, path);
  381. }
  382. }