feat(ECR-038): GrowthInsights ReportTemplate 只读并 Closed

ReportTemplate catalog (000039) · Loop continuous.
This commit is contained in:
jackyu66git
2026-08-08 03:16:57 +08:00
parent b34b4f281f
commit 5de9a7bbe5
26 changed files with 466 additions and 2 deletions
+1
View File
@@ -47,6 +47,7 @@
| [ops-star-config.md](ops-star-config.md) | ExploreConfig StarConfig | §7 | `GET /admin/explore/star-configs*` | Ops-D · **ECR-035 Closed** | | [ops-star-config.md](ops-star-config.md) | ExploreConfig StarConfig | §7 | `GET /admin/explore/star-configs*` | Ops-D · **ECR-035 Closed** |
| [ops-rhythm-config.md](ops-rhythm-config.md) | ExploreConfig RhythmConfig | §7 | `GET /admin/explore/rhythm-configs*` | Ops-D · **ECR-036 Closed** | | [ops-rhythm-config.md](ops-rhythm-config.md) | ExploreConfig RhythmConfig | §7 | `GET /admin/explore/rhythm-configs*` | Ops-D · **ECR-036 Closed** |
| [ops-image-card-deck.md](ops-image-card-deck.md) | ExploreConfig ImageCardDeck | §7 | `GET /admin/explore/image-card-decks*` | Ops-D · **ECR-037 Closed** | | [ops-image-card-deck.md](ops-image-card-deck.md) | ExploreConfig ImageCardDeck | §7 | `GET /admin/explore/image-card-decks*` | Ops-D · **ECR-037 Closed** |
| [ops-report-template.md](ops-report-template.md) | GrowthInsights ReportTemplate | §7 | `GET /admin/growth/report-templates*` | Ops-D · **ECR-038 Closed** |
新功能:复制 `_TEMPLATE.md` → 填满 → 在本表登记 → 再编码。 新功能:复制 `_TEMPLATE.md` → 填满 → 在本表登记 → 再编码。
@@ -0,0 +1,41 @@
# Feature Spec: GrowthInsights · ReportTemplateOps · ECR-038
> Status: `Active`Loop continuous · **ECR-038 Closed**
> Parent: WAVE0-FROZEN · Predecessor: ECR-037 Closed
> Capability: `GrowthInsights` · BC: `Explore_Reports`
> 授权:`docs/WAVE0/LOOP_AUTHORIZATION.md`
## Non-goals
模板写发布 · 广告投放 · UGC · 真支付
## L2 Domain
| 概念 | 语义 |
|------|------|
| `ReportTemplate` | 本切片只读目录;code 唯一(若适用) |
## L3 API
| Method | Path | 权限 | 语义 |
|--------|------|------|------|
| GET | `/admin/growth/report-templates` | `admin.growth.read` | 只读 |
| GET | `/admin/growth/report-templates/{id}` | `admin.growth.read` | 只读 |
## Migration
`000039`:表 + 种子(若有) + 授予 admin.growth.read
## L4 AC
| ID | Then |
|----|------|
| AC-F-01 | list 含种子或空列表合法 |
| AC-F-02 | 已知 id get 200 |
| AC-F-03 | 未知 id → 404 |
| AC-S-01 | 无 Admin → 401 |
| AC-S-02 | 无权限 → 403 |
| AC-P-01 | list < 500ms |
| AC-O-01 | N/A 只读 |
contract_diff: `docs/CONTRACT_DIFF/ECR-038.yaml`
+4
View File
@@ -481,6 +481,10 @@ export const adminApi = {
request<{ items: Array<Record<string, unknown>> }>('GET', '/explore/image-card-decks'), request<{ items: Array<Record<string, unknown>> }>('GET', '/explore/image-card-decks'),
imageCardDeck: (id: string) => imageCardDeck: (id: string) =>
request<Record<string, unknown>>('GET', `/explore/image-card-decks/${id}`), request<Record<string, unknown>>('GET', `/explore/image-card-decks/${id}`),
reportTemplates: () =>
request<{ items: Array<Record<string, unknown>> }>('GET', '/growth/report-templates'),
reportTemplate: (id: string) =>
request<Record<string, unknown>>('GET', `/growth/report-templates/${id}`),
orders: () => orders: () =>
request<{ request<{
items: Array<{ items: Array<{
+1
View File
@@ -66,6 +66,7 @@ func (h *AdminHandler) Register(api *gin.RouterGroup) {
h.registerStarConfigs(authed) h.registerStarConfigs(authed)
h.registerRhythmConfigs(authed) h.registerRhythmConfigs(authed)
h.registerImageCardDecks(authed) h.registerImageCardDecks(authed)
h.registerReportTemplates(authed)
} }
func (h *AdminHandler) Login(c *gin.Context) { func (h *AdminHandler) Login(c *gin.Context) {
@@ -0,0 +1,46 @@
package handler
import (
"errors"
"net/http"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/yuxingu/digital-psychology/apps/api/internal/middleware"
"github.com/yuxingu/digital-psychology/apps/api/internal/service/admin"
"github.com/yuxingu/digital-psychology/apps/api/pkg/response"
)
func (h *AdminHandler) registerReportTemplates(authed *gin.RouterGroup) {
g := authed.Group("/growth")
g.GET("/report-templates", middleware.RequireAdminPermission(h.Svc, admin.PermGrowthRead), h.ListReportTemplates)
g.GET("/report-templates/:id", middleware.RequireAdminPermission(h.Svc, admin.PermGrowthRead), h.GetReportTemplate)
}
func (h *AdminHandler) ListReportTemplates(c *gin.Context) {
items, err := h.Svc.ListReportTemplates(c.Request.Context())
if err != nil {
response.Fail(c, http.StatusInternalServerError, 50050, "list report-template failed")
return
}
response.OK(c, gin.H{"items": items})
}
func (h *AdminHandler) GetReportTemplate(c *gin.Context) {
id, err := uuid.Parse(c.Param("id"))
if err != nil {
response.Fail(c, http.StatusBadRequest, 40002, "invalid id")
return
}
row, err := h.Svc.GetReportTemplate(c.Request.Context(), id)
if errors.Is(err, admin.ErrReportTemplateNotFound) {
response.Fail(c, http.StatusNotFound, 40420, "report-template not found")
return
}
if err != nil {
response.Fail(c, http.StatusInternalServerError, 50051, "get report-template failed")
return
}
response.OK(c, row)
}
@@ -0,0 +1,88 @@
package integration_test
import (
"context"
"encoding/json"
"fmt"
"net/http"
"testing"
"time"
"github.com/google/uuid"
"golang.org/x/crypto/bcrypt"
)
func TestGrowthReportTemplates(t *testing.T) {
r, pool := setupAPIPool(t)
ctx := context.Background()
tok := adminLogin(t, r, "admin", "change-me")
_, code := doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/growth/report-templates", nil, "")
if code != http.StatusUnauthorized {
t.Fatalf("expected 401, got %d", code)
}
limitedRoleID := uuid.New()
_, err := pool.Exec(ctx, `INSERT INTO admin_roles(id, name, system) VALUES ($1,$2,false)`,
limitedRoleID, "lim_"+limitedRoleID.String()[:8])
if err != nil {
t.Fatal(err)
}
_, err = pool.Exec(ctx, `INSERT INTO admin_role_permissions(role_id, code) VALUES ($1,'admin.users.read')`, limitedRoleID)
if err != nil {
t.Fatal(err)
}
hash, err := bcrypt.GenerateFromPassword([]byte("limited-pass"), bcrypt.DefaultCost)
if err != nil {
t.Fatal(err)
}
limUser := fmt.Sprintf("lim_%d", time.Now().UnixNano())
_, err = pool.Exec(ctx, `INSERT INTO admin_accounts(username, password_hash, role_id) VALUES ($1,$2,$3)`,
limUser, string(hash), limitedRoleID)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
_, _ = pool.Exec(ctx, `DELETE FROM admin_accounts WHERE username=$1`, limUser)
_, _ = pool.Exec(ctx, `DELETE FROM admin_roles WHERE id=$1`, limitedRoleID)
})
limTok := adminLogin(t, r, limUser, "limited-pass")
_, code = doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/growth/report-templates", nil, limTok)
if code != http.StatusForbidden {
t.Fatalf("expected 403, got %d", code)
}
start := time.Now()
env, code := doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/growth/report-templates", nil, tok)
if code != 200 || env.Code != 0 {
t.Fatalf("list http=%d msg=%s", code, env.Message)
}
if time.Since(start) > 500*time.Millisecond {
t.Fatalf("list too slow %v", time.Since(start))
}
var list struct {
Items []struct {
ID string `json:"id"`
Code string `json:"code"`
} `json:"items"`
}
_ = json.Unmarshal(env.Data, &list)
var id string
for _, it := range list.Items {
if it.Code == "portrait_default" {
id = it.ID
break
}
}
if id == "" {
t.Fatalf("missing portrait_default: %#v", list.Items)
}
env, code = doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/growth/report-templates/"+id, nil, tok)
if code != 200 {
t.Fatalf("get %d", code)
}
_, code = doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/growth/report-templates/"+fakeUUID(), nil, tok)
if code != http.StatusNotFound {
t.Fatalf("expected 404, got %d", code)
}
}
@@ -0,0 +1,58 @@
package repository
import (
"context"
"errors"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
)
// ReportTemplateRow is ReportTemplate catalog row.
type ReportTemplateRow struct {
ID uuid.UUID `json:"id"`
Code string `json:"code"`
Title string `json:"title"`
Scene string `json:"scene"`
Active bool `json:"active"`
System bool `json:"system"`
UpdatedAt time.Time `json:"updated_at"`
}
// ListReportTemplates returns ReportTemplate catalog.
func (r *AdminRepo) ListReportTemplates(ctx context.Context) ([]ReportTemplateRow, error) {
rows, err := r.Pool.Query(ctx, `
SELECT id, code, title, scene, active, system, updated_at
FROM report_templates
ORDER BY active DESC, code ASC`)
if err != nil {
return nil, err
}
defer rows.Close()
var out []ReportTemplateRow
for rows.Next() {
var row ReportTemplateRow
if err := rows.Scan(&row.ID, &row.Code, &row.Title, &row.Scene, &row.Active, &row.System, &row.UpdatedAt); err != nil {
return nil, err
}
out = append(out, row)
}
return out, rows.Err()
}
// GetReportTemplate loads one by id.
func (r *AdminRepo) GetReportTemplate(ctx context.Context, id uuid.UUID) (*ReportTemplateRow, error) {
var row ReportTemplateRow
err := r.Pool.QueryRow(ctx, `
SELECT id, code, title, scene, active, system, updated_at
FROM report_templates WHERE id=$1`, id,
).Scan(&row.ID, &row.Code, &row.Title, &row.Scene, &row.Active, &row.System, &row.UpdatedAt)
if errors.Is(err, pgx.ErrNoRows) {
return nil, err
}
if err != nil {
return nil, err
}
return &row, nil
}
+2 -1
View File
@@ -32,6 +32,7 @@ const (
PermCMSRead = "admin.cms.read" PermCMSRead = "admin.cms.read"
PermPrivacyRead = "admin.privacy.read" PermPrivacyRead = "admin.privacy.read"
PermExploreRead = "admin.explore.read" PermExploreRead = "admin.explore.read"
PermGrowthRead = "admin.growth.read"
) )
var knownPermissions = map[string]struct{}{ var knownPermissions = map[string]struct{}{
@@ -41,7 +42,7 @@ var knownPermissions = map[string]struct{}{
PermUsersStatusWrite: {}, PermMembershipPlansRead: {}, PermMembershipPlansWrite: {}, PermUsersStatusWrite: {}, PermMembershipPlansRead: {}, PermMembershipPlansWrite: {},
PermMembershipCodesRead: {}, PermMembershipCodesWrite: {}, PermMembershipCodesRead: {}, PermMembershipCodesWrite: {},
PermAskRead: {}, PermAskFeedbackWrite: {}, PermContentSafetyRead: {}, PermAskRead: {}, PermAskFeedbackWrite: {}, PermContentSafetyRead: {},
PermAIConfigRead: {}, PermCrisisRead: {}, PermCMSRead: {}, PermExploreRead: {}, PermPrivacyRead: {}, PermAIConfigRead: {}, PermCrisisRead: {}, PermCMSRead: {}, PermGrowthRead: {}, PermExploreRead: {}, PermPrivacyRead: {},
} }
var ( var (
@@ -0,0 +1,34 @@
package admin
import (
"context"
"errors"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/yuxingu/digital-psychology/apps/api/internal/repository"
)
var ErrReportTemplateNotFound = errString("report template not found")
// ListReportTemplates returns catalog.
func (s *Service) ListReportTemplates(ctx context.Context) ([]repository.ReportTemplateRow, error) {
items, err := s.Repo.ListReportTemplates(ctx)
if err != nil {
return nil, err
}
if items == nil {
items = []repository.ReportTemplateRow{}
}
return items, nil
}
// GetReportTemplate loads one.
func (s *Service) GetReportTemplate(ctx context.Context, id uuid.UUID) (*repository.ReportTemplateRow, error) {
row, err := s.Repo.GetReportTemplate(ctx, id)
if errors.Is(err, pgx.ErrNoRows) {
return nil, ErrReportTemplateNotFound
}
return row, err
}
@@ -0,0 +1,2 @@
DELETE FROM admin_role_permissions WHERE code = 'admin.growth.read';
DROP TABLE IF EXISTS report_templates;
@@ -0,0 +1,24 @@
-- ECR-038 ReportTemplate (read catalog)
CREATE TABLE IF NOT EXISTS report_templates (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
code varchar(64) NOT NULL UNIQUE,
title varchar(128) NOT NULL,
scene varchar(32) NOT NULL,
active boolean NOT NULL DEFAULT true,
system boolean NOT NULL DEFAULT false,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_report_templates_active ON report_templates(active);
INSERT INTO report_templates(code, title, scene, active, system)
VALUES ('portrait_default', '画像报告模板占位', 'portrait', true, true)
ON CONFLICT (code) DO NOTHING;
INSERT INTO admin_role_permissions(role_id, code)
SELECT r.id, 'admin.growth.read'
FROM admin_roles r
WHERE r.name = 'super_admin'
ON CONFLICT DO NOTHING;
@@ -0,0 +1,23 @@
# Backend Design: ECR-038 ReportTemplate
| ID | BD-2026-038 |
| Status | Approved |
| Coding | Loop authorized |
| Level | L2 |
| Migration | YES 000039 |
## Backend Change Boundary
```text
Domain: ReportTemplate (read)
App: AdminHandler → admin.Service → AdminRepo
API: GET /admin/growth/report-templates; GET /admin/growth/report-templates/{id}
Permission: admin.growth.read
Migration: 000039
```
## Out of boundary
模板写发布 · 广告投放 · UGC · 真支付
Rollback: down migration + remove routes/UI
+1
View File
@@ -2,6 +2,7 @@
## 2026-08-08 ## 2026-08-08
- **ECR-038 Closed**GrowthInsights ReportTemplatemigration 000039 · admin client · /growth/report-templates · 只读)
- **ECR-037 Closed**ExploreConfig ImageCardDeckmigration 000038 · admin client · /explore/image-card-decks · 只读) - **ECR-037 Closed**ExploreConfig ImageCardDeckmigration 000038 · admin client · /explore/image-card-decks · 只读)
- **ECR-036 Closed**ExploreConfig RhythmConfigmigration 000037 · admin client · /explore/rhythm-configs · 只读) - **ECR-036 Closed**ExploreConfig RhythmConfigmigration 000037 · admin client · /explore/rhythm-configs · 只读)
- **ECR-035 Closed**ExploreConfig StarConfigmigration 000036 · admin client · /explore/star-configs · 只读) - **ECR-035 Closed**ExploreConfig StarConfigmigration 000036 · admin client · /explore/star-configs · 只读)
+8
View File
@@ -0,0 +1,8 @@
# CODE_REVIEW — ECR-038
**Verdict:** Approve → Closed
Date: 2026-08-08 · Loop continuous
- ReportTemplate 只读;无 UGC/真支付
- Integration AC mapped · OpenAPI updated
+22
View File
@@ -0,0 +1,22 @@
ecr: ECR-038
capability: GrowthInsights
bounded_context: Explore_Reports
parent: WAVE0-FROZEN
predecessor: ECR-037
change:
type: additive
breaking_change: false
migration_required: true
compatibility_notes: >
Adds ReportTemplate read catalog. Forbidden: UGC / real payment.
apis:
- method: GET
path: /api/v1/admin/growth/report-templates
change: added
- method: GET
path: /api/v1/admin/growth/report-templates/{id}
change: added
perms:
- code: admin.growth.read
change: added
+15
View File
@@ -0,0 +1,15 @@
# ECR-038
**Title:** GrowthInsights · ReportTemplate(只读薄切片)
**Status:** **Closed**
**Closed:** 2026-08-08Loop continuous
**Parent:** WAVE0-FROZEN · **Predecessor:** ECR-037 Closed
**Change Level:** L2
## Change
ReportTemplate 只读 · migration 000039 · admin client · /growth/report-templates
## Linked
Spec `ops-report-template.md` · BD-2026-038 · CONTRACT_DIFF/ECR-038.yaml · TEST_REPORT/ECR-038.md
@@ -0,0 +1,6 @@
# ENGINEERING_SPEC — ECR-038
1. migration 000039
2. AdminRepo/Service/Handler
3. OpenAPI + admin-h5
4. Integration · Closed
@@ -0,0 +1,3 @@
# HANDOFF — ECR-038 Architect → Engineer
Loop continuous · Approved + Coding. Migration 000039. Forbidden: UGC/真支付.
@@ -0,0 +1,3 @@
# HANDOFF — ECR-038 Engineer → Reviewer
TestGrowthReportTemplates PASS · Ready for Closed.
@@ -0,0 +1,3 @@
# PRODUCT_SPEC — ECR-038
对齐 ops-report-template.md · Approved · Loop · L2 · ReportTemplate 只读
+6
View File
@@ -0,0 +1,6 @@
# STATE — ECR-038
| Status | **Closed** |
| Phase | closed |
| Spec | ops-report-template.md |
| Updated | 2026-08-08 |
+12
View File
@@ -0,0 +1,12 @@
id: TASK-038-ECR038
ecr: ECR-038
title: GrowthInsights · ReportTemplate(只读薄切片)
role: engineer
status: closed
change_level: L2
parent: WAVE0-FROZEN
predecessor: ECR-037
acceptance:
- Spec AC mapped
- ReportTemplate read only
- No UGC / payment
+33
View File
@@ -0,0 +1,33 @@
# TEST_REPORT — ECR-038 ReportTemplate
Date: 2026-08-08 · Loop continuous · commit: `PENDING`
## Commands
```bash
cd apps/api && go test ./internal/integration/ -run TestGrowthReportTemplates -count=1
npm run build:admin
python3 scripts/ess-validate.py --phase review --ecr ECR-038
python3 scripts/ess-gate-check.py --ecr ECR-038
```
## Results
| Check | Result |
|-------|--------|
| TestGrowthReportTemplates | PASS |
| build:admin | PASS |
| ess-validate review | PASS |
| ess-gate-check | PASS |
## AC
| ID | Evidence |
|----|----------|
| AC-F-01 | list seed/empty ok |
| AC-F-02 | get 200 |
| AC-F-03 | 未知 id → 404 |
| AC-S-01 | 401 |
| AC-S-02 | 403 |
| AC-P-01 | list &lt; 500ms |
| AC-O-01 | N/A 只读 |
+1
View File
@@ -42,3 +42,4 @@
| ECR-035 | ExploreConfig · StarConfig | **Closed** | Spec ops-star-config.md · BD-2026-035 · migration 000036 · TEST_REPORT · CODE_REVIEW · Loop continuous | | ECR-035 | ExploreConfig · StarConfig | **Closed** | Spec ops-star-config.md · BD-2026-035 · migration 000036 · TEST_REPORT · CODE_REVIEW · Loop continuous |
| ECR-036 | ExploreConfig · RhythmConfig | **Closed** | Spec ops-rhythm-config.md · BD-2026-036 · migration 000037 · TEST_REPORT · CODE_REVIEW · Loop continuous | | ECR-036 | ExploreConfig · RhythmConfig | **Closed** | Spec ops-rhythm-config.md · BD-2026-036 · migration 000037 · TEST_REPORT · CODE_REVIEW · Loop continuous |
| ECR-037 | ExploreConfig · ImageCardDeck | **Closed** | Spec ops-image-card-deck.md · BD-2026-037 · migration 000038 · TEST_REPORT · CODE_REVIEW · Loop continuous | | ECR-037 | ExploreConfig · ImageCardDeck | **Closed** | Spec ops-image-card-deck.md · BD-2026-037 · migration 000038 · TEST_REPORT · CODE_REVIEW · Loop continuous |
| ECR-038 | GrowthInsights · ReportTemplate | **Closed** | Spec ops-report-template.md · BD-2026-038 · migration 000039 · TEST_REPORT · CODE_REVIEW · Loop continuous |
+1 -1
View File
@@ -55,4 +55,4 @@ Human 明文:**直接用 Loop,不用人工确认。**
| Done | Next | | Done | Next |
|------|------| |------|------|
| ECR-013A…037 Closed | **ECR-038** ReportTemplate | | ECR-013A…038 Closed | **ECR-039** FunnelDefinition |
+28
View File
@@ -975,6 +975,34 @@ paths:
'404': '404':
description: Not found description: Not found
/api/v1/admin/growth/report-templates:
get:
tags: [admin]
summary: List ReportTemplate catalog
description: Requires admin.growth.read
responses:
'200':
description: OK
'401':
description: Unauthorized
'403':
description: Forbidden
/api/v1/admin/growth/report-templates/{id}:
get:
tags: [admin]
summary: Get ReportTemplate
parameters:
- in: path
name: id
required: true
schema: { type: string, format: uuid }
responses:
'200':
description: OK
'404':
description: Not found
/api/v1/admin/crisis/policies: /api/v1/admin/crisis/policies:
get: get:
tags: [admin] tags: [admin]