完善:质量分析平台查询与分析功能

This commit is contained in:
2026-10-22 21:45:29 +08:00
parent 1e8a655adc
commit 5fbeb52b93
54 changed files with 2331 additions and 564 deletions
+136 -90
View File
@@ -1,7 +1,7 @@
import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from 'react';
import * as echarts from 'echarts/core';
import { BarChart, LineChart } from 'echarts/charts';
import { GridComponent, LegendComponent, MarkLineComponent, TooltipComponent } from 'echarts/components';
import { GraphicComponent, GridComponent, LegendComponent, MarkLineComponent, TooltipComponent } from 'echarts/components';
import { SVGRenderer } from 'echarts/renderers';
import {
Alert,
@@ -42,14 +42,17 @@ import { M01Insights } from './AnalyticsCompletion';
import { readableSelectPopup } from './readableSelectPopup';
import { isInternalDataField } from './publicDataDisplay';
import { previousCompleteMonth, previousCompleteQuarter } from './periodDefaults';
import { defectWeightRate } from './trendMetrics';
import './query-motion.css';
import { ExtraQueryFilters } from './ExtraQueryFilters';
echarts.use([BarChart, LineChart, GridComponent, LegendComponent, MarkLineComponent, TooltipComponent, SVGRenderer]);
echarts.use([BarChart, LineChart, GraphicComponent, GridComponent, LegendComponent, MarkLineComponent, TooltipComponent, SVGRenderer]);
const MONTHS = Array.from({ length: 12 }, (_, index) => `${String(index + 1).padStart(2, '0')}月`);
const TABLE_PAGE_SIZE = 20;
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(['美洲产业部', '欧洲产业部', '欧洲磁钢']);
@@ -110,7 +113,7 @@ function visibleStageRate(row: MetricRow | undefined, stage: Stage, rateBasis: '
}
function visibleCompositeRate(row: MetricRow | undefined, rateBasis: 'original' | 'withoutHeadquartersScrap' = 'original'): number | null {
if (!(hasStageRows(row, 'black') && hasStageRows(row, 'bright'))) return 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;
@@ -221,18 +224,22 @@ function toApiParams(args: {
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,
@@ -240,6 +247,19 @@ function toApiParams(args: {
};
}
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;
@@ -249,7 +269,10 @@ export default function QueryPage({ page, onUnauthorized }: {
const { message } = App.useApp();
const baseView = SCOPE[page] || 'overall';
const initialQuery = queryFromLocation();
const [viewOverride, setViewOverride] = useState<ViewKind | undefined>(() => initialQuery.view && initialQuery.view !== baseView ? initialQuery.view : undefined);
const [viewOverrideState, setViewOverrideState] = useState<{ page: PageKey; view: ViewKind } | undefined>(() => initialQuery.view && initialQuery.view !== baseView ? { page, view: initialQuery.view } : undefined);
const routeViewOverride = initialQuery.view && initialQuery.view !== baseView ? initialQuery.view : undefined;
const viewOverride = routeViewOverride || (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);
@@ -265,15 +288,18 @@ export default function QueryPage({ page, onUnauthorized }: {
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, setIncludeUnassigned] = useState(initialQuery.includeUnassigned === true);
const [trendGranularity, setTrendGranularity] = useState<'month' | 'quarter' | 'year'>(initialQuery.trendGranularity || (initialQuery.quarter ? 'quarter' : 'month'));
const [search, setSearch] = useState('');
const [appliedSearch, setAppliedSearch] = useState('');
const [fullFields, setFullFields] = useState(false);
const [data, setData] = useState<MetricsResponse | null>(null);
const [dataKey, setDataKey] = useState('');
const [trendData, setTrendData] = useState<TrendMetricRow[]>([]);
const [trendDataKey, setTrendDataKey] = useState('');
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);
@@ -285,6 +311,7 @@ export default function QueryPage({ page, onUnauthorized }: {
const [loading, setLoading] = useState(false);
const [trendLoading, setTrendLoading] = useState(false);
const [error, setError] = useState('');
const [errorKey, setErrorKey] = useState('');
const [queryRevision, setQueryRevision] = useState(0);
const [selectedRecord, setSelectedRecord] = useState<MetricRow | null>(null);
const [recordsOpen, setRecordsOpen] = useState(false);
@@ -293,18 +320,19 @@ export default function QueryPage({ page, onUnauthorized }: {
const [basisOpen, setBasisOpen] = useState(false);
const trendAnchorTop = useRef<number | null>(null);
useEffect(() => {
const timer = window.setTimeout(() => setAppliedSearch(search), 300);
return () => window.clearTimeout(timer);
}, [search]);
useEffect(() => {
setTrendObject('');
setDrilledProduct('');
setSearch('');
setViewOverride(undefined);
if (!new URLSearchParams(window.location.search).has('context')) {
const previous = previousCompleteMonth();
setPeriod(page === 'overall' ? 'year' : 'month');
setYear(page === 'overall' ? new Date().getFullYear() : previous.year);
setMonth(previous.month);
setTrendGranularity('month');
}
setAppliedSearch('');
setViewOverrideState(undefined);
setRecordsOpen(false);
setSelectedRecord(null);
}, [page]);
useEffect(() => {
@@ -341,38 +369,38 @@ export default function QueryPage({ page, onUnauthorized }: {
if (next.length !== group.length) { setGroup(next); setProduct([]); }
}, [options, department, group, allowedGroupSet]);
const queryParams = useMemo(() => toApiParams({ year, period, month, quarter, department, group, product, projectGroup, view, includeUnassigned, trendGranularity }), [year, period, month, quarter, department, group, product, projectGroup, view, includeUnassigned, trendGranularity]);
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 }), [year, period, month, quarter, department, group, productFilterForQuery, appliedSearch, projectGroup, extraFilters, view, includeUnassigned, trendGranularity]);
const queryKey = useMemo(() => JSON.stringify(queryParams), [queryParams]);
const drilldownContextKey = JSON.stringify({ view, year, department, group, product, projectGroup, includeUnassigned });
const drilldownContextKey = JSON.stringify({ view, year, department, group, product, projectGroup, extraFilters, includeUnassigned });
useEffect(() => {
setDrilledProduct('');
}, [drilldownContextKey]);
const metricParams = useMemo<QueryParams>(() => ({ ...queryParams, trendGranularity: 'month' }), [queryParams]);
const metricKey = useMemo(() => JSON.stringify(metricParams), [metricParams]);
const currentMetricsData = dataKey === metricKey ? data : null;
const currentMetricsError = errorKey === metricKey ? error : '';
const queryPending = !currentMetricsData && !currentMetricsError;
const queryBusy = loading || queryPending;
const metricKeyRef = useRef(metricKey);
metricKeyRef.current = metricKey;
const useSummaryTrend = period === 'year' && !trendObject && trendGranularity === 'month';
const trendParams = useMemo<QueryParams>(() => {
const params: QueryParams = { ...queryParams };
const params = applyTrendObject(queryParams, trendObject, view);
delete params.month;
delete params.quarter;
if (trendGranularity === 'year') Reflect.deleteProperty(params, 'year');
if (trendObject) {
if (view === 'department') params.department = trendObject;
if (view === 'group') params.group = trendObject;
if (view === 'product') params.product = trendObject;
if (view === 'projectGroup') params.projectGroup = trendObject;
}
return params;
}, [queryKey, trendObject, trendGranularity, view]);
const defectQueryParams = useMemo<QueryParams>(() => {
const params: QueryParams = { ...queryParams };
if (trendObject) {
if (view === 'department') params.department = trendObject;
if (view === 'group') params.group = trendObject;
if (view === 'product') params.product = trendObject;
if (view === 'projectGroup') params.projectGroup = trendObject;
}
return params;
}, [queryKey, trendObject, view]);
const defectQueryParams = useMemo<QueryParams>(() => applyTrendObject(queryParams, trendObject, view), [queryKey, trendObject, view]);
const defectQueryKey = JSON.stringify(defectQueryParams);
const trendKey = JSON.stringify(trendParams);
const trendKeyRef = useRef(trendKey);
@@ -393,7 +421,9 @@ export default function QueryPage({ page, onUnauthorized }: {
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);
if (useSummaryTrend && trendKeyRef.current === trendKey) {
@@ -401,10 +431,12 @@ export default function QueryPage({ page, onUnauthorized }: {
setTrendDataKey(trendKey);
}
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();
}, [metricKey, queryRevision, onUnauthorized]);
@@ -451,20 +483,26 @@ export default function QueryPage({ page, onUnauthorized }: {
useEffect(() => {
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);
if (!onUnauthorized(errorValue)) {
setTrendTarget(null);
setTrendTargetKey(trendKey);
}
});
return () => { alive = false; };
}, [trendKey, onUnauthorized]);
const visibleTrendData = useMemo(() => fullYearTrend(trendData, year, trendGranularity), [trendData, year, trendGranularity]);
const currentTrendTarget = trendTargetKey === trendKey ? trendTarget : null;
const visibleTrendData = useMemo(() => fullYearTrend(trendDataKey === trendKey ? trendData : [], year, trendGranularity), [trendData, trendDataKey, trendKey, year, trendGranularity]);
const drilledTrendData = useMemo(
() => trendDataKey === trendKey ? visibleTrendData : fullYearTrend([], year, 'month'),
[trendDataKey, trendKey, visibleTrendData, year],
@@ -477,12 +515,12 @@ export default function QueryPage({ page, onUnauthorized }: {
const rawRows: MetricRow[] = page === 'overall' && period === 'year'
? (() => {
const byMonth = new Map<number, TrendMetricRow>();
for (const item of data?.trend || []) { const parsed = monthNumber(item.month); if (parsed) byMonth.set(parsed, item); }
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' && data
? data.rows.length ? data.rows : [data.summary]
: data?.rows || [];
: 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
@@ -497,10 +535,10 @@ export default function QueryPage({ page, onUnauthorized }: {
- (typeof aWeight === 'number' && Number.isFinite(aWeight) ? aWeight : -Infinity) || 0;
})
: scopedRows;
if (!search.trim()) return orderedRows;
const term = search.trim().toLocaleLowerCase();
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, data, search, year, view, department, allowedGroupSet]);
}, [page, period, currentMetricsData, appliedSearch, year, view, department, allowedGroupSet]);
const openRecords = useCallback((row: MetricRow | null, stage: Stage, selectedMonth?: number) => {
setSelectedRecord(row);
@@ -552,15 +590,16 @@ export default function QueryPage({ page, onUnauthorized }: {
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 className="query-field" key={label}>
<label className="query-field query-primary-field" key={label}>
<span>{label}</span>
<Select
maxTagCount="responsive"
mode="multiple"
allowClear
showSearch
optionFilterProp="label"
{...readableSelectPopup}
placeholder={`全部${label} · 可多选`}
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}
@@ -569,12 +608,11 @@ export default function QueryPage({ page, onUnauthorized }: {
</label>
);
const currentMetricsData = dataKey === metricKey ? data : null;
const activeDefectData = trendObject
? defectQueryKey === queryKey ? currentMetricsData : trendObjectMetrics?.key === defectQueryKey ? trendObjectMetrics.data : null
: currentMetricsData;
const rowForSummary = data?.summary;
const rawFormulaDescriptions = data?.context.metricFormulaDescriptions;
const rowForSummary = currentMetricsData?.summary;
const rawFormulaDescriptions = currentMetricsData?.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'];
@@ -644,17 +682,18 @@ export default function QueryPage({ page, onUnauthorized }: {
}}
aria-label="统计周期"
/>
<label className="query-field"><span>年份</span><Select aria-label="年份" value={year} options={years.length ? years : [{ label: `${year}年`, value: year }]} onChange={setYear} loading={optionsLoading} /></label>
{period === 'month' && <label className="query-field"><span>月份</span><Select aria-label="月份" value={month} options={MONTHS.map((label, index) => ({ label, value: index + 1 }))} onChange={setMonth} /></label>}
{period === 'quarter' && <label className="query-field"><span>季度</span><Select aria-label="季度" value={quarter} options={[1, 2, 3, 4].map(value => ({ label: `第${value}季度`, value }))} onChange={setQuarter} /></label>}
<label 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={setYear} loading={optionsLoading} /></label>
{period === 'month' && <label 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={setMonth} /></label>}
{period === 'quarter' && <label 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={setQuarter} /></label>}
{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)}
{options?.projectGroupStatus === 'READY' && filterSelect('项目组', projectGroup, options.projectGroups, setProjectGroup)}
<Checkbox checked={includeUnassigned} onChange={event => setIncludeUnassigned(event.target.checked)}>包含未分类行</Checkbox>
<ExtraQueryFilters projectGroup={projectGroup} projectGroups={options?.projectGroupStatus === 'READY' ? options.projectGroups : undefined} onProjectGroup={setProjectGroup} value={extraFilters} onChange={setExtraFilters} onUnauthorized={onUnauthorized} />
<Checkbox className="query-unassigned" checked={includeUnassigned} onChange={event => setIncludeUnassigned(event.target.checked)}>包含未分类行</Checkbox>
<div className="query-toolbar-tail">
<span className={`query-status ${loading ? 'busy' : error ? 'failed' : ''}`}><i />{loading ? '正在查询' : error ? '查询失败' : '查询完成'}</span>
<Button type="text" onClick={() => { const previous = previousCompleteMonth(); const previousQuarter = previousCompleteQuarter(); setDepartment([]); setGroup([]); setProduct([]); setProjectGroup([]); setIncludeUnassigned(false); setSearch(''); setTrendObject(''); setYear(page === 'overall' ? new Date().getFullYear() : previous.year); setMonth(previous.month); setQuarter(previousQuarter.quarter); setPeriod(page === 'overall' ? 'year' : 'month'); setTrendGranularity('month'); }}>重置</Button>
<span className={`query-status ${queryBusy ? 'busy' : currentMetricsError ? 'failed' : ''}`}><i />{queryBusy ? '正在查询' : currentMetricsError ? '查询失败' : '查询完成'}</span>
<Button type="text" onClick={() => { const previous = previousCompleteMonth(); const previousQuarter = previousCompleteQuarter(); setDepartment([]); setGroup([]); setProduct([]); setProjectGroup([]); setExtraFilters({}); setIncludeUnassigned(false); setSearch(''); setTrendObject(''); setYear(page === 'overall' ? new Date().getFullYear() : previous.year); setMonth(previous.month); setQuarter(previousQuarter.quarter); setPeriod(page === 'overall' ? 'year' : 'month'); setTrendGranularity('month'); }}>重置</Button>
</div>
{organizationSummary.length > 0 && <div className="organization-breadcrumb" aria-label="当前组织路径">
<span>组织路径</span><Button type="link" onClick={() => { setDepartment([]); setGroup([]); setProduct([]); }}>全部组织</Button>
@@ -662,10 +701,10 @@ export default function QueryPage({ page, onUnauthorized }: {
</div>}
</section>
{error && <Alert showIcon type="error" message="质量指标查询失败" description={error} action={<Button size="small" icon={<ReloadOutlined />} onClick={() => setQueryRevision(value => value + 1)}>重试</Button>} />}
{currentMetricsError && <Alert showIcon type="error" message="质量指标查询失败" description={currentMetricsError} action={<Button size="small" icon={<ReloadOutlined />} onClick={() => setQueryRevision(value => value + 1)}>重试</Button>} />}
<section className="metric-strip" aria-label="质量指标">
<div className="rate-basis-control"><span>亮片本部报废调整</span><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={rateBasis === 'original' ? '综合合格率' : '综合调整率'} value={rateText(visibleCompositeRate(rowForSummary, rateBasis))} note={visibleCompositeRate(rowForSummary, rateBasis) == null ? '需同时有黑片与亮片来源' : '按当前启用规则计算'} onClick={() => setBasisOpen(true)} />
<MetricCard primary label={rateBasis === 'original' ? '综合合格率' : '综合调整率'} value={rateText(visibleCompositeRate(rowForSummary, rateBasis))} onClick={() => setBasisOpen(true)} />
<MetricCard label="黑片合格率" value={rateText(visibleStageRate(rowForSummary, 'black'))} note={hasStageRows(rowForSummary, 'black') ? hasValidRateDenominator(rowForSummary, 'black') ? `合格重量 ${numberText(rowForSummary?.black?.qualifiedWeight)} kg` : '按当前启用规则及空值策略计算' : '缺少黑片来源'} stage="black" onClick={() => openRecords(null, 'black')} />
<MetricCard label={rateBasis === 'original' ? '亮片合格率' : '亮片调整率'} value={rateText(visibleStageRate(rowForSummary, 'bright', rateBasis))} note={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((rowForSummary.black.scrapWeight ?? 0) + (rowForSummary.bright.scrapWeight ?? 0))} kg` : '—'} note={hasStageRows(rowForSummary, 'black') || hasStageRows(rowForSummary, 'bright') ? `黑片 ${numberText(rowForSummary?.black?.scrapWeight)} kg · 亮片 ${numberText(rowForSummary?.bright?.scrapWeight)} kg` : '缺少阶段来源'} onClick={() => openRecords(null, 'black')} />
@@ -680,7 +719,7 @@ export default function QueryPage({ page, onUnauthorized }: {
<div className="section-heading-row">
<SectionHeading title={drilledProduct ? '产品月度质量数据' : page === 'overall' ? `${period === 'year' ? '年度月度' : period === 'quarter' ? '季度' : '月度'}汇总` : `${scopeName}质量汇总`} subtitle={drilledProduct ? `${year} 年 · ${drilledProduct} · 重量 / kg 合格率 / %` : '重量 / kg 合格率 / %'} />
<div className="table-tools">
<Input allowClear={!drilledProduct} disabled={Boolean(drilledProduct)} prefix={<SearchOutlined />} placeholder={`搜索${view === 'group' ? '业务分组' : view === 'product' ? '产品' : '汇总对象'}`} value={drilledProduct || search} onChange={event => setSynchronizedSearch(event.target.value)} aria-label="搜索汇总对象" />
<Input allowClear={!drilledProduct} disabled={Boolean(drilledProduct)} maxLength={view === 'product' ? 256 : undefined} prefix={<SearchOutlined />} placeholder={view === 'product' ? '输入关键词或完整产品名称' : `搜索${view === 'group' ? '业务分组' : '汇总对象'}`} value={drilledProduct || search} onChange={event => setSynchronizedSearch(event.target.value)} aria-label={view === 'product' ? '搜索产品名称并同步筛选指标和趋势' : '搜索汇总对象'} />
<Segmented value={fullFields ? 'full' : 'key'} options={[{ label: '关键指标', value: 'key' }, { label: '完整字段', value: 'full' }]} onChange={value => setFullFields(value === 'full')} aria-label="字段显示" />
<Tooltip title="点击综合合格率可查看计算依据"><Button type="text" icon={<InfoCircleOutlined />} aria-label="查看计算依据" onClick={() => setBasisOpen(true)} /></Tooltip>
{drilledProduct && <Button onClick={() => { setDrilledProduct(''); setTrendObject(''); setTrendMode('production'); }}>返回产品汇总</Button>}
@@ -702,7 +741,7 @@ export default function QueryPage({ page, onUnauthorized }: {
onBasis={() => setBasisOpen(true)}
onDrilldown={() => undefined}
/>
) : loading && !data ? <div className="loading-panel"><Spin />正在查询真实指标数据…</div> : visibleRows.length === 0 ? <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={error ? '查询失败,暂无可展示结果' : '当前条件下暂无数据'} /> : (
) : queryPending ? <div className="loading-panel query-metrics-loading"><Spin />正在查询真实指标数据…</div> : visibleRows.length === 0 ? <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={currentMetricsError ? '查询失败,暂无可展示结果' : '当前条件下暂无数据'} /> : (
<MetricTable
rows={visibleRows}
view={view}
@@ -728,7 +767,7 @@ export default function QueryPage({ page, onUnauthorized }: {
}}
/>
)}
<div className="table-footer"><span>{drilledProduct ? trendLoading && trendDataKey !== trendKey ? `${drilledProduct} · 正在查询月度数据` : `${drilledProduct} · 共 ${drilledTrendData.length} 个月` : page === 'overall' && period === 'year' ? `年度月份 12 行 · 已有数据 ${new Set((data?.trend || []).map(item => String(item.month))).size} 个月` : `共 ${visibleRows.length} 行`}</span></div>
<div className="table-footer"><span>{drilledProduct ? trendLoading && trendDataKey !== trendKey ? `${drilledProduct} · 正在查询月度数据` : `${drilledProduct} · 共 ${drilledTrendData.length} 个月` : page === 'overall' && period === 'year' ? `年度月份 12 行 · 已有数据 ${new Set((currentMetricsData?.trend || []).map(item => String(item.month))).size} 个月` : `共 ${visibleRows.length} 行`}</span></div>
</section>
<div className="analysis-stack">
@@ -746,8 +785,8 @@ export default function QueryPage({ page, onUnauthorized }: {
<div className="trend-chart-shell" aria-busy={trendLoading}>
{trendMode === 'data'
? <TrendTable rows={visibleTrendData} rateBasis={rateBasis} onMonth={selectTrendPeriod} />
: <TrendChart rows={visibleTrendData} mode={trendMode} stage={trendStage} rateBasis={rateBasis} targetRate={trendTarget} selectedPeriod={selectedTrendPeriod} onMonth={selectTrendPeriod} />}
{trendLoading && <span className="trend-refresh-indicator"><Spin size="small" />正在更新趋势</span>}
: <TrendChart rows={visibleTrendData} mode={trendMode} stage={trendStage} rateBasis={rateBasis} targetRate={currentTrendTarget} selectedPeriod={selectedTrendPeriod} onMonth={selectTrendPeriod} />}
{(trendLoading || (useSummaryTrend && queryBusy)) && <span className="trend-refresh-indicator"><Spin size="small" />正在更新趋势</span>}
</div>
<div className="chart-footnote"><span>全年期间均显示;无数据期间留空,指标由源分量重新汇总。</span><span>点击期间筛选,再次点击可取消</span></div>
</section>
@@ -771,12 +810,12 @@ export default function QueryPage({ page, onUnauthorized }: {
</section>;
})}
</div>
<DefectParetoPanel releaseId={data?.release?.id} query={defectQueryParams} externalScrapWeight={blackDefectItems.find(item => item.name === '外废')?.weight} onUnauthorized={onUnauthorized} />
<DefectParetoPanel key={defectQueryKey} releaseId={currentMetricsData?.release?.id} query={defectQueryParams} externalScrapWeight={blackDefectItems.find(item => item.name === '外废')?.weight} onUnauthorized={onUnauthorized} />
</section>
</div>
</>
<M01Insights query={queryParams} onUnauthorized={onUnauthorized} />
<M01Insights key={queryKey} query={queryParams} onUnauthorized={onUnauthorized} />
<div className="query-footer"><span>查询数据由服务端按当前数据返回</span><Button type="link" onClick={() => setBasisOpen(true)}>计算口径</Button></div>
@@ -810,12 +849,12 @@ export default function QueryPage({ page, onUnauthorized }: {
);
}
function MetricCard({ primary, label, value, note, stage, onClick }: { primary?: boolean; label: string; value: string; note: string; stage?: Stage; onClick: () => void }) {
function MetricCard({ primary, label, value, note, stage, onClick }: { primary?: boolean; label: string; value: string; note?: string; stage?: Stage; onClick: () => void }) {
const parts = value.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></> : value}</strong>
<small>{note}</small>
{note && <small>{note}</small>}
</button>;
}
@@ -827,7 +866,7 @@ function DefectBreakdown({ items, stage, totalWeight, maximum, onDetail }: { ite
<span className="defect-track"><i className={stage} style={{ width: `${maximum > 0 ? Math.max(0, (item.weight || 0) / maximum * 100) : 0}%` }} /></span>
<span className="defect-weight">{numberText(item.weight)}</span>
<span className="defect-rate">{rateText(item.rate)}</span>
<span className="defect-rate">{rateText(item.weight != null && totalWeight != null && totalWeight > 0 ? item.weight / totalWeight : null)}</span>
<span className="defect-rate">{rateText(defectWeightRate(item.weight, totalWeight))}</span>
</button>)}
</div>;
}
@@ -845,6 +884,8 @@ function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUnauthoriz
const [themeRevision, setThemeRevision] = useState(0);
const fineQuery = useMemo(() => ({
year: query.year,
...(query.productSearch ? { productSearch: query.productSearch } : {}),
...(query.extraFilters ? { extraFilters: query.extraFilters } : {}),
...(query.month != null ? { month: query.month } : {}),
...(query.quarter != null ? { quarter: query.quarter } : {}),
...(query.department ? { department: query.department } : {}),
@@ -852,7 +893,7 @@ function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUnauthoriz
...(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.projectGroup, query.includeUnassigned]);
}), [query.year, query.month, query.quarter, query.department, query.group, query.product, query.productSearch, query.projectGroup, query.extraFilters, query.includeUnassigned]);
const fineQueryKey = JSON.stringify(fineQuery);
useEffect(() => {
@@ -956,8 +997,8 @@ function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUnauthoriz
{ type: 'value', name: '累计占比', min: 0, max: 100, nameTextStyle: { color: ink, fontSize: 10 }, axisLabel: { color: ink, fontSize: 10, formatter: '{value}%' }, splitLine: { show: false } },
],
series: [
{ name: '报废重量', type: 'bar', barMaxWidth: 36, data: items.map(item => ({ value: item.weight, itemStyle: { color: item.kind === 'category' ? '#9aa4b2' : item.key.startsWith('black:') ? blue : teal } })) },
{ name: '累计占比', type: 'line', yAxisIndex: 1, symbol: 'circle', symbolSize: 5, lineStyle: { width: 2, color: '#d58c35' }, itemStyle: { color: '#d58c35', borderColor: surface, borderWidth: 1 }, data: cumulative },
{ name: '报废重量', type: 'bar', z: 1, barMaxWidth: 36, data: items.map(item => ({ value: item.weight, itemStyle: { color: item.kind === 'category' ? '#9aa4b2' : item.key.startsWith('black:') ? blue : teal } })) },
{ 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 },
],
};
instance.setOption(option, { notMerge: true, lazyUpdate: false });
@@ -1076,7 +1117,7 @@ function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedPeriod,
const rowsRef = useRef(rows);
const modeRef = useRef(mode);
const stageRef = useRef(stage);
const maskNodes = useRef(new Map<string, HTMLDivElement>());
const graphicIds = useRef(new Set<string>());
const previousSelection = useRef<string | undefined>(undefined);
const selectionReady = useRef(false);
const [lineSelectedPeriod, setLineSelectedPeriod] = useState<string | undefined>(undefined);
@@ -1118,6 +1159,7 @@ function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedPeriod,
if (!container.current || !hasRows) return;
const instance = echarts.init(container.current, undefined, { renderer: 'svg' });
chart.current = instance;
graphicIds.current.clear();
instance.on('click', params => {
if (params.componentType !== 'series' && params.componentType !== 'xAxis') return;
const currentRows = rowsRef.current;
@@ -1177,7 +1219,7 @@ function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedPeriod,
xAxis: { type: 'category', data: labels, triggerEvent: true, axisLine: { lineStyle: { color: line } }, axisLabel: { color: ink, margin: 12 }, axisTick: { show: false } },
};
let option: echarts.EChartsCoreOption;
const pointStyle = { symbol: 'circle', symbolSize: 5, showSymbol: true, emphasis: { focus: 'none' as const, scale: 1.35 }, connectNulls: false };
const pointStyle = { 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;
@@ -1198,8 +1240,8 @@ function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedPeriod,
{ type: 'value', name: '合格率 / %', nameGap: 18, min: minRate, max: maxRate, nameTextStyle: { color: ink, align: 'right', fontSize: 11 }, axisLabel: { color: ink, formatter: '{value}%', fontSize: 11 }, axisLine: { show: false }, axisTick: { show: false }, splitLine: { show: false } },
],
series: [
{ id: 'qualified-weight', name: `${stageName}合格重量`, type: 'bar', stack: 'weight', yAxisIndex: 0, barWidth, itemStyle: { color: barColor }, emphasis: { itemStyle: { color: blue } }, data: barData('qualifiedWeight') },
{ id: 'scrap-weight', name: `${stageName}报废重量`, type: 'bar', stack: 'weight', yAxisIndex: 0, barWidth, itemStyle: { color: '#edaa83' }, emphasis: { itemStyle: { color: '#e58e5d' } }, data: barData('scrapWeight') },
{ id: 'qualified-weight', name: `${stageName}合格重量`, type: 'bar', z: 1, stack: 'weight', yAxisIndex: 0, barWidth, itemStyle: { color: barColor }, emphasis: { itemStyle: { color: blue } }, data: barData('qualifiedWeight') },
{ id: 'scrap-weight', name: `${stageName}报废重量`, type: 'bar', z: 1, stack: 'weight', yAxisIndex: 0, barWidth, itemStyle: { color: '#edaa83' }, emphasis: { itemStyle: { color: '#e58e5d' } }, data: barData('scrapWeight') },
{ id: 'composite-rate', name: rateBasis === 'original' ? '综合合格率' : '综合调整率', type: 'line', yAxisIndex: 1, ...pointStyle, ...targetLine, lineStyle: { width: 2.5, color: blue }, itemStyle: { color: blue, borderColor: surface, borderWidth: 1.5 }, data: rows.map(row => rateNumber(visibleCompositeRate(row, rateBasis))) },
{ id: 'black-rate', name: '黑片合格率', type: 'line', yAxisIndex: 1, ...pointStyle, lineStyle: { width: 1.8, color: '#9278bf' }, itemStyle: { color: '#9278bf', borderColor: surface, borderWidth: 1 }, data: rows.map(row => rateNumber(visibleStageRate(row, 'black'))) },
{ id: 'bright-rate', name: rateBasis === 'original' ? '亮片合格率' : '亮片不含本部报废调整率', type: 'line', yAxisIndex: 1, ...pointStyle, lineStyle: { width: 1.8, color: teal }, itemStyle: { color: teal, borderColor: surface, borderWidth: 1 }, data: rows.map(row => rateNumber(visibleStageRate(row, 'bright', rateBasis))) },
@@ -1211,7 +1253,7 @@ function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedPeriod,
option = {
...base,
yAxis: [{ type: 'value', name: '不良率 / %', nameGap: 18, nameTextStyle: { color: ink, align: 'left', fontSize: 11 }, axisLabel: { color: ink, formatter: '{value}%', fontSize: 11 }, 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, ...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 defect?.rate == null ? null : defect.rate * 100; }) })),
series: names.map((name, index) => ({ id: `defect-${stage}-${name}`, name, type: 'line' as const, ...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)); }) })),
};
}
instance.setOption(option, { replaceMerge: ['series', 'yAxis'], lazyUpdate: false });
@@ -1225,34 +1267,36 @@ function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedPeriod,
}, [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;
for (const mask of barMasks) {
const node = maskNodes.current.get(mask.period);
if (!node) continue;
const wasDimmed = previous != null && mask.period !== previous;
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;
if (!changed && node.getAnimations().length) continue;
node.getAnimations().forEach(animation => animation.cancel());
const finalClip = dimmed ? 'inset(0 0 0 0)' : 'inset(0 0 100% 0)';
node.style.clipPath = finalClip;
if (animate && wasDimmed !== dimmed) {
node.animate([
{ clipPath: dimmed ? 'inset(0 0 100% 0)' : 'inset(0 0 0 0)' },
{ clipPath: finalClip },
], { duration: 340, easing: 'cubic-bezier(.22, .8, .25, 1)' });
}
}
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: .72 } },
{ 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]);
}, [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' ? '黑片' : '亮片'}不良率趋势`} />
{barMasks.map(mask => <div key={mask.period} className="chart-bar-wash" ref={node => { if (node) maskNodes.current.set(mask.period, node); else maskNodes.current.delete(mask.period); }} style={{ left: mask.left, top: mask.top, width: mask.width, height: mask.height }} />)}
{barMasks.map(mask => <div key={`focus-${mask.period}`} className={`chart-bar-focus ${dimmedPeriod === mask.period ? 'active' : ''}`} style={{ left: mask.left, top: mask.top, width: mask.width, height: mask.height }} />)}
</div>
{!rows.length && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前数据未返回趋势" />}
</div>;
@@ -1332,11 +1376,13 @@ function RecordsDrawer({
const exportRecords = async () => {
const params: RecordExportParams = {
year: recordQuery.year,
...(recordQuery.extraFilters ? { extraFilters: recordQuery.extraFilters } : {}),
...(recordQuery.month !== undefined ? { month: recordQuery.month } : {}),
...(recordQuery.quarter !== undefined ? { quarter: recordQuery.quarter } : {}),
...(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 } : {}),