feat(ECR-046): ScaleDefinition 元数据写面闭环并 Closed
explore.write POST/PUT · create→draft · status 仍 ECR-008 · migration 000055 · Loop STOP Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -16,6 +16,8 @@ func (h *AdminHandler) registerExploreScales(authed *gin.RouterGroup) {
|
||||
g := authed.Group("/explore")
|
||||
g.GET("/scales", middleware.RequireAnyAdminPermission(h.Svc, admin.PermExploreRead, admin.PermContentWrite), h.ListExploreScales)
|
||||
g.GET("/scales/:id", middleware.RequireAnyAdminPermission(h.Svc, admin.PermExploreRead, admin.PermContentWrite), h.GetExploreScale)
|
||||
g.POST("/scales", middleware.RequireAdminPermission(h.Svc, admin.PermExploreWrite), h.CreateExploreScale)
|
||||
g.PUT("/scales/:id", middleware.RequireAdminPermission(h.Svc, admin.PermExploreWrite), h.UpdateExploreScale)
|
||||
}
|
||||
|
||||
func (h *AdminHandler) ListExploreScales(c *gin.Context) {
|
||||
@@ -44,3 +46,66 @@ func (h *AdminHandler) GetExploreScale(c *gin.Context) {
|
||||
}
|
||||
response.OK(c, row)
|
||||
}
|
||||
|
||||
func (h *AdminHandler) CreateExploreScale(c *gin.Context) {
|
||||
adminID, ok := middleware.AdminIDFromContext(c)
|
||||
if !ok {
|
||||
response.Fail(c, http.StatusUnauthorized, 40101, "admin auth required")
|
||||
return
|
||||
}
|
||||
var body admin.ScaleDefinitionWriteBody
|
||||
if err := c.ShouldBindJSON(&body); err != nil {
|
||||
response.Fail(c, http.StatusBadRequest, 40054, "invalid body")
|
||||
return
|
||||
}
|
||||
row, err := h.Svc.CreateScaleDefinition(c.Request.Context(), adminID, body)
|
||||
if errors.Is(err, admin.ErrInvalidScaleDefinition) {
|
||||
response.Fail(c, http.StatusBadRequest, 40055, "invalid scale definition")
|
||||
return
|
||||
}
|
||||
if errors.Is(err, admin.ErrScaleDefinitionConflict) {
|
||||
response.Fail(c, http.StatusConflict, 40912, "scale slug conflict")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.Fail(c, http.StatusInternalServerError, 50062, "create scale definition failed")
|
||||
return
|
||||
}
|
||||
response.OK(c, row)
|
||||
}
|
||||
|
||||
func (h *AdminHandler) UpdateExploreScale(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.ScaleDefinitionWriteBody
|
||||
if err := c.ShouldBindJSON(&body); err != nil {
|
||||
response.Fail(c, http.StatusBadRequest, 40054, "invalid body")
|
||||
return
|
||||
}
|
||||
row, err := h.Svc.UpdateScaleDefinition(c.Request.Context(), adminID, id, body)
|
||||
if errors.Is(err, admin.ErrScaleNotFound) {
|
||||
response.Fail(c, http.StatusNotFound, 40430, "scale not found")
|
||||
return
|
||||
}
|
||||
if errors.Is(err, admin.ErrInvalidScaleDefinition) {
|
||||
response.Fail(c, http.StatusBadRequest, 40055, "invalid scale definition")
|
||||
return
|
||||
}
|
||||
if errors.Is(err, admin.ErrScaleDefinitionConflict) {
|
||||
response.Fail(c, http.StatusConflict, 40912, "scale slug conflict")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.Fail(c, http.StatusInternalServerError, 50063, "update scale definition failed")
|
||||
return
|
||||
}
|
||||
response.OK(c, row)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
func TestExploreScaleDefinitionWrite(t *testing.T) {
|
||||
r, pool := setupAPIPool(t)
|
||||
ctx := context.Background()
|
||||
tok := adminLogin(t, r, "admin", "change-me")
|
||||
|
||||
slug := fmt.Sprintf("scale-w-%d", time.Now().UnixNano()%1_000_000)
|
||||
body := map[string]any{"slug": slug, "title": "测试量表元数据", "description": "desc"}
|
||||
env, httpCode := doAdminJSON(t, r, http.MethodPost, "/api/v1/admin/explore/scales", 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"`
|
||||
Slug string `json:"slug"`
|
||||
Status string `json:"status"`
|
||||
Title string `json:"title"`
|
||||
}
|
||||
_ = json.Unmarshal(env.Data, &created)
|
||||
if created.ID == "" || created.Status != "draft" {
|
||||
t.Fatalf("bad create %#v", created)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
_, _ = pool.Exec(ctx, `DELETE FROM scales WHERE id=$1`, created.ID)
|
||||
})
|
||||
|
||||
_, httpCode = doAdminJSON(t, r, http.MethodPost, "/api/v1/admin/explore/scales", body, tok)
|
||||
if httpCode != http.StatusConflict {
|
||||
t.Fatalf("dup expected 409 got %d", httpCode)
|
||||
}
|
||||
|
||||
// draft must not appear on C-end published list
|
||||
key := mustRegister(t, r)
|
||||
env, key = doJSON(t, r, http.MethodGet, "/api/v1/scales", nil, key)
|
||||
var pub struct {
|
||||
Items []struct {
|
||||
Slug string `json:"slug"`
|
||||
} `json:"items"`
|
||||
}
|
||||
_ = json.Unmarshal(env.Data, &pub)
|
||||
for _, it := range pub.Items {
|
||||
if it.Slug == slug {
|
||||
t.Fatal("draft listed on C-end")
|
||||
}
|
||||
}
|
||||
|
||||
body["title"] = "改标题"
|
||||
env, httpCode = doAdminJSON(t, r, http.MethodPut, "/api/v1/admin/explore/scales/"+created.ID, body, tok)
|
||||
if httpCode != 200 {
|
||||
t.Fatalf("update %d", httpCode)
|
||||
}
|
||||
_ = json.Unmarshal(env.Data, &created)
|
||||
if created.Title != "改标题" || created.Status != "draft" {
|
||||
t.Fatalf("put changed status or missed title %#v", created)
|
||||
}
|
||||
|
||||
// publish via ECR-008 channel
|
||||
_, httpCode = doAdminJSON(t, r, http.MethodPatch, "/api/v1/admin/scales/"+created.ID, map[string]any{"status": "published"}, tok)
|
||||
if httpCode != 200 {
|
||||
t.Fatalf("patch status %d", httpCode)
|
||||
}
|
||||
env, _ = doJSON(t, r, http.MethodGet, "/api/v1/scales", nil, key)
|
||||
_ = json.Unmarshal(env.Data, &pub)
|
||||
found := false
|
||||
for _, it := range pub.Items {
|
||||
if it.Slug == slug {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatal("published missing on C-end")
|
||||
}
|
||||
|
||||
var n int
|
||||
_ = pool.QueryRow(ctx, `
|
||||
SELECT COUNT(*) FROM admin_audit_logs
|
||||
WHERE action IN ('explore.scale_definition.create','explore.scale_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, "sd_ro_"+limitedRoleID.String()[:8])
|
||||
_, _ = pool.Exec(ctx, `INSERT INTO admin_role_permissions(role_id, code) VALUES ($1,'admin.explore.read')`, limitedRoleID)
|
||||
hash, _ := bcrypt.GenerateFromPassword([]byte("ro-pass"), bcrypt.DefaultCost)
|
||||
roUser := fmt.Sprintf("sdro_%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/explore/scales", map[string]any{
|
||||
"slug": "x-ro", "title": "no", "description": "",
|
||||
}, roTok)
|
||||
if httpCode != http.StatusForbidden {
|
||||
t.Fatalf("expected 403 got %d", httpCode)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgconn"
|
||||
)
|
||||
|
||||
// ScaleDefinitionWriteInput is explore-side metadata payload (no status).
|
||||
type ScaleDefinitionWriteInput struct {
|
||||
Slug string
|
||||
Title string
|
||||
Description string
|
||||
}
|
||||
|
||||
// CreateScaleDefinitionWithAudit inserts draft scale metadata + audit.
|
||||
func (r *ScaleRepo) CreateScaleDefinitionWithAudit(
|
||||
ctx context.Context, adminID uuid.UUID, in ScaleDefinitionWriteInput, meta json.RawMessage,
|
||||
) (*ScaleAdminItem, error) {
|
||||
tx, err := r.Pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
var it ScaleAdminItem
|
||||
err = tx.QueryRow(ctx, `
|
||||
INSERT INTO scales(slug, title, description, status)
|
||||
VALUES ($1,$2,$3,'draft')
|
||||
RETURNING id, slug, title, description, status`,
|
||||
in.Slug, in.Title, in.Description,
|
||||
).Scan(&it.ID, &it.Slug, &it.Title, &it.Description, &it.Status)
|
||||
if err != nil {
|
||||
return nil, mapScaleDefinitionWriteErr(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,'explore.scale_definition.create','scale',$2,$3)`,
|
||||
adminID, it.ID.String(), meta,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &it, nil
|
||||
}
|
||||
|
||||
// UpdateScaleDefinitionWithAudit updates metadata only (never status).
|
||||
func (r *ScaleRepo) UpdateScaleDefinitionWithAudit(
|
||||
ctx context.Context, adminID, id uuid.UUID, in ScaleDefinitionWriteInput, meta json.RawMessage,
|
||||
) (*ScaleAdminItem, error) {
|
||||
tx, err := r.Pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
var it ScaleAdminItem
|
||||
err = tx.QueryRow(ctx, `
|
||||
UPDATE scales
|
||||
SET slug=$2, title=$3, description=$4, updated_at=now()
|
||||
WHERE id=$1 AND deleted_at IS NULL
|
||||
RETURNING id, slug, title, description, status`,
|
||||
id, in.Slug, in.Title, in.Description,
|
||||
).Scan(&it.ID, &it.Slug, &it.Title, &it.Description, &it.Status)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, pgx.ErrNoRows
|
||||
}
|
||||
if err != nil {
|
||||
return nil, mapScaleDefinitionWriteErr(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,'explore.scale_definition.update','scale',$2,$3)`,
|
||||
adminID, id.String(), meta,
|
||||
); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &it, nil
|
||||
}
|
||||
|
||||
func mapScaleDefinitionWriteErr(err error) error {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
||||
return errString("scale slug conflict")
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// ScaleSlugConflict reports unique violation.
|
||||
func ScaleSlugConflict(err error) bool {
|
||||
return err != nil && strings.Contains(err.Error(), "scale slug conflict")
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
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 (
|
||||
ErrInvalidScaleDefinition = errors.New("invalid scale definition")
|
||||
ErrScaleDefinitionConflict = errors.New("scale slug conflict")
|
||||
scaleSlugRe = regexp.MustCompile(`^[a-z][a-z0-9-]{1,62}$`)
|
||||
)
|
||||
|
||||
// ScaleDefinitionWriteBody is explore-side JSON (no status).
|
||||
type ScaleDefinitionWriteBody struct {
|
||||
Slug string `json:"slug"`
|
||||
Title string `json:"title"`
|
||||
Description string `json:"description"`
|
||||
}
|
||||
|
||||
// CreateScaleDefinition creates draft metadata.
|
||||
func (s *Service) CreateScaleDefinition(ctx context.Context, adminID uuid.UUID, body ScaleDefinitionWriteBody) (*repository.ScaleAdminItem, error) {
|
||||
if s.Scales == nil {
|
||||
return nil, errors.New("scales unavailable")
|
||||
}
|
||||
in, err := normalizeScaleDefinitionWrite(body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
meta, _ := json.Marshal(map[string]any{"slug": in.Slug})
|
||||
row, err := s.Scales.CreateScaleDefinitionWithAudit(ctx, adminID, in, meta)
|
||||
if repository.ScaleSlugConflict(err) {
|
||||
return nil, ErrScaleDefinitionConflict
|
||||
}
|
||||
return row, err
|
||||
}
|
||||
|
||||
// UpdateScaleDefinition updates metadata; preserves status.
|
||||
func (s *Service) UpdateScaleDefinition(ctx context.Context, adminID, id uuid.UUID, body ScaleDefinitionWriteBody) (*repository.ScaleAdminItem, error) {
|
||||
if s.Scales == nil {
|
||||
return nil, errors.New("scales unavailable")
|
||||
}
|
||||
in, err := normalizeScaleDefinitionWrite(body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
meta, _ := json.Marshal(map[string]any{"slug": in.Slug})
|
||||
row, err := s.Scales.UpdateScaleDefinitionWithAudit(ctx, adminID, id, in, meta)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrScaleNotFound
|
||||
}
|
||||
if repository.ScaleSlugConflict(err) {
|
||||
return nil, ErrScaleDefinitionConflict
|
||||
}
|
||||
return row, err
|
||||
}
|
||||
|
||||
func normalizeScaleDefinitionWrite(body ScaleDefinitionWriteBody) (repository.ScaleDefinitionWriteInput, error) {
|
||||
slug := strings.TrimSpace(body.Slug)
|
||||
title := strings.TrimSpace(body.Title)
|
||||
desc := strings.TrimSpace(body.Description)
|
||||
if !scaleSlugRe.MatchString(slug) {
|
||||
return repository.ScaleDefinitionWriteInput{}, ErrInvalidScaleDefinition
|
||||
}
|
||||
if title == "" || utf8.RuneCountInString(title) > 128 {
|
||||
return repository.ScaleDefinitionWriteInput{}, ErrInvalidScaleDefinition
|
||||
}
|
||||
if utf8.RuneCountInString(desc) > 512 {
|
||||
return repository.ScaleDefinitionWriteInput{}, ErrInvalidScaleDefinition
|
||||
}
|
||||
return repository.ScaleDefinitionWriteInput{Slug: slug, Title: title, Description: desc}, nil
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
-- ECR-046 rollback marker (permission shared — do not revoke explore.write)
|
||||
SELECT 1;
|
||||
@@ -0,0 +1,7 @@
|
||||
-- ECR-046 ScaleDefinition metadata write (reuse admin.explore.write)
|
||||
|
||||
INSERT INTO admin_role_permissions(role_id, code)
|
||||
SELECT r.id, 'admin.explore.write'
|
||||
FROM admin_roles r
|
||||
WHERE r.name = 'super_admin'
|
||||
ON CONFLICT DO NOTHING;
|
||||
Reference in New Issue
Block a user