Эх сурвалжийг харах

feat(T03): TrendChart 增强 + api.js 新增导出

- TrendChart.vue: 新增 mode/refLow/refHigh/allPeriodDates/showAxisLabels props;画参考范围背景带(Y 轴包含 refLow/refHigh);缺失期断线;X 轴抽稀(axisLabelIndices);上传日/单位不一致 * 标记;pointTap emit
- utils/api.js: 补缺 S7 getIndicatorSourceTypes 导出;新增 getReportIndicators/getIndicatorTimeline/getIndicatorPeriods/backfillIndicatorValues(T02 接口契约封装)
E2E Test Bot 3 долоо хоног өмнө
parent
commit
3693d23921

+ 251 - 59
cfc-frontend/pages/health/components/TrendChart.vue

@@ -2,7 +2,7 @@
   <view class="trend-chart-wrap" :style="{ '--font-scale': fontScale }">
     <view class="trend-container" :style="containerStyle">
       <canvas :id="canvasId" type="2d" class="trend-canvas" :style="canvasStyle"></canvas>
-      <view class="trend-tap-layer" @click="onCanvasTap"></view>
+      <view class="trend-tap-layer" @tap="onCanvasTap"></view>
     </view>
     <view class="trend-legend" v-if="series.length > 1">
       <view class="legend-item" v-for="(s, i) in series" :key="getItemKey(s, i)">
@@ -15,23 +15,37 @@
 
 <script>
 import { BrandColors } from '../../../utils/brand-colors.js'
+import { axisLabelIndices } from '@/utils/indicator-change.js'
+import { parseDate } from '@/utils/format.js'
+import fontScaleMixin from '@/mixins/font-scale.js'
 /**
- * TrendChart - 多序列折线图 Canvas 组件
- * 用法:<TrendChart :series="[{name,color,points:[{reportDate,value,unit}]}]" height="360" />
- * 参照 RadarChart.vue 的 type=2d + DPR + 重试初始化模式。
+ * TrendChart - 多序列折线图 Canvas 组件(T03 增强版)
+ *
+ * 新增能力:
+ *   - mode: 'line'|'single'|'pair'|'empty'|'line_aggregated' 消费后端 chartMode
+ *   - refLow/refHigh: 画参考范围背景带,Y 轴范围必须包含两者
+ *   - allPeriodDates: 完整 X 轴日期序列(含缺失期),用于断线与等距布局
+ *   - showAxisLabels: X 轴标签是否显示(n ≤ 8 默认显示,其余由 axisLabelIndices 抽稀)
+ *   - pointTap emit: { index, point, x, y } — P2-2 长按读数基础
  */
