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;
+19 -13
View File
@@ -11,6 +11,8 @@ import { StageSourceFilters } from './StageSourceFilters';
import { SalesOrderTypeSelect } from './ExtraQueryFilters';
import { salesOrderTypeSelection } from './salesOrderTypes';
import { stageProductQuery, sortStageRowsByTotalWeight } from './stageProductQuery';
import { freezeSourceRecordsQuery } from './sourceRecordsContext';
import { useDefectDrilldown } from './useDefectDrilldown';
import { usePageCache } from './pageCache';
import { useDelayedIndicator } from './useDelayedBusy';
import { defaultQueryMonth, previousCompleteMonth, previousCompleteQuarter } from './periodDefaults';
@@ -28,8 +30,8 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
const {message}=App.useApp();const {active,initialSearch,refreshKey,onLocationChange,currentReleaseId}=usePageCache();
const [initial]=useState(()=>queryFromLocation(initialSearch));const defaults=previousCompleteMonth();
const automaticPeriod=useRef(!initial.year&&!initial.month&&!initial.quarter);
const [period,setPeriod]=useState<PeriodKind>(initial.quarter?'quarter':initial.month?'month':initial.year?'year':'month');
const [year,setYear]=useState(initial.year||defaults.year);const [month,setMonth]=useState(initial.month||defaults.month);const [quarter,setQuarter]=useState(initial.quarter||previousCompleteQuarter().quarter);
const [period,setPeriod]=useState<PeriodKind>(initial.quarter?'quarter':initial.month?'month':'year');
const [year,setYear]=useState(initial.year||(period==='month'?defaults.year:period==='quarter'?previousCompleteQuarter().year:new Date().getFullYear()));const [month,setMonth]=useState(initial.month||defaults.month);const [quarter,setQuarter]=useState(initial.quarter||previousCompleteQuarter().quarter);
const [department,setDepartment]=useState(()=>decodeQueryValueList(initial.department));const [group,setGroup]=useState(()=>decodeQueryValueList(initial.group));const [product,setProduct]=useState(()=>decodeQueryValueList(initial.product));const [projectGroup,setProjectGroup]=useState(()=>decodeQueryValueList(initial.projectGroup));
const [sourceFilters,setSourceFilters]=useState<SourceColumnFilter[]>(initial.columnFilters||[]);const [search,setSearch]=useState(initial.productSearch||'');const [appliedSearch,setAppliedSearch]=useState(initial.productSearch||'');const includeUnassigned=true;
const [moreFiltersOpen,setMoreFiltersOpen]=useState(false);
@@ -49,7 +51,7 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
const loadSupport=useCallback(async()=>{
const generation=++supportGeneration.current;supportController.current?.abort();const controller=new AbortController();supportController.current=controller;
setSupportLoading(true);setSupportError('');
try{const [choices,source,filterFields]=await Promise.all([api.options(controller.signal),api.sourceColumnCatalog(initial.releaseId||currentReleaseId||undefined,controller.signal),api.filterFields(false,controller.signal)]);if(generation!==supportGeneration.current)return;if(automaticPeriod.current){const available=defaultQueryMonth(choices);setYear(available.year);setMonth(available.month);automaticPeriod.current=false;}setOptions(choices);setCatalog(source);setExtraFields(filterFields.filter(field=>field.key==='salesOrderType'));}
try{const [choices,source,filterFields]=await Promise.all([api.options(controller.signal),api.sourceColumnCatalog(initial.releaseId||currentReleaseId||undefined,controller.signal),api.filterFields(false,controller.signal)]);if(generation!==supportGeneration.current)return;if(automaticPeriod.current){const available=defaultQueryMonth(choices);setMonth(available.month);automaticPeriod.current=false;}setOptions(choices);setCatalog(source);setExtraFields(filterFields.filter(field=>field.key==='salesOrderType'));}
catch(error){if(generation===supportGeneration.current&&!onUnauthorized(error))setSupportError(error instanceof Error?error.message:'查询条件读取失败');}
finally{if(generation===supportGeneration.current)setSupportLoading(false);}
},[onUnauthorized,initial.releaseId,currentReleaseId]);
@@ -57,7 +59,7 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
const fields=useMemo(()=>catalog?.sourceFields.filter(field=>field.type==='source_value'&&field.stages.includes(stage))||[],[catalog,stage]);
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,extraFilters]);
useEffect(()=>{setDrilledProduct('');},[department,group,product,projectGroup,sourceFilters,extraFilters]);
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,extraFilters,view:'product',trendGranularity:'month',releaseId:initial.releaseId||currentReleaseId||catalog?.releaseId},stage,sourceFilters),[year,period,month,quarter,department,group,queryProducts,drilledProduct,projectGroup,appliedSearch,includeUnassigned,catalog,stage,sourceFilters,extraFilters,initial.releaseId,currentReleaseId]);
// 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]);
@@ -82,8 +84,8 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
const queryFailed=!!(error||supportError);
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([]);setExtraFilters({});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 returnToProducts=()=>{setDrilledProduct('');setSearch(drillParentSearch.current);setAppliedSearch(drillParentSearch.current);if(trendMode!=='defects')setTrendMode('production');};
const reset=()=>{automaticPeriod.current=false;const previous=defaultQueryMonth(options);const currentYear=new Date().getFullYear();setYear(currentYear);setMonth(previous.month);setQuarter(previousCompleteQuarter().quarter);setPeriod('year');setTrendGranularity('month');setDepartment([]);setGroup([]);setProduct([]);setProjectGroup([]);setSourceFilters([]);setExtraFilters({});setSearch('');setAppliedSearch('');setDrilledProduct('');setApplied(stageProductQuery({year:currentYear,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]);
@@ -98,9 +100,12 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
const trendRefreshing=!trendError&&(trendLoading||trendResponse?.key!==trendKey);
const showTrendLoading=useDelayedIndicator(trendRefreshing);
const tableReady=!!current&&(!drilledProduct||(trendResponse?.key===trendKey&&!trendLoading&&!trendError));
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 table=useRetainedResult(tableReady&&applied?{rows:drilledProduct?visibleTrend:sortedRows,query:applied,drilledProduct,granularity:trendGranularity,period:drilledProduct?'year' as const:applied.month?'month' as const:applied.quarter?'quarter' as const:'year' as const}:null);
const defectDrill=useDefectDrilldown({active,mode:trendMode,stage,query:{...(applied||draft),releaseId:current?.release?.id||applied?.releaseId},trendQuery:trendQuery||draft,
tableQuery:drilledProduct?(trendQuery||draft):(applied||draft),tableDimension:drilledProduct?'period':'product',tableGranularity:trendGranularity,
refreshKey:JSON.stringify([refreshKey,revision]),onUnauthorized,display:defectDisplay,onDisplay:setDefectDisplay});
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 openDetail=(row:MetricRow|null,_stage:Stage,selectedMonth?:number)=>{if(!applied||!current?.release)return;setRecordVisible(true);setRecords({row,query:freezeSourceRecordsQuery(applied,current.release.id,drilledProduct?'overall':'product',row,selectedMonth)});};
const runExport=async()=>{setExporting(true);try{await exporter.current?.exportExcel();}catch(e){message.error(e instanceof Error?e.message:'导出失败');}finally{setExporting(false);}};
const formulaKey=stage==='black'?'blackRate':rateBasis==='original'?'brightRate':'brightRateWithoutHeadquartersScrap';
return <div className="query-page stage-product-page">
@@ -137,26 +142,27 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
defectDisplay={defectDisplay} onDefectDisplay={setDefectDisplay} fullFields={trendFullFields} onFullFields={setTrendFullFields}
object={trendObject} onObject={setTrendObject} objects={trendOptions} scopeName="产品">
{trendError&&<Alert type="warning" showIcon message={trendResponse?"趋势更新失败,当前显示上次结果":"趋势读取失败"} description={trendResponse?`${trendError};当前范围:${loadedQueryScope(trendResponse.query,decodeQueryValueList)}`:trendError} action={<Button onClick={()=>setTrendRevision(v=>v+1)}>重试</Button>}/>}
{defectDrill.controls}
<div className="trend-chart-shell" aria-busy={trendRefreshing} inert={trendRefreshing||!!trendError}>
{trendMode==='data'
? <TrendTable rows={displayedTrend} defectDisplay={defectDisplay} rateBasis={rateBasis} onlyStage={stage} fullFields={trendFullFields} onMonth={selectTrendPeriod}/>
: <TrendChart rows={displayedTrend} mode={trendMode} stage={stage} onlyStage={stage} rateBasis={rateBasis} targetRate={null} selectedPeriod={selectedTrendPeriod} onMonth={selectTrendPeriod}/>}
: <TrendChart defectDrilldown={trendResponse?.key===trendKey&&!trendLoading&&!trendError?defectDrill.trend:undefined} drillableCategories={defectDrill.categories} onDefect={defectDrill.choose} rows={displayedTrend} mode={trendMode} stage={stage} onlyStage={stage} rateBasis={rateBasis} targetRate={null} selectedPeriod={selectedTrendPeriod} onMonth={selectTrendPeriod}/>}
{showTrendLoading&&<span className="trend-refresh-indicator"><Spin size="small"/>{trendResponse?`正在更新 · 当前显示上次筛选的${loadedQueryScope(trendResponse.query,decodeQueryValueList)}`:'正在读取趋势'}</span>}
</div>
</QueryTrendPanel>
<QueryTablePanel heading={<SectionHeading title={table?.drilledProduct?'产品月度质量数据':`${label}产品质量汇总`} subtitle={table?.drilledProduct?`${table.query.year} 年 · ${table.drilledProduct==='__UNASSIGNED__'?'未分类':table.drilledProduct} · 重量 / kg 合格率 / %`:'重量 / kg 合格率 / %'}/>}
<QueryTablePanel heading={<SectionHeading title={table?.drilledProduct?`产品${table.granularity==='quarter'?'季度':table.granularity==='year'?'年度':'月度'}质量数据`:`${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()}>
exporting={exporting} exportDisabled={!!defectDrill.category&&(!defectDrill.table||defectDrill.pending||!!defectDrill.error)||!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?'完整字段':'关键指标'}`}
<MetricTable defectDrilldown={tableReady&&!queryBusy?defectDrill.table:undefined} ref={exporter} exportFilename={`${table?.drilledProduct||label}产品汇总-${table?.query.year||year}-${fullFields?'完整字段':'关键指标'}`}
paginationScope={JSON.stringify({query:table?.query,drilledProduct:table?.drilledProduct})}
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');}}/>
onDrilldown={row=>{if(drilledProduct)return;const selected=row.product||'__UNASSIGNED__';drillParentSearch.current=appliedSearch;setDrilledProduct(selected);setTrendGranularity('month');if(trendMode!=='defects')setTrendMode('production');}}/>
</SmoothTableFrame>
</QueryTablePanel>
<section className="panel section-panel defects-panel" data-snapshot-module="defects" aria-busy={loading||!current}>
+8
View File
@@ -17,6 +17,8 @@ import type {
SourceColumnField,
Collection,
FineDefectTopResponse,
FineDefectCatalogResponse,
DefectDrilldownResponse,
MetricsResponse,
TrendResponse,
OptionsResponse,
@@ -272,6 +274,12 @@ export const api = {
fineDefectTop(params: Record<string, unknown>, signal?: AbortSignal) {
return queryPost<FineDefectTopResponse>('/api/analysis/defects', params, signal);
},
fineDefectCatalog(params: Record<string, unknown>, signal?: AbortSignal) {
return queryPost<FineDefectCatalogResponse>('/api/analysis/defects', params, signal);
},
defectDrilldown(params: Record<string, unknown>, signal?: AbortSignal) {
return queryPost<DefectDrilldownResponse>('/api/analysis/defects/drilldown', params, signal);
},
records(params: RecordsParams, signal?: AbortSignal) {
return request<RecordsResponse>(`/api/records?${toQuery(params)}`, { signal });
},
+19
View File
@@ -0,0 +1,19 @@
import type { DefectDrilldownResponse, MetricRow, QueryParams, TrendMetricRow } from './types';
export const defectRateLabel = (label: string) => label.endsWith('重量') ? `${label.slice(0,-2)}废率` : `${label}率`;
export function defectScope(query: QueryParams): Record<string, unknown> {
const {view: _view,trendGranularity: _granularity,...scope}=query;
return scope;
}
export function defectGroup(data: DefectDrilldownResponse, row: MetricRow) {
const period=row as TrendMetricRow;
const sourceKey=(row as MetricRow & {sourceMetricKey?:string}).sourceMetricKey??row.key;
const key=data.dimension==='period'?String(period.period??period.month):data.dimension==='overall'?'overall':sourceKey??'__UNASSIGNED__';
return data.groups.find(group=>group.key===key);
}
export function defectCell(data: DefectDrilldownResponse, row: MetricRow, field: string, display: 'weight'|'rate'): number|null {
const group=defectGroup(data,row);
if(field==='parent')return (display==='rate'?group?.parentRate:group?.parentWeight)??null;
const child=group?.children.find(value=>value.key===field);
return (display==='rate'?child?.rate:child?.weight)??null;
}
+113 -17
View File
@@ -1,12 +1,13 @@
import { isValidElement, type Key } from 'react';
import { getStoredWorkspaceThemeId, getWorkspaceTheme, type WorkspaceThemeId } from './ui-themes.ts';
type ExportColumn = { exportRate?: boolean; key?: Key; title?: unknown; children?: readonly ExportColumn[] };
type ExportColumn = { exportRate?: boolean; key?: Key; title?: unknown; width?: string | number; children?: readonly ExportColumn[] };
type ExportValue = string | number | null;
function nodeText(node: unknown): string {
if (typeof node === 'string' || typeof node === 'number') return String(node);
if (Array.isArray(node)) return node.map(nodeText).join('');
if (isValidElement<{ children?: unknown }>(node)) return nodeText(node.props.children);
if (isValidElement<{ children?: unknown }>(node)) return `${node.type === 'small' ? '\n' : ''}${nodeText(node.props.children)}`;
return '';
}
@@ -22,24 +23,119 @@ export function workbookColumns(columns: readonly ExportColumn[], parents: strin
});
}
export async function createMetricWorkbook<T>(columns: readonly ExportColumn[], rows: readonly T[], value: (key: string, row: T) => ExportValue) {
function dataColumns(columns: readonly ExportColumn[]): ExportColumn[] {
return columns.flatMap(column => {
if (column.children) {
const children = dataColumns(column.children);
return children.length ? [{ ...column, children }] : [];
}
return String(column.key ?? '') && column.key !== 'actions' ? [column] : [];
});
}
function mix(foreground: string, background: string, proportion: number): string {
return 'FF' + [1, 3, 5].map(offset => Math.round(
parseInt(foreground.slice(offset, offset + 2), 16) * proportion
+ parseInt(background.slice(offset, offset + 2), 16) * (1 - proportion),
).toString(16).padStart(2, '0')).join('').toUpperCase();
}
// Mirrors the query table's theme tokens and semantic colors. Dark always exports as light.
export function metricWorkbookPalette(themeId: WorkspaceThemeId = 'light') {
const theme = getWorkspaceTheme(themeId === 'dark' ? 'light' : themeId);
return {
ink: mix(theme.ink, theme.surface, 1), surface: mix(theme.surface, theme.surface, 1),
grid: mix(theme.metricGrid, theme.surface, 1), headGrid: mix(theme.metricGridHead, theme.surface, 1),
head: mix(theme.surface, theme.background, .55), alternate: mix(theme.surface, theme.soft, .97),
black: 'FF20252B', bright: mix(theme.primary, theme.surface, 1), combined: mix(theme.teal, theme.surface, 1),
blackHead: mix('#20252B', theme.surface, .07), brightHead: mix(theme.primary, theme.surface, .10),
combinedFill: mix(theme.teal, theme.surface, .05),
};
}
export async function createMetricWorkbook<T>(columns: readonly ExportColumn[], rows: readonly T[], value: (key: string, row: T) => ExportValue, themeId: WorkspaceThemeId = getStoredWorkspaceThemeId()) {
const { default: ExcelJS } = await import('exceljs');
const workbook = new ExcelJS.Workbook();
const sheet = workbook.addWorksheet('质量汇总', { views: [{ state: 'frozen', xSplit: 1, ySplit: 1 }] });
const fields = workbookColumns(columns);
sheet.columns = fields.map(field => ({ header: field.header, key: field.key, width: field.key === 'object' ? 38 : Math.max(18, Math.min(field.header.length * 2, 48)) }));
for (const row of rows) sheet.addRow(fields.map(field => {
const result = value(field.key, row);
return typeof result === 'number' && !Number.isFinite(result) ? null : result;
}));
fields.forEach((field, index) => {
if (field.key !== 'object') sheet.getColumn(index + 1).numFmt = field.rate ? '0.00%' : '#,##0.0';
workbook.creator = '质量数据分析平台';
const tree = dataColumns(columns);
const fields = workbookColumns(tree);
const depth = (items: readonly ExportColumn[]): number => Math.max(1, ...items.map(column => column.children ? 1 + depth(column.children) : 1));
const headerRows = depth(tree);
const palette = metricWorkbookPalette(themeId);
const sheet = workbook.addWorksheet('质量汇总', {
views: [{ state: 'frozen', xSplit: fields.length ? 1 : 0, ySplit: headerRows, showGridLines: false }],
properties: { defaultRowHeight: 26.25 },
pageSetup: { orientation: 'landscape', paperSize: 9, fitToPage: true, fitToWidth: 1, fitToHeight: 0 },
});
sheet.getRow(1).font = { bold: true, color: { argb: 'FFFFFFFF' } };
sheet.getRow(1).fill = { type: 'pattern', pattern: 'solid', fgColor: { argb: 'FF6379DF' } };
sheet.getRow(1).alignment = { vertical: 'middle', wrapText: true };
sheet.getRow(1).height = 36;
sheet.autoFilter = { from: { row: 1, column: 1 }, to: { row: Math.max(1, rows.length + 1), column: fields.length } };
if (!fields.length) return workbook;
const border = (argb: string) => ({
top: { style: 'thin' as const, color: { argb } }, bottom: { style: 'thin' as const, color: { argb } },
left: { style: 'thin' as const, color: { argb } }, right: { style: 'thin' as const, color: { argb } },
});
const solid = (argb: string) => ({ type: 'pattern' as const, pattern: 'solid' as const, fgColor: { argb } });
let leafIndex = 0;
const writeHeaders = (items: readonly ExportColumn[], level: number) => {
for (const column of items) {
const start = leafIndex + 1;
const key = String(column.key ?? '');
const isGroup = !!column.children;
if (column.children) writeHeaders(column.children, level + 1);
else {
leafIndex++;
const pixels = Number(column.width) || (key === 'object' ? 220 : 112);
sheet.getColumn(start).width = Math.max(14, Math.min(60, (pixels - 5) / 7));
sheet.getColumn(start).key = key;
sheet.getColumn(start).numFmt = key === 'object' ? '@' : fields[start - 1].rate ? '0.00%' : '#,##0.0';
}
const lastRow = isGroup ? level : headerRows;
const end = leafIndex;
const black = key === 'stage-black' || key === 'black-rate';
const bright = key === 'stage-bright' || key === 'bright-rate';
const combined = key === 'compositeRate';
const fill = combined ? palette.combinedFill : isGroup && black ? palette.blackHead : isGroup && bright ? palette.brightHead : palette.head;
const color = combined ? palette.combined : black ? palette.black : bright ? palette.bright : palette.ink;
for (let r = level; r <= lastRow; r++) for (let c = start; c <= end; c++) {
const cell = sheet.getCell(r, c);
cell.fill = solid(fill);
cell.border = border(palette.headGrid);
cell.font = { name: '微软雅黑', size: 10.5, bold: true, color: { argb: color } };
cell.alignment = { horizontal: 'center', vertical: 'middle', wrapText: true };
}
if (lastRow > level || end > start) sheet.mergeCells(level, start, lastRow, end);
const label = nodeText(column.title).trim();
sheet.getCell(level, start).value = !isGroup && key !== 'object' && !fields[start - 1].rate ? `${label}\n(kg)` : label;
}
};
writeHeaders(tree, 1);
for (let i = 1; i <= headerRows; i++) {
let lines = 1;
sheet.getRow(i).eachCell(cell => { if (typeof cell.value === 'string') lines = Math.max(lines, cell.value.split('\n').length); });
sheet.getRow(i).height = Math.max(27, lines * 16 + 6);
}
rows.forEach((row, index) => {
const exported = sheet.getRow(headerRows + index + 1);
let lines = 1;
fields.forEach((field, column) => {
const result = value(field.key, row);
const cell = exported.getCell(column + 1);
cell.value = typeof result === 'number' && !Number.isFinite(result) ? null : result;
const combined = field.key === 'compositeRate';
const color = combined ? palette.combined : field.key === 'black-rate' ? palette.black : field.key === 'bright-rate' ? palette.bright : palette.ink;
cell.font = { name: field.key === 'object' ? '微软雅黑' : 'Arial', size: combined ? 11.25 : field.key === 'object' ? 12 : 9.75, bold: field.key === 'object' || field.key.endsWith('-rate') || combined, color: { argb: color } };
cell.fill = solid(combined ? palette.combinedFill : index % 2 ? palette.alternate : palette.surface);
cell.border = border(palette.grid);
cell.alignment = { horizontal: 'center', vertical: 'middle', wrapText: true };
if (typeof result === 'string') {
const width = sheet.getColumn(column + 1).width! - 2;
const textLines = result.split(/\r?\n/).reduce((total, line) => total + Math.max(1, Math.ceil(Array.from(line).reduce((length, char) => length + (/[^\x00-\xff]/.test(char) ? 2 : 1), 0) / width)), 0);
lines = Math.max(lines, textLines);
}
});
exported.height = Math.max(26.25, lines * 16 + 8);
});
sheet.autoFilter = { from: { row: headerRows, column: 1 }, to: { row: headerRows + rows.length, column: fields.length } };
sheet.pageSetup.printTitlesRow = `1:${headerRows}`;
sheet.pageSetup.printArea = `A1:${sheet.getColumn(fields.length).letter}${headerRows + rows.length}`;
return workbook;
}
+4
View File
@@ -53,3 +53,7 @@
.smooth-table-frame { min-width: 0; overflow: clip; transition: height 520ms cubic-bezier(.22,.61,.36,1); }
.animated-metric-text { font-variant-numeric: tabular-nums lining-nums; }
@media (prefers-reduced-motion: reduce) { .smooth-table-frame { transition: none; } }
.defect-drilldown-controls { display:flex;align-items:center;flex-wrap:wrap;gap:8px;margin:0 0 8px;color:var(--ink);font-size:13px; }
.defect-drilldown-controls > .ant-btn {padding-inline:0;}
.defect-drilldown-notice {color:var(--muted-ink);font-size:12px;margin-left:auto;}
+13 -3
View File
@@ -1,14 +1,24 @@
import type { MetricRow, QueryParams, ViewKind } from './types';
import type { MetricRow, QueryParams, TrendMetricRow, ViewKind } from './types';
/** Freeze the clicked metric's filters and release together for every detail/export request. */
export function freezeSourceRecordsQuery(query: QueryParams, releaseId: string, view: ViewKind, row: MetricRow | null, month?: number): QueryParams {
if (!releaseId) throw new Error('指标数据尚未就绪,请重新查询后打开来源明细。');
const frozen = JSON.parse(JSON.stringify(query)) as QueryParams;
frozen.releaseId = releaseId;
if (month) { frozen.month = month; delete frozen.quarter; }
const periodRow = row as TrendMetricRow | null;
const period = view === 'overall' ? String(periodRow?.period ?? periodRow?.month ?? '') : '';
const match = period.match(/^(\d{4})(?:-(?:Q([1-4])|(0?[1-9]|1[0-2])))?$/);
if (match || month) {
delete frozen.month; delete frozen.quarter; delete frozen.monthStart; delete frozen.monthEnd;
if (match) {
frozen.year = Number(match[1]);
if (match[2]) frozen.quarter = Number(match[2]);
if (match[3]) frozen.month = Number(match[3]);
} else if (month) frozen.month = month;
}
if (row && view !== 'overall') {
const dimension = view === 'projectGroup' ? 'projectGroup' : view;
frozen[dimension] = row.key === '__UNASSIGNED__' ? '__UNASSIGNED__' : row[dimension] || row.key;
frozen[dimension] = row.key === '__UNASSIGNED__' || !row[dimension] && !row.key?.trim() ? '__UNASSIGNED__' : row[dimension] || row.key;
}
return frozen;
}
+11
View File
@@ -62,6 +62,17 @@ export interface FineDefectTopResponse {
notice?: string;
}
export interface FineDefectCatalogResponse {
categories: Array<{stage:Stage;category:string;available:boolean;reason?:string}>;
fields: Array<{stage:Stage;key:string;label:string;category:string;available?:boolean}>;
}
export interface DefectDrilldownResponse {
releaseId:string;stage:Stage;category:string;dimension:string;granularity:string;
fields:Array<{key:string;label:string;category:string}>;
groups:Array<{key:string;totalWeight:number|null;parentWeight:number|null;parentRate:number|null;reconciliationStatus:string;
children:Array<{key:string;weight:number|null;rate:number|null}>}>;
}
export interface StageMetric {
qualifiedWeight: number | null;
scrapWeight: number | null;
+56
View File
@@ -0,0 +1,56 @@
import { useEffect, useMemo, useRef, useState } from 'react';
import { Alert, Button, Spin } from 'antd';
import { api } from './api';
import { defectScope } from './defectDrilldown';
import type { DefectDrilldownResponse, FineDefectCatalogResponse, QueryParams, Stage } from './types';
export function useDefectDrilldown({active,mode,stage,query,trendQuery,tableQuery,tableDimension,tableGranularity,onUnauthorized,display,onDisplay,refreshKey=0}:{
refreshKey?:string|number;active:boolean;mode:string;stage:Stage;query:QueryParams;trendQuery:QueryParams;tableQuery:QueryParams;
tableDimension:string;tableGranularity:string;onUnauthorized:(error:unknown)=>boolean;display:'weight'|'rate';onDisplay:(display:'weight'|'rate')=>void;
}) {
const [selection,setSelection]=useState<{stage:Stage;category:string}|null>(null);
const [catalogFailure,setCatalogFailure]=useState('');
const [catalog,setCatalog]=useState<FineDefectCatalogResponse|null>(null);
const [loaded,setLoaded]=useState<{key:string;trend:DefectDrilldownResponse;table:DefectDrilldownResponse}|null>(null);
const [failure,setFailure]=useState<{key:string;message:string}|null>(null);
const [revision,setRevision]=useState(0);
const previousDisplay=useRef(display);
const enabled=active&&mode==='defects';
const category=mode==='defects'&&selection?.stage===stage?selection.category:null;
const catalogKey=JSON.stringify([enabled,stage,defectScope(query),revision,refreshKey]);
const key=JSON.stringify([category,stage,trendQuery,tableQuery,tableDimension,tableGranularity,revision,refreshKey]);
useEffect(()=>{
if(!enabled||!query.releaseId)return;
const controller=new AbortController();setCatalog(null);setCatalogFailure('');
api.fineDefectCatalog({...defectScope(query),stage,mode:'catalog'},controller.signal)
.then(value=>{if(!controller.signal.aborted)setCatalog(value);})
.catch(error=>{if(!controller.signal.aborted&&!onUnauthorized(error))setCatalogFailure(error instanceof Error?error.message:'细分目录读取失败');});
return()=>controller.abort();
},[catalogKey,onUnauthorized]);
useEffect(()=>{
if(selection&&(selection.stage!==stage||mode!=='defects')){setSelection(null);onDisplay(previousDisplay.current);}
},[stage,mode]);
useEffect(()=>{
if(!enabled||!category||!query.releaseId)return;
const controller=new AbortController();setFailure(null);
const common={stage,category,releaseId:query.releaseId};
Promise.all([
api.defectDrilldown({...defectScope(trendQuery),...common,dimension:'period',trendGranularity:trendQuery.trendGranularity||'month'},controller.signal),
api.defectDrilldown({...defectScope(tableQuery),...common,dimension:tableDimension,trendGranularity:tableGranularity},controller.signal),
]).then(([trend,table])=>{
if(controller.signal.aborted)return;
if([trend,table].some(value=>value.releaseId!==query.releaseId||value.stage!==stage||value.category!==category))throw new Error('细分查询范围已变化,请重试。');
setLoaded({key,trend,table});
}).catch(error=>{if(!controller.signal.aborted&&!onUnauthorized(error))setFailure({key,message:error instanceof Error?error.message:'细分查询失败'});});
return()=>controller.abort();
},[enabled,key,onUnauthorized]);
const current=loaded?.key===key?loaded:null;
const error=failure?.key===key?failure.message:'';
const pending=!!category&&!current&&!error;
const categories=useMemo(()=>(catalog?.categories||[]).filter(item=>item.stage===stage&&item.available&&catalog?.fields.some(field=>field.stage===stage&&field.category===item.category&&field.available!==false)).map(item=>item.category),[catalog,stage]);
const choose=(next:string)=>{if(!categories.includes(next))return;if(!category)previousDisplay.current=display;setSelection({stage,category:next});onDisplay('rate');};
const clear=()=>{setSelection(null);onDisplay(previousDisplay.current);};
const incomplete=!!current&&[current.trend,current.table].some(data=>data.groups.some(group=>group.reconciliationStatus!=='RECONCILED'));
const controls=category?<div className="defect-drilldown-controls"><Button type="link" onClick={clear}>全部分类</Button><span>› {category}</span>{pending&&<span><Spin size="small"/> 正在读取细分</span>}{error&&<Alert type="error" showIcon message={error} action={<Button size="small" onClick={()=>setRevision(v=>v+1)}>重试</Button>}/>} {incomplete&&<span className="defect-drilldown-notice">细分来源未完全覆盖分类总量</span>}</div>:catalogFailure&&enabled?<Alert type="error" showIcon message="细分目录读取失败" description={catalogFailure} action={<Button size="small" onClick={()=>setRevision(v=>v+1)}>重试</Button>}/>:null;
return {category,categories,choose,clear,controls,pending,error,trend:current?.trend,table:current?.table};
}