|
|
@@ -1,7 +1,12 @@
|
|
|
package com.etotem.cfc.service;
|
|
|
|
|
|
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
|
|
+import com.etotem.cfc.entity.BodyFatScaleRecord;
|
|
|
+import com.etotem.cfc.entity.FamilyMember;
|
|
|
import com.etotem.cfc.entity.IndicatorDefinition;
|
|
|
import com.etotem.cfc.entity.IndicatorValue;
|
|
|
+import com.etotem.cfc.mapper.BodyFatScaleRecordMapper;
|
|
|
+import com.etotem.cfc.mapper.FamilyMemberMapper;
|
|
|
import com.etotem.cfc.mapper.IndicatorDefinitionMapper;
|
|
|
import com.etotem.cfc.mapper.IndicatorValueMapper;
|
|
|
import com.fasterxml.jackson.databind.JsonNode;
|
|
|
@@ -12,11 +17,13 @@ import lombok.extern.slf4j.Slf4j;
|
|
|
import org.springframework.beans.factory.annotation.Value;
|
|
|
import org.springframework.http.*;
|
|
|
import org.springframework.stereotype.Service;
|
|
|
+import org.springframework.util.StringUtils;
|
|
|
import org.springframework.web.client.RestTemplate;
|
|
|
|
|
|
import javax.annotation.Resource;
|
|
|
import java.io.File;
|
|
|
import java.io.IOException;
|
|
|
+import java.math.BigDecimal;
|
|
|
import java.nio.file.Files;
|
|
|
import java.nio.file.Path;
|
|
|
import java.nio.file.Paths;
|
|
|
@@ -42,13 +49,19 @@ public class BodyFatScaleService {
|
|
|
@Resource
|
|
|
private IndicatorValueMapper indicatorValueMapper;
|
|
|
|
|
|
+ @Resource
|
|
|
+ private BodyFatScaleRecordMapper bodyFatScaleRecordMapper;
|
|
|
+
|
|
|
+ @Resource
|
|
|
+ private FamilyMemberMapper familyMemberMapper;
|
|
|
+
|
|
|
private final RestTemplate restTemplate = new RestTemplate();
|
|
|
private final ObjectMapper objectMapper = new ObjectMapper();
|
|
|
|
|
|
/**
|
|
|
* 体脂秤指标编码定义
|
|
|
*/
|
|
|
- private static final Map<String, String> BODY_FAT_INDICATORS = new HashMap<String, String>();
|
|
|
+ private static final Map<String, String> BODY_FAT_INDICATORS = new HashMap<>();
|
|
|
static {
|
|
|
BODY_FAT_INDICATORS.put("体重", "weight");
|
|
|
BODY_FAT_INDICATORS.put("BMI", "bmi");
|
|
|
@@ -224,50 +237,137 @@ public class BodyFatScaleService {
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
- * 保存指标到 indicator_values 表
|
|
|
- * sourceType = "body_fat_scale",sourceId = memberId
|
|
|
+ * 保存指标到 indicator_values 表(幂等 upsert,支持多期时序)。
|
|
|
+ * 每次调用创建一个 body_fat_scale_records 记录,indicator_values.source_id = recordId;
|
|
|
+ * 唯一键 uk_source_definition (source_type, source_id, definition_id) 保证同一记录重复保存
|
|
|
+ * 是 upsert 覆盖而不是插入新行,从而避免 DuplicateKeyException 导致整批失败。
|
|
|
*/
|
|
|
public Map<String, Object> saveMetrics(Long memberId, List<Map<String, Object>> metrics) {
|
|
|
- Map<String, Object> result = new LinkedHashMap<>();
|
|
|
+ return saveMetrics(memberId, metrics, null, null);
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 完整签名:允许显式传入 recordId(幂等复用已有测量记录)、imageUrl、measuredAt。
|
|
|
+ * recordId 为空时自动创建新记录(同日同图片则复用已有记录)。
|
|
|
+ */
|
|
|
+ public Map<String, Object> saveMetrics(Long memberId, List<Map<String, Object>> metrics,
|
|
|
+ String imageUrl, Date measuredAt) {
|
|
|
+ if (memberId == null) {
|
|
|
+ throw new IllegalArgumentException("memberId 不能为空");
|
|
|
+ }
|
|
|
+ if (metrics == null || metrics.isEmpty()) {
|
|
|
+ return new HashMap<>();
|
|
|
+ }
|
|
|
+
|
|
|
+ // 解析家庭ID
|
|
|
+ Long familyId = resolveFamilyId(memberId);
|
|
|
+
|
|
|
+ // 找一条已有的同名测量记录(幂等复用):优先同图片URL,其次同测量日期
|
|
|
+ Long reuseRecordId = null;
|
|
|
+ if (imageUrl != null && !imageUrl.isEmpty()) {
|
|
|
+ BodyFatScaleRecord existingByImage = bodyFatScaleRecordMapper.selectOne(
|
|
|
+ new LambdaQueryWrapper<BodyFatScaleRecord>()
|
|
|
+ .eq(BodyFatScaleRecord::getMemberId, memberId)
|
|
|
+ .eq(BodyFatScaleRecord::getImageUrl, imageUrl)
|
|
|
+ .orderByDesc(BodyFatScaleRecord::getId)
|
|
|
+ .last("LIMIT 1"));
|
|
|
+ if (existingByImage != null) {
|
|
|
+ reuseRecordId = existingByImage.getId();
|
|
|
+ }
|
|
|
+ }
|
|
|
+ if (reuseRecordId == null && measuredAt != null) {
|
|
|
+ BodyFatScaleRecord existingByDate = bodyFatScaleRecordMapper.selectOne(
|
|
|
+ new LambdaQueryWrapper<BodyFatScaleRecord>()
|
|
|
+ .eq(BodyFatScaleRecord::getMemberId, memberId)
|
|
|
+ .eq(BodyFatScaleRecord::getMeasuredAt, measuredAt)
|
|
|
+ .orderByDesc(BodyFatScaleRecord::getId)
|
|
|
+ .last("LIMIT 1"));
|
|
|
+ if (existingByDate != null) {
|
|
|
+ reuseRecordId = existingByDate.getId();
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ // 获取或创建 record
|
|
|
+ Long recordId;
|
|
|
+ if (reuseRecordId != null) {
|
|
|
+ recordId = reuseRecordId;
|
|
|
+ } else {
|
|
|
+ BodyFatScaleRecord record = new BodyFatScaleRecord();
|
|
|
+ record.setMemberId(memberId);
|
|
|
+ record.setFamilyId(familyId);
|
|
|
+ record.setImageUrl(imageUrl);
|
|
|
+ record.setMeasuredAt(measuredAt);
|
|
|
+ bodyFatScaleRecordMapper.insert(record);
|
|
|
+ recordId = record.getId();
|
|
|
+ log.info("体脂秤测量记录已创建 recordId={}, memberId={}", recordId, memberId);
|
|
|
+ }
|
|
|
+
|
|
|
+ // 取当前日期的 SQL DATE 作为 fallback report_date
|
|
|
+ java.sql.Date fallbackDate = new java.sql.Date(new Date().getTime());
|
|
|
+ java.sql.Date reportDate = (measuredAt != null)
|
|
|
+ ? new java.sql.Date(measuredAt.getTime()) : fallbackDate;
|
|
|
+ String dateSource = (measuredAt != null) ? "real" : "upload";
|
|
|
+
|
|
|
AtomicInteger saved = new AtomicInteger(0);
|
|
|
AtomicInteger skipped = new AtomicInteger(0);
|
|
|
+ AtomicInteger updated = new AtomicInteger(0);
|
|
|
|
|
|
for (Map<String, Object> metric : metrics) {
|
|
|
- String name = (String) metric.get("name");
|
|
|
- String valueStr = (String) metric.get("value");
|
|
|
- String unit = (String) metric.get("unit");
|
|
|
+ String name = metric.get("name") != null ? metric.get("name").toString().trim() : "";
|
|
|
+ String valueStr = metric.get("value") != null ? metric.get("value").toString().trim() : "";
|
|
|
+ String unit = metric.get("unit") != null ? metric.get("unit").toString().trim() : "";
|
|
|
|
|
|
- if (name == null || name.trim().isEmpty() || valueStr == null || valueStr.trim().isEmpty()) {
|
|
|
+ if (name.isEmpty() || valueStr.isEmpty()) {
|
|
|
skipped.incrementAndGet();
|
|
|
continue;
|
|
|
}
|
|
|
|
|
|
- // 查找或创建 indicator_definition
|
|
|
- IndicatorDefinition def = findOrCreateDefinition(name, unit);
|
|
|
- if (def == null) {
|
|
|
- skipped.incrementAndGet();
|
|
|
- continue;
|
|
|
- }
|
|
|
-
|
|
|
- // 保存 indicator_value
|
|
|
- IndicatorValue iv = new IndicatorValue();
|
|
|
- iv.setSourceType("body_fat_scale");
|
|
|
- iv.setSourceId(memberId);
|
|
|
- iv.setDefinitionId(def.getId());
|
|
|
- iv.setValue(valueStr + (unit != null && !unit.trim().isEmpty() ? " " + unit : ""));
|
|
|
try {
|
|
|
- iv.setNumericValue(new java.math.BigDecimal(valueStr));
|
|
|
+ // 查找或创建 indicator_definition
|
|
|
+ IndicatorDefinition def = findOrCreateDefinition(name, unit);
|
|
|
+ if (def == null) {
|
|
|
+ skipped.incrementAndGet();
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+
|
|
|
+ // 幂等写入 indicator_values
|
|
|
+ IndicatorValue iv = new IndicatorValue();
|
|
|
+ iv.setSourceType("body_fat_scale");
|
|
|
+ iv.setSourceId(recordId);
|
|
|
+ iv.setDefinitionId(def.getId());
|
|
|
+ iv.setSubjectId(memberId);
|
|
|
+ iv.setFamilyId(familyId);
|
|
|
+ iv.setValue(valueStr + (StringUtils.hasText(unit) ? " " + unit : ""));
|
|
|
+ try {
|
|
|
+ iv.setNumericValue(new BigDecimal(valueStr));
|
|
|
+ } catch (Exception ignore) {
|
|
|
+ // 非数值保留字符串
|
|
|
+ }
|
|
|
+ iv.setUnit(unit);
|
|
|
+ iv.setReportDate(reportDate);
|
|
|
+ iv.setDateSource(dateSource);
|
|
|
+ iv.setRefRangeSnapshot(def.getRefRange());
|
|
|
+ iv.setStatus("normal");
|
|
|
+
|
|
|
+ int rows = indicatorValueMapper.upsertMapping(iv);
|
|
|
+ if (rows > 0) {
|
|
|
+ updated.incrementAndGet();
|
|
|
+ }
|
|
|
+ saved.incrementAndGet();
|
|
|
} catch (Exception e) {
|
|
|
- // 非数值也保留字符串值
|
|
|
+ // 单条指标失败不阻断整批(避免旧 insert 时的 DuplicateKeyException 炸整批)
|
|
|
+ log.warn("体脂秤指标写入失败 member={} record={} name={}: {}",
|
|
|
+ memberId, recordId, name, e.getMessage());
|
|
|
+ skipped.incrementAndGet();
|
|
|
}
|
|
|
- iv.setRecordedAt(new Date());
|
|
|
- indicatorValueMapper.insert(iv);
|
|
|
- saved.incrementAndGet();
|
|
|
}
|
|
|
|
|
|
+ Map<String, Object> result = new LinkedHashMap<>();
|
|
|
result.put("saved", saved.get());
|
|
|
result.put("skipped", skipped.get());
|
|
|
+ result.put("updated", updated.get());
|
|
|
result.put("memberId", memberId);
|
|
|
+ result.put("recordId", recordId);
|
|
|
return result;
|
|
|
}
|
|
|
|
|
|
@@ -277,7 +377,7 @@ public class BodyFatScaleService {
|
|
|
private IndicatorDefinition findOrCreateDefinition(String name, String unit) {
|
|
|
// 先按中文名查找
|
|
|
List<IndicatorDefinition> defs = indicatorDefinitionMapper.selectList(
|
|
|
- new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<IndicatorDefinition>()
|
|
|
+ new LambdaQueryWrapper<IndicatorDefinition>()
|
|
|
.eq(IndicatorDefinition::getName, name)
|
|
|
.eq(IndicatorDefinition::getStatus, 1));
|
|
|
if (!defs.isEmpty()) {
|
|
|
@@ -286,20 +386,20 @@ public class BodyFatScaleService {
|
|
|
// 再按编码查找
|
|
|
String code = nameToCode(name);
|
|
|
defs = indicatorDefinitionMapper.selectList(
|
|
|
- new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<IndicatorDefinition>()
|
|
|
+ new LambdaQueryWrapper<IndicatorDefinition>()
|
|
|
.eq(IndicatorDefinition::getCode, code)
|
|
|
.eq(IndicatorDefinition::getStatus, 1));
|
|
|
if (!defs.isEmpty()) {
|
|
|
return defs.get(0);
|
|
|
}
|
|
|
- // 创建新定义
|
|
|
+ // 创建新定义(P1-6 口径:未命中 mapping 时自动创建 status=1)
|
|
|
IndicatorDefinition def = new IndicatorDefinition();
|
|
|
def.setDomain("physical");
|
|
|
def.setCategory("体脂秤");
|
|
|
def.setCode(code);
|
|
|
def.setName(name);
|
|
|
def.setDataType("number");
|
|
|
- def.setUnit(unit != null && !unit.trim().isEmpty() ? unit : "");
|
|
|
+ def.setUnit(unit);
|
|
|
def.setSortOrder(0);
|
|
|
def.setStatus(1);
|
|
|
indicatorDefinitionMapper.insert(def);
|
|
|
@@ -314,6 +414,19 @@ public class BodyFatScaleService {
|
|
|
return BODY_FAT_INDICATORS.getOrDefault(name, name.toLowerCase().replace(" ", "_"));
|
|
|
}
|
|
|
|
|
|
+ private Long resolveFamilyId(Long memberId) {
|
|
|
+ if (memberId == null) {
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+ try {
|
|
|
+ FamilyMember member = familyMemberMapper.selectById(memberId);
|
|
|
+ return member != null ? member.getFamilyId() : null;
|
|
|
+ } catch (Exception e) {
|
|
|
+ log.warn("查询家庭成员 familyId 失败 memberId={}: {}", memberId, e.getMessage());
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
/**
|
|
|
* 批量分析并保存(一次性处理多张图片)
|
|
|
*/
|
|
|
@@ -321,20 +434,26 @@ public class BodyFatScaleService {
|
|
|
Map<String, Object> summary = new LinkedHashMap<>();
|
|
|
List<Map<String, Object>> allResults = new ArrayList<>();
|
|
|
AtomicInteger totalSaved = new AtomicInteger(0);
|
|
|
+ AtomicInteger totalUpdated = new AtomicInteger(0);
|
|
|
+ AtomicInteger totalSkipped = new AtomicInteger(0);
|
|
|
|
|
|
for (String path : imagePaths) {
|
|
|
Map<String, Object> imgResult = analyzeImage(path);
|
|
|
List<Map<String, Object>> metrics = (List<Map<String, Object>>) imgResult.get("metrics");
|
|
|
if (metrics != null && !metrics.isEmpty()) {
|
|
|
- Map<String, Object> saved = saveMetrics(memberId, metrics);
|
|
|
+ Map<String, Object> saved = saveMetrics(memberId, metrics, path, null);
|
|
|
imgResult.put("saved", saved);
|
|
|
totalSaved.addAndGet((int) saved.getOrDefault("saved", 0));
|
|
|
+ totalUpdated.addAndGet((int) saved.getOrDefault("updated", 0));
|
|
|
+ totalSkipped.addAndGet((int) saved.getOrDefault("skipped", 0));
|
|
|
}
|
|
|
allResults.add(imgResult);
|
|
|
}
|
|
|
|
|
|
summary.put("totalImages", imagePaths.size());
|
|
|
summary.put("totalSaved", totalSaved.get());
|
|
|
+ summary.put("totalUpdated", totalUpdated.get());
|
|
|
+ summary.put("totalSkipped", totalSkipped.get());
|
|
|
summary.put("results", allResults);
|
|
|
return summary;
|
|
|
}
|