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

feat(attribution): SOP-ATTRIB 提前放行家庭归因 + 前端接 B2 动态确认问卷

- application.yml: app.attribution.enabled false->true(阶段四 D1 已提前放行)
- utils/api.js: 新增 getAttributionConfirmQuestions -> POST /api/survey/attribution/confirm-questions
- survey-questionnaire.vue: 识别 dimension===family_attribution 走 B2 动态下发,
  按 ConfirmQuestionVO(id/code/group/title/type/options/unit/required/riskLevel/refRange) 渲染,
  支持 date/single/scale/multi/text/number 控件 + 条件题显隐(answeredSummary 重新下发),
  不再把 questionsJson 对象当数组遍历;必填校验 + 按 code 键提交 answersJson
Sisyphus Agent пре 2 недеља
родитељ
комит
3c7432b48b

+ 1 - 1
cfc-backend/src/main/resources/application.yml

@@ -205,7 +205,7 @@ logging:
 app:
   init-test-data: false  # 是否初始化测试/种子数据,生产环境应关闭
   attribution:
-    enabled: false  # 家庭归因全流程开关(E12 合规后置:默认 false,仅测试/mock 数据;真实用户放行=阶段四 D1)
+    enabled: true  # 家庭归因全流程开关(阶段四 D1 已提前放行:生产开启;真实用户走 B2 动态下发)
 
 # Admin 登录配置
 admin:

+ 238 - 16
cfc-frontend/pages/health/survey-questionnaire.vue

@@ -4,37 +4,138 @@
       <text class="header-title">{{ templateTitle }}</text>
       <text class="header-dimension" v-if="templateDimension">适用维度: {{ templateDimension }}</text>
       <text class="header-period" v-if="periodStart || periodEnd">周期: {{ periodStart && formatDate(periodStart) }} - {{ periodEnd && formatDate(periodEnd) }}</text>
+      <text v-if="isAttribution && hasHighRisk" class="header-risk">⚠️ 本问卷包含高风险问题(近 3 个月情绪/睡眠/自伤念头),请如实填写;如有持续失眠、自伤念头或拒学,请及时就医,平台不阻断填写。</text>
     </view>
-    <view class="question-section" v-for="(q, qIdx) in questions" :key="qIdx">
+
+    <view v-if="isAttribution && loading" class="loading-area">
+      <text class="loading-text">问卷加载中...</text>
+    </view>
+    <view v-else-if="isAttribution && !questions.length" class="loading-area">
+      <text class="loading-text">暂无下发题目(模板未就绪或无匹配题目)</text>
+    </view>
+
+    <view class="question-section" v-for="(q, qIdx) in questions" :key="getQuestionKey(q, qIdx)">
       <view class="question-header">
