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 = { overall: 'overall', department: 'department', group: 'group', product: 'product' }; const SCOPE_NAMES: Record = { 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) .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(); 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 { 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; 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)[viewOverride] : SCOPE_NAMES[page] || '总体'; const [options, setOptions] = useState(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(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(() => decodeQueryValueList(initialQuery.department)); const [group, setGroup] = useState(() => decodeQueryValueList(initialQuery.group)); const [product, setProduct] = useState(() => decodeQueryValueList(initialQuery.product)); const [projectGroup, setProjectGroup] = useState(() => decodeQueryValueList(initialQuery.projectGroup)); const [extraFilters, setExtraFilters] = useState>(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(null); const [dataKey, setDataKey] = useState(''); const [trendData, setTrendData] = useState([]); const [trendDataKey, setTrendDataKey] = useState(''); const [trendFailure, setTrendFailure] = useState<{ key: string; message: string } | null>(null); const [trendTarget, setTrendTarget] = useState(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('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(null); const [recordsOpen, setRecordsOpen] = useState(false); const [recordStage, setRecordStage] = useState('black'); const [recordMonth, setRecordMonth] = useState(); const [recordQuerySnapshot, setRecordQuerySnapshot] = useState(null); const [basisOpen, setBasisOpen] = useState(false); const trendAnchorTop = useRef(null); const summaryExport = useRef<{ exportExcel: () => Promise }>(null); const [summaryExporting, setSummaryExporting] = useState(false); const trendSection = useRef(null); const defectsSection = useRef(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, trendGranularity: 'month' }), [queryParams]); const metricKey = useMemo(() => JSON.stringify(metricParams), [metricParams]); 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(() => { 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(() => applyTrendObject(queryParams, trendObject, view), [queryKey, trendObject, view]); const defectQueryKey = JSON.stringify(defectQueryParams); const trendKey = JSON.stringify(trendParams); 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 || optionsLoading || optionsError) return; const controller = new AbortController(); setLoading(true); setError(''); setErrorKey(''); api.metrics(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, optionsLoading, optionsError]); 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, 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 || optionsLoading || optionsError) return; setTrendFailure(null); 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, optionsLoading, optionsError]); useEffect(() => { if (!active || optionsLoading || optionsError) 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 : {}; 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, optionsLoading, optionsError]); 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(); 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) => (
{label} { automaticPeriod.current = false; setYear(value); }} loading={optionsLoading} />
{period === 'month' &&
月份 ({ label: `第${value}季度`, value }))} onChange={value => { automaticPeriod.current = false; setQuarter(value); }} />
} {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)}
{queryBusy || summaryBusy ? '正在查询' : currentMetricsError || summaryMetricsError ? '查询失败' : '查询完成'}
{organizationSummary.length > 0 &&
组织路径 {organizationSummary.map((label, index) => {index > 0 && ›}{label})}
} {currentMetricsError && } onClick={() => setQueryRevision(value => value + 1)}>重试} />} {drilledProduct && summaryMetricsError && setQueryRevision(value => value + 1)}>重试} />}
setRateBasis(value as typeof rateBasis)} aria-label="合格率口径" />
setBasisOpen(true)} /> openRecords(null, 'black')} /> openRecords(null, 'bright')} /> openRecords(null, 'black')} />
{['department', 'group', 'product'].includes(page) && <> {options?.projectGroupStatus === 'UNCONFIGURED' && } } <>
setTrendStage(value as Stage)} aria-label="趋势阶段" />}> {currentTrendError && setTrendRevision(value => value + 1)}>重试} />}
{trendMode === 'data' ? : } {showTrendLoading && {retainedTrend ? `正在更新 · 当前显示上次筛选的${loadedQueryScope(retainedTrend.query, decodeQueryValueList)}` : '正在读取趋势'}}
} 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)) && } {drilledProduct && }} 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} 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'); } }} />
{defectsRefreshing && 正在更新}
{trendObjectMetricsError && }
{(['black', 'bright'] as const).map(stage => { const items = stage === 'black' ? blackDefectItems : brightDefectItems; return

{stage === 'black' ? '黑片' : '亮片'}

{items.length ? item.weight ?? 0))} onDetail={() => openRecords(null, stage, undefined, defectQueryParams, activeDefectData)} /> : !defectsRefreshing && }
; })}
{displayedDefectData ? item.name === '外废')?.weight} onUnauthorized={onUnauthorized} /> : !defectsRefreshing &&
不良数据暂不可用
}
setBasisOpen(false)} footer={} width={680}>
当前综合合格率{rateText(visibleCompositeRate(rowForSummary, rateBasis))}黑片 {rateText(visibleStageRate(rowForSummary, 'black'))} · 亮片 {rateText(visibleStageRate(rowForSummary, 'bright', rateBasis))}

