feat: drill defect trends into detailed rates and preserve query context

This commit is contained in:
2026-11-13 13:37:32 +08:00
parent 48ae58e577
commit 63bf8c16d3
31 changed files with 1215 additions and 107 deletions
+75 -28
View File
@@ -33,6 +33,7 @@ import { ArrowLeftOutlined, DownloadOutlined, InfoCircleOutlined, ReloadOutlined
import { ApiError, api, decodeQueryValueList, encodeQueryValueList } from './api';
import type {
DefectMetric,
DefectDrilldownResponse,
FineDefectTopResponse,
MetricRow,
MetricsResponse,
@@ -59,6 +60,8 @@ 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]);
@@ -152,7 +155,7 @@ 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}/);
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;
@@ -298,7 +301,7 @@ export default function QueryPage({ page, onUnauthorized }: {
const automaticPeriod = useRef(page !== 'overall' && !initialQuery.year && !initialQuery.month && !initialQuery.quarter);
const defaultMonth = previousCompleteMonth();
const defaultQuarter = previousCompleteQuarter();
const [period, setPeriod] = useState<PeriodKind>(initialQuery.month ? 'month' : initialQuery.quarter ? 'quarter' : initialQuery.year || page === 'overall' ? 'year' : 'month');
const [period, setPeriod] = useState<PeriodKind>(initialQuery.month ? 'month' : initialQuery.quarter ? 'quarter' : 'year');
const [year, setYear] = useState(initialQuery.year || (period === 'month' ? defaultMonth.year : period === 'quarter' ? defaultQuarter.year : new Date().getFullYear()));
const [month, setMonth] = useState(initialQuery.month || defaultMonth.month);
const [quarter, setQuarter] = useState(initialQuery.quarter || defaultQuarter.quarter);
@@ -364,7 +367,7 @@ export default function QueryPage({ page, onUnauthorized }: {
setOptions(result);
if (automaticPeriod.current) {
const available = defaultQueryMonth(result);
setYear(available.year); setMonth(available.month);
setMonth(available.month);
automaticPeriod.current = false;
}
setOptionsError('');
@@ -405,7 +408,7 @@ export default function QueryPage({ page, onUnauthorized }: {
}, [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, year, department, group, product, projectGroup, extraFilters, includeUnassigned });
const drilldownContextKey = JSON.stringify({ view, department, group, product, projectGroup, extraFilters, includeUnassigned });
useEffect(() => {
setDrilledProduct('');
}, [drilldownContextKey]);
@@ -576,7 +579,7 @@ export default function QueryPage({ page, onUnauthorized }: {
view: drilledProduct ? 'overall' as const : view,
layoutView: drilledProduct ? 'product' as const : view,
period: drilledProduct ? 'year' as const : period,
year, month, quarter, drilledProduct, paginationScope: JSON.stringify({query:queryParams,drilledProduct,view}),
year, month, quarter, drilledProduct, granularity: trendGranularity, paginationScope: JSON.stringify({query:queryParams,drilledProduct,view}),
} : null);
const tableRows = retainedTable?.rows || [];
const tablePeriod = retainedTable?.period || period;
@@ -584,6 +587,14 @@ export default function QueryPage({ page, onUnauthorized }: {
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;
@@ -649,7 +660,8 @@ export default function QueryPage({ page, onUnauthorized }: {
const openRecords = useCallback((row: MetricRow | null, stage: Stage, selectedMonth?: number, sourceQuery?: QueryParams, sourceData?: MetricsResponse | null) => {
const source = sourceData === undefined ? summaryMetricsData : sourceData;
if (!source?.release?.id) { message.info('指标数据尚未就绪,请重新查询后打开来源明细。'); return; }
setRecordQuerySnapshot(freezeSourceRecordsQuery(sourceQuery || (drilledProduct ? defectQueryParams : queryParams), source.release.id, view, row, selectedMonth));
// Product drilldown rows represent months; the product is already bound in the query.
setRecordQuerySnapshot(freezeSourceRecordsQuery(sourceQuery || (drilledProduct ? defectQueryParams : queryParams), source.release.id, drilledProduct ? 'overall' : view, row, selectedMonth));
setSelectedRecord(row); setRecordStage(stage); setRecordMonth(selectedMonth); setRecordsOpen(true);
}, [summaryMetricsData, drilledProduct, defectQueryParams, queryParams, view, message]);
const summaryMetricsError = drilledProduct ? trendObjectMetricsError : currentMetricsError;
@@ -678,7 +690,7 @@ export default function QueryPage({ page, onUnauthorized }: {
const trendOptions = useMemo(() => {
const base = view === 'department' ? options?.departments?.filter(name => !RETIRED_DEPARTMENTS.has(name)) : view === 'group' ? allowedGroups : view === 'product'
? department.length || group.length ? organizationPathOptions.products : options?.products : [];
return (base || []).map(value => ({ label: value, value }));
return [...(base || []).map(value => ({ label: value, value })), ...(view === 'product' ? [{ label: '未分类', value: '__UNASSIGNED__' }] : [])];
}, [view, options, allowedGroups, department, group, organizationPathOptions]);
useEffect(() => {
if (options && trendObject && !trendOptions.some(item => item.value === trendObject)) {
@@ -738,7 +750,7 @@ export default function QueryPage({ page, onUnauthorized }: {
<ExtraQueryFilters key={queryRevision} releaseId={queryParams.releaseId} projectGroup={projectGroup} projectGroups={options?.projectGroupStatus === 'READY' ? options.projectGroups : undefined} onProjectGroup={setProjectGroup} value={extraFilters} onChange={setExtraFilters} onUnauthorized={onUnauthorized} />
<div className="query-toolbar-tail"><span className={`query-status ${queryBusy || summaryBusy ? 'busy' : currentMetricsError || summaryMetricsError ? 'failed' : ''}`}><i />{queryBusy || summaryBusy ? '正在查询' : currentMetricsError || summaryMetricsError ? '查询失败' : '查询完成'}</span>
<QuerySnapshotButton title={drilledProduct ? `${drilledProduct} · 产品质量查询` : page === 'overall' ? '总体合格率' : `${scopeName}质量查询`} queryKey={JSON.stringify([queryParams,trendMode,trendObject,trendStage,trendGranularity,rateBasis,fullFields,defectDisplay,queryRevision])} disabled={queryBusy || summaryBusy || !summaryMetricsData} onUnauthorized={onUnauthorized} />
<Button type="default" onClick={() => { automaticPeriod.current = false; const previous = defaultQueryMonth(options); const previousQuarter = previousCompleteQuarter(); setViewOverride(); setDrilledProduct(''); setDepartment([]); setGroup([]); setProduct([]); setProjectGroup([]); setExtraFilters({}); setSearch(''); setAppliedSearch(''); setTrendObject(''); setYear(page === 'overall' ? new Date().getFullYear() : previous.year); setMonth(previous.month); setQuarter(previousQuarter.quarter); setPeriod(page === 'overall' ? 'year' : 'month'); setTrendGranularity('month'); }}>重置</Button>
<Button type="default" onClick={() => { automaticPeriod.current = false; const previous = defaultQueryMonth(options); const previousQuarter = previousCompleteQuarter(); setViewOverride(); setDrilledProduct(''); setDepartment([]); setGroup([]); setProduct([]); setProjectGroup([]); setExtraFilters({}); setSearch(''); setAppliedSearch(''); setTrendObject(''); setYear(new Date().getFullYear()); setMonth(previous.month); setQuarter(previousQuarter.quarter); setPeriod('year'); setTrendGranularity('month'); }}>重置</Button>
</div>
{organizationSummary.length > 0 && <div className="organization-breadcrumb" aria-label="当前组织路径">
<span>组织路径</span><Button type="link" onClick={() => { setDepartment([]); setGroup([]); setProduct([]); }}>全部组织</Button>
@@ -769,22 +781,23 @@ export default function QueryPage({ page, onUnauthorized }: {
objects={trendOptions} scopeName={scopeName}
stageSwitch={<Segmented value={trendStage} options={[{ label: '亮片', value: 'bright' }, { label: '黑片', value: 'black' }]} onChange={value => setTrendStage(value as Stage)} aria-label="趋势阶段" />}>
{currentTrendError && <Alert type="warning" showIcon message={retainedTrend ? "趋势更新失败,当前显示上次结果" : "趋势读取失败"} description={retainedTrend ? `${currentTrendError};当前范围:${loadedQueryScope(retainedTrend.query, decodeQueryValueList)}` : currentTrendError} action={<Button onClick={() => setTrendRevision(value => value + 1)}>重试</Button>} />}
<div className="trend-chart-shell" aria-busy={trendRefreshing} inert={trendRefreshing || trendDataKey !== trendKey}>
{defectDrill.controls}
<div className="trend-chart-shell" aria-busy={trendRefreshing} inert={trendRefreshing || trendDataKey !== trendKey}>
{trendMode === 'data'
? <TrendTable rows={renderedTrendData} defectDisplay={defectDisplay} rateBasis={rateBasis} fullFields={trendFullFields} onMonth={selectTrendPeriod} />
: <TrendChart rows={renderedTrendData} mode={trendMode} stage={trendStage} rateBasis={rateBasis} targetRate={renderedTrendTarget} selectedPeriod={selectedTrendPeriod} onMonth={selectTrendPeriod} />}
: <TrendChart defectDrilldown={trendDataKey===trendKey&&!trendLoading&&!currentTrendError?defectDrill.trend:undefined} drillableCategories={defectDrill.categories} onDefect={defectDrill.choose} rows={renderedTrendData} mode={trendMode} stage={trendStage} rateBasis={rateBasis} targetRate={renderedTrendTarget} selectedPeriod={selectedTrendPeriod} onMonth={selectTrendPeriod} />}
{showTrendLoading && <span className="trend-refresh-indicator"><Spin size="small" />{retainedTrend ? `正在更新 · 当前显示上次筛选的${loadedQueryScope(retainedTrend.query, decodeQueryValueList)}` : '正在读取趋势'}</span>}
</div>
</QueryTrendPanel>
<QueryTablePanel
heading={<SectionHeading title={tableProduct ? '产品月度质量数据' : page === 'overall' ? `${tablePeriod === 'year' ? '年度月度' : tablePeriod === 'quarter' ? '季度' : '月度'}汇总` : `${scopeName}质量汇总`} subtitle={tableProduct ? `${retainedTable?.year || year} 年 · ${tableProduct} · 重量 / kg 合格率 / %` : '重量 / kg 合格率 / %'} />} busy={queryBusy || !tableReady}
search={drilledProduct || search} onSearchChange={setSearch} onSearch={() => applySearch()} productView={view === 'product'} searchPlaceholder={view === 'group' ? '搜索业务分组' : undefined} searchDisabled={Boolean(drilledProduct)}
heading={<SectionHeading title={tableProduct ? `产品${retainedTable?.granularity === 'quarter' ? '季度' : retainedTable?.granularity === 'year' ? '年度' : '月度'}质量数据` : page === 'overall' ? `${tablePeriod === 'year' ? '年度月度' : tablePeriod === 'quarter' ? '季度' : '月度'}汇总` : `${scopeName}质量汇总`} subtitle={tableProduct ? `${retainedTable?.year || year} 年 · ${tableProductLabel} · 重量 / kg 合格率 / %` : '重量 / kg 合格率 / %'} />} busy={queryBusy || !tableReady}
search={drilledProduct ? tableProductLabel : search} onSearchChange={setSearch} onSearch={() => applySearch()} productView={view === 'product'} searchPlaceholder={view === 'group' ? '搜索业务分组' : undefined} searchDisabled={Boolean(drilledProduct)}
fullFields={fullFields} onFullFields={setFullFields} defectDisplay={defectDisplay} onDefectDisplay={setDefectDisplay}
returnControls={<>{!drilledProduct && (view !== baseView || view === 'group' || view === 'product' && (group.length > 0 || department.length > 0)) && <Button className="query-return-button" icon={<ArrowLeftOutlined />} onClick={() => { setSearch(''); setAppliedSearch(''); setTrendObject(''); if (view === 'product') { setProduct([]); setGroup([]); setViewOverride('group'); } else if (view === 'group') { setGroup([]); setDepartment([]); setViewOverride('department'); } else { setViewOverride(); } }}>返回上一级</Button>}
{drilledProduct && <Button className="query-return-button" icon={<ArrowLeftOutlined />} onClick={() => { setDrilledProduct(''); setTrendObject(''); setTrendMode('production'); }}>返回上一级</Button>}</>}
exporting={summaryExporting} exportDisabled={queryBusy || summaryBusy || !tableReady || !summaryMetricsData || Boolean(drilledProduct && (trendLoading || currentTrendError)) || !(drilledProduct ? drilledTrendData : visibleRows).length}
{drilledProduct && <Button className="query-return-button" icon={<ArrowLeftOutlined />} onClick={() => { setDrilledProduct(''); setTrendObject(''); if(trendMode!=='defects')setTrendMode('production'); }}>返回上一级</Button>}</>}
exporting={summaryExporting} exportDisabled={!!defectDrill.category && (!defectDrill.table || defectDrill.pending || !!defectDrill.error) || queryBusy || summaryBusy || !tableReady || !summaryMetricsData || Boolean(drilledProduct && (trendLoading || currentTrendError)) || !(drilledProduct ? drilledTrendData : visibleRows).length}
onExport={async () => {
setSummaryExporting(true);
try { await summaryExport.current?.exportExcel(); }
@@ -794,6 +807,7 @@ export default function QueryPage({ page, onUnauthorized }: {
<SmoothTableFrame busy={queryBusy || !tableReady} blocked={queryBusy || summaryBusy || !tableReady}>
<MetricTable
ref={summaryExport}
defectDrilldown={tableReady&&!queryBusy?defectDrill.table:undefined}
paginationScope={retainedTable?.paginationScope}
exportFilename={`${drilledProduct || scopeName}质量汇总-${year}${drilledProduct || period === 'year' ? '' : period === 'month' ? `-${String(month).padStart(2, '0')}` : `-Q${quarter}`}-${fullFields ? '完整字段' : '关键指标'}`}
rows={tableRows}
@@ -815,12 +829,12 @@ export default function QueryPage({ page, onUnauthorized }: {
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.product || row.label;
const selectedProduct = row.key === '__UNASSIGNED__' || !row.product && !row.key?.trim() ? '__UNASSIGNED__' : row.product || row.label;
if (!selectedProduct) return;
setDrilledProduct(selectedProduct);
setTrendObject(selectedProduct);
setTrendGranularity('month');
setTrendMode('production');
if(trendMode!=='defects')setTrendMode('production');
}
}}
/>
@@ -1081,9 +1095,9 @@ const totalWeightTitle = (label: string) => <span className="query-total-weight-
const rateBasisTitle = (label: string, basis: QueryRateBasis, kind: 'bright' | 'composite', onBasis?: () => void) => <span className="query-total-weight-title query-rate-rule-title"><span className="query-rate-label">{onBasis ? <button className="header-link" onClick={onBasis}>{label}</button> : label}{basis !== 'original' && <small className="query-rate-subtitle">(去本部报废)</small>}</span>{basis !== 'original' && <Tooltip trigger={['hover', 'focus']} title={<div>{kind === 'composite' && <>综合合格率=黑片合格率×亮片合格率。<br /></>}原口径:亮片合格重量÷亮片总重量。<br />去本部报废:(亮片合格重量+本部报废)÷亮片总重量,同时从亮片报废重量中扣除本部报废,总重量不变。<br />当前:去本部报废。计算结果以已发布数据版本及生效规则为准。</div>}><InfoCircleOutlined tabIndex={0} role="img" aria-label={`${kind === 'composite' ? '综合合格率' : '亮片合格率'}计算说明`} /></Tooltip>}</span>;
export function MetricTable({
ref, exportFilename, rows, view, layoutView = view, pageSizeOverride, paginationScope, period, month, quarter, fullFields, rateBasis, onDetail, onBasis, onDrilldown, onlyStage, defectDisplay = 'weight', emptyText = '当前条件下暂无数据',
ref, exportFilename, rows, view, defectDrilldown, layoutView = view, pageSizeOverride, paginationScope, period, month, quarter, fullFields, rateBasis, onDetail, onBasis, onDrilldown, onlyStage, defectDisplay = 'weight', emptyText = '当前条件下暂无数据',
}: {
ref?: React.Ref<{ exportExcel: () => Promise<void> }>; exportFilename: string;
ref?: React.Ref<{ exportExcel: () => Promise<void> }>; exportFilename: string; defectDrilldown?: DefectDrilldownResponse;
rows: MetricRow[]; view: ViewKind; layoutView?: ViewKind; pageSizeOverride?: number; paginationScope?: string; period: PeriodKind; month: number; quarter: number; fullFields: boolean;
rateBasis: 'original' | 'withoutHeadquartersScrap';
onDetail: (row: MetricRow | null, stage: Stage, month?: number) => void; onBasis: () => void; onDrilldown: (row: MetricRow) => void;
@@ -1091,7 +1105,9 @@ export function MetricTable({
}) {
const compact = useCompactTable();
const isOverall = view === 'overall';
const title = (row: MetricRow) => isOverall && period === 'year'
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);
@@ -1123,15 +1139,25 @@ export function MetricTable({
totalWeight: '总重量', qualifiedWeight: '合格重量', scrapWeight: '报废重量',
headquartersScrapWeight: '本部报废', rate: '合格率',
};
const stageColumns = (stage: Stage): ColumnsType<MetricRow> => metricStageColumnPlan(rows, stage, fullFields, rateBasis).map(column => {
const stageColumns = (stage: Stage): ColumnsType<MetricRow> => {
const base: ColumnsType<MetricRow> = metricStageColumnPlan(rows, stage, defectDrilldown ? false : fullFields, rateBasis).map(column => {
if (column.kind === 'defect') return defectColumns(stage, [column.name])[0];
const metricColumn = numeric(fieldLabels[column.field], stage, column.field);
return stage === 'bright' && column.field === 'rate'
? { ...metricColumn, render: (_: unknown, row: MetricRow) => <Button type="link" className="table-value" tabIndex={-1} style={{ userSelect: 'text', WebkitUserSelect: 'text' }}><AnimatedMetricText value={rateText(visibleStageRate(row, 'bright', rateBasis))} /></Button> }
: metricColumn;
});
if(defectDrilldown?.stage===stage) {
const data=defectDrilldown;
const fields=[{key:'parent',label:data.category},...data.fields];
const columns=fields.map(field=>({key:`${stage}-fine-${field.key}`,title:defectDisplay==='rate'?fineDefectRateLabel(field.label):field.label.replace(/重量$/,''),exportRate:defectDisplay==='rate',align:'center' as const,width:140,
render:(_:unknown,row:MetricRow)=>{const value=defectCell(data,row,field.key,defectDisplay);return defectDisplay==='rate'?rateText(value):numberText(value);}}));
base.splice(base.length-1,0,...columns);
}
return base;
};
const allColumns: ColumnsType<MetricRow> = [
{ title: isOverall ? period === 'year' ? '月份' : '统计期间' : view === 'group' ? '产业部 / 业务分组' : view === 'product' ? '产品规格' : view === 'projectGroup' ? '项目组' : view === 'department' ? '产业部' : '对象', key: 'object', dataIndex: 'label', fixed: 'left', width: compact ? isOverall ? 100 : 180 : isOverall ? 120 : layoutView === 'product' ? (fullFields ? 240 : 300) : layoutView === 'group' ? (fullFields ? 220 : 260) : (fullFields ? 180 : 220), render: (_: unknown, row) => <span className="object-cell">{view === 'department' || view === 'group' || view === 'product' ? <Button type="link" className="object-drilldown" style={{ userSelect: 'text', WebkitUserSelect: 'text' }} onClick={() => { if (window.getSelection()?.isCollapsed !== false) onDrilldown(row); }}>{title(row)} <span>›</span></Button> : <strong>{title(row)}</strong>}{view === 'group' && row.department && <small>{row.department}</small>}</span> },
{ title: isOverall ? period === 'year' && !rows.some(row => ['quarter', 'year'].includes((row as TrendMetricRow).granularity || '')) ? '月份' : '统计期间' : view === 'group' ? '产业部 / 业务分组' : view === 'product' ? '产品规格' : view === 'projectGroup' ? '项目组' : view === 'department' ? '产业部' : '对象', key: 'object', dataIndex: 'label', fixed: 'left', width: compact ? isOverall ? 100 : 180 : isOverall ? 120 : layoutView === 'product' ? (fullFields ? 240 : 300) : layoutView === 'group' ? (fullFields ? 220 : 260) : (fullFields ? 180 : 220), render: (_: unknown, row) => <span className="object-cell">{view === 'department' || view === 'group' || view === 'product' ? <Button type="link" className="object-drilldown" style={{ userSelect: 'text', WebkitUserSelect: 'text' }} onClick={() => { if (window.getSelection()?.isCollapsed !== false) onDrilldown(row); }}>{title(row)} <span>›</span></Button> : <strong>{title(row)}</strong>}{view === 'group' && row.department && <small>{row.department}</small>}</span> },
{ key: 'stage-black', title: <span className="stage-heading black"><i />黑片</span>, children: stageColumns('black') },
{ key: 'stage-bright', title: <span className="stage-heading bright"><i />亮片</span>, children: stageColumns('bright') },
{ title: rateBasisTitle('综合合格率', rateBasis, 'composite', onBasis), key: 'compositeRate', dataIndex: 'compositeRate', align: 'center', fixed: compact ? undefined : 'right', width: 120, className: 'combined-column', render: (_: number | null, row: MetricRow) => <button className="combined-value" tabIndex={-1} style={{ userSelect: 'text', WebkitUserSelect: 'text' }}><AnimatedMetricText value={rateText(visibleCompositeRate(row, rateBasis))} /></button> },
@@ -1143,6 +1169,7 @@ export function MetricTable({
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;
@@ -1152,7 +1179,7 @@ export function MetricTable({
return field === 'rate' ? visibleStageRate(row, stage, stage === 'bright' ? rateBasis : 'original') : stageValue(row, stage, field, rateBasis);
}),
}));
const dataSource = rows.map((row, index) => ({ ...row, key: row.key || `${title(row)}-${index}` }));
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;
@@ -1184,7 +1211,7 @@ 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 }: { rows: TrendMetricRow[]; mode: 'production' | 'defects'; stage: Stage; rateBasis: 'original' | 'withoutHeadquartersScrap'; targetRate: number | null; selectedPeriod?: string; onMonth: (value: number | string) => void; onlyStage?: Stage }) {
export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedPeriod, onMonth, onlyStage, defectDrilldown, drillableCategories = [], onDefect }: { defectDrilldown?:DefectDrilldownResponse; drillableCategories?:string[]; onDefect?:(category:string)=>void; rows: TrendMetricRow[]; mode: 'production' | 'defects'; stage: Stage; rateBasis: 'original' | 'withoutHeadquartersScrap'; targetRate: number | null; selectedPeriod?: string; onMonth: (value: number | string) => void; onlyStage?: Stage }) {
const { active } = usePageCache();
const container = useRef<HTMLDivElement>(null);
const [snapshotRequested, setSnapshotRequested] = useState(false);
@@ -1197,6 +1224,8 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
const visible = useResourceVisibility(container, active) || snapshotRequested;
const chart = useRef<ReturnType<typeof echarts.init> | null>(null);
const onMonthRef = useRef(onMonth);
const drillRef = useRef({onDefect,drillableCategories,drilled:!!defectDrilldown});
drillRef.current={onDefect,drillableCategories,drilled:!!defectDrilldown};
const rowsRef = useRef(rows);
const modeRef = useRef(mode);
const stageRef = useRef(stage);
@@ -1214,7 +1243,7 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
const refreshBarMasks = useCallback(() => {
const instance = chart.current;
if (!instance || modeRef.current !== 'production') { setBarMasks([]); return; }
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 => {
@@ -1249,6 +1278,11 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
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));
@@ -1304,7 +1338,14 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
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`;
return `${item.marker || ''}${escapeTooltipText(name)}:${formatted}`;
let weight='';
if(defectDrilldown&&onlyRates&&item.dataIndex!==undefined) {
const group=defectGroup(defectDrilldown,rows[item.dataIndex]);
const field=defectDrilldown.fields.find(field=>fineDefectRateLabel(field.label)===name);
const value=field?group?.children.find(child=>child.key===field.key)?.weight:group?.parentWeight;
weight=`(${numberText(value)} kg)`;
}
return `${item.marker || ''}${escapeTooltipText(name)}:${formatted}${weight}`;
})].join('<br/>');
};
const base: echarts.EChartsCoreOption = {
@@ -1317,7 +1358,7 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
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: true, axisLine: { lineStyle: { color: line } }, axisLabel: { color: ink, fontFamily, fontSize, margin: 12 }, axisTick: { show: false } },
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 };
@@ -1355,16 +1396,22 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
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, ...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)); }) })),
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]);
}, [rows, mode, stage, rateBasis, targetRate, themeRevision, refreshBarMasks, onlyStage, selectedPeriod, active, visible, defectDrilldown, drillableCategories.join('\0')]);
const dimmedPeriod = selectedPeriod === lineSelectedPeriod ? undefined : selectedPeriod;