import { ManagementSections } from './ManagementSections'; import { configurationDateTime } from './configurationName'; import { alertObject, alertsForStatus, monitorLabel } from './taskMonitorModel'; import { useEffect, useRef, useState } from 'react'; import { Alert, App, Button, Checkbox, Drawer, Empty, Form, Input, InputNumber, Modal, Select, Spin, Switch, Tabs, Tag } from 'antd'; import type { ColumnsType } from 'antd/es/table'; import { QualityTable as Table } from './QualityTable'; import { DownloadOutlined, ReloadOutlined } from '@ant-design/icons'; import { ApiError, api, collectionItems } from './api'; import type { AuthUser, SourceItem } from './types'; import { readableSelectPopup } from './readableSelectPopup'; import { isInternalDataField } from './publicDataDisplay'; import './completion.css'; type Row = Record; const TABLE_PAGE_SIZE = 15; const INTERNAL_REVISION_FIELDS = new Set(['sourcerevisionid', 'targetrevisionid', 'expectedrevisionid', 'currentrevisionid', 'candidaterevisionid', 'baserevisionid']); const obj = (value: unknown): Row => value && typeof value === 'object' && !Array.isArray(value) ? value as Row : {}; const rows = (value: unknown): Row[] => Array.isArray(value) ? value.filter(item => item && typeof item === 'object') as Row[] : []; const text = (value: unknown, empty = '—') => value === null || value === undefined || value === '' ? empty : typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' ? String(value) : empty; const withoutSystemMetadata = (value: unknown): unknown => { if (Array.isArray(value)) return value.map(withoutSystemMetadata); if (!value || typeof value !== 'object') return value; return Object.fromEntries(Object.entries(value as Row) .filter(([key]) => !isInternalDataField(key) && !INTERNAL_REVISION_FIELDS.has(key.replace(/[^a-z0-9]/gi, '').toLowerCase())) .map(([key, child]) => [key, withoutSystemMetadata(child)])); }; const drilldownStatusText = (value: unknown) => ({ DISABLED: '未启用', NOT_NEEDED: '本次无发现项', PENDING: '等待调度', QUEUED: '排队中', RUNNING: '分析中', COMPLETED: '已完成', FAILED: '失败', CANCELLED: '已取消', BLOCKED_AUTHORIZATION: '权限不足', } as Record)[String(value)] || text(value, '未返回'); function showDownload(data: { blob: Blob; filename: string }) { const url = URL.createObjectURL(data.blob); const anchor = document.createElement('a'); anchor.href = url; anchor.download = data.filename; document.body.appendChild(anchor); anchor.click(); anchor.remove(); window.setTimeout(() => URL.revokeObjectURL(url), 1000); } function ErrorPanel({ title, error, onRetry }: { title: string; error: string; onRetry: () => void }) { return error ? 重试} /> : null; } const INSPECTION_DEFAULTS: Row = { rateDropEnabled: true, rateDropPp: 1, defectTopEnabled: true, minTopShare: 0.1, minStageRows: 1, quietPeriodHours: 24, productTopEnabled: true, productTopLimit: 5, productTopMinShare: 0.05, newObjectEnabled: true, newObjectMinRows: 1, sustainedWorseningEnabled: true, sustainedWorseningMonths: 3, sustainedWorseningPp: 1, targetGapEnabled: true, targetGapPp: 1, aiDrilldownEnabled: false, aiMaxFindings: 3, }; function analysisDeepLink(sessionId: string, turnId: string): string { const url = new URL(window.location.href); url.searchParams.set('page', 'analysis'); url.searchParams.set('sessionId', sessionId); url.searchParams.set('turnId', turnId); return `${url.pathname}${url.search}${url.hash}`; } function InspectionStrategyPanel({ user, onUnauthorized }: { user: AuthUser; onUnauthorized: (error: unknown) => boolean }) { const { message } = App.useApp(); const canManage = user.roles.some(role => ['SYSTEM_ADMIN', 'SYSTEM_OPERATOR'].includes(role)); const canRun = user.roles.some(role => ['QUALITY_VIEWER', 'BUSINESS_ANALYST'].includes(role)); const [strategies, setStrategies] = useState([]); const [releaseId, setReleaseId] = useState(''); const [runs, setRuns] = useState([]); const [loading, setLoading] = useState(false); const [running, setRunning] = useState(false); const [saving, setSaving] = useState(false); const [error, setError] = useState(''); const [selectedRun, setSelectedRun] = useState(null); const [editing, setEditing] = useState(null); const [form] = Form.useForm(); const load = async () => { setLoading(true); setError(''); const results = await Promise.allSettled([ canManage ? api.inspectionStrategies() : Promise.resolve({ items: [] }), api.releases(), ]); if (results[0].status === 'fulfilled') setStrategies(collectionItems(results[0].value)); else if (!onUnauthorized(results[0].reason)) setError(results[0].reason instanceof Error ? results[0].reason.message : '巡检策略读取失败'); if (results[1].status === 'fulfilled') { const current = String(results[1].value.currentReleaseId || ''); setReleaseId(current); } else if (!onUnauthorized(results[1].reason)) { const failure = results[1].reason; setError(value => [value, failure instanceof Error ? failure.message : '当前数据读取失败'].filter(Boolean).join(';')); } setLoading(false); }; const loadRuns = async (selectedRelease = releaseId) => { if (!canRun || !selectedRelease) { setRuns([]); return; } setRuns([]); try { const result = await api.inspectionRuns(selectedRelease); setRuns(collectionItems(result)); } catch (value) { if (!onUnauthorized(value)) setError(value instanceof Error ? value.message : '巡检运行记录读取失败'); } }; useEffect(() => { void load(); }, []); useEffect(() => { if (releaseId) void loadRuns(releaseId); }, [releaseId]); const openEditor = async (row?: Row) => { if (!canManage) return; setSaving(true); try { const source = row?.id ? await api.inspectionStrategy(String(row.id)) : {}; const strategy = obj(source); setEditing(row ? { ...row, ...strategy } : {}); const config = { ...INSPECTION_DEFAULTS, ...obj(strategy.config || row?.config) }; form.setFieldsValue({ name: String(strategy.name || row?.name || ''), active: strategy.active === true || row?.active === true, ...config }); } catch (value) { if (!onUnauthorized(value)) message.error(value instanceof Error ? value.message : '巡检策略详情读取失败'); } finally { setSaving(false); } }; const save = async () => { try { const value = await form.validateFields(); const config = Object.fromEntries(Object.keys(INSPECTION_DEFAULTS).map(key => [key, value[key]])); setSaving(true); const body = { name: String(value.name).trim(), active: value.active === true, config, ...(editing?.id ? { expectedRowVersion: Number(editing.rowVersion || 0) } : {}) }; if (editing?.id) await api.updateInspectionStrategy(String(editing.id), body); else await api.createInspectionStrategy(body); message.success('巡检策略已保存'); setEditing(null); form.resetFields(); await load(); } catch (value) { if (value && typeof value === 'object' && 'errorFields' in value) return; if (!onUnauthorized(value)) message.error(value instanceof ApiError && value.status === 409 ? '巡检策略已被更新,请重新读取。' : value instanceof Error ? value.message : '巡检策略保存失败'); } finally { setSaving(false); } }; const run = async () => { if (!canRun || !releaseId) return; setRunning(true); setError(''); try { const result = await api.runInspection(releaseId); setRuns(collectionItems(result)); if (result.resultAvailable === false) message.warning('巡检已执行;当前授权不包含完整结果字段。'); else message.success('巡检已执行,运行记录已刷新。'); } catch (value) { if (!onUnauthorized(value)) setError(value instanceof Error ? value.message : '巡检执行失败'); } finally { setRunning(false); } }; const strategyColumns: ColumnsType = [ { title: '策略名称', dataIndex: 'name', key: 'name', fixed: 'left', width: 220 }, { title: '状态', dataIndex: 'active', key: 'active', width: 100, render: value => {value === true ? '启用' : '停用'} }, { title: '阈值配置', key: 'config', width: 620, render: (_, row) => { const config = obj(row.config); return `率降 ${config.rateDropEnabled === true ? `${text(config.rateDropPp)} pp` : '关闭'} · 缺陷 TOP ${config.defectTopEnabled === true ? `${text(config.minTopShare)} 占比` : '关闭'} · 产品 TOP ${config.productTopEnabled === true ? `${text(config.productTopLimit)} 项 / ${text(config.productTopMinShare)} 占比` : '关闭'} · 新对象 ${config.newObjectEnabled === true ? `${text(config.newObjectMinRows)} 行` : '关闭'} · 连续恶化 ${config.sustainedWorseningEnabled === true ? `${text(config.sustainedWorseningMonths)} 月 / ${text(config.sustainedWorseningPp)} pp` : '关闭'} · 目标差距 ${config.targetGapEnabled === true ? `${text(config.targetGapPp)} pp` : '关闭'} · AI 下钻 ${config.aiDrilldownEnabled === true ? `启用(最多 ${text(config.aiMaxFindings)} 项)` : '关闭'}`; } }, { title: '更新时间', dataIndex: 'updatedAt', key: 'updatedAt', width: 190 }, ...(canManage ? [{ title: '操作', key: 'actions', width: 110, render: (_: unknown, row: Row) => } as ColumnsType[number]] : []), ]; const runColumns: ColumnsType = [ { title: '巡检时间', dataIndex: 'createdAt', key: 'createdAt', width: 190 }, { title: '策略', dataIndex: 'strategyName', key: 'strategyName', width: 200 }, { title: '状态', dataIndex: 'status', key: 'status', width: 125, render: value => {text(value)} }, { title: '结果状态', key: 'result', width: 300, render: (_, row) => { const result = obj(row.result); const findings = rows(result.findings); return row.result === undefined ? text(row.errorCode, '受权限限制或未返回结果') : `发现项 ${findings.length} · 确定性 ${result.deterministic === true ? '是' : result.deterministic === false ? '否' : '—'} · AI 下钻 ${drilldownStatusText(result.aiDrilldownStatus)}`; } }, { title: '操作', key: 'actions', width: 100, render: (_, row) => }, ]; const metricFields: Array<{ key: string; label: string; min: number; max: number; step?: number }> = [ { key: 'rateDropPp', label: '合格率下降阈值(百分点)', min: 0, max: 100, step: 0.1 }, { key: 'minTopShare', label: '缺陷 TOP 最低占比', min: 0, max: 1, step: 0.01 }, { key: 'minStageRows', label: '阶段最少样本行数', min: 1, max: 100000 }, { key: 'quietPeriodHours', label: '重复告警静默(小时)', min: 0, max: 8760 }, { key: 'productTopLimit', label: '产品 TOP 数量', min: 1, max: 100 }, { key: 'productTopMinShare', label: '产品 TOP 最低占比', min: 0, max: 1, step: 0.01 }, { key: 'newObjectMinRows', label: '新对象最少行数', min: 1, max: 100000 }, { key: 'sustainedWorseningMonths', label: '连续恶化月数', min: 2, max: 24 }, { key: 'sustainedWorseningPp', label: '连续恶化阈值(百分点)', min: 0, max: 100, step: 0.1 }, { key: 'targetGapPp', label: '目标差距阈值(百分点)', min: 0, max: 100, step: 0.1 }, { key: 'aiMaxFindings', label: 'AI 下钻最多发现项', min: 1, max: 3 }, ]; const booleanFields: Array<[string, string]> = [ ['rateDropEnabled', '合格率下降'], ['defectTopEnabled', '缺陷 TOP'], ['productTopEnabled', '产品 TOP'], ['newObjectEnabled', '新对象'], ['sustainedWorseningEnabled', '连续恶化'], ['targetGapEnabled', '目标差距'], ['aiDrilldownEnabled', '受控 AI 下钻'], ]; const selectedResult = obj(selectedRun?.result); const findingRows = rows(selectedResult.findings); const ruleRows = rows(selectedResult.rules).map(rule => ({ ...rule, reason: text(rule.reason, String(rule.status).toUpperCase() === 'UNAVAILABLE' ? '服务端标记为数据或适用条件不足,未返回具体原因' : '—') })); const coverage = obj(selectedResult.coverage); const missingStageRows = rows(coverage.missingStages); const sourceMonthRows = rows(coverage.sourceMonths); const drilldownRows = rows(selectedResult.aiDrilldowns); const drilldown = drilldownRows[0] || { sessionId: selectedResult.analysisSessionId, turnId: selectedResult.analysisTurnId, status: selectedResult.aiDrilldownStatus, findings: selectedResult.aiDrilldownFindings, }; const findingTypeLabel = (value: unknown) => ({ RATE_DROP: '合格率下降', SCRAP_TOP: '缺陷 TOP', PRODUCT_SCRAP_TOP: '产品 TOP', SUSTAINED_WORSENING: '连续恶化', NEW_PRODUCT_OBJECT: '新产品对象', TARGET_GAP: '目标差距' } as Record)[String(value)] || text(value); const severityLabel = (value: unknown) => ({ HIGH: '高', MEDIUM: '中', LOW: '低' } as Record)[String(value)] || text(value); const findingColumns: ColumnsType = [ { title: '发现类型', dataIndex: 'type', key: 'type', width: 170, render: findingTypeLabel }, { title: '对象 / 指标', dataIndex: 'subject', key: 'subject', width: 230 }, { title: '级别', dataIndex: 'severity', key: 'severity', width: 85, render: value => {severityLabel(value)} }, { title: '发现说明', dataIndex: 'summary', key: 'summary', width: 420 }, ]; const ruleColumns: ColumnsType = [ { title: '检查规则', dataIndex: 'id', key: 'id', width: 190 }, { title: '状态', dataIndex: 'status', key: 'status', width: 140, render: value => {String(value).toUpperCase() === 'AVAILABLE' ? '可检查' : String(value).toUpperCase() === 'UNAVAILABLE' ? '数据不足' : String(value).toUpperCase() === 'NO_FINDINGS' ? '未发现异常' : String(value).toUpperCase() === 'DISABLED' ? '已关闭' : text(value)} }, { title: '发现数', dataIndex: 'findingCount', key: 'findingCount', width: 95, align: 'right' }, { title: '未具备数据 / 原因', dataIndex: 'reason', key: 'reason', width: 440 }, ]; const aiFindingRows = rows(drilldown.findings); const aiFindingColumns: ColumnsType = [ { title: '发现类型', dataIndex: 'type', key: 'type', width: 190, render: findingTypeLabel }, { title: '对象', dataIndex: 'subject', key: 'subject', width: 320 }, { title: '级别', dataIndex: 'severity', key: 'severity', width: 90, render: severityLabel }, ]; const sessionIdForLink = text(drilldown.sessionId || selectedResult.analysisSessionId, ''); const turnIdForLink = text(drilldown.turnId || selectedResult.analysisTurnId, ''); return
质量巡检策略与运行记录策略阈值由服务端执行;运行结果受当前用户数据权限约束
{canManage && }
{!canManage && } {error && { void load(); void loadRuns(); }} />} {loading ?
读取巡检策略…
: canManage ? strategies.length ? String(row.id)} pagination={false} scroll={{ x: 1300 }} /> : : null}
{canRun && }
{!canRun && } {canRun && (runs.length ?
String(row.id)} pagination={{ pageSize: 15, showSizeChanger: false }} scroll={{ x: 1120 }} /> : )} { setEditing(null); form.resetFields(); }} onOk={() => void save()} width={Math.min(820, window.innerWidth - 24)}>

