| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224 |
- package com.etotem.cfc.controller;
- import com.etotem.cfc.common.Result;
- import com.etotem.cfc.common.AdminRoles;
- import com.etotem.cfc.service.PurchaseService;
- import com.etotem.cfc.service.DanReportUploadService;
- import com.etotem.cfc.dto.HealthAnalysisResult;
- import com.etotem.cfc.dto.MemberMatchResult;
- import com.etotem.cfc.dto.ParsedDiseaseRisk;
- import com.etotem.cfc.dto.ParsedGutFlora;
- import com.etotem.cfc.dto.ParsedIndicator;
- import com.etotem.cfc.dto.ParsedFoodSuitability;
- import com.etotem.cfc.dto.ParsedReportPayload;
- import com.etotem.cfc.dto.ParsedReportResult;
- import java.math.BigDecimal;
- import javax.servlet.http.HttpServletRequest;
- import com.etotem.cfc.entity.Food;
- import com.etotem.cfc.entity.FamilyMember;
- import com.etotem.cfc.entity.FoodRecommendIndex;
- import com.etotem.cfc.entity.HealthDiseaseRisk;
- import com.etotem.cfc.entity.HealthGutFlora;
- import com.etotem.cfc.entity.HealthIndicator;
- import com.etotem.cfc.entity.HealthReport;
- import com.etotem.cfc.entity.HealthReportDraft;
- import com.etotem.cfc.entity.DanReportUpload;
- import com.etotem.cfc.entity.ReportTransferRequest;
- import com.etotem.cfc.entity.NutritionDeficiencyRecord;
- import com.etotem.cfc.entity.NutritionIndicatorMapping;
- import com.etotem.cfc.entity.User;
- import com.etotem.cfc.mapper.HealthReportDraftMapper;
- import com.etotem.cfc.mapper.FamilyMemberMapper;
- import com.etotem.cfc.mapper.UserMapper;
- import com.etotem.cfc.service.UserService;
- import com.etotem.cfc.service.FamilyMemberNutritionProfileService;
- import com.etotem.cfc.service.DimensionScoreService;
- import com.etotem.cfc.service.FoodRecommendService;
- import com.etotem.cfc.service.FamilyFoodOverviewService;
- import com.etotem.cfc.service.FoodService;
- import com.etotem.cfc.service.HealthAnalysisService;
- import com.etotem.cfc.service.HealthReportDraftService;
- import com.etotem.cfc.service.HealthReportService;
- import com.etotem.cfc.service.ReportArchiveCompareService;
- import com.etotem.cfc.service.MemberIndicatorCurrentService;
- import com.etotem.cfc.service.BasicQuotaService;
- import com.etotem.cfc.service.NutritionDeficiencyService;
- import com.etotem.cfc.service.NormalizeIndicatorPipeline;
- import com.etotem.cfc.service.PdfParseService;
- import com.etotem.cfc.service.ReportCollectService;
- import com.etotem.cfc.service.ReportTransferService;
- import com.etotem.cfc.service.ReportBlockAssembler;
- import com.etotem.cfc.service.ReportBlockService;
- import com.etotem.cfc.service.StorageService;
- import com.etotem.cfc.service.OnboardingService;
- import com.etotem.cfc.service.ReportMemberPermissionService;
- import com.etotem.cfc.service.TongueDiagnosisService;
- import com.etotem.cfc.service.BasicQuotaService;
- import com.etotem.cfc.service.BodyFatScaleService;
- import com.etotem.cfc.service.api.WechatServiceInterface;
- import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
- import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
- import com.fasterxml.jackson.databind.ObjectMapper;
- import io.swagger.v3.oas.annotations.Operation;
- import io.swagger.v3.oas.annotations.tags.Tag;
- import lombok.extern.slf4j.Slf4j;
- import org.springframework.web.bind.annotation.*;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.web.multipart.MultipartFile;
- import javax.annotation.Resource;
- import javax.servlet.http.HttpServletRequest;
- import java.io.File;
- import java.io.IOException;
- import java.nio.file.Files;
- import java.nio.file.Path;
- import java.nio.file.Paths;
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Date;
- import java.util.HashMap;
- import java.util.HashSet;
- import java.util.LinkedHashMap;
- import java.util.List;
- import java.util.Map;
- import java.util.Set;
- import java.util.UUID;
- import org.springframework.http.ResponseEntity;
- import org.springframework.web.client.RestTemplate;
- import com.etotem.cfc.util.ParamUtils;
- /**
- * 健康检测报告接口 — 体检报告/菌群检测报告的录入与查询
- */
- @Slf4j
- @Tag(name = "健康检测报告", description = "健康报告上传、查询、指标明细")
- @RestController
- @RequestMapping("/api/health")
- public class HealthReportController {
- private static final String LANGGRAPH_BASE_URL = "http://localhost:9000";
- private static final String REPORT_PARSE_URL = LANGGRAPH_BASE_URL + "/api/v1/report/parse";
- /** P0-3 ③:collect/status 响应暴露 collect_validation(键名)——前端轮询时可核对 _解析自检 结果 */
- public static final String COLLECT_VALIDATION_KEY = "collect_validation";
- /**
- * LangGraph 服务地址(生产环境通过 application.yml 覆盖,避免 Docker 容器跨主机调用失败)
- * TODO(部署): 容器化部署时需确保 Java 上传目录(uploads/health-reports)
- * 对 LangGraph 容器可见(共享 volume 或主机路径挂载),否则 file_path 不可访问将回退本地解析。
- */
- @Value("${upload.base-dir:/data/cfc-uploads}")
- private String uploadBaseDir;
- @Value("${langgraph.base-url:http://localhost:9000}")
- private String langgraphBaseUrl;
- @Resource
- private HealthReportService healthReportService;
- @Resource
- private ReportTransferService reportTransferService;
- @Resource
- private PdfParseService pdfParseService;
- @Resource
- private NutritionDeficiencyService nutritionDeficiencyService;
- @Resource
- private FamilyMemberNutritionProfileService childNutritionProfileService;
- @Resource
- private HealthAnalysisService healthAnalysisService;
- @Resource
- private FoodService foodService;
- @Resource
- private HealthReportDraftService healthReportDraftService;
- @Resource
- private ObjectMapper objectMapper;
- @Resource
- private RestTemplate restTemplate;
- @Resource
- private DimensionScoreService dimensionScoreService;
- @Resource
- private TongueDiagnosisService tongueDiagnosisService;
- @Resource
- private ReportMemberPermissionService reportMemberPermissionService;
- @Resource
- private DanReportUploadService danReportUploadService;
- @Resource
- private FoodRecommendService foodRecommendService;
- @Resource
- private FamilyFoodOverviewService familyFoodOverviewService;
- @Resource
- private FamilyMemberMapper familyMemberMapper;
- @Resource
- private HealthReportDraftMapper healthReportDraftMapper;
- @Resource
- private WechatServiceInterface wechatService;
- @Resource
- private BodyFatScaleService bodyFatScaleService;
- @Resource
- private UserMapper userMapper;
- @Resource
- private UserService userService;
- @Resource
- private ReportBlockService reportBlockService;
- @Resource
- private BasicQuotaService basicQuotaService;
- @Resource
- private StorageService storageService;
- @Resource
- private ReportBlockAssembler reportBlockAssembler;
- @Resource
- private com.etotem.cfc.service.PurchaseService purchaseService;
- @Resource
- private NormalizeIndicatorPipeline normalizeIndicatorPipeline;
- @Resource
- private MemberIndicatorCurrentService memberIndicatorCurrentService;
- @Resource
- private com.etotem.cfc.service.HealthPlanService healthPlanService;
- @Resource
- private ReportCollectService reportCollectService;
- @Resource
- private com.etotem.cfc.service.AiGateway aiGateway;
- @Resource
- private com.etotem.cfc.service.ReportFeedbackService reportFeedbackService;
- @Resource
- private OnboardingService onboardingService;
- @Resource
- private ReportArchiveCompareService reportArchiveCompareService;
- /**
- * 创建健康报告(含指标明细)
- */
- @Operation(summary = "创建健康报告")
- @PostMapping("/report/create")
- public Result<HealthReport> createReport(
- @RequestBody Map<String, Object> params,
- @RequestAttribute("userId") Long userId,
- @RequestAttribute(value = "familyId", required = false) Long familyId,
- @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
- // 付费墙拦截:检查是否购买健康启航计划
- java.util.Map<String, Object> purchaseCheck = purchaseService.checkPurchase(userId);
- if (!Boolean.TRUE.equals(purchaseCheck.get("isActive"))) {
- return Result.error(4001, "请先购买健康启航计划体验包");
- }
- if (familyId == null) {
- return Result.noFamily("请先创建或加入家庭");
- }
- Long memberId = ParamUtils.getLong(params.get("memberId"), currentMemberId);
- if (memberId == null) {
- return Result.error("memberId不能为空");
- }
- String reportType = (String) params.get("reportType");
- if (reportType == null || reportType.trim().isEmpty()) {
- return Result.error("reportType不能为空: physical_exam / gut_flora");
- }
- // 契约 §4.59.2:reportType 仅允许 physical_exam / gut_flora,其余取值(空串/非法值)一律拒绝
- if (!"physical_exam".equals(reportType) && !"gut_flora".equals(reportType)) {
- return Result.error("不支持的reportType: physical_exam / gut_flora");
- }
- // 构建报告主体
- HealthReport report = new HealthReport();
- report.setUserId(memberId);
- report.setReportType(reportType);
- report.setOverallScore(params.get("overallScore") != null
- ? Integer.valueOf(params.get("overallScore").toString()) : null);
- report.setGutHealthScore(params.get("gutHealthScore") != null
- ? Integer.valueOf(params.get("gutHealthScore").toString()) : null);
- report.setChronicDiseaseScore(params.get("chronicDiseaseScore") != null
- ? Integer.valueOf(params.get("chronicDiseaseScore").toString()) : null);
- report.setNutritionScore(params.get("nutritionScore") != null
- ? Integer.valueOf(params.get("nutritionScore").toString()) : null);
- report.setGutAge((String) params.get("gutAge"));
- report.setGutType((String) params.get("gutType"));
- report.setGutBalanceScore(params.get("gutBalanceScore") != null
- ? Integer.valueOf(params.get("gutBalanceScore").toString()) : null);
- report.setGutDiversityScore(params.get("gutDiversityScore") != null
- ? Integer.valueOf(params.get("gutDiversityScore").toString()) : null);
- report.setBeneficialBacteriaScore(params.get("beneficialBacteriaScore") != null
- ? Integer.valueOf(params.get("beneficialBacteriaScore").toString()) : null);
- report.setHarmfulBacteriaScore(params.get("harmfulBacteriaScore") != null
- ? Integer.valueOf(params.get("harmfulBacteriaScore").toString()) : null);
- report.setCoreSpeciesScore(params.get("coreSpeciesScore") != null
- ? Integer.valueOf(params.get("coreSpeciesScore").toString()) : null);
- report.setHealthRating((String) params.get("healthRating"));
- report.setFileUrl((String) params.get("fileUrl"));
- report.setRemark((String) params.get("remark"));
- // 报告日期(默认当天)
- report.setReportDate(new java.util.Date());
- // 指标明细(可选)
- @SuppressWarnings("unchecked")
- List<Map<String, Object>> indicatorList =
- (List<Map<String, Object>>) params.get("indicators");
- List<HealthIndicator> indicators = null;
- if (indicatorList != null) {
- indicators = new java.util.ArrayList<>();
- for (int i = 0; i < indicatorList.size(); i++) {
- Map<String, Object> item = indicatorList.get(i);
- HealthIndicator ind = new HealthIndicator();
- ind.setCategory((String) item.get("category"));
- ind.setIndicatorName((String) item.get("indicatorName"));
- ind.setIndicatorValue(item.get("indicatorValue") != null
- ? item.get("indicatorValue").toString() : null);
- ind.setUnit((String) item.get("unit"));
- ind.setRefRange((String) item.get("refRange"));
- ind.setStatus((String) item.get("status"));
- ind.setSymptoms((String) item.get("symptoms"));
- ind.setSortOrder(i);
- indicators.add(ind);
- }
- }
- HealthReport created = healthReportService.createReport(report, indicators);
- return Result.success(created);
- }
- /**
- * 获取家庭成员的最新健康报告
- */
- @Operation(summary = "获取最新健康报告")
- @PostMapping("/report/latest")
- public Result<HealthReport> getLatestReport(
- @RequestBody Map<String, Object> params,
- @RequestAttribute(value = "familyId", required = false) Long familyId,
- @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
- if (familyId == null) {
- return Result.noFamily("请先创建或加入家庭");
- }
- Long memberId = ParamUtils.getLong(params.get("memberId"), currentMemberId);
- if (memberId == null) {
- return Result.error("memberId不能为空");
- }
- HealthReport report = healthReportService.getLatestReport(memberId);
- return Result.success(report);
- }
- /**
- * 获取家庭成员的所有健康报告列表
- * 未传 memberId 时返回当前家庭的全部报告;传 memberId 时按成员过滤(兼容 users.id / family_members.id)
- */
- @Operation(summary = "获取健康报告列表")
- @PostMapping("/report/list")
- public Result<Object> listReports(
- @RequestBody Map<String, Object> params,
- @RequestAttribute("userId") Long userId,
- @RequestAttribute(value = "familyId", required = false) Long familyId) {
- // B3-4:分页支持——page 不传时行为与现一致(返回 List,兼容小程序端);page 传时返回分页结构。
- int page = params.get("page") != null ? Integer.parseInt(params.get("page").toString()) : 0;
- // 返回条数:显式传 size 则截取前 size 条;不传则返回全部分页列表
- int size = params.get("size") != null ? Integer.parseInt(params.get("size").toString()) : 0;
- Long memberId = ParamUtils.getLong(params.get("memberId"));
- List<HealthReport> reports;
- java.util.Set<Long> visibleForDan = null;
- if (memberId != null) {
- // 成员级权限:管理员 / 本人 / 被授权成员可见,否则返回空列表
- if (familyId == null || !reportMemberPermissionService.canViewMemberReports(userId, memberId, familyId)) {
- return Result.success(new ArrayList<>());
- }
- reports = healthReportService.getMemberReports(memberId, familyId);
- } else if (familyId != null) {
- // 未指定 memberId 时,返回当前家庭的全部报告(按权限过滤)
- java.util.Set<Long> visible = reportMemberPermissionService.visibleIdentityIds(userId, familyId);
- if (visible == null) {
- // 管理员:全部可见
- reports = healthReportService.getFamilyReports(familyId);
- } else {
- List<HealthReport> all = healthReportService.getFamilyReports(familyId);
- reports = new ArrayList<>();
- for (HealthReport r : all) {
- Long subj = r.getSubjectId();
- Long owner = r.getUserId();
- if ((subj != null && visible.contains(subj))
- || (subj == null && owner != null && visible.contains(owner))) {
- reports.add(r);
- }
- }
- // DAN 报告按可见成员过滤(family_members.id 语义)
- visibleForDan = visible;
- }
- } else {
- // 无家庭信息时返回空列表,避免前端报错
- return Result.success(new ArrayList<>());
- }
- // 合并 DAN 报告(已确认入库的)到列表,保证报告列表页能看到 DAN 报告
- List<HealthReport> merged = mergeDanReports(reports, memberId, familyId, visibleForDan, userId);
- if (page > 0) {
- // B3-4:分页返回结构(对齐项目分页惯例,与 /report/admin-list 的 records/total 口径一致);
- // teacher 端代传历史页已按 res.data.records / res.data.total 读取。
- int pageSize = size > 0 ? size : 20;
- int total = merged.size();
- int from = (page - 1) * pageSize;
- if (from > total) {
- from = total;
- }
- int to = Math.min(from + pageSize, total);
- List<HealthReport> records = from < total
- ? new ArrayList<>(merged.subList(from, to)) : new ArrayList<>();
- healthReportService.fillSubjectAndProxyNames(records);
- Map<String, Object> pageResult = new java.util.HashMap<>();
- pageResult.put("records", records);
- pageResult.put("total", total);
- pageResult.put("current", page);
- pageResult.put("size", pageSize);
- pageResult.put("pages", (int) Math.ceil((double) total / pageSize));
- return Result.success(pageResult);
- }
- if (size > 0) {
- // B1-6:列表补展示字段(报告对象姓名 / 代上传人姓名),实体上的 @TableField(exist=false) 字段
- List<HealthReport> limited = limitLatest(merged, size);
- healthReportService.fillSubjectAndProxyNames(limited);
- return Result.success(limited);
- }
- // B1-6:列表补展示字段(报告对象姓名 / 代上传人姓名)
- healthReportService.fillSubjectAndProxyNames(merged);
- return Result.success(merged);
- }
- /**
- * 合并 DAN 报告到健康报告列表(转成 HealthReport 兼容结构,reportType='dan')
- */
- private List<HealthReport> mergeDanReports(List<HealthReport> reports, Long memberId, Long familyId,
- java.util.Set<Long> visibleForDan, Long userId) {
- List<DanReportUpload> danList = danReportUploadService.listConfirmedForReportList(memberId, familyId, visibleForDan);
- if (danList.isEmpty()) {
- return reports == null ? new ArrayList<>() : reports;
- }
- java.util.Map<Long, Long> idToMemberId = new java.util.HashMap<>();
- for (DanReportUpload u : danList) {
- if (u.getFamilyMemberId() != null) {
- idToMemberId.put(u.getId(), u.getFamilyMemberId());
- }
- }
- List<HealthReport> result = reports == null ? new ArrayList<>() : new ArrayList<>(reports);
- // 成员昵称缓存(personName 展示)
- java.util.Map<Long, String> memberNameCache = new java.util.HashMap<>();
- for (DanReportUpload u : danList) {
- HealthReport hr = new HealthReport();
- hr.setId(u.getId());
- hr.setReportType("dan");
- hr.setFamilyId(u.getFamilyId());
- hr.setSubjectId(u.getFamilyMemberId());
- hr.setUserId(u.getUploaderUserId());
- hr.setCreatedAt(u.getUploadedAt() != null ? u.getUploadedAt() : u.getConfirmedAt());
- hr.setReportDate(u.getConfirmedAt() != null ? u.getConfirmedAt() : u.getUploadedAt());
- if (u.getFamilyMemberId() != null) {
- String name = memberNameCache.get(u.getFamilyMemberId());
- if (name == null) {
- try {
- com.etotem.cfc.entity.FamilyMember fm = familyMemberMapper.selectById(u.getFamilyMemberId());
- name = fm != null ? (fm.getNickname() != null ? fm.getNickname() : ("成员" + fm.getId())) : null;
- } catch (Exception e) {
- name = null;
- }
- if (name == null) name = "";
- memberNameCache.put(u.getFamilyMemberId(), name);
- }
- hr.setPersonName(name);
- }
- hr.setStatus("active");
- result.add(hr);
- }
- // 按上传时间倒序(DAN 与健康报告统一排序)
- result.sort((a, b) -> {
- java.util.Date da = a.getCreatedAt();
- java.util.Date db = b.getCreatedAt();
- if (da == null) return 1;
- if (db == null) return -1;
- return db.compareTo(da);
- });
- return result;
- }
- /**
- * 截取列表前 N 条(列表已按报告日期倒序,取最近 N 条)
- */
- private List<HealthReport> limitLatest(List<HealthReport> reports, int max) {
- if (reports == null || reports.size() <= max) {
- return reports;
- }
- return new ArrayList<>(reports.subList(0, max));
- }
- @Operation(summary = "获取全家健康报告列表(方案页选择用)")
- @PostMapping("/reports/family")
- public Result<List<HealthReport>> listFamilyReports(
- @RequestAttribute(value = "familyId", required = false) Long familyId) {
- if (familyId == null) {
- return Result.error("familyId不能为空");
- }
- List<HealthReport> reports = healthReportService.getFamilyReports(familyId);
- return Result.success(reports);
- }
- /**
- * 管理端分页查询所有报告
- */
- @Operation(summary = "管理端报告列表(分页)")
- @PostMapping("/report/admin-list")
- public Result<Page<Map<String, Object>>> listAllReports(
- @RequestBody Map<String, Object> params) {
- int page = params.get("page") != null ? Integer.parseInt(params.get("page").toString()) : 1;
- int size = params.get("size") != null ? Integer.parseInt(params.get("size").toString()) : 20;
- Page<Map<String, Object>> result = healthReportService.listAllReportsForAdmin(page, size);
- return Result.success(result);
- }
- /**
- * 新增(§4.1):获取报告指标详情(含上一期对照)
- * 相比老接口 /indicator/list 返回裸 List<HealthIndicator>,本接口增加
- * previous / change / summary 五档形态数据(first_record / pending_backfill / improved / worsened / flat)。
- */
- @Operation(summary = "获取报告指标详情(含上一期对照)")
- @PostMapping("/report/indicators")
- public Result<Map<String, Object>> getReportIndicatorsWithPrevious(
- @RequestBody Map<String, Object> params,
- @RequestAttribute("userId") Long userId,
- @RequestAttribute(value = "familyId", required = false) Long familyId) {
- Long reportId = ParamUtils.getLong(params.get("reportId"));
- if (reportId == null) {
- return Result.error("reportId不能为空");
- }
- HealthReport report = healthReportService.getReportById(reportId);
- if (report == null) {
- return Result.error("报告不存在");
- }
- // 权限校验:管理员 / 本人 / 被授权成员可见(沿用 getReportDetail 逻辑)
- Long reportFamilyId = report.getFamilyId() != null ? report.getFamilyId() : familyId;
- if (reportFamilyId == null) {
- return Result.error("无权查看该报告");
- }
- Long subjectId = report.getSubjectId();
- if (subjectId == null) {
- boolean self = report.getUserId() != null && report.getUserId().equals(userId);
- if (!self && !reportMemberPermissionService.isFamilyAdmin(userId, reportFamilyId)) {
- return Result.error("无权查看该报告");
- }
- } else if (!reportMemberPermissionService.canViewMemberReports(userId, subjectId, reportFamilyId)) {
- return Result.error("无权查看该报告");
- }
- Boolean withPrevious = params.get("withPrevious") != null
- ? Boolean.valueOf(params.get("withPrevious").toString()) : true;
- // 复用已加载的 report 与指标行,避免重复查询(验收标准第 6 条:SQL ≤ 5 次)
- List<HealthIndicator> indicators = healthReportService.getReportIndicators(reportId);
- Map<String, Object> data = healthReportService.getReportIndicatorsWithPrevious(report, indicators, withPrevious);
- return Result.success(data);
- }
- /**
- * 获取某份报告的所有指标明细
- */
- @Operation(summary = "获取报告指标明细")
- @PostMapping("/indicator/list")
- public Result<List<HealthIndicator>> listIndicators(
- @RequestBody Map<String, Object> params) {
- Long reportId = ParamUtils.getLong(params.get("reportId"));
- if (reportId == null) {
- return Result.error("reportId不能为空");
- }
- List<HealthIndicator> indicators = healthReportService.getReportIndicators(reportId);
- return Result.success(indicators);
- }
- /**
- * 获取某成员某维度的最新指标值(用于首页指标卡片展示)
- */
- @Operation(summary = "获取成员维度指标列表")
- @PostMapping("/indicators")
- public Result<List<Map<String, Object>>> getMemberIndicators(
- @RequestBody Map<String, Object> params,
- @RequestAttribute("userId") Long userId,
- @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
- Long memberId = ParamUtils.getLong(params.get("memberId"), currentMemberId);
- String domain = (String) params.get("domain");
- if (memberId == null || domain == null) {
- return Result.error("memberId和domain不能为空");
- }
- try {
- List<Map<String, Object>> list = healthReportService.getLatestIndicatorsByDomain(memberId, domain);
- return Result.success(list);
- } catch (Exception e) {
- log.warn("获取指标失败: {}", e.getMessage());
- return Result.success(java.util.Collections.emptyList());
- }
- }
- /**
- * 获取成员最新菌群报告核心指标(用于身页面肠道菌群卡片)
- */
- @Operation(summary = "获取菌群指标")
- @PostMapping("/gut-flora")
- public Result<List<Map<String, Object>>> getGutFlora(
- @RequestBody Map<String, Object> params,
- @RequestAttribute("userId") Long userId,
- @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
- Long memberId = ParamUtils.getLong(params.get("memberId"), currentMemberId);
- if (memberId == null) return Result.error("memberId不能为空");
- try {
- List<Map<String, Object>> list = healthReportService.getGutFloraIndicators(memberId);
- return Result.success(list);
- } catch (Exception e) {
- log.warn("获取菌群指标失败: {}", e.getMessage());
- return Result.success(java.util.Collections.emptyList());
- }
- }
- /**
- * [admin] 回填成员指标当前值 diff(对存量未走新确认流程的报告手动触发)
- * 入参: memberId(必填);调用 healthReportService.rebuildForMember
- */
- @Operation(summary = "回填成员指标当前值(admin)")
- @PostMapping("/indicators/rebuild")
- public Result<Map<String, Object>> rebuildIndicatorCurrent(
- @RequestBody Map<String, Object> params,
- @RequestAttribute("userId") Long userId,
- @RequestAttribute(value = "role", required = false) String role) {
- Long memberId = ParamUtils.getLong(params.get("memberId"));
- if (memberId == null) return Result.error("memberId不能为空");
- if (!"admin".equals(role)) return Result.error("权限不足");
- try {
- healthReportService.rebuildForMember(memberId);
- Map<String, Object> out = new java.util.HashMap<>();
- out.put("memberId", memberId);
- out.put("rebuilt", true);
- return Result.success(out);
- } catch (Exception e) {
- log.warn("回填指标当前值失败 memberId={}: {}", memberId, e.getMessage());
- return Result.error("回填失败: " + e.getMessage());
- }
- }
- /**
- * 获取成员指标当前值 + 相对上一份报告的变化 delta(用于指标卡片与方案生成)
- * 数据来源:member_indicator_current(报告确认/编辑时由 refreshMemberIndicatorCurrent 写入)
- */
- @Operation(summary = "获取成员指标当前值与变化")
- @PostMapping("/indicators/current")
- public Result<List<Map<String, Object>>> getMemberIndicatorCurrent(
- @RequestBody Map<String, Object> params,
- @RequestAttribute("userId") Long userId,
- @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
- Long memberId = ParamUtils.getLong(params.get("memberId"), currentMemberId);
- String domain = (String) params.get("domain");
- if (memberId == null) {
- return Result.error("memberId不能为空");
- }
- try {
- List<Map<String, Object>> list = memberIndicatorCurrentService.getCurrentIndicators(memberId, domain);
- return Result.success(list);
- } catch (Exception e) {
- log.warn("获取成员指标当前值失败 memberId={}: {}", memberId, e.getMessage());
- return Result.success(java.util.Collections.emptyList());
- }
- }
- /**
- * 获取家庭成员身体维度数据详情(健康指标解读)
- */
- @Operation(summary = "获取身体维度数据详情")
- @PostMapping("/body/detail")
- public Result<List<HealthIndicator>> getBodyDetail(
- @RequestBody Map<String, Object> params,
- @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
- Long memberId = ParamUtils.getLong(params.get("memberId"), currentMemberId);
- if (memberId == null) {
- return Result.error("memberId不能为空");
- }
- List<HealthIndicator> detail = healthReportService.getBodyDetail(memberId);
- return Result.success(detail);
- }
- /**
- * 获取报告完整详情(含指标明细 + 菌群数据 + 疾病风险评估)
- */
- @Operation(summary = "获取报告完整详情")
- @PostMapping("/report/detail")
- public Result<Map<String, Object>> getReportDetail(
- @RequestBody Map<String, Object> params,
- @RequestAttribute("userId") Long userId,
- @RequestAttribute(value = "familyId", required = false) Long familyId) {
- Long reportId = ParamUtils.getLong(params.get("reportId"));
- if (reportId == null) {
- return Result.error("reportId不能为空");
- }
- HealthReport report = healthReportService.getReportById(reportId);
- if (report == null) {
- return Result.error("报告不存在");
- }
- // 权限校验:管理员 / 本人 / 被授权成员可见
- Long reportFamilyId = report.getFamilyId() != null ? report.getFamilyId() : familyId;
- if (reportFamilyId == null) {
- return Result.error("无权查看该报告");
- }
- Long subjectId = report.getSubjectId();
- if (subjectId == null) {
- // 无归属成员:仅本人上传者或管理员可见
- boolean self = report.getUserId() != null && report.getUserId().equals(userId);
- if (!self && !reportMemberPermissionService.isFamilyAdmin(userId, reportFamilyId)) {
- return Result.error("无权查看该报告");
- }
- } else if (!reportMemberPermissionService.canViewMemberReports(userId, subjectId, reportFamilyId)) {
- return Result.error("无权查看该报告");
- }
- Map<String, Object> detail = healthReportService.getReportDetail(reportId);
- return Result.success(detail);
- }
- /**
- * 获取报告 payload(编辑回填用,按需加载,减少首屏性能开销)
- */
- @Operation(summary = "获取报告payload(编辑回填)")
- @PostMapping("/report/payload")
- public Result<Map<String, Object>> getReportPayload(
- @RequestBody Map<String, Object> params,
- @RequestAttribute("userId") Long userId,
- @RequestAttribute(value = "familyId", required = false) Long familyId) {
- Long reportId = ParamUtils.getLong(params.get("reportId"));
- if (reportId == null) {
- return Result.error("reportId不能为空");
- }
- HealthReport report = healthReportService.getReportById(reportId);
- if (report == null) {
- return Result.error("报告不存在");
- }
- Long reportFamilyId = report.getFamilyId() != null ? report.getFamilyId() : familyId;
- if (reportFamilyId == null) {
- return Result.error("无权查看该报告");
- }
- Long subjectId = report.getSubjectId();
- if (subjectId == null) {
- boolean self = report.getUserId() != null && report.getUserId().equals(userId);
- if (!self && !reportMemberPermissionService.isFamilyAdmin(userId, reportFamilyId)) {
- return Result.error("无权查看该报告");
- }
- } else if (!reportMemberPermissionService.canViewMemberReports(userId, subjectId, reportFamilyId)) {
- return Result.error("无权查看该报告");
- }
- Map<String, Object> payload = healthReportService.getReportPayload(reportId);
- return Result.success(payload);
- }
- /**
- * 编辑已发布报告 — 修正 AI 解析错误的值
- */
- @Operation(summary = "编辑已发布报告数据")
- @PostMapping("/report/edit")
- public Result<String> editReport(
- @RequestBody Map<String, Object> params,
- @RequestAttribute("userId") Long userId,
- @RequestAttribute(value = "familyId", required = false) Long familyId) {
- Long reportId = ParamUtils.getLong(params.get("reportId"));
- if (reportId == null) {
- return Result.error("reportId不能为空");
- }
- if (userId == null) {
- return Result.error("用户未登录");
- }
- HealthReport report = healthReportService.getReportById(reportId);
- if (report == null) {
- return Result.error("报告不存在");
- }
- // 归属校验(与 getReportPayload 同范式:能回填即可保存)
- Long reportFamilyId = report.getFamilyId() != null ? report.getFamilyId() : familyId;
- if (reportFamilyId == null) {
- return Result.error("无权编辑该报告");
- }
- Long reportSubjectId = report.getSubjectId();
- if (reportSubjectId == null) {
- boolean self = report.getUserId() != null && report.getUserId().equals(userId);
- if (!self && !reportMemberPermissionService.isFamilyAdmin(userId, reportFamilyId)) {
- return Result.error("无权编辑该报告");
- }
- } else if (!reportMemberPermissionService.canViewMemberReports(userId, reportSubjectId, reportFamilyId)) {
- return Result.error("无权编辑该报告");
- }
- Long subjectId = ParamUtils.getLong(params.get("subjectId"));
- // subjectId 可为 null:用户取消绑定成员时传 null,表示解绑(不纳入家庭维度计算)
- // subjectId 与旧值不同时:重算旧成员 + 新成员维度分
- @SuppressWarnings("unchecked")
- Map<String, Object> payload = (Map<String, Object>) params.get("payload");
- if (payload == null) {
- return Result.error("payload不能为空");
- }
- healthReportService.updateReportFromPayload(reportId, payload, subjectId, userId);
- return Result.success("已保存");
- }
- /**
- * 删除健康报告(逻辑删除 + 清理关联数据)。
- *
- * <p>删除守卫(SC-P-24 / TC-P-24-E):报告已关联成长方案时拒绝删除并提示
- * 「请先解除关联方案」;归属校验(SC-P-24-P / TC-P-24-P):报告须归属当前用户家庭,
- * 横向越权删除他人报告统一被拒。</p>
- *
- * <p>E09 家庭内成员级校验:跨家庭拒绝后,家庭内亦仅上传者本人或家庭管理员可删除,
- * 防止同家庭成员越权删除他人报告。</p>
- */
- @Operation(summary = "删除健康报告")
- @PostMapping("/report/delete")
- public Result<String> deleteReport(
- @RequestBody Map<String, Object> params,
- @RequestAttribute("userId") Long userId,
- @RequestAttribute(value = "familyId", required = false) Long familyId) {
- Long reportId = ParamUtils.getLong(params.get("reportId"));
- if (reportId == null) {
- return Result.error("reportId不能为空");
- }
- if (userId == null) {
- return Result.error("用户未登录");
- }
- HealthReport report = healthReportService.getReportById(reportId);
- if (report == null) {
- return Result.error("报告不存在");
- }
- // 归属校验(TC-P-24-P):报告须归属当前用户家庭,横向越权删除被拒
- if (familyId != null && report.getFamilyId() != null && !familyId.equals(report.getFamilyId())) {
- return Result.error(403, "无权删除该报告");
- }
- // E09 越权修复:家庭内亦仅上传者本人或家庭管理员可删除
- boolean isOwner = report.getUserId() != null && report.getUserId().equals(userId);
- boolean isAdmin = report.getFamilyId() != null
- && reportMemberPermissionService.isFamilyAdmin(userId, report.getFamilyId());
- if (!isOwner && !isAdmin) {
- return Result.error("无权删除该报告");
- }
- try {
- healthReportService.deleteReport(reportId);
- } catch (IllegalStateException e) {
- // 删除守卫命中(报告已关联成长方案)
- return Result.error(409, e.getMessage());
- }
- return Result.success("已删除");
- }
- /**
- * 报告对比(SC-P-24 / TC-P-24「对比展示差异」,§4.59.10 契约缺口落地)。
- *
- * <p>入参 {@code {reportAId, reportBId}};类型一致才可比对,返回差异标注。</p>
- */
- @Operation(summary = "报告对比")
- @PostMapping("/report/compare")
- public Result<Map<String, Object>> compareReports(
- @RequestBody Map<String, Object> params,
- @RequestAttribute("userId") Long userId) {
- Long reportAId = ParamUtils.getLong(params.get("reportAId"));
- Long reportBId = ParamUtils.getLong(params.get("reportBId"));
- if (reportAId == null || reportBId == null) {
- return Result.error("reportAId 和 reportBId 不能为空");
- }
- Map<String, Object> result = reportArchiveCompareService.compareReports(reportAId, reportBId);
- return Result.success(result);
- }
- /**
- * 获取健康报告文件下载信息(小程序端"下载报告")
- * 返回完整可下载 URL 供 uni.downloadFile 使用;
- * 本地存储的相对路径(/uploads/**)自动拼接当前请求域名,避免前端拼接与域名白名单差异。
- */
- @Operation(summary = "获取健康报告文件下载信息")
- @PostMapping("/report/download")
- public Result<Map<String, Object>> downloadReport(
- @RequestBody Map<String, Object> params,
- @RequestAttribute("userId") Long userId,
- @RequestAttribute(value = "familyId", required = false) Long familyId,
- HttpServletRequest request) {
- if (userId == null) {
- return Result.error("用户未登录");
- }
- Long reportId = ParamUtils.getLong(params.get("reportId"));
- if (reportId == null) {
- return Result.error("reportId不能为空");
- }
- HealthReport report = healthReportService.getReportById(reportId);
- if (report == null) {
- return Result.error("报告不存在");
- }
- // E09-b 越权下载修复:与 detail/payload 同范式(能查看即可下载)
- Long reportFamilyId = report.getFamilyId() != null ? report.getFamilyId() : familyId;
- if (reportFamilyId == null) {
- return Result.error("无权下载该报告");
- }
- Long reportSubjectId = report.getSubjectId();
- if (reportSubjectId == null) {
- boolean self = report.getUserId() != null && report.getUserId().equals(userId);
- if (!self && !reportMemberPermissionService.isFamilyAdmin(userId, reportFamilyId)) {
- return Result.error("无权下载该报告");
- }
- } else if (!reportMemberPermissionService.canViewMemberReports(userId, reportSubjectId, reportFamilyId)) {
- return Result.error("无权下载该报告");
- }
- String fileUrl = report.getFileUrl();
- if (fileUrl == null || fileUrl.trim().isEmpty()) {
- return Result.error("该报告无文件可下载");
- }
- // 本地存储返回相对路径 /uploads/**,拼接当前请求域名得到完整 URL
- if (fileUrl.startsWith("/")) {
- String scheme = request.getHeader("X-Forwarded-Proto");
- if (scheme == null || scheme.trim().isEmpty()) {
- scheme = request.getScheme();
- }
- String host = request.getHeader("Host");
- if (host != null && !host.isEmpty()) {
- fileUrl = scheme + "://" + host + fileUrl;
- }
- }
- Map<String, Object> data = new LinkedHashMap<>();
- data.put("fileUrl", fileUrl);
- data.put("fileName", fileUrl.substring(fileUrl.lastIndexOf('/') + 1));
- return Result.success(data);
- }
- /**
- * 上传并解析肠道菌群报告PDF(向后兼容 — 内部自动执行两阶段:解析→确认)
- */
- @Operation(summary = "上传并解析肠道菌群报告PDF(兼容接口,自动确认)")
- @PostMapping("/report/upload")
- public Result<Map<String, Object>> uploadReport(
- @RequestParam("file") MultipartFile file,
- @RequestAttribute("userId") Long userId,
- @RequestAttribute(value = "familyId", required = false) Long familyId) {
- if (file.isEmpty()) {
- return Result.error("文件不能为空");
- }
- String contentType = file.getContentType();
- String originalFilename = file.getOriginalFilename();
- if (originalFilename == null || (!originalFilename.toLowerCase().endsWith(".pdf")
- && (contentType == null || !contentType.equalsIgnoreCase("application/pdf")))) {
- return Result.error("仅支持PDF文件");
- }
- try {
- ParsedReportResult parsed = pdfParseService.parse(file.getInputStream());
- if (parsed.getOverallScore() == null && parsed.getGutHealthScore() == null) {
- return Result.error("无法解析PDF文件,请确认是募极生物肠道菌群报告");
- }
- String fileUrl = storageService.storeFile(file, "health-reports");
- ParsedReportPayload.Payload payload = convertToPayload(parsed);
- String payloadJson = objectMapper.writeValueAsString(payload);
- HealthReportDraft draft = healthReportDraftService.createDraft(
- userId, familyId, "gut_flora", fileUrl, originalFilename, payloadJson);
- Long matchedMemberId = null;
- String matchedMemberName = null;
- if (familyId != null && parsed.getPersonName() != null) {
- matchedMemberId = healthReportService.matchFamilyMemberByName(parsed.getPersonName(), familyId);
- }
- HealthReport report = buildReportFromPayload(draft, payload, matchedMemberId);
- List<HealthIndicator> indicators = buildIndicatorsFromPayload(payload);
- List<HealthGutFlora> gutFlora = buildGutFloraFromPayload(payload);
- List<HealthDiseaseRisk> diseaseRisks = buildDiseaseRisksFromPayload(payload);
- HealthReport created = healthReportService.createReport(report, indicators, gutFlora, diseaseRisks);
- // 落库 payload 快照 + 创建日志
- healthReportService.savePayloadSnapshot(created.getId(), userId, "create", null, payloadJson);
- if (payload.getFoods() != null && !payload.getFoods().isEmpty()) {
- List<Food> foods = buildFoodsFromPayload(payload);
- foodService.saveFoodsForReport(created.getId(), foods);
- }
- if (matchedMemberId != null) {
- matchedMemberName = parsed.getPersonName();
- log.info("报告{}自动匹配到成员{}", created.getId(), matchedMemberId);
- try {
- dimensionScoreService.refreshFromGutReport(matchedMemberId, created.getId());
- log.info("已刷新成员{}的7维健康评分", matchedMemberId);
- } catch (Exception e) {
- log.warn("刷新7维健康评分失败: {}", e.getMessage());
- }
- try {
- foodRecommendService.recalculateForUser(matchedMemberId);
- log.info("已刷新成员{}的食材推荐指数", matchedMemberId);
- } catch (Exception e) {
- log.warn("刷新食材推荐指数失败: {}", e.getMessage());
- }
- }
- healthReportDraftService.markConfirmed(draft.getId(), created.getId());
- // 新手任务联动:完成首次报告上传任务(老用户无任务记录时静默跳过)
- try { onboardingService.completeTask(userId, "REPORT_UPLOAD"); } catch (Exception e) { log.warn("新手任务 REPORT_UPLOAD 更新失败: {}", e.getMessage()); }
- Map<String, Object> detail = healthReportService.getReportDetail(created.getId());
- detail.put("matchedMemberId", matchedMemberId);
- detail.put("matchedMemberName", matchedMemberName);
- detail.put("extractedName", parsed.getPersonName());
- detail.put("extractedReportNumber", parsed.getReportNumber());
- detail.put("extractedReportDate", parsed.getReportDate());
- detail.put("needBind", matchedMemberId == null);
- return Result.success(detail);
- } catch (IOException e) {
- log.error("PDF解析失败", e);
- return Result.error("PDF解析失败: " + e.getMessage());
- }
- }
- /**
- * 两阶段入库 Phase 0: 仅上传文件,不解析。返回 draftId 和 fileUrl,
- * 供前端展示「开始解析」按钮并导航至确认页触发异步解析。
- */
- @Operation(summary = "仅上传报告文件(不解析)")
- @PostMapping("/report/upload-only")
- public Result<Map<String, Object>> uploadOnly(
- @RequestParam("file") MultipartFile file,
- @RequestParam(value = "type", defaultValue = "auto") String type,
- @RequestParam(value = "memberId", required = false) Long memberId,
- @RequestAttribute("userId") Long userId,
- @RequestAttribute(value = "familyId", required = false) Long familyId) {
- if ("tongue".equals(type)) {
- // 舌诊照片:直接走舌诊流程(AI 视觉分析 + 存舌诊记录),不走 PDF 采集链
- try {
- Map<String, Object> tongueResult = tongueDiagnosisService.parsePreview(file, memberId);
- tongueResult.put("type", "tongue");
- return Result.success(tongueResult);
- } catch (Exception e) {
- log.error("舌诊解析失败", e);
- return Result.error("舌诊解析失败: " + e.getMessage());
- }
- }
- if (file.isEmpty()) {
- return Result.error("文件不能为空");
- }
- String contentType = file.getContentType();
- String originalFilename = file.getOriginalFilename();
- try {
- // 先读取文件字节:图片用于安全检测,PDF用于MD5去重(storeFile 后 temp 文件会被转移,无法再读)
- byte[] fileBytes = file.getBytes();
- String fileHash = computeMd5(fileBytes);
- // 图片类型:安全检测 + 保存
- if ("image".equals(type) || isImageContent(contentType)) {
- if (!wechatService.checkImage(fileBytes)) {
- return Result.error("图片内容包含敏感信息,上传失败");
- }
- // auto 模式下的图片先判断是否为舌象照片:是 → 直接走舌诊流程,
- // 避免舌诊照片被当作 PDF 报告走采集链导致 EOF 错误
- if ("auto".equals(type) || "image".equals(type)) {
- try {
- boolean isTongue = aiGateway.detectTongue(fileBytes, originalFilename);
- if (isTongue) {
- Map<String, Object> tongueResult = tongueDiagnosisService.parsePreview(file, memberId);
- tongueResult.put("type", "tongue");
- return Result.success(tongueResult);
- }
- } catch (Exception e) {
- log.warn("舌象照片分类失败,按普通图片处理: {}", e.getMessage());
- }
- }
- } else {
- // PDF 类型校验
- String lcName = originalFilename != null ? originalFilename.toLowerCase() : "";
- if (!lcName.endsWith(".pdf")
- && (contentType == null || !contentType.equalsIgnoreCase("application/pdf"))) {
- return Result.error("仅支持PDF文件");
- }
- }
- // 重复上传检测:同一 MD5 已入库或正在采集中则直接返回,不再重复解析
- Long existingReportId = healthReportService.findReportIdByFileHash(fileHash, reportTypeOfUpload(type, familyId));
- if (existingReportId != null) {
- Map<String, Object> dup = new LinkedHashMap<>();
- dup.put("duplicate", true);
- dup.put("reportId", existingReportId);
- HealthReport existingReport = healthReportService.getReportById(existingReportId);
- boolean crossFamily = existingReport != null
- && existingReport.getFamilyId() != null
- && (familyId == null || !familyId.equals(existingReport.getFamilyId()));
- if (crossFamily) {
- // 同一份报告已被其他家庭上传:需原家庭同意后方可转入本家庭,禁止直接跳详情
- dup.put("crossFamily", true);
- dup.put("message", "该报告已由其他家庭上传,发起转移申请并经对方同意后,报告将转入您的家庭");
- } else {
- dup.put("message", "该报告已上传过,无需重复解析");
- }
- return Result.success(dup);
- }
- Long collectingDraftId = healthReportService.findCollectingDraftIdByFileHash(fileHash);
- if (collectingDraftId != null) {
- Map<String, Object> dup = new LinkedHashMap<>();
- dup.put("duplicate", true);
- dup.put("draftId", collectingDraftId);
- dup.put("collecting", true);
- dup.put("message", "该报告正在解析中,请稍候");
- return Result.success(dup);
- }
- String fileUrl = storageService.storeFile(file, "health-reports");
- String reportType = familyId != null && !("pdf".equals(type) || "auto".equals(type))
- ? "physical_exam" : "gut_flora";
- // 创建空载荷草稿(不含解析数据)
- ParsedReportPayload.Payload emptyPayload = new ParsedReportPayload.Payload();
- String payloadJson = objectMapper.writeValueAsString(emptyPayload);
- HealthReportDraft draft = healthReportDraftService.createDraft(
- userId, familyId, reportType, fileUrl, originalFilename, payloadJson, fileHash, memberId);
- // 提交异步采集:指纹判定类型后走专用脚本/opencode,完成自动入库,前端轮询 parse_status
- reportCollectService.submitAsyncCollect(draft.getId());
- Map<String, Object> result = new LinkedHashMap<>();
- result.put("draftId", draft.getId());
- result.put("fileUrl", fileUrl);
- result.put("originalFilename", originalFilename);
- result.put("parseStatus", ReportCollectService.STATUS_COLLECTING);
- result.put("collecting", true);
- return Result.success(result);
- } catch (IOException e) {
- log.error("文件上传失败", e);
- return Result.error("文件上传失败: " + e.getMessage());
- }
- }
- /**
- * 计算上传文件的MD5哈希(用于重复上传去重)
- */
- private String computeMd5(byte[] data) {
- try {
- java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
- byte[] digest = md.digest(data);
- StringBuilder sb = new StringBuilder();
- for (byte b : digest) {
- sb.append(String.format("%02x", b));
- }
- return sb.toString();
- } catch (Exception e) {
- log.warn("计算文件MD5失败: {}", e.getMessage());
- return null;
- }
- }
- /**
- * 根据上传类型推导报告类型(与下方 reportType 计算保持一致,供去重查询使用)
- */
- private String reportTypeOfUpload(String type, Long familyId) {
- return familyId != null && !("pdf".equals(type) || "auto".equals(type))
- ? "physical_exam" : "gut_flora";
- }
- /**
- * 查询异步采集任务状态(前端轮询):返回 parse_status/parse_method/parse_error/reportId
- */
- @Operation(summary = "查询异步采集状态")
- @PostMapping("/report/collect/status")
- public Result<Map<String, Object>> collectStatus(
- @RequestBody Map<String, Object> params,
- @RequestAttribute("userId") Long userId) {
- Long draftId = ParamUtils.getLong(params.get("draftId"));
- if (draftId == null) {
- return Result.error("draftId不能为空");
- }
- HealthReportDraft draft = healthReportDraftService.getDraftById(draftId);
- if (draft == null) {
- return Result.error("草稿不存在");
- }
- if (!draft.getUserId().equals(userId)) {
- return Result.error("无权访问此草稿");
- }
- Map<String, Object> result = new LinkedHashMap<>();
- result.put("draftId", draftId);
- result.put("parseStatus", draft.getParseStatus());
- result.put("parseMethod", draft.getParseMethod());
- result.put("parseError", draft.getParseError());
- result.put("reportId", draft.getConfirmedReportId());
- result.put("reportType", draft.getReportType());
- // P0-3 ③:暴露 collect_validation(含 _解析自检 透传结果),前端轮询可核对
- result.put(COLLECT_VALIDATION_KEY, draft.getCollectValidation());
- return Result.success(result);
- }
- /**
- * 查询当前用户所有"采集中"的草稿(供报告列表顶部展示采集进度)
- */
- @Operation(summary = "查询采集中草稿列表")
- @PostMapping("/report/collecting-list")
- public Result<java.util.List<Map<String, Object>>> collectingList(
- @RequestAttribute("userId") Long userId) {
- java.util.List<HealthReportDraft> drafts = healthReportDraftService.listCollectingByUser(userId);
- java.util.List<Map<String, Object>> result = new java.util.ArrayList<>();
- for (HealthReportDraft d : drafts) {
- Map<String, Object> item = new LinkedHashMap<>();
- item.put("draftId", d.getId());
- item.put("originalFilename", d.getOriginalFilename());
- item.put("reportType", d.getReportType());
- item.put("createdAt", d.getCreatedAt());
- item.put("parseStatus", d.getParseStatus());
- result.add(item);
- }
- return Result.success(result);
- }
- /**
- * 体脂秤图片上传 + AI 识别(一步完成:上传→识别→存库)
- */
- @Operation(summary = "体脂秤图片上传并自动识别指标")
- @PostMapping("/report/bodyfat-upload")
- public Result<Map<String, Object>> uploadBodyFat(
- @RequestParam("file") MultipartFile file,
- @RequestAttribute("userId") Long userId,
- @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
- if (file.isEmpty()) {
- return Result.error("文件不能为空");
- }
- String contentType = file.getContentType();
- if (contentType == null || !contentType.startsWith("image/")) {
- return Result.error("仅支持图片文件(JPG/PNG)");
- }
- try {
- byte[] imageBytes = file.getBytes();
- if (!wechatService.checkImage(imageBytes)) {
- return Result.error("图片内容包含敏感信息,上传失败");
- }
- } catch (Exception e) {
- return Result.error("图片读取失败: " + e.getMessage());
- }
- String fileUrl = storageService.storeFile(file, "health-reports");
- Map<String, Object> analysisResult = bodyFatScaleService.analyzeImage(fileUrl);
- List<Map<String, Object>> metrics = (List<Map<String, Object>>) analysisResult.get("metrics");
- if (metrics == null) metrics = Collections.emptyList();
- Map<String, Object> result = new LinkedHashMap<>();
- result.put("metrics", metrics);
- result.put("fileUrl", fileUrl);
- return Result.success(result);
- }
- /**
- * 体脂秤指标直接入库(前端识别/人工修正后提交 {memberId, metrics:[{name,value,unit}]})
- */
- @Operation(summary = "保存体脂秤指标(无需上传图片)")
- @PostMapping("/report/bodyfat-save")
- public Result<Map<String, Object>> saveBodyFat(@RequestBody Map<String, Object> body,
- @RequestAttribute("userId") Long userId) {
- Long memberId = ParamUtils.getLong(body.get("memberId"));
- if (memberId == null) {
- return Result.error("memberId不能为空");
- }
- @SuppressWarnings("unchecked")
- List<Map<String, Object>> metrics = (List<Map<String, Object>>) body.get("metrics");
- if (metrics == null || metrics.isEmpty()) {
- return Result.error("无可保存的指标");
- }
- return Result.success(bodyFatScaleService.saveMetrics(memberId, metrics));
- }
- /**
- * 两阶段入库 Phase 1: 按 draftId 触发解析。读取已保存的文件,
- * 执行 LangGraph / 本地 Java 解析,更新草稿载荷后返回完整解析结果。
- */
- @Operation(summary = "按草稿ID触发解析")
- @PostMapping("/report/parse")
- public Result<Map<String, Object>> parseByDraftId(
- @RequestBody Map<String, Object> params,
- @RequestAttribute(value = "familyId", required = false) Long familyId,
- @RequestAttribute("userId") Long userId) {
- Long draftId = ParamUtils.getLong(params.get("draftId"));
- if (draftId == null) {
- return Result.error("draftId不能为空");
- }
- HealthReportDraft draft = healthReportDraftService.getActiveDraft(draftId);
- if (draft == null) {
- return Result.error("草稿不存在、已确认或已过期");
- }
- if (!draft.getUserId().equals(userId)) {
- return Result.error("无权操作此草稿");
- }
- String fileUrl = draft.getFileUrl();
- String originalFilename = draft.getOriginalFilename();
- try {
- // LangGraph 需要本地路径:经 getFilePath 下载到共享卷(LangGraph 容器可读)
- try {
- String lgPath = storageService.getFilePath(fileUrl);
- Map<String, Object> lgRequest = new HashMap<>();
- lgRequest.put("file_path", lgPath);
- lgRequest.put("user_id", userId);
- if (familyId != null) {
- lgRequest.put("family_id", familyId);
- }
- ResponseEntity<Map> lgResponse = restTemplate.postForEntity(
- langgraphBaseUrl + "/api/v1/report/parse", lgRequest, Map.class);
- Map<String, Object> lgBody = lgResponse.getBody();
- if (lgBody != null && Integer.valueOf(200).equals(lgBody.get("code"))) {
- Map<String, Object> lgData = (Map<String, Object>) lgBody.get("data");
- if (lgData != null) {
- return buildParseResultFromLg(lgData, draft, familyId);
- }
- }
- } catch (Exception e) {
- log.warn("LangGraph 解析失败,回退到本地 Java 解析: {}", e.getMessage());
- }
- // Fallback: 本地 Java 解析(下载 OSS 文件到本地临时目录,或直接读共享卷)
- String absolutePath = storageService.getFilePath(fileUrl);
- java.io.File localFile = new java.io.File(absolutePath);
- if (!localFile.exists()) {
- return Result.error("文件不存在或已过期: " + originalFilename);
- }
- return parseLocalFallback(absolutePath, draft, familyId, userId);
- } catch (Exception e) {
- log.error("文件解析失败", e);
- return Result.error("解析失败: " + e.getMessage());
- }
- }
- /**
- * 构造 LangGraph 解析结果(复用 parsePreview 中的逻辑)
- */
- private Result<Map<String, Object>> buildParseResultFromLg(
- Map<String, Object> lgData, HealthReportDraft draft,
- Long familyId) throws Exception {
- ParsedReportPayload.Payload lgPayload = buildPayloadFromLgData(lgData);
- String payloadJson = objectMapper.writeValueAsString(lgPayload);
- healthReportDraftService.updatePayload(draft.getId(), payloadJson);
- Map<String, Object> overview = (Map<String, Object>) lgData.get("overview");
- String personName = overview != null ? (String) overview.get("person_name") : null;
- String gender = overview != null ? (String) overview.get("gender") : null;
- Integer age = overview != null ? toInteger(overview.get("age")) : null;
- MemberMatchResult matchResult = healthReportService.matchMemberByProfile(
- personName, gender, age, familyId);
- Map<String, Object> result = new LinkedHashMap<>();
- result.put("draftId", draft.getId());
- result.put("payload", lgPayload);
- result.put("matchedMemberId", matchResult.getMatchedMemberId());
- result.put("confidence", matchResult.getConfidence());
- result.put("matchLabel", matchResult.getMatchLabel());
- result.put("candidates", matchResult.getCandidates());
- result.put("extractedName", personName);
- result.put("extractedGender", gender);
- result.put("extractedAge", age);
- result.put("needBind", matchResult.getMatchedMemberId() == null && familyId != null);
- try {
- saveResultToJsonFile(result);
- } catch (Exception e) {
- log.warn("保存结果到 JSON 文件失败:{}", e.getMessage());
- }
- return Result.success(result);
- }
- /**
- * 本地 Java 解析回退
- */
- private Result<Map<String, Object>> parseLocalFallback(
- String absolutePath, HealthReportDraft draft, Long familyId, Long userId)
- throws Exception {
- try (java.io.FileInputStream fis = new java.io.FileInputStream(absolutePath)) {
- ParsedReportResult parsed = pdfParseService.parse(fis);
- if (parsed.getOverallScore() == null && parsed.getGutHealthScore() == null) {
- return Result.error("无法解析PDF文件,请确认是募极生物肠道菌群报告");
- }
- ParsedReportPayload.Payload payload = convertToPayload(parsed);
- String payloadJson = objectMapper.writeValueAsString(payload);
- healthReportDraftService.updatePayload(draft.getId(), payloadJson);
- MemberMatchResult matchResult = healthReportService.matchMemberByProfile(
- parsed.getPersonName(), parsed.getGender(), parsed.getAge(), familyId);
- Map<String, Object> result = new LinkedHashMap<>();
- result.put("draftId", draft.getId());
- result.put("payload", payload);
- result.put("matchedMemberId", matchResult.getMatchedMemberId());
- result.put("confidence", matchResult.getConfidence());
- result.put("matchLabel", matchResult.getMatchLabel());
- result.put("candidates", matchResult.getCandidates());
- result.put("extractedName", parsed.getPersonName());
- result.put("extractedGender", parsed.getGender());
- result.put("extractedAge", parsed.getAge());
- // B1-1:前端预览三行(被检测人/报告编号/报告日期)还读这两个字段,补齐避免恒 '-'
- result.put("extractedReportNumber", parsed.getReportNumber());
- result.put("extractedReportDate", parsed.getReportDate());
- result.put("needBind", matchResult.getMatchedMemberId() == null && familyId != null);
- return Result.success(result);
- }
- }
- /**
- * 两阶段入库 Phase 1: 上传PDF → 解析 → 存草稿 → 返回draftId + 解析载荷 + 成员匹配
- * 不落库到 health_reports 等正式表。支持 PDF 解析(auto)和图片上传(image)。
- *
- * @deprecated 使用 /report/upload(仅上传)+ /report/parse(按草稿解析)替代
- */
- @Operation(summary = "上传解析报告(预览,不入库)")
- @PostMapping("/report/parse-preview")
- public Result<Map<String, Object>> parsePreview(
- @RequestParam("file") MultipartFile file,
- @RequestParam(value = "type", defaultValue = "auto") String type,
- @RequestAttribute(value = "familyId", required = false) Long familyId,
- @RequestParam(value = "memberId", required = false) Long memberId,
- @RequestAttribute("userId") Long userId) {
- if ("tongue".equals(type)) {
- if (memberId == null) {
- return Result.error("memberId is required for tongue diagnosis");
- }
- Map<String, Object> result = tongueDiagnosisService.parsePreview(file, memberId);
- return Result.success(result);
- }
- if (file == null || file.isEmpty()) {
- return Result.error("文件不能为空");
- }
- String contentType = file.getContentType();
- String originalFilename = file.getOriginalFilename();
- try {
- // 图片上传:保存文件 + 创建空草稿(无自动解析)
- if ("image".equals(type) || isImageContent(contentType)) {
- // 图片内容安全检测
- try {
- byte[] imageBytes = file.getBytes();
- if (!wechatService.checkImage(imageBytes)) {
- return Result.error("图片内容包含敏感信息,上传失败");
- }
- } catch (IOException e) {
- return Result.error("图片读取失败: " + e.getMessage());
- }
- String fileUrl = storageService.storeFile(file, "health-reports");
- String reportType = familyId != null ? "physical_exam" : "gut_flora";
- // 创建空载荷草稿,后续由 confirm 阶段用户补充
- ParsedReportPayload.Payload emptyPayload = new ParsedReportPayload.Payload();
- String payloadJson = objectMapper.writeValueAsString(emptyPayload);
- HealthReportDraft draft = healthReportDraftService.createDraft(
- userId, familyId, reportType, fileUrl, originalFilename, payloadJson);
- Map<String, Object> result = new LinkedHashMap<>();
- result.put("draftId", draft.getId());
- result.put("payload", emptyPayload);
- result.put("fileUrl", fileUrl);
- result.put("needBind", false);
- return Result.success(result);
- }
- // PDF 解析(默认路径)
- String lcName = originalFilename != null ? originalFilename.toLowerCase() : "";
- if (!lcName.endsWith(".pdf")
- && (contentType == null || !contentType.equalsIgnoreCase("application/pdf"))) {
- return Result.error("仅支持PDF文件");
- }
- // 保存文件(通过 StorageService 支持本地磁盘或京东云 OSS)
- String fileUrl = storageService.storeFile(file, "health-reports");
- // 尝试 LangGraph 解析(LangGraph 只认本地路径,必须经 getFilePath 下载到共享卷)
- try {
- Map<String, Object> lgRequest = new HashMap<>();
- lgRequest.put("file_path", storageService.getFilePath(fileUrl));
- lgRequest.put("user_id", userId);
- if (familyId != null) {
- lgRequest.put("family_id", familyId);
- }
- ResponseEntity<Map> lgResponse = restTemplate.postForEntity(
- langgraphBaseUrl + "/api/v1/report/parse", lgRequest, Map.class);
- Map<String, Object> lgBody = lgResponse.getBody();
- if (lgBody != null && Integer.valueOf(200).equals(lgBody.get("code"))) {
- Map<String, Object> lgData = (Map<String, Object>) lgBody.get("data");
- if (lgData != null) {
- ParsedReportPayload.Payload lgPayload = buildPayloadFromLgData(lgData);
- String payloadJson = objectMapper.writeValueAsString(lgPayload);
- HealthReportDraft draft = healthReportDraftService.createDraft(
- userId, familyId, "gut_flora", fileUrl, originalFilename, payloadJson);
- Map<String, Object> overview = (Map<String, Object>) lgData.get("overview");
- String personName = overview != null ? (String) overview.get("person_name") : null;
- String gender = overview != null ? (String) overview.get("gender") : null;
- Integer age = overview != null ? toInteger(overview.get("age")) : null;
- MemberMatchResult matchResult = healthReportService.matchMemberByProfile(
- personName, gender, age, familyId);
- Map<String, Object> result = new LinkedHashMap<>();
- result.put("draftId", draft.getId());
- result.put("payload", lgPayload);
- result.put("matchedMemberId", matchResult.getMatchedMemberId());
- result.put("confidence", matchResult.getConfidence());
- result.put("matchLabel", matchResult.getMatchLabel());
- result.put("candidates", matchResult.getCandidates());
- result.put("extractedName", personName);
- result.put("extractedGender", gender);
- result.put("extractedAge", age);
- result.put("needBind", matchResult.getMatchedMemberId() == null && familyId != null);
- try {
- saveResultToJsonFile(result);
- } catch (Exception e) {
- log.warn("保存结果到 JSON 文件失败:{}", e.getMessage());
- }
- return Result.success(result);
- }
- }
- } catch (Exception e) {
- log.warn("LangGraph 解析失败,回退到本地 Java 解析: {}", e.getMessage());
- }
- // Fallback: 本地 Java 解析
- ParsedReportResult parsed = pdfParseService.parse(file.getInputStream());
- if (parsed.getOverallScore() == null && parsed.getGutHealthScore() == null) {
- return Result.error("无法解析PDF文件,请确认是募极生物肠道菌群报告");
- }
- ParsedReportPayload.Payload payload = convertToPayload(parsed);
- String payloadJson = objectMapper.writeValueAsString(payload);
- HealthReportDraft draft = healthReportDraftService.createDraft(
- userId, familyId, "gut_flora", fileUrl, originalFilename, payloadJson);
- // 使用多字段匹配(姓名+性别+年龄)
- MemberMatchResult matchResult = healthReportService.matchMemberByProfile(
- parsed.getPersonName(),
- parsed.getGender(),
- parsed.getAge(),
- familyId
- );
- Map<String, Object> result = new LinkedHashMap<>();
- result.put("draftId", draft.getId());
- result.put("payload", payload);
- result.put("matchedMemberId", matchResult.getMatchedMemberId());
- result.put("confidence", matchResult.getConfidence());
- result.put("matchLabel", matchResult.getMatchLabel());
- result.put("candidates", matchResult.getCandidates());
- result.put("extractedName", parsed.getPersonName());
- result.put("extractedGender", parsed.getGender());
- result.put("extractedAge", parsed.getAge());
- result.put("needBind", matchResult.getMatchedMemberId() == null && familyId != null);
- // 保存结果到本地 JSON 文件
- try {
- saveResultToJsonFile(result);
- } catch (Exception e) {
- log.warn("保存结果到 JSON 文件失败:{}", e.getMessage());
- // 不影响主要流程,只是记录警告
- }
- return Result.success(result);
- } catch (IOException e) {
- log.error("文件处理失败", e);
- return Result.error("文件处理失败: " + e.getMessage());
- }
- }
- /**
- * 判断是否为图片 MIME 类型
- */
- private boolean isImageContent(String contentType) {
- if (contentType == null) return false;
- return contentType.startsWith("image/");
- }
- /**
- * 两阶段入库 Phase 2: 确认草稿 → 写入正式表 → 刷新7维评分
- * 前端可回传修改后的 payload(用户在线编辑指标后整体提交)。
- */
- @Operation(summary = "确认报告草稿(正式入库)")
- @PostMapping("/report/confirm")
- public Result<Map<String, Object>> confirmDraft(
- @RequestParam(value = "type", defaultValue = "pdf") String type,
- @RequestBody Map<String, Object> params,
- @RequestAttribute("userId") Long userId) {
- if ("tongue".equals(type)) {
- Long recordId = ParamUtils.getLong(params.get("recordId"));
- Long subjectId = ParamUtils.getLong(params.get("subjectId"));
- @SuppressWarnings("unchecked")
- List<Map<String, Object>> indicators = (List<Map<String, Object>>) params.getOrDefault("indicators", null);
- Map<String, Object> result = tongueDiagnosisService.confirm(recordId, indicators, subjectId);
- return Result.success(result);
- }
- Long draftId = ParamUtils.getLong(params.get("draftId"));
- if (draftId == null) {
- return Result.error("draftId不能为空");
- }
- HealthReportDraft draft = healthReportDraftService.getActiveDraft(draftId);
- if (draft == null || "confirmed".equals(draft.getStatus()) || "discarded".equals(draft.getStatus())) {
- return Result.error("草稿不存在、已确认或已过期");
- }
- if (!draft.getUserId().equals(userId)) {
- return Result.error("无权操作此草稿");
- }
- try {
- ParsedReportPayload.Payload payload;
- Object payloadObj = params.get("payload");
- String payloadJson;
- if (payloadObj != null) {
- payloadJson = objectMapper.writeValueAsString(payloadObj);
- payload = objectMapper.readValue(payloadJson, ParsedReportPayload.Payload.class);
- } else {
- payloadJson = draft.getPayloadJson();
- payload = objectMapper.readValue(payloadJson, ParsedReportPayload.Payload.class);
- }
- Long subjectId = ParamUtils.getLong(params.get("subjectId"));
- HealthReport report = buildReportFromPayload(draft, payload, subjectId);
- List<HealthIndicator> indicators = buildIndicatorsFromPayload(payload);
- List<HealthGutFlora> gutFlora = buildGutFloraFromPayload(payload);
- List<HealthDiseaseRisk> diseaseRisks = buildDiseaseRisksFromPayload(payload);
- HealthReport created = healthReportService.createReport(report, indicators, gutFlora, diseaseRisks);
- // G2(DS-2026-10-25-01):confirm 链路补写统一指标层时序(失败不阻断确认)
- try {
- normalizeIndicatorPipeline.processReport(created, payload);
- } catch (Exception e) {
- log.warn("confirm 归一化管道写入失败 reportId={}: {}", created.getId(), e.getMessage());
- }
- // 落库 payload 快照 + 创建日志
- healthReportService.savePayloadSnapshot(created.getId(), userId, "create", null, payloadJson);
- if (payload.getFoods() != null && !payload.getFoods().isEmpty()) {
- List<Food> foods = buildFoodsFromPayload(payload);
- foodService.saveFoodsForReport(created.getId(), foods);
- }
- if (subjectId != null) {
- healthReportService.bindReportToMember(created.getId(), subjectId);
- try {
- dimensionScoreService.refreshFromGutReport(subjectId, created.getId());
- log.info("已刷新成员{}的7维健康评分", subjectId);
- } catch (Exception e) {
- log.warn("刷新7维健康评分失败: {}", e.getMessage());
- }
- try {
- healthReportService.refreshMemberIndicatorCurrent(subjectId, created.getId());
- log.info("已刷新成员{}的指标当前值diff", subjectId);
- } catch (Exception e) {
- log.warn("刷新指标当前值diff失败: {}", e.getMessage());
- }
- try {
- foodRecommendService.recalculateForUser(subjectId);
- log.info("已刷新成员{}的食材推荐指数", subjectId);
- } catch (Exception e) {
- log.warn("刷新食材推荐指数失败: {}", e.getMessage());
- }
- } else if (draft.getFamilyId() != null && payload.getSummary() != null
- && payload.getSummary().getPersonName() != null) {
- Long matchedId = healthReportService.matchFamilyMemberByName(
- payload.getSummary().getPersonName(), draft.getFamilyId());
- if (matchedId != null) {
- healthReportService.bindReportToMember(created.getId(), matchedId);
- try {
- dimensionScoreService.refreshFromGutReport(matchedId, created.getId());
- } catch (Exception e) {
- log.warn("刷新7维健康评分失败: {}", e.getMessage());
- }
- try {
- healthReportService.refreshMemberIndicatorCurrent(matchedId, created.getId());
- log.info("已刷新成员{}的指标当前值diff", matchedId);
- } catch (Exception e) {
- log.warn("刷新指标当前值diff失败: {}", e.getMessage());
- }
- try {
- foodRecommendService.recalculateForUser(matchedId);
- log.info("已刷新成员{}的食材推荐指数", matchedId);
- } catch (Exception e) {
- log.warn("刷新食材推荐指数失败: {}", e.getMessage());
- }
- subjectId = matchedId;
- }
- }
- healthReportDraftService.markConfirmed(draftId, created.getId());
- // 幂等短路(S-cfc-363 / RED-1):markConfirmed 后同步将本地草稿置为非 pending 态,
- // 使并发/重复确认(getActiveDraft 返回同一草稿实例)在入口快速拒绝,避免重复入库 + 重复刷新评分
- draft.setStatus("confirmed");
- draft.setConfirmedReportId(created.getId());
- // 落库通用展示块(blocks 组装失败不阻断确认)
- try {
- String reportType = created.getReportType();
- reportBlockService.save(reportType, created.getId(),
- reportBlockAssembler.assembleWithTemplate(reportType, payload));
- } catch (Exception e) {
- log.warn("保存展示块失败 reportId={}: {}", created.getId(), e.getMessage());
- }
- Map<String, Object> detail = healthReportService.getReportDetail(created.getId());
- if (subjectId != null) {
- detail.put("subjectId", subjectId);
- }
- detail.put("reportId", created.getId());
- detail.put("reportType", created.getReportType());
- triggerAutoPlanAfterConfirm(detail, draft.getFamilyId(), subjectId, created.getReportType());
- return Result.success(detail);
- } catch (Exception e) {
- log.error("确认草稿失败", e);
- return Result.error("确认草稿失败: " + e.getMessage());
- }
- }
- /** 报告确认入库后自动生成并发布健康方案(舌诊等不适用类型跳过) */
- private void triggerAutoPlanAfterConfirm(Map<String, Object> detail, Long familyId,
- Long subjectId, String reportType) {
- if (familyId == null || subjectId == null || !shouldAutoGeneratePlan(reportType)) {
- return;
- }
- try {
- Long planId = healthPlanService.autoGenerateAndPublish(familyId, subjectId, reportType);
- if (planId != null) {
- detail.put("planId", planId);
- }
- } catch (Exception e) {
- log.warn("确认入库后自动生成方案失败 reportType={}: {}", reportType, e.getMessage());
- }
- }
- private boolean shouldAutoGeneratePlan(String reportType) {
- return reportType != null && !"tongue".equals(reportType);
- }
- /**
- * 放弃草稿
- */
- @Operation(summary = "放弃报告草稿")
- @PostMapping("/report/discard")
- public Result<String> discardDraft(
- @RequestParam(value = "type", defaultValue = "pdf") String type,
- @RequestBody Map<String, Object> params,
- @RequestAttribute("userId") Long userId) {
- if ("tongue".equals(type)) {
- Long recordId = ParamUtils.getLong(params.get("recordId"));
- tongueDiagnosisService.discard(recordId);
- return Result.success("草稿已删除");
- }
- Long draftId = ParamUtils.getLong(params.get("draftId"));
- if (draftId == null) {
- return Result.error("draftId不能为空");
- }
- HealthReportDraft draft = healthReportDraftService.getActiveDraft(draftId);
- if (draft == null) {
- return Result.error("草稿不存在或已处理");
- }
- if (!draft.getUserId().equals(userId)) {
- return Result.error("无权操作此草稿");
- }
- healthReportDraftService.markDiscarded(draftId);
- return Result.success("草稿已放弃");
- }
- /**
- * 手动绑定报告到家庭成员
- */
- @Operation(summary = "绑定报告到成员")
- @PostMapping("/report/bind")
- public Result<String> bindReport(
- @RequestBody Map<String, Object> params) {
- Long reportId = ParamUtils.getLong(params.get("reportId"));
- Long subjectId = ParamUtils.getLong(params.get("subjectId"));
- if (reportId == null || subjectId == null) {
- return Result.error("reportId和subjectId不能为空");
- }
- healthReportService.bindReportToMember(reportId, subjectId);
- return Result.success("报告绑定成功");
- }
- /**
- * 重新分配报告归属
- *
- * <p>将报告从旧归属切换到新归属,或解除归属(subjectId 设为 null)。
- * 归属变更后自动重新计算五维能量维度和食材推荐指数。</p>
- *
- * <p>权限检查:仅家庭成员或管理员可操作,通过 familyId 验证报告归属。</p>
- *
- * @param params 请求体:reportId (必填), subjectId (可为 null 表示解绑)
- * @param familyId 当前登录用户的家庭ID(由 JwtInterceptor 注入)
- * @return 操作结果
- */
- @PostMapping("/report/reassign")
- public Result<String> reassignReport(@RequestBody Map<String, Object> params,
- @RequestAttribute(value = "familyId", required = false) Long familyId) {
- Long reportId = ParamUtils.getLong(params.get("reportId"));
- Long newSubjectId = ParamUtils.getLong(params.get("subjectId")); // null = unbind
-
- healthReportService.reassignReport(reportId, newSubjectId, familyId);
- return Result.success("归属已更新");
- }
- /**
- * 发起报告跨家庭转移申请(申请方家庭)
- *
- * <p>同一份报告(文件MD5相同)已被其他家庭上传时,上传接口返回 crossFamily=true,
- * 前端弹窗确认后调用本接口发起申请;原家庭在「健康报告」列表同意后报告转入本家庭。</p>
- *
- * @param params 请求体:reportId (必填)
- * @param familyId 当前登录用户的家庭ID(申请方,由 JwtInterceptor 注入)
- * @param userId 当前登录用户ID
- * @return 转移申请摘要 {requestId, status}
- */
- @PostMapping("/report/transfer/request")
- public Result<Map<String, Object>> requestReportTransfer(
- @RequestBody Map<String, Object> params,
- @RequestAttribute(value = "familyId", required = false) Long familyId,
- @RequestAttribute("userId") Long userId) {
- if (familyId == null) {
- return Result.noFamily("请先创建或加入家庭");
- }
- Long reportId = ParamUtils.getLong(params.get("reportId"));
- try {
- ReportTransferRequest request = reportTransferService.createRequest(reportId, familyId, userId);
- Map<String, Object> data = new LinkedHashMap<>();
- data.put("requestId", request.getId());
- data.put("status", request.getStatus());
- return Result.success(data);
- } catch (RuntimeException e) {
- return Result.error(e.getMessage());
- }
- }
- /**
- * 同意转移(原归属家庭):报告 family_id 转入申请方,本家庭不再可见
- */
- @PostMapping("/report/transfer/approve")
- public Result<String> approveReportTransfer(
- @RequestBody Map<String, Object> params,
- @RequestAttribute(value = "familyId", required = false) Long familyId,
- @RequestAttribute("userId") Long userId) {
- if (familyId == null) {
- return Result.noFamily("请先创建或加入家庭");
- }
- Long requestId = ParamUtils.getLong(params.get("requestId"));
- try {
- reportTransferService.approve(requestId, familyId, userId);
- return Result.success("已同意转移,报告已转入对方家庭");
- } catch (RuntimeException e) {
- return Result.error(e.getMessage());
- }
- }
- /**
- * 拒绝转移(原归属家庭):报告留在本家庭
- */
- @PostMapping("/report/transfer/deny")
- public Result<String> denyReportTransfer(
- @RequestBody Map<String, Object> params,
- @RequestAttribute(value = "familyId", required = false) Long familyId,
- @RequestAttribute("userId") Long userId) {
- if (familyId == null) {
- return Result.noFamily("请先创建或加入家庭");
- }
- Long requestId = ParamUtils.getLong(params.get("requestId"));
- String remark = params.get("remark") != null ? String.valueOf(params.get("remark")) : null;
- try {
- reportTransferService.deny(requestId, familyId, userId, remark);
- return Result.success("已拒绝该转移申请");
- } catch (RuntimeException e) {
- return Result.error(e.getMessage());
- }
- }
- /**
- * 查询本家庭相关的转移申请列表
- *
- * @return {incoming: 待本家庭处理(原归属方), outgoing: 本家庭发起的(申请方)}
- */
- @PostMapping("/report/transfer/list")
- public Result<Map<String, Object>> listReportTransfers(
- @RequestAttribute(value = "familyId", required = false) Long familyId) {
- if (familyId == null) {
- return Result.noFamily("请先创建或加入家庭");
- }
- return Result.success(reportTransferService.listRequests(familyId));
- }
- /**
- * 获取某家庭中所有未绑定成员的报告列表
- */
- @PostMapping("/report/unlinked")
- public Result<List<HealthReport>> getUnlinkedReports(
- @RequestAttribute(value = "familyId", required = false) Long familyId) {
- if (familyId == null) {
- return Result.noFamily("请先创建或加入家庭");
- }
- List<HealthReport> reports = healthReportService.getUnlinkedReports(familyId);
- return Result.success(reports);
- }
- /**
- * 添加报告查看权限(授权家庭成员查看报告)
- */
- @Operation(summary = "添加报告查看权限")
- @PostMapping("/report/permission/add")
- public Result<String> addReportPermission(
- @RequestBody Map<String, Object> params) {
- Long reportId = ParamUtils.getLong(params.get("reportId"));
- Long targetUserId = ParamUtils.getLong(params.get("userId"));
- if (reportId == null || targetUserId == null) {
- return Result.error("reportId和userId不能为空");
- }
- healthReportService.addReportPermission(reportId, targetUserId);
- return Result.success("权限添加成功");
- }
- /**
- * 移除报告查看权限
- */
- @Operation(summary = "移除报告查看权限")
- @PostMapping("/report/permission/remove")
- public Result<String> removeReportPermission(
- @RequestBody Map<String, Object> params) {
- Long reportId = ParamUtils.getLong(params.get("reportId"));
- Long targetUserId = ParamUtils.getLong(params.get("userId"));
- if (reportId == null || targetUserId == null) {
- return Result.error("reportId和userId不能为空");
- }
- healthReportService.removeReportPermission(reportId, targetUserId);
- return Result.success("权限移除成功");
- }
- /**
- * 检查用户是否有报告查看权限
- */
- @Operation(summary = "检查报告查看权限")
- @PostMapping("/report/permission/check")
- public Result<Boolean> checkReportPermission(
- @RequestBody Map<String, Object> params) {
- Long reportId = ParamUtils.getLong(params.get("reportId"));
- Long targetUserId = ParamUtils.getLong(params.get("userId"));
- if (reportId == null || targetUserId == null) {
- return Result.error("reportId和userId不能为空");
- }
- boolean hasPermission = healthReportService.hasReportPermission(reportId, targetUserId);
- return Result.success(hasPermission);
- }
- @Operation(summary = "获取营养缺乏分析")
- @PostMapping("/nutrition/deficiency")
- public Result<List<NutritionDeficiencyRecord>> getDeficiencyAnalysis(
- @RequestBody Map<String, Object> params) {
- Long memberId = ParamUtils.getLong(params.get("memberId"));
- if (memberId == null) {
- return Result.error("memberId不能为空");
- }
- Long reportId = ParamUtils.getLong(params.get("reportId"));
- List<NutritionDeficiencyRecord> records = nutritionDeficiencyService.analyzeDeficiency(memberId, reportId);
- return Result.success(records);
- }
- @Operation(summary = "获取家庭成员营养档案")
- @PostMapping("/nutrition/profile")
- public Result<Map<String, Object>> getNutritionProfile(
- @RequestBody Map<String, Object> params) {
- Long memberId = ParamUtils.getLong(params.get("memberId"));
- if (memberId == null) {
- return Result.error("memberId不能为空");
- }
- Map<String, Object> profile = childNutritionProfileService.getProfile(memberId);
- return Result.success(profile);
- }
- @Operation(summary = "获取营养缺乏摘要")
- @PostMapping("/nutrition/deficiency-summary")
- public Result<Map<String, Object>> getDeficiencySummary(
- @RequestBody Map<String, Object> params) {
- Long memberId = ParamUtils.getLong(params.get("memberId"));
- if (memberId == null) {
- return Result.error("memberId不能为空");
- }
- Map<String, Object> summary = childNutritionProfileService.getDeficiencySummary(memberId);
- return Result.success(summary);
- }
- @Operation(summary = "获取报告趋势数据")
- @PostMapping("/nutrition/trend")
- public Result<Map<String, Object>> getReportTrendData(
- @RequestBody Map<String, Object> params) {
- Long memberId = ParamUtils.getLong(params.get("memberId"));
- if (memberId == null) {
- return Result.error("memberId不能为空");
- }
- Map<String, Object> trend = childNutritionProfileService.getReportTrendData(memberId);
- return Result.success(trend);
- }
- @Operation(summary = "获取健康分析(含营养缺乏)")
- @PostMapping("/analysis")
- public Result<Map<String, Object>> getHealthAnalysis(
- @RequestBody Map<String, Object> params) {
- Long memberId = ParamUtils.getLong(params.get("memberId"));
- if (memberId == null) {
- return Result.error("memberId不能为空");
- }
- HealthAnalysisResult analysisResult = healthAnalysisService.analyzeLatestByUser(memberId);
- List<NutritionDeficiencyRecord> deficiencyRecords = nutritionDeficiencyService.analyzeDeficiency(memberId, null);
- Map<String, Object> result = new java.util.HashMap<>();
- result.put("analysis", analysisResult);
- result.put("deficiencyRecords", deficiencyRecords);
- return Result.success(result);
- }
- @Operation(summary = "管理指标-营养素映射")
- @PostMapping("/nutrition/mappings")
- public Result<List<NutritionIndicatorMapping>> listMappings() {
- List<NutritionIndicatorMapping> mappings = nutritionDeficiencyService.getAllMappings();
- return Result.success(mappings);
- }
- @Operation(summary = "创建指标-营养素映射")
- @PostMapping("/nutrition/mapping/create")
- public Result<?> createMapping(@RequestBody NutritionIndicatorMapping mapping) {
- nutritionDeficiencyService.saveMapping(mapping);
- return Result.success(null);
- }
- @Operation(summary = "更新指标-营养素映射")
- @PostMapping("/nutrition/mapping/update")
- public Result<?> updateMapping(@RequestBody NutritionIndicatorMapping mapping) {
- nutritionDeficiencyService.saveMapping(mapping);
- return Result.success(null);
- }
- @Operation(summary = "删除指标-营养素映射")
- @PostMapping("/nutrition/mapping/delete")
- public Result<?> deleteMapping(@RequestBody Map<String, Object> params) {
- Long id = ParamUtils.getLong(params.get("id"));
- if (id == null) {
- return Result.error("id不能为空");
- }
- nutritionDeficiencyService.deleteMapping(id);
- return Result.success(null);
- }
- @Operation(summary = "获取食材推荐列表")
- @PostMapping("/foods")
- public Result<List<Food>> listFoods(@RequestBody(required = false) Map<String, Object> params,
- @RequestAttribute(value = "userId", required = false) Long userId) {
- Long reportId = params != null ? ParamUtils.getLong(params.get("reportId")) : null;
- List<Food> foods;
- if (reportId != null) {
- // 指定报告:返回该报告的食材推荐
- foods = foodService.listByReportId(reportId);
- } else {
- // 未指定报告:优先用 memberId(成员视角),其次 JWT userId(本人视角)
- // food_recommend_idx 以 subjectId 维度写入,家庭主账号 JWT userId 查不到家庭成员的推荐。
- // 成员视角须用 resolveMemberViewToUserId 归一(family_members.id → users.id),
- // 规避 users 与 family_members.id 数值重叠时把成员误判为无关用户(家庭72 书宁宁案例)。
- Long memberId = params != null ? ParamUtils.getLong(params.get("memberId")) : null;
- Long uid;
- if (memberId != null) {
- Long resolved = foodRecommendService.resolveMemberViewToUserId(memberId);
- uid = resolved != null ? resolved : -1L;
- } else {
- uid = userId != null ? userId : -1L;
- }
- foods = foodRecommendService.getCurrentFoodsAsFoodList(uid);
- }
- return Result.success(foods);
- }
- /**
- * 归档报告
- */
- @Operation(summary = "归档健康报告")
- @PostMapping("/report/archive")
- public Result<String> archiveReport(
- @RequestBody Map<String, Object> params) {
- Long reportId = ParamUtils.getLong(params.get("reportId"));
- if (reportId == null) {
- return Result.error("reportId不能为空");
- }
- healthReportService.archiveReport(reportId);
- return Result.success("报告已归档");
- }
- /**
- * 批量归档报告(软删除)— 管理端选中删除
- */
- @Operation(summary = "批量归档健康报告(软删除)")
- @PostMapping("/report/archive-batch")
- public Result<String> archiveReportsBatch(
- @RequestBody Map<String, Object> params,
- @RequestAttribute(value = "role", required = false) String role) {
- @SuppressWarnings("unchecked")
- List<Long> reportIds = (List<Long>) params.get("reportIds");
- if (reportIds == null || reportIds.isEmpty()) {
- return Result.error("reportIds不能为空");
- }
- int archived = healthReportService.archiveReportsBatch(reportIds);
- return Result.success("已归档 " + archived + " 份报告");
- }
- @Operation(summary = "获取家庭成员食材推荐(含完整营养数据)")
- @PostMapping("/foods/by-family")
- public Result<Map<String, Object>> getFoodsByFamily(@RequestAttribute(value = "familyId", required = false) Long familyId) {
- if (familyId == null) {
- return Result.noFamily("请先创建或加入家庭");
- }
- Map<Long, List<FoodRecommendIndex>> byMember = foodRecommendService.getByFamily(familyId);
- Set<Long> foodIds = new HashSet<>();
- Map<Long, String> memberNames = new LinkedHashMap<>();
- for (Map.Entry<Long, List<FoodRecommendIndex>> entry : byMember.entrySet()) {
- for (FoodRecommendIndex idx : entry.getValue()) {
- foodIds.add(idx.getFoodId());
- }
- }
- List<FamilyMember> members = familyMemberMapper.selectList(
- new LambdaQueryWrapper<FamilyMember>().eq(FamilyMember::getFamilyId, familyId));
- for (FamilyMember m : members) {
- if (m.getUserId() != null) {
- memberNames.put(m.getUserId(), m.getNickname() != null ? m.getNickname() : "");
- }
- }
- List<Map<String, Object>> totalList = new ArrayList<>();
- for (Long foodId : foodIds) {
- Food food = foodService.getById(foodId);
- if (food != null) {
- Map<String, Object> item = new LinkedHashMap<>();
- item.put("id", food.getId());
- item.put("name", food.getName());
- item.put("category", food.getCategory());
- item.put("calories", food.getCalories());
- item.put("protein", food.getProtein());
- item.put("carbs", food.getCarbs());
- item.put("fat", food.getFat());
- item.put("fiber", food.getFiber());
- item.put("energyKj", food.getEnergyKj());
- item.put("starch", food.getStarch());
- item.put("cholesterol", food.getCholesterol());
- for (Map.Entry<Long, List<FoodRecommendIndex>> entry : byMember.entrySet()) {
- for (FoodRecommendIndex idx : entry.getValue()) {
- if (foodId.equals(idx.getFoodId())) {
- item.put("recommendIndex", idx.getIndexScore());
- break;
- }
- }
- if (item.containsKey("recommendIndex")) break;
- }
- if (!item.containsKey("recommendIndex")) {
- item.put("recommendIndex", null);
- }
- totalList.add(item);
- }
- }
- Map<String, Object> result = new LinkedHashMap<>();
- result.put("total", totalList);
- result.put("byMember", byMember);
- result.put("memberNames", memberNames);
- // T28/迁移465:家庭总览分段聚合(family_food_overview,有成员<0取最低值、全员>=0取平均值),
- // 无记录或旧规则历史行(overview_score 为 NULL)时后端先按新口径 backfill 再返回
- result.put("overview", familyFoodOverviewService.getOverviewMaps(familyId));
- return Result.success(result);
- }
- /**
- * 自动创建家庭成员(从PDF身份信息)
- */
- @Operation(summary = "自动创建家庭成员")
- @PostMapping("/report/auto-create-member")
- public Result<Map<String, Object>> autoCreateMember(
- @RequestBody Map<String, Object> params,
- @RequestAttribute("userId") Long userId,
- @RequestAttribute(value = "familyId", required = false) Long familyId) {
- if (familyId == null) {
- return Result.noFamily("请先创建或加入家庭");
- }
- String name = (String) params.get("name");
- String gender = (String) params.get("gender");
- Object ageObj = params.get("age");
- Integer age = ageObj != null ? Integer.parseInt(ageObj.toString()) : null;
- Long draftId = ParamUtils.getLong(params.get("draftId"));
- if (name == null || name.trim().isEmpty()) {
- return Result.error("姓名不能为空");
- }
- try {
- String fileUrl = null;
- String originalFilename = null;
- String payloadJson = null;
- if (draftId != null) {
- HealthReportDraft draft = healthReportDraftService.getActiveDraft(draftId);
- if (draft != null) {
- fileUrl = draft.getFileUrl();
- originalFilename = draft.getOriginalFilename();
- payloadJson = draft.getPayloadJson();
- }
- }
- Long memberId = healthReportService.autoCreateMemberFromReport(
- name, gender, age, familyId, "gut_flora", fileUrl, originalFilename, payloadJson);
- Map<String, Object> result = new LinkedHashMap<>();
- result.put("memberId", memberId);
- result.put("isNew", true);
- result.put("name", name.trim());
- return Result.success(result);
- } catch (IllegalArgumentException e) {
- return Result.error(e.getMessage());
- } catch (Exception e) {
- log.error("自动创建成员失败", e);
- return Result.error("自动创建成员失败: " + e.getMessage());
- }
- }
- /**
- * 管理端:获取待审核报告草稿列表
- */
- @Operation(summary = "管理端:获取待审核报告草稿列表")
- @PostMapping("/report/audit/pending")
- public Result<List<HealthReportDraft>> listPendingAudits(
- @RequestBody Map<String, Object> params) {
- int page = params.get("page") != null ? Integer.parseInt(params.get("page").toString()) : 1;
- int size = params.get("size") != null ? Integer.parseInt(params.get("size").toString()) : 20;
- List<HealthReportDraft> drafts = healthReportService.listPendingAudits(page, size);
- return Result.success(drafts);
- }
- /**
- * 管理端:审核确认报告
- */
- @Operation(summary = "管理端:审核确认报告")
- @PostMapping("/report/audit/confirm")
- public Result<Map<String, Object>> auditConfirm(
- @RequestBody Map<String, Object> params,
- @RequestAttribute("userId") Long auditorId,
- @RequestAttribute("role") String role,
- @RequestAttribute("roles") List<String> roles) {
- Long draftId = ParamUtils.getLong(params.get("draftId"));
- Long subjectId = ParamUtils.getLong(params.get("subjectId"));
- if (draftId == null) {
- return Result.error("draftId不能为空");
- }
- try {
- // B2-3:admin 判定——平台角色可确认任意草稿;非平台角色仅能确认自己创建的草稿
- boolean isAdmin = "admin".equals(role) || AdminRoles.hasAnyPlatformRole(roles);
- Map<String, Object> result = healthReportService.auditConfirm(draftId, subjectId, auditorId, isAdmin);
- Long confirmedSubjectId = ParamUtils.getLong(result.get("subjectId"));
- if (confirmedSubjectId != null) {
- try {
- foodRecommendService.recalculateForUser(confirmedSubjectId);
- } catch (Exception e) {
- log.warn("审核确认后刷新食材推荐失败: {}", e.getMessage());
- }
- }
- return Result.success(result);
- } catch (Exception e) {
- log.error("审核确认失败", e);
- return Result.error("审核确认失败: " + e.getMessage());
- }
- }
- /**
- * 管理端:审核丢弃报告
- */
- @Operation(summary = "管理端:审核丢弃报告")
- @PostMapping("/report/audit/discard")
- public Result<String> auditDiscard(
- @RequestBody Map<String, Object> params) {
- Long draftId = ParamUtils.getLong(params.get("draftId"));
- if (draftId == null) {
- return Result.error("draftId不能为空");
- }
- try {
- healthReportService.auditDiscard(draftId);
- return Result.success("报告已丢弃");
- } catch (Exception e) {
- log.error("审核丢弃失败", e);
- return Result.error("审核丢弃失败: " + e.getMessage());
- }
- }
- private ParsedReportPayload.Payload convertToPayload(ParsedReportResult parsed) {
- ParsedReportPayload.Payload payload = new ParsedReportPayload.Payload();
- ParsedReportPayload.Summary summary = new ParsedReportPayload.Summary();
- summary.setOverallScore(parsed.getOverallScore());
- summary.setGutHealthScore(parsed.getGutHealthScore());
- summary.setChronicDiseaseScore(parsed.getChronicDiseaseScore());
- summary.setNutritionScore(parsed.getNutritionScore());
- summary.setBalanceScore(parsed.getBalanceScore());
- summary.setDiversityScore(parsed.getDiversityScore());
- summary.setBeneficialScore(parsed.getBeneficialScore());
- summary.setHarmfulScore(parsed.getHarmfulScore());
- summary.setCoreGenusScore(parsed.getCoreGenusScore());
- summary.setGutAge(parsed.getGutAge());
- summary.setGutType(parsed.getGutType());
- summary.setReportNumber(parsed.getReportNumber());
- summary.setReportDate(parsed.getReportDate());
- summary.setPersonName(parsed.getPersonName());
- summary.setGender(parsed.getGender());
- summary.setAge(parsed.getAge());
- summary.setBirthday(parsed.getBirthday());
- payload.setSummary(summary);
- if (parsed.getIndicators() != null) {
- List<ParsedReportPayload.Indicator> indicators = new ArrayList<>();
- for (ParsedIndicator pi : parsed.getIndicators()) {
- ParsedReportPayload.Indicator ind = new ParsedReportPayload.Indicator();
- ind.setCategory(pi.getCategory());
- ind.setIndicatorName(pi.getIndicatorName());
- ind.setIndicatorValue(pi.getIndicatorValue());
- ind.setRefRange(pi.getRefRange());
- ind.setStatus(pi.getStatus());
- ind.setSymptoms(pi.getSymptoms());
- indicators.add(ind);
- }
- payload.setIndicators(indicators);
- }
- if (parsed.getGutFlora() != null) {
- List<ParsedReportPayload.Flora> gutFlora = new ArrayList<>();
- for (ParsedGutFlora pgf : parsed.getGutFlora()) {
- gutFlora.add(convertFlora(pgf));
- }
- payload.setGutFlora(gutFlora);
- }
- if (parsed.getProbioticSpecies() != null) {
- List<ParsedReportPayload.Flora> probiotics = new ArrayList<>();
- for (ParsedGutFlora pgf : parsed.getProbioticSpecies()) {
- probiotics.add(convertFlora(pgf));
- }
- payload.setProbioticSpecies(probiotics);
- }
- if (parsed.getFoodSuitability() != null) {
- List<ParsedReportPayload.FoodItem> foods = new ArrayList<>();
- for (ParsedFoodSuitability pfs : parsed.getFoodSuitability()) {
- ParsedReportPayload.FoodItem fi = new ParsedReportPayload.FoodItem();
- fi.setName(pfs.getFoodName());
- fi.setCategory(pfs.getCategory());
- fi.setScore(pfs.getScore());
- fi.setEnergyKj(pfs.getEnergyKj());
- fi.setProtein(pfs.getProtein());
- fi.setFat(pfs.getFat());
- fi.setCarbs(pfs.getCarbs());
- fi.setStarch(pfs.getStarch());
- fi.setFiber(pfs.getFiber());
- fi.setCholesterol(pfs.getCholesterol());
- foods.add(fi);
- }
- payload.setFoods(foods);
- }
- if (parsed.getDiseaseRisks() != null) {
- List<ParsedReportPayload.DiseaseRisk> risks = new ArrayList<>();
- for (ParsedDiseaseRisk pdr : parsed.getDiseaseRisks()) {
- ParsedReportPayload.DiseaseRisk dr = new ParsedReportPayload.DiseaseRisk();
- dr.setDiseaseName(pdr.getDiseaseName());
- dr.setRiskValue(pdr.getRiskValue());
- dr.setRiskLevel(pdr.getRiskLevel());
- risks.add(dr);
- }
- payload.setDiseaseRisks(risks);
- }
- return payload;
- }
- private ParsedReportPayload.Flora convertFlora(ParsedGutFlora pgf) {
- ParsedReportPayload.Flora f = new ParsedReportPayload.Flora();
- f.setBacteriaName(pgf.getBacteriaName());
- f.setBacteriaValue(pgf.getBacteriaValue());
- f.setNormalRange(pgf.getNormalRange());
- f.setPopulationLevel(pgf.getPopulationLevel());
- f.setDetectionRate(pgf.getDetectionRate());
- f.setDescription(pgf.getDescription());
- f.setCategory(pgf.getCategory());
- f.setLevel(pgf.getLevel());
- return f;
- }
- private ParsedReportPayload.Payload buildPayloadFromLgData(Map<String, Object> lgData) {
- ParsedReportPayload.Payload payload = new ParsedReportPayload.Payload();
- Map<String, Object> overview = (Map<String, Object>) lgData.get("overview");
- if (overview != null) {
- ParsedReportPayload.Summary summary = new ParsedReportPayload.Summary();
- summary.setPersonName((String) overview.get("person_name"));
- summary.setAge(toInteger(overview.get("age")));
- summary.setGender((String) overview.get("gender"));
- summary.setOverallScore(toInteger(overview.get("overallScore")));
- summary.setGutHealthScore(toInteger(overview.get("gutHealthScore")));
- summary.setChronicDiseaseScore(toInteger(overview.get("chronicDiseaseScore")));
- summary.setNutritionScore(toInteger(overview.get("nutritionScore")));
- summary.setBalanceScore(toInteger(overview.get("balanceScore")));
- summary.setDiversityScore(toInteger(overview.get("diversityScore")));
- summary.setBeneficialScore(toInteger(overview.get("beneficialScore")));
- summary.setHarmfulScore(toInteger(overview.get("harmfulScore")));
- summary.setCoreGenusScore(toInteger(overview.get("coreGenusScore")));
- summary.setGutAge(objectToString(overview.get("gutAge")));
- summary.setGutType(objectToString(overview.get("gutType")));
- summary.setShannonIndex(objectToString(overview.get("shannonIndex")));
- summary.setReportNumber(objectToString(overview.get("report_number")));
- summary.setBirthday(objectToString(overview.get("birthday")));
- payload.setSummary(summary);
- }
- List<Map<String, Object>> diseaseRisks = (List<Map<String, Object>>) lgData.get("disease_risks");
- if (diseaseRisks != null) {
- List<ParsedReportPayload.DiseaseRisk> risks = new ArrayList<>();
- for (Map<String, Object> dr : diseaseRisks) {
- ParsedReportPayload.DiseaseRisk risk = new ParsedReportPayload.DiseaseRisk();
- risk.setDiseaseName((String) dr.get("name"));
- risk.setRiskValue(objectToString(dr.get("value")));
- risk.setRiskLevel((String) dr.get("status"));
- risks.add(risk);
- }
- payload.setDiseaseRisks(risks);
- }
- List<Map<String, Object>> indicators = (List<Map<String, Object>>) lgData.get("indicators");
- if (indicators != null) {
- List<ParsedReportPayload.Indicator> inds = new ArrayList<>();
- for (Map<String, Object> ind : indicators) {
- ParsedReportPayload.Indicator indicator = new ParsedReportPayload.Indicator();
- indicator.setCategory((String) ind.get("category"));
- indicator.setIndicatorName((String) ind.get("indicatorName"));
- indicator.setIndicatorValue(objectToString(ind.get("indicatorValue")));
- indicator.setUnit((String) ind.get("unit"));
- indicator.setRefRange((String) ind.get("refRange"));
- indicator.setStatus((String) ind.get("status"));
- indicator.setSymptoms((String) ind.get("symptoms"));
- inds.add(indicator);
- }
- payload.setIndicators(inds);
- }
- // 菌群/饮食推荐分组(LangGraph 输出 snake_case 键,缺省时安全跳过)
- payload.setGutFlora(convertLgFloraList(lgData.get("gut_flora")));
- payload.setProbioticSpecies(convertLgFloraList(lgData.get("probiotic_species")));
- payload.setTaxonomyClass(convertLgFloraList(lgData.get("taxonomy_class")));
- payload.setTaxonomyOrder(convertLgFloraList(lgData.get("taxonomy_order")));
- payload.setTaxonomyFamily(convertLgFloraList(lgData.get("taxonomy_family")));
- payload.setTaxonomyGenus(convertLgFloraList(lgData.get("taxonomy_genus")));
- payload.setTaxonomySpecies(convertLgFloraList(lgData.get("taxonomy_species")));
- payload.setPathogenGenus(convertLgFloraList(lgData.get("pathogen_genus")));
- payload.setPathogenDetection(convertLgFloraList(lgData.get("pathogen_detection")));
- payload.setFoods(convertLgFoodList(lgData.get("foods")));
- return payload;
- }
- /**
- * 将 LangGraph 输出的菌群列表(snake_case 元素)转换为 ParsedReportPayload.Flora 列表。
- * 键缺失或类型不符时安全返回空列表。
- */
- private List<ParsedReportPayload.Flora> convertLgFloraList(Object raw) {
- List<ParsedReportPayload.Flora> floraList = new ArrayList<>();
- if (!(raw instanceof List)) {
- return floraList;
- }
- for (Object item : (List<?>) raw) {
- if (!(item instanceof Map)) {
- continue;
- }
- Map<String, Object> m = (Map<String, Object>) item;
- ParsedReportPayload.Flora f = new ParsedReportPayload.Flora();
- f.setBacteriaName(objectToString(m.get("name")));
- f.setBacteriaValue(objectToString(m.get("value")));
- f.setNormalRange(objectToString(m.get("normal_range")));
- f.setPopulationLevel(objectToString(m.get("population_level")));
- f.setDetectionRate(objectToString(m.get("detection_rate")));
- f.setDescription(objectToString(m.get("description")));
- f.setCategory(objectToString(m.get("category")));
- f.setLevel(objectToString(m.get("level")));
- if (f.getBacteriaName() == null && f.getDescription() == null) {
- continue;
- }
- floraList.add(f);
- }
- return floraList;
- }
- /**
- * 将 LangGraph 输出的饮食推荐列表(snake_case 元素)转换为 ParsedReportPayload.FoodItem 列表。
- */
- private List<ParsedReportPayload.FoodItem> convertLgFoodList(Object raw) {
- List<ParsedReportPayload.FoodItem> foodList = new ArrayList<>();
- if (!(raw instanceof List)) {
- return foodList;
- }
- for (Object item : (List<?>) raw) {
- if (!(item instanceof Map)) {
- continue;
- }
- Map<String, Object> m = (Map<String, Object>) item;
- ParsedReportPayload.FoodItem fi = new ParsedReportPayload.FoodItem();
- fi.setName(objectToString(m.get("name")));
- fi.setCategory(objectToString(m.get("category")));
- fi.setScore(toInteger(m.get("score")));
- fi.setEnergyKj(toDecimal(m.get("energy_kj")));
- fi.setProtein(toDecimal(m.get("protein")));
- fi.setFat(toDecimal(m.get("fat")));
- fi.setCarbs(toDecimal(m.get("carbs")));
- fi.setStarch(toDecimal(m.get("starch")));
- fi.setFiber(toDecimal(m.get("fiber")));
- fi.setCholesterol(toDecimal(m.get("cholesterol")));
- if (fi.getName() == null) {
- continue;
- }
- foodList.add(fi);
- }
- return foodList;
- }
- private static BigDecimal toDecimal(Object value) {
- if (value == null) {
- return null;
- }
- if (value instanceof BigDecimal) {
- return (BigDecimal) value;
- }
- if (value instanceof Number) {
- return BigDecimal.valueOf(((Number) value).doubleValue());
- }
- try {
- return new BigDecimal(value.toString());
- } catch (Exception e) {
- return null;
- }
- }
- private static Integer toInteger(Object value) {
- if (value == null) return null;
- if (value instanceof Integer) return (Integer) value;
- if (value instanceof Number) return ((Number) value).intValue();
- try {
- return Integer.valueOf(value.toString());
- } catch (Exception e) {
- return null;
- }
- }
- private static String objectToString(Object value) {
- if (value == null) return null;
- return value.toString();
- }
- private HealthReport buildReportFromPayload(HealthReportDraft draft, ParsedReportPayload.Payload payload, Long subjectId) {
- HealthReport report = new HealthReport();
- report.setUserId(draft.getUserId());
- report.setFamilyId(draft.getFamilyId());
- // A方案:subject_id 统一为 family_members.id 口径(users.id 归一化到成员卡)
- report.setSubjectId(healthReportService.resolveSubjectToMemberId(subjectId, draft.getFamilyId()));
- report.setReportType(draft.getReportType());
- report.setFileUrl(draft.getFileUrl());
- report.setReportFormat(payload.getReportFormat());
- ParsedReportPayload.Summary s = payload.getSummary();
- if (s != null) {
- report.setOverallScore(s.getOverallScore());
- report.setGutHealthScore(s.getGutHealthScore());
- report.setChronicDiseaseScore(s.getChronicDiseaseScore());
- report.setNutritionScore(s.getNutritionScore());
- report.setBalanceScore(s.getBalanceScore());
- report.setDiversityScore(s.getDiversityScore());
- report.setBeneficialScore(s.getBeneficialScore());
- report.setHarmfulScore(s.getHarmfulScore());
- report.setCoreGenusScore(s.getCoreGenusScore());
- report.setGutAge(s.getGutAge());
- report.setGutType(s.getGutType());
- report.setShannonIndex(s.getShannonIndex());
- report.setReportNumber(s.getReportNumber());
- report.setPersonName(s.getPersonName());
- if (s.getReportDate() != null && !s.getReportDate().isEmpty()) {
- try {
- java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
- report.setReportDate(sdf.parse(s.getReportDate()));
- } catch (Exception e) {
- report.setReportDate(new Date());
- }
- } else {
- report.setReportDate(new Date());
- }
- } else {
- report.setReportDate(new Date());
- }
- report.setRemark("募极生物肠道菌群检测报告");
- return report;
- }
- private List<HealthIndicator> buildIndicatorsFromPayload(ParsedReportPayload.Payload payload) {
- List<ParsedReportPayload.Indicator> list = payload.getIndicators();
- if (list == null || list.isEmpty()) return new ArrayList<>();
- List<HealthIndicator> indicators = new ArrayList<>();
- for (int i = 0; i < list.size(); i++) {
- ParsedReportPayload.Indicator pi = list.get(i);
- HealthIndicator ind = new HealthIndicator();
- ind.setCategory(pi.getCategory());
- ind.setIndicatorName(pi.getIndicatorName());
- ind.setIndicatorValue(pi.getIndicatorValue());
- ind.setUnit(pi.getUnit());
- ind.setRefRange(pi.getRefRange());
- ind.setStatus(pi.getStatus());
- ind.setSymptoms(pi.getSymptoms());
- ind.setSortOrder(i);
- if (pi.getCollectionDate() != null && !pi.getCollectionDate().isEmpty()) {
- try {
- java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd");
- ind.setCollectionDate(sdf.parse(pi.getCollectionDate()));
- } catch (Exception e) {
- // ignore parse error
- }
- }
- indicators.add(ind);
- }
- return indicators;
- }
- private List<HealthGutFlora> buildGutFloraFromPayload(ParsedReportPayload.Payload payload) {
- List<HealthGutFlora> result = new ArrayList<>();
- addFloraList(result, payload.getGutFlora());
- addFloraList(result, payload.getProbioticSpecies());
- addFloraList(result, payload.getTaxonomyClass());
- addFloraList(result, payload.getTaxonomyOrder());
- addFloraList(result, payload.getTaxonomyFamily());
- addFloraList(result, payload.getTaxonomyGenus());
- addFloraList(result, payload.getTaxonomySpecies());
- addFloraList(result, payload.getPathogenGenus());
- addFloraList(result, payload.getPathogenDetection());
- return result;
- }
- private void addFloraList(List<HealthGutFlora> target, List<ParsedReportPayload.Flora> source) {
- if (source != null) {
- for (ParsedReportPayload.Flora pf : source) {
- target.add(convertToGutFlora(pf));
- }
- }
- }
- private HealthGutFlora convertToGutFlora(ParsedReportPayload.Flora pf) {
- HealthGutFlora gf = new HealthGutFlora();
- gf.setBacteriaName(pf.getBacteriaName());
- gf.setBacteriaValue(pf.getBacteriaValue());
- gf.setNormalRange(pf.getNormalRange());
- gf.setPopulationLevel(pf.getPopulationLevel());
- gf.setDetectionRate(pf.getDetectionRate());
- gf.setDescription(pf.getDescription());
- // 分类层级表归一化:募极/北京的"菌纲构成/菌目构成..."→ taxonomy + 英文LEVEL,
- // 否则前端 taxonomy 标签页按 category='taxonomy' + level='CLASS' 过滤匹配不到
- gf.setCategory(normalizeFloraCategory(pf.getCategory()));
- gf.setLevel(normalizeFloraLevel(pf.getCategory(), pf.getLevel()));
- return gf;
- }
- /**
- * 菌群分类归一化:以"构成"结尾的层级分类(菌门构成/菌纲构成/菌目构成/菌科构成/菌属构成/菌种构成)
- * 统一映射为 taxonomy,与前端标签页过滤条件对齐。
- */
- private String normalizeFloraCategory(String category) {
- if (category == null) return null;
- if (category.endsWith("构成")) {
- return HealthGutFlora.CATEGORY_TAXONOMY; // "taxonomy"
- }
- return category;
- }
- /**
- * 菌群层级归一化:中文层级(门/纲/目/科/属/种)→ 英文 LEVEL 常量,
- * 与前端 levelMap 对齐。非层级数据(如 category=核心菌属 且 level=GENUS)原样保留。
- */
- private String normalizeFloraLevel(String category, String level) {
- if (level == null) return null;
- String normalized = level;
- if ("门".equals(level)) normalized = HealthGutFlora.LEVEL_PHYLUM;
- else if ("纲".equals(level)) normalized = HealthGutFlora.LEVEL_CLASS;
- else if ("目".equals(level)) normalized = HealthGutFlora.LEVEL_ORDER;
- else if ("科".equals(level)) normalized = HealthGutFlora.LEVEL_FAMILY;
- else if ("属".equals(level)) normalized = HealthGutFlora.LEVEL_GENUS;
- else if ("种".equals(level)) normalized = HealthGutFlora.LEVEL_SPECIES;
- return normalized;
- }
- private List<HealthDiseaseRisk> buildDiseaseRisksFromPayload(ParsedReportPayload.Payload payload) {
- List<ParsedReportPayload.DiseaseRisk> list = payload.getDiseaseRisks();
- if (list == null || list.isEmpty()) return new ArrayList<>();
- List<HealthDiseaseRisk> risks = new ArrayList<>();
- for (ParsedReportPayload.DiseaseRisk pr : list) {
- HealthDiseaseRisk dr = new HealthDiseaseRisk();
- dr.setDiseaseName(pr.getDiseaseName());
- dr.setRiskValue(pr.getRiskValue());
- dr.setRiskLevel(pr.getRiskLevel());
- risks.add(dr);
- }
- return risks;
- }
- private List<Food> buildFoodsFromPayload(ParsedReportPayload.Payload payload) {
- List<ParsedReportPayload.FoodItem> list = payload.getFoods();
- if (list == null || list.isEmpty()) return new ArrayList<>();
- List<Food> foods = new ArrayList<>();
- for (ParsedReportPayload.FoodItem pf : list) {
- if (pf == null || pf.getName() == null || pf.getName().trim().isEmpty()) {
- log.warn("跳过无效食材条目(元素为空或缺少名称)");
- continue;
- }
- Food food = new Food();
- food.setName(pf.getName());
- food.setCategory(pf.getCategory());
- food.setScore(pf.getScore());
- food.setEnergyKj(pf.getEnergyKj());
- food.setProtein(pf.getProtein());
- food.setFat(pf.getFat());
- food.setCarbs(pf.getCarbs());
- food.setStarch(pf.getStarch());
- food.setFiber(pf.getFiber());
- food.setCholesterol(pf.getCholesterol());
- food.setStatus("recommended");
- foods.add(food);
- }
- return foods;
- }
- /**
- * 提交报告反馈(持久化 + AI 解答)
- */
- @Operation(summary = "提交报告反馈(持久化 + AI 解答)")
- @PostMapping("/feedback/submit")
- public Result<?> submitFeedback(@RequestBody Map<String, Object> params,
- @RequestAttribute("userId") Long userId,
- @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
- Long reportId = ParamUtils.getLong(params.get("reportId"));
- Long draftId = ParamUtils.getLong(params.get("draftId"));
- Long memberId = ParamUtils.getLong(params.get("memberId"), currentMemberId);
- String type = params.get("type") != null ? params.get("type").toString() : null;
- String content = params.get("content") != null ? params.get("content").toString() : null;
- return reportFeedbackService.submit(userId, memberId, reportId, draftId, type, content);
- }
- @Operation(summary = "我的报告反馈列表(含 AI 解答)")
- @PostMapping("/feedback/list")
- public Result<?> listFeedback(@RequestAttribute("userId") Long userId,
- @RequestBody(required = false) Map<String, Object> params) {
- Long reportId = (params != null) ? ParamUtils.getLong(params.get("reportId")) : null;
- return reportFeedbackService.listMine(userId, reportId);
- }
- /**
- * 将解析结果保存到本地 JSON 文件(用于调试)
- */
- private void saveResultToJsonFile(Map<String, Object> result) throws IOException {
- // 创建输出目录
- String outputDir = "uploads" + File.separator + "json-results";
- File dir = new File(outputDir);
- if (!dir.exists()) {
- dir.mkdirs();
- }
-
- // 生成文件名:timestamp_result.json
- String timestamp = java.time.LocalDateTime.now().format(
- java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss")
- );
- String filename = timestamp + "_result.json";
- String filePath = outputDir + File.separator + filename;
-
- // 写入 JSON 文件
- try (java.io.PrintWriter writer = new java.io.PrintWriter(filePath, "UTF-8")) {
- writer.println(objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(result));
- }
-
- log.info("✅ 解析结果已保存到 JSON 文件:{}", filePath);
-
- // 同时打印部分关键信息到日志(限制长度避免过大)
- String summary = String.format(
- "[JSON 保存] draftId=%s, name=%s, matched=%s, confidence=%.2f",
- result.get("draftId"),
- result.get("extractedName"),
- result.get("matchedMemberId") != null ? "找到匹配" : "未匹配",
- result.get("confidence")
- );
- log.info(summary);
- }
- /**
- * 检查是否为授权代上传角色
- */
- private boolean isProxyUploader(String role, List<String> roles, User user) {
- // 超级管理员(admin):平台最高权限,可代传任何报告
- if ("admin".equals(role) || (roles != null && roles.contains("admin"))) return true;
- if ("teacher".equals(role)) return true;
- if (roles != null && roles.contains("teacher")) return true;
- if (user != null && "approved".equals(user.getNutritionistStatus())) return true;
- if (user != null && "planner".equals(user.getVendorType()) && "approved".equals(user.getVendorStatus())) return true;
- return false;
- }
- /**
- * B2-2 / B2-6:代传 familyId 绑定校验(发生在建草稿/写文件之前,越权不产生副作用)。
- *
- * <p>口径与 FamilyAccessInterceptor.getEffectiveFamilyIds 一致:平台角色(admin/operator/finance)
- * 直接放行;否则 familyId 必位于调用者有效家庭集内(own family / teacher_family_ids /
- * family_members 反查 / guide_family 绑定)。</p>
- *
- * @return true=允许代传该家庭;false=无权(controller 层返回 code=500 "无权为该家庭代传报告")
- */
- boolean canProxyForFamily(Long userId, String role, List<String> roles, Long familyId) {
- if ("admin".equals(role) || AdminRoles.hasAnyPlatformRole(roles)) {
- return true;
- }
- Set<Long> effective = userService.getEffectiveFamilyIds(userId);
- return effective != null && effective.contains(familyId);
- }
- /**
- * 规划师/营养师代用户上传报告(预览模式,仅解析不入库)
- *
- * <p>T29-B1-1:重构为与「两阶段入库」一致的模式——先建草稿拿到 draftId,再解析并回写草稿载荷,
- * 前端「确认入库」才能拿到 draftId(原先透传 LangGraph 原始返回,恒无 draftId → 前端卡死)。</p>
- * <p>链路:storeFile → createDraft → updateRemark(备注) → getFilePath → LangGraph 解析
- * (失败回退本地 Java 解析)→ 返回 draftId/payload/成员匹配/提取字段。</p>
- *
- * <p><b>B3-2 草稿过期降级:</b>入参支持 <code>file</code>(新上传,multipart)或
- * <code>fileUrl</code>(草稿过期后基于原文件重新解析,无需重新上传 PDF)。二者至少给一个,
- * 复用本接口同一条「建草稿 → 解析」链路,不另建新接口。</p>
- *
- * <p><b>B3-3 本地兜底提示:</b>LangGraph 不可用而走本地 Java 解析时,返回体带
- * <code>parseFallback=true</code> / <code>parseMethod="local"</code>,供前端提示
- * 「解析服务暂不可用,已用本地解析」。</p>
- *
- * <p><b>T29-B2-6 权限编排(三层校验,各层失败返回码):</b>
- * <ol>
- * <li>① 角色校验 {@link #isProxyUploader}:非 admin/teacher/approved 营养师/approved 规划师
- * → <code>Result.error(code=500, "无权限代上传报告,仅超级管理员/规划师/营养师可操作")</code>;</li>
- * <li>② familyId 绑定校验 {@link #canProxyForFamily}(B2-2,本方法内):
- * 非平台角色且 familyId 不在有效家庭集内
- * → <code>Result.error(code=500, "无权为该家庭代传报告")</code>(不建草稿、不写文件);</li>
- * <li>③ 家庭访问拦截器兜底(FamilyAccessInterceptor,B2-4 enforcement):
- * 越权 → <code>HTTP 403</code>,body <code>{"code":403,"message":"无权访问该家庭数据"}</code>。
- * (拦截器在 controller 之前执行,因此②③不会同时触发;②是对拦截器未覆盖路径的纵深防御。)</li>
- * </ol></p>
- */
- @Operation(summary = "代上传报告(预览)")
- @PostMapping("/report/proxy-parse")
- public Result<Map<String, Object>> proxyParsePreview(
- @RequestParam(value = "file", required = false) MultipartFile file,
- @RequestParam(value = "fileUrl", required = false) String fileUrl,
- @RequestParam(value = "familyId", required = false) Long familyId,
- @RequestParam(value = "subjectId", required = false) Long subjectId,
- @RequestParam(value = "reportType", defaultValue = "auto") String reportType,
- @RequestParam(value = "note", required = false) String note,
- @RequestAttribute("userId") Long userId,
- @RequestAttribute("role") String role,
- @RequestAttribute("roles") List<String> roles,
- HttpServletRequest request) {
- // B3-2:两种入参二选一——file(新上传,multipart)或 fileUrl(草稿过期后基于原文件重新解析)
- boolean hasFile = file != null && !file.isEmpty();
- boolean hasFileUrl = fileUrl != null && !fileUrl.trim().isEmpty();
- if (!hasFile && !hasFileUrl) {
- return Result.error("请选择PDF文件或提供fileUrl");
- }
- User user = userMapper.selectById(userId);
- if (!isProxyUploader(role, roles, user)) {
- return Result.error("无权限代上传报告,仅超级管理员/规划师/营养师可操作");
- }
- if (familyId == null) {
- return Result.error("familyId不能为空");
- }
- // B2-2 / B2-6:familyId 绑定校验(发生在建草稿/写文件之前,越权不产生副作用)。
- // 拦截器(B2-4)未覆盖或未生效时,此处作纵深防御。
- if (!canProxyForFamily(userId, role, roles, familyId)) {
- return Result.error("无权为该家庭代传报告");
- }
- // 新上传路径才校验 PDF 类型(fileUrl 重新解析路径的文件已在首次上传时校验过)
- if (hasFile) {
- String contentType = file.getContentType();
- String originalFilename = file.getOriginalFilename();
- String lcName = originalFilename != null ? originalFilename.toLowerCase() : "";
- if (!lcName.endsWith(".pdf")
- && (contentType == null || !contentType.equalsIgnoreCase("application/pdf"))) {
- return Result.error("仅支持PDF文件");
- }
- }
- try {
- // ① 确定文件访问地址:新上传 → storeFile 存本地/OSS;fileUrl → 复用既有文件
- boolean reparse = !hasFile && hasFileUrl;
- String resolvedFileUrl = hasFile ? storageService.storeFile(file, "health-reports") : fileUrl.trim();
- String originalFilename = hasFile ? file.getOriginalFilename() : null;
- // ② 先建草稿:保证预览必然有 draftId 供 /report/proxy-confirm 入库
- // reportType 传 auto 时落 gut_flora(与非代传链路一致)
- // health_report_drafts.payload_json 为 NOT NULL 列,先写空载荷 JSON
- // (与图片上传链路一致),解析成功后由 updatePayload 覆盖为真实载荷
- String draftReportType = (reportType == null || reportType.isEmpty() || "auto".equals(reportType))
- ? "gut_flora" : reportType;
- String emptyPayloadJson = objectMapper.writeValueAsString(new ParsedReportPayload.Payload());
- HealthReportDraft draft = healthReportDraftService.createDraft(
- userId, familyId, draftReportType, resolvedFileUrl, originalFilename, emptyPayloadJson);
- // ③ 备注写入草稿 remark(B3-6:updateRemark 实际写 remark 列),确认入库时同步到 proxy_upload_note
- if (note != null && !note.isEmpty()) {
- healthReportDraftService.updateRemark(draft.getId(), note);
- }
- // ④ LangGraph 需要本地路径:经 getFilePath 下载/定位到共享卷
- String absolutePath = storageService.getFilePath(resolvedFileUrl);
- // ⑤ 解析(LangGraph 优先,失败回退本地 Java 解析)
- Map<String, Object> data = parseProxyDraftFile(draft, absolutePath, userId, familyId, subjectId);
- if (data == null) {
- // 解析失败:草稿已无后续用途,标记丢弃,避免遗留空载荷 pending 草稿被误确认入库
- try {
- healthReportDraftService.markDiscarded(draft.getId());
- } catch (Exception ex) {
- log.warn("标记代传草稿为已丢弃失败 draftId={}: {}", draft.getId(), ex.getMessage());
- }
- return Result.error("报告解析失败,请确认是募极生物肠道菌群报告PDF");
- }
- // ⑥ 返回体补代传相关字段(前端既有字段契约)
- data.put("fileUrl", resolvedFileUrl);
- data.put("proxyUploaderId", userId);
- data.put("proxyUploadNote", note);
- data.put("reparse", reparse);
- return Result.success(data);
- } catch (Exception e) {
- log.error("代上传解析失败", e);
- return Result.error("解析失败: " + e.getMessage());
- }
- }
- /**
- * 代传草稿文件解析:LangGraph 优先,失败回退本地 Java 解析。
- * 两路都会把解析载荷写回 draft.payload_json,并返回完整预览结果
- * (draftId / payload / matchedMemberId / extracted 各字段 / needBind)。
- *
- * @return 解析结果体;文件不存在或两路均失败时返回 null
- */
- private Map<String, Object> parseProxyDraftFile(HealthReportDraft draft, String absolutePath,
- Long userId, Long familyId, Long subjectId) {
- File localFile = new File(absolutePath);
- if (!localFile.exists()) {
- log.warn("代传解析:文件不存在 draftId={}, path={}", draft.getId(), absolutePath);
- return null;
- }
- try {
- Map<String, Object> lgData = callLangGraphParse(absolutePath, userId, familyId, subjectId);
- if (lgData != null) {
- Map<String, Object> data = buildParseResultFromLg(lgData, draft, familyId).getData();
- putExtractedReportMeta(data, lgData);
- markParseMethod(data, false, "langgraph");
- return data;
- }
- log.warn("代传解析:LangGraph 无有效返回,回退本地 Java 解析 draftId={}", draft.getId());
- } catch (Exception e) {
- log.warn("代传解析:LangGraph 解析异常,回退本地 Java 解析 draftId={}: {}",
- draft.getId(), e.getMessage());
- }
- try {
- Map<String, Object> data = parseLocalFallback(absolutePath, draft, familyId, userId).getData();
- if (data != null) {
- // B3-3:本地兜底成功 → 前端提示「解析服务暂不可用,已用本地解析」
- markParseMethod(data, true, "local");
- }
- return data;
- } catch (Exception e) {
- log.error("代传解析:本地 Java 解析失败 draftId={}", draft.getId(), e);
- return null;
- }
- }
- /**
- * B3-3:标注本次解析走 LangGraph 还是本地 Java 兜底,供前端差异化提示。
- *
- * @param data 预览结果体(非 null)
- * @param fallback 是否走了本地 Java 兜底
- * @param method 解析方式标识(langgraph / local)
- */
- private void markParseMethod(Map<String, Object> data, boolean fallback, String method) {
- if (data == null) {
- return;
- }
- data.put("parseFallback", fallback);
- data.put("parseMethod", method);
- }
- /**
- * 补齐 LangGraph 预览结果的 extractedReportNumber / extractedReportDate。
- * buildParseResultFromLg 只回填 extractedName/Gender/Age,而前端预览页三行
- * (被检测人/报告编号/报告日期)还读这两个字段,缺省会一直显示 '-'。
- */
- private void putExtractedReportMeta(Map<String, Object> data, Map<String, Object> lgData) {
- if (data == null || lgData == null) {
- return;
- }
- Map<String, Object> overview = (Map<String, Object>) lgData.get("overview");
- if (overview != null) {
- data.put("extractedReportNumber", objectToString(overview.get("report_number")));
- data.put("extractedReportDate", objectToString(overview.get("report_date")));
- }
- }
- /**
- * 规划师/营养师代确认报告草稿(入库)
- */
- @Operation(summary = "代确认报告(入库)")
- @PostMapping("/report/proxy-confirm")
- public Result<Map<String, Object>> proxyConfirm(
- @RequestBody Map<String, Object> params,
- @RequestAttribute("userId") Long userId,
- @RequestAttribute("role") String role,
- @RequestAttribute("roles") List<String> roles) {
- User user = userMapper.selectById(userId);
- if (!isProxyUploader(role, roles, user)) {
- return Result.error("无权限");
- }
- Long draftId = ParamUtils.getLong(params.get("draftId"));
- Long subjectId = ParamUtils.getLong(params.get("subjectId"));
- if (draftId == null) {
- return Result.error("draftId不能为空");
- }
- try {
- // 先取草稿备注(代传 note):确认后写入 health_reports.proxy_upload_note
- HealthReportDraft draft = healthReportDraftService.getDraftById(draftId);
- String proxyUploadNote = draft != null ? draft.getRemark() : null;
- // B2-3:草稿归属校验下沉到 auditConfirm——仅创建者本人或平台角色可确认
- // (原代传链路"跳过草稿归属校验"的口径已废止:代传草稿只能由代传人本人或 admin 确认)
- boolean isAdmin = "admin".equals(role) || AdminRoles.hasAnyPlatformRole(roles);
- Map<String, Object> result = healthReportService.auditConfirm(draftId, subjectId, userId, isAdmin);
- Long reportId = (Long) result.get("reportId");
- // 维护"当前食材"推荐(有则更新,无则添加)
- Long confirmedSubjectId = ParamUtils.getLong(result.get("subjectId"));
- if (confirmedSubjectId != null) {
- try {
- foodRecommendService.recalculateForUser(confirmedSubjectId);
- } catch (Exception e) {
- log.warn("代确认后刷新食材推荐失败: {}", e.getMessage());
- }
- }
- // 设置代上传人 + 代上传备注
- if (reportId != null) {
- healthReportService.setProxyUploader(reportId, userId, proxyUploadNote);
- }
- // 触发 AI 解读(T29-B1-5:失败不再静默吞错,结果/失败原因随响应回传前端)
- Map<String, Object> aiResult = new HashMap<>();
- if (reportId != null && subjectId != null) {
- aiResult = triggerAiAnalysis(reportId, subjectId, userId);
- }
- if (Boolean.TRUE.equals(aiResult.get("success"))) {
- result.put("aiAnalysis", aiResult.get("analysis"));
- result.put("aiAnalysisStatus", "success");
- } else {
- result.put("aiAnalysisStatus", aiResult.get("reason"));
- Object aiMessage = aiResult.get("message") != null ? aiResult.get("message") : aiResult.get("toast");
- result.put("aiAnalysisMessage", aiMessage);
- }
- return Result.success(result);
- } catch (Exception e) {
- log.error("代确认失败", e);
- return Result.error("确认失败: " + e.getMessage());
- }
- }
- /**
- * 调用 LangGraph 解析报告
- */
- private Map<String, Object> callLangGraphParse(String absolutePath, Long userId, Long familyId, Long subjectId) {
- try {
- Map<String, Object> lgRequest = new HashMap<>();
- lgRequest.put("file_path", absolutePath);
- lgRequest.put("user_id", userId);
- lgRequest.put("family_id", familyId);
- ResponseEntity<Map> lgResponse = restTemplate.postForEntity(
- langgraphBaseUrl + "/api/v1/report/parse", lgRequest, Map.class);
- Map<String, Object> lgBody = lgResponse.getBody();
- if (lgBody != null && Integer.valueOf(200).equals(lgBody.get("code"))) {
- Map<String, Object> lgData = (Map<String, Object>) lgBody.get("data");
- if (lgData != null) {
- return lgData;
- }
- }
- } catch (Exception e) {
- log.warn("LangGraph 解析失败,回退: {}", e.getMessage());
- }
- return null;
- }
- /**
- * 触发 AI 解读(T29-B1-5:失败不再静默吞错,结果与失败原因回传调用方)
- *
- * @return {success, analysis, traceId} 成功;
- * {success=false, reason="quota", toast} 配额不足;
- * {success=false, reason="langgraph_failed", message} LangGraph 失败或返回空解读
- */
- private Map<String, Object> triggerAiAnalysis(Long reportId, Long subjectId, Long proxyUploaderId) {
- Map<String, Object> aiResult = new HashMap<>();
- aiResult.put("success", false);
- // BASIC 配额检查(报告 AI 解读,2026-10-23 新口径:BASIC 1 次/月;FAMILY 及以上不限次;FREE 维持既有口径扣减)
- if (proxyUploaderId != null) {
- com.etotem.cfc.dto.QuotaConsumeResult quotaResult = basicQuotaService.consumeMemberQuota(proxyUploaderId, "REPORT_READING", false);
- if (!quotaResult.isSuccess()) {
- log.info("报告 AI 解读配额不足: userId={}, toast={}", proxyUploaderId, quotaResult.getToastMsg());
- aiResult.put("reason", "quota");
- aiResult.put("toast", quotaResult.getToastMsg());
- return aiResult;
- }
- }
- try {
- Map<String, Object> analyzeReq = new HashMap<>();
- analyzeReq.put("report_id", reportId);
- analyzeReq.put("user_id", subjectId);
- analyzeReq.put("focus", "代上传报告解读");
- ResponseEntity<Map> resp = restTemplate.postForEntity(
- langgraphBaseUrl + "/api/v1/analyze", analyzeReq, Map.class);
- if (resp.getBody() != null) {
- Map<String, Object> body = resp.getBody();
- String analysis = objectToString(body.get("analysis"));
- String traceId = objectToString(body.get("trace_id"));
- if (analysis != null && !analysis.isEmpty()) {
- Map<String, Object> aiData = new HashMap<>();
- aiData.put("analysis", analysis);
- aiData.put("traceId", traceId);
- aiData.put("proxyUploaderId", proxyUploaderId);
- healthReportService.setAiAnalysis(reportId, aiData);
- log.info("AI解读已保存: reportId={}, traceId={}", reportId, traceId);
- aiResult.put("success", true);
- aiResult.put("analysis", analysis);
- aiResult.put("traceId", traceId);
- return aiResult;
- }
- aiResult.put("reason", "langgraph_failed");
- aiResult.put("message", "AI解读服务返回空结果");
- log.warn("AI解读返回空结果: reportId={}, body={}", reportId, body);
- } else {
- aiResult.put("reason", "langgraph_failed");
- aiResult.put("message", "AI解读服务无响应");
- log.warn("AI解读服务无响应: reportId={}", reportId);
- }
- } catch (Exception e) {
- aiResult.put("reason", "langgraph_failed");
- aiResult.put("message", "AI解读服务异常: " + e.getMessage());
- log.warn("AI解读触发失败: {}", e.getMessage(), e);
- }
- return aiResult;
- }
- /**
- * 获取身体维度异常指标(身体页面"指标告警")
- * 疾病风险:只返回非低风险项目
- * 营养评估+氨基酸评估:只返回异常状态(偏高/偏低/缺乏等)
- */
- @PostMapping("/report/body-abnormal")
- public Result<?> bodyAbnormal(@RequestBody Map<String, Object> params,
- @RequestAttribute(value = "currentMemberId", required = false) Long currentMemberId) {
- Long memberId = ParamUtils.getLong(params.get("memberId"), currentMemberId);
- if (memberId == null) return Result.success(new java.util.HashMap<>());
- return Result.success(healthReportService.getBodyAbnormalIndicators(memberId));
- }
- }
|