页面快照支持勾选查询条件、指标卡片、趋势、汇总表、不良构成和细分缺陷图,复制PNG或下载;增加取消、分阶段提示和等待超时恢复。 修复公共Select弹层准备帧被opacity覆盖导致的先闪出再展开,并取消查询字段原生label的重复点击转发。 同步已经验收上线的销售订单类型映射、排除筛选及预聚合,以及其线上权限、删除确认配套源码;保留既有公式编辑和名录编码修改。源码范围按发布清单冻结,不纳入本机数据、凭据及未发布工作。 验证:前后端独立源码构建通过;10项前端检查、4项订单分类单元测试通过;实际系统剪贴板粘贴PNG验证通过;线上配置及筛选结果与发布前一致,后端未重启。
777 lines
66 KiB
TypeScript
777 lines
66 KiB
TypeScript
import { useDeleteConfirmation } from './useDeleteConfirmation';
|
||
import { useEffect, useMemo, useState } from 'react';
|
||
import {
|
||
Alert, App, Button, Empty, Form, Input, InputNumber, Modal, Popconfirm,
|
||
Select, Segmented, Spin, Tag,
|
||
} from 'antd';
|
||
import type { ColumnsType } from 'antd/es/table';
|
||
import { QualityTable as Table } from './QualityTable';
|
||
import { DeleteOutlined, PlusOutlined, ReloadOutlined, SaveOutlined } from '@ant-design/icons';
|
||
import { ApiError, api, collectionItems } from './api';
|
||
import type { QueryParams, Stage, ViewKind } from './types';
|
||
import { readableSelectPopup } from './readableSelectPopup';
|
||
import './completion.css';
|
||
|
||
type Row = Record<string, unknown>;
|
||
const TABLE_PAGE_SIZE = 15;
|
||
|
||
function text(value: unknown, empty = '—'): string {
|
||
if (value === null || value === undefined || value === '') return empty;
|
||
return typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' ? String(value) : empty;
|
||
}
|
||
|
||
function record(value: unknown): Row {
|
||
return value && typeof value === 'object' && !Array.isArray(value) ? value as Row : {};
|
||
}
|
||
|
||
function list(value: unknown): Row[] {
|
||
return Array.isArray(value) ? value.filter(item => item && typeof item === 'object') as Row[] : [];
|
||
}
|
||
|
||
function listOfNames(value: unknown): string[] {
|
||
return Array.isArray(value) ? value.map(item => String(item || '').trim()).filter(Boolean) : [];
|
||
}
|
||
|
||
function pct(value: unknown): string {
|
||
return typeof value === 'number' && Number.isFinite(value) ? `${(value * 100).toFixed(2)}%` : '—';
|
||
}
|
||
|
||
function pp(value: unknown): string {
|
||
return typeof value === 'number' && Number.isFinite(value) ? `${value > 0 ? '+' : ''}${value.toFixed(2)} 个百分点` : '—';
|
||
}
|
||
|
||
function objectContext(params: QueryParams): Row {
|
||
const { view: _view, ...context } = params;
|
||
return context as Row;
|
||
}
|
||
|
||
function savedViewContext(params: QueryParams): Row {
|
||
const context = objectContext(params);
|
||
delete context.releaseId;
|
||
return context;
|
||
}
|
||
|
||
function previousPeriod(params: QueryParams): { year: number; month?: number; quarter?: number } {
|
||
if (params.month) return params.month === 1 ? { year: params.year - 1, month: 12 } : { year: params.year, month: params.month - 1 };
|
||
if (params.quarter) return params.quarter === 1 ? { year: params.year - 1, quarter: 4 } : { year: params.year, quarter: params.quarter - 1 };
|
||
return { year: params.year - 1 };
|
||
}
|
||
|
||
function samePeriodLastYear(params: QueryParams): { year: number; month?: number; quarter?: number } {
|
||
return { year: params.year - 1, ...(params.month ? { month: params.month } : {}), ...(params.quarter ? { quarter: params.quarter } : {}) };
|
||
}
|
||
|
||
function comparisonBody(current: QueryParams, comparisonPeriod: { year: number; month?: number; quarter?: number }, metric = 'compositeRate') {
|
||
const filters = objectContext(current);
|
||
delete filters.year; delete filters.month; delete filters.quarter; delete filters.releaseId; delete filters.view;
|
||
const comparisonFilters = { ...filters };
|
||
return {
|
||
metric,
|
||
current: { ...filters, ...(current.releaseId ? { releaseId: current.releaseId } : {}), year: current.year, ...(current.month ? { month: current.month } : {}), ...(current.quarter ? { quarter: current.quarter } : {}) },
|
||
comparison: { ...comparisonFilters, ...(current.releaseId ? { releaseId: current.releaseId } : {}), ...comparisonPeriod },
|
||
};
|
||
}
|
||
|
||
function SnapshotRates({ label, value }: { label: string; value: unknown }) {
|
||
const snapshot = record(value);
|
||
const summary = record(snapshot.summary);
|
||
const coverage = record(summary.coverage);
|
||
const hasBlack = Number(coverage.blackRows || 0) > 0;
|
||
const hasBright = Number(coverage.brightRows || 0) > 0;
|
||
return <div className="completion-snapshot">
|
||
<strong>{label}</strong>
|
||
<dl>
|
||
<dt>综合合格率</dt><dd>{hasBlack || hasBright ? pct(summary.compositeRate) : '—'}</dd>
|
||
<dt>黑片合格率</dt><dd>{hasBlack ? pct(record(summary.black).rate) : '—'}</dd>
|
||
<dt>亮片合格率</dt><dd>{hasBright ? pct(record(summary.bright).rate) : '—'}</dd>
|
||
<dt>覆盖行数</dt><dd>黑 {text(coverage.blackRows, text(record(snapshot.coverage).blackRows, '0'))} · 亮 {text(coverage.brightRows, text(record(snapshot.coverage).brightRows, '0'))}</dd>
|
||
</dl>
|
||
</div>;
|
||
}
|
||
|
||
function SharedQueryConditions({ label, value }: { label: string; value: unknown }) {
|
||
const context = record(record(value).context);
|
||
const periods = [
|
||
...(context.year ? [text(context.year)] : []),
|
||
...(context.quarter ? [`第${text(context.quarter)}季度`] : []),
|
||
...(context.month ? [`${text(context.month)}月`] : []),
|
||
];
|
||
const dimensions: Array<[string, unknown]> = [
|
||
['部门', context.department], ['分组', context.group], ['产品', context.product], ['项目组', context.projectGroup],
|
||
];
|
||
const conditions = [
|
||
...(periods.length ? [`期间 ${periods.join(' ')}`] : []),
|
||
...dimensions.filter(([, value]) => value !== null && value !== undefined && value !== '').map(([name, value]) => `${name} ${text(value)}`),
|
||
...(context.view ? [`维度 ${({ overall: '总体', department: '部门', group: '分组', product: '产品', projectGroup: '项目组' } as Record<string, string>)[String(context.view)] || text(context.view)}`] : []),
|
||
...(typeof context.includeUnassigned === 'boolean' ? [`未分配记录 ${context.includeUnassigned ? '包含' : '排除'}`] : []),
|
||
];
|
||
return conditions.length ? <p className="completion-note">{label}:{conditions.join(' · ')}</p> : null;
|
||
}
|
||
|
||
export function M01Insights({ query, onUnauthorized }: { query: QueryParams; onUnauthorized: (error: unknown) => boolean }) {
|
||
const [target, setTarget] = useState<Row | null>(null);
|
||
const [targetError, setTargetError] = useState('');
|
||
const [compare, setCompare] = useState<Row | null>(null);
|
||
const [compareError, setCompareError] = useState('');
|
||
const [busy, setBusy] = useState(false);
|
||
const [compareMode, setCompareMode] = useState<'previous' | 'yearOverYear'>('previous');
|
||
const prior = useMemo(() => compareMode === 'yearOverYear' ? samePeriodLastYear(query) : previousPeriod(query), [query.year, query.month, query.quarter, compareMode]);
|
||
const contextKey = JSON.stringify(query);
|
||
|
||
useEffect(() => {
|
||
let alive = true;
|
||
setTargetError('');
|
||
api.analyticsTarget({ ...objectContext(query), metric: 'COMPOSITE_RATE' }).then(value => {
|
||
if (alive) { setTarget(value); setTargetError(''); }
|
||
}).catch(error => { if (alive && !onUnauthorized(error)) setTargetError(error instanceof Error ? error.message : '目标状态读取失败'); });
|
||
return () => { alive = false; };
|
||
}, [contextKey, onUnauthorized]);
|
||
|
||
useEffect(() => { setCompare(null); setCompareError(''); }, [contextKey, compareMode]);
|
||
|
||
const runCompare = async () => {
|
||
setBusy(true); setCompareError('');
|
||
try { setCompare(await api.analyticsCompare(comparisonBody(query, prior))); }
|
||
catch (error) { if (!onUnauthorized(error)) setCompareError(error instanceof Error ? error.message : '比较查询失败'); }
|
||
finally { setBusy(false); }
|
||
};
|
||
const refreshAll = async () => {
|
||
setBusy(true); setTargetError(''); setCompareError('');
|
||
const [targetResult, compareResult] = await Promise.allSettled([
|
||
api.analyticsTarget({ ...objectContext(query), metric: 'COMPOSITE_RATE' }),
|
||
api.analyticsCompare(comparisonBody(query, prior)),
|
||
]);
|
||
if (targetResult.status === 'fulfilled') setTarget(targetResult.value);
|
||
else if (!onUnauthorized(targetResult.reason)) setTargetError(targetResult.reason instanceof Error ? targetResult.reason.message : '目标状态读取失败');
|
||
if (compareResult.status === 'fulfilled') setCompare(compareResult.value);
|
||
else if (!onUnauthorized(compareResult.reason)) setCompareError(compareResult.reason instanceof Error ? compareResult.reason.message : '比较查询失败');
|
||
setBusy(false);
|
||
};
|
||
const targetBody = record(target);
|
||
const targetValue = record(targetBody.target);
|
||
const comparison = record(compare);
|
||
const targetState = text(targetBody.status, '未返回');
|
||
const configuredTarget = typeof targetValue.value === 'number' ? targetValue.value : targetValue.targetRate;
|
||
const configured = targetState === 'CONFIGURED' && typeof configuredTarget === 'number';
|
||
const delta = record(comparison.delta);
|
||
const legacyDelta = record(comparison.deltaPP);
|
||
const percentagePoints = delta.percentagePoints ?? legacyDelta.composite ?? legacyDelta.compositeRate;
|
||
const contributions = record(comparison.contributions);
|
||
const blackContribution = contributions.black ?? contributions.blackPP;
|
||
const brightContribution = contributions.bright ?? contributions.brightPP;
|
||
const unexplainedContribution = contributions.unexplained ?? contributions.unexplainedPP ?? contributions.roundingResidualPP ?? contributions.residualPP;
|
||
const compareTarget = record(record(comparison.targets || comparison.target).comparison);
|
||
const compareTargetValue = record(compareTarget.target);
|
||
const comparability = record(comparison.comparability);
|
||
const comparable = comparison.coverageComparable === true || (comparability.comparable === true && comparability.coverageAligned !== false);
|
||
const comparisonReason = Array.isArray(comparability.reasons)
|
||
? (comparability.reasons as unknown[]).map(String).join(';') || text(comparability.coverageNotice, '规则口径与覆盖可比性由服务端返回')
|
||
: text(comparability.reason || comparability.coverageNotice, '规则口径与覆盖可比性由服务端返回');
|
||
|
||
return <section className="panel section-panel completion-insights" aria-label="目标与期间比较">
|
||
<div className="completion-panel-heading"><div><strong>目标与期间比较</strong><span>目标与比较结果均来自指标分析服务</span></div><Button icon={<ReloadOutlined />} loading={busy} onClick={() => { setCompare(null); setCompareError(''); void refreshAll(); }}>刷新比较</Button></div>
|
||
<div className="completion-insight-grid">
|
||
<div className="completion-insight-card">
|
||
<div className="completion-card-heading"><strong>当前筛选综合合格率目标</strong><Tag color={configured ? 'green' : targetState === 'CONFLICT' ? 'red' : 'default'}>{targetState === 'CONFIGURED' ? '已配置' : targetState === 'UNCONFIGURED' ? '未配置' : targetState === 'CONFLICT' ? '配置冲突' : targetState}</Tag></div>
|
||
{targetError ? <Alert showIcon type="error" message="目标读取失败" description={targetError} /> : configured
|
||
? <><div className="completion-target-value">{pct(configuredTarget)} <small>{text(targetValue.unit, '比例')}</small></div><p className="completion-note">当前目标已启用 · 匹配配置 {text(targetBody.matchingCount, '—')}</p></>
|
||
: <><div className="completion-empty-value">当前筛选没有唯一的已启用目标</div>{targetState === 'CONFLICT' && <p className="completion-note">存在 {list(targetBody.alternatives).length} 项候选配置;请到“指标与规则”检查配置冲突。</p>}</>}
|
||
</div>
|
||
<div className="completion-insight-card completion-compare-card">
|
||
<div className="completion-card-heading"><strong>{compareMode === 'yearOverYear' && (query.month || query.quarter) ? '与上年同期比较' : '与上一期间比较'}</strong><div className="completion-compare-controls">
|
||
<Segmented size="small" value={compareMode} options={[{ label: '上一期间', value: 'previous' }, { label: '上年同期', value: 'yearOverYear' }]} onChange={value => { setCompareMode(value as 'previous' | 'yearOverYear'); setCompare(null); }} aria-label="比较期间类型" />
|
||
<Button type="primary" loading={busy} onClick={() => void runCompare()}>开始比较</Button>
|
||
</div></div>
|
||
<p className="completion-note">比较期:{prior.year}年{prior.month ? ` ${prior.month}月` : prior.quarter ? ` 第${prior.quarter}季度` : '度'} · 规则口径与覆盖状态由服务端核对</p>
|
||
{compareError && <Alert showIcon type="error" message="比较失败" description={compareError} />}
|
||
{compare && <>
|
||
<div className="completion-compare-snapshots"><SnapshotRates label="当前期间" value={comparison.current} /><SnapshotRates label="比较期间" value={comparison.comparison} /></div>
|
||
<div className="completion-delta-grid">
|
||
<span><small>综合变化</small><strong>{pp(percentagePoints)}</strong></span>
|
||
<span><small>黑片贡献</small><strong>{pp(blackContribution)}</strong></span>
|
||
<span><small>亮片贡献</small><strong>{pp(brightContribution)}</strong></span>
|
||
</div>
|
||
<div className="completion-evidence-line"><Tag color={comparable ? 'green' : 'gold'}>{comparable ? '口径可比' : '需谨慎解释'}</Tag><span>{comparisonReason}</span><span>贡献未解释 {pp(unexplainedContribution)}</span></div>
|
||
{compareTarget.status && <p className="completion-note">比较期目标:{text(compareTarget.status)}{typeof compareTargetValue.value === 'number' ? ` · ${pct(compareTargetValue.value)}` : ''}{compareTarget.deltaPercentagePoints !== undefined ? ` · 目标差 ${pp(compareTarget.deltaPercentagePoints)}` : ''}</p>}
|
||
</>}
|
||
{!compare && !compareError && <div className="completion-placeholder">选择比较期间类型后运行,系统将并列显示期间结果、覆盖和可比性。</div>}
|
||
</div>
|
||
</div>
|
||
</section>;
|
||
}
|
||
|
||
export function M02SavedViews({ query, view, onUnauthorized, onApply }: { query: QueryParams; view: ViewKind; onUnauthorized: (error: unknown) => boolean; onApply: (context: Partial<QueryParams>) => void }) {
|
||
const confirmDelete = useDeleteConfirmation();
|
||
const { message } = App.useApp();
|
||
const [items, setItems] = useState<Row[]>([]);
|
||
const [sharedItems, setSharedItems] = useState<Row[]>([]);
|
||
const [loading, setLoading] = useState(true);
|
||
const [error, setError] = useState('');
|
||
const [busyId, setBusyId] = useState('');
|
||
const [modalOpen, setModalOpen] = useState(false);
|
||
const [shareItem, setShareItem] = useState<Row | null>(null);
|
||
const [shareCandidates, setShareCandidates] = useState<Row[]>([]);
|
||
const [shareRows, setShareRows] = useState<Row[]>([]);
|
||
const [shareRecipient, setShareRecipient] = useState<string>();
|
||
const [shareRowVersion, setShareRowVersion] = useState(0);
|
||
const [shareLoading, setShareLoading] = useState(false);
|
||
const [sharedPreview, setSharedPreview] = useState<Row | null>(null);
|
||
const [form] = Form.useForm<{ name: string }>();
|
||
const load = async () => {
|
||
setLoading(true);
|
||
try {
|
||
const [mine, shared] = await Promise.all([api.comparisonViews(), api.sharedComparisonViews()]);
|
||
setItems(collectionItems(mine)); setSharedItems(collectionItems(shared)); setError('');
|
||
}
|
||
catch (value) { if (!onUnauthorized(value)) setError(value instanceof Error ? value.message : '比较视图读取失败'); }
|
||
finally { setLoading(false); }
|
||
};
|
||
useEffect(() => { void load(); }, []);
|
||
const refreshShareInfo = async (item: Row) => {
|
||
const id = String(item.id || ''); if (!id) return;
|
||
const [candidates, shares] = await Promise.all([api.comparisonViewShareCandidates(), api.comparisonViewShares(id)]);
|
||
setShareCandidates(collectionItems(candidates)); setShareRows(collectionItems(shares));
|
||
setShareRowVersion(Number(shares.viewRowVersion ?? item.rowVersion ?? 0));
|
||
};
|
||
const save = async () => {
|
||
try {
|
||
const values = await form.validateFields();
|
||
await api.createComparisonView({ name: values.name.trim(), context: savedViewContext(query), groupBy: view, columns: ['compositeRate', 'black', 'bright'], releaseMode: 'CURRENT' });
|
||
message.success('个人比较视图已保存'); setModalOpen(false); form.resetFields(); await load();
|
||
} catch (value) { if (value && typeof value === 'object' && 'errorFields' in value) return; if (!onUnauthorized(value)) message.error(value instanceof Error ? value.message : '保存失败'); }
|
||
};
|
||
const manageShares = async (item: Row) => {
|
||
setShareItem(item); setShareRecipient(undefined); setShareRows([]); setShareLoading(true);
|
||
try { await refreshShareInfo(item); setModalOpen(false); }
|
||
catch (value) { if (!onUnauthorized(value)) message.error(value instanceof Error ? value.message : '读取共享对象失败'); setShareItem(null); }
|
||
finally { setShareLoading(false); }
|
||
};
|
||
const addShare = async () => {
|
||
const id = String(shareItem?.id || ''); if (!id || !shareRecipient) return;
|
||
setBusyId(id); setShareLoading(true);
|
||
try {
|
||
await api.shareComparisonView(id, { recipientUserId: shareRecipient, expectedRowVersion: shareRowVersion });
|
||
message.success('已共享给所选用户'); setShareRecipient(undefined);
|
||
await refreshShareInfo(shareItem!); await load();
|
||
} catch (value) { if (!onUnauthorized(value)) message.error(value instanceof Error ? value.message : '共享失败'); }
|
||
finally { setBusyId(''); setShareLoading(false); }
|
||
};
|
||
const revokeShare = async (row: Row) => {
|
||
const id = String(shareItem?.id || ''); const recipientId = String(row.recipientUserId || '');
|
||
if (!id || !recipientId) return;
|
||
setBusyId(`${id}:${recipientId}`); setShareLoading(true);
|
||
try {
|
||
await api.revokeComparisonViewShare(id, recipientId, shareRowVersion);
|
||
message.success('已撤销共享'); await refreshShareInfo(shareItem!); await load();
|
||
} catch (value) { if (!onUnauthorized(value)) message.error(value instanceof Error ? value.message : '撤销共享失败'); }
|
||
finally { setBusyId(''); setShareLoading(false); }
|
||
};
|
||
const open = async (item: Row) => {
|
||
const id = String(item.id || ''); if (!id) return;
|
||
setBusyId(id);
|
||
try {
|
||
const result = await api.openComparisonView(id);
|
||
if (item.shared === true) {
|
||
setSharedPreview({ name: item.name, ownerDisplayName: item.ownerDisplayName, snapshot: result.snapshot });
|
||
return;
|
||
}
|
||
const saved = record(result.view);
|
||
const definition = record(saved.definition || saved);
|
||
const context = record(definition.context);
|
||
delete context.releaseId;
|
||
onApply({ ...context, view: text(definition.groupBy, 'overall') as ViewKind });
|
||
message.success('已打开比较视图,结果使用当前数据重新查询');
|
||
} catch (value) { if (!onUnauthorized(value)) message.error(value instanceof Error ? value.message : '打开视图失败'); }
|
||
finally { setBusyId(''); }
|
||
};
|
||
const remove = async (item: Row) => {
|
||
const id = String(item.id || ''); if (!id) return;
|
||
setBusyId(id);
|
||
try { await api.deleteComparisonView(id); message.success('已删除个人视图'); await load(); }
|
||
catch (value) { if (!onUnauthorized(value)) message.error(value instanceof Error ? value.message : '删除视图失败'); }
|
||
finally { setBusyId(''); }
|
||
};
|
||
const columns: ColumnsType<Row> = [
|
||
{ title: '视图名称', dataIndex: 'name', key: 'name', width: 210 },
|
||
{ title: '分组维度', key: 'groupBy', width: 140, render: (_, row) => text(record(row.definition).groupBy, '总体') },
|
||
{ title: '数据范围', key: 'dataScope', width: 180, render: () => '打开时使用当前数据' },
|
||
{ title: '操作', key: 'actions', width: 250, render: (_, row) => <span className="completion-actions"><Button type="link" loading={busyId === String(row.id)} onClick={() => void open(row)}>打开</Button><Button type="link" onClick={() => void manageShares(row)}>共享</Button><Button type="link" danger loading={busyId === String(row.id)} onClick={()=>confirmDelete({title:`删除个人视图“${text(row.name || row.title,"当前视图")}”?`,description:"确认后立即删除此个人比较视图,原始业务数据保留。",onConfirm:()=>remove(row)})}>删除</Button></span> },
|
||
];
|
||
const sharedColumns: ColumnsType<Row> = [
|
||
{ title: '视图名称', dataIndex: 'name', key: 'name', width: 230 },
|
||
{ title: '共享者', dataIndex: 'ownerDisplayName', key: 'owner', width: 160 },
|
||
{ title: '共享时间', dataIndex: 'sharedAt', key: 'sharedAt', width: 210, render: value => text(value) },
|
||
{ title: '操作', key: 'actions', width: 100, render: (_, row) => <Button type="link" loading={busyId === String(row.id)} onClick={() => void open(row)}>打开</Button> },
|
||
];
|
||
const shareColumns: ColumnsType<Row> = [
|
||
{ title: '接收人', dataIndex: 'displayName', key: 'displayName' },
|
||
{ title: '状态', key: 'valid', render: (_, row) => row.active !== true ? <Tag>已撤销</Tag> : row.valid === true ? <Tag color="green">有效</Tag> : <Tag color="orange">权限已变化</Tag> },
|
||
{ title: '操作', key: 'action', width: 100, render: (_, row) => row.active === true ? <Popconfirm title="撤销此用户的访问权限?" onConfirm={() => void revokeShare(row)}><Button type="link" danger loading={busyId === `${String(shareItem?.id)}:${String(row.recipientUserId)}`}>撤销</Button></Popconfirm> : null },
|
||
];
|
||
const sharedSnapshot = record(sharedPreview?.snapshot);
|
||
const isSharedComparison = Boolean(sharedSnapshot.current && sharedSnapshot.comparison);
|
||
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><Button icon={<SaveOutlined />} type="primary" onClick={() => { form.setFieldsValue({ name: '' }); setModalOpen(true); }}>保存当前视图</Button></div></div>
|
||
{error && <Alert showIcon type="error" message="保存视图不可用" description={error} />}
|
||
<div className="completion-section-heading"><strong>我的视图</strong></div>
|
||
{loading ? <div className="completion-loading"><Spin />读取个人视图…</div> : items.length ? <Table size="small" bordered columns={columns} dataSource={items} rowKey={item => String(item.id)} pagination={false} scroll={{ x: 850 }} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前没有已保存的个人视图" />}
|
||
<div className="completion-section-heading"><strong>共享给我的视图</strong></div>
|
||
{!loading && (sharedItems.length ? <Table size="small" bordered columns={sharedColumns} dataSource={sharedItems} rowKey={item => String(item.id)} pagination={false} scroll={{ x: 700 }} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前没有可访问的共享视图" />)}
|
||
<Modal className="management-modal" open={modalOpen} title="保存个人比较视图" okText="保存" onCancel={() => setModalOpen(false)} onOk={() => void save()}>
|
||
<Form form={form} layout="vertical"><Form.Item name="name" label="视图名称" rules={[{ required: true, whitespace: true, message: '请填写名称' }]}><Input maxLength={80} /></Form.Item></Form>
|
||
</Modal>
|
||
<Modal className="management-modal" open={shareItem !== null} title={`共享视图:${text(shareItem?.name)}`} okText="共享给所选用户" confirmLoading={shareLoading} okButtonProps={{ disabled: !shareRecipient || !shareCandidates.length }} onCancel={() => setShareItem(null)} onOk={() => void addShare()}>
|
||
<p className="completion-note">收件人仅显示当前数据范围、字段和查询权限与您相同的活跃用户。权限变化后,共享访问会自动失效。</p>
|
||
<Select {...readableSelectPopup} showSearch optionFilterProp="label" placeholder="选择收件用户" value={shareRecipient} onChange={setShareRecipient} options={shareCandidates.map(user => ({ value: String(user.id), label: String(user.displayName) }))} style={{ width: '100%', marginBottom: 16 }} loading={shareLoading} />
|
||
<Table size="small" bordered loading={shareLoading} columns={shareColumns} dataSource={shareRows} rowKey={row => String(row.recipientUserId)} pagination={false} locale={{ emptyText: '尚未共享给其他用户' }} />
|
||
</Modal>
|
||
<Modal className="management-modal" open={sharedPreview !== null} title={text(sharedPreview?.name, '共享视图')} footer={<Button type="primary" onClick={() => setSharedPreview(null)}>关闭</Button>} onCancel={() => setSharedPreview(null)}>
|
||
<p className="completion-note">共享者:{text(sharedPreview?.ownerDisplayName)} · 本次结果按你的当前权限重新计算。</p>
|
||
{isSharedComparison ? <>
|
||
<SharedQueryConditions label="当前期口径" value={sharedSnapshot.current} />
|
||
<SharedQueryConditions label="比较期口径" value={sharedSnapshot.comparison} />
|
||
<div className="completion-compare-snapshots"><SnapshotRates label="当前期间" value={sharedSnapshot.current} /><SnapshotRates label="比较期间" value={sharedSnapshot.comparison} /></div>
|
||
<div className="completion-delta-grid"><span><small>综合变化</small><strong>{pp(record(sharedSnapshot.delta).percentagePoints)}</strong></span></div>
|
||
</> : <><SharedQueryConditions label="查询口径" value={sharedPreview?.snapshot} /><SnapshotRates label="重新计算结果" value={sharedPreview?.snapshot} /></>}
|
||
</Modal>
|
||
</section>;
|
||
}
|
||
|
||
export function ScrapAnalyticsPanel({ query, onUnauthorized }: { query: QueryParams; onUnauthorized: (error: unknown) => boolean }) {
|
||
const confirmDelete = useDeleteConfirmation();
|
||
const [stage, setStage] = useState<Stage>('black');
|
||
const [dimension, setDimension] = useState('category');
|
||
const [limit, setLimit] = useState(10);
|
||
const [top, setTop] = useState<Row[]>([]);
|
||
const [busy, setBusy] = useState(false);
|
||
const [error, setError] = useState('');
|
||
const [compareError, setCompareError] = useState('');
|
||
const [compare, setCompare] = useState<Row | null>(null);
|
||
const [decomposition, setDecomposition] = useState<Row | null>(null);
|
||
const [impactResult, setImpactResult] = useState<Row | null>(null);
|
||
const [impactBusy, setImpactBusy] = useState(false);
|
||
const [impactError, setImpactError] = useState('');
|
||
const [compareBusy, setCompareBusy] = useState(false);
|
||
const [checklists, setChecklists] = useState<Row[]>([]);
|
||
const [activeChecklistId, setActiveChecklistId] = useState('');
|
||
const [checklistItems, setChecklistItems] = useState<Row[]>([]);
|
||
const [checklistBusy, setChecklistBusy] = useState(false);
|
||
const [checklistError, setChecklistError] = useState('');
|
||
const [checklistModal, setChecklistModal] = useState(false);
|
||
const [checklistTitle, setChecklistTitle] = useState('');
|
||
const [topResultId, setTopResultId] = useState('');
|
||
const [topResultQuery, setTopResultQuery] = useState<Row>({});
|
||
const [topShareBasis, setTopShareBasis] = useState('');
|
||
const [comparisonYear, setComparisonYear] = useState(query.year - 1);
|
||
const [comparisonMonth, setComparisonMonth] = useState(query.month);
|
||
const [comparisonQuarter, setComparisonQuarter] = useState(query.quarter);
|
||
|
||
useEffect(() => { setCompare(null); setDecomposition(null); setImpactResult(null); setCompareError(''); setImpactError(''); }, [JSON.stringify(query), stage, dimension, comparisonYear, comparisonMonth, comparisonQuarter]);
|
||
const loadChecklists = async (preferredId?: string) => {
|
||
try {
|
||
const response = await api.checklists(); const rows = list(response.items); setChecklists(rows);
|
||
const target = preferredId || activeChecklistId || String(rows[0]?.id || '');
|
||
setActiveChecklistId(target);
|
||
if (target) {
|
||
const detail = await api.checklist(target);
|
||
setChecklistItems(list(detail.items));
|
||
} else setChecklistItems([]);
|
||
setChecklistError('');
|
||
} catch (value) { if (!onUnauthorized(value)) setChecklistError(value instanceof Error ? value.message : '个人核查清单读取失败'); }
|
||
};
|
||
useEffect(() => { void loadChecklists(); }, []);
|
||
const currentBody = useMemo(() => objectContext(query), [query]);
|
||
useEffect(() => {
|
||
let alive = true; setBusy(true); setError(''); setTop([]); setTopResultId(''); setTopResultQuery({}); setTopShareBasis('');
|
||
api.analyticsTop({ ...currentBody, stage, dimension, limit }).then(value => { if (alive) { setTop(list(value.rows)); setTopResultId(text(value.resultId, '')); setTopResultQuery(record(value.resultQuery)); setTopShareBasis(text(value.shareBasis, '')); } })
|
||
.catch(value => { if (alive && !onUnauthorized(value)) setError(value instanceof Error ? value.message : '排名读取失败'); })
|
||
.finally(() => { if (alive) setBusy(false); });
|
||
return () => { alive = false; };
|
||
}, [JSON.stringify(currentBody), stage, dimension, limit, onUnauthorized]);
|
||
|
||
const runChangeAnalysis = async () => {
|
||
setCompareBusy(true); setCompareError(''); setCompare(null); setDecomposition(null);
|
||
const body = comparisonBody(query, { year: comparisonYear, ...(comparisonMonth ? { month: comparisonMonth } : {}), ...(comparisonQuarter ? { quarter: comparisonQuarter } : {}) });
|
||
try {
|
||
const comparisonResult = await api.analyticsCompare(body);
|
||
setCompare(comparisonResult);
|
||
if (['department', 'group', 'product', 'projectGroup'].includes(dimension)) {
|
||
const structureResult = await api.structureDecomposition({ stage, dimension, current: { ...currentBody, year: query.year, ...(query.month ? { month: query.month } : {}), ...(query.quarter ? { quarter: query.quarter } : {}) }, comparison: { ...currentBody, year: comparisonYear, ...(comparisonMonth ? { month: comparisonMonth } : {}), ...(comparisonQuarter ? { quarter: comparisonQuarter } : {}) } });
|
||
setDecomposition(structureResult);
|
||
} else setDecomposition(null);
|
||
} catch (value) { if (!onUnauthorized(value)) setCompareError(value instanceof Error ? value.message : '影响分析失败'); }
|
||
finally { setCompareBusy(false); }
|
||
};
|
||
const addEvidence = async (row: Row) => {
|
||
if (!activeChecklistId || !topResultId) return;
|
||
setChecklistBusy(true);
|
||
try {
|
||
const releaseId = text(topResultQuery.releaseId, '');
|
||
if (!releaseId) throw new Error('服务端没有返回可引用的排名结果,无法保存核查项');
|
||
const subject = `${stage === 'black' ? '黑片' : '亮片'} · ${dimension === 'category' ? '原报废类别' : dimension} · ${text(row.label)}`;
|
||
const findings = `已确认事实:报废重量 ${text(row.weight)} kg;服务端排名分母 ${text(row.denominator)} kg;单项占比 ${pct(row.share)};来源覆盖行数 ${text(record(row.coverage).rows)}。`;
|
||
const checks = `待核查动作:按原始来源明细核对该排名对象的阶段、分类及重量汇总,并记录核对结论。`;
|
||
await api.addChecklistItem(activeChecklistId, {
|
||
resultId: topResultId, resultKind: 'top', resultQuery: topResultQuery,
|
||
releaseId, context: currentBody,
|
||
title: `${stage === 'black' ? '黑片' : '亮片'} · ${text(row.label)}`,
|
||
subject,
|
||
findings,
|
||
unconfirmed: '未确认推断:当前排名只反映所选条件下的重量排序,尚未由原始行复核原因或责任归属。',
|
||
checks,
|
||
evidenceRefs: [{ type: 'TOP_RESULT', value: topResultId }, ...(row.sourceCategory ? [{ type: 'SOURCE_CATEGORY', value: row.sourceCategory }] : [])],
|
||
});
|
||
const detail = await api.checklist(activeChecklistId); setChecklistItems(list(detail.items)); setChecklistError('');
|
||
} catch (value) { if (!onUnauthorized(value)) setChecklistError(value instanceof Error ? value.message : '保存核查证据失败'); }
|
||
finally { setChecklistBusy(false); }
|
||
};
|
||
const runObjectImpact = async () => {
|
||
if (!['department', 'group', 'product', 'projectGroup'].includes(dimension)) return;
|
||
setImpactBusy(true); setImpactError(''); setImpactResult(null);
|
||
const toSide = (period: { year: number; month?: number; quarter?: number }) => {
|
||
const filters = objectContext(query);
|
||
delete filters.view; delete filters.year; delete filters.month; delete filters.quarter; delete filters.releaseId;
|
||
return { ...filters, ...(query.releaseId ? { releaseId: query.releaseId } : {}), ...period };
|
||
};
|
||
try {
|
||
const result = await api.analyticsImpact({
|
||
stage, dimension,
|
||
current: toSide({ year: query.year, ...(query.month ? { month: query.month } : {}), ...(query.quarter ? { quarter: query.quarter } : {}) }),
|
||
comparison: toSide({ year: comparisonYear, ...(comparisonMonth ? { month: comparisonMonth } : {}), ...(comparisonQuarter ? { quarter: comparisonQuarter } : {}) }),
|
||
});
|
||
setImpactResult(result);
|
||
} catch (value) { if (!onUnauthorized(value)) setImpactError(value instanceof Error ? value.message : '对象影响分析失败'); }
|
||
finally { setImpactBusy(false); }
|
||
};
|
||
const createChecklist = async () => {
|
||
const title = checklistTitle.trim(); if (!title) return;
|
||
setChecklistBusy(true);
|
||
try {
|
||
const created = await api.createChecklist({ title });
|
||
const id = text(created.id, ''); setChecklistTitle(''); setChecklistModal(false);
|
||
await loadChecklists(id);
|
||
} catch (value) { if (!onUnauthorized(value)) setChecklistError(value instanceof Error ? value.message : '创建核查清单失败'); }
|
||
finally { setChecklistBusy(false); }
|
||
};
|
||
const removeChecklistItem = async (item: Row) => {
|
||
if (!activeChecklistId || !item.id) return;
|
||
setChecklistBusy(true);
|
||
try { await api.deleteChecklistItem(activeChecklistId, String(item.id)); const detail = await api.checklist(activeChecklistId); setChecklistItems(list(detail.items)); }
|
||
catch (value) { if (!onUnauthorized(value)) setChecklistError(value instanceof Error ? value.message : '移除核查证据失败'); }
|
||
finally { setChecklistBusy(false); }
|
||
};
|
||
const topColumns: ColumnsType<Row> = [
|
||
{ title: '排名', dataIndex: 'rank', key: 'rank', align: 'center', width: 70 },
|
||
{ title: dimension === 'category' ? '原报废类别' : '分析对象', dataIndex: 'label', key: 'label', fixed: 'left', width: 230, render: (_, row) => <span className="object-cell"><strong>{text(row.label)}</strong>{Boolean(row.sourceCategory) && <small>原始类别:{text(row.sourceCategory)}</small>}</span> },
|
||
{ title: '报废重量 / kg', dataIndex: 'weight', key: 'weight', align: 'right', width: 150, render: value => text(value) },
|
||
{ title: '占比分母 / kg', dataIndex: 'denominator', key: 'denominator', align: 'right', width: 160, render: value => text(value) },
|
||
{ title: '占比', dataIndex: 'share', key: 'share', align: 'right', width: 110, render: value => pct(value) },
|
||
{ title: '覆盖行数', key: 'coverage', width: 105, align: 'right', render: (_, row) => text(record(row.coverage).rows) },
|
||
{ title: '核查', key: 'evidence', width: 110, render: (_, row) => <Button type="link" loading={checklistBusy} disabled={!activeChecklistId || !topResultId} onClick={() => void addEvidence(row)}>加入清单</Button> },
|
||
];
|
||
const groupRows = list(record(decomposition).groups);
|
||
const groupColumns: ColumnsType<Row> = [
|
||
{ title: '对象', dataIndex: 'key', key: 'key', fixed: 'left', width: 180 },
|
||
{ title: '状态', dataIndex: 'status', key: 'status', width: 110, render: value => <Tag>{text(value)}</Tag> },
|
||
{ title: '当前 / 比较结构占比', key: 'share', align: 'right', width: 180, render: (_, row) => `${pct(row.currentShare)} / ${pct(row.comparisonShare)}` },
|
||
{ title: '当前 / 比较率', key: 'rate', align: 'center', width: 170, render: (_, row) => `${pct(row.currentRate)} / ${pct(row.comparisonRate)}` },
|
||
{ title: '表现贡献', dataIndex: 'performancePP', key: 'performancePP', align: 'right', width: 140, render: pp },
|
||
{ title: '结构贡献', dataIndex: 'mixPP', key: 'mixPP', align: 'right', width: 140, render: pp },
|
||
];
|
||
const compareResult = record(compare);
|
||
const delta = record(compareResult.delta);
|
||
const legacyDelta = record(compareResult.deltaPP);
|
||
const contributions = record(compareResult.contributions);
|
||
const comparePp = delta.percentagePoints ?? legacyDelta.composite ?? legacyDelta.compositeRate;
|
||
const blackPp = contributions.black ?? contributions.blackPP;
|
||
const brightPp = contributions.bright ?? contributions.brightPP;
|
||
const unexplainedPp = contributions.unexplained ?? contributions.unexplainedPP ?? contributions.roundingResidualPP ?? contributions.residualPP;
|
||
const comparable = record(compareResult.comparability);
|
||
const comparisonReason = Array.isArray(comparable.reasons)
|
||
? (comparable.reasons as unknown[]).map(String).join(';') || text(comparable.coverageNotice, '比较状态由服务端返回')
|
||
: text(comparable.reason || comparable.coverageNotice, '比较状态由服务端返回');
|
||
const available = decomposition?.available === true;
|
||
const checklistColumns: ColumnsType<Row> = [
|
||
{ title: '核查事项', dataIndex: 'title', key: 'title', fixed: 'left', width: 250 },
|
||
{ title: '阶段 / 对象', dataIndex: 'subject', key: 'subject', width: 260, render: value => typeof value === 'string' ? value : (() => { const subject = record(value); return `${subject.stage === 'black' ? '黑片' : subject.stage === 'bright' ? '亮片' : '—'} · ${text(subject.label)}`; })() },
|
||
{ title: '重算综合率', key: 'snapshot', align: 'right', width: 130, render: (_, row) => { const summary = record(record(row.metricSnapshot || row.snapshot).summary); return pct(summary.compositeRate); } },
|
||
{ title: '证据状态', key: 'evidence', width: 125, render: (_, row) => row.evidenceAvailable === false ? <Tag color="gold">当前不可见</Tag> : <Tag color="green">已重新授权</Tag> },
|
||
{ title: '操作', key: 'remove', width: 90, render: (_, row) => <Button type="link" danger loading={checklistBusy} onClick={() => confirmDelete({title:`移除核查证据“${text(row.title || row.label || row.name || row.objectKey,"当前证据")}”?`,description:"仅从核查清单中移除这项证据,原始业务数据保留;确认后立即生效。",confirmText:"确认移除",onConfirm:()=>removeChecklistItem(row)})}>移除</Button> },
|
||
];
|
||
const impactRows = list(impactResult?.groups);
|
||
const impactColumns: ColumnsType<Row> = [
|
||
{ title: '对象', dataIndex: 'label', key: 'label', fixed: 'left', width: 190 },
|
||
{ title: '状态', dataIndex: 'status', key: 'status', width: 100, render: value => <Tag>{text(value)}</Tag> },
|
||
{ title: '当前 / 比较重量', key: 'weights', align: 'right', width: 180, render: (_, row) => `${text(row.currentWeight)} / ${text(row.comparisonWeight)}` },
|
||
{ title: '当前 / 比较结构占比', key: 'share', align: 'right', width: 190, render: (_, row) => `${pct(row.currentShare)} / ${pct(row.comparisonShare)}` },
|
||
{ title: '当前 / 比较率', key: 'rates', align: 'right', width: 170, render: (_, row) => `${pct(row.currentRate)} / ${pct(row.comparisonRate)}` },
|
||
{ title: '重量变化', dataIndex: 'weightDelta', key: 'weightDelta', align: 'right', width: 120 },
|
||
{ title: '表现 / 结构 / 总影响', key: 'impact', align: 'right', width: 230, render: (_, row) => `${pp(row.performancePP)} / ${pp(row.mixPP)} / ${pp(row.impactPP)}` },
|
||
{ title: '当前 / 比较行数', key: 'rows', align: 'right', width: 160, render: (_, row) => `${text(row.currentRows)} / ${text(row.comparisonRows)}` },
|
||
];
|
||
|
||
return <div className="completion-scrap-stack">
|
||
<section className="panel section-panel completion-tools">
|
||
<div className="completion-panel-heading"><div><strong>本期报废排名</strong><span>当前期间损失按重量降序;占比分母:{topShareBasis || '服务端未返回口径'};只展示服务端返回的单项占比,不计算累计 TOP 阈值</span></div><Button icon={<ReloadOutlined />} loading={busy} onClick={() => { setBusy(true); setTopShareBasis(''); api.analyticsTop({ ...currentBody, stage, dimension, limit }).then(value => { setTop(list(value.rows)); setTopResultId(text(value.resultId, '')); setTopResultQuery(record(value.resultQuery)); setTopShareBasis(text(value.shareBasis, '')); }).catch(value => { if (!onUnauthorized(value)) setError(value instanceof Error ? value.message : '排名读取失败'); }).finally(() => setBusy(false)); }}>刷新排名</Button></div>
|
||
<div className="completion-filter-row"><Segmented value={stage} options={[{ label: '黑片', value: 'black' }, { label: '亮片', value: 'bright' }]} onChange={value => setStage(value as Stage)} aria-label="报废阶段" /><Select value={dimension} onChange={setDimension} aria-label="排名维度" options={[{ label: '原报废类别', value: 'category' }, { label: '产业部', value: 'department' }, { label: '业务分组', value: 'group' }, { label: '产品', value: 'product' }, { label: '项目组', value: 'projectGroup' }]} /><Select value={limit} onChange={setLimit} aria-label="显示排名数量" options={[10, 20, 50].map(value => ({ label: `TOP ${value}`, value }))} /></div>
|
||
{error && <Alert showIcon type="error" message="报废排名不可用" description={error} />}
|
||
{busy ? <div className="completion-loading"><Spin />读取排名…</div> : top.length ? <Table size="small" bordered columns={topColumns} dataSource={top} rowKey={row => String(row.key || row.rank)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1040 }} /> : !error && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前条件没有报废排名数据" />}
|
||
</section>
|
||
|
||
<section className="panel section-panel completion-tools">
|
||
<div className="completion-panel-heading"><div><strong>阶段贡献与影响分解</strong><span>比较服务端正式率,并核对阶段贡献与结构分解前提</span></div></div>
|
||
<div className="completion-filter-row"><label className="completion-compare-period">比较年份<InputNumber min={2000} max={2200} value={comparisonYear} onChange={value => value && setComparisonYear(value)} /></label>{query.month && <Select aria-label="比较月份" value={comparisonMonth} onChange={setComparisonMonth} options={Array.from({ length: 12 }, (_, index) => ({ label: `${index + 1}月`, value: index + 1 }))} />}{query.quarter && <Select aria-label="比较季度" value={comparisonQuarter} onChange={setComparisonQuarter} options={[1, 2, 3, 4].map(value => ({ label: `第${value}季度`, value }))} />}<Button type="primary" loading={compareBusy} onClick={() => void runChangeAnalysis()}>执行同期影响分析</Button></div>
|
||
{compareError && <Alert showIcon type="error" message="期间比较失败" description={compareError} />}
|
||
{compare && <>
|
||
<div className="completion-delta-grid"><span><small>综合变化</small><strong>{pp(comparePp)}</strong></span><span><small>黑片贡献</small><strong>{pp(blackPp)}</strong></span><span><small>亮片贡献</small><strong>{pp(brightPp)}</strong></span><span><small>未解释</small><strong>{pp(unexplainedPp)}</strong></span></div>
|
||
<div className="completion-contribution"><span>比较可比性 <strong>{comparable.comparable === true ? '可比' : comparable.comparable === false ? '不可比' : '未确定'}</strong></span><span>覆盖可比 <strong>{comparable.coverageAligned === true ? '是' : comparable.coverageAligned === false ? '否' : '—'}</strong></span><span>{comparisonReason}</span></div>
|
||
</>}
|
||
{decomposition && <><Alert showIcon type={available ? 'info' : 'warning'} message={available ? `结构分解可用 · ${text(decomposition.methodId)}` : '结构分解前提未满足'} description={available ? `表现 ${pp(decomposition.performancePP)} · 结构 ${pp(decomposition.mixPP)} · 交互 ${pp(decomposition.interactionPP)} · 未解释 ${pp(decomposition.unexplainedPP)}` : text(decomposition.reason, '服务端未提供分解原因')} /><div className="completion-table-wrap">{groupRows.length > 0 && <Table size="small" bordered columns={groupColumns} dataSource={groupRows} rowKey={row => String(row.key)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 950 }} />}</div></>}
|
||
{['department', 'group', 'product', 'projectGroup'].includes(dimension) ? <div className="completion-impact-tools"><Button onClick={() => void runObjectImpact()} loading={impactBusy}>执行对象影响分析</Button>{impactError && <Alert showIcon type="error" message="对象影响分析失败" description={impactError} />}{impactResult && <><Alert showIcon type={impactResult.available === true ? 'info' : 'warning'} message={impactResult.available === true ? `对象影响可用 · ${text(impactResult.methodId)}` : '对象影响暂不可用'} description={impactResult.available === true ? `总体变化 ${pp(impactResult.deltaPP)} · 对象影响合计 ${pp(impactResult.totalImpactPP)} · 未解释 ${pp(impactResult.unexplainedPP)}${impactResult.assumptions ? ` · ${text(impactResult.assumptions)}` : ''}` : text(impactResult.reason, '服务端未提供不可用原因')} />{impactRows.length > 0 && <Table size="small" bordered columns={impactColumns} dataSource={impactRows} rowKey={row => String(row.key)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 1390 }} />}</>}</div> : <Alert showIcon type="info" message="对象影响分析需选择分类以外的分析维度" description="当前原报废类别不是可加总对象维度;请选择产业部、业务分组、产品或项目组后运行对象影响分析。" />}
|
||
{compare && dimension === 'category' && <Alert showIcon type="info" message="类别排名已完成期间比较" description="原报废类别不是结构分解维度。选择产业部、业务分组、产品或项目组后,可查看对应结构分解。" />}
|
||
{compareBusy && <div className="completion-loading"><Spin />正在对齐比较期间与指标口径…</div>}
|
||
{!compare && !decomposition && !compareBusy && <div className="completion-placeholder">选择比较期间后运行。规则口径、覆盖、阶段缺失和结构分组由服务端判断。</div>}
|
||
</section>
|
||
|
||
<section className="panel section-panel completion-tools">
|
||
<div className="completion-panel-heading"><div><strong>个人核查清单</strong><span>私有持久化;打开时按当前授权范围重新计算快照</span></div><div className="completion-actions"><Select {...readableSelectPopup} aria-label="选择个人核查清单" placeholder="选择清单" value={activeChecklistId || undefined} options={checklists.map(item => ({ label: text(item.title || item.name), value: String(item.id) }))} onChange={value => { setActiveChecklistId(value); setChecklistBusy(true); api.checklist(value).then(detail => setChecklistItems(list(detail.items))).catch(valueError => { if (!onUnauthorized(valueError)) setChecklistError(valueError instanceof Error ? valueError.message : '清单打开失败'); }).finally(() => setChecklistBusy(false)); }} /><Button icon={<ReloadOutlined />} loading={checklistBusy} onClick={() => void loadChecklists()}>刷新</Button><Button type="primary" icon={<PlusOutlined />} onClick={() => setChecklistModal(true)}>新建清单</Button></div></div>
|
||
{checklistError && <Alert showIcon type="error" message="个人核查清单操作失败" description={checklistError} />}
|
||
{checklistBusy ? <div className="completion-loading"><Spin />读取清单与重新计算快照…</div> : checklistItems.length ? <Table size="small" bordered columns={checklistColumns} dataSource={checklistItems} rowKey={row => String(row.id)} pagination={false} expandable={{ expandedRowRender: row => <div className="completion-checklist-evidence"><div><strong>已确认事实</strong><p>{text(row.findings, '—')}</p></div><div><strong>未确认推断</strong><p>{text(row.unconfirmed, '无')}</p></div><div><strong>待核查动作</strong><p>{text(row.checks, '—')}</p></div></div> }} scroll={{ x: 920 }} /> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={activeChecklistId ? '当前清单没有核查项目;从上方排名加入结果' : '创建个人清单后,可保存排名结果及其服务端查询指纹'} />}
|
||
{!activeChecklistId && top.length > 0 && <p className="completion-note">请先创建或选择清单;加入操作将保存服务端结果指纹、完整查询条件与可见快照,不使用排名序号充当证据编号。</p>}
|
||
<Modal className="management-modal" open={checklistModal} title="新建个人核查清单" okText="创建清单" confirmLoading={checklistBusy} onCancel={() => setChecklistModal(false)} onOk={() => void createChecklist()}><Input autoFocus value={checklistTitle} maxLength={160} placeholder="清单名称" onChange={event => setChecklistTitle(event.target.value)} onPressEnter={() => void createChecklist()} /></Modal>
|
||
</section>
|
||
</div>;
|
||
}
|
||
|
||
export function TargetVersionAdmin({ onUnauthorized }: { onUnauthorized: (error: unknown) => boolean }) {
|
||
const confirmDelete = useDeleteConfirmation();
|
||
const { message } = App.useApp();
|
||
const [items, setItems] = useState<Row[]>([]);
|
||
const [loading, setLoading] = useState(true);
|
||
const [error, setError] = useState('');
|
||
const [editing, setEditing] = useState<Row | null>(null);
|
||
const [busy, setBusy] = useState(false);
|
||
const [targetRows, setTargetRows] = useState<Row[]>([]);
|
||
const [targetYears, setTargetYears] = useState<number[]>([2026, 2027, 2028]);
|
||
const [referenceNames, setReferenceNames] = useState<Row>({ departments: [], groups: [], groupDepartments: {} });
|
||
const retiredDepartments = new Set(['美洲产业部', '欧洲产业部', '欧洲磁钢']);
|
||
const normalizeDepartment = (value: unknown) => {
|
||
const department = String(value || '').trim();
|
||
return department === '质量管理部' ? '质量中心' : department;
|
||
};
|
||
const isRetiredDepartment = (value: unknown) => retiredDepartments.has(normalizeDepartment(value));
|
||
const dimensionKeys = ['department', 'group', 'product', 'projectGroup'] as const;
|
||
const dimensionLabels: Record<(typeof dimensionKeys)[number], string> = {
|
||
department: '产业部', group: '业务分组', product: '产品', projectGroup: '项目组',
|
||
};
|
||
const metricOptions = [
|
||
{ label: '综合合格率', value: 'COMPOSITE_RATE' },
|
||
{ label: '黑片合格率', value: 'BLACK_RATE' },
|
||
{ label: '亮片合格率', value: 'BRIGHT_RATE' },
|
||
{ label: '综合合格率(不含本部报废)', value: 'COMPOSITE_RATE_WITHOUT_HEADQUARTERS_SCRAP' },
|
||
{ label: '亮片合格率(不含本部报废)', value: 'BRIGHT_RATE_WITHOUT_HEADQUARTERS_SCRAP' },
|
||
];
|
||
const hasScope = (row: Row) => dimensionKeys.some(key => String(row[key] || '').trim());
|
||
const rowKey = () => `target-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
|
||
const newRow = (editorScope: boolean, dimensions: Row = {}): Row => ({
|
||
editorKey: rowKey(), editorScope, metric: 'COMPOSITE_RATE', values: {}, metadataByYear: {},
|
||
department: '', group: '', product: '', projectGroup: '', ...dimensions,
|
||
});
|
||
const patchRow = (row: Row, patch: Row) => {
|
||
const key = String(row.editorKey || '');
|
||
setTargetRows(current => current.map(item => String(item.editorKey || '') === key ? { ...item, ...patch } : item));
|
||
};
|
||
const patchCell = (row: Row, year: number, value: number | null) => {
|
||
const key = String(row.editorKey || '');
|
||
setTargetRows(current => current.map(item => String(item.editorKey || '') === key
|
||
? { ...item, values: { ...record(item.values), [String(year)]: value } }
|
||
: item));
|
||
};
|
||
const removeRow = (row: Row) => confirmDelete({title:`删除“${dimensionKeys.map(key=>String(row[key]||'')).filter(Boolean).join(' / ') || '总体'}”的目标行?`,description:`将移除当前编辑内容中“${metricOptions.find(item=>item.value===row.metric)?.label || '所选指标'}”及其各年度目标,保存目标后生效。`,onConfirm:()=>{const key=String(row.editorKey || '');setTargetRows(current=>current.filter(item=>String(item.editorKey || '')!==key));}});
|
||
const isScopeRow = (row: Row) => row.editorScope === true;
|
||
const overallRows = targetRows.filter(row => !isScopeRow(row));
|
||
const scopeRows = targetRows.filter(isScopeRow);
|
||
const referenceGroupDepartments = record(referenceNames.groupDepartments);
|
||
const departmentOptions = [...new Set([
|
||
...listOfNames(referenceNames.departments),
|
||
...scopeRows.map(row => normalizeDepartment(row.department)),
|
||
].filter(value => value && !isRetiredDepartment(value)))].map(value => ({ label: value, value }));
|
||
const groupOptionsFor = (row: Row) => {
|
||
const department = normalizeDepartment(row.department);
|
||
return [...new Set([
|
||
...listOfNames(referenceNames.groups).filter(group => {
|
||
const owner = normalizeDepartment(referenceGroupDepartments[group]);
|
||
return !isRetiredDepartment(owner) && (!department || !owner || owner === department);
|
||
}),
|
||
String(row.group || '').trim(),
|
||
].filter(Boolean))].map(value => ({ label: value, value }));
|
||
};
|
||
const metricColumn: ColumnsType<Row>[number] = {
|
||
title: '指标', dataIndex: 'metric', key: 'metric', width: 150, align: 'center',
|
||
render: (value, row) => <Select classNames={{ popup: { root: 'target-editor-select-popup' } }} popupMatchSelectWidth={320} aria-label="目标指标" value={text(value, 'COMPOSITE_RATE')} options={metricOptions} onChange={metric => patchRow(row, { metric })} />,
|
||
};
|
||
const rateColumns: ColumnsType<Row> = targetYears.map(year => ({
|
||
title: String(year), key: `year-${year}`, width: 116, align: 'center',
|
||
render: (_value, row) => {
|
||
const raw = record(row.values)[String(year)];
|
||
const value = raw === null || raw === undefined || raw === '' ? null : Number(raw);
|
||
return <span className="target-editor-rate">
|
||
<InputNumber min={0} max={100} step={0.1} precision={2} value={value}
|
||
onChange={next => patchCell(row, year, next)} aria-label={`${year}年合格率目标百分比`} />
|
||
{value !== null && <span>%</span>}
|
||
</span>;
|
||
},
|
||
}));
|
||
const overallColumns: ColumnsType<Row> = [
|
||
metricColumn, ...rateColumns,
|
||
{ title: '操作', key: 'actions', width: 48, fixed: 'right', align: 'center', render: (_, row) => <Button aria-label="删除总体目标行" title="删除" danger type="text" icon={<DeleteOutlined />} onClick={() => removeRow(row)} /> },
|
||
];
|
||
const scopeColumns: ColumnsType<Row> = [
|
||
metricColumn,
|
||
...dimensionKeys.map(key => ({
|
||
title: key === 'department' ? '产业部 / 地区' : dimensionLabels[key], dataIndex: key, key,
|
||
width: key === 'department' || key === 'group' ? 158 : 132, align: 'center' as const,
|
||
render: (value: unknown, row: Row) => key === 'department' || key === 'group'
|
||
? <Select classNames={{ popup: { root: 'target-editor-select-popup' } }} popupMatchSelectWidth={260}
|
||
showSearch optionFilterProp="label" allowClear aria-label={key === 'department' ? '产业部 / 地区' : '业务分组'}
|
||
value={String(value || '') || undefined}
|
||
options={key === 'department' ? departmentOptions : groupOptionsFor(row)}
|
||
onChange={selected => patchRow(row, { [key]: selected || '', editorScope: true })} />
|
||
: <Input value={String(value || '')}
|
||
aria-label={dimensionLabels[key]} maxLength={190}
|
||
onChange={event => patchRow(row, { [key]: event.target.value, editorScope: true })} />,
|
||
})),
|
||
...rateColumns,
|
||
{ title: '操作', key: 'actions', width: 48, fixed: 'right', align: 'center', render: (_, row) => <Button aria-label="删除范围目标行" title="删除" danger type="text" icon={<DeleteOutlined />} onClick={() => removeRow(row)} /> },
|
||
];
|
||
const load = async () => {
|
||
setLoading(true);
|
||
try { const response = await api.targetVersions(); setItems(collectionItems(response)); setError(''); }
|
||
catch (value) { if (!onUnauthorized(value)) setError(value instanceof Error ? value.message : '质量目标读取失败'); }
|
||
finally { setLoading(false); }
|
||
};
|
||
useEffect(() => { void load(); }, []);
|
||
const open = async (item: Row) => {
|
||
const id = String(item.id || ''); if (!id) return;
|
||
setBusy(true); setError('');
|
||
try {
|
||
const detail = await api.targetVersion(id);
|
||
const version = record(detail.version || item);
|
||
let references: Row = { departments: [], groups: [], groupDepartments: {} };
|
||
try { references = record(await api.referenceNames()); }
|
||
catch (referenceError) {
|
||
if (onUnauthorized(referenceError)) throw referenceError;
|
||
message.warning('产业部和业务分组名录暂不可读,仍可编辑已有目标。');
|
||
}
|
||
setReferenceNames(references);
|
||
const annualTargets = list(detail.targets).filter(target => String(target.periodType || '').toUpperCase() === 'YEAR');
|
||
const years = [...new Set([2026, 2027, 2028, ...annualTargets.map(target => Number(target.year)).filter(year => Number.isInteger(year) && year >= 2000 && year <= 2100)])].sort((a, b) => a - b);
|
||
const metrics = [...new Set(['COMPOSITE_RATE', ...annualTargets.map(target => String(target.metric || '').toUpperCase()).filter(metric => metricOptions.some(option => option.value === metric))])];
|
||
const overallByMetric = new Map<string, Row>();
|
||
const scopeByKey = new Map<string, Row>();
|
||
const scopeSignature = (metric: string, dimensions: Row) => JSON.stringify([metric, ...dimensionKeys.map(key => String(dimensions[key] || '').trim())]);
|
||
const ensureOverall = (metric: string) => {
|
||
const existing = overallByMetric.get(metric);
|
||
if (existing) return existing;
|
||
const created = newRow(false, { metric });
|
||
overallByMetric.set(metric, created);
|
||
return created;
|
||
};
|
||
const ensureScope = (metric: string, dimensions: Row) => {
|
||
const normalized = { ...dimensions, department: normalizeDepartment(dimensions.department) };
|
||
const key = scopeSignature(metric, normalized);
|
||
const existing = scopeByKey.get(key);
|
||
if (existing) return existing;
|
||
const created = newRow(true, { ...normalized, metric });
|
||
scopeByKey.set(key, created);
|
||
return created;
|
||
};
|
||
for (const metric of metrics) ensureOverall(metric);
|
||
const departments = Array.isArray(references.departments) ? references.departments.map(value => String(value || '').trim()).filter(value => value && !isRetiredDepartment(value)) : [];
|
||
const groups = Array.isArray(references.groups) ? references.groups.map(value => String(value || '').trim()).filter(Boolean) : [];
|
||
const groupDepartments = record(references.groupDepartments);
|
||
for (const department of [...new Set(departments)]) ensureScope('COMPOSITE_RATE', { department });
|
||
for (const group of [...new Set(groups)]) if (!isRetiredDepartment(groupDepartments[group])) ensureScope('COMPOSITE_RATE', { department: groupDepartments[group] ? normalizeDepartment(groupDepartments[group]) : '', group });
|
||
annualTargets.forEach(target => {
|
||
const year = Number(target.year);
|
||
const metric = String(target.metric || '').toUpperCase();
|
||
if (!Number.isInteger(year) || !metricOptions.some(option => option.value === metric)) return;
|
||
const dimensions = record(target.dimensions);
|
||
if (isRetiredDepartment(dimensions.department)) return;
|
||
const scoped = dimensionKeys.some(key => String(dimensions[key] || '').trim());
|
||
const row = scoped ? ensureScope(metric, dimensions) : ensureOverall(metric);
|
||
row.values = { ...record(row.values), [String(year)]: Number(target.value) * 100 };
|
||
row.metadataByYear = { ...record(row.metadataByYear), [String(year)]: { source: target.source, note: target.note } };
|
||
});
|
||
if (!annualTargets.length) {
|
||
const defaultOverall = ensureOverall('COMPOSITE_RATE');
|
||
defaultOverall.values = { ...record(defaultOverall.values), '2026': 95.5 };
|
||
}
|
||
const matrixRows = [...overallByMetric.values(), ...scopeByKey.values()];
|
||
if (!scopeByKey.size) matrixRows.push(newRow(true));
|
||
setTargetYears(years); setTargetRows(matrixRows);
|
||
setEditing({ ...version, targets: annualTargets });
|
||
} catch (value) { if (!onUnauthorized(value)) setError(value instanceof Error ? value.message : '目标规则详情读取失败'); }
|
||
finally { setBusy(false); }
|
||
};
|
||
const save = async () => {
|
||
if (!editing?.id) return;
|
||
try {
|
||
const targets: Row[] = [];
|
||
for (const target of overallRows) {
|
||
if (!metricOptions.some(option => option.value === target.metric)) { message.warning('请选择有效的总体目标指标。'); return; }
|
||
for (const year of targetYears) {
|
||
const raw = record(target.values)[String(year)];
|
||
if (raw === null || raw === undefined || raw === '') continue;
|
||
const percent = Number(raw);
|
||
if (!Number.isFinite(percent) || percent < 0 || percent > 100) { message.warning('总体目标合格率请填写 0–100。'); return; }
|
||
const metadata = record(record(target.metadataByYear)[String(year)]);
|
||
targets.push({ metric: target.metric, periodType: 'YEAR', year, dimensions: {}, value: percent / 100, unit: 'RATE', ...(metadata.source ? { source: metadata.source } : {}), ...(metadata.note ? { note: metadata.note } : {}) });
|
||
}
|
||
}
|
||
if (!targets.some(target => Object.keys(record(target.dimensions)).length === 0)) { message.warning('请至少填写一项总体年度目标。'); return; }
|
||
for (const target of scopeRows) {
|
||
if (!metricOptions.some(option => option.value === target.metric)) { message.warning('请选择有效的范围目标指标。'); return; }
|
||
const dimensions: Row = {};
|
||
for (const key of dimensionKeys) if (String(target[key] || '').trim()) dimensions[key] = String(target[key]).trim();
|
||
if (retiredDepartments.has(String(dimensions.department || ''))) { message.warning('已取消的产业部不能配置目标。'); return; }
|
||
if (!hasScope(dimensions)) {
|
||
if (targetYears.some(year => record(target.values)[String(year)] !== null && record(target.values)[String(year)] !== undefined && record(target.values)[String(year)] !== '')) {
|
||
message.warning('请先填写产业部 / 地区、业务分组、产品或项目组,再填写范围目标。'); return;
|
||
}
|
||
continue;
|
||
}
|
||
for (const year of targetYears) {
|
||
const raw = record(target.values)[String(year)];
|
||
if (raw === null || raw === undefined || raw === '') continue; // Blank cells inherit the overall annual target.
|
||
const percent = Number(raw);
|
||
if (!Number.isFinite(percent) || percent < 0 || percent > 100) { message.warning('范围目标合格率请填写 0–100。'); return; }
|
||
const metadata = record(record(target.metadataByYear)[String(year)]);
|
||
targets.push({ metric: target.metric, periodType: 'YEAR', year, dimensions, value: percent / 100, unit: 'RATE', ...(metadata.source ? { source: metadata.source } : {}), ...(metadata.note ? { note: metadata.note } : {}) });
|
||
}
|
||
}
|
||
setBusy(true);
|
||
await api.updateCurrentTargets({ targets, expectedRowVersion: Number(editing.rowVersion || 0) });
|
||
message.success('质量目标已保存,当前报表立即生效'); setEditing(null); 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 { setBusy(false); }
|
||
};
|
||
const currentTarget = items.find(item => String(item.status).toUpperCase() === 'ACTIVE');
|
||
return <section className="panel section-panel completion-tools target-admin">
|
||
<div className="completion-panel-heading"><div><strong>质量目标配置</strong><span>直接维护当前目标;月度、季度查询使用所在年度目标,产业部和业务分组可按年覆盖</span></div><Button icon={<ReloadOutlined />} onClick={() => void load()}>刷新</Button></div>
|
||
{error && <Alert showIcon type="error" message="目标配置不可用" description={error} />}
|
||
{loading ? <div className="completion-loading"><Spin />读取质量目标…</div> : currentTarget ? <div className="target-current-summary"><strong>当前质量目标</strong><span>已配置 {text(currentTarget.targetCount, '0')} 项年度目标</span><Button type="primary" loading={busy} onClick={() => void open(currentTarget)}>编辑目标</Button></div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前没有启用的质量目标" />}
|
||
<Modal className="management-modal target-editor-modal" open={Boolean(editing)} title="编辑质量目标" width="min(1280px, calc(100vw - 32px))" okText="保存并立即生效" confirmLoading={busy} onCancel={() => setEditing(null)} onOk={() => void save()}>
|
||
<div className="target-editor-section">
|
||
<div className="target-editor-heading"><div><strong>总体年度目标</strong><span>列为年份;每个指标按年维护,范围目标为空时引用此处目标</span></div><div className="completion-actions"><Button icon={<PlusOutlined />} onClick={() => { const year = Math.max(2028, ...targetYears) + 1; if (year > 2100) { message.warning('最多支持添加到 2100 年。'); return; } setTargetYears(current => [...current, year].sort((a, b) => a - b)); }}>新增年度</Button><Button icon={<PlusOutlined />} onClick={() => setTargetRows(rows => [...rows, newRow(false)])}>新增总体指标</Button></div></div>
|
||
<Table className="target-editor-table" size="small" bordered columns={overallColumns} dataSource={overallRows} rowKey={row => String(row.editorKey)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 150 + targetYears.length * 116 + 48 }} />
|
||
</div>
|
||
<div className="target-editor-section">
|
||
<div className="target-editor-heading"><div><strong>产业部 / 地区与业务分组年度目标</strong><span>产业部、业务分组从名录选择;产品和项目组可直接输入。目标留空表示沿用总体目标</span></div><Button icon={<PlusOutlined />} onClick={() => setTargetRows(rows => [...rows, newRow(true)])}>新增产业部 / 分组</Button></div>
|
||
<Table className="target-editor-table" size="small" bordered columns={scopeColumns} dataSource={scopeRows} rowKey={row => String(row.editorKey)} pagination={{ pageSize: TABLE_PAGE_SIZE, showSizeChanger: false }} scroll={{ x: 150 + 158 * 2 + 132 * 2 + targetYears.length * 116 + 48 }} locale={{ emptyText: '暂无产业部或业务分组;可新增后直接输入' }} />
|
||
</div>
|
||
<Alert showIcon type="info" message="保存后立即生效" description="例如输入 95.5 即为 95.5%。范围目标空白时沿用同一年、同一指标的总体目标;保存后当前及已发布报表使用更新后的目标。" />
|
||
</Modal>
|
||
</section>;
|
||
}
|