feat(ECR-017): AskOperations 问答会话只读并 Closed
新增 admin.ask.read、GET /admin/ask/threads*(AskSessionView)与 admin-h5「问答」页;禁改消息/UGC/真支付。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -47,6 +47,7 @@ func (h *AdminHandler) Register(api *gin.RouterGroup) {
|
||||
h.registerMembershipPlans(authed)
|
||||
h.registerRedemption(authed)
|
||||
h.registerInsight(authed)
|
||||
h.registerAskOps(authed)
|
||||
}
|
||||
|
||||
func (h *AdminHandler) Login(c *gin.Context) {
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"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) registerAskOps(authed *gin.RouterGroup) {
|
||||
authed.GET("/ask/threads", middleware.RequireAdminPermission(h.Svc, admin.PermAskRead), h.ListAskThreads)
|
||||
authed.GET("/ask/threads/:id", middleware.RequireAdminPermission(h.Svc, admin.PermAskRead), h.GetAskThread)
|
||||
}
|
||||
|
||||
func (h *AdminHandler) ListAskThreads(c *gin.Context) {
|
||||
limit, _ := strconv.Atoi(c.DefaultQuery("limit", "20"))
|
||||
offset, _ := strconv.Atoi(c.DefaultQuery("offset", "0"))
|
||||
var userID *uuid.UUID
|
||||
if q := c.Query("user_id"); q != "" {
|
||||
id, err := uuid.Parse(q)
|
||||
if err != nil {
|
||||
response.Fail(c, http.StatusBadRequest, 40002, "invalid user_id")
|
||||
return
|
||||
}
|
||||
userID = &id
|
||||
}
|
||||
items, err := h.Svc.ListAskSessions(c.Request.Context(), userID, limit, offset)
|
||||
if err != nil {
|
||||
response.Fail(c, http.StatusInternalServerError, 50019, "list ask threads failed")
|
||||
return
|
||||
}
|
||||
response.OK(c, gin.H{"items": items})
|
||||
}
|
||||
|
||||
func (h *AdminHandler) GetAskThread(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
response.Fail(c, http.StatusBadRequest, 40002, "invalid thread id")
|
||||
return
|
||||
}
|
||||
detail, err := h.Svc.GetAskSessionDetail(c.Request.Context(), id)
|
||||
if errors.Is(err, admin.ErrAskThreadNotFound) {
|
||||
response.Fail(c, http.StatusNotFound, 40402, "ask thread not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.Fail(c, http.StatusInternalServerError, 50020, "get ask thread failed")
|
||||
return
|
||||
}
|
||||
response.OK(c, detail)
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
func TestAskOperations(t *testing.T) {
|
||||
r, pool := setupAPIPool(t)
|
||||
ctx := context.Background()
|
||||
tok := adminLogin(t, r, "admin", "change-me")
|
||||
|
||||
_, code := doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/ask/threads", nil, "")
|
||||
if code != http.StatusUnauthorized {
|
||||
t.Fatalf("expected 401, got %d", code)
|
||||
}
|
||||
|
||||
limitedRoleID := uuid.New()
|
||||
_, err := pool.Exec(ctx, `
|
||||
INSERT INTO admin_roles(id, name, system) VALUES ($1, $2, false)`,
|
||||
limitedRoleID, "ask_lim_"+limitedRoleID.String()[:8])
|
||||
if err != nil {
|
||||
t.Fatalf("insert role: %v", err)
|
||||
}
|
||||
_, err = pool.Exec(ctx, `
|
||||
INSERT INTO admin_role_permissions(role_id, code) VALUES ($1,'admin.users.read')`, limitedRoleID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte("limited-pass"), bcrypt.DefaultCost)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
limitedUser := fmt.Sprintf("asklim_%d", time.Now().UnixNano())
|
||||
_, err = pool.Exec(ctx, `
|
||||
INSERT INTO admin_accounts(username, password_hash, role_id)
|
||||
VALUES ($1,$2,$3)`, limitedUser, string(hash), limitedRoleID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
_, _ = pool.Exec(ctx, `DELETE FROM admin_accounts WHERE username=$1`, limitedUser)
|
||||
_, _ = pool.Exec(ctx, `DELETE FROM admin_roles WHERE id=$1`, limitedRoleID)
|
||||
})
|
||||
|
||||
limTok := adminLogin(t, r, limitedUser, "limited-pass")
|
||||
_, code = doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/ask/threads", nil, limTok)
|
||||
if code != http.StatusForbidden {
|
||||
t.Fatalf("expected 403 without ask.read, got %d", code)
|
||||
}
|
||||
|
||||
key := mustRegister(t, r)
|
||||
env, key := doJSON(t, r, http.MethodPost, "/api/v1/profiles", map[string]any{
|
||||
"relation": "self", "birth_date": "1992-06-01", "display_name": "问",
|
||||
}, key)
|
||||
profileID := decodeData[map[string]any](t, env.Data)["id"].(string)
|
||||
|
||||
env, key = doJSON(t, r, http.MethodPost, "/api/v1/ask/threads", map[string]any{
|
||||
"profile_id": profileID, "scene": "self",
|
||||
}, key)
|
||||
threadID := decodeData[map[string]any](t, env.Data)["id"].(string)
|
||||
|
||||
_, key = doJSON(t, r, http.MethodPost, "/api/v1/ask/threads/"+threadID+"/messages", map[string]any{
|
||||
"content": "运营可读吗",
|
||||
}, key)
|
||||
|
||||
start := time.Now()
|
||||
env, code = doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/ask/threads", nil, tok)
|
||||
if code != 200 || env.Code != 0 {
|
||||
t.Fatalf("list http=%d code=%d msg=%s", code, env.Code, env.Message)
|
||||
}
|
||||
if time.Since(start) > 500*time.Millisecond {
|
||||
t.Fatalf("list too slow: %v", time.Since(start))
|
||||
}
|
||||
var list struct {
|
||||
Items []struct {
|
||||
ID string `json:"id"`
|
||||
MessageCount int `json:"message_count"`
|
||||
} `json:"items"`
|
||||
}
|
||||
_ = json.Unmarshal(env.Data, &list)
|
||||
found := false
|
||||
for _, it := range list.Items {
|
||||
if it.ID == threadID && it.MessageCount >= 1 {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("expected thread %s in list: %#v", threadID, list.Items)
|
||||
}
|
||||
|
||||
env, code = doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/ask/threads/"+threadID, nil, tok)
|
||||
if code != 200 {
|
||||
t.Fatalf("detail http=%d msg=%s", code, env.Message)
|
||||
}
|
||||
var detail struct {
|
||||
Messages []struct {
|
||||
Role string `json:"role"`
|
||||
Content string `json:"content"`
|
||||
} `json:"messages"`
|
||||
}
|
||||
_ = json.Unmarshal(env.Data, &detail)
|
||||
if len(detail.Messages) < 2 {
|
||||
t.Fatalf("expected user+assistant, got %#v", detail.Messages)
|
||||
}
|
||||
_ = key
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
// AskSessionView is ops read meta for one ask thread.
|
||||
type AskSessionView struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
UserID uuid.UUID `json:"user_id"`
|
||||
ProfileID uuid.UUID `json:"profile_id"`
|
||||
Scene *string `json:"scene,omitempty"`
|
||||
MessageCount int `json:"message_count"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// AskMessageView is a read-only message row for ops.
|
||||
type AskMessageView struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Role string `json:"role"`
|
||||
Content string `json:"content"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
}
|
||||
|
||||
// ListAskSessions returns recent ask threads (optional user filter).
|
||||
func (r *AdminRepo) ListAskSessions(ctx context.Context, userID *uuid.UUID, limit, offset int) ([]AskSessionView, error) {
|
||||
if limit <= 0 || limit > 100 {
|
||||
limit = 20
|
||||
}
|
||||
if offset < 0 {
|
||||
offset = 0
|
||||
}
|
||||
rows, err := r.Pool.Query(ctx, `
|
||||
SELECT t.id, t.user_id, t.profile_id, t.scene, t.created_at, t.updated_at,
|
||||
(SELECT count(*)::int FROM ask_messages m
|
||||
WHERE m.thread_id=t.id AND m.deleted_at IS NULL) AS message_count
|
||||
FROM ask_threads t
|
||||
WHERE t.deleted_at IS NULL
|
||||
AND ($1::uuid IS NULL OR t.user_id=$1)
|
||||
ORDER BY t.updated_at DESC
|
||||
LIMIT $2 OFFSET $3`, userID, limit, offset)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []AskSessionView
|
||||
for rows.Next() {
|
||||
var s AskSessionView
|
||||
if err := rows.Scan(
|
||||
&s.ID, &s.UserID, &s.ProfileID, &s.Scene, &s.CreatedAt, &s.UpdatedAt, &s.MessageCount,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, s)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// GetAskSession loads one thread meta or ErrNoRows.
|
||||
func (r *AdminRepo) GetAskSession(ctx context.Context, threadID uuid.UUID) (*AskSessionView, error) {
|
||||
var s AskSessionView
|
||||
err := r.Pool.QueryRow(ctx, `
|
||||
SELECT t.id, t.user_id, t.profile_id, t.scene, t.created_at, t.updated_at,
|
||||
(SELECT count(*)::int FROM ask_messages m
|
||||
WHERE m.thread_id=t.id AND m.deleted_at IS NULL) AS message_count
|
||||
FROM ask_threads t
|
||||
WHERE t.id=$1 AND t.deleted_at IS NULL`, threadID,
|
||||
).Scan(&s.ID, &s.UserID, &s.ProfileID, &s.Scene, &s.CreatedAt, &s.UpdatedAt, &s.MessageCount)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, err
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &s, nil
|
||||
}
|
||||
|
||||
// ListAskMessagesForAdmin returns messages oldest-first.
|
||||
func (r *AdminRepo) ListAskMessagesForAdmin(ctx context.Context, threadID uuid.UUID) ([]AskMessageView, error) {
|
||||
rows, err := r.Pool.Query(ctx, `
|
||||
SELECT id, role, content, created_at
|
||||
FROM ask_messages
|
||||
WHERE thread_id=$1 AND deleted_at IS NULL
|
||||
ORDER BY created_at ASC`, threadID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []AskMessageView
|
||||
for rows.Next() {
|
||||
var m AskMessageView
|
||||
if err := rows.Scan(&m.ID, &m.Role, &m.Content, &m.CreatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, m)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"github.com/yuxingu/digital-psychology/apps/api/internal/repository"
|
||||
)
|
||||
|
||||
// AskSessionDetail is AskSessionView plus messages.
|
||||
type AskSessionDetail struct {
|
||||
repository.AskSessionView
|
||||
Messages []repository.AskMessageView `json:"messages"`
|
||||
}
|
||||
|
||||
var ErrAskThreadNotFound = errString("ask thread not found")
|
||||
|
||||
// ListAskSessions lists AskSessionView rows.
|
||||
func (s *Service) ListAskSessions(ctx context.Context, userID *uuid.UUID, limit, offset int) ([]repository.AskSessionView, error) {
|
||||
items, err := s.Repo.ListAskSessions(ctx, userID, limit, offset)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if items == nil {
|
||||
items = []repository.AskSessionView{}
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
// GetAskSessionDetail loads meta + messages.
|
||||
func (s *Service) GetAskSessionDetail(ctx context.Context, threadID uuid.UUID) (*AskSessionDetail, error) {
|
||||
view, err := s.Repo.GetAskSession(ctx, threadID)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrAskThreadNotFound
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
msgs, err := s.Repo.ListAskMessagesForAdmin(ctx, threadID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if msgs == nil {
|
||||
msgs = []repository.AskMessageView{}
|
||||
}
|
||||
return &AskSessionDetail{AskSessionView: *view, Messages: msgs}, nil
|
||||
}
|
||||
@@ -24,6 +24,7 @@ const (
|
||||
PermMembershipPlansWrite = "admin.membership.plans.write"
|
||||
PermMembershipCodesRead = "admin.membership.codes.read"
|
||||
PermMembershipCodesWrite = "admin.membership.codes.write"
|
||||
PermAskRead = "admin.ask.read"
|
||||
)
|
||||
|
||||
var knownPermissions = map[string]struct{}{
|
||||
@@ -32,6 +33,7 @@ var knownPermissions = map[string]struct{}{
|
||||
PermContentWrite: {}, PermRolesRead: {}, PermRolesWrite: {},
|
||||
PermUsersStatusWrite: {}, PermMembershipPlansRead: {}, PermMembershipPlansWrite: {},
|
||||
PermMembershipCodesRead: {}, PermMembershipCodesWrite: {},
|
||||
PermAskRead: {},
|
||||
}
|
||||
|
||||
var (
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
-- ECR-017 down
|
||||
|
||||
DELETE FROM admin_role_permissions WHERE code = 'admin.ask.read';
|
||||
@@ -0,0 +1,7 @@
|
||||
-- ECR-017 AskOperations: admin.ask.read
|
||||
|
||||
INSERT INTO admin_role_permissions(role_id, code)
|
||||
SELECT r.id, 'admin.ask.read'
|
||||
FROM admin_roles r
|
||||
WHERE r.name = 'super_admin'
|
||||
ON CONFLICT DO NOTHING;
|
||||
Reference in New Issue
Block a user