feat(ECR-043): StarConfig 写面闭环并 Closed
加法权限 admin.explore.write、POST/PUT+审计、C端 GET /star/configs、 H5 无 active 空态/失败回退;migration 000052。ExploreConfig Loop STOP,禁自动 ECR-044。 Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
@@ -595,9 +595,46 @@ export const adminApi = {
|
||||
privacyRequest: (id: string) =>
|
||||
request<Record<string, unknown>>('GET', `/privacy/requests/${id}`),
|
||||
starConfigs: () =>
|
||||
request<{ items: Array<Record<string, unknown>> }>('GET', '/explore/star-configs'),
|
||||
request<{
|
||||
items: Array<{
|
||||
id: string
|
||||
code: string
|
||||
title: string
|
||||
active: boolean
|
||||
system: boolean
|
||||
updated_at: string
|
||||
}>
|
||||
}>('GET', '/explore/star-configs'),
|
||||
starConfig: (id: string) =>
|
||||
request<Record<string, unknown>>('GET', `/explore/star-configs/${id}`),
|
||||
request<{
|
||||
id: string
|
||||
code: string
|
||||
title: string
|
||||
active: boolean
|
||||
system: boolean
|
||||
updated_at: string
|
||||
}>('GET', `/explore/star-configs/${id}`),
|
||||
createStarConfig: (body: { code: string; title: string; active: boolean }) =>
|
||||
request<{
|
||||
id: string
|
||||
code: string
|
||||
title: string
|
||||
active: boolean
|
||||
system: boolean
|
||||
updated_at: string
|
||||
}>('POST', '/explore/star-configs', body),
|
||||
updateStarConfig: (
|
||||
id: string,
|
||||
body: { code: string; title: string; active: boolean },
|
||||
) =>
|
||||
request<{
|
||||
id: string
|
||||
code: string
|
||||
title: string
|
||||
active: boolean
|
||||
system: boolean
|
||||
updated_at: string
|
||||
}>('PUT', `/explore/star-configs/${id}`, body),
|
||||
rhythmConfigs: () =>
|
||||
request<{ items: Array<Record<string, unknown>> }>('GET', '/explore/rhythm-configs'),
|
||||
rhythmConfig: (id: string) =>
|
||||
|
||||
@@ -35,6 +35,7 @@ async function onLogout() {
|
||||
<RouterLink to="/ai">AI</RouterLink>
|
||||
<RouterLink to="/crisis">危机</RouterLink>
|
||||
<RouterLink to="/cms">CMS</RouterLink>
|
||||
<RouterLink to="/star-configs">星座配置</RouterLink>
|
||||
<RouterLink to="/catalogs">目录仓</RouterLink>
|
||||
<RouterLink to="/orders">订单</RouterLink>
|
||||
<RouterLink v-if="auth.can('admin.membership.plans.read')" to="/pricing">定价</RouterLink>
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
<script setup lang="ts">
|
||||
import { onMounted, reactive, ref } from 'vue'
|
||||
import { adminApi } from '@/api/client'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
|
||||
type Row = Awaited<ReturnType<typeof adminApi.starConfigs>>['items'][number]
|
||||
|
||||
const auth = useAuthStore()
|
||||
const canWrite = () => auth.can('admin.explore.write')
|
||||
|
||||
const loading = ref(false)
|
||||
const error = ref('')
|
||||
const items = ref<Row[]>([])
|
||||
const selected = ref<Row | null>(null)
|
||||
const saving = ref(false)
|
||||
const formErr = ref('')
|
||||
const form = reactive({
|
||||
code: '',
|
||||
title: '',
|
||||
active: true,
|
||||
})
|
||||
|
||||
async function load() {
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
try {
|
||||
const res = await adminApi.starConfigs()
|
||||
items.value = res.items || []
|
||||
} catch (e) {
|
||||
error.value = e instanceof Error ? e.message : '加载失败'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
function resetForm() {
|
||||
form.code = ''
|
||||
form.title = ''
|
||||
form.active = true
|
||||
selected.value = null
|
||||
formErr.value = ''
|
||||
}
|
||||
|
||||
async function openRow(id: string) {
|
||||
formErr.value = ''
|
||||
try {
|
||||
const row = await adminApi.starConfig(id)
|
||||
selected.value = row
|
||||
form.code = row.code
|
||||
form.title = row.title
|
||||
form.active = row.active
|
||||
} catch {
|
||||
selected.value = null
|
||||
}
|
||||
}
|
||||
|
||||
function payload() {
|
||||
return {
|
||||
code: form.code.trim(),
|
||||
title: form.title.trim(),
|
||||
active: form.active,
|
||||
}
|
||||
}
|
||||
|
||||
async function createRow() {
|
||||
if (!canWrite()) return
|
||||
saving.value = true
|
||||
formErr.value = ''
|
||||
try {
|
||||
const row = await adminApi.createStarConfig(payload())
|
||||
await load()
|
||||
await openRow(row.id)
|
||||
} catch (e) {
|
||||
formErr.value = e instanceof Error ? e.message : '创建失败'
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function saveRow() {
|
||||
if (!selected.value || !canWrite()) return
|
||||
saving.value = true
|
||||
formErr.value = ''
|
||||
try {
|
||||
const row = await adminApi.updateStarConfig(selected.value.id, payload())
|
||||
selected.value = row
|
||||
await load()
|
||||
} catch (e) {
|
||||
formErr.value = e instanceof Error ? e.message : '保存失败'
|
||||
} finally {
|
||||
saving.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function toggleActive() {
|
||||
if (!selected.value || !canWrite()) return
|
||||
form.active = !form.active
|
||||
await saveRow()
|
||||
}
|
||||
|
||||
onMounted(() => {
|
||||
void load()
|
||||
})
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<section>
|
||||
<h1>星座配置</h1>
|
||||
<p class="muted">StarConfig 写面 · 下架仅 active=false · ECR-043</p>
|
||||
<p v-if="!canWrite()" class="err">需要 admin.explore.write 才可写</p>
|
||||
<p v-if="loading" class="muted">加载中…</p>
|
||||
<p v-else-if="error" class="err">{{ error }}</p>
|
||||
<div v-else class="layout">
|
||||
<div class="card">
|
||||
<h2>列表</h2>
|
||||
<button v-if="canWrite()" class="btn" type="button" @click="resetForm">新建</button>
|
||||
<p v-if="!items.length" class="muted">暂无</p>
|
||||
<table v-else>
|
||||
<thead>
|
||||
<tr><th>代码</th><th>标题</th><th>状态</th><th></th></tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<tr v-for="b in items" :key="b.id">
|
||||
<td><code>{{ b.code }}</code></td>
|
||||
<td>{{ b.title }}</td>
|
||||
<td>{{ b.active ? '启用' : '停用' }}</td>
|
||||
<td><button class="btn" type="button" @click="openRow(b.id)">编辑</button></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="card">
|
||||
<h2>{{ selected ? '编辑' : '新建' }}</h2>
|
||||
<label>代码 <input v-model="form.code" :disabled="!!selected?.system || !canWrite()" /></label>
|
||||
<label>标题 <input v-model="form.title" :disabled="!canWrite()" /></label>
|
||||
<label class="check"><input v-model="form.active" type="checkbox" :disabled="!canWrite()" /> 启用</label>
|
||||
<p v-if="formErr" class="err">{{ formErr }}</p>
|
||||
<div v-if="canWrite()" class="actions">
|
||||
<button v-if="!selected" class="btn primary" type="button" :disabled="saving" @click="createRow">
|
||||
创建
|
||||
</button>
|
||||
<template v-else>
|
||||
<button class="btn primary" type="button" :disabled="saving" @click="saveRow">保存</button>
|
||||
<button class="btn" type="button" :disabled="saving" @click="toggleActive">
|
||||
{{ form.active ? '下架' : '上架' }}
|
||||
</button>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
<style scoped>
|
||||
h1 { margin: 0 0 0.35rem; font-size: 1.35rem; }
|
||||
h2 { margin: 0 0 0.6rem; font-size: 1.05rem; }
|
||||
.layout { display: grid; grid-template-columns: 1.2fr 1fr; gap: 1rem; margin-top: 1rem; }
|
||||
code { font-size: 0.8rem; }
|
||||
.card label { display: block; margin: 0.4rem 0; font-size: 0.9rem; }
|
||||
.card input { width: 100%; margin-top: 0.2rem; }
|
||||
.check { display: flex; align-items: center; gap: 0.4rem; }
|
||||
.actions { display: flex; gap: 0.5rem; margin-top: 0.75rem; }
|
||||
.btn.primary { font-weight: 600; }
|
||||
@media (max-width: 900px) { .layout { grid-template-columns: 1fr; } }
|
||||
</style>
|
||||
@@ -24,6 +24,12 @@ const router = createRouter({
|
||||
{ path: 'ai', name: 'ai', component: () => import('@/pages/AIConfigPage.vue') },
|
||||
{ path: 'crisis', name: 'crisis', component: () => import('@/pages/CrisisPage.vue') },
|
||||
{ path: 'cms', name: 'cms', component: () => import('@/pages/CMSPage.vue') },
|
||||
{
|
||||
path: 'star-configs',
|
||||
name: 'star-configs',
|
||||
component: () => import('@/pages/StarConfigPage.vue'),
|
||||
meta: { permission: 'admin.explore.read' },
|
||||
},
|
||||
{ path: 'catalogs', name: 'catalogs', component: () => import('@/pages/CatalogHubPage.vue') },
|
||||
{ path: 'push', name: 'push', component: () => import('@/pages/PushJobsPage.vue') },
|
||||
{ path: 'admins', name: 'admins', component: () => import('@/pages/AdminsPage.vue'), meta: { superOnly: true } },
|
||||
|
||||
@@ -16,6 +16,8 @@ func (h *AdminHandler) registerStarConfigs(authed *gin.RouterGroup) {
|
||||
g := authed.Group("/explore")
|
||||
g.GET("/star-configs", middleware.RequireAdminPermission(h.Svc, admin.PermExploreRead), h.ListStarConfigs)
|
||||
g.GET("/star-configs/:id", middleware.RequireAdminPermission(h.Svc, admin.PermExploreRead), h.GetStarConfig)
|
||||
g.POST("/star-configs", middleware.RequireAdminPermission(h.Svc, admin.PermExploreWrite), h.CreateStarConfig)
|
||||
g.PUT("/star-configs/:id", middleware.RequireAdminPermission(h.Svc, admin.PermExploreWrite), h.UpdateStarConfig)
|
||||
}
|
||||
|
||||
func (h *AdminHandler) ListStarConfigs(c *gin.Context) {
|
||||
@@ -44,3 +46,66 @@ func (h *AdminHandler) GetStarConfig(c *gin.Context) {
|
||||
}
|
||||
response.OK(c, row)
|
||||
}
|
||||
|
||||
func (h *AdminHandler) CreateStarConfig(c *gin.Context) {
|
||||
adminID, ok := middleware.AdminIDFromContext(c)
|
||||
if !ok {
|
||||
response.Fail(c, http.StatusUnauthorized, 40101, "admin auth required")
|
||||
return
|
||||
}
|
||||
var body admin.StarConfigWriteBody
|
||||
if err := c.ShouldBindJSON(&body); err != nil {
|
||||
response.Fail(c, http.StatusBadRequest, 40054, "invalid body")
|
||||
return
|
||||
}
|
||||
row, err := h.Svc.CreateStarConfig(c.Request.Context(), adminID, body)
|
||||
if errors.Is(err, admin.ErrInvalidStarConfig) {
|
||||
response.Fail(c, http.StatusBadRequest, 40055, "invalid star config")
|
||||
return
|
||||
}
|
||||
if errors.Is(err, admin.ErrStarConfigConflict) {
|
||||
response.Fail(c, http.StatusConflict, 40912, "star config code conflict")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.Fail(c, http.StatusInternalServerError, 50052, "create star config failed")
|
||||
return
|
||||
}
|
||||
response.OK(c, row)
|
||||
}
|
||||
|
||||
func (h *AdminHandler) UpdateStarConfig(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.StarConfigWriteBody
|
||||
if err := c.ShouldBindJSON(&body); err != nil {
|
||||
response.Fail(c, http.StatusBadRequest, 40054, "invalid body")
|
||||
return
|
||||
}
|
||||
row, err := h.Svc.UpdateStarConfig(c.Request.Context(), adminID, id, body)
|
||||
if errors.Is(err, admin.ErrStarConfigNotFound) {
|
||||
response.Fail(c, http.StatusNotFound, 40420, "star-config not found")
|
||||
return
|
||||
}
|
||||
if errors.Is(err, admin.ErrInvalidStarConfig) {
|
||||
response.Fail(c, http.StatusBadRequest, 40055, "invalid star config")
|
||||
return
|
||||
}
|
||||
if errors.Is(err, admin.ErrStarConfigConflict) {
|
||||
response.Fail(c, http.StatusConflict, 40912, "star config code conflict")
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.Fail(c, http.StatusInternalServerError, 50053, "update star 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"
|
||||
)
|
||||
|
||||
// StarConfigPublicHandler serves GET /api/v1/star/configs (DeviceAuth).
|
||||
type StarConfigPublicHandler struct {
|
||||
Repo *repository.AdminRepo
|
||||
}
|
||||
|
||||
// Register mounts public star config routes.
|
||||
func (h *StarConfigPublicHandler) Register(api *gin.RouterGroup) {
|
||||
api.GET("/star/configs", h.ListActive)
|
||||
}
|
||||
|
||||
func (h *StarConfigPublicHandler) ListActive(c *gin.Context) {
|
||||
if h.Repo == nil {
|
||||
response.OK(c, gin.H{"items": []repository.StarConfigRow{}})
|
||||
return
|
||||
}
|
||||
items, err := h.Repo.ListActiveStarConfigs(c.Request.Context())
|
||||
if err != nil {
|
||||
response.Fail(c, http.StatusInternalServerError, 50054, "star configs failed")
|
||||
return
|
||||
}
|
||||
if items == nil {
|
||||
items = []repository.StarConfigRow{}
|
||||
}
|
||||
response.OK(c, gin.H{"items": items})
|
||||
}
|
||||
@@ -101,6 +101,7 @@ func NewRouter(pool *pgxpool.Pool, cfg config.Config) *gin.Engine {
|
||||
(&handler.AuthHandler{Svc: authSvc}).Register(authed)
|
||||
(&handler.AnalyticsHandler{Svc: analyticsSvc}).Register(authed)
|
||||
(&handler.HomeHandler{Svc: homeSvc}).Register(authed)
|
||||
(&handler.StarConfigPublicHandler{Repo: adminRepo}).Register(authed)
|
||||
|
||||
gated := authed.Group("")
|
||||
gated.Use(middleware.RequireRegistered(pool))
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
package integration_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
func TestExploreStarConfigWrite(t *testing.T) {
|
||||
r, pool := setupAPIPool(t)
|
||||
ctx := context.Background()
|
||||
tok := adminLogin(t, r, "admin", "change-me")
|
||||
devKey := fmt.Sprintf("star-cfg-%d", time.Now().UnixNano())
|
||||
|
||||
code := fmt.Sprintf("star_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/star-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 star_configs WHERE id=$1`, created.ID)
|
||||
})
|
||||
|
||||
_, httpCode = doAdminJSON(t, r, http.MethodPost, "/api/v1/admin/explore/star-configs", body, tok)
|
||||
if httpCode != http.StatusConflict {
|
||||
t.Fatalf("dup expected 409 got %d", httpCode)
|
||||
}
|
||||
|
||||
env, _, httpCode = doJSONExpect(t, r, http.MethodGet, "/api/v1/star/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/star-configs/"+created.ID, body, tok)
|
||||
if httpCode != 200 {
|
||||
t.Fatalf("update %d", httpCode)
|
||||
}
|
||||
env, _, _ = doJSONExpect(t, r, http.MethodGet, "/api/v1/star/configs", nil, devKey, 0)
|
||||
_ = json.Unmarshal(env.Data, &pub)
|
||||
for _, it := range pub.Items {
|
||||
if it.Code == code {
|
||||
t.Fatal("inactive still listed")
|
||||
}
|
||||
}
|
||||
|
||||
// Deactivate all including seed — C-end may be empty
|
||||
_, _ = pool.Exec(ctx, `UPDATE star_configs SET active=false`)
|
||||
t.Cleanup(func() {
|
||||
_, _ = pool.Exec(ctx, `UPDATE star_configs SET active=true WHERE system=true`)
|
||||
})
|
||||
env, _, _ = doJSONExpect(t, r, http.MethodGet, "/api/v1/star/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.star_config.create','explore.star_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, "sc_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("scro_%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/star-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"
|
||||
)
|
||||
|
||||
// StarConfigWriteInput is create/update payload.
|
||||
type StarConfigWriteInput struct {
|
||||
Code string
|
||||
Title string
|
||||
Active bool
|
||||
}
|
||||
|
||||
// ListActiveStarConfigs returns active configs for C-end.
|
||||
func (r *AdminRepo) ListActiveStarConfigs(ctx context.Context) ([]StarConfigRow, error) {
|
||||
rows, err := r.Pool.Query(ctx, `
|
||||
SELECT id, code, title, active, system, updated_at
|
||||
FROM star_configs
|
||||
WHERE active = true
|
||||
ORDER BY code ASC
|
||||
LIMIT 100`)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []StarConfigRow
|
||||
for rows.Next() {
|
||||
var row StarConfigRow
|
||||
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()
|
||||
}
|
||||
|
||||
// CreateStarConfigWithAudit inserts and audits.
|
||||
func (r *AdminRepo) CreateStarConfigWithAudit(
|
||||
ctx context.Context, adminID uuid.UUID, in StarConfigWriteInput, meta json.RawMessage,
|
||||
) (*StarConfigRow, error) {
|
||||
tx, err := r.Pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
var row StarConfigRow
|
||||
err = tx.QueryRow(ctx, `
|
||||
INSERT INTO star_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, mapStarConfigWriteErr(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.star_config.create','star_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
|
||||
}
|
||||
|
||||
// UpdateStarConfigWithAudit updates and audits.
|
||||
func (r *AdminRepo) UpdateStarConfigWithAudit(
|
||||
ctx context.Context, adminID, id uuid.UUID, in StarConfigWriteInput, meta json.RawMessage,
|
||||
) (*StarConfigRow, 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 star_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 StarConfigRow
|
||||
err = tx.QueryRow(ctx, `
|
||||
UPDATE star_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, mapStarConfigWriteErr(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.star_config.update','star_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 mapStarConfigWriteErr(err error) error {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
||||
return errString("star config code conflict")
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// StarConfigCodeConflict reports unique violation.
|
||||
func StarConfigCodeConflict(err error) bool {
|
||||
return err != nil && strings.Contains(err.Error(), "star config code conflict")
|
||||
}
|
||||
@@ -34,6 +34,7 @@ const (
|
||||
PermCMSWrite = "admin.cms.write"
|
||||
PermPrivacyRead = "admin.privacy.read"
|
||||
PermExploreRead = "admin.explore.read"
|
||||
PermExploreWrite = "admin.explore.write"
|
||||
PermGrowthRead = "admin.growth.read"
|
||||
)
|
||||
|
||||
@@ -44,7 +45,7 @@ var knownPermissions = map[string]struct{}{
|
||||
PermUsersStatusWrite: {}, PermMembershipPlansRead: {}, PermMembershipPlansWrite: {},
|
||||
PermMembershipCodesRead: {}, PermMembershipCodesWrite: {},
|
||||
PermAskRead: {}, PermAskTranscriptRead: {}, PermAskFeedbackWrite: {}, PermContentSafetyRead: {},
|
||||
PermAIConfigRead: {}, PermCrisisRead: {}, PermCMSRead: {}, PermCMSWrite: {}, PermGrowthRead: {}, PermExploreRead: {}, PermPrivacyRead: {},
|
||||
PermAIConfigRead: {}, PermCrisisRead: {}, PermCMSRead: {}, PermCMSWrite: {}, PermGrowthRead: {}, PermExploreRead: {}, PermExploreWrite: {}, PermPrivacyRead: {},
|
||||
}
|
||||
|
||||
var (
|
||||
|
||||
@@ -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 (
|
||||
ErrInvalidStarConfig = errors.New("invalid star config")
|
||||
ErrStarConfigConflict = errors.New("star config code conflict")
|
||||
starConfigCodeRe = regexp.MustCompile(`^[a-z][a-z0-9_]{1,62}$`)
|
||||
)
|
||||
|
||||
// StarConfigWriteBody is JSON for create/update.
|
||||
type StarConfigWriteBody struct {
|
||||
Code string `json:"code"`
|
||||
Title string `json:"title"`
|
||||
Active bool `json:"active"`
|
||||
}
|
||||
|
||||
// CreateStarConfig validates, inserts, audits.
|
||||
func (s *Service) CreateStarConfig(ctx context.Context, adminID uuid.UUID, body StarConfigWriteBody) (*repository.StarConfigRow, error) {
|
||||
in, err := normalizeStarConfigWrite(body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
meta, _ := json.Marshal(map[string]any{"code": in.Code, "active": in.Active})
|
||||
row, err := s.Repo.CreateStarConfigWithAudit(ctx, adminID, in, meta)
|
||||
if repository.StarConfigCodeConflict(err) {
|
||||
return nil, ErrStarConfigConflict
|
||||
}
|
||||
return row, err
|
||||
}
|
||||
|
||||
// UpdateStarConfig validates, updates, audits.
|
||||
func (s *Service) UpdateStarConfig(ctx context.Context, adminID, id uuid.UUID, body StarConfigWriteBody) (*repository.StarConfigRow, error) {
|
||||
in, err := normalizeStarConfigWrite(body)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
meta, _ := json.Marshal(map[string]any{"code": in.Code, "active": in.Active})
|
||||
row, err := s.Repo.UpdateStarConfigWithAudit(ctx, adminID, id, in, meta)
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, ErrStarConfigNotFound
|
||||
}
|
||||
if repository.StarConfigCodeConflict(err) {
|
||||
return nil, ErrStarConfigConflict
|
||||
}
|
||||
return row, err
|
||||
}
|
||||
|
||||
func normalizeStarConfigWrite(body StarConfigWriteBody) (repository.StarConfigWriteInput, error) {
|
||||
code := strings.TrimSpace(body.Code)
|
||||
title := strings.TrimSpace(body.Title)
|
||||
if !starConfigCodeRe.MatchString(code) {
|
||||
return repository.StarConfigWriteInput{}, ErrInvalidStarConfig
|
||||
}
|
||||
if title == "" || utf8.RuneCountInString(title) > 128 {
|
||||
return repository.StarConfigWriteInput{}, ErrInvalidStarConfig
|
||||
}
|
||||
return repository.StarConfigWriteInput{Code: code, Title: title, Active: body.Active}, nil
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
-- ECR-043 rollback
|
||||
|
||||
DELETE FROM admin_role_permissions
|
||||
WHERE code = 'admin.explore.write'
|
||||
AND role_id IN (SELECT id FROM admin_roles WHERE name = 'super_admin');
|
||||
@@ -0,0 +1,7 @@
|
||||
-- ECR-043 ExploreConfig StarConfig write (additive permission)
|
||||
|
||||
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;
|
||||
@@ -36,6 +36,8 @@ export function useStarProfilePage() {
|
||||
const loading = ref(false)
|
||||
const needBirth = ref(true)
|
||||
const error = ref('')
|
||||
/** Fail-open: true until proven empty; API error keeps generation. */
|
||||
const configAvailable = ref(true)
|
||||
const report = ref<GrowthReport | null>(null)
|
||||
const paying = ref(false)
|
||||
const shareOpen = ref(false)
|
||||
@@ -149,7 +151,21 @@ export function useStarProfilePage() {
|
||||
clearDayTimer()
|
||||
}
|
||||
|
||||
async function refreshConfigGate() {
|
||||
try {
|
||||
const res = await api.getStarConfigs()
|
||||
configAvailable.value = (res.items || []).length > 0
|
||||
} catch {
|
||||
configAvailable.value = true
|
||||
}
|
||||
}
|
||||
|
||||
async function generate(y: number, m: number, d: number) {
|
||||
if (!configAvailable.value) {
|
||||
error.value = '星座配置暂未开放'
|
||||
needBirth.value = true
|
||||
return
|
||||
}
|
||||
loading.value = true
|
||||
error.value = ''
|
||||
needBirth.value = false
|
||||
@@ -175,6 +191,10 @@ export function useStarProfilePage() {
|
||||
}
|
||||
|
||||
async function start() {
|
||||
if (!configAvailable.value) {
|
||||
error.value = '星座配置暂未开放'
|
||||
return
|
||||
}
|
||||
const y = Number(year.value)
|
||||
const m = Number(month.value)
|
||||
const d = Number(day.value)
|
||||
@@ -188,6 +208,7 @@ export function useStarProfilePage() {
|
||||
|
||||
async function load() {
|
||||
if (!(await ensureAccount(router, route.fullPath))) return
|
||||
await refreshConfigGate()
|
||||
const reportId = String(route.query.report_id || '')
|
||||
if (reportId) {
|
||||
loading.value = true
|
||||
@@ -204,6 +225,11 @@ export function useStarProfilePage() {
|
||||
}
|
||||
return
|
||||
}
|
||||
if (!configAvailable.value) {
|
||||
needBirth.value = true
|
||||
report.value = null
|
||||
return
|
||||
}
|
||||
loading.value = true
|
||||
try {
|
||||
const cached = await loadSelfLatest('star')
|
||||
@@ -268,6 +294,7 @@ export function useStarProfilePage() {
|
||||
return {
|
||||
loading,
|
||||
needBirth,
|
||||
configAvailable,
|
||||
error,
|
||||
report,
|
||||
paying,
|
||||
|
||||
@@ -17,8 +17,15 @@
|
||||
</template>
|
||||
|
||||
<div class="body">
|
||||
<div v-if="!configAvailable && !report" class="empty-gate">
|
||||
<HomeToolIcon name="star" :size="56" />
|
||||
<p class="empty-title">星座配置暂未开放</p>
|
||||
<p class="empty-sub">运营尚未启用星座配置,请稍后再来</p>
|
||||
<button class="cta-off" type="button" disabled>生成我的星座</button>
|
||||
</div>
|
||||
|
||||
<StarBirthForm
|
||||
v-if="needBirth && !report"
|
||||
v-else-if="needBirth && !report"
|
||||
v-model:year="year"
|
||||
v-model:month="month"
|
||||
v-model:day="day"
|
||||
@@ -110,6 +117,7 @@ const { selfLabel } = useAccountNickname()
|
||||
const {
|
||||
loading,
|
||||
needBirth,
|
||||
configAvailable,
|
||||
error,
|
||||
report,
|
||||
paying,
|
||||
@@ -195,4 +203,35 @@ function onPlanetSelect(key: string) {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
.body { padding: 8px 16px 24px; }
|
||||
.empty-gate {
|
||||
text-align: center;
|
||||
padding: 28px 16px 12px;
|
||||
}
|
||||
.empty-title {
|
||||
font-family: var(--font-display);
|
||||
font-size: 20px;
|
||||
font-weight: 700;
|
||||
margin-top: 10px;
|
||||
letter-spacing: 0.06em;
|
||||
}
|
||||
.empty-sub {
|
||||
font-size: 13px;
|
||||
color: rgba(0, 0, 0, 0.42);
|
||||
margin-top: 8px;
|
||||
line-height: 1.5;
|
||||
}
|
||||
.cta-off {
|
||||
margin-top: 16px;
|
||||
width: 100%;
|
||||
max-width: 320px;
|
||||
padding: 13px;
|
||||
border: none;
|
||||
border-radius: 22px;
|
||||
color: #fff;
|
||||
font-size: 15px;
|
||||
font-weight: 600;
|
||||
background: linear-gradient(135deg, #ff7a6e, var(--color-primary));
|
||||
opacity: 0.45;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
</style>
|
||||
|
||||
Reference in New Issue
Block a user