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:
@@ -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) =>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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,
|
||||
}
|
||||
|
||||
@@ -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()
|
||||
|
||||
Reference in New Issue
Block a user