同步:补齐已发布的查询面板与不良构成源码
This commit is contained in:
@@ -0,0 +1,115 @@
|
||||
import { useEffect, useRef, useState } from 'react';
|
||||
import * as echarts from 'echarts/core';
|
||||
import { BarChart } from 'echarts/charts';
|
||||
import { GridComponent, TooltipComponent } from 'echarts/components';
|
||||
import { SVGRenderer } from 'echarts/renderers';
|
||||
import type { DefectMetric, Stage } from './types';
|
||||
import { defectWeightRate } from './trendMetrics';
|
||||
import './defect-composition.css';
|
||||
|
||||
echarts.use([BarChart, GridComponent, TooltipComponent, SVGRenderer]);
|
||||
const weightText = (value: number | null | undefined) => typeof value === 'number' && Number.isFinite(value) ? value.toLocaleString('en-US', { minimumFractionDigits: 1, maximumFractionDigits: 1 }) : '—';
|
||||
const rateText = (value: number | null | undefined) => typeof value === 'number' && Number.isFinite(value) ? `${(value * 100).toFixed(2)}%` : '—';
|
||||
const escape = (value: string) => value.replace(/[&<>"']/g, char => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[char]!));
|
||||
|
||||
function categoryColors(color: string, surface: string, count: number): string[] {
|
||||
return Array.from({ length: count }, (_, index) => {
|
||||
const mix = index === 0 ? 0 : Math.min(.8, .3 + (index - 1) * .25);
|
||||
return `#${[1, 3, 5].map(offset => Math.round(parseInt(color.slice(offset, offset + 2), 16) * (1 - mix) + parseInt(surface.slice(offset, offset + 2), 16) * mix).toString(16).padStart(2, '0')).join('')}`;
|
||||
});
|
||||
}
|
||||
|
||||
export default function DefectComposition({ items, stage, totalWeight, onDetail }: {
|
||||
items: DefectMetric[];
|
||||
stage: Stage;
|
||||
totalWeight?: number | null;
|
||||
onDetail: () => void;
|
||||
}) {
|
||||
const container = useRef<HTMLDivElement>(null);
|
||||
const latest = useRef({ items, stage, totalWeight, onDetail });
|
||||
latest.current = { items, stage, totalWeight, onDetail };
|
||||
const redraw = useRef<() => void>(() => undefined);
|
||||
const [colors, setColors] = useState<string[]>([]);
|
||||
const hasShares = items.some(item => typeof item.rate === 'number' && Number.isFinite(item.rate) && item.rate > 0 && item.rate <= 1);
|
||||
|
||||
useEffect(() => {
|
||||
const node = container.current;
|
||||
if (!node) return;
|
||||
let chart: ReturnType<typeof echarts.init> | undefined;
|
||||
redraw.current = () => {
|
||||
if (!node.clientWidth) return;
|
||||
const current = latest.current;
|
||||
const css = getComputedStyle(node);
|
||||
const ink = css.getPropertyValue('--ink').trim() || '#222C3C';
|
||||
const muted = css.getPropertyValue('--muted-ink').trim() || '#637187';
|
||||
const line = css.getPropertyValue('--line').trim() || '#DCE2EC';
|
||||
const surface = css.getPropertyValue('--surface').trim() || '#FFFFFF';
|
||||
const color = css.getPropertyValue(current.stage === 'black' ? '--defect-black' : '--defect-bright').trim() || (current.stage === 'black' ? '#718797' : '#607AE1');
|
||||
const palette = categoryColors(color, surface, current.items.length);
|
||||
if (current.stage === 'black' && document.documentElement.dataset.workspaceTheme !== 'dark') {
|
||||
// Match the selected blue-gray swatches; keep the existing dark-theme contrast treatment.
|
||||
for (const index of [1, 2]) {
|
||||
const tone = css.getPropertyValue(`--defect-black-${index + 1}`).trim();
|
||||
if (tone && index < palette.length) palette[index] = tone;
|
||||
}
|
||||
}
|
||||
setColors(old => old.join() === palette.join() ? old : palette);
|
||||
const fontFamily = css.getPropertyValue('--font-ui').trim() || css.fontFamily;
|
||||
const numericFamily = css.getPropertyValue('--font-numeric').trim() || 'Arial';
|
||||
const stageName = current.stage === 'black' ? '黑片' : '亮片';
|
||||
if (!chart) {
|
||||
chart = echarts.init(node, undefined, { renderer: 'svg' });
|
||||
chart.on('click', () => latest.current.onDetail());
|
||||
}
|
||||
const option: echarts.EChartsCoreOption = {
|
||||
animation: !window.matchMedia('(prefers-reduced-motion: reduce)').matches,
|
||||
animationDuration: 420,
|
||||
animationDurationUpdate: 520,
|
||||
textStyle: { color: ink, fontFamily, fontSize: 12 },
|
||||
grid: { top: 8, left: 20, right: 20, bottom: 28 },
|
||||
tooltip: {
|
||||
trigger: 'item', backgroundColor: surface, borderColor: line,
|
||||
textStyle: { color: ink, fontFamily, fontSize: 12 },
|
||||
formatter: (raw: unknown) => {
|
||||
const item = current.items[(raw as { seriesIndex: number }).seriesIndex];
|
||||
return item ? `${stageName} · ${escape(item.name)}<br/>重量:${weightText(item.weight)} kg<br/>占比:${rateText(item.rate)}<br/>废率:${rateText(defectWeightRate(item.weight, current.totalWeight))}` : '';
|
||||
},
|
||||
},
|
||||
xAxis: { type: 'value', min: 0, max: 100, interval: 25, axisLine: { show: true, lineStyle: { color: line } }, axisTick: { show: false }, splitLine: { show: false }, axisLabel: { fontFamily: numericFamily, fontSize: 11, color: muted, formatter: '{value}%' } },
|
||||
yAxis: { type: 'category', data: [''], show: false },
|
||||
series: current.items.map((item, index) => ({
|
||||
id: `composition-${current.stage}-${item.name}`, name: item.name, type: 'bar', stack: 'composition', barWidth: 28,
|
||||
data: [typeof item.rate === 'number' && Number.isFinite(item.rate) && item.rate >= 0 && item.rate <= 1 ? item.rate * 100 : null],
|
||||
itemStyle: { color: palette[index] },
|
||||
label: { show: typeof item.rate === 'number' && item.rate >= .15, position: 'inside', formatter: rateText(item.rate), color: index === 0 && document.documentElement.dataset.workspaceTheme !== 'dark' ? '#FFFFFF' : ink, fontFamily: numericFamily, fontSize: 13, fontWeight: 600 },
|
||||
emphasis: { itemStyle: { opacity: .85 } },
|
||||
})),
|
||||
};
|
||||
chart.setOption(option, { replaceMerge: ['series'] });
|
||||
};
|
||||
redraw.current();
|
||||
const resize = new ResizeObserver(() => {
|
||||
const { clientWidth: width, clientHeight: height } = node;
|
||||
if (width <= 0 || height <= 0) return;
|
||||
if (chart) chart.resize({ width, height, animation: { duration: 0 } }); else redraw.current();
|
||||
});
|
||||
resize.observe(node);
|
||||
const theme = new MutationObserver(() => redraw.current());
|
||||
theme.observe(document.documentElement, { attributes: true, attributeFilter: ['data-workspace-theme'] });
|
||||
return () => { resize.disconnect(); theme.disconnect(); chart?.dispose(); redraw.current = () => undefined; };
|
||||
}, []);
|
||||
|
||||
useEffect(() => { redraw.current(); }, [items, stage, totalWeight]);
|
||||
|
||||
return <div className="defect-composition">
|
||||
<div className="defect-composition-unit">占比 / %</div>
|
||||
<div className="defect-composition-plot" ref={container} role="img" aria-label={`${stage === 'black' ? '黑片' : '亮片'}分类报废占比,详细数值见下方表格`} style={{ visibility: hasShares ? undefined : 'hidden' }} />
|
||||
{!hasShares && <div className="defect-composition-empty">暂无可绘制的构成占比</div>}
|
||||
<table className="defect-composition-table"><thead><tr><th scope="col">不良分类</th><th scope="col">重量 / kg</th><th scope="col">占比</th><th scope="col">废率</th></tr></thead><tbody>
|
||||
{items.map((item, index) => <tr key={item.name} onClick={() => { if (window.getSelection()?.isCollapsed !== false) onDetail(); }}>
|
||||
<td><button type="button" className="defect-composition-category" aria-label={`查看${stage === 'black' ? '黑片' : '亮片'}${item.name}来源明细`}><i aria-hidden="true" style={{ backgroundColor: colors[index] }} />{item.name}</button></td>
|
||||
<td className="defect-composition-weight">{weightText(item.weight)}</td><td>{rateText(item.rate)}</td><td>{rateText(defectWeightRate(item.weight, totalWeight))}</td>
|
||||
</tr>)}
|
||||
</tbody></table>
|
||||
</div>;
|
||||
}
|
||||
@@ -17,7 +17,6 @@ import {
|
||||
CheckOutlined,
|
||||
DatabaseOutlined,
|
||||
DownOutlined,
|
||||
DeploymentUnitOutlined,
|
||||
KeyOutlined,
|
||||
LineChartOutlined,
|
||||
LoadingOutlined,
|
||||
@@ -67,7 +66,6 @@ const navGroups = [
|
||||
items: [
|
||||
['overall', '总体合格率', AppstoreOutlined],
|
||||
['department', '产业部', ApartmentOutlined],
|
||||
['group', '产业部-业务分组', DeploymentUnitOutlined],
|
||||
['product', '产品汇总', DatabaseOutlined],
|
||||
['blackProduct', '黑片汇总', DatabaseOutlined],
|
||||
['brightProduct', '亮片汇总', DatabaseOutlined],
|
||||
|
||||
+61
-92
@@ -47,6 +47,9 @@ import { readableSelectPopup } from './readableSelectPopup';
|
||||
import { isInternalDataField, readableMetricFormula } from './publicDataDisplay';
|
||||
import { defaultQueryMonth, previousCompleteMonth, previousCompleteQuarter } from './periodDefaults';
|
||||
import { defectWeightRate } from './trendMetrics';
|
||||
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';
|
||||
@@ -299,10 +302,10 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
const [options, setOptions] = useState<OptionsResponse | null>(null);
|
||||
const [optionsError, setOptionsError] = useState('');
|
||||
const [optionsLoading, setOptionsLoading] = useState(true);
|
||||
const automaticPeriod = useRef(!initialQuery.year && !initialQuery.month && !initialQuery.quarter);
|
||||
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 ? 'year' : 'month');
|
||||
const [period, setPeriod] = useState<PeriodKind>(initialQuery.month ? 'month' : initialQuery.quarter ? 'quarter' : initialQuery.year || page === 'overall' ? 'year' : 'month');
|
||||
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);
|
||||
@@ -599,35 +602,9 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
}, []);
|
||||
const selectTrendPeriod = useCallback((value: number | string) => {
|
||||
automaticPeriod.current = false;
|
||||
const raw = String(value);
|
||||
const quarterMatch = raw.match(/^(\d{4})-Q([1-4])$/);
|
||||
const yearMonth = raw.match(/^(\d{4})-(\d{1,2})$/);
|
||||
const yearMatch = raw.match(/^(\d{4})$/);
|
||||
if (quarterMatch) {
|
||||
if (period === 'quarter' && year === Number(quarterMatch[1]) && quarter === Number(quarterMatch[2])) {
|
||||
captureTrendAnchor(); setPeriod('year'); return;
|
||||
}
|
||||
if (period !== 'quarter' || year !== Number(quarterMatch[1]) || quarter !== Number(quarterMatch[2])) captureTrendAnchor();
|
||||
setYear(Number(quarterMatch[1])); setQuarter(Number(quarterMatch[2])); setPeriod('quarter');
|
||||
} else if (yearMonth) {
|
||||
if (period === 'month' && year === Number(yearMonth[1]) && month === Number(yearMonth[2])) {
|
||||
captureTrendAnchor(); setPeriod('year'); return;
|
||||
}
|
||||
if (period !== 'month' || year !== Number(yearMonth[1]) || month !== Number(yearMonth[2])) captureTrendAnchor();
|
||||
setYear(Number(yearMonth[1])); setMonth(Number(yearMonth[2])); setPeriod('month');
|
||||
} else if (yearMatch) {
|
||||
if (period !== 'year' || year !== Number(yearMatch[1])) captureTrendAnchor();
|
||||
setYear(Number(yearMatch[1])); setPeriod('year');
|
||||
} else {
|
||||
const selected = monthNumber(value);
|
||||
if (selected) {
|
||||
if (period === 'month' && month === selected) {
|
||||
captureTrendAnchor(); setPeriod('year'); return;
|
||||
}
|
||||
if (period !== 'month' || month !== selected) captureTrendAnchor();
|
||||
setPeriod('month'); setMonth(selected);
|
||||
}
|
||||
}
|
||||
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(() => {
|
||||
@@ -770,7 +747,7 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
<ExtraQueryFilters key={queryRevision} 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>
|
||||
<Button type="default" onClick={() => { automaticPeriod.current = false; const previous = defaultQueryMonth(options); const previousQuarter = previousCompleteQuarter(); setDepartment([]); setGroup([]); setProduct([]); setProjectGroup([]); setExtraFilters({}); setSearch(''); setAppliedSearch(''); setTrendObject(''); setYear(previous.year); setMonth(previous.month); setQuarter(previousQuarter.quarter); setPeriod('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(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>
|
||||
@@ -794,18 +771,11 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
|
||||
<>
|
||||
<div className="analysis-stack">
|
||||
<section className="panel section-panel trend-panel" ref={trendSection} id={active ? 'monthly-trend' : undefined}>
|
||||
<div className="section-heading-row trend-heading-row">
|
||||
<SectionHeading title={`${trendGranularity === 'month' ? '月度' : trendGranularity === 'quarter' ? '季度' : '年度'}变化趋势`} />
|
||||
<Segmented value={trendMode} options={[{ label: '合格率与产量', value: 'production' }, { label: '不良率', value: 'defects' }, { label: `${trendGranularity === 'quarter' ? '季度' : trendGranularity === 'year' ? '年度' : '月度'}数据`, value: 'data' }]} onChange={value => setTrendMode(value as typeof trendMode)} aria-label="趋势视图" />
|
||||
</div>
|
||||
<div className="trend-controls">
|
||||
{trendMode==='data'&&<Segmented value={defectDisplay} options={[{label:'不良重量',value:'weight'},{label:'不良率',value:'rate'}]} onChange={value=>setDefectDisplay(value as typeof defectDisplay)} aria-label="趋势不良显示方式"/>}
|
||||
<label className="query-field trend-granularity"><span>趋势粒度</span><Select {...readableSelectPopup} value={trendGranularity} options={[{ label: '按月', value: 'month' }, { label: '按季度', value: 'quarter' }, { label: '按年度', value: 'year' }]} onChange={value => setTrendGranularity(value)} aria-label="趋势粒度" /></label>
|
||||
<label className="query-field trend-object"><span>趋势对象</span><Select {...readableSelectPopup} allowClear placeholder={`当前${scopeName}筛选`} value={trendObject || undefined} options={trendOptions} onChange={setSynchronizedTrendObject} aria-label="趋势对象" />
|
||||
</label>
|
||||
{trendMode !== 'data' && <Segmented value={trendStage} options={[{ label: '亮片', value: 'bright' }, { label: '黑片', value: 'black' }]} onChange={value => setTrendStage(value as Stage)} aria-label="趋势阶段" />}
|
||||
</div>
|
||||
<QueryTrendPanel panelRef={trendSection} id={active ? 'monthly-trend' : undefined}
|
||||
mode={trendMode} onMode={setTrendMode} granularity={trendGranularity} onGranularity={setTrendGranularity}
|
||||
defectDisplay={defectDisplay} onDefectDisplay={setDefectDisplay} object={trendObject} onObject={setSynchronizedTrendObject}
|
||||
objects={trendOptions} scopeName={scopeName}
|
||||
stageSwitch={<Segmented value={trendStage} options={[{ label: '亮片', value: 'bright' }, { label: '黑片', value: 'black' }]} onChange={value => setTrendStage(value as Stage)} aria-label="趋势阶段" />}>
|
||||
{currentTrendError && <Alert type="warning" showIcon message="趋势读取失败" description={currentTrendError} action={<Button onClick={() => setQueryRevision(value => value + 1)}>重试</Button>} />}
|
||||
<div className="trend-chart-shell" aria-busy={trendRefreshing} inert={trendRefreshing || trendDataKey !== trendKey}>
|
||||
{trendMode === 'data'
|
||||
@@ -813,29 +783,22 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
: <TrendChart rows={renderedTrendData} mode={trendMode} stage={trendStage} rateBasis={rateBasis} targetRate={renderedTrendTarget} selectedPeriod={selectedTrendPeriod} onMonth={selectTrendPeriod} />}
|
||||
{trendRefreshing && <span className="trend-refresh-indicator"><Spin size="small" />正在更新趋势</span>}
|
||||
</div>
|
||||
</section>
|
||||
</QueryTrendPanel>
|
||||
|
||||
|
||||
<section className="panel section-panel table-panel">
|
||||
<div className="section-heading-row">
|
||||
<SectionHeading title={tableProduct ? '产品月度质量数据' : page === 'overall' ? `${tablePeriod === 'year' ? '年度月度' : tablePeriod === 'quarter' ? '季度' : '月度'}汇总` : `${scopeName}质量汇总`} subtitle={tableProduct ? `${retainedTable?.year || year} 年 · ${tableProduct} · 重量 / kg 合格率 / %` : '重量 / kg 合格率 / %'} />
|
||||
<div className="table-tools">
|
||||
{(queryBusy || !tableReady) && <span className="defect-refresh-indicator"><Spin size="small" />正在更新</span>}
|
||||
<Input allowClear={!drilledProduct} disabled={Boolean(drilledProduct)} maxLength={view === 'product' ? 256 : undefined} prefix={<SearchOutlined />} placeholder={view === 'product' ? '输入关键词或完整产品名称' : `搜索${view === 'group' ? '业务分组' : '汇总对象'}`} value={drilledProduct || search} onChange={event => setSearch(event.target.value)} aria-label={view === 'product' ? '搜索产品名称并同步筛选指标和趋势' : '搜索汇总对象'} />
|
||||
<Button type="primary" disabled={Boolean(drilledProduct)} onClick={() => applySearch()} aria-label="开始搜索">搜索</Button>
|
||||
<Segmented value={fullFields ? 'full' : 'key'} options={[{ label: '关键指标', value: 'key' }, { label: '完整字段', value: 'full' }]} onChange={value => setFullFields(value === 'full')} aria-label="字段显示" />
|
||||
<Segmented value={defectDisplay} options={[{label:'不良重量',value:'weight'},{label:'不良率',value:'rate'}]} onChange={value=>setDefectDisplay(value as typeof defectDisplay)} aria-label="不良显示方式" />
|
||||
{!drilledProduct && (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 { setGroup([]); setDepartment([]); setViewOverride('department'); } }}>返回上一级</Button>}
|
||||
{drilledProduct && <Button className="query-return-button" icon={<ArrowLeftOutlined />} onClick={() => { setDrilledProduct(''); setTrendObject(''); setTrendMode('production'); }}>返回上一级</Button>}
|
||||
<Button type="primary" className="query-export-button" icon={<DownloadOutlined />} aria-label="Excel导出" loading={summaryExporting} disabled={queryBusy || summaryBusy || !summaryMetricsData || Boolean(drilledProduct && trendLoading) || !(drilledProduct ? drilledTrendData : visibleRows).length} onClick={async () => {
|
||||
<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)}
|
||||
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 || !summaryMetricsData || Boolean(drilledProduct && trendLoading) || !(drilledProduct ? drilledTrendData : visibleRows).length}
|
||||
onExport={async () => {
|
||||
setSummaryExporting(true);
|
||||
try { await summaryExport.current?.exportExcel(); }
|
||||
catch (error) { message.error(`导出失败:${chooseError(error)}`); }
|
||||
finally { setSummaryExporting(false); }
|
||||
}}>Excel导出</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mobile-scroll-hint">横向滑动查看完整指标</div>
|
||||
}}>
|
||||
<SmoothTableFrame busy={queryBusy || !tableReady} blocked={queryBusy || summaryBusy || !tableReady}>
|
||||
<MetricTable
|
||||
ref={summaryExport}
|
||||
@@ -869,7 +832,7 @@ export default function QueryPage({ page, onUnauthorized }: {
|
||||
}}
|
||||
/>
|
||||
</SmoothTableFrame>
|
||||
</section>
|
||||
</QueryTablePanel>
|
||||
|
||||
<section className="panel section-panel defects-panel" ref={defectsSection} aria-busy={defectsRefreshing} style={{ minHeight: queryBusy && trendAnchorTop.current != null ? defectsHeight.current : undefined }}>
|
||||
<div className="section-heading-row">
|
||||
@@ -937,23 +900,15 @@ export function MetricCard({ primary, label, value, note, stage, onClick }: { pr
|
||||
</button>;
|
||||
}
|
||||
|
||||
export function DefectBreakdown({ items, stage, totalWeight, maximum, onDetail }: { items: DefectMetric[]; stage: Stage; totalWeight?: number | null; maximum: number; onDetail: () => void }) {
|
||||
return <div className="defect-list">
|
||||
<div className="defect-header"><span>不良分类</span><span aria-hidden="true" /><span>重量 / kg</span><span>占比</span><span>废率</span></div>
|
||||
{items.map(item => <button className="defect-row" key={item.name} onClick={onDetail}>
|
||||
<span className="defect-name">{item.name}</span>
|
||||
<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(defectWeightRate(item.weight, totalWeight))}</span>
|
||||
</button>)}
|
||||
</div>;
|
||||
export function DefectBreakdown({ items, stage, totalWeight, onDetail }: { items: DefectMetric[]; stage: Stage; totalWeight?: number | null; maximum: number; onDetail: () => void }) {
|
||||
return <DefectComposition items={items} stage={stage} totalWeight={totalWeight} onDetail={onDetail} />;
|
||||
}
|
||||
|
||||
|
||||
export function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUnauthorized, onlyStage, refreshKey = 0, pending = false }: {
|
||||
releaseId?: string; query: QueryParams; externalScrapWeight?: number | null; onUnauthorized: (error: unknown) => boolean; onlyStage?: Stage; refreshKey?: number; pending?: boolean;
|
||||
}) {
|
||||
const { active } = usePageCache();
|
||||
const container = useRef<HTMLDivElement>(null);
|
||||
const chart = useRef<ReturnType<typeof echarts.init> | null>(null);
|
||||
const [responses, setResponses] = useState<{ black: FineDefectTopResponse; bright: FineDefectTopResponse; externalScrapWeight?: number | null } | null>(null);
|
||||
@@ -1005,13 +960,18 @@ export function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUna
|
||||
|
||||
useEffect(() => {
|
||||
const node = container.current;
|
||||
if (!node) return;
|
||||
const instance = echarts.init(node, undefined, { renderer: 'svg' });
|
||||
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(() => instance.resize());
|
||||
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 [];
|
||||
@@ -1039,8 +999,8 @@ export function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUna
|
||||
const styles = getComputedStyle(container.current);
|
||||
const ink = styles.getPropertyValue('--ink').trim() || '#222222';
|
||||
const line = styles.getPropertyValue('--line').trim() || '#dfe5ef';
|
||||
const blue = styles.getPropertyValue('--blue').trim() || '#607ae1';
|
||||
const teal = styles.getPropertyValue('--teal').trim() || '#008f7d';
|
||||
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 => {
|
||||
@@ -1081,12 +1041,12 @@ export function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUna
|
||||
{ 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, data: items.map(item => ({ id: item.key, name: item.label, value: item.weight, itemStyle: { color: item.kind === 'category' ? '#9aa4b2' : item.key.startsWith('black:') ? blue : teal } })) },
|
||||
{ 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]);
|
||||
}, [items, totalWeight, themeRevision, active]);
|
||||
|
||||
return <section className="defect-pareto-section" aria-busy={loading || pending} aria-label={onlyStage ? `${onlyStage === 'black' ? '黑片' : '亮片'}报废重量柏拉图` : '综合报废重量柏拉图'}>
|
||||
<div className="defect-pareto-heading"><strong>{onlyStage ? `${onlyStage === 'black' ? '黑片' : '亮片'}报废重量柏拉图` : '黑片与亮片综合报废重量柏拉图'}</strong>{loading && <span className="defect-refresh-indicator"><Spin size="small" />正在更新</span>}</div>
|
||||
@@ -1219,6 +1179,7 @@ function trendBarWidth(chartWidth: number, count: number): number {
|
||||
}
|
||||
|
||||
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 }) {
|
||||
const { active } = usePageCache();
|
||||
const container = useRef<HTMLDivElement>(null);
|
||||
const chart = useRef<ReturnType<typeof echarts.init> | null>(null);
|
||||
const onMonthRef = useRef(onMonth);
|
||||
@@ -1267,10 +1228,12 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!container.current || !hasRows) return;
|
||||
const instance = echarts.init(container.current, undefined, { renderer: 'svg' });
|
||||
if (!container.current || !hasRows || !active) 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 (params.componentType !== 'series' && params.componentType !== 'xAxis') return;
|
||||
const currentRows = rowsRef.current;
|
||||
@@ -1285,8 +1248,9 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
|
||||
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();
|
||||
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 }] });
|
||||
@@ -1296,7 +1260,7 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
|
||||
});
|
||||
observer.observe(container.current);
|
||||
return () => { observer.disconnect(); instance.dispose(); chart.current = null; };
|
||||
}, [hasRows, refreshBarMasks]);
|
||||
}, [hasRows, refreshBarMasks, active]);
|
||||
|
||||
useEffect(() => {
|
||||
const instance = chart.current;
|
||||
@@ -1308,6 +1272,8 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
|
||||
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));
|
||||
@@ -1329,7 +1295,8 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
|
||||
};
|
||||
const base: echarts.EChartsCoreOption = {
|
||||
animation: !window.matchMedia('(prefers-reduced-motion: reduce)').matches,
|
||||
animationDuration: 0,
|
||||
animationDuration: 520,
|
||||
animationEasing: 'cubicOut',
|
||||
animationDurationUpdate: 520,
|
||||
animationEasingUpdate: 'cubicOut',
|
||||
textStyle: { fontFamily, color: ink, fontSize },
|
||||
@@ -1346,6 +1313,7 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
|
||||
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',
|
||||
@@ -1362,9 +1330,9 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
|
||||
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, ...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: '亮片合格率', 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))) },
|
||||
{ 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 {
|
||||
@@ -1382,7 +1350,7 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
|
||||
}
|
||||
instance.setOption(option, { replaceMerge: ['series', 'yAxis'], lazyUpdate: false });
|
||||
refreshBarMasks();
|
||||
}, [rows, mode, stage, rateBasis, targetRate, themeRevision, refreshBarMasks, onlyStage, selectedPeriod]);
|
||||
}, [rows, mode, stage, rateBasis, targetRate, themeRevision, refreshBarMasks, onlyStage, selectedPeriod, active]);
|
||||
|
||||
const dimmedPeriod = selectedPeriod === lineSelectedPeriod ? undefined : selectedPeriod;
|
||||
|
||||
@@ -1426,7 +1394,7 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
|
||||
</div>;
|
||||
}
|
||||
|
||||
function TrendTable({ rows, rateBasis, onMonth, defectDisplay = 'weight' }: { rows: TrendMetricRow[]; rateBasis: 'original' | 'withoutHeadquartersScrap'; onMonth: (value: number | string) => void; defectDisplay?: 'weight'|'rate' }) {
|
||||
export function TrendTable({ rows, rateBasis, onMonth, defectDisplay = 'weight', onlyStage }: { rows: TrendMetricRow[]; rateBasis: 'original' | 'withoutHeadquartersScrap'; onMonth: (value: number | string) => void; defectDisplay?: 'weight'|'rate'; onlyStage?: Stage }) {
|
||||
const compact = useCompactTable();
|
||||
const columns: ColumnsType<TrendMetricRow> = [
|
||||
{ title: '统计期间', dataIndex: 'month', key: 'month', align: 'center', fixed: 'left', width: 130, render: (_: unknown, row) => <Button type="link" onClick={() => onMonth(row.month)}>{row.periodLabel || String(row.month)}</Button> },
|
||||
@@ -1440,7 +1408,8 @@ function TrendTable({ rows, rateBasis, onMonth, defectDisplay = 'weight' }: { ro
|
||||
{ title: rateBasisTitle('亮片合格率', rateBasis, 'bright'), dataIndex: ['bright', 'rate'], key: 'brightRate', align: 'center', width: rateBasis === 'original' ? 180 : 194, className: 'rate-cell bright', render: (_: number | null, row: TrendMetricRow) => rateText(visibleStageRate(row, 'bright', rateBasis)) },
|
||||
{ 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)) },
|
||||
];
|
||||
return rows.length ? <div className="metric-table-scroll trend-data-table"><Table size="small" bordered tableLayout="fixed" columns={columns} dataSource={rows} rowKey={row => String(row.month)} pagination={false} scroll={{ x: columns.reduce((total, column) => total + Number(column.width || 0), 0) }} />
|
||||
const visibleColumns = onlyStage ? columns.filter(column => column.key === 'month' || String(column.key).startsWith(onlyStage)) : columns;
|
||||
return rows.length ? <div className="metric-table-scroll trend-data-table"><Table size="small" bordered tableLayout="fixed" columns={visibleColumns} dataSource={rows} rowKey={row => String(row.month)} pagination={false} scroll={{ x: visibleColumns.reduce((total, column) => total + Number(column.width || 0), 0) }} />
|
||||
</div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前数据未返回趋势" />;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import type { ReactNode, Ref } from 'react';
|
||||
import { Button, Input, Segmented, Select, Spin } from 'antd';
|
||||
import { DownloadOutlined, SearchOutlined } from '@ant-design/icons';
|
||||
import { readableSelectPopup } from './readableSelectPopup';
|
||||
|
||||
type Granularity = 'month' | 'quarter' | 'year';
|
||||
type TrendMode = 'production' | 'defects' | 'data';
|
||||
type DefectDisplay = 'weight' | 'rate';
|
||||
|
||||
export function QueryTrendPanel({ panelRef, id, mode, onMode, granularity, onGranularity, defectDisplay, onDefectDisplay, object, onObject, objects, scopeName, stageSwitch, children }: {
|
||||
panelRef?: Ref<HTMLElement>; id?: string; mode: TrendMode; onMode: (value: TrendMode) => void;
|
||||
granularity: Granularity; onGranularity: (value: Granularity) => void;
|
||||
defectDisplay: DefectDisplay; onDefectDisplay: (value: DefectDisplay) => void;
|
||||
object?: string; onObject: (value?: string) => void; objects: Array<{ label: string; value: string }>;
|
||||
scopeName: string; stageSwitch?: ReactNode; children: ReactNode;
|
||||
}) {
|
||||
const periodName = granularity === 'month' ? '月度' : granularity === 'quarter' ? '季度' : '年度';
|
||||
return <section className="panel section-panel trend-panel" ref={panelRef} id={id}>
|
||||
<div className="section-heading-row trend-heading-row">
|
||||
<div className="section-heading"><h2>{periodName}变化趋势</h2></div>
|
||||
<Segmented value={mode} options={[{ label: '合格率与产量', value: 'production' }, { label: '不良率', value: 'defects' }, { label: `${periodName}数据`, value: 'data' }]} onChange={onMode} aria-label="趋势视图" />
|
||||
</div>
|
||||
<div className="trend-controls">
|
||||
{mode === 'data' && <Segmented value={defectDisplay} options={[{ label: '不良重量', value: 'weight' }, { label: '不良率', value: 'rate' }]} onChange={onDefectDisplay} aria-label="趋势不良显示方式" />}
|
||||
<label className="query-field trend-granularity"><span>趋势粒度</span><Select {...readableSelectPopup} value={granularity} options={[{ label: '按月', value: 'month' }, { label: '按季度', value: 'quarter' }, { label: '按年度', value: 'year' }]} onChange={onGranularity} aria-label="趋势粒度" /></label>
|
||||
<label className="query-field trend-object"><span>趋势对象</span><Select {...readableSelectPopup} allowClear placeholder={`当前${scopeName}筛选`} value={object || undefined} options={objects} onChange={onObject} aria-label="趋势对象" /></label>
|
||||
{mode !== 'data' && stageSwitch}
|
||||
</div>
|
||||
{children}
|
||||
</section>;
|
||||
}
|
||||
|
||||
export function QueryTablePanel({ heading, busy, search, onSearchChange, onSearch, productView = true, searchPlaceholder, searchDisabled = false, searchUnavailable = false, fullFields, onFullFields, defectDisplay, onDefectDisplay, returnControls, exporting, exportDisabled, onExport, children }: {
|
||||
heading: ReactNode; busy?: boolean; search: string; onSearchChange: (value: string) => void; onSearch: () => void;
|
||||
productView?: boolean; searchPlaceholder?: string; searchDisabled?: boolean; searchUnavailable?: boolean;
|
||||
fullFields: boolean; onFullFields: (value: boolean) => void; defectDisplay: DefectDisplay; onDefectDisplay: (value: DefectDisplay) => void;
|
||||
returnControls?: ReactNode; exporting: boolean; exportDisabled: boolean; onExport: () => void; children: ReactNode;
|
||||
}) {
|
||||
return <section className="panel section-panel table-panel">
|
||||
<div className="section-heading-row">
|
||||
{heading}
|
||||
<div className="table-tools">
|
||||
{busy && <span className="defect-refresh-indicator"><Spin size="small" />正在更新</span>}
|
||||
<Input allowClear={!searchDisabled} disabled={searchDisabled} maxLength={productView ? 256 : undefined} prefix={<SearchOutlined />} placeholder={searchPlaceholder || (productView ? '输入关键词或完整产品名称' : '搜索汇总对象')} value={search} onChange={event => onSearchChange(event.target.value)} onPressEnter={onSearch} aria-label={productView ? '搜索产品名称并同步筛选指标和趋势' : '搜索汇总对象'} />
|
||||
<Button type="primary" disabled={searchDisabled || searchUnavailable} onClick={onSearch} aria-label="开始搜索">搜索</Button>
|
||||
<Segmented value={fullFields ? 'full' : 'key'} options={[{ label: '关键指标', value: 'key' }, { label: '完整字段', value: 'full' }]} onChange={value => onFullFields(value === 'full')} aria-label="字段显示" />
|
||||
<Segmented value={defectDisplay} options={[{ label: '不良重量', value: 'weight' }, { label: '不良率', value: 'rate' }]} onChange={onDefectDisplay} aria-label="不良显示方式" />
|
||||
{returnControls}
|
||||
<Button type="primary" className="query-export-button" icon={<DownloadOutlined />} aria-label="Excel导出" loading={exporting} disabled={exportDisabled} onClick={onExport}>Excel导出</Button>
|
||||
</div>
|
||||
</div>
|
||||
<div className="mobile-scroll-hint">横向滑动查看完整指标</div>
|
||||
{children}
|
||||
</section>;
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
import { SmoothTableFrame, useRetainedResult } from './QueryResultMotion';
|
||||
import { queryScrapWeight } from './queryMetricValues';
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||
import { Alert, App, Button, Empty, Input, Modal, Segmented, Select, Spin } from 'antd';
|
||||
import { DownOutlined, DownloadOutlined, UpOutlined } from '@ant-design/icons';
|
||||
import { Alert, App, Button, Empty, Modal, Segmented, Select, Spin } from 'antd';
|
||||
import { ArrowLeftOutlined, DownOutlined, UpOutlined } from '@ant-design/icons';
|
||||
import { api, decodeQueryValueList, encodeQueryValueList } from './api';
|
||||
import { MetricTable, MetricCard, DefectBreakdown, DefectParetoPanel, SectionHeading, RecordsDrawer, TrendChart, fullYearTrend, queryFromLocation } from './QueryPage';
|
||||
import { MetricTable, MetricCard, DefectBreakdown, DefectParetoPanel, SectionHeading, RecordsDrawer, TrendChart, TrendTable, fullYearTrend, queryFromLocation } from './QueryPage';
|
||||
import { StageSourceFilters } from './StageSourceFilters';
|
||||
import { stageProductQuery, sortStageRowsByTotalWeight } from './stageProductQuery';
|
||||
import { usePageCache } from './pageCache';
|
||||
@@ -12,6 +12,8 @@ import { defaultQueryMonth, previousCompleteMonth, previousCompleteQuarter } fro
|
||||
import { readableSelectPopup } from './readableSelectPopup';
|
||||
import { readableMetricFormula } from './publicDataDisplay';
|
||||
import type { MetricRow, MetricsResponse, OptionsResponse, PeriodKind, QueryParams, SourceColumnField, SourceColumnFilter, Stage } from './types';
|
||||
import { QueryTrendPanel, QueryTablePanel } from './QueryPanels';
|
||||
import { selectTrendPeriod as nextTrendPeriod } from './trendPeriodSelection';
|
||||
import './stage-product.css';
|
||||
|
||||
const weight=(v:number|null|undefined)=>typeof v==='number'?v.toLocaleString('zh-CN',{maximumFractionDigits:2}):'—';
|
||||
@@ -29,6 +31,7 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
|
||||
const [applied,setApplied]=useState<QueryParams|null>(null);const [revision,setRevision]=useState(0);const [response,setResponse]=useState<{key:string;value:MetricsResponse}|null>(null);const [loading,setLoading]=useState(false);const [failure,setFailure]=useState<{key:string;message:string}|null>(null);
|
||||
const [defectDisplay,setDefectDisplay]=useState<'weight'|'rate'>('weight');
|
||||
const [fullFields,setFullFields]=useState(true);const [rateBasis,setRateBasis]=useState<'original'|'withoutHeadquartersScrap'>('original');const [basisOpen,setBasisOpen]=useState(false);const [trendMode,setTrendMode]=useState<'production'|'defects'|'data'>('production');
|
||||
const [drilledProduct,setDrilledProduct]=useState('');const drillParentSearch=useRef('');
|
||||
const [trendGranularity,setTrendGranularity]=useState<'month'|'quarter'|'year'>('month');
|
||||
const [trendResponse,setTrendResponse]=useState<{key:string;value:MetricsResponse}|null>(null);const [trendError,setTrendError]=useState('');const [trendLoading,setTrendLoading]=useState(false);
|
||||
const [recordVisible,setRecordVisible]=useState(false);const [records,setRecords]=useState<{row:MetricRow|null;query:QueryParams}|null>(null);const exporter=useRef<{exportExcel:()=>Promise<void>}>(null);const [exporting,setExporting]=useState(false);
|
||||
@@ -41,7 +44,10 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
|
||||
},[onUnauthorized]);
|
||||
useEffect(()=>{if(active)void loadSupport();},[active,refreshKey,loadSupport]);
|
||||
const fields=useMemo(()=>catalog?.sourceFields.filter(field=>field.type==='source_value'&&field.stages.includes(stage))||[],[catalog,stage]);
|
||||
const draft=useMemo(()=>stageProductQuery({year,...(period==='month'?{month}:period==='quarter'?{quarter}:{}),department:encodeQueryValueList(department),group:encodeQueryValueList(group),product:encodeQueryValueList(product),projectGroup:encodeQueryValueList(projectGroup),productSearch:appliedSearch.trim()||undefined,includeUnassigned,view:'product',trendGranularity:'month',releaseId:catalog?.releaseId},stage,sourceFilters),[year,period,month,quarter,department,group,product,projectGroup,appliedSearch,includeUnassigned,catalog,stage,sourceFilters]);
|
||||
const exactProductSearch=useMemo(()=>(options?.products||[]).find(name=>name.trim().toLocaleLowerCase()===appliedSearch.trim().toLocaleLowerCase())||'', [options,appliedSearch]);
|
||||
const queryProducts=useMemo(()=>drilledProduct?[drilledProduct]:exactProductSearch?product.length&&!product.includes(exactProductSearch)?['__codex_no_product_search_match__']:[exactProductSearch]:product,[drilledProduct,exactProductSearch,product]);
|
||||
useEffect(()=>{setDrilledProduct('');},[year,department,group,product,projectGroup,sourceFilters]);
|
||||
const draft=useMemo(()=>stageProductQuery({year,...(period==='month'?{month}:period==='quarter'?{quarter}:{}),department:encodeQueryValueList(department),group:encodeQueryValueList(group),product:encodeQueryValueList(queryProducts),projectGroup:encodeQueryValueList(projectGroup),productSearch:drilledProduct?undefined:appliedSearch.trim()||undefined,includeUnassigned,view:'product',trendGranularity:'month',releaseId:catalog?.releaseId},stage,sourceFilters),[year,period,month,quarter,department,group,queryProducts,drilledProduct,projectGroup,appliedSearch,includeUnassigned,catalog,stage,sourceFilters]);
|
||||
// Apply organizational/source filters directly, like the other query pages. Product text search keeps its explicit submit.
|
||||
useEffect(()=>{if(active&&catalog&&!supportLoading&&!supportError)setApplied(previous=>JSON.stringify(previous)===JSON.stringify(draft)?previous:draft);},[active,catalog,draft,supportLoading,supportError]);
|
||||
const queryKey=JSON.stringify({query:applied,revision});const current=response?.key===queryKey?response.value:null;const error=failure?.key===queryKey?failure.message:'';
|
||||
@@ -59,20 +65,27 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
|
||||
const selectedTrendPeriod=trendGranularity==='month'&&applied?.month
|
||||
? `${applied.year}-${String(applied.month).padStart(2,'0')}`
|
||||
: trendGranularity==='quarter'&&applied?.quarter ? `${applied.year}-Q${applied.quarter}` : undefined;
|
||||
const selectTrendPeriod=(value:number|string)=>{if(!applied)return;automaticPeriod.current=false;const text=String(value);if(trendGranularity==='year'){const selectedYear=Number(text);if(Number.isFinite(selectedYear)){setYear(selectedYear);setPeriod('year');setApplied({...applied,year:selectedYear,month:undefined,quarter:undefined});}}else if(trendGranularity==='quarter'){const selectedQuarter=Number(text.replace(/^.*Q/,''));if(selectedQuarter>=1&&selectedQuarter<=4){setQuarter(selectedQuarter);setPeriod('quarter');setApplied({...applied,quarter:selectedQuarter,month:undefined});}}else{const selectedMonth=Number(text.slice(-2));if(selectedMonth>=1&&selectedMonth<=12){setMonth(selectedMonth);setPeriod('month');setApplied({...applied,month:selectedMonth,quarter:undefined});}}setRevision(v=>v+1);};
|
||||
const selectTrendPeriod=(value:number|string)=>{automaticPeriod.current=false;const next=nextTrendPeriod(value,{period,year,month,quarter});setYear(next.year);setMonth(next.month);setQuarter(next.quarter);setPeriod(next.period);};
|
||||
const dirty=!!applied&&JSON.stringify(draft)!==JSON.stringify(applied);
|
||||
const queryBusy=supportLoading||loading||(!error&&!supportError&&(dirty||!current));
|
||||
const queryFailed=!!(error||supportError);
|
||||
const submit=()=>{automaticPeriod.current=false;const value=search.trim();setAppliedSearch(value);setApplied(stageProductQuery({...draft,productSearch:value||undefined},stage,sourceFilters));setRevision(v=>v+1);};
|
||||
const reset=()=>{automaticPeriod.current=false;const previous=defaultQueryMonth(options);setYear(previous.year);setMonth(previous.month);setQuarter(previousCompleteQuarter().quarter);setPeriod('month');setTrendGranularity('month');setDepartment([]);setGroup([]);setProduct([]);setProjectGroup([]);setSourceFilters([]);setSearch('');setAppliedSearch('');setApplied(stageProductQuery({year:previous.year,month:previous.month,includeUnassigned,view:'product',trendGranularity:'month',releaseId:catalog?.releaseId},stage,[]));setRevision(v=>v+1);};
|
||||
const submit=()=>{automaticPeriod.current=false;setAppliedSearch(search.trim());setDrilledProduct('');setRevision(v=>v+1);};
|
||||
const setTrendObject=(value?:string)=>{const selected=value||'';setDrilledProduct('');setSearch(selected);setAppliedSearch(selected);};
|
||||
const returnToProducts=()=>{setDrilledProduct('');setSearch(drillParentSearch.current);setAppliedSearch(drillParentSearch.current);setTrendMode('production');};
|
||||
const reset=()=>{automaticPeriod.current=false;const previous=defaultQueryMonth(options);setYear(previous.year);setMonth(previous.month);setQuarter(previousCompleteQuarter().quarter);setPeriod('month');setTrendGranularity('month');setDepartment([]);setGroup([]);setProduct([]);setProjectGroup([]);setSourceFilters([]);setSearch('');setAppliedSearch('');setDrilledProduct('');setApplied(stageProductQuery({year:previous.year,month:previous.month,includeUnassigned,view:'product',trendGranularity:'month',releaseId:catalog?.releaseId},stage,[]));setRevision(v=>v+1);};
|
||||
const groups=(options?.groups||[]).filter(name=>!department.length||department.includes(options?.groupDepartments?.[name]||''));
|
||||
const paths=options?.organizationPaths||[];const products=department.length||group.length?[...new Set(paths.filter(path=>(!department.length||department.includes(path.department||''))&&(!group.length||group.includes(path.group||''))).map(path=>path.product).filter((v):v is string=>!!v))]:options?.products||[];
|
||||
const trendOptions=useMemo(()=>[...products.map(value=>({label:value,value})),...(drilledProduct==='__UNASSIGNED__'?[{label:'未分类',value:drilledProduct}]:[])],[products,drilledProduct]);
|
||||
const trendObject=drilledProduct||exactProductSearch;
|
||||
const drilledLabel=drilledProduct==='__UNASSIGNED__'?'未分类':drilledProduct;
|
||||
const select=(name:string,value:string[],choices:string[],change:(v:string[])=>void,extra=false)=><label className={`query-field ${extra?'query-extra-field':'query-primary-field'}`}><span>{name}</span><Select {...readableSelectPopup} mode="multiple" allowClear showSearch optionFilterProp="label" aria-label={name} placeholder="全部" maxTagCount="responsive" value={value} options={[...new Set([...choices,...value])].map(v=>({label:v==='__UNASSIGNED__'?'未分类':v,value:v}))} onChange={change}/></label>;
|
||||
const moreFilterCount=(projectGroup.length?1:0)+sourceFilters.length;
|
||||
const moreFilterSummary=[projectGroup.length?`项目组:${projectGroup.map(v=>v==='__UNASSIGNED__'?'未分类':v).join('、')}`:'',...sourceFilters.map(rule=>fields.find(field=>field.key===rule.field)?.label||rule.field)].filter(Boolean).join(';');
|
||||
const displayed = useRetainedResult(current && applied ? { data: current, query: applied } : null);
|
||||
const displayedQuery = displayed?.query || applied;
|
||||
const sortedRows=useMemo(()=>sortStageRowsByTotalWeight(displayed?.data.rows||[],stage),[displayed?.data,stage]);
|
||||
const trendRefreshing=trendLoading||!current||trendResponse?.key!==trendKey;
|
||||
const tableReady=!!current&&(!drilledProduct||!trendRefreshing);
|
||||
const table=useRetainedResult(tableReady&&applied?{rows:drilledProduct?visibleTrend:sortedRows,query:applied,drilledProduct,period:drilledProduct?'year' as const:applied.month?'month' as const:applied.quarter?'quarter' as const:'year' as const}:null);
|
||||
const summary=displayed?.data.summary[stage];const stageRate=stage==='bright'&&rateBasis==='withoutHeadquartersScrap'?summary?.rateWithoutHeadquartersScrap:summary?.rate;
|
||||
const openDetail=(row:MetricRow|null,_stage:Stage,selectedMonth?:number)=>{if(!applied||!current?.release)return;setRecordVisible(true);setRecords({row,query:{...applied,releaseId:current.release.id,...(row&&selectedMonth==null?{product:row.product||'__UNASSIGNED__'}:{}),...(selectedMonth?{month:selectedMonth,quarter:undefined}: {})}});};
|
||||
const runExport=async()=>{setExporting(true);try{await exporter.current?.exportExcel();}catch(e){message.error(e instanceof Error?e.message:'导出失败');}finally{setExporting(false);}};
|
||||
@@ -105,17 +118,40 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
|
||||
<MetricCard label="报废重量" value={`${weight(queryScrapWeight(summary,stage,rateBasis))} kg`} onClick={()=>openDetail(null,stage)}/>
|
||||
<MetricCard label="总重量" value={`${weight(summary?.totalWeight)} kg`} onClick={()=>openDetail(null,stage)}/>
|
||||
</section>
|
||||
<div className="analysis-stack"><section className="panel section-panel trend-panel"><div className="section-heading-row trend-heading-row"><SectionHeading title={`${trendGranularity==='year'?'年度':trendGranularity==='quarter'?'季度':'月度'}变化趋势`} subtitle={`${year} 年 · 当前${label}筛选`}/><Segmented value={trendMode} aria-label="趋势视图" options={[{label:'合格率与产量',value:'production'},{label:'不良率',value:'defects'},{label:`${trendGranularity==='year'?'年度':trendGranularity==='quarter'?'季度':'月度'}数据`,value:'data'}]} onChange={v=>setTrendMode(v as typeof trendMode)}/></div><div className="trend-controls">{trendMode==='data'&&<Segmented value={defectDisplay} aria-label="趋势不良显示方式" options={[{label:'不良重量',value:'weight'},{label:'不良率',value:'rate'}]} onChange={v=>setDefectDisplay(v as typeof defectDisplay)}/>}<label className="query-field trend-granularity"><span>趋势粒度</span><Select {...readableSelectPopup} value={trendGranularity} options={[{label:'按月',value:'month'},{label:'按季度',value:'quarter'},{label:'按年度',value:'year'}]} onChange={setTrendGranularity} aria-label="趋势粒度"/></label></div>{trendError&&<Alert type="warning" message="趋势读取失败" description={trendError}/>}<div className="trend-chart-shell" aria-busy={trendLoading}>{trendMode==='data'?<MetricTable exportFilename={`${label}月度趋势-${year}`} rows={displayedTrend} view="overall" layoutView="product" period="year" month={month} quarter={quarter} fullFields={fullFields} defectDisplay={defectDisplay} rateBasis={rateBasis} onlyStage={stage} onDetail={openDetail} onBasis={()=>setBasisOpen(true)} onDrilldown={()=>{}}/>:<TrendChart rows={displayedTrend} mode={trendMode} stage={stage} onlyStage={stage} rateBasis={rateBasis} targetRate={null} selectedPeriod={selectedTrendPeriod} onMonth={selectTrendPeriod}/>}{trendLoading&&<span className="trend-refresh-indicator"><Spin size="small"/>正在更新趋势</span>}</div>{trendMode!=='data'&&<div className="chart-footnote"><span>指标由来源分量汇总,使用当前生效公式。</span></div>}</section>
|
||||
<section className="panel section-panel table-panel"><div className="section-heading-row"><SectionHeading title={`${label}汇总`} subtitle="重量 / kg 合格率 / %"/><div className="table-tools"><Input aria-label="搜索产品名称" placeholder="输入产品名称关键词" allowClear value={search} onChange={e=>setSearch(e.target.value)} onPressEnter={submit}/><Button onClick={submit} disabled={!catalog||!!supportError}>搜索</Button><Segmented value={fullFields?'full':'key'} aria-label="字段显示" options={[{label:'关键指标',value:'key'},{label:'完整字段',value:'full'}]} onChange={v=>setFullFields(v==='full')}/><Segmented value={defectDisplay} aria-label="不良显示方式" options={[{label:'不良重量',value:'weight'},{label:'不良率',value:'rate'}]} onChange={v=>setDefectDisplay(v as typeof defectDisplay)}/><Button type="primary" className="query-export-button" icon={<DownloadOutlined/>} aria-label="Excel导出" loading={exporting} disabled={!current||loading} onClick={()=>void runExport()}>Excel导出</Button></div></div>
|
||||
<SmoothTableFrame busy={loading||!current} blocked={!current||loading}><MetricTable ref={exporter} exportFilename={`${label}产品汇总-${year}`} rows={sortedRows} view="product" period={displayedQuery?.month?'month':displayedQuery?.quarter?'quarter':'year'} month={displayedQuery?.month||month} quarter={displayedQuery?.quarter||quarter} fullFields={fullFields} defectDisplay={defectDisplay} rateBasis={rateBasis} onlyStage={stage} onDetail={openDetail} onBasis={()=>setBasisOpen(true)} onDrilldown={row=>{setProduct([row.product||'__UNASSIGNED__']);setSearch('');setAppliedSearch('');setApplied({...applied!,product:row.product||'__UNASSIGNED__',productSearch:undefined});setRevision(v=>v+1);}}/></SmoothTableFrame>
|
||||
</section>
|
||||
<div className="analysis-stack">
|
||||
<QueryTrendPanel mode={trendMode} onMode={setTrendMode} granularity={trendGranularity} onGranularity={setTrendGranularity}
|
||||
defectDisplay={defectDisplay} onDefectDisplay={setDefectDisplay} object={trendObject} onObject={setTrendObject} objects={trendOptions} scopeName="产品">
|
||||
{trendError&&<Alert type="warning" showIcon message="趋势读取失败" description={trendError} action={<Button onClick={()=>setRevision(v=>v+1)}>重试</Button>}/>}
|
||||
<div className="trend-chart-shell" aria-busy={trendRefreshing} inert={trendRefreshing||!!trendError}>
|
||||
{trendMode==='data'
|
||||
? <TrendTable rows={displayedTrend} defectDisplay={defectDisplay} rateBasis={rateBasis} onlyStage={stage} onMonth={selectTrendPeriod}/>
|
||||
: <TrendChart rows={displayedTrend} mode={trendMode} stage={stage} onlyStage={stage} rateBasis={rateBasis} targetRate={null} selectedPeriod={selectedTrendPeriod} onMonth={selectTrendPeriod}/>}
|
||||
{trendRefreshing&&<span className="trend-refresh-indicator"><Spin size="small"/>正在更新趋势</span>}
|
||||
</div>
|
||||
</QueryTrendPanel>
|
||||
<QueryTablePanel heading={<SectionHeading title={table?.drilledProduct?'产品月度质量数据':`${label}产品质量汇总`} subtitle={table?.drilledProduct?`${table.query.year} 年 · ${table.drilledProduct==='__UNASSIGNED__'?'未分类':table.drilledProduct} · 重量 / kg 合格率 / %`:'重量 / kg 合格率 / %'}/>}
|
||||
busy={queryBusy||!tableReady} search={drilledLabel||search} onSearchChange={setSearch} onSearch={submit} searchDisabled={!!drilledProduct} searchUnavailable={!catalog||!!supportError}
|
||||
fullFields={fullFields} onFullFields={setFullFields} defectDisplay={defectDisplay} onDefectDisplay={setDefectDisplay}
|
||||
returnControls={drilledProduct&&<Button className="query-return-button" icon={<ArrowLeftOutlined/>} onClick={returnToProducts}>返回上一级</Button>}
|
||||
exporting={exporting} exportDisabled={!current||loading||!tableReady||!table?.rows.length} onExport={()=>void runExport()}>
|
||||
<SmoothTableFrame busy={queryBusy||!tableReady} blocked={queryBusy||!tableReady}>
|
||||
<MetricTable ref={exporter} exportFilename={`${table?.drilledProduct||label}产品汇总-${table?.query.year||year}-${fullFields?'完整字段':'关键指标'}`}
|
||||
rows={table?.rows||[]} view={table?.drilledProduct?'overall':'product'} layoutView="product" pageSizeOverride={table?.drilledProduct?12:undefined}
|
||||
period={table?.period||period} month={table?.query.month||month} quarter={table?.query.quarter||quarter}
|
||||
fullFields={fullFields} defectDisplay={defectDisplay} rateBasis={rateBasis} onlyStage={stage} onDetail={openDetail} onBasis={()=>setBasisOpen(true)}
|
||||
emptyText={queryBusy?'正在更新数据…':error?'查询失败,暂无可展示结果':'当前条件下暂无数据'}
|
||||
onDrilldown={row=>{if(drilledProduct)return;const selected=row.product||'__UNASSIGNED__';drillParentSearch.current=appliedSearch;setDrilledProduct(selected);setTrendGranularity('month');setTrendMode('production');}}/>
|
||||
</SmoothTableFrame>
|
||||
</QueryTablePanel>
|
||||
<section className="panel section-panel defects-panel" aria-busy={loading||!current}>
|
||||
<div className="section-heading-row"><SectionHeading title="不良具体构成" subtitle={`${label} · 占比为分类报废内占比;废率为该类重量 ÷ 总重量`}/></div>
|
||||
<div className="section-heading-row"><SectionHeading title="不良具体构成"/></div>
|
||||
<div className="stage-defect-comparison">
|
||||
<section className="defect-stage-column" inert={!current||loading} aria-label={`${label}不良构成`}>
|
||||
<h3 className={`defect-stage-title ${stage}`}><i/>{label}</h3>
|
||||
{displayed?.data.defects[stage]?.length ? <DefectBreakdown items={displayed.data.defects[stage]} stage={stage} totalWeight={summary?.totalWeight} maximum={Math.max(0,...displayed.data.defects[stage].map(item=>item.weight||0))} onDetail={()=>openDetail(null,stage)}/> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description={loading?'正在查询不良数据…':'当前条件下暂无不良分类数据'}/>}
|
||||
</section>
|
||||
{displayed&&<DefectParetoPanel releaseId={displayed.data.release?.id} query={displayed.query} pending={!current||loading} refreshKey={revision} onlyStage={stage} externalScrapWeight={stage==='black'?displayed.data.defects.black.find(item=>item.name==='外废')?.weight:undefined} onUnauthorized={onUnauthorized}/>}
|
||||
</div>
|
||||
</section></div>
|
||||
<Modal open={basisOpen} title={`${label}计算口径`} onCancel={()=>setBasisOpen(false)} footer={<Button onClick={()=>setBasisOpen(false)}>关闭</Button>}><p>{readableMetricFormula((current?.context.metricFormulaDescriptions as Record<string,unknown>|undefined)?.[formulaKey])}</p></Modal>
|
||||
{records&&<RecordsDrawer key={JSON.stringify(records)} open={recordVisible} row={records.row} query={records.query} stage={stage} lockedStage onStage={()=>{}} onClose={()=>setRecordVisible(false)} onUnauthorized={onUnauthorized}/>}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
.query-page { --defect-black: #718797; --defect-black-2: #A9BAC5; --defect-black-3: #D5E0E6; --defect-bright: var(--query-bright,var(--blue)); }
|
||||
:root[data-workspace-theme='dark'] .query-page { --defect-black: #B9BEC8; }
|
||||
.query-page .defect-stage-title.black { color: var(--defect-black); }
|
||||
.query-page .defect-stage-title.bright { color: var(--defect-bright); }
|
||||
.query-page .defect-stage-title.black i,.query-page .defect-stage-title.bright i { background: currentColor; }
|
||||
.defect-composition { position: relative; min-width: 0; padding-top: 2px; }
|
||||
.defect-composition-unit { font-size: var(--font-note); line-height: 18px; color: var(--muted-ink); }
|
||||
.defect-composition-plot { width: 100%; min-width: 0; height: 94px; }
|
||||
.defect-composition-empty { position: absolute; inset: 23px 0 auto; height: 65px; display: flex; align-items: center; justify-content: center; color: var(--muted-ink); font-size: var(--font-control); }
|
||||
.defect-composition-table { width: 100%; table-layout: fixed; border-collapse: collapse; margin: 8px 0 0; font-size: var(--font-table); }
|
||||
.defect-composition-table th { width: 25%; padding: 0 4px; text-align: center; height: 30px; font-size: var(--font-note); font-weight: 500; color: var(--ink); }
|
||||
.defect-composition-table td { height: 37px; padding: 0 4px; text-align: center; border-top: 1px solid color-mix(in srgb,var(--line) 65%,transparent); color: var(--muted-ink); font-family: var(--font-numeric); font-variant-numeric: tabular-nums; cursor: pointer; }
|
||||
.defect-composition-table td.defect-composition-weight { color: var(--ink); font-weight: 600; }
|
||||
.defect-composition-table tr:hover td { background: var(--hover); }
|
||||
.defect-composition-category { display: inline-grid; grid-template-columns: 9px minmax(0,1fr); align-items: center; gap: 9px; width: calc(3em + 18px); max-width: 100%; padding: 5px 0; text-align: center; color: var(--ink); font: var(--font-table) var(--font-ui); background: transparent; border: 0; cursor: pointer; }
|
||||
.defect-composition-category i { flex: 0 0 9px; height: 9px; background: var(--blue); }
|
||||
.defect-composition-category:focus-visible { outline: 2px solid var(--blue); outline-offset: 3px; }
|
||||
.defect-stage-grid:has(.defect-composition) > .defect-stage-column { padding: 0 16px 14px; }
|
||||
.defect-stage-grid:has(.defect-composition) .defect-stage-title { padding: 14px 1px 10px; }
|
||||
@media(max-width:760px) { :is(.defect-stage-grid,.stage-defect-comparison):has(.defect-composition) > .defect-stage-column { padding: 0 12px 12px; } }
|
||||
@@ -11,4 +11,12 @@
|
||||
.stage-metric-strip { grid-template-columns: repeat(2,minmax(0,1fr)); }
|
||||
}
|
||||
|
||||
.stage-product-page .defects-panel > .defect-stage-column { padding: 14px; }
|
||||
.stage-defect-comparison { display: grid; grid-template-columns: minmax(300px,1fr) minmax(0,2fr); border-top: 1px solid var(--line); }
|
||||
.stage-defect-comparison > .defect-stage-column { padding: 0 16px 14px; }
|
||||
.stage-defect-comparison .defect-stage-title { min-height: 40px; padding: 10px 0; }
|
||||
.stage-defect-comparison > .defect-pareto-section { min-width: 0; border-top: 0; border-left: 1px solid var(--line); padding: 0 12px 10px; }
|
||||
.stage-defect-comparison .defect-pareto-chart { height: 360px; }
|
||||
@media(max-width:1000px) {
|
||||
.stage-defect-comparison { grid-template-columns: 1fr; }
|
||||
.stage-defect-comparison > .defect-pareto-section { border-left: 0; border-top: 1px solid var(--line); }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import type { PeriodKind } from './types';
|
||||
|
||||
type PeriodSelection = { period: PeriodKind; year: number; month: number; quarter: number };
|
||||
|
||||
export function selectTrendPeriod(value: number | string, current: PeriodSelection): PeriodSelection {
|
||||
const raw = String(value);
|
||||
const quarterly = raw.match(/^(\d{4})-Q([1-4])$/);
|
||||
const monthly = raw.match(/^(\d{4})-(\d{1,2})$/);
|
||||
if (quarterly) {
|
||||
const year = Number(quarterly[1]), quarter = Number(quarterly[2]);
|
||||
return { ...current, year, quarter, period: current.period === 'quarter' && current.year === year && current.quarter === quarter ? 'year' : 'quarter' };
|
||||
}
|
||||
if (monthly) {
|
||||
const year = Number(monthly[1]), month = Number(monthly[2]);
|
||||
if (month < 1 || month > 12) return current;
|
||||
return { ...current, year, month, period: current.period === 'month' && current.year === year && current.month === month ? 'year' : 'month' };
|
||||
}
|
||||
if (/^\d{4}$/.test(raw)) return { ...current, year: Number(raw), period: 'year' };
|
||||
const month = Number(raw.match(/\d{1,2}/)?.[0]);
|
||||
return Number.isInteger(month) && month >= 1 && month <= 12
|
||||
? { ...current, month, period: current.period === 'month' && current.month === month ? 'year' : 'month' }
|
||||
: current;
|
||||
}
|
||||
Reference in New Issue
Block a user