70131c6161
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 条通过。
625 lines
34 KiB
TypeScript
625 lines
34 KiB
TypeScript
import { newOperationID } from './operationKey'
|
||
export type ReviewState = 'pending' | 'approved' | 'rejected'
|
||
export type Visibility = 'internal' | 'external'
|
||
export type AcceptanceState = 'pending' | 'passed' | 'failed' | 'manual_required'
|
||
export type ReviewGateStatus = 'ready' | 'blocked'
|
||
export type ReleaseBatchState = 'draft' | 'sealed' | 'cancelled'
|
||
export type ReleaseOperation = 'publish' | 'rollback'
|
||
export type ReleaseExecutionState = 'pending' | 'running' | 'completed' | 'failed' | 'rolling_back' | 'rolled_back' | 'rollback_failed'
|
||
|
||
export interface ReviewCandidate {
|
||
publication_id: string
|
||
title: string
|
||
source_type: 'pp' | 'alist' | 'dingtalk' | 'manual'
|
||
current_visibility: Visibility
|
||
knowledge_exists: AcceptanceState
|
||
chunks_present: AcceptanceState
|
||
retrieval_hit: AcceptanceState
|
||
gate_status: ReviewGateStatus
|
||
gate_code: string
|
||
review_state: ReviewState
|
||
decided_visibility: Visibility | ''
|
||
decision_code: string
|
||
reviewer_ref: string
|
||
reviewed_at: string | null
|
||
updated_at: string
|
||
}
|
||
|
||
export interface ReviewCandidatePage {
|
||
items: ReviewCandidate[]
|
||
total: number
|
||
limit: number
|
||
offset: number
|
||
}
|
||
|
||
export interface PublicationReview {
|
||
id: string
|
||
publication_id: string
|
||
decision: 'approved' | 'rejected'
|
||
decided_visibility: Visibility
|
||
reviewer_ref: string
|
||
decision_code: string
|
||
created_at: string
|
||
}
|
||
|
||
export interface ReleaseBatch {
|
||
release_change_set_id?: string
|
||
id: string
|
||
name: string
|
||
state: ReleaseBatchState
|
||
policy_version: string
|
||
created_by: string
|
||
sealed_by: string
|
||
item_count: number
|
||
created_at: string
|
||
sealed_at: string | null
|
||
}
|
||
|
||
export interface ReleaseBatchPage {
|
||
items: ReleaseBatch[]
|
||
total: number
|
||
limit: number
|
||
offset: number
|
||
}
|
||
|
||
export interface ReleaseBatchItem {
|
||
publication_id: string
|
||
title: string
|
||
decided_visibility: Visibility
|
||
action: 'upsert' | 'delete'
|
||
}
|
||
|
||
export interface ReleaseBatchDetail extends ReleaseBatch {
|
||
items: ReleaseBatchItem[]
|
||
}
|
||
|
||
export interface ReleaseExecution {
|
||
id: string
|
||
release_batch_id: string
|
||
operation: ReleaseOperation
|
||
prior_execution_id: string
|
||
state: ReleaseExecutionState
|
||
target_environment: 'production'
|
||
authorized_by: string
|
||
job_id: string
|
||
item_count: number
|
||
batch_size: number
|
||
current_batch: number
|
||
total_batches: number
|
||
completed_item_count: number
|
||
failed_item_count: number
|
||
error_code: string
|
||
failure_level?: string
|
||
restore_trigger?: string
|
||
created_at: string
|
||
started_at: string | null
|
||
completed_at: string | null
|
||
}
|
||
|
||
export interface ReleaseExecutionPage {
|
||
items: ReleaseExecution[]
|
||
total: number
|
||
limit: number
|
||
offset: number
|
||
}
|
||
|
||
export interface ReleaseItemExecution {
|
||
publication_id: string
|
||
title: string
|
||
action: 'upsert' | 'delete'
|
||
state: 'pending' | 'staged' | 'activated' | 'verified' | 'failed' | 'rolled_back'
|
||
previous_production_revision: string
|
||
production_revision: string
|
||
error_code: string
|
||
created_at: string
|
||
completed_at: string | null
|
||
target_knowledge_base_id: string
|
||
}
|
||
|
||
export interface ReleaseExecutionDetail extends ReleaseExecution {
|
||
items: ReleaseItemExecution[]
|
||
}
|
||
|
||
export interface ReleaseCapabilities {
|
||
production_release_requests_enabled: boolean
|
||
production_backup_restore_verified: boolean
|
||
/** 当前审核策略(只读展示):off / internal / all。旧服务端不返回时按空串处理。 */
|
||
test_auto_review_policy: string
|
||
}
|
||
|
||
export interface ReleasePlanItem {
|
||
publication_id: string
|
||
title: string
|
||
target_scope: Visibility
|
||
action: 'add' | 'update' | 'delete' | 'blocked'
|
||
test_state: 'ready' | 'not_ready' | 'not_required'
|
||
production_state: 'present' | 'absent'
|
||
can_release: boolean
|
||
blocker: string
|
||
}
|
||
|
||
export interface ReleasePlan {
|
||
items: ReleasePlanItem[]
|
||
summary: { add: number; update: number; delete: number; blocked: number; unchanged: number }
|
||
}
|
||
|
||
const sourceTypes = new Set(['pp', 'alist', 'dingtalk', 'manual'])
|
||
const visibilities = new Set<Visibility>(['internal', 'external'])
|
||
const acceptanceStates = new Set<AcceptanceState>(['pending', 'passed', 'failed', 'manual_required'])
|
||
const reviewStates = new Set<ReviewState>(['pending', 'approved', 'rejected'])
|
||
const gateStatuses = new Set<ReviewGateStatus>(['ready', 'blocked'])
|
||
const batchStates = new Set<ReleaseBatchState>(['draft', 'sealed', 'cancelled'])
|
||
const releaseOperations = new Set<ReleaseOperation>(['publish', 'rollback'])
|
||
const releaseExecutionStates = new Set<ReleaseExecutionState>(['pending', 'running', 'completed', 'failed', 'rolling_back', 'rolled_back', 'rollback_failed'])
|
||
const releaseItemStates = new Set<ReleaseItemExecution['state']>(['pending', 'staged', 'activated', 'verified', 'failed', 'rolled_back'])
|
||
const releasePlanActions = new Set<ReleasePlanItem['action']>(['add', 'update', 'delete', 'blocked'])
|
||
const releasePlanTestStates = new Set<ReleasePlanItem['test_state']>(['ready', 'not_ready', 'not_required'])
|
||
|
||
export function parseReviewCandidatesResponse(value: unknown): ReviewCandidatePage {
|
||
const envelope = parsePageEnvelope(value, 'review candidates')
|
||
return {
|
||
items: envelope.rawItems.map(parseReviewCandidate),
|
||
total: envelope.total,
|
||
limit: envelope.limit,
|
||
offset: envelope.offset,
|
||
}
|
||
}
|
||
|
||
export function parseReleaseBatchesResponse(value: unknown): ReleaseBatchPage {
|
||
const envelope = parsePageEnvelope(value, 'release batches')
|
||
return {
|
||
items: envelope.rawItems.map(parseReleaseBatch),
|
||
total: envelope.total,
|
||
limit: envelope.limit,
|
||
offset: envelope.offset,
|
||
}
|
||
}
|
||
|
||
export function parseReleaseBatchDetailResponse(value: unknown): ReleaseBatchDetail {
|
||
if (!isRecord(value) || !isRecord(value.data) || !Array.isArray(value.data.items)) {
|
||
throw new Error('invalid release batch detail response')
|
||
}
|
||
const batch = parseReleaseBatch(value.data)
|
||
const items = value.data.items.map((raw): ReleaseBatchItem => {
|
||
if (!isRecord(raw) || typeof raw.publication_id !== 'string' || typeof raw.title !== 'string' ||
|
||
typeof raw.decided_visibility !== 'string' || !visibilities.has(raw.decided_visibility as Visibility) ||
|
||
(raw.action !== 'upsert' && raw.action !== 'delete')) {
|
||
throw new Error('invalid release batch item')
|
||
}
|
||
return { publication_id: raw.publication_id, title: raw.title, decided_visibility: raw.decided_visibility as Visibility, action: raw.action }
|
||
})
|
||
return { ...batch, items }
|
||
}
|
||
|
||
export function parseReleaseExecutionsResponse(value: unknown): ReleaseExecutionPage {
|
||
const envelope = parsePageEnvelope(value, 'release executions')
|
||
return {
|
||
items: envelope.rawItems.map(parseReleaseExecution),
|
||
total: envelope.total,
|
||
limit: envelope.limit,
|
||
offset: envelope.offset,
|
||
}
|
||
}
|
||
|
||
export function parseReleaseExecutionDetailResponse(value: unknown): ReleaseExecutionDetail {
|
||
if (!isRecord(value) || !isRecord(value.data) || !Array.isArray(value.data.items)) {
|
||
throw new Error('invalid release execution detail response')
|
||
}
|
||
const execution = parseReleaseExecution(value.data)
|
||
const items = value.data.items.map(parseReleaseItemExecution)
|
||
return { ...execution, items }
|
||
}
|
||
|
||
export function parseReleaseCapabilitiesResponse(value: unknown): ReleaseCapabilities {
|
||
if (!isRecord(value) || !isRecord(value.data) || typeof value.data.production_release_requests_enabled !== 'boolean' || typeof value.data.production_backup_restore_verified !== 'boolean') {
|
||
throw new Error('invalid release capabilities response')
|
||
}
|
||
// 审核策略是只读展示项:旧服务端不返回时不报错(空串 = 界面不显示这一行)。
|
||
const policy = typeof value.data.test_auto_review_policy === 'string' ? value.data.test_auto_review_policy : ''
|
||
return {
|
||
production_release_requests_enabled: value.data.production_release_requests_enabled,
|
||
production_backup_restore_verified: value.data.production_backup_restore_verified,
|
||
test_auto_review_policy: policy,
|
||
}
|
||
}
|
||
|
||
export function parseReleasePlanResponse(value: unknown): ReleasePlan {
|
||
if (!isRecord(value) || !isRecord(value.data) || !Array.isArray(value.data.items) || !isRecord(value.data.summary)) {
|
||
throw new Error('invalid release plan response')
|
||
}
|
||
const summary = value.data.summary
|
||
if (!isCount(summary.add) || !isCount(summary.update) || !isCount(summary.delete) || !isCount(summary.blocked) || !isCount(summary.unchanged)) {
|
||
throw new Error('invalid release plan response')
|
||
}
|
||
const items = value.data.items.map((raw): ReleasePlanItem => {
|
||
if (!isRecord(raw) || typeof raw.publication_id !== 'string' || typeof raw.title !== 'string' ||
|
||
typeof raw.target_scope !== 'string' || !visibilities.has(raw.target_scope as Visibility) ||
|
||
typeof raw.action !== 'string' || !releasePlanActions.has(raw.action as ReleasePlanItem['action']) ||
|
||
typeof raw.test_state !== 'string' || !releasePlanTestStates.has(raw.test_state as ReleasePlanItem['test_state']) ||
|
||
(raw.production_state !== 'present' && raw.production_state !== 'absent') || typeof raw.can_release !== 'boolean' || typeof raw.blocker !== 'string') {
|
||
throw new Error('invalid release plan item')
|
||
}
|
||
return {
|
||
publication_id: raw.publication_id,
|
||
title: raw.title,
|
||
target_scope: raw.target_scope as Visibility,
|
||
action: raw.action as ReleasePlanItem['action'],
|
||
test_state: raw.test_state as ReleasePlanItem['test_state'],
|
||
production_state: raw.production_state,
|
||
can_release: raw.can_release,
|
||
blocker: raw.blocker,
|
||
}
|
||
})
|
||
return { items, summary: { add: summary.add, update: summary.update, delete: summary.delete, blocked: summary.blocked, unchanged: summary.unchanged } }
|
||
}
|
||
|
||
export async function fetchReviewCandidates(reviewState: ReviewState | '' = '', limit = 20, offset = 0, signal?: AbortSignal): Promise<ReviewCandidatePage> {
|
||
const params = new URLSearchParams({ review_state: reviewState, limit: String(limit), offset: String(offset) })
|
||
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,
|
||
}, '提交审核决定失败')
|
||
if (!isRecord(value) || !isRecord(value.data)) throw new Error('invalid publication review response')
|
||
const raw = value.data
|
||
if (typeof raw.id !== 'string' || typeof raw.publication_id !== 'string' ||
|
||
(raw.decision !== 'approved' && raw.decision !== 'rejected') || typeof raw.decided_visibility !== 'string' ||
|
||
!visibilities.has(raw.decided_visibility as Visibility) || typeof raw.reviewer_ref !== 'string' ||
|
||
typeof raw.decision_code !== 'string' || typeof raw.created_at !== 'string') {
|
||
throw new Error('invalid publication review response')
|
||
}
|
||
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 = '', 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 {
|
||
seq: number
|
||
publication_id: string
|
||
title: string
|
||
target_scope: Visibility
|
||
action: 'add' | 'update' | 'delete' | 'blocked' | 'unchanged'
|
||
test_state: string
|
||
production_state: string
|
||
can_release: boolean
|
||
blocker: string
|
||
}
|
||
export interface ReleaseChangeSet {
|
||
id: string
|
||
number: number
|
||
name: string
|
||
state: 'planned' | 'confirmed' | 'consumed' | 'cancelled'
|
||
source_snapshot_ids: string[]
|
||
source_change_set_ids: string[]
|
||
acceptance_cutoff: string
|
||
production_baseline_ref: string
|
||
item_count: number
|
||
add_count: number
|
||
update_count: number
|
||
delete_count: number
|
||
blocked_count: number
|
||
manifest_sha256: string
|
||
created_by: string
|
||
created_at: string
|
||
confirmed_by: string
|
||
confirmed_at: string | null
|
||
}
|
||
export interface ReleaseChangeSetDetail extends ReleaseChangeSet {
|
||
items: ReleaseChangeSetItem[]
|
||
}
|
||
|
||
function parseChangeSetEnvelope(value: unknown): ReleaseChangeSet {
|
||
if (!isRecord(value) || !isRecord(value.data)) throw new Error('发布计划集响应无效')
|
||
const data = value.data
|
||
const text = (key: string) => typeof data[key] === 'string' ? data[key] as string : ''
|
||
const number = (key: string) => typeof data[key] === 'number' && Number.isFinite(data[key]) ? data[key] as number : 0
|
||
const id = text('id')
|
||
const manifest = text('manifest_sha256')
|
||
if (!id || !/^[0-9a-f]{64}$/.test(manifest)) throw new Error('发布计划集响应缺少标识或清单摘要')
|
||
const snapshots = Array.isArray(data.source_snapshot_ids) ? data.source_snapshot_ids.filter((item): item is string => typeof item === 'string') : []
|
||
const catalogSets = Array.isArray(data.source_change_set_ids) ? data.source_change_set_ids.filter((item): item is string => typeof item === 'string') : []
|
||
const confirmedRaw = data.confirmed_at
|
||
return {
|
||
id, number: number('number'), name: text('name'),
|
||
state: data.state === 'confirmed' || data.state === 'consumed' || data.state === 'cancelled' ? data.state : 'planned',
|
||
source_snapshot_ids: snapshots, source_change_set_ids: catalogSets,
|
||
acceptance_cutoff: text('acceptance_cutoff'), production_baseline_ref: text('production_baseline_ref'),
|
||
item_count: number('item_count'), add_count: number('add_count'), update_count: number('update_count'),
|
||
delete_count: number('delete_count'), blocked_count: number('blocked_count'),
|
||
manifest_sha256: manifest, created_by: text('created_by'), created_at: text('created_at'),
|
||
confirmed_by: text('confirmed_by'), confirmed_at: typeof confirmedRaw === 'string' && confirmedRaw ? confirmedRaw : null,
|
||
}
|
||
}
|
||
|
||
// R1: freeze the live release plan into an immutable versioned change set.
|
||
export async function generateReleaseChangeSet(name: string): Promise<ReleaseChangeSet> {
|
||
return parseChangeSetEnvelope(await sendJSON('/api/v1/release-change-sets', { name }, '生成发布计划集失败'))
|
||
}
|
||
|
||
export async function confirmReleaseChangeSet(changeSetID: string): Promise<ReleaseChangeSet> {
|
||
return parseChangeSetEnvelope(await sendJSON(`/api/v1/release-change-sets/${encodeURIComponent(changeSetID)}/confirm`, {}, '确认发布计划集失败'))
|
||
}
|
||
|
||
export async function fetchLatestReleaseChangeSet(signal?: AbortSignal): Promise<ReleaseChangeSetDetail | null> {
|
||
const response = await fetch('/api/v1/release-change-sets/latest', { headers: { Accept: 'application/json' }, signal })
|
||
if (response.status === 404) return null
|
||
if (!response.ok) throw new Error(`加载发布计划集失败(HTTP ${response.status})`)
|
||
const value = await response.json() as unknown
|
||
const base = parseChangeSetEnvelope(value)
|
||
const data = (value as Record<string, unknown>).data as Record<string, unknown>
|
||
const rawItems = Array.isArray(data.items) ? data.items : []
|
||
const items: ReleaseChangeSetItem[] = []
|
||
for (const raw of rawItems) {
|
||
if (!isRecord(raw)) continue
|
||
const action = raw.action
|
||
const scope = raw.target_scope
|
||
if (typeof raw.publication_id !== 'string' || (action !== 'add' && action !== 'update' && action !== 'delete' && action !== 'blocked' && action !== 'unchanged') || (scope !== 'internal' && scope !== 'external')) continue
|
||
items.push({
|
||
seq: typeof raw.seq === 'number' ? raw.seq : 0, publication_id: raw.publication_id, title: typeof raw.title === 'string' ? raw.title : '',
|
||
target_scope: scope, action, test_state: typeof raw.test_state === 'string' ? raw.test_state : '', production_state: typeof raw.production_state === 'string' ? raw.production_state : '',
|
||
can_release: raw.can_release === true, blocker: typeof raw.blocker === 'string' ? raw.blocker : '',
|
||
})
|
||
}
|
||
return { ...base, items }
|
||
}
|
||
|
||
export async function sealReleaseBatch(batchID: string): Promise<ReleaseBatch> {
|
||
return parseBatchEnvelope(await sendJSON(`/api/v1/release-batches/${encodeURIComponent(batchID)}/seal`, {}, '封批失败'))
|
||
}
|
||
|
||
export async function fetchReleaseBatches(state: ReleaseBatchState | '' = '', limit = 20, offset = 0, signal?: AbortSignal): Promise<ReleaseBatchPage> {
|
||
const params = new URLSearchParams({ state, limit: String(limit), offset: String(offset) })
|
||
return parseReleaseBatchesResponse(await getJSON(`/api/v1/release-batches?${params}`, signal, '加载封批列表失败'))
|
||
}
|
||
|
||
export async function fetchReleaseBatch(batchID: string, signal?: AbortSignal): Promise<ReleaseBatchDetail> {
|
||
return parseReleaseBatchDetailResponse(await getJSON(`/api/v1/release-batches/${encodeURIComponent(batchID)}`, signal, '加载封批详情失败'))
|
||
}
|
||
|
||
export async function fetchReleaseExecutions(operation: ReleaseOperation | '' = '', state: ReleaseExecutionState | '' = '', limit = 20, offset = 0, signal?: AbortSignal): Promise<ReleaseExecutionPage> {
|
||
const params = new URLSearchParams({ operation, state, limit: String(limit), offset: String(offset) })
|
||
return parseReleaseExecutionsResponse(await getJSON(`/api/v1/release-executions?${params}`, signal, '加载生产发布审计失败'))
|
||
}
|
||
|
||
export async function fetchReleaseExecution(executionID: string, signal?: AbortSignal): Promise<ReleaseExecutionDetail> {
|
||
return parseReleaseExecutionDetailResponse(await getJSON(`/api/v1/release-executions/${encodeURIComponent(executionID)}`, signal, '加载生产发布详情失败'))
|
||
}
|
||
|
||
export async function fetchReleaseCapabilities(signal?: AbortSignal): Promise<ReleaseCapabilities> {
|
||
return parseReleaseCapabilitiesResponse(await getJSON('/api/v1/release-capabilities', signal, '加载生产发布门禁失败'))
|
||
}
|
||
|
||
export async function fetchReleasePlan(signal?: AbortSignal): Promise<ReleasePlan> {
|
||
return parseReleasePlanResponse(await getJSON('/api/v1/release-plan', signal, '加载发布计划失败'))
|
||
}
|
||
|
||
function parseReviewCandidate(raw: unknown): ReviewCandidate {
|
||
if (!isRecord(raw) || typeof raw.publication_id !== 'string' || typeof raw.title !== 'string' ||
|
||
typeof raw.source_type !== 'string' || !sourceTypes.has(raw.source_type) ||
|
||
typeof raw.current_visibility !== 'string' || !visibilities.has(raw.current_visibility as Visibility) ||
|
||
typeof raw.knowledge_exists !== 'string' || !acceptanceStates.has(raw.knowledge_exists as AcceptanceState) ||
|
||
typeof raw.chunks_present !== 'string' || !acceptanceStates.has(raw.chunks_present as AcceptanceState) ||
|
||
typeof raw.retrieval_hit !== 'string' || !acceptanceStates.has(raw.retrieval_hit as AcceptanceState) ||
|
||
typeof raw.gate_status !== 'string' || !gateStatuses.has(raw.gate_status as ReviewGateStatus) ||
|
||
typeof raw.gate_code !== 'string' || typeof raw.review_state !== 'string' || !reviewStates.has(raw.review_state as ReviewState) ||
|
||
typeof raw.decided_visibility !== 'string' || (raw.decided_visibility !== '' && !visibilities.has(raw.decided_visibility as Visibility)) ||
|
||
typeof raw.decision_code !== 'string' || typeof raw.reviewer_ref !== 'string' ||
|
||
(raw.reviewed_at !== null && typeof raw.reviewed_at !== 'string') || typeof raw.updated_at !== 'string') {
|
||
throw new Error('invalid review candidate')
|
||
}
|
||
return {
|
||
publication_id: raw.publication_id, title: raw.title, source_type: raw.source_type as ReviewCandidate['source_type'],
|
||
current_visibility: raw.current_visibility as Visibility, knowledge_exists: raw.knowledge_exists as AcceptanceState,
|
||
chunks_present: raw.chunks_present as AcceptanceState, retrieval_hit: raw.retrieval_hit as AcceptanceState,
|
||
gate_status: raw.gate_status as ReviewGateStatus, gate_code: raw.gate_code, review_state: raw.review_state as ReviewState,
|
||
decided_visibility: raw.decided_visibility as Visibility | '', decision_code: raw.decision_code, reviewer_ref: raw.reviewer_ref,
|
||
reviewed_at: raw.reviewed_at as string | null, updated_at: raw.updated_at,
|
||
}
|
||
}
|
||
|
||
function parseReleaseExecution(raw: unknown): ReleaseExecution {
|
||
if (!isRecord(raw) || typeof raw.id !== 'string' || typeof raw.release_batch_id !== 'string' ||
|
||
typeof raw.operation !== 'string' || !releaseOperations.has(raw.operation as ReleaseOperation) ||
|
||
typeof raw.prior_execution_id !== 'string' || typeof raw.state !== 'string' || !releaseExecutionStates.has(raw.state as ReleaseExecutionState) ||
|
||
raw.target_environment !== 'production' || typeof raw.authorized_by !== 'string' || typeof raw.job_id !== 'string' ||
|
||
!isCount(raw.item_count) || !isCount(raw.batch_size) || !isCount(raw.current_batch) || !isCount(raw.total_batches) || !isCount(raw.completed_item_count) || !isCount(raw.failed_item_count) ||
|
||
typeof raw.error_code !== 'string' || typeof raw.created_at !== 'string' ||
|
||
(raw.started_at !== null && typeof raw.started_at !== 'string') ||
|
||
(raw.completed_at !== null && typeof raw.completed_at !== 'string')) {
|
||
throw new Error('invalid release execution')
|
||
}
|
||
return {
|
||
id: raw.id, release_batch_id: raw.release_batch_id, operation: raw.operation as ReleaseOperation,
|
||
prior_execution_id: raw.prior_execution_id, state: raw.state as ReleaseExecutionState,
|
||
target_environment: 'production', authorized_by: raw.authorized_by, job_id: raw.job_id,
|
||
item_count: raw.item_count, batch_size: raw.batch_size, current_batch: raw.current_batch, total_batches: raw.total_batches, completed_item_count: raw.completed_item_count, failed_item_count: raw.failed_item_count,
|
||
error_code: raw.error_code, created_at: raw.created_at, started_at: raw.started_at as string | null,
|
||
completed_at: raw.completed_at as string | null,
|
||
failure_level: typeof raw.failure_level === 'string' ? raw.failure_level : '',
|
||
restore_trigger: typeof raw.restore_trigger === 'string' ? raw.restore_trigger : '',
|
||
}
|
||
}
|
||
|
||
function parseReleaseItemExecution(raw: unknown): ReleaseItemExecution {
|
||
if (!isRecord(raw) || typeof raw.publication_id !== 'string' || typeof raw.title !== 'string' ||
|
||
(raw.action !== 'upsert' && raw.action !== 'delete') ||
|
||
typeof raw.state !== 'string' || !releaseItemStates.has(raw.state as ReleaseItemExecution['state']) ||
|
||
typeof raw.previous_production_revision !== 'string' || typeof raw.production_revision !== 'string' ||
|
||
typeof raw.error_code !== 'string' || typeof raw.created_at !== 'string' ||
|
||
(raw.completed_at !== null && typeof raw.completed_at !== 'string')) {
|
||
throw new Error('invalid release item execution')
|
||
}
|
||
return {
|
||
publication_id: raw.publication_id, title: raw.title, action: raw.action, state: raw.state as ReleaseItemExecution['state'],
|
||
previous_production_revision: raw.previous_production_revision, production_revision: raw.production_revision,
|
||
target_knowledge_base_id: typeof raw.target_knowledge_base_id === 'string' ? raw.target_knowledge_base_id : '',
|
||
error_code: raw.error_code, created_at: raw.created_at, completed_at: raw.completed_at as string | null,
|
||
}
|
||
}
|
||
|
||
function parseReleaseBatch(raw: unknown): ReleaseBatch {
|
||
if (!isRecord(raw) || typeof raw.id !== 'string' || typeof raw.name !== 'string' ||
|
||
typeof raw.state !== 'string' || !batchStates.has(raw.state as ReleaseBatchState) || typeof raw.policy_version !== 'string' ||
|
||
typeof raw.created_by !== 'string' || typeof raw.sealed_by !== 'string' || !isCount(raw.item_count) ||
|
||
typeof raw.created_at !== 'string' || (raw.sealed_at !== null && typeof raw.sealed_at !== 'string')) {
|
||
throw new Error('invalid release batch')
|
||
}
|
||
return { id: raw.id, name: raw.name, state: raw.state as ReleaseBatchState, policy_version: raw.policy_version, created_by: raw.created_by, sealed_by: raw.sealed_by, item_count: raw.item_count, created_at: raw.created_at, sealed_at: raw.sealed_at as string | null }
|
||
}
|
||
|
||
function parseBatchEnvelope(value: unknown): ReleaseBatch {
|
||
if (!isRecord(value) || !isRecord(value.data)) throw new Error('invalid release batch response')
|
||
return parseReleaseBatch(value.data)
|
||
}
|
||
|
||
function parsePageEnvelope(value: unknown, label: string) {
|
||
if (!isRecord(value) || !Array.isArray(value.data) || !isCount(value.total) || !isCount(value.limit) || value.limit < 1 || !isCount(value.offset)) {
|
||
throw new Error(`invalid ${label} response`)
|
||
}
|
||
return { rawItems: value.data, total: value.total, limit: value.limit, offset: value.offset }
|
||
}
|
||
|
||
// 服务端对写操作会回 {"error": "<原因>"}。旧写法只显示 HTTP 状态码,等于把原因丢掉——
|
||
// 运维看到「创建封批失败(HTTP 422)」完全无从下手(实测:真实原因是"所选知识不在已冻结的
|
||
// 发布清单里",先点「生成新版本」+「确认冻结」即可)。这里把原因带上,并对已知原因给出下一步。
|
||
const releaseFailureHints: Record<string, string> = {
|
||
'release change set must be confirmed and cover every requested publication':
|
||
':所选知识不在已冻结的发布清单里 —— 请先点「生成新版本」再「确认冻结(此后不可更改)」,然后重新建批',
|
||
'release batch contains ineligible publications':
|
||
':所选知识当前不满足发布条件(需重新确认审核结论/测试结果/发布范围)',
|
||
'current release plan has no releasable item': ':当前发布计划里没有可发布项',
|
||
}
|
||
|
||
async function failureMessage(response: Response, message: string): Promise<string> {
|
||
const body = await response.json().catch(() => null) as unknown
|
||
const reason = isRecord(body) && typeof body.error === 'string' ? body.error : ''
|
||
if (!reason) return `${message}(HTTP ${response.status})`
|
||
return `${message}(HTTP ${response.status})${releaseFailureHints[reason] ?? `:${reason}`}`
|
||
}
|
||
|
||
async function getJSON(url: string, signal: AbortSignal | undefined, message: string): Promise<unknown> {
|
||
const response = await fetch(url, { headers: { Accept: 'application/json' }, signal })
|
||
if (!response.ok) throw new Error(await failureMessage(response, message))
|
||
return response.json()
|
||
}
|
||
|
||
async function sendJSON(url: string, body: unknown, message: string): Promise<unknown> {
|
||
const response = await fetch(url, { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'Idempotency-Key': newOperationID() }, body: JSON.stringify(body) })
|
||
if (!response.ok) throw new Error(await failureMessage(response, message))
|
||
return response.json()
|
||
}
|
||
|
||
function isRecord(value: unknown): value is Record<string, unknown> {
|
||
return typeof value === 'object' && value !== null
|
||
}
|
||
|
||
function isCount(value: unknown): value is number {
|
||
return typeof value === 'number' && Number.isInteger(value) && value >= 0
|
||
}
|
||
|
||
const auditText = (row: Record<string, unknown>, key: string): string => typeof row[key] === 'string' ? row[key] as string : ''
|
||
const auditNumber = (row: Record<string, unknown>, key: string): number => typeof row[key] === 'number' && Number.isFinite(row[key]) ? row[key] as number : 0
|
||
export interface AuditSnapshot { id: string; source_name: string; node_count: number; file_count: number; observed_at: string }
|
||
export interface AuditCatalogSet { id: string; state: string; add_count: number; update_count: number; move_count: number; delete_count: number }
|
||
export interface AuditChainItem { publication_id: string; title: string; action: string; item_state: string; review_id: string; acceptance_run_id: string; source_item_id: string; source_item_version_id: string; production_revision: string; error_code: string }
|
||
export interface ReleaseAuditChain {
|
||
execution_id: string; operation: string; state: string; failure_level: string
|
||
release_batch_id: string; release_batch_name: string; created_by: string; sealed_by: string; authorized_by: string
|
||
release_change_set_id: string; release_change_set_name: string; release_change_set_state: string
|
||
release_change_set_created_by: string; release_change_set_confirmed_by: string; release_change_set_confirmed_at: string | null
|
||
manifest_sha256: string; snapshots: AuditSnapshot[]; catalog_change_sets: AuditCatalogSet[]
|
||
prior_execution_id: string; rollback_execution_id: string; items: AuditChainItem[]
|
||
}
|
||
export async function fetchReleaseAuditChain(executionID: string, signal?: AbortSignal): Promise<ReleaseAuditChain | null> {
|
||
const response = await fetch(`/api/v1/release-executions/${encodeURIComponent(executionID)}/audit-chain`, { headers: { Accept: 'application/json' }, signal })
|
||
if (response.status === 404) return null
|
||
if (!response.ok) throw new Error(`加载发布审计链失败(HTTP ${response.status})`)
|
||
const value = await response.json() as unknown
|
||
if (!isRecord(value) || !isRecord(value.data)) throw new Error('发布审计链响应无效')
|
||
const data = value.data
|
||
const rows = (key: string): Record<string, unknown>[] => Array.isArray(data[key]) ? (data[key] as unknown[]).filter(isRecord) : []
|
||
return {
|
||
execution_id: auditText(data, 'execution_id'), operation: auditText(data, 'operation'), state: auditText(data, 'state'), failure_level: auditText(data, 'failure_level'),
|
||
release_batch_id: auditText(data, 'release_batch_id'), release_batch_name: auditText(data, 'release_batch_name'), created_by: auditText(data, 'created_by'), sealed_by: auditText(data, 'sealed_by'), authorized_by: auditText(data, 'authorized_by'),
|
||
release_change_set_id: auditText(data, 'release_change_set_id'), release_change_set_name: auditText(data, 'release_change_set_name'), release_change_set_state: auditText(data, 'release_change_set_state'),
|
||
release_change_set_created_by: auditText(data, 'release_change_set_created_by'), release_change_set_confirmed_by: auditText(data, 'release_change_set_confirmed_by'),
|
||
release_change_set_confirmed_at: typeof data.release_change_set_confirmed_at === 'string' ? data.release_change_set_confirmed_at : null,
|
||
manifest_sha256: auditText(data, 'manifest_sha256'),
|
||
snapshots: rows('snapshots').map((row) => ({ id: auditText(row, 'id'), source_name: auditText(row, 'source_name'), node_count: auditNumber(row, 'node_count'), file_count: auditNumber(row, 'file_count'), observed_at: auditText(row, 'observed_at') })),
|
||
catalog_change_sets: rows('catalog_change_sets').map((row) => ({ id: auditText(row, 'id'), state: auditText(row, 'state'), add_count: auditNumber(row, 'add_count'), update_count: auditNumber(row, 'update_count'), move_count: auditNumber(row, 'move_count'), delete_count: auditNumber(row, 'delete_count') })),
|
||
prior_execution_id: auditText(data, 'prior_execution_id'), rollback_execution_id: auditText(data, 'rollback_execution_id'),
|
||
items: rows('items').map((row) => ({ publication_id: auditText(row, 'publication_id'), title: auditText(row, 'title'), action: auditText(row, 'action'), item_state: auditText(row, 'item_state'), review_id: auditText(row, 'review_id'), acceptance_run_id: auditText(row, 'acceptance_run_id'), source_item_id: auditText(row, 'source_item_id'), source_item_version_id: auditText(row, 'source_item_version_id'), production_revision: auditText(row, 'production_revision'), error_code: auditText(row, 'error_code') })),
|
||
}
|
||
}
|
||
|
||
// ——— 生产动作(授权发布 / 重排 / 回滚)———
|
||
// 页面通道:管理员会话 + 服务端逐字核对的固定确认语句。Bearer 通道仍留给运维脚本。
|
||
export type ProductionActionKind = 'authorize' | 'retry' | 'rollback'
|
||
|
||
export const productionConfirmationPhrases: Record<ProductionActionKind, string> = {
|
||
authorize: 'publish-to-production',
|
||
retry: 'retry-production-release',
|
||
rollback: 'rollback-production-release',
|
||
}
|
||
|
||
export interface ProductionActionSummary {
|
||
id: string
|
||
state: string
|
||
operation: string
|
||
item_count: number
|
||
}
|
||
|
||
const productionActionPaths: Record<ProductionActionKind, (id: string) => 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<ProductionActionSummary> {
|
||
const response = await fetch(productionActionPaths[kind](id), {
|
||
method: 'POST',
|
||
headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'Idempotency-Key': newOperationID() },
|
||
body: JSON.stringify({ 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 data = payload.data
|
||
return {
|
||
id: typeof data.id === 'string' ? data.id : id,
|
||
state: typeof data.state === 'string' ? data.state : '',
|
||
operation: typeof data.operation === 'string' ? data.operation : '',
|
||
item_count: typeof data.item_count === 'number' ? data.item_count : 0,
|
||
}
|
||
}
|