feat(ECR-018): Entitlement 用户权益只读并 Closed
聚合 GET /admin/users/:id/entitlements(Membership∪DeepAccess∪问答额度)与 admin-h5 权益 Tab;无 migration / 无真支付。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -48,6 +48,7 @@ func (h *AdminHandler) Register(api *gin.RouterGroup) {
|
||||
h.registerRedemption(authed)
|
||||
h.registerInsight(authed)
|
||||
h.registerAskOps(authed)
|
||||
h.registerEntitlement(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) registerEntitlement(authed *gin.RouterGroup) {
|
||||
authed.GET("/users/:id/entitlements", middleware.RequireAdminPermission(h.Svc, admin.PermUsersRead), h.GetUserEntitlements)
|
||||
}
|
||||
|
||||
func (h *AdminHandler) GetUserEntitlements(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
response.Fail(c, http.StatusBadRequest, 40002, "invalid user id")
|
||||
return
|
||||
}
|
||||
ent, err := h.Svc.GetUserEntitlement(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, 50021, "get entitlements failed")
|
||||
return
|
||||
}
|
||||
response.OK(c, ent)
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestUserEntitlements(t *testing.T) {
|
||||
r, _ := setupAPIPool(t)
|
||||
tok := adminLogin(t, r, "admin", "change-me")
|
||||
|
||||
_, code := doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/users/"+fakeUUID()+"/entitlements", nil, "")
|
||||
if code != http.StatusUnauthorized {
|
||||
t.Fatalf("expected 401, got %d", code)
|
||||
}
|
||||
|
||||
testBearer = ""
|
||||
phone := fmt.Sprintf("1%010d", time.Now().UnixNano()%10_000_000_000)
|
||||
nick := "ent_" + 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)
|
||||
testBearer = sess["token"].(string)
|
||||
t.Cleanup(func() { testBearer = "" })
|
||||
|
||||
env, key = doJSON(t, r, http.MethodPost, "/api/v1/profiles", map[string]any{
|
||||
"relation": "self", "birth_date": "1990-01-01", "display_name": "权",
|
||||
}, key)
|
||||
profileID := decodeData[map[string]any](t, env.Data)["id"].(string)
|
||||
|
||||
env, key = doJSON(t, r, http.MethodPost, "/api/v1/reports/portrait", map[string]any{
|
||||
"profile_id": profileID,
|
||||
}, key)
|
||||
reportID := decodeData[map[string]any](t, env.Data)["id"].(string)
|
||||
|
||||
env, key = doJSON(t, r, http.MethodPost, "/api/v1/orders", map[string]any{
|
||||
"kind": "deep_access", "report_id": reportID,
|
||||
}, key)
|
||||
orderID := decodeData[map[string]any](t, env.Data)["order_id"].(string)
|
||||
_, key = doJSON(t, r, http.MethodPost, "/api/v1/orders/"+orderID+"/pay-mock", nil, 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 %d", code)
|
||||
}
|
||||
var list struct {
|
||||
Items []struct {
|
||||
ID string `json:"id"`
|
||||
} `json:"items"`
|
||||
}
|
||||
_ = json.Unmarshal(env.Data, &list)
|
||||
userID := list.Items[0].ID
|
||||
|
||||
start := time.Now()
|
||||
env, code = doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/users/"+userID+"/entitlements", nil, tok)
|
||||
if code != 200 || env.Code != 0 {
|
||||
t.Fatalf("entitlements http=%d msg=%s", code, env.Message)
|
||||
}
|
||||
if time.Since(start) > 500*time.Millisecond {
|
||||
t.Fatalf("too slow %v", time.Since(start))
|
||||
}
|
||||
var before struct {
|
||||
Flags struct {
|
||||
ViaMem bool `json:"report_detail_via_membership"`
|
||||
Count int `json:"deep_access_count"`
|
||||
} `json:"flags"`
|
||||
Deep []any `json:"deep_accesses"`
|
||||
}
|
||||
_ = json.Unmarshal(env.Data, &before)
|
||||
if before.Flags.Count < 1 || len(before.Deep) < 1 {
|
||||
t.Fatalf("expected deep_access: %#v", before)
|
||||
}
|
||||
if before.Flags.ViaMem {
|
||||
t.Fatal("expected membership inactive before grant")
|
||||
}
|
||||
|
||||
_, code = doAdminJSON(t, r, http.MethodPost, "/api/v1/admin/users/"+userID+"/membership/grant",
|
||||
map[string]string{"plan": "month"}, tok)
|
||||
if code != 200 {
|
||||
t.Fatalf("grant %d", code)
|
||||
}
|
||||
|
||||
env, code = doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/users/"+userID+"/entitlements", nil, tok)
|
||||
if code != 200 {
|
||||
t.Fatalf("after grant %d", code)
|
||||
}
|
||||
var after struct {
|
||||
Flags struct {
|
||||
ViaMem bool `json:"report_detail_via_membership"`
|
||||
} `json:"flags"`
|
||||
Membership struct {
|
||||
Active bool `json:"active"`
|
||||
} `json:"membership"`
|
||||
}
|
||||
_ = json.Unmarshal(env.Data, &after)
|
||||
if !after.Flags.ViaMem || !after.Membership.Active {
|
||||
t.Fatalf("expected active membership entitlement: %#v", after)
|
||||
}
|
||||
_ = key
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// DeepAccessBrief is one deep_access row for ops Entitlement.
|
||||
type DeepAccessBrief struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
ReportID uuid.UUID `json:"report_id"`
|
||||
ReportType string `json:"report_type,omitempty"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// ListDeepAccessForUser returns recent deep accesses with report type.
|
||||
func (r *AdminRepo) ListDeepAccessForUser(ctx context.Context, userID uuid.UUID, limit int) ([]DeepAccessBrief, error) {
|
||||
if limit <= 0 || limit > 50 {
|
||||
limit = 20
|
||||
}
|
||||
rows, err := r.Pool.Query(ctx, `
|
||||
SELECT d.id, d.report_id, coalesce(g.type, ''), d.created_at
|
||||
FROM deep_accesses d
|
||||
LEFT JOIN growth_reports g ON g.id = d.report_id AND g.deleted_at IS NULL
|
||||
WHERE d.user_id=$1 AND d.deleted_at IS NULL
|
||||
ORDER BY d.created_at DESC
|
||||
LIMIT $2`, userID, limit)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []DeepAccessBrief
|
||||
for rows.Next() {
|
||||
var b DeepAccessBrief
|
||||
if err := rows.Scan(&b.ID, &b.ReportID, &b.ReportType, &b.CreatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, b)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// CountDeepAccessForUser counts non-deleted deep accesses.
|
||||
func (r *AdminRepo) CountDeepAccessForUser(ctx context.Context, userID uuid.UUID) (int, error) {
|
||||
var n int
|
||||
err := r.Pool.QueryRow(ctx, `
|
||||
SELECT count(*)::int FROM deep_accesses
|
||||
WHERE user_id=$1 AND deleted_at IS NULL`, userID).Scan(&n)
|
||||
return n, err
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/yuxingu/digital-psychology/apps/api/internal/repository"
|
||||
)
|
||||
|
||||
// EntitlementFlags summarizes effective rights.
|
||||
type EntitlementFlags struct {
|
||||
ReportDetailViaMembership bool `json:"report_detail_via_membership"`
|
||||
DeepAccessCount int `json:"deep_access_count"`
|
||||
}
|
||||
|
||||
// UserEntitlement is the CommerceEntitlement ops read model.
|
||||
type UserEntitlement struct {
|
||||
UserID uuid.UUID `json:"user_id"`
|
||||
Membership *repository.MembershipRow `json:"membership"`
|
||||
AskPaidQuotaLeft int `json:"ask_paid_quota_left"`
|
||||
Flags EntitlementFlags `json:"flags"`
|
||||
DeepAccesses []repository.DeepAccessBrief `json:"deep_accesses"`
|
||||
}
|
||||
|
||||
// GetUserEntitlement aggregates membership + deep access + quotas.
|
||||
func (s *Service) GetUserEntitlement(ctx context.Context, userID uuid.UUID) (*UserEntitlement, error) {
|
||||
ok, err := s.Repo.UserExists(ctx, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !ok {
|
||||
return nil, ErrUserNotFound
|
||||
}
|
||||
_, _, paidLeft, _, _, err := s.Repo.GetUserAccount(ctx, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
mem, err := s.Reports.GetMembership(ctx, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
count, err := s.Repo.CountDeepAccessForUser(ctx, userID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
items, err := s.Repo.ListDeepAccessForUser(ctx, userID, 20)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if items == nil {
|
||||
items = []repository.DeepAccessBrief{}
|
||||
}
|
||||
return &UserEntitlement{
|
||||
UserID: userID,
|
||||
Membership: mem,
|
||||
AskPaidQuotaLeft: paidLeft,
|
||||
Flags: EntitlementFlags{
|
||||
ReportDetailViaMembership: mem != nil && mem.Active,
|
||||
DeepAccessCount: count,
|
||||
},
|
||||
DeepAccesses: items,
|
||||
}, nil
|
||||
}
|
||||
Reference in New Issue
Block a user