feat(ECR-047): FunnelDefinition 写面闭环并 Closed

growth.write POST/PUT · migration 000056 · 无新 C 端 · Loop STOP

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
jackyu66git
2026-08-13 22:14:21 +08:00
co-authored by Cursor
parent 258deb0184
commit 1db5fcc018
29 changed files with 877 additions and 12 deletions
+2 -1
View File
@@ -56,7 +56,8 @@
| [ops-image-card-deck.md](ops-image-card-deck.md) | ExploreConfig ImageCardDeck(只读) | §7 | `/admin/explore/image-card-decks*` | Ops · **ECR-037** | | [ops-image-card-deck.md](ops-image-card-deck.md) | ExploreConfig ImageCardDeck(只读) | §7 | `/admin/explore/image-card-decks*` | Ops · **ECR-037** |
| [ops-image-card-deck-write.md](ops-image-card-deck-write.md) | ImageCardDeck **写面** | §7 | admin 写 · `GET /cards/decks` | ExploreConfig · **ECR-045** | | [ops-image-card-deck-write.md](ops-image-card-deck-write.md) | ImageCardDeck **写面** | §7 | admin 写 · `GET /cards/decks` | ExploreConfig · **ECR-045** |
| [ops-report-template.md](ops-report-template.md) | GrowthInsights ReportTemplate | §7 | `/admin/growth/report-templates*` | Ops · **ECR-038** | | [ops-report-template.md](ops-report-template.md) | GrowthInsights ReportTemplate | §7 | `/admin/growth/report-templates*` | Ops · **ECR-038** |
| [ops-funnel-definition.md](ops-funnel-definition.md) | GrowthInsights FunnelDefinition | §7 | `/admin/analytics/funnel-definitions*` | Ops · **ECR-039** | | [ops-funnel-definition.md](ops-funnel-definition.md) | GrowthInsights FunnelDefinition(只读) | §7 | `/admin/analytics/funnel-definitions*` | Ops · **ECR-039** |
| [ops-funnel-definition-write.md](ops-funnel-definition-write.md) | FunnelDefinition **写面** | §7 | admin POST/PUT · growth.write | GrowthInsights · **ECR-047** |
| [ops-scale-definition.md](ops-scale-definition.md) | ExploreConfig ScaleDefinition(只读) | §7 | `/admin/explore/scales*` | Ops · **ECR-040** | | [ops-scale-definition.md](ops-scale-definition.md) | ExploreConfig ScaleDefinition(只读) | §7 | `/admin/explore/scales*` | Ops · **ECR-040** |
| [ops-scale-definition-write.md](ops-scale-definition-write.md) | ScaleDefinition **写面** | §7 | admin POST/PUT · status 仍 ECR-008 | ExploreConfig · **ECR-046** | | [ops-scale-definition-write.md](ops-scale-definition-write.md) | ScaleDefinition **写面** | §7 | admin POST/PUT · status 仍 ECR-008 | ExploreConfig · **ECR-046** |
@@ -0,0 +1,72 @@
# Feature Spec: GrowthInsights · FunnelDefinition 写面(Ops · ECR-047
> Status: `Active`**Implemented · ECR-047 Closed**
> Map: `§7` · Capability: `GrowthInsights` · BC: `Analytics_OpsB`
> Auth: `docs/WAVE0/ECR-047_WRITE_AUTHORIZATION.md`**仅 ECR-047**
> Predecessor: ECR-039 Closed(只读)· ECR-046 Closed
> 关联:[ops-funnel-definition.md](ops-funnel-definition.md)
---
## 1. 目标
运营可 **创建 / 更新 / 上下架** `FunnelDefinition`(漏斗目录);写鉴权 + 审计;**无**新 C 端路由。
**Closed 后立即 STOP**,不自动 ECR-048。
## 2. In / Out
| In | Out |
|----|-----|
| Admin POST/PUT `/admin/analytics/funnel-definitions*` | ReportTemplate 写 |
| 加法 `admin.growth.write` | SystemPrompt · Knowledge · Chunk |
| 复用表 `funnel_definitions` | soft-delete · 真支付 · UGC |
| 审计 | 题干 · Crisis/Handoff |
| | 自动 ECR-048 · 新 C 端路由 |
## 3. Domain
| 字段 | 规则 |
|------|------|
| `code` | 唯一;`^[a-z][a-z0-9_]{1,62}$``system=true` **不可改 code** |
| `title` | 必填 · ≤128 |
| `active` | `false` = 下架(唯一下架手段) |
| `system` | 种子行;禁止物理删除 |
## 4. API
| Method | Path | 权限 |
|--------|------|------|
| GET | `/admin/analytics/funnel-definitions` · `/{id}` | `admin.growth.read` |
| POST | `/admin/analytics/funnel-definitions` | `admin.growth.write` |
| PUT | `/admin/analytics/funnel-definitions/{id}` | `admin.growth.write` |
无 DELETE · 无新 C 端路径。
## 5. Permission / Migration
- Migration `000056_ops_funnel_definition_write`:授予 `super_admin``admin.growth.write`
- 编码时占号(Max=`000055``000056`
## 6. UI
admin-h5 漏斗定义页:列表 + 新建/编辑/上下架。
## 7. AC
| ID | Then |
|----|------|
| AC-F-01 | POST → list/get 可见 |
| AC-F-02 | PUT active=false → list 仍可见且 active=false |
| AC-F-03 | 重复 code → 409 |
| AC-S-01/02 | 401;仅 growth.read → POST 403 |
| AC-A-01 | 写产生审计 |
| AC-O-01 | 无 soft-delete · 无 ReportTemplate/Prompt 写路径 |
## 8. Closed 后
**立即 STOP**。ECR-048 须新 Candidate Review + Human 拍板。
## 9. Trace
ECR-047 · BD-2026-047 · CONTRACT_DIFF · ECR-047_WRITE_AUTHORIZATION
@@ -1,6 +1,7 @@
# Feature Spec: GrowthInsights · FunnelDefinitionOps · ECR-039 # Feature Spec: GrowthInsights · FunnelDefinitionOps · ECR-039
> Status: `Active`Loop continuous · **ECR-039 Closed** > Status: `Active`Loop continuous · **ECR-039 Closed**
> **写面:** [ops-funnel-definition-write.md](ops-funnel-definition-write.md)**ECR-047 Closed**
> Parent: WAVE0-FROZEN · Predecessor: ECR-038 Closed > Parent: WAVE0-FROZEN · Predecessor: ECR-038 Closed
> Capability: `GrowthInsights` · BC: `Analytics_OpsB` > Capability: `GrowthInsights` · BC: `Analytics_OpsB`
> 授权:`docs/WAVE0/LOOP_AUTHORIZATION.md` > 授权:`docs/WAVE0/LOOP_AUTHORIZATION.md`
+39 -2
View File
@@ -722,9 +722,46 @@ export const adminApi = {
reportTemplate: (id: string) => reportTemplate: (id: string) =>
request<Record<string, unknown>>('GET', `/growth/report-templates/${id}`), request<Record<string, unknown>>('GET', `/growth/report-templates/${id}`),
funnelDefinitions: () => funnelDefinitions: () =>
request<{ items: Array<Record<string, unknown>> }>('GET', '/analytics/funnel-definitions'), request<{
items: Array<{
id: string
code: string
title: string
active: boolean
system: boolean
updated_at: string
}>
}>('GET', '/analytics/funnel-definitions'),
funnelDefinition: (id: string) => funnelDefinition: (id: string) =>
request<Record<string, unknown>>('GET', `/analytics/funnel-definitions/${id}`), request<{
id: string
code: string
title: string
active: boolean
system: boolean
updated_at: string
}>('GET', `/analytics/funnel-definitions/${id}`),
createFunnelDefinition: (body: { code: string; title: string; active: boolean }) =>
request<{
id: string
code: string
title: string
active: boolean
system: boolean
updated_at: string
}>('POST', '/analytics/funnel-definitions', body),
updateFunnelDefinition: (
id: string,
body: { code: string; title: string; active: boolean },
) =>
request<{
id: string
code: string
title: string
active: boolean
system: boolean
updated_at: string
}>('PUT', `/analytics/funnel-definitions/${id}`, body),
exploreScales: () => exploreScales: () =>
request<{ request<{
items: Array<{ items: Array<{
+1
View File
@@ -39,6 +39,7 @@ async function onLogout() {
<RouterLink to="/rhythm-configs">节律配置</RouterLink> <RouterLink to="/rhythm-configs">节律配置</RouterLink>
<RouterLink to="/image-card-decks">意象牌组</RouterLink> <RouterLink to="/image-card-decks">意象牌组</RouterLink>
<RouterLink to="/scale-definitions">量表元数据</RouterLink> <RouterLink to="/scale-definitions">量表元数据</RouterLink>
<RouterLink to="/funnel-definitions">漏斗定义</RouterLink>
<RouterLink to="/catalogs">目录仓</RouterLink> <RouterLink to="/catalogs">目录仓</RouterLink>
<RouterLink to="/orders">订单</RouterLink> <RouterLink to="/orders">订单</RouterLink>
<RouterLink v-if="auth.can('admin.membership.plans.read')" to="/pricing">定价</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.funnelDefinitions>>['items'][number]
const auth = useAuthStore()
const canWrite = () => auth.can('admin.growth.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.funnelDefinitions()
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.funnelDefinition(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.createFunnelDefinition(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.updateFunnelDefinition(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">FunnelDefinition 写面 · 下架仅 active=false · ECR-047</p>
<p v-if="!canWrite()" class="err">需要 admin.growth.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>
+6
View File
@@ -48,6 +48,12 @@ const router = createRouter({
component: () => import('@/pages/ScaleDefinitionPage.vue'), component: () => import('@/pages/ScaleDefinitionPage.vue'),
meta: { permission: 'admin.explore.read' }, meta: { permission: 'admin.explore.read' },
}, },
{
path: 'funnel-definitions',
name: 'funnel-definitions',
component: () => import('@/pages/FunnelDefinitionPage.vue'),
meta: { permission: 'admin.growth.read' },
},
{ path: 'catalogs', name: 'catalogs', component: () => import('@/pages/CatalogHubPage.vue') }, { path: 'catalogs', name: 'catalogs', component: () => import('@/pages/CatalogHubPage.vue') },
{ path: 'push', name: 'push', component: () => import('@/pages/PushJobsPage.vue') }, { path: 'push', name: 'push', component: () => import('@/pages/PushJobsPage.vue') },
{ path: 'admins', name: 'admins', component: () => import('@/pages/AdminsPage.vue'), meta: { superOnly: true } }, { path: 'admins', name: 'admins', component: () => import('@/pages/AdminsPage.vue'), meta: { superOnly: true } },
@@ -16,6 +16,8 @@ func (h *AdminHandler) registerFunnelDefinitions(authed *gin.RouterGroup) {
g := authed.Group("/analytics") g := authed.Group("/analytics")
g.GET("/funnel-definitions", middleware.RequireAdminPermission(h.Svc, admin.PermGrowthRead), h.ListFunnelDefinitions) g.GET("/funnel-definitions", middleware.RequireAdminPermission(h.Svc, admin.PermGrowthRead), h.ListFunnelDefinitions)
g.GET("/funnel-definitions/:id", middleware.RequireAdminPermission(h.Svc, admin.PermGrowthRead), h.GetFunnelDefinition) g.GET("/funnel-definitions/:id", middleware.RequireAdminPermission(h.Svc, admin.PermGrowthRead), h.GetFunnelDefinition)
g.POST("/funnel-definitions", middleware.RequireAdminPermission(h.Svc, admin.PermGrowthWrite), h.CreateFunnelDefinition)
g.PUT("/funnel-definitions/:id", middleware.RequireAdminPermission(h.Svc, admin.PermGrowthWrite), h.UpdateFunnelDefinition)
} }
func (h *AdminHandler) ListFunnelDefinitions(c *gin.Context) { func (h *AdminHandler) ListFunnelDefinitions(c *gin.Context) {
@@ -44,3 +46,66 @@ func (h *AdminHandler) GetFunnelDefinition(c *gin.Context) {
} }
response.OK(c, row) response.OK(c, row)
} }
func (h *AdminHandler) CreateFunnelDefinition(c *gin.Context) {
adminID, ok := middleware.AdminIDFromContext(c)
if !ok {
response.Fail(c, http.StatusUnauthorized, 40101, "admin auth required")
return
}
var body admin.FunnelDefinitionWriteBody
if err := c.ShouldBindJSON(&body); err != nil {
response.Fail(c, http.StatusBadRequest, 40054, "invalid body")
return
}
row, err := h.Svc.CreateFunnelDefinition(c.Request.Context(), adminID, body)
if errors.Is(err, admin.ErrInvalidFunnelDefinition) {
response.Fail(c, http.StatusBadRequest, 40055, "invalid funnel definition")
return
}
if errors.Is(err, admin.ErrFunnelDefinitionConflict) {
response.Fail(c, http.StatusConflict, 40912, "funnel definition code conflict")
return
}
if err != nil {
response.Fail(c, http.StatusInternalServerError, 50052, "create funnel definition failed")
return
}
response.OK(c, row)
}
func (h *AdminHandler) UpdateFunnelDefinition(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.FunnelDefinitionWriteBody
if err := c.ShouldBindJSON(&body); err != nil {
response.Fail(c, http.StatusBadRequest, 40054, "invalid body")
return
}
row, err := h.Svc.UpdateFunnelDefinition(c.Request.Context(), adminID, id, body)
if errors.Is(err, admin.ErrFunnelDefinitionNotFound) {
response.Fail(c, http.StatusNotFound, 40420, "funnel-definition not found")
return
}
if errors.Is(err, admin.ErrInvalidFunnelDefinition) {
response.Fail(c, http.StatusBadRequest, 40055, "invalid funnel definition")
return
}
if errors.Is(err, admin.ErrFunnelDefinitionConflict) {
response.Fail(c, http.StatusConflict, 40912, "funnel definition code conflict")
return
}
if err != nil {
response.Fail(c, http.StatusInternalServerError, 50053, "update funnel definition failed")
return
}
response.OK(c, row)
}
@@ -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 TestGrowthFunnelDefinitionWrite(t *testing.T) {
r, pool := setupAPIPool(t)
ctx := context.Background()
tok := adminLogin(t, r, "admin", "change-me")
code := fmt.Sprintf("fn_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/analytics/funnel-definitions", 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"`
Active bool `json:"active"`
}
_ = json.Unmarshal(env.Data, &created)
if created.ID == "" || created.Code != code || !created.Active {
t.Fatalf("bad create %#v", created)
}
t.Cleanup(func() {
_, _ = pool.Exec(ctx, `DELETE FROM funnel_definitions WHERE id=$1`, created.ID)
})
_, httpCode = doAdminJSON(t, r, http.MethodPost, "/api/v1/admin/analytics/funnel-definitions", body, tok)
if httpCode != http.StatusConflict {
t.Fatalf("dup expected 409 got %d", httpCode)
}
env, httpCode = doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/analytics/funnel-definitions", nil, tok)
if httpCode != 200 {
t.Fatalf("list %d", httpCode)
}
var list struct {
Items []struct {
Code string `json:"code"`
Active bool `json:"active"`
} `json:"items"`
}
_ = json.Unmarshal(env.Data, &list)
found := false
for _, it := range list.Items {
if it.Code == code && it.Active {
found = true
break
}
}
if !found {
t.Fatalf("missing active in list %#v", list.Items)
}
body["active"] = false
body["title"] = "测试漏斗下架"
env, httpCode = doAdminJSON(t, r, http.MethodPut, "/api/v1/admin/analytics/funnel-definitions/"+created.ID, body, tok)
if httpCode != 200 {
t.Fatalf("update %d", httpCode)
}
var updated struct {
Active bool `json:"active"`
Title string `json:"title"`
}
_ = json.Unmarshal(env.Data, &updated)
if updated.Active || updated.Title != "测试漏斗下架" {
t.Fatalf("bad update %#v", updated)
}
var n int
_ = pool.QueryRow(ctx, `
SELECT COUNT(*) FROM admin_audit_logs
WHERE action IN ('growth.funnel_definition.create','growth.funnel_definition.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, "fn_ro_"+limitedRoleID.String()[:8])
_, _ = pool.Exec(ctx, `INSERT INTO admin_role_permissions(role_id, code) VALUES ($1,'admin.growth.read')`, limitedRoleID)
hash, _ := bcrypt.GenerateFromPassword([]byte("ro-pass"), bcrypt.DefaultCost)
roUser := fmt.Sprintf("fnro_%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/analytics/funnel-definitions", 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,116 @@
package repository
import (
"context"
"encoding/json"
"errors"
"strings"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
)
// FunnelDefinitionWriteInput is create/update payload.
type FunnelDefinitionWriteInput struct {
Code string
Title string
Active bool
}
// CreateFunnelDefinitionWithAudit inserts and audits.
func (r *AdminRepo) CreateFunnelDefinitionWithAudit(
ctx context.Context, adminID uuid.UUID, in FunnelDefinitionWriteInput, meta json.RawMessage,
) (*FunnelDefinitionRow, error) {
tx, err := r.Pool.Begin(ctx)
if err != nil {
return nil, err
}
defer tx.Rollback(ctx)
var row FunnelDefinitionRow
err = tx.QueryRow(ctx, `
INSERT INTO funnel_definitions(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, mapFunnelDefinitionWriteErr(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,'growth.funnel_definition.create','funnel_definition',$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
}
// UpdateFunnelDefinitionWithAudit updates and audits.
func (r *AdminRepo) UpdateFunnelDefinitionWithAudit(
ctx context.Context, adminID, id uuid.UUID, in FunnelDefinitionWriteInput, meta json.RawMessage,
) (*FunnelDefinitionRow, 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 funnel_definitions 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 FunnelDefinitionRow
err = tx.QueryRow(ctx, `
UPDATE funnel_definitions
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, mapFunnelDefinitionWriteErr(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,'growth.funnel_definition.update','funnel_definition',$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 mapFunnelDefinitionWriteErr(err error) error {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
return errString("funnel definition code conflict")
}
return err
}
// FunnelDefinitionCodeConflict reports unique violation.
func FunnelDefinitionCodeConflict(err error) bool {
return err != nil && strings.Contains(err.Error(), "funnel definition code conflict")
}
@@ -0,0 +1,71 @@
package admin
import (
"context"
"encoding/json"
"errors"
"regexp"
"strings"
"unicode/utf8"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/yuxingu/digital-psychology/apps/api/internal/repository"
)
var (
ErrInvalidFunnelDefinition = errors.New("invalid funnel definition")
ErrFunnelDefinitionConflict = errors.New("funnel definition code conflict")
funnelDefinitionCodeRe = regexp.MustCompile(`^[a-z][a-z0-9_]{1,62}$`)
)
// FunnelDefinitionWriteBody is JSON for create/update.
type FunnelDefinitionWriteBody struct {
Code string `json:"code"`
Title string `json:"title"`
Active bool `json:"active"`
}
// CreateFunnelDefinition validates, inserts, audits.
func (s *Service) CreateFunnelDefinition(ctx context.Context, adminID uuid.UUID, body FunnelDefinitionWriteBody) (*repository.FunnelDefinitionRow, error) {
in, err := normalizeFunnelDefinitionWrite(body)
if err != nil {
return nil, err
}
meta, _ := json.Marshal(map[string]any{"code": in.Code, "active": in.Active})
row, err := s.Repo.CreateFunnelDefinitionWithAudit(ctx, adminID, in, meta)
if repository.FunnelDefinitionCodeConflict(err) {
return nil, ErrFunnelDefinitionConflict
}
return row, err
}
// UpdateFunnelDefinition validates, updates, audits.
func (s *Service) UpdateFunnelDefinition(ctx context.Context, adminID, id uuid.UUID, body FunnelDefinitionWriteBody) (*repository.FunnelDefinitionRow, error) {
in, err := normalizeFunnelDefinitionWrite(body)
if err != nil {
return nil, err
}
meta, _ := json.Marshal(map[string]any{"code": in.Code, "active": in.Active})
row, err := s.Repo.UpdateFunnelDefinitionWithAudit(ctx, adminID, id, in, meta)
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrFunnelDefinitionNotFound
}
if repository.FunnelDefinitionCodeConflict(err) {
return nil, ErrFunnelDefinitionConflict
}
return row, err
}
func normalizeFunnelDefinitionWrite(body FunnelDefinitionWriteBody) (repository.FunnelDefinitionWriteInput, error) {
code := strings.TrimSpace(body.Code)
title := strings.TrimSpace(body.Title)
if !funnelDefinitionCodeRe.MatchString(code) {
return repository.FunnelDefinitionWriteInput{}, ErrInvalidFunnelDefinition
}
if title == "" || utf8.RuneCountInString(title) > 128 {
return repository.FunnelDefinitionWriteInput{}, ErrInvalidFunnelDefinition
}
return repository.FunnelDefinitionWriteInput{Code: code, Title: title, Active: body.Active}, nil
}
+2 -1
View File
@@ -36,6 +36,7 @@ const (
PermExploreRead = "admin.explore.read" PermExploreRead = "admin.explore.read"
PermExploreWrite = "admin.explore.write" PermExploreWrite = "admin.explore.write"
PermGrowthRead = "admin.growth.read" PermGrowthRead = "admin.growth.read"
PermGrowthWrite = "admin.growth.write"
) )
var knownPermissions = map[string]struct{}{ var knownPermissions = map[string]struct{}{
@@ -45,7 +46,7 @@ var knownPermissions = map[string]struct{}{
PermUsersStatusWrite: {}, PermMembershipPlansRead: {}, PermMembershipPlansWrite: {}, PermUsersStatusWrite: {}, PermMembershipPlansRead: {}, PermMembershipPlansWrite: {},
PermMembershipCodesRead: {}, PermMembershipCodesWrite: {}, PermMembershipCodesRead: {}, PermMembershipCodesWrite: {},
PermAskRead: {}, PermAskTranscriptRead: {}, PermAskFeedbackWrite: {}, PermContentSafetyRead: {}, PermAskRead: {}, PermAskTranscriptRead: {}, PermAskFeedbackWrite: {}, PermContentSafetyRead: {},
PermAIConfigRead: {}, PermCrisisRead: {}, PermCMSRead: {}, PermCMSWrite: {}, PermGrowthRead: {}, PermExploreRead: {}, PermExploreWrite: {}, PermPrivacyRead: {}, PermAIConfigRead: {}, PermCrisisRead: {}, PermCMSRead: {}, PermCMSWrite: {}, PermGrowthRead: {}, PermGrowthWrite: {}, PermExploreRead: {}, PermExploreWrite: {}, PermPrivacyRead: {},
} }
var ( var (
@@ -0,0 +1,5 @@
-- ECR-047 rollback
DELETE FROM admin_role_permissions
WHERE code = 'admin.growth.write'
AND role_id IN (SELECT id FROM admin_roles WHERE name = 'super_admin');
@@ -0,0 +1,7 @@
-- ECR-047 GrowthInsights FunnelDefinition write (additive admin.growth.write)
INSERT INTO admin_role_permissions(role_id, code)
SELECT r.id, 'admin.growth.write'
FROM admin_roles r
WHERE r.name = 'super_admin'
ON CONFLICT DO NOTHING;
@@ -0,0 +1,23 @@
# Backend Design: ECR-047 FunnelDefinition Write
| Field | Value |
|-------|-------|
| ID | BD-2026-047 |
| Status | **Closed** |
| Coding | **Closed** |
| Migration | `000056_ops_funnel_definition_write` |
## Boundary
```text
POST/PUT /api/v1/admin/analytics/funnel-definitions*
Permission: admin.growth.write
Fields: code, title, active
system=true: code immutable
Audit: growth.funnel_definition.create|update
No C-end route · no DELETE
```
## Out
ReportTemplate · Prompt · soft-delete · auto ECR-048
+3
View File
@@ -2,6 +2,9 @@
## 2026-08-13 ## 2026-08-13
- **ECR-047 Closed** FunnelDefinition 薄写(`admin.growth.write` POST/PUT · migration `000056` · 无新 C 端)· **Loop STOP** · 禁自动 ECR-048 · 无 ReportTemplate
- **ECR-047 Candidate Review Approved** 首刀 = **FunnelDefinition** 薄写(code/title/active`admin.growth.write`)· **不**做 ReportTemplate · Spec/Loop/Coding **未开** · Auth 草案 PENDING
- **ECR-047 Candidate Review DRAFT** ExploreConfig 写面耗尽后开刀;**推荐 ReportTemplate** · 备选 FunnelDefinition · 禁 Prompt/Knowledge/Chunk · Spec/Loop/Coding **未开**
- **ECR-046 Closed** ScaleDefinition 元数据薄写(`explore.write` POST/PUT · create→draft · status 仍 ECR-008 · migration `000055`)· **Loop STOP** · 禁自动 ECR-047 · 无题干编辑 - **ECR-046 Closed** ScaleDefinition 元数据薄写(`explore.write` POST/PUT · create→draft · status 仍 ECR-008 · migration `000055`)· **Loop STOP** · 禁自动 ECR-047 · 无题干编辑
- **ECR-046 Candidate Review Approved** 首刀 = **ScaleDefinition 元数据薄写**slug/title/descriptioncreate→draft)· **status 仍独占 ECR-008** · Spec/Loop/Coding **未开** · Auth 草案 PENDING - **ECR-046 Candidate Review Approved** 首刀 = **ScaleDefinition 元数据薄写**slug/title/descriptioncreate→draft)· **status 仍独占 ECR-008** · Spec/Loop/Coding **未开** · Auth 草案 PENDING
- **ECR-046 Candidate Review DRAFT** 推荐 ExploreConfig 写面波次 **STOP**;慎选 ScaleDefinition(须相对 ECR-008 增量);禁 Prompt/Knowledge/Chunk · 待 Human 拍板 - **ECR-046 Candidate Review DRAFT** 推荐 ExploreConfig 写面波次 **STOP**;慎选 ScaleDefinition(须相对 ECR-008 增量);禁 Prompt/Knowledge/Chunk · 待 Human 拍板
+3
View File
@@ -0,0 +1,3 @@
# CODE_REVIEW — ECR-047
**Verdict:** Approve · FunnelDefinition 薄写 only · 无 ReportTemplate/Prompt/soft-delete · Closed 后 STOP · ECR-008 Live Promote 仍 BLOCKED
+18
View File
@@ -0,0 +1,18 @@
ecr: ECR-047
capability: GrowthInsights
change:
type: additive
breaking_change: false
migration_required: true
apis:
- method: POST
path: /api/v1/admin/analytics/funnel-definitions
change: added
- method: PUT
path: /api/v1/admin/analytics/funnel-definitions/{id}
change: added
perms:
- code: admin.growth.write
change: added
migration: 000056_ops_funnel_definition_write
notes: no C-end route; ReportTemplate out of scope
@@ -0,0 +1,20 @@
# ECR-047
**Title:** GrowthInsights · FunnelDefinition 薄写面
**Status:** **Closed**2026-08-13
**Auth:** `ECR-047_WRITE_AUTHORIZATION.md` · Closed 后 STOP
## Change
1. Spec `ops-funnel-definition-write`
2. POST/PUT `/admin/analytics/funnel-definitions*` + `admin.growth.write` + 审计
3. 无新 C 端路由
4. Migration `000056` · OpenAPI · admin-h5
## Forbidden
ReportTemplate · Prompt 族 · soft-delete · 支付/UGC · 自动 ECR-048
## Acceptance
TEST_REPORT/ECR-047 · CODE_REVIEW Approve · Done · Closed.
@@ -0,0 +1,3 @@
# HANDOFF — Architect → Engineer · ECR-047
Auth Approved · Spec Ready · BD Approved · FunnelDefinition ONLY · migration 000056 · Closed → STOP.
@@ -0,0 +1,4 @@
# HANDOFF — Engineer → Reviewer · ECR-047
TestGrowthFunnelDefinitionWrite PASS · governance max 000056 · Ready Closed.
无 ReportTemplate/Prompt · STOP · 禁自动 ECR-048.
@@ -0,0 +1,3 @@
# PRODUCT_SPEC — ECR-047
对齐 `ops-funnel-definition-write.md` · **Closed**.
+6 -5
View File
@@ -53,20 +53,21 @@
- **本仓:** `ess_intake: strict` · Retro FAIL · 单 ECR Context - **本仓:** `ess_intake: strict` · Retro FAIL · 单 ECR Context
- **Ops foundation** `docs/WAVE0/` · `.ai/domain/boundary-rules.md` · `glossary.yaml` · Loop: `docs/WAVE0/LOOP_AUTHORIZATION.md` - **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 - ECR: main 线 ECR-006016 ClosedOps 扩展 ECR-013A/B · 017040;分叉已固定为 `ECR-012-star` / `014-plan` / `015-code` / `016-insight`(见 TRACEABILITY
- **Next ECR / Max Migration** **Next=`ECR-047`(禁自动开)** · **Max=`000055`** - **Next ECR / Max Migration** **Next=`ECR-048`(禁自动开)** · **Max=`000056`**
- **Write-Wave CMS** 041042 Closed · STOP - **Write-Wave CMS** 041042 Closed · STOP
- **ExploreConfig** ECR-043…046 Closed · **Loop STOP** · Prompt/Knowledge/Chunk STOP - **ExploreConfig** ECR-043…046 Closed · 同构写面 **耗尽 · STOP** · Prompt/Knowledge/Chunk STOP
- **GrowthInsights** ECR-047 FunnelDefinition Closed · **Loop STOP** · ReportTemplate 写面未开
- **Release** ECR-008 Live Promote **BLOCKED**(独立门禁 · 勿与 Write-Wave 混谈) - **Release** ECR-008 Live Promote **BLOCKED**(独立门禁 · 勿与 Write-Wave 混谈)
- EXP: (无) - EXP: (无)
- STATE: `docs/STATE/`(含 ECR-041…046 - STATE: `docs/STATE/`(含 ECR-041…047
- TRACEABILITY: `docs/TRACEABILITY.md` · 门禁 `scripts/repo-governance-check.py` - TRACEABILITY: `docs/TRACEABILITY.md` · 门禁 `scripts/repo-governance-check.py`
- ADR: `.ai/adr/0007-ess-ai-dual-track.md` - ADR: `.ai/adr/0007-ess-ai-dual-track.md`
- Product status: `.ai/product/p1-status.md`**P1 Complete**)· `.ai/product/p2-status.md`**P2 Complete** - Product status: `.ai/product/p1-status.md`**P1 Complete**)· `.ai/product/p2-status.md`**P2 Complete**
- Active Spec: `account-auth` · `explore-test` · `home` · `star-profile` · `life-rhythm` · `input-compliance` · `ops-system` · `profile` · `ops-banner-write` · `ops-star-config-write` · `ops-rhythm-config-write` · `ops-image-card-deck-write` · `ops-scale-definition-write` - Active Spec: `account-auth` · `explore-test` · `home` · `star-profile` · `life-rhythm` · `input-compliance` · `ops-system` · `profile` · `ops-banner-write` · `ops-star-config-write` · `ops-rhythm-config-write` · `ops-image-card-deck-write` · `ops-scale-definition-write` · `ops-funnel-definition-write`
## WIP(尚未单独 ECR ## WIP(尚未单独 ECR
- (无 · ECR-046 Closed · Loop STOP - (无 · ECR-047 Closed · Loop STOP
- BD-2026-044 状态补丁:工作区可暂留 · **不**自动提交 - BD-2026-044 状态补丁:工作区可暂留 · **不**自动提交
## Pointers ## Pointers
+7
View File
@@ -0,0 +1,7 @@
# STATE — ECR-047
| Status | **Closed** |
| Spec | ops-funnel-definition-write |
| Migration | 000056_ops_funnel_definition_write |
| Closed | 2026-08-13 |
| Next | STOP · ECR-048 禁自动开 |
+11
View File
@@ -0,0 +1,11 @@
# TEST_REPORT — ECR-047 FunnelDefinition Write
**Commit:** (pending Close)
```bash
go test ./internal/integration/ -count=1 -run TestGrowthFunnelDefinitionWrite
python3 scripts/repo-governance-check.py
```
PASS · create · 409 · PUT 下架 · audit · 403
REPO GOVERNANCE: PASS · max 000056 · Next ECR-048(禁自动开)
+3 -2
View File
@@ -4,8 +4,8 @@
| Anchor | Value | Rule | | Anchor | Value | Rule |
|--------|-------|------| |--------|-------|------|
| **Next ECR** | `ECR-047` | **冻结:** 须重新 Candidate Review + Human 单独拍板;**禁止自动开刀** | | **Next ECR** | `ECR-048` | **冻结:** 须重新 Candidate Review + Human 单独拍板;**禁止自动开刀** |
| **Max Migration** | `000055` | 禁止凭记忆 | | **Max Migration** | `000056` | 禁止凭记忆 |
- ECR identity **全局唯一**(含已 Closed);禁止同号双义。分叉只用 `ECR-NNN-suffix` / `ECR-NNNA` - ECR identity **全局唯一**(含已 Closed);禁止同号双义。分叉只用 `ECR-NNN-suffix` / `ECR-NNNA`
- Migration **6 位版本号唯一**。撞号修复见 `docs/MIGRATION_RENUMBER.md` - Migration **6 位版本号唯一**。撞号修复见 `docs/MIGRATION_RENUMBER.md`
@@ -72,5 +72,6 @@
| ECR-044 | ExploreConfig · RhythmConfig 薄写面 | **Closed** | Spec ops-rhythm-config-write · BD-2026-044 · migration **000053** · Closed 后 STOP · 禁自动 ECR-045 | | ECR-044 | ExploreConfig · RhythmConfig 薄写面 | **Closed** | Spec ops-rhythm-config-write · BD-2026-044 · migration **000053** · Closed 后 STOP · 禁自动 ECR-045 |
| ECR-045 | ExploreConfig · ImageCardDeck 薄写面 | **Closed** | Spec ops-image-card-deck-write · BD-2026-045 · migration **000054** · Closed 后 STOP · 禁自动 ECR-046 · 无牌面编辑 | | ECR-045 | ExploreConfig · ImageCardDeck 薄写面 | **Closed** | Spec ops-image-card-deck-write · BD-2026-045 · migration **000054** · Closed 后 STOP · 禁自动 ECR-046 · 无牌面编辑 |
| ECR-046 | ExploreConfig · ScaleDefinition 元数据薄写 | **Closed** | Spec ops-scale-definition-write · BD-2026-046 · migration **000055** · status 仍 ECR-008 · Closed 后 STOP · 禁自动 ECR-047 | | ECR-046 | ExploreConfig · ScaleDefinition 元数据薄写 | **Closed** | Spec ops-scale-definition-write · BD-2026-046 · migration **000055** · status 仍 ECR-008 · Closed 后 STOP · 禁自动 ECR-047 |
| ECR-047 | GrowthInsights · FunnelDefinition 薄写面 | **Closed** | Spec ops-funnel-definition-write · BD-2026-047 · migration **000056** · Closed 后 STOP · 禁自动 ECR-048 |
> **Migration** 合并后 `000015``000023` 曾撞号,已重编号至 `000050`。以 `apps/api/migrations/` 与 `docs/MIGRATION_RENUMBER.md` 为准(文档中旧号引用可能滞后)。 > **Migration** 合并后 `000015``000023` 曾撞号,已重编号至 `000050`。以 `apps/api/migrations/` 与 `docs/MIGRATION_RENUMBER.md` 为准(文档中旧号引用可能滞后)。
+49
View File
@@ -0,0 +1,49 @@
# ECR-047 Candidate Review — GrowthInsights · FunnelDefinition
> **RESOLVED 2026-08-13Human: Candidate Review → Auth/Spec/开码 → Closed):**
> 首刀 = **FunnelDefinition 薄写** · **Closed** · Loop **STOP** · 禁自动 ECR-048
**Date:** 2026-08-13
**Mode:** Candidate Review **Approved** · Spec **Closed** · Coding **Closed**
**Anchors:** Next=`ECR-048`(禁自动开)· Max Migration=`000056`
## 锁定现状
| 项 | 状态 |
|----|------|
| ECR-041042 | CMS 写面 **Closed** · STOP |
| ECR-043046 | ExploreConfig 同构写面 **Closed** · STOP |
| ECR-038 | ReportTemplate **只读** · **本刀不做** |
| ECR-039 | FunnelDefinition **只读** · 本刀写面增量 |
| ECR-008 Live Promote | **BLOCKED** |
| Continuous Loop | **STOP**046 耗尽 · 不得继承) |
| 硬 STOP | 支付 / UGC / soft-delete / Crisis·Handoff / Prompt / Knowledge / Chunk |
## 决议
**ECR-047 = GrowthInsights · FunnelDefinition 薄写面**
拟议(Spec 细化):
- 复用表 `funnel_definitions`
- 加法权限 `admin.growth.write`(授予 super_admin
- Admin `POST/PUT /admin/analytics/funnel-definitions*`
- 字段仅 `code` · `title` · `active`(与只读表对齐)
- `system=true` 种子行:允许改 title/active**禁止**改 `code` / 物理删(Spec 锁死)
- 审计 `growth.funnel_definition.create|update`
- **无**新 C 端路由
- Migration:编码时占 **000056**
- Continuous Loop**仅**单独 Auth 且 **仅限 ECR-047**Closed → STOP · **禁自动 ECR-048**
## 硬 STOP
ReportTemplate 同 ECR · Prompt / Knowledge / Chunk · 支付 · UGC · soft-delete · Crisis/Handoff · 题干 · ECR-008 Live Promote 解禁 · 自动下一刀
## 下一步(仍不写码)
1. ~~Candidate Review approve · FunnelDefinition~~ **Done**
2. Human:批准 **ECR-047 专用** Write Authorization
3. Spec `ops-funnel-definition-write` · ECR · BD
4. 开码口令后才改 `apps/`
**本回合交付 = Candidate Review RESOLVED;无 Spec · 无 Auth Loop · 无 `apps/`。**
+27
View File
@@ -0,0 +1,27 @@
# GrowthInsights Write Authorization — ECR-047 only
| Field | Value |
|-------|-------|
| Date | 2026-08-13 |
| Authorizer | Human |
| Status | **Approved · ECR-047 Closed · Loop STOP** |
| Scope | **FunnelDefinition 薄写面 ONLY** |
| Continuous Loop | **Finished · STOP** |
| After Closed | **STOP** · 禁止自动 ECR-048 |
## Human 拍板(2026-08-13
1. Candidate Review = FunnelDefinition
2. Write Auth → Spec → 开码
3. 加法 `admin.growth.write` · 字段 code/title/active · 无新 C 端路由
4. Continuous Loop **仅限 ECR-047**
## Hard STOP
ReportTemplate 同刀 · Prompt / Knowledge / Chunk · 支付 · UGC · soft-delete · Crisis/Handoff · 题干 · Closed 后自动下一刀 · ECR-008 Live Promote 解禁
## Refs
Candidate Review: `ECR-047-CANDIDATE_REVIEW.md`
Spec: `.ai/product/feature-spec/ops-funnel-definition-write.md`
ECR: `docs/ECR/ECR-047-funnel-definition-write.md`
+35
View File
@@ -1436,6 +1436,21 @@ paths:
description: Unauthorized description: Unauthorized
'403': '403':
description: Forbidden description: Forbidden
post:
tags: [admin]
summary: Create FunnelDefinition
description: Requires admin.growth.write · ECR-047 · code/title/active only
responses:
'200':
description: OK
'400':
description: Invalid
'401':
description: Unauthorized
'403':
description: Forbidden
'409':
description: Code conflict
/api/v1/admin/analytics/funnel-definitions/{id}: /api/v1/admin/analytics/funnel-definitions/{id}:
get: get:
@@ -1451,6 +1466,26 @@ paths:
description: OK description: OK
'404': '404':
description: Not found description: Not found
put:
tags: [admin]
summary: Update FunnelDefinition
description: Requires admin.growth.write · deactivate via active=false · ECR-047
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: Code conflict
/api/v1/admin/crisis/policies: /api/v1/admin/crisis/policies:
get: get: