HealthReportController.java 150 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224
  1. package com.etotem.cfc.controller;
  2. import com.etotem.cfc.common.Result;
  3. import com.etotem.cfc.common.AdminRoles;
  4. import com.etotem.cfc.service.PurchaseService;
  5. import com.etotem.cfc.service.DanReportUploadService;
  6. import com.etotem.cfc.dto.HealthAnalysisResult;
  7. import com.etotem.cfc.dto.MemberMatchResult;
  8. import com.etotem.cfc.dto.ParsedDiseaseRisk;
  9. import com.etotem.cfc.dto.ParsedGutFlora;
  10. import com.etotem.cfc.dto.ParsedIndicator;
  11. import com.etotem.cfc.dto.ParsedFoodSuitability;
  12. import com.etotem.cfc.dto.ParsedReportPayload;
  13. import com.etotem.cfc.dto.ParsedReportResult;
  14. import java.math.BigDecimal;
  15. import javax.servlet.http.HttpServletRequest;
  16. import com.etotem.cfc.entity.Food;
  17. import com.etotem.cfc.entity.FamilyMember;
  18. import com.etotem.cfc.entity.FoodRecommendIndex;
  19. import com.etotem.cfc.entity.HealthDiseaseRisk;
  20. import com.etotem.cfc.entity.HealthGutFlora;
  21. import com.etotem.cfc.entity.HealthIndicator;
  22. import com.etotem.cfc.entity.HealthReport;
  23. import com.etotem.cfc.entity.HealthReportDraft;
  24. import com.etotem.cfc.entity.DanReportUpload;
  25. import com.etotem.cfc.entity.ReportTransferRequest;
  26. import com.etotem.cfc.entity.NutritionDeficiencyRecord;
  27. import com.etotem.cfc.entity.NutritionIndicatorMapping;
  28. import com.etotem.cfc.entity.User;
  29. import com.etotem.cfc.mapper.HealthReportDraftMapper;
  30. import com.etotem.cfc.mapper.FamilyMemberMapper;
  31. import com.etotem.cfc.mapper.UserMapper;
  32. import com.etotem.cfc.service.UserService;
  33. import com.etotem.cfc.service.FamilyMemberNutritionProfileService;
  34. import com.etotem.cfc.service.DimensionScoreService;
  35. import com.etotem.cfc.service.FoodRecommendService;
  36. import com.etotem.cfc.service.FamilyFoodOverviewService;
  37. import com.etotem.cfc.service.FoodService;
  38. import com.etotem.cfc.service.HealthAnalysisService;
  39. import com.etotem.cfc.service.HealthReportDraftService;
  40. import com.etotem.cfc.service.HealthReportService;
  41. import com.etotem.cfc.service.ReportArchiveCompareService;
  42. import com.etotem.cfc.service.MemberIndicatorCurrentService;
  43. import com.etotem.cfc.service.BasicQuotaService;
  44. import com.etotem.cfc.service.NutritionDeficiencyService;
  45. import com.etotem.cfc.service.NormalizeIndicatorPipeline;
  46. import com.etotem.cfc.service.PdfParseService;
  47. import com.etotem.cfc.service.ReportCollectService;
  48. import com.etotem.cfc.service.ReportTransferService;
  49. import com.etotem.cfc.service.ReportBlockAssembler;
  50. import com.etotem.cfc.service.ReportBlockService;
  51. import com.etotem.cfc.service.StorageService;
  52. import com.etotem.cfc.service.OnboardingService;
  53. import com.etotem.cfc.service.ReportMemberPermissionService;
  54. import com.etotem.cfc.service.TongueDiagnosisService;
  55. import com.etotem.cfc.service.BasicQuotaService;
  56. import com.etotem.cfc.service.BodyFatScaleService;
  57. import com.etotem.cfc.service.api.WechatServiceInterface;
  58. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  59. import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
  60. import com.fasterxml.jackson.databind.ObjectMapper;
  61. import io.swagger.v3.oas.annotations.Operation;
  62. import io.swagger.v3.oas.annotations.tags.Tag;
  63. import lombok.extern.slf4j.Slf4j;
  64. import org.springframework.web.bind.annotation.*;
  65. import org.springframework.beans.factory.annotation.Value;
  66. import org.springframework.web.multipart.MultipartFile;
  67. import javax.annotation.Resource;
  68. import javax.servlet.http.HttpServletRequest;
  69. import java.io.File;
  70. import java.io.IOException;
  71. import java.nio.file.Files;
  72. import java.nio.file.Path;
  73. import java.nio.file.Paths;
  74. import java.util.ArrayList;
  75. import java.util.Collections;
  76. import java.util.Date;
  77. import java.util.HashMap;
  78. import java.util.HashSet;
  79. import java.util.LinkedHashMap;
  80. import java.util.List;
  81. import java.util.Map;
  82. import java.util.Set;
  83. import java.util.UUID;
  84. import org.springframework.http.ResponseEntity;
  85. import org.springframework.web.client.RestTemplate;
  86. import com.etotem.cfc.util.ParamUtils;
  87. /**
  88. * 健康检测报告接口 — 体检报告/菌群检测报告的录入与查询
  89. */
  90. @Slf4j
  91. @Tag(name = "健康检测报告", description = "健康报告上传、查询、指标明细")
  92. @RestController
  93. @RequestMapping("/api/health")
  94. public class HealthReportController {
  95. private static final String LANGGRAPH_BASE_URL = "http://localhost:9000";
  96. private static final String REPORT_PARSE_URL = LANGGRAPH_BASE_URL + "/api/v1/report/parse";
  97. /** P0-3 ③:collect/status 响应暴露 collect_validation(键名)——前端轮询时可核对 _解析自检 结果 */
  98. public static final String COLLECT_VALIDATION_KEY = "collect_validation";
  99. /**
  100. * LangGraph 服务地址(生产环境通过 application.yml 覆盖,避免 Docker 容器跨主机调用失败)
  101. * TODO(部署): 容器化部署时需确保 Java 上传目录(uploads/health-reports)
  102. * 对 LangGraph 容器可见(共享 volume 或主机路径挂载),否则 file_path 不可访问将回退本地解析。
  103. */
  104. @Value("${upload.base-dir:/data/cfc-uploads}")
  105. private String uploadBaseDir;
  106. @Value("${langgraph.base-url:http://localhost:9000}")
  107. private String langgraphBaseUrl;
  108. @Resource
  109. private HealthReportService healthReportService;
  110. @Resource
  111. private ReportTransferService reportTransferService;
  112. @Resource
  113. private PdfParseService pdfParseService;
  114. @Resource
  115. private NutritionDeficiencyService nutritionDeficiencyService;
  116. @Resource
  117. private FamilyMemberNutritionProfileService childNutritionProfileService;
  118. @Resource
  119. private HealthAnalysisService healthAnalysisService;
  120. @Resource
  121. private FoodService foodService;
  122. @Resource
  123. private HealthReportDraftService healthReportDraftService;
  124. @Resource
  125. private ObjectMapper objectMapper;
  126. @Resource
  127. private RestTemplate restTemplate;
  128. @Resource
  129. private DimensionScoreService dimensionScoreService;
  130. @Resource
  131. private TongueDiagnosisService tongueDiagnosisService;
  132. @Resource
  133. private ReportMemberPermissionService reportMemberPermissionService;
  134. @Resource
  135. private DanReportUploadService danReportUploadService;
  136. @Resource
  137. private FoodRecommendService foodRecommendService;
  138. @Resource
  139. private FamilyFoodOverviewService familyFoodOverviewService;
  140. @Resource
  141. private FamilyMemberMapper familyMemberMapper;
  142. @Resource
  143. private HealthReportDraftMapper healthReportDraftMapper;
  144. @Resource
  145. private WechatServiceInterface wechatService;
  146. @Resource
  147. private BodyFatScaleService bodyFatScaleService;
  148. @Resource
  149. private UserMapper userMapper;
  150. @Resource
  151. private UserService userService;
  152. @Resource
  153. private ReportBlockService reportBlockService;
  154. @Resource
  155. private BasicQuotaService basicQuotaService;
  156. @Resource
  157. private StorageService storageService;
  158. @Resource
  159. private ReportBlockAssembler reportBlockAssembler;
  160. @Resource
  161. private com.etotem.cfc.service.PurchaseService purchaseService;
  162. @Resource
  163. private NormalizeIndicatorPipeline normalizeIndicatorPipeline;
  164. @Resource
  165. private MemberIndicatorCurrentService memberIndicatorCurrentService;
  166. @Resource
  167. private com.etotem.cfc.service.HealthPlanService healthPlanService;
  168. @Resource
  169. private ReportCollectService reportCollectService;
  170. @Resource
  171. private com.etotem.cfc.service.AiGateway aiGateway;
  172. @Resource
  173. private com.etotem.cfc.service.ReportFeedbackService reportFeedbackService;
  174. @Resource
  175. private OnboardingService onboardingService;
  176. @Resource
  177. private ReportArchiveCompareService reportArchiveCompareService;
  178. /**
  179. * 创建健康报告(含指标明细)
  180. */
  181. @Operation(summary = "创建健康报告")
  182. @PostMapping("/report/create")
  183. public Result<HealthReport> createReport(
  184. @RequestBody Map<String, Object> params,
  185. @RequestAttribute("userId") Long userId,
  186. @RequestAttribute(value = "familyId", required = false) Long familyId,
  187. @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
  188. // 付费墙拦截:检查是否购买健康启航计划
  189. java.util.Map<String, Object> purchaseCheck = purchaseService.checkPurchase(userId);
  190. if (!Boolean.TRUE.equals(purchaseCheck.get("isActive"))) {
  191. return Result.error(4001, "请先购买健康启航计划体验包");
  192. }
  193. if (familyId == null) {
  194. return Result.noFamily("请先创建或加入家庭");
  195. }
  196. Long memberId = ParamUtils.getLong(params.get("memberId"), currentMemberId);
  197. if (memberId == null) {
  198. return Result.error("memberId不能为空");
  199. }
  200. String reportType = (String) params.get("reportType");
  201. if (reportType == null || reportType.trim().isEmpty()) {
  202. return Result.error("reportType不能为空: physical_exam / gut_flora");
  203. }
  204. // 契约 §4.59.2:reportType 仅允许 physical_exam / gut_flora,其余取值(空串/非法值)一律拒绝
  205. if (!"physical_exam".equals(reportType) && !"gut_flora".equals(reportType)) {
  206. return Result.error("不支持的reportType: physical_exam / gut_flora");
  207. }
  208. // 构建报告主体
  209. HealthReport report = new HealthReport();
  210. report.setUserId(memberId);
  211. report.setReportType(reportType);
  212. report.setOverallScore(params.get("overallScore") != null
  213. ? Integer.valueOf(params.get("overallScore").toString()) : null);
  214. report.setGutHealthScore(params.get("gutHealthScore") != null
  215. ? Integer.valueOf(params.get("gutHealthScore").toString()) : null);
  216. report.setChronicDiseaseScore(params.get("chronicDiseaseScore") != null
  217. ? Integer.valueOf(params.get("chronicDiseaseScore").toString()) : null);
  218. report.setNutritionScore(params.get("nutritionScore") != null
  219. ? Integer.valueOf(params.get("nutritionScore").toString()) : null);
  220. report.setGutAge((String) params.get("gutAge"));
  221. report.setGutType((String) params.get("gutType"));
  222. report.setGutBalanceScore(params.get("gutBalanceScore") != null
  223. ? Integer.valueOf(params.get("gutBalanceScore").toString()) : null);
  224. report.setGutDiversityScore(params.get("gutDiversityScore") != null
  225. ? Integer.valueOf(params.get("gutDiversityScore").toString()) : null);
  226. report.setBeneficialBacteriaScore(params.get("beneficialBacteriaScore") != null
  227. ? Integer.valueOf(params.get("beneficialBacteriaScore").toString()) : null);
  228. report.setHarmfulBacteriaScore(params.get("harmfulBacteriaScore") != null
  229. ? Integer.valueOf(params.get("harmfulBacteriaScore").toString()) : null);
  230. report.setCoreSpeciesScore(params.get("coreSpeciesScore") != null
  231. ? Integer.valueOf(params.get("coreSpeciesScore").toString()) : null);
  232. report.setHealthRating((String) params.get("healthRating"));
  233. report.setFileUrl((String) params.get("fileUrl"));
  234. report.setRemark((String) params.get("remark"));
  235. // 报告日期(默认当天)
  236. report.setReportDate(new java.util.Date());
  237. // 指标明细(可选)
  238. @SuppressWarnings("unchecked")
  239. List<Map<String, Object>> indicatorList =
  240. (List<Map<String, Object>>) params.get("indicators");
  241. List<HealthIndicator> indicators = null;
  242. if (indicatorList != null) {
  243. indicators = new java.util.ArrayList<>();
  244. for (int i = 0; i < indicatorList.size(); i++) {
  245. Map<String, Object> item = indicatorList.get(i);
  246. HealthIndicator ind = new HealthIndicator();
  247. ind.setCategory((String) item.get("category"));
  248. ind.setIndicatorName((String) item.get("indicatorName"));
  249. ind.setIndicatorValue(item.get("indicatorValue") != null
  250. ? item.get("indicatorValue").toString() : null);
  251. ind.setUnit((String) item.get("unit"));
  252. ind.setRefRange((String) item.get("refRange"));
  253. ind.setStatus((String) item.get("status"));
  254. ind.setSymptoms((String) item.get("symptoms"));
  255. ind.setSortOrder(i);
  256. indicators.add(ind);
  257. }
  258. }
  259. HealthReport created = healthReportService.createReport(report, indicators);
  260. return Result.success(created);
  261. }
  262. /**
  263. * 获取家庭成员的最新健康报告
  264. */
  265. @Operation(summary = "获取最新健康报告")
  266. @PostMapping("/report/latest")
  267. public Result<HealthReport> getLatestReport(
  268. @RequestBody Map<String, Object> params,
  269. @RequestAttribute(value = "familyId", required = false) Long familyId,
  270. @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
  271. if (familyId == null) {
  272. return Result.noFamily("请先创建或加入家庭");
  273. }
  274. Long memberId = ParamUtils.getLong(params.get("memberId"), currentMemberId);
  275. if (memberId == null) {
  276. return Result.error("memberId不能为空");
  277. }
  278. HealthReport report = healthReportService.getLatestReport(memberId);
  279. return Result.success(report);
  280. }
  281. /**
  282. * 获取家庭成员的所有健康报告列表
  283. * 未传 memberId 时返回当前家庭的全部报告;传 memberId 时按成员过滤(兼容 users.id / family_members.id)
  284. */
  285. @Operation(summary = "获取健康报告列表")
  286. @PostMapping("/report/list")
  287. public Result<Object> listReports(
  288. @RequestBody Map<String, Object> params,
  289. @RequestAttribute("userId") Long userId,
  290. @RequestAttribute(value = "familyId", required = false) Long familyId) {
  291. // B3-4:分页支持——page 不传时行为与现一致(返回 List,兼容小程序端);page 传时返回分页结构。
  292. int page = params.get("page") != null ? Integer.parseInt(params.get("page").toString()) : 0;
  293. // 返回条数:显式传 size 则截取前 size 条;不传则返回全部分页列表
  294. int size = params.get("size") != null ? Integer.parseInt(params.get("size").toString()) : 0;
  295. Long memberId = ParamUtils.getLong(params.get("memberId"));
  296. List<HealthReport> reports;
  297. java.util.Set<Long> visibleForDan = null;
  298. if (memberId != null) {
  299. // 成员级权限:管理员 / 本人 / 被授权成员可见,否则返回空列表
  300. if (familyId == null || !reportMemberPermissionService.canViewMemberReports(userId, memberId, familyId)) {
  301. return Result.success(new ArrayList<>());
  302. }
  303. reports = healthReportService.getMemberReports(memberId, familyId);
  304. } else if (familyId != null) {
  305. // 未指定 memberId 时,返回当前家庭的全部报告(按权限过滤)
  306. java.util.Set<Long> visible = reportMemberPermissionService.visibleIdentityIds(userId, familyId);
  307. if (visible == null) {
  308. // 管理员:全部可见
  309. reports = healthReportService.getFamilyReports(familyId);
  310. } else {
  311. List<HealthReport> all = healthReportService.getFamilyReports(familyId);
  312. reports = new ArrayList<>();
  313. for (HealthReport r : all) {
  314. Long subj = r.getSubjectId();
  315. Long owner = r.getUserId();
  316. if ((subj != null && visible.contains(subj))
  317. || (subj == null && owner != null && visible.contains(owner))) {
  318. reports.add(r);
  319. }
  320. }
  321. // DAN 报告按可见成员过滤(family_members.id 语义)
  322. visibleForDan = visible;
  323. }
  324. } else {
  325. // 无家庭信息时返回空列表,避免前端报错
  326. return Result.success(new ArrayList<>());
  327. }
  328. // 合并 DAN 报告(已确认入库的)到列表,保证报告列表页能看到 DAN 报告
  329. List<HealthReport> merged = mergeDanReports(reports, memberId, familyId, visibleForDan, userId);
  330. if (page > 0) {
  331. // B3-4:分页返回结构(对齐项目分页惯例,与 /report/admin-list 的 records/total 口径一致);
  332. // teacher 端代传历史页已按 res.data.records / res.data.total 读取。
  333. int pageSize = size > 0 ? size : 20;
  334. int total = merged.size();
  335. int from = (page - 1) * pageSize;
  336. if (from > total) {
  337. from = total;
  338. }
  339. int to = Math.min(from + pageSize, total);
  340. List<HealthReport> records = from < total
  341. ? new ArrayList<>(merged.subList(from, to)) : new ArrayList<>();
  342. healthReportService.fillSubjectAndProxyNames(records);
  343. Map<String, Object> pageResult = new java.util.HashMap<>();
  344. pageResult.put("records", records);
  345. pageResult.put("total", total);
  346. pageResult.put("current", page);
  347. pageResult.put("size", pageSize);
  348. pageResult.put("pages", (int) Math.ceil((double) total / pageSize));
  349. return Result.success(pageResult);
  350. }
  351. if (size > 0) {
  352. // B1-6:列表补展示字段(报告对象姓名 / 代上传人姓名),实体上的 @TableField(exist=false) 字段
  353. List<HealthReport> limited = limitLatest(merged, size);
  354. healthReportService.fillSubjectAndProxyNames(limited);
  355. return Result.success(limited);
  356. }
  357. // B1-6:列表补展示字段(报告对象姓名 / 代上传人姓名)
  358. healthReportService.fillSubjectAndProxyNames(merged);
  359. return Result.success(merged);
  360. }
  361. /**
  362. * 合并 DAN 报告到健康报告列表(转成 HealthReport 兼容结构,reportType='dan')
  363. */
  364. private List<HealthReport> mergeDanReports(List<HealthReport> reports, Long memberId, Long familyId,
  365. java.util.Set<Long> visibleForDan, Long userId) {
  366. List<DanReportUpload> danList = danReportUploadService.listConfirmedForReportList(memberId, familyId, visibleForDan);
  367. if (danList.isEmpty()) {
  368. return reports == null ? new ArrayList<>() : reports;
  369. }
  370. java.util.Map<Long, Long> idToMemberId = new java.util.HashMap<>();
  371. for (DanReportUpload u : danList) {
  372. if (u.getFamilyMemberId() != null) {
  373. idToMemberId.put(u.getId(), u.getFamilyMemberId());
  374. }
  375. }
  376. List<HealthReport> result = reports == null ? new ArrayList<>() : new ArrayList<>(reports);
  377. // 成员昵称缓存(personName 展示)
  378. java.util.Map<Long, String> memberNameCache = new java.util.HashMap<>();
  379. for (DanReportUpload u : danList) {
  380. HealthReport hr = new HealthReport();
  381. hr.setId(u.getId());
  382. hr.setReportType("dan");
  383. hr.setFamilyId(u.getFamilyId());
  384. hr.setSubjectId(u.getFamilyMemberId());
  385. hr.setUserId(u.getUploaderUserId());
  386. hr.setCreatedAt(u.getUploadedAt() != null ? u.getUploadedAt() : u.getConfirmedAt());
  387. hr.setReportDate(u.getConfirmedAt() != null ? u.getConfirmedAt() : u.getUploadedAt());
  388. if (u.getFamilyMemberId() != null) {
  389. String name = memberNameCache.get(u.getFamilyMemberId());
  390. if (name == null) {
  391. try {
  392. com.etotem.cfc.entity.FamilyMember fm = familyMemberMapper.selectById(u.getFamilyMemberId());
  393. name = fm != null ? (fm.getNickname() != null ? fm.getNickname() : ("成员" + fm.getId())) : null;
  394. } catch (Exception e) {
  395. name = null;
  396. }
  397. if (name == null) name = "";
  398. memberNameCache.put(u.getFamilyMemberId(), name);
  399. }
  400. hr.setPersonName(name);
  401. }
  402. hr.setStatus("active");
  403. result.add(hr);
  404. }
  405. // 按上传时间倒序(DAN 与健康报告统一排序)
  406. result.sort((a, b) -> {
  407. java.util.Date da = a.getCreatedAt();
  408. java.util.Date db = b.getCreatedAt();
  409. if (da == null) return 1;
  410. if (db == null) return -1;
  411. return db.compareTo(da);
  412. });
  413. return result;
  414. }
  415. /**
  416. * 截取列表前 N 条(列表已按报告日期倒序,取最近 N 条)
  417. */
  418. private List<HealthReport> limitLatest(List<HealthReport> reports, int max) {
  419. if (reports == null || reports.size() <= max) {
  420. return reports;
  421. }
  422. return new ArrayList<>(reports.subList(0, max));
  423. }
  424. @Operation(summary = "获取全家健康报告列表(方案页选择用)")
  425. @PostMapping("/reports/family")
  426. public Result<List<HealthReport>> listFamilyReports(
  427. @RequestAttribute(value = "familyId", required = false) Long familyId) {
  428. if (familyId == null) {
  429. return Result.error("familyId不能为空");
  430. }
  431. List<HealthReport> reports = healthReportService.getFamilyReports(familyId);
  432. return Result.success(reports);
  433. }
  434. /**
  435. * 管理端分页查询所有报告
  436. */
  437. @Operation(summary = "管理端报告列表(分页)")
  438. @PostMapping("/report/admin-list")
  439. public Result<Page<Map<String, Object>>> listAllReports(
  440. @RequestBody Map<String, Object> params) {
  441. int page = params.get("page") != null ? Integer.parseInt(params.get("page").toString()) : 1;
  442. int size = params.get("size") != null ? Integer.parseInt(params.get("size").toString()) : 20;
  443. Page<Map<String, Object>> result = healthReportService.listAllReportsForAdmin(page, size);
  444. return Result.success(result);
  445. }
  446. /**
  447. * 新增(§4.1):获取报告指标详情(含上一期对照)
  448. * 相比老接口 /indicator/list 返回裸 List&lt;HealthIndicator&gt;,本接口增加
  449. * previous / change / summary 五档形态数据(first_record / pending_backfill / improved / worsened / flat)。
  450. */
  451. @Operation(summary = "获取报告指标详情(含上一期对照)")
  452. @PostMapping("/report/indicators")
  453. public Result<Map<String, Object>> getReportIndicatorsWithPrevious(
  454. @RequestBody Map<String, Object> params,
  455. @RequestAttribute("userId") Long userId,
  456. @RequestAttribute(value = "familyId", required = false) Long familyId) {
  457. Long reportId = ParamUtils.getLong(params.get("reportId"));
  458. if (reportId == null) {
  459. return Result.error("reportId不能为空");
  460. }
  461. HealthReport report = healthReportService.getReportById(reportId);
  462. if (report == null) {
  463. return Result.error("报告不存在");
  464. }
  465. // 权限校验:管理员 / 本人 / 被授权成员可见(沿用 getReportDetail 逻辑)
  466. Long reportFamilyId = report.getFamilyId() != null ? report.getFamilyId() : familyId;
  467. if (reportFamilyId == null) {
  468. return Result.error("无权查看该报告");
  469. }
  470. Long subjectId = report.getSubjectId();
  471. if (subjectId == null) {
  472. boolean self = report.getUserId() != null && report.getUserId().equals(userId);
  473. if (!self && !reportMemberPermissionService.isFamilyAdmin(userId, reportFamilyId)) {
  474. return Result.error("无权查看该报告");
  475. }
  476. } else if (!reportMemberPermissionService.canViewMemberReports(userId, subjectId, reportFamilyId)) {
  477. return Result.error("无权查看该报告");
  478. }
  479. Boolean withPrevious = params.get("withPrevious") != null
  480. ? Boolean.valueOf(params.get("withPrevious").toString()) : true;
  481. // 复用已加载的 report 与指标行,避免重复查询(验收标准第 6 条:SQL ≤ 5 次)
  482. List<HealthIndicator> indicators = healthReportService.getReportIndicators(reportId);
  483. Map<String, Object> data = healthReportService.getReportIndicatorsWithPrevious(report, indicators, withPrevious);
  484. return Result.success(data);
  485. }
  486. /**
  487. * 获取某份报告的所有指标明细
  488. */
  489. @Operation(summary = "获取报告指标明细")
  490. @PostMapping("/indicator/list")
  491. public Result<List<HealthIndicator>> listIndicators(
  492. @RequestBody Map<String, Object> params) {
  493. Long reportId = ParamUtils.getLong(params.get("reportId"));
  494. if (reportId == null) {
  495. return Result.error("reportId不能为空");
  496. }
  497. List<HealthIndicator> indicators = healthReportService.getReportIndicators(reportId);
  498. return Result.success(indicators);
  499. }
  500. /**
  501. * 获取某成员某维度的最新指标值(用于首页指标卡片展示)
  502. */
  503. @Operation(summary = "获取成员维度指标列表")
  504. @PostMapping("/indicators")
  505. public Result<List<Map<String, Object>>> getMemberIndicators(
  506. @RequestBody Map<String, Object> params,
  507. @RequestAttribute("userId") Long userId,
  508. @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
  509. Long memberId = ParamUtils.getLong(params.get("memberId"), currentMemberId);
  510. String domain = (String) params.get("domain");
  511. if (memberId == null || domain == null) {
  512. return Result.error("memberId和domain不能为空");
  513. }
  514. try {
  515. List<Map<String, Object>> list = healthReportService.getLatestIndicatorsByDomain(memberId, domain);
  516. return Result.success(list);
  517. } catch (Exception e) {
  518. log.warn("获取指标失败: {}", e.getMessage());
  519. return Result.success(java.util.Collections.emptyList());
  520. }
  521. }
  522. /**
  523. * 获取成员最新菌群报告核心指标(用于身页面肠道菌群卡片)
  524. */
  525. @Operation(summary = "获取菌群指标")
  526. @PostMapping("/gut-flora")
  527. public Result<List<Map<String, Object>>> getGutFlora(
  528. @RequestBody Map<String, Object> params,
  529. @RequestAttribute("userId") Long userId,
  530. @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
  531. Long memberId = ParamUtils.getLong(params.get("memberId"), currentMemberId);
  532. if (memberId == null) return Result.error("memberId不能为空");
  533. try {
  534. List<Map<String, Object>> list = healthReportService.getGutFloraIndicators(memberId);
  535. return Result.success(list);
  536. } catch (Exception e) {
  537. log.warn("获取菌群指标失败: {}", e.getMessage());
  538. return Result.success(java.util.Collections.emptyList());
  539. }
  540. }
  541. /**
  542. * [admin] 回填成员指标当前值 diff(对存量未走新确认流程的报告手动触发)
  543. * 入参: memberId(必填);调用 healthReportService.rebuildForMember
  544. */
  545. @Operation(summary = "回填成员指标当前值(admin)")
  546. @PostMapping("/indicators/rebuild")
  547. public Result<Map<String, Object>> rebuildIndicatorCurrent(
  548. @RequestBody Map<String, Object> params,
  549. @RequestAttribute("userId") Long userId,
  550. @RequestAttribute(value = "role", required = false) String role) {
  551. Long memberId = ParamUtils.getLong(params.get("memberId"));
  552. if (memberId == null) return Result.error("memberId不能为空");
  553. if (!"admin".equals(role)) return Result.error("权限不足");
  554. try {
  555. healthReportService.rebuildForMember(memberId);
  556. Map<String, Object> out = new java.util.HashMap<>();
  557. out.put("memberId", memberId);
  558. out.put("rebuilt", true);
  559. return Result.success(out);
  560. } catch (Exception e) {
  561. log.warn("回填指标当前值失败 memberId={}: {}", memberId, e.getMessage());
  562. return Result.error("回填失败: " + e.getMessage());
  563. }
  564. }
  565. /**
  566. * 获取成员指标当前值 + 相对上一份报告的变化 delta(用于指标卡片与方案生成)
  567. * 数据来源:member_indicator_current(报告确认/编辑时由 refreshMemberIndicatorCurrent 写入)
  568. */
  569. @Operation(summary = "获取成员指标当前值与变化")
  570. @PostMapping("/indicators/current")
  571. public Result<List<Map<String, Object>>> getMemberIndicatorCurrent(
  572. @RequestBody Map<String, Object> params,
  573. @RequestAttribute("userId") Long userId,
  574. @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
  575. Long memberId = ParamUtils.getLong(params.get("memberId"), currentMemberId);
  576. String domain = (String) params.get("domain");
  577. if (memberId == null) {
  578. return Result.error("memberId不能为空");
  579. }
  580. try {
  581. List<Map<String, Object>> list = memberIndicatorCurrentService.getCurrentIndicators(memberId, domain);
  582. return Result.success(list);
  583. } catch (Exception e) {
  584. log.warn("获取成员指标当前值失败 memberId={}: {}", memberId, e.getMessage());
  585. return Result.success(java.util.Collections.emptyList());
  586. }
  587. }
  588. /**
  589. * 获取家庭成员身体维度数据详情(健康指标解读)
  590. */
  591. @Operation(summary = "获取身体维度数据详情")
  592. @PostMapping("/body/detail")
  593. public Result<List<HealthIndicator>> getBodyDetail(
  594. @RequestBody Map<String, Object> params,
  595. @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
  596. Long memberId = ParamUtils.getLong(params.get("memberId"), currentMemberId);
  597. if (memberId == null) {
  598. return Result.error("memberId不能为空");
  599. }
  600. List<HealthIndicator> detail = healthReportService.getBodyDetail(memberId);
  601. return Result.success(detail);
  602. }
  603. /**
  604. * 获取报告完整详情(含指标明细 + 菌群数据 + 疾病风险评估)
  605. */
  606. @Operation(summary = "获取报告完整详情")
  607. @PostMapping("/report/detail")
  608. public Result<Map<String, Object>> getReportDetail(
  609. @RequestBody Map<String, Object> params,
  610. @RequestAttribute("userId") Long userId,
  611. @RequestAttribute(value = "familyId", required = false) Long familyId) {
  612. Long reportId = ParamUtils.getLong(params.get("reportId"));
  613. if (reportId == null) {
  614. return Result.error("reportId不能为空");
  615. }
  616. HealthReport report = healthReportService.getReportById(reportId);
  617. if (report == null) {
  618. return Result.error("报告不存在");
  619. }
  620. // 权限校验:管理员 / 本人 / 被授权成员可见
  621. Long reportFamilyId = report.getFamilyId() != null ? report.getFamilyId() : familyId;
  622. if (reportFamilyId == null) {
  623. return Result.error("无权查看该报告");
  624. }
  625. Long subjectId = report.getSubjectId();
  626. if (subjectId == null) {
  627. // 无归属成员:仅本人上传者或管理员可见
  628. boolean self = report.getUserId() != null && report.getUserId().equals(userId);
  629. if (!self && !reportMemberPermissionService.isFamilyAdmin(userId, reportFamilyId)) {
  630. return Result.error("无权查看该报告");
  631. }
  632. } else if (!reportMemberPermissionService.canViewMemberReports(userId, subjectId, reportFamilyId)) {
  633. return Result.error("无权查看该报告");
  634. }
  635. Map<String, Object> detail = healthReportService.getReportDetail(reportId);
  636. return Result.success(detail);
  637. }
  638. /**
  639. * 获取报告 payload(编辑回填用,按需加载,减少首屏性能开销)
  640. */
  641. @Operation(summary = "获取报告payload(编辑回填)")
  642. @PostMapping("/report/payload")
  643. public Result<Map<String, Object>> getReportPayload(
  644. @RequestBody Map<String, Object> params,
  645. @RequestAttribute("userId") Long userId,
  646. @RequestAttribute(value = "familyId", required = false) Long familyId) {
  647. Long reportId = ParamUtils.getLong(params.get("reportId"));
  648. if (reportId == null) {
  649. return Result.error("reportId不能为空");
  650. }
  651. HealthReport report = healthReportService.getReportById(reportId);
  652. if (report == null) {
  653. return Result.error("报告不存在");
  654. }
  655. Long reportFamilyId = report.getFamilyId() != null ? report.getFamilyId() : familyId;
  656. if (reportFamilyId == null) {
  657. return Result.error("无权查看该报告");
  658. }
  659. Long subjectId = report.getSubjectId();
  660. if (subjectId == null) {
  661. boolean self = report.getUserId() != null && report.getUserId().equals(userId);
  662. if (!self && !reportMemberPermissionService.isFamilyAdmin(userId, reportFamilyId)) {
  663. return Result.error("无权查看该报告");
  664. }
  665. } else if (!reportMemberPermissionService.canViewMemberReports(userId, subjectId, reportFamilyId)) {
  666. return Result.error("无权查看该报告");
  667. }
  668. Map<String, Object> payload = healthReportService.getReportPayload(reportId);
  669. return Result.success(payload);
  670. }
  671. /**
  672. * 编辑已发布报告 — 修正 AI 解析错误的值
  673. */
  674. @Operation(summary = "编辑已发布报告数据")
  675. @PostMapping("/report/edit")
  676. public Result<String> editReport(
  677. @RequestBody Map<String, Object> params,
  678. @RequestAttribute("userId") Long userId,
  679. @RequestAttribute(value = "familyId", required = false) Long familyId) {
  680. Long reportId = ParamUtils.getLong(params.get("reportId"));
  681. if (reportId == null) {
  682. return Result.error("reportId不能为空");
  683. }
  684. if (userId == null) {
  685. return Result.error("用户未登录");
  686. }
  687. HealthReport report = healthReportService.getReportById(reportId);
  688. if (report == null) {
  689. return Result.error("报告不存在");
  690. }
  691. // 归属校验(与 getReportPayload 同范式:能回填即可保存)
  692. Long reportFamilyId = report.getFamilyId() != null ? report.getFamilyId() : familyId;
  693. if (reportFamilyId == null) {
  694. return Result.error("无权编辑该报告");
  695. }
  696. Long reportSubjectId = report.getSubjectId();
  697. if (reportSubjectId == null) {
  698. boolean self = report.getUserId() != null && report.getUserId().equals(userId);
  699. if (!self && !reportMemberPermissionService.isFamilyAdmin(userId, reportFamilyId)) {
  700. return Result.error("无权编辑该报告");
  701. }
  702. } else if (!reportMemberPermissionService.canViewMemberReports(userId, reportSubjectId, reportFamilyId)) {
  703. return Result.error("无权编辑该报告");
  704. }
  705. Long subjectId = ParamUtils.getLong(params.get("subjectId"));
  706. // subjectId 可为 null:用户取消绑定成员时传 null,表示解绑(不纳入家庭维度计算)
  707. // subjectId 与旧值不同时:重算旧成员 + 新成员维度分
  708. @SuppressWarnings("unchecked")
  709. Map<String, Object> payload = (Map<String, Object>) params.get("payload");
  710. if (payload == null) {
  711. return Result.error("payload不能为空");
  712. }
  713. healthReportService.updateReportFromPayload(reportId, payload, subjectId, userId);
  714. return Result.success("已保存");
  715. }
  716. /**
  717. * 删除健康报告(逻辑删除 + 清理关联数据)。
  718. *
  719. * <p>删除守卫(SC-P-24 / TC-P-24-E):报告已关联成长方案时拒绝删除并提示
  720. * 「请先解除关联方案」;归属校验(SC-P-24-P / TC-P-24-P):报告须归属当前用户家庭,
  721. * 横向越权删除他人报告统一被拒。</p>
  722. *
  723. * <p>E09 家庭内成员级校验:跨家庭拒绝后,家庭内亦仅上传者本人或家庭管理员可删除,
  724. * 防止同家庭成员越权删除他人报告。</p>
  725. */
  726. @Operation(summary = "删除健康报告")
  727. @PostMapping("/report/delete")
  728. public Result<String> deleteReport(
  729. @RequestBody Map<String, Object> params,
  730. @RequestAttribute("userId") Long userId,
  731. @RequestAttribute(value = "familyId", required = false) Long familyId) {
  732. Long reportId = ParamUtils.getLong(params.get("reportId"));
  733. if (reportId == null) {
  734. return Result.error("reportId不能为空");
  735. }
  736. if (userId == null) {
  737. return Result.error("用户未登录");
  738. }
  739. HealthReport report = healthReportService.getReportById(reportId);
  740. if (report == null) {
  741. return Result.error("报告不存在");
  742. }
  743. // 归属校验(TC-P-24-P):报告须归属当前用户家庭,横向越权删除被拒
  744. if (familyId != null && report.getFamilyId() != null && !familyId.equals(report.getFamilyId())) {
  745. return Result.error(403, "无权删除该报告");
  746. }
  747. // E09 越权修复:家庭内亦仅上传者本人或家庭管理员可删除
  748. boolean isOwner = report.getUserId() != null && report.getUserId().equals(userId);
  749. boolean isAdmin = report.getFamilyId() != null
  750. && reportMemberPermissionService.isFamilyAdmin(userId, report.getFamilyId());
  751. if (!isOwner && !isAdmin) {
  752. return Result.error("无权删除该报告");
  753. }
  754. try {
  755. healthReportService.deleteReport(reportId);
  756. } catch (IllegalStateException e) {
  757. // 删除守卫命中(报告已关联成长方案)
  758. return Result.error(409, e.getMessage());
  759. }
  760. return Result.success("已删除");
  761. }
  762. /**
  763. * 报告对比(SC-P-24 / TC-P-24「对比展示差异」,§4.59.10 契约缺口落地)。
  764. *
  765. * <p>入参 {@code {reportAId, reportBId}};类型一致才可比对,返回差异标注。</p>
  766. */
  767. @Operation(summary = "报告对比")
  768. @PostMapping("/report/compare")
  769. public Result<Map<String, Object>> compareReports(
  770. @RequestBody Map<String, Object> params,
  771. @RequestAttribute("userId") Long userId) {
  772. Long reportAId = ParamUtils.getLong(params.get("reportAId"));
  773. Long reportBId = ParamUtils.getLong(params.get("reportBId"));
  774. if (reportAId == null || reportBId == null) {
  775. return Result.error("reportAId 和 reportBId 不能为空");
  776. }
  777. Map<String, Object> result = reportArchiveCompareService.compareReports(reportAId, reportBId);
  778. return Result.success(result);
  779. }
  780. /**
  781. * 获取健康报告文件下载信息(小程序端"下载报告")
  782. * 返回完整可下载 URL 供 uni.downloadFile 使用;
  783. * 本地存储的相对路径(/uploads/**)自动拼接当前请求域名,避免前端拼接与域名白名单差异。
  784. */
  785. @Operation(summary = "获取健康报告文件下载信息")
  786. @PostMapping("/report/download")
  787. public Result<Map<String, Object>> downloadReport(
  788. @RequestBody Map<String, Object> params,
  789. @RequestAttribute("userId") Long userId,
  790. @RequestAttribute(value = "familyId", required = false) Long familyId,
  791. HttpServletRequest request) {
  792. if (userId == null) {
  793. return Result.error("用户未登录");
  794. }
  795. Long reportId = ParamUtils.getLong(params.get("reportId"));
  796. if (reportId == null) {
  797. return Result.error("reportId不能为空");
  798. }
  799. HealthReport report = healthReportService.getReportById(reportId);
  800. if (report == null) {
  801. return Result.error("报告不存在");
  802. }
  803. // E09-b 越权下载修复:与 detail/payload 同范式(能查看即可下载)
  804. Long reportFamilyId = report.getFamilyId() != null ? report.getFamilyId() : familyId;
  805. if (reportFamilyId == null) {
  806. return Result.error("无权下载该报告");
  807. }
  808. Long reportSubjectId = report.getSubjectId();
  809. if (reportSubjectId == null) {
  810. boolean self = report.getUserId() != null && report.getUserId().equals(userId);
  811. if (!self && !reportMemberPermissionService.isFamilyAdmin(userId, reportFamilyId)) {
  812. return Result.error("无权下载该报告");
  813. }
  814. } else if (!reportMemberPermissionService.canViewMemberReports(userId, reportSubjectId, reportFamilyId)) {
  815. return Result.error("无权下载该报告");
  816. }
  817. String fileUrl = report.getFileUrl();
  818. if (fileUrl == null || fileUrl.trim().isEmpty()) {
  819. return Result.error("该报告无文件可下载");
  820. }
  821. // 本地存储返回相对路径 /uploads/**,拼接当前请求域名得到完整 URL
  822. if (fileUrl.startsWith("/")) {
  823. String scheme = request.getHeader("X-Forwarded-Proto");
  824. if (scheme == null || scheme.trim().isEmpty()) {
  825. scheme = request.getScheme();
  826. }
  827. String host = request.getHeader("Host");
  828. if (host != null && !host.isEmpty()) {
  829. fileUrl = scheme + "://" + host + fileUrl;
  830. }
  831. }
  832. Map<String, Object> data = new LinkedHashMap<>();
  833. data.put("fileUrl", fileUrl);
  834. data.put("fileName", fileUrl.substring(fileUrl.lastIndexOf('/') + 1));
  835. return Result.success(data);
  836. }
  837. /**
  838. * 上传并解析肠道菌群报告PDF(向后兼容 — 内部自动执行两阶段:解析→确认)
  839. */
  840. @Operation(summary = "上传并解析肠道菌群报告PDF(兼容接口,自动确认)")
  841. @PostMapping("/report/upload")
  842. public Result<Map<String, Object>> uploadReport(
  843. @RequestParam("file") MultipartFile file,
  844. @RequestAttribute("userId") Long userId,
  845. @RequestAttribute(value = "familyId", required = false) Long familyId) {
  846. if (file.isEmpty()) {
  847. return Result.error("文件不能为空");
  848. }
  849. String contentType = file.getContentType();
  850. String originalFilename = file.getOriginalFilename();
  851. if (originalFilename == null || (!originalFilename.toLowerCase().endsWith(".pdf")
  852. && (contentType == null || !contentType.equalsIgnoreCase("application/pdf")))) {
  853. return Result.error("仅支持PDF文件");
  854. }
  855. try {
  856. ParsedReportResult parsed = pdfParseService.parse(file.getInputStream());
  857. if (parsed.getOverallScore() == null && parsed.getGutHealthScore() == null) {
  858. return Result.error("无法解析PDF文件,请确认是募极生物肠道菌群报告");
  859. }
  860. String fileUrl = storageService.storeFile(file, "health-reports");
  861. ParsedReportPayload.Payload payload = convertToPayload(parsed);
  862. String payloadJson = objectMapper.writeValueAsString(payload);
  863. HealthReportDraft draft = healthReportDraftService.createDraft(
  864. userId, familyId, "gut_flora", fileUrl, originalFilename, payloadJson);
  865. Long matchedMemberId = null;
  866. String matchedMemberName = null;
  867. if (familyId != null && parsed.getPersonName() != null) {
  868. matchedMemberId = healthReportService.matchFamilyMemberByName(parsed.getPersonName(), familyId);
  869. }
  870. HealthReport report = buildReportFromPayload(draft, payload, matchedMemberId);
  871. List<HealthIndicator> indicators = buildIndicatorsFromPayload(payload);
  872. List<HealthGutFlora> gutFlora = buildGutFloraFromPayload(payload);
  873. List<HealthDiseaseRisk> diseaseRisks = buildDiseaseRisksFromPayload(payload);
  874. HealthReport created = healthReportService.createReport(report, indicators, gutFlora, diseaseRisks);
  875. // 落库 payload 快照 + 创建日志
  876. healthReportService.savePayloadSnapshot(created.getId(), userId, "create", null, payloadJson);
  877. if (payload.getFoods() != null && !payload.getFoods().isEmpty()) {
  878. List<Food> foods = buildFoodsFromPayload(payload);
  879. foodService.saveFoodsForReport(created.getId(), foods);
  880. }
  881. if (matchedMemberId != null) {
  882. matchedMemberName = parsed.getPersonName();
  883. log.info("报告{}自动匹配到成员{}", created.getId(), matchedMemberId);
  884. try {
  885. dimensionScoreService.refreshFromGutReport(matchedMemberId, created.getId());
  886. log.info("已刷新成员{}的7维健康评分", matchedMemberId);
  887. } catch (Exception e) {
  888. log.warn("刷新7维健康评分失败: {}", e.getMessage());
  889. }
  890. try {
  891. foodRecommendService.recalculateForUser(matchedMemberId);
  892. log.info("已刷新成员{}的食材推荐指数", matchedMemberId);
  893. } catch (Exception e) {
  894. log.warn("刷新食材推荐指数失败: {}", e.getMessage());
  895. }
  896. }
  897. healthReportDraftService.markConfirmed(draft.getId(), created.getId());
  898. // 新手任务联动:完成首次报告上传任务(老用户无任务记录时静默跳过)
  899. try { onboardingService.completeTask(userId, "REPORT_UPLOAD"); } catch (Exception e) { log.warn("新手任务 REPORT_UPLOAD 更新失败: {}", e.getMessage()); }
  900. Map<String, Object> detail = healthReportService.getReportDetail(created.getId());
  901. detail.put("matchedMemberId", matchedMemberId);
  902. detail.put("matchedMemberName", matchedMemberName);
  903. detail.put("extractedName", parsed.getPersonName());
  904. detail.put("extractedReportNumber", parsed.getReportNumber());
  905. detail.put("extractedReportDate", parsed.getReportDate());
  906. detail.put("needBind", matchedMemberId == null);
  907. return Result.success(detail);
  908. } catch (IOException e) {
  909. log.error("PDF解析失败", e);
  910. return Result.error("PDF解析失败: " + e.getMessage());
  911. }
  912. }
  913. /**
  914. * 两阶段入库 Phase 0: 仅上传文件,不解析。返回 draftId 和 fileUrl,
  915. * 供前端展示「开始解析」按钮并导航至确认页触发异步解析。
  916. */
  917. @Operation(summary = "仅上传报告文件(不解析)")
  918. @PostMapping("/report/upload-only")
  919. public Result<Map<String, Object>> uploadOnly(
  920. @RequestParam("file") MultipartFile file,
  921. @RequestParam(value = "type", defaultValue = "auto") String type,
  922. @RequestParam(value = "memberId", required = false) Long memberId,
  923. @RequestAttribute("userId") Long userId,
  924. @RequestAttribute(value = "familyId", required = false) Long familyId) {
  925. if ("tongue".equals(type)) {
  926. // 舌诊照片:直接走舌诊流程(AI 视觉分析 + 存舌诊记录),不走 PDF 采集链
  927. try {
  928. Map<String, Object> tongueResult = tongueDiagnosisService.parsePreview(file, memberId);
  929. tongueResult.put("type", "tongue");
  930. return Result.success(tongueResult);
  931. } catch (Exception e) {
  932. log.error("舌诊解析失败", e);
  933. return Result.error("舌诊解析失败: " + e.getMessage());
  934. }
  935. }
  936. if (file.isEmpty()) {
  937. return Result.error("文件不能为空");
  938. }
  939. String contentType = file.getContentType();
  940. String originalFilename = file.getOriginalFilename();
  941. try {
  942. // 先读取文件字节:图片用于安全检测,PDF用于MD5去重(storeFile 后 temp 文件会被转移,无法再读)
  943. byte[] fileBytes = file.getBytes();
  944. String fileHash = computeMd5(fileBytes);
  945. // 图片类型:安全检测 + 保存
  946. if ("image".equals(type) || isImageContent(contentType)) {
  947. if (!wechatService.checkImage(fileBytes)) {
  948. return Result.error("图片内容包含敏感信息,上传失败");
  949. }
  950. // auto 模式下的图片先判断是否为舌象照片:是 → 直接走舌诊流程,
  951. // 避免舌诊照片被当作 PDF 报告走采集链导致 EOF 错误
  952. if ("auto".equals(type) || "image".equals(type)) {
  953. try {
  954. boolean isTongue = aiGateway.detectTongue(fileBytes, originalFilename);
  955. if (isTongue) {
  956. Map<String, Object> tongueResult = tongueDiagnosisService.parsePreview(file, memberId);
  957. tongueResult.put("type", "tongue");
  958. return Result.success(tongueResult);
  959. }
  960. } catch (Exception e) {
  961. log.warn("舌象照片分类失败,按普通图片处理: {}", e.getMessage());
  962. }
  963. }
  964. } else {
  965. // PDF 类型校验
  966. String lcName = originalFilename != null ? originalFilename.toLowerCase() : "";
  967. if (!lcName.endsWith(".pdf")
  968. && (contentType == null || !contentType.equalsIgnoreCase("application/pdf"))) {
  969. return Result.error("仅支持PDF文件");
  970. }
  971. }
  972. // 重复上传检测:同一 MD5 已入库或正在采集中则直接返回,不再重复解析
  973. Long existingReportId = healthReportService.findReportIdByFileHash(fileHash, reportTypeOfUpload(type, familyId));
  974. if (existingReportId != null) {
  975. Map<String, Object> dup = new LinkedHashMap<>();
  976. dup.put("duplicate", true);
  977. dup.put("reportId", existingReportId);
  978. HealthReport existingReport = healthReportService.getReportById(existingReportId);
  979. boolean crossFamily = existingReport != null
  980. && existingReport.getFamilyId() != null
  981. && (familyId == null || !familyId.equals(existingReport.getFamilyId()));
  982. if (crossFamily) {
  983. // 同一份报告已被其他家庭上传:需原家庭同意后方可转入本家庭,禁止直接跳详情
  984. dup.put("crossFamily", true);
  985. dup.put("message", "该报告已由其他家庭上传,发起转移申请并经对方同意后,报告将转入您的家庭");
  986. } else {
  987. dup.put("message", "该报告已上传过,无需重复解析");
  988. }
  989. return Result.success(dup);
  990. }
  991. Long collectingDraftId = healthReportService.findCollectingDraftIdByFileHash(fileHash);
  992. if (collectingDraftId != null) {
  993. Map<String, Object> dup = new LinkedHashMap<>();
  994. dup.put("duplicate", true);
  995. dup.put("draftId", collectingDraftId);
  996. dup.put("collecting", true);
  997. dup.put("message", "该报告正在解析中,请稍候");
  998. return Result.success(dup);
  999. }
  1000. String fileUrl = storageService.storeFile(file, "health-reports");
  1001. String reportType = familyId != null && !("pdf".equals(type) || "auto".equals(type))
  1002. ? "physical_exam" : "gut_flora";
  1003. // 创建空载荷草稿(不含解析数据)
  1004. ParsedReportPayload.Payload emptyPayload = new ParsedReportPayload.Payload();
  1005. String payloadJson = objectMapper.writeValueAsString(emptyPayload);
  1006. HealthReportDraft draft = healthReportDraftService.createDraft(
  1007. userId, familyId, reportType, fileUrl, originalFilename, payloadJson, fileHash, memberId);
  1008. // 提交异步采集:指纹判定类型后走专用脚本/opencode,完成自动入库,前端轮询 parse_status
  1009. reportCollectService.submitAsyncCollect(draft.getId());
  1010. Map<String, Object> result = new LinkedHashMap<>();
  1011. result.put("draftId", draft.getId());
  1012. result.put("fileUrl", fileUrl);
  1013. result.put("originalFilename", originalFilename);
  1014. result.put("parseStatus", ReportCollectService.STATUS_COLLECTING);
  1015. result.put("collecting", true);
  1016. return Result.success(result);
  1017. } catch (IOException e) {
  1018. log.error("文件上传失败", e);
  1019. return Result.error("文件上传失败: " + e.getMessage());
  1020. }
  1021. }
  1022. /**
  1023. * 计算上传文件的MD5哈希(用于重复上传去重)
  1024. */
  1025. private String computeMd5(byte[] data) {
  1026. try {
  1027. java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
  1028. byte[] digest = md.digest(data);
  1029. StringBuilder sb = new StringBuilder();
  1030. for (byte b : digest) {
  1031. sb.append(String.format("%02x", b));
  1032. }
  1033. return sb.toString();
  1034. } catch (Exception e) {
  1035. log.warn("计算文件MD5失败: {}", e.getMessage());
  1036. return null;
  1037. }
  1038. }
  1039. /**
  1040. * 根据上传类型推导报告类型(与下方 reportType 计算保持一致,供去重查询使用)
  1041. */
  1042. private String reportTypeOfUpload(String type, Long familyId) {
  1043. return familyId != null && !("pdf".equals(type) || "auto".equals(type))
  1044. ? "physical_exam" : "gut_flora";
  1045. }
  1046. /**
  1047. * 查询异步采集任务状态(前端轮询):返回 parse_status/parse_method/parse_error/reportId
  1048. */
  1049. @Operation(summary = "查询异步采集状态")
  1050. @PostMapping("/report/collect/status")
  1051. public Result<Map<String, Object>> collectStatus(
  1052. @RequestBody Map<String, Object> params,
  1053. @RequestAttribute("userId") Long userId) {
  1054. Long draftId = ParamUtils.getLong(params.get("draftId"));
  1055. if (draftId == null) {
  1056. return Result.error("draftId不能为空");
  1057. }
  1058. HealthReportDraft draft = healthReportDraftService.getDraftById(draftId);
  1059. if (draft == null) {
  1060. return Result.error("草稿不存在");
  1061. }
  1062. if (!draft.getUserId().equals(userId)) {
  1063. return Result.error("无权访问此草稿");
  1064. }
  1065. Map<String, Object> result = new LinkedHashMap<>();
  1066. result.put("draftId", draftId);
  1067. result.put("parseStatus", draft.getParseStatus());
  1068. result.put("parseMethod", draft.getParseMethod());
  1069. result.put("parseError", draft.getParseError());
  1070. result.put("reportId", draft.getConfirmedReportId());
  1071. result.put("reportType", draft.getReportType());
  1072. // P0-3 ③:暴露 collect_validation(含 _解析自检 透传结果),前端轮询可核对
  1073. result.put(COLLECT_VALIDATION_KEY, draft.getCollectValidation());
  1074. return Result.success(result);
  1075. }
  1076. /**
  1077. * 查询当前用户所有"采集中"的草稿(供报告列表顶部展示采集进度)
  1078. */
  1079. @Operation(summary = "查询采集中草稿列表")
  1080. @PostMapping("/report/collecting-list")
  1081. public Result<java.util.List<Map<String, Object>>> collectingList(
  1082. @RequestAttribute("userId") Long userId) {
  1083. java.util.List<HealthReportDraft> drafts = healthReportDraftService.listCollectingByUser(userId);
  1084. java.util.List<Map<String, Object>> result = new java.util.ArrayList<>();
  1085. for (HealthReportDraft d : drafts) {
  1086. Map<String, Object> item = new LinkedHashMap<>();
  1087. item.put("draftId", d.getId());
  1088. item.put("originalFilename", d.getOriginalFilename());
  1089. item.put("reportType", d.getReportType());
  1090. item.put("createdAt", d.getCreatedAt());
  1091. item.put("parseStatus", d.getParseStatus());
  1092. result.add(item);
  1093. }
  1094. return Result.success(result);
  1095. }
  1096. /**
  1097. * 体脂秤图片上传 + AI 识别(一步完成:上传→识别→存库)
  1098. */
  1099. @Operation(summary = "体脂秤图片上传并自动识别指标")
  1100. @PostMapping("/report/bodyfat-upload")
  1101. public Result<Map<String, Object>> uploadBodyFat(
  1102. @RequestParam("file") MultipartFile file,
  1103. @RequestAttribute("userId") Long userId,
  1104. @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
  1105. if (file.isEmpty()) {
  1106. return Result.error("文件不能为空");
  1107. }
  1108. String contentType = file.getContentType();
  1109. if (contentType == null || !contentType.startsWith("image/")) {
  1110. return Result.error("仅支持图片文件(JPG/PNG)");
  1111. }
  1112. try {
  1113. byte[] imageBytes = file.getBytes();
  1114. if (!wechatService.checkImage(imageBytes)) {
  1115. return Result.error("图片内容包含敏感信息,上传失败");
  1116. }
  1117. } catch (Exception e) {
  1118. return Result.error("图片读取失败: " + e.getMessage());
  1119. }
  1120. String fileUrl = storageService.storeFile(file, "health-reports");
  1121. Map<String, Object> analysisResult = bodyFatScaleService.analyzeImage(fileUrl);
  1122. List<Map<String, Object>> metrics = (List<Map<String, Object>>) analysisResult.get("metrics");
  1123. if (metrics == null) metrics = Collections.emptyList();
  1124. Map<String, Object> result = new LinkedHashMap<>();
  1125. result.put("metrics", metrics);
  1126. result.put("fileUrl", fileUrl);
  1127. return Result.success(result);
  1128. }
  1129. /**
  1130. * 体脂秤指标直接入库(前端识别/人工修正后提交 {memberId, metrics:[{name,value,unit}]})
  1131. */
  1132. @Operation(summary = "保存体脂秤指标(无需上传图片)")
  1133. @PostMapping("/report/bodyfat-save")
  1134. public Result<Map<String, Object>> saveBodyFat(@RequestBody Map<String, Object> body,
  1135. @RequestAttribute("userId") Long userId) {
  1136. Long memberId = ParamUtils.getLong(body.get("memberId"));
  1137. if (memberId == null) {
  1138. return Result.error("memberId不能为空");
  1139. }
  1140. @SuppressWarnings("unchecked")
  1141. List<Map<String, Object>> metrics = (List<Map<String, Object>>) body.get("metrics");
  1142. if (metrics == null || metrics.isEmpty()) {
  1143. return Result.error("无可保存的指标");
  1144. }
  1145. return Result.success(bodyFatScaleService.saveMetrics(memberId, metrics));
  1146. }
  1147. /**
  1148. * 两阶段入库 Phase 1: 按 draftId 触发解析。读取已保存的文件,
  1149. * 执行 LangGraph / 本地 Java 解析,更新草稿载荷后返回完整解析结果。
  1150. */
  1151. @Operation(summary = "按草稿ID触发解析")
  1152. @PostMapping("/report/parse")
  1153. public Result<Map<String, Object>> parseByDraftId(
  1154. @RequestBody Map<String, Object> params,
  1155. @RequestAttribute(value = "familyId", required = false) Long familyId,
  1156. @RequestAttribute("userId") Long userId) {
  1157. Long draftId = ParamUtils.getLong(params.get("draftId"));
  1158. if (draftId == null) {
  1159. return Result.error("draftId不能为空");
  1160. }
  1161. HealthReportDraft draft = healthReportDraftService.getActiveDraft(draftId);
  1162. if (draft == null) {
  1163. return Result.error("草稿不存在、已确认或已过期");
  1164. }
  1165. if (!draft.getUserId().equals(userId)) {
  1166. return Result.error("无权操作此草稿");
  1167. }
  1168. String fileUrl = draft.getFileUrl();
  1169. String originalFilename = draft.getOriginalFilename();
  1170. try {
  1171. // LangGraph 需要本地路径:经 getFilePath 下载到共享卷(LangGraph 容器可读)
  1172. try {
  1173. String lgPath = storageService.getFilePath(fileUrl);
  1174. Map<String, Object> lgRequest = new HashMap<>();
  1175. lgRequest.put("file_path", lgPath);
  1176. lgRequest.put("user_id", userId);
  1177. if (familyId != null) {
  1178. lgRequest.put("family_id", familyId);
  1179. }
  1180. ResponseEntity<Map> lgResponse = restTemplate.postForEntity(
  1181. langgraphBaseUrl + "/api/v1/report/parse", lgRequest, Map.class);
  1182. Map<String, Object> lgBody = lgResponse.getBody();
  1183. if (lgBody != null && Integer.valueOf(200).equals(lgBody.get("code"))) {
  1184. Map<String, Object> lgData = (Map<String, Object>) lgBody.get("data");
  1185. if (lgData != null) {
  1186. return buildParseResultFromLg(lgData, draft, familyId);
  1187. }
  1188. }
  1189. } catch (Exception e) {
  1190. log.warn("LangGraph 解析失败,回退到本地 Java 解析: {}", e.getMessage());
  1191. }
  1192. // Fallback: 本地 Java 解析(下载 OSS 文件到本地临时目录,或直接读共享卷)
  1193. String absolutePath = storageService.getFilePath(fileUrl);
  1194. java.io.File localFile = new java.io.File(absolutePath);
  1195. if (!localFile.exists()) {
  1196. return Result.error("文件不存在或已过期: " + originalFilename);
  1197. }
  1198. return parseLocalFallback(absolutePath, draft, familyId, userId);
  1199. } catch (Exception e) {
  1200. log.error("文件解析失败", e);
  1201. return Result.error("解析失败: " + e.getMessage());
  1202. }
  1203. }
  1204. /**
  1205. * 构造 LangGraph 解析结果(复用 parsePreview 中的逻辑)
  1206. */
  1207. private Result<Map<String, Object>> buildParseResultFromLg(
  1208. Map<String, Object> lgData, HealthReportDraft draft,
  1209. Long familyId) throws Exception {
  1210. ParsedReportPayload.Payload lgPayload = buildPayloadFromLgData(lgData);
  1211. String payloadJson = objectMapper.writeValueAsString(lgPayload);
  1212. healthReportDraftService.updatePayload(draft.getId(), payloadJson);
  1213. Map<String, Object> overview = (Map<String, Object>) lgData.get("overview");
  1214. String personName = overview != null ? (String) overview.get("person_name") : null;
  1215. String gender = overview != null ? (String) overview.get("gender") : null;
  1216. Integer age = overview != null ? toInteger(overview.get("age")) : null;
  1217. MemberMatchResult matchResult = healthReportService.matchMemberByProfile(
  1218. personName, gender, age, familyId);
  1219. Map<String, Object> result = new LinkedHashMap<>();
  1220. result.put("draftId", draft.getId());
  1221. result.put("payload", lgPayload);
  1222. result.put("matchedMemberId", matchResult.getMatchedMemberId());
  1223. result.put("confidence", matchResult.getConfidence());
  1224. result.put("matchLabel", matchResult.getMatchLabel());
  1225. result.put("candidates", matchResult.getCandidates());
  1226. result.put("extractedName", personName);
  1227. result.put("extractedGender", gender);
  1228. result.put("extractedAge", age);
  1229. result.put("needBind", matchResult.getMatchedMemberId() == null && familyId != null);
  1230. try {
  1231. saveResultToJsonFile(result);
  1232. } catch (Exception e) {
  1233. log.warn("保存结果到 JSON 文件失败:{}", e.getMessage());
  1234. }
  1235. return Result.success(result);
  1236. }
  1237. /**
  1238. * 本地 Java 解析回退
  1239. */
  1240. private Result<Map<String, Object>> parseLocalFallback(
  1241. String absolutePath, HealthReportDraft draft, Long familyId, Long userId)
  1242. throws Exception {
  1243. try (java.io.FileInputStream fis = new java.io.FileInputStream(absolutePath)) {
  1244. ParsedReportResult parsed = pdfParseService.parse(fis);
  1245. if (parsed.getOverallScore() == null && parsed.getGutHealthScore() == null) {
  1246. return Result.error("无法解析PDF文件,请确认是募极生物肠道菌群报告");
  1247. }
  1248. ParsedReportPayload.Payload payload = convertToPayload(parsed);
  1249. String payloadJson = objectMapper.writeValueAsString(payload);
  1250. healthReportDraftService.updatePayload(draft.getId(), payloadJson);
  1251. MemberMatchResult matchResult = healthReportService.matchMemberByProfile(
  1252. parsed.getPersonName(), parsed.getGender(), parsed.getAge(), familyId);
  1253. Map<String, Object> result = new LinkedHashMap<>();
  1254. result.put("draftId", draft.getId());
  1255. result.put("payload", payload);
  1256. result.put("matchedMemberId", matchResult.getMatchedMemberId());
  1257. result.put("confidence", matchResult.getConfidence());
  1258. result.put("matchLabel", matchResult.getMatchLabel());
  1259. result.put("candidates", matchResult.getCandidates());
  1260. result.put("extractedName", parsed.getPersonName());
  1261. result.put("extractedGender", parsed.getGender());
  1262. result.put("extractedAge", parsed.getAge());
  1263. // B1-1:前端预览三行(被检测人/报告编号/报告日期)还读这两个字段,补齐避免恒 '-'
  1264. result.put("extractedReportNumber", parsed.getReportNumber());
  1265. result.put("extractedReportDate", parsed.getReportDate());
  1266. result.put("needBind", matchResult.getMatchedMemberId() == null && familyId != null);
  1267. return Result.success(result);
  1268. }
  1269. }
  1270. /**
  1271. * 两阶段入库 Phase 1: 上传PDF → 解析 → 存草稿 → 返回draftId + 解析载荷 + 成员匹配
  1272. * 不落库到 health_reports 等正式表。支持 PDF 解析(auto)和图片上传(image)。
  1273. *
  1274. * @deprecated 使用 /report/upload(仅上传)+ /report/parse(按草稿解析)替代
  1275. */
  1276. @Operation(summary = "上传解析报告(预览,不入库)")
  1277. @PostMapping("/report/parse-preview")
  1278. public Result<Map<String, Object>> parsePreview(
  1279. @RequestParam("file") MultipartFile file,
  1280. @RequestParam(value = "type", defaultValue = "auto") String type,
  1281. @RequestAttribute(value = "familyId", required = false) Long familyId,
  1282. @RequestParam(value = "memberId", required = false) Long memberId,
  1283. @RequestAttribute("userId") Long userId) {
  1284. if ("tongue".equals(type)) {
  1285. if (memberId == null) {
  1286. return Result.error("memberId is required for tongue diagnosis");
  1287. }
  1288. Map<String, Object> result = tongueDiagnosisService.parsePreview(file, memberId);
  1289. return Result.success(result);
  1290. }
  1291. if (file == null || file.isEmpty()) {
  1292. return Result.error("文件不能为空");
  1293. }
  1294. String contentType = file.getContentType();
  1295. String originalFilename = file.getOriginalFilename();
  1296. try {
  1297. // 图片上传:保存文件 + 创建空草稿(无自动解析)
  1298. if ("image".equals(type) || isImageContent(contentType)) {
  1299. // 图片内容安全检测
  1300. try {
  1301. byte[] imageBytes = file.getBytes();
  1302. if (!wechatService.checkImage(imageBytes)) {
  1303. return Result.error("图片内容包含敏感信息,上传失败");
  1304. }
  1305. } catch (IOException e) {
  1306. return Result.error("图片读取失败: " + e.getMessage());
  1307. }
  1308. String fileUrl = storageService.storeFile(file, "health-reports");
  1309. String reportType = familyId != null ? "physical_exam" : "gut_flora";
  1310. // 创建空载荷草稿,后续由 confirm 阶段用户补充
  1311. ParsedReportPayload.Payload emptyPayload = new ParsedReportPayload.Payload();
  1312. String payloadJson = objectMapper.writeValueAsString(emptyPayload);
  1313. HealthReportDraft draft = healthReportDraftService.createDraft(
  1314. userId, familyId, reportType, fileUrl, originalFilename, payloadJson);
  1315. Map<String, Object> result = new LinkedHashMap<>();
  1316. result.put("draftId", draft.getId());
  1317. result.put("payload", emptyPayload);
  1318. result.put("fileUrl", fileUrl);
  1319. result.put("needBind", false);
  1320. return Result.success(result);
  1321. }
  1322. // PDF 解析(默认路径)
  1323. String lcName = originalFilename != null ? originalFilename.toLowerCase() : "";
  1324. if (!lcName.endsWith(".pdf")
  1325. && (contentType == null || !contentType.equalsIgnoreCase("application/pdf"))) {
  1326. return Result.error("仅支持PDF文件");
  1327. }
  1328. // 保存文件(通过 StorageService 支持本地磁盘或京东云 OSS)
  1329. String fileUrl = storageService.storeFile(file, "health-reports");
  1330. // 尝试 LangGraph 解析(LangGraph 只认本地路径,必须经 getFilePath 下载到共享卷)
  1331. try {
  1332. Map<String, Object> lgRequest = new HashMap<>();
  1333. lgRequest.put("file_path", storageService.getFilePath(fileUrl));
  1334. lgRequest.put("user_id", userId);
  1335. if (familyId != null) {
  1336. lgRequest.put("family_id", familyId);
  1337. }
  1338. ResponseEntity<Map> lgResponse = restTemplate.postForEntity(
  1339. langgraphBaseUrl + "/api/v1/report/parse", lgRequest, Map.class);
  1340. Map<String, Object> lgBody = lgResponse.getBody();
  1341. if (lgBody != null && Integer.valueOf(200).equals(lgBody.get("code"))) {
  1342. Map<String, Object> lgData = (Map<String, Object>) lgBody.get("data");
  1343. if (lgData != null) {
  1344. ParsedReportPayload.Payload lgPayload = buildPayloadFromLgData(lgData);
  1345. String payloadJson = objectMapper.writeValueAsString(lgPayload);
  1346. HealthReportDraft draft = healthReportDraftService.createDraft(
  1347. userId, familyId, "gut_flora", fileUrl, originalFilename, payloadJson);
  1348. Map<String, Object> overview = (Map<String, Object>) lgData.get("overview");
  1349. String personName = overview != null ? (String) overview.get("person_name") : null;
  1350. String gender = overview != null ? (String) overview.get("gender") : null;
  1351. Integer age = overview != null ? toInteger(overview.get("age")) : null;
  1352. MemberMatchResult matchResult = healthReportService.matchMemberByProfile(
  1353. personName, gender, age, familyId);
  1354. Map<String, Object> result = new LinkedHashMap<>();
  1355. result.put("draftId", draft.getId());
  1356. result.put("payload", lgPayload);
  1357. result.put("matchedMemberId", matchResult.getMatchedMemberId());
  1358. result.put("confidence", matchResult.getConfidence());
  1359. result.put("matchLabel", matchResult.getMatchLabel());
  1360. result.put("candidates", matchResult.getCandidates());
  1361. result.put("extractedName", personName);
  1362. result.put("extractedGender", gender);
  1363. result.put("extractedAge", age);
  1364. result.put("needBind", matchResult.getMatchedMemberId() == null && familyId != null);
  1365. try {
  1366. saveResultToJsonFile(result);
  1367. } catch (Exception e) {
  1368. log.warn("保存结果到 JSON 文件失败:{}", e.getMessage());
  1369. }
  1370. return Result.success(result);
  1371. }
  1372. }
  1373. } catch (Exception e) {
  1374. log.warn("LangGraph 解析失败,回退到本地 Java 解析: {}", e.getMessage());
  1375. }
  1376. // Fallback: 本地 Java 解析
  1377. ParsedReportResult parsed = pdfParseService.parse(file.getInputStream());
  1378. if (parsed.getOverallScore() == null && parsed.getGutHealthScore() == null) {
  1379. return Result.error("无法解析PDF文件,请确认是募极生物肠道菌群报告");
  1380. }
  1381. ParsedReportPayload.Payload payload = convertToPayload(parsed);
  1382. String payloadJson = objectMapper.writeValueAsString(payload);
  1383. HealthReportDraft draft = healthReportDraftService.createDraft(
  1384. userId, familyId, "gut_flora", fileUrl, originalFilename, payloadJson);
  1385. // 使用多字段匹配(姓名+性别+年龄)
  1386. MemberMatchResult matchResult = healthReportService.matchMemberByProfile(
  1387. parsed.getPersonName(),
  1388. parsed.getGender(),
  1389. parsed.getAge(),
  1390. familyId
  1391. );
  1392. Map<String, Object> result = new LinkedHashMap<>();
  1393. result.put("draftId", draft.getId());
  1394. result.put("payload", payload);
  1395. result.put("matchedMemberId", matchResult.getMatchedMemberId());
  1396. result.put("confidence", matchResult.getConfidence());
  1397. result.put("matchLabel", matchResult.getMatchLabel());
  1398. result.put("candidates", matchResult.getCandidates());
  1399. result.put("extractedName", parsed.getPersonName());
  1400. result.put("extractedGender", parsed.getGender());
  1401. result.put("extractedAge", parsed.getAge());
  1402. result.put("needBind", matchResult.getMatchedMemberId() == null && familyId != null);
  1403. // 保存结果到本地 JSON 文件
  1404. try {
  1405. saveResultToJsonFile(result);
  1406. } catch (Exception e) {
  1407. log.warn("保存结果到 JSON 文件失败:{}", e.getMessage());
  1408. // 不影响主要流程,只是记录警告
  1409. }
  1410. return Result.success(result);
  1411. } catch (IOException e) {
  1412. log.error("文件处理失败", e);
  1413. return Result.error("文件处理失败: " + e.getMessage());
  1414. }
  1415. }
  1416. /**
  1417. * 判断是否为图片 MIME 类型
  1418. */
  1419. private boolean isImageContent(String contentType) {
  1420. if (contentType == null) return false;
  1421. return contentType.startsWith("image/");
  1422. }
  1423. /**
  1424. * 两阶段入库 Phase 2: 确认草稿 → 写入正式表 → 刷新7维评分
  1425. * 前端可回传修改后的 payload(用户在线编辑指标后整体提交)。
  1426. */
  1427. @Operation(summary = "确认报告草稿(正式入库)")
  1428. @PostMapping("/report/confirm")
  1429. public Result<Map<String, Object>> confirmDraft(
  1430. @RequestParam(value = "type", defaultValue = "pdf") String type,
  1431. @RequestBody Map<String, Object> params,
  1432. @RequestAttribute("userId") Long userId) {
  1433. if ("tongue".equals(type)) {
  1434. Long recordId = ParamUtils.getLong(params.get("recordId"));
  1435. Long subjectId = ParamUtils.getLong(params.get("subjectId"));
  1436. @SuppressWarnings("unchecked")
  1437. List<Map<String, Object>> indicators = (List<Map<String, Object>>) params.getOrDefault("indicators", null);
  1438. Map<String, Object> result = tongueDiagnosisService.confirm(recordId, indicators, subjectId);
  1439. return Result.success(result);
  1440. }
  1441. Long draftId = ParamUtils.getLong(params.get("draftId"));
  1442. if (draftId == null) {
  1443. return Result.error("draftId不能为空");
  1444. }
  1445. HealthReportDraft draft = healthReportDraftService.getActiveDraft(draftId);
  1446. if (draft == null || "confirmed".equals(draft.getStatus()) || "discarded".equals(draft.getStatus())) {
  1447. return Result.error("草稿不存在、已确认或已过期");
  1448. }
  1449. if (!draft.getUserId().equals(userId)) {
  1450. return Result.error("无权操作此草稿");
  1451. }
  1452. try {
  1453. ParsedReportPayload.Payload payload;
  1454. Object payloadObj = params.get("payload");
  1455. String payloadJson;
  1456. if (payloadObj != null) {
  1457. payloadJson = objectMapper.writeValueAsString(payloadObj);
  1458. payload = objectMapper.readValue(payloadJson, ParsedReportPayload.Payload.class);
  1459. } else {
  1460. payloadJson = draft.getPayloadJson();
  1461. payload = objectMapper.readValue(payloadJson, ParsedReportPayload.Payload.class);
  1462. }
  1463. Long subjectId = ParamUtils.getLong(params.get("subjectId"));
  1464. HealthReport report = buildReportFromPayload(draft, payload, subjectId);
  1465. List<HealthIndicator> indicators = buildIndicatorsFromPayload(payload);
  1466. List<HealthGutFlora> gutFlora = buildGutFloraFromPayload(payload);
  1467. List<HealthDiseaseRisk> diseaseRisks = buildDiseaseRisksFromPayload(payload);
  1468. HealthReport created = healthReportService.createReport(report, indicators, gutFlora, diseaseRisks);
  1469. // G2(DS-2026-10-25-01):confirm 链路补写统一指标层时序(失败不阻断确认)
  1470. try {
  1471. normalizeIndicatorPipeline.processReport(created, payload);
  1472. } catch (Exception e) {
  1473. log.warn("confirm 归一化管道写入失败 reportId={}: {}", created.getId(), e.getMessage());
  1474. }
  1475. // 落库 payload 快照 + 创建日志
  1476. healthReportService.savePayloadSnapshot(created.getId(), userId, "create", null, payloadJson);
  1477. if (payload.getFoods() != null && !payload.getFoods().isEmpty()) {
  1478. List<Food> foods = buildFoodsFromPayload(payload);
  1479. foodService.saveFoodsForReport(created.getId(), foods);
  1480. }
  1481. if (subjectId != null) {
  1482. healthReportService.bindReportToMember(created.getId(), subjectId);
  1483. try {
  1484. dimensionScoreService.refreshFromGutReport(subjectId, created.getId());
  1485. log.info("已刷新成员{}的7维健康评分", subjectId);
  1486. } catch (Exception e) {
  1487. log.warn("刷新7维健康评分失败: {}", e.getMessage());
  1488. }
  1489. try {
  1490. healthReportService.refreshMemberIndicatorCurrent(subjectId, created.getId());
  1491. log.info("已刷新成员{}的指标当前值diff", subjectId);
  1492. } catch (Exception e) {
  1493. log.warn("刷新指标当前值diff失败: {}", e.getMessage());
  1494. }
  1495. try {
  1496. foodRecommendService.recalculateForUser(subjectId);
  1497. log.info("已刷新成员{}的食材推荐指数", subjectId);
  1498. } catch (Exception e) {
  1499. log.warn("刷新食材推荐指数失败: {}", e.getMessage());
  1500. }
  1501. } else if (draft.getFamilyId() != null && payload.getSummary() != null
  1502. && payload.getSummary().getPersonName() != null) {
  1503. Long matchedId = healthReportService.matchFamilyMemberByName(
  1504. payload.getSummary().getPersonName(), draft.getFamilyId());
  1505. if (matchedId != null) {
  1506. healthReportService.bindReportToMember(created.getId(), matchedId);
  1507. try {
  1508. dimensionScoreService.refreshFromGutReport(matchedId, created.getId());
  1509. } catch (Exception e) {
  1510. log.warn("刷新7维健康评分失败: {}", e.getMessage());
  1511. }
  1512. try {
  1513. healthReportService.refreshMemberIndicatorCurrent(matchedId, created.getId());
  1514. log.info("已刷新成员{}的指标当前值diff", matchedId);
  1515. } catch (Exception e) {
  1516. log.warn("刷新指标当前值diff失败: {}", e.getMessage());
  1517. }
  1518. try {
  1519. foodRecommendService.recalculateForUser(matchedId);
  1520. log.info("已刷新成员{}的食材推荐指数", matchedId);
  1521. } catch (Exception e) {
  1522. log.warn("刷新食材推荐指数失败: {}", e.getMessage());
  1523. }
  1524. subjectId = matchedId;
  1525. }
  1526. }
  1527. healthReportDraftService.markConfirmed(draftId, created.getId());
  1528. // 幂等短路(S-cfc-363 / RED-1):markConfirmed 后同步将本地草稿置为非 pending 态,
  1529. // 使并发/重复确认(getActiveDraft 返回同一草稿实例)在入口快速拒绝,避免重复入库 + 重复刷新评分
  1530. draft.setStatus("confirmed");
  1531. draft.setConfirmedReportId(created.getId());
  1532. // 落库通用展示块(blocks 组装失败不阻断确认)
  1533. try {
  1534. String reportType = created.getReportType();
  1535. reportBlockService.save(reportType, created.getId(),
  1536. reportBlockAssembler.assembleWithTemplate(reportType, payload));
  1537. } catch (Exception e) {
  1538. log.warn("保存展示块失败 reportId={}: {}", created.getId(), e.getMessage());
  1539. }
  1540. Map<String, Object> detail = healthReportService.getReportDetail(created.getId());
  1541. if (subjectId != null) {
  1542. detail.put("subjectId", subjectId);
  1543. }
  1544. detail.put("reportId", created.getId());
  1545. detail.put("reportType", created.getReportType());
  1546. triggerAutoPlanAfterConfirm(detail, draft.getFamilyId(), subjectId, created.getReportType());
  1547. return Result.success(detail);
  1548. } catch (Exception e) {
  1549. log.error("确认草稿失败", e);
  1550. return Result.error("确认草稿失败: " + e.getMessage());
  1551. }
  1552. }
  1553. /** 报告确认入库后自动生成并发布健康方案(舌诊等不适用类型跳过) */
  1554. private void triggerAutoPlanAfterConfirm(Map<String, Object> detail, Long familyId,
  1555. Long subjectId, String reportType) {
  1556. if (familyId == null || subjectId == null || !shouldAutoGeneratePlan(reportType)) {
  1557. return;
  1558. }
  1559. try {
  1560. Long planId = healthPlanService.autoGenerateAndPublish(familyId, subjectId, reportType);
  1561. if (planId != null) {
  1562. detail.put("planId", planId);
  1563. }
  1564. } catch (Exception e) {
  1565. log.warn("确认入库后自动生成方案失败 reportType={}: {}", reportType, e.getMessage());
  1566. }
  1567. }
  1568. private boolean shouldAutoGeneratePlan(String reportType) {
  1569. return reportType != null && !"tongue".equals(reportType);
  1570. }
  1571. /**
  1572. * 放弃草稿
  1573. */
  1574. @Operation(summary = "放弃报告草稿")
  1575. @PostMapping("/report/discard")
  1576. public Result<String> discardDraft(
  1577. @RequestParam(value = "type", defaultValue = "pdf") String type,
  1578. @RequestBody Map<String, Object> params,
  1579. @RequestAttribute("userId") Long userId) {
  1580. if ("tongue".equals(type)) {
  1581. Long recordId = ParamUtils.getLong(params.get("recordId"));
  1582. tongueDiagnosisService.discard(recordId);
  1583. return Result.success("草稿已删除");
  1584. }
  1585. Long draftId = ParamUtils.getLong(params.get("draftId"));
  1586. if (draftId == null) {
  1587. return Result.error("draftId不能为空");
  1588. }
  1589. HealthReportDraft draft = healthReportDraftService.getActiveDraft(draftId);
  1590. if (draft == null) {
  1591. return Result.error("草稿不存在或已处理");
  1592. }
  1593. if (!draft.getUserId().equals(userId)) {
  1594. return Result.error("无权操作此草稿");
  1595. }
  1596. healthReportDraftService.markDiscarded(draftId);
  1597. return Result.success("草稿已放弃");
  1598. }
  1599. /**
  1600. * 手动绑定报告到家庭成员
  1601. */
  1602. @Operation(summary = "绑定报告到成员")
  1603. @PostMapping("/report/bind")
  1604. public Result<String> bindReport(
  1605. @RequestBody Map<String, Object> params) {
  1606. Long reportId = ParamUtils.getLong(params.get("reportId"));
  1607. Long subjectId = ParamUtils.getLong(params.get("subjectId"));
  1608. if (reportId == null || subjectId == null) {
  1609. return Result.error("reportId和subjectId不能为空");
  1610. }
  1611. healthReportService.bindReportToMember(reportId, subjectId);
  1612. return Result.success("报告绑定成功");
  1613. }
  1614. /**
  1615. * 重新分配报告归属
  1616. *
  1617. * <p>将报告从旧归属切换到新归属,或解除归属(subjectId 设为 null)。
  1618. * 归属变更后自动重新计算五维能量维度和食材推荐指数。</p>
  1619. *
  1620. * <p>权限检查:仅家庭成员或管理员可操作,通过 familyId 验证报告归属。</p>
  1621. *
  1622. * @param params 请求体:reportId (必填), subjectId (可为 null 表示解绑)
  1623. * @param familyId 当前登录用户的家庭ID(由 JwtInterceptor 注入)
  1624. * @return 操作结果
  1625. */
  1626. @PostMapping("/report/reassign")
  1627. public Result<String> reassignReport(@RequestBody Map<String, Object> params,
  1628. @RequestAttribute(value = "familyId", required = false) Long familyId) {
  1629. Long reportId = ParamUtils.getLong(params.get("reportId"));
  1630. Long newSubjectId = ParamUtils.getLong(params.get("subjectId")); // null = unbind
  1631. healthReportService.reassignReport(reportId, newSubjectId, familyId);
  1632. return Result.success("归属已更新");
  1633. }
  1634. /**
  1635. * 发起报告跨家庭转移申请(申请方家庭)
  1636. *
  1637. * <p>同一份报告(文件MD5相同)已被其他家庭上传时,上传接口返回 crossFamily=true,
  1638. * 前端弹窗确认后调用本接口发起申请;原家庭在「健康报告」列表同意后报告转入本家庭。</p>
  1639. *
  1640. * @param params 请求体:reportId (必填)
  1641. * @param familyId 当前登录用户的家庭ID(申请方,由 JwtInterceptor 注入)
  1642. * @param userId 当前登录用户ID
  1643. * @return 转移申请摘要 {requestId, status}
  1644. */
  1645. @PostMapping("/report/transfer/request")
  1646. public Result<Map<String, Object>> requestReportTransfer(
  1647. @RequestBody Map<String, Object> params,
  1648. @RequestAttribute(value = "familyId", required = false) Long familyId,
  1649. @RequestAttribute("userId") Long userId) {
  1650. if (familyId == null) {
  1651. return Result.noFamily("请先创建或加入家庭");
  1652. }
  1653. Long reportId = ParamUtils.getLong(params.get("reportId"));
  1654. try {
  1655. ReportTransferRequest request = reportTransferService.createRequest(reportId, familyId, userId);
  1656. Map<String, Object> data = new LinkedHashMap<>();
  1657. data.put("requestId", request.getId());
  1658. data.put("status", request.getStatus());
  1659. return Result.success(data);
  1660. } catch (RuntimeException e) {
  1661. return Result.error(e.getMessage());
  1662. }
  1663. }
  1664. /**
  1665. * 同意转移(原归属家庭):报告 family_id 转入申请方,本家庭不再可见
  1666. */
  1667. @PostMapping("/report/transfer/approve")
  1668. public Result<String> approveReportTransfer(
  1669. @RequestBody Map<String, Object> params,
  1670. @RequestAttribute(value = "familyId", required = false) Long familyId,
  1671. @RequestAttribute("userId") Long userId) {
  1672. if (familyId == null) {
  1673. return Result.noFamily("请先创建或加入家庭");
  1674. }
  1675. Long requestId = ParamUtils.getLong(params.get("requestId"));
  1676. try {
  1677. reportTransferService.approve(requestId, familyId, userId);
  1678. return Result.success("已同意转移,报告已转入对方家庭");
  1679. } catch (RuntimeException e) {
  1680. return Result.error(e.getMessage());
  1681. }
  1682. }
  1683. /**
  1684. * 拒绝转移(原归属家庭):报告留在本家庭
  1685. */
  1686. @PostMapping("/report/transfer/deny")
  1687. public Result<String> denyReportTransfer(
  1688. @RequestBody Map<String, Object> params,
  1689. @RequestAttribute(value = "familyId", required = false) Long familyId,
  1690. @RequestAttribute("userId") Long userId) {
  1691. if (familyId == null) {
  1692. return Result.noFamily("请先创建或加入家庭");
  1693. }
  1694. Long requestId = ParamUtils.getLong(params.get("requestId"));
  1695. String remark = params.get("remark") != null ? String.valueOf(params.get("remark")) : null;
  1696. try {
  1697. reportTransferService.deny(requestId, familyId, userId, remark);
  1698. return Result.success("已拒绝该转移申请");
  1699. } catch (RuntimeException e) {
  1700. return Result.error(e.getMessage());
  1701. }
  1702. }
  1703. /**
  1704. * 查询本家庭相关的转移申请列表
  1705. *
  1706. * @return {incoming: 待本家庭处理(原归属方), outgoing: 本家庭发起的(申请方)}
  1707. */
  1708. @PostMapping("/report/transfer/list")
  1709. public Result<Map<String, Object>> listReportTransfers(
  1710. @RequestAttribute(value = "familyId", required = false) Long familyId) {
  1711. if (familyId == null) {
  1712. return Result.noFamily("请先创建或加入家庭");
  1713. }
  1714. return Result.success(reportTransferService.listRequests(familyId));
  1715. }
  1716. /**
  1717. * 获取某家庭中所有未绑定成员的报告列表
  1718. */
  1719. @PostMapping("/report/unlinked")
  1720. public Result<List<HealthReport>> getUnlinkedReports(
  1721. @RequestAttribute(value = "familyId", required = false) Long familyId) {
  1722. if (familyId == null) {
  1723. return Result.noFamily("请先创建或加入家庭");
  1724. }
  1725. List<HealthReport> reports = healthReportService.getUnlinkedReports(familyId);
  1726. return Result.success(reports);
  1727. }
  1728. /**
  1729. * 添加报告查看权限(授权家庭成员查看报告)
  1730. */
  1731. @Operation(summary = "添加报告查看权限")
  1732. @PostMapping("/report/permission/add")
  1733. public Result<String> addReportPermission(
  1734. @RequestBody Map<String, Object> params) {
  1735. Long reportId = ParamUtils.getLong(params.get("reportId"));
  1736. Long targetUserId = ParamUtils.getLong(params.get("userId"));
  1737. if (reportId == null || targetUserId == null) {
  1738. return Result.error("reportId和userId不能为空");
  1739. }
  1740. healthReportService.addReportPermission(reportId, targetUserId);
  1741. return Result.success("权限添加成功");
  1742. }
  1743. /**
  1744. * 移除报告查看权限
  1745. */
  1746. @Operation(summary = "移除报告查看权限")
  1747. @PostMapping("/report/permission/remove")
  1748. public Result<String> removeReportPermission(
  1749. @RequestBody Map<String, Object> params) {
  1750. Long reportId = ParamUtils.getLong(params.get("reportId"));
  1751. Long targetUserId = ParamUtils.getLong(params.get("userId"));
  1752. if (reportId == null || targetUserId == null) {
  1753. return Result.error("reportId和userId不能为空");
  1754. }
  1755. healthReportService.removeReportPermission(reportId, targetUserId);
  1756. return Result.success("权限移除成功");
  1757. }
  1758. /**
  1759. * 检查用户是否有报告查看权限
  1760. */
  1761. @Operation(summary = "检查报告查看权限")
  1762. @PostMapping("/report/permission/check")
  1763. public Result<Boolean> checkReportPermission(
  1764. @RequestBody Map<String, Object> params) {
  1765. Long reportId = ParamUtils.getLong(params.get("reportId"));
  1766. Long targetUserId = ParamUtils.getLong(params.get("userId"));
  1767. if (reportId == null || targetUserId == null) {
  1768. return Result.error("reportId和userId不能为空");
  1769. }
  1770. boolean hasPermission = healthReportService.hasReportPermission(reportId, targetUserId);
  1771. return Result.success(hasPermission);
  1772. }
  1773. @Operation(summary = "获取营养缺乏分析")
  1774. @PostMapping("/nutrition/deficiency")
  1775. public Result<List<NutritionDeficiencyRecord>> getDeficiencyAnalysis(
  1776. @RequestBody Map<String, Object> params) {
  1777. Long memberId = ParamUtils.getLong(params.get("memberId"));
  1778. if (memberId == null) {
  1779. return Result.error("memberId不能为空");
  1780. }
  1781. Long reportId = ParamUtils.getLong(params.get("reportId"));
  1782. List<NutritionDeficiencyRecord> records = nutritionDeficiencyService.analyzeDeficiency(memberId, reportId);
  1783. return Result.success(records);
  1784. }
  1785. @Operation(summary = "获取家庭成员营养档案")
  1786. @PostMapping("/nutrition/profile")
  1787. public Result<Map<String, Object>> getNutritionProfile(
  1788. @RequestBody Map<String, Object> params) {
  1789. Long memberId = ParamUtils.getLong(params.get("memberId"));
  1790. if (memberId == null) {
  1791. return Result.error("memberId不能为空");
  1792. }
  1793. Map<String, Object> profile = childNutritionProfileService.getProfile(memberId);
  1794. return Result.success(profile);
  1795. }
  1796. @Operation(summary = "获取营养缺乏摘要")
  1797. @PostMapping("/nutrition/deficiency-summary")
  1798. public Result<Map<String, Object>> getDeficiencySummary(
  1799. @RequestBody Map<String, Object> params) {
  1800. Long memberId = ParamUtils.getLong(params.get("memberId"));
  1801. if (memberId == null) {
  1802. return Result.error("memberId不能为空");
  1803. }
  1804. Map<String, Object> summary = childNutritionProfileService.getDeficiencySummary(memberId);
  1805. return Result.success(summary);
  1806. }
  1807. @Operation(summary = "获取报告趋势数据")
  1808. @PostMapping("/nutrition/trend")
  1809. public Result<Map<String, Object>> getReportTrendData(
  1810. @RequestBody Map<String, Object> params) {
  1811. Long memberId = ParamUtils.getLong(params.get("memberId"));
  1812. if (memberId == null) {
  1813. return Result.error("memberId不能为空");
  1814. }
  1815. Map<String, Object> trend = childNutritionProfileService.getReportTrendData(memberId);
  1816. return Result.success(trend);
  1817. }
  1818. @Operation(summary = "获取健康分析(含营养缺乏)")
  1819. @PostMapping("/analysis")
  1820. public Result<Map<String, Object>> getHealthAnalysis(
  1821. @RequestBody Map<String, Object> params) {
  1822. Long memberId = ParamUtils.getLong(params.get("memberId"));
  1823. if (memberId == null) {
  1824. return Result.error("memberId不能为空");
  1825. }
  1826. HealthAnalysisResult analysisResult = healthAnalysisService.analyzeLatestByUser(memberId);
  1827. List<NutritionDeficiencyRecord> deficiencyRecords = nutritionDeficiencyService.analyzeDeficiency(memberId, null);
  1828. Map<String, Object> result = new java.util.HashMap<>();
  1829. result.put("analysis", analysisResult);
  1830. result.put("deficiencyRecords", deficiencyRecords);
  1831. return Result.success(result);
  1832. }
  1833. @Operation(summary = "管理指标-营养素映射")
  1834. @PostMapping("/nutrition/mappings")
  1835. public Result<List<NutritionIndicatorMapping>> listMappings() {
  1836. List<NutritionIndicatorMapping> mappings = nutritionDeficiencyService.getAllMappings();
  1837. return Result.success(mappings);
  1838. }
  1839. @Operation(summary = "创建指标-营养素映射")
  1840. @PostMapping("/nutrition/mapping/create")
  1841. public Result<?> createMapping(@RequestBody NutritionIndicatorMapping mapping) {
  1842. nutritionDeficiencyService.saveMapping(mapping);
  1843. return Result.success(null);
  1844. }
  1845. @Operation(summary = "更新指标-营养素映射")
  1846. @PostMapping("/nutrition/mapping/update")
  1847. public Result<?> updateMapping(@RequestBody NutritionIndicatorMapping mapping) {
  1848. nutritionDeficiencyService.saveMapping(mapping);
  1849. return Result.success(null);
  1850. }
  1851. @Operation(summary = "删除指标-营养素映射")
  1852. @PostMapping("/nutrition/mapping/delete")
  1853. public Result<?> deleteMapping(@RequestBody Map<String, Object> params) {
  1854. Long id = ParamUtils.getLong(params.get("id"));
  1855. if (id == null) {
  1856. return Result.error("id不能为空");
  1857. }
  1858. nutritionDeficiencyService.deleteMapping(id);
  1859. return Result.success(null);
  1860. }
  1861. @Operation(summary = "获取食材推荐列表")
  1862. @PostMapping("/foods")
  1863. public Result<List<Food>> listFoods(@RequestBody(required = false) Map<String, Object> params,
  1864. @RequestAttribute(value = "userId", required = false) Long userId) {
  1865. Long reportId = params != null ? ParamUtils.getLong(params.get("reportId")) : null;
  1866. List<Food> foods;
  1867. if (reportId != null) {
  1868. // 指定报告:返回该报告的食材推荐
  1869. foods = foodService.listByReportId(reportId);
  1870. } else {
  1871. // 未指定报告:优先用 memberId(成员视角),其次 JWT userId(本人视角)
  1872. // food_recommend_idx 以 subjectId 维度写入,家庭主账号 JWT userId 查不到家庭成员的推荐。
  1873. // 成员视角须用 resolveMemberViewToUserId 归一(family_members.id → users.id),
  1874. // 规避 users 与 family_members.id 数值重叠时把成员误判为无关用户(家庭72 书宁宁案例)。
  1875. Long memberId = params != null ? ParamUtils.getLong(params.get("memberId")) : null;
  1876. Long uid;
  1877. if (memberId != null) {
  1878. Long resolved = foodRecommendService.resolveMemberViewToUserId(memberId);
  1879. uid = resolved != null ? resolved : -1L;
  1880. } else {
  1881. uid = userId != null ? userId : -1L;
  1882. }
  1883. foods = foodRecommendService.getCurrentFoodsAsFoodList(uid);
  1884. }
  1885. return Result.success(foods);
  1886. }
  1887. /**
  1888. * 归档报告
  1889. */
  1890. @Operation(summary = "归档健康报告")
  1891. @PostMapping("/report/archive")
  1892. public Result<String> archiveReport(
  1893. @RequestBody Map<String, Object> params) {
  1894. Long reportId = ParamUtils.getLong(params.get("reportId"));
  1895. if (reportId == null) {
  1896. return Result.error("reportId不能为空");
  1897. }
  1898. healthReportService.archiveReport(reportId);
  1899. return Result.success("报告已归档");
  1900. }
  1901. /**
  1902. * 批量归档报告(软删除)— 管理端选中删除
  1903. */
  1904. @Operation(summary = "批量归档健康报告(软删除)")
  1905. @PostMapping("/report/archive-batch")
  1906. public Result<String> archiveReportsBatch(
  1907. @RequestBody Map<String, Object> params,
  1908. @RequestAttribute(value = "role", required = false) String role) {
  1909. @SuppressWarnings("unchecked")
  1910. List<Long> reportIds = (List<Long>) params.get("reportIds");
  1911. if (reportIds == null || reportIds.isEmpty()) {
  1912. return Result.error("reportIds不能为空");
  1913. }
  1914. int archived = healthReportService.archiveReportsBatch(reportIds);
  1915. return Result.success("已归档 " + archived + " 份报告");
  1916. }
  1917. @Operation(summary = "获取家庭成员食材推荐(含完整营养数据)")
  1918. @PostMapping("/foods/by-family")
  1919. public Result<Map<String, Object>> getFoodsByFamily(@RequestAttribute(value = "familyId", required = false) Long familyId) {
  1920. if (familyId == null) {
  1921. return Result.noFamily("请先创建或加入家庭");
  1922. }
  1923. Map<Long, List<FoodRecommendIndex>> byMember = foodRecommendService.getByFamily(familyId);
  1924. Set<Long> foodIds = new HashSet<>();
  1925. Map<Long, String> memberNames = new LinkedHashMap<>();
  1926. for (Map.Entry<Long, List<FoodRecommendIndex>> entry : byMember.entrySet()) {
  1927. for (FoodRecommendIndex idx : entry.getValue()) {
  1928. foodIds.add(idx.getFoodId());
  1929. }
  1930. }
  1931. List<FamilyMember> members = familyMemberMapper.selectList(
  1932. new LambdaQueryWrapper<FamilyMember>().eq(FamilyMember::getFamilyId, familyId));
  1933. for (FamilyMember m : members) {
  1934. if (m.getUserId() != null) {
  1935. memberNames.put(m.getUserId(), m.getNickname() != null ? m.getNickname() : "");
  1936. }
  1937. }
  1938. List<Map<String, Object>> totalList = new ArrayList<>();
  1939. for (Long foodId : foodIds) {
  1940. Food food = foodService.getById(foodId);
  1941. if (food != null) {
  1942. Map<String, Object> item = new LinkedHashMap<>();
  1943. item.put("id", food.getId());
  1944. item.put("name", food.getName());
  1945. item.put("category", food.getCategory());
  1946. item.put("calories", food.getCalories());
  1947. item.put("protein", food.getProtein());
  1948. item.put("carbs", food.getCarbs());
  1949. item.put("fat", food.getFat());
  1950. item.put("fiber", food.getFiber());
  1951. item.put("energyKj", food.getEnergyKj());
  1952. item.put("starch", food.getStarch());
  1953. item.put("cholesterol", food.getCholesterol());
  1954. for (Map.Entry<Long, List<FoodRecommendIndex>> entry : byMember.entrySet()) {
  1955. for (FoodRecommendIndex idx : entry.getValue()) {
  1956. if (foodId.equals(idx.getFoodId())) {
  1957. item.put("recommendIndex", idx.getIndexScore());
  1958. break;
  1959. }
  1960. }
  1961. if (item.containsKey("recommendIndex")) break;
  1962. }
  1963. if (!item.containsKey("recommendIndex")) {
  1964. item.put("recommendIndex", null);
  1965. }
  1966. totalList.add(item);
  1967. }
  1968. }
  1969. Map<String, Object> result = new LinkedHashMap<>();
  1970. result.put("total", totalList);
  1971. result.put("byMember", byMember);
  1972. result.put("memberNames", memberNames);
  1973. // T28/迁移465:家庭总览分段聚合(family_food_overview,有成员<0取最低值、全员>=0取平均值),
  1974. // 无记录或旧规则历史行(overview_score 为 NULL)时后端先按新口径 backfill 再返回
  1975. result.put("overview", familyFoodOverviewService.getOverviewMaps(familyId));
  1976. return Result.success(result);
  1977. }
  1978. /**
  1979. * 自动创建家庭成员(从PDF身份信息)
  1980. */
  1981. @Operation(summary = "自动创建家庭成员")
  1982. @PostMapping("/report/auto-create-member")
  1983. public Result<Map<String, Object>> autoCreateMember(
  1984. @RequestBody Map<String, Object> params,
  1985. @RequestAttribute("userId") Long userId,
  1986. @RequestAttribute(value = "familyId", required = false) Long familyId) {
  1987. if (familyId == null) {
  1988. return Result.noFamily("请先创建或加入家庭");
  1989. }
  1990. String name = (String) params.get("name");
  1991. String gender = (String) params.get("gender");
  1992. Object ageObj = params.get("age");
  1993. Integer age = ageObj != null ? Integer.parseInt(ageObj.toString()) : null;
  1994. Long draftId = ParamUtils.getLong(params.get("draftId"));
  1995. if (name == null || name.trim().isEmpty()) {
  1996. return Result.error("姓名不能为空");
  1997. }
  1998. try {
  1999. String fileUrl = null;
  2000. String originalFilename = null;
  2001. String payloadJson = null;
  2002. if (draftId != null) {
  2003. HealthReportDraft draft = healthReportDraftService.getActiveDraft(draftId);
  2004. if (draft != null) {
  2005. fileUrl = draft.getFileUrl();
  2006. originalFilename = draft.getOriginalFilename();
  2007. payloadJson = draft.getPayloadJson();
  2008. }
  2009. }
  2010. Long memberId = healthReportService.autoCreateMemberFromReport(
  2011. name, gender, age, familyId, "gut_flora", fileUrl, originalFilename, payloadJson);
  2012. Map<String, Object> result = new LinkedHashMap<>();
  2013. result.put("memberId", memberId);
  2014. result.put("isNew", true);
  2015. result.put("name", name.trim());
  2016. return Result.success(result);
  2017. } catch (IllegalArgumentException e) {
  2018. return Result.error(e.getMessage());
  2019. } catch (Exception e) {
  2020. log.error("自动创建成员失败", e);
  2021. return Result.error("自动创建成员失败: " + e.getMessage());
  2022. }
  2023. }
  2024. /**
  2025. * 管理端:获取待审核报告草稿列表
  2026. */
  2027. @Operation(summary = "管理端:获取待审核报告草稿列表")
  2028. @PostMapping("/report/audit/pending")
  2029. public Result<List<HealthReportDraft>> listPendingAudits(
  2030. @RequestBody Map<String, Object> params) {
  2031. int page = params.get("page") != null ? Integer.parseInt(params.get("page").toString()) : 1;
  2032. int size = params.get("size") != null ? Integer.parseInt(params.get("size").toString()) : 20;
  2033. List<HealthReportDraft> drafts = healthReportService.listPendingAudits(page, size);
  2034. return Result.success(drafts);
  2035. }
  2036. /**
  2037. * 管理端:审核确认报告
  2038. */
  2039. @Operation(summary = "管理端:审核确认报告")
  2040. @PostMapping("/report/audit/confirm")
  2041. public Result<Map<String, Object>> auditConfirm(
  2042. @RequestBody Map<String, Object> params,
  2043. @RequestAttribute("userId") Long auditorId,
  2044. @RequestAttribute("role") String role,
  2045. @RequestAttribute("roles") List<String> roles) {
  2046. Long draftId = ParamUtils.getLong(params.get("draftId"));
  2047. Long subjectId = ParamUtils.getLong(params.get("subjectId"));
  2048. if (draftId == null) {
  2049. return Result.error("draftId不能为空");
  2050. }
  2051. try {
  2052. // B2-3:admin 判定——平台角色可确认任意草稿;非平台角色仅能确认自己创建的草稿
  2053. boolean isAdmin = "admin".equals(role) || AdminRoles.hasAnyPlatformRole(roles);
  2054. Map<String, Object> result = healthReportService.auditConfirm(draftId, subjectId, auditorId, isAdmin);
  2055. Long confirmedSubjectId = ParamUtils.getLong(result.get("subjectId"));
  2056. if (confirmedSubjectId != null) {
  2057. try {
  2058. foodRecommendService.recalculateForUser(confirmedSubjectId);
  2059. } catch (Exception e) {
  2060. log.warn("审核确认后刷新食材推荐失败: {}", e.getMessage());
  2061. }
  2062. }
  2063. return Result.success(result);
  2064. } catch (Exception e) {
  2065. log.error("审核确认失败", e);
  2066. return Result.error("审核确认失败: " + e.getMessage());
  2067. }
  2068. }
  2069. /**
  2070. * 管理端:审核丢弃报告
  2071. */
  2072. @Operation(summary = "管理端:审核丢弃报告")
  2073. @PostMapping("/report/audit/discard")
  2074. public Result<String> auditDiscard(
  2075. @RequestBody Map<String, Object> params) {
  2076. Long draftId = ParamUtils.getLong(params.get("draftId"));
  2077. if (draftId == null) {
  2078. return Result.error("draftId不能为空");
  2079. }
  2080. try {
  2081. healthReportService.auditDiscard(draftId);
  2082. return Result.success("报告已丢弃");
  2083. } catch (Exception e) {
  2084. log.error("审核丢弃失败", e);
  2085. return Result.error("审核丢弃失败: " + e.getMessage());
  2086. }
  2087. }
  2088. private ParsedReportPayload.Payload convertToPayload(ParsedReportResult parsed) {
  2089. ParsedReportPayload.Payload payload = new ParsedReportPayload.Payload();
  2090. ParsedReportPayload.Summary summary = new ParsedReportPayload.Summary();
  2091. summary.setOverallScore(parsed.getOverallScore());
  2092. summary.setGutHealthScore(parsed.getGutHealthScore());
  2093. summary.setChronicDiseaseScore(parsed.getChronicDiseaseScore());
  2094. summary.setNutritionScore(parsed.getNutritionScore());
  2095. summary.setBalanceScore(parsed.getBalanceScore());
  2096. summary.setDiversityScore(parsed.getDiversityScore());
  2097. summary.setBeneficialScore(parsed.getBeneficialScore());
  2098. summary.setHarmfulScore(parsed.getHarmfulScore());
  2099. summary.setCoreGenusScore(parsed.getCoreGenusScore());
  2100. summary.setGutAge(parsed.getGutAge());
  2101. summary.setGutType(parsed.getGutType());
  2102. summary.setReportNumber(parsed.getReportNumber());
  2103. summary.setReportDate(parsed.getReportDate());
  2104. summary.setPersonName(parsed.getPersonName());
  2105. summary.setGender(parsed.getGender());
  2106. summary.setAge(parsed.getAge());
  2107. summary.setBirthday(parsed.getBirthday());
  2108. payload.setSummary(summary);
  2109. if (parsed.getIndicators() != null) {
  2110. List<ParsedReportPayload.Indicator> indicators = new ArrayList<>();
  2111. for (ParsedIndicator pi : parsed.getIndicators()) {
  2112. ParsedReportPayload.Indicator ind = new ParsedReportPayload.Indicator();
  2113. ind.setCategory(pi.getCategory());
  2114. ind.setIndicatorName(pi.getIndicatorName());
  2115. ind.setIndicatorValue(pi.getIndicatorValue());
  2116. ind.setRefRange(pi.getRefRange());
  2117. ind.setStatus(pi.getStatus());
  2118. ind.setSymptoms(pi.getSymptoms());
  2119. indicators.add(ind);
  2120. }
  2121. payload.setIndicators(indicators);
  2122. }
  2123. if (parsed.getGutFlora() != null) {
  2124. List<ParsedReportPayload.Flora> gutFlora = new ArrayList<>();
  2125. for (ParsedGutFlora pgf : parsed.getGutFlora()) {
  2126. gutFlora.add(convertFlora(pgf));
  2127. }
  2128. payload.setGutFlora(gutFlora);
  2129. }
  2130. if (parsed.getProbioticSpecies() != null) {
  2131. List<ParsedReportPayload.Flora> probiotics = new ArrayList<>();
  2132. for (ParsedGutFlora pgf : parsed.getProbioticSpecies()) {
  2133. probiotics.add(convertFlora(pgf));
  2134. }
  2135. payload.setProbioticSpecies(probiotics);
  2136. }
  2137. if (parsed.getFoodSuitability() != null) {
  2138. List<ParsedReportPayload.FoodItem> foods = new ArrayList<>();
  2139. for (ParsedFoodSuitability pfs : parsed.getFoodSuitability()) {
  2140. ParsedReportPayload.FoodItem fi = new ParsedReportPayload.FoodItem();
  2141. fi.setName(pfs.getFoodName());
  2142. fi.setCategory(pfs.getCategory());
  2143. fi.setScore(pfs.getScore());
  2144. fi.setEnergyKj(pfs.getEnergyKj());
  2145. fi.setProtein(pfs.getProtein());
  2146. fi.setFat(pfs.getFat());
  2147. fi.setCarbs(pfs.getCarbs());
  2148. fi.setStarch(pfs.getStarch());
  2149. fi.setFiber(pfs.getFiber());
  2150. fi.setCholesterol(pfs.getCholesterol());
  2151. foods.add(fi);
  2152. }
  2153. payload.setFoods(foods);
  2154. }
  2155. if (parsed.getDiseaseRisks() != null) {
  2156. List<ParsedReportPayload.DiseaseRisk> risks = new ArrayList<>();
  2157. for (ParsedDiseaseRisk pdr : parsed.getDiseaseRisks()) {
  2158. ParsedReportPayload.DiseaseRisk dr = new ParsedReportPayload.DiseaseRisk();
  2159. dr.setDiseaseName(pdr.getDiseaseName());
  2160. dr.setRiskValue(pdr.getRiskValue());
  2161. dr.setRiskLevel(pdr.getRiskLevel());
  2162. risks.add(dr);
  2163. }
  2164. payload.setDiseaseRisks(risks);
  2165. }
  2166. return payload;
  2167. }
  2168. private ParsedReportPayload.Flora convertFlora(ParsedGutFlora pgf) {
  2169. ParsedReportPayload.Flora f = new ParsedReportPayload.Flora();
  2170. f.setBacteriaName(pgf.getBacteriaName());
  2171. f.setBacteriaValue(pgf.getBacteriaValue());
  2172. f.setNormalRange(pgf.getNormalRange());
  2173. f.setPopulationLevel(pgf.getPopulationLevel());
  2174. f.setDetectionRate(pgf.getDetectionRate());
  2175. f.setDescription(pgf.getDescription());
  2176. f.setCategory(pgf.getCategory());
  2177. f.setLevel(pgf.getLevel());
  2178. return f;
  2179. }
  2180. private ParsedReportPayload.Payload buildPayloadFromLgData(Map<String, Object> lgData) {
  2181. ParsedReportPayload.Payload payload = new ParsedReportPayload.Payload();
  2182. Map<String, Object> overview = (Map<String, Object>) lgData.get("overview");
  2183. if (overview != null) {
  2184. ParsedReportPayload.Summary summary = new ParsedReportPayload.Summary();
  2185. summary.setPersonName((String) overview.get("person_name"));
  2186. summary.setAge(toInteger(overview.get("age")));
  2187. summary.setGender((String) overview.get("gender"));
  2188. summary.setOverallScore(toInteger(overview.get("overallScore")));
  2189. summary.setGutHealthScore(toInteger(overview.get("gutHealthScore")));
  2190. summary.setChronicDiseaseScore(toInteger(overview.get("chronicDiseaseScore")));
  2191. summary.setNutritionScore(toInteger(overview.get("nutritionScore")));
  2192. summary.setBalanceScore(toInteger(overview.get("balanceScore")));
  2193. summary.setDiversityScore(toInteger(overview.get("diversityScore")));
  2194. summary.setBeneficialScore(toInteger(overview.get("beneficialScore")));
  2195. summary.setHarmfulScore(toInteger(overview.get("harmfulScore")));
  2196. summary.setCoreGenusScore(toInteger(overview.get("coreGenusScore")));
  2197. summary.setGutAge(objectToString(overview.get("gutAge")));
  2198. summary.setGutType(objectToString(overview.get("gutType")));
  2199. summary.setShannonIndex(objectToString(overview.get("shannonIndex")));
  2200. summary.setReportNumber(objectToString(overview.get("report_number")));
  2201. summary.setBirthday(objectToString(overview.get("birthday")));
  2202. payload.setSummary(summary);
  2203. }
  2204. List<Map<String, Object>> diseaseRisks = (List<Map<String, Object>>) lgData.get("disease_risks");
  2205. if (diseaseRisks != null) {
  2206. List<ParsedReportPayload.DiseaseRisk> risks = new ArrayList<>();
  2207. for (Map<String, Object> dr : diseaseRisks) {
  2208. ParsedReportPayload.DiseaseRisk risk = new ParsedReportPayload.DiseaseRisk();
  2209. risk.setDiseaseName((String) dr.get("name"));
  2210. risk.setRiskValue(objectToString(dr.get("value")));
  2211. risk.setRiskLevel((String) dr.get("status"));
  2212. risks.add(risk);
  2213. }
  2214. payload.setDiseaseRisks(risks);
  2215. }
  2216. List<Map<String, Object>> indicators = (List<Map<String, Object>>) lgData.get("indicators");
  2217. if (indicators != null) {
  2218. List<ParsedReportPayload.Indicator> inds = new ArrayList<>();
  2219. for (Map<String, Object> ind : indicators) {
  2220. ParsedReportPayload.Indicator indicator = new ParsedReportPayload.Indicator();
  2221. indicator.setCategory((String) ind.get("category"));
  2222. indicator.setIndicatorName((String) ind.get("indicatorName"));
  2223. indicator.setIndicatorValue(objectToString(ind.get("indicatorValue")));
  2224. indicator.setUnit((String) ind.get("unit"));
  2225. indicator.setRefRange((String) ind.get("refRange"));
  2226. indicator.setStatus((String) ind.get("status"));
  2227. indicator.setSymptoms((String) ind.get("symptoms"));
  2228. inds.add(indicator);
  2229. }
  2230. payload.setIndicators(inds);
  2231. }
  2232. // 菌群/饮食推荐分组(LangGraph 输出 snake_case 键,缺省时安全跳过)
  2233. payload.setGutFlora(convertLgFloraList(lgData.get("gut_flora")));
  2234. payload.setProbioticSpecies(convertLgFloraList(lgData.get("probiotic_species")));
  2235. payload.setTaxonomyClass(convertLgFloraList(lgData.get("taxonomy_class")));
  2236. payload.setTaxonomyOrder(convertLgFloraList(lgData.get("taxonomy_order")));
  2237. payload.setTaxonomyFamily(convertLgFloraList(lgData.get("taxonomy_family")));
  2238. payload.setTaxonomyGenus(convertLgFloraList(lgData.get("taxonomy_genus")));
  2239. payload.setTaxonomySpecies(convertLgFloraList(lgData.get("taxonomy_species")));
  2240. payload.setPathogenGenus(convertLgFloraList(lgData.get("pathogen_genus")));
  2241. payload.setPathogenDetection(convertLgFloraList(lgData.get("pathogen_detection")));
  2242. payload.setFoods(convertLgFoodList(lgData.get("foods")));
  2243. return payload;
  2244. }
  2245. /**
  2246. * 将 LangGraph 输出的菌群列表(snake_case 元素)转换为 ParsedReportPayload.Flora 列表。
  2247. * 键缺失或类型不符时安全返回空列表。
  2248. */
  2249. private List<ParsedReportPayload.Flora> convertLgFloraList(Object raw) {
  2250. List<ParsedReportPayload.Flora> floraList = new ArrayList<>();
  2251. if (!(raw instanceof List)) {
  2252. return floraList;
  2253. }
  2254. for (Object item : (List<?>) raw) {
  2255. if (!(item instanceof Map)) {
  2256. continue;
  2257. }
  2258. Map<String, Object> m = (Map<String, Object>) item;
  2259. ParsedReportPayload.Flora f = new ParsedReportPayload.Flora();
  2260. f.setBacteriaName(objectToString(m.get("name")));
  2261. f.setBacteriaValue(objectToString(m.get("value")));
  2262. f.setNormalRange(objectToString(m.get("normal_range")));
  2263. f.setPopulationLevel(objectToString(m.get("population_level")));
  2264. f.setDetectionRate(objectToString(m.get("detection_rate")));
  2265. f.setDescription(objectToString(m.get("description")));
  2266. f.setCategory(objectToString(m.get("category")));
  2267. f.setLevel(objectToString(m.get("level")));
  2268. if (f.getBacteriaName() == null && f.getDescription() == null) {
  2269. continue;
  2270. }
  2271. floraList.add(f);
  2272. }
  2273. return floraList;
  2274. }
  2275. /**
  2276. * 将 LangGraph 输出的饮食推荐列表(snake_case 元素)转换为 ParsedReportPayload.FoodItem 列表。
  2277. */
  2278. private List<ParsedReportPayload.FoodItem> convertLgFoodList(Object raw) {
  2279. List<ParsedReportPayload.FoodItem> foodList = new ArrayList<>();
  2280. if (!(raw instanceof List)) {
  2281. return foodList;
  2282. }
  2283. for (Object item : (List<?>) raw) {
  2284. if (!(item instanceof Map)) {
  2285. continue;
  2286. }
  2287. Map<String, Object> m = (Map<String, Object>) item;
  2288. ParsedReportPayload.FoodItem fi = new ParsedReportPayload.FoodItem();
  2289. fi.setName(objectToString(m.get("name")));
  2290. fi.setCategory(objectToString(m.get("category")));
  2291. fi.setScore(toInteger(m.get("score")));
  2292. fi.setEnergyKj(toDecimal(m.get("energy_kj")));
  2293. fi.setProtein(toDecimal(m.get("protein")));
  2294. fi.setFat(toDecimal(m.get("fat")));
  2295. fi.setCarbs(toDecimal(m.get("carbs")));
  2296. fi.setStarch(toDecimal(m.get("starch")));
  2297. fi.setFiber(toDecimal(m.get("fiber")));
  2298. fi.setCholesterol(toDecimal(m.get("cholesterol")));
  2299. if (fi.getName() == null) {
  2300. continue;
  2301. }
  2302. foodList.add(fi);
  2303. }
  2304. return foodList;
  2305. }
  2306. private static BigDecimal toDecimal(Object value) {
  2307. if (value == null) {
  2308. return null;
  2309. }
  2310. if (value instanceof BigDecimal) {
  2311. return (BigDecimal) value;
  2312. }
  2313. if (value instanceof Number) {
  2314. return BigDecimal.valueOf(((Number) value).doubleValue());
  2315. }
  2316. try {
  2317. return new BigDecimal(value.toString());
  2318. } catch (Exception e) {
  2319. return null;
  2320. }
  2321. }
  2322. private static Integer toInteger(Object value) {
  2323. if (value == null) return null;
  2324. if (value instanceof Integer) return (Integer) value;
  2325. if (value instanceof Number) return ((Number) value).intValue();
  2326. try {
  2327. return Integer.valueOf(value.toString());
  2328. } catch (Exception e) {
  2329. return null;
  2330. }
  2331. }
  2332. private static String objectToString(Object value) {
  2333. if (value == null) return null;
  2334. return value.toString();
  2335. }
  2336. private HealthReport buildReportFromPayload(HealthReportDraft draft, ParsedReportPayload.Payload payload, Long subjectId) {
  2337. HealthReport report = new HealthReport();
  2338. report.setUserId(draft.getUserId());
  2339. report.setFamilyId(draft.getFamilyId());
  2340. // A方案:subject_id 统一为 family_members.id 口径(users.id 归一化到成员卡)
  2341. report.setSubjectId(healthReportService.resolveSubjectToMemberId(subjectId, draft.getFamilyId()));
  2342. report.setReportType(draft.getReportType());
  2343. report.setFileUrl(draft.getFileUrl());
  2344. report.setReportFormat(payload.getReportFormat());
  2345. ParsedReportPayload.Summary s = payload.getSummary();
  2346. if (s != null) {
  2347. report.setOverallScore(s.getOverallScore());
  2348. report.setGutHealthScore(s.getGutHealthScore());
  2349. report.setChronicDiseaseScore(s.getChronicDiseaseScore());
  2350. report.setNutritionScore(s.getNutritionScore());
  2351. report.setBalanceScore(s.getBalanceScore());
  2352. report.setDiversityScore(s.getDiversityScore());
  2353. report.setBeneficialScore(s.getBeneficialScore());
  2354. report.setHarmfulScore(s.getHarmfulScore());
  2355. report.setCoreGenusScore(s.getCoreGenusScore());
  2356. report.setGutAge(s.getGutAge());
  2357. report.setGutType(s.getGutType());
  2358. report.setShannonIndex(s.getShannonIndex());
  2359. report.setReportNumber(s.getReportNumber());
  2360. report.setPersonName(s.getPersonName());
  2361. if (s.getReportDate() != null && !s.getReportDate().isEmpty()) {
  2362. try {
  2363. java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
  2364. report.setReportDate(sdf.parse(s.getReportDate()));
  2365. } catch (Exception e) {
  2366. report.setReportDate(new Date());
  2367. }
  2368. } else {
  2369. report.setReportDate(new Date());
  2370. }
  2371. } else {
  2372. report.setReportDate(new Date());
  2373. }
  2374. report.setRemark("募极生物肠道菌群检测报告");
  2375. return report;
  2376. }
  2377. private List<HealthIndicator> buildIndicatorsFromPayload(ParsedReportPayload.Payload payload) {
  2378. List<ParsedReportPayload.Indicator> list = payload.getIndicators();
  2379. if (list == null || list.isEmpty()) return new ArrayList<>();
  2380. List<HealthIndicator> indicators = new ArrayList<>();
  2381. for (int i = 0; i < list.size(); i++) {
  2382. ParsedReportPayload.Indicator pi = list.get(i);
  2383. HealthIndicator ind = new HealthIndicator();
  2384. ind.setCategory(pi.getCategory());
  2385. ind.setIndicatorName(pi.getIndicatorName());
  2386. ind.setIndicatorValue(pi.getIndicatorValue());
  2387. ind.setUnit(pi.getUnit());
  2388. ind.setRefRange(pi.getRefRange());
  2389. ind.setStatus(pi.getStatus());
  2390. ind.setSymptoms(pi.getSymptoms());
  2391. ind.setSortOrder(i);
  2392. if (pi.getCollectionDate() != null && !pi.getCollectionDate().isEmpty()) {
  2393. try {
  2394. java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
  2395. ind.setCollectionDate(sdf.parse(pi.getCollectionDate()));
  2396. } catch (Exception e) {
  2397. // ignore parse error
  2398. }
  2399. }
  2400. indicators.add(ind);
  2401. }
  2402. return indicators;
  2403. }
  2404. private List<HealthGutFlora> buildGutFloraFromPayload(ParsedReportPayload.Payload payload) {
  2405. List<HealthGutFlora> result = new ArrayList<>();
  2406. addFloraList(result, payload.getGutFlora());
  2407. addFloraList(result, payload.getProbioticSpecies());
  2408. addFloraList(result, payload.getTaxonomyClass());
  2409. addFloraList(result, payload.getTaxonomyOrder());
  2410. addFloraList(result, payload.getTaxonomyFamily());
  2411. addFloraList(result, payload.getTaxonomyGenus());
  2412. addFloraList(result, payload.getTaxonomySpecies());
  2413. addFloraList(result, payload.getPathogenGenus());
  2414. addFloraList(result, payload.getPathogenDetection());
  2415. return result;
  2416. }
  2417. private void addFloraList(List<HealthGutFlora> target, List<ParsedReportPayload.Flora> source) {
  2418. if (source != null) {
  2419. for (ParsedReportPayload.Flora pf : source) {
  2420. target.add(convertToGutFlora(pf));
  2421. }
  2422. }
  2423. }
  2424. private HealthGutFlora convertToGutFlora(ParsedReportPayload.Flora pf) {
  2425. HealthGutFlora gf = new HealthGutFlora();
  2426. gf.setBacteriaName(pf.getBacteriaName());
  2427. gf.setBacteriaValue(pf.getBacteriaValue());
  2428. gf.setNormalRange(pf.getNormalRange());
  2429. gf.setPopulationLevel(pf.getPopulationLevel());
  2430. gf.setDetectionRate(pf.getDetectionRate());
  2431. gf.setDescription(pf.getDescription());
  2432. // 分类层级表归一化:募极/北京的"菌纲构成/菌目构成..."→ taxonomy + 英文LEVEL,
  2433. // 否则前端 taxonomy 标签页按 category='taxonomy' + level='CLASS' 过滤匹配不到
  2434. gf.setCategory(normalizeFloraCategory(pf.getCategory()));
  2435. gf.setLevel(normalizeFloraLevel(pf.getCategory(), pf.getLevel()));
  2436. return gf;
  2437. }
  2438. /**
  2439. * 菌群分类归一化:以"构成"结尾的层级分类(菌门构成/菌纲构成/菌目构成/菌科构成/菌属构成/菌种构成)
  2440. * 统一映射为 taxonomy,与前端标签页过滤条件对齐。
  2441. */
  2442. private String normalizeFloraCategory(String category) {
  2443. if (category == null) return null;
  2444. if (category.endsWith("构成")) {
  2445. return HealthGutFlora.CATEGORY_TAXONOMY; // "taxonomy"
  2446. }
  2447. return category;
  2448. }
  2449. /**
  2450. * 菌群层级归一化:中文层级(门/纲/目/科/属/种)→ 英文 LEVEL 常量,
  2451. * 与前端 levelMap 对齐。非层级数据(如 category=核心菌属 且 level=GENUS)原样保留。
  2452. */
  2453. private String normalizeFloraLevel(String category, String level) {
  2454. if (level == null) return null;
  2455. String normalized = level;
  2456. if ("门".equals(level)) normalized = HealthGutFlora.LEVEL_PHYLUM;
  2457. else if ("纲".equals(level)) normalized = HealthGutFlora.LEVEL_CLASS;
  2458. else if ("目".equals(level)) normalized = HealthGutFlora.LEVEL_ORDER;
  2459. else if ("科".equals(level)) normalized = HealthGutFlora.LEVEL_FAMILY;
  2460. else if ("属".equals(level)) normalized = HealthGutFlora.LEVEL_GENUS;
  2461. else if ("种".equals(level)) normalized = HealthGutFlora.LEVEL_SPECIES;
  2462. return normalized;
  2463. }
  2464. private List<HealthDiseaseRisk> buildDiseaseRisksFromPayload(ParsedReportPayload.Payload payload) {
  2465. List<ParsedReportPayload.DiseaseRisk> list = payload.getDiseaseRisks();
  2466. if (list == null || list.isEmpty()) return new ArrayList<>();
  2467. List<HealthDiseaseRisk> risks = new ArrayList<>();
  2468. for (ParsedReportPayload.DiseaseRisk pr : list) {
  2469. HealthDiseaseRisk dr = new HealthDiseaseRisk();
  2470. dr.setDiseaseName(pr.getDiseaseName());
  2471. dr.setRiskValue(pr.getRiskValue());
  2472. dr.setRiskLevel(pr.getRiskLevel());
  2473. risks.add(dr);
  2474. }
  2475. return risks;
  2476. }
  2477. private List<Food> buildFoodsFromPayload(ParsedReportPayload.Payload payload) {
  2478. List<ParsedReportPayload.FoodItem> list = payload.getFoods();
  2479. if (list == null || list.isEmpty()) return new ArrayList<>();
  2480. List<Food> foods = new ArrayList<>();
  2481. for (ParsedReportPayload.FoodItem pf : list) {
  2482. if (pf == null || pf.getName() == null || pf.getName().trim().isEmpty()) {
  2483. log.warn("跳过无效食材条目(元素为空或缺少名称)");
  2484. continue;
  2485. }
  2486. Food food = new Food();
  2487. food.setName(pf.getName());
  2488. food.setCategory(pf.getCategory());
  2489. food.setScore(pf.getScore());
  2490. food.setEnergyKj(pf.getEnergyKj());
  2491. food.setProtein(pf.getProtein());
  2492. food.setFat(pf.getFat());
  2493. food.setCarbs(pf.getCarbs());
  2494. food.setStarch(pf.getStarch());
  2495. food.setFiber(pf.getFiber());
  2496. food.setCholesterol(pf.getCholesterol());
  2497. food.setStatus("recommended");
  2498. foods.add(food);
  2499. }
  2500. return foods;
  2501. }
  2502. /**
  2503. * 提交报告反馈(持久化 + AI 解答)
  2504. */
  2505. @Operation(summary = "提交报告反馈(持久化 + AI 解答)")
  2506. @PostMapping("/feedback/submit")
  2507. public Result<?> submitFeedback(@RequestBody Map<String, Object> params,
  2508. @RequestAttribute("userId") Long userId,
  2509. @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
  2510. Long reportId = ParamUtils.getLong(params.get("reportId"));
  2511. Long draftId = ParamUtils.getLong(params.get("draftId"));
  2512. Long memberId = ParamUtils.getLong(params.get("memberId"), currentMemberId);
  2513. String type = params.get("type") != null ? params.get("type").toString() : null;
  2514. String content = params.get("content") != null ? params.get("content").toString() : null;
  2515. return reportFeedbackService.submit(userId, memberId, reportId, draftId, type, content);
  2516. }
  2517. @Operation(summary = "我的报告反馈列表(含 AI 解答)")
  2518. @PostMapping("/feedback/list")
  2519. public Result<?> listFeedback(@RequestAttribute("userId") Long userId,
  2520. @RequestBody(required = false) Map<String, Object> params) {
  2521. Long reportId = (params != null) ? ParamUtils.getLong(params.get("reportId")) : null;
  2522. return reportFeedbackService.listMine(userId, reportId);
  2523. }
  2524. /**
  2525. * 将解析结果保存到本地 JSON 文件(用于调试)
  2526. */
  2527. private void saveResultToJsonFile(Map<String, Object> result) throws IOException {
  2528. // 创建输出目录
  2529. String outputDir = "uploads" + File.separator + "json-results";
  2530. File dir = new File(outputDir);
  2531. if (!dir.exists()) {
  2532. dir.mkdirs();
  2533. }
  2534. // 生成文件名:timestamp_result.json
  2535. String timestamp = java.time.LocalDateTime.now().format(
  2536. java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss")
  2537. );
  2538. String filename = timestamp + "_result.json";
  2539. String filePath = outputDir + File.separator + filename;
  2540. // 写入 JSON 文件
  2541. try (java.io.PrintWriter writer = new java.io.PrintWriter(filePath, "UTF-8")) {
  2542. writer.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(result));
  2543. }
  2544. log.info("✅ 解析结果已保存到 JSON 文件:{}", filePath);
  2545. // 同时打印部分关键信息到日志(限制长度避免过大)
  2546. String summary = String.format(
  2547. "[JSON 保存] draftId=%s, name=%s, matched=%s, confidence=%.2f",
  2548. result.get("draftId"),
  2549. result.get("extractedName"),
  2550. result.get("matchedMemberId") != null ? "找到匹配" : "未匹配",
  2551. result.get("confidence")
  2552. );
  2553. log.info(summary);
  2554. }
  2555. /**
  2556. * 检查是否为授权代上传角色
  2557. */
  2558. private boolean isProxyUploader(String role, List<String> roles, User user) {
  2559. // 超级管理员(admin):平台最高权限,可代传任何报告
  2560. if ("admin".equals(role) || (roles != null && roles.contains("admin"))) return true;
  2561. if ("teacher".equals(role)) return true;
  2562. if (roles != null && roles.contains("teacher")) return true;
  2563. if (user != null && "approved".equals(user.getNutritionistStatus())) return true;
  2564. if (user != null && "planner".equals(user.getVendorType()) && "approved".equals(user.getVendorStatus())) return true;
  2565. return false;
  2566. }
  2567. /**
  2568. * B2-2 / B2-6:代传 familyId 绑定校验(发生在建草稿/写文件之前,越权不产生副作用)。
  2569. *
  2570. * <p>口径与 FamilyAccessInterceptor.getEffectiveFamilyIds 一致:平台角色(admin/operator/finance)
  2571. * 直接放行;否则 familyId 必位于调用者有效家庭集内(own family / teacher_family_ids /
  2572. * family_members 反查 / guide_family 绑定)。</p>
  2573. *
  2574. * @return true=允许代传该家庭;false=无权(controller 层返回 code=500 "无权为该家庭代传报告")
  2575. */
  2576. boolean canProxyForFamily(Long userId, String role, List<String> roles, Long familyId) {
  2577. if ("admin".equals(role) || AdminRoles.hasAnyPlatformRole(roles)) {
  2578. return true;
  2579. }
  2580. Set<Long> effective = userService.getEffectiveFamilyIds(userId);
  2581. return effective != null && effective.contains(familyId);
  2582. }
  2583. /**
  2584. * 规划师/营养师代用户上传报告(预览模式,仅解析不入库)
  2585. *
  2586. * <p>T29-B1-1:重构为与「两阶段入库」一致的模式——先建草稿拿到 draftId,再解析并回写草稿载荷,
  2587. * 前端「确认入库」才能拿到 draftId(原先透传 LangGraph 原始返回,恒无 draftId → 前端卡死)。</p>
  2588. * <p>链路:storeFile → createDraft → updateRemark(备注) → getFilePath → LangGraph 解析
  2589. * (失败回退本地 Java 解析)→ 返回 draftId/payload/成员匹配/提取字段。</p>
  2590. *
  2591. * <p><b>B3-2 草稿过期降级:</b>入参支持 <code>file</code>(新上传,multipart)或
  2592. * <code>fileUrl</code>(草稿过期后基于原文件重新解析,无需重新上传 PDF)。二者至少给一个,
  2593. * 复用本接口同一条「建草稿 → 解析」链路,不另建新接口。</p>
  2594. *
  2595. * <p><b>B3-3 本地兜底提示:</b>LangGraph 不可用而走本地 Java 解析时,返回体带
  2596. * <code>parseFallback=true</code> / <code>parseMethod="local"</code>,供前端提示
  2597. * 「解析服务暂不可用,已用本地解析」。</p>
  2598. *
  2599. * <p><b>T29-B2-6 权限编排(三层校验,各层失败返回码):</b>
  2600. * <ol>
  2601. * <li>① 角色校验 {@link #isProxyUploader}:非 admin/teacher/approved 营养师/approved 规划师
  2602. * → <code>Result.error(code=500, "无权限代上传报告,仅超级管理员/规划师/营养师可操作")</code>;</li>
  2603. * <li>② familyId 绑定校验 {@link #canProxyForFamily}(B2-2,本方法内):
  2604. * 非平台角色且 familyId 不在有效家庭集内
  2605. * → <code>Result.error(code=500, "无权为该家庭代传报告")</code>(不建草稿、不写文件);</li>
  2606. * <li>③ 家庭访问拦截器兜底(FamilyAccessInterceptor,B2-4 enforcement):
  2607. * 越权 → <code>HTTP 403</code>,body <code>{"code":403,"message":"无权访问该家庭数据"}</code>。
  2608. * (拦截器在 controller 之前执行,因此②③不会同时触发;②是对拦截器未覆盖路径的纵深防御。)</li>
  2609. * </ol></p>
  2610. */
  2611. @Operation(summary = "代上传报告(预览)")
  2612. @PostMapping("/report/proxy-parse")
  2613. public Result<Map<String, Object>> proxyParsePreview(
  2614. @RequestParam(value = "file", required = false) MultipartFile file,
  2615. @RequestParam(value = "fileUrl", required = false) String fileUrl,
  2616. @RequestParam(value = "familyId", required = false) Long familyId,
  2617. @RequestParam(value = "subjectId", required = false) Long subjectId,
  2618. @RequestParam(value = "reportType", defaultValue = "auto") String reportType,
  2619. @RequestParam(value = "note", required = false) String note,
  2620. @RequestAttribute("userId") Long userId,
  2621. @RequestAttribute("role") String role,
  2622. @RequestAttribute("roles") List<String> roles,
  2623. HttpServletRequest request) {
  2624. // B3-2:两种入参二选一——file(新上传,multipart)或 fileUrl(草稿过期后基于原文件重新解析)
  2625. boolean hasFile = file != null && !file.isEmpty();
  2626. boolean hasFileUrl = fileUrl != null && !fileUrl.trim().isEmpty();
  2627. if (!hasFile && !hasFileUrl) {
  2628. return Result.error("请选择PDF文件或提供fileUrl");
  2629. }
  2630. User user = userMapper.selectById(userId);
  2631. if (!isProxyUploader(role, roles, user)) {
  2632. return Result.error("无权限代上传报告,仅超级管理员/规划师/营养师可操作");
  2633. }
  2634. if (familyId == null) {
  2635. return Result.error("familyId不能为空");
  2636. }
  2637. // B2-2 / B2-6:familyId 绑定校验(发生在建草稿/写文件之前,越权不产生副作用)。
  2638. // 拦截器(B2-4)未覆盖或未生效时,此处作纵深防御。
  2639. if (!canProxyForFamily(userId, role, roles, familyId)) {
  2640. return Result.error("无权为该家庭代传报告");
  2641. }
  2642. // 新上传路径才校验 PDF 类型(fileUrl 重新解析路径的文件已在首次上传时校验过)
  2643. if (hasFile) {
  2644. String contentType = file.getContentType();
  2645. String originalFilename = file.getOriginalFilename();
  2646. String lcName = originalFilename != null ? originalFilename.toLowerCase() : "";
  2647. if (!lcName.endsWith(".pdf")
  2648. && (contentType == null || !contentType.equalsIgnoreCase("application/pdf"))) {
  2649. return Result.error("仅支持PDF文件");
  2650. }
  2651. }
  2652. try {
  2653. // ① 确定文件访问地址:新上传 → storeFile 存本地/OSS;fileUrl → 复用既有文件
  2654. boolean reparse = !hasFile && hasFileUrl;
  2655. String resolvedFileUrl = hasFile ? storageService.storeFile(file, "health-reports") : fileUrl.trim();
  2656. String originalFilename = hasFile ? file.getOriginalFilename() : null;
  2657. // ② 先建草稿:保证预览必然有 draftId 供 /report/proxy-confirm 入库
  2658. // reportType 传 auto 时落 gut_flora(与非代传链路一致)
  2659. // health_report_drafts.payload_json 为 NOT NULL 列,先写空载荷 JSON
  2660. // (与图片上传链路一致),解析成功后由 updatePayload 覆盖为真实载荷
  2661. String draftReportType = (reportType == null || reportType.isEmpty() || "auto".equals(reportType))
  2662. ? "gut_flora" : reportType;
  2663. String emptyPayloadJson = objectMapper.writeValueAsString(new ParsedReportPayload.Payload());
  2664. HealthReportDraft draft = healthReportDraftService.createDraft(
  2665. userId, familyId, draftReportType, resolvedFileUrl, originalFilename, emptyPayloadJson);
  2666. // ③ 备注写入草稿 remark(B3-6:updateRemark 实际写 remark 列),确认入库时同步到 proxy_upload_note
  2667. if (note != null && !note.isEmpty()) {
  2668. healthReportDraftService.updateRemark(draft.getId(), note);
  2669. }
  2670. // ④ LangGraph 需要本地路径:经 getFilePath 下载/定位到共享卷
  2671. String absolutePath = storageService.getFilePath(resolvedFileUrl);
  2672. // ⑤ 解析(LangGraph 优先,失败回退本地 Java 解析)
  2673. Map<String, Object> data = parseProxyDraftFile(draft, absolutePath, userId, familyId, subjectId);
  2674. if (data == null) {
  2675. // 解析失败:草稿已无后续用途,标记丢弃,避免遗留空载荷 pending 草稿被误确认入库
  2676. try {
  2677. healthReportDraftService.markDiscarded(draft.getId());
  2678. } catch (Exception ex) {
  2679. log.warn("标记代传草稿为已丢弃失败 draftId={}: {}", draft.getId(), ex.getMessage());
  2680. }
  2681. return Result.error("报告解析失败,请确认是募极生物肠道菌群报告PDF");
  2682. }
  2683. // ⑥ 返回体补代传相关字段(前端既有字段契约)
  2684. data.put("fileUrl", resolvedFileUrl);
  2685. data.put("proxyUploaderId", userId);
  2686. data.put("proxyUploadNote", note);
  2687. data.put("reparse", reparse);
  2688. return Result.success(data);
  2689. } catch (Exception e) {
  2690. log.error("代上传解析失败", e);
  2691. return Result.error("解析失败: " + e.getMessage());
  2692. }
  2693. }
  2694. /**
  2695. * 代传草稿文件解析:LangGraph 优先,失败回退本地 Java 解析。
  2696. * 两路都会把解析载荷写回 draft.payload_json,并返回完整预览结果
  2697. * (draftId / payload / matchedMemberId / extracted 各字段 / needBind)。
  2698. *
  2699. * @return 解析结果体;文件不存在或两路均失败时返回 null
  2700. */
  2701. private Map<String, Object> parseProxyDraftFile(HealthReportDraft draft, String absolutePath,
  2702. Long userId, Long familyId, Long subjectId) {
  2703. File localFile = new File(absolutePath);
  2704. if (!localFile.exists()) {
  2705. log.warn("代传解析:文件不存在 draftId={}, path={}", draft.getId(), absolutePath);
  2706. return null;
  2707. }
  2708. try {
  2709. Map<String, Object> lgData = callLangGraphParse(absolutePath, userId, familyId, subjectId);
  2710. if (lgData != null) {
  2711. Map<String, Object> data = buildParseResultFromLg(lgData, draft, familyId).getData();
  2712. putExtractedReportMeta(data, lgData);
  2713. markParseMethod(data, false, "langgraph");
  2714. return data;
  2715. }
  2716. log.warn("代传解析:LangGraph 无有效返回,回退本地 Java 解析 draftId={}", draft.getId());
  2717. } catch (Exception e) {
  2718. log.warn("代传解析:LangGraph 解析异常,回退本地 Java 解析 draftId={}: {}",
  2719. draft.getId(), e.getMessage());
  2720. }
  2721. try {
  2722. Map<String, Object> data = parseLocalFallback(absolutePath, draft, familyId, userId).getData();
  2723. if (data != null) {
  2724. // B3-3:本地兜底成功 → 前端提示「解析服务暂不可用,已用本地解析」
  2725. markParseMethod(data, true, "local");
  2726. }
  2727. return data;
  2728. } catch (Exception e) {
  2729. log.error("代传解析:本地 Java 解析失败 draftId={}", draft.getId(), e);
  2730. return null;
  2731. }
  2732. }
  2733. /**
  2734. * B3-3:标注本次解析走 LangGraph 还是本地 Java 兜底,供前端差异化提示。
  2735. *
  2736. * @param data 预览结果体(非 null)
  2737. * @param fallback 是否走了本地 Java 兜底
  2738. * @param method 解析方式标识(langgraph / local)
  2739. */
  2740. private void markParseMethod(Map<String, Object> data, boolean fallback, String method) {
  2741. if (data == null) {
  2742. return;
  2743. }
  2744. data.put("parseFallback", fallback);
  2745. data.put("parseMethod", method);
  2746. }
  2747. /**
  2748. * 补齐 LangGraph 预览结果的 extractedReportNumber / extractedReportDate。
  2749. * buildParseResultFromLg 只回填 extractedName/Gender/Age,而前端预览页三行
  2750. * (被检测人/报告编号/报告日期)还读这两个字段,缺省会一直显示 '-'。
  2751. */
  2752. private void putExtractedReportMeta(Map<String, Object> data, Map<String, Object> lgData) {
  2753. if (data == null || lgData == null) {
  2754. return;
  2755. }
  2756. Map<String, Object> overview = (Map<String, Object>) lgData.get("overview");
  2757. if (overview != null) {
  2758. data.put("extractedReportNumber", objectToString(overview.get("report_number")));
  2759. data.put("extractedReportDate", objectToString(overview.get("report_date")));
  2760. }
  2761. }
  2762. /**
  2763. * 规划师/营养师代确认报告草稿(入库)
  2764. */
  2765. @Operation(summary = "代确认报告(入库)")
  2766. @PostMapping("/report/proxy-confirm")
  2767. public Result<Map<String, Object>> proxyConfirm(
  2768. @RequestBody Map<String, Object> params,
  2769. @RequestAttribute("userId") Long userId,
  2770. @RequestAttribute("role") String role,
  2771. @RequestAttribute("roles") List<String> roles) {
  2772. User user = userMapper.selectById(userId);
  2773. if (!isProxyUploader(role, roles, user)) {
  2774. return Result.error("无权限");
  2775. }
  2776. Long draftId = ParamUtils.getLong(params.get("draftId"));
  2777. Long subjectId = ParamUtils.getLong(params.get("subjectId"));
  2778. if (draftId == null) {
  2779. return Result.error("draftId不能为空");
  2780. }
  2781. try {
  2782. // 先取草稿备注(代传 note):确认后写入 health_reports.proxy_upload_note
  2783. HealthReportDraft draft = healthReportDraftService.getDraftById(draftId);
  2784. String proxyUploadNote = draft != null ? draft.getRemark() : null;
  2785. // B2-3:草稿归属校验下沉到 auditConfirm——仅创建者本人或平台角色可确认
  2786. // (原代传链路"跳过草稿归属校验"的口径已废止:代传草稿只能由代传人本人或 admin 确认)
  2787. boolean isAdmin = "admin".equals(role) || AdminRoles.hasAnyPlatformRole(roles);
  2788. Map<String, Object> result = healthReportService.auditConfirm(draftId, subjectId, userId, isAdmin);
  2789. Long reportId = (Long) result.get("reportId");
  2790. // 维护"当前食材"推荐(有则更新,无则添加)
  2791. Long confirmedSubjectId = ParamUtils.getLong(result.get("subjectId"));
  2792. if (confirmedSubjectId != null) {
  2793. try {
  2794. foodRecommendService.recalculateForUser(confirmedSubjectId);
  2795. } catch (Exception e) {
  2796. log.warn("代确认后刷新食材推荐失败: {}", e.getMessage());
  2797. }
  2798. }
  2799. // 设置代上传人 + 代上传备注
  2800. if (reportId != null) {
  2801. healthReportService.setProxyUploader(reportId, userId, proxyUploadNote);
  2802. }
  2803. // 触发 AI 解读(T29-B1-5:失败不再静默吞错,结果/失败原因随响应回传前端)
  2804. Map<String, Object> aiResult = new HashMap<>();
  2805. if (reportId != null && subjectId != null) {
  2806. aiResult = triggerAiAnalysis(reportId, subjectId, userId);
  2807. }
  2808. if (Boolean.TRUE.equals(aiResult.get("success"))) {
  2809. result.put("aiAnalysis", aiResult.get("analysis"));
  2810. result.put("aiAnalysisStatus", "success");
  2811. } else {
  2812. result.put("aiAnalysisStatus", aiResult.get("reason"));
  2813. Object aiMessage = aiResult.get("message") != null ? aiResult.get("message") : aiResult.get("toast");
  2814. result.put("aiAnalysisMessage", aiMessage);
  2815. }
  2816. return Result.success(result);
  2817. } catch (Exception e) {
  2818. log.error("代确认失败", e);
  2819. return Result.error("确认失败: " + e.getMessage());
  2820. }
  2821. }
  2822. /**
  2823. * 调用 LangGraph 解析报告
  2824. */
  2825. private Map<String, Object> callLangGraphParse(String absolutePath, Long userId, Long familyId, Long subjectId) {
  2826. try {
  2827. Map<String, Object> lgRequest = new HashMap<>();
  2828. lgRequest.put("file_path", absolutePath);
  2829. lgRequest.put("user_id", userId);
  2830. lgRequest.put("family_id", familyId);
  2831. ResponseEntity<Map> lgResponse = restTemplate.postForEntity(
  2832. langgraphBaseUrl + "/api/v1/report/parse", lgRequest, Map.class);
  2833. Map<String, Object> lgBody = lgResponse.getBody();
  2834. if (lgBody != null && Integer.valueOf(200).equals(lgBody.get("code"))) {
  2835. Map<String, Object> lgData = (Map<String, Object>) lgBody.get("data");
  2836. if (lgData != null) {
  2837. return lgData;
  2838. }
  2839. }
  2840. } catch (Exception e) {
  2841. log.warn("LangGraph 解析失败,回退: {}", e.getMessage());
  2842. }
  2843. return null;
  2844. }
  2845. /**
  2846. * 触发 AI 解读(T29-B1-5:失败不再静默吞错,结果与失败原因回传调用方)
  2847. *
  2848. * @return {success, analysis, traceId} 成功;
  2849. * {success=false, reason="quota", toast} 配额不足;
  2850. * {success=false, reason="langgraph_failed", message} LangGraph 失败或返回空解读
  2851. */
  2852. private Map<String, Object> triggerAiAnalysis(Long reportId, Long subjectId, Long proxyUploaderId) {
  2853. Map<String, Object> aiResult = new HashMap<>();
  2854. aiResult.put("success", false);
  2855. // BASIC 配额检查(报告 AI 解读,2026-10-23 新口径:BASIC 1 次/月;FAMILY 及以上不限次;FREE 维持既有口径扣减)
  2856. if (proxyUploaderId != null) {
  2857. com.etotem.cfc.dto.QuotaConsumeResult quotaResult = basicQuotaService.consumeMemberQuota(proxyUploaderId, "REPORT_READING", false);
  2858. if (!quotaResult.isSuccess()) {
  2859. log.info("报告 AI 解读配额不足: userId={}, toast={}", proxyUploaderId, quotaResult.getToastMsg());
  2860. aiResult.put("reason", "quota");
  2861. aiResult.put("toast", quotaResult.getToastMsg());
  2862. return aiResult;
  2863. }
  2864. }
  2865. try {
  2866. Map<String, Object> analyzeReq = new HashMap<>();
  2867. analyzeReq.put("report_id", reportId);
  2868. analyzeReq.put("user_id", subjectId);
  2869. analyzeReq.put("focus", "代上传报告解读");
  2870. ResponseEntity<Map> resp = restTemplate.postForEntity(
  2871. langgraphBaseUrl + "/api/v1/analyze", analyzeReq, Map.class);
  2872. if (resp.getBody() != null) {
  2873. Map<String, Object> body = resp.getBody();
  2874. String analysis = objectToString(body.get("analysis"));
  2875. String traceId = objectToString(body.get("trace_id"));
  2876. if (analysis != null && !analysis.isEmpty()) {
  2877. Map<String, Object> aiData = new HashMap<>();
  2878. aiData.put("analysis", analysis);
  2879. aiData.put("traceId", traceId);
  2880. aiData.put("proxyUploaderId", proxyUploaderId);
  2881. healthReportService.setAiAnalysis(reportId, aiData);
  2882. log.info("AI解读已保存: reportId={}, traceId={}", reportId, traceId);
  2883. aiResult.put("success", true);
  2884. aiResult.put("analysis", analysis);
  2885. aiResult.put("traceId", traceId);
  2886. return aiResult;
  2887. }
  2888. aiResult.put("reason", "langgraph_failed");
  2889. aiResult.put("message", "AI解读服务返回空结果");
  2890. log.warn("AI解读返回空结果: reportId={}, body={}", reportId, body);
  2891. } else {
  2892. aiResult.put("reason", "langgraph_failed");
  2893. aiResult.put("message", "AI解读服务无响应");
  2894. log.warn("AI解读服务无响应: reportId={}", reportId);
  2895. }
  2896. } catch (Exception e) {
  2897. aiResult.put("reason", "langgraph_failed");
  2898. aiResult.put("message", "AI解读服务异常: " + e.getMessage());
  2899. log.warn("AI解读触发失败: {}", e.getMessage(), e);
  2900. }
  2901. return aiResult;
  2902. }
  2903. /**
  2904. * 获取身体维度异常指标(身体页面"指标告警")
  2905. * 疾病风险:只返回非低风险项目
  2906. * 营养评估+氨基酸评估:只返回异常状态(偏高/偏低/缺乏等)
  2907. */
  2908. @PostMapping("/report/body-abnormal")
  2909. public Result<?> bodyAbnormal(@RequestBody Map<String, Object> params,
  2910. @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
  2911. Long memberId = ParamUtils.getLong(params.get("memberId"), currentMemberId);
  2912. if (memberId == null) return Result.success(new java.util.HashMap<>());
  2913. return Result.success(healthReportService.getBodyAbnormalIndicators(memberId));
  2914. }
  2915. }