feat(ECR-042): OpsCMS FeedSlot 薄写面

Admin POST/PUT 复用 admin.cms.write;C 端 GET /home/feed-slots;首页无 active 槽隐藏推荐区、失败回退展示;无新 migration。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
jackyu66git
2026-08-13 20:02:01 +08:00
co-authored by Cursor
parent 655141980a
commit 56f661748a
27 changed files with 773 additions and 25 deletions
+2 -1
View File
@@ -38,7 +38,8 @@
| [ops-knowledge-source.md](ops-knowledge-source.md) | AI 知识源 KnowledgeSource | §7 | `admin-h5` `/ai` | Ops · **ECR-023** |
| [ops-banner.md](ops-banner.md) | OpsCMS Banner(只读基线) | §7 | `admin-h5` `/cms` | Ops · **ECR-024** |
| [ops-banner-write.md](ops-banner-write.md) | OpsCMS Banner **写面** | §7 | admin CMS 写 · `GET /home/banners` | Write-Wave · **ECR-041** |
| [ops-feed-slot.md](ops-feed-slot.md) | OpsCMS FeedSlot | §7 | `admin-h5` `/cms` | Ops · **ECR-025** |
| [ops-feed-slot.md](ops-feed-slot.md) | OpsCMS FeedSlot(只读基线) | §7 | `admin-h5` `/cms` | Ops · **ECR-025** |
| [ops-feed-slot-write.md](ops-feed-slot-write.md) | OpsCMS FeedSlot **写面** | §7 | admin CMS 写 · `GET /home/feed-slots` | Write-Wave · **ECR-042** |
| [ops-scheduled-publication.md](ops-scheduled-publication.md) | OpsCMS ScheduledPublication | §7 | `/admin/cms/publications*` | Ops · **ECR-026** |
| [ops-knowledge-chunk.md](ops-knowledge-chunk.md) | AICoreConfig KnowledgeChunk | §7 | `/admin/ai/knowledge-chunks*` | Ops · **ECR-027** |
| [ops-tool-definition.md](ops-tool-definition.md) | AICoreConfig ToolDefinition | §7 | `/admin/ai/tools*` | Ops · **ECR-028** |
@@ -0,0 +1,40 @@
# Feature Spec: OpsCMS · FeedSlot 写面(Ops · ECR-042
> Status: `Active`**ECR-042 Closed**
> Map: `§7` · Capability: `OpsCMS` · BC: `Ops_CMS_NoUGC`
> Write-Wave: `docs/WAVE0/WRITE_WAVE_AUTHORIZATION.md`
> Predecessor: ECR-025 Closed · ECR-041 Closed
## Goal
运营可创建/更新/上下架 FeedSlot;C 端可读 active 槽位;首页主信息流区按 `home.main`(或 placement=home 的 active 槽)显隐;失败回退「仍展示推荐区」。
## In / Out
| In | Out |
|----|-----|
| Admin POST/PUT feed-slots · `admin.cms.write` | Banner 再扩 · ScheduledPublication 写 |
| C 端 GET `/home/feed-slots` | UGC 内容流正文 CMS · soft-delete |
| 首页:无 active home 槽 → 隐藏推荐区;API 失败 → 仍显示 | 真支付 · Crisis/Handoff · 新权限模型 |
## Domain
复用 `ops_feed_slots``code` 唯一 · `slot_key` · `placement` ∈ {home,explore,ask} · `active` · `system`system 不可改 code)。
## API
| Method | Path | Perm |
|--------|------|------|
| GET | `/admin/cms/feed-slots*` | cms.read |
| POST/PUT | `/admin/cms/feed-slots*` | cms.write |
| GET | `/home/feed-slots?placement=home` | DeviceAuth |
无 DELETE;下架 `active=false`
## AC
AC-F create/update/conflict/invalid · AC-S 401/403 · AC-A audit · AC-C 首页显隐与失败回退 · AC-O 无 Banner 合并 / 无 soft-delete
## Migration
无新表;权限已在 `000051`。本切片 **不新增 migration 文件**Max 保持 `000051`)。
+37
View File
@@ -521,6 +521,43 @@ export const adminApi = {
system: boolean
updated_at: string
}>('GET', `/cms/feed-slots/${id}`),
createFeedSlot: (body: {
code: string
title: string
slot_key: string
placement: string
active: boolean
}) =>
request<{
id: string
code: string
title: string
slot_key: string
placement: string
active: boolean
system: boolean
updated_at: string
}>('POST', '/cms/feed-slots', body),
updateFeedSlot: (
id: string,
body: {
code: string
title: string
slot_key: string
placement: string
active: boolean
},
) =>
request<{
id: string
code: string
title: string
slot_key: string
placement: string
active: boolean
system: boolean
updated_at: string
}>('PUT', `/cms/feed-slots/${id}`, body),
publications: () =>
request<{ items: Array<Record<string, unknown>> }>('GET', '/cms/publications'),
publication: (id: string) =>
+103 -12
View File
@@ -24,6 +24,15 @@ const slotsLoading = ref(false)
const slotsError = ref('')
const slots = ref<FeedSlot[]>([])
const selectedSlot = ref<FeedSlot | null>(null)
const slotSaving = ref(false)
const slotFormErr = ref('')
const slotForm = reactive({
code: '',
title: '',
slot_key: 'home.main',
placement: 'home',
active: true,
})
async function load() {
loading.value = true
@@ -79,13 +88,75 @@ async function openBanner(id: string) {
}
async function openSlot(id: string) {
slotFormErr.value = ''
try {
selectedSlot.value = await adminApi.feedSlot(id)
const s = await adminApi.feedSlot(id)
selectedSlot.value = s
slotForm.code = s.code
slotForm.title = s.title
slotForm.slot_key = s.slot_key
slotForm.placement = s.placement
slotForm.active = s.active
} catch {
selectedSlot.value = null
}
}
function resetSlotForm() {
slotForm.code = ''
slotForm.title = ''
slotForm.slot_key = 'home.main'
slotForm.placement = 'home'
slotForm.active = true
selectedSlot.value = null
slotFormErr.value = ''
}
function slotPayload() {
return {
code: slotForm.code.trim(),
title: slotForm.title.trim(),
slot_key: slotForm.slot_key.trim(),
placement: slotForm.placement,
active: slotForm.active,
}
}
async function createSlot() {
slotSaving.value = true
slotFormErr.value = ''
try {
const row = await adminApi.createFeedSlot(slotPayload())
await loadSlots()
await openSlot(row.id)
} catch (e) {
slotFormErr.value = e instanceof Error ? e.message : '创建失败'
} finally {
slotSaving.value = false
}
}
async function saveSlot() {
if (!selectedSlot.value) return
slotSaving.value = true
slotFormErr.value = ''
try {
const row = await adminApi.updateFeedSlot(selectedSlot.value.id, slotPayload())
selectedSlot.value = row
await loadSlots()
} catch (e) {
slotFormErr.value = e instanceof Error ? e.message : '保存失败'
} finally {
slotSaving.value = false
}
}
async function toggleSlotActive() {
if (!selectedSlot.value) return
slotForm.active = !slotForm.active
await saveSlot()
}
function payload() {
return {
code: form.code.trim(),
@@ -141,7 +212,7 @@ onMounted(() => {
<template>
<section>
<h1>运营位 CMS</h1>
<p class="muted">Banner 可写 · FeedSlot 只读 · UGC · 下架用停用</p>
<p class="muted">Banner / FeedSlot 可写 · 下架用停用 · UGC</p>
<p v-if="loading" class="muted">加载中</p>
<p v-else-if="error" class="err">{{ error }}</p>
<div v-else class="layout">
@@ -198,30 +269,50 @@ onMounted(() => {
<p v-else-if="slotsError" class="err gap">{{ slotsError }}</p>
<div v-else class="layout gap">
<div class="card">
<h2>栏目位 FeedSlot只读</h2>
<h2>栏目位 FeedSlot</h2>
<button class="btn" type="button" @click="resetSlotForm">新建</button>
<p v-if="!slots.length" class="muted">暂无</p>
<table v-else>
<thead>
<tr><th>代码</th><th>标题</th><th>slot_key</th><th>位置</th><th></th></tr>
<tr><th>代码</th><th>标题</th><th>slot_key</th><th>状态</th><th></th></tr>
</thead>
<tbody>
<tr v-for="s in slots" :key="s.id">
<td><code>{{ s.code }}</code></td>
<td>{{ s.title }}</td>
<td><code>{{ s.slot_key }}</code></td>
<td>{{ s.placement }}</td>
<td><button class="btn" type="button" @click="openSlot(s.id)">查看</button></td>
<td>{{ s.active ? '启用' : '停用' }}</td>
<td><button class="btn" type="button" @click="openSlot(s.id)">编辑</button></td>
</tr>
</tbody>
</table>
</div>
<div class="card">
<h2>栏目位详情</h2>
<template v-if="selectedSlot">
<p>{{ selectedSlot.title }} · {{ selectedSlot.placement }}</p>
<p class="muted">slot_key {{ selectedSlot.slot_key }}</p>
</template>
<p v-else class="muted">选择左侧栏目位</p>
<h2>{{ selectedSlot ? '编辑栏目位' : '新建栏目位' }}</h2>
<label>代码 <input v-model="slotForm.code" :disabled="!!selectedSlot?.system" /></label>
<label>标题 <input v-model="slotForm.title" /></label>
<label>slot_key <input v-model="slotForm.slot_key" /></label>
<label>
位置
<select v-model="slotForm.placement">
<option value="home">home</option>
<option value="explore">explore</option>
<option value="ask">ask</option>
</select>
</label>
<label class="check"><input v-model="slotForm.active" type="checkbox" /> 启用</label>
<p v-if="slotFormErr" class="err">{{ slotFormErr }}</p>
<div class="actions">
<button v-if="!selectedSlot" class="btn primary" type="button" :disabled="slotSaving" @click="createSlot">
创建
</button>
<template v-else>
<button class="btn primary" type="button" :disabled="slotSaving" @click="saveSlot">保存</button>
<button class="btn" type="button" :disabled="slotSaving" @click="toggleSlotActive">
{{ slotForm.active ? '下架' : '上架' }}
</button>
</template>
</div>
</div>
</div>
</section>
+65
View File
@@ -20,6 +20,8 @@ func (h *AdminHandler) registerCMS(authed *gin.RouterGroup) {
g.PUT("/banners/:id", middleware.RequireAdminPermission(h.Svc, admin.PermCMSWrite), h.UpdateBanner)
g.GET("/feed-slots", middleware.RequireAdminPermission(h.Svc, admin.PermCMSRead), h.ListFeedSlots)
g.GET("/feed-slots/:id", middleware.RequireAdminPermission(h.Svc, admin.PermCMSRead), h.GetFeedSlot)
g.POST("/feed-slots", middleware.RequireAdminPermission(h.Svc, admin.PermCMSWrite), h.CreateFeedSlot)
g.PUT("/feed-slots/:id", middleware.RequireAdminPermission(h.Svc, admin.PermCMSWrite), h.UpdateFeedSlot)
}
func (h *AdminHandler) ListBanners(c *gin.Context) {
@@ -138,3 +140,66 @@ func (h *AdminHandler) GetFeedSlot(c *gin.Context) {
}
response.OK(c, row)
}
func (h *AdminHandler) CreateFeedSlot(c *gin.Context) {
adminID, ok := middleware.AdminIDFromContext(c)
if !ok {
response.Fail(c, http.StatusUnauthorized, 40101, "admin auth required")
return
}
var body admin.FeedSlotWriteBody
if err := c.ShouldBindJSON(&body); err != nil {
response.Fail(c, http.StatusBadRequest, 40052, "invalid body")
return
}
row, err := h.Svc.CreateFeedSlot(c.Request.Context(), adminID, body)
if errors.Is(err, admin.ErrInvalidFeedSlot) {
response.Fail(c, http.StatusBadRequest, 40053, "invalid feed slot")
return
}
if errors.Is(err, admin.ErrFeedSlotConflict) {
response.Fail(c, http.StatusConflict, 40911, "feed slot code conflict")
return
}
if err != nil {
response.Fail(c, http.StatusInternalServerError, 50047, "create feed slot failed")
return
}
response.OK(c, row)
}
func (h *AdminHandler) UpdateFeedSlot(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.FeedSlotWriteBody
if err := c.ShouldBindJSON(&body); err != nil {
response.Fail(c, http.StatusBadRequest, 40052, "invalid body")
return
}
row, err := h.Svc.UpdateFeedSlot(c.Request.Context(), adminID, id, body)
if errors.Is(err, admin.ErrFeedSlotNotFound) {
response.Fail(c, http.StatusNotFound, 40411, "feed slot not found")
return
}
if errors.Is(err, admin.ErrInvalidFeedSlot) {
response.Fail(c, http.StatusBadRequest, 40053, "invalid feed slot")
return
}
if errors.Is(err, admin.ErrFeedSlotConflict) {
response.Fail(c, http.StatusConflict, 40911, "feed slot code conflict")
return
}
if err != nil {
response.Fail(c, http.StatusInternalServerError, 50048, "update feed slot failed")
return
}
response.OK(c, row)
}
+11
View File
@@ -21,6 +21,7 @@ func (h *HomeHandler) Register(api *gin.RouterGroup) {
g := api.Group("/home")
g.GET("/tools", h.Tools)
g.GET("/banners", h.Banners)
g.GET("/feed-slots", h.FeedSlots)
g.GET("/daily-tips", h.DailyTips)
}
@@ -46,6 +47,16 @@ func (h *HomeHandler) Banners(c *gin.Context) {
response.OK(c, gin.H{"items": items})
}
func (h *HomeHandler) FeedSlots(c *gin.Context) {
placement := c.DefaultQuery("placement", "home")
items, err := h.Svc.ListPublicFeedSlots(c.Request.Context(), placement)
if err != nil {
response.Fail(c, http.StatusInternalServerError, 50049, "home feed slots failed")
return
}
response.OK(c, gin.H{"items": items})
}
func (h *HomeHandler) DailyTips(c *gin.Context) {
uid, _ := middleware.UserIDFromContext(c)
tips, err := h.Svc.DailyTips(c.Request.Context(), uid)
@@ -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 TestOpsCMSFeedSlotWrite(t *testing.T) {
r, pool := setupAPIPool(t)
ctx := context.Background()
tok := adminLogin(t, r, "admin", "change-me")
devKey := fmt.Sprintf("feed-slot-write-%d", time.Now().UnixNano())
code := fmt.Sprintf("slot_w_%d", time.Now().UnixNano()%1_000_000)
body := map[string]any{
"code": code, "title": "测试槽", "slot_key": "home.test",
"placement": "home", "active": true,
}
env, httpCode := doAdminJSON(t, r, http.MethodPost, "/api/v1/admin/cms/feed-slots", 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.Fatalf("bad create")
}
t.Cleanup(func() {
_, _ = pool.Exec(ctx, `DELETE FROM ops_feed_slots WHERE id=$1`, created.ID)
})
_, httpCode = doAdminJSON(t, r, http.MethodPost, "/api/v1/admin/cms/feed-slots", body, tok)
if httpCode != http.StatusConflict {
t.Fatalf("dup expected 409 got %d", httpCode)
}
env, _, httpCode = doJSONExpect(t, r, http.MethodGet, "/api/v1/home/feed-slots?placement=home", nil, devKey, 0)
if httpCode != 200 {
t.Fatalf("home slots %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 slot %#v", pub.Items)
}
body["active"] = false
_, httpCode = doAdminJSON(t, r, http.MethodPut, "/api/v1/admin/cms/feed-slots/"+created.ID, body, tok)
if httpCode != 200 {
t.Fatalf("update %d", httpCode)
}
env, _, _ = doJSONExpect(t, r, http.MethodGet, "/api/v1/home/feed-slots?placement=home", nil, devKey, 0)
_ = json.Unmarshal(env.Data, &pub)
for _, it := range pub.Items {
if it.Code == code {
t.Fatalf("inactive still listed")
}
}
var n int
_ = pool.QueryRow(ctx, `
SELECT COUNT(*) FROM admin_audit_logs
WHERE action IN ('cms.feed_slot.create','cms.feed_slot.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, "fs_ro_"+limitedRoleID.String()[:8])
_, _ = pool.Exec(ctx, `INSERT INTO admin_role_permissions(role_id, code) VALUES ($1,'admin.cms.read')`, limitedRoleID)
hash, _ := bcrypt.GenerateFromPassword([]byte("ro-pass"), bcrypt.DefaultCost)
roUser := fmt.Sprintf("fsro_%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/cms/feed-slots", map[string]any{
"code": "x_ro", "title": "no", "slot_key": "home.x", "placement": "home", "active": true,
}, roTok)
if httpCode != http.StatusForbidden {
t.Fatalf("expected 403 got %d", httpCode)
}
}
@@ -0,0 +1,143 @@
package repository
import (
"context"
"encoding/json"
"errors"
"strings"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
)
// FeedSlotWriteInput is create/update payload.
type FeedSlotWriteInput struct {
Code string
Title string
SlotKey string
Placement string
Active bool
}
// ListActiveFeedSlots returns active slots for placement.
func (r *AdminRepo) ListActiveFeedSlots(ctx context.Context, placement string) ([]FeedSlotRow, error) {
rows, err := r.Pool.Query(ctx, `
SELECT id, code, title, slot_key, placement, active, system, updated_at
FROM ops_feed_slots
WHERE active = true AND placement = $1
ORDER BY code ASC
LIMIT 100`, placement)
if err != nil {
return nil, err
}
defer rows.Close()
var out []FeedSlotRow
for rows.Next() {
var s FeedSlotRow
if err := rows.Scan(
&s.ID, &s.Code, &s.Title, &s.SlotKey, &s.Placement, &s.Active, &s.System, &s.UpdatedAt,
); err != nil {
return nil, err
}
out = append(out, s)
}
return out, rows.Err()
}
// CreateFeedSlotWithAudit inserts and audits.
func (r *AdminRepo) CreateFeedSlotWithAudit(
ctx context.Context, adminID uuid.UUID, in FeedSlotWriteInput, meta json.RawMessage,
) (*FeedSlotRow, error) {
tx, err := r.Pool.Begin(ctx)
if err != nil {
return nil, err
}
defer tx.Rollback(ctx)
var s FeedSlotRow
err = tx.QueryRow(ctx, `
INSERT INTO ops_feed_slots(code, title, slot_key, placement, active, system)
VALUES ($1,$2,$3,$4,$5,false)
RETURNING id, code, title, slot_key, placement, active, system, updated_at`,
in.Code, in.Title, in.SlotKey, in.Placement, in.Active,
).Scan(&s.ID, &s.Code, &s.Title, &s.SlotKey, &s.Placement, &s.Active, &s.System, &s.UpdatedAt)
if err != nil {
return nil, mapFeedSlotWriteErr(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,'cms.feed_slot.create','feed_slot',$2,$3)`,
adminID, s.ID.String(), meta,
); err != nil {
return nil, err
}
if err := tx.Commit(ctx); err != nil {
return nil, err
}
return &s, nil
}
// UpdateFeedSlotWithAudit updates and audits.
func (r *AdminRepo) UpdateFeedSlotWithAudit(
ctx context.Context, adminID, id uuid.UUID, in FeedSlotWriteInput, meta json.RawMessage,
) (*FeedSlotRow, 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 ops_feed_slots 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 s FeedSlotRow
err = tx.QueryRow(ctx, `
UPDATE ops_feed_slots
SET code=$2, title=$3, slot_key=$4, placement=$5, active=$6, updated_at=now()
WHERE id=$1
RETURNING id, code, title, slot_key, placement, active, system, updated_at`,
id, code, in.Title, in.SlotKey, in.Placement, in.Active,
).Scan(&s.ID, &s.Code, &s.Title, &s.SlotKey, &s.Placement, &s.Active, &s.System, &s.UpdatedAt)
if err != nil {
return nil, mapFeedSlotWriteErr(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,'cms.feed_slot.update','feed_slot',$2,$3)`,
adminID, id.String(), meta,
); err != nil {
return nil, err
}
if err := tx.Commit(ctx); err != nil {
return nil, err
}
return &s, nil
}
func mapFeedSlotWriteErr(err error) error {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
return errString("feed slot code conflict")
}
return err
}
// FeedSlotCodeConflict reports unique violation.
func FeedSlotCodeConflict(err error) bool {
return err != nil && strings.Contains(err.Error(), "feed slot code 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 (
ErrInvalidFeedSlot = errors.New("invalid feed slot")
ErrFeedSlotConflict = errors.New("feed slot code conflict")
slotCodeRe = regexp.MustCompile(`^[a-z][a-z0-9_]{1,62}$`)
slotKeyRe = regexp.MustCompile(`^[a-z][a-z0-9_.]{1,62}$`)
)
// FeedSlotWriteBody is JSON for create/update.
type FeedSlotWriteBody struct {
Code string `json:"code"`
Title string `json:"title"`
SlotKey string `json:"slot_key"`
Placement string `json:"placement"`
Active bool `json:"active"`
}
// CreateFeedSlot validates, inserts, audits.
func (s *Service) CreateFeedSlot(ctx context.Context, adminID uuid.UUID, body FeedSlotWriteBody) (*repository.FeedSlotRow, error) {
in, err := normalizeFeedSlotWrite(body)
if err != nil {
return nil, err
}
meta, _ := json.Marshal(map[string]any{"code": in.Code, "active": in.Active})
row, err := s.Repo.CreateFeedSlotWithAudit(ctx, adminID, in, meta)
if repository.FeedSlotCodeConflict(err) {
return nil, ErrFeedSlotConflict
}
return row, err
}
// UpdateFeedSlot validates, updates, audits.
func (s *Service) UpdateFeedSlot(ctx context.Context, adminID, id uuid.UUID, body FeedSlotWriteBody) (*repository.FeedSlotRow, error) {
in, err := normalizeFeedSlotWrite(body)
if err != nil {
return nil, err
}
meta, _ := json.Marshal(map[string]any{"code": in.Code, "active": in.Active})
row, err := s.Repo.UpdateFeedSlotWithAudit(ctx, adminID, id, in, meta)
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrFeedSlotNotFound
}
if repository.FeedSlotCodeConflict(err) {
return nil, ErrFeedSlotConflict
}
return row, err
}
func normalizeFeedSlotWrite(body FeedSlotWriteBody) (repository.FeedSlotWriteInput, error) {
code := strings.TrimSpace(body.Code)
title := strings.TrimSpace(body.Title)
slotKey := strings.TrimSpace(body.SlotKey)
placement := strings.TrimSpace(body.Placement)
if !slotCodeRe.MatchString(code) || !slotKeyRe.MatchString(slotKey) {
return repository.FeedSlotWriteInput{}, ErrInvalidFeedSlot
}
if title == "" || utf8.RuneCountInString(title) > 128 {
return repository.FeedSlotWriteInput{}, ErrInvalidFeedSlot
}
if _, ok := bannerPlacements[placement]; !ok {
return repository.FeedSlotWriteInput{}, ErrInvalidFeedSlot
}
return repository.FeedSlotWriteInput{
Code: code, Title: title, SlotKey: slotKey, Placement: placement, Active: body.Active,
}, nil
}
+18
View File
@@ -58,6 +58,24 @@ func (s *Service) ListPublicBanners(ctx context.Context, placement string) ([]re
return items, nil
}
// ListPublicFeedSlots returns active feed slots for placement.
func (s *Service) ListPublicFeedSlots(ctx context.Context, placement string) ([]repository.FeedSlotRow, error) {
if placement == "" {
placement = "home"
}
if s.CMS == nil {
return []repository.FeedSlotRow{}, nil
}
items, err := s.CMS.ListActiveFeedSlots(ctx, placement)
if err != nil {
return nil, err
}
if items == nil {
items = []repository.FeedSlotRow{}
}
return items, nil
}
// ListAdmin returns all tools.
func (s *Service) ListAdmin(ctx context.Context) ([]repository.HomeTool, error) {
return s.Repo.ListAll(ctx)
@@ -65,6 +65,7 @@ export function useHomePage() {
gridRow2: [...homeGridRow2] as HomeTool[],
})
const feeds = ref<HomeFeed[]>([...homeFeeds])
const feedsVisible = ref(true)
onMounted(() => {
void api
@@ -101,6 +102,15 @@ export function useHomePage() {
.catch(() => {
/* keep static homeFeeds */
})
void api
.getHomeFeedSlots('home')
.then((res) => {
const items = res.items || []
feedsVisible.value = items.length > 0
})
.catch(() => {
feedsVisible.value = true
})
})
function goPlus(kind: 'inviteFill' | 'add' | 'synastry') {
@@ -128,6 +138,7 @@ export function useHomePage() {
tipsLoading,
...toRefs(grid),
feeds,
feedsVisible,
goPlus,
trackGrid,
}
+2 -1
View File
@@ -16,7 +16,7 @@
<div class="sheet reveal" style="--d: 100ms">
<HomeToolGrid :row1="gridRow1" :row2="gridRow2" @track="trackGrid" />
<HomePromoSection />
<HomeFeedSection :feeds="feeds" />
<HomeFeedSection v-if="feedsVisible" :feeds="feeds" />
</div>
</main>
</template>
@@ -38,6 +38,7 @@ const {
gridRow1,
gridRow2,
feeds,
feedsVisible,
goPlus,
trackGrid,
} = useHomePage()
@@ -0,0 +1,21 @@
# Backend Design: ECR-042 FeedSlot Write
| Field | Value |
|-------|-------|
| ID | BD-2026-042 |
| Status | Approved |
| Migration | NONE(复用 ops_feed_slots · perm 000051 |
| Level | L2 |
## Boundary
```text
POST/PUT /api/v1/admin/cms/feed-slots*
GET /api/v1/home/feed-slots
Permission: admin.cms.write (existing)
Audit: cms.feed_slot.create|update
```
## Out
Banner scope creep · soft-delete · UGC · payment · new RBAC subsystem
+1
View File
@@ -2,6 +2,7 @@
## 2026-08-13
- **ECR-042 Closed** OpsCMS FeedSlot 薄写面(复用 `admin.cms.write` · `GET /home/feed-slots` · 首页槽位显隐)· 无新 migration
- **ECR-041 Closed** OpsCMS Banner 薄写面(`admin.cms.write` · `GET /home/banners` · 首页投影回退 · migration `000051`)· Write-Wave 首刀;未做 FeedSlot
- **Write-Wave 开启:** `docs/WAVE0/WRITE_WAVE_AUTHORIZATION.md` · Continuous Loop 限定写面边界
- **仓侧治理最小补丁(非 ESS 内核):** `scripts/repo-governance-check.py`TRACEABILITY **Next ECR=`ECR-042`** · **Max Migration=`000051`**
+3
View File
@@ -0,0 +1,3 @@
# CODE_REVIEW — ECR-042
**Verdict:** Approve · FeedSlot write only · Banner untouched · no soft-delete/payment/UGC
+19
View File
@@ -0,0 +1,19 @@
ecr: ECR-042
capability: OpsCMS
change:
type: additive
breaking_change: false
migration_required: false
apis:
- method: POST
path: /api/v1/admin/cms/feed-slots
change: added
- method: PUT
path: /api/v1/admin/cms/feed-slots/{id}
change: added
- method: GET
path: /api/v1/home/feed-slots
change: added
perms:
- code: admin.cms.write
change: reused
+1 -8
View File
@@ -44,11 +44,4 @@ Spec `ops-banner-write` · BD-2026-041 · PRODUCT_SPEC/ECR-041 · CONTRACT_DIFF
## Coding gate
```text
repo-governance-check PASS
→ ess-validate design/implement as required
→ BD Approved
→ THEN Continuous Loop may start coding
```
本文件交付时 **禁止改 `apps/` / `packages/`**
Closed via Write-Wave Continuous Loop · Evidence: `docs/TEST_REPORT/ECR-041.md` · `docs/CODE_REVIEW/ECR-041.md`
+21
View File
@@ -0,0 +1,21 @@
# ECR-042
**Title:** OpsCMS · FeedSlot 薄写面
**Status:** **Closed**2026-08-13 · Write-Wave Continuous Loop
**Change Level:** L2
**Write-Wave:** Active · Predecessor ECR-041 Closed
## Change
1. Spec `ops-feed-slot-write`
2. Admin POST/PUT feed-slots + audit(复用 `admin.cms.write`
3. C 端 GET `/home/feed-slots`;首页推荐区按 home 槽 active 显隐
4. admin-h5 FeedSlot 编辑(Banner 写面不回退)
## Forbidden
Banner+FeedSlot 合并扩 scope · soft-delete · UGC · 真支付 · ScheduledPublication 写 · 新权限模型
## Trace
BD-2026-042 · CONTRACT_DIFF · TEST_REPORT · WRITE_WAVE_AUTHORIZATION
@@ -0,0 +1,3 @@
# HANDOFF — Architect → Engineer · ECR-042
Do FeedSlot write per ops-feed-slot-write.md. Reuse cms.write. No new migration. Don't touch Banner behavior beyond coexistence.
@@ -0,0 +1,3 @@
# HANDOFF — Engineer → Reviewer · ECR-042
TestOpsCMSFeedSlotWrite PASS · Ready Closed.
@@ -0,0 +1,3 @@
# PRODUCT_SPEC — ECR-042
对齐 ops-feed-slot-write.md · L2 · FeedSlot 写面
+2 -2
View File
@@ -53,8 +53,8 @@
- **本仓:** `ess_intake: strict` · Retro FAIL · 单 ECR Context
- **Ops foundation** `docs/WAVE0/` · `.ai/domain/boundary-rules.md` · `glossary.yaml` · Loop: `docs/WAVE0/LOOP_AUTHORIZATION.md`
- ECR: main 线 ECR-006016 ClosedOps 扩展 ECR-013A/B · 017040;分叉已固定为 `ECR-012-star` / `014-plan` / `015-code` / `016-insight`(见 TRACEABILITY
- **Next ECR / Max Migration**`docs/TRACEABILITY.md` 顶部锚点为准 · 现 **Next=`ECR-042`** · **Max=`000051`**
- **Write-Wave** `docs/WAVE0/WRITE_WAVE_AUTHORIZATION.md` · Active · **ECR-041 Banner Closed**;下一刀候选评估(非自动无限)
- **Next ECR / Max Migration** **Next=`ECR-043`** · **Max=`000051`**
- **Write-Wave** Active · ECR-041/042 Closed;下一刀须再评估边界
- EXP: (无)
- STATE: `docs/STATE/`(含 ECR-041
- TRACEABILITY: `docs/TRACEABILITY.md` · 门禁 `scripts/repo-governance-check.py`
+6
View File
@@ -0,0 +1,6 @@
# STATE — ECR-042
| Status | **Closed** |
| Spec | ops-feed-slot-write |
| Migration | none |
| Closed | 2026-08-13 |
+10
View File
@@ -0,0 +1,10 @@
# TEST_REPORT — ECR-042 FeedSlot Write
**Commit:** (fill)
```bash
go test ./internal/integration/ -count=1 -run TestOpsCMSFeedSlotWrite
python3 scripts/repo-governance-check.py
```
PASS · AC create/update/409/403/audit/C-end hide inactive · no new migration
+2 -1
View File
@@ -4,7 +4,7 @@
| Anchor | Value | Rule |
|--------|-------|------|
| **Next ECR** | `ECR-042` | 下一空闲裸号(候选:FeedSlot 写面,须符合 Write-Wave);或 `--print-anchors` |
| **Next ECR** | `ECR-043` | 下一空闲裸号(Write-Wave 候选须再评估);或 `--print-anchors` |
| **Max Migration** | `000051` | 新建 migration 必须读仓内实际 max 后 +1;禁止凭记忆;合入前 `repo-governance-check` PASS |
- ECR identity **全局唯一**(含已 Closed);禁止同号双义。分叉只用 `ECR-NNN-suffix` / `ECR-NNNA`
@@ -66,5 +66,6 @@
| ECR-040 | ExploreConfig · ScaleDefinition | **Closed** | Spec ops-scale-definition.md · BD-2026-040 |
| WRITE-WAVE | Ops 写面加深授权 | **Active** | `docs/WAVE0/WRITE_WAVE_AUTHORIZATION.md` · 真支付最后 · 禁 UGC/soft-delete |
| ECR-041 | OpsCMS · Banner 薄写面 | **Closed** | Spec ops-banner-write · BD-2026-041 · migration **000051** · 禁 FeedSlot |
| ECR-042 | OpsCMS · FeedSlot 薄写面 | **Closed** | Spec ops-feed-slot-write · BD-2026-042 · 无新 migration · 复用 cms.write |
> **Migration** 合并后 `000015``000023` 曾撞号,已重编号至 `000050`。以 `apps/api/migrations/` 与 `docs/MIGRATION_RENUMBER.md` 为准(文档中旧号引用可能滞后)。
+11
View File
@@ -291,6 +291,17 @@ export function createClient(opts: CreateClientOptions) {
active: boolean
}>
}>(`/api/v1/home/banners?placement=${encodeURIComponent(placement)}`),
getHomeFeedSlots: (placement = 'home') =>
call<{
items: Array<{
id: string
code: string
title: string
slot_key: string
placement: string
active: boolean
}>
}>(`/api/v1/home/feed-slots?placement=${encodeURIComponent(placement)}`),
getHomeDailyTips: () => call<HomeDailyTips>('/api/v1/home/daily-tips'),
}
}
+45
View File
@@ -841,6 +841,19 @@ paths:
description: Unauthorized
'403':
description: Forbidden
post:
tags: [admin]
summary: Create FeedSlot
description: Requires admin.cms.write · ECR-042
responses:
'200':
description: OK
'400':
description: Invalid
'403':
description: Forbidden
'409':
description: Conflict
/api/v1/admin/cms/feed-slots/{id}:
get:
@@ -856,6 +869,26 @@ paths:
description: OK
'404':
description: Not found
put:
tags: [admin]
summary: Update FeedSlot
description: Requires admin.cms.write · deactivate via active=false
parameters:
- in: path
name: id
required: true
schema: { type: string, format: uuid }
responses:
'200':
description: OK
'400':
description: Invalid
'403':
description: Forbidden
'404':
description: Not found
'409':
description: Conflict
/api/v1/admin/cms/publications:
get:
@@ -1495,6 +1528,18 @@ paths:
'200':
description: OK
/api/v1/home/feed-slots:
get:
tags: [system]
summary: Homepage active feed slots (ECR-042)
parameters:
- in: query
name: placement
schema: { type: string, default: home, enum: [home, explore, ask] }
responses:
'200':
description: OK
/api/v1/home/daily-tips:
get:
tags: [system]