1674 lines
121 KiB
TypeScript
1674 lines
121 KiB
TypeScript
import { usePriorityMetrics } from './usePriorityMetrics';
|
||
import { overviewTrend, sameTrendScope } from './priorityMetrics';
|
||
import { QuerySnapshotButton } from './QuerySnapshotButton';
|
||
import { loadedQueryScope, queryForLocation, readQueryLocation } from './queryLoadingScope';
|
||
import { AnimatedMetricText, SmoothTableFrame, useAnimatedMetricText, useRetainedResult } from './QueryResultMotion';
|
||
import { trendBarPalette } from './trendBarPalette';
|
||
import { getWorkspaceTheme } from './ui-themes';
|
||
import { queryScrapWeight, queryTotalScrapWeight, type QueryRateBasis } from './queryMetricValues';
|
||
import { BusinessValue } from './BusinessValue';
|
||
import { usePageCache } from './pageCache';
|
||
import { useDelayedIndicator } from './useDelayedBusy';
|
||
import { useResourceVisibility } from './useResourceVisibility';
|
||
import { useCallback, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState } from 'react';
|
||
import * as echarts from 'echarts/core';
|
||
import { BarChart, LineChart } from 'echarts/charts';
|
||
import { GraphicComponent, GridComponent, LegendComponent, MarkLineComponent, TooltipComponent } from 'echarts/components';
|
||
import { SVGRenderer } from 'echarts/renderers';
|
||
import {
|
||
Alert,
|
||
App,
|
||
Button,
|
||
Drawer,
|
||
Empty,
|
||
Input,
|
||
Modal,
|
||
Pagination,
|
||
Select,
|
||
Segmented,
|
||
Spin,
|
||
Table,
|
||
Tooltip,
|
||
} from 'antd';
|
||
import type { ColumnsType } from 'antd/es/table';
|
||
import { ArrowLeftOutlined, DownloadOutlined, InfoCircleOutlined, ReloadOutlined, SearchOutlined } from '@ant-design/icons';
|
||
import { ApiError, api, decodeQueryValueList, encodeQueryValueList } from './api';
|
||
import type {
|
||
DefectMetric,
|
||
DefectDrilldownResponse,
|
||
FineDefectTopResponse,
|
||
MetricRow,
|
||
MetricsResponse,
|
||
OptionsResponse,
|
||
PeriodKind,
|
||
QueryParams,
|
||
RecordExportParams,
|
||
RecordRow,
|
||
RecordsResponse,
|
||
Stage,
|
||
TrendMetricRow,
|
||
ViewKind,
|
||
} from './types';
|
||
import type { PageKey } from './QualityWorkspace';
|
||
import { readableSelectPopup } from './readableSelectPopup';
|
||
import { isInternalDataField, readableMetricFormula } from './publicDataDisplay';
|
||
import { defaultQueryMonth, previousCompleteMonth, previousCompleteQuarter } from './periodDefaults';
|
||
import { defectWeightRate } from './trendMetrics';
|
||
import { defaultFullMetricFields, metricStageColumnPlan, type MetricStageField } from './metricColumnPlan';
|
||
import DefectComposition from './DefectComposition';
|
||
import { QueryTrendPanel, QueryTablePanel } from './QueryPanels';
|
||
import { selectTrendPeriod as nextTrendPeriod } from './trendPeriodSelection';
|
||
import './query-motion.css';
|
||
import { ExtraQueryFilters } from './ExtraQueryFilters';
|
||
import { freezeSourceRecordsQuery } from './sourceRecordsContext';
|
||
import { downloadMetricWorkbook } from './metricWorkbook';
|
||
import { useDefectDrilldown } from './useDefectDrilldown';
|
||
import { defectCell, defectGroup, defectRateLabel as fineDefectRateLabel } from './defectDrilldown';
|
||
|
||
echarts.use([BarChart, LineChart, GraphicComponent, GridComponent, LegendComponent, MarkLineComponent, TooltipComponent, SVGRenderer]);
|
||
|
||
const MONTHS = Array.from({ length: 12 }, (_, index) => `${String(index + 1).padStart(2, '0')}月`);
|
||
// 图表直接沿用页面字号,不再补偿内部缩放。
|
||
function queryChartTypography(node: HTMLElement) {
|
||
const css = getComputedStyle(node);
|
||
const size = (token: string, fallback: number) => Math.round((Number.parseFloat(css.getPropertyValue(token)) || fallback) * 10) / 10;
|
||
return {
|
||
fontFamily: css.getPropertyValue('--font-ui').trim() || css.fontFamily,
|
||
numericFamily: css.getPropertyValue('--font-numeric').trim() || css.fontFamily,
|
||
fontSize: size('--font-control', 13),
|
||
tooltipFontSize: size('--font-reading', 14),
|
||
};
|
||
}
|
||
const TABLE_PAGE_SIZE = 15;
|
||
const SUMMARY_PAGE_SIZE = 15;
|
||
const SUMMARY_PAGE_SIZE_OPTIONS = ['10', '15', '20', '50', '100'];
|
||
const EMPTY_PRODUCT_SEARCH = '__codex_no_product_search_match__';
|
||
const SCOPE: Record<string, ViewKind> = { overall: 'overall', department: 'department', group: 'group', product: 'product' };
|
||
const SCOPE_NAMES: Record<string, string> = { overall: '总体', department: '产业部', group: '产业部-业务分组', product: '产品' };
|
||
const RETIRED_DEPARTMENTS = new Set(['美洲产业部', '欧洲产业部', '欧洲磁钢']);
|
||
const ORIGINAL_GROUP_ORDER = ['工业电机-VCM', '工业电机-美洲', '工业电机-欧洲', '工业电机-亚太', '工业电机-中国区', '汽车交通-国内', '汽车交通-海外', '消费电子-3C', '消费电子-电声', '消费电子-美洲'];
|
||
const groupRank = (value?: string | null) => { const index = ORIGINAL_GROUP_ORDER.indexOf(value || ''); return index < 0 ? ORIGINAL_GROUP_ORDER.length : index; };
|
||
|
||
function numberText(value: unknown, digits = 1): string {
|
||
return typeof value === 'number' && Number.isFinite(value)
|
||
? value.toLocaleString('zh-CN', { minimumFractionDigits: digits, maximumFractionDigits: digits })
|
||
: '—';
|
||
}
|
||
|
||
function rateText(value: number | null | undefined): string {
|
||
return typeof value === 'number' && Number.isFinite(value) ? `${(value * 100).toFixed(2)}%` : '—';
|
||
}
|
||
|
||
function defectRateLabel(label: string): string {
|
||
return `${label.replace(/(?:总重量|重量)(?:合计)?$/, '').replace(/率$/, '')}率`;
|
||
}
|
||
|
||
function rateNumber(value: number | null | undefined): number | null {
|
||
return typeof value === 'number' && Number.isFinite(value) ? value * 100 : null;
|
||
}
|
||
|
||
const SYSTEM_SOURCE_VERSION_KEYS = new Set([
|
||
'sourcerevisionid', 'targetrevisionid', 'expectedrevisionid', 'currentrevisionid', 'candidaterevisionid', 'baserevisionid',
|
||
]);
|
||
const SYSTEM_SOURCE_VERSION_LABELS = new Set([
|
||
'数据版本', '数据版本号', '发布版本', '发布版本号', '规则版本', '规则版本号', '映射版本', '映射版本号',
|
||
]);
|
||
function isSystemVersionField(key: string): boolean {
|
||
const normalized = key.replace(/[^a-z0-9]/gi, '').toLowerCase();
|
||
return isInternalDataField(key) || SYSTEM_SOURCE_VERSION_KEYS.has(normalized) || SYSTEM_SOURCE_VERSION_LABELS.has(key.trim());
|
||
}
|
||
|
||
function withoutSystemVersionFields(value: unknown): unknown {
|
||
if (Array.isArray(value)) return value.map(withoutSystemVersionFields);
|
||
if (!value || typeof value !== 'object') return value;
|
||
return Object.fromEntries(Object.entries(value as Record<string, unknown>)
|
||
.filter(([key]) => !isSystemVersionField(key))
|
||
.map(([key, child]) => [key, withoutSystemVersionFields(child)]));
|
||
}
|
||
|
||
function hasStageRows(row: MetricRow | undefined, stage: Stage): boolean {
|
||
return (row?.coverage?.[stage === 'black' ? 'blackRows' : 'brightRows'] ?? 0) > 0;
|
||
}
|
||
|
||
function hasValidRateDenominator(row: MetricRow | undefined, stage: Stage): boolean {
|
||
if (!row) return false;
|
||
if (stage === 'black') return row.black.totalWeight != null && row.black.totalWeight !== 0;
|
||
const qualified = row.bright.qualifiedWeight;
|
||
const scrap = row.bright.scrapWeight;
|
||
return (qualified != null || scrap != null) && (qualified ?? 0) + (scrap ?? 0) !== 0;
|
||
}
|
||
|
||
function visibleStageRate(row: MetricRow | undefined, stage: Stage, rateBasis: 'original' | 'withoutHeadquartersScrap' = 'original'): number | null {
|
||
if (!hasStageRows(row, stage)) return null;
|
||
if (stage === 'bright' && rateBasis === 'withoutHeadquartersScrap') {
|
||
return (row?.bright as MetricRow['bright'] & { rateWithoutHeadquartersScrap?: number | null })?.rateWithoutHeadquartersScrap ?? null;
|
||
}
|
||
return row?.[stage]?.rate ?? null;
|
||
}
|
||
|
||
function visibleCompositeRate(row: MetricRow | undefined, rateBasis: 'original' | 'withoutHeadquartersScrap' = 'original'): number | null {
|
||
if (!(hasStageRows(row, 'black') || hasStageRows(row, 'bright'))) return null;
|
||
return rateBasis === 'withoutHeadquartersScrap'
|
||
? (row as (MetricRow & { compositeRateWithoutHeadquartersScrap?: number | null }) | undefined)?.compositeRateWithoutHeadquartersScrap ?? null
|
||
: row?.compositeRate ?? null;
|
||
}
|
||
|
||
function monthNumber(value: number | string): number | null {
|
||
if (typeof value === 'number' && value >= 1 && value <= 12) return value;
|
||
const raw = String(value).trim();
|
||
const yearMonth = raw.match(/^\d{4}[-/]\s*(\d{1,2})$/);
|
||
const match = yearMonth || raw.match(/^(\d{1,2})(?:月)?$/);
|
||
if (!match) return null;
|
||
const result = Number(match[1] ?? match[0]);
|
||
return result >= 1 && result <= 12 ? result : null;
|
||
}
|
||
|
||
|
||
function fullYearTrend(rows: TrendMetricRow[], year: number, granularity: 'month' | 'quarter' | 'year'): TrendMetricRow[] {
|
||
if (granularity === 'year') return rows;
|
||
const byPeriod = new Map<string, TrendMetricRow>();
|
||
for (const row of rows) {
|
||
const key = String(row.period ?? row.month);
|
||
const normalized = granularity === 'quarter'
|
||
? key.match(/^(\d{4})-Q([1-4])$/)?.[0]
|
||
: key.match(/^(\d{4})-(\d{1,2})$/)?.slice(1);
|
||
const periodKey = Array.isArray(normalized) ? `${normalized[0]}-${String(Number(normalized[1])).padStart(2, '0')}` : normalized;
|
||
if (periodKey?.startsWith(`${year}-`)) byPeriod.set(periodKey, row);
|
||
}
|
||
return Array.from({ length: granularity === 'quarter' ? 4 : 12 }, (_, index) => {
|
||
const number = index + 1;
|
||
const key = granularity === 'quarter' ? `${year}-Q${number}` : `${year}-${String(number).padStart(2, '0')}`;
|
||
const label = granularity === 'quarter' ? `第${number}季度` : MONTHS[index];
|
||
if (byPeriod.has(key)) return { ...byPeriod.get(key)!, periodLabel: label };
|
||
const empty = blankMonthRow(year, granularity === 'quarter' ? number * 3 : number);
|
||
return { ...empty, key: `empty-${key}`, month: key, period: key,
|
||
periodLabel: label, granularity };
|
||
});
|
||
}
|
||
|
||
function blankMonthRow(year: number, month: number): TrendMetricRow {
|
||
const current = new Date();
|
||
const monthStatus: TrendMetricRow['monthStatus'] = year > current.getFullYear() || (year === current.getFullYear() && month > current.getMonth() + 1)
|
||
? 'future'
|
||
: year === current.getFullYear() && month === current.getMonth() + 1
|
||
? 'in_progress'
|
||
: 'unavailable';
|
||
const emptyStage = { qualifiedWeight: null, scrapWeight: null, totalWeight: null, rate: null, defects: [] };
|
||
return {
|
||
key: `empty-month-${year}-${month}`, label: MONTHS[month - 1], department: null, group: null, product: null,
|
||
compositeRate: null, black: { ...emptyStage, defects: [] }, bright: { ...emptyStage, defects: [] },
|
||
coverage: { blackRows: 0, brightRows: 0 }, month, monthStatus, noData: true,
|
||
};
|
||
}
|
||
|
||
function objectLabel(row: MetricRow, view: ViewKind): string {
|
||
if (view === 'overall') return row.label;
|
||
if (view === 'department') return row.department || row.label;
|
||
if (view === 'group') return row.group || row.label;
|
||
if (view === 'projectGroup') return row.projectGroup || row.label;
|
||
return row.product || row.label;
|
||
}
|
||
|
||
function stageValue(row: MetricRow | undefined, stage: Stage, field: 'qualifiedWeight' | 'scrapWeight' | 'totalWeight' | 'rate' | 'headquartersScrapWeight', basis: QueryRateBasis = 'original'): number | null {
|
||
return field === 'scrapWeight' ? queryScrapWeight(row?.[stage], stage, basis) : row?.[stage]?.[field] ?? null;
|
||
}
|
||
|
||
function defectList(row: MetricRow | undefined, stage: Stage): DefectMetric[] {
|
||
return row?.[stage]?.defects || [];
|
||
}
|
||
|
||
interface ChartTooltipParam {
|
||
name?: string | number;
|
||
axisValue?: string | number;
|
||
dataIndex?: number;
|
||
seriesName?: string;
|
||
marker?: string;
|
||
value?: unknown;
|
||
}
|
||
|
||
function chooseError(error: unknown): string {
|
||
return error instanceof Error ? error.message : '服务请求失败';
|
||
}
|
||
|
||
function escapeTooltipText(value: string): string {
|
||
return value.replace(/[&<>"']/g, character => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[character]!);
|
||
}
|
||
|
||
export function queryFromLocation(search = window.location.search): Partial<QueryParams> {
|
||
return readQueryLocation(search);
|
||
}
|
||
|
||
function toApiParams(args: {
|
||
year: number;
|
||
period: PeriodKind;
|
||
month: number;
|
||
quarter: number;
|
||
department?: string[];
|
||
group?: string[];
|
||
product?: string[];
|
||
productSearch?: string;
|
||
projectGroup?: string[];
|
||
extraFilters?: Record<string, string[]>;
|
||
trendGranularity: 'month' | 'quarter' | 'year';
|
||
view: ViewKind;
|
||
includeUnassigned: boolean;
|
||
}): QueryParams {
|
||
return {
|
||
year: args.year,
|
||
...(args.extraFilters && Object.keys(args.extraFilters).length ? { extraFilters: args.extraFilters } : {}),
|
||
...(args.period === 'month' ? { month: args.month } : {}),
|
||
...(args.period === 'quarter' ? { quarter: args.quarter } : {}),
|
||
...(encodeQueryValueList(args.department) ? { department: encodeQueryValueList(args.department) } : {}),
|
||
...(encodeQueryValueList(args.group) ? { group: encodeQueryValueList(args.group) } : {}),
|
||
...(encodeQueryValueList(args.product) ? { product: encodeQueryValueList(args.product) } : {}),
|
||
...(args.productSearch?.trim() ? { productSearch: args.productSearch.trim() } : {}),
|
||
...(encodeQueryValueList(args.projectGroup) ? { projectGroup: encodeQueryValueList(args.projectGroup) } : {}),
|
||
...(args.includeUnassigned ? { includeUnassigned: true } : {}),
|
||
trendGranularity: args.trendGranularity,
|
||
view: args.view,
|
||
};
|
||
}
|
||
|
||
function applyTrendObject(query: QueryParams, trendObject: string, view: ViewKind): QueryParams {
|
||
if (!trendObject) return { ...query };
|
||
const params: QueryParams = { ...query };
|
||
if (view === 'department') params.department = trendObject;
|
||
if (view === 'group') params.group = trendObject;
|
||
if (view === 'product') {
|
||
const selectedProducts = decodeQueryValueList(params.product);
|
||
params.product = selectedProducts.length === 0 || selectedProducts.includes(trendObject) ? trendObject : EMPTY_PRODUCT_SEARCH;
|
||
}
|
||
if (view === 'projectGroup') params.projectGroup = trendObject;
|
||
return params;
|
||
}
|
||
|
||
type TopResultRef = { kind: 'TOP'; resultId: string; releaseId: string };
|
||
export default function QueryPage({ page, onUnauthorized }: {
|
||
page: PageKey;
|
||
onUnauthorized: (error: unknown) => boolean;
|
||
onNavigate?: (page: PageKey, query: QueryParams, resultRef?: TopResultRef) => void;
|
||
}) {
|
||
const { message } = App.useApp();
|
||
const { active, initialSearch, refreshKey, onLocationChange, currentReleaseId } = usePageCache();
|
||
const baseView = SCOPE[page] || 'overall';
|
||
const [initialQuery] = useState(() => queryFromLocation(initialSearch));
|
||
const [viewOverrideState, setViewOverrideState] = useState<{ page: PageKey; view: ViewKind } | undefined>(() => initialQuery.view && initialQuery.view !== baseView ? { page, view: initialQuery.view } : undefined);
|
||
const viewOverride = viewOverrideState?.page === page ? viewOverrideState.view : undefined;
|
||
const setViewOverride = (next?: ViewKind) => setViewOverrideState(next ? { page, view: next } : undefined);
|
||
const view = viewOverride || baseView;
|
||
const scopeName = viewOverride ? ({ overall: '总体', department: '产业部', group: '产业部-业务分组', product: '产品', projectGroup: '项目组' } as Record<ViewKind, string>)[viewOverride] : SCOPE_NAMES[page] || '总体';
|
||
const [options, setOptions] = useState<OptionsResponse | null>(null);
|
||
const [optionsError, setOptionsError] = useState('');
|
||
const [optionsLoading, setOptionsLoading] = useState(true);
|
||
const automaticPeriod = useRef(page !== 'overall' && !initialQuery.year && !initialQuery.month && !initialQuery.quarter);
|
||
const defaultMonth = previousCompleteMonth();
|
||
const defaultQuarter = previousCompleteQuarter();
|
||
const [period, setPeriod] = useState<PeriodKind>(initialQuery.month ? 'month' : initialQuery.quarter ? 'quarter' : 'year');
|
||
const [year, setYear] = useState(initialQuery.year || (period === 'month' ? defaultMonth.year : period === 'quarter' ? defaultQuarter.year : new Date().getFullYear()));
|
||
const [month, setMonth] = useState(initialQuery.month || defaultMonth.month);
|
||
const [quarter, setQuarter] = useState(initialQuery.quarter || defaultQuarter.quarter);
|
||
const [department, setDepartment] = useState<string[]>(() => decodeQueryValueList(initialQuery.department));
|
||
const [group, setGroup] = useState<string[]>(() => decodeQueryValueList(initialQuery.group));
|
||
const [product, setProduct] = useState<string[]>(() => decodeQueryValueList(initialQuery.product));
|
||
const [projectGroup, setProjectGroup] = useState<string[]>(() => decodeQueryValueList(initialQuery.projectGroup));
|
||
const [extraFilters, setExtraFilters] = useState<Record<string,string[]>>(initialQuery.extraFilters || {});
|
||
const includeUnassigned = true;
|
||
const [trendGranularity, setTrendGranularity] = useState<'month' | 'quarter' | 'year'>(initialQuery.trendGranularity || (initialQuery.quarter ? 'quarter' : 'month'));
|
||
const [search, setSearch] = useState(initialQuery.productSearch || '');
|
||
const [appliedSearch, setAppliedSearch] = useState(initialQuery.productSearch || '');
|
||
const [fullFields, setFullFields] = useState(false);
|
||
const [trendFullFields, setTrendFullFields] = useState(() => defaultFullMetricFields(page));
|
||
const [defectDisplay, setDefectDisplay] = useState<'weight' | 'rate'>('weight');
|
||
const [data, setData] = useState<MetricsResponse | null>(null);
|
||
const [dataKey, setDataKey] = useState('');
|
||
const [trendData, setTrendData] = useState<TrendMetricRow[]>([]);
|
||
const [trendDataKey, setTrendDataKey] = useState('');
|
||
const [trendFailure, setTrendFailure] = useState<{ key: string; message: string } | null>(null);
|
||
const [trendTarget, setTrendTarget] = useState<number | null>(null);
|
||
const [trendTargetKey, setTrendTargetKey] = useState('');
|
||
const [trendObject, setTrendObject] = useState('');
|
||
const [drilledProduct, setDrilledProduct] = useState('');
|
||
const [trendObjectMetrics, setTrendObjectMetrics] = useState<{ key: string; data: MetricsResponse } | null>(null);
|
||
const [trendObjectMetricsLoading, setTrendObjectMetricsLoading] = useState(false);
|
||
const [trendObjectMetricsError, setTrendObjectMetricsError] = useState('');
|
||
const [trendMode, setTrendMode] = useState<'production' | 'defects' | 'data'>('production');
|
||
const [trendStage, setTrendStage] = useState<Stage>('bright');
|
||
const [rateBasis, setRateBasis] = useState<'original' | 'withoutHeadquartersScrap'>('original');
|
||
const [loading, setLoading] = useState(false);
|
||
const [trendLoading, setTrendLoading] = useState(false);
|
||
const [error, setError] = useState('');
|
||
const [errorKey, setErrorKey] = useState('');
|
||
const [queryRevision, setQueryRevision] = useState(0);
|
||
const [trendRevision, setTrendRevision] = useState(0);
|
||
const [selectedRecord, setSelectedRecord] = useState<MetricRow | null>(null);
|
||
const [recordsOpen, setRecordsOpen] = useState(false);
|
||
const [recordStage, setRecordStage] = useState<Stage>('black');
|
||
const [recordMonth, setRecordMonth] = useState<number>();
|
||
const [recordQuerySnapshot, setRecordQuerySnapshot] = useState<QueryParams | null>(null);
|
||
const [basisOpen, setBasisOpen] = useState(false);
|
||
const trendAnchorTop = useRef<number | null>(null);
|
||
const summaryExport = useRef<{ exportExcel: () => Promise<void> }>(null);
|
||
const [summaryExporting, setSummaryExporting] = useState(false);
|
||
const trendSection = useRef<HTMLElement>(null);
|
||
const defectsSection = useRef<HTMLElement>(null);
|
||
const defectsHeight = useRef(0);
|
||
const refreshSeen = useRef(refreshKey);
|
||
useEffect(() => {
|
||
if (active && refreshSeen.current !== refreshKey) { refreshSeen.current = refreshKey; setQueryRevision(value => value + 1); }
|
||
if (!active) { setRecordsOpen(false); setBasisOpen(false); }
|
||
}, [active, refreshKey]);
|
||
|
||
|
||
|
||
useEffect(() => {
|
||
if (!active) return;
|
||
let alive = true;
|
||
const controller = new AbortController();
|
||
api.options(controller.signal).then(result => {
|
||
if (!alive) return;
|
||
setOptions(result);
|
||
if (automaticPeriod.current) {
|
||
const available = defaultQueryMonth(result);
|
||
setMonth(available.month);
|
||
automaticPeriod.current = false;
|
||
}
|
||
setOptionsError('');
|
||
}).catch(errorValue => {
|
||
if (onUnauthorized(errorValue)) return;
|
||
if (alive) setOptionsError(chooseError(errorValue));
|
||
}).finally(() => { if (alive) setOptionsLoading(false); });
|
||
return () => { alive = false; controller.abort(); };
|
||
}, [active, onUnauthorized, queryRevision]);
|
||
|
||
const allowedGroups = useMemo(() => {
|
||
const parents = new Set(department);
|
||
return (options?.groups || []).filter(name => !parents.size || parents.has(options?.groupDepartments?.[name] || ''));
|
||
}, [department, options]);
|
||
const allowedGroupSet = useMemo(() => new Set(allowedGroups), [allowedGroups]);
|
||
|
||
useEffect(() => {
|
||
if (!options || !department.length) return;
|
||
const activeDepartments = department.filter(name => !RETIRED_DEPARTMENTS.has(name));
|
||
if (activeDepartments.length !== department.length) {
|
||
setDepartment(activeDepartments);
|
||
setGroup([]);
|
||
setProduct([]);
|
||
return;
|
||
}
|
||
const next = group.filter(name => allowedGroupSet.has(name));
|
||
if (next.length !== group.length) { setGroup(next); setProduct([]); }
|
||
}, [options, department, group, allowedGroupSet]);
|
||
|
||
const exactProductSearch = useMemo(() => {
|
||
const term = view === 'product' ? appliedSearch.trim().toLocaleLowerCase() : '';
|
||
return term ? (options?.products || []).find(name => name.trim().toLocaleLowerCase() === term) || '' : '';
|
||
}, [view, appliedSearch, options]);
|
||
const productFilterForQuery = useMemo(() => {
|
||
if (!exactProductSearch) return product;
|
||
if (product.length && !product.includes(exactProductSearch)) return [EMPTY_PRODUCT_SEARCH];
|
||
return [exactProductSearch];
|
||
}, [exactProductSearch, product]);
|
||
const queryParams = useMemo(() => ({ ...toApiParams({ year, period, month, quarter, department, group, product: productFilterForQuery, productSearch: view === 'product' ? appliedSearch : undefined, projectGroup, extraFilters, view, includeUnassigned, trendGranularity }), releaseId: initialQuery.releaseId || currentReleaseId || undefined }), [year, period, month, quarter, department, group, productFilterForQuery, appliedSearch, projectGroup, extraFilters, view, includeUnassigned, trendGranularity, initialQuery.releaseId, currentReleaseId]);
|
||
const queryKey = useMemo(() => JSON.stringify(queryParams), [queryParams]);
|
||
const drilldownContextKey = JSON.stringify({ view, department, group, product, projectGroup, extraFilters, includeUnassigned });
|
||
useEffect(() => {
|
||
setDrilledProduct('');
|
||
}, [drilldownContextKey]);
|
||
const metricParams = useMemo<QueryParams>(() => ({ ...queryParams, trendGranularity: 'month' }), [queryParams]);
|
||
const metricKey = useMemo(() => JSON.stringify([metricParams, queryRevision]), [metricParams, queryRevision]);
|
||
const metricsReady = !!(initialQuery.releaseId || currentReleaseId !== undefined) && (!metricParams.productSearch || !!options);
|
||
const overview = usePriorityMetrics(metricParams, active && metricsReady, queryRevision, onUnauthorized);
|
||
const currentOverview = overview.value;
|
||
const currentMetricsError = errorKey === metricKey ? error : '';
|
||
const currentMetricsData = dataKey === metricKey && !currentMetricsError ? data : null;
|
||
const queryPending = !currentMetricsData && !currentMetricsError;
|
||
const queryBusy = loading || queryPending;
|
||
const metricKeyRef = useRef(metricKey);
|
||
metricKeyRef.current = metricKey;
|
||
const trendParams = useMemo<QueryParams>(() => {
|
||
const params = applyTrendObject(queryParams, trendObject, view);
|
||
delete params.month;
|
||
delete params.quarter;
|
||
if (trendGranularity === 'year') Reflect.deleteProperty(params, 'year');
|
||
return params;
|
||
}, [queryKey, trendObject, trendGranularity, view]);
|
||
const defectQueryParams = useMemo<QueryParams>(() => applyTrendObject(queryParams, trendObject, view), [queryKey, trendObject, view]);
|
||
const defectQueryKey = JSON.stringify(defectQueryParams);
|
||
const trendKey = JSON.stringify([trendParams, queryRevision]);
|
||
const reuseOverviewTrend = sameTrendScope(metricParams, trendParams);
|
||
const trendGate = !overview.split && !reuseOverviewTrend || overview.settled;
|
||
const sharedTrend = reuseOverviewTrend ? currentOverview : null;
|
||
const trendKeyRef = useRef(trendKey);
|
||
trendKeyRef.current = trendKey;
|
||
|
||
useEffect(() => {
|
||
if (!active) return;
|
||
const url = new URL(window.location.href);
|
||
if (!['overall', 'department', 'group', 'product'].includes(url.searchParams.get('page') || 'overall')) return;
|
||
const bytes = new TextEncoder().encode(JSON.stringify({ query: queryForLocation(queryParams, initialQuery.releaseId) }));
|
||
let binary = '';
|
||
for (const byte of bytes) binary += String.fromCharCode(byte);
|
||
const context = btoa(binary).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
|
||
url.searchParams.set('context', context);
|
||
window.history.replaceState(window.history.state, '', `${url.pathname}${url.search}${url.hash}`);
|
||
onLocationChange(url.search);
|
||
}, [queryKey, active]);
|
||
|
||
useEffect(() => {
|
||
if (!active || !metricsReady || !overview.settled) return;
|
||
if (currentOverview && !overview.split) {
|
||
setData(currentOverview); setDataKey(metricKey); setLoading(false); setError(''); setErrorKey(''); return;
|
||
}
|
||
const controller = new AbortController();
|
||
setLoading(true);
|
||
setError('');
|
||
setErrorKey('');
|
||
(metricParams.view === 'overall' ? api.metrics : api.metricsTable)(metricParams, controller.signal).then(result => {
|
||
if (controller.signal.aborted || metricKeyRef.current !== metricKey) return;
|
||
setData(result);
|
||
setDataKey(metricKey);
|
||
setError('');
|
||
setErrorKey('');
|
||
}).catch(errorValue => {
|
||
if (controller.signal.aborted) return;
|
||
if (onUnauthorized(errorValue)) return;
|
||
setError(chooseError(errorValue));
|
||
setErrorKey(metricKey);
|
||
}).finally(() => { if (!controller.signal.aborted) setLoading(false); });
|
||
return () => controller.abort();
|
||
}, [active, metricKey, queryRevision, onUnauthorized, metricsReady, overview.settled, overview.split, currentOverview]);
|
||
|
||
useEffect(() => {
|
||
if (!active) return;
|
||
if (!trendObject || defectQueryKey === queryKey) {
|
||
setTrendObjectMetrics(null);
|
||
setTrendObjectMetricsLoading(false);
|
||
setTrendObjectMetricsError('');
|
||
return;
|
||
}
|
||
const controller = new AbortController();
|
||
setTrendObjectMetrics(null);
|
||
setTrendObjectMetricsLoading(true);
|
||
setTrendObjectMetricsError('');
|
||
api.metrics({ ...defectQueryParams, view: 'overall', trendGranularity: 'month' }, controller.signal)
|
||
.then(result => { if (!controller.signal.aborted) setTrendObjectMetrics({ key: defectQueryKey, data: result }); })
|
||
.catch(errorValue => {
|
||
if (controller.signal.aborted) return;
|
||
if (!onUnauthorized(errorValue)) setTrendObjectMetricsError(chooseError(errorValue));
|
||
})
|
||
.finally(() => { if (!controller.signal.aborted) setTrendObjectMetricsLoading(false); });
|
||
return () => controller.abort();
|
||
}, [active, trendObject, defectQueryKey, queryKey, queryRevision, onUnauthorized]);
|
||
|
||
useEffect(() => {
|
||
if (!active || !metricsReady || !trendGate) return;
|
||
setTrendFailure(null);
|
||
if (sharedTrend) {
|
||
setTrendData(overviewTrend(sharedTrend).trend); setTrendDataKey(trendKey); setTrendLoading(false); return;
|
||
}
|
||
const controller = new AbortController();
|
||
setTrendLoading(true);
|
||
api.trend(trendParams, controller.signal).then(result => {
|
||
if (controller.signal.aborted || trendKeyRef.current !== trendKey) return;
|
||
setTrendData(Array.isArray(result.trend) ? result.trend : []);
|
||
setTrendDataKey(trendKey);
|
||
})
|
||
.catch(errorValue => {
|
||
if (!controller.signal.aborted && !onUnauthorized(errorValue)) setTrendFailure({ key: trendKey, message: chooseError(errorValue) });
|
||
}).finally(() => { if (!controller.signal.aborted) setTrendLoading(false); });
|
||
return () => controller.abort();
|
||
}, [active, trendKey, queryRevision, trendRevision, onUnauthorized, metricsReady, trendGate, sharedTrend]);
|
||
|
||
useEffect(() => {
|
||
if (!active || !metricsReady || !overview.settled) return;
|
||
let alive = true;
|
||
setTrendTarget(null);
|
||
setTrendTargetKey('');
|
||
const targetContext = Object.fromEntries(Object.entries(trendParams).filter(([key]) => key !== 'view' && key !== 'trendGranularity'));
|
||
api.analyticsTarget({ ...targetContext, metric: 'COMPOSITE_RATE' }).then(result => {
|
||
const target = result.target && typeof result.target === 'object' ? result.target as Record<string, unknown> : {};
|
||
const value = typeof target.value === 'number' ? target.value : target.targetRate;
|
||
if (!alive) return;
|
||
setTrendTarget(result.status === 'CONFIGURED' && typeof value === 'number' && Number.isFinite(value) && value >= 0 && value <= 1 ? value * 100 : null);
|
||
setTrendTargetKey(trendKey);
|
||
}).catch(errorValue => {
|
||
if (!alive) return;
|
||
if (!onUnauthorized(errorValue)) {
|
||
setTrendTarget(null);
|
||
setTrendTargetKey(trendKey);
|
||
}
|
||
});
|
||
return () => { alive = false; };
|
||
}, [active, trendKey, queryRevision, trendRevision, onUnauthorized, metricsReady, overview.settled]);
|
||
|
||
const currentTrendTarget = trendTargetKey === trendKey ? trendTarget : null;
|
||
const visibleTrendData = useMemo(() => fullYearTrend(trendDataKey === trendKey ? trendData : [], year, trendGranularity), [trendData, trendDataKey, trendKey, year, trendGranularity]);
|
||
const currentTrendError = trendFailure?.key === trendKey ? trendFailure.message : '';
|
||
const trendRefreshing = !currentTrendError && (trendLoading || trendDataKey !== trendKey);
|
||
const showTrendLoading = useDelayedIndicator(trendRefreshing);
|
||
// 只在当前查询返回后替换画面;钻取等待期间保留上一次趋势和目标线。
|
||
const retainedTrend = useRetainedResult(trendDataKey === trendKey ? { rows: visibleTrendData, target: currentTrendTarget, query: trendParams } : null);
|
||
const renderedTrendData = retainedTrend?.rows || visibleTrendData;
|
||
const renderedTrendTarget = retainedTrend ? retainedTrend.target : currentTrendTarget;
|
||
const drilledTrendData = useMemo(
|
||
() => trendDataKey === trendKey ? visibleTrendData : fullYearTrend([], year, 'month'),
|
||
[trendDataKey, trendKey, visibleTrendData, year],
|
||
);
|
||
const selectedTrendPeriod = trendGranularity === 'month' && period === 'month'
|
||
? `${year}-${String(month).padStart(2, '0')}`
|
||
: trendGranularity === 'quarter' && period === 'quarter' ? `${year}-Q${quarter}` : undefined;
|
||
|
||
const visibleRows = useMemo(() => {
|
||
const rawRows: MetricRow[] = page === 'overall' && period === 'year'
|
||
? (() => {
|
||
const byMonth = new Map<number, TrendMetricRow>();
|
||
for (const item of currentMetricsData?.trend || []) { const parsed = monthNumber(item.month); if (parsed) byMonth.set(parsed, item); }
|
||
return Array.from({ length: 12 }, (_, index) => byMonth.get(index + 1) || blankMonthRow(year, index + 1));
|
||
})()
|
||
: page === 'overall' && currentMetricsData
|
||
? currentMetricsData.rows.length ? currentMetricsData.rows : [currentMetricsData.summary]
|
||
: currentMetricsData?.rows || [];
|
||
const scopedRows = view === 'department'
|
||
? rawRows.filter(row => !RETIRED_DEPARTMENTS.has(row.department || row.label))
|
||
: view === 'group' && department.length
|
||
? rawRows.filter(row => !!row.group && allowedGroupSet.has(row.group)) : rawRows;
|
||
const orderedRows = view === 'group'
|
||
? [...scopedRows].sort((a, b) => groupRank(a.group) - groupRank(b.group))
|
||
: view === 'product'
|
||
? [...scopedRows].sort((a, b) => {
|
||
const aWeight = a.bright.qualifiedWeight;
|
||
const bWeight = b.bright.qualifiedWeight;
|
||
return (typeof bWeight === 'number' && Number.isFinite(bWeight) ? bWeight : -Infinity)
|
||
- (typeof aWeight === 'number' && Number.isFinite(aWeight) ? aWeight : -Infinity) || 0;
|
||
})
|
||
: scopedRows;
|
||
if (!appliedSearch.trim()) return orderedRows;
|
||
const term = appliedSearch.trim().toLocaleLowerCase();
|
||
return orderedRows.filter(row => [row.label, row.department, row.group, row.product, row.projectGroup].filter(Boolean).join(' ').toLocaleLowerCase().includes(term));
|
||
}, [page, period, currentMetricsData, appliedSearch, year, view, department, allowedGroupSet]);
|
||
|
||
const tableReady = drilledProduct ? trendDataKey === trendKey && !trendLoading : !!currentMetricsData;
|
||
const retainedTable = useRetainedResult(tableReady ? {
|
||
rows: drilledProduct ? drilledTrendData : visibleRows,
|
||
view: drilledProduct ? 'overall' as const : view,
|
||
layoutView: drilledProduct ? 'product' as const : view,
|
||
period: drilledProduct ? 'year' as const : period,
|
||
year, month, quarter, drilledProduct, granularity: trendGranularity, paginationScope: JSON.stringify({query:queryParams,drilledProduct,view}),
|
||
} : null);
|
||
const tableRows = retainedTable?.rows || [];
|
||
const tablePeriod = retainedTable?.period || period;
|
||
const tableView = retainedTable?.view || view;
|
||
const tableMonth = retainedTable?.month || month;
|
||
const tableQuarter = retainedTable?.quarter || quarter;
|
||
const tableProduct = retainedTable?.drilledProduct || '';
|
||
const tableProductLabel = tableProduct === '__UNASSIGNED__' ? '未分类' : tableProduct;
|
||
|
||
const defectDrill = useDefectDrilldown({active,mode:trendMode,stage:trendStage,
|
||
query:{...defectQueryParams,releaseId:summaryMetricsDataRelease()},trendQuery:trendParams,
|
||
tableQuery:drilledProduct?trendParams:queryParams,
|
||
tableDimension:tableView==='overall'&&tablePeriod==='year'?'period':tableView,
|
||
tableGranularity:drilledProduct?trendGranularity:'month',refreshKey:JSON.stringify([refreshKey,queryRevision]),onUnauthorized,display:defectDisplay,onDisplay:setDefectDisplay});
|
||
function summaryMetricsDataRelease() { return (drilledProduct?trendObjectMetrics?.data:currentMetricsData)?.release?.id || currentMetricsData?.release?.id || queryParams.releaseId; }
|
||
|
||
const captureTrendAnchor = useCallback(() => {
|
||
trendAnchorTop.current = trendSection.current?.getBoundingClientRect().top ?? null;
|
||
// Keep enough document height while the downstream charts are replaced by
|
||
// loading content, otherwise the browser clamps scrollY before anchoring.
|
||
defectsHeight.current = defectsSection.current?.offsetHeight ?? 0;
|
||
}, []);
|
||
const selectTrendPeriod = useCallback((value: number | string) => {
|
||
automaticPeriod.current = false;
|
||
const next = nextTrendPeriod(value, { period, year, month, quarter });
|
||
if (next.period !== period || next.year !== year || next.month !== month || next.quarter !== quarter) captureTrendAnchor();
|
||
setYear(next.year); setMonth(next.month); setQuarter(next.quarter); setPeriod(next.period);
|
||
}, [period, year, month, quarter, captureTrendAnchor]);
|
||
|
||
useLayoutEffect(() => {
|
||
if (!active || trendAnchorTop.current == null) return;
|
||
const nextTop = trendSection.current?.getBoundingClientRect().top;
|
||
if (nextTop != null) window.scrollBy(0, nextTop - trendAnchorTop.current);
|
||
// Keep the anchor through the response as the new result may have a
|
||
// different row count. Clearing it at request start allowed a second jump.
|
||
if (currentMetricsData || currentMetricsError) trendAnchorTop.current = null;
|
||
}, [period, year, month, quarter, currentMetricsData, currentMetricsError]);
|
||
|
||
useEffect(() => {
|
||
const releaseAnchor = () => { trendAnchorTop.current = null; };
|
||
window.addEventListener('wheel', releaseAnchor, { passive: true });
|
||
window.addEventListener('touchstart', releaseAnchor, { passive: true });
|
||
return () => { window.removeEventListener('wheel', releaseAnchor); window.removeEventListener('touchstart', releaseAnchor); };
|
||
}, []);
|
||
|
||
const years = (options?.years || []).map(value => { const numeric = Number(String(value).match(/\d{4}/)?.[0]); return { label: `${numeric}年`, value: numeric }; }).filter(item => Number.isFinite(item.value));
|
||
const filterSelect = (label: string, value: string[], choices: string[] | undefined, change: (value: string[]) => void, allowUnassigned = true) => (
|
||
<div role="group" className="query-field query-primary-field" key={label}>
|
||
<span>{label}</span>
|
||
<Select
|
||
maxTagCount="responsive"
|
||
mode="multiple"
|
||
allowClear
|
||
showSearch
|
||
optionFilterProp="label"
|
||
{...readableSelectPopup}
|
||
placeholder="全部"
|
||
value={value}
|
||
options={[...(label === '业务分组' ? [...(choices || [])].sort((a, b) => groupRank(a) - groupRank(b)) : choices || []).map(item => ({ label: item, value: item })), ...(allowUnassigned ? [{ label: '未分类', value: '__UNASSIGNED__' }] : [])]}
|
||
onChange={change}
|
||
aria-label={label}
|
||
/>
|
||
</div>
|
||
);
|
||
|
||
const activeDefectData = trendObject
|
||
? defectQueryKey === queryKey ? currentOverview || currentMetricsData : trendObjectMetrics?.key === defectQueryKey ? trendObjectMetrics.data : null
|
||
: currentOverview || currentMetricsData;
|
||
const previousDefectSnapshot = useRef<{ data: MetricsResponse; query: QueryParams } | null>(null);
|
||
useLayoutEffect(() => {
|
||
if (activeDefectData) previousDefectSnapshot.current = { data: activeDefectData, query: defectQueryParams };
|
||
}, [activeDefectData, defectQueryKey]);
|
||
const displayedDefectData = activeDefectData || previousDefectSnapshot.current?.data;
|
||
const displayedDefectQuery = activeDefectData ? defectQueryParams : previousDefectSnapshot.current?.query || defectQueryParams;
|
||
const defectsRefreshing = !activeDefectData && (queryBusy || trendObjectMetricsLoading);
|
||
// 产品月度下钻复用当前对象的服务端指标,汇总表仍保留父层结果供返回。
|
||
const summaryMetricsData = drilledProduct ? activeDefectData : currentOverview || currentMetricsData;
|
||
const openRecords = useCallback((row: MetricRow | null, stage: Stage, selectedMonth?: number, sourceQuery?: QueryParams, sourceData?: MetricsResponse | null) => {
|
||
const source = sourceData === undefined ? summaryMetricsData : sourceData;
|
||
if (!source?.release?.id) { message.info('指标数据尚未就绪,请重新查询后打开来源明细。'); return; }
|
||
// Product drilldown rows represent months; the product is already bound in the query.
|
||
setRecordQuerySnapshot(freezeSourceRecordsQuery(sourceQuery || (drilledProduct ? defectQueryParams : queryParams), source.release.id, drilledProduct ? 'overall' : view, row, selectedMonth));
|
||
setSelectedRecord(row); setRecordStage(stage); setRecordMonth(selectedMonth); setRecordsOpen(true);
|
||
}, [summaryMetricsData, drilledProduct, defectQueryParams, queryParams, view, message]);
|
||
const summaryMetricsError = drilledProduct ? trendObjectMetricsError : currentMetricsError;
|
||
const summaryBusy = drilledProduct ? trendObjectMetricsLoading || !summaryMetricsData && !summaryMetricsError : !summaryMetricsData && queryBusy;
|
||
const displayedSummaryData = useRetainedResult(summaryMetricsData);
|
||
const rowForSummary = displayedSummaryData?.summary;
|
||
const rawFormulaDescriptions = summaryMetricsData?.context.metricFormulaDescriptions;
|
||
const formulaDescriptions = rawFormulaDescriptions && typeof rawFormulaDescriptions === 'object' && !Array.isArray(rawFormulaDescriptions) ? rawFormulaDescriptions as Record<string, unknown> : {};
|
||
const compositeFormula = formulaDescriptions[rateBasis === 'original' ? 'compositeRate' : 'compositeRateWithoutHeadquartersScrap'];
|
||
const brightFormula = formulaDescriptions[rateBasis === 'original' ? 'brightRate' : 'brightRateWithoutHeadquartersScrap'];
|
||
const formulaText = readableMetricFormula;
|
||
const blackDefectItems = displayedDefectData?.defects?.black || [];
|
||
const brightDefectItems = displayedDefectData?.defects?.bright || [];
|
||
const organizationPaths = options?.organizationPaths || [];
|
||
const organizationPathOptions = useMemo(() => {
|
||
const departments = new Set(department);
|
||
const groups = new Set(group);
|
||
const scoped = organizationPaths.filter(path =>
|
||
(!departments.size || (departments.has(path.department || '__UNASSIGNED__') && allowedGroupSet.has(path.group || '')
|
||
&& options?.groupDepartments?.[path.group || ''] === path.department))
|
||
&& (!groups.size || groups.has(path.group || '__UNASSIGNED__')));
|
||
return {
|
||
products: [...new Set(scoped.map(path => path.product).filter((value): value is string => !!value))],
|
||
};
|
||
}, [organizationPaths, department, group, allowedGroupSet, options]);
|
||
const trendOptions = useMemo(() => {
|
||
const base = view === 'department' ? options?.departments?.filter(name => !RETIRED_DEPARTMENTS.has(name)) : view === 'group' ? allowedGroups : view === 'product'
|
||
? department.length || group.length ? organizationPathOptions.products : options?.products : [];
|
||
return [...(base || []).map(value => ({ label: value, value })), ...(view === 'product' ? [{ label: '未分类', value: '__UNASSIGNED__' }] : [])];
|
||
}, [view, options, allowedGroups, department, group, organizationPathOptions]);
|
||
useEffect(() => {
|
||
if (options && trendObject && !trendOptions.some(item => item.value === trendObject)) {
|
||
setTrendObject('');
|
||
if (search.trim().toLocaleLowerCase() === trendObject.toLocaleLowerCase()) setSearch('');
|
||
}
|
||
}, [options, trendOptions, trendObject, search]);
|
||
const applySearch = (value = search) => {
|
||
setAppliedSearch(value.trim());
|
||
const normalized = value.trim().toLocaleLowerCase();
|
||
const exactOption = normalized ? trendOptions.find(item => item.value.trim().toLocaleLowerCase() === normalized) : undefined;
|
||
setTrendObject(exactOption?.value || '');
|
||
};
|
||
const setSynchronizedTrendObject = (value?: string) => {
|
||
const selected = value || '';
|
||
setTrendObject(selected);
|
||
setSearch(selected);
|
||
setAppliedSearch(selected);
|
||
};
|
||
const organizationSummary = [
|
||
department.length ? `产业部:${department.map(value => value === '__UNASSIGNED__' ? '未分类' : value).join('、')}` : '',
|
||
group.length ? `业务分组:${group.map(value => value === '__UNASSIGNED__' ? '未分类' : value).join('、')}` : '',
|
||
product.length ? `产品:${product.map(value => value === '__UNASSIGNED__' ? '未分类' : value).join('、')}` : '',
|
||
].filter(Boolean);
|
||
|
||
return (
|
||
<div className="query-page">
|
||
{optionsError && <Alert showIcon type="error" message="查询选项加载失败" description={optionsError} action={<Button size="small" icon={<ReloadOutlined />} onClick={() => { setOptionsLoading(true); api.options().then(result => { setOptions(result); setOptionsError(''); }).catch(e => { if (!onUnauthorized(e)) setOptionsError(chooseError(e)); }).finally(() => setOptionsLoading(false)); }}>重试</Button>} />}
|
||
<section className="query-toolbar panel" data-snapshot-module="filters" aria-label="查询条件">
|
||
<Segmented
|
||
value={period}
|
||
options={[{ label: '年度', value: 'year' }, { label: '季度', value: 'quarter' }, { label: '月度', value: 'month' }]}
|
||
onChange={value => {
|
||
automaticPeriod.current = false;
|
||
const nextPeriod = value as PeriodKind;
|
||
setPeriod(nextPeriod);
|
||
setTrendGranularity(nextPeriod === 'quarter' ? 'quarter' : 'month');
|
||
if (nextPeriod === 'month') {
|
||
const previous = defaultQueryMonth(options);
|
||
setYear(previous.year);
|
||
setMonth(previous.month);
|
||
} else if (nextPeriod === 'quarter') {
|
||
const previous = previousCompleteQuarter();
|
||
setYear(previous.year);
|
||
setQuarter(previous.quarter);
|
||
}
|
||
}}
|
||
aria-label="统计周期"
|
||
/>
|
||
<div role="group" className="query-field query-period-field query-period-year"><span>年份</span><Select aria-label="年份" value={year} options={years.length ? years : [{ label: `${year}年`, value: year }]} onChange={value => { automaticPeriod.current = false; setYear(value); }} loading={optionsLoading} /></div>
|
||
{period === 'month' && <div role="group" className="query-field query-period-field query-period-month"><span>月份</span><Select aria-label="月份" value={month} options={MONTHS.map((label, index) => ({ label, value: index + 1 }))} onChange={value => { automaticPeriod.current = false; setMonth(value); }} /></div>}
|
||
{period === 'quarter' && <div role="group" className="query-field query-period-field query-period-quarter"><span>季度</span><Select aria-label="季度" value={quarter} options={[1, 2, 3, 4].map(value => ({ label: `第${value}季度`, value }))} onChange={value => { automaticPeriod.current = false; setQuarter(value); }} /></div>}
|
||
{filterSelect('产业部', department, options?.departments?.filter(name => !RETIRED_DEPARTMENTS.has(name)), values => { setDepartment(values); setGroup([]); setProduct([]); })}
|
||
{filterSelect('业务分组', group, allowedGroups, values => { setGroup(values); setProduct([]); }, !department.length)}
|
||
{filterSelect('产品', product, department.length || group.length ? organizationPathOptions.products : options?.products, setProduct)}
|
||
|
||
<ExtraQueryFilters key={queryRevision} releaseId={queryParams.releaseId} projectGroup={projectGroup} projectGroups={options?.projectGroupStatus === 'READY' ? options.projectGroups : undefined} onProjectGroup={setProjectGroup} value={extraFilters} onChange={setExtraFilters} onUnauthorized={onUnauthorized} />
|
||
<div className="query-toolbar-tail"><span className={`query-status ${queryBusy || summaryBusy ? 'busy' : currentMetricsError || summaryMetricsError ? 'failed' : ''}`}><i />{queryBusy || summaryBusy ? '正在查询' : currentMetricsError || summaryMetricsError ? '查询失败' : '查询完成'}</span>
|
||
<QuerySnapshotButton title={drilledProduct ? `${drilledProduct} · 产品质量查询` : page === 'overall' ? '总体合格率' : `${scopeName}质量查询`} queryKey={JSON.stringify([queryParams,trendMode,trendObject,trendStage,trendGranularity,rateBasis,fullFields,defectDisplay,queryRevision])} disabled={queryBusy || summaryBusy || !summaryMetricsData} onUnauthorized={onUnauthorized} />
|
||
<Button type="default" onClick={() => { automaticPeriod.current = false; const previous = defaultQueryMonth(options); const previousQuarter = previousCompleteQuarter(); setViewOverride(); setDrilledProduct(''); setDepartment([]); setGroup([]); setProduct([]); setProjectGroup([]); setExtraFilters({}); setSearch(''); setAppliedSearch(''); setTrendObject(''); setYear(new Date().getFullYear()); setMonth(previous.month); setQuarter(previousQuarter.quarter); setPeriod('year'); setTrendGranularity('month'); }}>重置</Button>
|
||
</div>
|
||
{organizationSummary.length > 0 && <div className="organization-breadcrumb" aria-label="当前组织路径">
|
||
<span>组织路径</span><Button type="link" onClick={() => { setDepartment([]); setGroup([]); setProduct([]); }}>全部组织</Button>
|
||
{organizationSummary.map((label, index) => <span className="organization-crumb" key={label}>{index > 0 && <i>›</i>}<span>{label}</span><Button type="link" onClick={() => index === 0 ? (setDepartment([]), setGroup([]), setProduct([])) : index === 1 ? (setGroup([]), setProduct([])) : setProduct([])}>清除此层</Button></span>)}
|
||
</div>}
|
||
</section>
|
||
|
||
{currentMetricsError && <Alert showIcon type="error" message={currentOverview ? "表格读取失败,指标已更新" : data ? "更新失败,当前显示上次结果" : "质量指标查询失败"} description={currentMetricsError} action={<Button size="small" icon={<ReloadOutlined />} onClick={() => setQueryRevision(value => value + 1)}>重试</Button>} />}
|
||
{drilledProduct && summaryMetricsError && <Alert showIcon type="error" message="当前产品指标查询失败" description={summaryMetricsError} action={<Button size="small" onClick={() => setQueryRevision(value => value + 1)}>重试</Button>} />}
|
||
<section className={`metric-strip ${!displayedSummaryData ? 'query-awaiting-data' : ''}`} data-snapshot-module="metrics" aria-label="质量指标" aria-busy={summaryBusy} inert={!summaryMetricsData}>
|
||
<div className="rate-basis-control"><Segmented size="small" value={rateBasis} options={[{ label: '原口径', value: 'original' }, { label: '去本部报废', value: 'withoutHeadquartersScrap' }]} onChange={value => setRateBasis(value as typeof rateBasis)} aria-label="合格率口径" /></div>
|
||
<MetricCard primary label="综合合格率" value={rateText(visibleCompositeRate(rowForSummary, rateBasis))} onClick={() => setBasisOpen(true)} />
|
||
<MetricCard label="黑片合格率" value={rateText(visibleStageRate(rowForSummary, 'black'))} note={!displayedSummaryData ? (summaryBusy ? '正在更新…' : '指标暂不可用') : hasStageRows(rowForSummary, 'black') ? hasValidRateDenominator(rowForSummary, 'black') ? `合格重量 ${numberText(rowForSummary?.black?.qualifiedWeight)} kg` : '按当前启用规则及空值策略计算' : '缺少黑片来源'} stage="black" onClick={() => openRecords(null, 'black')} />
|
||
<MetricCard label="亮片合格率" value={rateText(visibleStageRate(rowForSummary, 'bright', rateBasis))} note={!displayedSummaryData ? (summaryBusy ? '正在更新…' : '指标暂不可用') : hasStageRows(rowForSummary, 'bright') ? hasValidRateDenominator(rowForSummary, 'bright') ? `合格重量 ${numberText(rowForSummary?.bright?.qualifiedWeight)} kg` : '按当前启用规则及空值策略计算' : '缺少亮片来源'} stage="bright" onClick={() => openRecords(null, 'bright')} />
|
||
<MetricCard label="报废总重" value={rowForSummary && (hasStageRows(rowForSummary, 'black') || hasStageRows(rowForSummary, 'bright')) ? `${numberText(queryTotalScrapWeight(rowForSummary, rateBasis))} kg` : '—'} note={!displayedSummaryData ? (summaryBusy ? '正在更新…' : '指标暂不可用') : hasStageRows(rowForSummary, 'black') || hasStageRows(rowForSummary, 'bright') ? `黑片 ${numberText(rowForSummary?.black?.scrapWeight)} kg · 亮片 ${numberText(queryScrapWeight(rowForSummary?.bright, 'bright', rateBasis))} kg` : '缺少阶段来源'} onClick={() => openRecords(null, 'black')} />
|
||
</section>
|
||
|
||
{['department', 'group', 'product'].includes(page) && <>
|
||
{options?.projectGroupStatus === 'UNCONFIGURED' && <Alert showIcon type="info" message="项目组映射尚未配置" description="项目组与源 Excel 业务分组是不同维度。映射启用前,此处不会将业务分组冒充项目组,也不会提供项目组筛选。" />}
|
||
</>}
|
||
|
||
<>
|
||
<div className="analysis-stack">
|
||
<QueryTrendPanel headingControls={defectDrill.controls} panelRef={trendSection} id={active ? 'monthly-trend' : undefined}
|
||
mode={trendMode} onMode={setTrendMode} granularity={trendGranularity} onGranularity={setTrendGranularity}
|
||
defectDisplay={defectDisplay} onDefectDisplay={setDefectDisplay} fullFields={trendFullFields} onFullFields={setTrendFullFields}
|
||
object={trendObject} onObject={setSynchronizedTrendObject}
|
||
objects={trendOptions} scopeName={scopeName}
|
||
stageSwitch={<Segmented value={trendStage} options={[{ label: '亮片', value: 'bright' }, { label: '黑片', value: 'black' }]} onChange={value => setTrendStage(value as Stage)} aria-label="趋势阶段" />}>
|
||
{currentTrendError && <Alert type="warning" showIcon message={retainedTrend ? "趋势更新失败,当前显示上次结果" : "趋势读取失败"} description={retainedTrend ? `${currentTrendError};当前范围:${loadedQueryScope(retainedTrend.query, decodeQueryValueList)}` : currentTrendError} action={<Button onClick={() => setTrendRevision(value => value + 1)}>重试</Button>} />}
|
||
<div className="trend-chart-shell" aria-busy={trendRefreshing} inert={trendRefreshing || trendDataKey !== trendKey}>
|
||
{trendMode === 'data'
|
||
? <TrendTable rows={renderedTrendData} defectDisplay={defectDisplay} rateBasis={rateBasis} fullFields={trendFullFields} onMonth={selectTrendPeriod} />
|
||
: <TrendChart defectDrilldown={trendDataKey===trendKey&&!trendLoading&&!currentTrendError?defectDrill.trend:undefined} drillableCategories={defectDrill.categories} onDefect={defectDrill.choose} rows={renderedTrendData} mode={trendMode} stage={trendStage} rateBasis={rateBasis} targetRate={renderedTrendTarget} selectedPeriod={selectedTrendPeriod} onMonth={selectTrendPeriod} />}
|
||
{showTrendLoading && <span className="trend-refresh-indicator"><Spin size="small" />{retainedTrend ? `正在更新 · 当前显示上次筛选的${loadedQueryScope(retainedTrend.query, decodeQueryValueList)}` : '正在读取趋势'}</span>}
|
||
</div>
|
||
</QueryTrendPanel>
|
||
|
||
|
||
<QueryTablePanel
|
||
heading={<SectionHeading title={tableProduct ? `产品${retainedTable?.granularity === 'quarter' ? '季度' : retainedTable?.granularity === 'year' ? '年度' : '月度'}质量数据` : page === 'overall' ? `${tablePeriod === 'year' ? '年度月度' : tablePeriod === 'quarter' ? '季度' : '月度'}汇总` : `${scopeName}质量汇总`} subtitle={tableProduct ? `${retainedTable?.year || year} 年 · ${tableProductLabel} · 重量 / kg 合格率 / %` : '重量 / kg 合格率 / %'} />} busy={queryBusy || !tableReady || defectDrill.tablePending}
|
||
search={drilledProduct ? tableProductLabel : search} onSearchChange={setSearch} onSearch={() => applySearch()} productView={view === 'product'} searchPlaceholder={view === 'group' ? '搜索业务分组' : undefined} searchDisabled={Boolean(drilledProduct)}
|
||
fullFields={fullFields} onFullFields={setFullFields} defectDisplay={defectDisplay} onDefectDisplay={setDefectDisplay}
|
||
returnControls={<>{!drilledProduct && (view !== baseView || view === 'group' || view === 'product' && (group.length > 0 || department.length > 0)) && <Button className="query-return-button" icon={<ArrowLeftOutlined />} onClick={() => { setSearch(''); setAppliedSearch(''); setTrendObject(''); if (view === 'product') { setProduct([]); setGroup([]); setViewOverride('group'); } else if (view === 'group') { setGroup([]); setDepartment([]); setViewOverride('department'); } else { setViewOverride(); } }}>返回上一级</Button>}
|
||
{drilledProduct && <Button className="query-return-button" icon={<ArrowLeftOutlined />} onClick={() => { setDrilledProduct(''); setTrendObject(''); if(trendMode!=='defects')setTrendMode('production'); }}>返回上一级</Button>}</>}
|
||
exporting={summaryExporting} exportDisabled={!!defectDrill.category && (!defectDrill.table || defectDrill.pending || !!defectDrill.error) || queryBusy || summaryBusy || !tableReady || !summaryMetricsData || Boolean(drilledProduct && (trendLoading || currentTrendError)) || !(drilledProduct ? drilledTrendData : visibleRows).length}
|
||
onExport={async () => {
|
||
setSummaryExporting(true);
|
||
try { await summaryExport.current?.exportExcel(); }
|
||
catch (error) { message.error(`导出失败:${chooseError(error)}`); }
|
||
finally { setSummaryExporting(false); }
|
||
}}>
|
||
{defectDrill.tableControls}
|
||
<SmoothTableFrame busy={queryBusy || !tableReady || defectDrill.tablePending} blocked={queryBusy || summaryBusy || !tableReady || defectDrill.tablePending}>
|
||
<MetricTable
|
||
ref={summaryExport}
|
||
defectDrilldown={tableReady&&!queryBusy?defectDrill.table:undefined}
|
||
paginationScope={retainedTable?.paginationScope}
|
||
exportFilename={`${drilledProduct || scopeName}质量汇总-${year}${drilledProduct || period === 'year' ? '' : period === 'month' ? `-${String(month).padStart(2, '0')}` : `-Q${quarter}`}-${fullFields ? '完整字段' : '关键指标'}`}
|
||
rows={tableRows}
|
||
view={tableView}
|
||
layoutView={retainedTable?.layoutView || view}
|
||
pageSizeOverride={tableProduct ? 12 : undefined}
|
||
period={tablePeriod}
|
||
month={tableMonth}
|
||
quarter={tableQuarter}
|
||
fullFields={fullFields}
|
||
defectDisplay={defectDisplay}
|
||
rateBasis={rateBasis}
|
||
onDetail={openRecords}
|
||
onBasis={() => setBasisOpen(true)}
|
||
emptyText={queryBusy ? '正在更新数据…' : currentMetricsError ? '查询失败,暂无可展示结果' : '当前条件下暂无数据'}
|
||
onDrilldown={row => {
|
||
if (drilledProduct) return;
|
||
if (view === 'overall') setViewOverride('department');
|
||
else if (view === 'department' && row.department) { setSearch(''); setAppliedSearch(''); setTrendObject(''); setGroup([]); setProduct([]); setDepartment([row.department]); setViewOverride('group'); }
|
||
else if (view === 'group' && row.group) { setSearch(''); setAppliedSearch(''); setTrendObject(''); setProduct([]); setGroup([row.group]); setViewOverride('product'); }
|
||
else if (view === 'product') {
|
||
const selectedProduct = row.key === '__UNASSIGNED__' || !row.product && !row.key?.trim() ? '__UNASSIGNED__' : row.product || row.label;
|
||
if (!selectedProduct) return;
|
||
setDrilledProduct(selectedProduct);
|
||
setTrendObject(selectedProduct);
|
||
setTrendGranularity('month');
|
||
if(trendMode!=='defects')setTrendMode('production');
|
||
}
|
||
}}
|
||
/>
|
||
</SmoothTableFrame>
|
||
</QueryTablePanel>
|
||
|
||
<section className="panel section-panel defects-panel" data-snapshot-module="defects" ref={defectsSection} aria-busy={defectsRefreshing} style={{ minHeight: queryBusy && trendAnchorTop.current != null ? defectsHeight.current : undefined }}>
|
||
<div className="section-heading-row">
|
||
<SectionHeading title="不良具体构成" />
|
||
{defectsRefreshing && <span className="defect-refresh-indicator"><Spin size="small" />正在更新</span>}
|
||
</div>
|
||
{trendObjectMetricsError && <Alert showIcon type="warning" message="当前趋势对象的不良数据读取失败" description={trendObjectMetricsError} />}
|
||
<div className="defect-stage-grid" inert={!activeDefectData}>
|
||
{(['black', 'bright'] as const).map(stage => {
|
||
const items = stage === 'black' ? blackDefectItems : brightDefectItems;
|
||
return <section className="defect-stage-column" key={stage} aria-label={`${stage === 'black' ? '黑片' : '亮片'}不良构成`}>
|
||
<h3 className={`defect-stage-title ${stage}`}><i />{stage === 'black' ? '黑片' : '亮片'}</h3>
|
||
{items.length
|
||
? <DefectBreakdown items={items} stage={stage} totalWeight={displayedDefectData?.summary?.[stage]?.totalWeight} maximum={Math.max(0, ...items.map(item => item.weight ?? 0))} onDetail={() => openRecords(null, stage, undefined, defectQueryParams, activeDefectData)} />
|
||
: !defectsRefreshing && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前条件下暂无不良分类数据" />}
|
||
</section>;
|
||
})}
|
||
</div>
|
||
{displayedDefectData ? <DefectParetoPanel releaseId={displayedDefectData.release?.id} query={displayedDefectQuery} refreshKey={queryRevision} pending={defectsRefreshing||queryBusy} externalScrapWeight={blackDefectItems.find(item => item.name === '外废')?.weight} onUnauthorized={onUnauthorized} /> : !defectsRefreshing && <div className="defect-pareto-status">不良数据暂不可用</div>}
|
||
</section>
|
||
</div>
|
||
</>
|
||
|
||
|
||
|
||
<Modal open={basisOpen} title="综合合格率计算口径" onCancel={() => setBasisOpen(false)} footer={<Button onClick={() => setBasisOpen(false)}>关闭</Button>} width={680}>
|
||
<div className="basis-card"><span>当前综合合格率</span><strong>{rateText(visibleCompositeRate(rowForSummary, rateBasis))}</strong><span>黑片 {rateText(visibleStageRate(rowForSummary, 'black'))} · 亮片 {rateText(visibleStageRate(rowForSummary, 'bright', rateBasis))}</span></div>
|
||
<p className="basis-copy">以下为当前查询实际使用的公式、适用条件与空值处理规则。月、季、年先汇总计算分量,再按生效公式计算。</p>
|
||
<dl className="basis-details">
|
||
<dt>综合公式</dt><dd>{formulaText(compositeFormula)}</dd>
|
||
<dt>黑片公式</dt><dd>{formulaText(formulaDescriptions.blackRate)}</dd>
|
||
<dt>{rateBasis === 'original' ? '亮片公式' : '亮片调整公式'}</dt><dd>{formulaText(brightFormula)}</dd>
|
||
<dt>统计范围</dt><dd>{year}年{period === 'month' ? ` ${MONTHS[month - 1]}` : period === 'quarter' ? ` 第${quarter}季度` : '度'} · {drilledProduct || scopeName}</dd>
|
||
<dt>总重量</dt><dd>黑片 {numberText(rowForSummary?.black?.totalWeight)} kg · 亮片 {numberText(rowForSummary?.bright?.totalWeight)} kg</dd>
|
||
<dt>覆盖行数</dt><dd>黑片 {rowForSummary?.coverage.blackRows ?? '—'} · 亮片 {rowForSummary?.coverage.brightRows ?? '—'}</dd>
|
||
<dt>来源行覆盖</dt><dd>原始 {summaryMetricsData?.coverage.rawRows ?? '—'} · 参与 {summaryMetricsData?.coverage.includedRows ?? '—'} · 未分类行 (已计入) {summaryMetricsData?.coverage.excludedBlankRows ?? '—'}</dd>
|
||
<dt>业务分类映射</dt><dd>未映射 {summaryMetricsData?.coverage.unmappedRows ?? '—'} 行</dd>
|
||
<dt>项目组维度</dt><dd>{summaryMetricsData?.coverage.projectGroupUnconfiguredRows ?? '—'} 行未配置项目组归属。该计数不等于排除行数;是否参与指标由当前筛选及规则决定。</dd>
|
||
</dl>
|
||
|
||
</Modal>
|
||
|
||
{recordQuerySnapshot && <RecordsDrawer
|
||
key={JSON.stringify({ query: recordQuerySnapshot, stage: recordStage })}
|
||
open={recordsOpen}
|
||
row={selectedRecord}
|
||
stage={recordStage}
|
||
onStage={setRecordStage}
|
||
onClose={() => { setSelectedRecord(null); setRecordMonth(undefined); setRecordsOpen(false); }}
|
||
query={recordQuerySnapshot}
|
||
month={recordMonth}
|
||
onUnauthorized={onUnauthorized}
|
||
/>}
|
||
</div>
|
||
);
|
||
}
|
||
|
||
export function MetricCard({ primary, label, value, note, stage, onClick }: { primary?: boolean; label: React.ReactNode; value: string; note?: string; stage?: Stage; onClick: () => void }) {
|
||
const displayedValue = useAnimatedMetricText(value);
|
||
const parts = displayedValue.match(/^(.*?)(%| kg)$/);
|
||
return <button className={`metric-card ${primary ? 'primary' : ''} ${stage || ''}`} onClick={onClick}>
|
||
<span className="metric-label">{stage && <i className={`stage-dot ${stage}`} />}{label}</span>
|
||
<strong className="metric-value">{parts ? <>{parts[1]}<span className="metric-unit">{parts[2]}</span></> : displayedValue}</strong>
|
||
{note && <small>{note}</small>}
|
||
</button>;
|
||
}
|
||
|
||
export function DefectBreakdown({ items, stage, totalWeight, onDetail }: { items: DefectMetric[]; stage: Stage; totalWeight?: number | null; maximum: number; onDetail: () => void }) {
|
||
return <DefectComposition items={items} stage={stage} totalWeight={totalWeight} onDetail={onDetail} />;
|
||
}
|
||
|
||
|
||
export function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUnauthorized, onlyStage, refreshKey = 0, pending = false }: {
|
||
releaseId?: string; query: QueryParams; externalScrapWeight?: number | null; onUnauthorized: (error: unknown) => boolean; onlyStage?: Stage; refreshKey?: number; pending?: boolean;
|
||
}) {
|
||
const { active } = usePageCache();
|
||
const container = useRef<HTMLDivElement>(null);
|
||
const chart = useRef<ReturnType<typeof echarts.init> | null>(null);
|
||
const [responses, setResponses] = useState<{ black: FineDefectTopResponse; bright: FineDefectTopResponse; externalScrapWeight?: number | null } | null>(null);
|
||
const [loading, setLoading] = useState(false);
|
||
const [error, setError] = useState('');
|
||
const [themeRevision, setThemeRevision] = useState(0);
|
||
const fineQuery = useMemo(() => ({
|
||
year: query.year,
|
||
...(query.productSearch ? { productSearch: query.productSearch } : {}),
|
||
...(query.extraFilters ? { extraFilters: query.extraFilters } : {}),
|
||
...(query.columnFilters?.length ? { columnFilters: query.columnFilters } : {}),
|
||
...(query.month != null ? { month: query.month } : {}),
|
||
...(query.quarter != null ? { quarter: query.quarter } : {}),
|
||
...(query.department ? { department: query.department } : {}),
|
||
...(query.group ? { group: query.group } : {}),
|
||
...(query.product ? { product: query.product } : {}),
|
||
...(query.projectGroup ? { projectGroup: query.projectGroup } : {}),
|
||
...(query.includeUnassigned ? { includeUnassigned: true } : {}),
|
||
}), [query.year, query.month, query.quarter, query.department, query.group, query.product, query.productSearch, query.projectGroup, query.extraFilters, query.columnFilters, query.includeUnassigned]);
|
||
const fineQueryKey = JSON.stringify(fineQuery);
|
||
const [snapshotRequested, setSnapshotRequested] = useState(false);
|
||
useEffect(() => {
|
||
const root = container.current?.closest('.query-page');
|
||
const request = (event: Event) => { if (active && (event as CustomEvent<{modules:string[]}>).detail?.modules.includes('pareto')) setSnapshotRequested(true); };
|
||
root?.addEventListener('quality:query-snapshot', request);
|
||
return () => root?.removeEventListener('quality:query-snapshot', request);
|
||
}, [active]);
|
||
const visible = useResourceVisibility(container, active) || snapshotRequested;
|
||
const showLoading = useDelayedIndicator(loading);
|
||
|
||
useEffect(() => {
|
||
if (!active || !visible || pending) return;
|
||
if (!releaseId) { setResponses(null); setLoading(false); setError(''); return; }
|
||
const controller = new AbortController();
|
||
const base = { releaseId, ...fineQuery, mode: 'top', dimension: 'defect', limit: 100 };
|
||
setLoading(true);
|
||
setError('');
|
||
Promise.all([
|
||
onlyStage === 'bright' ? Promise.resolve({kind:'fine_defect_top' as const,releaseId,sourceRows:0,rows:[]}) : api.fineDefectTop({ ...base, stage: 'black' }, controller.signal),
|
||
onlyStage === 'black' ? Promise.resolve({kind:'fine_defect_top' as const,releaseId,sourceRows:0,rows:[]}) : api.fineDefectTop({ ...base, stage: 'bright' }, controller.signal),
|
||
]).then(([black, bright]) => { if (!controller.signal.aborted) setResponses({ black, bright, externalScrapWeight }); })
|
||
.catch(value => {
|
||
if (controller.signal.aborted) return;
|
||
if (onUnauthorized(value)) return;
|
||
setError(value instanceof ApiError && value.status === 403 ? '当前账号没有查看细分缺陷源字段的权限' : chooseError(value));
|
||
})
|
||
.finally(() => { if (!controller.signal.aborted) setLoading(false); });
|
||
return () => controller.abort();
|
||
}, [active, visible, pending, releaseId, fineQueryKey, onUnauthorized, onlyStage, refreshKey, externalScrapWeight]);
|
||
|
||
useEffect(() => {
|
||
const refresh = () => setThemeRevision(value => value + 1);
|
||
const observer = new MutationObserver(refresh);
|
||
observer.observe(document.documentElement, { attributes: true, attributeFilter: ['data-workspace-theme'] });
|
||
const compact = window.matchMedia('(max-width: 760px)');
|
||
compact.addEventListener('change', refresh);
|
||
return () => { observer.disconnect(); compact.removeEventListener('change', refresh); };
|
||
}, []);
|
||
|
||
useEffect(() => {
|
||
const node = container.current;
|
||
if (!node || !active) return;
|
||
const instance = echarts.init(node, undefined, { renderer: 'svg', width: node.clientWidth, height: node.clientHeight });
|
||
chart.current = instance;
|
||
const observer = new ResizeObserver(() => {
|
||
const { clientWidth: width, clientHeight: height } = node;
|
||
if (width > 0 && height > 0 && (width !== instance.getWidth() || height !== instance.getHeight())) {
|
||
instance.resize({ width, height, animation: { duration: 0 } });
|
||
}
|
||
});
|
||
observer.observe(node);
|
||
return () => { observer.disconnect(); instance.dispose(); if (chart.current === instance) chart.current = null; };
|
||
}, [active]);
|
||
|
||
const items = useMemo(() => {
|
||
if (!responses) return [];
|
||
const raw: Array<{ key: string; label: string; category: string; weight: number | null; kind: 'source' | 'category' }> = (['black', 'bright'] as const).flatMap(stage => responses[stage].rows.map(row => ({
|
||
key: `${stage}:${row.key}`,
|
||
label: `${stage === 'black' ? '黑片' : '亮片'}·${row.label || row.key}`,
|
||
category: row.category,
|
||
weight: row.weight,
|
||
kind: 'source' as const,
|
||
})));
|
||
if (onlyStage !== 'bright' && typeof responses.externalScrapWeight === 'number' && Number.isFinite(responses.externalScrapWeight) && responses.externalScrapWeight > 0) {
|
||
raw.push({ key: 'black:externalScrap', label: '黑片·外废', category: '外废', weight: responses.externalScrapWeight, kind: 'category' });
|
||
}
|
||
return raw.filter(item => typeof item.weight === 'number' && Number.isFinite(item.weight) && item.weight > 0)
|
||
.sort((left, right) => right.weight! - left.weight! || left.label.localeCompare(right.label, 'zh-CN'));
|
||
}, [responses, onlyStage]);
|
||
const totalWeight = items.reduce((total, item) => total + (item.weight || 0), 0);
|
||
|
||
useEffect(() => {
|
||
const instance = chart.current;
|
||
if (!instance) return;
|
||
if (!items.length) { instance.clear(); return; }
|
||
if (!container.current) return;
|
||
const { fontFamily, numericFamily, fontSize, tooltipFontSize } = queryChartTypography(container.current);
|
||
const styles = getComputedStyle(container.current);
|
||
const ink = styles.getPropertyValue('--ink').trim() || '#222222';
|
||
const line = styles.getPropertyValue('--line').trim() || '#dfe5ef';
|
||
const black = styles.getPropertyValue('--defect-black').trim() || '#718797';
|
||
const bright = styles.getPropertyValue('--defect-bright').trim() || '#607AE1';
|
||
const surface = styles.getPropertyValue('--surface').trim() || '#ffffff';
|
||
let accumulated = 0;
|
||
const cumulative = items.map(item => {
|
||
accumulated += item.weight || 0;
|
||
return Number((accumulated / totalWeight * 100).toFixed(3));
|
||
});
|
||
const option: echarts.EChartsCoreOption = {
|
||
textStyle: { color: ink, fontFamily, fontSize },
|
||
animation: !window.matchMedia('(prefers-reduced-motion: reduce)').matches,
|
||
animationDuration: 420,
|
||
animationDurationUpdate: 520,
|
||
grid: { left: 32, right: 24, top: 48, bottom: 12, containLabel: true },
|
||
legend: { top: 8, data: ['报废重量', '累计占比'], textStyle: { color: ink, fontFamily, fontSize, fontWeight: 500 } },
|
||
tooltip: {
|
||
trigger: 'axis',
|
||
axisPointer: { type: 'shadow' },
|
||
backgroundColor: surface,
|
||
borderColor: line,
|
||
textStyle: { color: ink, fontFamily, fontSize: tooltipFontSize },
|
||
formatter: (rawParams: unknown) => {
|
||
const list = (Array.isArray(rawParams) ? rawParams : [rawParams]) as Array<{ dataIndex?: number }>;
|
||
const index = Number(list[0]?.dataIndex);
|
||
const item = items[index];
|
||
if (!item) return '';
|
||
const share = totalWeight > 0 ? (item.weight || 0) / totalWeight * 100 : 0;
|
||
return `<strong>${escapeTooltipText(item.label)}</strong><br/>分类:${escapeTooltipText(item.category)}<br/>报废重量:${numberText(item.weight)} kg<br/>综合占比:${share.toFixed(2)}%<br/>累计占比:${cumulative[index].toFixed(2)}%`;
|
||
},
|
||
},
|
||
xAxis: {
|
||
type: 'category',
|
||
data: items.map(item => item.label),
|
||
axisLabel: { color: ink, rotate: 35, interval: 0, hideOverlap: true, fontSize },
|
||
axisLine: { lineStyle: { color: line } },
|
||
axisTick: { alignWithLabel: true, lineStyle: { color: line } },
|
||
},
|
||
yAxis: [
|
||
{ type: 'value', name: '报废重量 / kg', nameTextStyle: { color: ink, fontSize }, axisLabel: { color: ink, fontFamily: numericFamily, fontSize }, splitLine: { lineStyle: { color: line, type: 'dashed' } } },
|
||
{ type: 'value', name: '累计占比', min: 0, max: 100, nameTextStyle: { color: ink, fontSize }, axisLabel: { color: ink, fontFamily: numericFamily, fontSize, formatter: '{value}%' }, splitLine: { show: false } },
|
||
],
|
||
series: [
|
||
{ id: 'pareto-weight', name: '报废重量', type: 'bar', z: 1, barMaxWidth: 36, itemStyle: { color: onlyStage === 'black' ? black : bright }, data: items.map(item => ({ id: item.key, name: item.label, value: item.weight, itemStyle: { color: item.kind === 'category' ? '#9aa4b2' : item.key.startsWith('black:') ? black : bright } })) },
|
||
{ id: 'pareto-cumulative', name: '累计占比', type: 'line', z: 10, yAxisIndex: 1, symbol: 'circle', symbolSize: 5, lineStyle: { width: 2, color: '#d58c35' }, itemStyle: { color: '#d58c35', borderColor: surface, borderWidth: 1 }, data: cumulative.map((value, index) => ({ id: items[index].key, name: items[index].label, value })) },
|
||
],
|
||
};
|
||
instance.setOption(option, { replaceMerge: ['series'], lazyUpdate: false });
|
||
}, [items, totalWeight, themeRevision, active]);
|
||
|
||
return <section className="defect-pareto-section" data-snapshot-module="pareto" data-snapshot-ready={error ? 'error' : responses && !loading && !pending ? 'true' : 'false'} aria-busy={loading || pending} aria-label={onlyStage ? `${onlyStage === 'black' ? '黑片' : '亮片'}报废重量柏拉图` : '综合报废重量柏拉图'}>
|
||
<div className="defect-pareto-heading"><strong>{onlyStage ? `${onlyStage === 'black' ? '黑片' : '亮片'}报废重量柏拉图` : '黑片与亮片综合报废重量柏拉图'}</strong>{showLoading && <span className="defect-refresh-indicator"><Spin size="small" />正在更新</span>}</div>
|
||
{error && <Alert showIcon type="warning" message="细分报废重量读取失败" description={error} />}
|
||
{!loading && !releaseId && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前没有已发布数据版本" />}
|
||
{!loading && !error && responses && !items.length && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前筛选下没有正值细分报废重量" />}
|
||
<div className="defect-pareto-chart" ref={container} inert={loading || pending || !!error} style={{ display: !releaseId || (responses && !items.length) ? 'none' : undefined }} aria-label="按报废重量降序排列,折线表示累计占比" />
|
||
</section>;
|
||
}
|
||
|
||
export function SectionHeading({ title, subtitle }: { title: string; subtitle?: string }) {
|
||
return <div className="section-heading"><h2>{title}</h2>{subtitle && <span>{subtitle}</span>}</div>;
|
||
}
|
||
|
||
function useCompactTable() {
|
||
const [compact, setCompact] = useState(() => window.matchMedia('(max-width: 760px)').matches);
|
||
useEffect(() => {
|
||
const media = window.matchMedia('(max-width: 760px)');
|
||
const update = () => setCompact(media.matches);
|
||
media.addEventListener('change', update);
|
||
return () => media.removeEventListener('change', update);
|
||
}, []);
|
||
return compact;
|
||
}
|
||
|
||
|
||
const totalWeightTitle = (label: string) => <span className="query-total-weight-title">{label}<Tooltip trigger={['hover', 'focus']} title={<div>黑片总重量为合格率计算使用的适用总重量。<br />按来源逐行计算:合格重量+报废重量-利用料及废品库对应的合格重量、报废重量;发料地点包含“利用料”或“废品”时扣减。<br />检验备注包含“过账”时,外废不计入报废重量;月、季、年均先汇总来源分量。具体取值以已发布数据版本及生效规则为准。</div>}><InfoCircleOutlined tabIndex={0} role="img" aria-label="黑片总重量计算说明" /></Tooltip></span>;
|
||
|
||
const rateBasisTitle = (label: string, basis: QueryRateBasis, kind: 'bright' | 'composite', onBasis?: () => void) => <span className="query-total-weight-title query-rate-rule-title"><span className="query-rate-label">{onBasis ? <button className="header-link" onClick={onBasis}>{label}</button> : label}{basis !== 'original' && <small className="query-rate-subtitle">(去本部报废)</small>}</span>{basis !== 'original' && <Tooltip trigger={['hover', 'focus']} title={<div>{kind === 'composite' && <>综合合格率=黑片合格率×亮片合格率。<br /></>}原口径:亮片合格重量÷亮片总重量。<br />去本部报废:(亮片合格重量+本部报废)÷亮片总重量,同时从亮片报废重量中扣除本部报废,总重量不变。<br />当前:去本部报废。计算结果以已发布数据版本及生效规则为准。</div>}><InfoCircleOutlined tabIndex={0} role="img" aria-label={`${kind === 'composite' ? '综合合格率' : '亮片合格率'}计算说明`} /></Tooltip>}</span>;
|
||
|
||
export function MetricTable({
|
||
ref, exportFilename, rows, view, defectDrilldown, layoutView = view, pageSizeOverride, paginationScope, period, month, quarter, fullFields, rateBasis, onDetail, onBasis, onDrilldown, onlyStage, defectDisplay = 'weight', emptyText = '当前条件下暂无数据',
|
||
}: {
|
||
ref?: React.Ref<{ exportExcel: () => Promise<void> }>; exportFilename: string; defectDrilldown?: DefectDrilldownResponse;
|
||
rows: MetricRow[]; view: ViewKind; layoutView?: ViewKind; pageSizeOverride?: number; paginationScope?: string; period: PeriodKind; month: number; quarter: number; fullFields: boolean;
|
||
rateBasis: 'original' | 'withoutHeadquartersScrap';
|
||
onDetail: (row: MetricRow | null, stage: Stage, month?: number) => void; onBasis: () => void; onDrilldown: (row: MetricRow) => void;
|
||
emptyText?: string; onlyStage?: Stage; defectDisplay?: 'weight'|'rate';
|
||
}) {
|
||
const compact = useCompactTable();
|
||
const isOverall = view === 'overall';
|
||
const title = (row: MetricRow) => isOverall && period === 'year' && ['quarter', 'year'].includes((row as TrendMetricRow).granularity || '')
|
||
? (row as TrendMetricRow).periodLabel || row.label
|
||
: isOverall && period === 'year'
|
||
? (monthNumber((row as TrendMetricRow).month) ? MONTHS[monthNumber((row as TrendMetricRow).month)! - 1] : row.label)
|
||
: isOverall && period === 'month' ? MONTHS[month - 1]
|
||
: isOverall && period === 'quarter' ? `第${quarter}季度` : objectLabel(row, view);
|
||
const openRow = (row: MetricRow, stage: Stage) => {
|
||
if ((row as TrendMetricRow).noData) return;
|
||
onDetail(row, stage, isOverall && period === 'year' ? monthNumber((row as TrendMetricRow).month) || undefined : isOverall && period === 'month' ? month : undefined);
|
||
};
|
||
const numeric = (label: string, stage: Stage, field: 'qualifiedWeight' | 'scrapWeight' | 'totalWeight' | 'rate' | 'headquartersScrapWeight', className = '') => ({
|
||
title: stage === 'black' && field === 'totalWeight' ? totalWeightTitle(`${compact ? '黑片' : ''}${label}`) : stage === 'bright' && field === 'rate' ? rateBasisTitle(`${compact ? '亮片' : ''}${label}`, rateBasis, 'bright') : `${compact ? stage === 'black' ? '黑片' : '亮片' : ''}${defectDisplay === 'rate' && (field === 'scrapWeight' || field === 'headquartersScrapWeight') ? defectRateLabel(label) : label}`,
|
||
exportRate: defectDisplay === 'rate' && (field === 'scrapWeight' || field === 'headquartersScrapWeight'),
|
||
key: `${stage}-${field}`,
|
||
align: 'center' as const,
|
||
width: field === 'rate' ? (stage === 'bright' && rateBasis !== 'original' ? 164 : fullFields ? 96 : 116) : (fullFields ? 112 : 145),
|
||
className: `${field === 'rate' ? `rate-cell ${stage}` : 'weight-cell'} ${className}`,
|
||
render: (_: unknown, row: MetricRow) => <Button type="link" className="table-value" tabIndex={-1} style={{ userSelect: 'text', WebkitUserSelect: 'text' }}><AnimatedMetricText value={field === 'rate' ? rateText(visibleStageRate(row, stage)) : defectDisplay === 'rate' && (field === 'scrapWeight' || field === 'headquartersScrapWeight') ? rateText(defectWeightRate(stageValue(row, stage, field, rateBasis),stageValue(row, stage, 'totalWeight'))) : numberText(stageValue(row, stage, field, rateBasis))} /></Button>,
|
||
});
|
||
const defectColumns = (stage: Stage, names: string[]) => names.map(name => ({
|
||
title: `${compact ? stage === 'black' ? '黑片' : '亮片' : ''}${defectDisplay === 'rate' ? defectRateLabel(name) : name}`,
|
||
exportRate: defectDisplay === 'rate',
|
||
key: `${stage}-defect-${name}`,
|
||
align: 'center' as const,
|
||
width: fullFields ? 100 : 130,
|
||
render: (_: unknown, row: MetricRow) => {
|
||
const value = defectList(row, stage).find(item => item.name === name);
|
||
return <Button type="link" className="table-value" tabIndex={-1} style={{ userSelect: 'text', WebkitUserSelect: 'text' }}><AnimatedMetricText value={defectDisplay === 'rate' ? rateText(defectWeightRate(value?.weight,stageValue(row,stage,'totalWeight'))) : numberText(value?.weight ?? null)} /></Button>;
|
||
},
|
||
}));
|
||
const fieldLabels: Record<MetricStageField, string> = {
|
||
totalWeight: '总重量', qualifiedWeight: '合格重量', scrapWeight: '报废重量',
|
||
headquartersScrapWeight: '本部报废', rate: '合格率',
|
||
};
|
||
const stageColumns = (stage: Stage): ColumnsType<MetricRow> => {
|
||
const base: ColumnsType<MetricRow> = metricStageColumnPlan(rows, stage, defectDrilldown ? false : fullFields, rateBasis).map(column => {
|
||
if (column.kind === 'defect') return defectColumns(stage, [column.name])[0];
|
||
const metricColumn = numeric(fieldLabels[column.field], stage, column.field);
|
||
return stage === 'bright' && column.field === 'rate'
|
||
? { ...metricColumn, render: (_: unknown, row: MetricRow) => <Button type="link" className="table-value" tabIndex={-1} style={{ userSelect: 'text', WebkitUserSelect: 'text' }}><AnimatedMetricText value={rateText(visibleStageRate(row, 'bright', rateBasis))} /></Button> }
|
||
: metricColumn;
|
||
});
|
||
if(defectDrilldown?.stage===stage) {
|
||
const data=defectDrilldown;
|
||
const fields=[{key:'parent',label:data.category},...data.fields];
|
||
const columns=fields.map(field=>({key:`${stage}-fine-${field.key}`,title:defectDisplay==='rate'?fineDefectRateLabel(field.label):field.label.replace(/重量$/,''),exportRate:defectDisplay==='rate',align:'center' as const,width:140,
|
||
render:(_:unknown,row:MetricRow)=>{const value=defectCell(data,row,field.key,defectDisplay);return defectDisplay==='rate'?rateText(value):numberText(value);}}));
|
||
base.splice(base.length-1,0,...columns);
|
||
}
|
||
return base;
|
||
};
|
||
const allColumns: ColumnsType<MetricRow> = [
|
||
{ title: isOverall ? period === 'year' && !rows.some(row => ['quarter', 'year'].includes((row as TrendMetricRow).granularity || '')) ? '月份' : '统计期间' : view === 'group' ? '产业部 / 业务分组' : view === 'product' ? '产品规格' : view === 'projectGroup' ? '项目组' : view === 'department' ? '产业部' : '对象', key: 'object', dataIndex: 'label', fixed: 'left', width: compact ? isOverall ? 100 : 180 : isOverall ? 120 : layoutView === 'product' ? (fullFields ? 240 : 300) : layoutView === 'group' ? (fullFields ? 220 : 260) : (fullFields ? 180 : 220), render: (_: unknown, row) => <span className="object-cell">{view === 'department' || view === 'group' || view === 'product' ? <Button type="link" className="object-drilldown" style={{ userSelect: 'text', WebkitUserSelect: 'text' }} onClick={() => { if (window.getSelection()?.isCollapsed !== false) onDrilldown(row); }}>{title(row)} <span>›</span></Button> : <strong>{title(row)}</strong>}{view === 'group' && row.department && <small>{row.department}</small>}</span> },
|
||
{ key: 'stage-black', title: <span className="stage-heading black"><i />黑片</span>, children: stageColumns('black') },
|
||
{ key: 'stage-bright', title: <span className="stage-heading bright"><i />亮片</span>, children: stageColumns('bright') },
|
||
{ title: rateBasisTitle('综合合格率', rateBasis, 'composite', onBasis), key: 'compositeRate', dataIndex: 'compositeRate', align: 'center', fixed: compact ? undefined : 'right', width: 120, className: 'combined-column', render: (_: number | null, row: MetricRow) => <button className="combined-value" tabIndex={-1} style={{ userSelect: 'text', WebkitUserSelect: 'text' }}><AnimatedMetricText value={rateText(visibleCompositeRate(row, rateBasis))} /></button> },
|
||
{ title: '操作', key: 'actions', fixed: compact ? undefined : 'right', width: 96, align: 'center', render: (_: unknown, row) => (row as TrendMetricRow).noData ? <span>—</span> : <Button type="link" onClick={() => openRow(row, onlyStage || 'black')}>来源明细</Button> },
|
||
];
|
||
const columns = onlyStage ? allColumns.filter(column => !['compositeRate', `stage-${onlyStage === 'black' ? 'bright' : 'black'}`].includes(String(column.key))) : allColumns;
|
||
useImperativeHandle(ref, () => ({
|
||
exportExcel: () => downloadMetricWorkbook(exportFilename, columns, rows, (key, row) => {
|
||
if (key === 'object') return [title(row), view === 'group' ? row.department : null].filter(Boolean).join(' / ');
|
||
if (key === 'compositeRate') return visibleCompositeRate(row, rateBasis);
|
||
const stage: Stage = key.startsWith('black-') ? 'black' : 'bright';
|
||
if (defectDrilldown && key.startsWith(`${stage}-fine-`)) return defectCell(defectDrilldown,row,key.slice(`${stage}-fine-`.length),defectDisplay);
|
||
if (key.startsWith(`${stage}-defect-`)) {
|
||
const weight=defectList(row, stage).find(item => item.name === key.slice(`${stage}-defect-`.length))?.weight ?? null;
|
||
return defectDisplay === 'rate' ? defectWeightRate(weight,stageValue(row,stage,'totalWeight')) : weight;
|
||
}
|
||
const field = key.slice(stage.length + 1) as 'qualifiedWeight' | 'scrapWeight' | 'totalWeight' | 'headquartersScrapWeight' | 'rate';
|
||
if (defectDisplay === 'rate' && (field === 'scrapWeight' || field === 'headquartersScrapWeight')) return defectWeightRate(stageValue(row,stage,field,rateBasis),stageValue(row,stage,'totalWeight'));
|
||
return field === 'rate' ? visibleStageRate(row, stage, stage === 'bright' ? rateBasis : 'original') : stageValue(row, stage, field, rateBasis);
|
||
}),
|
||
}));
|
||
const dataSource = rows.map((row, index) => ({ ...row, sourceMetricKey: row.key, key: row.key || `${title(row)}-${index}` }));
|
||
const [currentPage, setCurrentPage] = useState(1);
|
||
const [pageSize, setPageSize] = useState(SUMMARY_PAGE_SIZE);
|
||
const effectivePage = pageSizeOverride == null ? Math.min(currentPage, Math.max(1, Math.ceil(rows.length / pageSize))) : 1;
|
||
const effectivePageSize = pageSizeOverride ?? pageSize;
|
||
useEffect(() => setCurrentPage(1), [paginationScope ?? rows]);
|
||
const columnWidth = (column: ColumnsType<MetricRow>[number]): number => {
|
||
if ('children' in column && column.children?.length) {
|
||
return column.children.reduce((total, child) => total + columnWidth(child), 0);
|
||
}
|
||
return typeof column.width === 'number' && Number.isFinite(column.width) ? column.width : 120;
|
||
};
|
||
const scrollWidth = Math.ceil(columns.reduce((total, column) => total + columnWidth(column), 0));
|
||
const scroll = { x: scrollWidth };
|
||
const displayColumns = compact ? columns.flatMap(column => 'children' in column && column.children ? column.children : [column]) : columns;
|
||
const pageRows = dataSource.slice((effectivePage - 1) * effectivePageSize, effectivePage * effectivePageSize);
|
||
return <div className="metric-table-scroll"><Table<MetricRow> size="small" bordered tableLayout="fixed" columns={displayColumns} dataSource={pageRows} pagination={false} scroll={scroll} rowKey="key" locale={{ emptyText }} />
|
||
{pageSizeOverride == null && <MetricTablePagination current={effectivePage} total={dataSource.length} pageSize={pageSize} onChange={(nextPage, nextPageSize) => { setPageSize(nextPageSize); setCurrentPage(nextPageSize === pageSize ? nextPage : 1); }} />}
|
||
</div>;
|
||
}
|
||
|
||
function MetricTablePagination({ current, total, pageSize, onChange }: { current: number; total: number; pageSize: number;
|
||
onChange: (page: number, pageSize: number) => void }) {
|
||
if (total <= Math.min(pageSize, SUMMARY_PAGE_SIZE)) return null;
|
||
return <div className="metric-table-pagination"><Pagination current={current} total={total} pageSize={pageSize} showSizeChanger pageSizeOptions={SUMMARY_PAGE_SIZE_OPTIONS}
|
||
showTotal={(count, range) => `显示 ${range[0]}–${range[1]} 行,共 ${count.toLocaleString('zh-CN')} 行`} onChange={onChange} /></div>;
|
||
}
|
||
|
||
function trendBarWidth(chartWidth: number, count: number): number {
|
||
return Math.max(12, Math.min(64, Math.floor(((chartWidth - 132) / Math.max(count, 1)) * 0.8)));
|
||
}
|
||
|
||
export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedPeriod, onMonth, onlyStage, defectDrilldown, drillableCategories = [], onDefect }: { defectDrilldown?:DefectDrilldownResponse; drillableCategories?:string[]; onDefect?:(category:string)=>void; rows: TrendMetricRow[]; mode: 'production' | 'defects'; stage: Stage; rateBasis: 'original' | 'withoutHeadquartersScrap'; targetRate: number | null; selectedPeriod?: string; onMonth: (value: number | string) => void; onlyStage?: Stage }) {
|
||
const { active } = usePageCache();
|
||
const container = useRef<HTMLDivElement>(null);
|
||
const [snapshotRequested, setSnapshotRequested] = useState(false);
|
||
useEffect(() => {
|
||
const root = container.current?.closest('.query-page');
|
||
const request = (event: Event) => { if (active && (event as CustomEvent<{modules:string[]}>).detail?.modules.includes('trend')) setSnapshotRequested(true); };
|
||
root?.addEventListener('quality:query-snapshot', request);
|
||
return () => root?.removeEventListener('quality:query-snapshot', request);
|
||
}, [active]);
|
||
const visible = useResourceVisibility(container, active) || snapshotRequested;
|
||
const chart = useRef<ReturnType<typeof echarts.init> | null>(null);
|
||
const onMonthRef = useRef(onMonth);
|
||
const drillRef = useRef({onDefect,drillableCategories,drilled:!!defectDrilldown});
|
||
drillRef.current={onDefect,drillableCategories,drilled:!!defectDrilldown};
|
||
const rowsRef = useRef(rows);
|
||
const modeRef = useRef(mode);
|
||
const stageRef = useRef(stage);
|
||
const graphicIds = useRef(new Set<string>());
|
||
const previousSelection = useRef<string | undefined>(undefined);
|
||
const selectionReady = useRef(false);
|
||
const [lineSelectedPeriod, setLineSelectedPeriod] = useState<string | undefined>(undefined);
|
||
const [barMasks, setBarMasks] = useState<Array<{ period: string; left: number; top: number; width: number; height: number }>>([]);
|
||
const [themeRevision, setThemeRevision] = useState(0);
|
||
const hasRows = rows.length > 0;
|
||
onMonthRef.current = onMonth;
|
||
rowsRef.current = rows;
|
||
modeRef.current = mode;
|
||
stageRef.current = stage;
|
||
|
||
const refreshBarMasks = useCallback(() => {
|
||
const instance = chart.current;
|
||
if (!instance || modeRef.current !== 'production') { setBarMasks(previous => previous.length ? [] : previous); return; }
|
||
const zero = Number(instance.convertToPixel({ yAxisIndex: 0 }, 0));
|
||
const width = trendBarWidth(instance.getWidth(), rowsRef.current.length);
|
||
const next = rowsRef.current.flatMap(row => {
|
||
const currentStage = row[stageRef.current];
|
||
if (!hasStageRows(row, stageRef.current)) return [];
|
||
const total = (currentStage.qualifiedWeight ?? 0) + (currentStage.scrapWeight ?? 0);
|
||
if (total <= 0) return [];
|
||
const x = Number(instance.convertToPixel({ xAxisIndex: 0 }, row.periodLabel || String(row.month)));
|
||
const top = Number(instance.convertToPixel({ yAxisIndex: 0 }, total));
|
||
if (!Number.isFinite(x) || !Number.isFinite(top) || !Number.isFinite(zero)) return [];
|
||
return [{ period: String(row.period ?? row.month), left: x - width / 2, top, width, height: Math.max(0, zero - top) }];
|
||
});
|
||
setBarMasks(previous => previous.length === next.length && previous.every((mask, index) =>
|
||
mask.period === next[index].period && mask.left === next[index].left && mask.top === next[index].top && mask.width === next[index].width && mask.height === next[index].height
|
||
) ? previous : next);
|
||
}, []);
|
||
|
||
useEffect(() => {
|
||
const refresh = () => setThemeRevision(value => value + 1);
|
||
const observer = new MutationObserver(refresh);
|
||
observer.observe(document.documentElement, { attributes: true, attributeFilter: ['data-workspace-theme'] });
|
||
const compact = window.matchMedia('(max-width: 760px)');
|
||
compact.addEventListener('change', refresh);
|
||
return () => { observer.disconnect(); compact.removeEventListener('change', refresh); };
|
||
}, []);
|
||
|
||
useEffect(() => {
|
||
if (!container.current || !hasRows || !visible) return;
|
||
const instance = echarts.init(container.current, undefined, { renderer: 'svg', width: container.current.clientWidth, height: container.current.clientHeight });
|
||
chart.current = instance;
|
||
graphicIds.current.clear();
|
||
selectionReady.current = false;
|
||
setBarMasks([]);
|
||
instance.on('click', params => {
|
||
if(modeRef.current==='defects') {
|
||
const drill=drillRef.current;
|
||
if(params.componentType==='series'&&!drill.drilled&&drill.drillableCategories.includes(String(params.seriesName)))drill.onDefect?.(String(params.seriesName));
|
||
return;
|
||
}
|
||
if (params.componentType !== 'series' && params.componentType !== 'xAxis') return;
|
||
const currentRows = rowsRef.current;
|
||
const index = params.dataIndex ?? currentRows.findIndex(row => (row.periodLabel || String(row.month)) === String(params.value ?? params.name));
|
||
const item = index >= 0 ? currentRows[index] : undefined;
|
||
const value = item?.month ?? params.name ?? params.axisValue ?? params.value;
|
||
if (value != null) {
|
||
setLineSelectedPeriod(params.componentType === 'series' && params.seriesType === 'line' ? String(item?.period ?? item?.month ?? value) : undefined);
|
||
onMonthRef.current(value);
|
||
}
|
||
});
|
||
const observer = new ResizeObserver(() => {
|
||
if (!container.current) return;
|
||
const { clientWidth, clientHeight } = container.current;
|
||
if (clientWidth <= 0 || clientHeight <= 0) return;
|
||
if (clientWidth !== instance.getWidth() || clientHeight !== instance.getHeight()) {
|
||
instance.resize({ width: clientWidth, height: clientHeight, animation: { duration: 0 } });
|
||
if (modeRef.current === 'production') {
|
||
const barWidth = trendBarWidth(instance.getWidth(), rowsRef.current.length);
|
||
instance.setOption({ series: [{ id: 'qualified-weight', barWidth }, { id: 'scrap-weight', barWidth }] });
|
||
}
|
||
refreshBarMasks();
|
||
}
|
||
});
|
||
observer.observe(container.current);
|
||
return () => { observer.disconnect(); instance.dispose(); chart.current = null; };
|
||
}, [hasRows, refreshBarMasks, visible]);
|
||
|
||
useEffect(() => {
|
||
const instance = chart.current;
|
||
if (!instance || !container.current) return;
|
||
const css = getComputedStyle(container.current);
|
||
const { fontFamily, numericFamily, fontSize, tooltipFontSize } = queryChartTypography(container.current);
|
||
const ink = css.getPropertyValue('--ink').trim() || '#111111';
|
||
const blue = css.getPropertyValue('--blue').trim() || '#5368d7';
|
||
const bars = trendBarPalette(getWorkspaceTheme(document.documentElement.dataset.workspaceTheme).id);
|
||
const barColor = bars.qualified;
|
||
const teal = css.getPropertyValue('--teal').trim() || '#008f7d';
|
||
const blackLine = css.getPropertyValue('--defect-black').trim() || '#718797';
|
||
const brightLine = css.getPropertyValue('--defect-bright').trim() || blue;
|
||
const line = css.getPropertyValue('--line').trim() || '#dfe5ef';
|
||
const surface = css.getPropertyValue('--surface').trim() || '#ffffff';
|
||
const labels = rows.map(row => row.periodLabel || String(row.month));
|
||
const barData = (field: 'qualifiedWeight' | 'scrapWeight') => rows.map(row => ({
|
||
id: String(row.period ?? row.month),
|
||
value: hasStageRows(row, stage) ? stageValue(row, stage, field, rateBasis) : null,
|
||
itemStyle: { color: field === 'qualifiedWeight'
|
||
? (String(row.period ?? row.month) === selectedPeriod ? bars.selectedQualified : bars.qualified)
|
||
: (String(row.period ?? row.month) === selectedPeriod ? bars.selectedScrap : bars.scrap) },
|
||
}));
|
||
const formatTooltip = (params: unknown, onlyRates = false) => {
|
||
const items: ChartTooltipParam[] = Array.isArray(params) ? params as ChartTooltipParam[] : [params as ChartTooltipParam];
|
||
const title = String(items[0]?.name || items[0]?.axisValue || '');
|
||
return [escapeTooltipText(title), ...items.map(item => {
|
||
const name = String(item.seriesName || '');
|
||
const formatted = item.value == null ? '—' : onlyRates || name.includes('率') ? `${Number(item.value).toFixed(2)}%` : `${numberText(item.value)} kg`;
|
||
let weight='';
|
||
if(defectDrilldown&&onlyRates&&item.dataIndex!==undefined) {
|
||
const group=defectGroup(defectDrilldown,rows[item.dataIndex]);
|
||
const field=defectDrilldown.fields.find(field=>fineDefectRateLabel(field.label)===name);
|
||
const value=field?group?.children.find(child=>child.key===field.key)?.weight:group?.parentWeight;
|
||
weight=`(${numberText(value)} kg)`;
|
||
}
|
||
return `${item.marker || ''}${escapeTooltipText(name)}:${formatted}${weight}`;
|
||
})].join('<br/>');
|
||
};
|
||
const base: echarts.EChartsCoreOption = {
|
||
animation: !window.matchMedia('(prefers-reduced-motion: reduce)').matches,
|
||
animationDuration: 520,
|
||
animationEasing: 'cubicOut',
|
||
animationDurationUpdate: 520,
|
||
animationEasingUpdate: 'cubicOut',
|
||
textStyle: { fontFamily, color: ink, fontSize },
|
||
grid: { left: 65, right: mode === 'production' ? 67 : 32, top: 70, bottom: 38 },
|
||
legend: { type: 'scroll', top: 0, left: 9, right: 9, itemWidth: 14, itemHeight: 7, itemGap: 20, textStyle: { color: ink, fontFamily, fontSize, fontWeight: 500 } },
|
||
tooltip: { trigger: 'axis', backgroundColor: surface, borderColor: line, borderWidth: 1, padding: [10, 13], textStyle: { color: ink, fontFamily, fontSize: tooltipFontSize }, transitionDuration: 0, axisPointer: { type: 'line', lineStyle: { color: blue, width: 1, type: 'dashed' } }, formatter: (params: unknown) => formatTooltip(params, mode === 'defects') },
|
||
xAxis: { type: 'category', data: labels, triggerEvent: mode === 'production', axisLine: { lineStyle: { color: line } }, axisLabel: { color: ink, fontFamily, fontSize, margin: 12 }, axisTick: { show: false } },
|
||
};
|
||
let option: echarts.EChartsCoreOption;
|
||
const pointStyle = { smooth: 0.15, smoothMonotone: 'x' as const, z: 10, symbol: 'circle', symbolSize: 5, showSymbol: true, emphasis: { focus: 'none' as const, scale: 1.35 }, connectNulls: false };
|
||
if (mode === 'production') {
|
||
const rates = [...rows.flatMap(row => [visibleCompositeRate(row, rateBasis), visibleStageRate(row, 'black'), visibleStageRate(row, 'bright', rateBasis)]).filter((value): value is number => value != null).map(value => value * 100), ...(targetRate == null ? [] : [targetRate])];
|
||
const minRate = rates.length ? Math.max(0, Math.floor(Math.min(...rates) - 2)) : 0;
|
||
const maxRate = rates.length ? Math.max(100, Math.ceil(Math.max(...rates) + 1)) : 100;
|
||
const stageName = stage === 'black' ? '黑片' : '亮片';
|
||
const barWidth = trendBarWidth(instance.getWidth(), rows.length);
|
||
const ratePoints = { ...pointStyle, symbol: 'emptyCircle', symbolSize: 6 };
|
||
const targetLine = targetRate == null ? {} : { markLine: {
|
||
silent: true,
|
||
symbol: 'none',
|
||
lineStyle: { color: '#c47a47', width: 1.5, type: 'dashed' as const },
|
||
label: { show: true, formatter: `综合合格率目标 ${targetRate.toFixed(2)}%`, position: 'insideEndTop' as const, color: '#a55d30', fontSize },
|
||
data: [{ yAxis: targetRate }],
|
||
} };
|
||
option = {
|
||
...base,
|
||
yAxis: [
|
||
{ type: 'value', name: '重量 / kg', nameGap: 18, nameTextStyle: { color: ink, align: 'left', fontSize }, axisLabel: { color: ink, fontFamily: numericFamily, fontSize }, axisLine: { show: false }, axisTick: { show: false }, splitLine: { lineStyle: { color: line, type: 'dashed' } } },
|
||
{ type: 'value', name: '合格率 / %', nameGap: 18, min: minRate, max: maxRate, nameTextStyle: { color: ink, align: 'right', fontSize }, axisLabel: { color: ink, formatter: '{value}%', fontFamily: numericFamily, fontSize }, axisLine: { show: false }, axisTick: { show: false }, splitLine: { show: false } },
|
||
],
|
||
series: [
|
||
{ id: 'qualified-weight', name: `${stageName}合格重量`, type: 'bar', z: 1, stack: 'weight', yAxisIndex: 0, barWidth, itemStyle: { color: barColor }, emphasis: { itemStyle: { color: bars.hoverQualified } }, data: barData('qualifiedWeight') },
|
||
{ id: 'scrap-weight', name: `${stageName}报废重量`, type: 'bar', z: 1, stack: 'weight', yAxisIndex: 0, barWidth, itemStyle: { color: bars.scrap }, emphasis: { itemStyle: { color: bars.hoverScrap } }, data: barData('scrapWeight') },
|
||
{ id: 'composite-rate', name: '综合合格率', type: 'line', yAxisIndex: 1, ...ratePoints, ...targetLine, symbolSize: 7, emphasis: { ...pointStyle.emphasis, scale: 1.15 }, lineStyle: { width: 3.2, color: teal, cap: 'round', join: 'round' }, itemStyle: { color: teal, borderColor: teal, borderWidth: 2 }, data: rows.map(row => rateNumber(visibleCompositeRate(row, rateBasis))) },
|
||
{ id: 'black-rate', name: '黑片合格率', type: 'line', yAxisIndex: 1, ...ratePoints, lineStyle: { width: 2.6, color: blackLine, cap: 'round', join: 'round' }, itemStyle: { color: blackLine, borderColor: blackLine, borderWidth: 2 }, data: rows.map(row => rateNumber(visibleStageRate(row, 'black'))) },
|
||
{ id: 'bright-rate', name: '亮片合格率', type: 'line', yAxisIndex: 1, ...ratePoints, lineStyle: { width: 2.6, color: brightLine, cap: 'round', join: 'round' }, itemStyle: { color: brightLine, borderColor: brightLine, borderWidth: 2 }, data: rows.map(row => rateNumber(visibleStageRate(row, 'bright', rateBasis))) },
|
||
],
|
||
};
|
||
} else {
|
||
const names = Array.from(new Set(rows.flatMap(row => row[stage].defects.map(defect => defect.name))));
|
||
const palette = [blue, teal, '#bf7d58', '#9278bf', '#598eae'];
|
||
option = {
|
||
...base,
|
||
yAxis: [{ type: 'value', name: '不良率 / %', nameGap: 18, nameTextStyle: { color: ink, align: 'left', fontSize }, axisLabel: { color: ink, formatter: '{value}%', fontFamily: numericFamily, fontSize }, axisLine: { show: false }, axisTick: { show: false }, splitLine: { lineStyle: { color: line, type: 'dashed' } } }],
|
||
series: names.map((name, index) => ({ id: `defect-${stage}-${name}`, name, type: 'line' as const, triggerLineEvent:true, cursor:drillableCategories.includes(name)?'pointer':'default', ...pointStyle, lineStyle: { width: 2, color: palette[index % palette.length] }, itemStyle: { color: palette[index % palette.length] }, data: rows.map(row => { const defect = row[stage].defects.find(item => item.name === name); return rateNumber(defectWeightRate(defect?.weight, row[stage].totalWeight)); }) })),
|
||
};
|
||
}
|
||
if(mode==='defects'&&defectDrilldown) {
|
||
const data=defectDrilldown;
|
||
const palette=[blue,teal,'#bf7d58','#9278bf','#598eae','#9c8850','#5b9c86','#ba6f83','#6b7ca5'];
|
||
option={...option,series:[{id:'fine-parent',name:fineDefectRateLabel(data.category),type:'line',...pointStyle,symbol:'none',lineStyle:{width:1.5,type:'dashed',color:ink,opacity:.5},data:rows.map(row=>rateNumber(defectGroup(data,row)?.parentRate))},
|
||
...data.fields.map((field,index)=>({id:`fine-${field.key}`,name:fineDefectRateLabel(field.label),type:'line' as const,...pointStyle,lineStyle:{width:2,color:palette[index%palette.length]},itemStyle:{color:palette[index%palette.length]},data:rows.map(row=>rateNumber(defectGroup(data,row)?.children.find(child=>child.key===field.key)?.rate))}))]};
|
||
}
|
||
if(onlyStage && mode === 'production') {
|
||
const stageOption=option as {series?:Array<{id?:string}>;legend?:unknown};
|
||
stageOption.series=stageOption.series?.filter(item=>item.id==='qualified-weight'||item.id==='scrap-weight'||item.id===`${onlyStage}-rate`);
|
||
}
|
||
instance.setOption(option, { replaceMerge: ['series', 'yAxis'], lazyUpdate: false });
|
||
refreshBarMasks();
|
||
}, [rows, mode, stage, rateBasis, targetRate, themeRevision, refreshBarMasks, onlyStage, selectedPeriod, active, visible, defectDrilldown, drillableCategories.join('\0')]);
|
||
|
||
const dimmedPeriod = selectedPeriod === lineSelectedPeriod ? undefined : selectedPeriod;
|
||
|
||
useEffect(() => {
|
||
if (lineSelectedPeriod && selectedPeriod !== lineSelectedPeriod) setLineSelectedPeriod(undefined);
|
||
}, [lineSelectedPeriod, selectedPeriod]);
|
||
|
||
useLayoutEffect(() => {
|
||
const instance = chart.current;
|
||
if (!instance || !container.current) return;
|
||
const previous = previousSelection.current;
|
||
const changed = selectionReady.current && previous !== dimmedPeriod;
|
||
const animate = changed && !window.matchMedia('(prefers-reduced-motion: reduce)').matches;
|
||
const surface = getComputedStyle(container.current).getPropertyValue('--surface').trim() || '#ffffff';
|
||
const masks = mode === 'production' ? barMasks : [];
|
||
const nextIds = new Set(masks.flatMap(mask => [`wash-${mask.period}`, `focus-${mask.period}`]));
|
||
// Keep the animated bar treatment inside the chart's paint order: bars 1,
|
||
// wash 2, focus 3, lines 10. A DOM overlay would also cover every line.
|
||
const elements = masks.flatMap(mask => {
|
||
const dimmed = dimmedPeriod != null && mask.period !== dimmedPeriod;
|
||
return [
|
||
{ id: `wash-${mask.period}`, type: 'rect', silent: true, z: 2, transition: ['shape'],
|
||
shape: { x: mask.left, y: mask.top, width: mask.width, height: dimmed ? mask.height : 0 }, style: { fill: surface, opacity: trendBarPalette(getWorkspaceTheme(document.documentElement.dataset.workspaceTheme).id).wash } },
|
||
{ id: `focus-${mask.period}`, type: 'rect', silent: true, z: 3, transition: ['style'],
|
||
shape: { x: mask.left, y: mask.top, width: mask.width, height: mask.height },
|
||
style: { fill: 'transparent', stroke: 'rgba(137,165,255,.7)', lineWidth: 1, shadowBlur: 11, shadowColor: 'rgba(117,151,255,.26)', opacity: dimmedPeriod === mask.period ? 1 : 0 } },
|
||
];
|
||
});
|
||
const removed = [...graphicIds.current].filter(id => !nextIds.has(id)).map(id => ({ id, $action: 'remove' as const }));
|
||
instance.setOption({ graphic: { animation: animate, animationDurationUpdate: 340, animationEasingUpdate: 'cubicOut', elements: [...elements, ...removed] } });
|
||
graphicIds.current = nextIds;
|
||
previousSelection.current = dimmedPeriod;
|
||
selectionReady.current = true;
|
||
}, [dimmedPeriod, barMasks, mode, themeRevision]);
|
||
|
||
return <div className="chart-viewport">
|
||
<div className="chart-surface">
|
||
<div className={`chart-container ${rows.length ? '' : 'chart-empty'}`} ref={container} role="img" aria-label={mode === 'production' ? '重量和合格率趋势' : `${stage === 'black' ? '黑片' : '亮片'}不良率趋势`} />
|
||
</div>
|
||
{!rows.length && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前数据未返回趋势" />}
|
||
</div>;
|
||
}
|
||
|
||
export function TrendTable({ rows, rateBasis, onMonth, defectDisplay = 'weight', onlyStage, fullFields = false }: { rows: TrendMetricRow[]; rateBasis: 'original' | 'withoutHeadquartersScrap'; onMonth: (value: number | string) => void; defectDisplay?: 'weight'|'rate'; onlyStage?: Stage; fullFields?: boolean }) {
|
||
const compact = useCompactTable();
|
||
const stageLabel = (stage: Stage) => stage === 'black' ? '黑片' : '亮片';
|
||
const metricLabels: Record<MetricStageField, string> = {
|
||
totalWeight: '总重量', qualifiedWeight: '合格重量', scrapWeight: '报废重量',
|
||
headquartersScrapWeight: '本部报废', rate: '合格率',
|
||
};
|
||
const stageColumns = (stage: Stage): ColumnsType<TrendMetricRow> => metricStageColumnPlan(rows, stage, fullFields, rateBasis).map(column => {
|
||
const prefix = stageLabel(stage);
|
||
if (column.kind === 'defect') {
|
||
return {
|
||
title: `${prefix}${defectDisplay === 'rate' ? defectRateLabel(column.name) : column.name}${defectDisplay === 'rate' ? '' : ' / kg'}`,
|
||
key: `${stage}-defect-${column.name}`, align: 'center', width: fullFields ? 130 : 160,
|
||
render: (_: unknown, row: TrendMetricRow) => {
|
||
const value = row[stage].defects.find(item => item.name === column.name)?.weight ?? null;
|
||
return defectDisplay === 'rate' ? rateText(defectWeightRate(value, row[stage].totalWeight)) : numberText(value);
|
||
},
|
||
};
|
||
}
|
||
const field = column.field;
|
||
const baseLabel = `${prefix}${metricLabels[field]}`;
|
||
const title = field === 'totalWeight' && stage === 'black'
|
||
? totalWeightTitle(`${baseLabel} / kg`)
|
||
: field === 'rate' && stage === 'bright'
|
||
? rateBasisTitle(baseLabel, rateBasis, 'bright')
|
||
: `${defectDisplay === 'rate' && (field === 'scrapWeight' || field === 'headquartersScrapWeight') ? defectRateLabel(baseLabel) : baseLabel}${field === 'rate' || defectDisplay === 'rate' && (field === 'scrapWeight' || field === 'headquartersScrapWeight') ? '' : ' / kg'}`;
|
||
const width = field === 'rate' ? stage === 'bright' && rateBasis !== 'original' ? 194 : stage === 'black' ? 130 : 180 : fullFields ? 130 : 160;
|
||
return {
|
||
title, dataIndex: [stage, field], key: `${stage}-${field}`, align: 'center', width,
|
||
className: field === 'rate' ? `rate-cell ${stage}` : 'weight-cell',
|
||
render: (_: unknown, row: TrendMetricRow) => {
|
||
if (field === 'rate') return rateText(visibleStageRate(row, stage, stage === 'bright' ? rateBasis : 'original'));
|
||
if (field === 'scrapWeight') {
|
||
const value = queryScrapWeight(row[stage], stage, rateBasis);
|
||
return defectDisplay === 'rate' ? rateText(defectWeightRate(value, row[stage].totalWeight)) : numberText(value);
|
||
}
|
||
if (field === 'headquartersScrapWeight') {
|
||
const value = row.bright.headquartersScrapWeight ?? null;
|
||
return defectDisplay === 'rate' ? rateText(defectWeightRate(value, row.bright.totalWeight)) : numberText(value);
|
||
}
|
||
return numberText(row[stage][field]);
|
||
},
|
||
};
|
||
});
|
||
const columns: ColumnsType<TrendMetricRow> = [
|
||
{ title: '统计期间', dataIndex: 'month', key: 'month', align: 'center', fixed: 'left', width: 130, render: (_: unknown, row) => <Button type="link" onClick={() => onMonth(row.month)}>{row.periodLabel || String(row.month)}</Button> },
|
||
...stageColumns('black'), ...stageColumns('bright'),
|
||
{ title: rateBasisTitle('综合合格率', rateBasis, 'composite'), dataIndex: 'compositeRate', key: 'compositeRate', align: 'center', width: 120, fixed: compact ? undefined : 'right', className: 'combined-column', render: (_: number | null, row: MetricRow) => rateText(visibleCompositeRate(row, rateBasis)) },
|
||
];
|
||
const visibleColumns = onlyStage ? columns.filter(column => column.key === 'month' || String(column.key).startsWith(onlyStage)) : columns;
|
||
return rows.length ? <div className="metric-table-scroll trend-data-table"><Table size="small" bordered tableLayout="fixed" columns={visibleColumns} dataSource={rows} rowKey={row => String(row.month)} pagination={false} scroll={{ x: visibleColumns.reduce((total, column) => total + Number(column.width || 0), 0) }} />
|
||
</div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前数据未返回趋势" />;
|
||
}
|
||
|
||
export function RecordsDrawer({
|
||
open, row, stage, onStage, onClose, query, month, onUnauthorized, lockedStage,
|
||
}: {
|
||
open: boolean; row: MetricRow | null; stage: Stage; onStage: (stage: Stage) => void; onClose: () => void;
|
||
query: QueryParams; month?: number; onUnauthorized: (error: unknown) => boolean; lockedStage?: boolean;
|
||
}) {
|
||
const { message } = App.useApp();
|
||
const { active, refreshKey } = usePageCache();
|
||
const recordPages = useRef(new Map<string, RecordsResponse>());
|
||
const [page, setPage] = useState(1);
|
||
const [response, setResponse] = useState<{ key: string; data: RecordsResponse } | null>(null);
|
||
const [loading, setLoading] = useState(false);
|
||
const [failure, setFailure] = useState<{ key: string; message: string } | null>(null);
|
||
const [field, setField] = useState<string>();
|
||
const [fieldSearch, setFieldSearch] = useState('');
|
||
const [sort, setSort] = useState<string>();
|
||
const [direction, setDirection] = useState<'asc' | 'desc'>('asc');
|
||
const [selectedColumns, setSelectedColumns] = useState<string[]>();
|
||
const [rawFields, setRawFields] = useState<string[]>([]);
|
||
const [exporting, setExporting] = useState(false);
|
||
const [revision, setRevision] = useState(0);
|
||
const exportController = useRef<AbortController | null>(null);
|
||
useEffect(() => () => exportController.current?.abort(), []);
|
||
const recordQuery = query;
|
||
const requestParams = useMemo(() => ({ ...recordQuery, stage, page, pageSize: TABLE_PAGE_SIZE,
|
||
...(field ? { field } : {}), ...(field && fieldSearch.trim() ? { search: fieldSearch.trim() } : {}),
|
||
...(sort ? { sort, direction } : {}),
|
||
}), [recordQuery, stage, page, field, fieldSearch, sort, direction]);
|
||
const requestKey = JSON.stringify([requestParams, revision, refreshKey]);
|
||
const result = response?.key === requestKey ? response.data : null;
|
||
const error = failure?.key === requestKey ? failure.message : '';
|
||
const fetching = loading || !result && !error;
|
||
const retainedResult = useRetainedResult(result);
|
||
const showRecordLoading = useDelayedIndicator(fetching && open);
|
||
|
||
useEffect(() => {
|
||
if (!open || !active) return;
|
||
const cached = recordPages.current.get(requestKey);
|
||
if (cached) { setResponse({ key: requestKey, data: cached }); setFailure(null); setLoading(false); return; }
|
||
const controller = new AbortController();
|
||
setLoading(true);
|
||
setFailure(null);
|
||
api.records(requestParams, controller.signal).then(value => {
|
||
if (controller.signal.aborted) return;
|
||
const lastPage = Math.max(1, Math.ceil(value.total / value.pageSize));
|
||
if (page > lastPage) { recordPages.current.clear(); setPage(lastPage); return; }
|
||
recordPages.current.set(requestKey, value);
|
||
if (recordPages.current.size > 8) recordPages.current.delete(recordPages.current.keys().next().value!);
|
||
setResponse({ key: requestKey, data: value });
|
||
const pageFields = value.rows.flatMap(record => Object.keys(record.raw || {}).filter(key => !isSystemVersionField(key)));
|
||
if (pageFields.length) setRawFields(existing => [...new Set([...existing, ...pageFields])]);
|
||
})
|
||
.catch(errorValue => {
|
||
if (controller.signal.aborted) return;
|
||
if (!onUnauthorized(errorValue)) setFailure({ key: requestKey, message: chooseError(errorValue) });
|
||
}).finally(() => { if (!controller.signal.aborted) setLoading(false); });
|
||
return () => controller.abort();
|
||
}, [open, active, requestKey, revision, onUnauthorized]);
|
||
|
||
const visibleRawFields = selectedColumns ?? rawFields.slice(0, 8);
|
||
const exportRecords = async () => {
|
||
const params: RecordExportParams = {
|
||
year: recordQuery.year,
|
||
...(recordQuery.extraFilters ? { extraFilters: recordQuery.extraFilters } : {}),
|
||
...(recordQuery.columnFilters ? { columnFilters: recordQuery.columnFilters } : {}),
|
||
...(lockedStage ? { stage } : {}),
|
||
...(recordQuery.month !== undefined ? { month: recordQuery.month } : {}),
|
||
...(recordQuery.quarter !== undefined ? { quarter: recordQuery.quarter } : {}),
|
||
...(recordQuery.monthStart !== undefined ? { monthStart: recordQuery.monthStart } : {}),
|
||
...(recordQuery.monthEnd !== undefined ? { monthEnd: recordQuery.monthEnd } : {}),
|
||
...(recordQuery.department !== undefined ? { department: recordQuery.department } : {}),
|
||
...(recordQuery.group !== undefined ? { group: recordQuery.group } : {}),
|
||
...(recordQuery.product !== undefined ? { product: recordQuery.product } : {}),
|
||
...(recordQuery.productSearch !== undefined ? { productSearch: recordQuery.productSearch } : {}),
|
||
...(recordQuery.projectGroup !== undefined ? { projectGroup: recordQuery.projectGroup } : {}),
|
||
...(recordQuery.includeUnassigned !== undefined ? { includeUnassigned: recordQuery.includeUnassigned } : {}),
|
||
...(recordQuery.releaseId !== undefined ? { releaseId: recordQuery.releaseId } : {}),
|
||
};
|
||
const controller = new AbortController();
|
||
exportController.current?.abort(); exportController.current = controller;
|
||
setExporting(true);
|
||
try {
|
||
const { blob, filename } = await api.exportRecords(params, controller.signal);
|
||
if (controller.signal.aborted) return;
|
||
const url = URL.createObjectURL(blob);
|
||
const link = document.createElement('a');
|
||
link.href = url;
|
||
link.download = filename;
|
||
document.body.appendChild(link);
|
||
link.click();
|
||
link.remove();
|
||
window.setTimeout(() => URL.revokeObjectURL(url), 1000);
|
||
message.success(lockedStage ? '当前阶段明细 Excel 已开始下载' : '明细 Excel 已开始下载,含黑片和亮片两个工作表');
|
||
} catch (errorValue) {
|
||
if (!controller.signal.aborted && !onUnauthorized(errorValue)) message.error(chooseError(errorValue));
|
||
} finally {
|
||
if (!controller.signal.aborted) setExporting(false);
|
||
}
|
||
};
|
||
const fixedColumns: ColumnsType<RecordRow> = [
|
||
{ title: '来源文件', dataIndex: 'sourceFile', key: 'sourceFile', fixed: 'left', width: 220, ellipsis: true },
|
||
{ title: '原始行数据', key: 'rawRecord', fixed: 'left', width: 200, render: (_: unknown, record: RecordRow) => {
|
||
const raw = withoutSystemVersionFields(record.raw || {}) as Record<string, unknown>;
|
||
const fieldCount = Object.keys(raw).length;
|
||
return <details className="source-fields source-raw-fields">
|
||
<summary>查看全部原始字段({fieldCount})</summary>
|
||
<p>以下为该来源行导入时保存的字段值,按当前字段授权筛选。</p>
|
||
<BusinessValue value={raw} />
|
||
</details>;
|
||
} },
|
||
...(retainedResult?.rows.some(record=>Object.hasOwn(record,'salesOrderType'))?[{title:'销售订单类型',dataIndex:'salesOrderType',key:'salesOrderType',width:170,render:(value:string|null)=>value||'未匹配'}]:[]),
|
||
{ title: '工作表', dataIndex: 'sheet', key: 'sheet', width: 120 },
|
||
{ title: '行号', dataIndex: 'rowNumber', key: 'rowNumber', align: 'right', width: 85 },
|
||
{ title: '月份', dataIndex: 'month', key: 'month', align: 'center', width: 100, render: value => {
|
||
const month = monthNumber(value);
|
||
return month ? MONTHS[month - 1] : String(value || '—');
|
||
} },
|
||
{ title: '产业部', dataIndex: 'department', key: 'department', width: 160 },
|
||
{ title: '业务分组', dataIndex: 'group', key: 'group', width: 190 },
|
||
{ title: '产品', dataIndex: 'product', key: 'product', width: 190 },
|
||
...visibleRawFields.map(name => ({ title: name, key: `raw:${name}`, dataIndex: ['raw', name], width: 180, ellipsis: true, render: (_: unknown, record: RecordRow) => String(record.raw?.[name] ?? '—') })),
|
||
{ title: '规范化值与转换说明', key: 'transform', width: 260, render: (_: unknown, record: RecordRow) => <details className="source-fields"><summary>查看本行转换</summary><strong>规范化值</strong><BusinessValue value={withoutSystemVersionFields(record.normalized || {})} /><strong>转换说明</strong><ul>{(record.transformNotes || []).map((note, index) => <li key={index}>{typeof note === 'string' ? note : <BusinessValue value={withoutSystemVersionFields(note)} />}</li>)}</ul></details> },
|
||
{ title: '计算分量', dataIndex: 'components', key: 'components', width: 270, render: value => <details className="source-fields"><summary>查看计算分量</summary><BusinessValue value={withoutSystemVersionFields(value)} /></details> },
|
||
];
|
||
|
||
return <Drawer className="source-records-drawer" open={open} onClose={onClose} width={Math.min(1120, window.innerWidth)} title={<div className="drawer-title">来源明细 <small>{row?.label || (month ? MONTHS[month - 1] : '当前筛选条件')}</small></div>} destroyOnClose>
|
||
<div className="drawer-controls"><Segmented disabled={lockedStage} value={stage} options={[{ label: '黑片', value: 'black' }, { label: '亮片', value: 'bright' }]} onChange={value => { onStage(value as Stage); setPage(1); setRawFields([]); setField(undefined); setFieldSearch(''); setSelectedColumns(undefined); setSort(undefined); }} aria-label="明细阶段" /><span>{result ? `共 ${result.total} 条来源记录 · 已载入 ${rawFields.length} 个原始字段` : '按当前查询条件获取原始来源行'}</span><Button size="small" icon={<DownloadOutlined />} loading={exporting} disabled={fetching || !result || !!error} onClick={exportRecords} title={lockedStage ? '导出当前阶段和筛选范围的全部来源明细' : '导出当前查询范围全部来源明细,含黑片和亮片两个工作表'}>导出明细 Excel</Button></div>
|
||
<div className="record-query-tools">
|
||
<div role="group"><span>字段检索</span><Select aria-label="字段检索" {...readableSelectPopup} allowClear showSearch optionFilterProp="label" placeholder="选择原始字段" value={field} options={rawFields.map(name => ({ label: name, value: name }))} onChange={value => { setField(value); setPage(1); }} /></div>
|
||
<Input allowClear disabled={!field} prefix={<SearchOutlined />} placeholder={field ? `搜索字段:${field}` : '先选择检索字段'} value={fieldSearch} onChange={event => { setFieldSearch(event.target.value); setPage(1); }} />
|
||
<div role="group"><span>显示列</span><Select aria-label="显示列" {...readableSelectPopup} mode="multiple" allowClear showSearch optionFilterProp="label" placeholder="默认显示前 8 个字段" value={selectedColumns} options={rawFields.map(name => ({ label: name, value: name }))} onChange={value => { setSelectedColumns(value); setPage(1); }} /></div>
|
||
<div role="group"><span>排序字段</span><Select aria-label="排序字段" {...readableSelectPopup} allowClear showSearch optionFilterProp="label" placeholder="默认顺序" value={sort} options={[
|
||
{ label: '月份', value: 'month' }, { label: '来源文件', value: 'sourceFile' }, { label: '工作表', value: 'sheet' }, { label: '行号', value: 'rowNumber' },
|
||
{ label: '产业部', value: 'department' }, { label: '业务分组', value: 'group' }, { label: '项目组', value: 'projectGroup' }, { label: '产品', value: 'product' },
|
||
...(field ? [{ label: `原始字段:${field}`, value: 'rawField' }] : []),
|
||
]} onChange={value => { setSort(value); setPage(1); }} /></div>
|
||
<Segmented value={direction} options={[{ label: '升序', value: 'asc' }, { label: '降序', value: 'desc' }]} onChange={value => { setDirection(value as 'asc' | 'desc'); setPage(1); }} aria-label="排序方向" />
|
||
</div>
|
||
{error && <Alert type="error" showIcon message={retainedResult ? "更新失败,当前显示上次结果" : "来源明细加载失败"} description={error} action={<Button size="small" onClick={() => setRevision(value => value + 1)}>重试</Button>} />}
|
||
{showRecordLoading && <div role="status">{retainedResult ? '正在更新,当前显示上次来源结果' : <><Spin size="small" />正在读取来源行…</>}</div>}
|
||
<div aria-busy={fetching} inert={!result || !!error}>
|
||
{retainedResult?.rows.length ? <Table size="small" bordered columns={fixedColumns} dataSource={retainedResult.rows} rowKey="id" pagination={false} scroll={{ x: 1800 + visibleRawFields.length * 180 }} /> : !fetching && !error && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前条件没有来源记录" />}
|
||
</div>
|
||
{result && result.total > result.pageSize && <Pagination className="records-pagination" current={page} pageSize={result.pageSize} total={result.total} showTotal={total => `共 ${total} 条`} onChange={next => setPage(next)} />}
|
||
</Drawer>;
|
||
}
|
||
|
||
export { fullYearTrend };
|