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
+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
}