feat(release): 批量审核 + 建批即锁定 —— 发布管理单文档交互降到 3~4 次

P0-3:
- 批量审核:新增 POST /api/v1/review-candidates/batch-decision,逐条复用单条审核的写入
  路径(同一套合法性校验与"最新验收轮次"绑定),逐条回报 decided/skipped/skipped_ids;
  不可审核的条目只计入 skipped,不打断整批,其他错误整批回滚(不留半成品)。
  界面新增「全选可批准」「批量批准选中」「批量驳回选中」。
- 建批即锁定:建批请求加 seal 字段,服务端在创建后立即执行既有的密封(仍逐项复核门禁,
  失败整批回滚),草稿态不再单独占一步;界面按钮改为「创建并锁定清单」,流程说明从 8 步改 7 步。
- 判据修正:「可批准」原先把已驳回的算进去(review_state !== 'approved'),改为只含 pending + 门禁通过。

语义边界(写进测试):批量批准按人工身份记录,人工可推翻自己先前的驳回;system:auto 发起的
批量批准对人工驳回过的那条必须跳过(Decided=0/Skipped=1)——机器永远不覆盖人工。

测试:review_batch_integration_test.go(批量决定/跳报/重复 id 拒绝/机器不覆盖人工、
建批即锁定)、review_batch_test.go(幂等键、400/409/500/501 映射、服务端盖操作人)、
reviewRelease.test.ts(批量请求体与逐条回报、建批带 seal)。前端 181 条通过。
This commit is contained in:
姚章浩
2026-10-10 15:29:31 +08:00
parent c83a6c8086
commit 70131c6161
15 changed files with 575 additions and 42 deletions
+28
View File
@@ -3224,6 +3224,34 @@
}
}
}
},
"/api/v1/review-candidates/batch-decision": {
"post": {
"tags": [
"Release"
],
"operationId": "batchReviewCandidates",
"summary": "一次对多条审核候选做同一个决定(批量批准/驳回,逐条复用单条写入路径)",
"parameters": [
{
"$ref": "#/components/parameters/IdempotencyKey"
}
],
"responses": {
"200": {
"$ref": "#/components/responses/Envelope"
},
"400": {
"$ref": "#/components/responses/BadRequest"
},
"409": {
"$ref": "#/components/responses/Conflict"
},
"500": {
"$ref": "#/components/responses/InternalError"
}
}
}
}
},
"components": {
+3 -2
View File
@@ -39,14 +39,15 @@ dws wiki +space-list --limit 1 -f json # 真实调用验证,期望 ok:true
- 路由到哪个测试库由 **系统设置 → 测试知识库绑定** 决定;`不需要` 不入库。
## 3. 发布准备:勾选 → 建批 → 锁定 **【变:P0-1 建批时冻结 + P0-2 自动批准】**
**发布管理** → 在「审核要发布的知识」里勾选(对内知识通常已由系统批准)→ 填批次名 → `创建草稿批次` → 锁定。
**发布管理** → 在「审核要发布的知识」里勾选(对内知识通常已由系统批准;未决定的可用「全选可批准」+「批量批准选中」一次批)→ 填批次名 → `创建并锁定清单`(一步完成,无需再点锁定)。
- **不再需要 `生成新版本` / `确认冻结`**:服务端在"建批这一下"把当前实时计划冻结成一份**已确认**版本并绑定该批次。
语义不变——批一旦建立,清单/摘要/验收轮次/目标库绑定全部不可变、回滚按它走;变的只是"谁在什么时候按固化键"。
- 同一份计划复用同一版本(摘要一致即复用),所以连续建批不会堆版本;计划变了才新建一版。
- **审核**:`TEST_AUTO_REVIEW_POLICY` = `off` | `internal`(默认,仅对内)| `all`。默认下**对内知识验收通过即由系统批准**
(审核记录 `reviewer_ref=system:auto`),对外仍需人工;策略可在容器环境变量调整,界面上只读展示当前值。
人工随时可驳回/改判;系统只允许写"第一条"审核,**永远不会覆盖人工结论**。
- 密封(锁定)后批次不可改;锁定后才能授权生产发布。锁定 ≠ 上线。
- 建批即锁定:清单在建批那一刻冻结并立即密封,批次不可再改;锁定后才能授权生产发布。锁定 ≠ 上线。
- 批量批准按**人工身份**记录(reviewer=当前登录人),人工可以推翻自己先前的驳回;系统自动批准(`system:auto`)永远只写第一条、不覆盖任何人工结论。
## 4. 待入库 → 处理 **【既有】**
文档工作台/待入库列表 → 选中 → `开始处理` → 上传 → 解析 → 索引 → `completed`。
+11
View File
@@ -164,6 +164,17 @@
- ⚠️ 过程中踩到并修掉 **Bug #6**(见 F.3h):禁止导入只写 `source_items.policy_state`,而**两处**"期望策略"解析
(计划 + 建批 delete 就绪判定)都不看它 → 计划不给 delete、建批直接 422
### C7 批量审核 + 建批即锁定 ★2026-10-10 实测(发布管理减负 P0-3)
- 界面:审核区块新增「全选可批准(N)」「批量批准选中(N)」「批量驳回选中(N)」;建批按钮改为「创建并锁定清单」。
- 证据(建批即锁定):勾选 2 条已批准 → 填名 → 一次点击 → 批次 `rb-95210ddcc14bbcb6afee323acd87b945`
(`验收-批量两项-20261010`)出来就是 **`sealed`**(2 项、`sealed_by=admin`),**没有单独的"锁定"这一步**;
且复用同一份冻结版本 `rcs-028ac704…`(计划摘要未变 → 同版本复用)。
- 判据修正:界面「可批准」原先把**已驳回**的也算进去(`review_state !== 'approved'`),已改为只含 `pending` + 门禁通过——
已驳回的不会被"全选"顺手翻回批准。
- 语义边界(集成测试固化):批量批准按人工身份写入,人工可推翻自己先前的驳回;
`system:auto` 发起的批量批准对人工驳回过的那条必须跳过(`Decided=0 / Skipped=1`)。
### C6 建批时冻结 + 自动批准 ★2026-10-10 实测(发布管理减负 P0-1 / P0-2)
- 期望:**不再有** `生成新版本` / `确认冻结` 两步;对内知识验收通过后由系统自动批准;建批即绑定一份已确认版本。
+5 -2
View File
@@ -38,9 +38,12 @@ type CreateReleaseBatchRequest struct {
PublicationIDs []string
DeletePublicationIDs []string
// ReleaseChangeSetID (R1): a formal batch must cite a CONFIRMED persistent
// release change set; empty keeps legacy ad-hoc batches draft-only.
// release change set. Empty means "freeze the live plan at bind time" (P0-1).
ReleaseChangeSetID string
Now time.Time
// SealImmediately (P0-3): 建批后立即锁定。清单在冻结时已不可变,草稿态只剩
// "查看/锁定"两个按钮,等于让操作员多按一次;锁定仍会逐项复核门禁。
SealImmediately bool
Now time.Time
}
type SealReleaseBatchRequest struct {
+20
View File
@@ -57,6 +57,26 @@ type PublicationReview struct {
CreatedAt time.Time `json:"created_at"`
}
// ReviewPublicationsBatchRequest 一次对多条候选做同一个审核决定(批量批准/驳回)。
type ReviewPublicationsBatchRequest struct {
PublicationIDs []string
Decision ReviewState
DecidedVisibility Visibility
DecisionCode string
ReviewerRef string
Now time.Time
}
// ReviewPublicationsBatchResult 逐条结果:Decided 是真正写入的,SkippedIDs 是那时不可审核的。
// 跳过的条目绝不静默——界面要能说清"哪几条没批成、为什么"。
type ReviewPublicationsBatchResult struct {
Selected int `json:"selected"`
Decided int `json:"decided"`
Skipped int `json:"skipped"`
SkippedIDs []string `json:"skipped_ids"`
Reviews []PublicationReview `json:"reviews"`
}
type ReviewPublicationRequest struct {
PublicationID string
Decision ReviewState
+118
View File
@@ -0,0 +1,118 @@
package httpapi
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"knowledge-governance/internal/governance"
"knowledge-governance/internal/platform/postgres"
)
// reviewBatchFakeStore:在既有 fakeJobStore 之上补出批量审核能力,验证批量端点的
// 幂等键要求、逐条结果回报与错误映射。
type reviewBatchFakeStore struct {
fakeJobStore
captured governance.ReviewPublicationsBatchRequest
result governance.ReviewPublicationsBatchResult
replayed bool
err error
}
func (s *reviewBatchFakeStore) ReviewPublicationsBatchWithOperation(_ context.Context, request governance.ReviewPublicationsBatchRequest, _ string) (governance.ReviewPublicationsBatchResult, bool, error) {
s.captured = request
return s.result, s.replayed, s.err
}
func TestBatchReviewCandidatesHandler(t *testing.T) {
store := &reviewBatchFakeStore{result: governance.ReviewPublicationsBatchResult{Selected: 3, Decided: 2, Skipped: 1, SkippedIDs: []string{"tp-c"}, Reviews: []governance.PublicationReview{}}}
handler, err := NewHandler(Config{Store: store})
if err != nil {
t.Fatal(err)
}
// 缺幂等键:写路由一律要求。
missing := httptest.NewRecorder()
handler.ServeHTTP(missing, httptest.NewRequest(http.MethodPost, "/api/v1/review-candidates/batch-decision", strings.NewReader(`{"publication_ids":["tp-a"],"decision":"approved","decided_visibility":"internal","decision_code":"approved_for_release"}`)))
if missing.Code != http.StatusBadRequest {
t.Fatalf("missing idempotency key status=%d", missing.Code)
}
// 空选择:直接拒绝。
empty := httptest.NewRecorder()
emptyRequest := httptest.NewRequest(http.MethodPost, "/api/v1/review-candidates/batch-decision", strings.NewReader(`{"publication_ids":[],"decision":"approved","decided_visibility":"internal","decision_code":"approved_for_release"}`))
emptyRequest.Header.Set("Idempotency-Key", "op-batch-1")
handler.ServeHTTP(empty, emptyRequest)
if empty.Code != http.StatusBadRequest {
t.Fatalf("empty selection status=%d", empty.Code)
}
// 正常:逐条结果原样回报,操作人由服务端盖章。
ok := httptest.NewRecorder()
okRequest := httptest.NewRequest(http.MethodPost, "/api/v1/review-candidates/batch-decision", strings.NewReader(`{"publication_ids":["tp-a","tp-b","tp-c"],"decision":"approved","decided_visibility":"internal","decision_code":"approved_for_release"}`))
okRequest.Header.Set("Idempotency-Key", "op-batch-2")
handler.ServeHTTP(ok, okRequest)
if ok.Code != http.StatusOK {
t.Fatalf("batch review status=%d body=%s", ok.Code, ok.Body.String())
}
var body struct {
Data struct {
Selected int `json:"selected"`
Decided int `json:"decided"`
Skipped int `json:"skipped"`
SkippedIDs []string `json:"skipped_ids"`
} `json:"data"`
}
if err := json.Unmarshal(ok.Body.Bytes(), &body); err != nil {
t.Fatal(err)
}
if body.Data.Decided != 2 || body.Data.Skipped != 1 || len(body.Data.SkippedIDs) != 1 || body.Data.SkippedIDs[0] != "tp-c" {
t.Fatalf("batch result=%#v", body.Data)
}
if store.captured.ReviewerRef == "" {
t.Fatal("reviewer must be stamped by the server")
}
// 错误映射。
for _, testCase := range []struct {
name string
err error
status int
}{
{"invalid", postgres.ErrInvalidPublicationReview, http.StatusBadRequest},
{"conflict", postgres.ErrOperationRequestConflict, http.StatusConflict},
{"unexpected", errors.New("boom"), http.StatusInternalServerError},
} {
failing := &reviewBatchFakeStore{err: testCase.err}
failingHandler, err := NewHandler(Config{Store: failing})
if err != nil {
t.Fatal(err)
}
recorder := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodPost, "/api/v1/review-candidates/batch-decision", strings.NewReader(`{"publication_ids":["tp-a"],"decision":"approved","decided_visibility":"internal","decision_code":"approved_for_release"}`))
request.Header.Set("Idempotency-Key", "op-batch-3")
failingHandler.ServeHTTP(recorder, request)
if recorder.Code != testCase.status {
t.Fatalf("%s status=%d want=%d", testCase.name, recorder.Code, testCase.status)
}
}
// 未接线:诚实 501。
unwired, err := NewHandler(Config{Store: storeWithoutReviewBatch{Store: store}})
if err != nil {
t.Fatal(err)
}
unwiredRecorder := httptest.NewRecorder()
unwiredRequest := httptest.NewRequest(http.MethodPost, "/api/v1/review-candidates/batch-decision", strings.NewReader(`{"publication_ids":["tp-a"],"decision":"approved","decided_visibility":"internal","decision_code":"approved_for_release"}`))
unwiredRequest.Header.Set("Idempotency-Key", "op-batch-4")
unwired.ServeHTTP(unwiredRecorder, unwiredRequest)
if unwiredRecorder.Code != http.StatusNotImplemented {
t.Fatalf("unwired status=%d", unwiredRecorder.Code)
}
}
type storeWithoutReviewBatch struct{ Store }
+57 -1
View File
@@ -375,6 +375,9 @@ func NewHandler(config Config) (http.Handler, error) {
mux.HandleFunc("GET /api/v1/review-candidates", func(w http.ResponseWriter, r *http.Request) {
listReviewCandidates(w, r, config.Store)
})
mux.HandleFunc("POST /api/v1/review-candidates/batch-decision", func(w http.ResponseWriter, r *http.Request) {
batchReviewCandidates(w, r, config)
})
mux.HandleFunc("POST /api/v1/review-candidates/{id}/decision", func(w http.ResponseWriter, r *http.Request) {
reviewPublication(w, r, config)
})
@@ -1504,6 +1507,56 @@ type createReleaseBatchRequest struct {
PublicationIDs []string `json:"publication_ids"`
DeletePublicationIDs []string `json:"delete_publication_ids"`
ReleaseChangeSetID string `json:"release_change_set_id"`
// Seal:建批后立即锁定(P0-3,清单已不可变,草稿态只是多按一次)。
Seal bool `json:"seal"`
}
// reviewBatchStore 是本路由需要的最小能力面:真实 Store 实现它,既有 fake 不必跟着改。
type reviewBatchStore interface {
ReviewPublicationsBatchWithOperation(context.Context, governance.ReviewPublicationsBatchRequest, string) (governance.ReviewPublicationsBatchResult, bool, error)
}
// batchReviewCandidates:一次对多条候选做同一个审核决定(批量批准/驳回)。
// 服务端逐条复用单条审核写入(同一套合法性校验),并逐条回报"哪几条没批成"。
func batchReviewCandidates(w http.ResponseWriter, r *http.Request, config Config) {
operationID, ok := requireOperationID(w, r)
if !ok {
return
}
var input struct {
PublicationIDs []string `json:"publication_ids"`
Decision string `json:"decision"`
DecidedVisibility string `json:"decided_visibility"`
DecisionCode string `json:"decision_code"`
}
if err := decodeStrictJSON(r, &input); err != nil || len(input.PublicationIDs) == 0 || len(input.PublicationIDs) > 100 {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid review batch request"})
return
}
batcher, ok := config.Store.(reviewBatchStore)
if !ok {
writeJSON(w, http.StatusNotImplemented, map[string]string{"error": "review batch is not wired"})
return
}
result, replayed, err := batcher.ReviewPublicationsBatchWithOperation(r.Context(), governance.ReviewPublicationsBatchRequest{
PublicationIDs: input.PublicationIDs, Decision: governance.ReviewState(input.Decision),
DecidedVisibility: governance.Visibility(input.DecidedVisibility), DecisionCode: input.DecisionCode,
ReviewerRef: actorFor(r), Now: config.Now().UTC(),
}, operationID)
switch {
case errors.Is(err, postgresstore.ErrOperationRequestConflict):
writeJSON(w, http.StatusConflict, map[string]string{"error": "Idempotency-Key conflicts with a different request"})
case errors.Is(err, postgresstore.ErrInvalidPublicationReview):
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid review batch request"})
case err != nil:
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not record review batch"})
default:
operation := "decided"
if replayed {
operation = "replayed"
}
writeJSON(w, http.StatusOK, map[string]any{"data": result, "operation": operation})
}
}
func createReleaseBatch(w http.ResponseWriter, r *http.Request, config Config) {
@@ -1517,7 +1570,7 @@ func createReleaseBatch(w http.ResponseWriter, r *http.Request, config Config) {
return
}
batch, replayed, err := config.Store.CreateReleaseBatchWithOperation(r.Context(), governance.CreateReleaseBatchRequest{
Name: input.Name, CreatedBy: actorFor(r), PublicationIDs: input.PublicationIDs, DeletePublicationIDs: input.DeletePublicationIDs, ReleaseChangeSetID: input.ReleaseChangeSetID, Now: config.Now().UTC(),
Name: input.Name, CreatedBy: actorFor(r), PublicationIDs: input.PublicationIDs, DeletePublicationIDs: input.DeletePublicationIDs, ReleaseChangeSetID: input.ReleaseChangeSetID, SealImmediately: input.Seal, Now: config.Now().UTC(),
}, operationID)
switch {
case errors.Is(err, postgresstore.ErrOperationRequestConflict):
@@ -1531,6 +1584,9 @@ func createReleaseBatch(w http.ResponseWriter, r *http.Request, config Config) {
case errors.Is(err, postgresstore.ErrReleaseChangeSetEmpty):
// 建批时冻结依赖当前实时计划;计划为空就没得冻。
writeJSON(w, http.StatusUnprocessableEntity, map[string]string{"error": "current release plan has no releasable item"})
case errors.Is(err, postgresstore.ErrReleaseBatchGateConflict):
// 建批即锁定时逐项复核门禁失败:整批已回滚,不会留下半成品。
writeJSON(w, http.StatusUnprocessableEntity, map[string]string{"error": "release batch contains ineligible publications"})
case err != nil:
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not create release batch"})
default:
@@ -76,7 +76,8 @@ func (s *Store) CreateReleaseBatchWithOperation(ctx context.Context, request gov
Upsert []string `json:"publication_ids"`
Delete []string `json:"delete_publication_ids"`
Set string `json:"release_change_set_id"`
}{request.Name, request.CreatedBy, request.PublicationIDs, request.DeletePublicationIDs, request.ReleaseChangeSetID})
Seal bool `json:"seal_immediately"`
}{request.Name, request.CreatedBy, request.PublicationIDs, request.DeletePublicationIDs, request.ReleaseChangeSetID, request.SealImmediately})
if err != nil {
return governance.ReleaseBatch{}, false, err
}
@@ -85,6 +86,22 @@ func (s *Store) CreateReleaseBatchWithOperation(ctx context.Context, request gov
})
}
func (s *Store) ReviewPublicationsBatchWithOperation(ctx context.Context, request governance.ReviewPublicationsBatchRequest, operationID string) (governance.ReviewPublicationsBatchResult, bool, error) {
fingerprint, err := operationFingerprint(struct {
IDs []string `json:"publication_ids"`
By string `json:"reviewer_ref"`
Decide string `json:"decision"`
Look string `json:"decided_visibility"`
Code string `json:"decision_code"`
}{request.PublicationIDs, request.ReviewerRef, string(request.Decision), string(request.DecidedVisibility), request.DecisionCode})
if err != nil {
return governance.ReviewPublicationsBatchResult{}, false, err
}
return runOperation(s, ctx, "publication.review.batch", operationID, fingerprint, request.Now, func(tx pgx.Tx) (governance.ReviewPublicationsBatchResult, error) {
return NewStore(tx).ReviewPublicationsBatch(ctx, request)
})
}
func (s *Store) GenerateReleaseChangeSetWithOperation(ctx context.Context, request governance.GenerateReleaseChangeSetRequest, operationID string) (governance.ReleaseChangeSet, bool, error) {
fingerprint, err := operationFingerprint(struct {
Name string `json:"name"`
@@ -379,6 +379,15 @@ func (s *Store) CreateReleaseBatch(ctx context.Context, request governance.Creat
if err != nil {
return governance.ReleaseBatch{}, fmt.Errorf("create release batch: %w", err)
}
if request.SealImmediately {
// P0-3:建批即锁定。清单在冻结时已不可变,草稿态只剩"查看/锁定"两个按钮,
// 等于让操作员多按一次;这里合成一步(锁定仍逐项复核门禁,失败即整批回滚)。
sealed, sealErr := s.SealReleaseBatch(ctx, governance.SealReleaseBatchRequest{BatchID: batch.ID, SealedBy: request.CreatedBy, Now: request.Now})
if sealErr != nil {
return governance.ReleaseBatch{}, sealErr
}
return sealed, nil
}
return batch, nil
}
@@ -0,0 +1,141 @@
package postgres
import (
"context"
"errors"
"os"
"testing"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"knowledge-governance/internal/governance"
)
// 批量审核:逐条复用单条审核的写入路径,且**如实回报**哪几条当时不可审核
// (例如人工刚驳回过的那条不会被机器翻回去)。
func TestReviewPublicationsBatchDecidesEligibleAndReportsSkipped(t *testing.T) {
databaseURL := isolatedIntegrationDatabaseURL(t, os.Getenv("TEST_DATABASE_URL"))
if databaseURL == "" {
t.Skip("TEST_DATABASE_URL is not set")
}
ctx := context.Background()
pool, err := pgxpool.New(ctx, databaseURL)
if err != nil {
t.Fatal(err)
}
defer pool.Close()
if err := ApplyMigrations(ctx, pool); err != nil {
t.Fatal(err)
}
store := NewStore(pool)
now := time.Date(2026, 10, 10, 15, 0, 0, 0, time.UTC)
if _, err := pool.Exec(ctx, `INSERT INTO source_connections (id, source_type, name) VALUES ('conn-manual', 'manual', 'Manual')`); err != nil {
t.Fatal(err)
}
insertReviewFixture(t, ctx, pool, 12, "tp-batch-a", now)
insertReviewFixture(t, ctx, pool, 13, "tp-batch-b", now)
insertReviewFixture(t, ctx, pool, 14, "tp-batch-c", now)
// 人工先把 c 驳回:机器不得覆盖。
if _, err := store.ReviewPublication(ctx, governance.ReviewPublicationRequest{
PublicationID: "tp-batch-c", Decision: governance.ReviewRejected, DecidedVisibility: governance.VisibilityInternal,
ReviewerRef: "admin", DecisionCode: "needs_correction", Now: now.Add(time.Minute),
}); err != nil {
t.Fatal(err)
}
// 人工发起的批量批准:可审核的写进去,不可审核的(这里是根本不存在的条目)如实跳报。
// 注意 c 也在其中——人工当然可以推翻自己先前的驳回,那是人工决策,不是机器覆盖。
result, err := store.ReviewPublicationsBatch(ctx, governance.ReviewPublicationsBatchRequest{
PublicationIDs: []string{"tp-batch-a", "tp-batch-b", "tp-batch-missing"},
Decision: governance.ReviewApproved, DecidedVisibility: governance.VisibilityInternal,
ReviewerRef: "engineer-1", DecisionCode: "approved_for_release", Now: now.Add(2 * time.Minute),
})
if err != nil {
t.Fatalf("ReviewPublicationsBatch() error = %v", err)
}
if result.Selected != 3 || result.Decided != 2 || result.Skipped != 1 {
t.Fatalf("batch result = %#v", result)
}
if len(result.SkippedIDs) != 1 || result.SkippedIDs[0] != "tp-batch-missing" {
t.Fatalf("skipped ids = %#v", result.SkippedIDs)
}
// 机器发起的批量批准:人工驳回过的那条必须被跳过(永远不覆盖人工结论)。
systemResult, err := store.ReviewPublicationsBatch(ctx, governance.ReviewPublicationsBatchRequest{
PublicationIDs: []string{"tp-batch-c"},
Decision: governance.ReviewApproved, DecidedVisibility: governance.VisibilityInternal,
ReviewerRef: "system:auto", DecisionCode: "approved_for_release", Now: now.Add(3 * time.Minute),
})
if err != nil {
t.Fatalf("system batch error = %v", err)
}
if systemResult.Decided != 0 || systemResult.Skipped != 1 {
t.Fatalf("system batch must not override a human decision: %#v", systemResult)
}
var approvedCount int
if err := pool.QueryRow(ctx, `SELECT COUNT(*)::integer FROM publication_reviews WHERE publication_id IN ('tp-batch-a','tp-batch-b') AND decision='approved' AND reviewer_ref='engineer-1'`).Scan(&approvedCount); err != nil {
t.Fatal(err)
}
if approvedCount != 2 {
t.Fatalf("approved reviews = %d, want 2", approvedCount)
}
// c 的人工驳回必须原样保留。
var decision, reviewer string
if err := pool.QueryRow(ctx, `SELECT decision, reviewer_ref FROM publication_reviews WHERE publication_id='tp-batch-c' ORDER BY created_at DESC, id DESC LIMIT 1`).Scan(&decision, &reviewer); err != nil {
t.Fatal(err)
}
if decision != "rejected" || reviewer != "admin" {
t.Fatalf("human decision was overwritten: %q by %q", decision, reviewer)
}
// 非法输入整批拒绝(含重复 id)。
if _, err := store.ReviewPublicationsBatch(ctx, governance.ReviewPublicationsBatchRequest{
PublicationIDs: []string{"tp-batch-a", "tp-batch-a"}, Decision: governance.ReviewApproved,
DecidedVisibility: governance.VisibilityInternal, ReviewerRef: "engineer-1",
DecisionCode: "approved_for_release", Now: now,
}); !errors.Is(err, ErrInvalidPublicationReview) {
t.Fatalf("duplicate ids error = %v, want ErrInvalidPublicationReview", err)
}
}
// 建批即锁定:一次调用就该得到 sealed 批次(草稿态不再单独占一步),且锁定会逐项复核门禁。
func TestCreateReleaseBatchSealsImmediately(t *testing.T) {
databaseURL := isolatedIntegrationDatabaseURL(t, os.Getenv("TEST_DATABASE_URL"))
if databaseURL == "" {
t.Skip("TEST_DATABASE_URL is not set")
}
ctx := context.Background()
pool, err := pgxpool.New(ctx, databaseURL)
if err != nil {
t.Fatal(err)
}
defer pool.Close()
if err := ApplyMigrations(ctx, pool); err != nil {
t.Fatal(err)
}
store := NewStore(pool)
now := time.Date(2026, 10, 10, 16, 0, 0, 0, time.UTC)
if _, err := pool.Exec(ctx, `INSERT INTO source_connections (id, source_type, name) VALUES ('conn-manual', 'manual', 'Manual')`); err != nil {
t.Fatal(err)
}
insertReviewFixture(t, ctx, pool, 2, "tp-seal-a", now)
if _, err := store.ReviewPublication(ctx, governance.ReviewPublicationRequest{
PublicationID: "tp-seal-a", Decision: governance.ReviewApproved, DecidedVisibility: governance.VisibilityInternal,
ReviewerRef: "engineer-1", DecisionCode: "approved_for_release", Now: now.Add(time.Minute),
}); err != nil {
t.Fatal(err)
}
batch, err := store.CreateReleaseBatch(ctx, governance.CreateReleaseBatchRequest{
Name: "建批即锁定", CreatedBy: "engineer-1", PublicationIDs: []string{"tp-seal-a"}, SealImmediately: true, Now: now.Add(2 * time.Minute),
})
if err != nil {
t.Fatalf("seal-on-create must succeed: %v", err)
}
if batch.State != governance.ReleaseBatchSealed {
t.Fatalf("batch state = %q, want sealed", batch.State)
}
if batch.ReleaseChangeSetID == "" || batch.SealedBy == "" {
t.Fatalf("sealed batch must carry frozen manifest and sealer: %#v", batch)
}
}
+38
View File
@@ -238,6 +238,44 @@ func (s *Store) ReviewPublication(ctx context.Context, request governance.Review
return review, nil
}
// ReviewPublicationsBatch 逐条复用 ReviewPublication(同一套合法性校验与"最新验收轮次"绑定),
// 不做第二套 SQL。某条当时不可审核(例如人工刚驳回过)只计入 SkippedIDs,不打断整批;
// 其他错误整批回滚——批量操作不能留下"一半批了、一半没批"的模糊状态。
func (s *Store) ReviewPublicationsBatch(ctx context.Context, request governance.ReviewPublicationsBatchRequest) (governance.ReviewPublicationsBatchResult, error) {
if !validPublicationReview(governance.ReviewPublicationRequest{
PublicationID: "tp-batch-validation", Decision: request.Decision, DecidedVisibility: request.DecidedVisibility,
ReviewerRef: request.ReviewerRef, DecisionCode: request.DecisionCode, Now: request.Now,
}) {
return governance.ReviewPublicationsBatchResult{}, ErrInvalidPublicationReview
}
if len(request.PublicationIDs) == 0 || len(request.PublicationIDs) > 100 {
return governance.ReviewPublicationsBatchResult{}, ErrInvalidPublicationReview
}
seen := make(map[string]bool, len(request.PublicationIDs))
result := governance.ReviewPublicationsBatchResult{Selected: len(request.PublicationIDs), SkippedIDs: []string{}, Reviews: []governance.PublicationReview{}}
for _, publicationID := range request.PublicationIDs {
if !validShortID(publicationID) || seen[publicationID] {
return governance.ReviewPublicationsBatchResult{}, ErrInvalidPublicationReview
}
seen[publicationID] = true
review, err := s.ReviewPublication(ctx, governance.ReviewPublicationRequest{
PublicationID: publicationID, Decision: request.Decision, DecidedVisibility: request.DecidedVisibility,
ReviewerRef: request.ReviewerRef, DecisionCode: request.DecisionCode, Now: request.Now,
})
switch {
case err == nil:
result.Decided++
result.Reviews = append(result.Reviews, review)
case errors.Is(err, ErrPublicationReviewNotEligible):
result.Skipped++
result.SkippedIDs = append(result.SkippedIDs, publicationID)
default:
return governance.ReviewPublicationsBatchResult{}, err
}
}
return result, nil
}
func validPublicationReview(request governance.ReviewPublicationRequest) bool {
if !validShortID(request.PublicationID) || request.Now.IsZero() ||
request.DecidedVisibility != governance.VisibilityInternal && request.DecidedVisibility != governance.VisibilityExternal ||
+10 -10
View File
@@ -353,28 +353,28 @@ describe('ReleaseManagement', () => {
releasePlan={releasePlan}
selectedDeleteIDs={['tp-delete']} onToggleDelete={vi.fn()}
/>)
for (const text of ['来源与目录 → 测试知识库 → 生产知识库','自动发布计划','新增 1','更新 0','删除 1','未变化 11284','B.pdf','C.pdf','D.pdf','将从生产检索中移除','我确认所选删除项会停止生产检索','已选择删除:1(待确认)','已选 1 项(删除待确认)','为什么按钮不能点:请确认所选删除项会停止生产检索;至少 1 项动作通过确认;请填写批次名称','至少 1 项动作通过确认','来源当前不可用,保留生产知识','正在执行自动回滚','批次 1 / 1','每批最多 50 项','Snapshot #20260906-090000Z','审核要发布的知识', '需人工确认', '批准', '驳回', '创建草稿批次', '锁定清单(不会上线)', 'Synthetic batch', '删除生产知识', '已从生产检索中移除', '已恢复生产知识', '仍可检查调整', 'Release Worker保持关闭', '锁定清单 ≠ 上线', '生产确认、发布验证与回滚', '生产操作权限:已阻断', '生产请求门禁已开启', '快照恢复验证未通过', '生产发布已阻断']) {
for (const text of ['来源与目录 → 测试知识库 → 生产知识库','自动发布计划','新增 1','更新 0','删除 1','未变化 11284','B.pdf','C.pdf','D.pdf','将从生产检索中移除','我确认所选删除项会停止生产检索','已选择删除:1(待确认)','已选 1 项(删除待确认)','为什么按钮不能点:请确认所选删除项会停止生产检索;至少 1 项动作通过确认;请填写批次名称','至少 1 项动作通过确认','来源当前不可用,保留生产知识','正在执行自动回滚','批次 1 / 1','每批最多 50 项','Snapshot #20260906-090000Z','审核要发布的知识', '需人工确认', '批准', '驳回', '创建并锁定清单', '锁定清单(不会上线)', 'Synthetic batch', '删除生产知识', '已从生产检索中移除', '已恢复生产知识', '仍可检查调整', 'Release Worker保持关闭', '锁定清单 ≠ 上线', '生产确认、发布验证与回滚', '生产操作权限:已阻断', '生产请求门禁已开启', '快照恢复验证未通过', '生产发布已阻断']) {
expect(html).toContain(text)
}
for (const text of [
'从检查到发布,只走这 8 步',
'从检查到发布,只走这 7 步',
'1. 查看来源变化',
'2. 确认测试结果',
'3. 审核发布内容',
'4. 创建发布批次',
'5. 锁定发布清单',
'6. 生产负责人确认',
'7. 发布并验证',
'8. 必要时回滚',
'当前在第 3 步,共 8 步',
'4. 创建并锁定发布清单',
'4. 创建并锁定发布清单',
'5. 生产负责人确认',
'6. 发布并验证',
'7. 必要时回滚',
'当前在第 3 步,共 7 步',
'现在要做:审核 1 项知识',
'还有 1 项等待审核;已批准文件可先创建批次',
'完成本步的 3 件事',
'只审核本次准备发布的文件',
'勾选要发布的已批准知识',
'填写批次名称并创建草稿',
'填写批次名称后创建(创建即冻结并锁定清单)',
'现在先做:逐条选择“批准”或“驳回”(操作自动记在当前登录人名下)',
'完成后进入:第 4 步,创建发布批次',
'完成后进入:第 4 步,创建并锁定发布清单',
'为什么按钮不能点:请确认所选删除项会停止生产检索',
'如何决定批准或驳回',
'可以批准:基础测试通过,你已确认搜索结果相关,而且发布范围正确',
+60 -23
View File
@@ -12,7 +12,7 @@ import { fetchSourceAssets } from './assets'
import type { LegacyStatus, SourceAssetPage } from './assets'
import { fetchJobs } from './jobs'
import type { Job, JobState } from './jobs'
import { confirmReleaseChangeSet, createReleaseBatch, fetchLatestReleaseChangeSet, fetchReleaseAuditChain, fetchReleaseBatch, fetchReleaseBatches, fetchReleaseCapabilities, fetchReleaseExecution, fetchReleaseExecutions, fetchReleasePlan, fetchReviewCandidates, generateReleaseChangeSet, productionConfirmationPhrases, reviewPublication, runProductionAction, sealReleaseBatch } from './reviewRelease'
import { confirmReleaseChangeSet, createReleaseBatch, fetchLatestReleaseChangeSet, fetchReleaseAuditChain, fetchReleaseBatch, fetchReleaseBatches, fetchReleaseCapabilities, fetchReleaseExecution, fetchReleaseExecutions, fetchReleasePlan, fetchReviewCandidates, generateReleaseChangeSet, productionConfirmationPhrases, reviewPublication, runProductionAction, sealReleaseBatch, reviewPublicationsBatch } from './reviewRelease'
import type { ProductionActionKind } from './reviewRelease'
import type { ReleaseAuditChain, ReleaseBatchDetail, ReleaseBatchPage, ReleaseCapabilities, ReleaseChangeSetDetail, ReleaseExecutionDetail, ReleaseExecutionPage, ReleasePlan, ReleasePlanItem, ReviewCandidatePage, Visibility } from './reviewRelease'
import { fetchSourceConnections, fetchSourceScanDetail, fetchSourceScans, triggerSourceScan } from './sourceConnections'
@@ -200,6 +200,8 @@ interface ModulePageProps extends JobDashboardProps {
batchError?: string | null
mutatingBatchId?: string | null
onReview?: ReleaseManagementProps['onReview']
onBatchReview?: ReleaseManagementProps['onBatchReview']
reviewBatchMessage?: string
onReviewRefresh?: () => void
onCreateBatch?: ReleaseManagementProps['onCreateBatch']
onSealBatch?: ReleaseManagementProps['onSealBatch']
@@ -254,7 +256,7 @@ const emptyExecutionPage: ReleaseExecutionPage = { items: [], total: 0, limit: 2
const disabledReleaseCapabilities: ReleaseCapabilities = { production_release_requests_enabled: false, production_backup_restore_verified: false, test_auto_review_policy: '' }
const emptyReleasePlan: ReleasePlan = { items: [], summary: { add: 0, update: 0, delete: 0, blocked: 0, unchanged: 0 } }
export function ModulePage({ moduleId, jobs, loading, error, onRefresh, connectionPage = emptyConnectionPage, connectionLoading = false, connectionError = null, onConnectionRefresh = () => undefined, scanningConnectionId = null, onTriggerSourceScan = () => undefined, scanPage = emptyScanPage, scanDetail = null, scanLoading = false, scanError = null, selectedScanId = null, onSelectScan = () => undefined, assetPage = emptyAssetPage, assetLoading = false, assetError = null, assetState = '', onAssetStateChange = () => undefined, onAssetPageChange = () => undefined, onAssetRefresh = () => undefined, publicationPage = emptyPublicationPage, publicationLoading = false, publicationError = null, publicationState = '', retryingId = null, onPublicationStateChange = () => undefined, onPublicationPageChange = () => undefined, onPublicationRefresh = () => undefined, onRetry = () => undefined, reviewPage = emptyReviewPage, reviewLoading = false, reviewError = null, reviewingId = null, batchPage = emptyBatchPage, batchDetail = null, batchLoading = false, batchError = null, mutatingBatchId = null, onReview = () => undefined, onReviewRefresh = () => undefined, onCreateBatch = () => undefined, onSealBatch = () => undefined, onSelectBatch = () => undefined, onBatchRefresh = () => undefined, releaseCapabilities = disabledReleaseCapabilities, releasePlan = emptyReleasePlan, releaseChangeSet = null, changeSetBusy = false, changeSetError = null, onGenerateChangeSet = () => undefined, onConfirmChangeSet = () => undefined, selectedDeleteIDs = [], onToggleDelete = () => undefined, executionPage = emptyExecutionPage, executionDetail = null, executionChain = null, executionLoading = false, executionError = null, onSelectExecution = () => undefined, onExecutionRefresh = () => undefined, pendingReleaseAction = null, releaseActionPhrase = '', releaseActionBusy = false, releaseActionError = null, releaseActionMessage = null, onStartReleaseAction = () => undefined, onReleaseActionPhrase = () => undefined, onSubmitReleaseAction = () => undefined, onCancelReleaseAction = () => undefined }: ModulePageProps) {
export function ModulePage({ moduleId, jobs, loading, error, onRefresh, connectionPage = emptyConnectionPage, connectionLoading = false, connectionError = null, onConnectionRefresh = () => undefined, scanningConnectionId = null, onTriggerSourceScan = () => undefined, scanPage = emptyScanPage, scanDetail = null, scanLoading = false, scanError = null, selectedScanId = null, onSelectScan = () => undefined, assetPage = emptyAssetPage, assetLoading = false, assetError = null, assetState = '', onAssetStateChange = () => undefined, onAssetPageChange = () => undefined, onAssetRefresh = () => undefined, publicationPage = emptyPublicationPage, publicationLoading = false, publicationError = null, publicationState = '', retryingId = null, onPublicationStateChange = () => undefined, onPublicationPageChange = () => undefined, onPublicationRefresh = () => undefined, onRetry = () => undefined, reviewPage = emptyReviewPage, reviewLoading = false, reviewError = null, reviewingId = null, batchPage = emptyBatchPage, batchDetail = null, batchLoading = false, batchError = null, mutatingBatchId = null, onReview = () => undefined, onBatchReview = () => undefined, reviewBatchMessage = '', onReviewRefresh = () => undefined, onCreateBatch = () => undefined, onSealBatch = () => undefined, onSelectBatch = () => undefined, onBatchRefresh = () => undefined, releaseCapabilities = disabledReleaseCapabilities, releasePlan = emptyReleasePlan, releaseChangeSet = null, changeSetBusy = false, changeSetError = null, onGenerateChangeSet = () => undefined, onConfirmChangeSet = () => undefined, selectedDeleteIDs = [], onToggleDelete = () => undefined, executionPage = emptyExecutionPage, executionDetail = null, executionChain = null, executionLoading = false, executionError = null, onSelectExecution = () => undefined, onExecutionRefresh = () => undefined, pendingReleaseAction = null, releaseActionPhrase = '', releaseActionBusy = false, releaseActionError = null, releaseActionMessage = null, onStartReleaseAction = () => undefined, onReleaseActionPhrase = () => undefined, onSubmitReleaseAction = () => undefined, onCancelReleaseAction = () => undefined }: ModulePageProps) {
if (moduleId === 'tasks') {
return <TestPublications page={publicationPage} loading={publicationLoading} error={publicationError} state={publicationState} retryingId={retryingId} onStateChange={onPublicationStateChange} onPageChange={onPublicationPageChange} onRefresh={onPublicationRefresh} onRetry={onRetry} />
}
@@ -265,7 +267,7 @@ export function ModulePage({ moduleId, jobs, loading, error, onRefresh, connecti
return <SourceConnections page={connectionPage} loading={connectionLoading} error={connectionError} scanningConnectionId={scanningConnectionId} scanPage={scanPage} scanDetail={scanDetail} scanLoading={scanLoading} scanError={scanError} selectedScanId={selectedScanId} onRefresh={onConnectionRefresh} onTriggerScan={onTriggerSourceScan} onSelectScan={onSelectScan} />
}
if (moduleId === 'releases') {
return <ReleaseManagement reviewPage={reviewPage} reviewLoading={reviewLoading} reviewError={reviewError} reviewingId={reviewingId} batchPage={batchPage} batchDetail={batchDetail} batchLoading={batchLoading} batchError={batchError} mutatingBatchId={mutatingBatchId} onReview={onReview} onReviewRefresh={onReviewRefresh} onCreateBatch={onCreateBatch} onSealBatch={onSealBatch} onSelectBatch={onSelectBatch} onBatchRefresh={onBatchRefresh} releaseCapabilities={releaseCapabilities} releasePlan={releasePlan} releaseChangeSet={releaseChangeSet} changeSetBusy={changeSetBusy} changeSetError={changeSetError} onGenerateChangeSet={onGenerateChangeSet} onConfirmChangeSet={onConfirmChangeSet} selectedDeleteIDs={selectedDeleteIDs} onToggleDelete={onToggleDelete} executionPage={executionPage} executionDetail={executionDetail} executionChain={executionChain} executionLoading={executionLoading} executionError={executionError} onSelectExecution={onSelectExecution} onExecutionRefresh={onExecutionRefresh} pendingReleaseAction={pendingReleaseAction} releaseActionPhrase={releaseActionPhrase} releaseActionBusy={releaseActionBusy} releaseActionError={releaseActionError} releaseActionMessage={releaseActionMessage} onStartReleaseAction={onStartReleaseAction} onReleaseActionPhrase={onReleaseActionPhrase} onSubmitReleaseAction={onSubmitReleaseAction} onCancelReleaseAction={onCancelReleaseAction} />
return <ReleaseManagement reviewPage={reviewPage} reviewLoading={reviewLoading} reviewError={reviewError} reviewingId={reviewingId} batchPage={batchPage} batchDetail={batchDetail} batchLoading={batchLoading} batchError={batchError} mutatingBatchId={mutatingBatchId} onReview={onReview} onBatchReview={onBatchReview} reviewBatchMessage={reviewBatchMessage} onReviewRefresh={onReviewRefresh} onCreateBatch={onCreateBatch} onSealBatch={onSealBatch} onSelectBatch={onSelectBatch} onBatchRefresh={onBatchRefresh} releaseCapabilities={releaseCapabilities} releasePlan={releasePlan} releaseChangeSet={releaseChangeSet} changeSetBusy={changeSetBusy} changeSetError={changeSetError} onGenerateChangeSet={onGenerateChangeSet} onConfirmChangeSet={onConfirmChangeSet} selectedDeleteIDs={selectedDeleteIDs} onToggleDelete={onToggleDelete} executionPage={executionPage} executionDetail={executionDetail} executionChain={executionChain} executionLoading={executionLoading} executionError={executionError} onSelectExecution={onSelectExecution} onExecutionRefresh={onExecutionRefresh} pendingReleaseAction={pendingReleaseAction} releaseActionPhrase={releaseActionPhrase} releaseActionBusy={releaseActionBusy} releaseActionError={releaseActionError} releaseActionMessage={releaseActionMessage} onStartReleaseAction={onStartReleaseAction} onReleaseActionPhrase={onReleaseActionPhrase} onSubmitReleaseAction={onSubmitReleaseAction} onCancelReleaseAction={onCancelReleaseAction} />
}
if (moduleId === 'settings') {
return <SystemSettings />
@@ -657,6 +659,10 @@ interface ReleaseManagementProps {
batchError: string | null
mutatingBatchId: string | null
onReview: (publicationID: string, decision: 'approved' | 'rejected', visibility: Visibility, decisionCode: string) => void
/** P0-3 批量审核:一次对多条候选下同一个决定。 */
onBatchReview?: (publicationIDs: string[], decision: 'approved' | 'rejected', visibility: Visibility, decisionCode: string) => void
/** 批量审核的结果消息(如实说明哪几条没批成)。 */
reviewBatchMessage?: string
onReviewRefresh: () => void
onCreateBatch: (name: string, publicationIDs: string[], deletePublicationIDs: string[]) => void
onSealBatch: (batchID: string) => void
@@ -776,11 +782,10 @@ const releaseFlowSteps = [
{ title: '1. 查看来源变化', kind: '只读查看' },
{ title: '2. 确认测试结果', kind: '只读查看' },
{ title: '3. 审核发布内容', kind: '普通业务操作' },
{ title: '4. 创建发布批次', kind: '普通业务操作' },
{ title: '5. 锁定发布清单', kind: '普通业务操作' },
{ title: '6. 生产负责人确认', kind: '生产危险操作' },
{ title: '7. 发布并验证', kind: '生产危险操作' },
{ title: '8. 必要时回滚', kind: '生产危险操作' },
{ title: '4. 创建并锁定发布清单', kind: '普通业务操作' },
{ title: '5. 生产负责人确认', kind: '生产危险操作' },
{ title: '6. 发布并验证', kind: '生产危险操作' },
{ title: '7. 必要时回滚', kind: '生产危险操作' },
] as const
function releaseGuidance(props: ReleaseManagementProps, pending: number) {
@@ -795,17 +800,17 @@ function releaseGuidance(props: ReleaseManagementProps, pending: number) {
title: `现在要做:审核 ${pending} 项知识`,
reason: `还有 ${pending} 项等待审核;已批准文件可先创建批次`,
action: '逐条选择“批准”或“驳回”(操作自动记在当前登录人名下)',
after: '第 4 步,创建发布批次',
after: '第 4 步,创建并锁定发布清单',
impact: '普通业务操作,不会影响生产',
href: '#review-actions',
button: '前往审核列表',
}
if (drafts > 0) return {
step: 5,
step: 4,
title: `现在要做:锁定 ${drafts} 个草稿批次`,
reason: '暂时不能继续:草稿内容还可以变化,发布清单尚未锁定',
action: '核对批次内容,然后点击“锁定清单(不会上线)”',
after: '第 6 步,等待生产负责人确认',
after: '第 5 步,等待生产负责人确认',
impact: '普通业务操作,不会影响生产',
href: '#batch-actions',
button: '查看草稿批次',
@@ -814,11 +819,11 @@ function releaseGuidance(props: ReleaseManagementProps, pending: number) {
step: 4,
title: `现在要做:把 ${approved} 项已批准知识加入批次`,
reason: '暂时不能继续:已批准内容还没有组成一次发布清单',
action: '勾选已批准内容,填写批次名称并创建草稿',
after: '第 5 步,锁定本次发布清单',
action: '勾选已批准内容,填写批次名称后创建(创建即冻结并锁定)',
after: '第 5 步,等待生产负责人确认',
impact: '普通业务操作,不会影响生产',
href: '#review-actions',
button: '创建发布批次',
button: '创建并锁定清单',
}
if (sealed > 0 && props.executionPage.total === 0) return {
step: 6,
@@ -903,7 +908,7 @@ export function ReleaseManagement(props: ReleaseManagementProps) {
? '生产操作权限:已阻断'
: '生产操作权限:等待负责人确认'
// 建批只绑定"已确认"的版本;所选知识不在那份清单里时必定 422(今天实测的坑)。
// 就地把它变成可操作:说明原因 + 给一个"生成新版本并确认冻结"的按钮。
// P0-1 之后建批会自己冻结当前计划,所以不再有"所选知识不在冻结清单里"这种阻断。
// P0-1 之后不再有"所选知识不在已冻结清单里"这种阻断:清单在建批那一刻才冻结。
const batchBlocker = [
selectedCount === 0 ? '请先勾选已批准或待删除的知识' : '',
@@ -928,7 +933,7 @@ export function ReleaseManagement(props: ReleaseManagementProps) {
<section className="release-snapshot-callout"><span aria-hidden="true">ⓘ</span><div><strong>{props.releaseCapabilities.production_backup_restore_verified ? '发布前将创建可恢复快照' : '生产发布当前不可执行'}</strong><small>{props.releaseCapabilities.production_backup_restore_verified ? '发布失败时系统会按已验证的快照执行回滚。' : '尚未通过生产备份恢复验证,当前只能审核和锁定发布清单。'}</small></div></section>
<details className="release-help"><summary>查看审核与发布说明</summary>
<section className="release-journey" aria-label="发布流程">
<div className="journey-heading"><div><span>操作顺序</span><h2>从检查到发布,只走这 8 步</h2></div><p>蓝色是当前步骤;绿色表示已完成;红色步骤会修改生产环境。</p></div>
<div className="journey-heading"><div><span>操作顺序</span><h2>从检查到发布,只走这 7 步</h2></div><p>蓝色是当前步骤;绿色表示已完成;红色步骤会修改生产环境。</p></div>
<ol className="journey-steps">
{releaseFlowSteps.map((item, index) => {
const number = index + 1
@@ -943,11 +948,11 @@ export function ReleaseManagement(props: ReleaseManagementProps) {
</ol>
</section>
<section className="current-guidance" aria-label="当前阶段">
<div className="guidance-step">当前在第 {guidance.step} 步,共 8 步</div>
<div className="guidance-step">当前在第 {guidance.step} 步,共 7 步</div>
<div className="guidance-copy">
<h2>{guidance.title}</h2>
<strong>{guidance.reason}</strong>
{guidance.step === 3 ? <div className="current-checklist"><b>完成本步的 3 件事</b><ol><li>只审核本次准备发布的文件</li><li>勾选要发布的已批准知识</li><li>填写批次名称并创建草稿</li></ol></div> : null}
{guidance.step === 3 ? <div className="current-checklist"><b>完成本步的 3 件事</b><ol><li>只审核本次准备发布的文件</li><li>勾选要发布的已批准知识</li><li>填写批次名称后创建(创建即冻结并锁定清单)</li></ol></div> : null}
<p>{`现在先做:${guidance.action}`}</p>
<p>{`完成后进入:${guidance.after}`}</p>
<span>{guidance.impact}</span>
@@ -1016,8 +1021,18 @@ export function ReleaseManagement(props: ReleaseManagementProps) {
</section>
<section className="panel review-panel" id="review-actions">
<div className="panel-heading release-toolbar">
<div><h2>第 3 步:审核要发布的知识</h2><p>先确认测试结果和对内/对外范围,再批准或驳回。批准后才能勾选加入批次。</p>{autoReviewNote(props.releaseCapabilities.test_auto_review_policy) ? <p className="tiny" role="note">{autoReviewNote(props.releaseCapabilities.test_auto_review_policy)}</p> : null}</div>
<div><h2>第 3 步:审核要发布的知识</h2><p>先确认测试结果和对内/对外范围,再批准或驳回。批准后才能勾选加入批次。可批准的多条支持一次批量批准。</p>{autoReviewNote(props.releaseCapabilities.test_auto_review_policy) ? <p className="tiny" role="note">{autoReviewNote(props.releaseCapabilities.test_auto_review_policy)}</p> : null}</div>
</div>
{(() => {
// 「可批准」只含尚未决定且门禁通过的条目:已驳回的不能被"全选"顺手翻回来。
const batchable = props.reviewPage.items.filter((item) => item.gate_status === 'ready' && item.review_state === 'pending').map((item) => item.publication_id)
return <div className="release-toolbar"><div className="release-toolbar-actions">
<button type="button" disabled={!batchable.length || props.reviewingId === 'batch'} onClick={() => setSelectedIDs(batchable)}>全选可批准({batchable.length})</button>
<button type="button" disabled={!selectedIDs.length || props.reviewingId === 'batch'} onClick={() => void props.onBatchReview?.(selectedIDs, 'approved', 'internal', 'approved_for_release')}>{props.reviewingId === 'batch' ? '正在批量处理…' : `批量批准选中(${selectedIDs.length})`}</button>
<button type="button" disabled={!selectedIDs.length || props.reviewingId === 'batch'} onClick={() => void props.onBatchReview?.(selectedIDs, 'rejected', 'internal', 'needs_correction')}>批量驳回选中({selectedIDs.length})</button>
{props.reviewBatchMessage ? <small role="status">{props.reviewBatchMessage}</small> : null}
</div></div>
})()}
{batchBlocker ? <div className="button-reason" role="note"><strong>{`为什么按钮不能点:${batchBlocker}`}</strong></div> : null}
<div className="review-decision-guide" aria-label="审核判断标准">
<h3>如何决定批准或驳回</h3>
@@ -1046,10 +1061,10 @@ export function ReleaseManagement(props: ReleaseManagementProps) {
})}
</tbody></table></div> : null}
<div className="batch-requirements" aria-label="创建批次条件"><strong>创建批次还需要</strong><span className={props.selectedDeleteIDs.length === 0 || deleteConfirmed ? 'met' : 'unmet'}>确认所选发布动作</span><span className={confirmedSelection ? 'met' : 'unmet'}>至少 1 项动作通过确认</span><span className={batchName.trim() ? 'met' : 'unmet'}>填写批次名称</span></div>
<div className="batch-create-bar"><label>批次名称<input value={batchName} onChange={(event) => setBatchName(event.target.value)} placeholder="例如:9月第一批知识" /></label><span>已选 {selectedCount} 项{props.selectedDeleteIDs.length > 0 && !deleteConfirmed ? '(删除待确认)' : ''}</span><button type="button" title={batchBlocker || '创建后仍可检查和调整'} disabled={Boolean(batchBlocker) || props.batchLoading} onClick={() => props.onCreateBatch(batchName, selectedIDs, props.selectedDeleteIDs)}>创建草稿批次</button></div>
<div className="batch-create-bar"><label>批次名称<input value={batchName} onChange={(event) => setBatchName(event.target.value)} placeholder="例如:9月第一批知识" /></label><span>已选 {selectedCount} 项{props.selectedDeleteIDs.length > 0 && !deleteConfirmed ? '(删除待确认)' : ''}</span><button type="button" title={batchBlocker || '创建即锁定清单(清单在建批时冻结,锁定不会上线)'} disabled={Boolean(batchBlocker) || props.batchLoading} onClick={() => props.onCreateBatch(batchName, selectedIDs, props.selectedDeleteIDs)}>创建并锁定清单</button></div>
</section>
<section className="panel batch-panel" id="batch-actions">
<div className="panel-heading"><div><h2>第 4–5 步:创建并锁定发布清单</h2><p>草稿可以继续核对;点击“锁定清单(不会上线)”后,本次内容不再变化,但仍不会发布到生产。</p></div><span className="safe-badge">锁定清单 ≠ 上线</span></div>
<div className="panel-heading"><div><h2>第 4 步:创建并锁定发布清单</h2><p>建批时自动冻结清单并立即锁定:本批内容此后不再变化,但仍不会发布到生产。</p></div><span className="safe-badge">锁定清单 ≠ 上线</span></div>
{props.batchError ? <div className="error-banner" role="alert">{props.batchError}</div> : null}
{!props.batchLoading && !props.batchError && props.batchPage.items.length === 0 ? <div className="empty-state">尚无草稿或已锁定的发布清单。</div> : null}
{props.batchPage.items.length > 0 ? <div className="batch-grid"><div className="table-wrap"><table><thead><tr><th>批次名称</th><th>状态</th><th>知识数量</th><th>内容状态</th><th>操作</th></tr></thead><tbody>
@@ -1057,7 +1072,7 @@ export function ReleaseManagement(props: ReleaseManagementProps) {
</tbody></table></div><div className="batch-detail"><h3>本批次包含</h3>{props.batchDetail ? <>{props.batchDetail.items.map((item) => <div className="batch-detail-row" key={item.publication_id}><span><strong>{item.title}</strong><small>{item.action === 'delete' ? '删除生产知识' : '新增或更新生产知识'}</small></span><b>{item.decided_visibility === 'internal' ? '仅内部员工' : '允许外部用户'}</b></div>)}{props.batchDetail.items.length === 0 ? <div className="empty-state">批次没有知识。</div> : null}</> : <div className="empty-state">点击“查看内容”核对本次发布清单。</div>}</div></div> : null}
</section>
<section className="panel execution-panel" id="release-execution">
<div className="panel-heading"><div><h2>第 6–8 步:生产确认、发布验证与回滚</h2><p>生产动作只对管理员开放:点击后需逐字输入固定确认语句;服务端请求门禁与执行门禁仍须开启。发布后的三通道读回与官方 API 验收由 Release Worker 自动完成,这里只读展示结果。</p></div><span className="safe-badge">{props.releaseCapabilities.production_release_requests_enabled ? '生产操作可执行(待确认)' : '生产操作已锁定'}</span></div>
<div className="panel-heading"><div><h2>第 5–7 步:生产确认、发布验证与回滚</h2><p>生产动作只对管理员开放:点击后需逐字输入固定确认语句;服务端请求门禁与执行门禁仍须开启。发布后的三通道读回与官方 API 验收由 Release Worker 自动完成,这里只读展示结果。</p></div><span className="safe-badge">{props.releaseCapabilities.production_release_requests_enabled ? '生产操作可执行(待确认)' : '生产操作已锁定'}</span></div>
{props.pendingReleaseAction ? <div className="release-action-confirm" role="group" aria-label="生产动作确认">
<p><b>{releaseActionLabels[props.pendingReleaseAction.kind]}</b>「{props.pendingReleaseAction.label}」—— 请输入固定确认语句 <code>{productionConfirmationPhrases[props.pendingReleaseAction.kind]}</code> 后执行。</p>
<input value={props.releaseActionPhrase ?? ''} onChange={(event) => props.onReleaseActionPhrase?.(event.target.value)} placeholder={productionConfirmationPhrases[props.pendingReleaseAction.kind]} aria-label="生产动作确认语句" />
@@ -1394,13 +1409,33 @@ export default function App() {
}
}, [reloadChangeSet])
const [reviewMessage, setReviewMessage] = useState('')
// P0-3 批量审核:逐条其实都由服务端处理,这里只管调用与如实回报。
const handleBatchReview = useCallback(async (publicationIDs: string[], decision: 'approved' | 'rejected', visibility: Visibility, decisionCode: string) => {
setReviewingId('batch')
setBatchError(null)
try {
const result = await reviewPublicationsBatch(publicationIDs, decision, visibility, decisionCode)
const label = decision === 'approved' ? '批准' : '驳回'
setReviewMessage(result.skipped > 0
? `已${label} ${result.decided} 项;${result.skipped} 项当时不可审核(${result.skipped_ids.join('、')})`
: `已${label} ${result.decided} 项`)
await loadReviews()
} catch (cause) {
setBatchError(cause instanceof Error ? cause.message : '批量审核失败')
} finally {
setReviewingId(null)
}
}, [loadReviews])
const handleCreateBatch = useCallback(async (name: string, publicationIDs: string[], deletePublicationIDs: string[]) => {
setMutatingBatchId('creating')
setBatchError(null)
try {
// 不传版本 id:服务端在"建批这一下"冻结当前计划(同摘要复用同一版本),
// 操作员因此不必先「生成新版本」再「确认冻结」。
const batch = await createReleaseBatch(name, publicationIDs, deletePublicationIDs, '')
// seal=true:建批即锁定(P0-3),草稿态不再单独占一步。
const batch = await createReleaseBatch(name, publicationIDs, deletePublicationIDs, '', true)
setSelectedDeleteIDs([])
await loadBatches()
setBatchDetail(await fetchReleaseBatch(batch.id))
@@ -1638,6 +1673,8 @@ export default function App() {
batchError={batchError}
mutatingBatchId={mutatingBatchId}
onReview={(publicationID, decision, visibility, decisionCode) => void handleReview(publicationID, decision, visibility, decisionCode)}
onBatchReview={handleBatchReview}
reviewBatchMessage={reviewMessage}
onReviewRefresh={() => void loadReviews()}
onCreateBatch={(name, publicationIDs, deletePublicationIDs) => void handleCreateBatch(name, publicationIDs, deletePublicationIDs)}
onSealBatch={(batchID) => void handleSealBatch(batchID)}
+32 -1
View File
@@ -23,6 +23,7 @@ import {
parseReviewCandidatesResponse,
reviewPublication,
sealReleaseBatch,
reviewPublicationsBatch,
} from './reviewRelease'
afterEach(() => vi.unstubAllGlobals())
@@ -94,7 +95,7 @@ describe('review and batch requests', () => {
// P0: the browser must never name the actor again; the server stamps it.
expect(JSON.parse((fetchMock.mock.calls[1][1] as RequestInit).body as string)).toEqual({ decision: 'approved', decided_visibility: 'internal', decision_code: 'approved_for_release' })
expect(fetchMock.mock.calls[2][0]).toBe('/api/v1/release-batches')
expect(JSON.parse((fetchMock.mock.calls[2][1] as RequestInit).body as string)).toEqual({ name: 'Batch', publication_ids: ['tp-safe'], delete_publication_ids: ['tp-delete'], release_change_set_id: '' })
expect(JSON.parse((fetchMock.mock.calls[2][1] as RequestInit).body as string)).toEqual({ name: 'Batch', publication_ids: ['tp-safe'], delete_publication_ids: ['tp-delete'], release_change_set_id: '', seal: false })
expect(fetchMock.mock.calls[3][0]).toBe('/api/v1/release-batches/rb-safe/seal')
expect(fetchMock.mock.calls[4][0]).toBe('/api/v1/release-batches?state=draft&limit=20&offset=0')
})
@@ -255,3 +256,33 @@ describe('审核策略的只读展示', () => {
expect(parsed.test_auto_review_policy).toBe('')
})
})
describe('批量审核与建批即锁定', () => {
it('批量审核发送选中的条目与同一决定', async () => {
const fetchMock = vi.fn().mockResolvedValue({ ok: true, json: async () => ({ data: { selected: 2, decided: 2, skipped: 0, skipped_ids: [], reviews: [] } }) })
vi.stubGlobal('fetch', fetchMock)
const result = await reviewPublicationsBatch(['tp-a', 'tp-b'], 'approved', 'internal', 'approved_for_release')
expect(result).toEqual({ selected: 2, decided: 2, skipped: 0, skipped_ids: [] })
const [url, init] = fetchMock.mock.calls[0]
expect(url).toBe('/api/v1/review-candidates/batch-decision')
expect(JSON.parse(String(init.body))).toEqual({ publication_ids: ['tp-a', 'tp-b'], decision: 'approved', decided_visibility: 'internal', decision_code: 'approved_for_release' })
})
it('如实回报被跳过的条目', async () => {
const fetchMock = vi.fn().mockResolvedValue({ ok: true, json: async () => ({ data: { selected: 3, decided: 2, skipped: 1, skipped_ids: ['tp-c'], reviews: [] } }) })
vi.stubGlobal('fetch', fetchMock)
const result = await reviewPublicationsBatch(['tp-a', 'tp-b', 'tp-c'], 'approved', 'internal', 'approved_for_release')
expect(result.skipped).toBe(1)
expect(result.skipped_ids).toEqual(['tp-c'])
})
it('建批要求服务端立即冻结并锁定', async () => {
// 只断言请求体:响应形状由 parseBatchEnvelope 自己的用例覆盖。
const fetchMock = vi.fn().mockResolvedValue({ ok: false, status: 500, json: async () => ({ error: 'boom' }) })
vi.stubGlobal('fetch', fetchMock)
await expect(createReleaseBatch('批次', ['tp-a'], [], '', true)).rejects.toThrow()
const [, init] = fetchMock.mock.calls[0]
expect(JSON.parse(String(init.body)).seal).toBe(true)
expect(JSON.parse(String(init.body)).release_change_set_id).toBe('')
})
})
+25 -2
View File
@@ -258,6 +258,28 @@ export async function fetchReviewCandidates(reviewState: ReviewState | '' = '',
return parseReviewCandidatesResponse(await getJSON(`/api/v1/review-candidates?${params}`, signal, '加载审核队列失败'))
}
export interface ReviewBatchResult {
selected: number
decided: number
skipped: number
skipped_ids: string[]
}
/**
* 一次对多条候选做同一个审核决定。服务端逐条复用单条审核的写入路径,
* 并回报"哪几条当时不可审核",界面据此如实说明,而不是含糊地当作全成功。
*/
export async function reviewPublicationsBatch(publicationIDs: string[], decision: 'approved' | 'rejected', visibility: Visibility, decisionCode: string): Promise<ReviewBatchResult> {
const value = await sendJSON('/api/v1/review-candidates/batch-decision', {
publication_ids: publicationIDs, decision, decided_visibility: visibility, decision_code: decisionCode,
}, '批量审核失败')
if (!isRecord(value) || !isRecord(value.data)) throw new Error('invalid review batch response')
const data = value.data
if (!isCount(data.selected) || !isCount(data.decided) || !isCount(data.skipped)) throw new Error('invalid review batch response')
const skipped = Array.isArray(data.skipped_ids) ? data.skipped_ids.filter((item): item is string => typeof item === 'string') : []
return { selected: data.selected, decided: data.decided, skipped: data.skipped, skipped_ids: skipped }
}
export async function reviewPublication(publicationID: string, decision: 'approved' | 'rejected', visibility: Visibility, decisionCode: string): Promise<PublicationReview> {
const value = await sendJSON(`/api/v1/review-candidates/${encodeURIComponent(publicationID)}/decision`, {
decision, decided_visibility: visibility, decision_code: decisionCode,
@@ -273,8 +295,9 @@ export async function reviewPublication(publicationID: string, decision: 'approv
return { id: raw.id, publication_id: raw.publication_id, decision: raw.decision, decided_visibility: raw.decided_visibility as Visibility, reviewer_ref: raw.reviewer_ref, decision_code: raw.decision_code, created_at: raw.created_at }
}
export async function createReleaseBatch(name: string, publicationIDs: string[], deletePublicationIDs: string[] = [], releaseChangeSetID = ''): Promise<ReleaseBatch> {
return parseBatchEnvelope(await sendJSON('/api/v1/release-batches', { name, publication_ids: publicationIDs, delete_publication_ids: deletePublicationIDs, release_change_set_id: releaseChangeSetID }, '创建封批失败'))
export async function createReleaseBatch(name: string, publicationIDs: string[], deletePublicationIDs: string[] = [], releaseChangeSetID = '', seal = false): Promise<ReleaseBatch> {
// seal=true:建批即锁定(P0-3)。清单在冻结时已不可变,草稿态只是多按一次。
return parseBatchEnvelope(await sendJSON('/api/v1/release-batches', { name, publication_ids: publicationIDs, delete_publication_ids: deletePublicationIDs, release_change_set_id: releaseChangeSetID, seal }, '创建封批失败'))
}
export interface ReleaseChangeSetItem {