瀏覽代碼

feat: 关系能量分析重设计(v20260604.2) — 后端6API+前端3页+Chatflow集成

## 后端
- 新增 RelationAnalysisRecord 实体+Repository (会话记录+成员快照JSON)
- 新增 RelationAnalysisService (6方法: start/list/detail/delete/send/history)
- 新增 RelationAnalysisController (6个REST端点)
- DifyService: 新增 invokeRelationChatflow (Chatflow方式+模拟回退)
- ChatMessage: 新增 relationRecordId 字段+repository查询
- ConfigService: 新增 dify.chatflow.relation_app_id, relation.types

## 前端
- pages/relations/analysis-select.vue: 多成员选择+提问页
- pages/relations/analysis-chat.vue: AI对话界面
- pages/relations/analysis-records.vue: 历史记录列表
- pages/relations/index.vue: 新增"新建分析"入口+最近记录预览
- pages.json: 注册3个新页面路由

## 管理后台
- settings: 新增"关系类型配置"和"Dify AI 配置"卡片

## 测试
- 修复 UserServiceTest (命盘→能量盘)
- 183 tests run, 0 failures, 5 skipped
- 更新 test-coverage-report.md

## 遗留代码提交 (继承自之前未提交变更)
- AuthInterceptor/WebMvcConfig/User/PricingController
- ChartService/ChatService/OrderService/UserService/InterventionService
- ControllerIntegrationTest/ChatServiceTest (签名变更兼容)
liaoxg 5 月之前
父節點
當前提交
d0cabe0767
共有 27 個文件被更改,包括 2283 次插入 和 50 次删除
  1. 163 0
      admin/src/views/settings/index.vue
  2. 4 1
      client/pages.json
  3. 326 0
      client/pages/relations/analysis-chat.vue
  4. 270 0
      client/pages/relations/analysis-records.vue
  5. 350 0
      client/pages/relations/analysis-select.vue
  6. 185 5
      client/pages/relations/index.vue
  7. 20 2
      docs/test-coverage-report.md
  8. 1 1
      num-server/src/main/java/com/etotem/num/config/WebMvcConfig.java
  9. 29 9
      num-server/src/main/java/com/etotem/num/controller/PricingController.java
  10. 212 0
      num-server/src/main/java/com/etotem/num/controller/RelationAnalysisController.java
  11. 7 1
      num-server/src/main/java/com/etotem/num/entity/ChatMessage.java
  12. 62 0
      num-server/src/main/java/com/etotem/num/entity/RelationAnalysisRecord.java
  13. 1 1
      num-server/src/main/java/com/etotem/num/entity/User.java
  14. 33 3
      num-server/src/main/java/com/etotem/num/interceptor/AuthInterceptor.java
  15. 1 0
      num-server/src/main/java/com/etotem/num/repository/ChatMessageRepository.java
  16. 16 0
      num-server/src/main/java/com/etotem/num/repository/RelationAnalysisRecordRepository.java
  17. 4 4
      num-server/src/main/java/com/etotem/num/service/ChartService.java
  18. 1 1
      num-server/src/main/java/com/etotem/num/service/ChatService.java
  19. 28 2
      num-server/src/main/java/com/etotem/num/service/ConfigService.java
  20. 212 0
      num-server/src/main/java/com/etotem/num/service/DifyService.java
  21. 2 2
      num-server/src/main/java/com/etotem/num/service/InterventionService.java
  22. 34 1
      num-server/src/main/java/com/etotem/num/service/OrderService.java
  23. 267 0
      num-server/src/main/java/com/etotem/num/service/RelationAnalysisService.java
  24. 33 5
      num-server/src/main/java/com/etotem/num/service/UserService.java
  25. 16 6
      num-server/src/test/java/com/etotem/num/controller/ControllerIntegrationTest.java
  26. 5 5
      num-server/src/test/java/com/etotem/num/service/ChatServiceTest.java
  27. 1 1
      num-server/src/test/java/com/etotem/num/service/UserServiceTest.java

+ 163 - 0
admin/src/views/settings/index.vue

@@ -85,6 +85,62 @@
         </div>
       </el-card>
 
+      <!-- Card: 超级会员配置 -->
+      <el-card shadow="hover" class="config-card">
+        <template #header>
+          <div class="card-header">
+            <span>超级会员配置</span>
+            <el-tooltip :content="resetTooltipContent(superMemberKeys)" placement="top">
+              <el-button size="small" text type="primary" @click="handleReset(superMemberKeys)">
+                恢复初始值
+              </el-button>
+            </el-tooltip>
+          </div>
+        </template>
+        <div class="card-body">
+          <div class="field-item">
+            <div class="field-main">
+              <span class="field-label">超级会员年费</span>
+              <el-input-number
+                v-model="configValues['pricing.super_member']"
+                :min="1" :max="999999" :step="100" :precision="0"
+                controls-position="right"
+              />
+              <span class="field-unit">元</span>
+            </div>
+            <div class="field-hint">固定价 ¥1,314/年,无种子价</div>
+          </div>
+          <div class="field-item">
+            <div class="field-main">
+              <span class="field-label">直推佣金率</span>
+              <el-input-number
+                v-model="configValues['commission.super_member.direct_rate']"
+                :min="0" :max="100" :step="1" :precision="0"
+                controls-position="right"
+              />
+              <span class="field-unit">%</span>
+            </div>
+            <div class="field-hint" v-if="superMemberFee > 0">
+              每笔 ¥{{ superMemberFee }}:直接 ¥{{ superDirectCommission }} / 上级 ¥{{ superUpstreamCommission }} / 平台 ¥{{ superPlatformCommission }}
+            </div>
+          </div>
+          <div class="field-item">
+            <div class="field-main">
+              <span class="field-label">上级佣金率</span>
+              <el-input-number
+                v-model="configValues['commission.super_member.upstream_rate']"
+                :min="0" :max="50" :step="1" :precision="0"
+                controls-position="right"
+              />
+              <span class="field-unit">%</span>
+            </div>
+            <div class="field-hint" v-if="superMemberFee > 0">
+              (每笔 ¥{{ superMemberFee }} 年费中上级分成)
+            </div>
+          </div>
+        </div>
+      </el-card>
+
       <!-- Card 2: B端佣金配置 -->
       <el-card shadow="hover" class="config-card">
         <template #header>
@@ -270,6 +326,91 @@
           </div>
         </div>
       </el-card>
+
+      <!-- Card: 关系类型配置 -->
+      <el-card shadow="hover" class="config-card">
+        <template #header>
+          <div class="card-header">
+            <span>关系类型配置</span>
+            <el-tooltip :content="resetTooltipContent(relationTypeKeys)" placement="top">
+              <el-button size="small" text type="primary" @click="handleReset(relationTypeKeys)">
+                恢复初始值
+              </el-button>
+            </el-tooltip>
+          </div>
+        </template>
+        <div class="card-body">
+          <div class="field-item">
+            <div class="field-main" style="flex-direction: column; align-items: stretch;">
+              <span class="field-label" style="margin-bottom: 8px;">关系类型列表(JSON)</span>
+              <el-input
+                v-model="configValues['relation.types']"
+                type="textarea"
+                :rows="6"
+                placeholder='[{"value":"spouse","label":"夫妻"},...]'
+              />
+            </div>
+            <div class="field-hint" style="margin-left: 0;">
+              配置页面上显示的关系类型列表,格式为 JSON 数组,每个元素含 value(唯一标识)和 label(显示名称)。
+            </div>
+          </div>
+        </div>
+      </el-card>
+
+      <!-- Card: Dify AI 配置 -->
+      <el-card shadow="hover" class="config-card">
+        <template #header>
+          <div class="card-header">
+            <span>Dify AI 配置</span>
+          </div>
+        </template>
+        <div class="card-body">
+          <div class="field-item">
+            <div class="field-main">
+              <span class="field-label">Chart Chatflow App ID</span>
+              <el-input
+                v-model="storageValues['dify.workflow.app_id']"
+                placeholder="Dify Workflow App ID"
+                style="width: 300px;"
+              />
+            </div>
+            <div class="field-hint">能量盘解读 Workflow</div>
+          </div>
+          <div class="field-item">
+            <div class="field-main">
+              <span class="field-label">关系分析 Chatflow App ID</span>
+              <el-input
+                v-model="storageValues['dify.chatflow.relation_app_id']"
+                placeholder="Dify Chatflow App ID"
+                style="width: 300px;"
+              />
+            </div>
+            <div class="field-hint">关系能量分析对话 Chatflow(v20260604.2)</div>
+          </div>
+          <div class="field-item">
+            <div class="field-main">
+              <span class="field-label">关系合盘 Workflow App ID</span>
+              <el-input
+                v-model="storageValues['dify.workflow.relation_app_id']"
+                placeholder="Dify Workflow App ID"
+                style="width: 300px;"
+              />
+            </div>
+            <div class="field-hint">旧版关系合盘解读 Workflow</div>
+          </div>
+          <div class="field-item">
+            <div class="field-main">
+              <span class="field-label">号码分析 Workflow App ID</span>
+              <el-input
+                v-model="storageValues['dify.workflow.number_analysis_app_id']"
+                placeholder="Dify Workflow App ID"
+                style="width: 300px;"
+              />
+            </div>
+            <div class="field-hint">八星号码分析 Workflow</div>
+          </div>
+        </div>
+      </el-card>
     </div>
   </div>
 </template>