-        <text class="question-num">Q{{ qIdx + 1 }}</text>
-        <text class="question-text">{{ q.text }}</text>
+        <text class="question-num">Q{{ q.id || (qIdx + 1) }}</text>
+        <text class="question-group" v-if="q.group && q.group.length > 0">{{ q.group }}</text>
+        <text class="question-text">{{ q.title || q.text }}</text>
+        <text class="question-required" v-if="q.required">*</text>
+      </view>
+      <view class="question-hint" v-if="q.refRange && q.refRange.length > 0">{{ q.refRange }}</view>
+      <view class="question-high-risk-badge" v-if="q.riskLevel === 'high'">⚠️ 高风险 · 建议专业评估</view>
+
+      <!-- 家庭归因(B2 动态下发):按 ConfirmQuestionVO 类型渲染 -->
+      <view v-if="isAttribution">
+        <!-- date -->
+        <view v-if="q.type === 'date'" class="date-picker-area">
+          <picker mode="date" :value="answers[q.code] || ''" @change="onDateChange(q, $event)">
+            <view class="picker-box" :class="answers[q.code] ? 'picker-set' : ''">
+              <text class="picker-text">{{ answers[q.code] || '请选择日期' }}</text>
+            </view>
+          </picker>
+          <text class="unit-label" v-if="q.unit && q.unit.length > 0">{{ q.unit }}</text>
+        </view>
+
+        <!-- single / scale:单选 -->
+        <view v-else-if="q.type === 'single' || q.type === 'scale'" class="options-list">
+          <view class="option-item"
+                v-for="(opt, oIdx) in q.options"
+                :key="oIdx"
+                :class="(answers[q.code] || '') === opt ? 'option-selected' : ''"
+                @click="setAnswer(q, opt)">
+            <view class="option-radio" :class="(answers[q.code] || '') === opt ? 'radio-checked' : ''"></view>
+            <text class="option-text">{{ opt }}</text>
+            <text class="unit-label" v-if="q.unit && q.unit.length > 0">{{ q.unit }}</text>
+          </view>
+        </view>
+
+        <!-- multi:多选 -->
+        <view v-else-if="q.type === 'multi'" class="options-list">
+          <view class="option-item"
+                v-for="(opt, oIdx) in q.options"
+                :key="oIdx"
+                :class="(answers[q.code] || []).indexOf(opt) > -1 ? 'option-selected' : ''"
+                @click="toggleMulti(q, opt)">
+            <view class="option-checkbox" :class="(answers[q.code] || []).indexOf(opt) > -1 ? 'checkbox-checked' : ''">
+              <text v-if="(answers[q.code] || []).indexOf(opt) > -1" class="check-mark">✓</text>
+            </view>
+            <text class="option-text">{{ opt }}</text>
+            <text class="unit-label" v-if="q.unit && q.unit.length > 0">{{ q.unit }}</text>
+          </view>
+        </view>
+
+        <!-- number:数字输入 -->
+        <view v-else-if="q.type === 'number'" class="text-input-area">
+          <input class="number-input" type="digit" placeholder="请输入数字"
+                 :value="answers[q.code] || ''" @input="onTextInput(q, $event)" />
+          <text class="unit-label" v-if="q.unit && q.unit.length > 0">{{ q.unit }}</text>
+        </view>
+
+        <!-- text / 兜底:文本输入 -->
+        <view v-else class="text-input-area">
+          <input class="text-input" type="text" placeholder="请输入"
+                 :value="answers[q.code] || ''" @input="onTextInput(q, $event)" />
+          <text class="unit-label" v-if="q.unit && q.unit.length > 0">{{ q.unit }}</text>
+        </view>
       </view>
-      <view class="options-list">
-        <view class="option-item" :class="answers[qIdx] === opt ? 'option-selected' : ''" v-for="(opt, oIdx) in q.options" :key="oIdx" @click="selectOption(qIdx, opt)">
+
+      <!-- 普通定期调研:原有单选渲染(索引键) -->
+      <view v-else class="options-list">
+        <view class="option-item" :class="answers[qIdx] === opt ? 'option-selected' : ''"
+              v-for="(opt, oIdx) in q.options" :key="oIdx" @click="selectOption(qIdx, opt)">
           <view class="option-radio" :class="answers[qIdx] === opt ? 'radio-checked' : ''"></view>
           <text class="option-text">{{ opt }}</text>
         </view>
       </view>
     </view>
+
     <view class="footer-area">
-      <button class="btn-submit" :disabled="isSubmitting" @click="handleSubmit">{{ isSubmitting ? '提交中...' : '提交答案' }}</button>
+      <button class="btn-submit" :disabled="isSubmitting || (isAttribution && !questions.length)" @click="handleSubmit">{{ isSubmitting ? '提交中...' : '提交答案' }}</button>
     </view>
   </view>
 </template>
 <script>
