From f8faed0b219ac367628d86c4619af0530ede8220 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=A7=9A=E7=AB=A0=E6=B5=A9?= Date: Sat, 10 Oct 2026 15:48:30 +0800 Subject: [PATCH] =?UTF-8?q?feat(release):=20=E5=8F=91=E5=B8=83=E5=88=B0?= =?UTF-8?q?=E7=94=9F=E4=BA=A7=E4=B8=80=E9=94=AE=E5=AE=8C=E6=88=90=EF=BC=88?= =?UTF-8?q?=E5=BB=BA=E6=89=B9+=E9=94=81=E5=AE=9A+=E6=8E=88=E6=9D=83?= =?UTF-8?q?=E5=90=88=E6=88=90=E4=B8=80=E4=B8=AA=E5=8A=A8=E4=BD=9C=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 用户的反馈是对的:上一轮只砍掉了"冻结/锁定"两个按钮,但一条文档从"已批准"到"发出"实际仍要 ~9 次交互(找条目→勾选→填名→建批→滚到清单→找批次→授权→输语句→提交),因为"批次仪式"本身 还留在路径上。 - 新端点 POST /api/v1/release-batches/publish-now:在同一操作里先建批(SealImmediately,冻结 即锁定)再授权生产发布,返回 {batch, execution}。 - 不放松任何约束:请求门禁(403)、备份恢复验证门禁(412)、管理员身份(401)、固定确认语句(400)、 发布前快照硬门禁(409)、建批门禁(422) 全部沿用既有实现,无旁路;名称可省(服务端固定回退名, 保证重放指纹一致)。 - 界面:审核行上直接「发布到生产」(管理员 + 门禁开启时显示),工具栏支持选中多条一次发布; 复用既有确认弹窗(固定语句)。批次名不再是必经步骤。 - 实测(面板):点行级按钮 → 输 `publish-to-production` → 提交 → 批次 rb-bee80550…(sealed) + 执行 rx-3d831129…(completed, 项级 verified) → 页面回滚 rx-43835fac…(rolled_back, absent)。 测试:publish_now_test.go(四道关卡 + 组合调用 + 名称回退)与 reviewRelease.test.ts(请求体/回传/错误原因); Go 26 包、前端 183 条全过。 --- api/openapi.yaml | 85 ++++++++++++++++++++++ docs/OPERATIONS_RUNBOOK.md | 4 +- docs/USER_FLOWS_ACCEPTANCE.md | 13 ++++ internal/httpapi/publish_now_test.go | 101 +++++++++++++++++++++++++++ internal/httpapi/server.go | 97 +++++++++++++++++++++++++ web/src/App.tsx | 31 +++++--- web/src/reviewRelease.test.ts | 21 +++++- web/src/reviewRelease.ts | 40 ++++++++++- 8 files changed, 378 insertions(+), 14 deletions(-) create mode 100644 internal/httpapi/publish_now_test.go diff --git a/api/openapi.yaml b/api/openapi.yaml index 40077a2..9e0260a 100644 --- a/api/openapi.yaml +++ b/api/openapi.yaml @@ -3252,6 +3252,46 @@ } } } + }, + "/api/v1/release-batches/publish-now": { + "post": { + "tags": [ + "Release" + ], + "operationId": "publishNowPublications", + "summary": "一个动作完成「建批(冻结+锁定)→ 授权生产发布」(沿用门禁、固定语句与管理员身份)", + "parameters": [ + { + "$ref": "#/components/parameters/IdempotencyKey" + } + ], + "responses": { + "202": { + "$ref": "#/components/responses/OperationEnvelope" + }, + "400": { + "$ref": "#/components/responses/BadRequest" + }, + "401": { + "$ref": "#/components/responses/Unauthorized" + }, + "403": { + "$ref": "#/components/responses/Forbidden" + }, + "409": { + "$ref": "#/components/responses/Conflict" + }, + "412": { + "$ref": "#/components/responses/PreconditionFailed" + }, + "422": { + "$ref": "#/components/responses/Unprocessable" + }, + "500": { + "$ref": "#/components/responses/InternalError" + } + } + } } }, "components": { @@ -3394,6 +3434,51 @@ } } } + }, + "Unauthorized": { + "description": "需要生产发布授权(管理员会话或运维通道)", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string" + } + } + } + } + } + }, + "PreconditionFailed": { + "description": "生产门禁未满足(例如备份恢复验证未通过)", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string" + } + } + } + } + } + }, + "Unprocessable": { + "description": "请求内容不满足发布条件", + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "error": { + "type": "string" + } + } + } + } + } } }, "schemas": { diff --git a/docs/OPERATIONS_RUNBOOK.md b/docs/OPERATIONS_RUNBOOK.md index 59df0f9..b689e52 100644 --- a/docs/OPERATIONS_RUNBOOK.md +++ b/docs/OPERATIONS_RUNBOOK.md @@ -39,7 +39,9 @@ dws wiki +space-list --limit 1 -f json # 真实调用验证,期望 ok:true - 路由到哪个测试库由 **系统设置 → 测试知识库绑定** 决定;`不需要` 不入库。 ## 3. 发布准备:勾选 → 建批 → 锁定 **【变:P0-1 建批时冻结 + P0-2 自动批准】** -**发布管理** → 在「审核要发布的知识」里勾选(对内知识通常已由系统批准;未决定的可用「全选可批准」+「批量批准选中」一次批)→ 填批次名 → `创建并锁定清单`(一步完成,无需再点锁定)。 +**发布管理 → 审核要发布的知识**: +- **最快路径(推荐,单个或几条)**:在已批准那条上直接点 **`发布到生产`** → 输入固定语句 → 提交。服务端在同一个动作里完成「建批(冻结+锁定)→ 授权生产发布」,无需填批次名、无需先建批再锁定。 +- 需要一批多条时:勾选 → 填批次名 → `创建并锁定清单`(建批即锁定),再到发布清单点 `授权发布`。 - **不再需要 `生成新版本` / `确认冻结`**:服务端在"建批这一下"把当前实时计划冻结成一份**已确认**版本并绑定该批次。 语义不变——批一旦建立,清单/摘要/验收轮次/目标库绑定全部不可变、回滚按它走;变的只是"谁在什么时候按固化键"。 - 同一份计划复用同一版本(摘要一致即复用),所以连续建批不会堆版本;计划变了才新建一版。 diff --git a/docs/USER_FLOWS_ACCEPTANCE.md b/docs/USER_FLOWS_ACCEPTANCE.md index 8f83f7f..736e4fd 100644 --- a/docs/USER_FLOWS_ACCEPTANCE.md +++ b/docs/USER_FLOWS_ACCEPTANCE.md @@ -164,6 +164,19 @@ - ⚠️ 过程中踩到并修掉 **Bug #6**(见 F.3h):禁止导入只写 `source_items.policy_state`,而**两处**"期望策略"解析 (计划 + 建批 delete 就绪判定)都不看它 → 计划不给 delete、建批直接 422 +### C8 一键发布(建批+锁定+授权合成一个动作)★2026-10-10 实测 + +- 入口:审核行上的 **`发布到生产`**(管理员 + 生产门禁开启时显示),或工具栏「发布到生产(选中 N 项)」。 +- 证据:点行级按钮 → 确认弹窗输入固定语句 → 提交 → 库内一次得到: + 批次 `rb-bee80550b6fae758a4b1076db1c6bc36`(`立即发布 · 2026/10/10`、**sealed**、1 项、绑定冻结版本) + + 执行 `rx-3d831129e01322a8dfcf08b09cd4adbe`(publish、**completed**、项级 `verified`、`production_revision=rv-934f2a64…`) + → 随后在页面上回滚:`rx-43835fac7d218c008933f1cb93c75b2b` → `rolled_back`、项级 `production_revision=absent` + (回滚状态由适配层读回校验 `verify restored` 后才置位)。 +- 与之前对照:同一条文档从"已批准"到"发出",此前需 找条目→勾选→填名→建批→滚到清单→找批次→授权→输语句→提交(~9 次交互); + 现在 **3 次**(点发布 → 输固定语句 → 提交)。 +- 约束未放松(服务端测试固化):请求门禁关闭 → 403;备份恢复验证未过 → 412;非管理员 → 401;错语句/空选择 → 400; + 建批失败(门禁不通过)→ 422;密封后不满足生产门禁 → 409。 + ### C7 批量审核 + 建批即锁定 ★2026-10-10 实测(发布管理减负 P0-3) - 界面:审核区块新增「全选可批准(N)」「批量批准选中(N)」「批量驳回选中(N)」;建批按钮改为「创建并锁定清单」。 diff --git a/internal/httpapi/publish_now_test.go b/internal/httpapi/publish_now_test.go new file mode 100644 index 0000000..8517bbb --- /dev/null +++ b/internal/httpapi/publish_now_test.go @@ -0,0 +1,101 @@ +package httpapi + +import ( + "bytes" + "context" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" + + "knowledge-governance/internal/governance" +) + +// publish-now 把「建批(冻结+锁定)」与「授权生产发布」合成一个动作, +// 但四个关卡一个都不放松:请求门禁、备份恢复验证、管理员身份、固定确认语句。 +func TestPublishNowComposesSealAndAuthorization(t *testing.T) { + request := func(body string, identity *sessionIdentity) *http.Request { + r := httptest.NewRequest(http.MethodPost, "/api/v1/release-batches/publish-now", bytes.NewBufferString(body)) + r.Header.Set("Content-Type", "application/json") + r.Header.Set("Idempotency-Key", "op-publish-now") + if identity != nil { + r = r.WithContext(context.WithValue(r.Context(), sessionKey{}, *identity)) + } + return r + } + admin := &sessionIdentity{Username: "yaozhanghao", Role: roleAdmin} + engineer := &sessionIdentity{Username: "engineer-1", Role: roleEngineer} + valid := `{"publication_ids":["tp-a"],"confirmation":"publish-to-production"}` + + // 请求门禁关闭。 + closedHandler, err := NewHandler(Config{Store: &fakeJobStore{}, Now: func() time.Time { return time.Now().UTC() }, + ProductionReleaseRequestsEnabled: false, ProductionBackupRestoreVerified: true, + ProductionReleaseAuthorizerRef: "release-owner", ProductionReleaseAuthorizationToken: "safe-token"}) + if err != nil { + t.Fatal(err) + } + recorder := httptest.NewRecorder() + closedHandler.ServeHTTP(recorder, request(valid, admin)) + if recorder.Code != http.StatusForbidden { + t.Fatalf("gate off status=%d", recorder.Code) + } + + // 备份恢复验证未过。 + unverified, err := NewHandler(Config{Store: &fakeJobStore{}, Now: func() time.Time { return time.Now().UTC() }, + ProductionReleaseRequestsEnabled: true, ProductionBackupRestoreVerified: false, + ProductionReleaseAuthorizerRef: "release-owner", ProductionReleaseAuthorizationToken: "safe-token"}) + if err != nil { + t.Fatal(err) + } + recorder = httptest.NewRecorder() + unverified.ServeHTTP(recorder, request(valid, admin)) + if recorder.Code != http.StatusPreconditionFailed { + t.Fatalf("backup unverified status=%d", recorder.Code) + } + + // 非管理员 / 错语句 / 空选择。 + handler, store := productionActionHandler(t) + store.createBatchResult = governance.ReleaseBatch{ID: "rb-now", Name: "立即发布", State: governance.ReleaseBatchSealed, ItemCount: 1, ReleaseChangeSetID: "rcs-now"} + for _, testCase := range []struct { + name string + body string + identity *sessionIdentity + status int + }{ + {"engineer session", valid, engineer, http.StatusUnauthorized}, + {"no session", valid, nil, http.StatusUnauthorized}, + {"wrong phrase", `{"publication_ids":["tp-a"],"confirmation":"publish"}`, admin, http.StatusBadRequest}, + {"empty selection", `{"publication_ids":[],"confirmation":"publish-to-production"}`, admin, http.StatusBadRequest}, + } { + recorder := httptest.NewRecorder() + handler.ServeHTTP(recorder, request(testCase.body, testCase.identity)) + if recorder.Code != testCase.status { + t.Fatalf("%s status=%d want=%d", testCase.name, recorder.Code, testCase.status) + } + } + + // 正常路径:建批就是"立即锁定",随后完成授权,两步在同一个操作里。 + store.createBatchRequest = governance.CreateReleaseBatchRequest{} + store.authorizeReleaseCalled = false + recorder = httptest.NewRecorder() + handler.ServeHTTP(recorder, request(`{"publication_ids":["tp-a","tp-b"],"name":"立即发布 · 测试","confirmation":"publish-to-production"}`, admin)) + if recorder.Code != http.StatusAccepted { + t.Fatalf("publish-now status=%d body=%s", recorder.Code, recorder.Body.String()) + } + if !store.createBatchRequest.SealImmediately { + t.Fatal("publish-now must create the batch already sealed") + } + if store.createBatchRequest.Name != "立即发布 · 测试" || len(store.createBatchRequest.PublicationIDs) != 2 { + t.Fatalf("batch request = %#v", store.createBatchRequest) + } + if !store.authorizeReleaseCalled || store.authorizeReleaseRequest.BatchID != "rb-now" { + t.Fatalf("authorize was not composed: called=%v request=%#v", store.authorizeReleaseCalled, store.authorizeReleaseRequest) + } + if store.authorizeReleaseRequest.AuthorizationCode != "production_release_authorized" { + t.Fatalf("authorization code = %q", store.authorizeReleaseRequest.AuthorizationCode) + } + if !strings.Contains(recorder.Body.String(), "rx-safe") { + t.Fatalf("response must carry the execution: %s", recorder.Body.String()) + } +} diff --git a/internal/httpapi/server.go b/internal/httpapi/server.go index 6ab5197..2eb8a41 100644 --- a/internal/httpapi/server.go +++ b/internal/httpapi/server.go @@ -428,6 +428,11 @@ func NewHandler(config Config) (http.Handler, error) { mux.HandleFunc("POST /api/v1/release-batches/{id}/seal", func(w http.ResponseWriter, r *http.Request) { sealReleaseBatch(w, r, config) }) + // 一个动作把"建批(冻结+锁定)→ 授权生产发布"走完:门禁、固定确认语句、管理员身份、 + // 发布前快照门禁全部沿用既有实现,不新增旁路。 + mux.HandleFunc("POST /api/v1/release-batches/publish-now", func(w http.ResponseWriter, r *http.Request) { + publishNowPublications(w, r, config) + }) mux.HandleFunc("POST /api/v1/release-batches/{id}/authorize-production", func(w http.ResponseWriter, r *http.Request) { authorizeProductionRelease(w, r, config) }) @@ -1760,6 +1765,98 @@ type authorizeProductionReleaseRequest struct { Confirmation string `json:"confirmation"` } +type publishNowRequest struct { + PublicationIDs []string `json:"publication_ids"` + DeletePublicationIDs []string `json:"delete_publication_ids"` + Name string `json:"name"` + Confirmation string `json:"confirmation"` +} + +// publishNowPublications:把「建批(冻结 + 锁定)」和「授权生产发布」合成一个动作。 +// +// 它不放松任何约束——只是把操作员本来要按顺序点两次按钮、再来一次确认语句的流程, +// 变成一次带确认语句的提交:请求门禁、备份恢复验证门禁、管理员身份、固定确认语句、 +// 发布前快照硬门禁、清单不可变全都照旧由既有两个入口把关。 +func publishNowPublications(w http.ResponseWriter, r *http.Request, config Config) { + if !config.ProductionReleaseRequestsEnabled { + writeJSON(w, http.StatusForbidden, map[string]string{"error": "production release requests are disabled"}) + return + } + if !config.ProductionBackupRestoreVerified { + writeJSON(w, http.StatusPreconditionFailed, map[string]string{"error": "production backup restore verification is required"}) + return + } + actor, releaseAuthorized := productionReleaseActor(r, config) + if !releaseAuthorized { + writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "production release authorization required"}) + return + } + var input publishNowRequest + if err := decodeStrictJSON(r, &input); err != nil || input.Confirmation != "publish-to-production" { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid production release authorization"}) + return + } + if len(input.PublicationIDs) == 0 && len(input.DeletePublicationIDs) == 0 { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "select at least one publication"}) + return + } + seen := make(map[string]bool, len(input.PublicationIDs)+len(input.DeletePublicationIDs)) + for _, publicationID := range append(append([]string{}, input.PublicationIDs...), input.DeletePublicationIDs...) { + if !validCatalogID(publicationID) || seen[publicationID] || len(seen) > 100 { + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid publication_ids"}) + return + } + seen[publicationID] = true + } + operationID, ok := requireOperationID(w, r) + if !ok { + return + } + name := strings.TrimSpace(input.Name) + if name == "" || len(name) > 200 || strings.ContainsAny(name, "\x00\r\n") { + // 固定回退名:同一请求重放时指纹一致,幂等不会被时间戳破坏。 + name = "立即发布" + } + now := config.Now().UTC() + batch, _, err := config.Store.CreateReleaseBatchWithOperation(r.Context(), governance.CreateReleaseBatchRequest{ + Name: name, CreatedBy: actor, PublicationIDs: input.PublicationIDs, DeletePublicationIDs: input.DeletePublicationIDs, + SealImmediately: true, Now: now, + }, operationID) + switch { + case errors.Is(err, postgresstore.ErrOperationRequestConflict): + writeJSON(w, http.StatusConflict, map[string]string{"error": "Idempotency-Key conflicts with a different request"}) + return + case errors.Is(err, postgresstore.ErrInvalidReleaseBatch): + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid release batch request"}) + return + case errors.Is(err, postgresstore.ErrReleaseBatchNotEligible), errors.Is(err, postgresstore.ErrReleaseBatchGateConflict): + writeJSON(w, http.StatusUnprocessableEntity, map[string]string{"error": "release batch contains ineligible publications"}) + return + case errors.Is(err, postgresstore.ErrReleaseChangeSetUnconfirmed), errors.Is(err, postgresstore.ErrReleaseChangeSetEmpty): + writeJSON(w, http.StatusUnprocessableEntity, map[string]string{"error": "release change set must be confirmed and cover every requested publication"}) + return + case err != nil: + writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not create release batch"}) + return + } + execution, _, err := config.Store.AuthorizeReleaseBatchWithOperation(r.Context(), governance.AuthorizeReleaseBatchRequest{ + BatchID: batch.ID, AuthorizedBy: actor, AuthorizationCode: "production_release_authorized", Now: now, + }, operationID+":authorize") + 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.ErrInvalidReleaseAuthorization): + writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid production release authorization"}) + case errors.Is(err, postgresstore.ErrReleaseAuthorizationGateConflict): + // 批次已锁定但不满足生产门禁(例如快照缺失):如实说明,批次留着不浪费。 + writeJSON(w, http.StatusConflict, map[string]string{"error": "sealed batch no longer satisfies the production release gate"}) + case err != nil: + writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "could not authorize production release"}) + default: + writeJSON(w, http.StatusAccepted, map[string]any{"data": map[string]any{"batch": batch, "execution": execution}}) + } +} + func authorizeProductionRelease(w http.ResponseWriter, r *http.Request, config Config) { if !config.ProductionReleaseRequestsEnabled { writeJSON(w, http.StatusForbidden, map[string]string{"error": "production release requests are disabled"}) diff --git a/web/src/App.tsx b/web/src/App.tsx index aa94ba7..2cd83fd 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -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, reviewPublicationsBatch } from './reviewRelease' +import { confirmReleaseChangeSet, createReleaseBatch, fetchLatestReleaseChangeSet, fetchReleaseAuditChain, fetchReleaseBatch, fetchReleaseBatches, fetchReleaseCapabilities, fetchReleaseExecution, fetchReleaseExecutions, fetchReleasePlan, fetchReviewCandidates, generateReleaseChangeSet, productionConfirmationPhrases, reviewPublication, runProductionAction, sealReleaseBatch, reviewPublicationsBatch , runPublishNow} 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' @@ -228,7 +228,7 @@ interface ModulePageProps extends JobDashboardProps { releaseActionBusy?: boolean releaseActionError?: string | null releaseActionMessage?: string | null - onStartReleaseAction?: (kind: ProductionActionKind, id: string, label: string) => void + onStartReleaseAction?: (kind: ProductionActionKind, id: string, label: string, ids?: string[], deleteIDs?: string[]) => void onReleaseActionPhrase?: (value: string) => void onSubmitReleaseAction?: () => void onCancelReleaseAction?: () => void @@ -239,6 +239,9 @@ export interface PendingReleaseAction { kind: ProductionActionKind id: string label: string + /** publish_now 专用:这次要发布哪些条目(含待删除)。 */ + publicationIDs?: string[] + deletePublicationIDs?: string[] } const emptyAssetPage: SourceAssetPage = { items: [], summary: { total: 0, completed: 0, content_alias: 0, over_limit: 0 }, limit: 50, offset: 0 } @@ -689,13 +692,13 @@ interface ReleaseManagementProps { releaseActionBusy?: boolean releaseActionError?: string | null releaseActionMessage?: string | null - onStartReleaseAction?: (kind: ProductionActionKind, id: string, label: string) => void + onStartReleaseAction?: (kind: ProductionActionKind, id: string, label: string, ids?: string[], deleteIDs?: string[]) => void onReleaseActionPhrase?: (value: string) => void onSubmitReleaseAction?: () => void onCancelReleaseAction?: () => void } -const releaseActionLabels: Record = { authorize: '授权发布', retry: '重排执行', rollback: '回滚发布' } +const releaseActionLabels: Record = { authorize: '授权发布', retry: '重排执行', rollback: '回滚发布', publish_now: '发布到生产' } const acceptanceLabels: Record = { pending: '待验收', @@ -1026,10 +1029,13 @@ export function ReleaseManagement(props: ReleaseManagementProps) { {(() => { // 「可批准」只含尚未决定且门禁通过的条目:已驳回的不能被"全选"顺手翻回来。 const batchable = props.reviewPage.items.filter((item) => item.gate_status === 'ready' && item.review_state === 'pending').map((item) => item.publication_id) + // 已批准且可发布的选中项:一键"发布到生产"(建批+锁定+授权合成一个动作)。 + const publishableSelected = selectedIDs.filter((id) => props.reviewPage.items.some((item) => item.publication_id === id && item.review_state === 'approved' && item.gate_status === 'ready')) return
+ {isAdmin && props.releaseCapabilities.production_release_requests_enabled ? : null} {props.reviewBatchMessage ? {props.reviewBatchMessage} : null}
})()} @@ -1056,7 +1062,7 @@ export function ReleaseManagement(props: ReleaseManagementProps) { {reviewGateLabel(item)} {reviewLabels[item.review_state]}{item.reviewer_ref ? {item.reviewer_ref} : null} -
+
{isAdmin && props.releaseCapabilities.production_release_requests_enabled && item.review_state === 'approved' && item.gate_status === 'ready' ? : null}
})} : null} @@ -1498,8 +1504,8 @@ export default function App() { // 页面上的生产动作:点按钮 → 逐字输入固定确认语句 → 提交。服务端同时校验 // 管理员会话、请求门禁与确认语句;Bearer 通道留给运维脚本,行为不变。 - const handleStartReleaseAction = useCallback((kind: ProductionActionKind, id: string, label: string) => { - setPendingReleaseAction({ kind, id, label }) + const handleStartReleaseAction = useCallback((kind: ProductionActionKind, id: string, label: string, ids?: string[], deleteIDs?: string[]) => { + setPendingReleaseAction({ kind, id, label, publicationIDs: ids, deletePublicationIDs: deleteIDs }) setReleaseActionPhrase('') setReleaseActionError(null) setReleaseActionMessage(null) @@ -1517,8 +1523,15 @@ export default function App() { setReleaseActionError(null) setReleaseActionMessage(null) try { - const summary = await runProductionAction(pendingReleaseAction.kind, pendingReleaseAction.id, releaseActionPhrase.trim()) - setReleaseActionMessage(`${releaseActionLabels[pendingReleaseAction.kind]}已受理:执行 ${summary.id}(${summary.state || 'pending'}) · ${summary.item_count} 项`) + if (pendingReleaseAction.kind === 'publish_now') { + // 名称留空由服务端兜底;这里给一个可读的默认名(确定性内容,重放指纹一致)。 + const defaultName = `立即发布 · ${new Date().toLocaleDateString('zh-CN')}` + const result = await runPublishNow(pendingReleaseAction.publicationIDs ?? [], pendingReleaseAction.deletePublicationIDs ?? [], defaultName, releaseActionPhrase.trim()) + setReleaseActionMessage(`已受理发布:批次 ${result.batch_name || result.batch_id} · 执行 ${result.execution_id}`) + } else { + const summary = await runProductionAction(pendingReleaseAction.kind, pendingReleaseAction.id, releaseActionPhrase.trim()) + setReleaseActionMessage(`${releaseActionLabels[pendingReleaseAction.kind]}已受理:执行 ${summary.id}(${summary.state || 'pending'}) · ${summary.item_count} 项`) + } setPendingReleaseAction(null) setReleaseActionPhrase('') await loadReleaseExecutions() diff --git a/web/src/reviewRelease.test.ts b/web/src/reviewRelease.test.ts index 0cf36ba..3ad851b 100644 --- a/web/src/reviewRelease.test.ts +++ b/web/src/reviewRelease.test.ts @@ -24,6 +24,7 @@ import { reviewPublication, sealReleaseBatch, reviewPublicationsBatch, + runPublishNow, } from './reviewRelease' afterEach(() => vi.unstubAllGlobals()) @@ -222,7 +223,7 @@ describe('production actions', () => { it('surfaces the server reason and keeps the phrases fixed', async () => { vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ error: 'production release authorization required' }), { status: 401 }))) await expect(runProductionAction('authorize', 'rb-1', 'publish-to-production')).rejects.toThrow('production release authorization required') - expect(productionConfirmationPhrases).toEqual({ authorize: 'publish-to-production', retry: 'retry-production-release', rollback: 'rollback-production-release' }) + expect(productionConfirmationPhrases).toEqual({ authorize: 'publish-to-production', retry: 'retry-production-release', rollback: 'rollback-production-release', publish_now: 'publish-to-production' }) vi.unstubAllGlobals() }) }) @@ -286,3 +287,21 @@ describe('批量审核与建批即锁定', () => { expect(JSON.parse(String(init.body)).release_change_set_id).toBe('') }) }) + +describe('发布到生产(建批+锁定+授权合成一个动作)', () => { + it('提交条目与固定确认语句,回传批次与执行', async () => { + const fetchMock = vi.fn().mockResolvedValue({ ok: true, json: async () => ({ data: { batch: { id: 'rb-now', name: '立即发布 · 2026/10/10' }, execution: { id: 'rx-now' } } }) }) + vi.stubGlobal('fetch', fetchMock) + const result = await runPublishNow(['tp-a', 'tp-b'], [], '立即发布 · 2026/10/10', 'publish-to-production') + expect(result).toEqual({ batch_id: 'rb-now', batch_name: '立即发布 · 2026/10/10', execution_id: 'rx-now' }) + const [url, init] = fetchMock.mock.calls[0] + expect(url).toBe('/api/v1/release-batches/publish-now') + expect(JSON.parse(String(init.body))).toEqual({ publication_ids: ['tp-a', 'tp-b'], delete_publication_ids: [], name: '立即发布 · 2026/10/10', confirmation: 'publish-to-production' }) + }) + + it('服务端拒绝时把原因带出来', async () => { + const fetchMock = vi.fn().mockResolvedValue({ ok: false, status: 412, json: async () => ({ error: 'production backup restore verification is required' }) }) + vi.stubGlobal('fetch', fetchMock) + await expect(runPublishNow(['tp-a'], [], 'x', 'publish-to-production')).rejects.toThrow('production backup restore verification is required') + }) +}) diff --git a/web/src/reviewRelease.ts b/web/src/reviewRelease.ts index dc75a0a..1ddf298 100644 --- a/web/src/reviewRelease.ts +++ b/web/src/reviewRelease.ts @@ -581,12 +581,15 @@ export async function fetchReleaseAuditChain(executionID: string, signal?: Abort // ——— 生产动作(授权发布 / 重排 / 回滚)——— // 页面通道:管理员会话 + 服务端逐字核对的固定确认语句。Bearer 通道仍留给运维脚本。 -export type ProductionActionKind = 'authorize' | 'retry' | 'rollback' +export type ProductionActionKind = 'authorize' | 'retry' | 'rollback' | 'publish_now' +/** 仍按"批次/执行 id"寻址的三个动作;publish_now 传的是发布条目本身。 */ +type ConfirmedActionKind = Exclude export const productionConfirmationPhrases: Record = { authorize: 'publish-to-production', retry: 'retry-production-release', rollback: 'rollback-production-release', + publish_now: 'publish-to-production', } export interface ProductionActionSummary { @@ -596,13 +599,44 @@ export interface ProductionActionSummary { item_count: number } -const productionActionPaths: Record string> = { +const productionActionPaths: Record string> = { authorize: (id) => `/api/v1/release-batches/${encodeURIComponent(id)}/authorize-production`, retry: (id) => `/api/v1/release-executions/${encodeURIComponent(id)}/retry`, rollback: (id) => `/api/v1/release-executions/${encodeURIComponent(id)}/authorize-rollback`, } -export async function runProductionAction(kind: ProductionActionKind, id: string, confirmation: string): Promise { +export interface PublishNowResult { + batch_id: string + batch_name: string + execution_id: string +} + +/** + * 一个动作把「建批(冻结 + 锁定)」和「授权生产发布」走完。 + * 服务端不放松任何约束:请求门禁、备份恢复验证门禁、管理员身份、固定确认语句、 + * 发布前快照硬门禁全部照旧;这里只是把操作员的两步点击合成一次带确认的提交。 + */ +export async function runPublishNow(publicationIDs: string[], deletePublicationIDs: string[], name: string, confirmation: string): Promise { + const response = await fetch('/api/v1/release-batches/publish-now', { + method: 'POST', + headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'Idempotency-Key': newOperationID() }, + body: JSON.stringify({ publication_ids: publicationIDs, delete_publication_ids: deletePublicationIDs, name, confirmation }), + }) + const payload: unknown = await response.json().catch(() => null) + if (!response.ok) { + const reason = isRecord(payload) && typeof payload.error === 'string' ? payload.error : `发布到生产失败(HTTP ${response.status})` + throw new Error(reason) + } + if (!isRecord(payload) || !isRecord(payload.data)) throw new Error('发布到生产响应无效') + const batch = payload.data.batch + const execution = payload.data.execution + if (!isRecord(batch) || !isRecord(execution) || typeof batch.id !== 'string' || typeof execution.id !== 'string') { + throw new Error('发布到生产响应无效') + } + return { batch_id: batch.id, batch_name: typeof batch.name === 'string' ? batch.name : '', execution_id: execution.id } +} + +export async function runProductionAction(kind: ConfirmedActionKind, id: string, confirmation: string): Promise { const response = await fetch(productionActionPaths[kind](id), { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'Idempotency-Key': newOperationID() },