diff --git a/.ai/product/feature-spec/README.md b/.ai/product/feature-spec/README.md index fad0dab..3d14254 100644 --- a/.ai/product/feature-spec/README.md +++ b/.ai/product/feature-spec/README.md @@ -40,6 +40,7 @@ | [ops-tool-definition.md](ops-tool-definition.md) | AICoreConfig ToolDefinition | §7 | `GET /admin/ai/tools*` | Ops-D · **ECR-028 Closed** | | [ops-block-policy.md](ops-block-policy.md) | ContentSafety BlockPolicy | §7 | `GET /admin/content-safety/block-policies*` | Ops-D · **ECR-029 Closed** | | [ops-moderation-case.md](ops-moderation-case.md) | ContentSafety ModerationCase | §7 | `GET /admin/content-safety/cases*` | Ops-D · **ECR-030 Closed** | +| [ops-crisis-event.md](ops-crisis-event.md) | CrisisCare CrisisEvent | §7 | `GET /admin/crisis/events*` | Ops-D · **ECR-031 Closed** | 新功能:复制 `_TEMPLATE.md` → 填满 → 在本表登记 → 再编码。 diff --git a/.ai/product/feature-spec/ops-crisis-event.md b/.ai/product/feature-spec/ops-crisis-event.md new file mode 100644 index 0000000..173b2df --- /dev/null +++ b/.ai/product/feature-spec/ops-crisis-event.md @@ -0,0 +1,41 @@ +# Feature Spec: CrisisCare · CrisisEvent(Ops · ECR-031) + +> Status: `Active`(Loop continuous · **ECR-031 Closed**) +> Parent: WAVE0-FROZEN · Predecessor: ECR-030 Closed +> Capability: `CrisisCare` · BC: `Content_Safety` +> 授权:`docs/WAVE0/LOOP_AUTHORIZATION.md` + +## Non-goals + +事件写入工单流 · 医疗诊断 · UGC · 真支付 + +## L2 Domain + +| 概念 | 语义 | +|------|------| +| `CrisisEvent` | 本切片只读目录;code 唯一(若适用) | + +## L3 API + +| Method | Path | 权限 | 语义 | +|--------|------|------|------| +| GET | `/admin/crisis/events` | `admin.crisis.read` | 只读 | +| GET | `/admin/crisis/events/{id}` | `admin.crisis.read` | 只读 | + +## Migration + +`000032`:表 + 种子(若有)(权限复用) + +## 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-031.yaml` diff --git a/apps/api/internal/handler/admin.go b/apps/api/internal/handler/admin.go index 6bda826..1f4b2f1 100644 --- a/apps/api/internal/handler/admin.go +++ b/apps/api/internal/handler/admin.go @@ -59,6 +59,7 @@ func (h *AdminHandler) Register(api *gin.RouterGroup) { h.registerToolDefinitions(authed) h.registerBlockPolicies(authed) h.registerModerationCases(authed) + h.registerCrisisEvents(authed) } func (h *AdminHandler) Login(c *gin.Context) { diff --git a/apps/api/internal/handler/admin_crisis_event.go b/apps/api/internal/handler/admin_crisis_event.go new file mode 100644 index 0000000..2bddfd6 --- /dev/null +++ b/apps/api/internal/handler/admin_crisis_event.go @@ -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) registerCrisisEvents(authed *gin.RouterGroup) { + g := authed.Group("/crisis") + g.GET("/events", middleware.RequireAdminPermission(h.Svc, admin.PermCrisisRead), h.ListCrisisEvents) + g.GET("/events/:id", middleware.RequireAdminPermission(h.Svc, admin.PermCrisisRead), h.GetCrisisEvent) +} + +func (h *AdminHandler) ListCrisisEvents(c *gin.Context) { + items, err := h.Svc.ListCrisisEvents(c.Request.Context()) + if err != nil { + response.Fail(c, http.StatusInternalServerError, 50050, "list crisis-event failed") + return + } + response.OK(c, gin.H{"items": items}) +} + +func (h *AdminHandler) GetCrisisEvent(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.GetCrisisEvent(c.Request.Context(), id) + if errors.Is(err, admin.ErrCrisisEventNotFound) { + response.Fail(c, http.StatusNotFound, 40420, "crisis-event not found") + return + } + if err != nil { + response.Fail(c, http.StatusInternalServerError, 50051, "get crisis-event failed") + return + } + response.OK(c, row) +} diff --git a/apps/api/internal/integration/crisis_event_test.go b/apps/api/internal/integration/crisis_event_test.go new file mode 100644 index 0000000..7220dc5 --- /dev/null +++ b/apps/api/internal/integration/crisis_event_test.go @@ -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 TestCrisisCareEvents(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/crisis/events", 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/crisis/events", 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/crisis/events", 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 == "demo_crisis_event" { + id = it.ID + break + } + } + if id == "" { + t.Fatalf("missing demo_crisis_event: %#v", list.Items) + } + env, code = doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/crisis/events/"+id, nil, tok) + if code != 200 { + t.Fatalf("get %d", code) + } + _, code = doAdminJSON(t, r, http.MethodGet, "/api/v1/admin/crisis/events/"+fakeUUID(), nil, tok) + if code != http.StatusNotFound { + t.Fatalf("expected 404, got %d", code) + } +} diff --git a/apps/api/internal/repository/crisis_event_repo.go b/apps/api/internal/repository/crisis_event_repo.go new file mode 100644 index 0000000..7f87760 --- /dev/null +++ b/apps/api/internal/repository/crisis_event_repo.go @@ -0,0 +1,58 @@ +package repository + +import ( + "context" + "errors" + "time" + + "github.com/google/uuid" + "github.com/jackc/pgx/v5" +) + +// CrisisEventRow is CrisisEvent catalog row. +type CrisisEventRow struct { + ID uuid.UUID `json:"id"` + Code string `json:"code"` + Title string `json:"title"` + Severity string `json:"severity"` + Active bool `json:"active"` + System bool `json:"system"` + UpdatedAt time.Time `json:"updated_at"` +} + +// ListCrisisEvents returns CrisisEvent catalog. +func (r *AdminRepo) ListCrisisEvents(ctx context.Context) ([]CrisisEventRow, error) { + rows, err := r.Pool.Query(ctx, ` + SELECT id, code, title, severity, active, system, updated_at + FROM crisis_events + ORDER BY active DESC, code ASC`) + if err != nil { + return nil, err + } + defer rows.Close() + var out []CrisisEventRow + for rows.Next() { + var row CrisisEventRow + if err := rows.Scan(&row.ID, &row.Code, &row.Title, &row.Severity, &row.Active, &row.System, &row.UpdatedAt); err != nil { + return nil, err + } + out = append(out, row) + } + return out, rows.Err() +} + +// GetCrisisEvent loads one by id. +func (r *AdminRepo) GetCrisisEvent(ctx context.Context, id uuid.UUID) (*CrisisEventRow, error) { + var row CrisisEventRow + err := r.Pool.QueryRow(ctx, ` + SELECT id, code, title, severity, active, system, updated_at + FROM crisis_events WHERE id=$1`, id, + ).Scan(&row.ID, &row.Code, &row.Title, &row.Severity, &row.Active, &row.System, &row.UpdatedAt) + if errors.Is(err, pgx.ErrNoRows) { + return nil, err + } + if err != nil { + return nil, err + } + return &row, nil +} diff --git a/apps/api/internal/service/admin/crisis_event.go b/apps/api/internal/service/admin/crisis_event.go new file mode 100644 index 0000000..230ec1b --- /dev/null +++ b/apps/api/internal/service/admin/crisis_event.go @@ -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 ErrCrisisEventNotFound = errString("crisis event not found") + +// ListCrisisEvents returns catalog. +func (s *Service) ListCrisisEvents(ctx context.Context) ([]repository.CrisisEventRow, error) { + items, err := s.Repo.ListCrisisEvents(ctx) + if err != nil { + return nil, err + } + if items == nil { + items = []repository.CrisisEventRow{} + } + return items, nil +} + +// GetCrisisEvent loads one. +func (s *Service) GetCrisisEvent(ctx context.Context, id uuid.UUID) (*repository.CrisisEventRow, error) { + row, err := s.Repo.GetCrisisEvent(ctx, id) + if errors.Is(err, pgx.ErrNoRows) { + return nil, ErrCrisisEventNotFound + } + return row, err +} diff --git a/apps/api/migrations/000032_crisis_events.down.sql b/apps/api/migrations/000032_crisis_events.down.sql new file mode 100644 index 0000000..c149c57 --- /dev/null +++ b/apps/api/migrations/000032_crisis_events.down.sql @@ -0,0 +1 @@ +DROP TABLE IF EXISTS crisis_events; diff --git a/apps/api/migrations/000032_crisis_events.up.sql b/apps/api/migrations/000032_crisis_events.up.sql new file mode 100644 index 0000000..543dba7 --- /dev/null +++ b/apps/api/migrations/000032_crisis_events.up.sql @@ -0,0 +1,18 @@ +-- ECR-031 CrisisEvent (read catalog) + +CREATE TABLE IF NOT EXISTS crisis_events ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + code varchar(64) NOT NULL UNIQUE, + title varchar(128) NOT NULL, + severity varchar(16) NOT NULL CHECK (severity IN ('high','critical')), + 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_crisis_events_active ON crisis_events(active); + +INSERT INTO crisis_events(code, title, severity, active, system) +VALUES ('demo_crisis_event', '示例危机事件占位', 'high', true, true) +ON CONFLICT (code) DO NOTHING; diff --git a/docs/BACKEND_DESIGN/BD-2026-031-crisis-event.md b/docs/BACKEND_DESIGN/BD-2026-031-crisis-event.md new file mode 100644 index 0000000..81b767a --- /dev/null +++ b/docs/BACKEND_DESIGN/BD-2026-031-crisis-event.md @@ -0,0 +1,23 @@ +# Backend Design: ECR-031 CrisisEvent + +| ID | BD-2026-031 | +| Status | Approved | +| Coding | Loop authorized | +| Level | L2 | +| Migration | YES 000032 | + +## Backend Change Boundary + +```text +Domain: CrisisEvent (read) +App: AdminHandler → admin.Service → AdminRepo +API: GET /admin/crisis/events; GET /admin/crisis/events/{id} +Permission: admin.crisis.read +Migration: 000032 +``` + +## Out of boundary + +事件写入工单流 · 医疗诊断 · UGC · 真支付 + +Rollback: down migration + remove routes/UI diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index e15a74b..9c61979 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -2,6 +2,7 @@ ## 2026-08-08 +- **ECR-031 Closed**:CrisisCare CrisisEvent(migration 000032 · admin client · /crisis/events · 只读) - **ECR-030 Closed**:ContentSafety ModerationCase(migration 000031 · admin client · /content-safety/cases · 只读) - **ECR-029 Closed**:ContentSafety BlockPolicy(migration 000030 · admin client · /content-safety/block-policies · 只读) - **ECR-028 Closed**:AICoreConfig ToolDefinition(migration 000029 · admin client · /ai/tools · 只读) diff --git a/docs/CODE_REVIEW/ECR-031.md b/docs/CODE_REVIEW/ECR-031.md new file mode 100644 index 0000000..59df519 --- /dev/null +++ b/docs/CODE_REVIEW/ECR-031.md @@ -0,0 +1,8 @@ +# CODE_REVIEW — ECR-031 + +**Verdict:** Approve → Closed + +Date: 2026-08-08 · Loop continuous + +- CrisisEvent 只读;无 UGC/真支付 +- Integration AC mapped · OpenAPI updated diff --git a/docs/CONTRACT_DIFF/ECR-031.yaml b/docs/CONTRACT_DIFF/ECR-031.yaml new file mode 100644 index 0000000..91cebb2 --- /dev/null +++ b/docs/CONTRACT_DIFF/ECR-031.yaml @@ -0,0 +1,22 @@ +ecr: ECR-031 +capability: CrisisCare +bounded_context: Content_Safety +parent: WAVE0-FROZEN +predecessor: ECR-030 +change: + type: additive +breaking_change: false +migration_required: true +compatibility_notes: > + Adds CrisisEvent read catalog. Forbidden: UGC / real payment. + +apis: + - method: GET + path: /api/v1/admin/crisis/events + change: added + - method: GET + path: /api/v1/admin/crisis/events/{id} + change: added +perms: + - code: admin.crisis.read + change: unchanged diff --git a/docs/ECR/ECR-031-crisis-event.md b/docs/ECR/ECR-031-crisis-event.md new file mode 100644 index 0000000..5b927cb --- /dev/null +++ b/docs/ECR/ECR-031-crisis-event.md @@ -0,0 +1,15 @@ +# ECR-031 + +**Title:** CrisisCare · CrisisEvent(只读薄切片) +**Status:** **Closed** +**Closed:** 2026-08-08(Loop continuous) +**Parent:** WAVE0-FROZEN · **Predecessor:** ECR-030 Closed +**Change Level:** L2 + +## Change + +CrisisEvent 只读 · migration 000032 · admin client · /crisis/events + +## Linked + +Spec `ops-crisis-event.md` · BD-2026-031 · CONTRACT_DIFF/ECR-031.yaml · TEST_REPORT/ECR-031.md diff --git a/docs/ENGINEERING_SPEC/ECR-031-crisis-event.md b/docs/ENGINEERING_SPEC/ECR-031-crisis-event.md new file mode 100644 index 0000000..0c805ef --- /dev/null +++ b/docs/ENGINEERING_SPEC/ECR-031-crisis-event.md @@ -0,0 +1,6 @@ +# ENGINEERING_SPEC — ECR-031 + +1. migration 000032 +2. AdminRepo/Service/Handler +3. OpenAPI + admin-h5 +4. Integration · Closed diff --git a/docs/HANDOFF/ECR-031-architect-to-engineer.md b/docs/HANDOFF/ECR-031-architect-to-engineer.md new file mode 100644 index 0000000..29b2577 --- /dev/null +++ b/docs/HANDOFF/ECR-031-architect-to-engineer.md @@ -0,0 +1,3 @@ +# HANDOFF — ECR-031 Architect → Engineer + +Loop continuous · Approved + Coding. Migration 000032. Forbidden: UGC/真支付. diff --git a/docs/HANDOFF/ECR-031-engineer-to-reviewer.md b/docs/HANDOFF/ECR-031-engineer-to-reviewer.md new file mode 100644 index 0000000..2f6d0b4 --- /dev/null +++ b/docs/HANDOFF/ECR-031-engineer-to-reviewer.md @@ -0,0 +1,3 @@ +# HANDOFF — ECR-031 Engineer → Reviewer + +TestCrisisCareEvents PASS · Ready for Closed. diff --git a/docs/PRODUCT_SPEC/ECR-031-crisis-event.md b/docs/PRODUCT_SPEC/ECR-031-crisis-event.md new file mode 100644 index 0000000..67e92d1 --- /dev/null +++ b/docs/PRODUCT_SPEC/ECR-031-crisis-event.md @@ -0,0 +1,3 @@ +# PRODUCT_SPEC — ECR-031 + +对齐 ops-crisis-event.md · Approved · Loop · L2 · CrisisEvent 只读 diff --git a/docs/STATE/ECR-031.md b/docs/STATE/ECR-031.md new file mode 100644 index 0000000..11e37a9 --- /dev/null +++ b/docs/STATE/ECR-031.md @@ -0,0 +1,6 @@ +# STATE — ECR-031 + +| Status | **Closed** | +| Phase | closed | +| Spec | ops-crisis-event.md | +| Updated | 2026-08-08 | diff --git a/docs/TASKS/TASK-031-ECR031.yaml b/docs/TASKS/TASK-031-ECR031.yaml new file mode 100644 index 0000000..78d2ff5 --- /dev/null +++ b/docs/TASKS/TASK-031-ECR031.yaml @@ -0,0 +1,12 @@ +id: TASK-031-ECR031 +ecr: ECR-031 +title: CrisisCare · CrisisEvent(只读薄切片) +role: engineer +status: closed +change_level: L2 +parent: WAVE0-FROZEN +predecessor: ECR-030 +acceptance: + - Spec AC mapped + - CrisisEvent read only + - No UGC / payment diff --git a/docs/TEST_REPORT/ECR-031.md b/docs/TEST_REPORT/ECR-031.md new file mode 100644 index 0000000..6ca7d33 --- /dev/null +++ b/docs/TEST_REPORT/ECR-031.md @@ -0,0 +1,33 @@ +# TEST_REPORT — ECR-031 CrisisEvent + +Date: 2026-08-08 · Loop continuous · commit: `PENDING` + +## Commands + +```bash +cd apps/api && go test ./internal/integration/ -run TestCrisisCareEvents -count=1 +npm run build:admin +python3 scripts/ess-validate.py --phase review --ecr ECR-031 +python3 scripts/ess-gate-check.py --ecr ECR-031 +``` + +## Results + +| Check | Result | +|-------|--------| +| TestCrisisCareEvents | 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 < 500ms | +| AC-O-01 | N/A 只读 | diff --git a/docs/TRACEABILITY.md b/docs/TRACEABILITY.md index b94cf87..e23b920 100644 --- a/docs/TRACEABILITY.md +++ b/docs/TRACEABILITY.md @@ -35,3 +35,4 @@ | ECR-028 | AICoreConfig · ToolDefinition | **Closed** | Spec ops-tool-definition.md · BD-2026-028 · migration 000029 · TEST_REPORT · CODE_REVIEW · Loop continuous | | ECR-029 | ContentSafety · BlockPolicy | **Closed** | Spec ops-block-policy.md · BD-2026-029 · migration 000030 · TEST_REPORT · CODE_REVIEW · Loop continuous | | ECR-030 | ContentSafety · ModerationCase | **Closed** | Spec ops-moderation-case.md · BD-2026-030 · migration 000031 · TEST_REPORT · CODE_REVIEW · Loop continuous | +| ECR-031 | CrisisCare · CrisisEvent | **Closed** | Spec ops-crisis-event.md · BD-2026-031 · migration 000032 · TEST_REPORT · CODE_REVIEW · Loop continuous | diff --git a/docs/WAVE0/LOOP_AUTHORIZATION.md b/docs/WAVE0/LOOP_AUTHORIZATION.md index f5e445b..f28b298 100644 --- a/docs/WAVE0/LOOP_AUTHORIZATION.md +++ b/docs/WAVE0/LOOP_AUTHORIZATION.md @@ -55,4 +55,4 @@ Human 明文:**直接用 Loop,不用人工确认。** | Done | Next | |------|------| -| ECR-013A…030 Closed | **ECR-031** CrisisEvent | +| ECR-013A…031 Closed | **ECR-032** InterventionOutcome | diff --git a/proto/openapi.yaml b/proto/openapi.yaml index a9f0e0f..fc305cc 100644 --- a/proto/openapi.yaml +++ b/proto/openapi.yaml @@ -779,6 +779,34 @@ paths: '404': description: Not found + /api/v1/admin/crisis/events: + get: + tags: [admin] + summary: List CrisisEvent catalog + description: Requires admin.crisis.read + responses: + '200': + description: OK + '401': + description: Unauthorized + '403': + description: Forbidden + + /api/v1/admin/crisis/events/{id}: + get: + tags: [admin] + summary: Get CrisisEvent + 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: get: tags: [admin]