-import { getActiveTemplates, submitSurvey } from '../../utils/api.js'
+import { getActiveTemplates, submitSurvey, getAttributionConfirmQuestions } from '../../utils/api.js'
 import fontScaleMixin from '@/mixins/font-scale.js'
 export default {
   mixins: [fontScaleMixin],
-  data() { return { templateId: null, templateTitle: '定期调研', templateDimension: '', questions: [], answers: {}, periodStart: '', periodEnd: '', isSubmitting: false } },
+  data() {
+    return {
+      templateId: null,
+      templateTitle: '定期调研',
+      templateDimension: '',
+      questions: [],
+      answers: {},
+      periodStart: '',
+      periodEnd: '',
+      isSubmitting: false,
+      // 家庭归因(B2 动态下发)
+      isAttribution: false,
+      loading: false,
+      hasHighRisk: false,
+      familyId: '',
+      memberId: '',
+      attributionId: '',
+      answeredSummary: {},
+      _revealTimer: null
+    }
+  },
   onLoad(options) {
     if (options.templateId) this.templateId = parseInt(options.templateId)
     if (options.templateTitle) this.templateTitle = decodeURIComponent(options.templateTitle)
     if (options.templateDimension) this.templateDimension = options.templateDimension
     if (options.periodStart) this.periodStart = options.periodStart
     if (options.periodEnd) this.periodEnd = options.periodEnd
+    if (options.familyId) this.familyId = options.familyId
+    if (options.memberId) this.memberId = options.memberId
+    if (options.attributionId) this.attributionId = options.attributionId
     if (options.questions) { try { this.questions = JSON.parse(decodeURIComponent(options.questions)) } catch(e) { this.questions = [] } }
+    // 家庭归因确认问卷:直接走 B2 动态下发(模板 questionsJson 是对象,不再当数组遍历)
+    if (this.templateDimension === 'family_attribution' || options.dim === 'family_attribution') {
+      this.isAttribution = true
+      this.loadAttributionQuestions()
+      return
+    }
     // 有 templateId 或带 dim 参数(如首页"再次了解"回跳 dim=all)且无内联题目时,加载模板
     if (this.questions.length) return
     if (this.templateId || options.dim) this.loadTemplate()
@@ -42,6 +143,7 @@ export default {
   methods: {
     formatDate(s) { return s ? s.substring(0, 10) : '' },
     selectOption(qIdx, opt) { this.$set(this.answers, qIdx, opt) },
+    getQuestionKey(q, idx) { return (q && q.id) ? q.id : idx },
     async loadTemplate() {
       try {
         var res = await getActiveTemplates()
@@ -59,25 +161,129 @@ export default {
             this.templateId = found.id
             this.templateTitle = found.title || '定期调研'
             this.templateDimension = found.dimension || ''
-            if (found.questionsJson) { try { this.questions = JSON.parse(found.questionsJson) } catch(e) {} }
+            // 家庭归因模板:questionsJson 是对象(含 target/questions),走 B2 动态下发
+            if (found.dimension === 'family_attribution') {
+              this.isAttribution = true
+              this.loadAttributionQuestions()
+              return
+            }
+            if (found.questionsJson) {
+              try {
+                var parsed = JSON.parse(found.questionsJson)
+                if (parsed instanceof Array) this.questions = parsed
+              } catch(e) {}
+            }
           }
         }
       } catch(e) { console.error('加载模板失败', e) }
     },
+    // ===== 家庭归因 B2 动态下发 =====
+    async loadAttributionQuestions() {
+      var self = this
+      this.loading = true
+      try {
+        var famId = this.familyId || uni.getStorageSync('familyId') || ''
+        var memId = this.memberId || uni.getStorageSync('currentMemberId') || uni.getStorageSync('currentChildId') || ''
+        var attrId = this.attributionId || uni.getStorageSync('attributionId') || ''
+        var res = await getAttributionConfirmQuestions(famId, memId, attrId, this.answeredSummary)
+        if (res.code === 200 && res.data) {
+          var list = (res.data.questions instanceof Array) ? res.data.questions : []
+          if (res.data.templateId) this.templateId = res.data.templateId
+          if (res.data.templateTitle) this.templateTitle = res.data.templateTitle
+          this.hasHighRisk = !!res.data.hasHighRisk
+          // 条件题显隐:清理已隐藏题目的答案,保留仍在列表中的答案
+          var keepCodes = {}
+          for (var i = 0; i < list.length; i++) keepCodes[list[i].code] = true
+          for (var key in this.answers) {
+            if (!keepCodes[key]) {
+              delete this.answers[key]
+              delete this.answeredSummary[key]
+            }
+          }
+          // 初始化各题答案(multi → 数组,其余 → 空串)
+          for (var j = 0; j < list.length; j++) {
+            var code = list[j].code
+            if (this.answers[code] === undefined) {
+              this.$set(this.answers, code, list[j].type === 'multi' ? [] : '')
+            }
+          }
+          this.questions = list
+          this.templateDimension = 'family_attribution'
+        } else {
+          console.error('归因问卷加载失败', res)
+          uni.showToast({ title: (res && res.message) || '问卷加载失败', icon: 'none' })
+          this.questions = []
+        }
+      } catch(e) {
+        console.error('归因问卷加载异常', e)
+        uni.showToast({ title: '网络异常,请重试', icon: 'none' })
+        this.questions = []
+      } finally {
+        this.loading = false
+      }
+    },
+    setAnswer(q, value) {
+      this.$set(this.answers, q.code, value)
+      this.$set(this.answeredSummary, q.code, value)
+      // text/number 不作为条件变量,不触发重新下发;其余题型变化可能影响条件题显隐
+      if (q.type !== 'text' && q.type !== 'number') this.triggerReveal()
+    },
+    triggerReveal() {
+      var self = this
+      if (this._revealTimer) clearTimeout(this._revealTimer)
+      this._revealTimer = setTimeout(function() { self.loadAttributionQuestions() }, 350)
+    },
+    onDateChange(q, e) { this.setAnswer(q, e.detail.value) },
+    onTextInput(q, e) {
+      var v = e.detail.value
+      this.answers[q.code] = v
+      this.answeredSummary[q.code] = v
+    },
+    toggleMulti(q, opt) {
+      var arr = this.answers[q.code] || []
+      var idx = arr.indexOf(opt)
+      var next = idx < 0 ? arr.concat([opt]) : arr.slice(0, idx).concat(arr.slice(idx + 1))
+      this.setAnswer(q, next)
+    },
     async handleSubmit() {
       var self = this
-      var memberId = uni.getStorageSync('currentChildId') || uni.getStorageSync('currentMemberId') || uni.getStorageSync('userId') || ''
-      var answersArr = []
-      for (var i = 0; i < this.questions.length; i++) answersArr.push(this.answers[i] || '')
-      var answersJson = JSON.stringify(answersArr)
+      if (this.isSubmitting) return
+      var memberId = this.memberId || uni.getStorageSync('currentChildId') || uni.getStorageSync('currentMemberId') || uni.getStorageSync('userId') || ''
       if (!this.templateId || !this.questions.length) { uni.showToast({ title: '问卷未加载,请从调研列表进入', icon: 'none' }); return }
+      // 必填校验(家庭归因题:按 code 键;普通调研:按索引键)
+      var missing = []
+      for (var i = 0; i < this.questions.length; i++) {
+        var q = this.questions[i]
+        if (!q.required) continue
+        var val = q.code !== undefined ? this.answers[q.code] : this.answers[i]
+        var empty = val === undefined || val === null || val === ''
+        if (!empty && val instanceof Array) empty = val.length === 0
+        if (empty) missing.push(q.id || (i + 1))
+      }
+      if (missing.length > 0) { uni.showToast({ title: '请完成必填题', icon: 'none' }); return }
       this.isSubmitting = true
       try {
+        var answersJson
+        if (this.isAttribution) {
+          // 家庭归因:以题目 code 为键的 JSON 对象(供 B1 归因分析消费)
+          var obj = {}
+          for (var k = 0; k < this.questions.length; k++) {
+            var qk = this.questions[k]
+            var vk = this.answers[qk.code]
+            if (vk !== undefined && vk !== null && vk !== '') obj[qk.code] = vk
+          }
+          answersJson = JSON.stringify(obj)
+        } else {
+          var arr = []
+          for (var m = 0; m < this.questions.length; m++) arr.push(this.answers[m] || '')
+          answersJson = JSON.stringify(arr)
+        }
         var d = { memberId: memberId, templateId: this.templateId, answersJson: answersJson }
         if (this.periodStart) d.periodStart = this.periodStart
         if (this.periodEnd) d.periodEnd = this.periodEnd
         var res = await submitSurvey(d)
         if (res.code === 200) { uni.showToast({ title: '提交成功', icon: 'success' }); setTimeout(function(){ uni.navigateTo({ url: '/pages/health/survey-history?memberId=' + (memberId || '') }) }, 1200) }
+        else uni.showToast({ title: res.message || '提交失败', icon: 'none' })
       } catch(e) { uni.showToast({ title: e.message || '提交失败', icon: 'none' }) }
       finally { this.isSubmitting = false }
     }
@@ -90,17 +296,33 @@ export default {
 .header-title{font-size: calc(32rpx * var(--font-scale, 1));font-weight:bold;color:$facade-text-strong;display:block;margin-bottom: 8rpx}
 .header-dimension{font-size: calc(24rpx * var(--font-scale, 1));color:$facade-text-muted;display:block;margin-bottom: 4rpx}
 .header-period{font-size: calc(24rpx * var(--font-scale, 1));color:$brand-primary;display:block}
+.header-risk{margin-top:12rpx;font-size: calc(23rpx * var(--font-scale, 1));color:$status-danger-strong;background:$status-danger-soft;border-radius:12rpx;padding:12rpx 16rpx;display:block;line-height:1.5}
+.loading-area{padding: 80rpx 24rpx;text-align:center}
+.loading-text{font-size: calc(26rpx * var(--font-scale, 1));color:$facade-text-muted}
 .question-section{background:$app-surface;margin: 16rpx 24rpx;border-radius:24rpx;padding: 24rpx;box-shadow:0 2rpx 12rpx rgba(0,0,0,0.06)}
-.question-header{display:flex;align-items:flex-start;margin-bottom: 16rpx}
+.question-header{display:flex;align-items:flex-start;margin-bottom: 16rpx;flex-wrap:wrap}
 .question-num{font-size: calc(24rpx * var(--font-scale, 1));font-weight:bold;color:$brand-primary;margin-right: 12rpx;flex-shrink:0}
+.question-group{font-size: calc(20rpx * var(--font-scale, 1));color:$brand-primary;background:$brand-primary-soft;border-radius:8rpx;padding:2rpx 12rpx;margin-right: 12rpx;flex-shrink:0}
 .question-text{font-size: calc(26rpx * var(--font-scale, 1));color:$facade-text-strong;flex:1}
+.question-required{color:$status-danger;font-weight:bold;margin-left:4rpx;flex-shrink:0}
+.question-hint{font-size: calc(22rpx * var(--font-scale, 1));color:$facade-text-muted;margin-bottom: 10rpx;line-height:1.4}
+.question-high-risk-badge{display:inline-block;font-size: calc(22rpx * var(--font-scale, 1));color:$status-danger-strong;background:$status-danger-soft;border:1rpx solid $danger-line;border-radius:10rpx;padding:4rpx 14rpx;margin-bottom: 14rpx}
 .option-item{display:flex;align-items:center;padding: 16rpx 0;border-bottom:1rpx solid $facade-fill}
 .option-item:last-child{border-bottom:none}
 .option-radio{width:28rpx;height:28rpx;border-radius:50%;border:2rpx solid $facade-border-soft;margin-right: 16rpx;flex-shrink:0}
 .radio-checked{border-color:$brand-primary;background:$brand-primary}
-.option-text{font-size: calc(26rpx * var(--font-scale, 1));color:$facade-text-strong}
+.option-checkbox{width:28rpx;height:28rpx;border-radius:8rpx;border:2rpx solid $facade-border-soft;margin-right: 16rpx;flex-shrink:0;display:flex;align-items:center;justify-content:center}
+.checkbox-checked{border-color:$brand-primary;background:$brand-primary}
+.check-mark{color:$app-surface;font-size: 20rpx;line-height:1}
+.option-text{font-size: calc(26rpx * var(--font-scale, 1));color:$facade-text-strong;flex:1}
 .option-selected .option-text{color:$brand-primary;font-weight:bold}
+.unit-label{font-size: calc(22rpx * var(--font-scale, 1));color:$facade-text-muted;margin-left: 8rpx;flex-shrink:0}
+.date-picker-area,.text-input-area,.number-input-area{display:flex;align-items:center}
+.picker-box{background:$uni-primary-pale;border:1rpx solid $facade-border-soft;border-radius:14rpx;padding: 18rpx 22rpx;min-width: 320rpx;flex:1}
+.picker-set{border-color:$brand-primary}
+.picker-text{font-size: calc(26rpx * var(--font-scale, 1));color:$facade-text-strong}
+.text-input,.number-input{background:$uni-primary-pale;border:1rpx solid $facade-border-soft;border-radius:14rpx;padding: 18rpx 22rpx;font-size: calc(26rpx * var(--font-scale, 1));color:$facade-text-strong;flex:1;min-height: 48rpx}
 .footer-area{padding: 20rpx 24rpx}
 .btn-submit{background:$brand-primary;color:$app-surface;border:none;border-radius:16rpx;font-size:calc(30rpx * var(--font-scale, 1));font-weight:bold;height:80rpx;line-height:80rpx}
 .btn-submit[disabled]{background:#ffb47a}
-</style>
+</style>

+ 9 - 0
cfc-frontend/utils/api.js

@@ -2224,6 +2224,15 @@ export const getSurveyStatus = (data) => request('/api/survey/status', 'POST', d
 export const getActiveTemplates = () => request('/api/survey/template/active', 'POST', {})
 export const submitSurvey = (data) => request('/api/survey/submit', 'POST', data)
 export const getSurveyHistory = (data) => request('/api/survey/history', 'POST', data)
+// 家庭归因动态确认问卷(B2 条件路由):按对象/年龄/结论下发第八章题目子集
+// answeredSummary: 已答题目 code→value,用于条件题显隐(后端按 answeredSummary 求值)
+export const getAttributionConfirmQuestions = (familyId, memberId, attributionId, answeredSummary) =>
+  request('/api/survey/attribution/confirm-questions', 'POST', {
+    familyId: familyId || undefined,
+    memberId: memberId || undefined,
+    attributionId: attributionId || undefined,
+    answeredSummary: answeredSummary || {}
+  })
 
 // ===== 寰鍔紙P0 鏈夋晥鍚姩锛� =====
 export const microActionList = () => request('/api/micro-action/list', 'POST', {})