Преглед изворни кода

feat(indicator-timeline): 补齐 spec 缺失 4 文件(SparkLine + MemberIndicatorTimeline + BodyFatScaleRecord/Mapper)

按 docs/superpowers/specs/2026-10-25-indicator-timeline-display-design.md §6.1#16/T05-5c/P2-1:
- cfc-frontend/pages/health/components/SparkLine.vue:§6.2 纯 view 点阵(8点4rpx、末点6rpx主色、首末点强制保留);修复 t03 参考实现 colorClass 未绑 wrapper 导致末点永远灰色的 bug
- cfc-web/views/nutritionist/MemberIndicatorTimeline.vue:P2-1 管理端最小版(家庭→成员级联选择 + 指标选择 + 期次表格,无图),数据源纯前端组合 admin-list + values/list(按 reportType/reportId 拉取后按 definitionId 过滤),dateSource=upload 打星标
- cfc-backend entity/mapper/BodyFatScaleRecord:迁移423 建表对应实体 + BaseMapper(字段与建表一致)
- 配套:api/indicator.js 增加 listIndicatorValues 封装(option a 必需);路由 /member-indicator-timeline + 侧边栏菜单项(perm health:indicators 复用)

不新增 DB 迁移;未纳入 t05 的 BodyFatScaleService 改造(G4 sourceId=recordId 修复留后续)。
Sisyphus пре 2 недеља
родитељ
комит
e7c4616b24

+ 36 - 0
cfc-backend/src/main/java/com/etotem/cfc/entity/BodyFatScaleRecord.java

@@ -0,0 +1,36 @@
+package com.etotem.cfc.entity;
+
+import com.baomidou.mybatisplus.annotation.IdType;
+import com.baomidou.mybatisplus.annotation.TableId;
+import com.baomidou.mybatisplus.annotation.TableName;
+import lombok.Data;
+
+import java.util.Date;
+
+/**
+ * 体脂秤测量记录 — 一次测量一条记录。
+ * 支撑 indicator_values.source_id = recordId(多期时序语义)。
+ * 表由 DatabaseInitializer 迁移423 建表。
+ */
+@Data
+@TableName("body_fat_scale_records")
+public class BodyFatScaleRecord {
+
+    @TableId(type = IdType.AUTO)
+    private Long id;
+
+    /** 家庭成员ID (family_members.id) */
+    private Long memberId;
+
+    /** 所属家庭ID (families.id),可空 */
+    private Long familyId;
+
+    /** 体脂秤照片URL,可空 */
+    private String imageUrl;
+
+    /** 测量日期(取不到为 NULL,观测 report_date 记为上传日) */
+    private Date measuredAt;
+
+    /** 记录创建时间(DB 默认 CURRENT_TIMESTAMP) */
+    private Date createdAt;
+}

+ 9 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/BodyFatScaleRecordMapper.java

@@ -0,0 +1,9 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.BodyFatScaleRecord;
+import org.apache.ibatis.annotations.Mapper;
+
+@Mapper
+public interface BodyFatScaleRecordMapper extends BaseMapper<BodyFatScaleRecord> {
+}

+ 124 - 0
cfc-frontend/pages/health/components/SparkLine.vue

@@ -0,0 +1,124 @@
+<template>
+  <view class="sparkline-wrap" :class="colorClass" :style="wrapStyle">
+    <view
+      v-for="(pt, idx) in renderedPoints"
+      :key="getItemKey(idx)"
+      class="spark-dot"
+      :class="{ 'spark-dot-last': isLast(idx) }"
+      :style="dotStyle(idx, pt)"
+    />
+  </view>
+</template>
+
+<script>
+/**
+ * §6.2 SparkLine 组件 — 纯 view 点阵实现,禁用 canvas。
+ *
+ * 约束(spec §6.2):
+ *   - 8 个数据点(n > 8 等距抽样,首末点强制保留)
+ *   - 末点(最新值)6rpx 主色实心,其余 4rpx 次级灰
+ *   - 不画连线(60×24rpx 空间内 rotate-border 会错位)
+ *   - 外层 position:relative + overflow:hidden,防止边缘点溢出
+ */
+export default {
+  name: 'SparkLine',
+  props: {
+    /** [{ reportDate, numericValue }],已按时间升序,长度 ≤ 12 */
+    points: { type: Array, default: function() { return [] } },
+    width: { type: Number, default: 60 },    // rpx
+    height: { type: Number, default: 24 },   // rpx
+    /** 趋势色,来自 utils/indicator-change.js 的 colorClassFor */
+    colorClass: { type: String, default: 'gray-text' }
+  },
+  computed: {
+    wrapStyle: function() {
+      return 'width:' + this.width + 'rpx;height:' + this.height + 'rpx'
+    },
+    /** 抽样后的点集(保留首末点) */
+    sampledPoints: function() {
+      var pts = this.points || []
+      var n = pts.length
+      if (n === 0) return []
+      if (n <= 8) return pts
+      // 等距抽样,强制保留首末
+      var limit = 8
+      var step = (n - 1) / (limit - 1)
+      var out = []
+      for (var i = 0; i < limit - 1; i++) {
+        out.push(pts[Math.round(i * step)])
+      }
+      out.push(pts[n - 1]) // ← 末点强制保留
+      return out
+    },
+    /** 极值用于归一化 */
+    minVal: function() {
+      var pts = this.sampledPoints
+      if (pts.length === 0) return 0
+      var m = Infinity
+      pts.forEach(function(p) {
+        if (p && !isNaN(p.numericValue) && p.numericValue < m) m = p.numericValue
+      })
+      return m === Infinity ? 0 : m
+    },
+    maxVal: function() {
+      var pts = this.sampledPoints
+      if (pts.length === 0) return 1
+      var m = -Infinity
+      pts.forEach(function(p) {
+        if (p && !isNaN(p.numericValue) && p.numericValue > m) m = p.numericValue
+      })
+      return m === -Infinity ? 1 : m
+    },
+    range: function() {
+      var r = this.maxVal - this.minVal
+      return r === 0 ? 1 : r
+    },
+    /** 渲染点集:每条含 left%、top%、是否是末点 */
+    renderedPoints: function() {
+      var pts = this.sampledPoints
+      if (pts.length === 0) return []
+      var n = pts.length
+      var minV = this.minVal
+      var rng = this.range
+      return pts.map(function(p, i) {
+        var v = p && !isNaN(p.numericValue) ? p.numericValue : minV
+        var leftPct = (n === 1) ? 50 : (i / (n - 1)) * 100
+        // top: minV → 100%, maxV → 0%
+        var topPct = 100 - ((v - minV) / rng) * 100
+        return { leftPct: leftPct, topPct: topPct, isLast: i === n - 1 }
+      })
+    }
+  },
+  methods: {
+    getItemKey: function(idx) { return 's_' + idx },
+    isLast: function(idx) {
+      return idx === (this.renderedPoints.length - 1)
+    },
+    dotStyle: function(idx, pt) {
+      var size = pt.isLast ? 6 : 4
+      return 'left:' + pt.leftPct + '%;top:' + pt.topPct + '%;width:' + size + 'rpx;height:' + size + 'rpx'
+    }
+  }
+}
+</script>
+
+<style scoped lang="scss">
+.sparkline-wrap {
+  position: relative;
+  overflow: hidden;
+  display: inline-block;
+}
+.spark-dot {
+  position: absolute;
+  border-radius: 999rpx;
+  transform: translate(-50%, -50%);
+  // 默认次级灰
+  background: $app-text-subtle;
+}
+.spark-dot-last {
+  // 末点主色(由外层 colorClass 决定)
+}
+.green-text .spark-dot-last { background: $status-success-strong-2; }
+.red-text .spark-dot-last   { background: $status-danger-deep; }
+.gray-text .spark-dot-last  { background: $facade-text-muted; }
+</style>

+ 5 - 0
cfc-web/src/api/indicator.js

@@ -4,6 +4,11 @@ export function listIndicatorDefinitions(params) {
   return request({ url: '/api/admin/indicator/list', method: 'post', data: params })
 }
 
+// 按数据源读取指标值(sourceType=报告类型,sourceId=reportId;体脂秤 sourceType=body_fat_scale,sourceId=memberId)
+export function listIndicatorValues(sourceType, sourceId) {
+  return request({ url: '/api/admin/indicator/values/list', method: 'post', data: { sourceType, sourceId } })
+}
+
 export function saveIndicatorCorrelation(data) {
   return request({ url: '/api/admin/indicator/correlation/save', method: 'post', data })
 }

