feat(ECR-044): RhythmConfig 写面闭环并 Closed

复用 admin.explore.write、POST/PUT+审计、C端 GET /rhythm/configs、
H5 无 active 空态/失败回退;migration 000053。ExploreConfig Loop STOP,禁自动 ECR-045。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
jackyu66git
2026-08-13 20:43:08 +08:00
co-authored by Cursor
parent fcc7667ba3
commit 87b463b2bb
33 changed files with 1006 additions and 35 deletions
@@ -16,6 +16,8 @@ func (h *AdminHandler) registerRhythmConfigs(authed *gin.RouterGroup) {
g := authed.Group("/explore")
g.GET("/rhythm-configs", middleware.RequireAdminPermission(h.Svc, admin.PermExploreRead), h.ListRhythmConfigs)
g.GET("/rhythm-configs/:id", middleware.RequireAdminPermission(h.Svc, admin.PermExploreRead), h.GetRhythmConfig)
g.POST("/rhythm-configs", middleware.RequireAdminPermission(h.Svc, admin.PermExploreWrite), h.CreateRhythmConfig)
g.PUT("/rhythm-configs/:id", middleware.RequireAdminPermission(h.Svc, admin.PermExploreWrite), h.UpdateRhythmConfig)
}
func (h *AdminHandler) ListRhythmConfigs(c *gin.Context) {
@@ -44,3 +46,66 @@ func (h *AdminHandler) GetRhythmConfig(c *gin.Context) {
}
response.OK(c, row)
}
func (h *AdminHandler) CreateRhythmConfig(c *gin.Context) {
adminID, ok := middleware.AdminIDFromContext(c)
if !ok {
response.Fail(c, http.StatusUnauthorized, 40101, "admin auth required")
return
}
var body admin.RhythmConfigWriteBody
if err := c.ShouldBindJSON(&body); err != nil {
response.Fail(c, http.StatusBadRequest, 40054, "invalid body")
return
}
row, err := h.Svc.CreateRhythmConfig(c.Request.Context(), adminID, body)
if errors.Is(err, admin.ErrInvalidRhythmConfig) {
response.Fail(c, http.StatusBadRequest, 40055, "invalid rhythm config")
return
}
if errors.Is(err, admin.ErrRhythmConfigConflict) {
response.Fail(c, http.StatusConflict, 40912, "rhythm config code conflict")
return
}
if err != nil {
response.Fail(c, http.StatusInternalServerError, 50052, "create rhythm config failed")
return
}
response.OK(c, row)
}
func (h *AdminHandler) UpdateRhythmConfig(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.RhythmConfigWriteBody
if err := c.ShouldBindJSON(&body); err != nil {
response.Fail(c, http.StatusBadRequest, 40054, "invalid body")
return
}
row, err := h.Svc.UpdateRhythmConfig(c.Request.Context(), adminID, id, body)
if errors.Is(err, admin.ErrRhythmConfigNotFound) {
response.Fail(c, http.StatusNotFound, 40420, "rhythm-config not found")
return
}
if errors.Is(err, admin.ErrInvalidRhythmConfig) {
response.Fail(c, http.StatusBadRequest, 40055, "invalid rhythm config")
return
}
if errors.Is(err, admin.ErrRhythmConfigConflict) {
response.Fail(c, http.StatusConflict, 40912, "rhythm config code conflict")
return
}
if err != nil {
response.Fail(c, http.StatusInternalServerError, 50053, "update rhythm config failed")
return
}
response.OK(c, row)
}
@@ -0,0 +1,36 @@
package handler
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/yuxingu/digital-psychology/apps/api/internal/repository"
"github.com/yuxingu/digital-psychology/apps/api/pkg/response"
)
// RhythmConfigPublicHandler serves GET /api/v1/rhythm/configs (DeviceAuth).
type RhythmConfigPublicHandler struct {
Repo *repository.AdminRepo
}
// Register mounts public rhythm config routes.
func (h *RhythmConfigPublicHandler) Register(api *gin.RouterGroup) {
api.GET("/rhythm/configs", h.ListActive)
}
func (h *RhythmConfigPublicHandler) ListActive(c *gin.Context) {
if h.Repo == nil {
response.OK(c, gin.H{"items": []repository.RhythmConfigRow{}})
return
}
items, err := h.Repo.ListActiveRhythmConfigs(c.Request.Context())
if err != nil {
response.Fail(c, http.StatusInternalServerError, 50054, "rhythm configs failed")
return
}
if items == nil {
items = []repository.RhythmConfigRow{}
}
response.OK(c, gin.H{"items": items})
}
+1
View File
@@ -102,6 +102,7 @@ func NewRouter(pool *pgxpool.Pool, cfg config.Config) *gin.Engine {
(&handler.AnalyticsHandler{Svc: analyticsSvc}).Register(authed)
(&handler.HomeHandler{Svc: homeSvc}).Register(authed)
(&handler.StarConfigPublicHandler{Repo: adminRepo}).Register(authed)
(&handler.RhythmConfigPublicHandler{Repo: adminRepo}).Register(authed)
gated := authed.Group("")
gated.Use(middleware.RequireRegistered(pool))
@@ -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 TestExploreRhythmConfigWrite(t *testing.T) {
r, pool := setupAPIPool(t)
ctx := context.Background()
tok := adminLogin(t, r, "admin", "change-me")
devKey := fmt.Sprintf("rhythm-cfg-%d", time.Now().UnixNano())
code := fmt.Sprintf("rhythm_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/explore/rhythm-configs", 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"`
}
_ = json.Unmarshal(env.Data, &created)
if created.ID == "" {
t.Fatal("bad create")
}
t.Cleanup(func() {
_, _ = pool.Exec(ctx, `DELETE FROM rhythm_configs WHERE id=$1`, created.ID)
})
_, httpCode = doAdminJSON(t, r, http.MethodPost, "/api/v1/admin/explore/rhythm-configs", body, tok)
if httpCode != http.StatusConflict {
t.Fatalf("dup expected 409 got %d", httpCode)
}
env, _, httpCode = doJSONExpect(t, r, http.MethodGet, "/api/v1/rhythm/configs", nil, devKey, 0)
if httpCode != 200 {
t.Fatalf("public %d", httpCode)
}
var pub struct {
Items []struct {
Code string `json:"code"`
} `json:"items"`
}
_ = json.Unmarshal(env.Data, &pub)
found := false
for _, it := range pub.Items {
if it.Code == code {
found = true
break
}
}
if !found {
t.Fatalf("missing active %#v", pub.Items)
}
body["active"] = false
_, httpCode = doAdminJSON(t, r, http.MethodPut, "/api/v1/admin/explore/rhythm-configs/"+created.ID, body, tok)
if httpCode != 200 {
t.Fatalf("update %d", httpCode)
}
env, _, _ = doJSONExpect(t, r, http.MethodGet, "/api/v1/rhythm/configs", nil, devKey, 0)
_ = json.Unmarshal(env.Data, &pub)
for _, it := range pub.Items {
if it.Code == code {
t.Fatal("inactive still listed")
}
}
_, _ = pool.Exec(ctx, `UPDATE rhythm_configs SET active=false`)
t.Cleanup(func() {
_, _ = pool.Exec(ctx, `UPDATE rhythm_configs SET active=true WHERE system=true`)
})
env, _, _ = doJSONExpect(t, r, http.MethodGet, "/api/v1/rhythm/configs", nil, devKey, 0)
_ = json.Unmarshal(env.Data, &pub)
if len(pub.Items) != 0 {
t.Fatalf("expected empty after all inactive, got %#v", pub.Items)
}
var n int
_ = pool.QueryRow(ctx, `
SELECT COUNT(*) FROM admin_audit_logs
WHERE action IN ('explore.rhythm_config.create','explore.rhythm_config.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, "rc_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("rcro_%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/rhythm-configs", 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,139 @@
package repository
import (
"context"
"encoding/json"
"errors"
"strings"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
)
// RhythmConfigWriteInput is create/update payload.
type RhythmConfigWriteInput struct {
Code string
Title string
Active bool
}
// ListActiveRhythmConfigs returns active configs for C-end.
func (r *AdminRepo) ListActiveRhythmConfigs(ctx context.Context) ([]RhythmConfigRow, error) {
rows, err := r.Pool.Query(ctx, `
SELECT id, code, title, active, system, updated_at
FROM rhythm_configs
WHERE active = true
ORDER BY code ASC
LIMIT 100`)
if err != nil {
return nil, err
}
defer rows.Close()
var out []RhythmConfigRow
for rows.Next() {
var row RhythmConfigRow
if err := rows.Scan(&row.ID, &row.Code, &row.Title, &row.Active, &row.System, &row.UpdatedAt); err != nil {
return nil, err
}
out = append(out, row)
}
return out, rows.Err()
}
// CreateRhythmConfigWithAudit inserts and audits.
func (r *AdminRepo) CreateRhythmConfigWithAudit(
ctx context.Context, adminID uuid.UUID, in RhythmConfigWriteInput, meta json.RawMessage,
) (*RhythmConfigRow, error) {
tx, err := r.Pool.Begin(ctx)
if err != nil {
return nil, err
}
defer tx.Rollback(ctx)
var row RhythmConfigRow
err = tx.QueryRow(ctx, `
INSERT INTO rhythm_configs(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, mapRhythmConfigWriteErr(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.rhythm_config.create','rhythm_config',$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
}
// UpdateRhythmConfigWithAudit updates and audits.
func (r *AdminRepo) UpdateRhythmConfigWithAudit(
ctx context.Context, adminID, id uuid.UUID, in RhythmConfigWriteInput, meta json.RawMessage,
) (*RhythmConfigRow, 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 rhythm_configs 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 RhythmConfigRow
err = tx.QueryRow(ctx, `
UPDATE rhythm_configs
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, mapRhythmConfigWriteErr(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.rhythm_config.update','rhythm_config',$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 mapRhythmConfigWriteErr(err error) error {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
return errString("rhythm config code conflict")
}
return err
}
// RhythmConfigCodeConflict reports unique violation.
func RhythmConfigCodeConflict(err error) bool {
return err != nil && strings.Contains(err.Error(), "rhythm config 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 (
ErrInvalidRhythmConfig = errors.New("invalid rhythm config")
ErrRhythmConfigConflict = errors.New("rhythm config code conflict")
rhythmConfigCodeRe = regexp.MustCompile(`^[a-z][a-z0-9_]{1,62}$`)
)
// RhythmConfigWriteBody is JSON for create/update.
type RhythmConfigWriteBody struct {
Code string `json:"code"`
Title string `json:"title"`
Active bool `json:"active"`
}
// CreateRhythmConfig validates, inserts, audits.
func (s *Service) CreateRhythmConfig(ctx context.Context, adminID uuid.UUID, body RhythmConfigWriteBody) (*repository.RhythmConfigRow, error) {
in, err := normalizeRhythmConfigWrite(body)
if err != nil {
return nil, err
}
meta, _ := json.Marshal(map[string]any{"code": in.Code, "active": in.Active})
row, err := s.Repo.CreateRhythmConfigWithAudit(ctx, adminID, in, meta)
if repository.RhythmConfigCodeConflict(err) {
return nil, ErrRhythmConfigConflict
}
return row, err
}
// UpdateRhythmConfig validates, updates, audits.
func (s *Service) UpdateRhythmConfig(ctx context.Context, adminID, id uuid.UUID, body RhythmConfigWriteBody) (*repository.RhythmConfigRow, error) {
in, err := normalizeRhythmConfigWrite(body)
if err != nil {
return nil, err
}
meta, _ := json.Marshal(map[string]any{"code": in.Code, "active": in.Active})
row, err := s.Repo.UpdateRhythmConfigWithAudit(ctx, adminID, id, in, meta)
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrRhythmConfigNotFound
}
if repository.RhythmConfigCodeConflict(err) {
return nil, ErrRhythmConfigConflict
}
return row, err
}
func normalizeRhythmConfigWrite(body RhythmConfigWriteBody) (repository.RhythmConfigWriteInput, error) {
code := strings.TrimSpace(body.Code)
title := strings.TrimSpace(body.Title)
if !rhythmConfigCodeRe.MatchString(code) {
return repository.RhythmConfigWriteInput{}, ErrInvalidRhythmConfig
}
if title == "" || utf8.RuneCountInString(title) > 128 {
return repository.RhythmConfigWriteInput{}, ErrInvalidRhythmConfig
}
return repository.RhythmConfigWriteInput{Code: code, Title: title, Active: body.Active}, nil
}