同步:完善质量分析工作台并更新主题字体

同步已上线的智能分析执行协议、来源查询、图表报告与管理页面配套代码。
补齐数据库迁移、运行依赖和回归测试,保留原有指标计算口径。
统一午夜黑及其他主题的控件细节、中文和业务数字字体。
排除本地业务数据、凭据、预览、发布与验收产物。

验证:生产构建通过,320项前端回归通过;本轮仅同步Git,不再次部署。
This commit is contained in:
2026-10-30 22:40:58 +08:00
parent edef747e3b
commit ff7bbe3e46
393 changed files with 62999 additions and 1783 deletions
+77 -29
View File
@@ -1,4 +1,6 @@
import { useEffect, useState } from 'react';
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';
@@ -495,11 +497,18 @@ export function BackupOperationsPanel({ user, onUnauthorized, onNavigate }: { us
};
const plan = obj(data?.plan); const backups = rows(data?.items);
const columns: ColumnsType<Row> = [
{ title: '备份时间', dataIndex: 'createdAt', key: 'createdAt', fixed: 'left', width: 190 },
{ title: '状态', dataIndex: 'status', key: 'status', width: 130, render: value => <Tag>{text(value)}</Tag> },
{ title: '备份时间', dataIndex: 'createdAt', key: 'createdAt', fixed: 'left', width: 190, render: value => configurationDateTime(value) || '—' },
{ title: '状态', dataIndex: 'status', key: 'status', width: 150, render: value => <Tag>{monitorLabel(value,'状态待确认')}</Tag> },
{ title: '恢复验证时间', dataIndex: 'restoreVerifiedAt', key: 'restoreVerifiedAt', width: 190 },
{ title: '还原用时', dataIndex: 'restoreElapsedSeconds', key: 'restoreElapsedSeconds', width: 110 },
{ 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 <details><summary>查看分项</summary>{checks.map(([key, label]) => <div key={key}>{label}:{verified[key] === true ? '已验证' : '未验证'}</div>)}</details>;
} },
{ title: '操作', key: 'action', width: 130, render: (_, row) => <Button type="link" loading={busy} onClick={() => void runJob('BACKUP_VERIFY', String(row.id))}>复核备份</Button> },
];
return <section className="panel section-panel completion-tools">
@@ -519,6 +528,7 @@ export function OperationsMonitorPanel({ user, onUnauthorized }: { user: AuthUse
const [error, setError] = useState('');
const [alertPolicy, setAlertPolicy] = useState<Row | null>(null);
const [policyOpen, setPolicyOpen] = useState(false);
const [alertStatus, setAlertStatus] = useState('OPEN');
const [policyBusy, setPolicyBusy] = useState(false);
const [policyError, setPolicyError] = useState('');
const [policyForm] = Form.useForm<Row>();
@@ -551,21 +561,23 @@ export function OperationsMonitorPanel({ user, onUnauthorized }: { user: AuthUse
};
const refresh = async () => {
setRefreshing(true);
try { const result = await api.refreshGovernanceMonitor(); setData(result); message.success('平台内巡检已完成'); setError(''); }
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 alertRows = rows(data?.alerts);
const allAlerts = rows(data?.alerts);
const alertRows = alertsForStatus(allAlerts, alertStatus);
const summaryLabels: Record<string,string> = {queuedTasks:'排队任务',runningTasks:'运行中任务',failedTasks:'失败任务',sourceAttention:'待处理来源',failedAnalysisTurns:'失败分析',openAlerts:'当前告警'};
const requestMetricRows = rows(data?.requestMetrics);
const alertColumns: ColumnsType<Row> = [
{ title: '级别', dataIndex: 'severity', key: 'severity', width: 100, render: value => <Tag color={String(value).toUpperCase().includes('CRIT') || String(value).toUpperCase().includes('ERROR') ? 'red' : 'gold'}>{text(value)}</Tag> },
{ title: '告警', dataIndex: 'title', key: 'title', width: 230, render: (_, row) => text(row.title || row.code) },
{ title: '级别', dataIndex: 'severity', key: 'severity', width: 100, render: value => <Tag color={String(value).toUpperCase().includes('CRIT') || String(value).toUpperCase().includes('ERROR') ? 'red' : 'gold'}>{({INFO:'提示',WARNING:'警告',ERROR:'错误',CRITICAL:'严重'} as Record<string,string>)[String(value)] || '未知级别'}</Tag> },
{ 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) => `${text(row.targetType)} · ${text(row.targetId)}` },
{ title: '时间', dataIndex: 'createdAt', key: 'createdAt', width: 190 },
{ title: '状态', dataIndex: 'status', key: 'status', width: 120 },
{ 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) => <><Tag color={value === 'RECOVERED' ? 'green' : 'orange'}>{monitorLabel(value)}</Tag>{value === 'OPEN' && row.silenced === true && <Tag>静默中</Tag>}</> },
];
const requestMetricColumns: ColumnsType<Row> = [
{ title: '路由', dataIndex: 'routePattern', key: 'routePattern', fixed: 'left', width: 280 },
@@ -575,15 +587,15 @@ export function OperationsMonitorPanel({ user, onUnauthorized }: { user: AuthUse
{ 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 },
{ title: '最近请求', dataIndex: 'lastSeen', key: 'lastSeen', width: 190, render: value => configurationDateTime(value) || '—' },
];
return <>
<section className="panel section-panel governance-monitor">
<div className="completion-panel-heading"><div><strong>运行指标、平台内告警与巡检</strong><span>只读取并更新服务端运行状态;不发送外部通知</span></div><div className="completion-actions"><Button icon={<ReloadOutlined />} loading={loading} onClick={() => void load()}>刷新</Button>{canRefresh && <><Button onClick={() => void editPolicy()} disabled={!alertPolicy}>告警阈值</Button><Button type="primary" loading={refreshing} onClick={() => void refresh()}>执行巡检</Button></>}</div></div>
<div className="completion-panel-heading"><div><strong>运行监控与告警</strong><span>只读取并更新服务端运行状态;不发送外部通知</span></div><div className="completion-actions"><Button icon={<ReloadOutlined />} loading={loading} onClick={() => void load()}>刷新</Button>{canRefresh && <><Button onClick={() => void editPolicy()} disabled={!alertPolicy}>告警阈值</Button><Button type="primary" loading={refreshing} onClick={() => void refresh()}>系统健康检查</Button></>}</div></div>
{error && <Alert showIcon type="error" message="运行监控暂不可用" description={error} />}
{policyError && <Alert showIcon type="error" message="告警策略不可用" description={policyError} />}
{loading ? <div className="completion-loading"><Spin />读取平台状态…</div> : <><div className="governance-monitor-grid">{summaryEntries.length ? summaryEntries.map(([key, value]) => <div key={key}><small>{key}</small><strong>{text(value)}</strong></div>) : <div className="completion-placeholder">服务端没有返回运行指标</div>}</div>{alertRows.length ? <Table size="small" bordered columns={alertColumns} dataSource={alertRows} rowKey={row => String(row.id || row.code)} pagination={{ pageSize: 10, showSizeChanger: false }} scroll={{ x: 1260 }} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前没有平台内告警" />}</>}
<h3>接口请求指标</h3><p className="completion-note">按路由聚合请求数、失败数与耗时;服务端不保存请求正文。</p>
{loading ? <div className="completion-loading"><Spin />读取平台状态…</div> : <><div className="governance-monitor-grid">{summaryEntries.length ? summaryEntries.map(([key, value]) => <div key={key}><small>{summaryLabels[key] || '其他指标'}</small><strong>{text(value)}</strong></div>) : <div className="completion-placeholder">服务端没有返回运行指标</div>}</div><Tabs activeKey={alertStatus} onChange={setAlertStatus} items={[{key:'OPEN',label:`当前告警(${alertsForStatus(allAlerts,'OPEN').length})`},{key:'RECOVERED',label:`已恢复(${alertsForStatus(allAlerts,'RECOVERED').length})`}]}/>{alertRows.length ? <Table size="small" bordered columns={alertColumns} dataSource={alertRows} rowKey={row => String(row.id || row.code)} pagination={{ pageSize: 10, showSizeChanger: false }} scroll={{ x: 1260 }} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={alertStatus === 'OPEN' ? '当前没有未恢复告警' : '暂无已恢复告警'} />}</>}
<h3>接口请求指标</h3><p className="completion-note">累计请求数、失败数与耗时;最近请求时间不代表统计起点。</p>
{loading ? <div className="completion-loading"><Spin />读取接口指标…</div> : requestMetricRows.length ? <Table size="small" bordered columns={requestMetricColumns} dataSource={requestMetricRows} rowKey={row => `${text(row.routePattern)}-${text(row.method)}`} pagination={{ pageSize: 12, showSizeChanger: false }} scroll={{ x: 1200 }} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="服务端尚未记录接口请求指标" />}
<Modal className="management-modal" open={policyOpen} title="告警阈值与静默策略" okText="保存策略" confirmLoading={policyBusy} onCancel={() => setPolicyOpen(false)} onOk={() => void savePolicy()}><Form form={policyForm} layout="vertical"><div className="governance-form-grid"><Form.Item name="queueAgeMinutes" label="队列告警(分钟)" rules={[{ required: true }]}><InputNumber min={1} max={1440} /></Form.Item><Form.Item name="diskFreeBytes" label="最低可用磁盘空间(字节)" rules={[{ required: true }]}><InputNumber min={104857600} max={1125899906842624} style={{ width: '100%' }} /></Form.Item><Form.Item name="backupAgeHours" label="备份超时(小时)" rules={[{ required: true }]}><InputNumber min={1} max={720} /></Form.Item><Form.Item name="quietPeriodMinutes" label="重复告警静默(分钟)" rules={[{ required: true }]}><InputNumber min={0} max={10080} /></Form.Item><Form.Item name="slowRequestMillis" label="慢请求阈值(毫秒)" rules={[{ required: true }]}><InputNumber min={100} max={120000} /></Form.Item><Form.Item name="silenceUntil" label="临时静默截止(ISO,可选)"><Input placeholder="2026-10-21T09:00:00Z" /></Form.Item></div><Form.Item name="severityOverrides" label="告警严重度覆盖(JSON)" rules={[{ required: true }]}><Input.TextArea rows={5} spellCheck={false} /></Form.Item><Form.Item name="reason" label="修改原因" rules={[{ required: true, whitespace: true }]}><Input.TextArea rows={2} /></Form.Item><p className="completion-note">保存后按新策略检查;严重度 key 只能使用服务端列出的告警类型。</p></Form></Modal>
</section>
@@ -692,32 +704,68 @@ export function UserAccessPolicyPanel({ onUnauthorized }: { onUnauthorized: (err
const [saving, setSaving] = useState(false);
const [error, setError] = useState('');
const [form] = Form.useForm<Row>();
const selectedUser = useRef<string | undefined>(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);
try { const result = await api.userAccessPolicy(id); const value = obj(result.policy || result); 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)) setError(value instanceof Error ? value.message : '访问策略读取失败'); }
finally { setLoading(false); }
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(() => {
api.users().then(value => setUsers(collectionItems(value))).catch(errorValue => { if (!onUnauthorized(errorValue)) setError(errorValue instanceof Error ? errorValue.message : '用户列表读取失败'); });
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 () => {
if (!userId || !policy) return;
try { const value = await form.validateFields(); setSaving(true); const allowedFields = String(value.allowedFields || '').split(/[\n,,]/).map(item => item.trim()).filter(Boolean); await api.updateUserAccessPolicy(userId, { 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) }); message.success('明细、证据及组织范围策略已更新'); await load(userId); }
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 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') => {
if (!userId) return; setPreviewBusy(true);
try { const result = kind === 'effective' ? await api.effectiveUserAccess(userId) : await api.userScopePreview(userId); if (kind === 'effective') setEffective(result); else setScopePreview(result); }
catch (value) { if (!onUnauthorized(value)) message.error(value instanceof Error ? value.message : '用户有效授权读取失败'); }
finally { setPreviewBusy(false); }
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 <div className="governance-panel-body"><div className="completion-panel-heading"><div><strong>用户明细与证据访问策略</strong><span>明细、原文件下载与字段授权由服务端二次校验</span></div><div className="completion-actions"><Button disabled={!userId} loading={previewBusy} onClick={() => void preview('effective')}>预览有效授权</Button><Button disabled={!userId} loading={previewBusy} onClick={() => void preview('scope')}>预览授权行数</Button></div></div><div className="governance-policy-select"><Select showSearch optionFilterProp="label" placeholder="选择用户" value={userId} options={userOptions} onChange={value => { setUserId(value); setEffective(null); setScopePreview(null); }} /></div>{error && <Alert showIcon type="error" message="访问策略不可用" description={error} />}{loading ? <div className="completion-loading"><Spin />读取访问策略…</div> : policy && <Form form={form} layout="vertical" className="governance-policy-form"><div className="governance-form-grid"><Form.Item name="detailAllowed" label="允许读取来源明细" valuePropName="checked"><Switch /></Form.Item><Form.Item name="evidenceAllowed" label="允许查看来源变更证据" valuePropName="checked"><Switch /></Form.Item><Form.Item name="originalDownloadAllowed" label="允许下载原始文件" valuePropName="checked"><Switch /></Form.Item><Form.Item name="inheritDepartmentChildren" label="继承下级产业部范围" valuePropName="checked"><Switch /></Form.Item><Form.Item name="validUntil" label="授权有效截止时间(ISO,可选)"><Input placeholder="2026-12-31T23:59:59Z" /></Form.Item></div><Form.Item name="allowedFields" label="允许字段(每行一个;* 表示全部已授权字段)"><Input.TextArea rows={5} spellCheck={false} /></Form.Item><Form.Item name="reason" label="修改原因" rules={[{ required: true, whitespace: true }]}><Input.TextArea rows={2} maxLength={300} /></Form.Item><Button type="primary" loading={saving} onClick={() => void save()}>保存访问策略</Button><p className="completion-note">空字段集合将由服务端按其默认策略处理。</p></Form>}{effective && <section className="completion-insight-card"><div className="completion-card-heading"><strong>服务端有效授权</strong><Tag color={effective.authorizationEffective === true ? 'green' : 'red'}>{effective.authorizationEffective === true ? '有效' : '未生效'}</Tag></div><p>用户 {text(effective.userId)} · 身份 {effective.active === true ? '启用' : '停用'} · 数据范围已由服务端核验</p><p>角色:{Array.isArray(effective.roles) ? (effective.roles as unknown[]).map(String).join('、') : '—'}</p><p>原始授权产业部:{grantedDepartments} · 有效产业部:{effectiveDepartments}</p><p>业务分组:{Array.isArray(effective.groups) ? (effective.groups as unknown[]).map(String).join('、') : '—'}</p><p>动作:{Array.isArray(effective.allowedActions) ? (effective.allowedActions as unknown[]).map(String).join('、') : '—'}</p><p>字段策略:{JSON.stringify(withoutSystemMetadata(effective.fieldPolicy ?? {}))}</p>{hierarchyRows.length > 0 && <p>层级展开依据:当前映射配置</p>}</section>}{scopePreview && <section className="completion-insight-card"><div className="completion-card-heading"><strong>授权范围行数</strong><Tag>{scopePreview.dataReturned === false ? '仅计数,未返回数据' : '服务端返回状态'}</Tag></div><p>原始授权产业部:{Array.isArray(scopePreview.grantedDepartments) ? (scopePreview.grantedDepartments as unknown[]).map(String).join('、') : '—'} · 有效产业部:{Array.isArray(scopePreview.departments) ? (scopePreview.departments as unknown[]).map(String).join('、') : '—'}</p>{rows(scopePreview.hierarchySource).length > 0 && <p>层级依据:当前映射配置</p>}{scopeCounts.length ? <Table size="small" bordered dataSource={scopeCounts} rowKey={row => 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' }]} /> : <Empty description="服务端没有返回授权计数" />}</section>}{!userId && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="选择用户后查看并编辑其访问范围" />}</div>;
return <div className="governance-panel-body"><div className="completion-panel-heading"><div><strong>用户明细与证据访问策略</strong><span>明细、原文件下载与字段授权由服务端二次校验</span></div><div className="completion-actions"><Button disabled={!userId || loading || saving || previewBusy} loading={previewBusy} onClick={() => void preview('effective')}>预览有效授权</Button><Button disabled={!userId || loading || saving || previewBusy} loading={previewBusy} onClick={() => void preview('scope')}>预览授权行数</Button></div></div><div className="governance-policy-select"><Select disabled={saving} showSearch optionFilterProp="label" placeholder="选择用户" value={userId} options={userOptions} onChange={selectUser} /></div>{error && <Alert showIcon type="error" message="访问策略不可用" description={error} />}{loading ? <div className="completion-loading"><Spin />读取访问策略…</div> : policy && policy.userId === userId && <Form form={form} disabled={saving} layout="vertical" className="governance-policy-form"><div className="governance-form-grid"><Form.Item name="detailAllowed" label="允许读取来源明细" valuePropName="checked"><Switch /></Form.Item><Form.Item name="evidenceAllowed" label="允许查看来源变更证据" valuePropName="checked"><Switch /></Form.Item><Form.Item name="originalDownloadAllowed" label="允许下载原始文件" valuePropName="checked"><Switch /></Form.Item><Form.Item name="inheritDepartmentChildren" label="继承下级产业部范围" valuePropName="checked"><Switch /></Form.Item><Form.Item name="validUntil" label="授权有效截止时间(ISO,可选)"><Input placeholder="2026-12-31T23:59:59Z" /></Form.Item></div><Form.Item name="allowedFields" label="允许字段(每行一个;* 表示全部已授权字段)"><Input.TextArea rows={5} spellCheck={false} /></Form.Item><Form.Item name="reason" label="修改原因" rules={[{ required: true, whitespace: true }]}><Input.TextArea rows={2} maxLength={300} /></Form.Item><Button type="primary" disabled={loading || policy?.userId !== userId} loading={saving} onClick={() => void save()}>保存访问策略</Button><p className="completion-note">空字段集合将由服务端按其默认策略处理。</p></Form>}{effective && <section className="completion-insight-card"><div className="completion-card-heading"><strong>服务端有效授权</strong><Tag color={effective.authorizationEffective === true ? 'green' : 'red'}>{effective.authorizationEffective === true ? '有效' : '未生效'}</Tag></div><p>用户 {text(effective.userId)} · 身份 {effective.active === true ? '启用' : '停用'} · 数据范围已由服务端核验</p><p>角色:{Array.isArray(effective.roles) ? (effective.roles as unknown[]).map(String).join('、') : '—'}</p><p>原始授权产业部:{grantedDepartments} · 有效产业部:{effectiveDepartments}</p><p>业务分组:{Array.isArray(effective.groups) ? (effective.groups as unknown[]).map(String).join('、') : '—'}</p><p>动作:{Array.isArray(effective.allowedActions) ? (effective.allowedActions as unknown[]).map(String).join('、') : '—'}</p><p>字段策略:{JSON.stringify(withoutSystemMetadata(effective.fieldPolicy ?? {}))}</p>{hierarchyRows.length > 0 && <p>层级展开依据:当前映射配置</p>}</section>}{scopePreview && <section className="completion-insight-card"><div className="completion-card-heading"><strong>授权范围行数</strong><Tag>{scopePreview.dataReturned === false ? '仅计数,未返回数据' : '服务端返回状态'}</Tag></div><p>原始授权产业部:{Array.isArray(scopePreview.grantedDepartments) ? (scopePreview.grantedDepartments as unknown[]).map(String).join('、') : '—'} · 有效产业部:{Array.isArray(scopePreview.departments) ? (scopePreview.departments as unknown[]).map(String).join('、') : '—'}</p>{rows(scopePreview.hierarchySource).length > 0 && <p>层级依据:当前映射配置</p>}{scopeCounts.length ? <Table size="small" bordered dataSource={scopeCounts} rowKey={row => 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' }]} /> : <Empty description="服务端没有返回授权计数" />}</section>}{!userId && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="选择用户后查看并编辑其访问范围" />}</div>;
}