feat(ECR-040): ExploreConfig ScaleDefinition 只读投影并 Closed

复用 scales 表只读投影;admin-h5 /catalogs 聚合 026–040 目录;Loop 队列 STOP。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
jackyu66git
2026-08-08 03:20:42 +08:00
co-authored by Cursor
parent 432c090046
commit e9c11cdf1d
26 changed files with 463 additions and 2 deletions
+9 -1
View File
@@ -457,6 +457,10 @@ export const adminApi = {
request<{ items: Array<Record<string, unknown>> }>('GET', '/content-safety/cases'),
case: (id: string) =>
request<Record<string, unknown>>('GET', `/content-safety/cases/${id}`),
events: () =>
request<{ items: Array<Record<string, unknown>> }>('GET', '/crisis/events'),
event: (id: string) =>
request<Record<string, unknown>>('GET', `/crisis/events/${id}`),
interventions: () =>
request<{ items: Array<Record<string, unknown>> }>('GET', '/crisis/interventions'),
intervention: (id: string) =>
@@ -467,7 +471,7 @@ export const adminApi = {
request<Record<string, unknown>>('GET', `/ask/handoffs/${id}`),
requests: () =>
request<{ items: Array<Record<string, unknown>> }>('GET', '/privacy/requests'),
request: (id: string) =>
privacyRequest: (id: string) =>
request<Record<string, unknown>>('GET', `/privacy/requests/${id}`),
starConfigs: () =>
request<{ items: Array<Record<string, unknown>> }>('GET', '/explore/star-configs'),
@@ -489,6 +493,10 @@ export const adminApi = {
request<{ items: Array<Record<string, unknown>> }>('GET', '/analytics/funnel-definitions'),
funnelDefinition: (id: string) =>
request<Record<string, unknown>>('GET', `/analytics/funnel-definitions/${id}`),
exploreScales: () =>
request<{ items: Array<Record<string, unknown>> }>('GET', '/explore/scales'),
exploreScale: (id: string) =>
request<Record<string, unknown>>('GET', `/explore/scales/${id}`),
orders: () =>
request<{
items: Array<{
+1
View File
@@ -35,6 +35,7 @@ async function onLogout() {
<RouterLink to="/ai">AI</RouterLink>
<RouterLink to="/crisis">危机</RouterLink>
<RouterLink to="/cms">CMS</RouterLink>
<RouterLink to="/catalogs">目录仓</RouterLink>
<RouterLink to="/orders">订单</RouterLink>
<RouterLink to="/audit">审计</RouterLink>
</nav>
@@ -0,0 +1,91 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { adminApi } from '@/api/client'
type Row = { id: string; code?: string; slug?: string; title?: string; status?: string }
const catalogs = [
{ key: 'publications', label: '定时发布', load: () => adminApi.publications() },
{ key: 'knowledgeChunks', label: '知识块', load: () => adminApi.knowledgeChunks() },
{ key: 'tools', label: '工具定义', load: () => adminApi.tools() },
{ key: 'blockPolicies', label: '拦截策略', load: () => adminApi.blockPolicies() },
{ key: 'cases', label: '审核案', load: () => adminApi.cases() },
{ key: 'events', label: '危机事件', load: () => adminApi.events() },
{ key: 'interventions', label: '干预结果', load: () => adminApi.interventions() },
{ key: 'handoffs', label: '转接案', load: () => adminApi.handoffs() },
{ key: 'privacy', label: '隐私请求', load: () => adminApi.requests() },
{ key: 'star', label: '星座配置', load: () => adminApi.starConfigs() },
{ key: 'rhythm', label: '节律配置', load: () => adminApi.rhythmConfigs() },
{ key: 'decks', label: '意象牌组', load: () => adminApi.imageCardDecks() },
{ key: 'templates', label: '报告模板', load: () => adminApi.reportTemplates() },
{ key: 'funnels', label: '漏斗定义', load: () => adminApi.funnelDefinitions() },
{ key: 'scales', label: '量表定义', load: () => adminApi.exploreScales() },
] as const
const active = ref(0)
const loading = ref(false)
const error = ref('')
const items = ref<Row[]>([])
async function load(idx = active.value) {
active.value = idx
loading.value = true
error.value = ''
try {
const res = (await catalogs[idx].load()) as { items?: Row[] }
items.value = (res.items || []) as Row[]
} catch (e) {
error.value = e instanceof Error ? e.message : '加载失败'
items.value = []
} finally {
loading.value = false
}
}
onMounted(() => {
void load(0)
})
</script>
<template>
<section>
<h1>目录只读仓</h1>
<p class="muted">ECR-026040 运营只读目录聚合不可写发布</p>
<div class="tabs">
<button
v-for="(c, i) in catalogs"
:key="c.key"
class="btn"
:class="{ on: i === active }"
type="button"
@click="load(i)"
>
{{ c.label }}
</button>
</div>
<p v-if="loading" class="muted">加载中</p>
<p v-else-if="error" class="err">{{ error }}</p>
<div v-else class="card">
<p v-if="!items.length" class="muted">暂无</p>
<table v-else>
<thead>
<tr><th>标识</th><th>标题</th><th>状态</th></tr>
</thead>
<tbody>
<tr v-for="it in items" :key="it.id">
<td><code>{{ it.code || it.slug || it.id.slice(0, 8) }}</code></td>
<td>{{ it.title || '—' }}</td>
<td>{{ it.status || '—' }}</td>
</tr>
</tbody>
</table>
</div>
</section>
</template>
<style scoped>
h1 { margin: 0 0 0.35rem; font-size: 1.35rem; }
.tabs { display: flex; flex-wrap: wrap; gap: 0.4rem; margin: 1rem 0; }
.btn.on { background: #ffe4e0; color: var(--accent); font-weight: 700; }
code { font-size: 0.8rem; }
</style>
+1
View File
@@ -22,6 +22,7 @@ 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: 'catalogs', name: 'catalogs', component: () => import('@/pages/CatalogHubPage.vue') },
{ path: 'audit', name: 'audit', component: () => import('@/pages/AuditPage.vue') },
],
},
+1
View File
@@ -68,6 +68,7 @@ func (h *AdminHandler) Register(api *gin.RouterGroup) {
h.registerImageCardDecks(authed)
h.registerReportTemplates(authed)
h.registerFunnelDefinitions(authed)
h.registerExploreScales(authed)
}
func (h *AdminHandler) Login(c *gin.Context) {
@@ -0,0 +1,46 @@
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) registerExploreScales(authed *gin.RouterGroup) {
g := authed.Group("/explore")
g.GET("/scales", middleware.RequireAdminPermission(h.Svc, admin.PermExploreRead), h.ListExploreScales)
g.GET("/scales/:id", middleware.RequireAdminPermission(h.Svc, admin.PermExploreRead), h.GetExploreScale)
}
func (h *AdminHandler) ListExploreScales(c *gin.Context) {
items, err := h.Svc.ListScalesAdmin(c.Request.Context())
if err != nil {
response.Fail(c, http.StatusInternalServerError, 50060, "list explore scales failed")
return
}
response.OK(c, gin.H{"items": items})
}
func (h *AdminHandler) GetExploreScale(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.GetScaleAdmin(c.Request.Context(), id)
if errors.Is(err, admin.ErrScaleNotFound) {
response.Fail(c, http.StatusNotFound, 40430, "scale not found")
return
}
if err != nil {
response.Fail(c, http.StatusInternalServerError, 50061, "get explore scale failed")
return
}
response.OK(c, row)
}
@@ -0,0 +1,81 @@
package integration_test
import (
"context"
"encoding/json"
"fmt"
"net/http"
"testing"
"time"
"github.com/google/uuid"
"golang.org/x/crypto/bcrypt"
)
func TestExploreScaleDefinitions(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/explore/scales", 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, "sc_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("sclim_%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/explore/scales", 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/explore/scales", 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"`
} `json:"items"`
}
_ = json.Unmarshal(env.Data, &list)
if len(list.Items) == 0 {
t.Fatal("expected at least one scale")
}
id := list.Items[0].ID
env, code = doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/explore/scales/"+id, nil, tok)
if code != 200 {
t.Fatalf("get %d", code)
}
_, code = doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/explore/scales/"+fakeUUID(), nil, tok)
if code != http.StatusNotFound {
t.Fatalf("expected 404, got %d", code)
}
}
@@ -120,6 +120,19 @@ func (r *ScaleRepo) ListAllAdmin(ctx context.Context) ([]ScaleAdminItem, error)
return out, rows.Err()
}
// GetAdmin loads one scale by id for ops read.
func (r *ScaleRepo) GetAdmin(ctx context.Context, id uuid.UUID) (*ScaleAdminItem, error) {
var it ScaleAdminItem
err := r.Pool.QueryRow(ctx, `
SELECT id, slug, title, description, status FROM scales
WHERE id=$1 AND deleted_at IS NULL`, id,
).Scan(&it.ID, &it.Slug, &it.Title, &it.Description, &it.Status)
if err != nil {
return nil, err
}
return &it, nil
}
// UpdateStatus sets published|draft.
func (r *ScaleRepo) UpdateStatus(ctx context.Context, id uuid.UUID, status string) error {
return r.UpdateStatusWithAudit(ctx, id, status, uuid.Nil, nil)
@@ -42,6 +42,18 @@ func (s *Service) ListScalesAdmin(ctx context.Context) ([]repository.ScaleAdminI
return s.Scales.ListAllAdmin(ctx)
}
// GetScaleAdmin loads one scale for explore read projection.
func (s *Service) GetScaleAdmin(ctx context.Context, id uuid.UUID) (*repository.ScaleAdminItem, error) {
if s.Scales == nil {
return nil, errors.New("scales unavailable")
}
row, err := s.Scales.GetAdmin(ctx, id)
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrScaleNotFound
}
return row, err
}
// PatchScaleStatus updates published|draft and audits in one transaction.
func (s *Service) PatchScaleStatus(ctx context.Context, adminID, scaleID uuid.UUID, status string) error {
if status != "published" && status != "draft" {