Files
quality_analyse/web/src/GovernanceCompletion.tsx
T

724 lines
89 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { useEffect, 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<string, unknown>;
const TABLE_PAGE_SIZE = 20;
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, string>)[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 ? <Alert showIcon type="error" message={title} description={error} action={<Button size="small" onClick={onRetry}>重试</Button>} /> : 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<Row[]>([]);
const [releaseId, setReleaseId] = useState('');
const [runs, setRuns] = useState<Row[]>([]);
const [loading, setLoading] = useState(false);
const [running, setRunning] = useState(false);
const [saving, setSaving] = useState(false);
const [error, setError] = useState('');
const [selectedRun, setSelectedRun] = useState<Row | null>(null);
const [editing, setEditing] = useState<Row | null>(null);
const [form] = Form.useForm<Row>();
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<Row> = [
{ title: '策略名称', dataIndex: 'name', key: 'name', fixed: 'left', width: 220 },
{ title: '状态', dataIndex: 'active', key: 'active', width: 100, render: value => <Tag color={value === true ? 'green' : 'default'}>{value === true ? '启用' : '停用'}</Tag> },
{ 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) => <Button type="link" loading={saving} onClick={() => void openEditor(row)}>编辑</Button> } as ColumnsType<Row>[number]] : []),
];
const runColumns: ColumnsType<Row> = [
{ title: '巡检时间', dataIndex: 'createdAt', key: 'createdAt', width: 190 },
{ title: '策略', dataIndex: 'strategyName', key: 'strategyName', width: 200 },
{ title: '状态', dataIndex: 'status', key: 'status', width: 125, render: value => <Tag color={String(value).toUpperCase().includes('FAIL') ? 'red' : 'blue'}>{text(value)}</Tag> },
{ 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) => <Button type="link" onClick={() => setSelectedRun(row)}>查看结果</Button> },
];
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, string>)[String(value)] || text(value);
const severityLabel = (value: unknown) => ({ HIGH: '高', MEDIUM: '中', LOW: '低' } as Record<string, string>)[String(value)] || text(value);
const findingColumns: ColumnsType<Row> = [
{ 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 => <Tag color={String(value).toUpperCase() === 'HIGH' ? 'red' : 'gold'}>{severityLabel(value)}</Tag> },
{ title: '发现说明', dataIndex: 'summary', key: 'summary', width: 420 },
];
const ruleColumns: ColumnsType<Row> = [
{ title: '检查规则', dataIndex: 'id', key: 'id', width: 190 },
{ title: '状态', dataIndex: 'status', key: 'status', width: 140, render: value => <Tag color={String(value).toUpperCase() === 'AVAILABLE' ? 'green' : String(value).toUpperCase() === 'UNAVAILABLE' ? 'gold' : 'default'}>{String(value).toUpperCase() === 'AVAILABLE' ? '可检查' : String(value).toUpperCase() === 'UNAVAILABLE' ? '数据不足' : String(value).toUpperCase() === 'NO_FINDINGS' ? '未发现异常' : String(value).toUpperCase() === 'DISABLED' ? '已关闭' : text(value)}</Tag> },
{ title: '发现数', dataIndex: 'findingCount', key: 'findingCount', width: 95, align: 'right' },
{ title: '未具备数据 / 原因', dataIndex: 'reason', key: 'reason', width: 440 },
];
const aiFindingRows = rows(drilldown.findings);
const aiFindingColumns: ColumnsType<Row> = [
{ 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 <section className="panel section-panel completion-tools">
<div className="completion-panel-heading"><div><strong>质量巡检策略与运行记录</strong><span>策略阈值由服务端执行;运行结果受当前用户数据权限约束</span></div><div className="completion-actions"><Button icon={<ReloadOutlined />} onClick={() => { void load(); void loadRuns(); }}>刷新</Button>{canManage && <Button onClick={() => void openEditor()}>新建策略</Button>}</div></div>
{!canManage && <Alert showIcon type="info" message="当前账号无巡检策略维护权限" description="服务端仅向授权角色返回可管理策略。" />}
{error && <ErrorPanel title="巡检数据读取或执行失败" error={error} onRetry={() => { void load(); void loadRuns(); }} />}
{loading ? <div className="completion-loading"><Spin />读取巡检策略…</div> : canManage ? strategies.length ? <Table size="small" bordered columns={strategyColumns} dataSource={strategies} rowKey={row => String(row.id)} pagination={false} scroll={{ x: 1300 }} /> : <Empty description="服务端当前没有已登记的巡检策略" /> : null}
<div className="completion-filter-row">{canRun && <Button type="primary" loading={running} disabled={!releaseId} onClick={() => void run()}>对当前数据执行巡检</Button>}</div>
{!canRun && <Alert showIcon type="info" message="当前账号不能执行巡检" description="运行和结果查看需要服务端授权的质量查看或业务分析角色及明细查询权限。" />}
{canRun && (runs.length ? <Table size="small" bordered columns={runColumns} dataSource={runs} rowKey={row => String(row.id)} pagination={{ pageSize: 8, showSizeChanger: false }} scroll={{ x: 1120 }} /> : <Empty description={releaseId ? '当前数据尚无巡检运行记录' : '当前还没有可巡检的数据'} />)}
<Modal className="management-modal" open={editing !== null} title={editing?.id ? `编辑巡检策略 · ${text(editing.name)}` : '新建巡检策略'} okText="保存策略" confirmLoading={saving} onCancel={() => { setEditing(null); form.resetFields(); }} onOk={() => void save()} width={Math.min(820, window.innerWidth - 24)}>
<Form form={form} layout="vertical"><Form.Item name="name" label="策略名称" rules={[{ required: true, whitespace: true }]}><Input maxLength={100} /></Form.Item><Form.Item name="active" label="启用策略" valuePropName="checked"><Switch checkedChildren="启用" unCheckedChildren="停用" /></Form.Item><h3>巡检规则</h3><div className="governance-form-grid">{booleanFields.map(([key, label]) => <Form.Item key={key} name={key} label={label} valuePropName="checked"><Switch /></Form.Item>)}{metricFields.map(field => <Form.Item key={field.key} name={field.key} label={field.label} rules={[{ required: true }]}><InputNumber min={field.min} max={field.max} step={field.step} style={{ width: '100%' }} /></Form.Item>)}</div><p className="completion-note">阈值范围由服务端校验;保存后对后续巡检生效。</p></Form><Alert showIcon type="info" message="受控 AI 下钻" description="启用后仅为巡检发现创建绑定当前用户、当前数据与授权范围的持久化分析轮次;模型不接收业务数据行或业务数值。最多选择 1–3 项。" />
</Modal>
<Drawer className="management-drawer" open={selectedRun !== null} title="巡检运行结果" width={Math.min(820, window.innerWidth)} onClose={() => setSelectedRun(null)}>{selectedRun && <><div className="governance-monitor-grid"><div><small>状态</small><strong>{text(selectedRun.status)}</strong></div><div><small>适用数据</small><strong>当前数据</strong></div><div><small>创建时间</small><strong>{text(selectedRun.createdAt)}</strong></div><div><small>完成时间</small><strong>{text(selectedRun.completedAt)}</strong></div></div>{selectedRun.error && <Alert showIcon type="error" message={text(selectedRun.errorCode, '巡检错误')} description={text(selectedRun.error)} />}{selectedRun.result === undefined ? <Alert showIcon type="warning" message="结果字段未返回" description="当前账号可能没有完整明细权限,或服务端运行尚未产出结果。" /> : <>
<p className="completion-note">确定性结果:{selectedResult.deterministic === true ? '是' : selectedResult.deterministic === false ? '否' : '—'}</p>
<h3>巡检发现项({findingRows.length})</h3>
{findingRows.length ? <Table size="small" bordered dataSource={findingRows} rowKey={(row, index) => `${text(row.type)}-${text(row.subject)}-${index}`} pagination={false} columns={findingColumns} expandable={{ expandedRowRender: row => <><p>{text(row.summary)}</p><details><summary>查看核查依据</summary><pre className="json-result">{JSON.stringify(withoutSystemMetadata(row.evidence || {}), null, 2)}</pre></details></> }} scroll={{ x: 900 }} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="本次没有触发已配置巡检规则的发现项" />}
<h3>规则覆盖与未满足条件</h3>
{ruleRows.length ? <Table size="small" bordered dataSource={ruleRows} rowKey={(row, index) => `${text(row.id)}-${index}`} pagination={false} columns={ruleColumns} scroll={{ x: 870 }} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="服务端没有返回规则覆盖结果" />}
<h3>来源覆盖</h3>
<div className="governance-monitor-grid"><div><small>原始行</small><strong>{text(coverage.rawRows)}</strong></div><div><small>纳入计算</small><strong>{text(coverage.includedRows)}</strong></div><div><small>未分类排除</small><strong>{text(coverage.excludedBlankRows)}</strong></div><div><small>未映射行</small><strong>{text(coverage.unmappedRows)}</strong></div><div><small>项目组未配置</small><strong>{text(coverage.projectGroupUnconfiguredRows)}</strong></div></div>
{missingStageRows.length > 0 && <><h4>缺少阶段来源</h4><Table size="small" bordered dataSource={missingStageRows} rowKey={(row, index) => `${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 && <><h4>月度来源覆盖</h4><Table size="small" bordered dataSource={sourceMonthRows} rowKey={(row, index) => `${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 }} /></>}
<h3>受控 AI 下钻</h3>
<div className="inspection-ai-summary"><Tag color={['COMPLETED'].includes(String(drilldown.status || selectedResult.aiDrilldownStatus).toUpperCase()) ? 'green' : ['FAILED', 'BLOCKED_AUTHORIZATION'].includes(String(drilldown.status || selectedResult.aiDrilldownStatus).toUpperCase()) ? 'red' : 'blue'}>{drilldownStatusText(drilldown.status || selectedResult.aiDrilldownStatus)}</Tag><span>{text(selectedResult.aiDrilldownQuestion, '基于巡检时的当前数据与服务端受控查询执行。')}</span>{sessionIdForLink && turnIdForLink && <Button type="link" href={analysisDeepLink(sessionIdForLink, turnIdForLink)}>在智能分析中继续查看</Button>}</div>
{aiFindingRows.length > 0 && <Table size="small" bordered dataSource={aiFindingRows} rowKey={(row, index) => `${text(row.type)}-${text(row.subject)}-${index}`} pagination={false} columns={aiFindingColumns} scroll={{ x: 620 }} />}
<details><summary>查看其他运行信息</summary><pre className="json-result">{JSON.stringify(withoutSystemMetadata(selectedResult), null, 2)}</pre></details>
</>}</>}</Drawer>
</section>;
}
export function SourceGovernancePanel({ user, currentReleaseId, onUnauthorized }: { user: AuthUser; currentReleaseId: string | null; onUnauthorized: (error: unknown) => boolean }) {
const { message } = App.useApp();
const [protocols, setProtocols] = useState<Row[]>([]);
const [coverage, setCoverage] = useState<Row | null>(null);
const [sourceChanges, setSourceChanges] = useState<Row[]>([]);
const [sourceItems, setSourceItems] = useState<SourceItem[]>([]);
const [documents, setDocuments] = useState<Row[]>([]);
const [revisions, setRevisions] = useState<Row[]>([]);
const [loading, setLoading] = useState(false);
const [errors, setErrors] = useState<Record<string, string>>({});
const [protocolOpen, setProtocolOpen] = useState(false);
const [changeOpen, setChangeOpen] = useState(false);
const [reviewItem, setReviewItem] = useState<Row | null>(null);
const [resolveItem, setResolveItem] = useState<SourceItem | null>(null);
const [evidenceRevision, setEvidenceRevision] = useState('');
const [evidence, setEvidence] = useState<Row | null>(null);
const [actionBusy, setActionBusy] = useState('');
const [protocolForm] = Form.useForm<Row>();
const [changeForm] = Form.useForm<Row>();
const [reviewForm] = Form.useForm<{ reason: string }>();
const [resolveForm] = Form.useForm<Row>();
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<string, string> = {};
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<Row> = [
{ 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 => <Tag color={value === 'VALIDATED' ? 'green' : value === 'MISSING' ? 'red' : 'blue'}>{text(value)}</Tag> },
{ title: '告警', key: 'alert', width: 120, render: (_, row) => row.blocking === true ? <Tag color="red">阻断</Tag> : row.overdue === true ? <Tag color="gold">逾期</Tag> : '—' },
];
const protocolColumns: ColumnsType<Row> = [
{ 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<Row> = [
{ 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 => <Tag>{text(value)}</Tag> },
{ title: '候选结果', key: 'result', width: 150, render: (_, row) => row.resultReleaseId ? '已生成候选' : row.importRunId ? '处理中' : '—' },
{ title: '操作', key: 'actions', fixed: 'right', width: 220, render: (_, row) => <span className="completion-actions">
{canReview && row.status === 'REQUESTED' && <Button type="link" onClick={() => { setReviewItem(row); reviewForm.resetFields(); }}>复核</Button>}
{canReview && row.status === 'APPROVED' && <Button type="link" loading={actionBusy === String(row.id)} onClick={() => void buildChange(row)}>构建候选</Button>}
</span> },
];
const revisionColumns: ColumnsType<Row> = [
{ 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 <span className="completion-actions"><Button type="link" disabled={!id} onClick={() => void showEvidence(id)}>查看证据</Button>{canDownload && <Button type="link" icon={<DownloadOutlined />} loading={actionBusy === id} disabled={!id} onClick={() => void download(id)}>下载原文件</Button>}</span>;
} },
];
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 <section className="panel section-panel governance-source-panel">
<div className="completion-panel-heading"><div><strong>来源协议、覆盖与变更</strong><span>当前数据的来源覆盖、到齐状态和原文件下载权限由服务端控制</span></div><div className="completion-actions"><Button icon={<ReloadOutlined />} loading={loading} onClick={() => void load()}>刷新治理信息</Button>{canMaintain && <><Button onClick={() => { protocolForm.setFieldsValue({ stage: 'black', year: new Date().getFullYear(), month: 1, scopeCode: 'ALL', shardCode: 'MAIN', sourceMode: 'MONTHLY_SNAPSHOT', filenamePattern: '*.xlsx', applicable: true, expected: true }); setProtocolOpen(true); }}>登记来源协议</Button><Button type="primary" onClick={() => { changeForm.setFieldsValue({ type: 'REVISION' }); setChangeOpen(true); }}>申请来源变更 / 撤销</Button></>}</div></div>
<ErrorPanel title="协议读取失败" error={errors.protocols || ''} onRetry={() => void load()} /><ErrorPanel title="到齐矩阵读取失败" error={errors.coverage || ''} onRetry={() => void load()} /><ErrorPanel title="来源记录读取失败" error={errors.documents || ''} onRetry={() => void load()} />
<Tabs activeKey={tab} onChange={setTab} items={[
{ key: 'coverage', label: '到齐与告警', children: <div className="governance-panel-body"><div className="governance-status-strip"><span>适用数据 <strong>当前数据</strong></span><Tag color={coverage?.complete === true ? 'green' : 'red'}>{coverage?.complete === true ? '覆盖完整' : coverage?.complete === false ? '覆盖未齐' : '未返回'}</Tag></div>{coverageItems.length ? <Table size="small" bordered columns={coverageColumns} dataSource={coverageItems} rowKey={row => String(row.protocolId || row.sourceSlot)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 980 }} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前数据没有已登记的来源协议覆盖项" />}</div> },
{ key: 'protocols', label: `来源协议(${protocols.length})`, children: <div className="governance-panel-body">{protocols.length ? <Table size="small" bordered columns={protocolColumns} dataSource={protocols} rowKey={row => String(row.id)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1120 }} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="服务端尚未登记来源协议" />}</div> },
{ key: 'changes', label: `来源变更与撤销(${sourceChanges.length})`, children: <div className="governance-panel-body">{conflictCandidates.length > 0 && <Alert showIcon type="warning" message={`${conflictCandidates.length} 个来源身份待裁决`} description={<span>{conflictCandidates.map(item => <Button type="link" key={item.id} onClick={() => { setResolveItem(item); resolveForm.setFieldsValue({ decision: 'REPLACE' }); }}>{item.sourceFile} · 裁决</Button>)}</span>} />}{errors.changes ? <Alert type="error" message={errors.changes} /> : sourceChanges.length ? <Table size="small" bordered columns={changeColumns} dataSource={sourceChanges} rowKey={row => String(row.id)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1080 }} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="暂无来源变更或撤销申请" />}</div> },
{ key: 'revisions', label: `原文件记录与证据(${revisions.length})`, children: <div className="governance-panel-body">{revisions.length ? <Table size="small" bordered columns={revisionColumns} dataSource={revisions} rowKey={row => String(row.id)} pagination={{ pageSize: 10, showSizeChanger: false }} scroll={{ x: 1280 }} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="服务端尚未返回归档原文件记录" />}</div> },
]} />
<Modal className="management-modal" open={protocolOpen} title="登记来源协议" width={760} okText="保存协议" confirmLoading={actionBusy === 'protocol'} onCancel={() => setProtocolOpen(false)} onOk={() => void submitProtocol()}>
<Alert showIcon type="info" message="协议定义用于来源身份和到齐校验" description="当前解析器仅验证月度快照和分片快照;来源槽位由阶段、期间、范围和分片共同确定。" />
<Form form={protocolForm} layout="vertical"><div className="governance-form-grid"><Form.Item name="stage" label="阶段" rules={[{ required: true }]}><Select options={[{ label: '黑片', value: 'black' }, { label: '亮片', value: 'bright' }]} /></Form.Item><Form.Item name="year" label="年份" rules={[{ required: true }]}><InputNumber min={1900} max={2100} /></Form.Item><Form.Item name="month" label="月份" rules={[{ required: true }]}><InputNumber min={1} max={12} /></Form.Item><Form.Item name="scopeCode" label="范围编码" rules={[{ required: true, whitespace: true }]}><Input placeholder="如 ALL 或部门编码" /></Form.Item><Form.Item name="shardCode" label="分片编码"><Input placeholder="MAIN" /></Form.Item><Form.Item name="sourceMode" label="来源模式" rules={[{ required: true }]}><Select options={[{ label: '月度完整快照', value: 'MONTHLY_SNAPSHOT' }, { label: '完整分片快照', value: 'SHARD_SNAPSHOT' }]} /></Form.Item><Form.Item name="filenamePattern" label="文件名规则" rules={[{ required: true }]}><Input placeholder="*.xlsx" /></Form.Item><Form.Item name="sourceSlot" label="来源槽位(可选)"><Input placeholder="留空由服务端按身份生成" /></Form.Item><Form.Item name="deadline" label="到齐截止时间(ISO,可选)"><Input placeholder="2026-11-05T17:00:00Z" /></Form.Item></div><Form.Item name="applicable" valuePropName="checked"><Checkbox>该阶段适用</Checkbox></Form.Item><Form.Item name="expected" valuePropName="checked"><Checkbox>列为预期到齐来源</Checkbox></Form.Item><Form.Item name="reason" label="登记原因" rules={[{ required: true, whitespace: true }]}><Input.TextArea rows={2} maxLength={300} /></Form.Item><small className="completion-note">解析工作表将使用已验证名称:{stage === 'black' ? '报废明细' : '明细'}。</small></Form>
</Modal>
<Modal className="management-modal" open={changeOpen} title="申请来源变更或撤销" okText="提交申请" confirmLoading={actionBusy === 'change'} onCancel={() => setChangeOpen(false)} onOk={() => void submitChange()}>
<Form form={changeForm} layout="vertical"><Form.Item name="type" label="申请类型" rules={[{ required: true }]}><Select options={[{ label: '替换/补录来源', value: 'REVISION' }, { label: '撤销当前来源', value: 'WITHDRAW' }]} /></Form.Item><Form.Item name="sourceDocumentId" label="当前已归档来源" rules={[{ required: true }]}><Select {...readableSelectPopup} showSearch optionFilterProp="label" options={documentChoices} placeholder="选择来源文档" /></Form.Item>{changeType === 'REVISION' && <Form.Item name="sourceCandidateId" label="待替换候选文件" rules={[{ required: true }]}><Select {...readableSelectPopup} showSearch optionFilterProp="label" options={candidateChoices} placeholder="选择已扫描或上传的候选文件" /></Form.Item>}<Form.Item name="reason" label="申请原因" rules={[{ required: true, whitespace: true }]}><Input.TextArea rows={3} maxLength={400} showCount /></Form.Item></Form>
</Modal>
<Modal className="management-modal" open={Boolean(reviewItem)} title="复核来源变更申请" okText="通过申请" confirmLoading={Boolean(actionBusy)} onCancel={() => setReviewItem(null)} onOk={() => void submitReview(true)} footer={(_, { OkBtn, CancelBtn }) => <><CancelBtn /><Button danger disabled={Boolean(actionBusy)} onClick={() => void submitReview(false)}>驳回申请</Button><OkBtn /></>}>
<p>类型:{text(reviewItem?.requestType)} · 来源:{text(documents.find(item => String(item.id) === String(reviewItem?.sourceDocumentId))?.sourceFile || reviewItem?.sourceSlot, '当前来源')}</p><p>申请原因:{text(reviewItem?.reason)}</p><Form form={reviewForm} layout="vertical"><Form.Item name="reason" label="审核理由" rules={[{ required: true, whitespace: true }]}><Input.TextArea rows={3} maxLength={400} /></Form.Item></Form>
</Modal>
<Modal className="management-modal" open={Boolean(resolveItem)} title="裁决来源身份与覆盖" okText="提交裁决" confirmLoading={Boolean(actionBusy)} onCancel={() => setResolveItem(null)} onOk={() => void resolveCandidate()}>
<p>候选文件:{resolveItem?.sourceFile} · 状态 {resolveItem?.status} · SHA-256 {resolveItem?.sha256}</p><Form form={resolveForm} layout="vertical"><Form.Item name="decision" label="处理方式" rules={[{ required: true }]}><Select options={[{ label: '替换同一来源', value: 'REPLACE' }, { label: '确认为合法分片', value: 'LEGAL_SHARD' }, { label: '退回候选', value: 'RETURN' }]} /></Form.Item>{resolveDecision !== 'RETURN' && <Form.Item name="protocolId" label="适用协议" rules={[{ required: true, message: '请选择协议' }]}><Select options={protocols.filter(item => item.active === true).map(item => ({ value: String(item.id), label: text(item.sourceSlot) }))} /></Form.Item>}<Form.Item name="reason" label="处理理由" rules={[{ required: true, whitespace: true }]}><Input.TextArea rows={3} maxLength={400} /></Form.Item></Form>
</Modal>
<Drawer className="management-drawer" open={Boolean(evidenceRevision)} title="原文件与处理证据" width={Math.min(850, window.innerWidth)} onClose={() => { setEvidenceRevision(''); setEvidence(null); }}>
{evidence ? <><div className="governance-evidence-summary"><strong>{text(obj(evidence.revision).sourceFile)}</strong><span>SHA-256 {text(obj(evidence.revision).sha256)}</span><span>归档状态 {text(obj(evidence.revision).status)}</span><span>接收时间 {text(obj(evidence.revision).receivedAt)}</span></div>{rows(evidence.builds).length ? <Table size="small" bordered dataSource={rows(evidence.builds)} rowKey={row => 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 }} /> : <Empty description="该来源尚未返回处理记录" />}{canDownload && <Button type="primary" icon={<DownloadOutlined />} loading={actionBusy === evidenceRevision} onClick={() => void download(evidenceRevision)}>下载受权原文件</Button>}</> : <div className="completion-loading"><Spin />读取来源记录…</div>}
</Drawer>
</section>;
}
export function CostConfigurationPanel({ user, onUnauthorized }: { user: AuthUser; onUnauthorized: (error: unknown) => boolean }) {
const { message } = App.useApp();
const [items, setItems] = useState<Row[]>([]);
const [loading, setLoading] = useState(true);
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const [editing, setEditing] = useState<Row | null>(null);
const [validation, setValidation] = useState<Row | null>(null);
const [form] = Form.useForm<Row>();
const canManage = user.roles.some(role => ['SYSTEM_ADMIN', 'DATA_MAINTAINER', 'RULE_MAINTAINER'].includes(role));
const load = async () => {
setLoading(true);
try { setItems(collectionItems(await api.costConfigurations())); setError(''); }
catch (value) { if (!onUnauthorized(value)) setError(value instanceof Error ? value.message : '成本来源配置读取失败'); }
finally { setLoading(false); }
};
useEffect(() => { void load(); }, []);
const open = (item?: Row) => {
setEditing(item || {}); setValidation(null);
const definition = obj(item?.definition);
form.setFieldsValue({ name: text(item?.name, ''), reason: '', sources: rows(definition.sources) });
};
const save = async () => {
try {
const values = await form.validateFields(); setBusy(true);
const body = { name: String(values.name || '').trim(), reason: String(values.reason || '').trim(), definition: { sources: values.sources || [] }, ...(editing?.id ? { expectedRowVersion: Number(editing.rowVersion || 0) } : {}) };
if (editing?.id) await api.updateCostConfiguration(String(editing.id), body); else await api.createCostConfiguration(body);
message.success('成本来源与公式基线已保存;未执行成本金额计算'); 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 validate = async (item: Row) => {
setBusy(true);
try { const result = await api.validateCostConfiguration(String(item.id), { expectedRowVersion: Number(item.rowVersion || 0) }); setValidation(obj(result.validation)); await load(); }
catch (value) { if (!onUnauthorized(value)) message.error(value instanceof ApiError && value.status === 409 ? '配置已被其他操作更新,请刷新后重试。' : value instanceof Error ? value.message : '来源配置校验失败'); }
finally { setBusy(false); }
};
const columns: ColumnsType<Row> = [
{ title: '配置名称', dataIndex: 'name', key: 'name', fixed: 'left', width: 220 },
{ title: '状态', dataIndex: 'status', key: 'status', width: 150, render: value => <Tag>{text(value)}</Tag> },
{ title: '来源数', key: 'sources', align: 'right', width: 90, render: (_, row) => rows(obj(row.definition).sources).length },
{ title: '操作', key: 'actions', width: 180, render: (_, row) => <span className="completion-actions"><Button type="link" disabled={!canManage || row.status !== 'DRAFT'} onClick={() => open(row)}>编辑</Button><Button type="link" loading={busy} onClick={() => void validate(row)}>校验</Button></span> },
];
return <section className="panel section-panel completion-tools">
<div className="completion-panel-heading"><div><strong>成本来源与计算基线登记</strong><span>仅记录来源字段、单位、审批引用与原公式;成本金额和降本计算保持关闭</span></div><div className="completion-actions"><Button icon={<ReloadOutlined />} onClick={() => void load()}>刷新</Button>{canManage && <Button type="primary" onClick={() => open()}>新建成本来源配置</Button>}</div></div>
{error && <Alert showIcon type="error" message="成本来源配置不可用" description={error} />}
{loading ? <div className="completion-loading"><Spin />读取成本来源配置…</div> : items.length ? <Table size="small" bordered columns={columns} dataSource={items} rowKey={row => String(row.id)} pagination={false} scroll={{ x: 740 }} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="服务端当前没有成本来源登记" />}
{validation && <Alert showIcon type={validation.valid === true ? 'success' : 'warning'} message={text(validation.readiness, validation.valid === true ? '来源字段已验证' : '来源信息需补充')} description={`错误 ${rows(validation.errors).length} 项 · 成本金额计算:${validation.calculationEnabled === false ? '未启用' : '未由服务端确认'}`} />}
<Modal className="management-modal" open={Boolean(editing)} title={editing?.id ? '编辑成本来源配置' : '登记成本来源配置'} width={900} okText="保存配置" confirmLoading={busy} onCancel={() => setEditing(null)} onOk={() => void save()}>
<Alert showIcon type="info" message="成本核算未启用" description="此表单只登记依赖和原公式,不接受成本金额,不生成成本或降本结论。" />
<Form form={form} layout="vertical"><Form.Item name="name" label="配置名称" rules={[{ required: true, whitespace: true }]}><Input maxLength={180} /></Form.Item><Form.List name="sources">{(fields, { add, remove }) => <div className="target-rule-list"><div className="resource-toolbar"><strong>成本来源字段映射</strong><Button onClick={() => add({ unit: 'CNY/kg' })}>添加来源</Button></div>{fields.map(field => <div className="target-rule-row" key={field.key}><Form.Item {...field} name={[field.name, 'sourceReference']} label="来源引用" rules={[{ required: true, whitespace: true }]}><Input /></Form.Item><Form.Item {...field} name={[field.name, 'objectCode']} label="对象编码" rules={[{ required: true, whitespace: true }]}><Input /></Form.Item><Form.Item {...field} name={[field.name, 'costField']} label="成本字段" rules={[{ required: true, whitespace: true }]}><Input /></Form.Item><Form.Item {...field} name={[field.name, 'unit']} label="单位" rules={[{ required: true, whitespace: true }]}><Input /></Form.Item><Form.Item {...field} name={[field.name, 'currency']} label="币种"><Input placeholder="CNY" /></Form.Item><Form.Item {...field} name={[field.name, 'approvalReference']} label="审批引用"><Input /></Form.Item><Form.Item {...field} name={[field.name, 'originalFormula']} label="原公式"><Input /></Form.Item><Form.Item {...field} name={[field.name, 'fromMonth']} label="起始月 YYYY-MM"><Input /></Form.Item><Form.Item {...field} name={[field.name, 'toMonth']} label="结束月 YYYY-MM"><Input /></Form.Item><Button danger onClick={() => remove(field.name)}>移除</Button></div>)}</div>}</Form.List><Form.Item name="reason" label="登记原因" rules={[{ required: true, whitespace: true }]}><Input.TextArea rows={2} maxLength={300} /></Form.Item></Form>
</Modal>
</section>;
}
export function BackupOperationsPanel({ user, onUnauthorized, onNavigate }: { user: AuthUser; onUnauthorized: (error: unknown) => boolean; onNavigate?: () => void }) {
const { message } = App.useApp();
const [data, setData] = useState<Row | null>(null);
const [loading, setLoading] = useState(true);
const [busy, setBusy] = useState(false);
const [error, setError] = useState('');
const [planOpen, setPlanOpen] = useState(false);
const [form] = Form.useForm<Row>();
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<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: 'restoreVerifiedAt', key: 'restoreVerifiedAt', width: 190 },
{ title: '还原用时', dataIndex: 'restoreElapsedSeconds', key: 'restoreElapsedSeconds', width: 110 },
{ 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">
<div className="completion-panel-heading"><div><strong>备份、恢复验证与计划</strong><span>恢复验证仅在隔离目录执行;当前不开放在线业务库覆盖恢复</span></div><div className="completion-actions"><Button icon={<ReloadOutlined />} onClick={() => void load()}>刷新</Button>{canManage && <><Button onClick={() => { form.setFieldsValue({ ...plan, reason: '' }); setPlanOpen(true); }}>备份计划</Button><Button type="primary" loading={busy} onClick={() => void runJob('BACKUP_CREATE_VERIFY')}>创建并验证备份</Button></>}</div></div>
{error && <Alert showIcon type="error" message="备份状态不可用" description={error} />}
{loading ? <div className="completion-loading"><Spin />读取备份与恢复状态…</div> : <><div className="governance-monitor-grid"><div><small>计划</small><strong>{plan.active === true ? '已启用' : plan.active === false ? '已停用' : '未配置'}</strong></div><div><small>周期 / RPO</small><strong>{text(plan.intervalHours)} 小时 / {text(plan.rpoHours)} 小时</strong></div><div><small>RTO</small><strong>{text(plan.rtoHours)} 小时</strong></div><div><small>在线恢复</small><strong>{obj(data).liveRestoreEnabled === true ? '开放' : '关闭'}</strong></div></div>{backups.length ? <Table size="small" bordered columns={columns} dataSource={backups} rowKey={row => String(row.id)} pagination={{ pageSize: 10, showSizeChanger: false }} scroll={{ x: 920 }} /> : <Empty description="服务端当前没有备份记录" />}</>}
{onNavigate && <Button type="link" onClick={onNavigate}>查看备份任务进度</Button>}
<Modal className="management-modal" open={planOpen} title="备份计划配置" okText="保存计划" confirmLoading={busy} onCancel={() => setPlanOpen(false)} onOk={() => void savePlan()}><Form form={form} layout="vertical"><Form.Item name="active" label="计划状态" valuePropName="checked"><Switch checkedChildren="启用" unCheckedChildren="停用" /></Form.Item><div className="governance-form-grid"><Form.Item name="intervalHours" label="备份周期(小时)" rules={[{ required: true }]}><InputNumber min={1} max={8760} /></Form.Item><Form.Item name="rpoHours" label="RPO(小时)" rules={[{ required: true }]}><InputNumber min={1} max={8760} /></Form.Item><Form.Item name="rtoHours" label="RTO(小时)" rules={[{ required: true }]}><InputNumber min={1} max={8760} /></Form.Item></div><Form.Item name="reason" label="修改原因" rules={[{ required: true, whitespace: true }]}><Input.TextArea rows={2} /></Form.Item></Form></Modal>
</section>;
}
export function OperationsMonitorPanel({ user, onUnauthorized }: { user: AuthUser; onUnauthorized: (error: unknown) => boolean }) {
const { message } = App.useApp();
const [data, setData] = useState<Row | null>(null);
const [loading, setLoading] = useState(true);
const [refreshing, setRefreshing] = useState(false);
const [error, setError] = useState('');
const [alertPolicy, setAlertPolicy] = useState<Row | null>(null);
const [policyOpen, setPolicyOpen] = useState(false);
const [policyBusy, setPolicyBusy] = useState(false);
const [policyError, setPolicyError] = useState('');
const [policyForm] = Form.useForm<Row>();
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 alertRows = rows(data?.alerts);
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: '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 },
];
const requestMetricColumns: ColumnsType<Row> = [
{ 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 },
];
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>
{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> : 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>
<InspectionStrategyPanel user={user} onUnauthorized={onUnauthorized} />
</>;
}
const ACTIONS_BY_TYPE: Record<string, string[]> = {
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<Row[]>([]);
const [allowedActions, setAllowedActions] = useState<string[]>([]);
const [serviceTypes, setServiceTypes] = useState<string[]>([]);
const [bindings, setBindings] = useState<Row[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState('');
const [editing, setEditing] = useState<Row | null>(null);
const [rotating, setRotating] = useState<Row | null>(null);
const [rotations, setRotations] = useState<Row[]>([]);
const [bindingEdit, setBindingEdit] = useState<{ type: string; identityId: string } | null>(null);
const [busy, setBusy] = useState(false);
const [form] = Form.useForm<Row>();
const [rotateForm] = Form.useForm<Row>();
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<Row> = [
{ 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) => <span className="object-cell"><strong>{text(row.credentialStatus)}</strong><small>{text(row.credentialReference, '未配置引用')}</small></span> },
{ title: '状态', dataIndex: 'active', key: 'active', width: 100, render: value => <Tag color={value === true ? 'green' : 'default'}>{value === true ? '启用' : '停用'}</Tag> },
{ title: '操作', key: 'action', fixed: 'right', width: 230, render: (_, row) => <span className="completion-actions">{canManage && <><Button type="link" onClick={() => open(row)}>编辑</Button><Button type="link" onClick={() => { setRotating(row); rotateForm.setFieldsValue({ credentialReference: text(row.credentialReference, ''), credentialStatus: text(row.credentialStatus, 'UNCONFIGURED'), reason: '' }); }}>轮换</Button></>}<Button type="link" onClick={async () => { try { setRotations(collectionItems(await api.serviceRotations(String(row.id)))); setRotating({ ...row, showRotations: true }); } catch (value) { if (!onUnauthorized(value)) message.error(value instanceof Error ? value.message : '轮换记录读取失败'); } }}>历史</Button></span> },
];
return <div className="governance-service-identities">
<section className="panel section-panel">
<div className="completion-panel-heading"><div><strong>服务身份与最小动作授权</strong><span>仅保存 env: 或 file: 凭据引用,不在浏览器或服务端表单中接收密钥文本</span></div><div className="completion-actions"><Button icon={<ReloadOutlined />} onClick={() => void load()}>刷新</Button>{canManage && <Button type="primary" onClick={() => open()}>新建服务身份</Button>}</div></div>
{error && <Alert showIcon type="error" message="服务身份管理不可用" description={error} />}
{loading ? <div className="completion-loading"><Spin />读取服务身份…</div> : items.length ? <Table size="small" bordered columns={columns} dataSource={items} rowKey={row => String(row.id)} pagination={false} scroll={{ x: 1200 }} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="尚未创建服务身份" />}
</section>
<section className="panel section-panel"><div className="completion-panel-heading"><div><strong>服务接入绑定</strong><span>只允许类型匹配且授权状态可用的身份</span></div></div>{serviceTypes.length ? <div className="governance-binding-list">{serviceTypes.map(type => <div key={type}><strong>{type}</strong><span>{text(bindings.find(item => item.serviceType === type)?.serviceIdentityId, '未绑定')}</span>{canManage && <Select aria-label={`${type}服务身份`} placeholder="选择身份" value={String(bindings.find(item => item.serviceType === type)?.serviceIdentityId || '') || undefined} loading={busy} options={items.filter(item => item.serviceType === type).map(item => ({ label: `${text(item.name)} · ${text(item.credentialStatus)}`, value: String(item.id) }))} onChange={value => void bind(type, value)} />}</div>)}</div> : <Empty description="服务类型尚未由服务端返回" />}</section>
<Modal className="management-modal" open={Boolean(editing) && !editing?.showRotations} title={editing?.id ? '编辑服务身份' : '新建服务身份'} okText="保存配置" confirmLoading={busy} onCancel={() => setEditing(null)} onOk={() => void save()}>
<Alert showIcon type="warning" message="服务身份默认停用" description="启用需要 READY 凭据引用和服务端允许的最小动作。输入凭据引用,不要粘贴密钥内容。" />
<Form form={form} layout="vertical"><Form.Item name="name" label="身份名称" rules={[{ required: true, whitespace: true }]}><Input maxLength={190} /></Form.Item><Form.Item name="serviceType" label="服务类型" rules={[{ required: true }]}><Select disabled={Boolean(editing?.id)} options={serviceTypes.map(value => ({ label: value, value }))} /></Form.Item><Form.Item name="allowedActions" label="允许动作" rules={[{ required: true, type: 'array', min: 1 }]}><Select mode="multiple" options={(ACTIONS_BY_TYPE[String(serviceType || '')] || allowedActions).filter((value: string) => allowedActions.includes(value)).map((value: string) => ({ label: value, value }))} /></Form.Item><Form.Item name="credentialReference" label="凭据引用" rules={[{ pattern: /^(?:env:[A-Z][A-Z0-9_]{0,100}|file:[A-Za-z0-9_./-]{1,240})$/, message: '使用 env:NAME 或 file:relative/path 引用,不填密钥内容' }]}><Input placeholder="env:QUALITY_MODEL_KEY" autoComplete="off" /></Form.Item><Form.Item name="credentialStatus" label="凭据状态" rules={[{ required: true }]}><Select options={['UNCONFIGURED', 'READY', 'EXPIRED', 'REVOKED'].map(value => ({ label: value, value }))} /></Form.Item>{Boolean(editing?.id) && <Form.Item name="active" label="身份状态" valuePropName="checked"><Switch checkedChildren="启用" unCheckedChildren="停用" /></Form.Item>}<Form.Item name="reason" label="操作原因" rules={[{ required: true, whitespace: true }]}><Input.TextArea rows={2} maxLength={300} /></Form.Item></Form>
</Modal>
<Modal className="management-modal" open={Boolean(rotating?.id) && !rotating?.showRotations} title="轮换凭据引用" okText="提交轮换" confirmLoading={busy} onCancel={() => setRotating(null)} onOk={() => void rotate()}><Form form={rotateForm} layout="vertical"><Form.Item name="credentialReference" label="凭据引用" rules={[{ required: true, pattern: /^(?:env:[A-Z][A-Z0-9_]{0,100}|file:[A-Za-z0-9_./-]{1,240})$/, message: '使用 env:NAME 或 file:relative/path 引用' }]}><Input autoComplete="off" /></Form.Item><Form.Item name="credentialStatus" label="状态"><Select options={['READY', 'EXPIRED', 'REVOKED', 'UNCONFIGURED'].map(value => ({ label: value, value }))} /></Form.Item><Form.Item name="reason" label="轮换理由" rules={[{ required: true, whitespace: true }]}><Input.TextArea rows={2} /></Form.Item></Form></Modal>
<Modal className="management-modal" open={Boolean(bindingEdit)} title="变更服务身份绑定" okText="保存绑定" confirmLoading={busy} onCancel={() => setBindingEdit(null)} onOk={() => void submitBinding()}><p>服务类型:{text(bindingEdit?.type)} · 身份 ID:{text(bindingEdit?.identityId)}</p><Form form={bindingForm} layout="vertical"><Form.Item name="reason" label="绑定原因" rules={[{ required: true, whitespace: true }]}><Input.TextArea rows={2} maxLength={300} /></Form.Item></Form></Modal>
<Drawer className="management-drawer" open={rotating?.showRotations === true} title="凭据引用变更历史" width={Math.min(680, window.innerWidth)} onClose={() => setRotating(null)}>{rotations.length ? <Table size="small" bordered dataSource={rotations} rowKey={row => String(row.id)} pagination={{ pageSize: 8, showSizeChanger: false }} columns={[{ title: '引用', dataIndex: 'credentialReference', key: 'credentialReference' }, { title: '状态', dataIndex: 'credentialStatus', key: 'credentialStatus' }, { title: '原因', dataIndex: 'reason', key: 'reason' }, { title: '时间', dataIndex: 'createdAt', key: 'createdAt' }]} /> : <Empty description="没有已返回的轮换记录" />}</Drawer>
</div>;
}
export function UserAccessPolicyPanel({ onUnauthorized }: { onUnauthorized: (error: unknown) => boolean }) {
const { message } = App.useApp();
const [userId, setUserId] = useState<string>();
const [policy, setPolicy] = useState<Row | null>(null);
const [users, setUsers] = useState<Row[]>([]);
const [effective, setEffective] = useState<Row | null>(null);
const [scopePreview, setScopePreview] = useState<Row | null>(null);
const [previewBusy, setPreviewBusy] = useState(false);
const [loading, setLoading] = useState(false);
const [saving, setSaving] = useState(false);
const [error, setError] = useState('');
const [form] = Form.useForm<Row>();
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) => {
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); }
};
useEffect(() => {
api.users().then(value => setUsers(collectionItems(value))).catch(errorValue => { if (!onUnauthorized(errorValue)) setError(errorValue instanceof Error ? errorValue.message : '用户列表读取失败'); });
}, []);
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 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 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>;
}