以下为当前查询实际使用的公式、适用条件与空值处理规则。月、季、年先汇总计算分量,再按生效公式计算。

综合公式
{formulaText(compositeFormula)}
黑片公式
{formulaText(formulaDescriptions.blackRate)}
{rateBasis === 'original' ? '亮片公式' : '亮片调整公式'}
{formulaText(brightFormula)}
统计范围
{year}年{period === 'month' ? ` ${MONTHS[month - 1]}` : period === 'quarter' ? ` 第${quarter}季度` : '度'} · {drilledProduct || scopeName}
总重量
黑片 {numberText(rowForSummary?.black?.totalWeight)} kg · 亮片 {numberText(rowForSummary?.bright?.totalWeight)} kg
覆盖行数
黑片 {rowForSummary?.coverage.blackRows ?? '—'} · 亮片 {rowForSummary?.coverage.brightRows ?? '—'}
来源行覆盖
原始 {summaryMetricsData?.coverage.rawRows ?? '—'} · 参与 {summaryMetricsData?.coverage.includedRows ?? '—'} · 未分类行 (已计入) {summaryMetricsData?.coverage.excludedBlankRows ?? '—'}
业务分类映射
未映射 {summaryMetricsData?.coverage.unmappedRows ?? '—'} 行
项目组维度
{summaryMetricsData?.coverage.projectGroupUnconfiguredRows ?? '—'} 行未配置项目组归属。该计数不等于排除行数;是否参与指标由当前筛选及规则决定。
{recordQuerySnapshot && { setSelectedRecord(null); setRecordMonth(undefined); setRecordsOpen(false); }} query={recordQuerySnapshot} month={recordMonth} onUnauthorized={onUnauthorized} />} ); } 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 ; } export function DefectBreakdown({ items, stage, totalWeight, onDetail }: { items: DefectMetric[]; stage: Stage; totalWeight?: number | null; maximum: number; onDetail: () => void }) { return ; } 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(null); const chart = useRef | 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) 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, 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 `${escapeTooltipText(item.label)}
分类:${escapeTooltipText(item.category)}
报废重量:${numberText(item.weight)} kg
综合占比:${share.toFixed(2)}%
累计占比:${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
{onlyStage ? `${onlyStage === 'black' ? '黑片' : '亮片'}报废重量柏拉图` : '黑片与亮片综合报废重量柏拉图'}{showLoading && 正在更新}
{error && } {!loading && !releaseId && } {!loading && !error && responses && !items.length && }
; } export function SectionHeading({ title, subtitle }: { title: string; subtitle?: string }) { return

{title}

{subtitle && {subtitle}}
; } 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) => {label}黑片总重量为合格率计算使用的适用总重量。
按来源逐行计算:合格重量+报废重量-利用料及废品库对应的合格重量、报废重量;发料地点包含“利用料”或“废品”时扣减。
检验备注包含“过账”时,外废不计入报废重量;月、季、年均先汇总来源分量。具体取值以已发布数据版本及生效规则为准。}>
; const rateBasisTitle = (label: string, basis: QueryRateBasis, kind: 'bright' | 'composite', onBasis?: () => void) => {onBasis ? : label}{basis !== 'original' && (去本部报废)}{basis !== 'original' && {kind === 'composite' && <>综合合格率=黑片合格率×亮片合格率。
}原口径:亮片合格重量÷亮片总重量。
去本部报废:(亮片合格重量+本部报废)÷亮片总重量,同时从亮片报废重量中扣除本部报废,总重量不变。
当前:去本部报废。计算结果以已发布数据版本及生效规则为准。}>
}
; 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 }>; 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) => , }); 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 ; }, })); const fieldLabels: Record = { totalWeight: '总重量', qualifiedWeight: '合格重量', scrapWeight: '报废重量', headquartersScrapWeight: '本部报废', rate: '合格率', }; const stageColumns = (stage: Stage): ColumnsType => { const base: ColumnsType = 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) => } : 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 = [ { 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) => {view === 'department' || view === 'group' || view === 'product' ? : {title(row)}}{view === 'group' && row.department && {row.department}} }, { key: 'stage-black', title: 黑片, children: stageColumns('black') }, { key: 'stage-bright', title: 亮片, 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) => }, { title: '操作', key: 'actions', fixed: compact ? undefined : 'right', width: 96, align: 'center', render: (_: unknown, row) => (row as TrendMetricRow).noData ? — : }, ]; 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[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
size="small" bordered tableLayout="fixed" columns={displayColumns} dataSource={pageRows} pagination={false} scroll={scroll} rowKey="key" locale={{ emptyText }} /> {pageSizeOverride == null && { setPageSize(nextPageSize); setCurrentPage(nextPageSize === pageSize ? nextPage : 1); }} />}
; } 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
`显示 ${range[0]}–${range[1]} 行,共 ${count.toLocaleString('zh-CN')} 行`} onChange={onChange} />
; } 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(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 | 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()); const previousSelection = useRef(undefined); const selectionReady = useRef(false); const [lineSelectedPeriod, setLineSelectedPeriod] = useState(undefined); const [barMasks, setBarMasks] = useState>([]); 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('
'); }; 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
{!rows.length && }
; } 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 = { totalWeight: '总重量', qualifiedWeight: '合格重量', scrapWeight: '报废重量', headquartersScrapWeight: '本部报废', rate: '合格率', }; const stageColumns = (stage: Stage): ColumnsType => 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 = [ { title: '统计期间', dataIndex: 'month', key: 'month', align: 'center', fixed: 'left', width: 130, render: (_: unknown, row) => }, ...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 ?
String(row.month)} pagination={false} scroll={{ x: visibleColumns.reduce((total, column) => total + Number(column.width || 0), 0) }} /> : ; } 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()); 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(); const [fieldSearch, setFieldSearch] = useState(''); const [sort, setSort] = useState(); const [direction, setDirection] = useState<'asc' | 'desc'>('asc'); const [selectedColumns, setSelectedColumns] = useState(); const [rawFields, setRawFields] = useState([]); const [exporting, setExporting] = useState(false); const [revision, setRevision] = useState(0); const exportController = useRef(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 = [ { 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; const fieldCount = Object.keys(raw).length; return
查看全部原始字段({fieldCount})

以下为该来源行导入时保存的字段值,按当前字段授权筛选。

; } }, ...(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) =>
查看本行转换规范化值转换说明
    {(record.transformNotes || []).map((note, index) =>
  • {typeof note === 'string' ? note : }
  • )}
}, { title: '计算分量', dataIndex: 'components', key: 'components', width: 270, render: value =>
查看计算分量
}, ]; return 来源明细 {row?.label || (month ? MONTHS[month - 1] : '当前筛选条件')}} destroyOnClose>
{ onStage(value as Stage); setPage(1); setRawFields([]); setField(undefined); setFieldSearch(''); setSelectedColumns(undefined); setSort(undefined); }} aria-label="明细阶段" />{result ? `共 ${result.total} 条来源记录 · 已载入 ${rawFields.length} 个原始字段` : '按当前查询条件获取原始来源行'}
字段检索} placeholder={field ? `搜索字段:${field}` : '先选择检索字段'} value={fieldSearch} onChange={event => { setFieldSearch(event.target.value); setPage(1); }} />
显示列 { setSort(value); setPage(1); }} />
{ setDirection(value as 'asc' | 'desc'); setPage(1); }} aria-label="排序方向" />
{error && setRevision(value => value + 1)}>重试} />} {showRecordLoading &&
{retainedResult ? '正在更新,当前显示上次来源结果' : <>正在读取来源行…}
}
{retainedResult?.rows.length ?
: !fetching && !error && } {result && result.total > result.pageSize && `共 ${total} 条`} onChange={next => setPage(next)} />} ; } export { fullYearTrend };