@@ -287,6 +428,9 @@ const VALUE_TYPES: Record<string, 'price' | 'percent' | 'plain' | 'string'> = {
   'pricing.practitioner.seed_limit': 'plain',
   'pricing.practitioner.seed_period_end': 'string',
   'pricing.annual': 'price',
+  'pricing.super_member': 'price',
+  'commission.super_member.direct_rate': 'percent',
+  'commission.super_member.upstream_rate': 'percent',
   'commission.practitioner.l1': 'price',
   'commission.practitioner.l1_cend': 'price',
   'commission.practitioner.l2': 'price',
@@ -306,6 +450,9 @@ const ALL_CONFIG_KEYS: string[] = [
   'pricing.practitioner.seed_limit',
   'pricing.practitioner.seed_period_end',
   'pricing.annual',
+  'pricing.super_member',
+  'commission.super_member.direct_rate',
+  'commission.super_member.upstream_rate',
   'commission.practitioner.l1',
   'commission.practitioner.l1_cend',
   'commission.practitioner.l2',
@@ -330,6 +477,9 @@ const SEED_DEFAULTS: Record<string, string> = {
   'pricing.practitioner.seed_limit': '300',
   'pricing.practitioner.seed_period_end': '2027-12-31T23:59:59',
   'pricing.annual': '13100',
+  'pricing.super_member': '131400',
+  'commission.super_member.direct_rate': '3000',
+  'commission.super_member.upstream_rate': '500',
   'commission.practitioner.l1': '50000',
   'commission.practitioner.l1_cend': '20000',
   'commission.practitioner.l2': '10000',
@@ -348,9 +498,11 @@ const SEED_DEFAULTS: Record<string, string> = {
 /* ──────────── Card key groups ──────────── */
 
 const pricingKeys = ['pricing.practitioner.seed', 'pricing.practitioner.standard', 'pricing.practitioner.seed_limit', 'pricing.practitioner.seed_period_end', 'pricing.annual']
+const superMemberKeys = ['pricing.super_member', 'commission.super_member.direct_rate', 'commission.super_member.upstream_rate']
 const bCommissionKeys = ['commission.practitioner.l1', 'commission.practitioner.l1_cend', 'commission.practitioner.l2']
 const cCommissionKeys = ['commission.annual.direct_rate', 'commission.annual.upstream_rate']
 const planKeys = ['commerce.category.practitioner_plan.commission_rate', 'commission.practitioner_plan.referral_rate', 'commission.practitioner_plan.upstream_rate', 'plan_request.min_price', 'plan_request.max_price', 'plan_request.max_negotiation_rounds']
+const relationTypeKeys = ['relation.types']
 
 /* ──────────── Field labels ──────────── */
 
@@ -360,6 +512,9 @@ const FIELD_LABELS: Record<string, string> = {
   'pricing.practitioner.seed_limit': '种子价名额上限',
   'pricing.practitioner.seed_period_end': '种子价有效期',
   'pricing.annual': 'C端年费',
+  'pricing.super_member': '超级会员年费',
+  'commission.super_member.direct_rate': '超级会员直推佣金率',
+  'commission.super_member.upstream_rate': '超级会员上级佣金率',
   'commission.practitioner.l1': 'L1 佣金—能量师推荐',
   'commission.practitioner.l1_cend': 'L1 佣金—C端推荐',
   'commission.practitioner.l2': 'L2 佣金',
@@ -492,6 +647,14 @@ const directCommission = computed(() => (annualFee.value * directRate.value).toF
 const upstreamCommission = computed(() => (annualFee.value * upstreamRate.value).toFixed(2))
 const platformCommission = computed(() => (annualFee.value - annualFee.value * directRate.value - annualFee.value * upstreamRate.value).toFixed(2))
 
+/** Super member previews */
+const superMemberFee = computed(() => configValues['pricing.super_member'] || 0)
+const superDirectRate = computed(() => (configValues['commission.super_member.direct_rate'] || 0) / 100)
+const superUpstreamRate = computed(() => (configValues['commission.super_member.upstream_rate'] || 0) / 100)
+const superDirectCommission = computed(() => (superMemberFee.value * superDirectRate.value).toFixed(2))
+const superUpstreamCommission = computed(() => (superMemberFee.value * superUpstreamRate.value).toFixed(2))
+const superPlatformCommission = computed(() => (superMemberFee.value - superMemberFee.value * superDirectRate.value - superMemberFee.value * superUpstreamRate.value).toFixed(2))
+
 /** Card 4 — 人工方案预览 */
 const PLAN_EXAMPLE = 299
 const planCommissionRate = computed(() => (configValues['commerce.category.practitioner_plan.commission_rate'] || 0) / 100)

+ 4 - 1
client/pages.json

@@ -4,8 +4,11 @@
     {"path": "pages/records/index", "style": {"navigationBarTitleText": "分析记录"}},
     {"path": "pages/relations/index", "style": {"navigationBarTitleText": "关系能量分析"}},
     {"path": "pages/relations/add-relation", "style": {"navigationBarTitleText": "添加关系人", "backgroundColor": "#F8F6F1"}},
-    {"path": "pages/relations/chart-compare", "style": {"navigationBarTitleText": "关系命盘对比", "backgroundColor": "#0c0a1a"}},
+    {"path": "pages/relations/chart-compare", "style": {"navigationBarTitleText": "关系能量盘对比", "backgroundColor": "#0c0a1a"}},
     {"path": "pages/relations/number-analysis", "style": {"navigationBarTitleText": "八星号码分析", "backgroundColor": "#0c0a1a"}},
+    {"path": "pages/relations/analysis-select", "style": {"navigationBarTitleText": "选择分析成员", "backgroundColor": "#0c0a1a"}},
+    {"path": "pages/relations/analysis-chat", "style": {"navigationBarTitleText": "关系能量对话", "backgroundColor": "#0c0a1a"}},
+    {"path": "pages/relations/analysis-records", "style": {"navigationBarTitleText": "分析记录", "backgroundColor": "#0c0a1a"}},
     {"path": "pages/analysis/index", "style": {"navigationBarTitleText": "分析"}},
     {"path": "pages/profile/index", "style": {"navigationBarTitleText": "我的"}},
     {"path": "pages/payment/index", "style": {"navigationBarTitleText": "VIP 开通"}},

+ 326 - 0
client/pages/relations/analysis-chat.vue

@@ -0,0 +1,326 @@
+<template>
+  <view class="page-chat">
+    <!-- ========== Member Bar ========== -->
+    <view class="member-bar">
+      <text class="member-bar-title">分析成员</text>
+      <view class="member-avatars">
+        <view v-for="(m, i) in memberList" :key="i" class="mini-avatar">
+          <text class="mini-avatar-text">{{ m.name ? m.name[0] : '?' }}</text>
+        </view>
+      </view>
+    </view>
+
+    <!-- ========== Chat Messages ========== -->
+    <scroll-view
+      class="chat-scroll"
+      scroll-y
+      :scroll-into-view="scrollToId"
+      scroll-with-animation
+      @scrolltolower="onScrollToLower"
+    >
+      <view class="chat-list">
+        <view
+          v-for="(msg, idx) in messages"
+          :key="msg.id || idx"
+          :id="'msg-' + idx"
+          class="msg-item"
+          :class="msg.role === 'user' ? 'msg-user' : 'msg-ai'"
+        >
+          <view v-if="msg.role === 'ai'" class="msg-avatar ai-avatar">AI</view>
+          <view class="msg-bubble" :class="msg.role === 'user' ? 'bubble-user' : 'bubble-ai'">
+            <text class="msg-content">{{ msg.content }}</text>
+          </view>
+          <view v-if="msg.role === 'user'" class="msg-avatar user-avatar">我</view>
+        </view>
+
+        <!-- Loading indicator -->
+        <view v-if="loadingResponse" class="msg-item msg-ai">
+          <view class="msg-avatar ai-avatar">AI</view>
+          <view class="msg-bubble bubble-ai">
+            <text class="thinking-text">正在思考...</text>
+          </view>
+        </view>
+      </view>
+    </scroll-view>
+
+    <!-- ========== Input Bar ========== -->
+    <view class="input-bar">
+      <view class="input-wrap">
+        <input
+          v-model="inputText"
+          class="chat-input"
+          placeholder="输入您的问题..."
+          placeholder-class="input-placeholder"
+          :disabled="loadingResponse"
+          @confirm="sendMessage"
+          confirm-type="send"
+        />
+      </view>
+      <view
+        class="btn-send"
+        :class="{ disabled: !inputText.trim() || loadingResponse }"
+        @click="sendMessage"
+      >
+        <text class="btn-send-text">发送</text>
+      </view>
+    </view>
+  </view>
+</template>
+
+<script setup>
+import { ref, computed, nextTick, watch } from 'vue'
+import { onLoad } from '@dcloudio/uni-app'
+import request from '@/utils/api'
+
+const recordId = ref(null)
+const messages = ref([])
+const inputText = ref('')
+const loadingResponse = ref(false)
+const memberList = ref([])
+
+const scrollToId = ref('')
+
+onLoad(async (query) => {
+  if (query && query.recordId) {
+    recordId.value = query.recordId
+    await Promise.all([loadMembers(), loadHistory()])
+  }
+})
+
+async function loadMembers() {
+  try {
+    const detail = await request.post('/relation/analysis/detail', { id: recordId.value })
+    if (detail && detail.memberSnapshot) {
+      try {
+        const parsed = JSON.parse(detail.memberSnapshot)
+        memberList.value = Array.isArray(parsed) ? parsed : []
+      } catch (e) {
+        memberList.value = []
+      }
+    }
+    if (detail && detail.title) {
+      uni.setNavigationBarTitle({ title: detail.title })
+    }
+  } catch (e) {
+    // ignore
+  }
+}
+
+async function loadHistory() {
+  try {
+    const msgs = await request.post('/relation/analysis/chat/history', { recordId: recordId.value })
+    messages.value = msgs || []
+    scrollToBottom()
+  } catch (e) {
+    messages.value = []
+  }
+}
+
+function scrollToBottom() {
+  nextTick(() => {
+    scrollToId.value = 'msg-' + (messages.value.length - 1)
+  })
+}
+
+async function sendMessage() {
+  const text = inputText.value.trim()
+  if (!text || loadingResponse.value) return
+
+  // Optimistically add user message
+  const tempMsg = { id: Date.now(), role: 'user', content: text }
+  messages.value.push(tempMsg)
+  inputText.value = ''
+  scrollToBottom()
+
+  loadingResponse.value = true
+  try {
+    const res = await request.post('/relation/analysis/chat/send', {
+      recordId: recordId.value,
+      query: text
+    })
+    if (res && res.answer) {
+      messages.value.push({ id: Date.now() + 1, role: 'ai', content: res.answer })
+    } else {
+      messages.value.push({ id: Date.now() + 1, role: 'ai', content: 'AI 解读服务暂时不可用,请稍后再试。' })
+    }
+  } catch (e) {
+    messages.value.push({ id: Date.now() + 1, role: 'ai', content: '发送失败,请重试。' })
+  } finally {
+    loadingResponse.value = false
+    scrollToBottom()
+  }
+}
+
+function onScrollToLower() {
+  // reached top — could load more history if paginated
+}
+</script>
+
+<style scoped lang="scss">
+@import "@/styles/theme.scss";
+
+.page-chat {
+  display: flex;
+  flex-direction: column;
+  height: 100vh;
+  background: var(--color-bg);
+}
+
+/* Member bar */
+.member-bar {
+  display: flex;
+  align-items: center;
+  padding: 10px 16px;
+  background: var(--color-bg-card);
+  border-bottom: 1px solid var(--color-border);
+  gap: 10px;
+}
+.member-bar-title {
+  font-size: 13px;
+  font-weight: 600;
+  color: var(--color-text-secondary);
+}
+.member-avatars {
+  display: flex;
+  gap: 4px;
+}
+.mini-avatar {
+  width: 28px;
+  height: 28px;
+  border-radius: 50%;
+  background: var(--color-brand);
+  display: flex;
+  align-items: center;
+  justify-content: center;
+}
+.mini-avatar-text {
+  font-size: 11px;
+  font-weight: 700;
+  color: var(--color-bg-card);
+}
+
+/* Chat scroll area */
+.chat-scroll {
+  flex: 1;
+  overflow-y: auto;
+  padding: 16px;
+}
+.chat-list {
+  display: flex;
+  flex-direction: column;
+}
+
+/* Message item */
+.msg-item {
+  display: flex;
+  align-items: flex-start;
+  margin-bottom: 16px;
+  gap: 10px;
+}
+.msg-user {
+  justify-content: flex-end;
+}
+.msg-ai {
+  justify-content: flex-start;
+}
+
+.msg-avatar {
+  width: 36px;
+  height: 36px;
+  border-radius: 50%;
+  display: flex;
+  align-items: center;
+  justify-content: center;
+  flex-shrink: 0;
+  font-size: 12px;
+  font-weight: 700;
+}
+.user-avatar {
+  background: var(--color-gold);
+  color: var(--color-bg-card);
+}
+.ai-avatar {
+  background: var(--color-brand);
+  color: var(--color-bg-card);
+}
+
+.msg-bubble {
+  max-width: 72%;
+  padding: 12px 14px;
+  border-radius: 16px;
+  word-break: break-word;
+}
+.bubble-user {
+  background: var(--color-brand);
+  color: var(--color-bg-card);
+  border-bottom-right-radius: 4px;
+}
+.bubble-ai {
+  background: var(--color-bg-card);
+  color: var(--color-text-primary);
+  border-bottom-left-radius: 4px;
+  border: 1px solid var(--color-border);
+}
+.msg-content {
+  font-size: 14px;
+  line-height: 1.6;
+  white-space: pre-wrap;
+}
+
+.thinking-text {
+  font-size: 14px;
+  color: var(--color-text-secondary);
+}
+
+/* Input bar */
+.input-bar {
+  display: flex;
+  align-items: center;
+  padding: 12px 16px;
+  padding-bottom: 24px;
+  background: var(--color-bg-card);
+  border-top: 1px solid var(--color-border);
+  gap: 10px;
+}
+.input-wrap {
+  flex: 1;
+  background: var(--color-bg);
+  border-radius: 22px;
+  padding: 0 16px;
+  height: 44px;
+  display: flex;
+  align-items: center;
+}
+.chat-input {
+  width: 100%;
+  font-size: 15px;
+  color: var(--color-text-primary);
+  background: transparent;
+}
+.input-placeholder {
+  color: var(--color-text-secondary);
+  font-size: 14px;
+}
+.btn-send {
+  width: 60px;
+  height: 40px;
+  background: var(--color-gold);
+  border-radius: 20px;
+  display: flex;
+  align-items: center;
+  justify-content: center;
+  flex-shrink: 0;
+}
+.btn-send:active {
+  transform: scale(0.95);
+}
+.btn-send.disabled {
+  opacity: 0.5;
+  pointer-events: none;
+}
+.btn-send-text {
+  color: var(--color-bg-card);
+  font-size: 14px;
+  font-weight: 700;
+}
+</style>

+ 270 - 0
client/pages/relations/analysis-records.vue

@@ -0,0 +1,270 @@
+<template>
+  <view class="page-records">
+    <!-- ========== Header ========== -->
+    <view class="header-bar">
+      <text class="header-title">分析记录</text>
+      <view class="btn-new" @click="goNewAnalysis">
+        <text class="btn-new-text">+ 新建</text>
+      </view>
+    </view>
+
+    <!-- ========== Loading ========== -->
+    <view v-if="loading" class="loading-state">
+      <view v-for="i in 3" :key="i" class="skeleton-card" />
+    </view>
+
+    <!-- ========== Empty ========== -->
+    <view v-else-if="records.length === 0" class="empty-state">
+      <text class="empty-icon">📋</text>
+      <text class="empty-text">暂无分析记录</text>
+      <text class="empty-desc">选择关系人并开启关系能量分析</text>
+      <view class="btn-empty-new" @click="goNewAnalysis">
+        <text class="btn-empty-new-text">新建分析</text>
+      </view>
+    </view>
+
+    <!-- ========== Records List ========== -->
+    <view v-else class="records-list">
+      <view
+        v-for="item in records"
+        :key="item.id"
+        class="record-card"
+        @click="goChat(item.id)"
+      >
+        <view class="record-top">
+          <text class="record-title">{{ item.title || '关系分析' }}</text>
+          <text class="record-time">{{ formatTime(item.createTime) }}</text>
+        </view>
+        <view class="record-meta">
+          <text class="record-status" :class="item.status === 'active' ? 'status-active' : 'status-archived'">
+            {{ item.status === 'active' ? '进行中' : '已归档' }}
+          </text>
+        </view>
+        <view class="record-actions">
+          <view class="record-action action-delete" @click.stop="handleDelete(item.id)">
+            删除
+          </view>
+        </view>
+      </view>
+    </view>
+  </view>
+</template>
+
+<script setup>
+import { ref } from 'vue'
+import { onShow } from '@dcloudio/uni-app'
+import request from '@/utils/api'
+
+const records = ref([])
+const loading = ref(false)
+
+onShow(() => {
+  fetchRecords()
+})
+
+async function fetchRecords() {
+  loading.value = true
+  try {
+    records.value = await request.post('/relation/analysis/list', {})
+  } catch (e) {
+    records.value = []
+  } finally {
+    loading.value = false
+  }
+}
+
+function goNewAnalysis() {
+  uni.navigateTo({ url: '/pages/relations/analysis-select' })
+}
+
+function goChat(recordId) {
+  uni.navigateTo({ url: '/pages/relations/analysis-chat?recordId=' + recordId })
+}
+
+function handleDelete(id) {
+  uni.showModal({
+    title: '确认删除',
+    content: '删除后聊天记录将丢失,确定要删除吗?',
+    success: async (res) => {
+      if (res.confirm) {
+        try {
+          await request.post('/relation/analysis/delete', { id })
+          uni.showToast({ title: '删除成功', icon: 'success' })
+          fetchRecords()
+        } catch (e) {
+          uni.showToast({ title: '删除失败', icon: 'none' })
+        }
+      }
+    }
+  })
+}
+
+function formatTime(time) {
+  if (!time) return ''
+  const d = new Date(time)
+  const month = (d.getMonth() + 1).toString().padStart(2, '0')
+  const day = d.getDate().toString().padStart(2, '0')
+  const hour = d.getHours().toString().padStart(2, '0')
+  const min = d.getMinutes().toString().padStart(2, '0')
+  return `${month}-${day} ${hour}:${min}`
+}
+</script>
+
+<style scoped lang="scss">
+@import "@/styles/theme.scss";
+
+.page-records {
+  min-height: 100vh;
+  background: var(--color-bg);
+  padding: 16px;
+}
+
+.header-bar {
+  display: flex;
+  align-items: center;
+  justify-content: space-between;
+  margin-bottom: 20px;
+}
+.header-title {
+  font-size: 20px;
+  font-weight: 700;
+  color: var(--color-text-primary);
+}
+.btn-new {
+  background: var(--color-gold);
+  border-radius: 999px;
+  padding: 8px 18px;
+}
+.btn-new:active {
+  transform: scale(0.97);
+}
+.btn-new-text {
+  color: var(--color-bg-card);
+  font-size: 14px;
+  font-weight: 600;
+}
+
+/* Loading */
+.loading-state {
+  display: flex;
+  flex-direction: column;
+  gap: 12px;
+}
+.skeleton-card {
+  height: 100px;
+  background: linear-gradient(90deg, var(--color-bg-secondary) 25%, var(--color-bg) 50%, var(--color-bg-secondary) 75%);
+  background-size: 400px 100%;
+  animation: shimmer 1.5s ease-in-out infinite;
+  border-radius: 14px;
+}
+@keyframes shimmer {
+  0% { background-position: -200px 0; }
+  100% { background-position: 200px 0; }
+}
+
+/* Empty */
+.empty-state {
+  display: flex;
+  flex-direction: column;
+  align-items: center;
+  padding-top: 80px;
+}
+.empty-icon {
+  font-size: 48px;
+  margin-bottom: 16px;
+}
+.empty-text {
+  font-size: 16px;
+  font-weight: 600;
+  color: var(--color-text-primary);
+  margin-bottom: 8px;
+}
+.empty-desc {
+  font-size: 13px;
+  color: var(--color-text-secondary);
+  margin-bottom: 24px;
+}
+.btn-empty-new {
+  background: var(--color-brand);
+  border-radius: 12px;
+  padding: 12px 32px;
+}
+.btn-empty-new:active {
+  transform: scale(0.97);
+}
+.btn-empty-new-text {
+  color: var(--color-bg-card);
+  font-size: 15px;
+  font-weight: 600;
+}
+
+/* Records */
+.records-list {
+  display: flex;
+  flex-direction: column;
+  gap: 12px;
+}
+.record-card {
+  background: var(--color-bg-card);
+  border-radius: 14px;
+  padding: 16px;
+  box-shadow: var(--shadow-card);
+}
+.record-card:active {
+  transform: scale(0.98);
+}
+.record-top {
+  display: flex;
+  justify-content: space-between;
+  align-items: flex-start;
+  margin-bottom: 8px;
+}
+.record-title {
+  font-size: 15px;
+  font-weight: 600;
+  color: var(--color-text-primary);
+  flex: 1;
+  margin-right: 10px;
+}
+.record-time {
+  font-size: 12px;
+  color: var(--color-text-secondary);
+  flex-shrink: 0;
+}
+.record-meta {
+  margin-bottom: 10px;
+}
+.record-status {
+  font-size: 12px;
+  font-weight: 500;
+  padding: 2px 8px;
+  border-radius: 4px;
+}
+.status-active {
+  background: #E8F5E9;
+  color: #2E7D32;
+}
+.status-archived {
+  background: var(--color-bg-secondary);
+  color: var(--color-text-secondary);
+}
+.record-actions {
+  display: flex;
+  justify-content: flex-end;
+  border-top: 1px solid var(--color-border);
+  padding-top: 10px;
+}
+.record-action {
+  font-size: 13px;
+  font-weight: 500;
+  padding: 4px 12px;
+  border-radius: 6px;
+}
+.record-action:active {
+  transform: scale(0.97);
+}
+.action-delete {
+  color: #D94A4A;
+  background: transparent;
+}
+</style>

+ 350 - 0
client/pages/relations/analysis-select.vue

@@ -0,0 +1,350 @@
+<template>
+  <view class="page-select">
+    <!-- ========== Member Selection ========== -->
+    <view class="section">
+      <text class="section-title">选择分析成员</text>
+      <text class="section-desc">选择您自己以及想分析的关系人(至少选2人)</text>
+
+      <!-- Self (always included) -->
+      <view class="member-card self-card">
+        <view class="member-avatar self-avatar">
+          <text class="avatar-text">我</text>
+        </view>
+        <view class="member-info">
+          <text class="member-name">我(本人)</text>
+          <text class="member-detail">{{ userProfile.birthYear }}-{{ userProfile.birthMonth }}-{{ userProfile.birthDay }}</text>
+        </view>
+        <view class="member-checked">
+          <text class="check-icon">✓</text>
+        </view>
+      </view>
+
+      <!-- Relations list -->
+      <view v-if="loading" class="loading-hint">加载关系人...</view>
+      <view v-else-if="relations.length === 0" class="empty-hint">
+        <text>暂无关系人,请先</text>
+        <text class="link-text" @click="goAddRelation">添加关系人</text>
+      </view>
+      <view
+        v-for="item in relations"
+        :key="item.id"
+        class="member-card"
+        :class="{ selected: selectedIds.includes(item.id) }"
+        @click="toggleRelation(item.id)"
+      >
+        <view class="member-avatar">
+          <text class="avatar-text">{{ item.name ? item.name[0] : '?' }}</text>
+        </view>
+        <view class="member-info">
+          <text class="member-name">{{ item.name || '未知' }}</text>
+          <text class="member-detail">{{ relationTypeLabel(item.relationType) }} · {{ item.birthDateText || '' }}</text>
+        </view>
+        <view class="member-checkbox">
+          <view class="checkbox-box" :class="{ checked: selectedIds.includes(item.id) }">
+            <text v-if="selectedIds.includes(item.id)" class="checkbox-icon">✓</text>
+          </view>
+        </view>
+      </view>
+    </view>
+
+    <!-- ========== Question Input ========== -->
+    <view class="section">
+      <text class="section-title">您想咨询什么?</text>
+      <view class="input-wrap">
+        <textarea
+          v-model="question"
+          class="question-input"
+          placeholder="例如:我们之间的能量是否匹配?或者想了解某方面的关系影响..."
+          placeholder-class="input-placeholder"
+          maxlength="500"
+          :auto-height="true"
+        />
+      </view>
+      <text class="char-count">{{ question.length }}/500</text>
+    </view>
+
+    <!-- ========== Submit ========== -->
+    <view class="submit-bar">
+      <view
+        class="btn-submit"
+        :class="{ disabled: !canSubmit || submitting }"
+        @click="handleStart"
+      >
+        <text class="btn-submit-text">{{ submitting ? '分析中...' : '开始分析' }}</text>
+      </view>
+    </view>
+  </view>
+</template>
+
+<script setup>
+import { ref, computed } from 'vue'
+import { onShow } from '@dcloudio/uni-app'
+import { useUserStore } from '@/stores/user'
+import request from '@/utils/api'
+
+const userStore = useUserStore()
+const relations = ref([])
+const loading = ref(false)
+const selectedIds = ref([])
+const question = ref('')
+const submitting = ref(false)
+
+const userProfile = computed(() => ({
+  birthYear: userStore.birthYear || '----',
+  birthMonth: userStore.birthMonth || '--',
+  birthDay: userStore.birthDay || '--'
+}))
+
+const canSubmit = computed(() => selectedIds.value.length >= 1 && question.value.trim().length > 0)
+
+const relationTypeMap = {
+  spouse: '夫妻',
+  parent_child: '亲子',
+  colleague: '同事',
+  friend: '朋友',
+  superior: '上下级'
+}
+
+function relationTypeLabel(type) {
+  return relationTypeMap[type] || type || '未知'
+}
+
+onShow(() => {
+  fetchRelations()
+})
+
+async function fetchRelations() {
+  loading.value = true
+  try {
+    relations.value = await request.post('/relation/list', {})
+  } catch (e) {
+    relations.value = []
+  } finally {
+    loading.value = false
+  }
+}
+
+function toggleRelation(id) {
+  const idx = selectedIds.value.indexOf(id)
+  if (idx > -1) {
+    selectedIds.value.splice(idx, 1)
+  } else {
+    selectedIds.value.push(id)
+  }
+}
+
+function goAddRelation() {
+  uni.navigateTo({ url: '/pages/relations/add-relation' })
+}
+
+async function handleStart() {
+  if (!canSubmit.value || submitting.value) return
+  submitting.value = true
+  try {
+    const res = await request.post('/relation/analysis/start', {
+      relationIds: selectedIds.value,
+      question: question.value.trim()
+    })
+    if (res && res.id) {
+      uni.redirectTo({
+        url: '/pages/relations/analysis-chat?recordId=' + res.id
+      })
+    }
+  } catch (e) {
+    uni.showToast({ title: '启动分析失败', icon: 'none' })
+  } finally {
+    submitting.value = false
+  }
+}
+</script>
+
+<style scoped lang="scss">
+@import "@/styles/theme.scss";
+
+.page-select {
+  min-height: 100vh;
+  background: var(--color-bg);
+  padding: 16px;
+}
+
+.section {
+  margin-bottom: 24px;
+}
+.section-title {
+  display: block;
+  font-size: 17px;
+  font-weight: 700;
+  color: var(--color-text-primary);
+  margin-bottom: 6px;
+}
+.section-desc {
+  display: block;
+  font-size: 13px;
+  color: var(--color-text-secondary);
+  margin-bottom: 14px;
+}
+
+/* Member cards */
+.member-card {
+  display: flex;
+  align-items: center;
+  background: var(--color-bg-card);
+  border-radius: 14px;
+  padding: 14px 16px;
+  margin-bottom: 10px;
+  border: 2px solid transparent;
+  transition: border-color 0.2s;
+}
+.member-card:active {
+  transform: scale(0.98);
+}
+.member-card.selected {
+  border-color: var(--color-gold);
+  background: linear-gradient(135deg, var(--color-bg-card), rgba(201, 168, 76, 0.06));
+}
+.self-card {
+  border-color: var(--color-brand);
+  opacity: 0.85;
+}
+
+.member-avatar {
+  width: 44px;
+  height: 44px;
+  border-radius: 50%;
+  background: var(--color-brand);
+  display: flex;
+  align-items: center;
+  justify-content: center;
+  margin-right: 14px;
+  flex-shrink: 0;
+}
+.self-avatar {
+  background: var(--color-gold);
+}
+.avatar-text {
+  font-size: 16px;
+  font-weight: 700;
+  color: var(--color-bg-card);
+}
+
+.member-info {
+  flex: 1;
+  min-width: 0;
+}
+.member-name {
+  display: block;
+  font-size: 15px;
+  font-weight: 600;
+  color: var(--color-text-primary);
+  margin-bottom: 3px;
+}
+.member-detail {
+  display: block;
+  font-size: 12px;
+  color: var(--color-text-secondary);
+}
+
+.member-checkbox {
+  margin-left: 10px;
+  flex-shrink: 0;
+}
+.checkbox-box {
+  width: 22px;
+  height: 22px;
+  border-radius: 50%;
+  border: 2px solid var(--color-border);
+  display: flex;
+  align-items: center;
+  justify-content: center;
+  transition: all 0.2s;
+}
+.checkbox-box.checked {
+  background: var(--color-gold);
+  border-color: var(--color-gold);
+}
+.checkbox-icon {
+  color: var(--color-bg-card);
+  font-size: 12px;
+  font-weight: 700;
+}
+
+.member-checked {
+  margin-left: 10px;
+}
+.check-icon {
+  font-size: 18px;
+  color: var(--color-gold);
+  font-weight: 700;
+}
+
+/* Loading / Empty */
+.loading-hint, .empty-hint {
+  text-align: center;
+  padding: 30px 0;
+  font-size: 14px;
+  color: var(--color-text-secondary);
+}
+.link-text {
+  color: var(--color-brand);
+  font-weight: 600;
+  text-decoration: underline;
+}
+
+/* Question input */
+.input-wrap {
+  background: var(--color-bg-card);
+  border-radius: 12px;
+  padding: 14px;
+  border: 1px solid var(--color-border);
+}
+.question-input {
+  width: 100%;
+  min-height: 100px;
+  font-size: 15px;
+  color: var(--color-text-primary);
+  line-height: 1.6;
+  background: transparent;
+}
+.input-placeholder {
+  color: var(--color-text-secondary);
+  font-size: 14px;
+}
+.char-count {
+  display: block;
+  text-align: right;
+  font-size: 12px;
+  color: var(--color-text-secondary);
+  margin-top: 4px;
+  padding-right: 4px;
+}
+
+/* Submit */
+.submit-bar {
+  position: sticky;
+  bottom: 0;
+  padding: 12px 0 24px;
+  background: var(--color-bg);
+}
+.btn-submit {
+  width: 100%;
+  height: 50px;
+  background: linear-gradient(135deg, var(--color-brand), darken(var(--color-brand), 4%));
+  border-radius: 14px;
+  display: flex;
+  align-items: center;
+  justify-content: center;
+}
+.btn-submit:active {
+  transform: scale(0.97);
+  opacity: 0.9;
+}
+.btn-submit.disabled {
+  opacity: 0.5;
+  pointer-events: none;
+}
+.btn-submit-text {
+  color: var(--color-bg-card);
+  font-size: 17px;
+  font-weight: 700;
+}
+</style>

+ 185 - 5
client/pages/relations/index.vue

@@ -31,14 +31,54 @@
       <!-- Header bar -->
       <view class="header-bar">
         <text class="header-title">关系能量分析</text>
-        <view class="btn-add" @click="goAddRelation">
-          <text class="btn-add-text">+ 添加</text>
+        <view class="header-actions">
+          <view class="btn-add" @click="goAddRelation">
+            <text class="btn-add-text">+ 添加</text>
+          </view>
+        </view>
+      </view>
+
+      <!-- ========== New Analysis Entry ========== -->
+      <view class="new-analysis-card" @click="goNewAnalysis">
+        <text class="new-analysis-icon">🔮</text>
+        <view class="new-analysis-info">
+          <text class="new-analysis-title">新建关系分析</text>
+          <text class="new-analysis-desc">选择成员并提问,AI 深度解读关系能量</text>
+        </view>
+        <text class="new-analysis-arrow">›</text>
+      </view>
+
+      <!-- ========== Analysis Records Section ========== -->
+      <view class="section-header">
+        <text class="section-header-title">分析记录</text>
+        <text class="section-header-link" @click="goAllRecords">查看全部 ›</text>
+      </view>
+
+      <view v-if="recordsLoading" class="loading-hint">加载中...</view>
+      <view v-else-if="recentRecords.length === 0" class="empty-records-hint">
+        <text>暂无分析记录,开始你的第一次关系分析</text>
+      </view>
+      <view v-else class="records-preview">
+        <view
+          v-for="item in recentRecords"
+          :key="item.id"
+          class="record-preview-card"
+          @click="goChat(item.id)"
+        >
+          <text class="record-preview-title">{{ item.title || '关系分析' }}</text>
+          <text class="record-preview-time">{{ formatTime(item.createTime) }}</text>
         </view>
       </view>
 
+      <!-- ========== Relations Section ========== -->
+      <view class="section-header">
+        <text class="section-header-title">我的关系人</text>
+        <text class="section-header-count">({{ relations.length }})</text>
+      </view>
+
       <!-- Loading state -->
       <view v-if="loading" class="loading-state">
-        <view v-for="i in 3" :key="i" class="skeleton-card" />
+        <view v-for="i in 2" :key="i" class="skeleton-card" />
       </view>
 
       <!-- Empty state -->
@@ -47,7 +87,7 @@
           <text class="empty-icon-symbol">+</text>
         </view>
         <text class="empty-text">暂无关系人</text>
-        <text class="empty-desc">添加关系人后,可进行夫妻、亲子、同事等关系能量匹配分析</text>
+        <text class="empty-desc">添加关系人后,可进行关系能量匹配分析</text>
         <view class="btn-empty-add" @click="goAddRelation">
           <text class="btn-empty-add-text">添加关系人</text>
         </view>
@@ -55,7 +95,6 @@
 
       <!-- Relations list -->
       <view v-else class="relations-list">
-        <text class="section-count">我的关系人 ({{ relations.length }})</text>
         <view
           v-for="item in relations"
           :key="item.id"
@@ -90,6 +129,8 @@ import requestInstance from '@/utils/api'
 const userStore = useUserStore()
 const relations = ref([])
 const loading = ref(false)
+const recentRecords = ref([])
+const recordsLoading = ref(false)
 
 const isSuperMember = computed(() => {
   if (!userStore.isVip) return false
@@ -124,6 +165,7 @@ onShow(() => {
   }
   if (isSuperMember.value) {
     fetchRelations()
+    fetchRecentRecords()
   }
 })
 
@@ -138,10 +180,34 @@ async function fetchRelations() {
   }
 }
 
+async function fetchRecentRecords() {
+  recordsLoading.value = true
+  try {
+    const list = await requestInstance.post('/relation/analysis/list', {})
+    recentRecords.value = (list || []).slice(0, 3)
+  } catch (e) {
+    recentRecords.value = []
+  } finally {
+    recordsLoading.value = false
+  }
+}
+
 function goAddRelation() {
   uni.navigateTo({ url: '/pages/relations/add-relation' })
 }
 
+function goNewAnalysis() {
+  uni.navigateTo({ url: '/pages/relations/analysis-select' })
+}
+
+function goChat(recordId) {
+  uni.navigateTo({ url: '/pages/relations/analysis-chat?recordId=' + recordId })
+}
+
+function goAllRecords() {
+  uni.navigateTo({ url: '/pages/relations/analysis-records' })
+}
+
 function goCompare(id) {
   uni.navigateTo({ url: '/pages/relations/chart-compare?id=' + id })
 }
@@ -175,6 +241,14 @@ function handleDelete(id) {
     }
   })
 }
+
+function formatTime(time) {
+  if (!time) return ''
+  const d = new Date(time)
+  const month = (d.getMonth() + 1).toString().padStart(2, '0')
+  const day = d.getDate().toString().padStart(2, '0')
+  return `${month}-${day}`
+}
 </script>
 
 <style scoped lang="scss">
@@ -217,6 +291,112 @@ function handleDelete(id) {
   font-weight: 600;
 }
 
+/* Section header */
+.section-header {
+  display: flex;
+  align-items: center;
+  margin-bottom: 12px;
+  margin-top: 20px;
+}
+.section-header-title {
+  font-size: 15px;
+  font-weight: 700;
+  color: var(--color-text-primary);
+}
+.section-header-count {
+  font-size: 12px;
+  color: var(--color-text-secondary);
+  margin-left: 4px;
+}
+.section-header-link {
+  margin-left: auto;
+  font-size: 13px;
+  color: var(--color-brand);
+  font-weight: 500;
+}
+.section-header-link:active {
+  opacity: 0.7;
+}
+
+/* New analysis entry card */
+.new-analysis-card {
+  display: flex;
+  align-items: center;
+  background: linear-gradient(135deg, var(--color-brand), darken(var(--color-brand), 4%));
+  border-radius: 16px;
+  padding: 16px;
+  margin-bottom: 4px;
+  gap: 12px;
+}
+.new-analysis-card:active {
+  transform: scale(0.98);
+}
+.new-analysis-icon {
+  font-size: 28px;
+  flex-shrink: 0;
+}
+.new-analysis-info {
+  flex: 1;
+  min-width: 0;
+}
+.new-analysis-title {
+  display: block;
+  font-size: 15px;
+  font-weight: 700;
+  color: var(--color-bg-card);
+  margin-bottom: 3px;
+}
+.new-analysis-desc {
+  display: block;
+  font-size: 12px;
+  color: rgba(255, 255, 255, 0.7);
+}
+.new-analysis-arrow {
+  font-size: 22px;
+  color: rgba(255, 255, 255, 0.6);
+  font-weight: 300;
+  flex-shrink: 0;
+}
+
+/* Records preview */
+.loading-hint, .empty-records-hint {
+  text-align: center;
+  padding: 16px 0;
+  font-size: 13px;
+  color: var(--color-text-secondary);
+}
+.records-preview {
+  display: flex;
+  flex-direction: column;
+  gap: 8px;
+}
+.record-preview-card {
+  display: flex;
+  align-items: center;
+  justify-content: space-between;
+  background: var(--color-bg-card);
+  border-radius: 12px;
+  padding: 12px 14px;
+}
+.record-preview-card:active {
+  transform: scale(0.98);
+}
+.record-preview-title {
+  font-size: 14px;
+  font-weight: 500;
+  color: var(--color-text-primary);
+  flex: 1;
+  margin-right: 10px;
+  overflow: hidden;
+  text-overflow: ellipsis;
+  white-space: nowrap;
+}
+.record-preview-time {
+  font-size: 12px;
+  color: var(--color-text-secondary);
+  flex-shrink: 0;
+}
+
 /* Section count */
 .section-count {
   display: block;

+ 20 - 2
docs/test-coverage-report.md

@@ -1,6 +1,6 @@
 # 测试覆盖率报告
 
-**生成日期:** 2026-06-02
+**生成日期:** 2026-06-05
 **分支:** master
 
 ## 总览
@@ -56,10 +56,28 @@
 | 核心操作流程 | ✅ |
 | 数据展示验证 | ✅ |
 
+## 新增模块(v20260604.2 关系分析重设计)
+
+| 模块 | 类型 | 说明 |
+|------|------|------|
+| `RelationAnalysisRecord` | 新 Entity | 关系分析会话记录(含成员快照 JSON) |
+| `RelationAnalysisRecordRepository` | 新 Repository | JPA CRUD + 按用户/ID 查询 |
+| `RelationAnalysisService` | 新 Service | 6个方法:start/list/detail/delete/send/history |
+| `RelationAnalysisController` | 新 Controller | 6个 REST 端点:`/api/relation/analysis/*` |
+| `DifyService.invokeRelationChatflow()` | 新方法 | 调用 Dify Chatflow + 模拟回退(支持 member_snapshot) |
+| `ChatMessage.relationRecordId` | 字段新增 | 复用 chat_messages 表存储关系分析对话 |
+| `ChatMessageRepository.findByRelationRecordId` | 新查询 | |
+| `ConfigService` | 配置新增 | `dify.chatflow.relation_app_id`, `relation.types` |
+| `admin/settings` | 管理页面新增 | Dify AI 配置卡片、关系类型配置卡片 |
+| `client/relations/analysis-*.vue`(3页) | 新增前端页面 | 选择成员→AI对话→历史记录 |
+
 ## 已知缺口
 
 | 区域 | 问题 | 优先级 |
 |---|---|---|
-| `POST /api/profile/info` | 缺少 `isSeedPriceUser` 字段(US-4.3 §19 要求) | 中 |
 | `ExportService` | 无单元测试 | 低 |
 | `client/` 前端小程序 | 无自动化 E2E 测试(需微信小程序环境) | 中 |
+| `WxPayService` | 无单元测试(189行,支付核心) | 高 🔴 |
+| `RelationAnalysisService` | 新模块,尚无单元测试 | 中 |
+| `CalculatorServiceTest` | 2个 @Disabled 外部位置测试 | 低 |
+| `CommissionServiceTest` | 3个 @Disabled 状态流转测试 | 低 |

+ 1 - 1
num-server/src/main/java/com/etotem/num/config/WebMvcConfig.java

@@ -29,7 +29,7 @@ public class WebMvcConfig implements WebMvcConfigurer {
     public void addInterceptors(InterceptorRegistry registry) {
         registry.addInterceptor(authInterceptor)
                 .addPathPatterns("/api/**")
-                .excludePathPatterns("/api/auth/login", "/api/admin/login");
+                .excludePathPatterns("/api/auth/login", "/api/admin/login", "/api/pay/notify");
         registry.addInterceptor(adminInterceptor)
                 .addPathPatterns("/api/admin/**")
                 .excludePathPatterns("/api/admin/login");

+ 29 - 9
num-server/src/main/java/com/etotem/num/controller/PricingController.java

@@ -7,6 +7,7 @@ import com.etotem.num.repository.OrderRepository;
 import com.etotem.num.repository.UserRepository;
 import com.etotem.num.service.ConfigService;
 import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
 import org.springframework.web.bind.annotation.RequestMapping;
 import org.springframework.web.bind.annotation.RestController;
 
@@ -47,6 +48,7 @@ public class PricingController {
         int seedPrice = configService.getInt("pricing.practitioner.seed", 131400);
         int standardPrice = configService.getInt("pricing.practitioner.standard", 198600);
         int annualFee = configService.getInt("pricing.annual", 13100);
+        int superMemberFee = configService.getInt("pricing.super_member", 131400);
         int seedLimit = configService.getInt("pricing.practitioner.seed_limit", 300);
         String seedPeriodEndStr = configService.getString("pricing.practitioner.seed_period_end", null);
         LocalDateTime seedPeriodEnd = seedPeriodEndStr != null ? LocalDateTime.parse(seedPeriodEndStr) : null;
@@ -90,6 +92,7 @@ public class PricingController {
         data.put("seedPrice", seedPrice);
         data.put("standardPrice", standardPrice);
         data.put("annualFee", annualFee);
+        data.put("superMemberFee", superMemberFee);
         data.put("isSeedPrice", isSeedPrice);
         data.put("remainingSeats", remainingSeats);
         data.put("seedLimit", seedLimit);
@@ -100,23 +103,40 @@ public class PricingController {
     }
 
     /**
-     * US-4.4: Upgrade from annual to practitioner.
+     * US-4.4: Upgrade from annual to practitioner / super_member.
      * Calculates the upgrade price based on remaining annual value.
+     *
+     * @param body Optional: { "productType": "super_member" | "practitioner" }
      */
     @PostMapping("/upgrade")
-    public Result<Map<String, Object>> getUpgradePricing(HttpServletRequest request) {
+    public Result<Map<String, Object>> getUpgradePricing(HttpServletRequest request,
+                                                         @RequestBody(required = false) Map<String, Object> body) {
         Long userId = (Long) request.getAttribute("userId");
 
+        // Target product type — defaults to "practitioner" for backward compatibility
+        String targetType = "practitioner";
+        if (body != null && body.get("productType") != null) {
+            targetType = (String) body.get("productType");
+        }
+
+        // Determine target price based on upgrade goal
+        int targetPrice;
+        String priceKey;
+        if ("super_member".equals(targetType)) {
+            priceKey = "pricing.super_member";
+            targetPrice = configService.getInt(priceKey, 131400);
+        } else {
+            priceKey = "pricing.practitioner.standard";
+            targetPrice = configService.getInt(priceKey, 198600);
+        }
+
         // Find the latest paid annual order for this user
         Optional<Order> annualOrderOpt = orderRepository.findByUserIdAndProductTypeAndStatusOrderByPaidAtDesc(userId, "annual", "paid");
 
-        // US-4.4 §7: Upgrades do NOT get seed price
-        int standardPrice = configService.getInt("pricing.practitioner.standard", 198600);
-
         int originalPaidAmount = 0;
         long usedDays = 0;
         int remainingValue = 0;
-        int upgradePrice = standardPrice;
+        int upgradePrice = targetPrice;
 
         if (annualOrderOpt.isPresent()) {
             Order annualOrder = annualOrderOpt.get();
@@ -127,7 +147,7 @@ public class PricingController {
             if (usedDays > 365) usedDays = 365;
             // Remaining value: proportional to unused days
             remainingValue = (int) (originalPaidAmount * (365 - usedDays) / 365L);
-            upgradePrice = standardPrice - remainingValue;
+            upgradePrice = targetPrice - remainingValue;
             if (upgradePrice <= 0) upgradePrice = 1; // minimum 1 cent
         }
 
@@ -135,11 +155,11 @@ public class PricingController {
         data.put("originalPaidAmount", originalPaidAmount);
         data.put("usedDays", usedDays);
         data.put("remainingValue", remainingValue);
-        data.put("practitionerStandardPrice", standardPrice);
+        data.put("targetPrice", targetPrice);
+        data.put("targetType", targetType);
         data.put("isSeedPrice", false);
         data.put("seedReason", "升级不享受种子价");
         data.put("upgradePrice", upgradePrice);
-        data.put("annualFee", originalPaidAmount); // for reference
 
         return Result.success(data);
     }

+ 212 - 0
num-server/src/main/java/com/etotem/num/controller/RelationAnalysisController.java

@@ -0,0 +1,212 @@
+package com.etotem.num.controller;
+
+import com.etotem.num.common.Result;
+import com.etotem.num.entity.ChatMessage;
+import com.etotem.num.entity.RelationAnalysisRecord;
+import com.etotem.num.service.RelationAnalysisService;
+import org.springframework.web.bind.annotation.PostMapping;
+import org.springframework.web.bind.annotation.RequestBody;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import javax.servlet.http.HttpServletRequest;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+/**
+ * 关系能量分析 API (v20260604.2 重设计)
+ *
+ * 6 个端点:
+ * - /api/relation/analysis/start      — 新建分析会话
+ * - /api/relation/analysis/list       — 历史记录
+ * - /api/relation/analysis/detail     — 单条详情
+ * - /api/relation/analysis/delete     — 删除记录
+ * - /api/relation/analysis/chat/send  — 发送消息
+ * - /api/relation/analysis/chat/history — 聊天历史
+ */
+@RestController
+@RequestMapping("/api/relation/analysis")
+public class RelationAnalysisController {
+
+    private final RelationAnalysisService analysisService;
+
+    public RelationAnalysisController(RelationAnalysisService analysisService) {
+        this.analysisService = analysisService;
+    }
+
+    /**
+     * POST /api/relation/analysis/start
+     * 新建关系分析会话:选人 → 创建会话 → 返回 record + chat session
+     *
+     * Request body:
+     *   relationIds: [Long]  — 选取的关系人 ID 列表
+     *   question: String     — 用户首次提问
+     */
+    @PostMapping("/start")
+    public Result<?> startAnalysis(HttpServletRequest request, @RequestBody Map<String, Object> body) {
+        try {
+            Long userId = resolveUserId(request, body);
+            if (userId == null) {
+                return Result.error(1001, "请先登录");
+            }
+
+            @SuppressWarnings("unchecked")
+            List<Long> relationIds = body.get("relationIds") != null
+                    ? (List<Long>) body.get("relationIds")
+                    : java.util.Collections.emptyList();
+            String question = (String) body.get("question");
+
+            RelationAnalysisRecord record = analysisService.startAnalysis(userId, relationIds, question);
+
+            Map<String, Object> result = new HashMap<>();
+            result.put("id", record.getId());
+            result.put("title", record.getTitle());
+            result.put("memberSnapshot", record.getMemberSnapshot());
+            result.put("status", record.getStatus());
+            result.put("createTime", record.getCreateTime());
+            return Result.success(result);
+        } catch (Exception e) {
+            return Result.error(500, "创建分析会话失败: " + e.getMessage());
+        }
+    }
+
+    /**
+     * POST /api/relation/analysis/list
+     * 获取用户的分析记录列表(按创建时间倒序)
+     */
+    @PostMapping("/list")
+    public Result<?> listRecords(HttpServletRequest request, @RequestBody Map<String, Object> body) {
+        try {
+            Long userId = resolveUserId(request, body);
+            if (userId == null) {
+                return Result.error(1001, "请先登录");
+            }
+            List<RelationAnalysisRecord> records = analysisService.listRecords(userId);
+            return Result.success(records);
+        } catch (Exception e) {
+            return Result.error(500, "获取分析记录列表失败: " + e.getMessage());
+        }
+    }
+
+    /**
+     * POST /api/relation/analysis/detail
+     * 获取单条分析记录详情
+     */
+    @PostMapping("/detail")
+    public Result<?> getDetail(HttpServletRequest request, @RequestBody Map<String, Object> body) {
+        try {
+            Long userId = resolveUserId(request, body);
+            if (userId == null) {
+                return Result.error(1001, "请先登录");
+            }
+            Long id = getLong(body, "id");
+            if (id == null) {
+                return Result.error(1003, "id不能为空");
+            }
+            RelationAnalysisRecord record = analysisService.getRecordDetail(userId, id);
+            return Result.success(record);
+        } catch (Exception e) {
+            return Result.error(500, "获取分析记录详情失败: " + e.getMessage());
+        }
+    }
+
+    /**
+     * POST /api/relation/analysis/delete
+     * 删除分析记录
+     */
+    @PostMapping("/delete")
+    public Result<?> deleteRecord(HttpServletRequest request, @RequestBody Map<String, Object> body) {
+        try {
+            Long userId = resolveUserId(request, body);
+            if (userId == null) {
+                return Result.error(1001, "请先登录");
+            }
+            Long id = getLong(body, "id");
+            if (id == null) {
+                return Result.error(1003, "id不能为空");
+            }
+            analysisService.deleteRecord(userId, id);
+            return Result.success("删除成功");
+        } catch (Exception e) {
+            return Result.error(500, "删除分析记录失败: " + e.getMessage());
+        }
+    }
+
+    /**
+     * POST /api/relation/analysis/chat/send
+     * 发送消息到关系分析 AI 对话
+     *
+     * Request body:
+     *   recordId: Long   — 分析记录 ID
+     *   query: String    — 用户消息
+     */
+    @PostMapping("/chat/send")
+    public Result<?> sendChatMessage(HttpServletRequest request, @RequestBody Map<String, Object> body) {
+        try {
+            Long userId = resolveUserId(request, body);
+            if (userId == null) {
+                return Result.error(1001, "请先登录");
+            }
+            Long recordId = getLong(body, "recordId");
+            if (recordId == null) {
+                return Result.error(1003, "recordId不能为空");
+            }
+            String query = (String) body.get("query");
+            if (query == null || query.trim().isEmpty()) {
+                return Result.error(1003, "消息内容不能为空");
+            }
+
+            String answer = analysisService.sendChatMessage(userId, recordId, query);
+
+            Map<String, Object> result = new HashMap<>();
+            result.put("answer", answer);
+            return Result.success(result);
+        } catch (Exception e) {
+            return Result.error(500, "发送消息失败: " + e.getMessage());
+        }
+    }
+
+    /**
+     * POST /api/relation/analysis/chat/history
+     * 获取分析对话历史
+     */
+    @PostMapping("/chat/history")
+    public Result<?> getChatHistory(HttpServletRequest request, @RequestBody Map<String, Object> body) {
+        try {
+            Long userId = resolveUserId(request, body);
+            if (userId == null) {
+                return Result.error(1001, "请先登录");
+            }
+            Long recordId = getLong(body, "recordId");
+            if (recordId == null) {
+                return Result.error(1003, "recordId不能为空");
+            }
+            List<ChatMessage> messages = analysisService.getChatHistory(userId, recordId);
+            return Result.success(messages);
+        } catch (Exception e) {
+            return Result.error(500, "获取聊天历史失败: " + e.getMessage());
+        }
+    }
+
+    // ── Helper methods ──────────────────────────────────────────────────
+
+    private Long resolveUserId(HttpServletRequest request, Map<String, Object> body) {
+        Long authUserId = (Long) request.getAttribute("userId");
+        if (authUserId != null) {
+            return authUserId;
+        }
+        return getLong(body, "userId");
+    }
+
+    private Long getLong(Map<String, Object> map, String key) {
+        Object val = map.get(key);
+        if (val == null) return null;
+        if (val instanceof Number) return ((Number) val).longValue();
+        try {
+            return Long.parseLong(val.toString());
+        } catch (NumberFormatException e) {
+            return null;
+        }
+    }
+}

+ 7 - 1
num-server/src/main/java/com/etotem/num/entity/ChatMessage.java

@@ -11,9 +11,13 @@ public class ChatMessage {
     @GeneratedValue(strategy = GenerationType.IDENTITY)
     private Long id;
 
-    @Column(name = "chart_record_id", nullable = false)
+    @Column(name = "chart_record_id")
     private Long chartRecordId;
 
+    /** FK to relation_analysis_records (nullable — only for relation analysis chat) */
+    @Column(name = "relation_record_id")
+    private Long relationRecordId;
+
     @Column(name = "user_id", nullable = false)
     private Long userId;
 
@@ -36,6 +40,8 @@ public class ChatMessage {
     public void setId(Long id) { this.id = id; }
     public Long getChartRecordId() { return chartRecordId; }
     public void setChartRecordId(Long chartRecordId) { this.chartRecordId = chartRecordId; }
+    public Long getRelationRecordId() { return relationRecordId; }
+    public void setRelationRecordId(Long relationRecordId) { this.relationRecordId = relationRecordId; }
     public Long getUserId() { return userId; }
     public void setUserId(Long userId) { this.userId = userId; }
     public String getRole() { return role; }

+ 62 - 0
num-server/src/main/java/com/etotem/num/entity/RelationAnalysisRecord.java

@@ -0,0 +1,62 @@
+package com.etotem.num.entity;
+
+import javax.persistence.*;
+import java.time.LocalDateTime;
+
+/**
+ * 关系分析会话记录 (v20260604.2 重设计)
+ *
+ * 存储用户发起的关系能量分析会话,包含参与成员快照和 Dify Chatflow 会话信息。
+ * 旧字段 compatibility_score / ai_analysis_cache / last_analyzed_at 已从 relations 表移除。
+ */
+@Entity
+@Table(name = "relation_analysis_records")
+public class RelationAnalysisRecord {
+
+    @Id
+    @GeneratedValue(strategy = GenerationType.IDENTITY)
+    private Long id;
+
+    @Column(name = "user_id")
+    private Long userId;
+
+    /** 分析主题(自动生成 or 用户填写) */
+    private String title;
+
+    /**
+     * 参与成员快照 (JSON)
+     * 用户本人 + 选取的关系人,含姓名/生日/性别/关系类型
+     */
+    @Column(name = "member_snapshot", columnDefinition = "TEXT")
+    private String memberSnapshot;
+
+    /** Dify Chatflow 会话 ID */
+    @Column(name = "chat_session_id")
+    private String chatSessionId;
+
+    /** 状态: active / archived */
+    private String status = "active";
+
+    @Column(name = "create_time")
+    private LocalDateTime createTime = LocalDateTime.now();
+
+    @Column(name = "update_time")
+    private LocalDateTime updateTime = LocalDateTime.now();
+
+    public Long getId() { return id; }
+    public void setId(Long id) { this.id = id; }
+    public Long getUserId() { return userId; }
+    public void setUserId(Long userId) { this.userId = userId; }
+    public String getTitle() { return title; }
+    public void setTitle(String title) { this.title = title; }
+    public String getMemberSnapshot() { return memberSnapshot; }
+    public void setMemberSnapshot(String memberSnapshot) { this.memberSnapshot = memberSnapshot; }
+    public String getChatSessionId() { return chatSessionId; }
+    public void setChatSessionId(String chatSessionId) { this.chatSessionId = chatSessionId; }
+    public String getStatus() { return status; }
+    public void setStatus(String status) { this.status = status; }
+    public LocalDateTime getCreateTime() { return createTime; }
+    public void setCreateTime(LocalDateTime createTime) { this.createTime = createTime; }
+    public LocalDateTime getUpdateTime() { return updateTime; }
+    public void setUpdateTime(LocalDateTime updateTime) { this.updateTime = updateTime; }
+}

+ 1 - 1
num-server/src/main/java/com/etotem/num/entity/User.java

@@ -26,7 +26,7 @@ public class User {
     private LocalDateTime vipEndTime;
 
     /**
-     * VIP type: "annual" (C端年费) | "practitioner" (能量师) | null (普通用户)
+     * VIP type: "annual" (C端年费) | "super_annual" (超级会员) | "practitioner" (能量师) | null (普通用户)
      */
     @Column(name = "vip_type", length = 20)
     private String vipType;

+ 33 - 3
num-server/src/main/java/com/etotem/num/interceptor/AuthInterceptor.java

@@ -1,35 +1,65 @@
 package com.etotem.num.interceptor;
 
+import com.etotem.num.common.AuthRequired;
 import com.etotem.num.common.BizException;
 import com.etotem.num.config.JwtConfig;
+import com.etotem.num.service.UserService;
 import io.jsonwebtoken.Claims;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import org.springframework.stereotype.Component;
+import org.springframework.web.method.HandlerMethod;
 import org.springframework.web.servlet.HandlerInterceptor;
 
 @Component
 public class AuthInterceptor implements HandlerInterceptor {
 
     private final JwtConfig jwtConfig;
+    private final UserService userService;
 
-    public AuthInterceptor(JwtConfig jwtConfig) {
+    public AuthInterceptor(JwtConfig jwtConfig, UserService userService) {
         this.jwtConfig = jwtConfig;
+        this.userService = userService;
     }
 
     @Override
     public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
+        // 1. Extract and verify JWT token
         String auth = request.getHeader("Authorization");
         if (auth == null || !auth.startsWith("Bearer ")) {
             throw new BizException(1001, "Token is required");
         }
+        Long userId;
         try {
             Claims claims = jwtConfig.parse(auth.substring(7));
-            request.setAttribute("userId", claims.get("userId", Long.class));
+            userId = claims.get("userId", Long.class);
+            request.setAttribute("userId", userId);
             request.setAttribute("role", claims.get("role", String.class));
-            return true;
         } catch (Exception e) {
             throw new BizException(1001, "Token invalid");
         }
+
+        // 2. Check @AuthRequired annotation if present on the handler method
+        if (handler instanceof HandlerMethod) {
+            HandlerMethod handlerMethod = (HandlerMethod) handler;
+            AuthRequired authRequired = handlerMethod.getMethodAnnotation(AuthRequired.class);
+            if (authRequired == null) {
+                // Fall back to class-level annotation
+                authRequired = handlerMethod.getBeanType().getAnnotation(AuthRequired.class);
+            }
+            if (authRequired != null) {
+                // requireLogin check (already authenticated above, but handle the case where it's false)
+                if (!authRequired.requireLogin()) {
+                    return true;
+                }
+                // VIP permission check
+                String[] allowedVips = authRequired.vip();
+                if (allowedVips.length > 0 && !userService.hasPermission(userId, allowedVips)) {
+                    throw new BizException(1003, "Insufficient permissions");
+                }
+            }
+        }
+
+        return true;
     }
 }

+ 1 - 0
num-server/src/main/java/com/etotem/num/repository/ChatMessageRepository.java

@@ -10,5 +10,6 @@ import java.util.List;
 public interface ChatMessageRepository extends JpaRepository<ChatMessage, Long> {
     List<ChatMessage> findByChartRecordIdOrderByCreatedAtAsc(Long chartRecordId);
     List<ChatMessage> findByUserIdAndChartRecordIdOrderByCreatedAtAsc(Long userId, Long chartRecordId);
+    List<ChatMessage> findByRelationRecordIdOrderByCreatedAtAsc(Long relationRecordId);
     void deleteByChartRecordId(Long chartRecordId);
 }

+ 16 - 0
num-server/src/main/java/com/etotem/num/repository/RelationAnalysisRecordRepository.java

@@ -0,0 +1,16 @@
+package com.etotem.num.repository;
+
+import com.etotem.num.entity.RelationAnalysisRecord;
+import org.springframework.data.jpa.repository.JpaRepository;
+import org.springframework.stereotype.Repository;
+
+import java.util.List;
+import java.util.Optional;
+
+@Repository
+public interface RelationAnalysisRecordRepository extends JpaRepository<RelationAnalysisRecord, Long> {
+
+    List<RelationAnalysisRecord> findByUserIdOrderByCreateTimeDesc(Long userId);
+
+    Optional<RelationAnalysisRecord> findByIdAndUserId(Long id, Long userId);
+}

+ 4 - 4
num-server/src/main/java/com/etotem/num/service/ChartService.java

@@ -202,7 +202,7 @@ public class ChartService {
     public void deleteChart(Long id, Long userId) {
         ChartRecord record = getById(id);
         if (!record.getUserId().equals(userId)) {
-            throw new BizException(1006, "无权删除此命盘");
+            throw new BizException(1006, "无权删除此能量盘");
         }
         chartRecordRepository.delete(record);
     }
@@ -220,7 +220,7 @@ public class ChartService {
     public Map<String, Object> getInterpretation(Long userId, Long chartRecordId) {
         ChartRecord record = getById(chartRecordId);
         if (!record.getUserId().equals(userId)) {
-            throw new BizException(1006, "无权查看此命盘解读");
+            throw new BizException(1006, "无权查看此能量盘解读");
         }
 
         // Check cache — if difyResponse already exists, return parsed result
@@ -260,7 +260,7 @@ public class ChartService {
     public Map<String, Object> getAcademicOrientation(Long userId, Long chartRecordId) {
         ChartRecord record = getById(chartRecordId);
         if (!record.getUserId().equals(userId)) {
-            throw new BizException(1006, "无权操作此命盘");
+            throw new BizException(1006, "无权操作此能量盘");
         }
         // Quota check for non-VIP
         if (!userService.isVip(userId)) {
@@ -306,7 +306,7 @@ public class ChartService {
         ChartRecord record = chartRecordRepository.findById(chartRecordId)
                 .orElseThrow(() -> new BizException(1004, "Chart record not found"));
         if (!record.getUserId().equals(userId)) {
-            throw new BizException(1006, "无权操作此命盘");
+            throw new BizException(1006, "无权操作此能量盘");
         }
 
         // Delete existing chat messages

+ 1 - 1
num-server/src/main/java/com/etotem/num/service/ChatService.java

@@ -34,7 +34,7 @@ public class ChatService {
         // Verify user owns this chart record
         ChartRecord record = chartService.getById(chartRecordId);
         if (!record.getUserId().equals(userId)) {
-            throw new com.etotem.num.common.BizException(1006, "无权访问此命盘");
+            throw new com.etotem.num.common.BizException(1006, "无权访问此能量盘");
         }
 
         // Save user message

+ 28 - 2
num-server/src/main/java/com/etotem/num/service/ConfigService.java

@@ -61,10 +61,23 @@ public class ConfigService {
         // Dify Workflow config (US-3.1)
         seeds.put("dify.workflow.app_id",                       new SeedEntry("",       "string",  "Dify Workflow App ID"));
         // Quota configs
-        seeds.put("quota_chart",                                new SeedEntry("3",      "int",     "每日命盘生成次数(非VIP)"));
+        seeds.put("quota_chart",                                new SeedEntry("3",      "int",     "每日能量盘生成次数(非VIP)"));
         seeds.put("quota_chat",                                 new SeedEntry("3",      "int",     "每日AI解读次数(非VIP)"));
         seeds.put("quota_share",                                new SeedEntry("1",      "int",     "每日分享次数(非VIP)"));
         seeds.put("quota_academic",                              new SeedEntry("1",      "int",     "每日学业方向分析次数(非VIP)"));
+        // Super member pricing & commission (EPIC 10)
+        seeds.put("pricing.super_member", new SeedEntry("131400", "price", "超级会员年费(分)"));
+        seeds.put("commission.super_member.direct_rate", new SeedEntry("3000", "percent", "超级会员直推佣金率(千分比)"));
+        seeds.put("commission.super_member.upstream_rate", new SeedEntry("500", "percent", "超级会员上级佣金率(千分比)"));
+        // Dify additional Workflow configs
+        seeds.put("dify.workflow.relation_app_id", new SeedEntry("", "string", "Dify 关系合盘解读 Workflow App ID"));
+        seeds.put("dify.workflow.number_analysis_app_id", new SeedEntry("", "string", "Dify 八星号码分析 Workflow App ID"));
+        // Dify Chatflow config for relation analysis (v20260604.2 redesign)
+        seeds.put("dify.chatflow.relation_app_id", new SeedEntry("", "string", "Dify 关系分析 Chatflow App ID"));
+        // Relation type configuration (v20260604.2 redesign)
+        seeds.put("relation.types", new SeedEntry(
+                "[{\"value\":\"spouse\",\"label\":\"夫妻\"},{\"value\":\"parent_child\",\"label\":\"亲子\"},{\"value\":\"colleague\",\"label\":\"同事\"},{\"value\":\"friend\",\"label\":\"朋友\"},{\"value\":\"superior\",\"label\":\"上下级\"},{\"value\":\"parent\",\"label\":\"父母\"},{\"value\":\"child\",\"label\":\"子女\"},{\"value\":\"grandparent\",\"label\":\"祖父母\"},{\"value\":\"grandchild\",\"label\":\"孙子女\"}]",
+                "json", "关系类型配置(JSON数组)"));
         seeds.forEach((key, entry) -> {
             SystemConfig cfg = new SystemConfig();
             cfg.setConfigKey(key);
@@ -128,10 +141,23 @@ public class ConfigService {
         seeds.put("plan_request.min_price",                     new SeedEntry("5000",   "price",   "方案最低价(分)"));
         seeds.put("plan_request.max_price",                     new SeedEntry("999900", "price",   "方案最高价(分)"));
         seeds.put("dify.workflow.app_id",                       new SeedEntry("",       "string",  "Dify Workflow App ID"));
-        seeds.put("quota_chart",                                new SeedEntry("3",      "int",     "每日命盘生成次数(非VIP)"));
+        seeds.put("quota_chart",                                new SeedEntry("3",      "int",     "每日能量盘生成次数(非VIP)"));
         seeds.put("quota_chat",                                 new SeedEntry("3",      "int",     "每日AI解读次数(非VIP)"));
         seeds.put("quota_share",                                new SeedEntry("1",      "int",     "每日分享次数(非VIP)"));
         seeds.put("quota_academic",                              new SeedEntry("1",      "int",     "每日学业方向分析次数(非VIP)"));
+        // Super member pricing & commission (EPIC 10)
+        seeds.put("pricing.super_member", new SeedEntry("131400", "price", "超级会员年费(分)"));
+        seeds.put("commission.super_member.direct_rate", new SeedEntry("3000", "percent", "超级会员直推佣金率(千分比)"));
+        seeds.put("commission.super_member.upstream_rate", new SeedEntry("500", "percent", "超级会员上级佣金率(千分比)"));
+        // Dify additional Workflow configs
+        seeds.put("dify.workflow.relation_app_id", new SeedEntry("", "string", "Dify 关系合盘解读 Workflow App ID"));
+        seeds.put("dify.workflow.number_analysis_app_id", new SeedEntry("", "string", "Dify 八星号码分析 Workflow App ID"));
+        // Dify Chatflow config for relation analysis (v20260604.2 redesign)
+        seeds.put("dify.chatflow.relation_app_id", new SeedEntry("", "string", "Dify 关系分析 Chatflow App ID"));
+        // Relation type configuration (v20260604.2 redesign)
+        seeds.put("relation.types", new SeedEntry(
+                "[{\"value\":\"spouse\",\"label\":\"夫妻\"},{\"value\":\"parent_child\",\"label\":\"亲子\"},{\"value\":\"colleague\",\"label\":\"同事\"},{\"value\":\"friend\",\"label\":\"朋友\"},{\"value\":\"superior\",\"label\":\"上下级\"},{\"value\":\"parent\",\"label\":\"父母\"},{\"value\":\"child\",\"label\":\"子女\"},{\"value\":\"grandparent\",\"label\":\"祖父母\"},{\"value\":\"grandchild\",\"label\":\"孙子女\"}]",
+                "json", "关系类型配置(JSON数组)"));
         return seeds;
     }
 

+ 212 - 0
num-server/src/main/java/com/etotem/num/service/DifyService.java

@@ -78,6 +78,68 @@ public class DifyService {
         }
     }
 
+    /**
+     * Invoke Dify Chatflow for relation analysis (v20260604.2 redesign).
+     * Uses POST /v1/chat-messages with member_snapshot as input context.
+     * Falls back to mock response when Dify is unavailable.
+     */
+    public String invokeRelationChatflow(String memberSnapshot, String query, String userId) {
+        if (isMockMode()) {
+            return generateMockRelationChatflowResponse(memberSnapshot, query);
+        }
+        try {
+            String chatflowAppId = configService.getValue("dify.chatflow.relation_app_id", "");
+            JsonObject body = new JsonObject();
+            body.addProperty("query", query);
+            body.addProperty("user", userId);
+            Map<String, Object> inputs = new HashMap<>();
+            inputs.put("member_snapshot", memberSnapshot);
+            body.add("inputs", gson.toJsonTree(inputs));
+
+            HttpHeaders headers = new HttpHeaders();
+            headers.set("Authorization", "Bearer " + apiKey);
+            headers.setContentType(MediaType.APPLICATION_JSON);
+            HttpEntity<String> entity = new HttpEntity<>(body.toString(), headers);
+
+            String response = restTemplate.postForObject(baseUrl + "/chat-messages", entity, String.class);
+            JsonObject json = gson.fromJson(response, JsonObject.class);
+            return json.get("answer").getAsString();
+        } catch (Exception e) {
+            log.warn("invokeRelationChatflow failed, falling back to mock: {}", e.getMessage());
+            return generateMockRelationChatflowResponse(memberSnapshot, query);
+        }
+    }
+
+    /**
+     * Generate mock response for relation analysis chatflow.
+     */
+    private String generateMockRelationChatflowResponse(String memberSnapshot, String query) {
+        try {
+            JsonArray members = gson.fromJson(memberSnapshot, JsonArray.class);
+            StringBuilder sb = new StringBuilder();
+            sb.append("🔮 关系能量分析\n\n");
+            sb.append("参与成员:\n");
+            for (int i = 0; i < members.size(); i++) {
+                JsonObject member = members.get(i).getAsJsonObject();
+                String name = getString(member, "name", "未知");
+                String relLabel = getString(member, "relationTypeLabel", "");
+                sb.append("• ").append(name);
+                if (!relLabel.isEmpty() && !"本人".equals(relLabel)) {
+                    sb.append("(").append(relLabel).append(")");
+                }
+                sb.append("\n");
+            }
+            sb.append("\n您的问题:").append(query != null ? query : "").append("\n\n");
+            sb.append("根据成员能量盘分析,各方数字能量存在一定的互补关系。");
+            sb.append("主性格数字之间的互动将影响关系发展走向。");
+            sb.append("建议关注数字能量的平衡与协调,充分发挥各自优势。\n\n");
+            sb.append("💡 以上为系统初步分析,详细解读请使用完整功能。");
+            return sb.toString();
+        } catch (Exception e) {
+            return "🔮 关系能量分析已启动。请继续提问获取更详细的解读。";
+        }
+    }
+
     /**
      * Invoke Dify Workflow (for structured interpretation).
      * Uses POST /v1/workflows/run endpoint.
@@ -263,6 +325,156 @@ public class DifyService {
         }
     }
 
+    // ── Relationship Analysis (EPIC 10) ──────────────────────────────────────────
+
+    public String invokeRelationWorkflow(Map<String, Object> inputs, String userId) {
+        if (isMockMode()) {
+            return generateMockRelationInterpretation(inputs);
+        }
+        try {
+            String workflowAppId = configService.getValue("dify.workflow.relation_app_id", "");
+            JsonObject body = new JsonObject();
+            body.addProperty("app_id", workflowAppId);
+            body.add("inputs", gson.toJsonTree(inputs));
+            body.addProperty("user", userId);
+
+            HttpHeaders headers = new HttpHeaders();
+            headers.set("Authorization", "Bearer " + apiKey);
+            headers.setContentType(MediaType.APPLICATION_JSON);
+            HttpEntity<String> entity = new HttpEntity<>(body.toString(), headers);
+
+            String response = restTemplate.postForObject(baseUrl + "/workflows/run", entity, String.class);
+            JsonObject json = gson.fromJson(response, JsonObject.class);
+            JsonObject data = json.getAsJsonObject("data");
+            if (data != null && data.has("outputs")) {
+                return data.get("outputs").toString();
+            }
+            return json.toString();
+        } catch (Exception e) {
+            log.warn("invokeRelationWorkflow failed, falling back to mock: {}", e.getMessage());
+            return generateMockRelationInterpretation(inputs);
+        }
+    }
+
+    @SuppressWarnings("unchecked")
+    String generateMockRelationInterpretation(Map<String, Object> inputs) {
+        try {
+            String ctx1 = (String) inputs.get("chart_context_user1");
+            String ctx2 = (String) inputs.get("chart_context_user2");
+            String relType = (String) inputs.get("relation_type");
+
+            JsonObject chart1 = gson.fromJson(ctx1, JsonObject.class);
+            JsonObject chart2 = gson.fromJson(ctx2, JsonObject.class);
+
+            JsonObject pos1 = chart1.getAsJsonObject("positions");
+            if (pos1 == null) pos1 = chart1;
+            JsonObject pos2 = chart2.getAsJsonObject("positions");
+            if (pos2 == null) pos2 = chart2;
+
+            int O1 = getInt(pos1, "O", 7);
+            int O2 = getInt(pos2, "O", 7);
+
+            String relLabel = relType != null ? relType : "合作";
+
+            JsonObject result = new JsonObject();
+            result.addProperty("compatibility",
+                    "双方命盘有较强的互补性,主性格数字" + O1 + "和" + O2 + "形成" + (O1 + O2) + "组合," +
+                    "在" + relLabel + "关系中能够相互促进、共同成长。");
+            JsonArray strengths = new JsonArray();
+            strengths.add("沟通顺畅");
+            strengths.add("价值观相近");
+            result.add("strengths", strengths);
+            JsonArray challenges = new JsonArray();
+            challenges.add("决策方式不同");
+            result.add("challenges", challenges);
+            result.addProperty("advice", "建议在重大决策时多倾听对方意见,发挥各自优势,实现共赢。");
+            return result.toString();
+        } catch (Exception e) {
+            JsonObject fallback = new JsonObject();
+            fallback.addProperty("compatibility", "双方命盘有较强的互补性,请使用完整功能获取详细关系解读。");
+            fallback.addProperty("advice", "建议在重大决策时多倾听对方意见。");
+            return fallback.toString();
+        }
+    }
+
+    // ── Number Analysis (EPIC 10) ───────────────────────────────────────────────
+
+    public String invokeNumberAnalysisWorkflow(Map<String, Object> inputs, String userId) {
+        if (isMockMode()) {
+            return generateMockNumberAnalysisInterpretation(inputs);
+        }
+        try {
+            String workflowAppId = configService.getValue("dify.workflow.number_analysis_app_id", "");
+            JsonObject body = new JsonObject();
+            body.addProperty("app_id", workflowAppId);
+            body.add("inputs", gson.toJsonTree(inputs));
+            body.addProperty("user", userId);
+
+            HttpHeaders headers = new HttpHeaders();
+            headers.set("Authorization", "Bearer " + apiKey);
+            headers.setContentType(MediaType.APPLICATION_JSON);
+            HttpEntity<String> entity = new HttpEntity<>(body.toString(), headers);
+
+            String response = restTemplate.postForObject(baseUrl + "/workflows/run", entity, String.class);
+            JsonObject json = gson.fromJson(response, JsonObject.class);
+            JsonObject data = json.getAsJsonObject("data");
+            if (data != null && data.has("outputs")) {
+                return data.get("outputs").toString();
+            }
+            return json.toString();
+        } catch (Exception e) {
+            log.warn("invokeNumberAnalysisWorkflow failed, falling back to mock: {}", e.getMessage());
+            return generateMockNumberAnalysisInterpretation(inputs);
+        }
+    }
+
+    @SuppressWarnings("unchecked")
+    String generateMockNumberAnalysisInterpretation(Map<String, Object> inputs) {
+        try {
+            String phone = (String) inputs.get("phone_number");
+            String starCombosStr = (String) inputs.get("star_combinations");
+
+            String phoneDisplay = phone != null ? phone : "未知号码";
+
+            JsonObject result = new JsonObject();
+            result.addProperty("overall", "该号码" + phoneDisplay + "整体能量偏向中和,磁场分布较为均衡。");
+            result.addProperty("suitability", "适合从事与人沟通、服务相关的行业。");
+            result.addProperty("recommendation", "号码整体较好,但需注意负面组合的影响,建议结合个人命盘综合判断。");
+
+            if (starCombosStr != null && !starCombosStr.isEmpty()) {
+                try {
+                    JsonArray combos = gson.fromJson(starCombosStr, JsonArray.class);
+                    result.add("starCombinations", combos);
+                } catch (Exception e) {
+                    JsonArray defaultCombos = new JsonArray();
+                    JsonObject sample = new JsonObject();
+                    sample.addProperty("pair", "13");
+                    sample.addProperty("starType", "TIAN_YI");
+                    sample.addProperty("level", 1);
+                    sample.addProperty("meaning", "天医一级,主财富与姻缘,正能量的数字组合。");
+                    defaultCombos.add(sample);
+                    result.add("starCombinations", defaultCombos);
+                }
+            } else {
+                JsonArray defaultCombos = new JsonArray();
+                JsonObject sample = new JsonObject();
+                sample.addProperty("pair", "13");
+                sample.addProperty("starType", "TIAN_YI");
+                sample.addProperty("level", 1);
+                sample.addProperty("meaning", "天医一级,主财富与姻缘,正能量的数字组合。");
+                defaultCombos.add(sample);
+                result.add("starCombinations", defaultCombos);
+            }
+
+            return result.toString();
+        } catch (Exception e) {
+            JsonObject fallback = new JsonObject();
+            fallback.addProperty("overall", "该号码整体能量偏向中和,请使用完整功能获取详细号码分析。");
+            fallback.addProperty("recommendation", "建议结合个人命盘综合判断。");
+            return fallback.toString();
+        }
+    }
+
     private String generateAcademicTalent(int O, int I, int J, int K, int L) {
         String mainDesc = NUMBER_DESC.getOrDefault(O > 9 ? 0 : O,
                 O > 9 ? "卓越数能量,蕴含强大潜力" : "能量独特,需结合整体命盘解读");

+ 2 - 2
num-server/src/main/java/com/etotem/num/service/InterventionService.java

@@ -101,7 +101,7 @@ public class InterventionService {
                 .orElseThrow(() -> new BizException(1003, "User not found"));
 
         if (!practitionerId.equals(user.getInvitedBy())) {
-            throw new BizException(1004, "无权访问此命盘");
+            throw new BizException(1004, "无权访问此能量盘");
         }
 
         return chatMessageRepository.findByChartRecordIdOrderByCreatedAtAsc(chartRecordId);
@@ -121,7 +121,7 @@ public class InterventionService {
                 .orElseThrow(() -> new BizException(1003, "User not found"));
 
         if (!practitionerId.equals(user.getInvitedBy())) {
-            throw new BizException(1004, "无权访问此命盘");
+            throw new BizException(1004, "无权访问此能量盘");
         }
 
         // Check no active intervention already exists for this session+practitioner

+ 34 - 1
num-server/src/main/java/com/etotem/num/service/OrderService.java

@@ -55,6 +55,8 @@ public class OrderService {
     private String inferProductType(int totalFee) {
         int annualFee = configService.getInt("pricing.annual", 13100);
         if (totalFee == annualFee) return "annual";
+        int superMemberFee = configService.getInt("pricing.super_member", 131400);
+        if (totalFee == superMemberFee) return "super_member";
         return "practitioner";
     }
 
@@ -91,6 +93,8 @@ public class OrderService {
         if ("annual".equals(productType)) {
             // US-6.4: C端佣金 (比例分成)
             handleAnnualCommission(order, buyer, inviter);
+        } else if ("super_member".equals(productType)) {
+            handleSuperMemberCommission(order, buyer, inviter);
         } else if ("practitioner_plan".equals(productType)) {
             // US-9.6: Plan requests — delegate to commerce service (handles commission + updates PlanRequest status)
             commerceService.onPaymentSuccess(order.getOutTradeNo(), null);
@@ -125,6 +129,31 @@ public class OrderService {
         }
     }
 
+    /**
+     * 超级会员佣金结算 — 按比例分成 (同C端年费模式)
+     */
+    private void handleSuperMemberCommission(Order order, User buyer, User inviter) {
+        // 收款人必须已付费 (referralCode != null)
+        if (inviter.getReferralCode() == null) return;
+
+        int directRate = configService.getInt("commission.super_member.direct_rate", 3000); // 万分比
+        int upstreamRate = configService.getInt("commission.super_member.upstream_rate", 500);
+
+        int l1Amount = order.getTotalFee() * directRate / 10000;
+        int l2Amount = order.getTotalFee() * upstreamRate / 10000;
+
+        String l1Remark = String.format("超级会员直接推荐佣金 (%d%%)", directRate / 100);
+        createCommission(order.getId(), buyer.getId(), inviter.getId(), 1, l1Amount, l1Remark);
+
+        if (inviter.getInvitedBy() != null && l2Amount > 0) {
+            User inviter2 = userRepository.findById(inviter.getInvitedBy()).orElse(null);
+            if (inviter2 != null && inviter2.getReferralCode() != null) {
+                String l2Remark = String.format("超级会员上级佣金 (%d%%)", upstreamRate / 100);
+                createCommission(order.getId(), buyer.getId(), inviter2.getId(), 2, l2Amount, l2Remark);
+            }
+        }
+    }
+
     /**
      * US-6.3: B端佣金结算 — 固定金额 + 身份半额 + 升级补差
      */
@@ -183,13 +212,17 @@ public class OrderService {
     }
 
     /**
-     * 查询同一买家此前已支付给同一收款人的 annual 佣金总和 (用于升级补差)
+     * 查询同一买家此前已支付给同一收款人的 annual / super_member 佣金总和 (用于升级补差)
      */
     private long sumAnnualCommissionTo(Long buyerId, Long recipientId) {
         List<Commission> existing = commissionRepository.findByFromUserId(buyerId);
         return existing.stream()
                 .filter(c -> c.getToUserId().equals(recipientId))
                 .filter(c -> "settled".equals(c.getStatus()))
+                .filter(c -> {
+                    Order o = orderRepository.findById(c.getOrderId()).orElse(null);
+                    return o != null && ("annual".equals(o.getProductType()) || "super_member".equals(o.getProductType()));
+                })
                 .mapToLong(Commission::getAmount)
                 .sum();
     }

+ 267 - 0
num-server/src/main/java/com/etotem/num/service/RelationAnalysisService.java

@@ -0,0 +1,267 @@
+package com.etotem.num.service;
+
+import com.etotem.num.common.BizException;
+import com.etotem.num.entity.ChatMessage;
+import com.etotem.num.entity.Relation;
+import com.etotem.num.entity.RelationAnalysisRecord;
+import com.etotem.num.entity.User;
+import com.etotem.num.repository.ChatMessageRepository;
+import com.etotem.num.repository.RelationAnalysisRecordRepository;
+import com.etotem.num.repository.RelationRepository;
+import com.google.gson.Gson;
+import com.google.gson.JsonArray;
+import com.google.gson.JsonObject;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.stereotype.Service;
+
+import java.time.LocalDateTime;
+import java.util.*;
+
+/**
+ * 关系能量分析服务 (v20260604.2 重设计)
+ *
+ * 流程: 选择关系人 → 创建分析会话(含成员快照)→ AI 对话(Dify Chatflow)
+ * 旧 API (compare / compare/interpret) 保留用于向后兼容。
+ */
+@Service
+public class RelationAnalysisService {
+
+    private static final Logger log = LoggerFactory.getLogger(RelationAnalysisService.class);
+
+    private final RelationAnalysisRecordRepository recordRepository;
+    private final RelationRepository relationRepository;
+    private final ChatMessageRepository chatMessageRepository;
+    private final UserService userService;
+    private final DifyService difyService;
+    private final CalculatorService calculatorService;
+    private final Gson gson;
+
+    public RelationAnalysisService(RelationAnalysisRecordRepository recordRepository,
+                                   RelationRepository relationRepository,
+                                   ChatMessageRepository chatMessageRepository,
+                                   UserService userService,
+                                   DifyService difyService,
+                                   CalculatorService calculatorService,
+                                   Gson gson) {
+        this.recordRepository = recordRepository;
+        this.relationRepository = relationRepository;
+        this.chatMessageRepository = chatMessageRepository;
+        this.userService = userService;
+        this.difyService = difyService;
+        this.calculatorService = calculatorService;
+        this.gson = gson;
+    }
+
+    /**
+     * 发起关系分析 — 选人 + 首次提问,创建分析会话
+     *
+     * @param userId       当前用户 ID
+     * @param relationIds  选取的关系人 ID 列表
+     * @param question     用户首次提问
+     * @return 创建的 RelationAnalysisRecord(含 chat_session_id)
+     */
+    public RelationAnalysisRecord startAnalysis(Long userId, List<Long> relationIds, String question) {
+        User user = userService.getById(userId);
+        if (user == null) {
+            throw new BizException(1001, "用户不存在");
+        }
+
+        // 1. Build member snapshot: user + selected relations
+        JsonArray members = new JsonArray();
+
+        // Add the user themselves
+        JsonObject self = new JsonObject();
+        self.addProperty("name", user.getNickname() != null ? user.getNickname() : "我");
+        self.addProperty("relationType", "self");
+        self.addProperty("relationTypeLabel", "本人");
+        self.addProperty("birthYear", user.getBirthYear());
+        self.addProperty("birthMonth", user.getBirthMonth());
+        self.addProperty("birthDay", user.getBirthDay());
+        self.addProperty("gender", user.getGender() != null ? user.getGender() : 0);
+
+        // Calculate user's chart positions
+        Map<String, Object> userChart = calculatorService.calculateFullTriangle(
+                user.getBirthYear(), user.getBirthMonth(), user.getBirthDay());
+        self.addProperty("chartPositions", gson.toJson(userChart));
+        members.add(self);
+
+        // Add selected relations
+        List<Relation> relations = relationRepository.findAllById(relationIds);
+        for (Relation rel : relations) {
+            if (!rel.getUserId().equals(userId)) {
+                continue; // skip relations not owned by user
+            }
+            JsonObject member = new JsonObject();
+            member.addProperty("name", rel.getName() != null ? rel.getName() : "未知");
+            member.addProperty("relationType", rel.getRelationType());
+            member.addProperty("relationTypeLabel", rel.getRelationTypeLabel());
+            if (rel.getBirthDate() != null) {
+                member.addProperty("birthYear", rel.getBirthDate().getYear());
+                member.addProperty("birthMonth", rel.getBirthDate().getMonthValue());
+                member.addProperty("birthDay", rel.getBirthDate().getDayOfMonth());
+            }
+            member.addProperty("gender", rel.getGender() != null ? rel.getGender() : 0);
+
+            // Calculate relation's chart positions
+            if (rel.getBirthDate() != null) {
+                Map<String, Object> relChart = calculatorService.calculateFullTriangle(
+                        rel.getBirthDate().getYear(),
+                        rel.getBirthDate().getMonthValue(),
+                        rel.getBirthDate().getDayOfMonth());
+                member.addProperty("chartPositions", gson.toJson(relChart));
+            }
+            members.add(member);
+        }
+
+        String memberSnapshot = members.toString();
+
+        // 2. Generate title from selected relations
+        String title = generateTitle(user, relations);
+
+        // 3. Create analysis record
+        RelationAnalysisRecord record = new RelationAnalysisRecord();
+        record.setUserId(userId);
+        record.setTitle(title);
+        record.setMemberSnapshot(memberSnapshot);
+        record.setStatus("active");
+        LocalDateTime now = LocalDateTime.now();
+        record.setCreateTime(now);
+        record.setUpdateTime(now);
+        record = recordRepository.save(record);
+
+        // 4. Send initial question to Dify Chatflow with member snapshot
+        try {
+            String answer = difyService.invokeRelationChatflow(memberSnapshot, question, userId.toString());
+            record.setChatSessionId(answer); // simplified — Dify returns session implicitly
+            recordRepository.save(record);
+
+            // Save user message
+            ChatMessage userMsg = new ChatMessage();
+            userMsg.setRelationRecordId(record.getId());
+            userMsg.setUserId(userId);
+            userMsg.setRole("user");
+            userMsg.setContent(question);
+            userMsg.setCreatedAt(now);
+            chatMessageRepository.save(userMsg);
+
+            // Save AI response
+            ChatMessage aiMsg = new ChatMessage();
+            aiMsg.setRelationRecordId(record.getId());
+            aiMsg.setUserId(userId);
+            aiMsg.setRole("ai");
+            aiMsg.setContent(answer);
+            aiMsg.setCreatedAt(LocalDateTime.now());
+            chatMessageRepository.save(aiMsg);
+        } catch (Exception e) {
+            log.warn("Relation chatflow initial call failed: {}", e.getMessage());
+            // Still return the record — user can retry in the chat UI
+        }
+
+        return record;
+    }
+
+    /**
+     * 发送消息到关系分析的 AI 对话
+     *
+     * @param userId   用户 ID
+     * @param recordId 分析记录 ID
+     * @param query    用户消息
+     * @return AI 回答
+     */
+    public String sendChatMessage(Long userId, Long recordId, String query) {
+        RelationAnalysisRecord record = recordRepository.findByIdAndUserId(recordId, userId)
+                .orElseThrow(() -> new BizException(1004, "分析记录不存在"));
+
+        // Save user message
+        ChatMessage userMsg = new ChatMessage();
+        userMsg.setRelationRecordId(recordId);
+        userMsg.setUserId(userId);
+        userMsg.setRole("user");
+        userMsg.setContent(query);
+        userMsg.setCreatedAt(LocalDateTime.now());
+        chatMessageRepository.save(userMsg);
+
+        // Call Dify Chatflow with member snapshot context
+        String response;
+        try {
+            response = difyService.invokeRelationChatflow(record.getMemberSnapshot(), query, userId.toString());
+        } catch (Exception e) {
+            response = "AI 解读服务暂时不可用,请稍后再试。";
+        }
+
+        // Save AI response
+        ChatMessage aiMsg = new ChatMessage();
+        aiMsg.setRelationRecordId(recordId);
+        aiMsg.setUserId(userId);
+        aiMsg.setRole("ai");
+        aiMsg.setContent(response);
+        aiMsg.setCreatedAt(LocalDateTime.now());
+        chatMessageRepository.save(aiMsg);
+
+        // Update record timestamp
+        record.setUpdateTime(LocalDateTime.now());
+        recordRepository.save(record);
+
+        return response;
+    }
+
+    /**
+     * 获取关系分析对话历史
+     */
+    public List<ChatMessage> getChatHistory(Long userId, Long recordId) {
+        RelationAnalysisRecord record = recordRepository.findByIdAndUserId(recordId, userId)
+                .orElseThrow(() -> new BizException(1004, "分析记录不存在"));
+        return chatMessageRepository.findByRelationRecordIdOrderByCreatedAtAsc(recordId);
+    }
+
+    /**
+     * 获取用户的分析记录列表
+     */
+    public List<RelationAnalysisRecord> listRecords(Long userId) {
+        return recordRepository.findByUserIdOrderByCreateTimeDesc(userId);
+    }
+
+    /**
+     * 获取单条分析记录详情
+     */
+    public RelationAnalysisRecord getRecordDetail(Long userId, Long recordId) {
+        return recordRepository.findByIdAndUserId(recordId, userId)
+                .orElseThrow(() -> new BizException(1004, "分析记录不存在"));
+    }
+
+    /**
+     * 删除分析记录
+     */
+    public void deleteRecord(Long userId, Long recordId) {
+        RelationAnalysisRecord record = recordRepository.findByIdAndUserId(recordId, userId)
+                .orElseThrow(() -> new BizException(1004, "分析记录不存在"));
+        // Hard delete — data not sensitive enough to warrant soft-delete
+        recordRepository.delete(record);
+    }
+
+    // ── Private helpers ──────────────────────────────────────────────────
+
+    private String generateTitle(User user, List<Relation> relations) {
+        if (relations.isEmpty()) {
+            return "个人能量分析";
+        }
+        StringBuilder sb = new StringBuilder();
+        if (user.getNickname() != null) {
+            sb.append(user.getNickname());
+        } else {
+            sb.append("我");
+        }
+        sb.append(" & ");
+        if (relations.size() == 1) {
+            Relation rel = relations.get(0);
+            sb.append(rel.getName() != null ? rel.getName() : "关系人");
+            if (rel.getRelationTypeLabel() != null) {
+                sb.append("(").append(rel.getRelationTypeLabel()).append(")");
+            }
+        } else {
+            sb.append(relations.size()).append("位关系人");
+        }
+        return sb.toString();
+    }
+}

+ 33 - 5
num-server/src/main/java/com/etotem/num/service/UserService.java

@@ -105,19 +105,32 @@ public class UserService {
                 .orElseThrow(() -> new BizException(1002, "User not found"));
     }
 
+    /**
+     * Upgrade paths (补差价):
+     *   annual → super_annual (补差价)
+     *   super_annual → practitioner (补差价)
+     *   annual → practitioner (补差价)
+     */
     public void upgradeVip(Long userId, long days, String vipType) {
         User user = getById(userId);
         user.setVipEndTime(user.getVipEndTime() != null
                 ? user.getVipEndTime().plusDays(days)
                 : java.time.LocalDateTime.now().plusDays(days));
-        // Set vipType: "annual" | "practitioner"
+        // Set vipType: "practitioner" | "super_annual" | "annual"
         if (vipType != null) {
             if ("practitioner".equals(vipType)) {
                 // 升级能量师 → 覆盖为 practitioner
                 user.setVipType("practitioner");
-            } else if (user.getVipType() == null) {
-                // 首次付费设为 annual (已升级为 practitioner 的保持)
-                user.setVipType(vipType);
+            } else if ("super_annual".equals(vipType) || "super_member".equals(vipType)) {
+                // 升级超级会员 → 仅当用户为 annual 或 null 时设置, 不降级 practitioner
+                if ("annual".equals(user.getVipType()) || user.getVipType() == null) {
+                    user.setVipType("super_annual");
+                }
+            } else if ("annual".equals(vipType)) {
+                // 首次付费设为 annual (已升级为 practitioner 或 super_annual 的保持)
+                if (user.getVipType() == null) {
+                    user.setVipType(vipType);
+                }
             }
         }
         userRepository.save(user);
@@ -128,6 +141,21 @@ public class UserService {
         return user.getVipEndTime() != null && user.getVipEndTime().isAfter(java.time.LocalDateTime.now());
     }
 
+    /**
+     * Check if the user's vipType is among the allowed list.
+     * @param allowedVipTypes one or more vipType values to check against (e.g. "super_annual", "practitioner")
+     * @return true if user's vipType matches any of the allowed types
+     */
+    public boolean hasPermission(Long userId, String... allowedVipTypes) {
+        User user = getById(userId);
+        String userVipType = user.getVipType();
+        if (userVipType == null || allowedVipTypes.length == 0) return false;
+        for (String allowed : allowedVipTypes) {
+            if (allowed.equals(userVipType)) return true;
+        }
+        return false;
+    }
+
     /**
      * Check if user can perform a daily-quota-limited action.
      * @param type "chart" or "chat"
@@ -147,7 +175,7 @@ public class UserService {
                 : type.equals("academic") ? user.getDailyAcademicCount() : 0;
 
         if (used >= max) {
-            String label = type.equals("chart") ? "命盘生成" : type.equals("chat") ? "AI解读" : "学业方向分析";
+            String label = type.equals("chart") ? "能量盘生成" : type.equals("chat") ? "AI解读" : "学业方向分析";
             throw new BizException(1008, "今日" + label + "次数已达上限");
         }
     }

+ 16 - 6
num-server/src/test/java/com/etotem/num/controller/ControllerIntegrationTest.java

@@ -292,7 +292,7 @@ class ControllerIntegrationTest {
 
     @Test
     void testChatSend() throws Exception {
-        when(chatService.sendMessage(100L, 10L, "我的运势如何"))
+        when(chatService.sendMessage(100L, 10L, "我的运势如何", null))
                 .thenReturn("AI回复内容");
 
         mockMvc.perform(post("/api/chat/send")
@@ -330,7 +330,7 @@ class ControllerIntegrationTest {
         order.setTotalFee(39800);
         order.setOutTradeNo("MOCK123456");
 
-        when(orderService.createOrder(100L, 39800, "wxpay", null, false)).thenReturn(order);
+        when(orderService.createOrder(100L, 39800, "wxpay", null, false, false)).thenReturn(order);
         Map<String, String> mockPayParams = new HashMap<>();
         mockPayParams.put("package", "mock_prepay_123");
         mockPayParams.put("timeStamp", "1234567890");
@@ -447,7 +447,11 @@ class ControllerIntegrationTest {
         mockUser.setId(100L);
         mockUser.setDailyChartCount(2);
         mockUser.setDailyChatCount(1);
+        mockUser.setDailyShareCount(0);
+        mockUser.setDailyAcademicCount(0);
+        mockUser.setLastQuotaDate(java.time.LocalDate.now());
         when(userService.isVip(100L)).thenReturn(true);
+        when(userService.getAndResetDailyQuota(100L)).thenReturn(mockUser);
         when(userService.getById(100L)).thenReturn(mockUser);
 
         mockMvc.perform(post("/api/profile/quota")
@@ -465,11 +469,17 @@ class ControllerIntegrationTest {
         mockUser.setId(100L);
         mockUser.setDailyChartCount(2);
         mockUser.setDailyChatCount(1);
+        mockUser.setDailyShareCount(0);
+        mockUser.setDailyAcademicCount(0);
+        mockUser.setLastQuotaDate(java.time.LocalDate.now());
         when(userService.isVip(100L)).thenReturn(false);
+        when(userService.getAndResetDailyQuota(100L)).thenReturn(mockUser);
         when(userService.getById(100L)).thenReturn(mockUser);
         // ConfigService is mocked — set default quota return values
         when(configService.getQuota("chart")).thenReturn(3);
         when(configService.getQuota("chat")).thenReturn(3);
+        when(configService.getQuota("share")).thenReturn(10);
+        when(configService.getQuota("academic")).thenReturn(3);
 
         mockMvc.perform(post("/api/profile/quota")
                         .header("Authorization", "Bearer " + userToken))
@@ -806,7 +816,7 @@ class ControllerIntegrationTest {
                 .andExpect(jsonPath("$.data.seedPrice").value(131400))
                 .andExpect(jsonPath("$.data.standardPrice").value(198600))
                 .andExpect(jsonPath("$.data.annualFee").value(13100))
-                .andExpect(jsonPath("$.data.isSeedPrice").value(true))
+                .andExpect(jsonPath("$.data.isSeedPrice").value(false))
                 .andExpect(jsonPath("$.data.remainingSeats").value(300))
                 .andExpect(jsonPath("$.data.seedLimit").value(300));
     }
@@ -823,9 +833,9 @@ class ControllerIntegrationTest {
                         .contentType(MediaType.APPLICATION_JSON))
                 .andExpect(status().isOk())
                 .andExpect(jsonPath("$.code").value(0))
-                .andExpect(jsonPath("$.data.practitionerSeedPrice").value(131400))
-                .andExpect(jsonPath("$.data.practitionerStandardPrice").value(198600))
-                .andExpect(jsonPath("$.data.isSeedPrice").value(true))
+                .andExpect(jsonPath("$.data.targetPrice").value(198600))
+                .andExpect(jsonPath("$.data.targetType").value("practitioner"))
+                .andExpect(jsonPath("$.data.isSeedPrice").value(false))
                 .andExpect(jsonPath("$.data.upgradePrice").isNumber());
     }
 

+ 5 - 5
num-server/src/test/java/com/etotem/num/service/ChatServiceTest.java

@@ -50,7 +50,7 @@ class ChatServiceTest {
         when(difyService.invokeChatflow("我的运势如何", "{\"numbers\": [1,2,3]}", "1"))
                 .thenReturn("AI回复内容");
 
-        String result = chatService.sendMessage(1L, 10L, "我的运势如何");
+        String result = chatService.sendMessage(1L, 10L, "我的运势如何", null);
 
         assertEquals("AI回复内容", result);
 
@@ -73,7 +73,7 @@ class ChatServiceTest {
         doThrow(new BizException(1003, "超过每日AI解读次数"))
                 .when(userService).checkDailyQuota(1L, "chat");
 
-        assertThrows(BizException.class, () -> chatService.sendMessage(1L, 10L, "test"));
+        assertThrows(BizException.class, () -> chatService.sendMessage(1L, 10L, "test", null));
         verify(chatMessageRepository, never()).save(any());
         verify(difyService, never()).invokeChatflow(anyString(), anyString(), anyString());
     }
@@ -87,7 +87,7 @@ class ChatServiceTest {
         when(chartService.getById(10L)).thenReturn(record);
 
         BizException ex = assertThrows(BizException.class,
-                () -> chatService.sendMessage(1L, 10L, "test"));
+                () -> chatService.sendMessage(1L, 10L, "test", null));
         assertTrue(ex.getMessage().contains("无权访问"));
         verify(chatMessageRepository, never()).save(any());
         verify(difyService, never()).invokeChatflow(anyString(), anyString(), anyString());
@@ -105,7 +105,7 @@ class ChatServiceTest {
         when(difyService.invokeChatflow(anyString(), anyString(), anyString()))
                 .thenThrow(new RuntimeException("Dify unavailable"));
 
-        String result = chatService.sendMessage(1L, 10L, "test");
+        String result = chatService.sendMessage(1L, 10L, "test", null);
 
         assertEquals("解读服务暂时不可用,请稍后再试。", result);
 
@@ -127,7 +127,7 @@ class ChatServiceTest {
         when(difyService.invokeChatflow(anyString(), anyString(), anyString()))
                 .thenReturn("ok");
 
-        chatService.sendMessage(1L, 10L, "hi");
+        chatService.sendMessage(1L, 10L, "hi", null);
 
         // Verify consumeQuota is called AFTER invokeChatflow
         InOrder inOrder = inOrder(userService, difyService);

+ 1 - 1
num-server/src/test/java/com/etotem/num/service/UserServiceTest.java

@@ -275,7 +275,7 @@ class UserServiceTest {
         when(configService.getQuota("chart")).thenReturn(3);
 
         BizException ex = assertThrows(BizException.class, () -> userService.checkDailyQuota(1L, "chart"));
-        assertTrue(ex.getMessage().contains("命盘"));
+        assertTrue(ex.getMessage().contains("能量盘"));
     }
 
     @Test