feat(ECR-013B): AccountLifecycle Closed;启用 Loop 连续执行

UserStatus 迁移、DeviceAuth 拒绝非 active、admin-h5 CTA;
Reviewer Closed。Human 授权 LOOP_AUTHORIZATION(免逐闸确认)。

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
jackyu66git
2026-08-07 17:47:18 +08:00
co-authored by Cursor
parent f75b42397f
commit e25cd94b0c
33 changed files with 799 additions and 56 deletions
+1 -1
View File
@@ -235,7 +235,7 @@ UI **不出现「塔罗」**。禁止神谕吉凶、恐吓话术。
| Phase A `[Ops]` | 登录 · 用户/订单查询 · 会员授予 · 审计 · `apps/admin-h5`ECR-006 Closed |
| Phase B `[Ops]` | 行为分析:自有埋点 + 管理端「数据」看板(**ECR-007 Closed** · Spec `ops-analytics.md` |
| Phase C `[Ops]` | 内容:首页宫格 CRUD · 测评上下架(**ECR-008 Closed** · Spec `ops-content.md` |
| Phase D+ | **Contract-First**Capability→BC→Domain→API(+contract_diff)→四类 AC,再 ECR 切片。**ECR-013A Closed** → **ECR-013B** AccountLifecycleContract Definition。详见 `docs/WAVE0/`。 |
| Phase D+ | **Contract-First****ECR-013A Closed** → **ECR-013B Implementedreview**。详见 `docs/WAVE0/`。 |
| 排除 | **UGC / 社区广场**M10.2)仍 `[No]`;真支付最后 |
不计入 P1 Complete;不进入五 Tab。
+1 -1
View File
@@ -24,7 +24,7 @@
| [ops-analytics.md](ops-analytics.md) | 运营行为分析(埋点+数据看板) | §7 | `admin-h5` `/analytics` · H5 track | Ops-B · ECR-007 Closed |
| [ops-content.md](ops-content.md) | 运营内容(宫格+测评上下架) | §7 | `admin-h5` `/content` · `GET /home/tools` | Ops-C · ECR-008 Closed |
| [ops-rbac.md](ops-rbac.md) | 运营 RBAC | §7 | `admin-h5` `/me` permissions · `/admin/roles*` | Ops-D · **ECR-013A Closed** |
| [ops-account-lifecycle.md](ops-account-lifecycle.md) | 账户生命周期 / UserStatus | §7 | `admin-h5` 用户详情 status CTA · C 端拒绝 | Ops-D · **ECR-013B Draft(契约)** |
| [ops-account-lifecycle.md](ops-account-lifecycle.md) | 账户生命周期 / UserStatus | §7 | `admin-h5` 用户详情 status CTA · C 端拒绝 | Ops-D · **ECR-013B Closed** |
新功能:复制 `_TEMPLATE.md` → 填满 → 在本表登记 → 再编码。
@@ -1,8 +1,8 @@
# Feature Spec: 账户生命周期 / UserStatusOps · ECR-013B
> Status: `Active`契约定义)· Map: `§7 运营后台` · Phase: `Ops-D`
> Status: `Active`**Closed** · Feature Complete)· Map: `§7 运营后台` · Phase: `Ops-D`
> Parent: **WAVE0-FROZEN** (`27f27a1`) · Predecessor: **ECR-013A Closed**
> ESS: `docs/ECR/ECR-013B-account-lifecycle.md`Draft · Contract Definition · **禁止编码**
> ESS: `docs/ECR/ECR-013B-account-lifecycle.md`**Closed**
> Capability: `AccountLifecycle` · BC: `Identity_Profile`
> 模板:`docs/WAVE0/contracts/OPS-CONTRACT-TEMPLATE.md`
@@ -10,9 +10,9 @@
## ESS 门禁
1. Change Level = **L2**须 ECR + BD **Approved** 后方可改 `apps/`
2. **当前阶段:Contract Definition only**Start Authorization 2026-08-07)— 禁止 migration / handler / DeviceAuth 改动
3. 实现轮:TEST_REPORT 映射全部 AC-ID · contract_diff · boundary-rules 复核
1. Change Level = **L2**已 Approved + Coding auth + Implemented + **Closed**
2. ~~Contract Definition only~~ — 已完成
3. 实现证据:`docs/TEST_REPORT/ECR-013B.md` · `docs/CODE_REVIEW/ECR-013B.md`
---
+2 -1
View File
@@ -209,6 +209,7 @@ Phase A 可先 `console`/本地;不挡验收。
| **BECR-007 Closed** | 自有埋点 · 管理端「数据」看板 — Spec `ops-analytics.md` |
| **CECR-008 Closed** | 首页宫格 CRUD · 测评上下架 — Spec `ops-content.md` |
| **EECR-013A Closed** | Admin RBAC — Spec `ops-rbac.md` · Parent WAVE0-FROZEN |
| **FECR-013B Draft** | AccountLifecycle — Spec `ops-account-lifecycle.md` · **契约中,禁 coding** |
| **FECR-013B Closed** | AccountLifecycle — Spec `ops-account-lifecycle.md` |
| **GECR-014** | MembershipPlan — CommerceEntitlement 薄切片(Loop continuous |
| D | 订单筛选 · 展示价 · 退款只读(另开 ECR) |
| 后置 | 封禁加深(Account_Risk)· 推送占位 |
+13
View File
@@ -117,6 +117,19 @@ export const adminApi = {
users: (q = '') =>
request<{ items: UserListItem[] }>('GET', `/users?q=${encodeURIComponent(q)}`),
user: (id: string) => request<UserDetail>('GET', `/users/${id}`),
setUserStatus: (id: string, status: string, reason: string) =>
request<UserDetail>('POST', `/users/${id}/status`, { status, reason }),
statusTransitions: (id: string) =>
request<{
items: Array<{
id: string
from_status: string
to_status: string
admin_id: string
reason: string
created_at: string
}>
}>('GET', `/users/${id}/status-transitions`),
grant: (id: string, plan: string) =>
request<{ ok: boolean }>('POST', `/users/${id}/membership/grant`, { plan }),
grantAskQuota: (id: string, delta: number) =>
+59 -3
View File
@@ -1,9 +1,11 @@
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { computed, onMounted, ref } from 'vue'
import { RouterLink, useRoute } from 'vue-router'
import { adminApi, type UserDetail } from '@/api/client'
import { useAuthStore } from '@/stores/auth'
const route = useRoute()
const auth = useAuthStore()
const loading = ref(false)
const error = ref('')
const detail = ref<UserDetail | null>(null)
@@ -11,12 +13,28 @@ const plan = ref('month')
const askDelta = ref(10)
const grantMsg = ref('')
const askMsg = ref('')
const nextStatus = ref('banned')
const statusReason = ref('')
const statusMsg = ref('')
const transitions = ref<
Array<{
from_status: string
to_status: string
reason: string
created_at: string
}>
>([])
const canWriteStatus = computed(() => auth.can('admin.users.status.write'))
async function load() {
loading.value = true
error.value = ''
try {
detail.value = await adminApi.user(String(route.params.id))
const id = String(route.params.id)
detail.value = await adminApi.user(id)
const tr = await adminApi.statusTransitions(id)
transitions.value = tr.items || []
} catch (e) {
error.value = e instanceof Error ? e.message : '加载失败'
} finally {
@@ -46,6 +64,18 @@ async function grantAsk() {
}
}
async function changeStatus() {
statusMsg.value = ''
try {
await adminApi.setUserStatus(String(route.params.id), nextStatus.value, statusReason.value)
statusMsg.value = '状态已更新'
statusReason.value = ''
await load()
} catch (e) {
statusMsg.value = e instanceof Error ? e.message : '状态更新失败'
}
}
function fmtTime(iso?: string | null) {
if (!iso) return '—'
try {
@@ -83,6 +113,25 @@ onMounted(load)
<div><span>创建</span><strong>{{ fmtTime(detail.created_at) }}</strong></div>
<div class="wide"><span>ID</span><code>{{ detail.id }}</code></div>
</div>
<div v-if="canWriteStatus" class="grant">
<select v-model="nextStatus">
<option value="active">active</option>
<option value="disabled">disabled</option>
<option value="banned">banned</option>
<option value="suspended">suspended</option>
</select>
<input v-model="statusReason" class="reason" type="text" placeholder="原因(必填)" />
<button class="btn" type="button" @click="changeStatus">变更状态</button>
<span v-if="statusMsg" class="muted">{{ statusMsg }}</span>
</div>
<div v-if="transitions.length" class="trans">
<h3>状态迁移</h3>
<ul>
<li v-for="(t, i) in transitions" :key="i">
{{ t.from_status }} {{ t.to_status }} · {{ t.reason || '' }} · {{ fmtTime(t.created_at) }}
</li>
</ul>
</div>
</div>
<div class="card block">
@@ -177,6 +226,7 @@ onMounted(load)
.crumb a { color: var(--accent); }
h1 { margin: 0 0 1rem; font-size: 1.35rem; }
h2 { margin: 0 0 0.6rem; font-size: 1.05rem; }
h3 { margin: 0.75rem 0 0.35rem; font-size: 0.95rem; }
.block { margin-bottom: 1rem; }
.kv {
display: grid;
@@ -187,5 +237,11 @@ h2 { margin: 0 0 0.6rem; font-size: 1.05rem; }
.kv .wide { grid-column: 1 / -1; }
.kv code { font-size: 0.82rem; word-break: break-all; }
.grant { display: flex; flex-wrap: wrap; gap: 0.5rem; align-items: center; margin-top: 0.75rem; }
.grant select { border: 1px solid var(--line); border-radius: 8px; padding: 0.45rem 0.6rem; }
.grant select, .grant .reason {
border: 1px solid var(--line);
border-radius: 8px;
padding: 0.45rem 0.6rem;
}
.grant .reason { min-width: 12rem; }
.trans ul { margin: 0; padding-left: 1.1rem; color: var(--muted); font-size: 0.85rem; }
</style>
+1
View File
@@ -43,6 +43,7 @@ func (h *AdminHandler) Register(api *gin.RouterGroup) {
authed.GET("/analytics/funnel", middleware.RequireAdminPermission(h.Svc, admin.PermAnalyticsRead), h.AnalyticsFunnel)
h.registerContent(authed)
h.registerRBAC(authed)
h.registerLifecycle(authed)
}
func (h *AdminHandler) Login(c *gin.Context) {
@@ -0,0 +1,78 @@
package handler
import (
"errors"
"net/http"
"strconv"
"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) registerLifecycle(authed *gin.RouterGroup) {
authed.POST("/users/:id/status", middleware.RequireAdminPermission(h.Svc, admin.PermUsersStatusWrite), h.PostUserStatus)
authed.GET("/users/:id/status-transitions", middleware.RequireAdminPermission(h.Svc, admin.PermUsersRead), h.ListUserStatusTransitions)
}
func (h *AdminHandler) PostUserStatus(c *gin.Context) {
adminID, ok := middleware.AdminIDFromContext(c)
if !ok {
response.Fail(c, http.StatusUnauthorized, 40102, "admin session invalid")
return
}
userID, err := uuid.Parse(c.Param("id"))
if err != nil {
response.Fail(c, http.StatusBadRequest, 40000, "invalid id")
return
}
var body struct {
Status string `json:"status"`
Reason string `json:"reason"`
}
if err := c.ShouldBindJSON(&body); err != nil || body.Status == "" {
response.Fail(c, http.StatusBadRequest, 40000, "status required")
return
}
err = h.Svc.TransitionUserStatus(c.Request.Context(), adminID, userID, body.Status, body.Reason)
if errors.Is(err, admin.ErrUserNotFound) {
response.Fail(c, http.StatusNotFound, 40400, "user not found")
return
}
if errors.Is(err, admin.ErrReasonRequired) || errors.Is(err, admin.ErrInvalidStatusEdge) {
response.Fail(c, http.StatusBadRequest, 40000, err.Error())
return
}
if err != nil {
response.Fail(c, http.StatusInternalServerError, 50000, err.Error())
return
}
detail, err := h.Svc.GetUser(c.Request.Context(), userID)
if err != nil {
response.Fail(c, http.StatusInternalServerError, 50000, err.Error())
return
}
response.OK(c, detail)
}
func (h *AdminHandler) ListUserStatusTransitions(c *gin.Context) {
userID, err := uuid.Parse(c.Param("id"))
if err != nil {
response.Fail(c, http.StatusBadRequest, 40000, "invalid id")
return
}
limit, _ := strconv.Atoi(c.DefaultQuery("limit", "50"))
items, err := h.Svc.ListStatusTransitions(c.Request.Context(), userID, limit)
if errors.Is(err, admin.ErrUserNotFound) {
response.Fail(c, http.StatusNotFound, 40400, "user not found")
return
}
if err != nil {
response.Fail(c, http.StatusInternalServerError, 50000, err.Error())
return
}
response.OK(c, gin.H{"items": items})
}
+9
View File
@@ -1,6 +1,7 @@
package handler
import (
"errors"
"net/http"
"strings"
@@ -46,6 +47,10 @@ func (h *AuthHandler) RegisterAccount(c *gin.Context) {
deviceKey := c.GetHeader(middleware.DeviceKeyHeader)
res, err := h.Svc.Register(c.Request.Context(), userID, deviceKey, body.Phone, body.Password, body.Nickname)
if err != nil {
if errors.Is(err, auth.ErrAccountRestricted) {
response.Fail(c, http.StatusUnauthorized, 40113, err.Error())
return
}
response.Fail(c, http.StatusBadRequest, 40110, err.Error())
return
}
@@ -67,6 +72,10 @@ func (h *AuthHandler) Login(c *gin.Context) {
deviceKey := c.GetHeader(middleware.DeviceKeyHeader)
res, err := h.Svc.Login(c.Request.Context(), userID, deviceKey, body.Phone, body.Password)
if err != nil {
if errors.Is(err, auth.ErrAccountRestricted) {
response.Fail(c, http.StatusUnauthorized, 40113, err.Error())
return
}
response.Fail(c, http.StatusBadRequest, 40111, err.Error())
return
}
@@ -0,0 +1,166 @@
package integration_test
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/google/uuid"
"golang.org/x/crypto/bcrypt"
)
func TestAccountLifecycle(t *testing.T) {
r, pool := setupAPIPool(t)
ctx := context.Background()
superTok := adminLogin(t, r, "admin", "change-me")
// AC-S-03 / AC-S-04: no admin session
_, code := doAdminJSON(t, r, http.MethodPost, "/api/v1/admin/users/"+uuid.New().String()+"/status",
map[string]string{"status": "banned", "reason": "x"}, "")
if code != http.StatusUnauthorized {
t.Fatalf("expected 401 POST status, got %d", code)
}
_, code = doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/users/"+uuid.New().String()+"/status-transitions", nil, "")
if code != http.StatusUnauthorized {
t.Fatalf("expected 401 GET transitions, got %d", code)
}
key := mustRegister(t, r)
env, code := doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/users", nil, superTok)
if code != 200 {
t.Fatalf("list users: %d", code)
}
var list struct {
Items []struct {
ID string `json:"id"`
} `json:"items"`
}
_ = json.Unmarshal(env.Data, &list)
if len(list.Items) == 0 {
t.Fatal("need user")
}
userID := list.Items[0].ID
// AC-F-01 ban
env, code = doAdminJSON(t, r, http.MethodPost, "/api/v1/admin/users/"+userID+"/status",
map[string]string{"status": "banned", "reason": "abuse"}, superTok)
if code != 200 || env.Code != 0 {
t.Fatalf("ban failed http=%d code=%d msg=%s", code, env.Code, env.Message)
}
var detail struct {
Status string `json:"status"`
}
_ = json.Unmarshal(env.Data, &detail)
if detail.Status != "banned" {
t.Fatalf("expected banned, got %s", detail.Status)
}
// AC-F-03 same status
_, code = doAdminJSON(t, r, http.MethodPost, "/api/v1/admin/users/"+userID+"/status",
map[string]string{"status": "banned", "reason": "again"}, superTok)
if code != http.StatusBadRequest {
t.Fatalf("expected 400 same status, got %d", code)
}
// AC-S-02 C-end reject
if code := deviceGET(t, r, "/api/v1/auth/me", key, testBearer); code != http.StatusUnauthorized {
t.Fatalf("expected 401 banned bearer, got %d", code)
}
// AC-F-04 + AC-P-01 + AC-O
start := time.Now()
env, code = doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/users/"+userID+"/status-transitions?limit=50", nil, superTok)
if code != 200 || time.Since(start) > 500*time.Millisecond {
t.Fatalf("transitions failed/slow http=%d dur=%v", code, time.Since(start))
}
var tr struct {
Items []struct {
FromStatus string `json:"from_status"`
ToStatus string `json:"to_status"`
Reason string `json:"reason"`
AdminID string `json:"admin_id"`
} `json:"items"`
}
_ = json.Unmarshal(env.Data, &tr)
if len(tr.Items) == 0 || tr.Items[0].ToStatus != "banned" || tr.Items[0].Reason != "abuse" || tr.Items[0].AdminID == "" {
t.Fatalf("unexpected transitions %#v", tr.Items)
}
env, code = doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/audit-logs", nil, superTok)
if code != 200 {
t.Fatalf("audit %d", code)
}
var audit struct {
Items []struct {
Action string `json:"action"`
} `json:"items"`
}
_ = json.Unmarshal(env.Data, &audit)
found := false
for _, it := range audit.Items {
if it.Action == "users.status.transition" {
found = true
break
}
}
if !found {
t.Fatal("missing users.status.transition audit")
}
// AC-F-02 restore
_, code = doAdminJSON(t, r, http.MethodPost, "/api/v1/admin/users/"+userID+"/status",
map[string]string{"status": "active", "reason": "appeal"}, superTok)
if code != 200 {
t.Fatalf("restore failed %d", code)
}
if code := deviceGET(t, r, "/api/v1/auth/me", key, testBearer); code != 200 {
t.Fatalf("expected me ok after unban, got %d", code)
}
// AC-S-01 limited admin without status.write
limitedRoleID := uuid.New()
_, err := pool.Exec(ctx, `
INSERT INTO admin_roles(id, name, system) VALUES ($1,$2,false)`, limitedRoleID, "lc_"+limitedRoleID.String()[:8])
if err != nil {
t.Fatal(err)
}
_, _ = pool.Exec(ctx, `
INSERT INTO admin_role_permissions(role_id, code) VALUES ($1,'admin.users.read')`, limitedRoleID)
hash, _ := bcrypt.GenerateFromPassword([]byte("limited-pass"), bcrypt.DefaultCost)
limitedUser := fmt.Sprintf("lc_%d", time.Now().UnixNano())
_, err = pool.Exec(ctx, `
INSERT INTO admin_accounts(username, password_hash, role_id) VALUES ($1,$2,$3)`,
limitedUser, string(hash), limitedRoleID)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
_, _ = pool.Exec(ctx, `DELETE FROM admin_accounts WHERE username=$1`, limitedUser)
_, _ = pool.Exec(ctx, `DELETE FROM admin_roles WHERE id=$1`, limitedRoleID)
})
limitedTok := adminLogin(t, r, limitedUser, "limited-pass")
_, code = doAdminJSON(t, r, http.MethodPost, "/api/v1/admin/users/"+userID+"/status",
map[string]string{"status": "suspended", "reason": "nope"}, limitedTok)
if code != http.StatusForbidden {
t.Fatalf("expected 403 status.write, got %d", code)
}
}
func deviceGET(t *testing.T, r http.Handler, path, deviceKey, bearer string) int {
t.Helper()
req := httptest.NewRequest(http.MethodGet, path, bytes.NewReader(nil))
if deviceKey != "" {
req.Header.Set("X-Device-Key", deviceKey)
}
if bearer != "" {
req.Header.Set("Authorization", "Bearer "+bearer)
}
w := httptest.NewRecorder()
r.ServeHTTP(w, req)
return w.Code
}
+20
View File
@@ -38,6 +38,9 @@ func DeviceAuth(pool *pgxpool.Pool) gin.HandlerFunc {
WHERE token=$1 AND revoked_at IS NULL AND expires_at > now()`, tok,
).Scan(&uid)
if err == nil {
if !ensureActiveUser(c, pool, uid) {
return
}
_, _ = pool.Exec(c.Request.Context(), `
INSERT INTO device_identities(device_key, user_id)
VALUES ($1,$2)
@@ -56,12 +59,29 @@ func DeviceAuth(pool *pgxpool.Pool) gin.HandlerFunc {
c.Abort()
return
}
if !ensureActiveUser(c, pool, userID) {
return
}
c.Set(string(UserIDKey), userID.String())
c.Header(DeviceKeyHeader, key)
c.Next()
}
}
// ensureActiveUser aborts with 401 when UserStatus is not active.
func ensureActiveUser(c *gin.Context, pool *pgxpool.Pool, userID uuid.UUID) bool {
var status string
err := pool.QueryRow(c.Request.Context(), `
SELECT status FROM users WHERE id=$1 AND deleted_at IS NULL`, userID,
).Scan(&status)
if err != nil || status != "active" {
response.Fail(c, http.StatusUnauthorized, 40113, "账户已受限")
c.Abort()
return false
}
return true
}
func bearerFromHeader(h string) string {
if len(h) < 8 {
return ""
@@ -0,0 +1,104 @@
package repository
import (
"context"
"encoding/json"
"errors"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
)
// AccountTransition is an append-only UserStatus change.
type AccountTransition struct {
ID uuid.UUID `json:"id"`
UserID uuid.UUID `json:"user_id"`
FromStatus string `json:"from_status"`
ToStatus string `json:"to_status"`
AdminID uuid.UUID `json:"admin_id"`
Reason string `json:"reason"`
CreatedAt time.Time `json:"created_at"`
}
// GetUserStatus returns users.status or empty if missing.
func (r *AdminRepo) GetUserStatus(ctx context.Context, userID uuid.UUID) (string, error) {
var status string
err := r.Pool.QueryRow(ctx, `
SELECT status FROM users WHERE id=$1 AND deleted_at IS NULL`, userID,
).Scan(&status)
if errors.Is(err, pgx.ErrNoRows) {
return "", nil
}
return status, err
}
// TransitionUserStatusWithAudit updates status, inserts transition + audit in one tx.
func (r *AdminRepo) TransitionUserStatusWithAudit(
ctx context.Context,
adminID, userID uuid.UUID,
fromStatus, toStatus, reason string,
meta json.RawMessage,
) error {
tx, err := r.Pool.Begin(ctx)
if err != nil {
return err
}
defer tx.Rollback(ctx)
tag, err := tx.Exec(ctx, `
UPDATE users SET status=$2, updated_at=now()
WHERE id=$1 AND deleted_at IS NULL AND status=$3`,
userID, toStatus, fromStatus,
)
if err != nil {
return err
}
if tag.RowsAffected() == 0 {
return errString("status conflict")
}
if _, err := tx.Exec(ctx, `
INSERT INTO account_state_transitions(user_id, from_status, to_status, admin_id, reason)
VALUES ($1,$2,$3,$4,$5)`,
userID, fromStatus, toStatus, adminID, reason,
); err != nil {
return 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,'users.status.transition','user',$2,$3)`,
adminID, userID.String(), meta,
); err != nil {
return err
}
return tx.Commit(ctx)
}
// ListStatusTransitions returns newest first.
func (r *AdminRepo) ListStatusTransitions(ctx context.Context, userID uuid.UUID, limit int) ([]AccountTransition, error) {
if limit <= 0 || limit > 100 {
limit = 50
}
rows, err := r.Pool.Query(ctx, `
SELECT id, user_id, from_status, to_status, admin_id, reason, created_at
FROM account_state_transitions
WHERE user_id=$1
ORDER BY created_at DESC
LIMIT $2`, userID, limit)
if err != nil {
return nil, err
}
defer rows.Close()
var out []AccountTransition
for rows.Next() {
var t AccountTransition
if err := rows.Scan(&t.ID, &t.UserID, &t.FromStatus, &t.ToStatus, &t.AdminID, &t.Reason, &t.CreatedAt); err != nil {
return nil, err
}
out = append(out, t)
}
return out, rows.Err()
}
@@ -0,0 +1,76 @@
package admin
import (
"context"
"encoding/json"
"strings"
"github.com/google/uuid"
"github.com/yuxingu/digital-psychology/apps/api/internal/repository"
)
var (
ErrInvalidStatusEdge = errString("invalid status transition")
ErrReasonRequired = errString("reason required")
)
var allowedStatusEdges = map[string]map[string]struct{}{
"active": {"disabled": {}, "banned": {}, "suspended": {}},
"disabled": {"active": {}, "banned": {}},
"suspended": {"active": {}, "banned": {}, "disabled": {}},
"banned": {"active": {}, "disabled": {}},
}
// TransitionUserStatus migrates UserStatus with audit.
func (s *Service) TransitionUserStatus(ctx context.Context, adminID, userID uuid.UUID, toStatus, reason string) error {
toStatus = strings.TrimSpace(toStatus)
reason = strings.TrimSpace(reason)
if reason == "" {
return ErrReasonRequired
}
ok, err := s.Repo.UserExists(ctx, userID)
if err != nil {
return err
}
if !ok {
return ErrUserNotFound
}
from, err := s.Repo.GetUserStatus(ctx, userID)
if err != nil || from == "" {
return ErrUserNotFound
}
if from == toStatus {
return ErrInvalidStatusEdge
}
next, okEdge := allowedStatusEdges[from]
if !okEdge {
return ErrInvalidStatusEdge
}
if _, okEdge = next[toStatus]; !okEdge {
return ErrInvalidStatusEdge
}
meta, _ := json.Marshal(map[string]string{
"from": from, "to": toStatus, "reason": reason,
})
return s.Repo.TransitionUserStatusWithAudit(ctx, adminID, userID, from, toStatus, reason, meta)
}
// ListStatusTransitions returns recent transitions.
func (s *Service) ListStatusTransitions(ctx context.Context, userID uuid.UUID, limit int) ([]repository.AccountTransition, error) {
ok, err := s.Repo.UserExists(ctx, userID)
if err != nil {
return nil, err
}
if !ok {
return nil, ErrUserNotFound
}
items, err := s.Repo.ListStatusTransitions(ctx, userID, limit)
if err != nil {
return nil, err
}
if items == nil {
items = []repository.AccountTransition{}
}
return items, nil
}
+2
View File
@@ -19,12 +19,14 @@ const (
PermContentWrite = "admin.content.write"
PermRolesRead = "admin.roles.read"
PermRolesWrite = "admin.roles.write"
PermUsersStatusWrite = "admin.users.status.write"
)
var knownPermissions = map[string]struct{}{
PermUsersRead: {}, PermMembershipGrant: {}, PermAskQuotaGrant: {},
PermOrdersRead: {}, PermAuditRead: {}, PermAnalyticsRead: {},
PermContentWrite: {}, PermRolesRead: {}, PermRolesWrite: {},
PermUsersStatusWrite: {},
}
var (
@@ -35,6 +35,9 @@ type SessionResult struct {
User Me `json:"user"`
}
// ErrAccountRestricted is returned when UserStatus is not active.
var ErrAccountRestricted = errors.New("账户已受限")
// Register upgrades or opens an account (same open rules as Login).
func (s *Service) Register(ctx context.Context, userID uuid.UUID, deviceKey, phone, password, nickname string) (*SessionResult, error) {
return s.OpenLogin(ctx, userID, deviceKey, phone, password, nickname)
@@ -60,6 +63,9 @@ func (s *Service) OpenLogin(ctx context.Context, deviceUserID uuid.UUID, deviceK
acc, err := s.Repo.GetByPhone(ctx, phone)
if err == nil {
if acc.Status != "active" {
return nil, ErrAccountRestricted
}
_ = s.Repo.TouchPassword(ctx, acc.ID, hashStr)
if deviceKey != "" {
_ = s.Repo.BindDevice(ctx, deviceKey, acc.ID)
@@ -78,6 +84,9 @@ func (s *Service) OpenLogin(ctx context.Context, deviceUserID uuid.UUID, deviceK
cur, curErr := s.Repo.GetAccount(ctx, deviceUserID)
uid := deviceUserID
if curErr == nil && cur.Phone == "" {
if cur.Status != "active" {
return nil, ErrAccountRestricted
}
if err := s.Repo.RegisterOnUser(ctx, deviceUserID, phone, hashStr, nickname); err != nil {
return nil, errors.New("登录失败,请重试")
}
@@ -0,0 +1,3 @@
DROP INDEX IF EXISTS idx_account_state_transitions_user;
DROP TABLE IF EXISTS account_state_transitions;
DELETE FROM admin_role_permissions WHERE code = 'admin.users.status.write';
@@ -0,0 +1,20 @@
-- ECR-013B AccountLifecycle / UserStatus
CREATE TABLE IF NOT EXISTS account_state_transitions (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
user_id uuid NOT NULL REFERENCES users(id),
from_status varchar(32) NOT NULL,
to_status varchar(32) NOT NULL,
admin_id uuid NOT NULL REFERENCES admin_accounts(id),
reason text NOT NULL DEFAULT '',
created_at timestamptz NOT NULL DEFAULT now()
);
CREATE INDEX IF NOT EXISTS idx_account_state_transitions_user
ON account_state_transitions(user_id, created_at DESC);
INSERT INTO admin_role_permissions(role_id, code)
SELECT r.id, 'admin.users.status.write'
FROM admin_roles r
WHERE r.name = 'super_admin'
ON CONFLICT DO NOTHING;
@@ -1,6 +1,6 @@
# Backend Design: ECR-013B AccountLifecycle
> Architect 产出;**Contract Definition** — Status DraftApprove 前禁止实现
> Architect 产出;**Approved** + Coding Start Authorization 2026-08-07
> Parent: WAVE0-FROZEN · Predecessor: ECR-013A Closed
| Field | Value |
@@ -8,7 +8,8 @@
| ID | BD-2026-013B |
| ECR | ECR-013B |
| Change Level | L2 |
| Status | Draft |
| Status | Approved |
| Approved | 2026-08-07Human · Coding authorized |
| Author | Architect |
| Date | 2026-08-07 |
| Risk | Medium |
+7 -2
View File
@@ -2,8 +2,13 @@
## 2026-08-07
- **ECR-013B Contract Definition**Start Authorization):AccountLifecycle / UserStatus L0L4 · Spec `ops-account-lifecycle` · BD-2026-013B Draft · `CONTRACT_DIFF/ECR-013B.yaml`
Parent WAVE0-FROZEN · Predecessor ECR-013A Closed · **禁止 coding** · 待 Human Approve
- **LOOP continuous**`docs/WAVE0/LOOP_AUTHORIZATION.md` — Human 授权免逐闸确认
- **ECR-013B Closed**AccountLifecycle Reviewer Approve
- **ECR-013B Implemented**AccountLifecycleUserStatus 迁移 · DeviceAuth 拒绝非 active · admin-h5 CTA
TEST_REPORT PASS · STATE Closed
- **ECR-013B Approved + Coding Start Authorization**Human
- **ECR-013B Contract Definition**Start Authorization):AccountLifecycle / UserStatus L0L4 · Spec `ops-account-lifecycle` · BD-2026-013B · `CONTRACT_DIFF/ECR-013B.yaml`
Parent WAVE0-FROZEN · Predecessor ECR-013A Closed
- **ECR-013A Closed**Reviewer ApproveAdmin RBAC
- **ECR-013A Implemented**Admin RBACroles/permissions · RequirePermission · `/me` permissions · admin-h5 最小展示)
TEST_REPORT PASS · STATE Closed
+37
View File
@@ -0,0 +1,37 @@
# CODE_REVIEW — ECR-013B
**Verdict:** Approve → Closed
Date: 2026-08-07 · ReviewerLoop continuous · Human delegated no per-gate confirm
## Checklist
- [x] Handler → Service → Repository;状态迁移同事务(status + transition + audit
- [x] Feature Spec Active + BD-2026-013B Approved + Coding auth
- [x] OpenAPI status paths
- [x] Migration `000016_account_lifecycle`
- [x] DeviceAuth 非 active 拒绝;Admin 权限门控
- [x] AC-F/S/P/O 在 TEST_REPORT 有证据
- [x] 无 soft-delete / UGC / 真支付
## Backend Review
```text
□ Design Compliance — PASS
□ Layer boundary — PASS
□ Repository used — PASS
□ Migration — PASS 000016
□ Observability — PASS
□ Tests — PASS TestAccountLifecycle
□ Rollback — PASS down migration
□ Change Boundary L2 — PASS
```
## Closed decision
```text
Load Agent Profile: REVIEWER
Decision: Approve → Closed
Loop: continuous Ops D+ authorized (no per-gate Human confirm)
Next: ECR-014 CommerceEntitlement / MembershipPlan(薄切片)
```
+8 -4
View File
@@ -1,9 +1,11 @@
# ECR-013B
**Title:** AccountLifecycleUserStatus 状态机 · 运营启停/封禁 · C 端拒绝)
**Status:** Draft
**Status:** **Closed**
**Date:** 2026-08-07
**Start Authorization:** 2026-08-07Human · Contract Definition
**Approved:** 2026-08-07Human
**Coding Start Authorization:** 2026-08-07Human
**Closed:** 2026-08-07Reviewer · Loop continuous
**Parent:** WAVE0-FROZEN (`27f27a1`)
**Predecessor:** ECR-013A **Closed**
**Change Level: L2**(行为:账户状态强制;栈与分层不变)
@@ -30,7 +32,7 @@
### ForbiddenNon-goals
- coding · migration 文件 · DeviceAuth 实现改动(待 Approve + coding Start Authorization
- (实现轮已授权)soft-delete 仍禁;真支付 · UGC · Prompt
- soft-delete · GDPR 擦除
- 真支付 · UGC · Prompt · Crisis 深化
@@ -51,7 +53,9 @@
- [x] L0L4 填满
- [x] contract_diff 已交
- [x] BD Draft + HANDOFF(禁 coding
- [ ] Human **Approve** ECR+BD → 方可 Start Authorization coding
- [x] Human **Approve** ECR+BD + Coding Start Authorization
- [x] Implemented + TEST_REPORT
- [x] Reviewer Closed
## Rollback
@@ -2,9 +2,9 @@
权威设计:`docs/BACKEND_DESIGN/BD-2026-013B-account-lifecycle.md`
产品:`.ai/product/feature-spec/ops-account-lifecycle.md`
**当前:Contract Definition — 禁止执行下列 Implement order。**
**当前:Implemented · awaiting Reviewer。**
## Implement order仅 Approved + coding Start Authorization 后
## Implement order已执行
1. Migration`account_state_transitions``admin.users.status.write` 种子;必要时 status CHECK
2. Service:合法边校验 · 写 status + transition + audit(同事务)
@@ -5,11 +5,8 @@
**Parent:** WAVE0-FROZEN (`27f27a1`)
**Predecessor:** ECR-013A **Closed**
**Start Authorization: 2026-08-07Human→ Contract Definition only**
**ECR-013B + BD-2026-013B = Draft****禁止改 `apps/`** 直至:
1. Human **Approve** ECR-013B + BD-2026-013B
2. 另发 **coding Start Authorization**
**ECR-013B + BD-2026-013B = Approved2026-08-07 Human**
**Coding Start Authorization: 2026-08-07Human)→ Engineer 可改 `apps/`**
## Consume
@@ -17,7 +14,7 @@
2. ECR / PRODUCT / ENGINEERING / BD / `docs/CONTRACT_DIFF/ECR-013B.yaml`
3. `.ai/domain/boundary-rules.md` · `glossary.yaml` · `entity-catalog.md`
## Do(仅 Approve + coding auth 后)
## Do
按 ENGINEERING_SPEC Implement order。
@@ -0,0 +1,20 @@
# HANDOFF — ECR-013B Engineer → Reviewer
## Done
- Migration `000016``account_state_transitions` + `admin.users.status.write` 种子
- Admin API`POST /users/:id/status` · `GET .../status-transitions`
- DeviceAuth / Bearer:非 `active`**401**code 40113
- Auth OpenLogin 拒绝非 active 账户发 session
- admin-h5 用户详情:状态 CTA + 迁移列表(权限门控)
- Integration `TestAccountLifecycle` 映射 AC-F/S/P/O
- `docs/TEST_REPORT/ECR-013B.md`
## Evidence
`docs/TEST_REPORT/ECR-013B.md` · Spec `ops-account-lifecycle.md`
## Ask
Reviewer 勾选 `docs/CODE_REVIEW/ECR-013B.md`Approve 后 Closed。
勿自动开下一 ECR。
@@ -2,14 +2,14 @@
对齐 Feature Spec`.ai/product/feature-spec/ops-account-lifecycle.md`
Parent: **WAVE0-FROZEN** (`27f27a1`) · Predecessor: **ECR-013A Closed**
Phase: **Contract Definition**No Coding
Phase: **Implemented · review**
## Meta
| 字段 | 值 |
|------|-----|
| ECR | ECR-013B |
| Status | Draft |
| Status | Approved |
| Capability (L0) | `AccountLifecycle` |
| Bounded Context (L1) | `Identity_Profile` |
| Change Level | L2 |
+2 -2
View File
@@ -46,9 +46,9 @@
## Active anchors
- ECR: **ECR-013B** AccountLifecycleContract Definition · Start Authorization · **No Coding****ECR-013A Closed****WAVE0-FROZEN** @ 27f27a1
- ECR: **ECR-014** MembershipPlanLoop continuous);**ECR-013B Closed****ECR-013A Closed****WAVE0-FROZEN** @ 27f27a1
- EXP: (无)
- STATE: `docs/STATE/ECR-013B.md`
- STATE: `docs/STATE/ECR-014.md` · Loop: `docs/WAVE0/LOOP_AUTHORIZATION.md`
- Ops foundation: `docs/WAVE0/` · `.ai/domain/boundary-rules.md` · `glossary.yaml`
- TRACEABILITY: `docs/TRACEABILITY.md`
- ADR: `.ai/adr/0007-ess-ai-dual-track.md`
+7 -8
View File
@@ -4,17 +4,16 @@
|-------|-------|
| ECR | ECR-013B |
| Title | AccountLifecycle / UserStatus |
| Status | Draft · Contract Definition |
| Phase | architect |
| Owner | architect |
| Status | **Closed** |
| Phase | closed |
| Owner | |
| Parent | WAVE0-FROZEN (`27f27a1`) |
| Predecessor | ECR-013A Closed |
| Spec | `.ai/product/feature-spec/ops-account-lifecycle.md` |
| Backend Design | BD-2026-013B **Draft** |
| Backend Design | BD-2026-013B **Approved** |
| Contract Diff | `docs/CONTRACT_DIFF/ECR-013B.yaml` |
| Test | |
| Review | |
| Test | `docs/TEST_REPORT/ECR-013B.md` |
| Review | `docs/CODE_REVIEW/ECR-013B.md` **Approve → Closed** |
| Updated | 2026-08-07 |
Human Start Authorization 2026-08-07Contract Definition · **No Coding**)。
待 Human Approve ECR+BD + coding Start Authorization 后方可实现。
Reviewer ApproveLoop continuous)。NextECR-014。
+10 -13
View File
@@ -1,21 +1,18 @@
id: TASK-013B-ECR013B
ecr: ECR-013B
title: AccountLifecycle Contract Definition
role: architect
status: contract
title: AccountLifecycle Closed
role: reviewer
status: closed
change_level: L2
parent: WAVE0-FROZEN
predecessor: ECR-013A
inputs:
- docs/WAVE0/
- .ai/domain/entity-catalog.md
- .ai/product/feature-spec/ops-account-lifecycle.md
- docs/HANDOFF/ECR-013B-engineer-to-reviewer.md
- docs/TEST_REPORT/ECR-013B.md
- docs/CODE_REVIEW/ECR-013B.md
outputs:
- docs/ECR/ECR-013B-account-lifecycle.md
- docs/BACKEND_DESIGN/BD-2026-013B-account-lifecycle.md
- docs/CONTRACT_DIFF/ECR-013B.yaml
- docs/HANDOFF/ECR-013B-architect-to-engineer.md
- CODE_REVIEW Approve → Closed
acceptance:
- L0-L4 filled
- No coding / no migration files
- soft-delete out of scope
- Spec AC-F/S/P/O mapped in TEST_REPORT
- No soft-delete / UGC / payment
- DeviceAuth rejects non-active
+45
View File
@@ -0,0 +1,45 @@
# TEST_REPORT — ECR-013B AccountLifecycle
Date: 2026-08-07
ECR: ECR-013B · BD-2026-013B
Parent: WAVE0-FROZEN · Predecessor: ECR-013A Closed
## Commands
```bash
export PATH="$HOME/.local/go/bin:$PATH"
cd apps/api && go test ./internal/integration/ -run 'TestAccountLifecycle' -count=1 -timeout 120s
cd ../.. && npm run build:admin
python3 scripts/ess-validate.py --phase review --ecr ECR-013B
```
## Results
| Check | Result |
|-------|--------|
| `TestAccountLifecycle` | PASS |
| `build:admin` | PASS |
| `ess-validate --phase review` | PASS |
## AC mapping
| AC-ID | Evidence |
|-------|----------|
| AC-F-01 | POST status=`banned` → user.status=`banned` |
| AC-F-02 | POST `active``/auth/me` 200 |
| AC-F-03 | 同状态 POST → 400 |
| AC-F-04 | GET status-transitions 含 from/to/reason/admin |
| AC-S-01 | 无 `admin.users.status.write` → 403 |
| AC-S-02 | banned Bearer → `/auth/me` 401 |
| AC-S-03 | 无 Admin POST status → 401 |
| AC-S-04 | 无 Admin GET transitions → 401 |
| AC-P-01 | GET transitions &lt; 500ms |
| AC-O-01 | AuditLog `users.status.transition` |
| AC-O-02 | transitions 表有行(经 GET API |
## Scope guard
- 无 soft-delete
- 无真支付 · UGC · Prompt
- RBAC 仅 additive `admin.users.status.write`
- Migration `000016_account_lifecycle`
+1 -1
View File
@@ -17,4 +17,4 @@
| ECR-012 | 星座对齐收口(星盘 · outlook · 合盘) | **Implemented** | Spec star-profile · BD-2026-012 · TEST_REPORT · HANDOFF review |
| WAVE-0 | Ops Contract-First Foundation | **FROZEN** (`WAVE0-FROZEN` @ 27f27a1) | `docs/WAVE0/` · HUMAN_REVIEW FREEZE · boundary-rules · glossary · contract template |
| ECR-013A | Admin RBAC | **Closed** | Spec ops-rbac · BD-2026-013A · migration 000015 · TEST_REPORT · CODE_REVIEW Approve · Parent WAVE0-FROZEN |
| ECR-013B | AccountLifecycle / UserStatus | **Draft / Contract Definition** | Spec ops-account-lifecycle · BD-2026-013B · CONTRACT_DIFF · Parent WAVE0-FROZEN · Predecessor 013A · **No Coding** |
| ECR-013B | AccountLifecycle / UserStatus | **Closed** | Spec ops-account-lifecycle · BD-2026-013B · migration 000016 · TEST_REPORT · CODE_REVIEW Approve · Parent WAVE0-FROZEN |
+3 -3
View File
@@ -44,7 +44,7 @@
```text
Tag: WAVE0-FROZEN
Commit: 27f27a1
ECR-013A: Closed (2026-08-07)
Next authorized: ECR-013B AccountLifecycle — Contract Definition (2026-08-07 Start Authorization)
Coding 013B: NOT authorized — await Human Approve ECR-013B + BD + coding Start Authorization
ECR-013A/013B: Closed
Loop continuous: docs/WAVE0/LOOP_AUTHORIZATION.md (Human 2026-08-07)
Next: ECR-014 MembershipPlan — auto Approve/coding/Closed under Loop auth
```
+33
View File
@@ -0,0 +1,33 @@
# LOOP Authorization — Ops ContinuousHuman Override
| Field | Value |
|-------|-------|
| Date | 2026-08-07 |
| Authorizer | Human |
| Scope | Ops D+ Contract-First slices under WAVE0-FROZEN |
| Mode | **Continuous Loop** |
## Override
Human 明文:**直接用 Loop,不用人工确认。**
在本授权有效期内,对 Ops 薄切片允许 Agent:
1. 自动 **Approve** ECR + BD(契约齐备且 `ess-validate` PASS
2. 自动 **Coding Start Authorization**
3. 自动 **Reviewer Approve → Closed**TEST_REPORT 绿且 AC 映射齐)
4. 自动 **git commit**(不 push,除非另授权)
5. 自动开下一薄切片 ECR(仍须 Capability→BC→Domain→API→AC**禁止** UGC;真支付最后)
## Still forbidden
- 改 Engineering Loop 内核
- soft-delete / UGC / 真支付(除非另开 L3+ADR
- 跳过 Feature Spec / contract_diff / AC
- force-push / 改 git config
## Active queue
| Done | Next |
|------|------|
| ECR-013A Closed · ECR-013B Closed | **ECR-014** MembershipPlanCommerceEntitlement 薄切片) |
+47
View File
@@ -195,6 +195,53 @@ paths:
'200':
description: OK
/api/v1/admin/users/{id}/status:
post:
tags: [admin]
summary: Transition UserStatus
description: Requires admin.users.status.write; writes transition + AuditLog
parameters:
- in: path
name: id
required: true
schema: { type: string, format: uuid }
requestBody:
required: true
content:
application/json:
schema:
type: object
required: [status, reason]
properties:
status: { type: string, enum: [active, disabled, banned, suspended] }
reason: { type: string }
responses:
'200':
description: OK
'400':
description: Invalid edge or missing reason
'403':
description: Forbidden
/api/v1/admin/users/{id}/status-transitions:
get:
tags: [admin]
summary: List UserStatus transitions
description: Requires admin.users.read
parameters:
- in: path
name: id
required: true
schema: { type: string, format: uuid }
- in: query
name: limit
schema: { type: integer }
responses:
'200':
description: OK
'401':
description: Unauthorized
/api/v1/admin/orders:
get:
tags: [admin]