feat(ECR-047): FunnelDefinition 写面闭环并 Closed
growth.write POST/PUT · migration 000056 · 无新 C 端 · Loop STOP Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -16,6 +16,8 @@ func (h *AdminHandler) registerFunnelDefinitions(authed *gin.RouterGroup) {
|
||||
g := authed.Group("/analytics")
|
||||
g.GET("/funnel-definitions", middleware.RequireAdminPermission(h.Svc, admin.PermGrowthRead), h.ListFunnelDefinitions)
|
||||
g.GET("/funnel-definitions/:id", middleware.RequireAdminPermission(h.Svc, admin.PermGrowthRead), h.GetFunnelDefinition)
|
||||
g.POST("/funnel-definitions", middleware.RequireAdminPermission(h.Svc, admin.PermGrowthWrite), h.CreateFunnelDefinition)
|
||||
g.PUT("/funnel-definitions/:id", middleware.RequireAdminPermission(h.Svc, admin.PermGrowthWrite), h.UpdateFunnelDefinition)
|
||||
}
|
||||
|
||||
func (h *AdminHandler) ListFunnelDefinitions(c *gin.Context) {
|
||||
@@ -44,3 +46,66 @@ func (h *AdminHandler) GetFunnelDefinition(c *gin.Context) {
|
||||
}
|
||||
response.OK(c, row)
|
||||
}
|
||||
|
||||
func (h *AdminHandler) CreateFunnelDefinition(c *gin.Context) {
|
||||
adminID, ok := middleware.AdminIDFromContext(c)
|
||||
if !ok {
|
||||
response.Fail(c, http.StatusUnauthorized, 40101, "admin auth required")
|
||||
return
|
||||
}
|
||||
var body admin.FunnelDefinitionWriteBody
|
||||
if err := c.ShouldBindJSON(&body); err != nil {
|
||||
response.Fail(c, http.StatusBadRequest, 40054, "invalid body")
|
||||
return
|
||||
}
|
||||
row, err := h.Svc.CreateFunnelDefinition(c.Request.Context(), adminID, body)
|
||||
if errors.Is(err, admin.ErrInvalidFunnelDefinition) {
|
||||
response.Fail(c, http.StatusBadRequest, 40055, "invalid funnel definition")
|
||||
return
|
||||
}
|
||||
if errors.Is(err, admin.ErrFunnelDefinitionConflict) {
|
||||
response.Fail(c, http.StatusConflict, 40912, "funnel definition code conflict")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.Fail(c, http.StatusInternalServerError, 50052, "create funnel definition failed")
|
||||
return
|
||||
}
|
||||
response.OK(c, row)
|
||||
}
|
||||
|
||||
func (h *AdminHandler) UpdateFunnelDefinition(c *gin.Context) {
|
||||
adminID, ok := middleware.AdminIDFromContext(c)
|
||||
if !ok {
|
||||
response.Fail(c, http.StatusUnauthorized, 40101, "admin auth required")
|
||||
return
|
||||
}
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
response.Fail(c, http.StatusBadRequest, 40002, "invalid id")
|
||||
return
|
||||
}
|
||||
var body admin.FunnelDefinitionWriteBody
|
||||
if err := c.ShouldBindJSON(&body); err != nil {
|
||||
response.Fail(c, http.StatusBadRequest, 40054, "invalid body")
|
||||
return
|
||||
}
|
||||
row, err := h.Svc.UpdateFunnelDefinition(c.Request.Context(), adminID, id, body)
|
||||
if errors.Is(err, admin.ErrFunnelDefinitionNotFound) {
|
||||
response.Fail(c, http.StatusNotFound, 40420, "funnel-definition not found")
|
||||
return
|
||||
}
|
||||
if errors.Is(err, admin.ErrInvalidFunnelDefinition) {
|
||||
response.Fail(c, http.StatusBadRequest, 40055, "invalid funnel definition")
|
||||
return
|
||||
}
|
||||
if errors.Is(err, admin.ErrFunnelDefinitionConflict) {
|
||||
response.Fail(c, http.StatusConflict, 40912, "funnel definition code conflict")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.Fail(c, http.StatusInternalServerError, 50053, "update funnel definition failed")
|
||||
return
|
||||
}
|
||||
response.OK(c, row)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
func TestGrowthFunnelDefinitionWrite(t *testing.T) {
|
||||
r, pool := setupAPIPool(t)
|
||||
ctx := context.Background()
|
||||
tok := adminLogin(t, r, "admin", "change-me")
|
||||
|
||||
code := fmt.Sprintf("fn_w_%d", time.Now().UnixNano()%1_000_000)
|
||||
body := map[string]any{"code": code, "title": "测试漏斗", "active": true}
|
||||
env, httpCode := doAdminJSON(t, r, http.MethodPost, "/api/v1/admin/analytics/funnel-definitions", body, tok)
|
||||
if httpCode != 200 || env.Code != 0 {
|
||||
t.Fatalf("create http=%d code=%d msg=%s", httpCode, env.Code, env.Message)
|
||||
}
|
||||
var created struct {
|
||||
ID string `json:"id"`
|
||||
Code string `json:"code"`
|
||||
Active bool `json:"active"`
|
||||
}
|
||||
_ = json.Unmarshal(env.Data, &created)
|
||||
if created.ID == "" || created.Code != code || !created.Active {
|
||||
t.Fatalf("bad create %#v", created)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
_, _ = pool.Exec(ctx, `DELETE FROM funnel_definitions WHERE id=$1`, created.ID)
|
||||
})
|
||||
|
||||
_, httpCode = doAdminJSON(t, r, http.MethodPost, "/api/v1/admin/analytics/funnel-definitions", body, tok)
|
||||
if httpCode != http.StatusConflict {
|
||||
t.Fatalf("dup expected 409 got %d", httpCode)
|
||||
}
|
||||
|
||||
env, httpCode = doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/analytics/funnel-definitions", nil, tok)
|
||||
if httpCode != 200 {
|
||||
t.Fatalf("list %d", httpCode)
|
||||
}
|
||||
var list struct {
|
||||
Items []struct {
|
||||
Code string `json:"code"`
|
||||
Active bool `json:"active"`
|
||||
} `json:"items"`
|
||||
}
|
||||
_ = json.Unmarshal(env.Data, &list)
|
||||
found := false
|
||||
for _, it := range list.Items {
|
||||
if it.Code == code && it.Active {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("missing active in list %#v", list.Items)
|
||||
}
|
||||
|
||||
body["active"] = false
|
||||
body["title"] = "测试漏斗下架"
|
||||
env, httpCode = doAdminJSON(t, r, http.MethodPut, "/api/v1/admin/analytics/funnel-definitions/"+created.ID, body, tok)
|
||||
if httpCode != 200 {
|
||||
t.Fatalf("update %d", httpCode)
|
||||
}
|
||||
var updated struct {
|
||||
Active bool `json:"active"`
|
||||
Title string `json:"title"`
|
||||
}
|
||||
_ = json.Unmarshal(env.Data, &updated)
|
||||
if updated.Active || updated.Title != "测试漏斗下架" {
|
||||
t.Fatalf("bad update %#v", updated)
|
||||
}
|
||||
|
||||
var n int
|
||||
_ = pool.QueryRow(ctx, `
|
||||
SELECT COUNT(*) FROM admin_audit_logs
|
||||
WHERE action IN ('growth.funnel_definition.create','growth.funnel_definition.update') AND target_id=$1`,
|
||||
created.ID).Scan(&n)
|
||||
if n < 2 {
|
||||
t.Fatalf("audit %d", n)
|
||||
}
|
||||
|
||||
limitedRoleID := uuid.New()
|
||||
_, _ = pool.Exec(ctx, `INSERT INTO admin_roles(id, name, system) VALUES ($1,$2,false)`,
|
||||
limitedRoleID, "fn_ro_"+limitedRoleID.String()[:8])
|
||||
_, _ = pool.Exec(ctx, `INSERT INTO admin_role_permissions(role_id, code) VALUES ($1,'admin.growth.read')`, limitedRoleID)
|
||||
hash, _ := bcrypt.GenerateFromPassword([]byte("ro-pass"), bcrypt.DefaultCost)
|
||||
roUser := fmt.Sprintf("fnro_%d", time.Now().UnixNano())
|
||||
_, _ = pool.Exec(ctx, `INSERT INTO admin_accounts(username, password_hash, role_id) VALUES ($1,$2,$3)`,
|
||||
roUser, string(hash), limitedRoleID)
|
||||
t.Cleanup(func() {
|
||||
_, _ = pool.Exec(ctx, `DELETE FROM admin_accounts WHERE username=$1`, roUser)
|
||||
_, _ = pool.Exec(ctx, `DELETE FROM admin_roles WHERE id=$1`, limitedRoleID)
|
||||
})
|
||||
roTok := adminLogin(t, r, roUser, "ro-pass")
|
||||
_, httpCode = doAdminJSON(t, r, http.MethodPost, "/api/v1/admin/analytics/funnel-definitions", map[string]any{
|
||||
"code": "x_ro", "title": "no", "active": true,
|
||||
}, roTok)
|
||||
if httpCode != http.StatusForbidden {
|
||||
t.Fatalf("expected 403 got %d", httpCode)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
)
|
||||
|
||||
// FunnelDefinitionWriteInput is create/update payload.
|
||||
type FunnelDefinitionWriteInput struct {
|
||||
Code string
|
||||
Title string
|
||||
Active bool
|
||||
}
|
||||
|
||||
// CreateFunnelDefinitionWithAudit inserts and audits.
|
||||
func (r *AdminRepo) CreateFunnelDefinitionWithAudit(
|
||||
ctx context.Context, adminID uuid.UUID, in FunnelDefinitionWriteInput, meta json.RawMessage,
|
||||
) (*FunnelDefinitionRow, error) {
|
||||
tx, err := r.Pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
var row FunnelDefinitionRow
|
||||
err = tx.QueryRow(ctx, `
|
||||
INSERT INTO funnel_definitions(code, title, active, system)
|
||||
VALUES ($1,$2,$3,false)
|
||||
RETURNING id, code, title, active, system, updated_at`,
|
||||
in.Code, in.Title, in.Active,
|
||||
).Scan(&row.ID, &row.Code, &row.Title, &row.Active, &row.System, &row.UpdatedAt)
|
||||
if err != nil {
|
||||
return nil, mapFunnelDefinitionWriteErr(err)
|
||||
}
|
||||
if meta == nil {
|
||||
meta = json.RawMessage(`{}`)
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO admin_audit_logs(admin_id, action, target_type, target_id, meta)
|
||||
VALUES ($1,'growth.funnel_definition.create','funnel_definition',$2,$3)`,
|
||||
adminID, row.ID.String(), meta,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &row, nil
|
||||
}
|
||||
|
||||
// UpdateFunnelDefinitionWithAudit updates and audits.
|
||||
func (r *AdminRepo) UpdateFunnelDefinitionWithAudit(
|
||||
ctx context.Context, adminID, id uuid.UUID, in FunnelDefinitionWriteInput, meta json.RawMessage,
|
||||
) (*FunnelDefinitionRow, error) {
|
||||
tx, err := r.Pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
var system bool
|
||||
var oldCode string
|
||||
err = tx.QueryRow(ctx, `SELECT system, code FROM funnel_definitions WHERE id=$1`, id).Scan(&system, &oldCode)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, pgx.ErrNoRows
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
code := in.Code
|
||||
if system {
|
||||
code = oldCode
|
||||
}
|
||||
var row FunnelDefinitionRow
|
||||
err = tx.QueryRow(ctx, `
|
||||
UPDATE funnel_definitions
|
||||
SET code=$2, title=$3, active=$4, updated_at=now()
|
||||
WHERE id=$1
|
||||
RETURNING id, code, title, active, system, updated_at`,
|
||||
id, code, in.Title, in.Active,
|
||||
).Scan(&row.ID, &row.Code, &row.Title, &row.Active, &row.System, &row.UpdatedAt)
|
||||
if err != nil {
|
||||
return nil, mapFunnelDefinitionWriteErr(err)
|
||||
}
|
||||
if meta == nil {
|
||||
meta = json.RawMessage(`{}`)
|
||||
}
|
||||
if _, err := tx.Exec(ctx, `
|
||||
INSERT INTO admin_audit_logs(admin_id, action, target_type, target_id, meta)
|
||||
VALUES ($1,'growth.funnel_definition.update','funnel_definition',$2,$3)`,
|
||||
adminID, id.String(), meta,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &row, nil
|
||||
}
|
||||
|
||||
func mapFunnelDefinitionWriteErr(err error) error {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
||||
return errString("funnel definition code conflict")
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// FunnelDefinitionCodeConflict reports unique violation.
|
||||
func FunnelDefinitionCodeConflict(err error) bool {
|
||||
return err != nil && strings.Contains(err.Error(), "funnel definition code conflict")
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
package admin
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"github.com/yuxingu/digital-psychology/apps/api/internal/repository"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInvalidFunnelDefinition = errors.New("invalid funnel definition")
|
||||
ErrFunnelDefinitionConflict = errors.New("funnel definition code conflict")
|
||||
funnelDefinitionCodeRe = regexp.MustCompile(`^[a-z][a-z0-9_]{1,62}$`)
|
||||
)
|
||||
|
||||
// FunnelDefinitionWriteBody is JSON for create/update.
|
||||
type FunnelDefinitionWriteBody struct {
|
||||
Code string `json:"code"`
|
||||
Title string `json:"title"`
|
||||
Active bool `json:"active"`
|
||||
}
|
||||
|
||||
// CreateFunnelDefinition validates, inserts, audits.
|
||||
func (s *Service) CreateFunnelDefinition(ctx context.Context, adminID uuid.UUID, body FunnelDefinitionWriteBody) (*repository.FunnelDefinitionRow, error) {
|
||||
in, err := normalizeFunnelDefinitionWrite(body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
meta, _ := json.Marshal(map[string]any{"code": in.Code, "active": in.Active})
|
||||
row, err := s.Repo.CreateFunnelDefinitionWithAudit(ctx, adminID, in, meta)
|
||||
if repository.FunnelDefinitionCodeConflict(err) {
|
||||
return nil, ErrFunnelDefinitionConflict
|
||||
}
|
||||
return row, err
|
||||
}
|
||||
|
||||
// UpdateFunnelDefinition validates, updates, audits.
|
||||
func (s *Service) UpdateFunnelDefinition(ctx context.Context, adminID, id uuid.UUID, body FunnelDefinitionWriteBody) (*repository.FunnelDefinitionRow, error) {
|
||||
in, err := normalizeFunnelDefinitionWrite(body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
meta, _ := json.Marshal(map[string]any{"code": in.Code, "active": in.Active})
|
||||
row, err := s.Repo.UpdateFunnelDefinitionWithAudit(ctx, adminID, id, in, meta)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrFunnelDefinitionNotFound
|
||||
}
|
||||
if repository.FunnelDefinitionCodeConflict(err) {
|
||||
return nil, ErrFunnelDefinitionConflict
|
||||
}
|
||||
return row, err
|
||||
}
|
||||
|
||||
func normalizeFunnelDefinitionWrite(body FunnelDefinitionWriteBody) (repository.FunnelDefinitionWriteInput, error) {
|
||||
code := strings.TrimSpace(body.Code)
|
||||
title := strings.TrimSpace(body.Title)
|
||||
if !funnelDefinitionCodeRe.MatchString(code) {
|
||||
return repository.FunnelDefinitionWriteInput{}, ErrInvalidFunnelDefinition
|
||||
}
|
||||
if title == "" || utf8.RuneCountInString(title) > 128 {
|
||||
return repository.FunnelDefinitionWriteInput{}, ErrInvalidFunnelDefinition
|
||||
}
|
||||
return repository.FunnelDefinitionWriteInput{Code: code, Title: title, Active: body.Active}, nil
|
||||
}
|
||||
@@ -35,7 +35,8 @@ const (
|
||||
PermPrivacyRead = "admin.privacy.read"
|
||||
PermExploreRead = "admin.explore.read"
|
||||
PermExploreWrite = "admin.explore.write"
|
||||
PermGrowthRead = "admin.growth.read"
|
||||
PermGrowthRead = "admin.growth.read"
|
||||
PermGrowthWrite = "admin.growth.write"
|
||||
)
|
||||
|
||||
var knownPermissions = map[string]struct{}{
|
||||
@@ -45,7 +46,7 @@ var knownPermissions = map[string]struct{}{
|
||||
PermUsersStatusWrite: {}, PermMembershipPlansRead: {}, PermMembershipPlansWrite: {},
|
||||
PermMembershipCodesRead: {}, PermMembershipCodesWrite: {},
|
||||
PermAskRead: {}, PermAskTranscriptRead: {}, PermAskFeedbackWrite: {}, PermContentSafetyRead: {},
|
||||
PermAIConfigRead: {}, PermCrisisRead: {}, PermCMSRead: {}, PermCMSWrite: {}, PermGrowthRead: {}, PermExploreRead: {}, PermExploreWrite: {}, PermPrivacyRead: {},
|
||||
PermAIConfigRead: {}, PermCrisisRead: {}, PermCMSRead: {}, PermCMSWrite: {}, PermGrowthRead: {}, PermGrowthWrite: {}, PermExploreRead: {}, PermExploreWrite: {}, PermPrivacyRead: {},
|
||||
}
|
||||
|
||||
var (
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
-- ECR-047 rollback
|
||||
|
||||
DELETE FROM admin_role_permissions
|
||||
WHERE code = 'admin.growth.write'
|
||||
AND role_id IN (SELECT id FROM admin_roles WHERE name = 'super_admin');
|
||||
@@ -0,0 +1,7 @@
|
||||
-- ECR-047 GrowthInsights FunnelDefinition write (additive admin.growth.write)
|
||||
|
||||
INSERT INTO admin_role_permissions(role_id, code)
|
||||
SELECT r.id, 'admin.growth.write'
|
||||
FROM admin_roles r
|
||||
WHERE r.name = 'super_admin'
|
||||
ON CONFLICT DO NOTHING;
|
||||
Reference in New Issue
Block a user