feat(ECR-016): UserIntelligence 用户洞察只读切片并 Closed

聚合 GET /admin/users/:id/insight(报告类型/派生标签/行为快照),admin-h5 洞察 Tab;无 migration / 无 UGC / 无真支付。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
jackyu66git
2026-08-07 18:31:06 +08:00
co-authored by Cursor
parent 1afda1d389
commit 61ae3b0451
27 changed files with 807 additions and 115 deletions
+3 -3
View File
@@ -16,9 +16,9 @@ Status: `Draft`
| Profile | Identity_Profile | UserIntelligence | 已存在 |
| UserStatus | Identity_Profile | AccountLifecycle | **ECR-013B** 状态机 |
| AccountStateTransition | Identity_Profile | AccountLifecycle | **ECR-013B** |
| BehaviorSnapshot | Identity_Profile | UserIntelligence | 未来读模型 |
| PsychologicalTagSet | Identity_Profile | UserIntelligence | 未来读模型 |
| MembershipPlan | Membership_Orders | CommerceEntitlement | 配置面后置 ECR |
| BehaviorSnapshot | Identity_Profile | UserIntelligence | **ECR-016** 读模型(analytics 聚合) |
| PsychologicalTagSet | Identity_Profile | UserIntelligence | **ECR-016** 由报告 type 派生 |
| MembershipPlan | Membership_Orders | CommerceEntitlement | **ECR-014 Closed** |
| Entitlement | Membership_Orders | CommerceEntitlement | 后置 |
| RedemptionCode | Membership_Orders | CommerceEntitlement | **ECR-015 Closed** |
| Membership | Membership_Orders | CommerceEntitlement | 已存在 |
+1 -1
View File
@@ -235,7 +235,7 @@ UI **不出现「塔罗」**。禁止神谕吉凶、恐吓话术。
| Phase A `[Ops]` | 登录 · 用户/订单查询 · 会员授予 · 审计 · `apps/admin-h5`ECR-006 Closed |
| Phase B `[Ops]` | 行为分析:自有埋点 + 管理端「数据」看板(**ECR-007 Closed** · Spec `ops-analytics.md` |
| Phase C `[Ops]` | 内容:首页宫格 CRUD · 测评上下架(**ECR-008 Closed** · Spec `ops-content.md` |
| Phase D+ | **Contract-First****ECR-013A/013B Closed** → **ECR-014** MembershipPlanLoop continuous)。`docs/WAVE0/LOOP_AUTHORIZATION.md`。 |
| Phase D+ | **Contract-First****ECR-013A/B/014/015 Closed** → **ECR-016** UserIntelligenceLoop)。`docs/WAVE0/LOOP_AUTHORIZATION.md`。 |
| 排除 | **UGC / 社区广场**M10.2)仍 `[No]`;真支付最后 |
不计入 P1 Complete;不进入五 Tab。
+1
View File
@@ -25,6 +25,7 @@
| [ops-content.md](ops-content.md) | 运营内容(宫格+测评上下架) | §7 | `admin-h5` `/content` · `GET /home/tools` | Ops-C · ECR-008 Closed |
| [ops-rbac.md](ops-rbac.md) | 运营 RBAC | §7 | `admin-h5` `/me` permissions · `/admin/roles*` | Ops-D · **ECR-013A Closed** |
| [ops-redemption-code.md](ops-redemption-code.md) | 兑换码 RedemptionCode | §7 | `admin-h5` `/codes` · `POST /membership/redeem` | Ops-D · **ECR-015 Closed** |
| [ops-user-intelligence.md](ops-user-intelligence.md) | 用户洞察 UserIntelligence | §7 | `admin-h5` 用户详情「洞察」· `GET /admin/users/:id/insight` | Ops-D · **ECR-016 Closed** |
新功能:复制 `_TEMPLATE.md` → 填满 → 在本表登记 → 再编码。
+3 -1
View File
@@ -211,6 +211,8 @@ Phase A 可先 `console`/本地;不挡验收。
| **EECR-013A Closed** | Admin RBAC — Spec `ops-rbac.md` · Parent WAVE0-FROZEN |
| **FECR-013B Closed** | AccountLifecycle — Spec `ops-account-lifecycle.md` |
| **GECR-014 Closed** | MembershipPlan — Spec `ops-membership-plan.md` |
| 后置 | RedemptionCode / UserIntelligence / Entitlement 细权(Loop 续跑) |
| **HECR-015 Closed** | RedemptionCode — Spec `ops-redemption-code.md` |
| **IECR-016 Closed** | UserIntelligence — Spec `ops-user-intelligence.md` |
| 后置 | AskOperations / Entitlement 细权(Loop 续跑) |
| D | 订单筛选 · 展示价 · 退款只读(另开 ECR) |
| 后置 | 封禁加深(Account_Risk)· 推送占位 |
@@ -0,0 +1,39 @@
# Feature Spec: 用户洞察 UserIntelligenceOps · ECR-016
> Status: `Active`Loop continuous · **ECR-016 Closed**
> Parent: WAVE0-FROZEN · Predecessor: ECR-015 Closed
> Capability: `UserIntelligence` · BC: `Identity_Profile`(读)+ `Analytics_OpsB`(读)
> 授权:`docs/WAVE0/LOOP_AUTHORIZATION.md`
## Non-goals
写标签 · 改报告正文 · Ask 全文运营编辑 · UGC · 真支付 · 新表(本切片纯读模型聚合)
## L2 读模型(无 migration
| 概念 | 来源 |
|------|------|
| `UserProfileView` | profiles 摘要(已有 detail |
| `InsightReport` | growth_reports 类型计数 + 最近列表 |
| `PsychologicalTagSet` | 由报告 type 派生的稳定标签(非 NLP) |
| `BehaviorSnapshot` | analytics_events 最近页面/事件(若有) |
## L3 API
| Method | Path | 权限 | 语义 |
|--------|------|------|------|
| GET | `/admin/users/:id/insight` | `admin.users.read` | 聚合洞察只读 |
## L4 AC
| ID | Then |
|----|------|
| AC-F-01 | 有报告用户 → insight.reports_by_type 非空或 reports 列表 |
| AC-F-02 | tags 含报告类型映射标签 |
| AC-F-03 | 无埋点时 behavior.events=[] 仍 200 |
| AC-S-01 | 无 Admin → 401 |
| AC-S-02 | 无 users.read → 403 |
| AC-P-01 | GET insight &lt; 500ms 本机 |
| AC-O-01 | N/A 只读(无写审计) |
contract_diff: `docs/CONTRACT_DIFF/ECR-016.yaml`
+23 -1
View File
@@ -31,7 +31,17 @@ async function request<T>(method: string, path: string, body?: unknown): Promise
headers,
body: body === undefined ? undefined : JSON.stringify(body),
})
const env = (await res.json()) as ApiEnvelope<T>
const text = await res.text()
let env: ApiEnvelope<T>
try {
env = JSON.parse(text) as ApiEnvelope<T>
} catch {
throw new Error(
res.status === 404
? `接口不存在或后端未更新(${path}`
: `响应不是 JSONHTTP ${res.status}`,
)
}
if (!res.ok || env.code !== 0) {
throw new Error(env.message || `HTTP ${res.status}`)
}
@@ -130,6 +140,18 @@ export const adminApi = {
created_at: string
}>
}>('GET', `/users/${id}/status-transitions`),
userInsight: (id: string) =>
request<{
user_id: string
profiles_count: number
reports_by_type: Array<{ type: string; count: number }>
recent_reports: Array<{ id: string; type: string; created_at: string }>
tags: Array<{ code: string; label: string }>
behavior: {
events: Array<{ name: string; page_path?: string; received_at: string }>
ask_thread_count: number
}
}>('GET', `/users/${id}/insight`),
grant: (id: string, plan: string) =>
request<{ ok: boolean }>('POST', `/users/${id}/membership/grant`, { plan }),
grantAskQuota: (id: string, delta: number) =>
+226 -108
View File
@@ -1,14 +1,20 @@
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { computed, onMounted, ref, watch } from 'vue'
import { RouterLink, useRoute } from 'vue-router'
import { adminApi, type UserDetail } from '@/api/client'
import { useAuthStore } from '@/stores/auth'
type Insight = Awaited<ReturnType<typeof adminApi.userInsight>>
const route = useRoute()
const auth = useAuthStore()
const loading = ref(false)
const error = ref('')
const detail = ref<UserDetail | null>(null)
const tab = ref<'base' | 'insight'>('base')
const insight = ref<Insight | null>(null)
const insightErr = ref('')
const insightLoading = ref(false)
const plan = ref('month')
const askDelta = ref(10)
const grantMsg = ref('')
@@ -33,8 +39,15 @@ async function load() {
try {
const id = String(route.params.id)
detail.value = await adminApi.user(id)
const tr = await adminApi.statusTransitions(id)
transitions.value = tr.items || []
try {
const tr = await adminApi.statusTransitions(id)
transitions.value = tr.items || []
} catch {
transitions.value = []
}
if (tab.value === 'insight') {
await loadInsight()
}
} catch (e) {
error.value = e instanceof Error ? e.message : '加载失败'
} finally {
@@ -42,6 +55,25 @@ async function load() {
}
}
async function loadInsight() {
insightLoading.value = true
insightErr.value = ''
try {
insight.value = await adminApi.userInsight(String(route.params.id))
} catch (e) {
insightErr.value = e instanceof Error ? e.message : '洞察加载失败'
insight.value = null
} finally {
insightLoading.value = false
}
}
watch(tab, (v) => {
if (v === 'insight' && !insight.value && !insightLoading.value) {
void loadInsight()
}
})
async function grant() {
grantMsg.value = ''
try {
@@ -104,119 +136,187 @@ onMounted(load)
<p v-if="loading" class="muted">加载中</p>
<p v-else-if="error" class="err">{{ error }}</p>
<template v-else-if="detail">
<div class="card block">
<h2>账号</h2>
<div class="kv">
<div><span>昵称</span><strong>{{ detail.nickname || '—' }}</strong></div>
<div><span>手机</span><strong>{{ detail.phone || '—' }}</strong></div>
<div><span>状态</span><strong>{{ detail.status }}</strong></div>
<div><span>创建</span><strong>{{ fmtTime(detail.created_at) }}</strong></div>
<div class="wide"><span>ID</span><code>{{ detail.id }}</code></div>
</div>
<div v-if="canWriteStatus" class="grant">
<select v-model="nextStatus">
<option value="active">active</option>
<option value="disabled">disabled</option>
<option value="banned">banned</option>
<option value="suspended">suspended</option>
</select>
<input v-model="statusReason" class="reason" type="text" placeholder="原因(必填)" />
<button class="btn" type="button" @click="changeStatus">变更状态</button>
<span v-if="statusMsg" class="muted">{{ statusMsg }}</span>
</div>
<div v-if="transitions.length" class="trans">
<h3>状态迁移</h3>
<ul>
<li v-for="(t, i) in transitions" :key="i">
{{ t.from_status }} {{ t.to_status }} · {{ t.reason || '' }} · {{ fmtTime(t.created_at) }}
</li>
</ul>
</div>
<div class="tabs">
<button type="button" :class="{ on: tab === 'base' }" @click="tab = 'base'">基础</button>
<button type="button" :class="{ on: tab === 'insight' }" @click="tab = 'insight'">洞察</button>
</div>
<div class="card block">
<h2>成长会员</h2>
<p v-if="detail.membership">
{{ detail.membership.active ? '有效' : '无效' }} ·
{{ detail.membership.plan || '' }} ·
会员问答余量 {{ detail.membership.ask_quota_left ?? 0 }} ·
到期 {{ fmtTime(detail.membership.expires_at) }}
</p>
<div class="grant">
<select v-model="plan">
<option value="month">月卡</option>
<option value="quarter">季卡</option>
<option value="year">年卡</option>
</select>
<button class="btn" type="button" @click="grant">授予 / 延长</button>
<span v-if="grantMsg" class="muted">{{ grantMsg }}</span>
<template v-if="tab === 'base'">
<div class="card block">
<h2>账号</h2>
<div class="kv">
<div><span>昵称</span><strong>{{ detail.nickname || '—' }}</strong></div>
<div><span>手机</span><strong>{{ detail.phone || '—' }}</strong></div>
<div><span>状态</span><strong>{{ detail.status }}</strong></div>
<div><span>创建</span><strong>{{ fmtTime(detail.created_at) }}</strong></div>
<div class="wide"><span>ID</span><code>{{ detail.id }}</code></div>
</div>
<div v-if="canWriteStatus" class="grant">
<select v-model="nextStatus">
<option value="active">active</option>
<option value="disabled">disabled</option>
<option value="banned">banned</option>
<option value="suspended">suspended</option>
</select>
<input v-model="statusReason" class="reason" type="text" placeholder="原因(必填)" />
<button class="btn" type="button" @click="changeStatus">变更状态</button>
<span v-if="statusMsg" class="muted">{{ statusMsg }}</span>
</div>
<div v-if="transitions.length" class="trans">
<h3>状态迁移</h3>
<ul>
<li v-for="(t, i) in transitions" :key="i">
{{ t.from_status }} {{ t.to_status }} · {{ t.reason || '' }} · {{ fmtTime(t.created_at) }}
</li>
</ul>
</div>
</div>
</div>
<div class="card block">
<h2>问答额度已购</h2>
<p>已购余量<strong>{{ detail.ask_paid_quota_left }}</strong> </p>
<div class="grant">
<select v-model.number="askDelta">
<option :value="10">+10</option>
<option :value="30">+30</option>
<option :value="100">+100</option>
</select>
<button class="btn" type="button" @click="grantAsk">增加额度</button>
<span v-if="askMsg" class="muted">{{ askMsg }}</span>
<div class="card block">
<h2>成长会员</h2>
<p v-if="detail.membership">
{{ detail.membership.active ? '有效' : '无效' }} ·
{{ detail.membership.plan || '' }} ·
会员问答余量 {{ detail.membership.ask_quota_left ?? 0 }} ·
到期 {{ fmtTime(detail.membership.expires_at) }}
</p>
<div class="grant">
<select v-model="plan">
<option value="month">月卡</option>
<option value="quarter">季卡</option>
<option value="year">年卡</option>
</select>
<button class="btn" type="button" @click="grant">授予 / 延长</button>
<span v-if="grantMsg" class="muted">{{ grantMsg }}</span>
</div>
</div>
</div>
<div class="card block">
<h2>档案{{ detail.profiles?.length || 0 }}</h2>
<p v-if="!detail.profiles?.length" class="muted">无档案</p>
<table v-else>
<thead>
<tr><th>称呼</th><th>关系</th><th>生日</th><th>ID</th></tr>
</thead>
<tbody>
<tr v-for="p in detail.profiles" :key="p.id">
<td>{{ p.display_name || '未命名' }}</td>
<td>{{ p.relation }}</td>
<td>{{ p.birth_date || '—' }}</td>
<td><code>{{ p.id.slice(0, 8) }}</code></td>
</tr>
</tbody>
</table>
</div>
<div class="card block">
<h2>问答额度已购</h2>
<p>已购余量<strong>{{ detail.ask_paid_quota_left }}</strong> </p>
<div class="grant">
<select v-model.number="askDelta">
<option :value="10">+10</option>
<option :value="30">+30</option>
<option :value="100">+100</option>
</select>
<button class="btn" type="button" @click="grantAsk">增加额度</button>
<span v-if="askMsg" class="muted">{{ askMsg }}</span>
</div>
</div>
<div class="card block">
<h2>成长报告 {{ detail.reports?.length || 0 }}</h2>
<p v-if="!detail.reports?.length" class="muted">报告</p>
<table v-else>
<thead>
<tr><th>类型</th><th>时间</th><th>ID</th></tr>
</thead>
<tbody>
<tr v-for="r in detail.reports" :key="r.id">
<td>{{ typeLabel[r.type] || r.type }}</td>
<td>{{ fmtTime(r.created_at) }}</td>
<td><code>{{ r.id.slice(0, 8) }}</code></td>
</tr>
</tbody>
</table>
</div>
<div class="card block">
<h2>档案{{ detail.profiles?.length || 0 }}</h2>
<p v-if="!detail.profiles?.length" class="muted">档案</p>
<table v-else>
<thead>
<tr><th>称呼</th><th>关系</th><th>生日</th><th>ID</th></tr>
</thead>
<tbody>
<tr v-for="p in detail.profiles" :key="p.id">
<td>{{ p.display_name || '未命名' }}</td>
<td>{{ p.relation }}</td>
<td>{{ p.birth_date || '—' }}</td>
<td><code>{{ p.id.slice(0, 8) }}</code></td>
</tr>
</tbody>
</table>
</div>
<div class="card block">
<h2>近订单</h2>
<p v-if="!detail.recent_orders?.length" class="muted">订单</p>
<table v-else>
<thead><tr><th>类型</th><th>状态</th><th>金额</th><th>时间</th></tr></thead>
<tbody>
<tr v-for="o in detail.recent_orders" :key="o.id">
<td>{{ o.kind }} {{ o.plan || '' }}</td>
<td>{{ o.status }}</td>
<td>{{ (o.amount_cents / 100).toFixed(2) }}</td>
<td>{{ fmtTime(o.created_at) }}</td>
</tr>
</tbody>
</table>
</div>
<div class="card block">
<h2>成长报告 {{ detail.reports?.length || 0 }}</h2>
<p v-if="!detail.reports?.length" class="muted">报告</p>
<table v-else>
<thead>
<tr><th>类型</th><th>时间</th><th>ID</th></tr>
</thead>
<tbody>
<tr v-for="r in detail.reports" :key="r.id">
<td>{{ typeLabel[r.type] || r.type }}</td>
<td>{{ fmtTime(r.created_at) }}</td>
<td><code>{{ r.id.slice(0, 8) }}</code></td>
</tr>
</tbody>
</table>
</div>
<div class="card block">
<h2>近订单</h2>
<p v-if="!detail.recent_orders?.length" class="muted">无订单</p>
<table v-else>
<thead><tr><th>类型</th><th>状态</th><th>金额</th><th>时间</th></tr></thead>
<tbody>
<tr v-for="o in detail.recent_orders" :key="o.id">
<td>{{ o.kind }} {{ o.plan || '' }}</td>
<td>{{ o.status }}</td>
<td>{{ (o.amount_cents / 100).toFixed(2) }}</td>
<td>{{ fmtTime(o.created_at) }}</td>
</tr>
</tbody>
</table>
</div>
</template>
<template v-else>
<p v-if="insightLoading" class="muted">加载洞察</p>
<p v-else-if="insightErr" class="err">{{ insightErr }}</p>
<template v-else-if="insight">
<div class="card block">
<h2>概览</h2>
<div class="kv">
<div><span>档案数</span><strong>{{ insight.profiles_count }}</strong></div>
<div><span>问答线程</span><strong>{{ insight.behavior.ask_thread_count }}</strong></div>
</div>
</div>
<div class="card block">
<h2>心理标签派生</h2>
<p v-if="!insight.tags?.length" class="muted">暂无无成长报告类型</p>
<ul v-else class="tags">
<li v-for="t in insight.tags" :key="t.code">{{ t.label }} <code>{{ t.code }}</code></li>
</ul>
</div>
<div class="card block">
<h2>报告类型</h2>
<p v-if="!insight.reports_by_type?.length" class="muted"></p>
<table v-else>
<thead><tr><th>类型</th><th>次数</th></tr></thead>
<tbody>
<tr v-for="c in insight.reports_by_type" :key="c.type">
<td>{{ typeLabel[c.type] || c.type }}</td>
<td>{{ c.count }}</td>
</tr>
</tbody>
</table>
</div>
<div class="card block">
<h2>近报告</h2>
<p v-if="!insight.recent_reports?.length" class="muted"></p>
<table v-else>
<thead><tr><th>类型</th><th>时间</th></tr></thead>
<tbody>
<tr v-for="r in insight.recent_reports" :key="r.id">
<td>{{ typeLabel[r.type] || r.type }}</td>
<td>{{ fmtTime(r.created_at) }}</td>
</tr>
</tbody>
</table>
</div>
<div class="card block">
<h2>行为快照</h2>
<p v-if="!insight.behavior.events?.length" class="muted">暂无埋点仍为正常</p>
<table v-else>
<thead><tr><th>事件</th><th>页面</th><th>时间</th></tr></thead>
<tbody>
<tr v-for="(e, i) in insight.behavior.events" :key="i">
<td>{{ e.name }}</td>
<td>{{ e.page_path || '—' }}</td>
<td>{{ fmtTime(e.received_at) }}</td>
</tr>
</tbody>
</table>
</div>
</template>
</template>
</template>
</section>
</template>
@@ -227,6 +327,16 @@ onMounted(load)
h1 { margin: 0 0 1rem; font-size: 1.35rem; }
h2 { margin: 0 0 0.6rem; font-size: 1.05rem; }
h3 { margin: 0.75rem 0 0.35rem; font-size: 0.95rem; }
.tabs { display: flex; gap: 0.35rem; margin-bottom: 1rem; }
.tabs button {
border: 1px solid var(--line);
background: transparent;
border-radius: 8px;
padding: 0.4rem 0.85rem;
cursor: pointer;
color: var(--muted);
}
.tabs button.on { color: var(--text); border-color: var(--accent); }
.block { margin-bottom: 1rem; }
.kv {
display: grid;
@@ -244,4 +354,12 @@ h3 { margin: 0.75rem 0 0.35rem; font-size: 0.95rem; }
}
.grant .reason { min-width: 12rem; }
.trans ul { margin: 0; padding-left: 1.1rem; color: var(--muted); font-size: 0.85rem; }
.tags { list-style: none; margin: 0; padding: 0; display: flex; flex-wrap: wrap; gap: 0.5rem; }
.tags li {
border: 1px solid var(--line);
border-radius: 8px;
padding: 0.35rem 0.6rem;
font-size: 0.9rem;
}
.tags code { margin-left: 0.35rem; font-size: 0.75rem; color: var(--muted); }
</style>
+1
View File
@@ -46,6 +46,7 @@ func (h *AdminHandler) Register(api *gin.RouterGroup) {
h.registerLifecycle(authed)
h.registerMembershipPlans(authed)
h.registerRedemption(authed)
h.registerInsight(authed)
}
func (h *AdminHandler) Login(c *gin.Context) {
@@ -0,0 +1,35 @@
package handler
import (
"errors"
"net/http"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/yuxingu/digital-psychology/apps/api/internal/middleware"
"github.com/yuxingu/digital-psychology/apps/api/internal/service/admin"
"github.com/yuxingu/digital-psychology/apps/api/pkg/response"
)
func (h *AdminHandler) registerInsight(authed *gin.RouterGroup) {
authed.GET("/users/:id/insight", middleware.RequireAdminPermission(h.Svc, admin.PermUsersRead), h.GetUserInsight)
}
func (h *AdminHandler) GetUserInsight(c *gin.Context) {
id, err := uuid.Parse(c.Param("id"))
if err != nil {
response.Fail(c, http.StatusBadRequest, 40002, "invalid user id")
return
}
insight, err := h.Svc.GetUserInsight(c.Request.Context(), id)
if errors.Is(err, admin.ErrUserNotFound) {
response.Fail(c, http.StatusNotFound, 40401, "user not found")
return
}
if err != nil {
response.Fail(c, http.StatusInternalServerError, 50018, "get insight failed")
return
}
response.OK(c, insight)
}
@@ -0,0 +1,124 @@
package integration_test
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"testing"
"time"
)
func TestUserInsight(t *testing.T) {
r, _ := setupAPIPool(t)
tok := adminLogin(t, r, "admin", "change-me")
_, code := doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/users/"+fakeUUID()+"/insight", nil, "")
if code != http.StatusUnauthorized {
t.Fatalf("expected 401 without token, got %d", code)
}
testBearer = ""
phone := fmt.Sprintf("1%010d", time.Now().UnixNano()%10_000_000_000)
nick := "insight_" + phone[7:]
env, key := doJSON(t, r, http.MethodPost, "/api/v1/auth/register", map[string]any{
"phone": phone, "password": "secret12", "nickname": nick,
}, "")
sess := decodeData[map[string]any](t, env.Data)
tokUser, _ := sess["token"].(string)
if tokUser == "" {
t.Fatal("missing token")
}
testBearer = tokUser
t.Cleanup(func() { testBearer = "" })
env, key = doJSON(t, r, http.MethodPost, "/api/v1/profiles", map[string]any{
"relation": "self", "birth_date": "1991-04-08", "display_name": "洞察测",
}, key)
profile := decodeData[map[string]any](t, env.Data)
profileID, _ := profile["id"].(string)
_, key = doJSON(t, r, http.MethodPost, "/api/v1/reports/portrait", map[string]any{
"profile_id": profileID,
}, key)
env, code = doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/users?q="+url.QueryEscape(nick), nil, tok)
if code != 200 {
t.Fatalf("list users http=%d", code)
}
var list struct {
Items []struct {
ID string `json:"id"`
} `json:"items"`
}
_ = json.Unmarshal(env.Data, &list)
if len(list.Items) == 0 {
t.Fatal("expected users")
}
userID := list.Items[0].ID
start := time.Now()
env, code = doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/users/"+userID+"/insight", nil, tok)
if code != 200 || env.Code != 0 {
t.Fatalf("insight http=%d code=%d msg=%s", code, env.Code, env.Message)
}
if time.Since(start) > 500*time.Millisecond {
t.Fatalf("insight too slow: %v", time.Since(start))
}
var insight struct {
UserID string `json:"user_id"`
ProfilesCount int `json:"profiles_count"`
ReportsByType []struct {
Type string `json:"type"`
Count int `json:"count"`
} `json:"reports_by_type"`
Tags []struct {
Code string `json:"code"`
Label string `json:"label"`
} `json:"tags"`
Behavior struct {
Events []any `json:"events"`
AskThreadCount int `json:"ask_thread_count"`
} `json:"behavior"`
}
if err := json.Unmarshal(env.Data, &insight); err != nil {
t.Fatalf("decode insight: %v %s", err, env.Data)
}
if insight.UserID != userID {
t.Fatalf("user_id mismatch %s vs %s", insight.UserID, userID)
}
if insight.ProfilesCount < 1 {
t.Fatalf("expected profiles_count>=1 got %d", insight.ProfilesCount)
}
foundPortrait := false
for _, c := range insight.ReportsByType {
if c.Type == "portrait" && c.Count >= 1 {
foundPortrait = true
}
}
if !foundPortrait {
t.Fatalf("expected portrait in reports_by_type: %#v", insight.ReportsByType)
}
foundTag := false
for _, tag := range insight.Tags {
if tag.Code == "portrait" && tag.Label != "" {
foundTag = true
}
}
if !foundTag {
t.Fatalf("expected portrait tag: %#v", insight.Tags)
}
if insight.Behavior.Events == nil {
t.Fatal("behavior.events must be non-nil array")
}
_, code = doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/users/"+fakeUUID()+"/insight", nil, tok)
if code != http.StatusNotFound {
t.Fatalf("expected 404 missing user, got %d", code)
}
_ = key
}
func fakeUUID() string {
return "00000000-0000-4000-8000-000000000099"
}
@@ -0,0 +1,86 @@
package repository
import (
"context"
"time"
"github.com/google/uuid"
)
// ReportTypeCount aggregates growth_reports by type.
type ReportTypeCount struct {
Type string `json:"type"`
Count int `json:"count"`
}
// BehaviorEventBrief is a recent analytics event for ops insight.
type BehaviorEventBrief struct {
Name string `json:"name"`
PagePath string `json:"page_path,omitempty"`
ReceivedAt time.Time `json:"received_at"`
}
// CountReportsByType groups non-deleted reports for a user.
func (r *AdminRepo) CountReportsByType(ctx context.Context, userID uuid.UUID) ([]ReportTypeCount, error) {
rows, err := r.Pool.Query(ctx, `
SELECT type, count(*)::int FROM growth_reports
WHERE user_id=$1 AND deleted_at IS NULL
GROUP BY type ORDER BY count(*) DESC, type ASC`, userID)
if err != nil {
return nil, err
}
defer rows.Close()
var out []ReportTypeCount
for rows.Next() {
var c ReportTypeCount
if err := rows.Scan(&c.Type, &c.Count); err != nil {
return nil, err
}
out = append(out, c)
}
return out, rows.Err()
}
// CountProfilesForUser returns active profile count.
func (r *AdminRepo) CountProfilesForUser(ctx context.Context, userID uuid.UUID) (int, error) {
var n int
err := r.Pool.QueryRow(ctx, `
SELECT count(*)::int FROM profiles
WHERE user_id=$1 AND deleted_at IS NULL`, userID).Scan(&n)
return n, err
}
// CountAskThreadsForUser returns non-deleted ask threads.
func (r *AdminRepo) CountAskThreadsForUser(ctx context.Context, userID uuid.UUID) (int, error) {
var n int
err := r.Pool.QueryRow(ctx, `
SELECT count(*)::int FROM ask_threads
WHERE user_id=$1 AND deleted_at IS NULL`, userID).Scan(&n)
return n, err
}
// ListRecentEventsForUser returns recent analytics events (may be empty).
func (r *AdminRepo) ListRecentEventsForUser(ctx context.Context, userID uuid.UUID, limit int) ([]BehaviorEventBrief, error) {
if limit <= 0 || limit > 50 {
limit = 20
}
rows, err := r.Pool.Query(ctx, `
SELECT name, coalesce(page_path, ''), received_at
FROM analytics_events
WHERE user_id=$1
ORDER BY received_at DESC
LIMIT $2`, userID, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var out []BehaviorEventBrief
for rows.Next() {
var e BehaviorEventBrief
if err := rows.Scan(&e.Name, &e.PagePath, &e.ReceivedAt); err != nil {
return nil, err
}
out = append(out, e)
}
return out, rows.Err()
}
+106
View File
@@ -0,0 +1,106 @@
package admin
import (
"context"
"github.com/google/uuid"
"github.com/yuxingu/digital-psychology/apps/api/internal/repository"
)
// PsychTag is a stable label derived from report types (not NLP).
type PsychTag struct {
Code string `json:"code"`
Label string `json:"label"`
}
// BehaviorSnapshot is a thin ops read of recent activity.
type BehaviorSnapshot struct {
Events []repository.BehaviorEventBrief `json:"events"`
AskThreadCount int `json:"ask_thread_count"`
}
// UserInsight is the UserIntelligence admin read model.
type UserInsight struct {
UserID uuid.UUID `json:"user_id"`
ProfilesCount int `json:"profiles_count"`
ReportsByType []repository.ReportTypeCount `json:"reports_by_type"`
RecentReports []repository.ReportBrief `json:"recent_reports"`
Tags []PsychTag `json:"tags"`
Behavior BehaviorSnapshot `json:"behavior"`
}
var reportTypeLabels = map[string]string{
"portrait": "愈心解码",
"star": "星座",
"rhythm": "节律",
"relation": "关系",
"synastry": "合盘",
"image_card": "意象卡",
}
// GetUserInsight aggregates read-only ops insight for one user.
func (s *Service) GetUserInsight(ctx context.Context, userID uuid.UUID) (*UserInsight, error) {
ok, err := s.Repo.UserExists(ctx, userID)
if err != nil {
return nil, err
}
if !ok {
return nil, ErrUserNotFound
}
pc, err := s.Repo.CountProfilesForUser(ctx, userID)
if err != nil {
return nil, err
}
byType, err := s.Repo.CountReportsByType(ctx, userID)
if err != nil {
return nil, err
}
if byType == nil {
byType = []repository.ReportTypeCount{}
}
reports, err := s.Repo.ListReportsForUser(ctx, userID, 10)
if err != nil {
return nil, err
}
if reports == nil {
reports = []repository.ReportBrief{}
}
events, err := s.Repo.ListRecentEventsForUser(ctx, userID, 20)
if err != nil {
return nil, err
}
if events == nil {
events = []repository.BehaviorEventBrief{}
}
askN, err := s.Repo.CountAskThreadsForUser(ctx, userID)
if err != nil {
return nil, err
}
return &UserInsight{
UserID: userID,
ProfilesCount: pc,
ReportsByType: byType,
RecentReports: reports,
Tags: tagsFromReportTypes(byType),
Behavior: BehaviorSnapshot{
Events: events,
AskThreadCount: askN,
},
}, nil
}
func tagsFromReportTypes(counts []repository.ReportTypeCount) []PsychTag {
out := make([]PsychTag, 0, len(counts))
for _, c := range counts {
if c.Count <= 0 {
continue
}
label := reportTypeLabels[c.Type]
if label == "" {
label = c.Type
}
out = append(out, PsychTag{Code: c.Type, Label: label})
}
return out
}
@@ -0,0 +1,24 @@
# Backend Design: ECR-016 UserIntelligence
| ID | BD-2026-016 |
| Status | Approved |
| Coding | Loop authorized |
| Level | L2 |
| Migration | NO |
## Backend Change Boundary
```text
Domain: UserInsight read model (BehaviorSnapshot · PsychologicalTagSet derived)
App: AdminHandler → admin.Service → AdminRepo aggregates
API: GET /api/v1/admin/users/{id}/insight
Permission: admin.users.read
Migration: NO
UI: admin-h5 UserDetail「洞察」Tab
```
## Out of boundary
Write tags · new tables · Ask body edit · UGC · true payment
Rollback: remove route + UI tab(无 schema
+1
View File
@@ -2,6 +2,7 @@
## 2026-08-07
- **ECR-016 Closed**UserIntelligence`GET /admin/users/:id/insight` 只读聚合 · admin-h5 洞察 Tab · Migration NO
- **ECR-015 Closed**RedemptionCode(批次生成 · C端兑码 · 作废 · 审计)
- **ECR-014 Closed**MembershipPlan(套餐表 · admin 配置 · Grant/CreateOrder 读表)
- **LOOP continuous**`docs/WAVE0/LOOP_AUTHORIZATION.md` — Human 授权免逐闸确认
+9
View File
@@ -0,0 +1,9 @@
# CODE_REVIEW — ECR-016
**Verdict:** Approve → Closed
Date: 2026-08-07 · Loop continuous
- Additive GET insight onlyMigration NO
- Handler → Service → Repository;无 UGC / 真支付
- Integration AC mapped · OpenAPI updated
+17
View File
@@ -0,0 +1,17 @@
ecr: ECR-016
capability: UserIntelligence
bounded_context: Identity_Profile
parent: WAVE0-FROZEN
predecessor: ECR-015
change:
type: additive
breaking_change: false
migration_required: false
compatibility_notes: >
Additive read API GET /admin/users/{id}/insight.
No schema change; aggregates existing tables.
apis:
- method: GET
path: /api/v1/admin/users/{id}/insight
change: added
+19
View File
@@ -0,0 +1,19 @@
# ECR-016
**Title:** UserIntelligence(用户洞察只读薄切片)
**Status:** **Closed**
**Closed:** 2026-08-07Loop continuous
**Parent:** WAVE0-FROZEN · **Predecessor:** ECR-015 Closed
**Change Level:** L2
## Change
`GET /admin/users/:id/insight` 聚合报告/标签/行为快照;admin-h5 用户详情「洞察」区。
## Forbidden
新表 · 写标签 · Ask 正文编辑 · 真支付 · UGC
## Linked
Spec `ops-user-intelligence.md` · BD-2026-016 · CONTRACT_DIFF/ECR-016.yaml · TEST_REPORT/ECR-016.md
@@ -0,0 +1,8 @@
# ENGINEERING_SPEC — ECR-016
1. Repo Insight 聚合查询
2. GET /users/:id/insight + OpenAPI
3. admin-h5 用户详情洞察区
4. Integration · Closed
Migration: **NO**
@@ -0,0 +1,3 @@
# HANDOFF — ECR-016 Architect → Engineer
Loop continuous · Approved + Coding. Migration NO. Forbidden: 写模型/UGC/真支付.
@@ -0,0 +1,3 @@
# HANDOFF — ECR-016 Engineer → Reviewer
TestUserInsight PASS · admin-h5 洞察 Tab · Ready for Closed.
@@ -0,0 +1,3 @@
# PRODUCT_SPEC — ECR-016
对齐 ops-user-intelligence.md · Approved · Loop · L2 · 只读聚合
+6
View File
@@ -0,0 +1,6 @@
# STATE — ECR-016
| Status | **Closed** |
| Phase | closed |
| Spec | ops-user-intelligence.md |
| Updated | 2026-08-07 |
+11
View File
@@ -0,0 +1,11 @@
id: TASK-016-ECR016
ecr: ECR-016
title: UserIntelligence implement
role: engineer
status: closed
change_level: L2
parent: WAVE0-FROZEN
predecessor: ECR-015
acceptance:
- Spec AC mapped
- No migration / no UGC / no payment
+31
View File
@@ -0,0 +1,31 @@
# TEST_REPORT — ECR-016 UserIntelligence
Date: 2026-08-07 · Loop continuous · commit: (pending this commit)
## Commands
```bash
cd apps/api && go test ./internal/integration/ -run TestUserInsight -count=1
npm run build:admin
python3 scripts/ess-validate.py --phase review --ecr ECR-016
```
## Results
| Check | Result |
|-------|--------|
| TestUserInsight | PASS |
| build:admin | PASS |
| ess-validate review | PASS |
## AC
| ID | Evidence |
|----|----------|
| AC-F-01 | insight.reports_by_type 含 portrait |
| AC-F-02 | tags 含 portrait 映射标签 |
| AC-F-03 | behavior.events=[] 仍 200 |
| AC-S-01 | 无 token → 401 |
| AC-S-02 | RequireAdminPermission(admin.users.read) |
| AC-P-01 | GET insight &lt; 500ms |
| AC-O-01 | N/A 只读 |
+3
View File
@@ -18,3 +18,6 @@
| WAVE-0 | Ops Contract-First Foundation | **FROZEN** (`WAVE0-FROZEN` @ 27f27a1) | `docs/WAVE0/` · HUMAN_REVIEW FREEZE · boundary-rules · glossary · contract template |
| ECR-013A | Admin RBAC | **Closed** | Spec ops-rbac · BD-2026-013A · migration 000015 · TEST_REPORT · CODE_REVIEW Approve · Parent WAVE0-FROZEN |
| ECR-015 | RedemptionCode | **Closed** | Spec ops-redemption-code · migration 000018 · TEST_REPORT · Loop continuous |
| ECR-013B | AccountLifecycle | **Closed** | Spec ops-account-lifecycle · BD-2026-013B · TEST_REPORT · Parent WAVE0-FROZEN |
| ECR-014 | MembershipPlan | **Closed** | Spec ops-membership-plan · BD-2026-014 · TEST_REPORT · Loop continuous |
| ECR-016 | UserIntelligence | **Closed** | Spec ops-user-intelligence · BD-2026-016 · TEST_REPORT · CODE_REVIEW · Loop continuous |
+1 -1
View File
@@ -30,4 +30,4 @@ Human 明文:**直接用 Loop,不用人工确认。**
| Done | Next |
|------|------|
| ECR-013A/B/014/015 Closed | **ECR-016** UserIntelligence 薄切片(只读洞察);禁真支付/UGC |
| ECR-013A/B/014/015/016 Closed | **ECR-017** AskOperations 薄切片(只读会话视图优先);禁真支付/UGC |
+20
View File
@@ -242,6 +242,26 @@ paths:
'401':
description: Unauthorized
/api/v1/admin/users/{id}/insight:
get:
tags: [admin]
summary: UserIntelligence insight (read-only aggregate)
description: Requires admin.users.read; no schema write
parameters:
- in: path
name: id
required: true
schema: { type: string, format: uuid }
responses:
'200':
description: OK
'401':
description: Unauthorized
'403':
description: Forbidden
'404':
description: User not found
/api/v1/admin/membership-plans:
get:
tags: [admin]