Просмотр исходного кода

feat: P1-1 即时多巴胺反馈实现

- 后端: DailyFeedback entity/mapper/service/controller (3 端点)
- 数据库: schema.sql + DatabaseInitializer migration 103
- 前端: FeedbackToast, MilestoneCelebration, DailySummary 组件
- 预设文案引擎: 12 场景触发 + 里程碑判定
- Vuex 反馈状态模块 + parent-index 集成
- 微行动完成后自动触发即时反馈
iwt 4 месяцев назад
Родитель
Сommit
5b22eb9a8c

+ 21 - 0
cfc-backend/src/main/java/com/etotem/cfc/config/DatabaseInitializer.java

@@ -5449,6 +5449,27 @@ try {
     } catch (Exception e) {
         log.warn("创建micro_action_records表失败: {}", e.getMessage());
     }
+
+    // 迁移103: 创建 daily_feedback 表(AI/预设每日健康反馈)
+    try {
+        jdbcTemplate.execute("CREATE TABLE IF NOT EXISTS daily_feedback (" +
+            "id BIGINT AUTO_INCREMENT PRIMARY KEY, " +
+            "user_id BIGINT NOT NULL COMMENT '用户ID', " +
+            "child_id BIGINT NOT NULL COMMENT '家庭成员ID', " +
+            "feedback_date DATETIME NOT NULL COMMENT '反馈日期', " +
+            "feedback_type VARCHAR(20) DEFAULT 'daily' COMMENT '反馈类型: daily/weekly/milestone', " +
+            "content VARCHAR(500) NOT NULL COMMENT 'AI生成的反馈文本', " +
+            "milestone_event VARCHAR(100) COMMENT '关联的里程碑事件', " +
+            "is_read TINYINT DEFAULT 0 COMMENT '是否已读: 0未读 1已读', " +
+            "source VARCHAR(20) DEFAULT 'preset' COMMENT '来源: ai_generated / preset', " +
+            "created_at DATETIME DEFAULT CURRENT_TIMESTAMP, " +
+            "INDEX idx_child_date (child_id, feedback_date), " +
+            "INDEX idx_feedback_type (feedback_type)" +
+        ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='每日健康反馈'");
+        log.info("已创建daily_feedback表");
+    } catch (Exception e) {
+        log.warn("创建daily_feedback表失败: {}", e.getMessage());
+    }
     }
 
     private void runMigration82() {

+ 67 - 0
cfc-backend/src/main/java/com/etotem/cfc/controller/DailyFeedbackController.java

@@ -0,0 +1,67 @@
+package com.etotem.cfc.controller;
+
+import com.etotem.cfc.common.Result;
+import com.etotem.cfc.entity.DailyFeedback;
+import com.etotem.cfc.service.DailyFeedbackService;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.tags.Tag;
+import org.springframework.web.bind.annotation.*;
+
+import javax.annotation.Resource;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * 每日反馈接口 — 即时多巴胺反馈(L2: AI/预设深度反馈)
+ */
+@Tag(name = "每日反馈", description = "AI/预设每日健康反馈")
+@RestController
+@RequestMapping("/api/feedback")
+public class DailyFeedbackController {
+
+    @Resource
+    private DailyFeedbackService dailyFeedbackService;
+
+    @Operation(summary = "获取今日反馈")
+    @PostMapping("/today")
+    public Result<Map<String, Object>> today(
+            @RequestBody Map<String, Object> params,
+            @RequestAttribute("userId") Long userId) {
+        Long childId = params.get("childId") != null
+                ? Long.valueOf(params.get("childId").toString()) : null;
+        DailyFeedback feedback = dailyFeedbackService.getTodayFeedback(childId);
+
+        // Auto-generate if none exists
+        if (feedback == null && childId != null) {
+            feedback = dailyFeedbackService.generatePresetFeedback(userId, childId);
+        }
+
+        Map<String, Object> result = new HashMap<>();
+        result.put("feedback", feedback);
+        result.put("hasFeedback", feedback != null);
+        return Result.success(result);
+    }
+
+    @Operation(summary = "标记反馈为已读")
+    @PostMapping("/read")
+    public Result<String> markAsRead(@RequestBody Map<String, Object> params) {
+        Long id = params.get("id") != null
+                ? Long.valueOf(params.get("id").toString()) : null;
+        if (id == null) {
+            return Result.error("id不能为空");
+        }
+        dailyFeedbackService.markAsRead(id);
+        return Result.success("ok");
+    }
+
+    @Operation(summary = "获取最近反馈列表")
+    @PostMapping("/recent")
+    public Result<List<DailyFeedback>> recent(@RequestBody Map<String, Object> params) {
+        Long childId = params.get("childId") != null
+                ? Long.valueOf(params.get("childId").toString()) : null;
+        int limit = params.get("limit") != null
+                ? Integer.parseInt(params.get("limit").toString()) : 7;
+        return Result.success(dailyFeedbackService.getRecentFeedbacks(childId, limit));
+    }
+}

+ 43 - 0
cfc-backend/src/main/java/com/etotem/cfc/entity/DailyFeedback.java

@@ -0,0 +1,43 @@
+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.io.Serializable;
+import java.util.Date;
+
+@Data
+@TableName("daily_feedback")
+public class DailyFeedback implements Serializable {
+
+    @TableId(type = IdType.AUTO)
+    private Long id;
+
+    /** 用户ID */
+    private Long userId;
+
+    /** 家庭成员ID */
+    private Long childId;
+
+    /** 反馈日期 */
+    private Date feedbackDate;
+
+    /** 反馈类型: daily(每日摘要)/weekly(每周)/milestone(里程碑) */
+    private String feedbackType;
+
+    /** AI生成的反馈文本 */
+    private String content;
+
+    /** 关联的里程碑事件(如有) */
+    private String milestoneEvent;
+
+    /** 是否已读: 0未读 1已读 */
+    private Integer isRead;
+
+    /** 来源: ai_generated / preset */
+    private String source;
+
+    private Date createdAt;
+}

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

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

+ 129 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/DailyFeedbackService.java

@@ -0,0 +1,129 @@
+package com.etotem.cfc.service;
+
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
+import com.etotem.cfc.entity.DailyFeedback;
+import com.etotem.cfc.entity.HealthCheckin;
+import com.etotem.cfc.entity.MicroActionRecord;
+import com.etotem.cfc.mapper.DailyFeedbackMapper;
+import com.etotem.cfc.mapper.HealthCheckinMapper;
+import com.etotem.cfc.mapper.MicroActionRecordMapper;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.stereotype.Service;
+
+import javax.annotation.Resource;
+import java.text.SimpleDateFormat;
+import java.util.*;
+
+@Slf4j
+@Service
+public class DailyFeedbackService {
+
+    @Resource
+    private DailyFeedbackMapper dailyFeedbackMapper;
+
+    @Resource
+    private HealthCheckinMapper healthCheckinMapper;
+
+    @Resource
+    private MicroActionRecordMapper microActionRecordMapper;
+
+    /**
+     * 获取今日反馈
+     */
+    public DailyFeedback getTodayFeedback(Long childId) {
+        if (childId == null) return null;
+        String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
+        return dailyFeedbackMapper.selectOne(
+            new LambdaQueryWrapper<DailyFeedback>()
+                .eq(DailyFeedback::getChildId, childId)
+                .apply("DATE(feedback_date) = {0}", today)
+                .eq(DailyFeedback::getFeedbackType, "daily")
+                .last("LIMIT 1")
+        );
+    }
+
+    /**
+     * 标记反馈为已读
+     */
+    public void markAsRead(Long feedbackId) {
+        DailyFeedback fb = dailyFeedbackMapper.selectById(feedbackId);
+        if (fb != null) {
+            fb.setIsRead(1);
+            dailyFeedbackMapper.updateById(fb);
+        }
+    }
+
+    /**
+     * 获取最近N条反馈
+     */
+    public List<DailyFeedback> getRecentFeedbacks(Long childId, int limit) {
+        if (childId == null) return Collections.emptyList();
+        return dailyFeedbackMapper.selectList(
+            new LambdaQueryWrapper<DailyFeedback>()
+                .eq(DailyFeedback::getChildId, childId)
+                .orderByDesc(DailyFeedback::getFeedbackDate)
+                .last("LIMIT " + limit)
+        );
+    }
+
+    /**
+     * 生成预设反馈(基于当日行为)
+     * 目前使用预设文案,后续可对接AI Gateway
+     */
+    public DailyFeedback generatePresetFeedback(Long userId, Long childId) {
+        if (childId == null) return null;
+
+        // Check if already generated today
+        DailyFeedback existing = getTodayFeedback(childId);
+        if (existing != null) return existing;
+
+        // Check today's activities
+        String today = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
+
+        boolean hasCheckin = healthCheckinMapper.selectCount(
+            new LambdaQueryWrapper<HealthCheckin>()
+                .eq(HealthCheckin::getChildId, childId)
+                .apply("DATE(checkin_date) = {0}", today)
+        ) > 0;
+
+        boolean hasMicroAction = microActionRecordMapper.selectCount(
+            new LambdaQueryWrapper<MicroActionRecord>()
+                .eq(MicroActionRecord::getChildId, childId)
+                .apply("DATE(completed_date) = {0}", today)
+        ) > 0;
+
+        // Generate feedback text
+        String content;
+        if (hasCheckin || hasMicroAction) {
+            content = getRandomEncouragement();
+        } else {
+            content = "今天还没有记录健康行动,从一个小行动开始吧 ☕️";
+        }
+
+        DailyFeedback feedback = new DailyFeedback();
+        feedback.setUserId(userId);
+        feedback.setChildId(childId);
+        feedback.setFeedbackDate(new Date());
+        feedback.setFeedbackType("daily");
+        feedback.setContent(content);
+        feedback.setIsRead(0);
+        feedback.setSource("preset");
+        feedback.setCreatedAt(new Date());
+        dailyFeedbackMapper.insert(feedback);
+        return feedback;
+    }
+
+    private String getRandomEncouragement() {
+        String[] messages = {
+            "太棒了!今天又迈出了健康的一步 🎉",
+            "坚持就是胜利!每天进步一点点 💪",
+            "你的身体正在感谢你的每一个健康选择 🌟",
+            "今天的努力是明天的健康!继续加油 ⭐",
+            "每一个微行动都是对自己的关爱 ❤️",
+            "你今天做得很棒!健康习惯正在养成 🌱",
+            "今天的你已经比昨天更健康了!🔥",
+            "健康是一种生活方式,你今天活出了它!✨"
+        };
+        return messages[new Random().nextInt(messages.length)];
+    }
+}

+ 16 - 0
cfc-backend/src/main/resources/schema.sql

@@ -2950,3 +2950,19 @@ CREATE TABLE IF NOT EXISTS micro_action_records (
     INDEX idx_child_date (child_id, completed_date),
     INDEX idx_user_id (user_id)
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='微行动完成记录';
+
+-- 每日反馈表(AI/预设健康反馈)
+CREATE TABLE IF NOT EXISTS daily_feedback (
+    id BIGINT AUTO_INCREMENT PRIMARY KEY,
+    user_id BIGINT NOT NULL COMMENT '用户ID',
+    child_id BIGINT NOT NULL COMMENT '家庭成员ID',
+    feedback_date DATETIME NOT NULL COMMENT '反馈日期',
+    feedback_type VARCHAR(20) DEFAULT 'daily' COMMENT '反馈类型: daily/weekly/milestone',
+    content VARCHAR(500) NOT NULL COMMENT 'AI生成的反馈文本',
+    milestone_event VARCHAR(100) COMMENT '关联的里程碑事件',
+    is_read TINYINT DEFAULT 0 COMMENT '是否已读: 0未读 1已读',
+    source VARCHAR(20) DEFAULT 'preset' COMMENT '来源: ai_generated / preset',
+    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+    INDEX idx_child_date (child_id, feedback_date),
+    INDEX idx_feedback_type (feedback_type)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='每日健康反馈';

+ 84 - 0
cfc-frontend/components/DailySummary.vue

@@ -0,0 +1,84 @@
+<template>
+  <view class="daily-summary" v-if="feedback">
+    <view class="ds-header">
+      <text class="ds-label">💬 健康小语</text>
+      <text class="ds-dismiss" @click="dismiss">×</text>
+    </view>
+    <text class="ds-content">{{ feedback.content }}</text>
+    <view class="ds-footer">
+      <text class="ds-source">{{ feedback.source === 'ai_generated' ? 'AI生成' : '暖心提醒' }}</text>
+    </view>
+  </view>
+</template>
+
+<script>
+import api from '@/utils/api.js'
+export default {
+  props: {
+    childId: { type: Number, default: null }
+  },
+  data: function() {
+    return {
+      feedback: null,
+      dismissed: false
+    }
+  },
+  created: function() {
+    this.loadFeedback()
+  },
+  methods: {
+    loadFeedback: function() {
+      if (!this.childId) return
+      var self = this
+      api.getTodayFeedback({ childId: self.childId }).then(function(res) {
+        if (res.data && res.data.feedback) {
+          self.feedback = res.data.feedback
+        }
+      }).catch(function() {
+        // silent fail
+      })
+    },
+    dismiss: function() {
+      if (this.feedback && this.feedback.id) {
+        api.markFeedbackRead({ id: this.feedback.id })
+      }
+      this.feedback = null
+      this.$emit('dismiss')
+    }
+  },
+  watch: {
+    childId: function() {
+      this.feedback = null
+      this.loadFeedback()
+    }
+  }
+}
+</script>
+
+<style scoped>
+.daily-summary {
+  background: linear-gradient(135deg, #EBF5FF, #E0F2FE);
+  border-radius: 20rpx;
+  padding: 20rpx 24rpx;
+  margin: 20rpx 20rpx 0 20rpx;
+  border: 1rpx solid #BAE6FD;
+  position: relative;
+}
+.ds-header {
+  display: flex;
+  justify-content: space-between;
+  align-items: center;
+  margin-bottom: 8rpx;
+}
+.ds-label { font-size: 24rpx; font-weight: 600; color: #0369A1; }
+.ds-dismiss {
+  font-size: 36rpx;
+  color: #999;
+  padding: 0 8rpx;
+  line-height: 1;
+}
+.ds-dismiss:active { color: #666; }
+.ds-content { font-size: 28rpx; color: #333; line-height: 1.6; }
+.ds-footer { margin-top: 8rpx; }
+.ds-source { font-size: 20rpx; color: #94A3B8; }
+</style>

+ 65 - 0
cfc-frontend/components/FeedbackToast.vue

@@ -0,0 +1,65 @@
+<template>
+  <view class="feedback-overlay" v-if="visible" @touchmove.stop.prevent>
+    <view class="feedback-toast" :class="{ 'feedback-enter': animating, 'feedback-leave': !animating }">
+      <view class="feedback-icon">{{ icon }}</view>
+      <text class="feedback-text">{{ text }}</text>
+    </view>
+  </view>
+</template>
+
+<script>
+export default {
+  props: {
+    visible: { type: Boolean, default: false },
+    text: { type: String, default: '' },
+    icon: { type: String, default: '✅' },
+    animating: { type: Boolean, default: false }
+  }
+}
+</script>
+
+<style scoped>
+.feedback-overlay {
+  position: fixed;
+  top: 0;
+  left: 0;
+  right: 0;
+  bottom: 0;
+  z-index: 9999;
+  pointer-events: none;
+  display: flex;
+  align-items: center;
+  justify-content: center;
+}
+.feedback-toast {
+  display: flex;
+  flex-direction: column;
+  align-items: center;
+  gap: 12rpx;
+  background: rgba(0,0,0,0.75);
+  border-radius: 24rpx;
+  padding: 40rpx 60rpx;
+  backdrop-filter: blur(4px);
+}
+.feedback-icon { font-size: 80rpx; }
+.feedback-text {
+  font-size: 32rpx;
+  color: #fff;
+  font-weight: 600;
+  text-align: center;
+}
+.feedback-enter {
+  animation: feedbackPopIn 0.3s cubic-bezier(0.175, 0.885, 0.32, 1.275) forwards;
+}
+.feedback-leave {
+  animation: feedbackFadeOut 0.3s ease forwards;
+}
+@keyframes feedbackPopIn {
+  0%   { transform: scale(0.3); opacity: 0; }
+  100% { transform: scale(1); opacity: 1; }
+}
+@keyframes feedbackFadeOut {
+  0%   { opacity: 1; }
+  100% { opacity: 0; }
+}
+</style>

+ 89 - 0
cfc-frontend/components/MilestoneCelebration.vue

@@ -0,0 +1,89 @@
+<template>
+  <view class="celebration-overlay" v-if="visible" @click="dismiss" @touchmove.stop.prevent>
+    <!-- CSS粒子 -->
+    <view
+      class="celebration-particle"
+      v-for="p in particles"
+      :key="p.id"
+      :style="{
+        left: p.left + '%',
+        animationDelay: p.delay + 's',
+        animationDuration: p.duration + 's',
+        background: p.color,
+        width: p.size + 'rpx',
+        height: p.size + 'rpx'
+      }">
+    </view>
+    <!-- 文字 -->
+    <view class="celebration-content">
+      <text class="celebration-title">{{ title }}</text>
+      <text class="celebration-subtitle">{{ subtitle }}</text>
+    </view>
+  </view>
+</template>
+
+<script>
+export default {
+  props: {
+    visible: { type: Boolean, default: false },
+    title: { type: String, default: '' },
+    subtitle: { type: String, default: '' },
+    particles: { type: Array, default: function() { return [] } }
+  },
+  methods: {
+    dismiss: function() {
+      this.$emit('dismiss')
+    }
+  }
+}
+</script>
+
+<style scoped>
+.celebration-overlay {
+  position: fixed;
+  top: 0;
+  left: 0;
+  right: 0;
+  bottom: 0;
+  z-index: 9998;
+  background: rgba(0,0,0,0.6);
+  display: flex;
+  align-items: center;
+  justify-content: center;
+  overflow: hidden;
+}
+.celebration-particle {
+  position: absolute;
+  top: -20rpx;
+  border-radius: 50%;
+  animation: particleFall linear forwards;
+  opacity: 0.9;
+}
+.celebration-content {
+  display: flex;
+  flex-direction: column;
+  align-items: center;
+  gap: 16rpx;
+  z-index: 1;
+  animation: celebrationTextIn 0.5s cubic-bezier(0.175, 0.885, 0.32, 1.275) forwards;
+}
+.celebration-title {
+  font-size: 56rpx;
+  font-weight: 800;
+  color: #fff;
+  text-shadow: 0 4rpx 20rpx rgba(0,0,0,0.3);
+}
+.celebration-subtitle {
+  font-size: 32rpx;
+  color: rgba(255,255,255,0.9);
+}
+@keyframes particleFall {
+  0%   { transform: translateY(-20rpx) rotate(0deg); opacity: 0.9; }
+  50%  { opacity: 1; }
+  100% { transform: translateY(110vh) rotate(720deg); opacity: 0; }
+}
+@keyframes celebrationTextIn {
+  0%   { transform: scale(0) rotate(-10deg); opacity: 0; }
+  100% { transform: scale(1) rotate(0deg); opacity: 1; }
+}
+</style>

+ 36 - 2
cfc-frontend/pages/index/parent-index.vue

@@ -357,6 +357,23 @@
       </view>
     </template>
   </view>
+  <!-- ===== L1 即时反馈:Toast + 庆祝 ===== -->
+  <FeedbackToast
+    :visible="toastVisible"
+    :text="toastText"
+    :icon="toastIcon"
+    :animating="toastAnimating" />
+  <MilestoneCelebration
+    :visible="celebrationVisible"
+    :title="celebrationTitle"
+    :subtitle="celebrationSubtitle"
+    :particles="celebrationParticles"
+    @dismiss="celebrationVisible = false" />
+  <!-- ===== L2 深度反馈:每日健康小语 ===== -->
+  <DailySummary
+    v-if="selectedMemberId && selectedChild && selectedChild.id"
+    :childId="selectedChild.id"
+    @dismiss="onDailySummaryDismiss" />
 </template>
 
 <script>
@@ -374,9 +391,13 @@ import ContactImport from '../../components/ContactImport.vue'
 import RecommendedFeed from '../../components/RecommendedFeed.vue'
 import FamilyMemberStrip from '../../components/FamilyMemberStrip.vue'
 import MicroActionCard from '../../components/MicroActionCard.vue'
+import FeedbackToast from '../../components/FeedbackToast.vue'
+import MilestoneCelebration from '../../components/MilestoneCelebration.vue'
+import DailySummary from '../../components/DailySummary.vue'
+import feedbackEngine from '../../utils/feedback-engine.js'
 
 export default {
-  components: { PageBanner, RecommendedFeed, PlayfulCard, PlayfulButton, BaseBadge, BaseEmpty, BaseLoading, FamilyRelationGraph, WuxingSandbox, ContactCard, ContactImport, FamilyMemberStrip, MicroActionCard },
+  components: { PageBanner, RecommendedFeed, PlayfulCard, PlayfulButton, BaseBadge, BaseEmpty, BaseLoading, FamilyRelationGraph, WuxingSandbox, ContactCard, ContactImport, FamilyMemberStrip, MicroActionCard, FeedbackToast, MilestoneCelebration, DailySummary },
   data() {
     return {
       nickname: '',
@@ -426,7 +447,16 @@ export default {
         'linear-gradient(135deg, #F97316, #FB923C)',
         'linear-gradient(135deg, #6366F1, #818CF8)'
       ],
-      selectedMemberId: null
+      selectedMemberId: null,
+      // L1 即时反馈状态
+      toastVisible: false,
+      toastText: '',
+      toastIcon: '✅',
+      toastAnimating: false,
+      celebrationVisible: false,
+      celebrationTitle: '',
+      celebrationSubtitle: '',
+      celebrationParticles: []
     }
   },
   computed: {
@@ -767,6 +797,10 @@ export default {
     },
     onMicroActionCompleted() {
       this.loadData()
+      feedbackEngine.trigger('micro_action')
+    },
+    onDailySummaryDismiss() {
+      // DailySummary 已关闭,无额外操作
     },
     goMemberDetail(member) {
       if (!member || !member.memberId) return

+ 85 - 0
cfc-frontend/store/feedback.js

@@ -0,0 +1,85 @@
+/**
+ * 健康反馈状态模块
+ * L1即时反馈状态 + L2每日反馈展示状态
+ */
+
+import feedbackEngine from '../utils/feedback-engine.js'
+
+var feedbackStore = {
+  state: {
+    // L1 Toast
+    toastVisible: false,
+    toastText: '',
+    toastIcon: '',
+    toastAnimating: false,
+    // L1 Celebration
+    celebrationVisible: false,
+    celebrationTitle: '',
+    celebrationSubtitle: '',
+    celebrationParticles: [],
+    // L2 Daily summary
+    dailyFeedback: null,
+    dailyFeedbackLoaded: false
+  },
+  mutations: {
+    showToast: function(state, payload) {
+      state.toastText = payload.text
+      state.toastIcon = payload.icon || '✅'
+      state.toastVisible = true
+      state.toastAnimating = true
+    },
+    hideToast: function(state) {
+      state.toastVisible = false
+      state.toastAnimating = false
+    },
+    showCelebration: function(state, payload) {
+      state.celebrationTitle = payload.title
+      state.celebrationSubtitle = payload.subtitle
+      state.celebrationVisible = true
+      // Generate 50 particles
+      var particles = []
+      for (var i = 0; i < 50; i++) {
+        particles.push({
+          id: i,
+          left: Math.random() * 100,
+          delay: Math.random() * 0.5,
+          duration: 1 + Math.random() * 1.5,
+          color: ['#FF6B9D', '#F97316', '#10B981', '#6366F1', '#F59E0B', '#FF8C42'][Math.floor(Math.random() * 6)],
+          size: 8 + Math.floor(Math.random() * 16)
+        })
+      }
+      state.celebrationParticles = particles
+    },
+    hideCelebration: function(state) {
+      state.celebrationVisible = false
+      state.celebrationParticles = []
+    },
+    setDailyFeedback: function(state, feedback) {
+      state.dailyFeedback = feedback
+      state.dailyFeedbackLoaded = true
+    }
+  },
+  actions: {
+    initEngine: function({ commit }) {
+      // Register engine callbacks
+      feedbackEngine.registerCallbacks(
+        function(toastData) {
+          commit('showToast', toastData)
+          // Auto-hide after 2s
+          setTimeout(function() {
+            commit('hideToast')
+          }, 2000)
+        },
+        function(celebrationData) {
+          commit('showCelebration', celebrationData)
+          // Auto-hide after 3s
+          setTimeout(function() {
+            commit('hideCelebration')
+          }, 3000)
+        }
+      )
+    }
+  }
+}
+
+export default feedbackStore

+ 2 - 1
cfc-frontend/store/index.js

@@ -2,6 +2,7 @@ import Vue from 'vue'
 import Vuex from 'vuex'
 
 import tianpan from './modules/tianpan'
+import feedback from './feedback'
 
 Vue.use(Vuex)
 
@@ -164,7 +165,7 @@ const store = new Vuex.Store({
     }
   }
 ,
-  modules: { tianpan }
+  modules: { tianpan, feedback }
 })
 
 export default store

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

@@ -1463,6 +1463,11 @@ export const microActionToday = (data) => request('/api/micro-action/today', 'PO
 export const microActionComplete = (data) => request('/api/micro-action/complete', 'POST', data)
 export const microActionCheckToday = (data) => request('/api/micro-action/check-today', 'POST', data)
 
+// ===== 每日反馈(P1-1 即时多巴胺反馈) =====
+export const getTodayFeedback = (data) => request('/api/feedback/today', 'POST', data)
+export const markFeedbackRead = (data) => request('/api/feedback/read', 'POST', data)
+export const getRecentFeedbacks = (data) => request('/api/feedback/recent', 'POST', data)
+
 // ===== 娲诲姩妯″潡锛堢淮搴︾瓫閫夛級 =====
 export const getActivityList = (data) => request('/api/activity/list', 'POST', data)
 export const getActivityDetail = (id) => request('/api/activity/detail', 'POST', { id })

+ 61 - 0
cfc-frontend/utils/feedback-engine.js

@@ -0,0 +1,61 @@
+/**
+ * 即时多巴胺反馈触发引擎
+ * 判定何时触发什么反馈,协调 Toast/Milestone 组件
+ */
+
+import { getRandomText, getIcon, getSound, formatText } from './feedback-presets.js'
+
+// 存储外部注册的回调
+var _toastCallback = null
+var _celebrationCallback = null
+
+/**
+ * 注册反馈组件回调
+ * @param {Function} toastFn - 接收 {text, icon, sound} 触发 Toast
+ * @param {Function} celebrationFn - 接收 {title, subtitle} 触发全屏庆祝
+ */
+function registerCallbacks(toastFn, celebrationFn) {
+  _toastCallback = toastFn
+  _celebrationCallback = celebrationFn
+}
+
+/**
+ * 触发即时反馈(L1)
+ * @param {string} scene - 场景编码: micro_action/checkin/exercise/sleep/water/milestone_7/first_use/comeback
+ * @param {Object} vars - 模板变量,如 {minutes: 20}
+ */
+function trigger(scene, vars) {
+  var text = getRandomText(scene)
+  var icon = getIcon(scene)
+  var sound = getSound(scene)
+  var formatted = formatText(text, vars)
+
+  // 判断是否为里程碑(需要全屏庆祝)
+  if (scene && scene.indexOf('milestone_') === 0) {
+    var days = scene.replace('milestone_', '')
+    var titles = {
+      '3': '连续3天!',
+      '7': '连续一周!',
+      '14': '连续14天!',
+      '21': '连续21天!',
+      '30': '连续一个月!'
+    }
+    if (_celebrationCallback) {
+      _celebrationCallback({
+        title: titles[days] || '里程碑达成!',
+        subtitle: formatted
+      })
+    }
+  } else {
+    // 普通反馈:Toast
+    if (_toastCallback) {
+      _toastCallback({
+        text: formatted,
+        icon: icon,
+        sound: sound
+      })
+    }
+  }
+}
+
+export { registerCallbacks, trigger }

+ 98 - 0
cfc-frontend/utils/feedback-presets.js

@@ -0,0 +1,98 @@
+/**
+ * 即时多巴胺反馈 — 预设文案 + 音效映射表
+ * L1 即时反馈使用
+ */
+
+// 各场景触发时的文案
+var PRESETS = {
+  micro_action: {
+    texts: ['太棒了!🎉', '好样的!⭐', '一步一个脚印 💪', '健康在积累!🌱'],
+    icon: '✅',
+    sound: 'ding'
+  },
+  checkin: {
+    texts: ['今天又是健康的一天!🌟', '打卡成功!🔥', '坚持就是胜利 💪'],
+    icon: '📅',
+    sound: 'ding'
+  },
+  exercise: {
+    texts: ['今天动了{{minutes}}分钟!💪', '运动让大脑更聪明 🧠'],
+    icon: '🏃',
+    sound: 'light'
+  },
+  sleep: {
+    texts: ['优质睡眠!😴', '好睡眠是最好的免疫力 🌙'],
+    icon: '😴',
+    sound: 'light'
+  },
+  water: {
+    texts: ['补水成功 💧', '身体在感谢你!☕️'],
+    icon: '💧',
+    sound: 'light'
+  },
+  milestone_3: {
+    texts: ['连续3天!你已经超过了50%的新手 💪'],
+    icon: '🔥',
+    sound: 'ascend'
+  },
+  milestone_7: {
+    texts: ['一周了!习惯正在形成 🌱'],
+    icon: '🌱',
+    sound: 'ascend'
+  },
+  milestone_14: {
+    texts: ['两周!坚持就是你的超能力 ⚡'],
+    icon: '⚡',
+    sound: 'ascend'
+  },
+  milestone_21: {
+    texts: ['21天法则!习惯几乎自动化了 🔥'],
+    icon: '🔥',
+    sound: 'ascend'
+  },
+  milestone_30: {
+    texts: ['一个月!你是健康行动派 🏆'],
+    icon: '🏆',
+    sound: 'ascend'
+  },
+  first_use: {
+    texts: ['你的健康之旅开始了!🎉'],
+    icon: '🚀',
+    sound: 'ding'
+  },
+  comeback: {
+    texts: ['欢迎回来!每一次重启都是勇敢的 🌟'],
+    icon: '🌟',
+    sound: 'ding'
+  }
+}
+
+// 获取随机文案
+function getRandomText(scene) {
+  var preset = PRESETS[scene]
+  if (!preset) return ''
+  var list = preset.texts
+  return list[Math.floor(Math.random() * list.length)]
+}
+
+// 获取场景图标
+function getIcon(scene) {
+  var preset = PRESETS[scene]
+  return preset ? preset.icon : '✅'
+}
+
+// 获取场景音效类型
+function getSound(scene) {
+  var preset = PRESETS[scene]
+  return preset ? preset.sound : 'ding'
+}
+
+// 格式化文案(替换变量)
+function formatText(text, vars) {
+  if (!vars) return text
+  return text.replace(/\{\{(\w+)\}\}/g, function(m, key) {
+    return vars[key] !== undefined ? vars[key] : m
+  })
+}
+
+export { PRESETS, getRandomText, getIcon, getSound, formatText }