+ 6 - 0
cfc-web/src/router/index.js

@@ -629,6 +629,12 @@ const routes = [
         component: () => import('@/views/nutritionist/HealthIndicators.vue'),
         meta: { title: '健康指标', perm: 'health:indicators' }
       },
+      {
+        path: 'member-indicator-timeline',
+        name: 'MemberIndicatorTimeline',
+        component: () => import('@/views/nutritionist/MemberIndicatorTimeline.vue'),
+        meta: { title: '成员指标时间线', perm: 'health:indicators' }
+      },
       {
         path: 'health-checkins',
         name: 'HealthCheckinManage',

+ 1 - 0
cfc-web/src/views/Layout.vue

@@ -256,6 +256,7 @@ export default {
             { path: '/report-proxy-upload', label: '代传报告', icon: 'el-icon-upload', perm: 'health:reports' },
             { path: '/report-parse-status', label: '解析进度', icon: 'el-icon-data-line', perm: 'health:reports' },
             { path: '/health-indicators', label: '健康指标', icon: 'el-icon-data-line', perm: 'health:indicators' },
+            { path: '/member-indicator-timeline', label: '成员指标时间线', icon: 'el-icon-time', perm: 'health:indicators' },
             { path: '/health-checkins', label: '健康打卡', icon: 'el-icon-s-order', perm: 'health:checkins' },
             { path: '/emotion-alert', label: '情绪告警', icon: 'el-icon-warning', perm: 'health:checkins' },
             { path: '/nutrition-mappings', label: '营养素映射', icon: 'el-icon-connection', perm: 'health:mappings' },

+ 347 - 0
cfc-web/src/views/nutritionist/MemberIndicatorTimeline.vue

@@ -0,0 +1,347 @@
+<template>
+  <div class="member-indicator-timeline page-container">
+    <el-card>
+      <div slot="header">
+        <PageHeader title="成员指标时间线" />
+      </div>
+
+      <!-- 筛选栏 -->
+      <div class="filter-bar">
+        <el-select
+          v-model="familyId"
+          placeholder="选择家庭"
+          filterable
+          clearable
+          class="filter-select"
+          @change="onFamilyChange"
+        >
+          <el-option
+            v-for="f in families"
+            :key="f.id"
+            :label="f.name"
+            :value="f.id"
+          />
+        </el-select>
+
+        <el-select
+          v-model="memberValue"
+          placeholder="选择成员"
+          filterable
+          clearable
+          class="filter-select"
+          :disabled="!members.length"
+          @change="onMemberChange"
+        >
+          <el-option
+            v-for="m in members"
+            :key="(m.memberId || m.userId)"
+            :label="memberLabel(m)"
+            :value="(m.memberId || m.userId)"
+          />
+        </el-select>
+
+        <el-select
+          v-model="definitionId"
+          placeholder="选择指标"
+          filterable
+          clearable
+          class="filter-select"
+          @change="loadTimeline"
+        >
+          <el-option
+            v-for="d in definitions"
+            :key="d.id"
+            :label="d.name"
+            :value="d.id"
+          >
+            <span>{{ d.name }}</span>
+            <span v-if="d.unit" class="unit-hint">{{ d.unit }}</span>
+          </el-option>
+        </el-select>
+
+        <el-button type="primary" icon="el-icon-search" @click="loadTimeline">查询</el-button>
+      </div>
+
+      <el-alert
+        v-if="truncated"
+        type="warning"
+        :closable="false"
+        show-icon
+        title="报告总量超过单页上限(500),结果可能不完整;建议通过更精确的条件查询。"
+        class="truncate-alert"
+      />
+
+      <div class="adm-table-wrap">
+        <el-table
+          :data="rows"
+          v-loading="loading"
+          border
+          stripe
+          height="100%"
+        >
+          <el-table-column prop="reportDate" label="期次日期" width="120">
+            <template slot-scope="{ row }">
+              <span>{{ formatDate(row.reportDate) }}</span>
+              <el-tooltip v-if="row.dateSource === 'upload'" content="上传日期(非报告打印日期)" placement="top">
+                <span class="star-mark">*</span>
+              </el-tooltip>
+            </template>
+          </el-table-column>
+
+          <el-table-column label="报告类型" width="130">
+            <template slot-scope="{ row }">
+              <el-tag size="mini">{{ row.reportTypeLabel }}</el-tag>
+            </template>
+          </el-table-column>
+
+          <el-table-column label="数值" width="140">
+            <template slot-scope="{ row }">
+              <span>{{ row.value != null && row.value !== '' ? row.value : '-' }}</span>
+              <span v-if="row.unit" class="unit-text">{{ row.unit }}</span>
+            </template>
+          </el-table-column>
+
+          <el-table-column label="状态" width="100">
+            <template slot-scope="{ row }">
+              <el-tag v-if="row.status" size="mini" :type="statusTagType(row.status)">{{ row.status }}</el-tag>
+              <span v-else>-</span>
+            </template>
+          </el-table-column>
+
+          <el-table-column label="参考范围" width="120">
+            <template slot-scope="{ row }">
+              <span>{{ row.refRangeSnapshot || '-' }}</span>
+            </template>
+          </el-table-column>
+
+          <el-table-column label="备注" show-overflow-tooltip>
+            <template slot-scope="{ row }">
+              <span>{{ row.remark || '-' }}</span>
+            </template>
+          </el-table-column>
+        </el-table>
+      </div>
+
+      <el-empty
+        v-if="!loading && rows.length === 0"
+        description="该成员暂无此指标的期次数据"
+        :image-size="80"
+      />
+    </el-card>
+  </div>
+</template>
+
+<script>
+import SortMixin from '@/mixins/SortMixin'
+import { getFamilyList, getFamilyMembers, adminListHealthReports } from '@/api/admin'
+import { listIndicatorDefinitions, listIndicatorValues } from '@/api/indicator'
+
+export default {
+  mixins: [SortMixin],
+  name: 'MemberIndicatorTimeline',
+  data() {
+    return {
+      loading: false,
+      families: [],
+      familyId: null,
+      members: [],
+      memberValue: null,
+      selectedMember: null,
+      definitions: [],
+      definitionId: null,
+      rows: [],
+      truncated: false
+    }
+  },
+  created() {
+    this.loadFamilies()
+    this.loadDefinitions()
+  },
+  methods: {
+    // --- 家庭列表 ---
+    async loadFamilies() {
+      try {
+        const res = await getFamilyList({ page: 1, size: 100 })
+        this.families = (res.data && res.data.records) || res.data || []
+      } catch (e) {
+        console.error('loadFamilies', e)
+      }
+    },
+
+    // --- 家庭改变 -> 重置成员 ---
+    onFamilyChange() {
+      this.memberValue = null
+      this.selectedMember = null
+      this.members = []
+      this.rows = []
+      if (this.familyId) {
+        this.loadMembers()
+      }
+    },
+
+    // --- 成员列表 ---
+    async loadMembers() {
+      try {
+        const res = await getFamilyMembers(this.familyId)
+        this.members = (res.data && res.data.members) || []
+      } catch (e) {
+        console.error('loadMembers', e)
+      }
+    },
+
+    // --- 成员改变 -> 记录选中成员对象 ---
+    onMemberChange() {
+      this.selectedMember = this.members.find(m => (m.memberId || m.userId) === this.memberValue) || null
+      this.rows = []
+      if (this.definitionId) {
+        this.loadTimeline()
+      }
+    },
+
+    // --- 指标字典 ---
+    async loadDefinitions() {
+      try {
+        const res = await listIndicatorDefinitions({ status: 1 })
+        this.definitions = Array.isArray(res.data) ? res.data : []
+      } catch (e) {
+        console.error('loadDefinitions', e)
+      }
+    },
+
+    // --- 主查询:报告 -> 指标值 ---
+    async loadTimeline() {
+      if (!this.memberValue || !this.definitionId || !this.selectedMember) {
+        this.rows = []
+        return
+      }
+      this.loading = true
+      this.rows = []
+      this.truncated = false
+      try {
+        // 1) 取全量报告(admin 视角,size=500)
+        const reportsRes = await adminListHealthReports({ page: 1, size: 500 })
+        const reportsData = reportsRes.data || {}
+        const allReports = reportsData.records || []
+        this.truncated = (reportsData.total || 0) > allReports.length
+
+        // 2) 筛选该成员的报告(memberId 优先,userId 兼容)
+        const targetMemberId = this.selectedMember.memberId
+        const targetUserId = this.selectedMember.userId
+        const memberReports = allReports.filter(r => {
+          const mid = Number(r.memberId)
+          return (targetMemberId && mid === Number(targetMemberId))
+              || (targetUserId && mid === Number(targetUserId))
+        })
+
+        if (memberReports.length === 0) {
+          this.loading = false
+          return
+        }
+
+        // 3) 并行取指标值
+        const valuePromises = memberReports.map(r => {
+          const sourceType = r.reportType
+          const sourceId = r.id
+          return listIndicatorValues(sourceType, sourceId).then(vRes => {
+            const vals = Array.isArray(vRes.data) ? vRes.data : []
+            const match = vals.find(v => String(v.definitionId) === String(this.definitionId))
+            if (!match) return null
+            const def = this.definitions.find(d => String(d.id) === String(this.definitionId))
+            return {
+              reportDate: r.reportDate,
+              reportType: r.reportType,
+              reportTypeLabel: this.reportTypeLabel(r.reportType),
+              value: match.value,
+              numericValue: match.numericValue,
+              unit: match.unit || (def ? def.unit : ''),
+              status: match.status,
+              dateSource: match.dateSource,
+              refRangeSnapshot: match.refRangeSnapshot,
+              remark: match.remark
+            }
+          })
+        })
+        const results = await Promise.all(valuePromises)
+        this.rows = results.filter(Boolean).sort((a, b) => {
+          // reportDate desc; null/empty last
+          const da = a.reportDate ? new Date(a.reportDate).getTime() : 0
+          const db = b.reportDate ? new Date(b.reportDate).getTime() : 0
+          return db - da
+        })
+      } catch (e) {
+        console.error('loadTimeline', e)
+        this.$message?.error?.('加载指标时间线失败')
+      } finally {
+        this.loading = false
+      }
+    },
+
+    // --- 通用 ---
+    reportTypeLabel(t) {
+      if (!t) return '-'
+      const map = {
+        gut_flora: '菌群检测',
+        physical_exam: '体检报告',
+        dan: 'DAN测评',
+        dan_a2: 'DAN测评',
+        insurance: '保单',
+        fortune: '家庭周报'
+      }
+      return map[t] || t
+    },
+    formatDate(d) {
+      if (!d) return '-'
+      const s = String(d)
+      // ISO 或 yyyy-MM-dd 取前 10 位
+      return s.length >= 10 ? s.substring(0, 10) : s
+    },
+    // 复用 HealthIndicators 的 status 颜色判定逻辑
+    statusTagType(status) {
+      if (!status) return 'info'
+      const s = status.toLowerCase()
+      if (s.indexOf('低') >= 0 || s.indexOf('缺乏') >= 0 || s.indexOf('不足') >= 0 || s === 'low') return 'danger'
+      if (s.indexOf('高') >= 0 || s.indexOf('过量') >= 0 || s === 'high') return 'warning'
+      if (s.indexOf('临界') >= 0 || s.indexOf('边缘') >= 0 || s === 'borderline') return 'warning'
+      return 'info'
+    },
+    memberLabel(m) {
+      const name = m.nickname || m.childName || '未命名'
+      const role = m.effectiveRole ? (m.effectiveRole === 'parent' ? '家长' : m.effectiveRole === 'child' ? '孩子' : m.effectiveRole) : ''
+      return `${name}${role ? '(' + role + ')' : ''}`
+    }
+  }
+}
+</script>
+
+<style scoped>
+/* 筛选栏 */
+.filter-bar {
+  display: flex;
+  gap: 12px;
+  flex-wrap: wrap;
+  margin-bottom: 12px;
+  align-items: flex-end;
+}
+.filter-select {
+  min-width: 180px;
+  flex: 1;
+}
+.truncate-alert {
+  margin-bottom: 12px;
+}
+.unit-hint {
+  margin-left: 8px;
+  color: var(--adm-text-45);
+  font-size: 12px;
+}
+.unit-text {
+  margin-left: 4px;
+  color: var(--adm-text-45);
+  font-size: 12px;
+}
+.star-mark {
+  color: #E5A700;
+  font-weight: bold;
+  margin-left: 4px;
+}
+</style>