巡检规则

{booleanFields.map(([key, label]) => )}{metricFields.map(field => )}

阈值范围由服务端校验;保存后对后续巡检生效。

setSelectedRun(null)}>{selectedRun && <>
状态{text(selectedRun.status)}
适用数据当前数据
创建时间{text(selectedRun.createdAt)}
完成时间{text(selectedRun.completedAt)}
{selectedRun.error && }{selectedRun.result === undefined ? : <>

确定性结果:{selectedResult.deterministic === true ? '是' : selectedResult.deterministic === false ? '否' : '—'}

巡检发现项({findingRows.length})

{findingRows.length ?
`${text(row.type)}-${text(row.subject)}-${index}`} pagination={false} columns={findingColumns} expandable={{ expandedRowRender: row => <>

{text(row.summary)}

查看核查依据
{JSON.stringify(withoutSystemMetadata(row.evidence || {}), null, 2)}
}} scroll={{ x: 900 }} /> : }

规则覆盖与未满足条件

{ruleRows.length ?
`${text(row.id)}-${index}`} pagination={false} columns={ruleColumns} scroll={{ x: 870 }} /> : }

来源覆盖

原始行{text(coverage.rawRows)}
纳入计算{text(coverage.includedRows)}
未分类排除{text(coverage.excludedBlankRows)}
未映射行{text(coverage.unmappedRows)}
项目组未配置{text(coverage.projectGroupUnconfiguredRows)}
{missingStageRows.length > 0 && <>

缺少阶段来源

`${text(row.year)}-${text(row.month)}-${text(row.stage)}-${index}`} pagination={false} columns={[{ title: '年份', dataIndex: 'year', key: 'year', width: 100 }, { title: '月份', dataIndex: 'month', key: 'month', width: 100, render: value => `${text(value)} 月` }, { title: '缺失阶段', dataIndex: 'stage', key: 'stage', width: 160, render: value => value === 'black' ? '黑片' : value === 'bright' ? '亮片' : text(value) }]} scroll={{ x: 380 }} />} {sourceMonthRows.length > 0 && <>

月度来源覆盖

`${text(row.year)}-${text(row.month)}-${index}`} pagination={false} columns={[{ title: '年份', dataIndex: 'year', key: 'year', width: 100 }, { title: '月份', dataIndex: 'month', key: 'month', width: 100 }, { title: '黑片行数', dataIndex: 'blackRows', key: 'blackRows', align: 'right', width: 130 }, { title: '亮片行数', dataIndex: 'brightRows', key: 'brightRows', align: 'right', width: 130 }]} scroll={{ x: 500 }} />}

