diff --git a/cmd/api/main.go b/cmd/api/main.go index 50b3381..86f8217 100644 --- a/cmd/api/main.go +++ b/cmd/api/main.go @@ -86,7 +86,7 @@ func run(ctx context.Context, getenv func(string) string) error { ProductionBackupRestoreVerified: config.ProductionBackupRestoreVerified, ProductionReleaseAuthorizerRef: config.ProductionReleaseAuthorizerRef, ProductionReleaseAuthorizationToken: releaseAuthorizationToken, - Auth: &httpapi.AuthConfig{Store: authStore, SessionTTL: 12 * time.Hour}, + Auth: &httpapi.AuthConfig{Store: authStore, SessionTTL: 12 * time.Hour}, }) if err != nil { return err diff --git a/internal/httpapi/server.go b/internal/httpapi/server.go index 690a416..e7ea532 100644 --- a/internal/httpapi/server.go +++ b/internal/httpapi/server.go @@ -799,7 +799,7 @@ type scopeRuleInput struct { SourceItemID string `json:"source_item_id"` Visibility governance.Visibility `json:"visibility"` - Reason string `json:"reason"` + Reason string `json:"reason"` } func listScopeRules(w http.ResponseWriter, r *http.Request, store Store) { @@ -874,10 +874,10 @@ type sourceSettingsRevisionRequest struct { Schedule struct { RefreshIntervalSeconds *int `json:"refresh_interval_seconds"` } `json:"schedule"` - Operator string `json:"operator"` } -func (req sourceSettingsRevisionRequest) toDraft() postgresstore.SourceSettingsDraft { +// toDraft stamps the actor server-side; the browser never names the operator. +func (req sourceSettingsRevisionRequest) toDraft(actor string) postgresstore.SourceSettingsDraft { schedule := "{}" if req.Schedule.RefreshIntervalSeconds != nil { schedule = fmt.Sprintf(`{"refresh_interval_seconds":%d}`, *req.Schedule.RefreshIntervalSeconds) @@ -885,7 +885,7 @@ func (req sourceSettingsRevisionRequest) toDraft() postgresstore.SourceSettingsD return postgresstore.SourceSettingsDraft{ SourceType: req.SourceType, Name: req.Name, BaseURL: req.BaseURL, SecretRef: req.SecretRef, Enabled: req.Enabled, - Schedule: json.RawMessage(schedule), Operator: req.Operator, + Schedule: json.RawMessage(schedule), Operator: actor, } } @@ -922,7 +922,7 @@ func createSourceSettingsRevision(w http.ResponseWriter, r *http.Request, config writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid source settings revision"}) return } - revisionID, replayed, err := config.Store.CreateSourceSettingsRevisionWithOperation(r.Context(), connectionID, request.toDraft(), operationID, config.Now().UTC()) + revisionID, replayed, err := config.Store.CreateSourceSettingsRevisionWithOperation(r.Context(), connectionID, request.toDraft(actorFor(r)), operationID, config.Now().UTC()) if errors.Is(err, postgresstore.ErrOperationRequestConflict) { writeJSON(w, http.StatusConflict, map[string]string{"error": "Idempotency-Key conflicts with a different request"}) return @@ -1135,11 +1135,10 @@ func reviewPublication(w http.ResponseWriter, r *http.Request, config Config) { } type createUISettingsCandidateRequest struct { - DocumentRefreshSeconds int `json:"document_refresh_seconds"` - ResourceRefreshSeconds int `json:"resource_refresh_seconds"` - StalledAfterSeconds int `json:"stalled_after_seconds"` - FinalizingAfterSeconds int `json:"finalizing_after_seconds"` - UpdatedBy string `json:"updated_by"` + DocumentRefreshSeconds int `json:"document_refresh_seconds"` + ResourceRefreshSeconds int `json:"resource_refresh_seconds"` + StalledAfterSeconds int `json:"stalled_after_seconds"` + FinalizingAfterSeconds int `json:"finalizing_after_seconds"` } func getActiveUISettings(w http.ResponseWriter, r *http.Request, store Store) { @@ -1170,7 +1169,7 @@ func createUISettingsCandidate(w http.ResponseWriter, r *http.Request, config Co ResourceRefreshSeconds: request.ResourceRefreshSeconds, StalledAfterSeconds: request.StalledAfterSeconds, FinalizingAfterSeconds: request.FinalizingAfterSeconds, - UpdatedBy: request.UpdatedBy, + UpdatedBy: actorFor(r), Now: config.Now(), }, operationID) if errors.Is(err, postgresstore.ErrOperationRequestConflict) { diff --git a/internal/httpapi/server_test.go b/internal/httpapi/server_test.go index 810ab58..93cf441 100644 --- a/internal/httpapi/server_test.go +++ b/internal/httpapi/server_test.go @@ -442,13 +442,13 @@ func TestHandlerSourceSettingsRevisionEndpoints(t *testing.T) { } forbidden := httptest.NewRecorder() - handler.ServeHTTP(forbidden, httptest.NewRequest("POST", "/api/v1/source-connections/conn-1/settings/revisions", strings.NewReader(`{"source_type":"alist","name":"n","operator":"o","schedule":{}}`))) + handler.ServeHTTP(forbidden, httptest.NewRequest("POST", "/api/v1/source-connections/conn-1/settings/revisions", strings.NewReader(`{"source_type":"alist","name":"n","schedule":{}}`))) if forbidden.Code != http.StatusForbidden { t.Fatalf("intent header gate = %d, want 403", forbidden.Code) } missingKey := httptest.NewRecorder() - request := httptest.NewRequest("POST", "/api/v1/source-connections/conn-1/settings/revisions", strings.NewReader(`{"source_type":"alist","name":"国内工业AList","operator":"zherom","enabled":true,"schedule":{"refresh_interval_seconds":3600}}`)) + request := httptest.NewRequest("POST", "/api/v1/source-connections/conn-1/settings/revisions", strings.NewReader(`{"source_type":"alist","name":"国内工业AList","enabled":true,"schedule":{"refresh_interval_seconds":3600}}`)) request.Header.Set("X-Governance-Action", "source-settings") handler.ServeHTTP(missingKey, request) if missingKey.Code != http.StatusBadRequest { @@ -456,14 +456,14 @@ func TestHandlerSourceSettingsRevisionEndpoints(t *testing.T) { } created := httptest.NewRecorder() - request = httptest.NewRequest("POST", "/api/v1/source-connections/conn-1/settings/revisions", strings.NewReader(`{"source_type":"alist","name":"国内工业AList","operator":"zherom","enabled":true,"schedule":{"refresh_interval_seconds":3600}}`)) + request = httptest.NewRequest("POST", "/api/v1/source-connections/conn-1/settings/revisions", strings.NewReader(`{"source_type":"alist","name":"国内工业AList","enabled":true,"schedule":{"refresh_interval_seconds":3600}}`)) request.Header.Set("X-Governance-Action", "source-settings") request.Header.Set("Idempotency-Key", "create-v1") handler.ServeHTTP(created, request) if created.Code != http.StatusCreated { t.Fatalf("create = %d body=%s", created.Code, created.Body.String()) } - if store.createSettingsConnectionID != "conn-1" || store.createSettingsOperationID != "create-v1" || store.createSettingsDraft.Name != "国内工业AList" || store.createSettingsDraft.Operator != "zherom" { + if store.createSettingsConnectionID != "conn-1" || store.createSettingsOperationID != "create-v1" || store.createSettingsDraft.Name != "国内工业AList" || store.createSettingsDraft.Operator != "system" { t.Fatalf("create request = %s %+v op=%s", store.createSettingsConnectionID, store.createSettingsDraft, store.createSettingsOperationID) } if !strings.Contains(created.Body.String(), "scr-fake") || !strings.Contains(created.Body.String(), "created") { @@ -472,7 +472,7 @@ func TestHandlerSourceSettingsRevisionEndpoints(t *testing.T) { store.createSettingsErr = postgresstore.ErrInvalidSourceSettings rejected := httptest.NewRecorder() - request = httptest.NewRequest("POST", "/api/v1/source-connections/conn-1/settings/revisions", strings.NewReader(`{"source_type":"ftp","name":"x","operator":"o","schedule":{}}`)) + request = httptest.NewRequest("POST", "/api/v1/source-connections/conn-1/settings/revisions", strings.NewReader(`{"source_type":"ftp","name":"x","schedule":{}}`)) request.Header.Set("X-Governance-Action", "source-settings") request.Header.Set("Idempotency-Key", "create-v2") handler.ServeHTTP(rejected, request) @@ -482,7 +482,7 @@ func TestHandlerSourceSettingsRevisionEndpoints(t *testing.T) { store.createSettingsErr = postgresstore.ErrOperationRequestConflict conflicted := httptest.NewRecorder() - request = httptest.NewRequest("POST", "/api/v1/source-connections/conn-1/settings/revisions", strings.NewReader(`{"source_type":"alist","name":"x","operator":"o","schedule":{}}`)) + request = httptest.NewRequest("POST", "/api/v1/source-connections/conn-1/settings/revisions", strings.NewReader(`{"source_type":"alist","name":"x","schedule":{}}`)) request.Header.Set("X-Governance-Action", "source-settings") request.Header.Set("Idempotency-Key", "create-v3") handler.ServeHTTP(conflicted, request) @@ -952,20 +952,20 @@ func TestHandlerVersionsAndActivatesUISettings(t *testing.T) { t.Fatalf("get status=%d body=%s", get.Code, get.Body.String()) } noIntent := httptest.NewRecorder() - handler.ServeHTTP(noIntent, httptest.NewRequest(http.MethodPost, "/api/v1/ui-settings/candidates", bytes.NewBufferString(`{"document_refresh_seconds":30,"resource_refresh_seconds":60,"stalled_after_seconds":3600,"finalizing_after_seconds":14400,"updated_by":"engineer-1"}`))) + handler.ServeHTTP(noIntent, httptest.NewRequest(http.MethodPost, "/api/v1/ui-settings/candidates", bytes.NewBufferString(`{"document_refresh_seconds":30,"resource_refresh_seconds":60,"stalled_after_seconds":3600,"finalizing_after_seconds":14400}`))) if noIntent.Code != http.StatusForbidden { t.Fatalf("missing intent status=%d body=%s", noIntent.Code, noIntent.Body.String()) } create := httptest.NewRecorder() - createRequest := httptest.NewRequest(http.MethodPost, "/api/v1/ui-settings/candidates", bytes.NewBufferString(`{"document_refresh_seconds":30,"resource_refresh_seconds":60,"stalled_after_seconds":3600,"finalizing_after_seconds":14400,"updated_by":"engineer-1"}`)) + createRequest := httptest.NewRequest(http.MethodPost, "/api/v1/ui-settings/candidates", bytes.NewBufferString(`{"document_refresh_seconds":30,"resource_refresh_seconds":60,"stalled_after_seconds":3600,"finalizing_after_seconds":14400}`)) createRequest.Header.Set("X-Governance-Action", "ui-settings") createRequest.Header.Set("Idempotency-Key", "op-uis-create") handler.ServeHTTP(create, createRequest) - if create.Code != http.StatusCreated || store.createUISettingsRequest.Now != now || store.createUISettingsRequest.UpdatedBy != "engineer-1" || !strings.Contains(create.Body.String(), `"operation":"created"`) { + if create.Code != http.StatusCreated || store.createUISettingsRequest.Now != now || store.createUISettingsRequest.UpdatedBy != "system" || !strings.Contains(create.Body.String(), `"operation":"created"`) { t.Fatalf("create status=%d request=%#v body=%s", create.Code, store.createUISettingsRequest, create.Body.String()) } unknown := httptest.NewRecorder() - unknownRequest := httptest.NewRequest(http.MethodPost, "/api/v1/ui-settings/candidates", bytes.NewBufferString(`{"document_refresh_seconds":30,"resource_refresh_seconds":60,"stalled_after_seconds":3600,"finalizing_after_seconds":14400,"updated_by":"engineer-1","secret":"must-reject"}`)) + unknownRequest := httptest.NewRequest(http.MethodPost, "/api/v1/ui-settings/candidates", bytes.NewBufferString(`{"document_refresh_seconds":30,"resource_refresh_seconds":60,"stalled_after_seconds":3600,"finalizing_after_seconds":14400,"secret":"must-reject"}`)) unknownRequest.Header.Set("X-Governance-Action", "ui-settings") handler.ServeHTTP(unknown, unknownRequest) if unknown.Code != http.StatusBadRequest { diff --git a/internal/platform/postgres/auth.go b/internal/platform/postgres/auth.go index 94928f5..e80405c 100644 --- a/internal/platform/postgres/auth.go +++ b/internal/platform/postgres/auth.go @@ -108,7 +108,7 @@ func (s *Store) CreateUser(ctx context.Context, username, displayName, role, pas _, err = s.db.Exec(ctx, ` INSERT INTO users(id,username,display_name,role,password_hash,must_change_password,state,created_by,created_at,updated_at) VALUES($1,$2,$3,$4,$5,$6,'active',$7,$8,$8)`, -id, username, displayName, role, string(hash), true, createdBy, now.UTC()) + id, username, displayName, role, string(hash), true, createdBy, now.UTC()) if err != nil { if isUniqueViolation(err) { return AuthUser{}, ErrAuthDuplicateUsername @@ -308,12 +308,15 @@ func (s *Store) userLockedUntil(ctx context.Context, userID string) (time.Time, } func (s *Store) recordFailedLogin(ctx context.Context, userID string, now time.Time) error { + // Explicit parameter casts: PostgreSQL cannot infer the type of a bare + // parameter inside `$4::interval` / the integer comparison, and the + // extended-protocol Prepare would fail with "could not determine data type". _, err := s.db.Exec(ctx, ` UPDATE users SET failed_attempts = failed_attempts + 1, - locked_until = CASE WHEN failed_attempts + 1 >= $3 THEN $2 + $4::interval ELSE locked_until END, - updated_at = $2 -WHERE id = $1`, userID, now, authMaxFailedAttempts, fmt.Sprintf("%d minutes", int(authLockDuration.Minutes()))) + locked_until = CASE WHEN failed_attempts + 1 >= $3::int THEN $2::timestamptz + $4::interval ELSE locked_until END, + updated_at = $2::timestamptz +WHERE id = $1::varchar`, userID, now, authMaxFailedAttempts, fmt.Sprintf("%d minutes", int(authLockDuration.Minutes()))) if err != nil { return fmt.Errorf("record failed login: %w", err) } @@ -521,4 +524,3 @@ func derefTime(value *time.Time) time.Time { } return *value } - diff --git a/web/src/App.test.tsx b/web/src/App.test.tsx index d899487..f73445f 100644 --- a/web/src/App.test.tsx +++ b/web/src/App.test.tsx @@ -350,7 +350,7 @@ 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 [ @@ -366,14 +366,13 @@ describe('ReleaseManagement', () => { '当前在第 3 步,共 8 步', '现在要做:审核 1 项知识', '还有 1 项等待审核;已批准文件可先创建批次', - '完成本步的 4 件事', - '填写操作人姓名或工号', + '完成本步的 3 件事', '只审核本次准备发布的文件', '勾选要发布的已批准知识', '填写批次名称并创建草稿', - '现在先做:填写操作人姓名或工号,逐条选择“批准”或“驳回”', + '现在先做:逐条选择“批准”或“驳回”(操作自动记在当前登录人名下)', '完成后进入:第 4 步,创建发布批次', - '为什么按钮不能点:请先填写操作人姓名或工号', + '为什么按钮不能点:请确认所选删除项会停止生产检索', '如何决定批准或驳回', '可以批准:基础测试通过,你已确认搜索结果相关,而且发布范围正确', '应该驳回:内容错误、过期、敏感、搜索结果不相关,或者你无法确认', diff --git a/web/src/App.tsx b/web/src/App.tsx index cef671a..5b073d9 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -1,4 +1,5 @@ import { useCallback, useEffect, useMemo, useState } from 'react' +import { TopBarUser } from './auth' import { DocumentWorkbench } from './DocumentWorkbench' import { SourceCatalogBrowser } from './SourceCatalogBrowser' import { WeKnoraMonitor } from './WeKnoraMonitor' @@ -134,6 +135,7 @@ export function WorkspaceShell(props: WorkspaceShellProps) { })} +
{props.children}
@@ -207,8 +209,8 @@ interface ModulePageProps extends JobDashboardProps { releaseChangeSet?: ReleaseChangeSetDetail | null changeSetBusy?: boolean changeSetError?: string | null - onGenerateChangeSet?: (name: string, createdBy: string) => void - onConfirmChangeSet?: (changeSetID: string, confirmedBy: string) => void + onGenerateChangeSet?: (name: string) => void + onConfirmChangeSet?: (changeSetID: string) => void selectedDeleteIDs?: string[] onToggleDelete?: (publicationID: string) => void executionPage?: ReleaseExecutionPage @@ -635,10 +637,10 @@ interface ReleaseManagementProps { batchLoading: boolean batchError: string | null mutatingBatchId: string | null - onReview: (publicationID: string, decision: 'approved' | 'rejected', visibility: Visibility, reviewerRef: string, decisionCode: string) => void + onReview: (publicationID: string, decision: 'approved' | 'rejected', visibility: Visibility, decisionCode: string) => void onReviewRefresh: () => void - onCreateBatch: (name: string, createdBy: string, publicationIDs: string[], deletePublicationIDs: string[]) => void - onSealBatch: (batchID: string, sealedBy: string) => void + onCreateBatch: (name: string, publicationIDs: string[], deletePublicationIDs: string[]) => void + onSealBatch: (batchID: string) => void onSelectBatch: (batchID: string) => void onBatchRefresh: () => void releaseCapabilities: ReleaseCapabilities @@ -646,8 +648,8 @@ interface ReleaseManagementProps { releaseChangeSet?: ReleaseChangeSetDetail | null changeSetBusy?: boolean changeSetError?: string | null - onGenerateChangeSet?: (name: string, createdBy: string) => void - onConfirmChangeSet?: (changeSetID: string, confirmedBy: string) => void + onGenerateChangeSet?: (name: string) => void + onConfirmChangeSet?: (changeSetID: string) => void selectedDeleteIDs: string[] onToggleDelete: (publicationID: string) => void executionPage: ReleaseExecutionPage @@ -761,7 +763,7 @@ function releaseGuidance(props: ReleaseManagementProps, pending: number) { step: 3, title: `现在要做:审核 ${pending} 项知识`, reason: `还有 ${pending} 项等待审核;已批准文件可先创建批次`, - action: '填写操作人姓名或工号,逐条选择“批准”或“驳回”', + action: '逐条选择“批准”或“驳回”(操作自动记在当前登录人名下)', after: '第 4 步,创建发布批次', impact: '普通业务操作,不会影响生产', href: '#review-actions', @@ -840,7 +842,6 @@ export function ReleaseManagement(props: ReleaseManagementProps) { const changeSetError = props.changeSetError ?? null const onGenerateChangeSet = props.onGenerateChangeSet ?? (() => undefined) const onConfirmChangeSet = props.onConfirmChangeSet ?? (() => undefined) - const [reviewerRef, setReviewerRef] = useState('') const [batchName, setBatchName] = useState('') const [selectedIDs, setSelectedIDs] = useState([]) const [deleteConfirmed, setDeleteConfirmed] = useState(false) @@ -861,7 +862,6 @@ export function ReleaseManagement(props: ReleaseManagementProps) { ? '生产操作权限:已阻断' : '生产操作权限:等待负责人确认' const batchBlocker = [ - !reviewerRef ? '请先填写操作人姓名或工号' : '', selectedCount === 0 ? '请先勾选已批准或待删除的知识' : '', props.selectedDeleteIDs.length > 0 && !deleteConfirmed ? '请确认所选删除项会停止生产检索' : '', selectedCount > 0 && !confirmedSelection ? '至少 1 项动作通过确认' : '', @@ -903,7 +903,7 @@ export function ReleaseManagement(props: ReleaseManagementProps) {

{guidance.title}

{guidance.reason} - {guidance.step === 3 ?
完成本步的 4 件事
  1. 填写操作人姓名或工号
  2. 只审核本次准备发布的文件
  3. 勾选要发布的已批准知识
  4. 填写批次名称并创建草稿
: null} + {guidance.step === 3 ?
完成本步的 3 件事
  1. 只审核本次准备发布的文件
  2. 勾选要发布的已批准知识
  3. 填写批次名称并创建草稿
: null}

{`现在先做:${guidance.action}`}

{`完成后进入:${guidance.after}`}

{guidance.impact} @@ -958,8 +958,8 @@ export function ReleaseManagement(props: ReleaseManagementProps) { {changeSet && changeSet.state === 'planned' ?
查看冻结清单({changeSet.items.length}项)
    {changeSet.items.map((item) =>
  • {`${item.seq}. ${item.title} · ${item.target_scope === 'internal' ? '对内' : '对外'} · ${frozenActionLabel(item.action)}${item.can_release ? '' : '(阻断:' + (item.blocker === 'source_unavailable' ? '来源不可用' : '测试未就绪') + ')'}`}
  • )}
: null} {changeSetError ?

{changeSetError}

: null}
- - {changeSet && changeSet.state === 'planned' ? : null} + + {changeSet && changeSet.state === 'planned' ? : null} {changeSet && changeSet.state === 'confirmed' ? 创建批次将自动绑定 v{changeSet.number} 并校验清单 : 草稿批次需先由上方“确认冻结”固定目标}
@@ -975,7 +975,6 @@ export function ReleaseManagement(props: ReleaseManagementProps) {

第 3 步:审核要发布的知识

先确认测试结果和对内/对外范围,再批准或驳回。批准后才能勾选加入批次。

-
{batchBlocker ?
{`为什么按钮不能点:${batchBlocker}`}
: null}
@@ -1000,19 +999,19 @@ export function ReleaseManagement(props: ReleaseManagementProps) { {reviewGateLabel(item)} {reviewLabels[item.review_state]}{item.reviewer_ref ? {item.reviewer_ref} : null} -
+
})}
: null} -
创建批次还需要填写操作人确认所选发布动作至少 1 项动作通过确认填写批次名称
-
已选 {selectedCount} 项{props.selectedDeleteIDs.length > 0 && !deleteConfirmed ? '(删除待确认)' : ''}
+
创建批次还需要确认所选发布动作至少 1 项动作通过确认填写批次名称
+
已选 {selectedCount} 项{props.selectedDeleteIDs.length > 0 && !deleteConfirmed ? '(删除待确认)' : ''}

第 4–5 步:创建并锁定发布清单

草稿可以继续核对;点击“锁定清单(不会上线)”后,本次内容不再变化,但仍不会发布到生产。

锁定清单 ≠ 上线
{props.batchError ?
{props.batchError}
: null} {!props.batchLoading && !props.batchError && props.batchPage.items.length === 0 ?
尚无草稿或已锁定的发布清单。
: null} {props.batchPage.items.length > 0 ?
- {props.batchPage.items.map((batch) => )} + {props.batchPage.items.map((batch) => )}
批次名称状态知识数量内容状态操作
{batch.name}{batchLabels[batch.state]}{batch.item_count}{batch.state === 'sealed' ? '内容已锁定' : '仍可检查调整'}
{batch.state === 'draft' ? : null}
{batch.name}{batchLabels[batch.state]}{batch.item_count}{batch.state === 'sealed' ? '内容已锁定' : '仍可检查调整'}
{batch.state === 'draft' ? : null}

本批次包含

{props.batchDetail ? <>{props.batchDetail.items.map((item) =>
{item.title}{item.action === 'delete' ? '删除生产知识' : '新增或更新生产知识'}{item.decided_visibility === 'internal' ? '仅内部员工' : '允许外部用户'}
)}{props.batchDetail.items.length === 0 ?
批次没有知识。
: null} :
点击“查看内容”核对本次发布清单。
}
: null}
@@ -1297,11 +1296,11 @@ export default function App() { } }, []) - const handleReview = useCallback(async (publicationID: string, decision: 'approved' | 'rejected', visibility: Visibility, reviewerRef: string, decisionCode: string) => { + const handleReview = useCallback(async (publicationID: string, decision: 'approved' | 'rejected', visibility: Visibility, decisionCode: string) => { setReviewingId(publicationID) setReviewError(null) try { - await reviewPublication(publicationID, decision, visibility, reviewerRef, decisionCode) + await reviewPublication(publicationID, decision, visibility, decisionCode) await loadReviews() } catch (cause) { setReviewError(cause instanceof Error ? cause.message : '提交审核决定失败') @@ -1314,11 +1313,11 @@ export default function App() { setReleaseChangeSet(await fetchLatestReleaseChangeSet().catch(() => null)) }, []) - const handleGenerateChangeSet = useCallback(async (name: string, createdBy: string) => { + const handleGenerateChangeSet = useCallback(async (name: string) => { setChangeSetBusy(true) setChangeSetError(null) try { - await generateReleaseChangeSet(name, createdBy) + await generateReleaseChangeSet(name) await reloadChangeSet() } catch (cause) { setChangeSetError(cause instanceof Error ? cause.message : '生成发布计划集失败') @@ -1327,11 +1326,11 @@ export default function App() { } }, [reloadChangeSet]) - const handleConfirmChangeSet = useCallback(async (changeSetID: string, confirmedBy: string) => { + const handleConfirmChangeSet = useCallback(async (changeSetID: string) => { setChangeSetBusy(true) setChangeSetError(null) try { - await confirmReleaseChangeSet(changeSetID, confirmedBy) + await confirmReleaseChangeSet(changeSetID) await reloadChangeSet() } catch (cause) { setChangeSetError(cause instanceof Error ? cause.message : '确认发布计划集失败') @@ -1340,11 +1339,11 @@ export default function App() { } }, [reloadChangeSet]) - const handleCreateBatch = useCallback(async (name: string, createdBy: string, publicationIDs: string[], deletePublicationIDs: string[]) => { + const handleCreateBatch = useCallback(async (name: string, publicationIDs: string[], deletePublicationIDs: string[]) => { setMutatingBatchId('creating') setBatchError(null) try { - const batch = await createReleaseBatch(name, createdBy, publicationIDs, deletePublicationIDs, releaseChangeSet?.state === 'confirmed' ? releaseChangeSet.id : '') + const batch = await createReleaseBatch(name, publicationIDs, deletePublicationIDs, releaseChangeSet?.state === 'confirmed' ? releaseChangeSet.id : '') setSelectedDeleteIDs([]) await loadBatches() setBatchDetail(await fetchReleaseBatch(batch.id)) @@ -1355,11 +1354,11 @@ export default function App() { } }, [loadBatches, releaseChangeSet]) - const handleSealBatch = useCallback(async (batchID: string, sealedBy: string) => { + const handleSealBatch = useCallback(async (batchID: string) => { setMutatingBatchId(batchID) setBatchError(null) try { - await sealReleaseBatch(batchID, sealedBy) + await sealReleaseBatch(batchID) await loadBatches() setBatchDetail(await fetchReleaseBatch(batchID)) } catch (cause) { @@ -1548,10 +1547,10 @@ export default function App() { batchLoading={batchLoading} batchError={batchError} mutatingBatchId={mutatingBatchId} - onReview={(publicationID, decision, visibility, reviewerRef, decisionCode) => void handleReview(publicationID, decision, visibility, reviewerRef, decisionCode)} + onReview={(publicationID, decision, visibility, decisionCode) => void handleReview(publicationID, decision, visibility, decisionCode)} onReviewRefresh={() => void loadReviews()} - onCreateBatch={(name, createdBy, publicationIDs, deletePublicationIDs) => void handleCreateBatch(name, createdBy, publicationIDs, deletePublicationIDs)} - onSealBatch={(batchID, sealedBy) => void handleSealBatch(batchID, sealedBy)} + onCreateBatch={(name, publicationIDs, deletePublicationIDs) => void handleCreateBatch(name, publicationIDs, deletePublicationIDs)} + onSealBatch={(batchID) => void handleSealBatch(batchID)} onSelectBatch={(batchID) => void handleSelectBatch(batchID)} onBatchRefresh={() => void loadBatches()} releaseCapabilities={releaseCapabilities} diff --git a/web/src/MembersSection.tsx b/web/src/MembersSection.tsx new file mode 100644 index 0000000..2a68cc7 --- /dev/null +++ b/web/src/MembersSection.tsx @@ -0,0 +1,81 @@ +import { useCallback, useEffect, useState } from 'react' +import { createManagedUser, fetchManagedUsers, resetManagedUserPassword, setManagedUserRole, setManagedUserState } from './members' +import type { ManagedUser } from './members' +import { roleLabels, useOptionalAuth } from './auth' + +export const memberRoleLabels = roleLabels + +function friendly(cause: unknown, fallback: string): string { + return cause instanceof Error && cause.message ? cause.message : fallback +} + +export function MembersSection() { + const identity = useOptionalAuth()?.identity ?? null + const [users, setUsers] = useState([]) + const [loading, setLoading] = useState(true) + const [busy, setBusy] = useState(null) + const [error, setError] = useState(null) + const [message, setMessage] = useState(null) + const [form, setForm] = useState({ username: '', display_name: '', role: 'engineer' as ManagedUser['role'], password: '' }) + + const load = useCallback(async () => { + setLoading(true); setError(null) + try { setUsers(await fetchManagedUsers()) } + catch (cause) { setError(friendly(cause, '加载成员失败')) } + finally { setLoading(false) } + }, []) + useEffect(() => { void load() }, [load]) + + const run = async (key: string, action: () => Promise, success: string) => { + setBusy(key); setError(null); setMessage(null) + try { await action(); setMessage(success); await load() } + catch (cause) { setError(friendly(cause, '操作失败')) } + finally { setBusy(null) } + } + + const create = () => run('create', async () => { + await createManagedUser(form) + setForm({ username: '', display_name: '', role: 'engineer', password: '' }) + }, `成员 ${form.username} 已创建,初始密码只用于首次登录`) + + const formValid = /^[a-z0-9][a-z0-9._-]{1,63}$/.test(form.username.trim()) && form.password.length >= 8 + + return
+

成员与角色

登录后的一切操作自动记录在成员名下;角色决定谁能审核、封批和行使生产授权。

+ {loading ?

加载成员…

: null} + {error ?

{error}

: null} + {message ?

{message}

: null} +
+ {users.map((user) => { + const self = user.id === identity?.id + return + + + + + + + })} +
成员角色状态最近登录操作
{user.display_name || user.username}{user.username}{user.must_change_password ? ' · 待设置新密码' : ''}{self ? {memberRoleLabels[user.role]} : ( + + )}{user.state === 'active' ? '启用' : '已停用'}{user.last_login_at ? new Date(user.last_login_at).toLocaleString('zh-CN', { hour12: false }) : '从未登录'}
+ {!self ? : null} + {!self ? : 当前登录人} +
+
+ + + + + +
+ 停用不会删除任何业务记录,只禁止登录并立即撤销其在线会话。 +
+} diff --git a/web/src/ScopeRuleEditor.test.tsx b/web/src/ScopeRuleEditor.test.tsx index ca98320..091e102 100644 --- a/web/src/ScopeRuleEditor.test.tsx +++ b/web/src/ScopeRuleEditor.test.tsx @@ -5,7 +5,8 @@ import { ScopeRuleEditor } from './ScopeRuleEditor' describe('ScopeRuleEditor',()=>{ it('explains directory inheritance and keeps production publication separate',()=>{ const html=renderToStaticMarkup() - for(const text of ['此目录及子目录','当前设置:对内','人工:engineer','移除本级设置,恢复继承','不会自动发布到生产']) expect(html).toContain(text) + for(const text of ['此目录及子目录','当前设置:对内','由 engineer 设置','移除本级设置,恢复继承','不会自动发布到生产']) expect(html).toContain(text) + expect(html).not.toContain('操作人{ const html=renderToStaticMarkup() diff --git a/web/src/ScopeRuleEditor.tsx b/web/src/ScopeRuleEditor.tsx index 559485a..9b66843 100644 --- a/web/src/ScopeRuleEditor.tsx +++ b/web/src/ScopeRuleEditor.tsx @@ -12,22 +12,20 @@ interface Props { export function ScopeRuleEditor({target,currentRule,saving,error,onSave,onClear}:Props){ const [visibility,setVisibility]=useState(currentRule?.visibility||'') - const [operator,setOperator]=useState('') const [reason,setReason]=useState('') - const identityReady=operator.trim()!==''&&reason.trim()!==''&&!saving - const saveReady=identityReady&&visibility!=='' + const reasonReady=reason.trim()!==''&&!saving + const saveReady=reasonReady&&visibility!=='' const label=target.target_type==='item'?'仅此文件':target.directory_path?'此目录及子目录':'整个来源' - const base={...target,operator_ref:operator.trim(),reason:reason.trim()} + const base={...target,reason:reason.trim()} return
对内/对外设置{label}
{currentRule?当前设置:{currentRule.visibility==='external'?'对外':'对内'}:当前没有本级设置}
- {currentRule?

人工:{currentRule.updated_by} · 原因:{currentRule.reason}

:

当前继承上级规则或来源原始标记。

} + {currentRule?

由 {currentRule.updated_by} 设置 · 原因:{currentRule.reason}

:

当前继承上级规则或来源原始标记。

}
-
{error?

{error}

:null} -
{currentRule?:null}
- 这里只更新治理规则并记录审计,不会修改源文件,也不会自动发布到生产。 +
{currentRule?:null}
+ 这里只更新治理规则并记录审计,操作自动记在当前登录人名下;不会修改源文件,也不会自动发布到生产。
} diff --git a/web/src/SourceCatalogBrowser.tsx b/web/src/SourceCatalogBrowser.tsx index 3c32f98..9aabe99 100644 --- a/web/src/SourceCatalogBrowser.tsx +++ b/web/src/SourceCatalogBrowser.tsx @@ -105,7 +105,7 @@ export function SourceCatalogBrowser(){ useEffect(()=>{if(!selected||!page){setContextTabs([]);return}setContextTabs(page.breadcrumbs.map(item=>({key:item.node_id,label:item.name,onActivate:()=>{setParentID(item.node_id);setOffset(0)}})));return()=>setContextTabs([])},[selected,page,setContextTabs]) const selectSource=(source:CatalogSource)=>{setSelected(source);setParentID(source.root_node_id);setOffset(0);setPage(null);setRefreshJob(null);closeHistory()} const back=()=>{if(!page||page.breadcrumbs.length<2)return;setParentID(page.breadcrumbs[page.breadcrumbs.length-2].node_id);setOffset(0)} - const route=async(nodeIDs:string[],policy:CatalogPolicy):Promise=>{if(!selected||routingLoading)return false;setRoutingLoading(true);setRoutingMessage('');try{const result=await routeCatalogFiles({connection_id:selected.connection_id,node_ids:nodeIDs,policy,operator_ref:'web-console',reason:`目录页策略:${scope(policy)}`});setRoutingMessage(`策略已保存 ${result.selected_files} 份;可处理 ${result.routable_files} 份;内容未校验 ${result.hash_unknown_files} 份;未关联来源文件 ${result.unbound_files} 份;其余 ${result.unavailable_files} 份暂不可处理。变化需到“快照差异”确认后才会进入解析队列。`);setRevision(value=>value+1);return true}catch(cause){setRoutingMessage(cause instanceof Error?cause.message:'文件处理失败');return false}finally{setRoutingLoading(false)}} + const route=async(nodeIDs:string[],policy:CatalogPolicy):Promise=>{if(!selected||routingLoading)return false;setRoutingLoading(true);setRoutingMessage('');try{const result=await routeCatalogFiles({connection_id:selected.connection_id,node_ids:nodeIDs,policy,reason:`目录页策略:${scope(policy)}`});setRoutingMessage(`策略已保存 ${result.selected_files} 份;可处理 ${result.routable_files} 份;内容未校验 ${result.hash_unknown_files} 份;未关联来源文件 ${result.unbound_files} 份;其余 ${result.unavailable_files} 份暂不可处理。变化需到“快照差异”确认后才会进入解析队列。`);setRevision(value=>value+1);return true}catch(cause){setRoutingMessage(cause instanceof Error?cause.message:'文件处理失败');return false}finally{setRoutingLoading(false)}} const refresh=async()=>{if(!selected||refreshJob&&['pending','running','retry'].includes(refreshJob.state))return;setError(null);try{setRefreshJob(await triggerCatalogRefresh(selected.connection_id))}catch(cause){setError(cause instanceof Error?cause.message:'启动实时刷新失败')}} return {setRoutingMessage('');selectSource(source)}} onOpenFolder={node=>{setRoutingMessage('');setParentID(node.node_id);setOffset(0)}} onNavigateTo={nodeID=>{setRoutingMessage('');setParentID(nodeID);setOffset(0)}} onBack={back} onPageChange={setOffset} onRefresh={()=>void refresh()} onRoute={(nodeIDs,visibility)=>route(nodeIDs,visibility)} history={{open:historyOpen,snapshots:historySnapshots,active:historyActive,page:historyPage,loading:historyLoading,error:historyError,onOpen:()=>void openHistory(),onClose:closeHistory,onOpenSnapshot:snapshot=>void openHistorySnapshot(snapshot),onOpenFolder:(snapshot,nodeID)=>void openHistoryFolder(snapshot,nodeID)}} refreshHidden={refreshHidden} onToggleRefreshHidden={()=>setRefreshHidden(value=>!value)} /> } diff --git a/web/src/SystemSettings.tsx b/web/src/SystemSettings.tsx index d9d3416..d07e604 100644 --- a/web/src/SystemSettings.tsx +++ b/web/src/SystemSettings.tsx @@ -1,5 +1,7 @@ import { useCallback, useEffect, useState } from 'react' +import { MembersSection } from './MembersSection' +import { useOptionalAuth } from './auth' import { fetchMonitorOverview } from './monitor' import type { MonitorOverview } from './monitor' import { fetchReleaseCapabilities } from './reviewRelease' @@ -28,14 +30,15 @@ interface Props { initialSection?: SectionKey } -type SectionKey = 'sources' | 'services' | 'storage' | 'refresh' +type SectionKey = 'sources' | 'services' | 'storage' | 'refresh' | 'members' -const sections: { key: SectionKey; label: string }[] = [ +const sections: { key: SectionKey; label: string; adminOnly?: boolean }[] = [ { key: 'sources', label: '数据源配置' }, { key: 'services', label: '服务配置' }, { key: 'storage', label: '存储与备份' }, { key: 'refresh', label: '刷新策略' }, -] + { key: 'members', label: '成员与角色', adminOnly: true }, +] as { key: SectionKey; label: string; adminOnly?: boolean }[] const sourceTypeLabels: Record = { dingtalk: '钉钉知识库', pp: 'PP 资料下载中心', alist: 'AList 文件源', manual: '本地手工导入' } const sourceAuthLabels: Record = { dingtalk: '专用浏览器扫码会话', pp: '公开只读访问', alist: '直连 API Token', manual: '离线导入,无在线认证' } @@ -57,7 +60,6 @@ function formatHorizon(value: string | null): string { } function SourceSettingsCard({ connection, onSourcesChanged }: { connection: SourceConnectionListItem; onSourcesChanged: () => void }) { - const [operator, setOperator] = useState('') const [interval, setInterval] = useState(() => { if (!connection.next_refresh_at) return 0 const remaining = new Date(connection.next_refresh_at).getTime() - Date.now() @@ -78,7 +80,6 @@ function SourceSettingsCard({ connection, onSourcesChanged }: { connection: Sour const draft = { source_type: connection.source_type, name: connection.name, endpoint: '', credential_ref: '', enabled: nextEnabled, schedule: { refresh_interval_seconds: nextEnabled && interval > 0 ? interval : null }, - operator: operator.trim(), } const created = await createSourceSettingsRevision(connection.id, draft) const activated = await activateSourceSettingsRevision(connection.id, created.id) @@ -99,7 +100,7 @@ function SourceSettingsCard({ connection, onSourcesChanged }: { connection: Sour catch (cause) { setFailure(cause instanceof Error ? cause.message : '加载修订历史失败') } } - const canApply = operator.trim().length >= 2 && !busy + const canApply = !busy return
{connection.name}{sourceTypeLabels[connection.source_type] ?? connection.source_type}{connection.enabled ? '' : ' · 已停用'}
@@ -111,7 +112,6 @@ function SourceSettingsCard({ connection, onSourcesChanged }: { connection: Sour
{scheduled ? : 本地手工导入来源不支持定时刷新,只能手动触发扫描。} - {connection.enabled ?
@@ -131,12 +131,13 @@ function SourceSettingsCard({ connection, onSourcesChanged }: { connection: Sour } export function SystemSettingsView({ sources, connections, monitor, settings, productionEnabled, routingCapabilities, loading, saving, error, saveMessage, onSave, onSourcesChanged, onRefresh, initialSection = 'sources' }: Props) { + const auth = useOptionalAuth() + const identity = auth?.identity ?? null const [section, setSection] = useState(initialSection) const [documentRefresh, setDocumentRefresh] = useState<15 | 30 | 60>(settings?.document_refresh_seconds ?? 15) const [resourceRefresh, setResourceRefresh] = useState<30 | 60>(settings?.resource_refresh_seconds ?? 30) const [stalled, setStalled] = useState<1800 | 3600>(settings?.stalled_after_seconds ?? 1800) const [finalizing, setFinalizing] = useState<7200 | 14400>(settings?.finalizing_after_seconds ?? 7200) - const [operator, setOperator] = useState('') const [dirty, setDirty] = useState(false) useEffect(() => { @@ -148,12 +149,12 @@ export function SystemSettingsView({ sources, connections, monitor, settings, pr setDirty(false) }, [settings]) - const canSave = Boolean(settings && operator.trim().length >= 2 && !saving) + const canSave = Boolean(settings && !saving) return

系统设置

查看内容源、服务与备份状态;来源调度与刷新参数采用版本化保存。

{error ?
{error}
: null} {monitor && settings ?
- +
文档工程师可调整:来源调度周期、刷新间隔、停滞判断管理员设置已锁定:端点、凭据、映射、生产开关
设置服务已启用当前活动版本 · 启用人 {settings.updated_by} · 启用时间 {settings.activated_at ? new Date(settings.activated_at).toLocaleString('zh-CN') : '待激活'};新设置先验证,再原子切换。
@@ -174,6 +175,7 @@ export function SystemSettingsView({ sources, connections, monitor, settings, pr

存储与备份

文件资源与生产发布前快照使用独立受限配置。

Endpoint / Bucket
尚未配置
AccessKey / Secret
仅保存凭据引用,不可回读
CDN / 公开访问域名
尚未配置
临时签名有效期
待配置
测试备份前缀
/backup/weknora/test/
生产备份前缀
/backup/weknora/prod/
快照保留
最近 30 个生产快照
恢复验证
由生产门禁读回
  • PostgreSQL 未配置
  • Elasticsearch 未配置
  • 对象存储 未配置
  • Neo4j 未配置
  • 生产发布请求 {productionEnabled ? '等待管理员核对' : '关闭'}
  • Release Worker 网页不可启用
: null} + {section === 'members' && identity?.role === 'admin' ? : null} {section === 'refresh' ?

刷新策略

这些值保存在服务器活动版本中;保存不会修改端点、凭据或生产开关。

当前活动版本
@@ -182,8 +184,7 @@ export function SystemSettingsView({ sources, connections, monitor, settings, pr
- - + {visibleSaveMessage(saveMessage, dirty) ?

{saveMessage}

: null} 当前:文档 {secondsLabel(settings.document_refresh_seconds)}、资源 {secondsLabel(settings.resource_refresh_seconds)}、停滞 {secondsLabel(settings.stalled_after_seconds)}、finalizing {secondsLabel(settings.finalizing_after_seconds)}。
: null} diff --git a/web/src/WeKnoraMonitor.test.tsx b/web/src/WeKnoraMonitor.test.tsx index 2f4b35f..bc12dc1 100644 --- a/web/src/WeKnoraMonitor.test.tsx +++ b/web/src/WeKnoraMonitor.test.tsx @@ -24,12 +24,12 @@ describe('WeKnoraMonitorView',()=>{ expect(html).toContain('scope-badge internal">对内') expect(html).toContain('scope-badge external">对外') }) - it('offers explicit change-set confirmation with operator, selection and result message',()=>{ + it('offers explicit change-set confirmation with selection and result message (actor comes from session)',()=>{ const html=renderToStaticMarkup() expect(html).toContain('预览并选择变更文件') expect(html).toContain('aria-label="选择旧手册.pdf"') expect(html).toContain('确认处理(0)') - expect(html).toContain('aria-label="确认操作人"') + expect(html).not.toContain('操作人{ @@ -38,11 +38,11 @@ describe('WeKnoraMonitorView',()=>{ expect(html).toContain('已确认') expect(html).not.toContain('确认处理') expect(html).toContain('aria-label="选择旧手册.pdf" disabled') - expect(html).not.toContain('确认操作人') }) it('shows a plainly labelled simulation with per-lane inbox controls',()=>{ const changes=renderToStaticMarkup() - for(const text of ['本地模拟数据','持久快照差异','国内工业','新增 2','更新 1','移动 1','删除 1','未变化 10','旧手册.pdf','操作人','确认原因','开始处理(1)','刷新来源 ≠ 马上导入知识库','不代表测试服务器真实数据'])expect(changes).toContain(text) + for(const text of ['本地模拟数据','持久快照差异','国内工业','新增 2','更新 1','移动 1','删除 1','未变化 10','旧手册.pdf','确认原因','开始处理(1)','刷新来源 ≠ 马上导入知识库','不代表测试服务器真实数据'])expect(changes).toContain(text) + expect(changes).not.toContain('操作人) for(const text of ['需要你出手','CR20A.pdf','tp-failed'.slice(0,0)+'remote_parse_failed','失败阶段 文档解析','批量重试所选(1)','死信(尝试耗尽,不可自动重试)','下载 ✓','文档解析 ✗','建议先在 WeKnora 手动解析该文件确认格式'])expect(attention).toContain(text) const inflight=renderToStaticMarkup() diff --git a/web/src/WeKnoraMonitor.tsx b/web/src/WeKnoraMonitor.tsx index 5758e39..f409507 100644 --- a/web/src/WeKnoraMonitor.tsx +++ b/web/src/WeKnoraMonitor.tsx @@ -67,7 +67,7 @@ interface ViewProps { changeSets?: CatalogChangeSetDetail[] confirmingSetID?: string | null confirmMessage?: string - onConfirmChangeSet?: (changeSetID: string, itemSeqs: number[], operator: string, reason: string) => void + onConfirmChangeSet?: (changeSetID: string, itemSeqs: number[], reason: string) => void selectedKB: KnowledgeProgress | null status: MonitorStatus | '' queueStatus?: ProcessingState | '' @@ -87,19 +87,18 @@ interface ViewProps { lane?: string onLaneChange?: (lane: string) => void onRetry?: (id: string) => void - onBatchRetry?: (ids: string[], operator: string) => void - onStart?: (ids: string[], operator: string, reason: string) => void + onBatchRetry?: (ids: string[]) => void + onStart?: (ids: string[], reason: string) => void onRefresh: () => void } -function ChangeSetCard({changeSet,confirming,message,onConfirm}:{changeSet:CatalogChangeSetDetail;confirming:boolean;message:string;onConfirm?:(changeSetID:string,itemSeqs:number[],operator:string,reason:string)=>void}){ +function ChangeSetCard({changeSet,confirming,message,onConfirm}:{changeSet:CatalogChangeSetDetail;confirming:boolean;message:string;onConfirm?:(changeSetID:string,itemSeqs:number[],reason:string)=>void}){ const [open,setOpen]=useState(false) const [selected,setSelected]=useState([]) - const [operator,setOperator]=useState('') const actionable=changeSet.items.filter(item=>item.action!=='no_change') const confirmable=changeSet.state==='planned'&&actionable.length>0&&Boolean(onConfirm) const toggle=(seq:number)=>setSelected(current=>current.includes(seq)?current.filter(value=>value!==seq):[...current,seq]) - return
{changeSet.source_name}{new Date(changeSet.created_at).toLocaleString('zh-CN',{hour12:false})}{changeSet.state!=='planned'?已确认:null}
新增 {changeSet.add_count}更新 {changeSet.update_count}移动 {changeSet.move_count}范围变化 {changeSet.move_scope_count}删除 {changeSet.delete_count}未变化 {changeSet.no_change_count}
{actionable.length?
setOpen((event.target as HTMLDetailsElement).open)}>预览并选择变更文件
{actionable.map(item=>)}
{confirmable?
:null}{message?

{message}

:null}
:null}
+ return
{changeSet.source_name}{new Date(changeSet.created_at).toLocaleString('zh-CN',{hour12:false})}{changeSet.state!=='planned'?已确认:null}
新增 {changeSet.add_count}更新 {changeSet.update_count}移动 {changeSet.move_count}范围变化 {changeSet.move_scope_count}删除 {changeSet.delete_count}未变化 {changeSet.no_change_count}
{actionable.length?
setOpen((event.target as HTMLDetailsElement).open)}>预览并选择变更文件
{actionable.map(item=>)}
{confirmable?
:null}{message?

{message}

:null}
:null}
} export function WeKnoraMonitorView({ @@ -134,10 +133,8 @@ export function WeKnoraMonitorView({ onStart = () => undefined, onRefresh, }: ViewProps) { - const [startOperator, setStartOperator] = useState('') - const [startReason, setStartReason] = useState('已核对来源快照与测试知识库差异') - const [retryOperator, setRetryOperator] = useState('') - const [selectedRetryIDs, setSelectedRetryIDs] = useState([]) + const [startReason, setStartReason] = useState('已核对来源快照与测试知识库差异') + const [selectedRetryIDs, setSelectedRetryIDs] = useState([]) const toggleRetrySelection = (id: string) => setSelectedRetryIDs((current) => current.includes(id) ? current.filter((value) => value !== id) : [...current, id]) const stages: Array<[MonitorStatus, number]> = selectedKB ? [ ['completed', selectedKB.completed], ['pending', selectedKB.pending], ['finalizing', selectedKB.finalizing], @@ -168,7 +165,7 @@ export function WeKnoraMonitorView({
{chainSteps(item).map((step) => {step.stage}{step.state === 'done' ? ' ✓' : step.state === 'bad' ? ' ✗' : step.state === 'active' ? ` 中 ${duration(secondsSince(item.updated_at))}` : ''})}
{item.processing_state === 'failed' || item.processing_state === 'stalled' ? adviceFor(failureStage(item), item.last_error) : item.can_start ? '确认后将创建解析任务' : '无需操作,等待自动处理'}{item.change_set_id ? <> · 来源变更集 {item.change_set_id} : null} · {item.id}
-
{item.can_start ? : null}{item.can_retry ? : null}
+
{item.can_start ? : null}{item.can_retry ? : null}
const emptyLane = (text: string) =>
{text}
return
@@ -183,19 +180,18 @@ export function WeKnoraMonitorView({
{lane === 'attention' ?
-

需要你出手({attentionItems.length})

操作人 setRetryOperator(event.target.value)} />
+

需要你出手({attentionItems.length})

{batchMessage ?

{batchMessage}

: null} {attentionItems.length ? attentionItems.map(actionTask) : emptyLane('没有失败或停滞的任务。')}

死信(尝试耗尽,不可自动重试)

原始任务与审计行保留不动;重新入队会创建新尝试
- {failures.length ?
    {failures.map((failure) =>
  • {failure.error_code}{failure.job_type === 'test.upload' ? '上传解析' : failure.job_type}{failure.publication_id ? {failure.publication_id} : null}{failure.attempt}/{failure.max_attempts_at_failure} 次 · {new Date(failure.created_at).toLocaleString('zh-CN', { hour12: false })}{failure.publication_id ? : null}
  • )}
: emptyLane('当前没有等待处理的死信记录。')} + {failures.length ?
    {failures.map((failure) =>
  • {failure.error_code}{failure.job_type === 'test.upload' ? '上传解析' : failure.job_type}{failure.publication_id ? {failure.publication_id} : null}{failure.attempt}/{failure.max_attempts_at_failure} 次 · {new Date(failure.created_at).toLocaleString('zh-CN', { hour12: false })}{failure.publication_id ? : null}
  • )}
: emptyLane('当前没有等待处理的死信记录。')}
: null} {lane === 'changes' ?

持久快照差异 · 等待确认({changeSets.filter((set) => set.state === 'planned').length} 个来源)

刷新来源 ≠ 马上导入知识库;勾选变更项并确认后才创建解析任务
{changeSets.length ?
{changeSets.map(changeSet => )}
: emptyLane('当前没有持久快照差异。')}
- - - + +

待确认 {pendingPlans.length} · 新增 {addedPlans} · 更新 {updatedPlans}

{startMessage ?

{startMessage}

: null} @@ -348,13 +344,11 @@ export function WeKnoraMonitor() { } } - const retryBatch = async (ids: string[], operatorRaw: string) => { - const operator = operatorRaw.trim() - if (!operator) { setError('批量重试需要填写操作人'); return } + const retryBatch = async (ids: string[]) => { setRetryingIDs(ids) setBatchMessage('') try { - const result = await retryPublicationsBatch(ids, operator, '解析队列批量重试') + const result = await retryPublicationsBatch(ids, '解析队列批量重试') setError(null) const skipped = result.already_running + result.not_retryable setBatchMessage(`已重新入队 ${result.started} 项${skipped ? `,跳过 ${skipped} 项(处理中或不可重试)` : ''}`) @@ -366,11 +360,11 @@ export function WeKnoraMonitor() { } } - const startPlans = async (ids: string[], operator: string, reason: string) => { + const startPlans = async (ids: string[], reason: string) => { setStarting(true) setStartMessage('') try { - const result = await startTestPublications(ids, operator, reason) + const result = await startTestPublications(ids, reason) setStartMessage(`已确认 ${result.selected} 项;新建解析任务 ${result.started} 项;已开始 ${result.already_started} 项;不可处理 ${result.unavailable} 项。`) setError(null) setDocumentRevision((value) => value + 1) @@ -381,11 +375,11 @@ export function WeKnoraMonitor() { } } - const confirmChangeSet = async (changeSetID: string, itemSeqs: number[], operator: string, reason: string) => { + const confirmChangeSet = async (changeSetID: string, itemSeqs: number[], reason: string) => { if (confirmingSetID) return setConfirmingSetID(changeSetID); setLastConfirmSetID(changeSetID); setConfirmMessage('') try { - const {result,operation} = await confirmCatalogChangeSet(changeSetID, itemSeqs, operator, reason) + const {result,operation} = await confirmCatalogChangeSet(changeSetID, itemSeqs, reason) setConfirmMessage(`已${operation==='replayed'?'沿用上次结果':'提交'}:确认 ${result.confirmed_items} 项;新建上传任务 ${result.uploads_created} 个;已有任务 ${result.uploads_existing} 个;请求移除 ${result.removals_requested} 份;内容未就绪 ${result.skipped_no_artifact} 份;缺少目标知识库 ${result.skipped_no_target} 份;未变化 ${result.no_change_ignored} 项已忽略。`) setDocumentRevision((value) => value + 1) } catch (cause) { @@ -394,5 +388,5 @@ export function WeKnoraMonitor() { setConfirmingSetID(null) } } - return void confirmChangeSet(id,seqs,operator,reason)} selectedKB={selected} status={status} queueStatus={queueStatus} queueScope={queueScope} loading={loading} error={error} retryingIDs={retryingIDs} starting={starting} startMessage={startMessage} batchMessage={batchMessage} failures={failures} metrics={metrics} onSelectKB={(kb) => { setSelected(kb); setStatus(''); setFiles(null) }} onStatus={(value) => { setStatus(value); setFiles(null) }} onQueueStatus={setQueueStatus} onQueueScope={setQueueScope} lane={lane} onLaneChange={(value) => setLane(value as typeof lane)} onRetry={(id) => void retryOne(id)} onBatchRetry={(ids, operator) => void retryBatch(ids, operator)} onStart={(ids, operator, reason) => void startPlans(ids, operator, reason)} onRefresh={() => { setDocumentRevision((value) => value + 1); setResourceRevision((value) => value + 1) }} /> + return void confirmChangeSet(id,seqs,reason)} selectedKB={selected} status={status} queueStatus={queueStatus} queueScope={queueScope} loading={loading} error={error} retryingIDs={retryingIDs} starting={starting} startMessage={startMessage} batchMessage={batchMessage} failures={failures} metrics={metrics} onSelectKB={(kb) => { setSelected(kb); setStatus(''); setFiles(null) }} onStatus={(value) => { setStatus(value); setFiles(null) }} onQueueStatus={setQueueStatus} onQueueScope={setQueueScope} lane={lane} onLaneChange={(value) => setLane(value as typeof lane)} onRetry={(id) => void retryOne(id)} onBatchRetry={(ids) => void retryBatch(ids)} onStart={(ids, reason) => void startPlans(ids, reason)} onRefresh={() => { setDocumentRevision((value) => value + 1); setResourceRevision((value) => value + 1) }} /> } \ No newline at end of file diff --git a/web/src/auth.tsx b/web/src/auth.tsx new file mode 100644 index 0000000..5278b57 --- /dev/null +++ b/web/src/auth.tsx @@ -0,0 +1,219 @@ +import { createContext, useCallback, useContext, useEffect, useMemo, useState } from 'react' +import type { ReactNode } from 'react' + +export type AuthRole = 'viewer' | 'engineer' | 'admin' + +export interface AuthIdentity { + id: string + username: string + display_name: string + role: AuthRole + must_change_password: boolean +} + +export const roleLabels: Record = { viewer: '观察者', engineer: '知识工程师', admin: '管理员' } + +interface AuthContextValue { + identity: AuthIdentity | null + ready: boolean + login: (username: string, password: string) => Promise + logout: () => Promise + changePassword: (currentPassword: string, newPassword: string) => Promise + signedOut: number + notifySignedOut: () => void +} + +const AuthContext = createContext(null) + +export function useAuth(): AuthContextValue { + const value = useContext(AuthContext) + if (!value) throw new Error('useAuth requires AuthProvider') + return value +} + +// useOptionalAuth never throws: components that also render in static unit +// tests (workspace shell, settings view) degrade to "signed out" instead. +export function useOptionalAuth(): AuthContextValue | null { + return useContext(AuthContext) +} + +// signedOutTick lets data layers bounce the whole app back to the login +// screen when any request observes a 401 (expired or revoked session). +export function useSignedOutTick(): [number, () => void] { + const [tick, setTick] = useState(0) + const notify = useCallback(() => setTick((value) => value + 1), []) + return [tick, notify] +} + +async function readError(response: Response, fallback: string): Promise { + const payload = (await response.json().catch(() => null)) as { error?: string } | null + return payload?.error || `${fallback}(HTTP ${response.status})` +} + +export function AuthProvider({ children }: { children: ReactNode }) { + const [identity, setIdentity] = useState(null) + const [ready, setReady] = useState(false) + const [signedOut, bumpSignedOut] = useSignedOutTick() + + const probe = useCallback(async () => { + try { + const response = await fetch('/api/v1/auth/me', { credentials: 'same-origin' }) + if (response.ok) { + const value = (await response.json()) as { data?: AuthIdentity } + setIdentity(value.data ?? null) + } else { + setIdentity(null) + } + } catch { + setIdentity(null) + } finally { + setReady(true) + } + }, []) + + useEffect(() => { + void probe() + }, [probe]) + + useEffect(() => { + if (signedOut > 0) setIdentity(null) + }, [signedOut]) + + // A single global fetch interceptor keeps every existing data-layer fetch + // honest: any 401 from an authenticated endpoint (e.g. a revoked or expired + // session, or an engine re-start) bounces the console back to the login + // screen instead of leaving stale forms on screen. auth/me is excluded to + // avoid recursion during the probe itself. + useEffect(() => { + const original = window.fetch.bind(window) + window.fetch = async (input, init) => { + const response = await original(input, init) + const url = typeof input === 'string' ? input : input instanceof Request ? input.url : String(input) + if (response.status === 401 && url.includes('/api/v1/') && !url.includes('/auth/')) { + bumpSignedOut() + } + return response + } + return () => { + window.fetch = original + } + }, [bumpSignedOut]) + + const login = useCallback(async (username: string, password: string) => { + const response = await fetch('/api/v1/auth/login', { + method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ username, password }), + }) + if (!response.ok) return readError(response, '登录失败') + const value = (await response.json()) as { data: AuthIdentity } + setIdentity(value.data) + return null + }, []) + + const logout = useCallback(async () => { + await fetch('/api/v1/auth/logout', { method: 'POST', credentials: 'same-origin' }).catch(() => undefined) + setIdentity(null) + }, []) + + const changePassword = useCallback(async (currentPassword: string, newPassword: string) => { + const response = await fetch('/api/v1/auth/change-password', { + method: 'POST', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ current_password: currentPassword, new_password: newPassword }), + }) + if (!response.ok) return readError(response, '修改密码失败') + await probe() + return null + }, [probe]) + + const value = useMemo( + () => ({ identity, ready, login, logout, changePassword, signedOut, notifySignedOut: bumpSignedOut }), + [identity, ready, login, logout, changePassword, signedOut, bumpSignedOut]) + return {children} +} + +export function LoginScreen() { + const { login } = useAuth() + const [username, setUsername] = useState('') + const [password, setPassword] = useState('') + const [error, setError] = useState('') + const [busy, setBusy] = useState(false) + + const submit = async (event: React.FormEvent) => { + event.preventDefault() + setBusy(true) + const failure = await login(username.trim(), password) + setBusy(false) + setError(failure ?? '') + if (!failure) setPassword('') + } + + return ( +
+
+

知识治理平台

+

登录后所有操作将记录到你名下

+ + + {error ?

{error}

: null} + +
+
+ ) +} + +export function MustChangePasswordScreen() { + const { changePassword, identity, logout } = useAuth() + const [current, setCurrent] = useState('') + const [next, setNext] = useState('') + const [confirm, setConfirm] = useState('') + const [error, setError] = useState('') + const [busy, setBusy] = useState(false) + + const submit = async (event: React.FormEvent) => { + event.preventDefault() + if (next.length < 8) { setError('新密码至少 8 位'); return } + if (next !== confirm) { setError('两次输入的新密码不一致'); return } + setBusy(true) + const failure = await changePassword(current, next) + setBusy(false) + setError(failure ?? '') + if (!failure) { setCurrent(''); setNext(''); setConfirm('') } + } + + return ( +
+
+

首次登录需要设置新密码

+

账号 {identity?.username} 的初始密码只能完成这一次登录

+ + + + {error ?

{error}

: null} + + +
+
+ ) +} + +export function TopBarUser() { + const value = useOptionalAuth() + const [menuOpen, setMenuOpen] = useState(false) + if (!value || !value.identity) return null + const { identity, logout } = value + const name = identity.display_name || identity.username + return ( +
+ + {menuOpen ? ( +
setMenuOpen(false)}> + +
+ ) : null} +
+ ) +} diff --git a/web/src/authMembers.test.ts b/web/src/authMembers.test.ts new file mode 100644 index 0000000..8790984 --- /dev/null +++ b/web/src/authMembers.test.ts @@ -0,0 +1,41 @@ +import { describe, expect, it, vi } from 'vitest' +import { roleLabels } from './auth' +import { fetchManagedUsers, resetManagedUserPassword, setManagedUserState } from './members' + +describe('role labels', () => { + it('covers exactly the three platform roles', () => { + expect(Object.keys(roleLabels).sort()).toEqual(['admin', 'engineer', 'viewer']) + }) +}) + +describe('members API', () => { + it('parses the managed user roster', async () => { + const payload = { data: [{ id: 'usr-1', username: 'boss', display_name: '老板', role: 'admin', state: 'active', must_change_password: false }] } + const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify(payload), { status: 200 })) + vi.stubGlobal('fetch', fetchMock) + const users = await fetchManagedUsers() + expect(users).toHaveLength(1) + expect(users[0].role).toBe('admin') + expect(String(fetchMock.mock.calls[0][0])).toBe('/api/v1/users') + vi.unstubAllGlobals() + }) + it('rejects a role the server does not know', async () => { + vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: [{ id: 'u', username: 'x', role: 'superuser', state: 'active' }] })))) + await expect(fetchManagedUsers()).rejects.toThrow('成员响应无效') + vi.unstubAllGlobals() + }) + it('surfaces server errors for state changes', async () => { + vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ error: 'cannot disable the last active admin' }), { status: 409 }))) + await expect(setManagedUserState('usr-1', 'disabled')).rejects.toThrow('cannot disable the last active admin') + vi.unstubAllGlobals() + }) + it('resets passwords without sending any actor field', async () => { + const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: { reset: true } }), { status: 200 })) + vi.stubGlobal('fetch', fetchMock) + await resetManagedUserPassword('usr-2', 'temp-pass-1') + const body = JSON.parse(String(fetchMock.mock.calls[0][1].body)) + expect(body).toEqual({ temporary_password: 'temp-pass-1' }) + expect(fetchMock.mock.calls[0][0]).toBe('/api/v1/users/usr-2/reset-password') + vi.unstubAllGlobals() + }) +}) diff --git a/web/src/main.tsx b/web/src/main.tsx index 65802ae..7ee5c6a 100644 --- a/web/src/main.tsx +++ b/web/src/main.tsx @@ -2,6 +2,7 @@ import { StrictMode } from 'react' import { createRoot } from 'react-dom/client' import App from './App' +import { AuthProvider, LoginScreen, MustChangePasswordScreen, useAuth } from './auth' import './styles.css' const root = document.getElementById('root') @@ -9,8 +10,20 @@ if (!root) { throw new Error('missing #root element') } +function Gate() { + const { identity, ready } = useAuth() + if (!ready) { + return

正在检查登录状态…

+ } + if (!identity) return + if (identity.must_change_password) return + return +} + createRoot(root).render( - + + + , ) diff --git a/web/src/members.ts b/web/src/members.ts new file mode 100644 index 0000000..e8a51c3 --- /dev/null +++ b/web/src/members.ts @@ -0,0 +1,70 @@ +import { newOperationID } from './operationKey' + +export interface ManagedUser { + id: string + username: string + display_name: string + role: 'viewer' | 'engineer' | 'admin' + state: 'active' | 'disabled' + must_change_password: boolean + last_login_at?: string | null +} + +export const managedUserRoles = ['viewer', 'engineer', 'admin'] as const + +const record = (value: unknown): value is Record => Boolean(value) && typeof value === 'object' && !Array.isArray(value) + +function parseUser(raw: unknown): ManagedUser { + if (!record(raw) || typeof raw.id !== 'string' || typeof raw.username !== 'string' || typeof raw.role !== 'string' || + !managedUserRoles.includes(raw.role as ManagedUser['role']) || typeof raw.state !== 'string') { + throw new Error('成员响应无效') + } + return { + id: raw.id, username: raw.username, + display_name: typeof raw.display_name === 'string' ? raw.display_name : '', + role: raw.role as ManagedUser['role'], state: raw.state === 'disabled' ? 'disabled' : 'active', + must_change_password: raw.must_change_password === true, + last_login_at: typeof raw.last_login_at === 'string' ? raw.last_login_at : null, + } +} + +async function call(url: string, init: RequestInit, message: string): Promise { + const response = await fetch(url, { + credentials: 'same-origin', + ...init, + headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'Idempotency-Key': newOperationID(), ...(init.headers || {}) }, + }) + if (!response.ok) { + const payload = (await response.json().catch(() => null)) as { error?: string } | null + throw new Error(payload?.error || `${message}(HTTP ${response.status})`) + } + return response.json() +} + +export async function fetchManagedUsers(signal?: AbortSignal): Promise { + const value = await call('/api/v1/users', { method: 'GET', signal }, '加载成员失败') + if (!record(value) || !Array.isArray(value.data)) throw new Error('成员列表响应无效') + return value.data.map(parseUser) +} + +export async function createManagedUser(input: { username: string; display_name: string; role: ManagedUser['role']; password: string }): Promise { + const value = await call('/api/v1/users', { method: 'POST', body: JSON.stringify(input) }, '创建成员失败') + if (!record(value) || !record(value.data)) throw new Error('创建成员响应无效') + return parseUser(value.data) +} + +export async function setManagedUserRole(userID: string, role: ManagedUser['role']): Promise { + const value = await call(`/api/v1/users/${encodeURIComponent(userID)}/role`, { method: 'POST', body: JSON.stringify({ role }) }, '调整角色失败') + if (!record(value) || !record(value.data)) throw new Error('角色更新响应无效') + return parseUser(value.data) +} + +export async function setManagedUserState(userID: string, state: ManagedUser['state']): Promise { + const value = await call(`/api/v1/users/${encodeURIComponent(userID)}/state`, { method: 'POST', body: JSON.stringify({ state }) }, '更新账号状态失败') + if (!record(value) || !record(value.data)) throw new Error('账号状态响应无效') + return parseUser(value.data) +} + +export async function resetManagedUserPassword(userID: string, temporaryPassword: string): Promise { + await call(`/api/v1/users/${encodeURIComponent(userID)}/reset-password`, { method: 'POST', body: JSON.stringify({ temporary_password: temporaryPassword }) }, '重置密码失败') +} diff --git a/web/src/reviewRelease.test.ts b/web/src/reviewRelease.test.ts index 3236e16..82e7f3d 100644 --- a/web/src/reviewRelease.test.ts +++ b/web/src/reviewRelease.test.ts @@ -81,16 +81,18 @@ describe('review and batch requests', () => { vi.stubGlobal('fetch', fetchMock) await fetchReviewCandidates('pending') - await reviewPublication('tp-safe', 'approved', 'internal', 'engineer-1', 'approved_for_release') - await createReleaseBatch('Batch', 'engineer-1', ['tp-safe'], ['tp-delete']) - await sealReleaseBatch('rb-safe', 'engineer-2') + await reviewPublication('tp-safe', 'approved', 'internal', 'approved_for_release') + await createReleaseBatch('Batch', ['tp-safe'], ['tp-delete']) + await sealReleaseBatch('rb-safe') await fetchReleaseBatches('draft') expect(fetchMock.mock.calls[0][0]).toBe('/api/v1/review-candidates?review_state=pending&limit=20&offset=0') expect(fetchMock.mock.calls[1][0]).toBe('/api/v1/review-candidates/tp-safe/decision') - expect(JSON.parse((fetchMock.mock.calls[1][1] as RequestInit).body as string)).toEqual({ decision: 'approved', decided_visibility: 'internal', reviewer_ref: 'engineer-1', decision_code: 'approved_for_release' }) + // actor fields are server-stamped from the session; bodies must not carry them + // 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', created_by: 'engineer-1', 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: '' }) 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') }) @@ -145,7 +147,7 @@ describe('release change set (R1)', () => { it('generates with idempotency and rejects a manifest-less envelope', async () => { const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: changeSetPayload, operation: 'created' }), { status: 201 })) vi.stubGlobal('fetch', fetchMock) - const set = await generateReleaseChangeSet('9月发布', 'engineer-1') + const set = await generateReleaseChangeSet('9月发布') expect(set.id).toBe('rcs-1') expect(set.manifest_sha256).toBe('a'.repeat(64)) const [, init] = fetchMock.mock.calls[0] as [string, RequestInit] @@ -153,12 +155,12 @@ describe('release change set (R1)', () => { expect((init.body as string)).toContain('"name":"9月发布"') const bad = vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: { ...changeSetPayload, manifest_sha256: '' } }), { status: 201 })) vi.stubGlobal('fetch', bad) - await expect(generateReleaseChangeSet('x', 'y')).rejects.toThrow('发布计划集响应缺少标识或清单摘要') + await expect(generateReleaseChangeSet('x')).rejects.toThrow('发布计划集响应缺少标识或清单摘要') }) it('confirms via scoped endpoint and loads latest detail tolerating 404', async () => { const confirmMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: { ...changeSetPayload, state: 'confirmed', confirmed_by: 'boss', confirmed_at: '2026-09-12T08:00:00Z' }, operation: 'created' }), { status: 200 })) vi.stubGlobal('fetch', confirmMock) - const confirmed = await confirmReleaseChangeSet('rcs-1', 'boss') + const confirmed = await confirmReleaseChangeSet('rcs-1') expect(confirmed.state).toBe('confirmed') expect(confirmMock.mock.calls[0][0]).toBe('/api/v1/release-change-sets/rcs-1/confirm') const latest404 = vi.fn().mockResolvedValue(new Response('{}', { status: 404 })) diff --git a/web/src/reviewRelease.ts b/web/src/reviewRelease.ts index f781f07..62351d1 100644 --- a/web/src/reviewRelease.ts +++ b/web/src/reviewRelease.ts @@ -252,9 +252,9 @@ export async function fetchReviewCandidates(reviewState: ReviewState | '' = '', return parseReviewCandidatesResponse(await getJSON(`/api/v1/review-candidates?${params}`, signal, '加载审核队列失败')) } -export async function reviewPublication(publicationID: string, decision: 'approved' | 'rejected', visibility: Visibility, reviewerRef: string, decisionCode: string): Promise { +export async function reviewPublication(publicationID: string, decision: 'approved' | 'rejected', visibility: Visibility, decisionCode: string): Promise { const value = await sendJSON(`/api/v1/review-candidates/${encodeURIComponent(publicationID)}/decision`, { - decision, decided_visibility: visibility, reviewer_ref: reviewerRef, decision_code: decisionCode, + decision, decided_visibility: visibility, decision_code: decisionCode, }, '提交审核决定失败') if (!isRecord(value) || !isRecord(value.data)) throw new Error('invalid publication review response') const raw = value.data @@ -267,8 +267,8 @@ 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, createdBy: string, publicationIDs: string[], deletePublicationIDs: string[] = [], releaseChangeSetID = ''): Promise { - return parseBatchEnvelope(await sendJSON('/api/v1/release-batches', { name, created_by: createdBy, publication_ids: publicationIDs, delete_publication_ids: deletePublicationIDs, release_change_set_id: releaseChangeSetID }, '创建封批失败')) +export async function createReleaseBatch(name: string, publicationIDs: string[], deletePublicationIDs: string[] = [], releaseChangeSetID = ''): Promise { + return parseBatchEnvelope(await sendJSON('/api/v1/release-batches', { name, publication_ids: publicationIDs, delete_publication_ids: deletePublicationIDs, release_change_set_id: releaseChangeSetID }, '创建封批失败')) } export interface ReleaseChangeSetItem { @@ -330,12 +330,12 @@ function parseChangeSetEnvelope(value: unknown): ReleaseChangeSet { } // R1: freeze the live release plan into an immutable versioned change set. -export async function generateReleaseChangeSet(name: string, createdBy: string): Promise { - return parseChangeSetEnvelope(await sendJSON('/api/v1/release-change-sets', { name, created_by: createdBy }, '生成发布计划集失败')) +export async function generateReleaseChangeSet(name: string): Promise { + return parseChangeSetEnvelope(await sendJSON('/api/v1/release-change-sets', { name }, '生成发布计划集失败')) } -export async function confirmReleaseChangeSet(changeSetID: string, confirmedBy: string): Promise { - return parseChangeSetEnvelope(await sendJSON(`/api/v1/release-change-sets/${encodeURIComponent(changeSetID)}/confirm`, { confirmed_by: confirmedBy }, '确认发布计划集失败')) +export async function confirmReleaseChangeSet(changeSetID: string): Promise { + return parseChangeSetEnvelope(await sendJSON(`/api/v1/release-change-sets/${encodeURIComponent(changeSetID)}/confirm`, {}, '确认发布计划集失败')) } export async function fetchLatestReleaseChangeSet(signal?: AbortSignal): Promise { @@ -361,8 +361,8 @@ export async function fetchLatestReleaseChangeSet(signal?: AbortSignal): Promise return { ...base, items } } -export async function sealReleaseBatch(batchID: string, sealedBy: string): Promise { - return parseBatchEnvelope(await sendJSON(`/api/v1/release-batches/${encodeURIComponent(batchID)}/seal`, { sealed_by: sealedBy }, '封批失败')) +export async function sealReleaseBatch(batchID: string): Promise { + return parseBatchEnvelope(await sendJSON(`/api/v1/release-batches/${encodeURIComponent(batchID)}/seal`, {}, '封批失败')) } export async function fetchReleaseBatches(state: ReleaseBatchState | '' = '', limit = 20, offset = 0, signal?: AbortSignal): Promise { diff --git a/web/src/scopeRules.test.ts b/web/src/scopeRules.test.ts index 5db98f5..475e71c 100644 --- a/web/src/scopeRules.test.ts +++ b/web/src/scopeRules.test.ts @@ -15,10 +15,10 @@ describe('scope rule API',()=>{ const fetchMock=vi.fn().mockImplementation(()=>Promise.resolve(new Response(JSON.stringify({data:{target_type:'directory',connection_id:'conn-1',directory_path:'产品',visibility:'internal'}})))) vi.stubGlobal('fetch',fetchMock) const target={target_type:'directory' as const,connection_id:'conn-1',directory_path:'产品',source_item_id:''} - await setScopeRule({...target,visibility:'internal',operator_ref:'engineer-1',reason:'内部资料'}) - await clearScopeRule({...target,operator_ref:'engineer-1',reason:'恢复来源设置'}) + await setScopeRule({...target,visibility:'internal',reason:'内部资料'}) + await clearScopeRule({...target,reason:'恢复来源设置'}) expect(fetchMock.mock.calls[0][1]).toMatchObject({method:'PUT',headers:{Accept:'application/json','Content-Type':'application/json','Idempotency-Key':expect.any(String)}}) - expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({...target,visibility:'internal',operator_ref:'engineer-1',reason:'内部资料'}) + expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({...target,visibility:'internal',reason:'内部资料'}) expect(fetchMock.mock.calls[1][1]).toMatchObject({method:'DELETE',headers:{Accept:'application/json','Content-Type':'application/json','Idempotency-Key':expect.any(String)}}) expect(JSON.parse(fetchMock.mock.calls[1][1].body)).not.toHaveProperty('visibility') }) diff --git a/web/src/scopeRules.ts b/web/src/scopeRules.ts index bd1fd19..476e24c 100644 --- a/web/src/scopeRules.ts +++ b/web/src/scopeRules.ts @@ -22,12 +22,10 @@ export interface ScopeRuleTarget { export interface ScopeRuleDecision extends ScopeRuleTarget { visibility: Visibility - operator_ref: string reason: string } export interface ClearScopeRuleDecision extends ScopeRuleTarget { - operator_ref: string reason: string } diff --git a/web/src/sourceCatalog.test.ts b/web/src/sourceCatalog.test.ts index b7c2852..200d3d2 100644 --- a/web/src/sourceCatalog.test.ts +++ b/web/src/sourceCatalog.test.ts @@ -39,7 +39,7 @@ describe('source catalog API',()=>{ .mockResolvedValueOnce(new Response(JSON.stringify({data:{selected_files:2,routable_files:2,unbound_files:0,hash_unknown_files:0,unavailable_files:0}}))) vi.stubGlobal('fetch',fetchMock) expect((await fetchCatalogRoutingCapabilities()).internal_enabled).toBe(true) - const result=await routeCatalogFiles({connection_id:'conn-1',node_ids:['a','b'],policy:'both',operator_ref:'engineer-1',reason:'批量标注'}) + const result=await routeCatalogFiles({connection_id:'conn-1',node_ids:['a','b'],policy:'both',reason:'批量标注'}) expect(result.routable_files).toBe(2) expect(result.unbound_files).toBe(0) const payload=JSON.parse(fetchMock.mock.calls[1][1].body) @@ -52,7 +52,7 @@ describe('source catalog API',()=>{ it('returns the number of test-knowledge removals requested by a blocked policy',async()=>{ const fetchMock=vi.fn().mockResolvedValue(new Response(JSON.stringify({data:{selected_files:2,routable_files:0,unbound_files:2,hash_unknown_files:0,unavailable_files:0}}))) vi.stubGlobal('fetch',fetchMock) - const result=await routeCatalogFiles({connection_id:'conn-1',node_ids:['a','b'],policy:'blocked',operator_ref:'engineer-1',reason:'禁止导入'}) + const result=await routeCatalogFiles({connection_id:'conn-1',node_ids:['a','b'],policy:'blocked',reason:'禁止导入'}) expect(result.unbound_files).toBe(2) }) it('starts a durable background refresh job with no source credential payload',async()=>{ diff --git a/web/src/sourceCatalog.ts b/web/src/sourceCatalog.ts index ff9785a..35cbd9e 100644 --- a/web/src/sourceCatalog.ts +++ b/web/src/sourceCatalog.ts @@ -44,8 +44,8 @@ export async function fetchCatalogSnapshotNodes(connectionID:string,snapshotID:s return {current:parseNode(value.current),breadcrumbs:Array.isArray(value.breadcrumbs)?value.breadcrumbs.map(raw=>{if(!record(raw)||typeof raw.node_id!=='string'||typeof raw.name!=='string')throw new Error('目录路径响应无效');return raw as unknown as CatalogBreadcrumb}):[],items:value.items.map(parseNode),total:value.total,limit:value.limit,offset:value.offset} } export interface ConfirmChangeSetResult{change_set_id:string;confirmed_items:number;uploads_created:number;uploads_existing:number;removals_requested:number;skipped_no_artifact:number;skipped_no_target:number;no_change_ignored:number} -export async function confirmCatalogChangeSet(changeSetID:string,itemSeqs:number[],operatorRef:string,reason:string):Promise<{result:ConfirmChangeSetResult;operation:string}>{ - const response=await fetch(`/api/v1/source-catalog/change-sets/${encodeURIComponent(changeSetID)}/confirm`,{method:'POST',headers:{Accept:'application/json','Content-Type':'application/json','Idempotency-Key':newOperationID()},body:JSON.stringify({item_seqs:itemSeqs,operator_ref:operatorRef,reason})}) +export async function confirmCatalogChangeSet(changeSetID:string,itemSeqs:number[],reason:string):Promise<{result:ConfirmChangeSetResult;operation:string}>{ + const response=await fetch(`/api/v1/source-catalog/change-sets/${encodeURIComponent(changeSetID)}/confirm`,{method:'POST',headers:{Accept:'application/json','Content-Type':'application/json','Idempotency-Key':newOperationID()},body:JSON.stringify({item_seqs:itemSeqs,reason})}) if(!response.ok)throw new Error(response.status===409?'操作标识与另一请求冲突,请刷新后重试':`确认快照差异失败(HTTP ${response.status})`) const value=await response.json() as unknown;if(!record(value)||!record(value.data)||!count(value.data.confirmed_items)||!count(value.data.uploads_created)||!count(value.data.uploads_existing)||!count(value.data.removals_requested)||!count(value.data.skipped_no_artifact)||!count(value.data.skipped_no_target)||!count(value.data.no_change_ignored)||typeof value.operation!=='string')throw new Error('确认快照差异响应无效') return {result:value.data as unknown as ConfirmChangeSetResult,operation:value.operation} @@ -77,7 +77,7 @@ export async function fetchAllCatalogFolders(connectionID:string,parentID:string } export interface CatalogRoutingCapabilities{internal_enabled:boolean;external_enabled:boolean} -export interface CatalogRouteInput{connection_id:string;node_ids:string[];policy:CatalogPolicy;operator_ref:string;reason:string} +export interface CatalogRouteInput{connection_id:string;node_ids:string[];policy:CatalogPolicy;reason:string} export interface CatalogRouteResult{selected_files:number;routable_files:number;unbound_files:number;hash_unknown_files:number;unavailable_files:number} export async function fetchCatalogRoutingCapabilities(signal?:AbortSignal):Promise{ diff --git a/web/src/sourceConnections.test.ts b/web/src/sourceConnections.test.ts index 8c650aa..c169a34 100644 --- a/web/src/sourceConnections.test.ts +++ b/web/src/sourceConnections.test.ts @@ -157,7 +157,7 @@ describe('V1 source settings client', () => { .mockResolvedValueOnce(new Response(JSON.stringify({ data: { id: 'scr-2' }, operation: 'created' }), { status: 201 })) .mockResolvedValueOnce(new Response(JSON.stringify({ data: { connection_id: 'c', revision_id: 'scr-2' }, operation: 'replayed' }), { status: 200 })) vi.stubGlobal('fetch', fetchMock) - expect(await createSourceSettingsRevision('conn/1', { source_type: 'alist', name: 'A', endpoint: '', credential_ref: '', enabled: true, schedule: { refresh_interval_seconds: 3600 }, operator: 'zherom' })).toEqual({ operation: 'created', id: 'scr-2' }) + expect(await createSourceSettingsRevision('conn/1', { source_type: 'alist', name: 'A', endpoint: '', credential_ref: '', enabled: true, schedule: { refresh_interval_seconds: 3600 } })).toEqual({ operation: 'created', id: 'scr-2' }) expect(await activateSourceSettingsRevision('conn/1', 'scr/2')).toEqual({ operation: 'replayed', id: null }) const [createCall, activateCall] = fetchMock.mock.calls expect(createCall[0]).toBe('/api/v1/source-connections/conn%2F1/settings/revisions') @@ -168,7 +168,7 @@ describe('V1 source settings client', () => { }) it('surfaces server error details on failure', async () => { vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ error: 'manual sources cannot be scheduled' }), { status: 400 }))) - await expect(createSourceSettingsRevision('c', { source_type: 'manual', name: 'A', endpoint: '', credential_ref: '', enabled: true, schedule: { refresh_interval_seconds: 3600 }, operator: 'z' })).rejects.toThrow('保存来源设置草稿失败:manual sources cannot be scheduled') + await expect(createSourceSettingsRevision('c', { source_type: 'manual', name: 'A', endpoint: '', credential_ref: '', enabled: true, schedule: { refresh_interval_seconds: 3600 } })).rejects.toThrow('保存来源设置草稿失败:manual sources cannot be scheduled') }) it('parses revision history strictly', async () => { const revision = { id: 'scr-1', revision_number: 1, state: 'active', name: 'A', endpoint: 'http://x', credential_ref: 'ref', enabled: true, refresh_interval_seconds: '3600', created_by: 'z', created_at: '2026-09-12T01:00:00Z', validated_at: null, activated_at: '2026-09-12T01:00:00Z', retired_at: null } diff --git a/web/src/sourceConnections.ts b/web/src/sourceConnections.ts index ce93e77..298cd7d 100644 --- a/web/src/sourceConnections.ts +++ b/web/src/sourceConnections.ts @@ -310,7 +310,6 @@ export interface SourceSettingsDraftRequest { credential_ref: string enabled: boolean schedule: { refresh_interval_seconds?: number | null } - operator: string } const revisionStates = new Set(['validated', 'active', 'retired', 'failed']) diff --git a/web/src/styles.css b/web/src/styles.css index d2ca372..714f9f5 100644 --- a/web/src/styles.css +++ b/web/src/styles.css @@ -1914,3 +1914,67 @@ tbody tr:hover { .recent-row { grid-template-columns: minmax(0, 1fr) auto; } .recent-row time { grid-column: 1 / -1; text-align: left; } } + +/* ── 登录 / 强制改密 / 顶栏身份(A · Data-console) ─────────────── */ +.login-shell { + min-height: 100vh; + display: grid; + place-items: center; + background: + radial-gradient(1100px 500px at 15% -10%, var(--c-run-bg), transparent 60%), + linear-gradient(180deg, var(--bg-page), var(--bg-softer)); + padding: 24px; +} +.login-card { + width: min(400px, 100%); + background: var(--bg-panel); + border: 1px solid var(--border-base); + border-radius: 10px; + padding: 28px 26px 24px; + box-shadow: 0 18px 46px rgba(15, 23, 32, 0.10); + display: grid; + gap: 14px; +} +.login-card h1 { margin: 0; font-size: 20px; color: var(--ink-strong); letter-spacing: 0.01em; } +.login-subtitle { margin: 0; color: var(--ink-mute); font-size: 13px; } +.login-card label { display: grid; gap: 6px; font-size: 13px; color: var(--ink-base); font-weight: 600; } +.login-card input { + padding: 10px 12px; + border: 1px solid var(--border-strong); + border-radius: 6px; + font: inherit; + background: var(--bg-panel); + color: var(--ink-strong); +} +.login-card input:focus { outline: 2px solid var(--c-run); outline-offset: 1px; border-color: transparent; } +.login-card button[type="submit"] { width: 100%; margin-top: 4px; } +.login-error { margin: 0; font-size: 13px; color: var(--c-fail); background: var(--c-fail-bg); border: 1px solid var(--c-fail-border); border-radius: 6px; padding: 8px 10px; } +.login-secondary { background: transparent; border: none; color: var(--ink-mute); font-size: 12.5px; cursor: pointer; text-decoration: underline; } + +.topbar-user { position: relative; margin-left: auto; } +.topbar-user-button { + display: inline-flex; align-items: center; gap: 8px; + background: var(--bg-soft); border: 1px solid var(--border-base); border-radius: 999px; + padding: 4px 12px 4px 4px; cursor: pointer; color: var(--ink-base); font: inherit; +} +.topbar-user-button:hover { background: var(--bg-hover); } +.topbar-user-avatar { + width: 26px; height: 26px; border-radius: 50%; + background: var(--side-bg); color: var(--side-accent); + display: grid; place-items: center; font-size: 13px; font-weight: 700; +} +.topbar-user-name { font-size: 13px; font-weight: 600; } +.role-badge { font-size: 11px; padding: 1px 8px; border-radius: 999px; border: 1px solid var(--border-base); background: var(--bg-panel); color: var(--ink-mute); } +.role-badge.role-admin { color: var(--c-run); border-color: var(--c-run-border); background: var(--c-run-bg); } +.role-badge.role-engineer { color: var(--c-done); border-color: var(--c-done-border); background: var(--c-done-bg); } +.topbar-user-menu { + position: absolute; right: 0; top: calc(100% + 6px); z-index: 30; + background: var(--bg-panel); border: 1px solid var(--border-base); border-radius: 8px; + box-shadow: 0 12px 30px rgba(15, 23, 32, 0.12); min-width: 140px; padding: 4px; +} +.topbar-user-menu button { width: 100%; text-align: left; background: transparent; border: none; padding: 8px 10px; border-radius: 6px; cursor: pointer; font: inherit; color: var(--ink-base); } +.topbar-user-menu button:hover { background: var(--bg-hover); } + +.member-create-form { display: flex; flex-wrap: wrap; gap: 12px; align-items: flex-end; margin-top: 14px; padding-top: 14px; border-top: 1px solid var(--border-soft); } +.member-create-form label { display: grid; gap: 5px; font-size: 12.5px; color: var(--ink-base); font-weight: 600; } +.member-create-form input, .member-create-form select { padding: 8px 10px; border: 1px solid var(--border-strong); border-radius: 6px; font: inherit; background: var(--bg-panel); } diff --git a/web/src/testPublications.test.ts b/web/src/testPublications.test.ts index 50fa95f..222e5fe 100644 --- a/web/src/testPublications.test.ts +++ b/web/src/testPublications.test.ts @@ -94,11 +94,11 @@ describe('startTestPublications', () => { const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ data: { selected: 2, started: 1, already_started: 1, unavailable: 0 } }), { status: 202 })) vi.stubGlobal('fetch', fetchMock) - await expect(startTestPublications(['pub-a', 'pub-b'], 'engineer-1', '已核对差异')).resolves.toEqual({ selected: 2, started: 1, already_started: 1, unavailable: 0 }) + await expect(startTestPublications(['pub-a', 'pub-b'], '已核对差异')).resolves.toEqual({ selected: 2, started: 1, already_started: 1, unavailable: 0 }) expect(fetchMock).toHaveBeenCalledWith('/api/v1/test-publications/start', expect.objectContaining({ method: 'POST', headers: expect.objectContaining({ 'Idempotency-Key': expect.any(String) }), - body: JSON.stringify({ publication_ids: ['pub-a', 'pub-b'], operator_ref: 'engineer-1', reason: '已核对差异' }), + body: JSON.stringify({ publication_ids: ['pub-a', 'pub-b'], reason: '已核对差异' }), })) }) }) @@ -111,19 +111,19 @@ describe('retryPublicationsBatch', () => { }) vi.stubGlobal('fetch', fetchMock) - const result = await retryPublicationsBatch(['tp-1', 'tp-2'], '姚工', '解析服务恢复') + const result = await retryPublicationsBatch(['tp-1', 'tp-2'], '解析服务恢复') expect(fetchMock).toHaveBeenCalledWith('/api/v1/test-publications/retry-batch', expect.objectContaining({ method: 'POST' })) const call = fetchMock.mock.calls[0] as [string, RequestInit] - expect(JSON.parse(String(call[1].body))).toEqual({ publication_ids: ['tp-1', 'tp-2'], operator_ref: '姚工', reason: '解析服务恢复' }) + expect(JSON.parse(String(call[1].body))).toEqual({ publication_ids: ['tp-1', 'tp-2'], reason: '解析服务恢复' }) expect(result.started).toBe(1) expect(result.outcomes[1].result).toBe('already_running') }) it('rejects a malformed batch envelope', async () => { vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: async () => ({ data: {} }) })) - await expect(retryPublicationsBatch(['tp-1'], '姚工', 'r')).rejects.toThrow() + await expect(retryPublicationsBatch(['tp-1'], 'r')).rejects.toThrow() }) }) diff --git a/web/src/testPublications.ts b/web/src/testPublications.ts index 56217e5..9ff5499 100644 --- a/web/src/testPublications.ts +++ b/web/src/testPublications.ts @@ -118,11 +118,11 @@ export async function retryPublication(publicationId: string): Promise { } } -export async function startTestPublications(publicationIds: string[], operatorRef: string, reason: string): Promise { +export async function startTestPublications(publicationIds: string[], reason: string): Promise { const response = await fetch('/api/v1/test-publications/start', { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'Idempotency-Key': newOperationID() }, - body: JSON.stringify({ publication_ids: publicationIds, operator_ref: operatorRef, reason }), + body: JSON.stringify({ publication_ids: publicationIds, reason }), }) if (!response.ok) { const body = (await response.json().catch(() => null)) as { error?: string } | null @@ -142,11 +142,11 @@ export async function startTestPublications(publicationIds: string[], operatorRe export interface RetryOutcome { publication_id: string; result: 'started' | 'already_running' | 'not_retryable'; detail?: string } export interface RetryPublicationsBatchResult { batch_key: string; total: number; started: number; already_running: number; not_retryable: number; outcomes: RetryOutcome[] } -export async function retryPublicationsBatch(publicationIds: string[], operatorRef: string, reason: string): Promise { +export async function retryPublicationsBatch(publicationIds: string[], reason: string): Promise { const response = await fetch('/api/v1/test-publications/retry-batch', { method: 'POST', headers: { Accept: 'application/json', 'Content-Type': 'application/json', 'Idempotency-Key': newOperationID() }, - body: JSON.stringify({ publication_ids: publicationIds, operator_ref: operatorRef, reason }), + body: JSON.stringify({ publication_ids: publicationIds, reason }), }) if (!response.ok) { const body = (await response.json().catch(() => null)) as { error?: string } | null diff --git a/web/src/uiSettings.test.ts b/web/src/uiSettings.test.ts index 5356643..a3d49ec 100644 --- a/web/src/uiSettings.test.ts +++ b/web/src/uiSettings.test.ts @@ -29,12 +29,12 @@ describe('UI settings API', () => { vi.stubGlobal('fetch', fetchMock) await fetchActiveUISettings() - await createUISettingsCandidate({ document_refresh_seconds: 30, resource_refresh_seconds: 60, stalled_after_seconds: 3600, finalizing_after_seconds: 14400, updated_by: 'engineer-1' }) + await createUISettingsCandidate({ document_refresh_seconds: 30, resource_refresh_seconds: 60, stalled_after_seconds: 3600, finalizing_after_seconds: 14400 }) await activateUISettings('uis-candidate') expect(fetchMock.mock.calls[0][0]).toBe('/api/v1/ui-settings') expect(fetchMock.mock.calls[1][0]).toBe('/api/v1/ui-settings/candidates') - expect(fetchMock.mock.calls[1][1]).toMatchObject({ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ document_refresh_seconds: 30, resource_refresh_seconds: 60, stalled_after_seconds: 3600, finalizing_after_seconds: 14400, updated_by: 'engineer-1' }) }) + expect(fetchMock.mock.calls[1][1]).toMatchObject({ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ document_refresh_seconds: 30, resource_refresh_seconds: 60, stalled_after_seconds: 3600, finalizing_after_seconds: 14400 }) }) expect(fetchMock.mock.calls[2][0]).toBe('/api/v1/ui-settings/uis-candidate/activate') expect(fetchMock.mock.calls[2][1]).toMatchObject({ method: 'POST', headers: { 'Content-Type': 'application/json' }, body: '{}' }) vi.unstubAllGlobals() diff --git a/web/src/uiSettings.ts b/web/src/uiSettings.ts index 3ffb111..e4c6e7a 100644 --- a/web/src/uiSettings.ts +++ b/web/src/uiSettings.ts @@ -18,7 +18,6 @@ export interface UISettingsCandidateInput { resource_refresh_seconds: UISettings['resource_refresh_seconds'] stalled_after_seconds: UISettings['stalled_after_seconds'] finalizing_after_seconds: UISettings['finalizing_after_seconds'] - updated_by: string } export function settingsRefreshDelays(settings: Pick) {