优化:完善分类规则与Excel配置维护并加速查询翻页
This commit is contained in:
+160
-159
@@ -1,3 +1,8 @@
|
||||
import { ConfigurationWorkbookActions } from './ConfigurationWorkbookActions';
|
||||
import { MappingEditorContext } from './MappingEditorContext';
|
||||
import { ClassificationRuleEditor } from './ClassificationRuleEditor';
|
||||
import { ManagementSections } from './ManagementSections';
|
||||
import type { ClassificationSelection } from './classificationMaintenance';
|
||||
import { TasksMonitorPage } from './TasksMonitorPage';
|
||||
import { configurationDateTime, currentConfigurationName } from './configurationName';
|
||||
import { BusinessValue, currentMetricFormula } from './BusinessValue';
|
||||
@@ -6,7 +11,7 @@ import { AnalysisClarification } from './AnalysisClarification';
|
||||
import { pendingClarificationTurnId } from './analysisClarificationModel';
|
||||
import { useAnalysisVisualRecovery } from './analysisVisualRecovery';
|
||||
import { mergeModelThinking, modelThinkingEntries } from './analysisModelThinking';
|
||||
import { usePageCache } from './pageCache';
|
||||
import { usePageCache, useMaintenanceRefresh } from './pageCache';
|
||||
import { FilterFieldSettings } from './FilterFieldSettings';
|
||||
import { isInternalDataField, publicJson, readableRuleDescription } from './publicDataDisplay';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
@@ -26,7 +31,6 @@ import {
|
||||
Select,
|
||||
Spin,
|
||||
Switch,
|
||||
Tabs,
|
||||
Tag,
|
||||
} from 'antd';
|
||||
import type { ColumnsType } from 'antd/es/table';
|
||||
@@ -53,11 +57,11 @@ import { beginAnalysisSubmission, requestSubmissionCancellation, submissionOutco
|
||||
import { activeAnalysisTurn, analysisIsRunning, beginAnalysisSelection, defaultAnalysisSession, rememberAnalysisSession, rememberPendingAnalysisSession, settledAnalysisTurn } from './analysisConversationState';
|
||||
import './analysis-chat.css';
|
||||
|
||||
const TABLE_PAGE_SIZE = 20;
|
||||
const TABLE_PAGE_SIZE = 15;
|
||||
import { DataWorkflowHub, MasterWorkbookUpload, ReadableConfigDefinition, SourceFilesPanel, type PendingSourceDeletion } from './NoCodeDataWorkflow';
|
||||
import { MappingDefinitionEditor, MasterDataDefinitionEditor, MatchRulesDefinitionEditor, RuleDefinitionEditor, TechnicalDefinitionEditor, validateStructuredMappingDefinition, type ConfigDefinition } from './StructuredConfigEditors';
|
||||
import { useDataWorkflowOperation } from './useDataWorkflowOperation';
|
||||
import { CostConfigurationPanel, ServiceIdentityPanel, SourceGovernancePanel, UserAccessPolicyPanel } from './GovernanceCompletion';
|
||||
import { ServiceIdentityPanel, SourceGovernancePanel, UserAccessPolicyPanel } from './GovernanceCompletion';
|
||||
|
||||
function apiMessage(error: unknown): string {
|
||||
if (error instanceof ApiError && error.status === 409) return '当前数据或配置已变化,请刷新后重新操作。';
|
||||
@@ -225,9 +229,9 @@ function ManagementPageContents({ page, user, onUnauthorized, onNavigate }: Mana
|
||||
if (page === 'analysis') return <AnalysisPage onUnauthorized={onUnauthorized} user={user} />;
|
||||
if (page === 'access') return <AccessPage user={user} onUnauthorized={onUnauthorized} />;
|
||||
if (page === 'basis') return <BasisPage onUnauthorized={onUnauthorized} />;
|
||||
if (page === 'rules') return <><ConfigManagementPage kind={page} user={user} onUnauthorized={onUnauthorized} onNavigate={onNavigate} /><MetricDictionaryPanel user={user} onUnauthorized={onUnauthorized} />{user.roles.some(role => ['SYSTEM_ADMIN', 'RULE_MAINTAINER'].includes(role)) && <TargetVersionAdmin onUnauthorized={onUnauthorized} />}</>;
|
||||
if (page === 'masterData') return <><FilterFieldSettings canManage={user.roles.some(role => ['SYSTEM_ADMIN','DATA_MAINTAINER'].includes(role))} onUnauthorized={onUnauthorized} /><ConfigManagementPage kind={page} user={user} onUnauthorized={onUnauthorized} onNavigate={onNavigate} /></>;
|
||||
if (page === 'mappings') return <><ConfigManagementPage kind={page} user={user} onUnauthorized={onUnauthorized} onNavigate={onNavigate} /><MappingIssueResolutionPanel user={user} onUnauthorized={onUnauthorized} /><CostConfigurationPanel user={user} onUnauthorized={onUnauthorized} /></>;
|
||||
if (page === 'rules') return <ManagementSections items={[{ key: 'rules', label: '计算规则', children: <ConfigManagementPage kind={page} user={user} onUnauthorized={onUnauthorized} onNavigate={onNavigate} /> },{ key: 'dictionary', label: '指标定义', children: <MetricDictionaryPanel user={user} onUnauthorized={onUnauthorized} /> },...(user.roles.some(role => ['SYSTEM_ADMIN', 'RULE_MAINTAINER'].includes(role)) ? [{ key: 'targets', label: '目标管理', children: <TargetVersionAdmin onUnauthorized={onUnauthorized} /> }] : [])]} />;
|
||||
if (page === 'masterData') return <ManagementSections items={[{ key: 'catalog', label: '基础名录', children: <ConfigManagementPage kind={page} user={user} onUnauthorized={onUnauthorized} onNavigate={onNavigate} /> },{ key: 'filters', label: '查询字段', children: <FilterFieldSettings canManage={user.roles.some(role => ['SYSTEM_ADMIN','DATA_MAINTAINER'].includes(role))} onUnauthorized={onUnauthorized} /> }]} />;
|
||||
if (page === 'mappings') return <MappingMaintenancePage user={user} onUnauthorized={onUnauthorized} onNavigate={onNavigate} />;
|
||||
const resource: Record<string, { endpoint: 'imports' | 'tasks'; title: string; subtitle: string }> = {
|
||||
imports: { endpoint: 'imports', title: '导入与校验记录', subtitle: '接收后的来源文件及其校验任务状态。' },
|
||||
tasks: { endpoint: 'tasks', title: '后台任务', subtitle: '任务状态、进度和服务端返回的失败信息。' },
|
||||
@@ -237,7 +241,7 @@ function ManagementPageContents({ page, user, onUnauthorized, onNavigate }: Mana
|
||||
}
|
||||
|
||||
function PageHeader({ actions }: { title: string; description?: string; actions?: React.ReactNode }) {
|
||||
return actions ? <div className="page-heading page-actions-only"><div className="page-heading-actions">{actions}</div></div> : null;
|
||||
return actions ? <div className="management-module-actions"><div className="page-heading-actions">{actions}</div></div> : null;
|
||||
}
|
||||
|
||||
function SourcesPage({ onUnauthorized, user }: { onUnauthorized: (error: unknown) => boolean; user: AuthUser }) {
|
||||
@@ -246,7 +250,7 @@ function SourcesPage({ onUnauthorized, user }: { onUnauthorized: (error: unknown
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
const [maintenanceBusy, setMaintenanceBusy] = useState(false);
|
||||
const [historyOpen, setHistoryOpen] = useState(() => new URLSearchParams(window.location.search).get('showImportHistory') === '1');
|
||||
const [historyOpen] = useState(() => new URLSearchParams(window.location.search).get('showImportHistory') === '1');
|
||||
const pendingKey = `quality-pending-source-deletions:${user.id}`;
|
||||
const [pendingDeletion, setPendingDeletion] = useState<PendingSourceDeletion>(() => {
|
||||
try {
|
||||
@@ -270,16 +274,20 @@ function SourcesPage({ onUnauthorized, user }: { onUnauthorized: (error: unknown
|
||||
finally { setLoading(false); }
|
||||
};
|
||||
useEffect(() => { void load(); }, []);
|
||||
useMaintenanceRefresh(load);
|
||||
return <div className="management-page">
|
||||
{error && <Alert showIcon type="error" message="来源清单读取失败" description={error} action={<Button size="small" onClick={() => void load()}>重试</Button>} />}
|
||||
<DataWorkflowHub user={user} sources={sources} currentReleaseId={currentReleaseId} pendingDeletion={pendingDeletion} onDeleted={onDeleted} onBusyChange={setMaintenanceBusy} onUnauthorized={onUnauthorized} onRefresh={() => void load()} />
|
||||
<SourceFilesPanel user={user} sources={sources} loading={loading} pendingIds={pendingDeletion.ids} maintenanceBusy={maintenanceBusy} onToggleDelete={toggleDelete} onClearDeletes={() => setPendingDeletion({ ids: [], releaseId: null })} onUnauthorized={onUnauthorized} onRefresh={() => void load()} />
|
||||
<details className="nc-advanced-records" open={historyOpen} onToggle={event => setHistoryOpen(event.currentTarget.open)}><summary>导入记录与失败详情</summary>{historyOpen && <ImportHistoryPanel user={user} currentReleaseId={currentReleaseId} onUnauthorized={onUnauthorized} />}</details>
|
||||
<details className="nc-advanced-records"><summary>高级来源记录与审计</summary><SourceGovernancePanel user={user} currentReleaseId={currentReleaseId} onUnauthorized={onUnauthorized} /></details>
|
||||
<ManagementSections initialKey={historyOpen ? 'history' : 'intake'} items={[
|
||||
{ key: 'intake', label: '数据接入', children: <DataWorkflowHub user={user} sources={sources} currentReleaseId={currentReleaseId} pendingDeletion={pendingDeletion} onDeleted={onDeleted} onBusyChange={setMaintenanceBusy} onUnauthorized={onUnauthorized} onRefresh={() => void load()} /> },
|
||||
{ key: 'files', label: '来源文件', children: <SourceFilesPanel user={user} sources={sources} loading={loading} pendingIds={pendingDeletion.ids} maintenanceBusy={maintenanceBusy} onToggleDelete={toggleDelete} onClearDeletes={() => setPendingDeletion({ ids: [], releaseId: null })} onUnauthorized={onUnauthorized} onRefresh={() => void load()} /> },
|
||||
{ key: 'history', label: '导入记录', children: <ImportHistoryPanel user={user} currentReleaseId={currentReleaseId} onUnauthorized={onUnauthorized} /> },
|
||||
{ key: 'audit', label: '来源审计', children: <SourceGovernancePanel user={user} currentReleaseId={currentReleaseId} onUnauthorized={onUnauthorized} /> },
|
||||
]} />
|
||||
</div>;
|
||||
}
|
||||
|
||||
function ImportHistoryPanel({ user, currentReleaseId, onUnauthorized }: { user: AuthUser; currentReleaseId: string | null; onUnauthorized: (error: unknown) => boolean }) {
|
||||
const { active } = usePageCache();
|
||||
const [items, setItems] = useState<Record<string, unknown>[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState('');
|
||||
@@ -289,7 +297,7 @@ function ImportHistoryPanel({ user, currentReleaseId, onUnauthorized }: { user:
|
||||
finally { setLoading(false); }
|
||||
}, [onUnauthorized]);
|
||||
useEffect(() => { void load(); }, [load, currentReleaseId]);
|
||||
useEffect(() => { if (items.some(item => ['QUEUED', 'RUNNING'].includes(String(item.status).toUpperCase()))) { const timer = window.setTimeout(() => void load(), 2000); return () => window.clearTimeout(timer); } }, [items, load]);
|
||||
useEffect(() => { if (active && items.some(item => ['QUEUED', 'RUNNING'].includes(String(item.status).toUpperCase()))) { const timer = window.setTimeout(() => void load(), 2000); return () => window.clearTimeout(timer); } }, [items, load, active]);
|
||||
return <section className="panel section-panel"><div className="resource-toolbar"><strong>导入记录</strong><span>{items.length} 条 · 可查看处理结果和逐行校验问题</span></div>
|
||||
{error && <Alert showIcon type="error" message="导入记录读取失败" description={error} action={<Button onClick={() => void load()}>重试</Button>} />}
|
||||
{loading ? <Spin /> : <TaskTable items={items} importOnly user={user} onUnauthorized={onUnauthorized} onRefresh={() => void load()} />}
|
||||
@@ -360,7 +368,7 @@ function ruleDisplayName(value: unknown): string {
|
||||
|
||||
type PublishedConfigNames = Pick<OptionsResponse, 'departments' | 'groups' | 'products' | 'projectGroups'> & { groupDepartments?: Record<string, string | null> };
|
||||
|
||||
function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate }: { kind: 'rules' | 'mappings' | 'masterData'; user: AuthUser; onUnauthorized: (error: unknown) => boolean; onNavigate: (page: PageKey) => void }) {
|
||||
function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate, extraSections }: { extraSections?: { key: string; label: string; children: React.ReactNode }[]; kind: 'rules' | 'mappings' | 'masterData'; user: AuthUser; onUnauthorized: (error: unknown) => boolean; onNavigate: (page: PageKey) => void }) {
|
||||
const { message } = App.useApp();
|
||||
const [items, setItems] = useState<Record<string, unknown>[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
@@ -377,14 +385,15 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate }: { kind
|
||||
const [regressionBusy, setRegressionBusy] = useState(false);
|
||||
const [form] = Form.useForm<{ name: string; description: string }>();
|
||||
const [draftDefinition, setDraftDefinition] = useState<ConfigDefinition>({});
|
||||
const loadedDefinitionKey=useRef('');
|
||||
const [ruleSchema, setRuleSchema] = useState<Record<string, unknown> | null>(null);
|
||||
const [ruleSchemaError, setRuleSchemaError] = useState('');
|
||||
const [publishedNames, setPublishedNames] = useState<PublishedConfigNames | null>(null);
|
||||
const [matchMetadata,setMatchMetadata]=useState<Record<string,unknown>|null>(null);
|
||||
const [differenceItem, setDifferenceItem] = useState<Record<string, unknown> | null>(null);
|
||||
const [differenceConfirmed, setDifferenceConfirmed] = useState(false);
|
||||
const [workflowStatus, setWorkflowStatus] = useState<DataWorkflowStatus | null>(null);
|
||||
const [workflowStatusLoaded, setWorkflowStatusLoaded] = useState(false);
|
||||
const [simpleTab, setSimpleTab] = useState<'catalog' | 'lookups' | 'matchRules'>('catalog');
|
||||
const isRules = kind === 'rules';
|
||||
const title = isRules ? '计算规则' : kind === 'masterData' ? '基础数据' : '对应关系';
|
||||
const testMode = workflowStatus?.simplified === true && workflowStatus.mode === 'TEST';
|
||||
@@ -407,7 +416,7 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate }: { kind
|
||||
const loadEditorSupport = async () => {
|
||||
try {
|
||||
if (isRules) { setRuleSchema(await api.ruleSchema()); setRuleSchemaError(''); }
|
||||
else setPublishedNames(await api.referenceNames());
|
||||
else {const [names,metadata]=await Promise.all([api.referenceNames(),api.classificationMetadata()]);setPublishedNames(names);setMatchMetadata(metadata);}
|
||||
} catch (value) { if (!onUnauthorized(value)) { if (isRules) setRuleSchemaError(apiMessage(value)); else setError(`当前发布名录读取失败:${apiMessage(value)}`); } }
|
||||
};
|
||||
const refreshWorkflowStatus = async () => {
|
||||
@@ -419,7 +428,6 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate }: { kind
|
||||
void load(); void refreshWorkflowStatus();
|
||||
});
|
||||
useEffect(() => { void load(); }, [kind]);
|
||||
useEffect(() => { setSimpleTab(kind === 'mappings' ? 'lookups' : 'catalog'); }, [kind]);
|
||||
useEffect(() => { void loadEditorSupport(); }, [isRules]);
|
||||
useEffect(() => { void refreshWorkflowStatus(); }, [kind]);
|
||||
useEffect(() => {
|
||||
@@ -429,7 +437,8 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate }: { kind
|
||||
const storedDefinition = active?.definition ?? fallback?.definition;
|
||||
const definition = isRules && testMode && String(active?.id ?? fallback?.id) === 'pq-dax-v1' && ruleSchema?.defaultDefinition
|
||||
? ruleSchema.defaultDefinition : storedDefinition;
|
||||
if (definition && typeof definition === 'object') setDraftDefinition(JSON.parse(JSON.stringify(definition)) as ConfigDefinition);
|
||||
const definitionKey=JSON.stringify([kind,active?.id??fallback?.id,definition]);
|
||||
if (definition && typeof definition === 'object' && loadedDefinitionKey.current!==definitionKey) {loadedDefinitionKey.current=definitionKey;setDraftDefinition(JSON.parse(JSON.stringify(definition)) as ConfigDefinition);}
|
||||
const metadata = items.find(row => String(row.id) === String(active?.id)) ?? fallback;
|
||||
form.setFieldsValue({ name: testMode ? currentConfigurationName(active?.name ?? metadata?.name, metadata?.createdAt) : isRules ? ruleDisplayName(active?.name || fallback?.name || '测试计算规则') : String(active?.name || fallback?.name || '测试基础数据与对应关系'), description: isRules ? readableRuleDescription(active?.description || fallback?.description) : String(active?.description || fallback?.description || '') });
|
||||
}, [workflowStatus, items, kind, isRules, testMode, ruleSchema]);
|
||||
@@ -558,31 +567,42 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate }: { kind
|
||||
}
|
||||
};
|
||||
|
||||
useMaintenanceRefresh(() => { void load(); void refreshWorkflowStatus(); void loadEditorSupport(); });
|
||||
if (!workflowStatusLoaded) return <div className="management-page"><div className="loading-panel"><Spin />正在读取当前维护模式…</div></div>;
|
||||
if (testMode) return <div className="management-page nc-simplified-config-page">
|
||||
<PageHeader title={isRules ? '计算规则' : '基础数据与对应关系'} description={isRules ? '直接编辑当前使用的公式,保存后自动保存配置、重新计算并更新报表。' : '在同一处维护系统名录、Excel 对应关系和条件匹配规则,保存后自动更新报表。'} actions={<Button icon={<ReloadOutlined />} onClick={() => { void load(); void refreshWorkflowStatus(); void loadEditorSupport(); }}>刷新</Button>} />
|
||||
{error && <Alert showIcon type="error" message="配置清单读取失败" description={error} />}
|
||||
{isRules && ruleSchemaError && <Alert showIcon type="error" message="规则编辑结构读取失败" description={ruleSchemaError} />}
|
||||
{!canApplyWorkflow && <Alert showIcon type="info" message="当前账号可查看配置;保存和更新报表需要发布权限。" />}
|
||||
{workflowOperation.error && <Alert showIcon type="error" message={workflowOperation.operation?.status === 'FAILED' ? '保存或报表更新失败' : '进度读取失败'} description={workflowOperation.error} action={workflowOperation.operation?.operationId ? <Button size="small" onClick={workflowOperation.resume}>重试读取进度</Button> : undefined} />}
|
||||
{workflowOperation.operation && <section className="nc-operation-status panel"><div><strong>{workflowOperation.busy ? (simpleStageLabel[String(workflowOperation.operation.stage || workflowOperation.operation.status)] || '正在处理') : String(workflowOperation.operation.status).toUpperCase() === 'COMPLETED' ? '报表已更新' : '操作结束'}</strong></div><Progress percent={workflowOperation.busy ? undefined : String(workflowOperation.operation.status).toUpperCase() === 'COMPLETED' ? 100 : 0} status={String(workflowOperation.operation.status).toUpperCase() === 'FAILED' ? 'exception' : String(workflowOperation.operation.status).toUpperCase() === 'COMPLETED' ? 'success' : 'active'} /></section>}
|
||||
<section className="panel section-panel nc-simple-current-config">
|
||||
{isRules && <div className="resource-toolbar"><strong>当前计算规则</strong></div>}
|
||||
<Form form={form} component={isRules ? 'form' : false} layout="vertical">{isRules && <div className="structured-config-form-grid"><Form.Item name="name" label="配置名称"><Input readOnly placeholder="保存时自动生成" /></Form.Item><Form.Item name="description" label="说明(可选)"><Input disabled={!canApplyWorkflow} maxLength={1000} /></Form.Item></div>}</Form>
|
||||
{isRules ? canApplyWorkflow ? <RuleDefinitionEditor value={draftDefinition} onChange={setDraftDefinition} schema={ruleSchema} schemaError={ruleSchemaError} /> : <RuleContents value={draftDefinition} /> : <>
|
||||
<Tabs className="nc-simple-config-tabs" activeKey={simpleTab} onChange={key => setSimpleTab(key as typeof simpleTab)} items={[
|
||||
{ key: 'catalog', label: '名录', children: <><div className="nc-simple-config-intro">{canApplyWorkflow && <MasterWorkbookUpload kind="masterData" base={workflowMappingBase} expectedCurrentReleaseId={workflowStatus?.currentReleaseId ?? null} onUnauthorized={onUnauthorized} onComplete={() => { void load(); void refreshWorkflowStatus(); }} simplified />}</div><MasterDataDefinitionEditor value={draftDefinition} onChange={setDraftDefinition} publishedNames={publishedNames ?? undefined} simplified readOnly={!canApplyWorkflow} /></> },
|
||||
{ key: 'lookups', label: '基础对应', children: <><div className="nc-simple-config-intro">{canApplyWorkflow && <MasterWorkbookUpload kind="mappings" base={workflowMappingBase} expectedCurrentReleaseId={workflowStatus?.currentReleaseId ?? null} onUnauthorized={onUnauthorized} onComplete={() => { void load(); void refreshWorkflowStatus(); }} simplified />}</div><MappingDefinitionEditor value={draftDefinition} onChange={setDraftDefinition} simplified readOnly={!canApplyWorkflow} /></> },
|
||||
{ key: 'matchRules', label: '条件匹配', children: <MatchRulesDefinitionEditor value={draftDefinition} onChange={setDraftDefinition} metadata={workflowStatus} readOnly={!canApplyWorkflow} /> },
|
||||
]} />
|
||||
{validateStructuredMappingDefinition(draftDefinition, publishedNames?.groupDepartments).length > 0 && <Alert showIcon type="warning" message="有名录引用需要留意" description={<ul className="structured-config-error-list">{validateStructuredMappingDefinition(draftDefinition, publishedNames?.groupDepartments).slice(0, 12).map((issue, index) => <li key={`${issue}:${index}`}>{issue}</li>)}</ul>} />}
|
||||
</>}
|
||||
{canApplyWorkflow && <div className="nc-simple-save-row"><span>保存会自动检查配置、保存配置、按当前来源重算并更新报表。</span><Button type="primary" size="large" disabled={workflowOperation.busy || (isRules && !ruleSchema)} loading={workflowOperation.busy} onClick={() => void applyCurrent()}>保存并更新报表</Button></div>}
|
||||
</section>
|
||||
if (testMode) {
|
||||
const notices = <>
|
||||
{error && <Alert showIcon type="error" message="配置清单读取失败" description={error} />}
|
||||
{isRules && ruleSchemaError && <Alert showIcon type="error" message="规则编辑结构读取失败" description={ruleSchemaError} />}
|
||||
{!canApplyWorkflow && <Alert showIcon type="info" message="当前账号可查看配置;保存和更新报表需要发布权限。" />}
|
||||
{workflowOperation.error && <Alert showIcon type="error" message="保存或报表更新失败" description={workflowOperation.error} action={workflowOperation.operation?.operationId ? <Button size="small" onClick={workflowOperation.resume}>重试读取进度</Button> : undefined} />}
|
||||
{workflowOperation.operation && <section className="nc-operation-status panel"><div><strong>{simpleStageLabel[String(workflowOperation.operation.stage || workflowOperation.operation.status)] || '正在处理'}</strong></div><Progress percent={workflowOperation.busy ? undefined : String(workflowOperation.operation.status).toUpperCase() === 'COMPLETED' ? 100 : 0} status={String(workflowOperation.operation.status).toUpperCase() === 'FAILED' ? 'exception' : workflowOperation.busy ? 'active' : 'success'} /></section>}
|
||||
</>;
|
||||
const editor = (mode: 'catalog' | 'lookups' | 'matchRules' | 'rules') => <div className="management-page nc-simplified-config-page flat-config-page">
|
||||
{notices}
|
||||
<section className="panel section-panel flat-config-panel">
|
||||
<div className="flat-config-toolbar">
|
||||
<div className="completion-actions"><ConfigurationWorkbookActions value={draftDefinition} onChange={setDraftDefinition} scope={mode==='rules'?'rules':mode==='catalog'?'catalogs':'all'} label={mode==='rules'?'计算规则':mode==='catalog'?'基础名录':'对应关系配置'} defaults={Array.isArray(matchMetadata?.defaultRules)?matchMetadata.defaultRules:[]} readOnly={!canApplyWorkflow} disabled={loading||(isRules?!ruleSchema:!matchMetadata)} validate={isRules?undefined:validateStructuredMappingDefinition} whole /></div>
|
||||
<Button icon={<ReloadOutlined />} onClick={() => { void load(); void refreshWorkflowStatus(); void loadEditorSupport(); }}>刷新</Button>
|
||||
</div>
|
||||
{mode === 'rules' && <Form form={form} layout="vertical"><div className="structured-config-form-grid"><Form.Item name="name" label="配置名称"><Input readOnly /></Form.Item><Form.Item name="description" label="说明(可选)"><Input disabled={!canApplyWorkflow} maxLength={1000} /></Form.Item></div></Form>}
|
||||
{mode === 'rules' ? canApplyWorkflow ? <RuleDefinitionEditor value={draftDefinition} onChange={setDraftDefinition} schema={ruleSchema} schemaError={ruleSchemaError} showWorkbookActions={false} /> : <RuleContents value={draftDefinition} />
|
||||
: mode === 'catalog' ? <MasterDataDefinitionEditor value={draftDefinition} onChange={setDraftDefinition} publishedNames={publishedNames ?? undefined} simplified readOnly={!canApplyWorkflow} />
|
||||
: mode === 'lookups' ? <MappingDefinitionEditor value={draftDefinition} onChange={setDraftDefinition} simplified readOnly={!canApplyWorkflow} />
|
||||
: <MatchRulesDefinitionEditor value={draftDefinition} onChange={setDraftDefinition} metadata={matchMetadata??workflowStatus} readOnly={!canApplyWorkflow} />}
|
||||
{!isRules && validateStructuredMappingDefinition(draftDefinition, publishedNames?.groupDepartments).length > 0 && <Alert showIcon type="warning" message="有名录引用需要留意" description={<ul className="structured-config-error-list">{validateStructuredMappingDefinition(draftDefinition, publishedNames?.groupDepartments).slice(0,12).map((issue,index)=><li key={index}>{issue}</li>)}</ul>} />}
|
||||
{canApplyWorkflow && <div className="nc-simple-save-row"><span>保存后检查配置并更新报表。</span><Button type="primary" size="large" disabled={workflowOperation.busy || (isRules && !ruleSchema)} loading={workflowOperation.busy} onClick={() => void applyCurrent()}>保存并更新报表</Button></div>}
|
||||
</section>
|
||||
</div>;
|
||||
if (kind === 'masterData') return <><Form form={form} component={false} />{editor('catalog')}</>;
|
||||
if (kind === 'mappings') return <MappingEditorContext.Provider value={{definition:draftDefinition,update:setDraftDefinition,ready:!loading && !!workflowMappingBase?.id && !!matchMetadata,defaultRules:Array.isArray(matchMetadata?.defaultRules)?matchMetadata.defaultRules:[],projectGroups:publishedNames?.projectGroups??[],groups:Array.isArray((draftDefinition.masterData as Record<string,unknown>|undefined)?.groups)?((draftDefinition.masterData as Record<string,unknown>).groups as Record<string,unknown>[]).filter(row=>row.enabled!==false).map(row=>String(row.name)):publishedNames?.groups??[]}}><Form form={form} component={false} /><ManagementSections items={[
|
||||
{ key: 'lookups', label: '基础对应', children: editor('lookups') },
|
||||
{ key: 'matchRules', label: '条件匹配', children: editor('matchRules') },
|
||||
...(extraSections ?? []),
|
||||
]} /></MappingEditorContext.Provider>;
|
||||
return editor('rules');
|
||||
}
|
||||
|
||||
</div>;
|
||||
|
||||
return <div className="management-page">
|
||||
const standardContent = <div className="management-page">
|
||||
<PageHeader title={title} description={isRules ? '维护来源字段、行计算与指标公式;保留原公式,试算后确认差异再启用。' : kind === 'masterData' ? '独立维护产业部、业务分组、产品和项目组名录;与对应关系共同形成配置。' : '维护源字段到业务分组、项目组、产业部和产品的对应关系。'} actions={<>
|
||||
{canManage && !isRules && <MasterWorkbookUpload kind={kind === 'masterData' ? 'masterData' : 'mappings'} base={items.find(item => String(item.status).toUpperCase() === 'ACTIVE')} onUnauthorized={onUnauthorized} onComplete={() => void load()} />}
|
||||
{canManage && <Button type={isRules ? 'primary' : 'default'} disabled={loading || (isRules && !ruleSchema) || (kind === 'masterData' && !publishedNames)} onClick={() => openDraft()}>从启用版新建草稿</Button>}
|
||||
@@ -649,7 +669,7 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate }: { kind
|
||||
<Drawer className="management-drawer" open={impactOpen} title={`${title}依赖影响预览`} width={Math.min(980, window.innerWidth)} onClose={() => { setImpactOpen(false); setImpact(null); }}>{impact ? <>
|
||||
<div className="governance-monitor-grid"><div><small>影响来源</small><strong>{Array.isArray(impact.affectedSources) ? impact.affectedSources.length : toText(impact.affectedSources)}</strong></div><div><small>冻结状态</small><strong>{impact.frozen === true ? '已冻结' : impact.frozen === false ? '未冻结' : '—'}</strong></div><div><small>需要更新报表</small><strong>{impact.requiresNewRelease === true ? '是' : '否'}</strong></div></div>
|
||||
{impact.status === 'NO_PUBLISHED_RELEASE' && <Alert showIcon type="info" message="暂无可比较的数据" description="服务端没有可用于新旧映射对比的数据;当前没有可计算的映射影响。" />}
|
||||
<Alert showIcon type="info" message="当前数据保持不变" description={`命中变更键 ${changedKeyRows.length} 项 · 影响来源明细 ${impactHits.length} 项 · 重分组预览 ${regroupingPreview.length} 项 · 成本计算 ${impact.costCalculationEnabled === false ? '未启用' : '以服务端返回状态为准'}`} />
|
||||
<Alert showIcon type="info" message="当前数据保持不变" description={`命中变更键 ${changedKeyRows.length} 项 · 影响来源明细 ${impactHits.length} 项 · 重分组预览 ${regroupingPreview.length} 项`} />
|
||||
{isRules ? <><h3>依赖与来源</h3><DynamicTable items={[...(Array.isArray(impact.references) ? impact.references as Record<string, unknown>[] : []), ...(Array.isArray(impact.affectedSources) ? impact.affectedSources as Record<string, unknown>[] : [])]} /></> : <>
|
||||
<h3>映射键前后值</h3><Table size="small" bordered dataSource={changedKeyRows} rowKey={(row, index) => `${toText(row.mappingType)}:${toText(row.sourceKey)}:${index}`} pagination={false} scroll={{ x: 920 }} columns={[{ title: '映射类型', dataIndex: 'mappingType', key: 'mappingType', width: 150 }, { title: '源键', dataIndex: 'sourceKey', key: 'sourceKey', width: 240 }, { title: '变更前', dataIndex: 'before', key: 'before', width: 200, render: (value, row) => <>{toText(value)}{row.beforeEnabled === false && <Tag>停用</Tag>}</> }, { title: '变更后', dataIndex: 'after', key: 'after', width: 200, render: (value, row) => <>{toText(value)}{row.afterEnabled === false && <Tag>停用</Tag>}</> }, { title: '命中范围', key: 'ranges', render: (_, row) => `前:${toText(row.beforeRanges)} · 后:${toText(row.afterRanges)}` }]} locale={{ emptyText: '服务端未报告映射键变化' }} />
|
||||
<h3>命中来源与行数</h3><Table size="small" bordered dataSource={impactHits} rowKey={(row, index) => `${toText(row.sourceDocumentId)}:${toText(row.sourceKey)}:${index}`} pagination={false} scroll={{ x: 920 }} columns={[{ title: '来源槽位', dataIndex: 'sourceSlot', key: 'sourceSlot', width: 180 }, { title: '期间', dataIndex: 'month', key: 'month', width: 110 }, { title: '阶段', dataIndex: 'stage', key: 'stage', width: 90, render: value => value === 'black' ? '黑片' : value === 'bright' ? '亮片' : toText(value) }, { title: '源键', dataIndex: 'sourceKey', key: 'sourceKey', width: 220 }, { title: '命中行数', dataIndex: 'changedRows', key: 'changedRows', align: 'right', width: 110 }, { title: '源行数', dataIndex: 'rowCount', key: 'rowCount', align: 'right', width: 110 }, { title: '总重量', dataIndex: 'totalWeight', key: 'totalWeight', align: 'right', width: 120 }]} locale={{ emptyText: '无来源命中记录' }} />
|
||||
@@ -658,141 +678,121 @@ function ConfigManagementPage({ kind, user, onUnauthorized, onNavigate }: { kind
|
||||
<details className="completion-technical-detail"><summary>影响预览技术字段</summary><pre className="json-result">{publicJson(impact)}</pre></details>
|
||||
</> : <div className="completion-loading"><Spin />由服务端重新核对配置依赖…</div>}</Drawer>
|
||||
</div>;
|
||||
return extraSections ? <MappingEditorContext.Provider value={{definition:draftDefinition,ready:!loading && !!matchMetadata,defaultRules:Array.isArray(matchMetadata?.defaultRules)?matchMetadata.defaultRules:[],groups:publishedNames?.groups??[],projectGroups:publishedNames?.projectGroups??[],update:definition=>{void api.createMapping({name:`分类规则 ${configurationDateTime(new Date())}`,definition}).then(raw=>{const result=raw as Record<string,unknown>;setDraftDefinition(definition);setDrafting(result);form.setFieldsValue({name:String(result.name),description:''});void load();}).catch(value=>{if(!onUnauthorized(value))message.error(apiMessage(value));});}}}><ManagementSections items={[{ key: 'configuration', label: '对应关系', children: standardContent }, ...extraSections]} /></MappingEditorContext.Provider> : standardContent;
|
||||
}
|
||||
|
||||
function MappingIssueResolutionPanel({ user, onUnauthorized }: { user: AuthUser; onUnauthorized: (error: unknown) => boolean }) {
|
||||
const { message } = App.useApp();
|
||||
function MappingMaintenancePage({ user, onUnauthorized, onNavigate }: Omit<ManagementPageProps, 'page'>) {
|
||||
const canEdit=user.roles.some(role=>['SYSTEM_ADMIN','DATA_MAINTAINER','RULE_MAINTAINER'].includes(role));
|
||||
return <ConfigManagementPage kind="mappings" user={user} onUnauthorized={onUnauthorized} onNavigate={onNavigate} extraSections={[
|
||||
{key:'groups',label:'业务分组未分类',children:<ClassificationRuleEditor onUnauthorized={onUnauthorized}>{edit=><UnclassifiedSourcesPanel onUnauthorized={onUnauthorized} onEdit={canEdit?edit:undefined}/>}</ClassificationRuleEditor>},
|
||||
{key:'projects',label:'项目组未分类',children:<ClassificationRuleEditor onUnauthorized={onUnauthorized}>{edit=><MappingIssueResolutionPanel onUnauthorized={onUnauthorized} onEdit={canEdit?edit:undefined}/>}</ClassificationRuleEditor>},
|
||||
]}/>;
|
||||
}
|
||||
|
||||
function UnclassifiedSourcesPanel({ onUnauthorized, onEdit }: { onUnauthorized: (error: unknown) => boolean; onEdit?: (selection: ClassificationSelection) => void }) {
|
||||
const [items, setItems] = useState<Record<string, unknown>[]>([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [page, setPage] = useState(1);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState('');
|
||||
const { refreshKey } = usePageCache();
|
||||
const pages = useRef(new Map<string, Promise<ReturnType<typeof unwrapItems>>>());
|
||||
const loadRevision = useRef(0);
|
||||
const load = async (force = false) => {
|
||||
const revision = ++loadRevision.current;
|
||||
const key = `${refreshKey}:${page}`;
|
||||
if (force) pages.current.clear();
|
||||
setLoading(true);
|
||||
let request: Promise<ReturnType<typeof unwrapItems>> | undefined;
|
||||
try {
|
||||
request = pages.current.get(key) ?? api.unclassifiedSources(page, TABLE_PAGE_SIZE).then(unwrapItems);
|
||||
pages.current.set(key, request);
|
||||
if (pages.current.size > 12) pages.current.delete(pages.current.keys().next().value!);
|
||||
const result = await request;
|
||||
if (revision !== loadRevision.current) return;
|
||||
setItems(result.items); setTotal(Number(result.total ?? result.items.length)); setError('');
|
||||
} catch (value) { if (pages.current.get(key) === request) pages.current.delete(key); if (revision === loadRevision.current && !onUnauthorized(value)) setError(apiMessage(value)); }
|
||||
finally { if (revision === loadRevision.current) setLoading(false); }
|
||||
};
|
||||
useEffect(() => { void load(); }, [page]);
|
||||
const columns: ColumnsType<Record<string, unknown>> = [
|
||||
{ title: '阶段', dataIndex: 'stage', width: 85, render: value => value === 'black' ? '黑片' : '亮片' },
|
||||
{ title: '产业部', dataIndex: 'department', width: 140, render: toText },
|
||||
{ title: '产品', dataIndex: 'product', width: 180, render: toText },
|
||||
{ title: 'PDT代码', dataIndex: 'pdtCode', width: 90, render: toText },
|
||||
{ title: '销售区域', dataIndex: 'salesRegion', width: 110, render: toText },
|
||||
{ title: '原因', key: 'reason', width: 120, render: () => '业务分组未分类' },
|
||||
{ title: '期间', dataIndex: 'periods', width: 180 },
|
||||
{ title: '行数', dataIndex: 'rowCount', width: 75, align: 'right' },
|
||||
{ title: '总重量 / kg', dataIndex: 'totalWeight', width: 140, align: 'right' },
|
||||
{ title: '操作', key: 'action', width: 125, fixed: 'right', render: (_, row) => <Button type="link" disabled={!onEdit} onClick={() => onEdit?.({ kind: 'group', row })}>编辑分类</Button> },
|
||||
];
|
||||
useMaintenanceRefresh(() => { void load(true); });
|
||||
return <div className="management-page">
|
||||
{error && <Alert type="error" showIcon message={error} />}
|
||||
<section className="panel section-panel">
|
||||
<div className="resource-toolbar"><strong>业务分组未分类汇总</strong><div className="completion-actions"><span>共 {total} 条</span><Button icon={<ReloadOutlined />} onClick={() => void load(true)}>刷新</Button></div></div>
|
||||
<div className="resource-table"><Table size="small" bordered loading={loading} columns={columns} dataSource={items} rowKey={row => JSON.stringify([row.stage, row.department, row.product, row.sourceKey])} pagination={false} indexOffset={(page - 1) * TABLE_PAGE_SIZE} scroll={{ x: 1280 }} /></div>
|
||||
{total > TABLE_PAGE_SIZE && <Pagination className="records-pagination" current={page} pageSize={TABLE_PAGE_SIZE} total={total} onChange={setPage} />}
|
||||
</section>
|
||||
</div>;
|
||||
}
|
||||
|
||||
function MappingIssueResolutionPanel({ onUnauthorized, onEdit }: { onUnauthorized: (error: unknown) => boolean; onEdit?: (selection: ClassificationSelection) => void }) {
|
||||
const [items, setItems] = useState<Record<string, unknown>[]>([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
const [page, setPage] = useState(1);
|
||||
const [status, setStatus] = useState('OPEN');
|
||||
const [customerCode, setCustomerCode] = useState<string>();
|
||||
const [businessGroup, setBusinessGroup] = useState<string>();
|
||||
const [department, setDepartment] = useState<string>();
|
||||
const [filterOptions, setFilterOptions] = useState<{ customerCodes: string[]; businessGroups: string[]; departments: string[] }>({ customerCodes: [], businessGroups: [], departments: [] });
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [busy, setBusy] = useState(false);
|
||||
const loadRevision = useRef(0);
|
||||
const [error, setError] = useState('');
|
||||
const [currentReleaseId, setCurrentReleaseId] = useState<string | null>(null);
|
||||
const [activeMappings, setActiveMappings] = useState<Record<string, unknown>[]>([]);
|
||||
const [selectedId, setSelectedId] = useState('');
|
||||
const [detail, setDetail] = useState<Record<string, unknown> | null>(null);
|
||||
const [resolutionOpen, setResolutionOpen] = useState(false);
|
||||
const [resolution, setResolution] = useState<'ADD_MAPPING' | 'KEEP_ORIGINAL' | 'RETURN_SOURCE'>('ADD_MAPPING');
|
||||
const [form] = Form.useForm<{ decision: 'ADD_MAPPING' | 'KEEP_ORIGINAL' | 'RETURN_SOURCE'; mappedValue?: string; reason: string; baseMappingVersionId?: string }>();
|
||||
const canResolve = user.roles.some(role => ['SYSTEM_ADMIN', 'RULE_MAINTAINER', 'DATA_MAINTAINER'].includes(role));
|
||||
|
||||
const load = async () => {
|
||||
const { refreshKey } = usePageCache();
|
||||
const pages = useRef(new Map<string, ReturnType<typeof api.mappingIssues>>());
|
||||
const load = async (force = false) => {
|
||||
const revision = ++loadRevision.current;
|
||||
const key = JSON.stringify([refreshKey, page, status, customerCode, businessGroup, department]);
|
||||
if (force) pages.current.clear();
|
||||
setLoading(true);
|
||||
let request: ReturnType<typeof api.mappingIssues> | undefined;
|
||||
try {
|
||||
const result = await api.mappingIssues({ status: status || undefined, page, pageSize: TABLE_PAGE_SIZE });
|
||||
request = pages.current.get(key) ?? api.mappingIssues({ status: status || undefined, page, pageSize: TABLE_PAGE_SIZE, customerCode, businessGroup, department, mappingType: 'PROJECT_GROUP' });
|
||||
pages.current.set(key, request);
|
||||
if (pages.current.size > 12) pages.current.delete(pages.current.keys().next().value!);
|
||||
const result = await request;
|
||||
if (revision !== loadRevision.current) return;
|
||||
setFilterOptions(result.filterOptions ?? { customerCodes: [], businessGroups: [], departments: [] });
|
||||
const normalized = unwrapItems(result);
|
||||
setItems(normalized.items); setTotal(Number(normalized.total || normalized.items.length)); setError('');
|
||||
} catch (value) { if (!onUnauthorized(value)) setError(apiMessage(value)); }
|
||||
finally { setLoading(false); }
|
||||
} catch (value) { if (pages.current.get(key) === request) pages.current.delete(key); if (revision === loadRevision.current && !onUnauthorized(value)) setError(apiMessage(value)); }
|
||||
finally { if (revision === loadRevision.current) setLoading(false); }
|
||||
};
|
||||
useEffect(() => { void load(); }, [page, status]);
|
||||
useEffect(() => {
|
||||
let alive = true;
|
||||
Promise.allSettled([api.releases(), api.mappings()]).then(([releaseResult, mappingResult]) => {
|
||||
if (!alive) return;
|
||||
if (releaseResult.status === 'fulfilled') setCurrentReleaseId(releaseResult.value.currentReleaseId ?? null);
|
||||
if (mappingResult.status === 'fulfilled') setActiveMappings(unwrapItems(mappingResult.value).items.filter(item => String(item.status).toUpperCase() === 'ACTIVE'));
|
||||
});
|
||||
return () => { alive = false; };
|
||||
}, []);
|
||||
|
||||
const openIssue = async (id: string) => {
|
||||
setSelectedId(id); setDetail(null); setError('');
|
||||
try { setDetail(await api.mappingIssue(id)); }
|
||||
catch (value) { if (!onUnauthorized(value)) setError(apiMessage(value)); }
|
||||
};
|
||||
const openResolution = (issue: Record<string, unknown>) => {
|
||||
const decision = String(issue.status).toUpperCase() === 'OPEN' ? 'ADD_MAPPING' : 'KEEP_ORIGINAL';
|
||||
setResolution(decision);
|
||||
form.setFieldsValue({ decision, mappedValue: '', reason: '', baseMappingVersionId: undefined });
|
||||
setResolutionOpen(true);
|
||||
};
|
||||
const resolve = async () => {
|
||||
const issue = detail?.issue && typeof detail.issue === 'object' ? detail.issue as Record<string, unknown> : {};
|
||||
if (!issue.id) return;
|
||||
try {
|
||||
const values = await form.validateFields();
|
||||
setBusy(true);
|
||||
const result = await api.resolveMappingIssue(String(issue.id), {
|
||||
expectedRowVersion: Number(issue.rowVersion || 0),
|
||||
decision: values.decision,
|
||||
...(values.mappedValue?.trim() ? { mappedValue: values.mappedValue.trim() } : {}),
|
||||
...(values.baseMappingVersionId ? { baseMappingVersionId: values.baseMappingVersionId } : {}),
|
||||
reason: values.reason.trim(),
|
||||
});
|
||||
setDetail(result); setResolutionOpen(false); message.success('映射问题裁决已记录;发布数据尚未改变。'); await load();
|
||||
} catch (value) {
|
||||
if (value && typeof value === 'object' && 'errorFields' in value) return;
|
||||
if (!onUnauthorized(value)) { setError(apiMessage(value)); message.error(apiMessage(value)); }
|
||||
if (value instanceof ApiError && value.status === 409) { await load(); if (selectedId) await openIssue(selectedId); }
|
||||
} finally { setBusy(false); }
|
||||
};
|
||||
const revalidate = async (decision: Record<string, unknown>) => {
|
||||
const issue = detail?.issue && typeof detail.issue === 'object' ? detail.issue as Record<string, unknown> : {};
|
||||
const decisionId = String(decision.id || '');
|
||||
if (!issue.id || !decisionId || !currentReleaseId) return;
|
||||
setBusy(true);
|
||||
try {
|
||||
const latestMappings = unwrapItems(await api.mappings()).items;
|
||||
setActiveMappings(latestMappings.filter(mapping => String(mapping.status).toUpperCase() === 'ACTIVE'));
|
||||
if (!latestMappings.some(mapping => String(mapping.id) === String(decision.newMappingVersionId) && String(mapping.status).toUpperCase() === 'ACTIVE')) {
|
||||
throw new Error('对应映射尚未启用;请先在上方映射清单完成校验和启用。');
|
||||
}
|
||||
const result = await api.revalidateMappingIssue(String(issue.id), { decisionId, expectedCurrentReleaseId: currentReleaseId, idempotencyKey: crypto.randomUUID() });
|
||||
setDetail(result); message.success('已重新校验候选数据;请查看运行状态和检查结果。'); await load();
|
||||
} catch (value) {
|
||||
if (!onUnauthorized(value)) { setError(apiMessage(value)); message.error(apiMessage(value)); }
|
||||
if (value instanceof ApiError && value.status === 409) { await load(); if (selectedId) await openIssue(selectedId); }
|
||||
} finally { setBusy(false); }
|
||||
};
|
||||
|
||||
useEffect(() => { void load(); }, [page, status, customerCode, businessGroup, department]);
|
||||
const columns: ColumnsType<Record<string, unknown>> = [
|
||||
{ title: '源键', dataIndex: 'sourceKey', key: 'sourceKey', fixed: 'left', width: 250 },
|
||||
{ title: '映射类型', dataIndex: 'mappingType', key: 'mappingType', width: 170 },
|
||||
{ title: '客户代码', dataIndex: 'customerCode', key: 'customerCode', fixed: 'left', width: 120, render: toText },
|
||||
{ title: '业务分组', dataIndex: 'businessGroup', key: 'businessGroup', width: 190, render: toText },
|
||||
{ title: '产业部', dataIndex: 'departments', key: 'departments', width: 190, render: value => Array.isArray(value) && value.length ? value.join('、') : '—' },
|
||||
{ title: '映射类型', dataIndex: 'mappingType', key: 'mappingType', width: 120, render: value => ({ PROJECT_GROUP: '项目组', CATEGORY: '业务分组', DEPARTMENT: '产业部', PRODUCT: '产品' }[String(value)] ?? toText(value)) },
|
||||
{ title: '涉及行数', dataIndex: 'rowCount', key: 'rowCount', align: 'right', width: 110 },
|
||||
{ title: '涉及总重量', dataIndex: 'totalWeight', key: 'totalWeight', align: 'right', width: 130 },
|
||||
{ title: '问题期间', key: 'periods', width: 170, render: (_, row) => { const details = row.details && typeof row.details === 'object' ? row.details as Record<string, unknown> : {}; return Array.isArray(details.periods) ? (details.periods as unknown[]).map(toText).join('、') : '—'; } },
|
||||
{ title: '状态', dataIndex: 'status', key: 'status', width: 120, render: value => <Tag color={value === 'OPEN' ? 'orange' : value === 'REVALIDATED' ? 'green' : 'blue'}>{toText(value)}</Tag> },
|
||||
{ title: '操作', key: 'action', width: 120, fixed: 'right', render: (_, row) => <Button type="link" onClick={() => void openIssue(String(row.id || ''))}>查看与处理</Button> },
|
||||
{ title: '操作', key: 'action', width: 120, fixed: 'right', render: (_, row) => <Button type="link" disabled={!onEdit} onClick={() => onEdit?.({ kind: 'projectGroup', row })}>编辑分类</Button> },
|
||||
];
|
||||
const issue = detail?.issue && typeof detail.issue === 'object' ? detail.issue as Record<string, unknown> : {};
|
||||
const details = issue.details && typeof issue.details === 'object' ? issue.details as Record<string, unknown> : {};
|
||||
const decisions = Array.isArray(detail?.decisions) ? detail.decisions.filter(item => item && typeof item === 'object') as Record<string, unknown>[] : [];
|
||||
|
||||
useMaintenanceRefresh(() => { void load(true); });
|
||||
return <div className="management-page">
|
||||
<PageHeader title="未命中映射问题" description="按源键汇总真实未命中行;裁决会创建独立映射草稿,不直接修改已发布事实。" actions={<div className="completion-actions"><Select aria-label="映射问题状态" value={status} options={[{ label: '待处理', value: 'OPEN' }, { label: '已裁决', value: 'DECIDED' }, { label: '已退回', value: 'RETURNED' }, { label: '已重验', value: 'REVALIDATED' }, { label: '全部状态', value: '' }]} onChange={value => { setStatus(value); setPage(1); }} /><Button icon={<ReloadOutlined />} onClick={() => void load()}>刷新</Button></div>} />
|
||||
{error && <Alert showIcon type="error" message="映射问题操作失败" description={error} />}
|
||||
{!canResolve && <Alert showIcon type="info" message="当前账号仅可查看" description="问题裁决需映射维护、数据维护或系统管理授权。" />}
|
||||
<section className="panel section-panel"><div className="resource-toolbar"><strong>源键命中汇总</strong><span>共 {total} 条</span></div>{loading ? <div className="loading-panel"><Spin />正在读取未命中问题…</div> : items.length ? <div className="resource-table"><Table size="small" bordered columns={columns} dataSource={items} rowKey={row => String(row.id)} pagination={false} indexOffset={(page - 1) * TABLE_PAGE_SIZE} scroll={{ x: 1050 }} /></div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前状态没有未命中映射问题" />}{total > TABLE_PAGE_SIZE && <Pagination className="records-pagination" current={page} pageSize={TABLE_PAGE_SIZE} total={total} showTotal={count => `共 ${count} 条问题`} onChange={setPage} />}</section>
|
||||
<Drawer className="management-drawer" open={Boolean(selectedId)} title="未命中映射问题处理" width={Math.min(1000, window.innerWidth)} onClose={() => { setSelectedId(''); setDetail(null); }}>
|
||||
{!detail ? <div className="completion-loading"><Spin />读取源键命中与历史裁决…</div> : <>
|
||||
<div className="governance-monitor-grid"><div><small>源键</small><strong>{toText(issue.sourceKey)}</strong></div><div><small>映射类型</small><strong>{toText(issue.mappingType)}</strong></div><div><small>汇总行数</small><strong>{toText(issue.rowCount)}</strong></div><div><small>总重量</small><strong>{toText(issue.totalWeight)}</strong></div></div>
|
||||
<p>状态 {toText(issue.status)}</p>
|
||||
<h3>涉及来源与期间</h3><DynamicTable items={[
|
||||
...(Array.isArray(details.sourceCandidateIds) ? (details.sourceCandidateIds as unknown[]).map(value => ({ kind: '待接入候选', id: value })) : []),
|
||||
...(Array.isArray(details.sourceDocumentIds) ? (details.sourceDocumentIds as unknown[]).map(value => ({ kind: '已归档来源', id: value })) : []),
|
||||
...(Array.isArray(details.periods) ? (details.periods as unknown[]).map(value => ({ kind: '期间', id: value })) : []),
|
||||
]} />
|
||||
<h3>可证明的原始分类值</h3><DynamicTable items={Array.isArray(details.originalValues) ? (details.originalValues as unknown[]).map((value, index) => value && typeof value === 'object' ? { index, ...(value as Record<string, unknown>) } : { index, value }) : []} />
|
||||
{canResolve && ['OPEN', 'DECIDED'].includes(String(issue.status || '').toUpperCase()) && <Button type="primary" onClick={() => openResolution(issue)}>记录裁决</Button>}
|
||||
<h3>裁决与重验历史</h3>{decisions.length ? <Table size="small" bordered dataSource={decisions} rowKey={row => String(row.id)} pagination={false} scroll={{ x: 900 }} columns={[
|
||||
{ title: '裁决', dataIndex: 'decision', key: 'decision', width: 150 }, { title: '理由', dataIndex: 'reason', key: 'reason', width: 260 }, { title: '处理人', dataIndex: 'actorUserId', key: 'actor', width: 150 }, { title: '重验运行', dataIndex: 'newImportRunId', key: 'run', width: 190 },
|
||||
{ title: '操作', key: 'action', width: 140, render: (_, row) => { const canRun = (row.decision === 'ADD_MAPPING' || row.decision === 'KEEP_ORIGINAL') && Boolean(row.newMappingVersionId); return canRun ? <Button type="link" disabled={!canResolve || !currentReleaseId} loading={busy} title={!currentReleaseId ? '当前还没有报表数据' : '执行前重新读取映射状态,必须已启用'} onClick={() => void revalidate(row)}>重验并构建</Button> : null; } },
|
||||
]} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="尚无裁决记录" />}
|
||||
<p className="completion-note">新映射配置需先在本页上方“映射与成本配置”中完成编辑、校验和启用;重验会用全部来源创建新候选并重新检查源键是否解决,不会直接发布。</p>
|
||||
</>}
|
||||
</Drawer>
|
||||
<Modal className="management-modal" open={resolutionOpen} title="保存映射问题裁决" okText="记录裁决" confirmLoading={busy} onCancel={() => setResolutionOpen(false)} onOk={() => void resolve()}>
|
||||
<Form form={form} layout="vertical" onValuesChange={changed => { if (changed.decision) setResolution(changed.decision as typeof resolution); }}>
|
||||
<Form.Item name="decision" label="裁决方式" rules={[{ required: true }]}><Select options={[{ label: '新增映射', value: 'ADD_MAPPING' }, { label: '保留原分类(需原值可证明)', value: 'KEEP_ORIGINAL' }, { label: '退回来源', value: 'RETURN_SOURCE' }]} /></Form.Item>
|
||||
{resolution === 'ADD_MAPPING' && <Form.Item name="mappedValue" label="映射目标分类" rules={[{ required: true, whitespace: true, message: '新增映射请填写目标分类' }]}><Input maxLength={160} /></Form.Item>}
|
||||
{resolution !== 'RETURN_SOURCE' && <Form.Item name="baseMappingVersionId" label="映射配置(可选)"><Select {...readableSelectPopup} allowClear options={activeMappings.map(item => ({ label: `${toText(item.name)}`, value: String(item.id) }))} placeholder="留空由服务端使用当前映射配置" /></Form.Item>}
|
||||
<Form.Item name="reason" label="裁决理由" rules={[{ required: true, whitespace: true, message: '请说明裁决依据' }]}><Input.TextArea rows={3} maxLength={500} showCount /></Form.Item>
|
||||
</Form>
|
||||
{resolution === 'KEEP_ORIGINAL' && <Alert showIcon type="warning" message="原分类值验证" description="服务端要求该源键存在唯一可证明的原分类值;不可证明时将拒绝裁决。" />}
|
||||
</Modal>
|
||||
<section className="panel section-panel"><div className="resource-toolbar"><strong>项目组未分类汇总</strong><div className="completion-actions"><span>共 {total} 条</span><div className="completion-actions"><Select aria-label="映射问题状态" value={status} options={[{ label: '待处理', value: 'OPEN' }, { label: '已裁决', value: 'DECIDED' }, { label: '已退回', value: 'RETURNED' }, { label: '已重验', value: 'REVALIDATED' }, { label: '全部状态', value: '' }]} onChange={value => { setStatus(value); setPage(1); }} /><Button icon={<ReloadOutlined />} onClick={() => void load(true)}>刷新</Button></div></div></div>
|
||||
<div className="resource-toolbar mapping-issue-filters">
|
||||
<Select {...readableSelectPopup} showSearch allowClear aria-label="筛选客户代码" placeholder="客户代码" value={customerCode} options={filterOptions.customerCodes.map(value => ({ label: value, value }))} onChange={value => { setCustomerCode(value); setPage(1); }} />
|
||||
<Select {...readableSelectPopup} showSearch allowClear aria-label="筛选业务分组" placeholder="业务分组" value={businessGroup} options={filterOptions.businessGroups.map(value => ({ label: value, value }))} onChange={value => { setBusinessGroup(value); setPage(1); }} />
|
||||
<Select {...readableSelectPopup} showSearch allowClear aria-label="筛选产业部" placeholder="产业部" value={department} options={filterOptions.departments.map(value => ({ label: value, value }))} onChange={value => { setDepartment(value); setPage(1); }} />
|
||||
<Button onClick={() => { setCustomerCode(undefined); setBusinessGroup(undefined); setDepartment(undefined); setPage(1); }}>重置</Button>
|
||||
</div>{loading ? <div className="loading-panel"><Spin />正在读取未命中问题…</div> : items.length ? <div className="resource-table"><Table size="small" bordered columns={columns} dataSource={items} rowKey={row => String(row.id)} pagination={false} indexOffset={(page - 1) * TABLE_PAGE_SIZE} scroll={{ x: 1320 }} /></div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前状态没有项目组未分类记录" />}{total > TABLE_PAGE_SIZE && <Pagination className="records-pagination" current={page} pageSize={TABLE_PAGE_SIZE} total={total} showTotal={count => `共 ${count} 条问题`} onChange={setPage} />}</section>
|
||||
</div>;
|
||||
}
|
||||
|
||||
@@ -856,6 +856,7 @@ function MetricDictionaryPanel({ user, onUnauthorized }: { user: AuthUser; onUna
|
||||
{ title: '状态', dataIndex: 'enabled', key: 'enabled', width: 70, render: value => <Tag color={value === true ? 'green' : 'default'}>{value === true ? '启用' : value === false ? '停用' : '—'}</Tag> },
|
||||
{ title: '操作', key: 'actions', fixed: 'right', width: 100, render: (_, row) => <span className="task-actions"><Button type="link" onClick={() => setInspecting(row)}>查看</Button>{canManage && <Button type="link" onClick={() => openEditor(row)}>编辑术语</Button>}</span> },
|
||||
];
|
||||
useMaintenanceRefresh(load);
|
||||
return <section className="panel section-panel completion-tools">
|
||||
<div className="completion-panel-heading"><div><strong>指标术语字典</strong><span>维护展示名称与别名;计算公式在上方计算规则中维护</span></div><Button icon={<ReloadOutlined />} onClick={() => void load()}>刷新字典</Button></div>
|
||||
{dictionaryError && <Alert showIcon type="error" message="术语字典读取失败" description={dictionaryError} />}
|
||||
@@ -1773,7 +1774,7 @@ function AccessPage({ user, onUnauthorized }: { user: AuthUser; onUnauthorized:
|
||||
const canReadAudit = user.roles.some(role => ['SYSTEM_ADMIN', 'AUDIT_VIEWER'].includes(role));
|
||||
const canViewServiceIdentities = user.roles.some(role => ['SYSTEM_ADMIN', 'SYSTEM_OPERATOR', 'AUDIT_VIEWER'].includes(role));
|
||||
const defaultTab = canManageUsers ? 'users' : canReadAudit ? 'audit' : canViewServiceIdentities ? 'services' : '';
|
||||
const [activeTab, setActiveTab] = useState(defaultTab);
|
||||
const [activeTab] = useState(defaultTab);
|
||||
const tabs = [
|
||||
...(canManageUsers ? [{ key: 'users', label: '用户', children: <UsersResourceTab user={user} onUnauthorized={onUnauthorized} /> }] : []),
|
||||
...(canManageUsers ? [{ key: 'policy', label: '明细与证据范围', children: <UserAccessPolicyPanel onUnauthorized={onUnauthorized} /> }] : []),
|
||||
@@ -1782,8 +1783,8 @@ function AccessPage({ user, onUnauthorized }: { user: AuthUser; onUnauthorized:
|
||||
];
|
||||
return <div className="management-page">
|
||||
<PageHeader title="权限与审计" />
|
||||
<section className="panel access-summary"><div><span>当前账号</span><strong>{user.displayName || user.username}</strong>{user.displayName && user.displayName !== user.username && <small>{user.username}</small>}</div><div><span>角色</span><strong>{user.roles.length} 项</strong><small className="role-list role-summary-list">{user.roles.length ? user.roles.map((role, index) => <span key={`${role}-${index}`}>{shownRole(role)}</span>) : '服务端未返回角色'}</small></div><div><span>授权产业部</span><strong>{user.departments.length ? user.departments.map(name => name === '质量管理部' ? '质量中心' : name).join('、') : '未返回范围'}</strong></div><div><span>授权分组</span><strong>{user.groups.length ? user.groups.join('、') : user.roles.includes('SYSTEM_ADMIN') ? '未限制' : '未返回范围'}</strong></div></section>
|
||||
{tabs.length > 0 ? <section className="panel section-panel"><Tabs activeKey={activeTab} onChange={setActiveTab} items={tabs} /></section> : <Alert showIcon type="info" message="当前账号没有用户管理或审计记录读取权限" />}
|
||||
|
||||
{tabs.length > 0 ? <ManagementSections initialKey={activeTab} items={[...tabs, { key: 'summary', label: '当前授权', children: <section className="panel access-summary"><div><span>当前账号</span><strong>{user.displayName || user.username}</strong>{user.displayName && user.displayName !== user.username && <small>{user.username}</small>}</div><div><span>角色</span><strong>{user.roles.length} 项</strong><small className="role-list role-summary-list">{user.roles.length ? user.roles.map((role, index) => <span key={`${role}-${index}`}>{shownRole(role)}</span>) : '服务端未返回角色'}</small></div><div><span>授权产业部</span><strong>{user.departments.length ? user.departments.map(name => name === '质量管理部' ? '质量中心' : name).join('、') : '未返回范围'}</strong></div><div><span>授权分组</span><strong>{user.groups.length ? user.groups.join('、') : user.roles.includes('SYSTEM_ADMIN') ? '未限制' : '未返回范围'}</strong></div></section> }]} /> : <Alert showIcon type="info" message="当前账号没有用户管理或审计记录读取权限" />}
|
||||
</div>;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user