受控 AI 下钻

{drilldownStatusText(drilldown.status || selectedResult.aiDrilldownStatus)}{text(selectedResult.aiDrilldownQuestion, '基于巡检时的当前数据与服务端受控查询执行。')}{sessionIdForLink && turnIdForLink && }
{aiFindingRows.length > 0 &&
`${text(row.type)}-${text(row.subject)}-${index}`} pagination={false} columns={aiFindingColumns} scroll={{ x: 620 }} />}
查看其他运行信息
{JSON.stringify(withoutSystemMetadata(selectedResult), null, 2)}
}}; } export function SourceGovernancePanel({ user, currentReleaseId, onUnauthorized }: { user: AuthUser; currentReleaseId: string | null; onUnauthorized: (error: unknown) => boolean }) { const { message } = App.useApp(); const [protocols, setProtocols] = useState([]); const [coverage, setCoverage] = useState(null); const [sourceChanges, setSourceChanges] = useState([]); const [sourceItems, setSourceItems] = useState([]); const [documents, setDocuments] = useState([]); const [revisions, setRevisions] = useState([]); const [loading, setLoading] = useState(false); const [errors, setErrors] = useState>({}); const [protocolOpen, setProtocolOpen] = useState(false); const [changeOpen, setChangeOpen] = useState(false); const [reviewItem, setReviewItem] = useState(null); const [resolveItem, setResolveItem] = useState(null); const [evidenceRevision, setEvidenceRevision] = useState(''); const [evidence, setEvidence] = useState(null); const [actionBusy, setActionBusy] = useState(''); const [protocolForm] = Form.useForm(); const [changeForm] = Form.useForm(); const [reviewForm] = Form.useForm<{ reason: string }>(); const [resolveForm] = Form.useForm(); const [tab, setTab] = useState('coverage'); const canMaintain = user.roles.some(role => ['SYSTEM_ADMIN', 'DATA_MAINTAINER'].includes(role)); const canReview = user.roles.some(role => ['SYSTEM_ADMIN', 'DATA_PUBLISHER'].includes(role)); const canDownload = user.roles.some(role => ['SYSTEM_ADMIN', 'DATA_MAINTAINER', 'DATA_PUBLISHER', 'BUSINESS_ANALYST', 'QUALITY_VIEWER', 'AUDIT_VIEWER'].includes(role)); const stage = Form.useWatch('stage', protocolForm); const changeType = Form.useWatch('type', changeForm); const resolveDecision = Form.useWatch('decision', resolveForm); const load = async () => { setLoading(true); const failures: Record = {}; const results = await Promise.allSettled([ api.governanceProtocols(), api.governanceCoverage(currentReleaseId || undefined), api.sourceChanges(), api.sources(), api.governanceSourceDocuments(), ]); if (results[0].status === 'fulfilled') setProtocols(collectionItems(results[0].value)); else { if (!onUnauthorized(results[0].reason)) failures.protocols = results[0].reason instanceof Error ? results[0].reason.message : '协议读取失败'; } if (results[1].status === 'fulfilled') setCoverage(results[1].value); else { if (!onUnauthorized(results[1].reason)) failures.coverage = results[1].reason instanceof Error ? results[1].reason.message : '到齐矩阵读取失败'; } if (results[2].status === 'fulfilled') setSourceChanges(collectionItems(results[2].value)); else { if (!onUnauthorized(results[2].reason)) failures.changes = results[2].reason instanceof Error ? results[2].reason.message : '来源变更清单读取失败'; } if (results[3].status === 'fulfilled') setSourceItems(collectionItems(results[3].value)); else { if (!onUnauthorized(results[3].reason)) failures.candidates = results[3].reason instanceof Error ? results[3].reason.message : '候选文件读取失败'; } if (results[4].status === 'fulfilled') { setDocuments(collectionItems(results[4].value)); setRevisions(rows(results[4].value.revisions)); } else { if (!onUnauthorized(results[4].reason)) failures.documents = results[4].reason instanceof Error ? results[4].reason.message : '来源记录读取失败'; } setErrors(failures); setLoading(false); }; useEffect(() => { void load(); }, [currentReleaseId]); const submitProtocol = async () => { try { const value = await protocolForm.validateFields(); setActionBusy('protocol'); const body: Row = { ...value, ...(String(value.sourceSlot || '').trim() ? {} : { sourceSlot: undefined }), stage: value.stage, year: Number(value.year), month: Number(value.month), requiredSheet: value.stage === 'black' ? '报废明细' : '明细', expected: value.expected !== false, applicable: value.applicable !== false, deadline: String(value.deadline || '').trim() || undefined, shardCode: String(value.shardCode || '').trim() || 'MAIN', reason: String(value.reason || '').trim(), }; await api.createGovernanceProtocol(body); message.success('来源协议已保存'); setProtocolOpen(false); protocolForm.resetFields(); await load(); } catch (value) { if (value && typeof value === 'object' && 'errorFields' in value) return; if (!onUnauthorized(value)) message.error(value instanceof Error ? value.message : '协议保存失败'); } finally { setActionBusy(''); } }; const submitChange = async () => { try { const value = await changeForm.validateFields(); setActionBusy('change'); await api.createSourceChange({ ...value, reason: String(value.reason || '').trim(), idempotencyKey: crypto.randomUUID() }); message.success('来源变更申请已提交,当前数据保持不变'); setChangeOpen(false); changeForm.resetFields(); await load(); } catch (value) { if (value && typeof value === 'object' && 'errorFields' in value) return; if (!onUnauthorized(value)) message.error(value instanceof Error ? value.message : '来源变更申请失败'); } finally { setActionBusy(''); } }; const submitReview = async (approve: boolean) => { if (!reviewItem) return; try { const values = await reviewForm.validateFields(); setActionBusy(String(reviewItem.id)); await api.reviewSourceChange(String(reviewItem.id), { approve, reason: values.reason.trim(), expectedRowVersion: Number(reviewItem.rowVersion || 0) }); message.success(approve ? '变更申请已通过' : '变更申请已驳回'); setReviewItem(null); reviewForm.resetFields(); await load(); } catch (value) { if (value && typeof value === 'object' && 'errorFields' in value) return; if (!onUnauthorized(value)) message.error(value instanceof ApiError && value.status === 409 ? '申请已被其他操作更新,请刷新后复核。' : value instanceof Error ? value.message : '审核失败'); if (value instanceof ApiError && value.status === 409) await load(); } finally { setActionBusy(''); } }; const buildChange = async (item: Row) => { const id = String(item.id || ''); if (!id) return; setActionBusy(id); try { const result = await api.releases(); await api.buildSourceChange(id, { expectedCurrentReleaseId: result.currentReleaseId ?? null, idempotencyKey: crypto.randomUUID() }); message.success('来源变更处理已完成;请检查候选数据与校验状态。'); await load(); } catch (value) { if (!onUnauthorized(value)) message.error(value instanceof ApiError && value.status === 409 ? '当前数据或申请状态已变化,请刷新核对。' : value instanceof Error ? value.message : '变更处理失败'); if (value instanceof ApiError && value.status === 409) await load(); } finally { setActionBusy(''); } }; const resolveCandidate = async () => { if (!resolveItem) return; try { const value = await resolveForm.validateFields(); setActionBusy(resolveItem.id); await api.resolveSourceCandidate(resolveItem.id, { ...value, reason: String(value.reason || '').trim() }); message.success('候选来源身份已裁决'); setResolveItem(null); resolveForm.resetFields(); await load(); } catch (value) { if (value && typeof value === 'object' && 'errorFields' in value) return; if (!onUnauthorized(value)) message.error(value instanceof Error ? value.message : '来源裁决失败'); } finally { setActionBusy(''); } }; const showEvidence = async (id: string) => { setEvidenceRevision(id); setEvidence(null); try { setEvidence(await api.sourceRevisionEvidence(id)); } catch (value) { if (!onUnauthorized(value)) message.error(value instanceof Error ? value.message : '证据读取失败'); } }; const download = async (id: string) => { setActionBusy(id); try { showDownload(await api.downloadSourceRevision(id)); } catch (value) { if (!onUnauthorized(value)) message.error(value instanceof ApiError && value.status === 403 ? '当前账号无权下载此原始文件或文件超出组织范围。' : value instanceof Error ? value.message : '原文件下载失败'); } finally { setActionBusy(''); } }; const coverageItems = rows(coverage?.items); const coverageColumns: ColumnsType = [ { title: '来源槽位', dataIndex: 'sourceSlot', key: 'sourceSlot', fixed: 'left', width: 290 }, { title: '阶段', dataIndex: 'stage', key: 'stage', width: 85, render: value => value === 'black' ? '黑片' : value === 'bright' ? '亮片' : text(value) }, { title: '期间', key: 'period', width: 110, render: (_, row) => `${text(row.sourceYear)}-${String(row.sourceMonth ?? '').padStart(2, '0')}` }, { title: '预期', dataIndex: 'expected', key: 'expected', width: 80, render: value => value === true ? '是' : '否' }, { title: '已接收 / 已校验', key: 'received', align: 'right', width: 135, render: (_, row) => `${text(row.receivedCount, '0')} / ${text(row.validatedCount, '0')}` }, { title: '状态', dataIndex: 'status', key: 'status', width: 150, render: value => {text(value)} }, { title: '告警', key: 'alert', width: 120, render: (_, row) => row.blocking === true ? 阻断 : row.overdue === true ? 逾期 : '—' }, ]; const protocolColumns: ColumnsType = [ { title: '来源槽位', dataIndex: 'sourceSlot', key: 'sourceSlot', fixed: 'left', width: 270 }, { title: '阶段 / 期间', key: 'period', width: 130, render: (_, row) => `${text(row.stage)} · ${text(row.sourceYear)}-${String(row.sourceMonth ?? '').padStart(2, '0')}` }, { title: '范围 / 分片', key: 'scope', width: 170, render: (_, row) => `${text(row.scopeCode)} · ${text(row.shardCode, 'MAIN')}` }, { title: '来源模式', dataIndex: 'sourceMode', key: 'sourceMode', width: 160 }, { title: '工作表 / 文件规则', key: 'pattern', width: 210, render: (_, row) => `${text(row.requiredSheet)} · ${text(row.filenamePattern)}` }, { title: '状态', dataIndex: 'active', key: 'status', width: 100, render: value => value === true ? '启用' : '停用' }, ]; const changeColumns: ColumnsType = [ { title: '申请类型', dataIndex: 'requestType', key: 'requestType', width: 100, render: value => value === 'WITHDRAW' ? '撤销来源' : value === 'REVISION' ? '替换/补录来源' : text(value) }, { title: '来源文件', dataIndex: 'sourceFile', key: 'sourceFile', width: 210, render: (_, row) => text(row.sourceFile || row.sourceSlot, '来源文件') }, { title: '申请原因', dataIndex: 'reason', key: 'reason', width: 270, ellipsis: true }, { title: '状态', dataIndex: 'status', key: 'status', width: 120, render: value => {text(value)} }, { title: '候选结果', key: 'result', width: 150, render: (_, row) => row.resultReleaseId ? '已生成候选' : row.importRunId ? '处理中' : '—' }, { title: '操作', key: 'actions', fixed: 'right', width: 220, render: (_, row) => {canReview && row.status === 'REQUESTED' && } {canReview && row.status === 'APPROVED' && } }, ]; const revisionColumns: ColumnsType = [ { title: '原始文件', dataIndex: 'sourceFile', key: 'sourceFile', fixed: 'left', width: 260 }, { title: '来源槽位', dataIndex: 'sourceSlot', key: 'sourceSlot', width: 250, render: value => text(value, '关联来源') }, { title: 'SHA-256', dataIndex: 'sha256', key: 'sha256', width: 290, ellipsis: true }, { title: '文件大小', dataIndex: 'fileSize', key: 'fileSize', width: 110, align: 'right', render: value => typeof value === 'number' ? `${(value / 1024).toFixed(1)} KB` : text(value) }, { title: '归档状态', dataIndex: 'status', key: 'status', width: 110 }, { title: '接收时间', dataIndex: 'receivedAt', key: 'receivedAt', width: 190 }, { title: '操作', key: 'actions', fixed: 'right', width: 190, render: (_, row) => { const id = String(row.id || ''); return {canDownload && }; } }, ]; const conflictCandidates = sourceItems.filter(item => ['UNIDENTIFIED', 'COVERAGE_CONFLICT'].includes(String(item.status).toUpperCase())); const documentChoices = documents.map(item => ({ label: text(item.sourceFile || item.sourceSlot, '来源文档'), value: String(item.id || '') })).filter(item => item.value); const candidateChoices = sourceItems.map(item => ({ label: `${item.sourceFile} · ${item.year}-${String(item.month).padStart(2, '0')} · ${item.status}`, value: item.id })); return
来源协议、覆盖与变更当前数据的来源覆盖、到齐状态和原文件下载权限由服务端控制
{canMaintain && <>}
void load()} /> void load()} /> void load()} />
适用数据 当前数据{coverage?.complete === true ? '覆盖完整' : coverage?.complete === false ? '覆盖未齐' : '未返回'}
{coverageItems.length ?
String(row.protocolId || row.sourceSlot)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 980 }} /> : } }, { key: 'protocols', label: `来源协议(${protocols.length})`, children:
{protocols.length ?
String(row.id)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1120 }} /> : } }, { key: 'changes', label: `来源变更与撤销(${sourceChanges.length})`, children:
{conflictCandidates.length > 0 && {conflictCandidates.map(item => )}} />}{errors.changes ? : sourceChanges.length ?
String(row.id)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1080 }} /> : } }, { key: 'revisions', label: `原文件记录与证据(${revisions.length})`, children:
{revisions.length ?
String(row.id)} pagination={{ pageSize: 15, showSizeChanger: false }} scroll={{ x: 1280 }} /> : } }, ]} /> setProtocolOpen(false)} onOk={() => void submitProtocol()}>
该阶段适用列为预期到齐来源解析工作表将使用已验证名称:{stage === 'black' ? '报废明细' : '明细'}。
setChangeOpen(false)} onOk={() => void submitChange()}>
{changeType === 'REVISION' && {resolveDecision !== 'RETURN' &&
String(row.id)} pagination={false} columns={[{ title: '处理状态', dataIndex: 'status', key: 'status', width: 120 }, { title: '行数 / 拒绝', key: 'counts', align: 'right', render: (_, row) => `${text(row.rowCount)} / ${text(row.rejectedCount)}` }, { title: '分量摘要', dataIndex: 'componentSummary', key: 'componentSummary', render: value => text(value) }]} scroll={{ x: 520 }} /> : }{canDownload && } :
读取来源记录…
} ; } export function BackupOperationsPanel({ user, onUnauthorized, onNavigate }: { user: AuthUser; onUnauthorized: (error: unknown) => boolean; onNavigate?: () => void }) { const { message } = App.useApp(); const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [busy, setBusy] = useState(false); const [error, setError] = useState(''); const [planOpen, setPlanOpen] = useState(false); const [form] = Form.useForm(); const canManage = user.roles.some(role => ['SYSTEM_ADMIN', 'SYSTEM_OPERATOR'].includes(role)); const load = async () => { setLoading(true); try { setData(await api.governanceBackups()); setError(''); } catch (value) { if (!onUnauthorized(value)) setError(value instanceof Error ? value.message : '备份状态读取失败'); } finally { setLoading(false); } }; useEffect(() => { void load(); }, []); const runJob = async (type: string, backupId?: string) => { setBusy(true); try { await api.createBackupJob({ type, ...(backupId ? { backupId } : {}), idempotencyKey: crypto.randomUUID() }); message.success('备份任务已登记'); await load(); } catch (value) { if (!onUnauthorized(value)) message.error(value instanceof Error ? value.message : '备份任务提交失败'); } finally { setBusy(false); } }; const savePlan = async () => { try { const value = await form.validateFields(); setBusy(true); await api.updateBackupPlan({ ...value, reason: String(value.reason || '').trim(), expectedRowVersion: Number(obj(data?.plan).rowVersion || 0) }); message.success('备份计划已保存'); setPlanOpen(false); await load(); } catch (value) { if (value && typeof value === 'object' && 'errorFields' in value) return; if (!onUnauthorized(value)) message.error(value instanceof ApiError && value.status === 409 ? '备份计划已被更新,请刷新后重试。' : value instanceof Error ? value.message : '保存备份计划失败'); } finally { setBusy(false); } }; const plan = obj(data?.plan); const backups = rows(data?.items); const columns: ColumnsType = [ { title: '备份时间', dataIndex: 'createdAt', key: 'createdAt', fixed: 'left', width: 190, render: value => configurationDateTime(value) || '—' }, { title: '状态', dataIndex: 'status', key: 'status', width: 150, render: value => {monitorLabel(value,'状态待确认')} }, { title: '恢复验证时间', dataIndex: 'restoreVerifiedAt', key: 'restoreVerifiedAt', width: 190, render: value => configurationDateTime(value) || '—' }, { title: '还原用时(秒)', dataIndex: 'restoreElapsedSeconds', key: 'restoreElapsedSeconds', width: 110 }, { title: '验证范围', key: 'verification', width: 210, render: (_, row) => { const verified = obj(row.verification); const checks = [['databaseRestoreVerified', '数据库恢复'], ['archiveFilesVerified', '来源文件'], ['archiveReferencesVerified', '来源路径'], ['applicationFilesVerified', '应用文件'], ['requiredApplicationInputsVerified', '构建输入'], ['applicationStartupVerified', '应用启动']]; return
查看分项{checks.map(([key, label]) =>
{label}:{verified[key] === true ? '已验证' : '未验证'}
)}
; } }, { title: '操作', key: 'action', width: 130, render: (_, row) => }, ]; return
备份、恢复验证与计划恢复验证仅在隔离目录执行;当前不开放在线业务库覆盖恢复
{canManage && <>}
{error && } {loading ?
读取备份与恢复状态…
: <>
计划{plan.active === true ? '已启用' : plan.active === false ? '已停用' : '未配置'}
周期 / RPO{text(plan.intervalHours)} 小时 / {text(plan.rpoHours)} 小时
RTO{text(plan.rtoHours)} 小时
在线恢复{obj(data).liveRestoreEnabled === true ? '开放' : '关闭'}
{backups.length ?
String(row.id)} pagination={{ pageSize: 15, showSizeChanger: false }} scroll={{ x: 920 }} /> : }} {onNavigate && } setPlanOpen(false)} onOk={() => void savePlan()}>
; } export function OperationsMonitorPanel({ user, onUnauthorized }: { user: AuthUser; onUnauthorized: (error: unknown) => boolean }) { const { message } = App.useApp(); const [data, setData] = useState(null); const [loading, setLoading] = useState(true); const [refreshing, setRefreshing] = useState(false); const [error, setError] = useState(''); const [alertPolicy, setAlertPolicy] = useState(null); const [policyOpen, setPolicyOpen] = useState(false); const [alertStatus, setAlertStatus] = useState('OPEN'); const [policyBusy, setPolicyBusy] = useState(false); const [policyError, setPolicyError] = useState(''); const [policyForm] = Form.useForm(); const canRefresh = user.roles.some(role => ['SYSTEM_ADMIN', 'SYSTEM_OPERATOR'].includes(role)); const load = async () => { setLoading(true); try { setData(await api.governanceMonitor()); setError(''); } catch (value) { if (!onUnauthorized(value)) setError(value instanceof Error ? value.message : '运行监控读取失败'); } finally { setLoading(false); } }; useEffect(() => { void load(); }, []); const loadPolicy = async () => { try { const response = await api.governanceAlertPolicy(); const policy = obj(response.policy); setAlertPolicy(policy); setPolicyError(''); } catch (value) { if (!onUnauthorized(value)) setPolicyError(value instanceof Error ? value.message : '告警策略读取失败'); } }; useEffect(() => { if (canRefresh) void loadPolicy(); }, [canRefresh]); const editPolicy = () => { if (!alertPolicy) return; policyForm.setFieldsValue({ ...alertPolicy, severityOverrides: JSON.stringify(alertPolicy.severityOverrides || {}, null, 2), silenceUntil: text(alertPolicy.silenceUntil, ''), reason: '' }); setPolicyOpen(true); }; const savePolicy = async () => { try { const values = await policyForm.validateFields(); let severityOverrides: unknown; try { severityOverrides = JSON.parse(String(values.severityOverrides || '{}')); } catch { message.error('严重度配置不是有效 JSON'); return; } setPolicyBusy(true); await api.updateGovernanceAlertPolicy({ queueAgeMinutes: Number(values.queueAgeMinutes), diskFreeBytes: Number(values.diskFreeBytes), backupAgeHours: Number(values.backupAgeHours), quietPeriodMinutes: Number(values.quietPeriodMinutes), slowRequestMillis: Number(values.slowRequestMillis), severityOverrides, silenceUntil: String(values.silenceUntil || '').trim() || null, expectedRowVersion: Number(alertPolicy?.rowVersion || 0), reason: String(values.reason || '').trim() }); message.success('告警策略已保存'); setPolicyOpen(false); await loadPolicy(); } catch (value) { if (value && typeof value === 'object' && 'errorFields' in value) return; if (!onUnauthorized(value)) setPolicyError(value instanceof ApiError && value.status === 409 ? '告警策略已发生并发修改,请重新读取。' : value instanceof Error ? value.message : '告警策略保存失败'); } finally { setPolicyBusy(false); } }; const refresh = async () => { setRefreshing(true); try { const result = await api.refreshGovernanceMonitor(); setData(result); message.success('系统健康检查已完成'); setError(''); } catch (value) { if (!onUnauthorized(value)) setError(value instanceof Error ? value.message : '巡检失败'); } finally { setRefreshing(false); } }; const summary = obj(data?.summary); const summaryEntries = Object.entries(summary).filter(([, value]) => ['string', 'number', 'boolean'].includes(typeof value)); const allAlerts = rows(data?.alerts); const alertRows = alertsForStatus(allAlerts, alertStatus); const summaryLabels: Record = {queuedTasks:'排队任务',runningTasks:'运行中任务',failedTasks:'失败任务',sourceAttention:'待处理来源',failedAnalysisTurns:'失败分析',openAlerts:'当前告警'}; const requestMetricRows = rows(data?.requestMetrics); const alertColumns: ColumnsType = [ { title: '级别', dataIndex: 'severity', key: 'severity', width: 100, render: value => {({INFO:'提示',WARNING:'警告',ERROR:'错误',CRITICAL:'严重'} as Record)[String(value)] || '未知级别'} }, { title: '告警', dataIndex: 'title', key: 'title', width: 230, render: (_, row) => monitorLabel(row.alertType,'平台告警') }, { title: '说明', dataIndex: 'message', key: 'message', width: 430 }, { title: '对象', key: 'target', width: 210, render: (_, row) => alertObject(row) }, { title: alertStatus === 'RECOVERED' ? '恢复时间' : '最近发生', key: 'alertTime', width: 190, render: (_,row) => configurationDateTime(alertStatus === 'RECOVERED' ? row.recoveredAt : row.lastSeen) || '—' }, { title: '状态', dataIndex: 'status', key: 'status', width: 120, render: (value,row) => <>{monitorLabel(value)}{value === 'OPEN' && row.silenced === true && 静默中} }, ]; const requestMetricColumns: ColumnsType = [ { title: '路由', dataIndex: 'routePattern', key: 'routePattern', fixed: 'left', width: 280 }, { title: '方法', dataIndex: 'method', key: 'method', width: 90 }, { title: '请求数', dataIndex: 'requestCount', key: 'requestCount', align: 'right', width: 100 }, { title: '失败数', dataIndex: 'failureCount', key: 'failureCount', align: 'right', width: 100 }, { title: '慢请求数', dataIndex: 'slowCount', key: 'slowCount', align: 'right', width: 110 }, { title: '累计耗时 / ms', dataIndex: 'totalElapsedMillis', key: 'totalElapsedMillis', align: 'right', width: 140 }, { title: '最长耗时 / ms', dataIndex: 'maxElapsedMillis', key: 'maxElapsedMillis', align: 'right', width: 140 }, { title: '最近请求', dataIndex: 'lastSeen', key: 'lastSeen', width: 190, render: value => configurationDateTime(value) || '—' }, ]; return <>
运行监控与告警只读取并更新服务端运行状态;不发送外部通知
{canRefresh && <>}
{error && } {policyError && } {loading ?
读取平台状态…
: <>
{summaryEntries.length ? summaryEntries.map(([key, value]) =>
{summaryLabels[key] || '其他指标'}{text(value)}
) :
服务端没有返回运行指标
}
{alertRows.length ?
String(row.id || row.code)} pagination={{ pageSize: 15, showSizeChanger: false }} scroll={{ x: 1260 }} /> : }} }, { key: 'requests', label: '接口请求指标', children:

接口请求指标

累计请求数、失败数与耗时;最近请求时间不代表统计起点。

{loading ?
读取接口指标…
: requestMetricRows.length ?
`${text(row.routePattern)}-${text(row.method)}`} pagination={{ pageSize: 15, showSizeChanger: false }} scroll={{ x: 1200 }} /> : } }, { key: 'inspection', label: '巡检策略', children: }, ]} /> setPolicyOpen(false)} onOk={() => void savePolicy()}>

