feat(ECR-022): CrisisCare CrisisPolicy 只读并 Closed
新增 crisis_policies、admin.crisis.read、列表/试匹配 API 与 admin-h5「危机」页;禁 CrisisEvent 写/UGC/真支付。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -52,6 +52,7 @@ func (h *AdminHandler) Register(api *gin.RouterGroup) {
|
||||
h.registerEntitlement(authed)
|
||||
h.registerContentSafety(authed)
|
||||
h.registerAIConfig(authed)
|
||||
h.registerCrisis(authed)
|
||||
}
|
||||
|
||||
func (h *AdminHandler) Login(c *gin.Context) {
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
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) registerCrisis(authed *gin.RouterGroup) {
|
||||
g := authed.Group("/crisis")
|
||||
g.GET("/policies", middleware.RequireAdminPermission(h.Svc, admin.PermCrisisRead), h.ListCrisisPolicies)
|
||||
g.GET("/policies/:id", middleware.RequireAdminPermission(h.Svc, admin.PermCrisisRead), h.GetCrisisPolicy)
|
||||
g.POST("/evaluate", middleware.RequireAdminPermission(h.Svc, admin.PermCrisisRead), h.EvaluateCrisis)
|
||||
}
|
||||
|
||||
func (h *AdminHandler) ListCrisisPolicies(c *gin.Context) {
|
||||
items, err := h.Svc.ListCrisisPolicies(c.Request.Context())
|
||||
if err != nil {
|
||||
response.Fail(c, http.StatusInternalServerError, 50029, "list crisis policies failed")
|
||||
return
|
||||
}
|
||||
response.OK(c, gin.H{"items": items})
|
||||
}
|
||||
|
||||
func (h *AdminHandler) GetCrisisPolicy(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
response.Fail(c, http.StatusBadRequest, 40002, "invalid id")
|
||||
return
|
||||
}
|
||||
row, err := h.Svc.GetCrisisPolicy(c.Request.Context(), id)
|
||||
if errors.Is(err, admin.ErrCrisisPolicyNotFound) {
|
||||
response.Fail(c, http.StatusNotFound, 40405, "crisis policy not found")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.Fail(c, http.StatusInternalServerError, 50030, "get crisis policy failed")
|
||||
return
|
||||
}
|
||||
response.OK(c, row)
|
||||
}
|
||||
|
||||
func (h *AdminHandler) EvaluateCrisis(c *gin.Context) {
|
||||
var body struct {
|
||||
Text string `json:"text"`
|
||||
}
|
||||
if err := c.ShouldBindJSON(&body); err != nil {
|
||||
response.Fail(c, http.StatusBadRequest, 40000, "invalid body")
|
||||
return
|
||||
}
|
||||
matches, err := h.Svc.EvaluateCrisis(c.Request.Context(), body.Text)
|
||||
if err != nil {
|
||||
response.Fail(c, http.StatusInternalServerError, 50031, "evaluate failed")
|
||||
return
|
||||
}
|
||||
response.OK(c, gin.H{"matches": matches})
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
func TestCrisisCarePolicies(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/crisis/policies", 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, "cr_lim_"+limitedRoleID.String()[:8])
|
||||
if err != nil {
|
||||
t.Fatal(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)
|
||||
}
|
||||
limUser := fmt.Sprintf("crlim_%d", time.Now().UnixNano())
|
||||
_, err = pool.Exec(ctx, `
|
||||
INSERT INTO admin_accounts(username, password_hash, role_id) VALUES ($1,$2,$3)`,
|
||||
limUser, string(hash), limitedRoleID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
_, _ = pool.Exec(ctx, `DELETE FROM admin_accounts WHERE username=$1`, limUser)
|
||||
_, _ = pool.Exec(ctx, `DELETE FROM admin_roles WHERE id=$1`, limitedRoleID)
|
||||
})
|
||||
limTok := adminLogin(t, r, limUser, "limited-pass")
|
||||
_, code = doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/crisis/policies", nil, limTok)
|
||||
if code != http.StatusForbidden {
|
||||
t.Fatalf("expected 403, got %d", code)
|
||||
}
|
||||
|
||||
start := time.Now()
|
||||
env, code := doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/crisis/policies", nil, tok)
|
||||
if code != 200 || env.Code != 0 {
|
||||
t.Fatalf("list http=%d msg=%s", 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"`
|
||||
Code string `json:"code"`
|
||||
System bool `json:"system"`
|
||||
} `json:"items"`
|
||||
}
|
||||
_ = json.Unmarshal(env.Data, &list)
|
||||
if len(list.Items) < 1 {
|
||||
t.Fatal("expected seeded crisis policies")
|
||||
}
|
||||
firstID := list.Items[0].ID
|
||||
|
||||
env, code = doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/crisis/policies/"+firstID, nil, tok)
|
||||
if code != 200 {
|
||||
t.Fatalf("get %d", code)
|
||||
}
|
||||
|
||||
_, code = doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/crisis/policies/"+fakeUUID(), nil, tok)
|
||||
if code != http.StatusNotFound {
|
||||
t.Fatalf("expected 404, got %d", code)
|
||||
}
|
||||
|
||||
env, code = doAdminJSON(t, r, http.MethodPost, "/api/v1/admin/crisis/evaluate",
|
||||
map[string]string{"text": "我真的不想活了"}, tok)
|
||||
if code != 200 {
|
||||
t.Fatalf("evaluate %d msg=%s", code, env.Message)
|
||||
}
|
||||
var ev struct {
|
||||
Matches []struct {
|
||||
Code string `json:"code"`
|
||||
} `json:"matches"`
|
||||
}
|
||||
_ = json.Unmarshal(env.Data, &ev)
|
||||
if len(ev.Matches) < 1 {
|
||||
t.Fatalf("expected match, got %#v", ev)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
// CrisisPolicyRow is CrisisCare CrisisPolicy catalog.
|
||||
type CrisisPolicyRow struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Code string `json:"code"`
|
||||
Title string `json:"title"`
|
||||
Severity string `json:"severity"`
|
||||
Pattern string `json:"pattern"`
|
||||
Action string `json:"action"`
|
||||
HelplineText *string `json:"helpline_text,omitempty"`
|
||||
Active bool `json:"active"`
|
||||
System bool `json:"system"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
}
|
||||
|
||||
// CrisisMatch is one evaluate hit.
|
||||
type CrisisMatch struct {
|
||||
Code string `json:"code"`
|
||||
Title string `json:"title"`
|
||||
Severity string `json:"severity"`
|
||||
Action string `json:"action"`
|
||||
HelplineText *string `json:"helpline_text,omitempty"`
|
||||
}
|
||||
|
||||
// ListCrisisPolicies returns policies active-first.
|
||||
func (r *AdminRepo) ListCrisisPolicies(ctx context.Context) ([]CrisisPolicyRow, error) {
|
||||
rows, err := r.Pool.Query(ctx, `
|
||||
SELECT id, code, title, severity, pattern, action, helpline_text, active, system, updated_at
|
||||
FROM crisis_policies
|
||||
ORDER BY active DESC, severity DESC, code ASC`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []CrisisPolicyRow
|
||||
for rows.Next() {
|
||||
var p CrisisPolicyRow
|
||||
if err := rows.Scan(
|
||||
&p.ID, &p.Code, &p.Title, &p.Severity, &p.Pattern, &p.Action, &p.HelplineText,
|
||||
&p.Active, &p.System, &p.UpdatedAt,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, p)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// GetCrisisPolicy loads one policy.
|
||||
func (r *AdminRepo) GetCrisisPolicy(ctx context.Context, id uuid.UUID) (*CrisisPolicyRow, error) {
|
||||
var p CrisisPolicyRow
|
||||
err := r.Pool.QueryRow(ctx, `
|
||||
SELECT id, code, title, severity, pattern, action, helpline_text, active, system, updated_at
|
||||
FROM crisis_policies WHERE id=$1`, id,
|
||||
).Scan(
|
||||
&p.ID, &p.Code, &p.Title, &p.Severity, &p.Pattern, &p.Action, &p.HelplineText,
|
||||
&p.Active, &p.System, &p.UpdatedAt,
|
||||
)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, err
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &p, nil
|
||||
}
|
||||
|
||||
// EvaluateCrisisPolicies runs substring match preview (ops only).
|
||||
func (r *AdminRepo) EvaluateCrisisPolicies(ctx context.Context, text string) ([]CrisisMatch, error) {
|
||||
policies, err := r.ListCrisisPolicies(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
lower := strings.ToLower(text)
|
||||
var out []CrisisMatch
|
||||
for _, p := range policies {
|
||||
if !p.Active || p.Pattern == "" {
|
||||
continue
|
||||
}
|
||||
if strings.Contains(lower, strings.ToLower(p.Pattern)) {
|
||||
out = append(out, CrisisMatch{
|
||||
Code: p.Code, Title: p.Title, Severity: p.Severity,
|
||||
Action: p.Action, HelplineText: p.HelplineText,
|
||||
})
|
||||
}
|
||||
}
|
||||
if out == nil {
|
||||
out = []CrisisMatch{}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"github.com/yuxingu/digital-psychology/apps/api/internal/repository"
|
||||
)
|
||||
|
||||
var ErrCrisisPolicyNotFound = errString("crisis policy not found")
|
||||
|
||||
// ListCrisisPolicies returns CrisisPolicy catalog.
|
||||
func (s *Service) ListCrisisPolicies(ctx context.Context) ([]repository.CrisisPolicyRow, error) {
|
||||
items, err := s.Repo.ListCrisisPolicies(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if items == nil {
|
||||
items = []repository.CrisisPolicyRow{}
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
|
||||
// GetCrisisPolicy loads one policy.
|
||||
func (s *Service) GetCrisisPolicy(ctx context.Context, id uuid.UUID) (*repository.CrisisPolicyRow, error) {
|
||||
row, err := s.Repo.GetCrisisPolicy(ctx, id)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrCrisisPolicyNotFound
|
||||
}
|
||||
return row, err
|
||||
}
|
||||
|
||||
// EvaluateCrisis runs read-only policy preview.
|
||||
func (s *Service) EvaluateCrisis(ctx context.Context, text string) ([]repository.CrisisMatch, error) {
|
||||
return s.Repo.EvaluateCrisisPolicies(ctx, text)
|
||||
}
|
||||
@@ -28,6 +28,7 @@ const (
|
||||
PermAskFeedbackWrite = "admin.ask.feedback.write"
|
||||
PermContentSafetyRead = "admin.content_safety.read"
|
||||
PermAIConfigRead = "admin.ai_config.read"
|
||||
PermCrisisRead = "admin.crisis.read"
|
||||
)
|
||||
|
||||
var knownPermissions = map[string]struct{}{
|
||||
@@ -37,7 +38,7 @@ var knownPermissions = map[string]struct{}{
|
||||
PermUsersStatusWrite: {}, PermMembershipPlansRead: {}, PermMembershipPlansWrite: {},
|
||||
PermMembershipCodesRead: {}, PermMembershipCodesWrite: {},
|
||||
PermAskRead: {}, PermAskFeedbackWrite: {}, PermContentSafetyRead: {},
|
||||
PermAIConfigRead: {},
|
||||
PermAIConfigRead: {}, PermCrisisRead: {},
|
||||
}
|
||||
|
||||
var (
|
||||
|
||||
Reference in New Issue
Block a user