feat(web): login gate, session identity UI and member management

- main.tsx 挂 AuthProvider 门控:未登录→登录页;must_change_password→强制改密页
- 登录页/改密页/顶栏身份(头像+姓名+角色徽章+退出)按 A·Data-console token 样式
- 全局 fetch 拦截器:任意业务请求 401 自动回登录页(会话过期/被撤销不留死表单)
- 系统设置新增「成员与角色」分区(仅 admin 可见):名单、角色调整、启停、重置临时密码、新增成员
- 消灭全部手填操作人:审核/封批/确认计划集/范围规则/来源调度/UI 设置/开始处理/批量重试/
  目录差异确认共 9 处输入框删除,请求体不再携带 actor 字段(服务端从会话注入)
- 测试断言方向翻转:显式验证请求体不含 operator_ref/created_by 等字段
- 附带修复:登录失败计数 SQL 参数类型无法推断导致 500(pgx 扩展协议),显式 cast 解决

前端门禁:tsc 0 错、125 用例全绿、build 通过
This commit is contained in:
2026-09-13 16:27:11 +08:00
committed by 姚章浩
parent fbe80ad784
commit f6cb90cd70
30 changed files with 637 additions and 158 deletions
+1 -1
View File
@@ -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
+10 -11
View File
@@ -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) {
+10 -10
View File
@@ -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 {
+7 -5
View File
@@ -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
}
+4 -5
View File
@@ -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 步,创建发布批次',
'为什么按钮不能点:请先填写操作人姓名或工号',
'为什么按钮不能点:请确认所选删除项会停止生产检索',
'如何决定批准或驳回',
'可以批准:基础测试通过,你已确认搜索结果相关,而且发布范围正确',
'应该驳回:内容错误、过期、敏感、搜索结果不相关,或者你无法确认',
+30 -31
View File
@@ -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) {
})}
</div>
<WorkspaceContextTabsBar tabs={contextTabs} />
<TopBarUser />
</header>
<div className="workspace-content">{props.children}</div>
</section>
@@ -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<string[]>([])
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) {
<div className="guidance-copy">
<h2>{guidance.title}</h2>
<strong>{guidance.reason}</strong>
{guidance.step === 3 ? <div className="current-checklist"><b>完成本步的 4 件事</b><ol><li>填写操作人姓名或工号</li><li>只审核本次准备发布的文件</li><li>勾选要发布的已批准知识</li><li>填写批次名称并创建草稿</li></ol></div> : null}
{guidance.step === 3 ? <div className="current-checklist"><b>完成本步的 3 件事</b><ol><li>只审核本次准备发布的文件</li><li>勾选要发布的已批准知识</li><li>填写批次名称并创建草稿</li></ol></div> : null}
<p>{`现在先做:${guidance.action}`}</p>
<p>{`完成后进入:${guidance.after}`}</p>
<span>{guidance.impact}</span>
@@ -958,8 +958,8 @@ export function ReleaseManagement(props: ReleaseManagementProps) {
{changeSet && changeSet.state === 'planned' ? <details className="release-changeset-items"><summary>查看冻结清单({changeSet.items.length}项)</summary><ul>{changeSet.items.map((item) => <li key={item.seq}>{`${item.seq}. ${item.title} · ${item.target_scope === 'internal' ? '对内' : '对外'} · ${frozenActionLabel(item.action)}${item.can_release ? '' : '(阻断:' + (item.blocker === 'source_unavailable' ? '来源不可用' : '测试未就绪') + ')'}`}</li>)}</ul></details> : null}
{changeSetError ? <p className="form-error">{changeSetError}</p> : null}
<div className="release-changeset-actions">
<button type="button" className="secondary-action" disabled={!reviewerRef || changeSetBusy} title={reviewerRef ? '把当前实时发布计划固化为新版本(相同计划自动去重)' : '请先填写操作人'} onClick={() => onGenerateChangeSet(batchName.trim() || `发布计划 ${new Date().toLocaleDateString('zh-CN')}`, reviewerRef)}>生成新版本</button>
{changeSet && changeSet.state === 'planned' ? <button type="button" disabled={!reviewerRef || changeSetBusy} onClick={() => onConfirmChangeSet(changeSet.id, reviewerRef)}>确认冻结(此后不可更改)</button> : null}
<button type="button" className="secondary-action" disabled={changeSetBusy} title="把当前实时发布计划固化为新版本(相同计划自动去重)" onClick={() => onGenerateChangeSet(batchName.trim() || `发布计划 ${new Date().toLocaleDateString('zh-CN')}`)}>生成新版本</button>
{changeSet && changeSet.state === 'planned' ? <button type="button" disabled={changeSetBusy} onClick={() => onConfirmChangeSet(changeSet.id)}>确认冻结(此后不可更改)</button> : null}
{changeSet && changeSet.state === 'confirmed' ? <small className="safe-badge">创建批次将自动绑定 v{changeSet.number} 并校验清单</small> : <small>草稿批次需先由上方“确认冻结”固定目标</small>}
</div>
</div>
@@ -975,7 +975,6 @@ export function ReleaseManagement(props: ReleaseManagementProps) {
<section className="panel review-panel" id="review-actions">
<div className="panel-heading release-toolbar">
<div><h2>第 3 步:审核要发布的知识</h2><p>先确认测试结果和对内/对外范围,再批准或驳回。批准后才能勾选加入批次。</p></div>
<label>操作人(必填)<input value={reviewerRef} onChange={(event) => setReviewerRef(event.target.value)} placeholder="填写姓名或工号" /></label>
</div>
{batchBlocker ? <div className="button-reason" role="note"><strong>{`为什么按钮不能点:${batchBlocker}`}</strong></div> : null}
<div className="review-decision-guide" aria-label="审核判断标准">
@@ -1000,19 +999,19 @@ export function ReleaseManagement(props: ReleaseManagementProps) {
<td><span className={`status status-${item.gate_status === 'ready' ? 'completed' : 'failed'}`}>{reviewGateLabel(item)}</span></td>
<td><select value={visibility} onChange={(event) => setVisibilityByID((current) => ({ ...current, [item.publication_id]: event.target.value as Visibility }))}><option value="internal">仅内部员工</option><option value="external">允许外部用户</option></select></td>
<td><span className={`status status-${item.review_state === 'approved' ? 'completed' : item.review_state === 'rejected' ? 'failed' : 'pending'}`}>{reviewLabels[item.review_state]}</span>{item.reviewer_ref ? <small>{item.reviewer_ref}</small> : null}</td>
<td><div className="row-actions"><button type="button" disabled={!reviewerRef || item.gate_status !== 'ready' || props.reviewingId === item.publication_id} onClick={() => props.onReview(item.publication_id, 'approved', visibility, reviewerRef, 'approved_for_release')}>批准</button><button type="button" className="secondary-action" disabled={!reviewerRef || props.reviewingId === item.publication_id} onClick={() => props.onReview(item.publication_id, 'rejected', visibility, reviewerRef, 'needs_correction')}>驳回</button></div></td>
<td><div className="row-actions"><button type="button" disabled={item.gate_status !== 'ready' || props.reviewingId === item.publication_id} onClick={() => props.onReview(item.publication_id, 'approved', visibility, 'approved_for_release')}>批准</button><button type="button" className="secondary-action" disabled={props.reviewingId === item.publication_id} onClick={() => props.onReview(item.publication_id, 'rejected', visibility, 'needs_correction')}>驳回</button></div></td>
</tr>
})}
</tbody></table></div> : null}
<div className="batch-requirements" aria-label="创建批次条件"><strong>创建批次还需要</strong><span className={reviewerRef ? 'met' : 'unmet'}>填写操作人</span><span className={props.selectedDeleteIDs.length === 0 || deleteConfirmed ? 'met' : 'unmet'}>确认所选发布动作</span><span className={confirmedSelection ? 'met' : 'unmet'}>至少 1 项动作通过确认</span><span className={batchName.trim() ? 'met' : 'unmet'}>填写批次名称</span></div>
<div className="batch-create-bar"><label>批次名称<input value={batchName} onChange={(event) => setBatchName(event.target.value)} placeholder="例如:9月第一批知识" /></label><span>已选 {selectedCount} 项{props.selectedDeleteIDs.length > 0 && !deleteConfirmed ? '(删除待确认)' : ''}</span><button type="button" title={batchBlocker || '创建后仍可检查和调整'} disabled={Boolean(batchBlocker) || props.batchLoading} onClick={() => props.onCreateBatch(batchName, reviewerRef, selectedIDs, props.selectedDeleteIDs)}>创建草稿批次</button></div>
<div className="batch-requirements" aria-label="创建批次条件"><strong>创建批次还需要</strong><span className={props.selectedDeleteIDs.length === 0 || deleteConfirmed ? 'met' : 'unmet'}>确认所选发布动作</span><span className={confirmedSelection ? 'met' : 'unmet'}>至少 1 项动作通过确认</span><span className={batchName.trim() ? 'met' : 'unmet'}>填写批次名称</span></div>
<div className="batch-create-bar"><label>批次名称<input value={batchName} onChange={(event) => setBatchName(event.target.value)} placeholder="例如:9月第一批知识" /></label><span>已选 {selectedCount} 项{props.selectedDeleteIDs.length > 0 && !deleteConfirmed ? '(删除待确认)' : ''}</span><button type="button" title={batchBlocker || '创建后仍可检查和调整'} disabled={Boolean(batchBlocker) || props.batchLoading} onClick={() => props.onCreateBatch(batchName, selectedIDs, props.selectedDeleteIDs)}>创建草稿批次</button></div>
</section>
<section className="panel batch-panel" id="batch-actions">
<div className="panel-heading"><div><h2>第 4–5 步:创建并锁定发布清单</h2><p>草稿可以继续核对;点击“锁定清单(不会上线)”后,本次内容不再变化,但仍不会发布到生产。</p></div><span className="safe-badge">锁定清单 ≠ 上线</span></div>
{props.batchError ? <div className="error-banner" role="alert">{props.batchError}</div> : null}
{!props.batchLoading && !props.batchError && props.batchPage.items.length === 0 ? <div className="empty-state">尚无草稿或已锁定的发布清单。</div> : null}
{props.batchPage.items.length > 0 ? <div className="batch-grid"><div className="table-wrap"><table><thead><tr><th>批次名称</th><th>状态</th><th>知识数量</th><th>内容状态</th><th>操作</th></tr></thead><tbody>
{props.batchPage.items.map((batch) => <tr key={batch.id}><td><strong>{batch.name}</strong></td><td><span className={`status status-${batch.state === 'sealed' ? 'completed' : 'pending'}`}>{batchLabels[batch.state]}</span></td><td>{batch.item_count}</td><td>{batch.state === 'sealed' ? '内容已锁定' : '仍可检查调整'}</td><td><div className="row-actions"><button type="button" className="secondary-action" onClick={() => props.onSelectBatch(batch.id)}>查看内容</button>{batch.state === 'draft' ? <button type="button" disabled={!reviewerRef || props.mutatingBatchId === batch.id} onClick={() => props.onSealBatch(batch.id, reviewerRef)}>锁定清单(不会上线)</button> : null}</div></td></tr>)}
{props.batchPage.items.map((batch) => <tr key={batch.id}><td><strong>{batch.name}</strong></td><td><span className={`status status-${batch.state === 'sealed' ? 'completed' : 'pending'}`}>{batchLabels[batch.state]}</span></td><td>{batch.item_count}</td><td>{batch.state === 'sealed' ? '内容已锁定' : '仍可检查调整'}</td><td><div className="row-actions"><button type="button" className="secondary-action" onClick={() => props.onSelectBatch(batch.id)}>查看内容</button>{batch.state === 'draft' ? <button type="button" disabled={props.mutatingBatchId === batch.id} onClick={() => props.onSealBatch(batch.id)}>锁定清单(不会上线)</button> : null}</div></td></tr>)}
</tbody></table></div><div className="batch-detail"><h3>本批次包含</h3>{props.batchDetail ? <>{props.batchDetail.items.map((item) => <div className="batch-detail-row" key={item.publication_id}><span><strong>{item.title}</strong><small>{item.action === 'delete' ? '删除生产知识' : '新增或更新生产知识'}</small></span><b>{item.decided_visibility === 'internal' ? '仅内部员工' : '允许外部用户'}</b></div>)}{props.batchDetail.items.length === 0 ? <div className="empty-state">批次没有知识。</div> : null}</> : <div className="empty-state">点击“查看内容”核对本次发布清单。</div>}</div></div> : null}
</section>
<section className="panel execution-panel" id="release-execution">
@@ -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}
+81
View File
@@ -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<ManagedUser[]>([])
const [loading, setLoading] = useState(true)
const [busy, setBusy] = useState<string | null>(null)
const [error, setError] = useState<string | null>(null)
const [message, setMessage] = useState<string | null>(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<unknown>, 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 <section className="settings-panel wide" id="settings-members">
<div className="settings-section-heading"><div><h2>成员与角色</h2><p>登录后的一切操作自动记录在成员名下;角色决定谁能审核、封批和行使生产授权。</p></div></div>
{loading ? <p>加载成员…</p> : null}
{error ? <p className="error-message" role="alert">{error}</p> : null}
{message ? <p className="success-message" role="status">{message}</p> : null}
<div className="table-wrap"><table><thead><tr><th>成员</th><th>角色</th><th>状态</th><th>最近登录</th><th>操作</th></tr></thead><tbody>
{users.map((user) => {
const self = user.id === identity?.id
return <tr key={user.id}>
<td><strong>{user.display_name || user.username}</strong><small>{user.username}{user.must_change_password ? ' · 待设置新密码' : ''}</small></td>
<td>{self ? <span>{memberRoleLabels[user.role]}</span> : (
<select value={user.role} disabled={busy === user.id} aria-label={`${user.username} 角色`} onChange={(event) => void run(user.id, () => setManagedUserRole(user.id, event.target.value as ManagedUser['role']), '角色已更新,该成员需要重新登录')}>
<option value="viewer">观察者</option><option value="engineer">知识工程师</option><option value="admin">管理员</option>
</select>
)}</td>
<td><span className={`status status-${user.state === 'active' ? 'completed' : 'failed'}`}>{user.state === 'active' ? '启用' : '已停用'}</span></td>
<td>{user.last_login_at ? new Date(user.last_login_at).toLocaleString('zh-CN', { hour12: false }) : '从未登录'}</td>
<td><div className="row-actions">
{!self ? <button type="button" className="secondary-action" disabled={busy === user.id} onClick={() => {
const temporary = window.prompt(`为 ${user.username} 生成一个临时密码(至少 8 位,对方首次登录必须更换)`)
if (temporary) void run(user.id, () => resetManagedUserPassword(user.id, temporary), `${user.username} 的临时密码已生效`)
}}>重置密码</button> : null}
{!self ? <button type="button" className={user.state === 'active' ? 'danger' : 'secondary-action'} disabled={busy === user.id} onClick={() => void run(user.id, () => setManagedUserState(user.id, user.state === 'active' ? 'disabled' : 'active'), user.state === 'active' ? '账号已停用,其在线会话立即失效' : '账号已重新启用')}>
{user.state === 'active' ? '停用' : '启用'}
</button> : <small>当前登录人</small>}
</div></td>
</tr>
})}
</tbody></table></div>
<div className="member-create-form" aria-label="新增成员">
<label>用户名<input value={form.username} maxLength={64} placeholder="小写字母/数字,如 zhangsan" onChange={(event) => setForm((current) => ({ ...current, username: event.target.value.toLowerCase() }))} /></label>
<label>姓名<input value={form.display_name} maxLength={128} onChange={(event) => setForm((current) => ({ ...current, display_name: event.target.value }))} /></label>
<label>角色<select value={form.role} onChange={(event) => setForm((current) => ({ ...current, role: event.target.value as ManagedUser['role'] }))}><option value="viewer">观察者</option><option value="engineer">知识工程师</option><option value="admin">管理员</option></select></label>
<label>初始密码(≥8 位,首登强制修改)<input type="password" value={form.password} onChange={(event) => setForm((current) => ({ ...current, password: event.target.value }))} /></label>
<button type="button" disabled={!formValid || busy === 'create'} onClick={() => void create()}>新增成员</button>
</div>
<small>停用不会删除任何业务记录,只禁止登录并立即撤销其在线会话。</small>
</section>
}
+2 -1
View File
@@ -5,7 +5,8 @@ import { ScopeRuleEditor } from './ScopeRuleEditor'
describe('ScopeRuleEditor',()=>{
it('explains directory inheritance and keeps production publication separate',()=>{
const html=renderToStaticMarkup(<ScopeRuleEditor target={{target_type:'directory',connection_id:'conn-1',directory_path:'产品',source_item_id:''}} currentRule={{target_type:'directory',connection_id:'conn-1',directory_path:'产品',visibility:'internal',updated_by:'engineer',reason:'内部资料',updated_at:'2026-09-08T00:00:00Z'}} saving={false} onSave={vi.fn()} onClear={vi.fn()} />)
for(const text of ['此目录及子目录','当前设置:对内','人工:engineer','移除本级设置,恢复继承','不会自动发布到生产']) expect(html).toContain(text)
for(const text of ['此目录及子目录','当前设置:对内','由 engineer 设置','移除本级设置,恢复继承','不会自动发布到生产']) expect(html).toContain(text)
expect(html).not.toContain('操作人<input')
})
it('shows an honest inherited state when no direct rule exists',()=>{
const html=renderToStaticMarkup(<ScopeRuleEditor target={{target_type:'directory',connection_id:'conn-1',directory_path:'',source_item_id:''}} saving={false} onSave={vi.fn()} onClear={vi.fn()} />)
+6 -8
View File
@@ -12,22 +12,20 @@ interface Props {
export function ScopeRuleEditor({target,currentRule,saving,error,onSave,onClear}:Props){
const [visibility,setVisibility]=useState<Visibility|''>(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 <section className="scope-editor" aria-label="对内对外范围设置">
<div className="scope-editor-heading"><div><strong>对内/对外设置</strong><span>{label}</span></div>{currentRule?<span className={`scope-badge ${currentRule.visibility}`}>当前设置:{currentRule.visibility==='external'?'对外':'对内'}</span>:<span className="inherited-badge">当前没有本级设置</span>}</div>
{currentRule?<p className="scope-rule-meta">人工:{currentRule.updated_by} · 原因:{currentRule.reason}</p>:<p className="scope-rule-meta">当前继承上级规则或来源原始标记。</p>}
{currentRule?<p className="scope-rule-meta">由 {currentRule.updated_by} 设置 · 原因:{currentRule.reason}</p>:<p className="scope-rule-meta">当前继承上级规则或来源原始标记。</p>}
<div className="scope-editor-fields">
<label>拟修改为<select value={visibility} onChange={event=>setVisibility(event.target.value as Visibility|'')}><option value="">选择新范围</option><option value="internal">对内</option><option value="external">对外</option></select></label>
<label>操作人<input value={operator} maxLength={128} placeholder="姓名或工号" onChange={event=>setOperator(event.target.value)} /></label>
<label className="scope-reason">判断原因<input value={reason} maxLength={500} placeholder="例如:官网已公开 / 含内部参数" onChange={event=>setReason(event.target.value)} /></label>
</div>
{error?<p className="scope-error" role="alert">{error}</p>:null}
<div className="scope-editor-actions"><button disabled={!saveReady} onClick={()=>onSave({...base,visibility:visibility as Visibility})}>{saving?'保存中…':'保存范围'}</button>{currentRule?<button className="secondary" disabled={!identityReady} onClick={()=>onClear(base)}>移除本级设置,恢复继承</button>:null}</div>
<small>这里只更新治理规则并记录审计,不会修改源文件,也不会自动发布到生产。</small>
<div className="scope-editor-actions"><button disabled={!saveReady} onClick={()=>onSave({...base,visibility:visibility as Visibility})}>{saving?'保存中…':'保存范围'}</button>{currentRule?<button className="secondary" disabled={!reasonReady} onClick={()=>onClear(base)}>移除本级设置,恢复继承</button>:null}</div>
<small>这里只更新治理规则并记录审计,操作自动记在当前登录人名下;不会修改源文件,也不会自动发布到生产。</small>
</section>
}
+1 -1
View File
@@ -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<boolean>=>{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<boolean>=>{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 <SourceCatalogBrowserView sources={sources} selectedSource={selected} page={page} loading={loading} error={error} routingCapabilities={routingCapabilities} routingMessage={routingMessage} routingLoading={routingLoading} refreshJob={refreshJob} onSelectSource={source=>{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)} />
}
+13 -12
View File
@@ -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<string, string> = { dingtalk: '钉钉知识库', pp: 'PP 资料下载中心', alist: 'AList 文件源', manual: '本地手工导入' }
const sourceAuthLabels: Record<string, string> = { 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<number>(() => {
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 <article className="settings-source-row">
<div className="settings-source-name"><strong>{connection.name}</strong><span>{sourceTypeLabels[connection.source_type] ?? connection.source_type}{connection.enabled ? '' : ' · 已停用'}</span></div>
@@ -111,7 +112,6 @@ function SourceSettingsCard({ connection, onSourcesChanged }: { connection: Sour
<div className="source-schedule-form">
{scheduled ? <label>自动刷新周期<select value={interval} onChange={(event) => setInterval(Number(event.target.value))}>{intervalChoices.map((choice) => <option key={choice.value} value={choice.value}>{choice.label}</option>)}</select></label>
: <small className="manual-source-note">本地手工导入来源不支持定时刷新,只能手动触发扫描。</small>}
<label className="settings-operator">操作人(必填)<input value={operator} onChange={(event) => setOperator(event.target.value)} placeholder="姓名或工号" maxLength={128}/></label>
{connection.enabled
? <div className="source-schedule-actions"><button className="secondary" disabled={!canApply || (scheduled && interval === 0 && !connection.schedule_configured)} onClick={() => void submit(true)}>{busy ? '正在验证并启用…' : '保存并启用调度'}</button>
<button className="danger" disabled={!canApply} onClick={() => setPendingDisable(true)}>停用来源</button></div>
@@ -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<SectionKey>(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 <main className="page-shell system-settings">
<header className="hero compact"><div><h1>系统设置</h1><p className="subtitle">查看内容源、服务与备份状态;来源调度与刷新参数采用版本化保存。</p></div><button onClick={onRefresh} disabled={loading}>{loading ? '刷新中…' : '刷新状态'}</button></header>
{error ? <div className="error-banner" role="alert">{error}</div> : null}
{monitor && settings ? <div className="settings-layout">
<nav className="settings-nav" aria-label="系统设置分区">{sections.map((item) => <button key={item.key} className={section === item.key ? 'active' : ''} onClick={() => setSection(item.key)}>{item.label}</button>)}</nav>
<nav className="settings-nav" aria-label="系统设置分区">{sections.filter((item) => !item.adminOnly || identity?.role === 'admin').map((item) => <button key={item.key} className={section === item.key ? 'active' : ''} onClick={() => setSection(item.key)}>{item.label}</button>)}</nav>
<div className="settings-content">
<div className="settings-role-strip"><span className="engineer-role">文档工程师可调整:来源调度周期、刷新间隔、停滞判断</span><span className="admin-role">管理员设置已锁定:端点、凭据、映射、生产开关</span></div>
<div className="simulation-banner server-settings-banner"><strong>设置服务已启用</strong><span>当前活动版本 · 启用人 {settings.updated_by} · 启用时间 {settings.activated_at ? new Date(settings.activated_at).toLocaleString('zh-CN') : '待激活'};新设置先验证,再原子切换。</span></div>
@@ -174,6 +175,7 @@ export function SystemSettingsView({ sources, connections, monitor, settings, pr
<div className="settings-section-heading"><div><h2>存储与备份</h2><p>文件资源与生产发布前快照使用独立受限配置。</p></div></div>
<div className="storage-settings-grid"><dl><dt>Endpoint / Bucket</dt><dd>尚未配置</dd><dt>AccessKey / Secret</dt><dd>仅保存凭据引用,不可回读</dd><dt>CDN / 公开访问域名</dt><dd>尚未配置</dd><dt>临时签名有效期</dt><dd>待配置</dd></dl><dl><dt>测试备份前缀</dt><dd>/backup/weknora/test/</dd><dt>生产备份前缀</dt><dd>/backup/weknora/prod/</dd><dt>快照保留</dt><dd>最近 30 个生产快照</dd><dt>恢复验证</dt><dd>由生产门禁读回</dd></dl><ul className="target-list"><li>PostgreSQL <b>未配置</b></li><li>Elasticsearch <b>未配置</b></li><li>对象存储 <b>未配置</b></li><li>Neo4j <b>未配置</b></li><li>生产发布请求 <b>{productionEnabled ? '等待管理员核对' : '关闭'}</b></li><li>Release Worker <b>网页不可启用</b></li></ul></div>
</section> : null}
{section === 'members' && identity?.role === 'admin' ? <MembersSection /> : null}
{section === 'refresh' ? <section className="settings-panel wide" id="settings-refresh">
<div className="settings-section-heading"><div><h2>刷新策略</h2><p>这些值保存在服务器活动版本中;保存不会修改端点、凭据或生产开关。</p></div><span className="safe-badge">当前活动版本</span></div>
<div className="safe-setting-grid">
@@ -182,8 +184,7 @@ export function SystemSettingsView({ sources, connections, monitor, settings, pr
<label>解析停滞判定<select value={stalled} onChange={(event) => { setStalled(Number(event.target.value) as 1800 | 3600); setDirty(true) }}><option value={1800}>30分钟</option><option value={3600}>1小时</option></select></label>
<label>finalizing 告警<select value={finalizing} onChange={(event) => { setFinalizing(Number(event.target.value) as 7200 | 14400); setDirty(true) }}><option value={7200}>2小时</option><option value={14400}>4小时</option></select></label>
</div>
<label className="settings-operator">操作人(必填)<input value={operator} onChange={(event) => setOperator(event.target.value)} placeholder="姓名或工号" maxLength={128}/></label>
<button onClick={() => { setDirty(false); onSave({ document_refresh_seconds: documentRefresh, resource_refresh_seconds: resourceRefresh, stalled_after_seconds: stalled, finalizing_after_seconds: finalizing, updated_by: operator.trim() }) }} disabled={!canSave}>{saving ? '正在验证并应用…' : '保存并应用刷新与告警参数'}</button>
<button onClick={() => { setDirty(false); onSave({ document_refresh_seconds: documentRefresh, resource_refresh_seconds: resourceRefresh, stalled_after_seconds: stalled, finalizing_after_seconds: finalizing }) }} disabled={!canSave}>{saving ? '正在验证并应用…' : '保存并应用刷新与告警参数'}</button>
{visibleSaveMessage(saveMessage, dirty) ? <p className="success-message" role="status">{saveMessage}</p> : null}
<small>当前:文档 {secondsLabel(settings.document_refresh_seconds)}、资源 {secondsLabel(settings.resource_refresh_seconds)}、停滞 {secondsLabel(settings.stalled_after_seconds)}、finalizing {secondsLabel(settings.finalizing_after_seconds)}。</small>
</section> : null}
+4 -4
View File
@@ -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(<WeKnoraMonitorView {...baseProps} lane='changes' changeSets={changeSets} confirmingSetID='cs-1' confirmMessage='已提交:确认 2 项;新建上传任务 2 个' onConfirmChangeSet={vi.fn()} />)
expect(html).toContain('预览并选择变更文件')
expect(html).toContain('aria-label="选择旧手册.pdf"')
expect(html).toContain('确认处理(0)')
expect(html).toContain('aria-label="确认操作人"')
expect(html).not.toContain('操作人<input')
expect(html).toContain('已提交:确认 2 项;新建上传任务 2 个')
})
it('hides confirmation controls after the change set leaves planned state',()=>{
@@ -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(<WeKnoraMonitorView {...baseProps} lane='changes' />)
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('操作人<input')
const attention=renderToStaticMarkup(<WeKnoraMonitorView {...baseProps} lane='attention' />)
for(const text of ['需要你出手','CR20A.pdf','tp-failed'.slice(0,0)+'remote_parse_failed','失败阶段 文档解析','批量重试所选(1)','死信(尝试耗尽,不可自动重试)','下载 ✓','文档解析 ✗','建议先在 WeKnora 手动解析该文件确认格式'])expect(attention).toContain(text)
const inflight=renderToStaticMarkup(<WeKnoraMonitorView {...baseProps} lane='inflight' />)
+19 -25
View File
@@ -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<number[]>([])
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 <article><div><strong>{changeSet.source_name}</strong><small>{new Date(changeSet.created_at).toLocaleString('zh-CN',{hour12:false})}</small>{changeSet.state!=='planned'?<span className="scope-badge internal">已确认</span>:null}</div><div className="persisted-change-counts"><span>新增 {changeSet.add_count}</span><span>更新 {changeSet.update_count}</span><span>移动 {changeSet.move_count}</span><span>范围变化 {changeSet.move_scope_count}</span><span>删除 {changeSet.delete_count}</span><span>未变化 {changeSet.no_change_count}</span></div>{actionable.length?<details open={open} onToggle={event=>setOpen((event.target as HTMLDetailsElement).open)}><summary>预览并选择变更文件</summary><div className="changeset-selection">{actionable.map(item=><label key={item.seq} className="changeset-choice"><input type="checkbox" aria-label={`选择${item.title}`} disabled={!confirmable} checked={selected.includes(item.seq)} onChange={()=>toggle(item.seq)} /><b>{item.action==='add'?'新增':item.action==='update'?'更新':item.action==='move'?'移动(改名)':item.action==='move_scope'?'范围变化':'删除'}</b><span>{item.title}</span><small>{item.new_path||item.old_path}</small>{item.action==='delete'&&item.reason_code==='source_missing'?<small>来源缺失</small>:null}</label>)}</div>{confirmable?<div className="changeset-confirm"><label>操作人<input aria-label="确认操作人" placeholder="姓名或工号" value={operator} onChange={event=>setOperator(event.target.value)} /></label><button disabled={confirming||selected.length===0||!operator.trim()} onClick={()=>onConfirm?.(changeSet.id,[...selected].sort((a,b)=>a-b),operator.trim(),'人工确认快照差异执行')}>确认处理({selected.length})</button></div>:null}{message?<p role="status">{message}</p>:null}</details>:null}</article>
return <article><div><strong>{changeSet.source_name}</strong><small>{new Date(changeSet.created_at).toLocaleString('zh-CN',{hour12:false})}</small>{changeSet.state!=='planned'?<span className="scope-badge internal">已确认</span>:null}</div><div className="persisted-change-counts"><span>新增 {changeSet.add_count}</span><span>更新 {changeSet.update_count}</span><span>移动 {changeSet.move_count}</span><span>范围变化 {changeSet.move_scope_count}</span><span>删除 {changeSet.delete_count}</span><span>未变化 {changeSet.no_change_count}</span></div>{actionable.length?<details open={open} onToggle={event=>setOpen((event.target as HTMLDetailsElement).open)}><summary>预览并选择变更文件</summary><div className="changeset-selection">{actionable.map(item=><label key={item.seq} className="changeset-choice"><input type="checkbox" aria-label={`选择${item.title}`} disabled={!confirmable} checked={selected.includes(item.seq)} onChange={()=>toggle(item.seq)} /><b>{item.action==='add'?'新增':item.action==='update'?'更新':item.action==='move'?'移动(改名)':item.action==='move_scope'?'范围变化':'删除'}</b><span>{item.title}</span><small>{item.new_path||item.old_path}</small>{item.action==='delete'&&item.reason_code==='source_missing'?<small>来源缺失</small>:null}</label>)}</div>{confirmable?<div className="changeset-confirm"><button disabled={confirming||selected.length===0} onClick={()=>onConfirm?.(changeSet.id,[...selected].sort((a,b)=>a-b),'人工确认快照差异执行')}>确认处理({selected.length})</button></div>:null}{message?<p role="status">{message}</p>:null}</details>:null}</article>
}
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<string[]>([])
const [startReason, setStartReason] = useState('已核对来源快照与测试知识库差异')
const [selectedRetryIDs, setSelectedRetryIDs] = useState<string[]>([])
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({
<div className="task-chain" aria-label={`处理链${item.title}`}>{chainSteps(item).map((step) => <span key={step.stage} className={`chain-step ${step.state}`}>{step.stage}{step.state === 'done' ? ' ✓' : step.state === 'bad' ? ' ✗' : step.state === 'active' ? ` 中 ${duration(secondsSince(item.updated_at))}` : ''}</span>)}</div>
<div className={item.processing_state === 'failed' || item.processing_state === 'stalled' ? 'errline' : 'tiny muted-line'}>{item.processing_state === 'failed' || item.processing_state === 'stalled' ? adviceFor(failureStage(item), item.last_error) : item.can_start ? '确认后将创建解析任务' : '无需操作,等待自动处理'}{item.change_set_id ? <> · 来源变更集 <code>{item.change_set_id}</code></> : null} · <code>{item.id}</code></div>
</div>
<div className="inbox-task-actions">{item.can_start ? <button className="primary" disabled={starting || !startOperator.trim() || !startReason.trim()} onClick={() => onStart([item.id], startOperator.trim(), startReason.trim())}>确认并解析</button> : null}{item.can_retry ? <button className="primary" disabled={retryingIDs.includes(item.id)} onClick={() => onRetry(item.id)}>{retryingIDs.includes(item.id) ? '重试中…' : '重试'}</button> : null}</div>
<div className="inbox-task-actions">{item.can_start ? <button className="primary" disabled={starting || !startReason.trim()} onClick={() => onStart([item.id], startReason.trim())}>确认并解析</button> : null}{item.can_retry ? <button className="primary" disabled={retryingIDs.includes(item.id)} onClick={() => onRetry(item.id)}>{retryingIDs.includes(item.id) ? '重试中…' : '重试'}</button> : null}</div>
</article>
const emptyLane = (text: string) => <div className="empty-state">{text}</div>
return <main className="page-shell weknora-monitor inbox-layout">
@@ -183,19 +180,18 @@ export function WeKnoraMonitorView({
</nav>
<div className="inbox-work">
{lane === 'attention' ? <section className="inbox-section" aria-label="需人工处理">
<div className="section-head"><h2>需要你出手({attentionItems.length})</h2><span className="spacer" /><span className="tiny">操作人</span><input className="operator-input" aria-label="批量重试操作人" placeholder="姓名或工号" value={retryOperator} onChange={(event) => setRetryOperator(event.target.value)} /><button className="danger" disabled={!batchTargets.length || retryingIDs.length > 0} onClick={() => onBatchRetry(batchTargets, retryOperator)}>{retryingIDs.length ? '重试中…' : `批量重试所选(${batchTargets.length})`}</button></div>
<div className="section-head"><h2>需要你出手({attentionItems.length})</h2><span className="spacer" /><button className="danger" disabled={!batchTargets.length || retryingIDs.length > 0} onClick={() => onBatchRetry(batchTargets)}>{retryingIDs.length ? '重试中…' : `批量重试所选(${batchTargets.length})`}</button></div>
{batchMessage ? <p className="queue-batch-message" role="status">{batchMessage}</p> : null}
{attentionItems.length ? attentionItems.map(actionTask) : emptyLane('没有失败或停滞的任务。')}
<div className="section-head sub"><h3>死信(尝试耗尽,不可自动重试)</h3><span className="tiny">原始任务与审计行保留不动;重新入队会创建新尝试</span></div>
{failures.length ? <ul className="dlq-list">{failures.map((failure) => <li key={failure.id}><span className="monitor-status failed">{failure.error_code}</span><b>{failure.job_type === 'test.upload' ? '上传解析' : failure.job_type}</b>{failure.publication_id ? <code>{failure.publication_id}</code> : null}<small>{failure.attempt}/{failure.max_attempts_at_failure} 次 · {new Date(failure.created_at).toLocaleString('zh-CN', { hour12: false })}</small>{failure.publication_id ? <button disabled={retryingIDs.includes(failure.publication_id) || !retryOperator.trim()} onClick={() => onBatchRetry([failure.publication_id as string], retryOperator)}>重新入队</button> : null}</li>)}</ul> : emptyLane('当前没有等待处理的死信记录。')}
{failures.length ? <ul className="dlq-list">{failures.map((failure) => <li key={failure.id}><span className="monitor-status failed">{failure.error_code}</span><b>{failure.job_type === 'test.upload' ? '上传解析' : failure.job_type}</b>{failure.publication_id ? <code>{failure.publication_id}</code> : null}<small>{failure.attempt}/{failure.max_attempts_at_failure} 次 · {new Date(failure.created_at).toLocaleString('zh-CN', { hour12: false })}</small>{failure.publication_id ? <button disabled={retryingIDs.includes(failure.publication_id)} onClick={() => onBatchRetry([failure.publication_id as string])}>重新入队</button> : null}</li>)}</ul> : emptyLane('当前没有等待处理的死信记录。')}
</section> : null}
{lane === 'changes' ? <section className="inbox-section" aria-label="等待确认的差异">
<div className="section-head"><h2>持久快照差异 · 等待确认({changeSets.filter((set) => set.state === 'planned').length} 个来源)</h2><span className="tiny">刷新来源 ≠ 马上导入知识库;勾选变更项并确认后才创建解析任务</span></div>
{changeSets.length ? <div className="persisted-change-grid">{changeSets.map(changeSet => <ChangeSetCard key={changeSet.id} changeSet={changeSet} confirming={confirmingSetID === changeSet.id} message={confirmingSetID === changeSet.id ? confirmMessage : ''} onConfirm={onConfirmChangeSet} />)}</div> : emptyLane('当前没有持久快照差异。')}
<div className="difference-confirmation">
<label>操作人<input value={startOperator} onChange={(event) => setStartOperator(event.target.value)} placeholder="姓名或工号" /></label>
<label>确认原因<input value={startReason} onChange={(event) => setStartReason(event.target.value)} /></label>
<button disabled={starting || !pendingPlans.length || !startOperator.trim() || !startReason.trim()} onClick={() => onStart(pendingPlans.map((item) => item.id), startOperator.trim(), startReason.trim())}>{starting ? '正在生成任务…' : `开始处理(${pendingPlans.length})`}</button>
<label>确认原因<input value={startReason} onChange={(event) => setStartReason(event.target.value)} /></label>
<button disabled={starting || !pendingPlans.length || !startReason.trim()} onClick={() => onStart(pendingPlans.map((item) => item.id), startReason.trim())}>{starting ? '正在生成任务…' : `开始处理(${pendingPlans.length})`}</button>
</div>
<p className="tiny">待确认 {pendingPlans.length} · 新增 {addedPlans} · 更新 {updatedPlans}</p>
{startMessage ? <p className="difference-message" role="status">{startMessage}</p> : 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 <WeKnoraMonitorView overview={overview} files={files} queue={queue} plans={plans} changeSets={changeSets} confirmingSetID={confirmingSetID ?? lastConfirmSetID} confirmMessage={confirmMessage} onConfirmChangeSet={(id,seqs,operator,reason)=>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 <WeKnoraMonitorView overview={overview} files={files} queue={queue} plans={plans} changeSets={changeSets} confirmingSetID={confirmingSetID ?? lastConfirmSetID} confirmMessage={confirmMessage} onConfirmChangeSet={(id,seqs,reason)=>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) }} />
}
+219
View File
@@ -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<AuthRole, string> = { viewer: '观察者', engineer: '知识工程师', admin: '管理员' }
interface AuthContextValue {
identity: AuthIdentity | null
ready: boolean
login: (username: string, password: string) => Promise<string | null>
logout: () => Promise<void>
changePassword: (currentPassword: string, newPassword: string) => Promise<string | null>
signedOut: number
notifySignedOut: () => void
}
const AuthContext = createContext<AuthContextValue | null>(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<string> {
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<AuthIdentity | null>(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<AuthContextValue>(
() => ({ identity, ready, login, logout, changePassword, signedOut, notifySignedOut: bumpSignedOut }),
[identity, ready, login, logout, changePassword, signedOut, bumpSignedOut])
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>
}
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 (
<div className="login-shell">
<form className="login-card" onSubmit={submit} aria-label="登录">
<h1>知识治理平台</h1>
<p className="login-subtitle">登录后所有操作将记录到你名下</p>
<label>用户名<input value={username} autoFocus autoComplete="username" onChange={(event) => setUsername(event.target.value)} /></label>
<label>密码<input type="password" value={password} autoComplete="current-password" onChange={(event) => setPassword(event.target.value)} /></label>
{error ? <p className="login-error" role="alert">{error}</p> : null}
<button type="submit" disabled={busy || !username || !password}>{busy ? '登录中…' : '登录'}</button>
</form>
</div>
)
}
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 (
<div className="login-shell">
<form className="login-card" onSubmit={submit} aria-label="设置新密码">
<h1>首次登录需要设置新密码</h1>
<p className="login-subtitle">账号 {identity?.username} 的初始密码只能完成这一次登录</p>
<label>当前密码<input type="password" value={current} autoFocus autoComplete="current-password" onChange={(event) => setCurrent(event.target.value)} /></label>
<label>新密码(至少 8 位)<input type="password" value={next} autoComplete="new-password" onChange={(event) => setNext(event.target.value)} /></label>
<label>确认新密码<input type="password" value={confirm} autoComplete="new-password" onChange={(event) => setConfirm(event.target.value)} /></label>
{error ? <p className="login-error" role="alert">{error}</p> : null}
<button type="submit" disabled={busy}>{busy ? '保存中…' : '保存并进入'}</button>
<button type="button" className="login-secondary" onClick={() => void logout()}>退出</button>
</form>
</div>
)
}
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 (
<div className="topbar-user" data-testid="topbar-user">
<button type="button" className="topbar-user-button" aria-haspopup="menu" aria-expanded={menuOpen} onClick={() => setMenuOpen((value) => !value)}>
<span className="topbar-user-avatar" aria-hidden="true">{name.slice(0, 1)}</span>
<span className="topbar-user-name">{name}</span>
<span className={`role-badge role-${identity.role}`}>{roleLabels[identity.role]}</span>
</button>
{menuOpen ? (
<div className="topbar-user-menu" role="menu" onMouseLeave={() => setMenuOpen(false)}>
<button type="button" role="menuitem" onClick={() => { setMenuOpen(false); void logout() }}>退出登录</button>
</div>
) : null}
</div>
)
}
+41
View File
@@ -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()
})
})
+14 -1
View File
@@ -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 <div className="login-shell"><p className="login-subtitle">正在检查登录状态…</p></div>
}
if (!identity) return <LoginScreen />
if (identity.must_change_password) return <MustChangePasswordScreen />
return <App />
}
createRoot(root).render(
<StrictMode>
<App />
<AuthProvider>
<Gate />
</AuthProvider>
</StrictMode>,
)
+70
View File
@@ -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<string, unknown> => 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<unknown> {
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<ManagedUser[]> {
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<ManagedUser> {
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<ManagedUser> {
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<ManagedUser> {
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<void> {
await call(`/api/v1/users/${encodeURIComponent(userID)}/reset-password`, { method: 'POST', body: JSON.stringify({ temporary_password: temporaryPassword }) }, '重置密码失败')
}
+10 -8
View File
@@ -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 }))
+10 -10
View File
@@ -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<PublicationReview> {
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, 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<ReleaseBatch> {
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<ReleaseBatch> {
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<ReleaseChangeSet> {
return parseChangeSetEnvelope(await sendJSON('/api/v1/release-change-sets', { name, created_by: createdBy }, '生成发布计划集失败'))
export async function generateReleaseChangeSet(name: string): Promise<ReleaseChangeSet> {
return parseChangeSetEnvelope(await sendJSON('/api/v1/release-change-sets', { name }, '生成发布计划集失败'))
}
export async function confirmReleaseChangeSet(changeSetID: string, confirmedBy: string): Promise<ReleaseChangeSet> {
return parseChangeSetEnvelope(await sendJSON(`/api/v1/release-change-sets/${encodeURIComponent(changeSetID)}/confirm`, { confirmed_by: confirmedBy }, '确认发布计划集失败'))
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> {
@@ -361,8 +361,8 @@ export async function fetchLatestReleaseChangeSet(signal?: AbortSignal): Promise
return { ...base, items }
}
export async function sealReleaseBatch(batchID: string, sealedBy: string): Promise<ReleaseBatch> {
return parseBatchEnvelope(await sendJSON(`/api/v1/release-batches/${encodeURIComponent(batchID)}/seal`, { sealed_by: sealedBy }, '封批失败'))
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> {
+3 -3
View File
@@ -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')
})
-2
View File
@@ -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
}
+2 -2
View File
@@ -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()=>{
+3 -3
View File
@@ -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<CatalogRoutingCapabilities>{
+2 -2
View File
@@ -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 }
-1
View File
@@ -310,7 +310,6 @@ export interface SourceSettingsDraftRequest {
credential_ref: string
enabled: boolean
schedule: { refresh_interval_seconds?: number | null }
operator: string
}
const revisionStates = new Set<SourceSettingsRevisionState>(['validated', 'active', 'retired', 'failed'])
+64
View File
@@ -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); }
+5 -5
View File
@@ -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()
})
})
+4 -4
View File
@@ -118,11 +118,11 @@ export async function retryPublication(publicationId: string): Promise<void> {
}
}
export async function startTestPublications(publicationIds: string[], operatorRef: string, reason: string): Promise<StartTestPublicationsResult> {
export async function startTestPublications(publicationIds: string[], reason: string): Promise<StartTestPublicationsResult> {
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<RetryPublicationsBatchResult> {
export async function retryPublicationsBatch(publicationIds: string[], reason: string): Promise<RetryPublicationsBatchResult> {
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
+2 -2
View File
@@ -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()
-1
View File
@@ -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<UISettings, 'document_refresh_seconds' | 'resource_refresh_seconds'>) {