保存后按新策略检查;严重度 key 只能使用服务端列出的告警类型。

; } const ACTIONS_BY_TYPE: Record = { RECEIVER: ['source.receive'], IMPORTER: ['import.run'], QUERY: ['query.aggregate', 'query.detail'], WORKER: ['worker.execute', 'import.run'], MODEL: ['model.intent.parse'], }; export function ServiceIdentityPanel({ user, onUnauthorized }: { user: AuthUser; onUnauthorized: (error: unknown) => boolean }) { const { message } = App.useApp(); const [items, setItems] = useState([]); const [allowedActions, setAllowedActions] = useState([]); const [serviceTypes, setServiceTypes] = useState([]); const [bindings, setBindings] = useState([]); const [loading, setLoading] = useState(true); const [error, setError] = useState(''); const [editing, setEditing] = useState(null); const [rotating, setRotating] = useState(null); const [rotations, setRotations] = useState([]); const [bindingEdit, setBindingEdit] = useState<{ type: string; identityId: string } | null>(null); const [busy, setBusy] = useState(false); const [form] = Form.useForm(); const [rotateForm] = Form.useForm(); const [bindingForm] = Form.useForm<{ reason: string }>(); const canManage = user.roles.includes('SYSTEM_ADMIN'); const serviceType = Form.useWatch('serviceType', form); const load = async () => { setLoading(true); const canReadBindings = user.roles.some(role => ['SYSTEM_ADMIN', 'SYSTEM_OPERATOR'].includes(role)); const [identityResult, bindingResult] = await Promise.allSettled([api.serviceIdentities(), canReadBindings ? api.serviceBindings() : Promise.resolve({ items: [] as Row[] })]); if (identityResult.status === 'fulfilled') { setItems(collectionItems(identityResult.value)); setAllowedActions(Array.isArray(identityResult.value.allowedActions) ? identityResult.value.allowedActions.map(String) : []); setServiceTypes(Array.isArray(identityResult.value.serviceTypes) ? identityResult.value.serviceTypes.map(String) : []); } else if (!onUnauthorized(identityResult.reason)) setError(identityResult.reason instanceof Error ? identityResult.reason.message : '服务身份读取失败'); if (bindingResult.status === 'fulfilled') setBindings(collectionItems(bindingResult.value)); else if (!onUnauthorized(bindingResult.reason)) setError(bindingResult.reason instanceof Error ? bindingResult.reason.message : '服务绑定读取失败'); setLoading(false); }; useEffect(() => { void load(); }, []); const open = (item?: Row) => { const next = item || {}; setEditing(next); form.setFieldsValue({ name: text(next.name, ''), serviceType: text(next.serviceType, serviceTypes[0] || ''), allowedActions: Array.isArray(next.allowedActions) ? next.allowedActions.map(String) : [], credentialReference: text(next.credentialReference, ''), credentialStatus: text(next.credentialStatus, 'UNCONFIGURED'), active: next.active === true, reason: '' }); }; const save = async () => { try { const values = await form.validateFields(); setBusy(true); const id = String(editing?.id || ''); const body = { name: String(values.name || '').trim(), serviceType: values.serviceType, allowedActions: values.allowedActions || [], credentialReference: values.credentialReference || null, credentialStatus: values.credentialStatus, active: id ? values.active === true : false, ...(id ? { expectedRowVersion: Number(editing?.rowVersion || 0) } : {}), reason: String(values.reason || '').trim() }; if (id) await api.updateServiceIdentity(id, body); else await api.createServiceIdentity(body); message.success(id ? '服务身份已更新' : '服务身份已创建并保持停用'); setEditing(null); await load(); } catch (value) { if (value && typeof value === 'object' && 'errorFields' in value) return; if (!onUnauthorized(value)) message.error(value instanceof ApiError && value.status === 409 ? '服务身份已被其他操作更新,请刷新后重试。' : value instanceof Error ? value.message : '服务身份保存失败'); } finally { setBusy(false); } }; const rotate = async () => { if (!rotating?.id) return; try { const values = await rotateForm.validateFields(); setBusy(true); await api.rotateServiceIdentity(String(rotating.id), { credentialReference: values.credentialReference, credentialStatus: values.credentialStatus, reason: String(values.reason || '').trim(), expectedRowVersion: Number(rotating.rowVersion || 0) }); message.success('凭据引用状态已轮换,服务端未接收密钥内容'); setRotating(null); await load(); } catch (value) { if (value && typeof value === 'object' && 'errorFields' in value) return; if (!onUnauthorized(value)) message.error(value instanceof ApiError && value.status === 409 ? '服务身份已被其他操作更新。' : value instanceof Error ? value.message : '凭据轮换失败'); } finally { setBusy(false); } }; const bind = async (type: string, identityId: string) => { bindingForm.resetFields(); setBindingEdit({ type, identityId }); }; const submitBinding = async () => { if (!bindingEdit) return; let values: { reason: string }; try { values = await bindingForm.validateFields(); } catch { return; } setBusy(true); try { await api.updateServiceBinding(bindingEdit.type, { identityId: bindingEdit.identityId, reason: values.reason.trim() }); message.success(`${bindingEdit.type} 服务绑定已更新`); setBindingEdit(null); await load(); } catch (value) { if (!onUnauthorized(value)) message.error(value instanceof Error ? value.message : '服务身份绑定失败'); } finally { setBusy(false); } }; const columns: ColumnsType = [ { title: '服务身份', dataIndex: 'name', key: 'name', fixed: 'left', width: 190 }, { title: '类型', dataIndex: 'serviceType', key: 'serviceType', width: 120 }, { title: '授权动作', dataIndex: 'allowedActions', key: 'allowedActions', width: 280, render: value => Array.isArray(value) ? value.join('、') : '—' }, { title: '凭据引用 / 状态', key: 'credential', width: 260, render: (_, row) => {text(row.credentialStatus)}{text(row.credentialReference, '未配置引用')} }, { title: '状态', dataIndex: 'active', key: 'active', width: 100, render: value => {value === true ? '启用' : '停用'} }, { title: '操作', key: 'action', fixed: 'right', width: 230, render: (_, row) => {canManage && <>} }, ]; return
服务身份与最小动作授权仅保存 env: 或 file: 凭据引用,不在浏览器或服务端表单中接收密钥文本
{canManage && }
{error && } {loading ?
读取服务身份…
: items.length ?
String(row.id)} pagination={{ pageSize: 15, showSizeChanger: false }} scroll={{ x: 1200 }} /> : } }, { key: 'bindings', label: '接入绑定', children: <>
服务接入绑定只允许类型匹配且授权状态可用的身份
{serviceTypes.length ?
{serviceTypes.map(type =>
{type}{text(bindings.find(item => item.serviceType === type)?.serviceIdentityId, '未绑定')}{canManage && allowedActions.includes(value)).map((value: string) => ({ label: value, value }))} />
String(row.id)} pagination={{ pageSize: 15, showSizeChanger: false }} columns={[{ title: '引用', dataIndex: 'credentialReference', key: 'credentialReference' }, { title: '状态', dataIndex: 'credentialStatus', key: 'credentialStatus' }, { title: '原因', dataIndex: 'reason', key: 'reason' }, { title: '时间', dataIndex: 'createdAt', key: 'createdAt' }]} /> : } ; } export function UserAccessPolicyPanel({ onUnauthorized }: { onUnauthorized: (error: unknown) => boolean }) { const { message } = App.useApp(); const [userId, setUserId] = useState(); const [policy, setPolicy] = useState(null); const [users, setUsers] = useState([]); const [effective, setEffective] = useState(null); const [scopePreview, setScopePreview] = useState(null); const [previewBusy, setPreviewBusy] = useState(false); const [loading, setLoading] = useState(false); const [saving, setSaving] = useState(false); const [error, setError] = useState(''); const [form] = Form.useForm(); const selectedUser = useRef(undefined); const policyGeneration = useRef(0); const savingRef = useRef(false); const mounted = useRef(true); const selectUser = (id: string) => { if (savingRef.current) return; selectedUser.current = id; policyGeneration.current++; setUserId(id); setPolicy(null); form.resetFields(); setEffective(null); setScopePreview(null); setPreviewBusy(false); setError(''); setLoading(true); }; const userOptions = users.map(item => ({ label: `${text(item.displayName || item.username)} · ${text(item.username)}`, value: String(item.id) })).filter(item => item.value); const load = async (id: string) => { const generation = ++policyGeneration.current; const current = () => mounted.current && selectedUser.current === id && policyGeneration.current === generation; if (selectedUser.current !== id) return; setLoading(true); setPolicy(null); form.resetFields(); try { const result = await api.userAccessPolicy(id); if (!current()) return; const value = obj(result.policy || result); if (value.userId !== id) throw new Error('访问策略与当前用户不匹配,请重新选择用户。'); setPolicy(value); form.setFieldsValue({ detailAllowed: value.detailAllowed === true, evidenceAllowed: value.evidenceAllowed === true, originalDownloadAllowed: value.originalDownloadAllowed === true, inheritDepartmentChildren: value.inheritDepartmentChildren === true, allowedFields: Array.isArray(value.allowedFields) ? value.allowedFields.join('\n') : '*', validUntil: text(value.validUntil, ''), reason: '' }); setError(''); } catch (value) { if (!onUnauthorized(value) && current()) setError(value instanceof Error ? value.message : '访问策略读取失败'); } finally { if (current()) setLoading(false); } }; useEffect(() => { mounted.current = true; api.users().then(value => { if (mounted.current) setUsers(collectionItems(value)); }).catch(errorValue => { if (!onUnauthorized(errorValue) && mounted.current) setError(errorValue instanceof Error ? errorValue.message : '用户列表读取失败'); }); return () => { mounted.current = false; policyGeneration.current++; }; }, []); useEffect(() => { if (userId) void load(userId); else setPolicy(null); }, [userId]); const save = async () => { const id = selectedUser.current; if (!id || !policy || policy.userId !== id || loading || savingRef.current) return; const generation = policyGeneration.current; const current = () => mounted.current && selectedUser.current === id && policyGeneration.current === generation; savingRef.current = true; setSaving(true); try { const value = await form.validateFields(); if (!current()) return; const allowedFields = String(value.allowedFields || '').split(/[\n,,]/).map(item => item.trim()).filter(Boolean); await api.updateUserAccessPolicy(id, { detailAllowed: value.detailAllowed === true, evidenceAllowed: value.evidenceAllowed === true, originalDownloadAllowed: value.originalDownloadAllowed === true, inheritDepartmentChildren: value.inheritDepartmentChildren === true, allowedFields, validUntil: value.validUntil || null, reason: String(value.reason || '').trim(), expectedRowVersion: Number(policy.rowVersion || 0) }); if (!current()) return; message.success('明细、证据及组织范围策略已更新'); await load(id); } catch (value) { if (value && typeof value === 'object' && 'errorFields' in value) return; if (!onUnauthorized(value) && current()) message.error(value instanceof ApiError && value.status === 409 ? '授权策略已被更新,请重新读取。' : value instanceof Error ? value.message : '策略保存失败'); } finally { savingRef.current = false; if (mounted.current) setSaving(false); } }; const preview = async (kind: 'effective' | 'scope') => { const id = selectedUser.current; if (!id || loading || savingRef.current || previewBusy) return; const generation = policyGeneration.current; const current = () => mounted.current && selectedUser.current === id && policyGeneration.current === generation; setPreviewBusy(true); try { const result = kind === 'effective' ? await api.effectiveUserAccess(id) : await api.userScopePreview(id); if (!current()) return; if (kind === 'effective') setEffective(result); else setScopePreview(result); } catch (value) { if (!onUnauthorized(value) && current()) message.error(value instanceof Error ? value.message : '用户有效授权读取失败'); } finally { if (current()) setPreviewBusy(false); } }; const scopeCounts = rows(scopePreview?.counts); const effectiveDepartments = Array.isArray(effective?.departments) ? effective.departments.map(String).join('、') : '—'; const grantedDepartments = Array.isArray(effective?.grantedDepartments) ? effective.grantedDepartments.map(String).join('、') : '—'; const hierarchyRows = rows(effective?.hierarchySource); return
用户明细与证据访问策略明细、原文件下载与字段授权由服务端二次校验

空字段集合将由服务端按其默认策略处理。

}{effective &&
服务端有效授权{effective.authorizationEffective === true ? '有效' : '未生效'}

用户 {text(effective.userId)} · 身份 {effective.active === true ? '启用' : '停用'} · 数据范围已由服务端核验

角色:{Array.isArray(effective.roles) ? (effective.roles as unknown[]).map(String).join('、') : '—'}

原始授权产业部:{grantedDepartments} · 有效产业部:{effectiveDepartments}

业务分组:{Array.isArray(effective.groups) ? (effective.groups as unknown[]).map(String).join('、') : '—'}

动作:{Array.isArray(effective.allowedActions) ? (effective.allowedActions as unknown[]).map(String).join('、') : '—'}

字段策略:{JSON.stringify(withoutSystemMetadata(effective.fieldPolicy ?? {}))}

{hierarchyRows.length > 0 &&

层级展开依据:当前映射配置

}
}{scopePreview &&
授权范围行数{scopePreview.dataReturned === false ? '仅计数,未返回数据' : '服务端返回状态'}

原始授权产业部:{Array.isArray(scopePreview.grantedDepartments) ? (scopePreview.grantedDepartments as unknown[]).map(String).join('、') : '—'} · 有效产业部:{Array.isArray(scopePreview.departments) ? (scopePreview.departments as unknown[]).map(String).join('、') : '—'}

{rows(scopePreview.hierarchySource).length > 0 &&

层级依据:当前映射配置

}{scopeCounts.length ?
String(row.stage)} pagination={false} columns={[{ title: '阶段', dataIndex: 'stage', key: 'stage', width: 100, render: value => value === 'black' ? '黑片' : value === 'bright' ? '亮片' : text(value) }, { title: '总行数', dataIndex: 'totalRows', key: 'totalRows', align: 'right' }, { title: '授权行数', dataIndex: 'authorizedRows', key: 'authorizedRows', align: 'right' }]} /> : }}{!userId && }; }