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