-import fontScaleMixin from '@/mixins/font-scale.js'
 export default {
   mixins: [fontScaleMixin],
   props: {
-    /** 序列数组 [{ name, color, points:[{reportDate,value,unit}] }] */
+    /** 序列 [{ name, color, points:[{reportDate, dateSource, numericValue, unit, status, reportId}] }] */
     series: { type: Array, default: function() { return [] } },
+    /** 'line' 折线 | 'spark' 迷你(本组件不用,见 SparkLine)| 'compare' 双期对比条(由 IndicatorChangeRow 承担) */
+    mode: { type: String, default: 'line' },
+    /** 参考范围下界/上界,非 null 时画浅色横条背景带 */
+    refLow: { type: Number, default: null },
+    refHigh: { type: Number, default: null },
+    /** X 轴日期全集(含缺失期),用于等距布局与断线。不传则从 series 推导 */
+    allPeriodDates: { type: Array, default: function() { return [] } },
+    /** n ≤ 8 时每点标值;n ≥ 9 默认关闭 */
+    showValues: { type: Boolean, default: true },
+    /** X 轴日期标签,抽稀由组件内部按 allPeriodDates.length 决定 */
+    showAxisLabels: { type: Boolean, default: true },
     width: { type: Number, default: 690 },
-    height: { type: Number, default: 420 },
-    /** Y 轴自动范围下界(默认 min-5%) */
-    yMin: { type: Number, default: 0 },
-    /** 是否绘制数据点数值标注 */
-    showValues: { type: Boolean, default: true }
+    height: { type: Number, default: 420 }
   },
   data: function() {
     return {
@@ -46,7 +60,11 @@ export default {
     canvasStyle: function() { return 'width:' + this.width + 'rpx;height:' + this.height + 'rpx' }
   },
   watch: {
-    series: { handler: function() { if (this.canvasReady) this._doRender() }, deep: true }
+    series: { handler: function() { if (this.canvasReady) this._doRender() }, deep: true },
+    refLow: function() { if (this.canvasReady) this._doRender() },
+    refHigh: function() { if (this.canvasReady) this._doRender() },
+    allPeriodDates: { handler: function() { if (this.canvasReady) this._doRender() }, deep: true },
+    mode: function() { if (this.canvasReady) this._doRender() }
   },
   mounted: function() {
     var self = this
@@ -121,58 +139,133 @@ export default {
       return arr.filter(function(s) { return s && Array.isArray(s.points) && s.points.length > 0 })
     },
 
-    /** 计算 X 轴时间范围与 Y 轴数值范围 */
+    /**
+     * 计算 X/Y 轴范围:
+     *   - X:使用 allPeriodDates(含缺失期)确保等距布局
+     *   - Y:数据范围 + 8% padding,且必须包含 refLow/refHigh(如有)
+     */
     _computeRanges: function(seriesList) {
-      var min = Infinity, max = -Infinity, firstDate = null, lastDate = null
+      var min = Infinity, max = -Infinity
       seriesList.forEach(function(s) {
         s.points.forEach(function(p) {
-          var v = parseFloat(p.value)
+          var v = parseFloat(p.numericValue != null ? p.numericValue : p.value)
           if (!isNaN(v)) { if (v < min) min = v; if (v > max) max = v }
-          if (!firstDate || p.reportDate < firstDate) firstDate = p.reportDate
-          if (!lastDate || p.reportDate > lastDate) lastDate = p.reportDate
         })
       })
       if (min === Infinity) { min = 0; max = 1 }
       if (max === min) { max = min + 1 }
+      // 必须包含 refLow/refHigh
+      if (this.refLow != null && this.refLow < min) min = this.refLow
+      if (this.refHigh != null && this.refHigh > max) max = this.refHigh
       var pad = (max - min) * 0.08
-      return { yMin: Math.max(0, min - pad), yMax: max + pad, firstDate: firstDate, lastDate: lastDate }
+      return {
+        yMin: Math.max(0, min - pad),
+        yMax: max + pad,
+        firstDate: this.allPeriodDates && this.allPeriodDates[0] || null,
+        lastDate: this.allPeriodDates && this.allPeriodDates[this.allPeriodDates.length - 1] || null
+      }
+    },
+
+    /**
+     * X 轴映射:按 allPeriodDates 等距排列;缺失期不画线但占位
+     */
+    _xOf: function(dateStr, allDates, padL, plotW) {
+      if (!allDates || allDates.length <= 1) return padL + plotW / 2
+      var idx = allDates.indexOf(dateStr)
+      if (idx < 0) return padL
+      return padL + plotW * (idx / (allDates.length - 1))
+    },
+
+    /**
+     * 检查某日期在 seriesList 的所有点的 reportDate 中是否存在
+     */
+    _hasPointForDate: function(dateStr, seriesList) {
+      for (var si = 0; si < seriesList.length; si++) {
+        var pts = seriesList[si].points
+        for (var pi = 0; pi < pts.length; pi++) {
+          if (pts[pi].reportDate === dateStr) return true
+        }
+      }
+      return false
+    },
+
+    /**
+     * 判断某日期是否有非 real dateSource(上传日标记)
+     */
+    _hasUploadDateFor: function(dateStr, seriesList) {
+      for (var si = 0; si < seriesList.length; si++) {
+        var pts = seriesList[si].points
+        for (var pi = 0; pi < pts.length; pi++) {
+          if (pts[pi].reportDate === dateStr) {
+            var ds = pts[pi].dateSource
+            if (ds && ds !== 'real' && ds !== 'unknown') return true
+          }
+        }
+      }
+      return false
+    },
+
+    /**
+     * 判断某日期某个序列是否存在 unit 不一致(值后 * 标记)
+     */
+    _hasUnitMismatchFor: function(dateStr, point) {
+      // 由调用方传入 latestUnit 来判断;此处检查单点
+      return point && point.unit && point.unit !== (this._latestUnit || '')
     },
 
     _doRender: function() {
       if (!this.ctx) return
-      var self = this
       var ctx = this.ctx
       var w = this.canvasWidth, h = this.canvasHeight
       var padL = 34, padR = 14, padT = 16, padB = 26
       var plotW = w - padL - padR, plotH = h - padT - padB
       var seriesList = this._safeSeries(this.series)
-      if (seriesList.length === 0) {
+
+      // 空态 / 单值态处理
+      if (seriesList.length === 0 || this.mode === 'empty') {
         ctx.clearRect(0, 0, w, h)
         ctx.fillStyle = BrandColors.appTextSubtle
         ctx.font = '12px sans-serif'
         ctx.textAlign = 'center'
-        ctx.fillText('暂无趋势数据', w / 2, h / 2)
+        ctx.fillText('暂无该指标数据', w / 2, h / 2)
+        return
+      }
+      if (this.mode === 'single') {
+        ctx.clearRect(0, 0, w, h)
         return
       }
+
       var ranges = this._computeRanges(seriesList)
       var yMin = ranges.yMin, yMax = ranges.yMax
       function yOf(v) { return padT + plotH * (1 - (v - yMin) / (yMax - yMin)) }
-      // 日期横轴:按所有序列全部点排序后均分
-      var allDates = []
-      seriesList.forEach(function(s) {
-        s.points.forEach(function(p) {
-          if (allDates.indexOf(p.reportDate) < 0) allDates.push(p.reportDate)
-        })
-      })
-      allDates.sort()
-      function xOf(dateStr) {
-        if (allDates.length <= 1) return padL + plotW / 2
-        var idx = allDates.indexOf(dateStr)
-        if (idx < 0) return padL
-        return padL + plotW * (allDates.length === 1 ? 0.5 : idx / (allDates.length - 1))
+
+      // X 轴日期全集:优先使用 allPeriodDates(含缺失期),否则从 series 推导
+      var allDates = this.allPeriodDates && this.allPeriodDates.length > 0
+        ? this.allPeriodDates
+        : (function() {
+            var set = {}
+            seriesList.forEach(function(s) {
+              s.points.forEach(function(p) {
+                if (p && p.reportDate) set[p.reportDate] = true
+              })
+            })
+            var arr = Object.keys(set)
+            arr.sort()
+            return arr
+          })()
+
+      function xOf(dateStr) { return this._xOf(dateStr, allDates, padL, plotW) }.call(this)
+
+      // 取最新序列的 unit 作为基准(供单位不一致标记)
+      var latestUnit = ''
+      var lastSeries = seriesList[seriesList.length - 1]
+      if (lastSeries && lastSeries.points && lastSeries.points.length > 0) {
+        var lastPt = lastSeries.points[lastSeries.points.length - 1]
+        latestUnit = lastPt && lastPt.unit ? lastPt.unit : ''
       }
 
       ctx.clearRect(0, 0, w, h)
+
       // 网格(4 条横线 + 2 条纵线)
       ctx.strokeStyle = BrandColors.slateGhost
       ctx.lineWidth = 1
@@ -182,6 +275,7 @@ export default {
         ctx.moveTo(padL, gy); ctx.lineTo(w - padR, gy)
         ctx.stroke()
       }
+
       // Y 轴刻度文字
       ctx.fillStyle = BrandColors.appTextSubtle
       ctx.font = '10px sans-serif'
@@ -189,35 +283,80 @@ export default {
       for (var ti = 0; ti <= 3; ti++) {
         var tv = yMin + (yMax - yMin) * (1 - ti / 3)
         var ty = padT + plotH * (ti / 3)
-        ctx.fillText(self._fmtNum(tv), padL - 4, ty + 3)
+        ctx.fillText(this._fmtNum(tv), padL - 4, ty + 3)
+      }
+
+      // 参考范围背景带(refLow/refHigh 非 null 时绘制)
+      if (this.refLow != null && this.refHigh != null) {
+        var refTop = yOf(this.refHigh)
+        var refBot = yOf(this.refLow)
+        ctx.fillStyle = BrandColors.emerald50
+        ctx.fillRect(padL, refTop, plotW, refBot - refTop)
+        // 上边界虚线
+        ctx.strokeStyle = BrandColors.successLight3
+        ctx.lineWidth = 1
+        ctx.setLineDash([4, 4])
+        ctx.beginPath()
+        ctx.moveTo(padL, refTop)
+        ctx.lineTo(w - padR, refTop)
+        ctx.stroke()
+        // 下边界虚线
+        ctx.beginPath()
+        ctx.moveTo(padL, refBot)
+        ctx.lineTo(w - padR, refBot)
+        ctx.stroke()
+        ctx.setLineDash([])
+        // 标签
+        ctx.fillStyle = BrandColors.success
+        ctx.font = '9px sans-serif'
+        ctx.textAlign = 'left'
+        ctx.fillText('↑' + this._fmtNum(this.refHigh), w - padR - 50, refTop - 2)
+        ctx.fillText('↓' + this._fmtNum(this.refLow), w - padR - 50, refBot + 12)
       }
+
       // 折线 + 数据点 + 数值
       var palette = [BrandColors.primary, BrandColors.infoSky, BrandColors.success, BrandColors.primary, BrandColors.danger, BrandColors.wealth]
       seriesList.forEach(function(s, si) {
         var color = s.color || palette[si % palette.length]
         ctx.strokeStyle = color
         ctx.lineWidth = 2
-        ctx.beginPath()
+        ctx.fillStyle = color
         var started = false
+        var prevX = null, prevValidV = null
         s.points.forEach(function(p) {
-          var v = parseFloat(p.value)
+          var v = parseFloat(p.numericValue != null ? p.numericValue : p.value)
           if (isNaN(v)) return
-          var x = xOf(p.reportDate), y = yOf(v)
-          if (!started) { ctx.moveTo(x, y); started = true } else { ctx.lineTo(x, y) }
+          var x = xOf(p.reportDate)
+          var y = yOf(v)
+          // 缺失期断线:prevX 存在但当前日期不在 allDates 中 → 不连线
+          if (prevX != null && allDates.indexOf(p.reportDate) < 0) {
+            started = false
+            prevX = null
+            prevValidV = null
+            return
+          }
+          if (!started) { ctx.moveTo(x, y); started = true }
+          else { ctx.lineTo(x, y) }
+          prevX = x
+          prevValidV = v
         })
         ctx.stroke()
         // 数据点 + 值
         s.points.forEach(function(p) {
-          var v = parseFloat(p.value)
+          var v = parseFloat(p.numericValue != null ? p.numericValue : p.value)
           if (isNaN(v)) return
+          if (allDates.indexOf(p.reportDate) < 0) return
           var x = xOf(p.reportDate), y = yOf(v)
           ctx.fillStyle = color
           ctx.beginPath(); ctx.arc(x, y, 3.5, 0, 2 * Math.PI); ctx.fill()
-          if (self.showValues) {
+          if (self.showValues || self.mode === 'pair') {
+            var valText = self._fmtValue(p)
+            var star = ''
+            if (p && p.unit && latestUnit && p.unit !== latestUnit) star = '*'
             ctx.fillStyle = BrandColors.slate600
             ctx.font = '10px sans-serif'
             ctx.textAlign = 'center'
-            ctx.fillText(self._fmtValue(p), x, y - 8)
+            ctx.fillText(valText + star, x, y - 8)
           }
         })
         // 序列名(最右端上方)
@@ -225,21 +364,25 @@ export default {
         ctx.font = '11px sans-serif'
         ctx.textAlign = 'right'
         var last = s.points[s.points.length - 1]
-        if (last && !isNaN(parseFloat(last.value))) {
-          ctx.fillText(s.name || '', xOf(last.reportDate), yOf(parseFloat(last.value)) - 14)
+        if (last && !isNaN(parseFloat(last.numericValue != null ? last.numericValue : last.value))) {
+          var lv = parseFloat(last.numericValue != null ? last.numericValue : last.value)
+          ctx.fillText(s.name || '', xOf(last.reportDate), yOf(lv) - 14)
         }
       })
-      // X 轴日期标签(首/中/末)
-      ctx.fillStyle = BrandColors.appTextSubtle
-      ctx.font = '10px sans-serif'
-      ctx.textAlign = 'center'
-      if (allDates.length > 0) {
-        ctx.fillText(String(allDates[0]).slice(5), padL, h - 8)
-        if (allDates.length > 1) {
-          var midIdx = Math.floor((allDates.length - 1) / 2)
-          ctx.fillText(String(allDates[midIdx]).slice(5), padL + plotW * (midIdx / (allDates.length - 1)), h - 8)
-          ctx.fillText(String(allDates[allDates.length - 1]).slice(5), w - padR, h - 8)
-        }
+
+      // X 轴日期标签(按 allPeriodDates.length 抽稀)
+      if (this.showAxisLabels && allDates.length > 0) {
+        var indices = axisLabelIndices(allDates.length)
+        ctx.fillStyle = BrandColors.appTextSubtle
+        ctx.font = '10px sans-serif'
+        ctx.textAlign = 'center'
+        indices.forEach(function(idx) {
+          var dateStr = allDates[idx]
+          var x = xOf(dateStr)
+          var shortDate = String(dateStr).slice(5)
+          var uploadStar = self._hasUploadDateFor(dateStr, seriesList) ? '*' : ''
+          ctx.fillText(shortDate + uploadStar, x, h - 8)
+        })
       }
     },
 
@@ -249,14 +392,63 @@ export default {
       return v.toFixed(2)
     },
     _fmtValue: function(p) {
-      var v = parseFloat(p.value)
+      var v = parseFloat(p.numericValue != null ? p.numericValue : p.value)
       if (isNaN(v)) return '--'
       return this._fmtNum(v) + (p.unit ? p.unit : '')
     },
 
     onCanvasTap: function(e) {
-      // 一期无点击交互需求,预留:点击最近数据点可 emit 'pointTap'
-      this.$emit('chartTap')
+      // 预留:点击最近数据点可 emit 'pointTap' { index, point, x, y }
+      if (!this._canvasNode || !this.ctx) return
+      var win = uni.getWindowInfo ? uni.getWindowInfo() : { windowWidth: 375, pixelRatio: 2 }
+      var scale = (win.windowWidth || 375) / 750
+      var clientX = (e && e.touches && e.touches[0] && e.touches[0].clientX)
+        || (e && e.clientX)
+        || 0
+      var clientY = (e && e.touches && e.touches[0] && e.touches[0].clientY)
+        || (e && e.clientY)
+        || 0
+      var canvasX = (clientX - this._canvasLeft) / scale
+      var canvasY = (clientY - this._canvasTop) / scale
+      // 找最近点(简单线性扫描,P2-2 优化点)
+      var seriesList = this._safeSeries(this.series)
+      var allDates = this.allPeriodDates && this.allPeriodDates.length > 0
+        ? this.allPeriodDates
+        : (function() {
+            var set = {}
+            seriesList.forEach(function(s) {
+              s.points.forEach(function(p) {
+                if (p && p.reportDate) set[p.reportDate] = true
+              })
+            })
+            var arr = Object.keys(set); arr.sort()
+            return arr
+          })()
+      var self = this
+      function xOf(dateStr) {
+        if (!allDates || allDates.length <= 1) return this._xOf(dateStr, allDates, 34, this.canvasWidth - 34 - 14)
+        var idx = allDates.indexOf(dateStr)
+        if (idx < 0) return 34
+        return 34 + (this.canvasWidth - 34 - 14) * (idx / (allDates.length - 1))
+      }
+      var ranges = this._computeRanges(seriesList)
+      var yMin = ranges.yMin, yMax = ranges.yMax
+      function yOf(v) { return 16 + (this.canvasHeight - 16 - 26) * (1 - (v - yMin) / (yMax - yMin)) }
+      var closestIdx = -1, closestDist = Infinity
+      seriesList.forEach(function(s, si) {
+        s.points.forEach(function(p, pi) {
+          var v = parseFloat(p.numericValue != null ? p.numericValue : p.value)
+          if (isNaN(v)) return
+          var px = xOf.call(self, p.reportDate)
+          var py = yOf.call(self, v)
+          var d = Math.sqrt((canvasX - px) * (canvasX - px) + (canvasY - py) * (canvasY - py))
+          if (d < closestDist) { closestDist = d; closestIdx = pi }
+        })
+      })
+      if (closestIdx >= 0 && seriesList[0] && seriesList[0].points[closestIdx]) {
+        var pt = seriesList[0].points[closestIdx]
+        this.$emit('pointTap', { index: closestIdx, point: pt, x: xOf.call(self, pt.reportDate), y: yOf.call(self, pt.numericValue || pt.value) })
+      }
     }
   }
 }
@@ -302,4 +494,4 @@ export default {
   font-size: 22rpx;
   color: $facade-text-slate-deep;
 }
-</style>
+</style>

+ 11 - 1
cfc-frontend/utils/api.js

@@ -3434,7 +3434,17 @@ export const ssoLogin = (ticket) =>
 
 // ============ 指标变化曲线 / 速查 / 关联 ============
 // 规范入口(singular per URL)。后端契约见 design.md §6.1-6.4。
-/** 指标趋势(曲线页):{ subjectId, definitionIds:[] } */
+/** 成员已有指标时对应的报告类型列表(S7 补漏导出) */
+export const getIndicatorSourceTypes = (params) => request('/api/indicator/source-types', 'POST', params || {})
+/** 报告指标(含上一期对照):{ reportId, withPrevious } */
+export const getReportIndicators = (params) => request('/api/health/report/indicators', 'POST', params || {})
+/** 指标时间轴:{ subjectId, definitionIds, sourceType?, fromDate?, toDate?, granularity?, sourceKind? } */
+export const getIndicatorTimeline = (params) => request('/api/indicator/trend', 'POST', params || {})
+/** 期次列表:{ subjectId, sourceType? } */
+export const getIndicatorPeriods = (params) => request('/api/indicator/periods', 'POST', params || {})
+/** [admin] 存量时序回填:{ subjectId?, reportId?, limit?, dryRun? } */
+export const backfillIndicatorValues = (params) => request('/api/admin/indicator/backfill', 'POST', params || {})
+/** 指标趋势(曲线页,保留向后兼容别名):{ subjectId, definitionIds:[] } */
 export const getIndicatorTrend = (params) => request('/api/indicator/trend', 'POST', params || {})
 /** 变化幅度排名:{ subjectId, reportType?, category?, scope:'adjacent'|'first-vs-latest', orderBy:'up'|'down'|'magnitude', limit } */
 export const getIndicatorChangeRanking = (params) => request('/api/indicator/change-ranking', 'POST', params || {})