优化:完善查询指标口径、冻结布局与Excel导出

This commit is contained in:
2026-10-31 11:43:40 +08:00
parent 228d55da75
commit 9dbe85c65c
9 changed files with 301 additions and 72 deletions
+15
View File
@@ -36,3 +36,18 @@
- 查询页字号比例追加调整:适当放大筛选与表格、收小指标,四项指标标签统一13px/600;已按用户要求发布并同步源码。(用户反馈字号不协调,具体取值由Agent推断) - 查询页字号比例追加调整:适当放大筛选与表格、收小指标,四项指标标签统一13px/600;已按用户要求发布并同步源码。(用户反馈字号不协调,具体取值由Agent推断)
- 查询页趋势图与柏拉图同步使用页面字体变量:图例与单位使用界面字体、数值刻度使用数字字体,悬浮提示略大;抵消图表局部缩放,保持与表格文字协调。已检查趋势图深浅主题,类型检查与8项相关回归通过;底部预览已补入当前线上全年筛选的真实快照,33个细分字段齐全;已核对不良构成与柏拉图深浅主题,阶段标题14px、分类与数值13px、辅助表头12px,保留原有数据核对提示。2026-10-30 已按用户要求发布。 - 查询页趋势图与柏拉图同步使用页面字体变量:图例与单位使用界面字体、数值刻度使用数字字体,悬浮提示略大;抵消图表局部缩放,保持与表格文字协调。已检查趋势图深浅主题,类型检查与8项相关回归通过;底部预览已补入当前线上全年筛选的真实快照,33个细分字段齐全;已核对不良构成与柏拉图深浅主题,阶段标题14px、分类与数值13px、辅助表头12px,保留原有数据核对提示。2026-10-30 已按用户要求发布。
- 查询表格语义配色:黑片黑色、亮片沿用原黑片的主题蓝色、综合合格率沿用原亮片绿色,覆盖总体/产业部/业务分组/产品/黑片/亮片汇总及月度数据表;顶部指标同步。午夜黑主题中黑片文字以中性浅灰保证对比度。2026-10-31 已按用户要求发布。(用户指定颜色,深色适配由Agent推断)
- 查询字号进一步调整:顶部综合合格率42px(移动端沿用现有自适应),月份及产业部对象16px、表内综合合格率15px、所有查询表头14px/600;布局与其他业务数字字号不变。已检查深浅主题,无指标截断或页面横向溢出,2026-10-31 已按用户要求发布。(用户指定层级,具体取值由Agent推断)
- 查询列顺序:综合合格率移至操作列之前,桌面端两列固定右侧;完整字段模式采用重量112px、阶段合格率96px、不良分类100px,综合合格率120px、操作96px。对象列按月份/组织/产品分别设置;月度趋势数据表综合合格率也置于最右。导出沿用显示列顺序。已实测横向滚动右侧位置不变,2026-10-31 已发布。
- 跨两行查询表头字重700,单行表头600;右侧冻结综合合格率列补充独立左边框,贯穿表头与数据行。深浅主题与左右滚动已验证,2026-10-31 已发布。
- 指标卡片与顶部筛选栏同步冻结,按筛选栏实际高度定位,展开筛选与换行自动更新,并为小屏保留阅读空间。删除“亮片本部报废调整”说明,保留口径切换。
- 关键指标、完整字段与月度数据表的两阶段总重量均置于合格重量之前。黑片总重量增加悬浮规则提示,说明利用料/废品库扣减与过账外废处理;直接展示已发布数据结果。
- 原口径下本部报废列紧随扩散废;去本部报废时隐藏该列,并在卡片、表格、趋势、Excel中统一扣减亮片报废重量。不改来源数据、总重量与后端合格率公式;缺失分量时显示不可用。
- 指标名称保持“亮片合格率”“综合合格率”,切换后增加11px/400的“(去本部报废)”小字。顶部卡片与跨行综合表头分行显示,亮片二级表头单行显示以维持行高;说明图标样式与黑片总重一致,保留原有计算口径入口。
- 所有查询页导出按钮显示下载图标与“Excel导出”文字。
- 2026-10-31 已按用户要求发布;构建及31项相关检查通过,线上字段顺序、口径切换、导出入口与顶部冻结已核对。
+58 -54
View File
@@ -1,3 +1,5 @@
import { queryScrapWeight, queryTotalScrapWeight, type QueryRateBasis } from './queryMetricValues';
import { useStickyQueryMetrics } from './useStickyQueryMetrics';
import { BusinessValue } from './BusinessValue'; import { BusinessValue } from './BusinessValue';
import { usePageCache } from './pageCache'; import { usePageCache } from './pageCache';
import { useCallback, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState } from 'react'; import { useCallback, useEffect, useImperativeHandle, useLayoutEffect, useMemo, useRef, useState } from 'react';
@@ -22,7 +24,7 @@ import {
Tooltip, Tooltip,
} from 'antd'; } from 'antd';
import type { ColumnsType } from 'antd/es/table'; import type { ColumnsType } from 'antd/es/table';
import { DownloadOutlined, ReloadOutlined, SearchOutlined } from '@ant-design/icons'; import { DownloadOutlined, InfoCircleOutlined, ReloadOutlined, SearchOutlined } from '@ant-design/icons';
import { ApiError, api, decodeQueryValueList, encodeQueryValueList } from './api'; import { ApiError, api, decodeQueryValueList, encodeQueryValueList } from './api';
import type { import type {
DefectMetric, DefectMetric,
@@ -193,8 +195,8 @@ function objectLabel(row: MetricRow, view: ViewKind): string {
return row.product || row.label; return row.product || row.label;
} }
function stageValue(row: MetricRow | undefined, stage: Stage, field: 'qualifiedWeight' | 'scrapWeight' | 'totalWeight' | 'rate' | 'headquartersScrapWeight'): number | null { function stageValue(row: MetricRow | undefined, stage: Stage, field: 'qualifiedWeight' | 'scrapWeight' | 'totalWeight' | 'rate' | 'headquartersScrapWeight', basis: QueryRateBasis = 'original'): number | null {
return row?.[stage]?.[field] ?? null; return field === 'scrapWeight' ? queryScrapWeight(row?.[stage], stage, basis) : row?.[stage]?.[field] ?? null;
} }
function defectList(row: MetricRow | undefined, stage: Stage): DefectMetric[] { function defectList(row: MetricRow | undefined, stage: Stage): DefectMetric[] {
@@ -285,6 +287,7 @@ export default function QueryPage({ page, onUnauthorized }: {
onUnauthorized: (error: unknown) => boolean; onUnauthorized: (error: unknown) => boolean;
onNavigate?: (page: PageKey, query: QueryParams, resultRef?: TopResultRef) => void; onNavigate?: (page: PageKey, query: QueryParams, resultRef?: TopResultRef) => void;
}) { }) {
const stickyPageRef = useStickyQueryMetrics();
const { message } = App.useApp(); const { message } = App.useApp();
const { active, initialSearch, refreshKey, onLocationChange } = usePageCache(); const { active, initialSearch, refreshKey, onLocationChange } = usePageCache();
const baseView = SCOPE[page] || 'overall'; const baseView = SCOPE[page] || 'overall';
@@ -697,7 +700,7 @@ export default function QueryPage({ page, onUnauthorized }: {
].filter(Boolean); ].filter(Boolean);
return ( return (
<div className="query-page"> <div className="query-page" ref={stickyPageRef}>
{optionsError && <Alert showIcon type="error" message="查询选项加载失败" description={optionsError} action={<Button size="small" icon={<ReloadOutlined />} onClick={() => { setOptionsLoading(true); api.options().then(result => { setOptions(result); setOptionsError(''); }).catch(e => { if (!onUnauthorized(e)) setOptionsError(chooseError(e)); }).finally(() => setOptionsLoading(false)); }}>重试</Button>} />} {optionsError && <Alert showIcon type="error" message="查询选项加载失败" description={optionsError} action={<Button size="small" icon={<ReloadOutlined />} onClick={() => { setOptionsLoading(true); api.options().then(result => { setOptions(result); setOptionsError(''); }).catch(e => { if (!onUnauthorized(e)) setOptionsError(chooseError(e)); }).finally(() => setOptionsLoading(false)); }}>重试</Button>} />}
<section className="query-toolbar panel" aria-label="查询条件"> <section className="query-toolbar panel" aria-label="查询条件">
<Segmented <Segmented
@@ -741,19 +744,13 @@ export default function QueryPage({ page, onUnauthorized }: {
{currentMetricsError && <Alert showIcon type="error" message="质量指标查询失败" description={currentMetricsError} action={<Button size="small" icon={<ReloadOutlined />} onClick={() => setQueryRevision(value => value + 1)}>重试</Button>} />} {currentMetricsError && <Alert showIcon type="error" message="质量指标查询失败" description={currentMetricsError} action={<Button size="small" icon={<ReloadOutlined />} onClick={() => setQueryRevision(value => value + 1)}>重试</Button>} />}
{drilledProduct && summaryMetricsError && <Alert showIcon type="error" message="当前产品指标查询失败" description={summaryMetricsError} action={<Button size="small" onClick={() => setQueryRevision(value => value + 1)}>重试</Button>} />} {drilledProduct && summaryMetricsError && <Alert showIcon type="error" message="当前产品指标查询失败" description={summaryMetricsError} action={<Button size="small" onClick={() => setQueryRevision(value => value + 1)}>重试</Button>} />}
<section className={`metric-strip ${!summaryMetricsData ? 'query-awaiting-data' : ''}`} aria-label="质量指标" aria-busy={summaryBusy} inert={!summaryMetricsData}> <section className={`metric-strip ${!summaryMetricsData ? 'query-awaiting-data' : ''}`} aria-label="质量指标" aria-busy={summaryBusy} inert={!summaryMetricsData}>
<div className="rate-basis-control"><span>亮片本部报废调整</span><Segmented size="small" value={rateBasis} options={[{ label: '原口径', value: 'original' }, { label: '去本部报废', value: 'withoutHeadquartersScrap' }]} onChange={value => setRateBasis(value as typeof rateBasis)} aria-label="合格率口径" /></div> <div className="rate-basis-control"><Segmented size="small" value={rateBasis} options={[{ label: '原口径', value: 'original' }, { label: '去本部报废', value: 'withoutHeadquartersScrap' }]} onChange={value => setRateBasis(value as typeof rateBasis)} aria-label="合格率口径" /></div>
<MetricCard primary label={rateBasis === 'original' ? '综合合格率' : '综合调整率'} value={rateText(visibleCompositeRate(rowForSummary, rateBasis))} onClick={() => setBasisOpen(true)} /> <MetricCard primary label={rateMetricLabel('综合合格率', rateBasis)} value={rateText(visibleCompositeRate(rowForSummary, rateBasis))} onClick={() => setBasisOpen(true)} />
<MetricCard label="黑片合格率" value={rateText(visibleStageRate(rowForSummary, 'black'))} note={!summaryMetricsData ? (summaryBusy ? '正在更新…' : '指标暂不可用') : hasStageRows(rowForSummary, 'black') ? hasValidRateDenominator(rowForSummary, 'black') ? `合格重量 ${numberText(rowForSummary?.black?.qualifiedWeight)} kg` : '按当前启用规则及空值策略计算' : '缺少黑片来源'} stage="black" onClick={() => openRecords(null, 'black')} /> <MetricCard label="黑片合格率" value={rateText(visibleStageRate(rowForSummary, 'black'))} note={!summaryMetricsData ? (summaryBusy ? '正在更新…' : '指标暂不可用') : hasStageRows(rowForSummary, 'black') ? hasValidRateDenominator(rowForSummary, 'black') ? `合格重量 ${numberText(rowForSummary?.black?.qualifiedWeight)} kg` : '按当前启用规则及空值策略计算' : '缺少黑片来源'} stage="black" onClick={() => openRecords(null, 'black')} />
<MetricCard label={rateBasis === 'original' ? '亮片合格率' : '亮片调整率'} value={rateText(visibleStageRate(rowForSummary, 'bright', rateBasis))} note={!summaryMetricsData ? (summaryBusy ? '正在更新…' : '指标暂不可用') : hasStageRows(rowForSummary, 'bright') ? hasValidRateDenominator(rowForSummary, 'bright') ? `合格重量 ${numberText(rowForSummary?.bright?.qualifiedWeight)} kg` : '按当前启用规则及空值策略计算' : '缺少亮片来源'} stage="bright" onClick={() => openRecords(null, 'bright')} /> <MetricCard label={rateMetricLabel('亮片合格率', rateBasis)} value={rateText(visibleStageRate(rowForSummary, 'bright', rateBasis))} note={!summaryMetricsData ? (summaryBusy ? '正在更新…' : '指标暂不可用') : hasStageRows(rowForSummary, 'bright') ? hasValidRateDenominator(rowForSummary, 'bright') ? `合格重量 ${numberText(rowForSummary?.bright?.qualifiedWeight)} kg` : '按当前启用规则及空值策略计算' : '缺少亮片来源'} stage="bright" onClick={() => openRecords(null, 'bright')} />
<MetricCard label="报废总重" value={rowForSummary && (hasStageRows(rowForSummary, 'black') || hasStageRows(rowForSummary, 'bright')) ? `${numberText((rowForSummary.black.scrapWeight ?? 0) + (rowForSummary.bright.scrapWeight ?? 0))} kg` : '—'} note={!summaryMetricsData ? (summaryBusy ? '正在更新…' : '指标暂不可用') : hasStageRows(rowForSummary, 'black') || hasStageRows(rowForSummary, 'bright') ? `黑片 ${numberText(rowForSummary?.black?.scrapWeight)} kg · 亮片 ${numberText(rowForSummary?.bright?.scrapWeight)} kg` : '缺少阶段来源'} onClick={() => openRecords(null, 'black')} /> <MetricCard label="报废总重" value={rowForSummary && (hasStageRows(rowForSummary, 'black') || hasStageRows(rowForSummary, 'bright')) ? `${numberText(queryTotalScrapWeight(rowForSummary, rateBasis))} kg` : '—'} note={!summaryMetricsData ? (summaryBusy ? '正在更新…' : '指标暂不可用') : hasStageRows(rowForSummary, 'black') || hasStageRows(rowForSummary, 'bright') ? `黑片 ${numberText(rowForSummary?.black?.scrapWeight)} kg · 亮片 ${numberText(queryScrapWeight(rowForSummary?.bright, 'bright', rateBasis))} kg` : '缺少阶段来源'} onClick={() => openRecords(null, 'black')} />
</section> </section>
<div className="query-quality-summary" aria-label="数据覆盖摘要">
<span>{drilledProduct && <>{drilledProduct} · </>}{summaryMetricsData ? <>来源覆盖 {summaryMetricsData.coverage.sourceMonths.filter(item => item.blackRows > 0 || item.brightRows > 0).length} 个月 · 参与计算 {summaryMetricsData.coverage.includedRows.toLocaleString('zh-CN')} / 原始 {summaryMetricsData.coverage.rawRows.toLocaleString('zh-CN')} 行 · 未分类 {summaryMetricsData.coverage.excludedBlankRows.toLocaleString('zh-CN')} 行({includeUnassigned ? '已包含' : '本次排除'})</> : summaryBusy ? '正在更新来源覆盖…' : '来源覆盖暂不可用'}</span>
<Button type="link" size="small" disabled={!summaryMetricsData} onClick={() => setBasisOpen(true)}>计算口径</Button>
</div>
{['department', 'group', 'product'].includes(page) && <> {['department', 'group', 'product'].includes(page) && <>
{options?.projectGroupStatus === 'UNCONFIGURED' && <Alert showIcon type="info" message="项目组映射尚未配置" description="项目组与源 Excel 业务分组是不同维度。映射启用前,此处不会将业务分组冒充项目组,也不会提供项目组筛选。" />} {options?.projectGroupStatus === 'UNCONFIGURED' && <Alert showIcon type="info" message="项目组映射尚未配置" description="项目组与源 Excel 业务分组是不同维度。映射启用前,此处不会将业务分组冒充项目组,也不会提供项目组筛选。" />}
</>} </>}
@@ -769,12 +766,12 @@ export default function QueryPage({ page, onUnauthorized }: {
<Segmented value={defectDisplay} options={[{label:'不良重量',value:'weight'},{label:'不良率',value:'rate'}]} onChange={value=>setDefectDisplay(value as typeof defectDisplay)} 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 onClick={() => { setSearch(''); setAppliedSearch(''); setTrendObject(''); if (view === 'product') { setProduct([]); setGroup([]); setViewOverride('group'); } else { setGroup([]); setDepartment([]); setViewOverride('department'); } }}>{view === 'product' ? '返回业务分组' : '返回产业部'}</Button>} {!drilledProduct && (view === 'group' || view === 'product' && (group.length > 0 || department.length > 0)) && <Button onClick={() => { setSearch(''); setAppliedSearch(''); setTrendObject(''); if (view === 'product') { setProduct([]); setGroup([]); setViewOverride('group'); } else { setGroup([]); setDepartment([]); setViewOverride('department'); } }}>{view === 'product' ? '返回业务分组' : '返回产业部'}</Button>}
{drilledProduct && <Button onClick={() => { setDrilledProduct(''); setTrendObject(''); setTrendMode('production'); }}>返回产品汇总</Button>} {drilledProduct && <Button onClick={() => { setDrilledProduct(''); setTrendObject(''); setTrendMode('production'); }}>返回产品汇总</Button>}
<Tooltip title="导出 Excel"><Button type="text" icon={<DownloadOutlined />} aria-label="导出 Excel" loading={summaryExporting} disabled={queryBusy || summaryBusy || !summaryMetricsData || Boolean(drilledProduct && trendLoading) || !(drilledProduct ? drilledTrendData : visibleRows).length} onClick={async () => { <Button icon={<DownloadOutlined />} aria-label="Excel导出" loading={summaryExporting} disabled={queryBusy || summaryBusy || !summaryMetricsData || Boolean(drilledProduct && trendLoading) || !(drilledProduct ? drilledTrendData : visibleRows).length} onClick={async () => {
setSummaryExporting(true); setSummaryExporting(true);
try { await summaryExport.current?.exportExcel(); } try { await summaryExport.current?.exportExcel(); }
catch (error) { message.error(`导出失败:${chooseError(error)}`); } catch (error) { message.error(`导出失败:${chooseError(error)}`); }
finally { setSummaryExporting(false); } finally { setSummaryExporting(false); }
}} /></Tooltip> }}>Excel导出</Button>
</div> </div>
</div> </div>
<div className="mobile-scroll-hint">横向滑动查看完整指标</div> <div className="mobile-scroll-hint">横向滑动查看完整指标</div>
@@ -828,13 +825,12 @@ export default function QueryPage({ page, onUnauthorized }: {
/> />
)} )}
</div></Spin> </div></Spin>
<div className="table-footer"><span>{queryBusy ? '正在更新当前查询结果…' : drilledProduct ? trendLoading && trendDataKey !== trendKey ? `${drilledProduct} · 正在查询月度数据` : `${drilledProduct} · 共 ${drilledTrendData.length} 个月` : page === 'overall' && period === 'year' ? `年度月份 12 行 · 已有数据 ${new Set((currentMetricsData?.trend || []).map(item => String(item.month))).size} 个月` : `共 ${visibleRows.length} 行`}</span></div>
</section> </section>
<div className="analysis-stack"> <div className="analysis-stack">
<section className="panel section-panel trend-panel" ref={trendSection} id={active ? 'monthly-trend' : undefined}> <section className="panel section-panel trend-panel" ref={trendSection} id={active ? 'monthly-trend' : undefined}>
<div className="section-heading-row trend-heading-row"> <div className="section-heading-row trend-heading-row">
<SectionHeading title={`${trendGranularity === 'month' ? '月度' : trendGranularity === 'quarter' ? '季度' : '年度'}变化趋势`} subtitle={`${trendGranularity === 'year' ? '全部实际数据年份' : `${year} 年`} · ${trendObject || `当前${scopeName}筛选`}`} /> <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="趋势视图" /> <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>
<div className="trend-controls"> <div className="trend-controls">
@@ -850,12 +846,12 @@ export default function QueryPage({ page, onUnauthorized }: {
: <TrendChart rows={visibleTrendData} mode={trendMode} stage={trendStage} rateBasis={rateBasis} targetRate={currentTrendTarget} selectedPeriod={selectedTrendPeriod} onMonth={selectTrendPeriod} />} : <TrendChart rows={visibleTrendData} mode={trendMode} stage={trendStage} rateBasis={rateBasis} targetRate={currentTrendTarget} selectedPeriod={selectedTrendPeriod} onMonth={selectTrendPeriod} />}
{(trendLoading || (useSummaryTrend && queryBusy)) && <span className="trend-refresh-indicator"><Spin size="small" />正在更新趋势</span>} {(trendLoading || (useSummaryTrend && queryBusy)) && <span className="trend-refresh-indicator"><Spin size="small" />正在更新趋势</span>}
</div> </div>
<div className="chart-footnote"><span>全年期间均显示;无数据期间留空,指标由源分量重新汇总。</span><span>点击期间筛选,再次点击可取消</span></div> <div className="chart-footnote"><span style={{ marginLeft: 'auto' }}>点击期间筛选,再次点击可取消</span></div>
</section> </section>
<section className="panel section-panel defects-panel"> <section className="panel section-panel defects-panel">
<div className="section-heading-row"> <div className="section-heading-row">
<SectionHeading title="不良具体构成" subtitle={`${year}年${period === 'month' ? MONTHS[month - 1] : period === 'quarter' ? `第${quarter}季度` : '全年'}${trendObject ? ` · ${trendObject}` : ''} · 占比为分类报废内占比;废率为该类重量 ÷ 同阶段总重量`} /> <SectionHeading title="不良具体构成" />
</div> </div>
{trendObjectMetricsLoading && <div className="defect-pareto-status"><Spin size="small" />正在更新当前趋势对象的不良数据</div>} {trendObjectMetricsLoading && <div className="defect-pareto-status"><Spin size="small" />正在更新当前趋势对象的不良数据</div>}
{trendObjectMetricsError && <Alert showIcon type="warning" message="当前趋势对象的不良数据读取失败" description={trendObjectMetricsError} />} {trendObjectMetricsError && <Alert showIcon type="warning" message="当前趋势对象的不良数据读取失败" description={trendObjectMetricsError} />}
@@ -879,8 +875,8 @@ export default function QueryPage({ page, onUnauthorized }: {
<Modal open={basisOpen} title={`${rateBasis === 'original' ? '综合合格率' : '综合调整率'}计算口径`} onCancel={() => setBasisOpen(false)} footer={<Button onClick={() => setBasisOpen(false)}>关闭</Button>} width={680}> <Modal open={basisOpen} title="综合合格率计算口径" onCancel={() => setBasisOpen(false)} footer={<Button onClick={() => setBasisOpen(false)}>关闭</Button>} width={680}>
<div className="basis-card"><span>当前{rateBasis === 'original' ? '综合合格率' : '综合调整率'}</span><strong>{rateText(visibleCompositeRate(rowForSummary, rateBasis))}</strong><span>黑片 {rateText(visibleStageRate(rowForSummary, 'black'))} · {rateBasis === 'original' ? '亮片' : '亮片调整率'} {rateText(visibleStageRate(rowForSummary, 'bright', rateBasis))}</span></div> <div className="basis-card"><span>当前综合合格率</span><strong>{rateText(visibleCompositeRate(rowForSummary, rateBasis))}</strong><span>黑片 {rateText(visibleStageRate(rowForSummary, 'black'))} · 亮片 {rateText(visibleStageRate(rowForSummary, 'bright', rateBasis))}</span></div>
<p className="basis-copy">以下为当前查询实际使用的公式、适用条件与空值处理规则。月、季、年先汇总计算分量,再按生效公式计算。</p> <p className="basis-copy">以下为当前查询实际使用的公式、适用条件与空值处理规则。月、季、年先汇总计算分量,再按生效公式计算。</p>
<dl className="basis-details"> <dl className="basis-details">
<dt>综合公式</dt><dd>{formulaText(compositeFormula)}</dd> <dt>综合公式</dt><dd>{formulaText(compositeFormula)}</dd>
@@ -911,7 +907,7 @@ export default function QueryPage({ page, onUnauthorized }: {
); );
} }
export function MetricCard({ primary, label, value, note, stage, onClick }: { primary?: boolean; label: string; value: string; note?: string; stage?: Stage; onClick: () => void }) { export function MetricCard({ primary, label, value, note, stage, onClick }: { primary?: boolean; label: React.ReactNode; value: string; note?: string; stage?: Stage; onClick: () => void }) {
const parts = value.match(/^(.*?)(%| kg)$/); const parts = value.match(/^(.*?)(%| kg)$/);
return <button className={`metric-card ${primary ? 'primary' : ''} ${stage || ''}`} onClick={onClick}> return <button className={`metric-card ${primary ? 'primary' : ''} ${stage || ''}`} onClick={onClick}>
<span className="metric-label">{stage && <i className={`stage-dot ${stage}`} />}{label}</span> <span className="metric-label">{stage && <i className={`stage-dot ${stage}`} />}{label}</span>
@@ -933,7 +929,6 @@ export function DefectBreakdown({ items, stage, totalWeight, maximum, onDetail }
</div>; </div>;
} }
const FINE_DEFECT_FIELD_COUNT = 33;
export function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUnauthorized, onlyStage }: { export function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUnauthorized, onlyStage }: {
releaseId?: string; query: QueryParams; externalScrapWeight?: number | null; onUnauthorized: (error: unknown) => boolean; onlyStage?: Stage; releaseId?: string; query: QueryParams; externalScrapWeight?: number | null; onUnauthorized: (error: unknown) => boolean; onlyStage?: Stage;
@@ -1008,13 +1003,12 @@ export function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUna
kind: 'source' as const, kind: 'source' as const,
}))); })));
if (onlyStage !== 'bright' && typeof externalScrapWeight === 'number' && Number.isFinite(externalScrapWeight) && externalScrapWeight > 0) { if (onlyStage !== 'bright' && typeof externalScrapWeight === 'number' && Number.isFinite(externalScrapWeight) && externalScrapWeight > 0) {
raw.push({ key: 'black:externalScrap', label: '黑片·外废(仅大类重量)', category: '外废', weight: externalScrapWeight, kind: 'category' }); raw.push({ key: 'black:externalScrap', label: '黑片·外废', category: '外废', weight: externalScrapWeight, kind: 'category' });
} }
return raw.filter(item => typeof item.weight === 'number' && Number.isFinite(item.weight) && item.weight > 0) return raw.filter(item => typeof item.weight === 'number' && Number.isFinite(item.weight) && item.weight > 0)
.sort((left, right) => right.weight! - left.weight! || left.label.localeCompare(right.label, 'zh-CN')); .sort((left, right) => right.weight! - left.weight! || left.label.localeCompare(right.label, 'zh-CN'));
}, [responses, externalScrapWeight, onlyStage]); }, [responses, externalScrapWeight, onlyStage]);
const totalWeight = items.reduce((total, item) => total + (item.weight || 0), 0); const totalWeight = items.reduce((total, item) => total + (item.weight || 0), 0);
const visibleFieldCount = responses ? (responses.black.sourceFields?.length || 0) + (responses.bright.sourceFields?.length || 0) : 0;
useEffect(() => { useEffect(() => {
const instance = chart.current; const instance = chart.current;
@@ -1037,7 +1031,7 @@ export function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUna
textStyle: { color: ink, fontFamily, fontSize }, textStyle: { color: ink, fontFamily, fontSize },
animationDuration: 420, animationDuration: 420,
animationDurationUpdate: 520, animationDurationUpdate: 520,
grid: { left: 68, right: 72, top: 48, bottom: items.length > 12 ? 92 : 62, containLabel: true }, grid: { left: 32, right: 24, top: 48, bottom: 12, containLabel: true },
legend: { top: 8, data: ['报废重量', '累计占比'], textStyle: { color: ink, fontFamily, fontSize, fontWeight: 500 } }, legend: { top: 8, data: ['报废重量', '累计占比'], textStyle: { color: ink, fontFamily, fontSize, fontWeight: 500 } },
tooltip: { tooltip: {
trigger: 'axis', trigger: 'axis',
@@ -1051,7 +1045,7 @@ export function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUna
const item = items[index]; const item = items[index];
if (!item) return ''; if (!item) return '';
const share = totalWeight > 0 ? (item.weight || 0) / totalWeight * 100 : 0; const share = totalWeight > 0 ? (item.weight || 0) / totalWeight * 100 : 0;
return `<strong>${escapeTooltipText(item.label)}</strong><br/>分类:${escapeTooltipText(item.category)}<br/>报废重量:${numberText(item.weight)} kg<br/>综合占比:${share.toFixed(2)}%<br/>累计占比:${cumulative[index].toFixed(2)}%${item.kind === 'category' ? '<br/>来源仅提供大类重量' : '<br/>来自源表细分重量字段'}`; return `<strong>${escapeTooltipText(item.label)}</strong><br/>分类:${escapeTooltipText(item.category)}<br/>报废重量:${numberText(item.weight)} kg<br/>综合占比:${share.toFixed(2)}%<br/>累计占比:${cumulative[index].toFixed(2)}%`;
}, },
}, },
xAxis: { xAxis: {
@@ -1073,13 +1067,8 @@ export function DefectParetoPanel({ releaseId, query, externalScrapWeight, onUna
instance.setOption(option, { notMerge: true, lazyUpdate: false }); instance.setOption(option, { notMerge: true, lazyUpdate: false });
}, [items, totalWeight, themeRevision]); }, [items, totalWeight, themeRevision]);
const incompleteCategories = responses
? (['black', 'bright'] as const).flatMap(stage => responses[stage].coverage?.categories || [])
.filter(item => item.reconciliationStatus !== 'RECONCILED' && item.reconciliationStatus !== 'UNAVAILABLE').length
: 0;
return <section className="defect-pareto-section" aria-label={onlyStage ? `${onlyStage === 'black' ? '黑片' : '亮片'}报废重量柏拉图` : '综合报废重量柏拉图'}> return <section className="defect-pareto-section" aria-label={onlyStage ? `${onlyStage === 'black' ? '黑片' : '亮片'}报废重量柏拉图` : '综合报废重量柏拉图'}>
<div className="defect-pareto-heading"><strong>{onlyStage ? `${onlyStage === 'black' ? '黑片' : '亮片'}报废重量柏拉图` : '黑片与亮片综合报废重量柏拉图'}</strong><span>{responses ? `细分源字段 ${visibleFieldCount}${onlyStage ? '' : ` / ${FINE_DEFECT_FIELD_COUNT}`} 项${incompleteCategories ? ` · ${incompleteCategories} 类细分数据未与正式大类完全核对` : ''}` : '按当前筛选范围汇总全部可见细分报废重量'}</span></div> <div className="defect-pareto-heading"><strong>{onlyStage ? `${onlyStage === 'black' ? '黑片' : '亮片'}报废重量柏拉图` : '黑片与亮片综合报废重量柏拉图'}</strong></div>
{loading && <div className="defect-pareto-status"><Spin size="small" />正在汇总细分报废重量</div>} {loading && <div className="defect-pareto-status"><Spin size="small" />正在汇总细分报废重量</div>}
{error && <Alert showIcon type="warning" message="细分报废重量读取失败" description={error} />} {error && <Alert showIcon type="warning" message="细分报废重量读取失败" description={error} />}
{!loading && !releaseId && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前没有已发布数据版本" />} {!loading && !releaseId && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前没有已发布数据版本" />}
@@ -1103,6 +1092,12 @@ function useCompactTable() {
return compact; return compact;
} }
export const rateMetricLabel = (label: string, basis: QueryRateBasis) => <span className="query-rate-label">{label}{basis !== 'original' && <small className="query-rate-subtitle">(去本部报废)</small>}</span>;
const totalWeightTitle = (label: string) => <span className="query-total-weight-title">{label}<Tooltip trigger={['hover', 'focus']} title={<div>黑片总重量为合格率计算使用的适用总重量。<br />按来源逐行计算:合格重量+报废重量-利用料及废品库对应的合格重量、报废重量;发料地点包含“利用料”或“废品”时扣减。<br />检验备注包含“过账”时,外废不计入报废重量;月、季、年均先汇总来源分量。具体取值以已发布数据版本及生效规则为准。</div>}><InfoCircleOutlined tabIndex={0} role="img" aria-label="黑片总重量计算说明" /></Tooltip></span>;
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><Tooltip trigger={['hover', 'focus']} title={<div>{kind === 'composite' && <>综合合格率=黑片合格率×亮片合格率。<br /></>}原口径:亮片合格重量÷亮片总重量。<br />去本部报废:(亮片合格重量+本部报废)÷亮片总重量,同时从亮片报废重量中扣除本部报废,总重量不变。<br />当前:{basis === 'original' ? '原口径' : '去本部报废'}。计算结果以已发布数据版本及生效规则为准。</div>}><InfoCircleOutlined tabIndex={0} role="img" aria-label={`${kind === 'composite' ? '综合合格率' : '亮片合格率'}计算说明`} /></Tooltip></span>;
export function MetricTable({ export function MetricTable({
ref, exportFilename, rows, view, layoutView = view, pageSizeOverride, period, month, quarter, fullFields, rateBasis, onDetail, onBasis, onDrilldown, onlyStage, defectDisplay = 'weight', emptyText = '当前条件下暂无数据', ref, exportFilename, rows, view, layoutView = view, pageSizeOverride, period, month, quarter, fullFields, rateBasis, onDetail, onBasis, onDrilldown, onlyStage, defectDisplay = 'weight', emptyText = '当前条件下暂无数据',
}: { }: {
@@ -1125,31 +1120,37 @@ export function MetricTable({
onDetail(row, stage, isOverall && period === 'year' ? monthNumber((row as TrendMetricRow).month) || undefined : isOverall && period === 'month' ? month : undefined); onDetail(row, stage, isOverall && period === 'year' ? monthNumber((row as TrendMetricRow).month) || undefined : isOverall && period === 'month' ? month : undefined);
}; };
const numeric = (label: string, stage: Stage, field: 'qualifiedWeight' | 'scrapWeight' | 'totalWeight' | 'rate' | 'headquartersScrapWeight', className = '') => ({ const numeric = (label: string, stage: Stage, field: 'qualifiedWeight' | 'scrapWeight' | 'totalWeight' | 'rate' | 'headquartersScrapWeight', className = '') => ({
title: `${compact ? stage === 'black' ? '黑片' : '亮片' : ''}${defectDisplay === 'rate' && (field === 'scrapWeight' || field === 'headquartersScrapWeight') ? defectRateLabel(label) : label}`, title: stage === 'black' && field === 'totalWeight' ? totalWeightTitle(`${compact ? '黑片' : ''}${label}`) : stage === 'bright' && field === 'rate' ? rateBasisTitle(`${compact ? '亮片' : ''}${label}`, rateBasis, 'bright') : `${compact ? stage === 'black' ? '黑片' : '亮片' : ''}${defectDisplay === 'rate' && (field === 'scrapWeight' || field === 'headquartersScrapWeight') ? defectRateLabel(label) : label}`,
exportRate: defectDisplay === 'rate' && (field === 'scrapWeight' || field === 'headquartersScrapWeight'), exportRate: defectDisplay === 'rate' && (field === 'scrapWeight' || field === 'headquartersScrapWeight'),
key: `${stage}-${field}`, key: `${stage}-${field}`,
align: 'center' as const, align: 'center' as const,
width: field === 'rate' ? 116 : 145, width: field === 'rate' ? (stage === 'bright' && rateBasis !== 'original' ? 164 : fullFields ? 96 : 116) : (fullFields ? 112 : 145),
className: `${field === 'rate' ? `rate-cell ${stage}` : 'weight-cell'} ${className}`, className: `${field === 'rate' ? `rate-cell ${stage}` : 'weight-cell'} ${className}`,
render: (_: unknown, row: MetricRow) => <Button type="link" className="table-value" tabIndex={-1} style={{ userSelect: 'text', WebkitUserSelect: 'text' }}>{field === 'rate' ? rateText(visibleStageRate(row, stage)) : defectDisplay === 'rate' && (field === 'scrapWeight' || field === 'headquartersScrapWeight') ? rateText(defectWeightRate(stageValue(row, stage, field),stageValue(row, stage, 'totalWeight'))) : numberText(stageValue(row, stage, field))}</Button>, render: (_: unknown, row: MetricRow) => <Button type="link" className="table-value" tabIndex={-1} style={{ userSelect: 'text', WebkitUserSelect: 'text' }}>{field === 'rate' ? rateText(visibleStageRate(row, stage)) : defectDisplay === 'rate' && (field === 'scrapWeight' || field === 'headquartersScrapWeight') ? rateText(defectWeightRate(stageValue(row, stage, field, rateBasis),stageValue(row, stage, 'totalWeight'))) : numberText(stageValue(row, stage, field, rateBasis))}</Button>,
}); });
const defectColumns = (stage: Stage, names: string[]) => names.map(name => ({ const defectColumns = (stage: Stage, names: string[]) => names.map(name => ({
title: `${compact ? stage === 'black' ? '黑片' : '亮片' : ''}${defectDisplay === 'rate' ? defectRateLabel(name) : name}`, title: `${compact ? stage === 'black' ? '黑片' : '亮片' : ''}${defectDisplay === 'rate' ? defectRateLabel(name) : name}`,
exportRate: defectDisplay === 'rate', exportRate: defectDisplay === 'rate',
key: `${stage}-defect-${name}`, key: `${stage}-defect-${name}`,
align: 'center' as const, align: 'center' as const,
width: 130, width: fullFields ? 100 : 130,
render: (_: unknown, row: MetricRow) => { render: (_: unknown, row: MetricRow) => {
const value = defectList(row, stage).find(item => item.name === name); const value = defectList(row, stage).find(item => item.name === name);
return <Button type="link" className="table-value" tabIndex={-1} style={{ userSelect: 'text', WebkitUserSelect: 'text' }}>{defectDisplay === 'rate' ? rateText(defectWeightRate(value?.weight,stageValue(row,stage,'totalWeight'))) : numberText(value?.weight ?? null)}</Button>; return <Button type="link" className="table-value" tabIndex={-1} style={{ userSelect: 'text', WebkitUserSelect: 'text' }}>{defectDisplay === 'rate' ? rateText(defectWeightRate(value?.weight,stageValue(row,stage,'totalWeight'))) : numberText(value?.weight ?? null)}</Button>;
}, },
})); }));
const brightDetailColumns: ColumnsType<MetricRow> = defectColumns('bright', brightDefects);
if (fullFields && rateBasis === 'original') {
const diffusionIndex = brightDetailColumns.findIndex(column => column.key === 'bright-defect-扩散废');
brightDetailColumns.splice(diffusionIndex < 0 ? brightDetailColumns.length : diffusionIndex + 1, 0,
numeric('本部报废', 'bright', 'headquartersScrapWeight'));
}
const allColumns: ColumnsType<MetricRow> = [ 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 : layoutView === 'product' ? 300 : layoutView === 'group' ? 260 : 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' ? '月份' : '统计期间' : 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: <button className="header-link" onClick={onBasis}>{rateBasis === 'original' ? '综合合格率' : '综合调整率'}</button>, key: 'compositeRate', dataIndex: 'compositeRate', align: 'center', fixed: compact ? undefined : 'left', width: 140, className: 'combined-column', render: (_: number | null, row: MetricRow) => <button className="combined-value" tabIndex={-1} style={{ userSelect: 'text', WebkitUserSelect: 'text' }}>{rateText(visibleCompositeRate(row, rateBasis))}</button> }, { key: 'stage-black', title: <span className="stage-heading black"><i />黑片</span>, children: [numeric('总重量', 'black', 'totalWeight'), numeric('合格重量', 'black', 'qualifiedWeight'), numeric('报废重量', 'black', 'scrapWeight'), ...defectColumns('black', blackDefects), numeric('合格率', 'black', 'rate')] },
{ key: 'stage-black', title: <span className="stage-heading black"><i />黑片</span>, children: [numeric('合格重量', 'black', 'qualifiedWeight'), ...(fullFields ? [numeric('总重量', 'black', 'totalWeight')] : []), numeric('报废重量', 'black', 'scrapWeight'), ...defectColumns('black', blackDefects), numeric('合格率', 'black', 'rate')] }, { key: 'stage-bright', title: <span className="stage-heading bright"><i />亮片</span>, children: [numeric('总重量', 'bright', 'totalWeight'), numeric('合格重量', 'bright', 'qualifiedWeight'), numeric('报废重量', 'bright', 'scrapWeight'), ...brightDetailColumns, { ...numeric('合格率', 'bright', 'rate'), render: (_: unknown, row: MetricRow) => <Button type="link" className="table-value" tabIndex={-1} style={{ userSelect: 'text', WebkitUserSelect: 'text' }}>{rateText(visibleStageRate(row, 'bright', rateBasis))}</Button> }] },
{ key: 'stage-bright', title: <span className="stage-heading bright"><i />亮片</span>, children: [numeric('合格重量', 'bright', 'qualifiedWeight'), ...(fullFields ? [numeric('总重量', 'bright', 'totalWeight')] : []), numeric('报废重量', 'bright', 'scrapWeight'), ...(fullFields ? [numeric('本部报废重量', 'bright', 'headquartersScrapWeight')] : []), ...defectColumns('bright', brightDefects), { ...numeric(rateBasis === 'original' ? '合格率' : '不含本部报废调整率', 'bright', 'rate'), render: (_: unknown, row: MetricRow) => <Button type="link" className="table-value" tabIndex={-1} style={{ userSelect: 'text', WebkitUserSelect: 'text' }}>{rateText(visibleStageRate(row, 'bright', rateBasis))}</Button> }] }, { 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' }}>{rateText(visibleCompositeRate(row, rateBasis))}</button> },
{ title: '操作', key: 'actions', fixed: compact ? undefined : 'right', width: 100, align: 'center', render: (_: unknown, row) => (row as TrendMetricRow).noData ? <span>—</span> : <Button type="link" onClick={() => openRow(row, onlyStage || 'black')}>来源明细</Button> }, { title: '操作', key: 'actions', fixed: compact ? undefined : 'right', width: 96, align: 'center', render: (_: unknown, row) => (row as TrendMetricRow).noData ? <span>—</span> : <Button type="link" onClick={() => openRow(row, onlyStage || 'black')}>来源明细</Button> },
]; ];
const columns = onlyStage ? allColumns.filter(column => !['compositeRate', `stage-${onlyStage === 'black' ? 'bright' : 'black'}`].includes(String(column.key))) : allColumns; const columns = onlyStage ? allColumns.filter(column => !['compositeRate', `stage-${onlyStage === 'black' ? 'bright' : 'black'}`].includes(String(column.key))) : allColumns;
useImperativeHandle(ref, () => ({ useImperativeHandle(ref, () => ({
@@ -1162,8 +1163,8 @@ export function MetricTable({
return defectDisplay === 'rate' ? defectWeightRate(weight,stageValue(row,stage,'totalWeight')) : weight; return defectDisplay === 'rate' ? defectWeightRate(weight,stageValue(row,stage,'totalWeight')) : weight;
} }
const field = key.slice(stage.length + 1) as 'qualifiedWeight' | 'scrapWeight' | 'totalWeight' | 'headquartersScrapWeight' | 'rate'; const field = key.slice(stage.length + 1) as 'qualifiedWeight' | 'scrapWeight' | 'totalWeight' | 'headquartersScrapWeight' | 'rate';
if (defectDisplay === 'rate' && (field === 'scrapWeight' || field === 'headquartersScrapWeight')) return defectWeightRate(stageValue(row,stage,field),stageValue(row,stage,'totalWeight')); if (defectDisplay === 'rate' && (field === 'scrapWeight' || field === 'headquartersScrapWeight')) return defectWeightRate(stageValue(row,stage,field,rateBasis),stageValue(row,stage,'totalWeight'));
return field === 'rate' ? visibleStageRate(row, stage, stage === 'bright' ? rateBasis : 'original') : stageValue(row, stage, field); 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, key: row.key || `${title(row)}-${index}` }));
@@ -1182,7 +1183,7 @@ export function MetricTable({
const scroll = { x: scrollWidth }; const scroll = { x: scrollWidth };
const displayColumns = compact ? columns.flatMap(column => 'children' in column && column.children ? column.children : [column]) : columns; const displayColumns = compact ? columns.flatMap(column => 'children' in column && column.children ? column.children : [column]) : columns;
const pageRows = dataSource.slice((effectivePage - 1) * effectivePageSize, effectivePage * effectivePageSize); const pageRows = dataSource.slice((effectivePage - 1) * effectivePageSize, effectivePage * effectivePageSize);
return <div className="metric-table-scroll"><Table<MetricRow> size="small" bordered columns={displayColumns} dataSource={pageRows} pagination={false} scroll={scroll} rowKey="key" locale={{ emptyText }} /> return <div className="metric-table-scroll"><Table<MetricRow> size="small" bordered tableLayout="fixed" columns={displayColumns} dataSource={pageRows} pagination={false} scroll={scroll} rowKey="key" locale={{ emptyText }} />
{pageSizeOverride == null && <MetricTablePagination current={currentPage} total={dataSource.length} pageSize={pageSize} onChange={(nextPage, nextPageSize) => { setPageSize(nextPageSize); setCurrentPage(nextPageSize === pageSize ? nextPage : 1); }} />} {pageSizeOverride == null && <MetricTablePagination current={currentPage} total={dataSource.length} pageSize={pageSize} onChange={(nextPage, nextPageSize) => { setPageSize(nextPageSize); setCurrentPage(nextPageSize === pageSize ? nextPage : 1); }} />}
</div>; </div>;
} }
@@ -1291,7 +1292,7 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
const surface = css.getPropertyValue('--surface').trim() || '#ffffff'; const surface = css.getPropertyValue('--surface').trim() || '#ffffff';
const labels = rows.map(row => row.periodLabel || String(row.month)); const labels = rows.map(row => row.periodLabel || String(row.month));
const barData = (field: 'qualifiedWeight' | 'scrapWeight') => rows.map(row => ({ const barData = (field: 'qualifiedWeight' | 'scrapWeight') => rows.map(row => ({
value: hasStageRows(row, stage) ? row[stage][field] ?? null : null, value: hasStageRows(row, stage) ? stageValue(row, stage, field, rateBasis) : null,
})); }));
const formatTooltip = (params: unknown, onlyRates = false) => { const formatTooltip = (params: unknown, onlyRates = false) => {
const items: ChartTooltipParam[] = Array.isArray(params) ? params as ChartTooltipParam[] : [params as ChartTooltipParam]; const items: ChartTooltipParam[] = Array.isArray(params) ? params as ChartTooltipParam[] : [params as ChartTooltipParam];
@@ -1334,9 +1335,9 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
series: [ series: [
{ id: 'qualified-weight', name: `${stageName}合格重量`, type: 'bar', z: 1, stack: 'weight', yAxisIndex: 0, barWidth, itemStyle: { color: barColor }, emphasis: { itemStyle: { color: blue } }, data: barData('qualifiedWeight') }, { id: 'qualified-weight', name: `${stageName}合格重量`, type: 'bar', z: 1, stack: 'weight', yAxisIndex: 0, barWidth, itemStyle: { color: barColor }, emphasis: { itemStyle: { color: blue } }, data: barData('qualifiedWeight') },
{ id: 'scrap-weight', name: `${stageName}报废重量`, type: 'bar', z: 1, stack: 'weight', yAxisIndex: 0, barWidth, itemStyle: { color: '#edaa83' }, emphasis: { itemStyle: { color: '#e58e5d' } }, data: barData('scrapWeight') }, { id: 'scrap-weight', name: `${stageName}报废重量`, type: 'bar', z: 1, stack: 'weight', yAxisIndex: 0, barWidth, itemStyle: { color: '#edaa83' }, emphasis: { itemStyle: { color: '#e58e5d' } }, data: barData('scrapWeight') },
{ id: 'composite-rate', name: rateBasis === 'original' ? '综合合格率' : '综合调整率', type: 'line', yAxisIndex: 1, ...pointStyle, ...targetLine, lineStyle: { width: 2.5, color: blue }, itemStyle: { color: blue, borderColor: surface, borderWidth: 1.5 }, data: rows.map(row => rateNumber(visibleCompositeRate(row, rateBasis))) }, { id: '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: 'black-rate', name: '黑片合格率', type: 'line', yAxisIndex: 1, ...pointStyle, lineStyle: { width: 1.8, color: '#9278bf' }, itemStyle: { color: '#9278bf', borderColor: surface, borderWidth: 1 }, data: rows.map(row => rateNumber(visibleStageRate(row, 'black'))) },
{ id: 'bright-rate', name: rateBasis === 'original' ? '亮片合格率' : '亮片不含本部报废调整率', type: 'line', yAxisIndex: 1, ...pointStyle, lineStyle: { width: 1.8, color: teal }, itemStyle: { color: teal, borderColor: surface, borderWidth: 1 }, data: rows.map(row => rateNumber(visibleStageRate(row, 'bright', rateBasis))) }, { 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))) },
], ],
}; };
} else { } else {
@@ -1399,20 +1400,23 @@ export function TrendChart({ rows, mode, stage, rateBasis, targetRate, selectedP
} }
function TrendTable({ rows, rateBasis, onMonth, defectDisplay = 'weight', showMonthLinks = true }: { rows: TrendMetricRow[]; rateBasis: 'original' | 'withoutHeadquartersScrap'; onMonth: (value: number | string) => void; defectDisplay?: 'weight'|'rate'; showMonthLinks?: boolean }) { function TrendTable({ rows, rateBasis, onMonth, defectDisplay = 'weight', showMonthLinks = true }: { rows: TrendMetricRow[]; rateBasis: 'original' | 'withoutHeadquartersScrap'; onMonth: (value: number | string) => void; defectDisplay?: 'weight'|'rate'; showMonthLinks?: boolean }) {
const compact = useCompactTable();
const [currentPage, setCurrentPage] = useState(1); const [currentPage, setCurrentPage] = useState(1);
const [pageSize, setPageSize] = useState(SUMMARY_PAGE_SIZE); const [pageSize, setPageSize] = useState(SUMMARY_PAGE_SIZE);
useEffect(() => setCurrentPage(1), [rows]); useEffect(() => setCurrentPage(1), [rows]);
const columns: ColumnsType<TrendMetricRow> = [ 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> }, { 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> },
{ title: rateBasis === 'original' ? '综合合格率' : '综合调整率', dataIndex: 'compositeRate', key: 'compositeRate', align: 'center', width: 130, className: 'combined-column', render: (_: number | null, row: MetricRow) => rateText(visibleCompositeRate(row, rateBasis)) }, { title: totalWeightTitle('黑片总重量 / kg'), dataIndex: ['black', 'totalWeight'], key: 'blackTotal', align: 'center', width: 160, render: value => numberText(value) },
{ title: '黑片合格重量 / kg', dataIndex: ['black', 'qualifiedWeight'], key: 'blackQualified', align: 'center', width: 160, render: value => numberText(value) }, { title: '黑片合格重量 / kg', dataIndex: ['black', 'qualifiedWeight'], key: 'blackQualified', align: 'center', width: 160, render: value => numberText(value) },
{ title: defectDisplay === 'rate' ? '黑片报废率' : '黑片报废重量 / kg', dataIndex: ['black', 'scrapWeight'], key: 'blackScrap', align: 'center', width: 160, render: (_: unknown, row: TrendMetricRow) => defectDisplay === 'rate' ? rateText(defectWeightRate(row.black.scrapWeight,row.black.totalWeight)) : numberText(row.black.scrapWeight) }, { title: defectDisplay === 'rate' ? '黑片报废率' : '黑片报废重量 / kg', dataIndex: ['black', 'scrapWeight'], key: 'blackScrap', align: 'center', width: 160, render: (_: unknown, row: TrendMetricRow) => defectDisplay === 'rate' ? rateText(defectWeightRate(row.black.scrapWeight,row.black.totalWeight)) : numberText(row.black.scrapWeight) },
{ title: '黑片合格率', dataIndex: ['black', 'rate'], key: 'blackRate', align: 'center', width: 130, render: (_: number | null, row: TrendMetricRow) => rateText(visibleStageRate(row, 'black')) }, { title: '黑片合格率', dataIndex: ['black', 'rate'], key: 'blackRate', align: 'center', width: 130, className: 'rate-cell black', render: (_: number | null, row: TrendMetricRow) => rateText(visibleStageRate(row, 'black')) },
{ title: '亮片总重量 / kg', dataIndex: ['bright', 'totalWeight'], key: 'brightTotal', align: 'center', width: 160, render: value => numberText(value) },
{ title: '亮片合格重量 / kg', dataIndex: ['bright', 'qualifiedWeight'], key: 'brightQualified', align: 'center', width: 160, render: value => numberText(value) }, { title: '亮片合格重量 / kg', dataIndex: ['bright', 'qualifiedWeight'], key: 'brightQualified', align: 'center', width: 160, render: value => numberText(value) },
{ title: defectDisplay === 'rate' ? '亮片报废率' : '亮片报废重量 / kg', dataIndex: ['bright', 'scrapWeight'], key: 'brightScrap', align: 'center', width: 160, render: (_: unknown, row: TrendMetricRow) => defectDisplay === 'rate' ? rateText(defectWeightRate(row.bright.scrapWeight,row.bright.totalWeight)) : numberText(row.bright.scrapWeight) }, { title: defectDisplay === 'rate' ? '亮片报废率' : '亮片报废重量 / kg', dataIndex: ['bright', 'scrapWeight'], key: 'brightScrap', align: 'center', width: 160, render: (_: unknown, row: TrendMetricRow) => defectDisplay === 'rate' ? rateText(defectWeightRate(queryScrapWeight(row.bright,'bright',rateBasis),row.bright.totalWeight)) : numberText(queryScrapWeight(row.bright,'bright',rateBasis)) },
{ title: rateBasis === 'original' ? '亮片合格率' : '亮片不含本部报废调整率', dataIndex: ['bright', 'rate'], key: 'brightRate', align: 'center', width: 180, render: (_: number | null, row: TrendMetricRow) => rateText(visibleStageRate(row, 'bright', rateBasis)) }, { 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 columns={columns} dataSource={rows} rowKey={row => String(row.month)} pagination={{ current: currentPage, pageSize, showSizeChanger: rows.length > SUMMARY_PAGE_SIZE, pageSizeOptions: SUMMARY_PAGE_SIZE_OPTIONS, showTotal: (total, range) => `显示 ${range[0]}–${range[1]} 行,共 ${total} 个月`, onChange: (nextPage, nextPageSize) => { setPageSize(nextPageSize); setCurrentPage(nextPageSize === pageSize ? nextPage : 1); } }} scroll={{ x: 1130 }} /> 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={{ current: currentPage, pageSize, showSizeChanger: rows.length > SUMMARY_PAGE_SIZE, pageSizeOptions: SUMMARY_PAGE_SIZE_OPTIONS, showTotal: (total, range) => `显示 ${range[0]}–${range[1]} 行,共 ${total} 个月`, onChange: (nextPage, nextPageSize) => { setPageSize(nextPageSize); setCurrentPage(nextPageSize === pageSize ? nextPage : 1); } }} scroll={{ x: columns.reduce((total, column) => total + Number(column.width || 0), 0) }} />
{showMonthLinks && <div className="trend-month-links">{rows.map(row => <Button key={row.key} type="link" onClick={() => onMonth(row.month)}>{row.periodLabel || row.month}汇总</Button>)}</div>} {showMonthLinks && <div className="trend-month-links">{rows.map(row => <Button key={row.key} type="link" onClick={() => onMonth(row.month)}>{row.periodLabel || row.month}汇总</Button>)}</div>}
</div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前数据未返回趋势" />; </div> : <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} description="当前数据未返回趋势" />;
} }
+9 -6
View File
@@ -1,8 +1,10 @@
import { queryScrapWeight } from './queryMetricValues';
import { useStickyQueryMetrics } from './useStickyQueryMetrics';
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Alert, App, Button, Checkbox, Empty, Input, Modal, Segmented, Select, Spin } from 'antd'; import { Alert, App, Button, Checkbox, Empty, Input, Modal, Segmented, Select, Spin } from 'antd';
import { DownloadOutlined, ReloadOutlined, SearchOutlined } from '@ant-design/icons'; import { DownloadOutlined, ReloadOutlined, SearchOutlined } from '@ant-design/icons';
import { api, decodeQueryValueList, encodeQueryValueList } from './api'; import { api, decodeQueryValueList, encodeQueryValueList } from './api';
import { MetricTable, MetricCard, DefectBreakdown, DefectParetoPanel, SectionHeading, RecordsDrawer, TrendChart, fullYearTrend, queryFromLocation } from './QueryPage'; import { MetricTable, MetricCard, rateMetricLabel, DefectBreakdown, DefectParetoPanel, SectionHeading, RecordsDrawer, TrendChart, fullYearTrend, queryFromLocation } from './QueryPage';
import { StageSourceFilters } from './StageSourceFilters'; import { StageSourceFilters } from './StageSourceFilters';
import { stageProductQuery, sortStageRowsByTotalWeight } from './stageProductQuery'; import { stageProductQuery, sortStageRowsByTotalWeight } from './stageProductQuery';
import { usePageCache } from './pageCache'; import { usePageCache } from './pageCache';
@@ -15,6 +17,7 @@ import './stage-product.css';
const weight=(v:number|null|undefined)=>typeof v==='number'?v.toLocaleString('zh-CN',{maximumFractionDigits:2}):'—'; const weight=(v:number|null|undefined)=>typeof v==='number'?v.toLocaleString('zh-CN',{maximumFractionDigits:2}):'—';
const rate=(v:number|null|undefined)=>typeof v==='number'?`${(v*100).toFixed(2)}%`:'—'; const rate=(v:number|null|undefined)=>typeof v==='number'?`${(v*100).toFixed(2)}%`:'—';
export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onUnauthorized:(error:unknown)=>boolean}) { export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onUnauthorized:(error:unknown)=>boolean}) {
const stickyPageRef = useStickyQueryMetrics();
const {message}=App.useApp();const {active,initialSearch,refreshKey,onLocationChange}=usePageCache(); const {message}=App.useApp();const {active,initialSearch,refreshKey,onLocationChange}=usePageCache();
const [initial]=useState(()=>queryFromLocation(initialSearch));const defaults=previousCompleteMonth(); const [initial]=useState(()=>queryFromLocation(initialSearch));const defaults=previousCompleteMonth();
const [period,setPeriod]=useState<PeriodKind>(initial.quarter?'quarter':initial.month?'month':initial.year?'year':'month'); const [period,setPeriod]=useState<PeriodKind>(initial.quarter?'quarter':initial.month?'month':initial.year?'year':'month');
@@ -61,7 +64,7 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
const openDetail=(row:MetricRow|null,_stage:Stage,selectedMonth?:number)=>{if(!applied||!current?.release)return;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;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);}}; 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'; const formulaKey=stage==='black'?'blackRate':rateBasis==='original'?'brightRate':'brightRateWithoutHeadquartersScrap';
return <div className="query-page stage-product-page"> return <div className="query-page stage-product-page" ref={stickyPageRef}>
{supportError&&<Alert showIcon type="error" message="查询条件读取失败" description={supportError} action={<Button onClick={()=>void loadSupport()}>重试</Button>}/>} {supportError&&<Alert showIcon type="error" message="查询条件读取失败" description={supportError} action={<Button onClick={()=>void loadSupport()}>重试</Button>}/>}
<section className="query-toolbar panel" aria-label={`${label}汇总条件`}> <section className="query-toolbar panel" aria-label={`${label}汇总条件`}>
<Segmented aria-label="统计周期" value={period} options={[{label:'年度',value:'year'},{label:'季度',value:'quarter'},{label:'月度',value:'month'}]} onChange={v=>setPeriod(v as PeriodKind)}/> <Segmented aria-label="统计周期" value={period} options={[{label:'年度',value:'year'},{label:'季度',value:'quarter'},{label:'月度',value:'month'}]} onChange={v=>setPeriod(v as PeriodKind)}/>
@@ -80,14 +83,14 @@ export default function StageProductPage({stage,onUnauthorized}:{stage:Stage;onU
</section> </section>
{error&&<Alert showIcon type="error" message="查询失败" description={error} action={<Button onClick={()=>setRevision(v=>v+1)}>重试</Button>}/>} {error&&<Alert showIcon type="error" message="查询失败" description={error} action={<Button onClick={()=>setRevision(v=>v+1)}>重试</Button>}/>}
<section className="metric-strip stage-metric-strip" aria-label="质量指标" aria-busy={loading} inert={!current}> <section className="metric-strip stage-metric-strip" aria-label="质量指标" aria-busy={loading} inert={!current}>
{stage==='bright'&&<div className="rate-basis-control"><span>亮片本部报废调整</span><Segmented size="small" aria-label="合格率口径" value={rateBasis} options={[{label:'原口径',value:'original'},{label:'去本部报废',value:'withoutHeadquartersScrap'}]} onChange={v=>setRateBasis(v as typeof rateBasis)}/></div>} {stage==='bright'&&<div className="rate-basis-control"><Segmented size="small" aria-label="合格率口径" value={rateBasis} options={[{label:'原口径',value:'original'},{label:'去本部报废',value:'withoutHeadquartersScrap'}]} onChange={v=>setRateBasis(v as typeof rateBasis)}/></div>}
<MetricCard primary stage={stage} label={`${label}${rateBasis==='original'?'合格率':'调整率'}`} value={rate(stageRate)} onClick={()=>setBasisOpen(true)}/> <MetricCard primary stage={stage} label={rateMetricLabel(`${label}合格率`, stage === 'bright' ? rateBasis : 'original')} value={rate(stageRate)} onClick={()=>setBasisOpen(true)}/>
<MetricCard label="合格重量" value={`${weight(summary?.qualifiedWeight)} kg`} onClick={()=>openDetail(null,stage)}/> <MetricCard label="合格重量" value={`${weight(summary?.qualifiedWeight)} kg`} onClick={()=>openDetail(null,stage)}/>
<MetricCard label="报废重量" value={`${weight(summary?.scrapWeight)} kg`} onClick={()=>openDetail(null,stage)}/> <MetricCard label="报废重量" value={`${weight(queryScrapWeight(summary,stage,rateBasis))} kg`} onClick={()=>openDetail(null,stage)}/>
<MetricCard label="总重量" value={`${weight(summary?.totalWeight)} kg`} onClick={()=>openDetail(null,stage)}/> <MetricCard label="总重量" value={`${weight(summary?.totalWeight)} kg`} onClick={()=>openDetail(null,stage)}/>
</section> </section>
<div className="query-quality-summary"><span>{current?`来源覆盖 ${current.coverage.sourceMonths.filter(m=>(stage==='black'?m.blackRows:m.brightRows)>0).length} 个月 · 参与计算 ${current.coverage.includedRows.toLocaleString()} 行`:loading?'正在查询…':'暂无统计结果'}</span><Button type="link" disabled={!current} onClick={()=>setBasisOpen(true)}>计算口径</Button></div> <div className="query-quality-summary"><span>{current?`来源覆盖 ${current.coverage.sourceMonths.filter(m=>(stage==='black'?m.blackRows:m.brightRows)>0).length} 个月 · 参与计算 ${current.coverage.includedRows.toLocaleString()} 行`:loading?'正在查询…':'暂无统计结果'}</span><Button type="link" disabled={!current} onClick={()=>setBasisOpen(true)}>计算口径</Button></div>
<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 icon={<DownloadOutlined/>} aria-label="导出产品汇总" loading={exporting} disabled={!current||loading} onClick={()=>void runExport()}/></div></div> <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 icon={<DownloadOutlined/>} aria-label="Excel导出" loading={exporting} disabled={!current||loading} onClick={()=>void runExport()}>Excel导出</Button></div></div>
<Spin spinning={loading}><MetricTable ref={exporter} exportFilename={`${label}产品汇总-${year}`} rows={sortedRows} view="product" period={period} month={month} quarter={quarter} fullFields={fullFields} defectDisplay={defectDisplay} rateBasis={rateBasis} onlyStage={stage} onDetail={openDetail} onBasis={()=>setBasisOpen(true)} onDrilldown={row=>{setProduct([row.product||'__UNASSIGNED__']);setSearch('');setApplied({...applied!,product:row.product||'__UNASSIGNED__',productSearch:undefined});setRevision(v=>v+1);}}/></Spin> <Spin spinning={loading}><MetricTable ref={exporter} exportFilename={`${label}产品汇总-${year}`} rows={sortedRows} view="product" period={period} month={month} quarter={quarter} fullFields={fullFields} defectDisplay={defectDisplay} rateBasis={rateBasis} onlyStage={stage} onDetail={openDetail} onBasis={()=>setBasisOpen(true)} onDrilldown={row=>{setProduct([row.product||'__UNASSIGNED__']);setSearch('');setApplied({...applied!,product:row.product||'__UNASSIGNED__',productSearch:undefined});setRevision(v=>v+1);}}/></Spin>
</section> </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}/>}<Spin spinning={trendLoading}><div className="trend-chart-shell" aria-busy={trendLoading}>{trendMode==='data'?<MetricTable exportFilename={`${label}月度趋势-${year}`} rows={visibleTrend} 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={visibleTrend} mode={trendMode} stage={stage} onlyStage={stage} rateBasis={rateBasis} targetRate={null} onMonth={selectTrendPeriod}/>}</div></Spin><div className="chart-footnote"><span>指标由来源分量汇总,使用当前生效公式。</span><span>点击期间筛选</span></div></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}/>}<Spin spinning={trendLoading}><div className="trend-chart-shell" aria-busy={trendLoading}>{trendMode==='data'?<MetricTable exportFilename={`${label}月度趋势-${year}`} rows={visibleTrend} 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={visibleTrend} mode={trendMode} stage={stage} onlyStage={stage} rateBasis={rateBasis} targetRate={null} onMonth={selectTrendPeriod}/>}</div></Spin><div className="chart-footnote"><span>指标由来源分量汇总,使用当前生效公式。</span><span>点击期间筛选</span></div></section>
+21
View File
@@ -0,0 +1,21 @@
import type { MetricRow, Stage, StageMetric } from './types';
export type QueryRateBasis = 'original' | 'withoutHeadquartersScrap';
/** 只调整展示用报废重量,不改来源数据、总重量或服务端合格率。 */
export function queryScrapWeight(metric: StageMetric | null | undefined, stage: Stage, basis: QueryRateBasis): number | null {
const scrap = metric?.scrapWeight;
if (typeof scrap !== 'number' || !Number.isFinite(scrap)) return null;
if (stage !== 'bright' || basis === 'original') return scrap;
const headquarters = metric?.headquartersScrapWeight;
// 缺失或无权限的数据不能按零处理,避免误称已经扣除。
if (typeof headquarters !== 'number' || !Number.isFinite(headquarters)) return null;
return scrap - headquarters;
}
export function queryTotalScrapWeight(row: MetricRow | undefined, basis: QueryRateBasis): number | null {
if (!row) return null;
const black = row.coverage.blackRows > 0 ? queryScrapWeight(row.black, 'black', basis) : 0;
const bright = row.coverage.brightRows > 0 ? queryScrapWeight(row.bright, 'bright', basis) : 0;
return black == null || bright == null ? null : black + bright;
}
+58 -1
View File
@@ -25,7 +25,7 @@ body, button, input, textarea, select { font-family: var(--font-ui); }
--font-note: 12px; --font-note: 12px;
--font-section: 14px; --font-section: 14px;
--font-metric: 30px; --font-metric: 30px;
--font-metric-primary: 32px; --font-metric-primary: 42px;
} }
.query-page .metric-label, .query-page .metric-label,
.query-page .metric-card.primary .metric-label { .query-page .metric-card.primary .metric-label {
@@ -51,3 +51,60 @@ body, button, input, textarea, select { font-family: var(--font-ui); }
.query-page .defect-name { font-size: var(--font-body); font-weight: 500; } .query-page .defect-name { font-size: var(--font-body); font-weight: 500; }
.query-page .defect-header { font-size: var(--font-note); font-weight: 500; } .query-page .defect-header { font-size: var(--font-note); font-weight: 500; }
.query-page :is(.defect-weight, .defect-rate) { font-size: var(--font-table); } .query-page :is(.defect-weight, .defect-rate) { font-size: var(--font-table); }
/* 月份与产业部对象同级,综合合格率略高于普通数字,表头保持统一。 */
.query-page {
--font-query-object: 16px;
--font-query-combined: 15px;
--font-query-header: 14px;
}
:root .query-page .metric-table-scroll .object-cell :is(strong, .object-drilldown, .object-drilldown > span),
:root .query-page .trend-data-table .ant-table-tbody > tr > td:first-child .ant-btn {
font-size: var(--font-query-object);
font-weight: 600;
}
:root .query-page .metric-table-scroll :is(.combined-value, .ant-table-tbody .combined-column) {
font-size: var(--font-query-combined);
}
:root .query-page .metric-table-scroll .ant-table-thead > tr > th,
:root .query-page .metric-table-scroll .ant-table-thead :is(.header-link, .stage-heading) {
font-family: var(--font-ui);
font-size: var(--font-query-header);
font-weight: 600;
line-height: 1.4;
}
/* 跨两行的对象、综合合格率和操作表头加强层级。 */
:root .query-page .metric-table-scroll .ant-table-thead > tr > th[rowspan="2"],
:root .query-page .metric-table-scroll .ant-table-thead > tr > th[rowspan="2"] .header-link {
font-weight: 700;
}
.query-total-weight-title { display: inline-flex; align-items: center; justify-content: center; gap: 4px; }
.query-total-weight-title .anticon { color: var(--muted-ink); font-size: 12px; cursor: help; }
.query-total-weight-title .anticon:focus-visible { outline: 2px solid var(--blue); outline-offset: 2px; }
:root .query-page .metric-table-scroll th[rowspan="2"] .query-total-weight-title { font-weight: 700; }
.query-rate-label { display: inline-flex; flex-direction: column; align-items: center; gap: 2px; }
.metric-label .query-rate-label { align-items: flex-start; }
:root .query-page .query-rate-subtitle {
color: var(--muted-ink);
font-family: var(--font-ui);
font-size: 11px;
font-weight: 400;
line-height: 1.3;
white-space: nowrap;
}
.query-rate-rule-title > .anticon { align-self: flex-start; margin-top: 3px; }
/* 亮片二级表头单行显示口径,避免增加整行高度。 */
.query-page .metric-table-scroll .rate-cell.bright .query-rate-label {
flex-direction: row;
gap: 2px;
white-space: nowrap;
}
.query-page .metric-table-scroll .rate-cell.bright .query-rate-rule-title > .anticon {
align-self: center;
margin-top: 0;
}
+29
View File
@@ -0,0 +1,29 @@
import { useLayoutEffect, useRef } from 'react';
/** 跟随筛选栏实际高度定位指标区,兼容筛选展开、换行和页面缩放。 */
export function useStickyQueryMetrics() {
const pageRef = useRef<HTMLDivElement>(null);
useLayoutEffect(() => {
const page = pageRef.current;
const toolbar = page?.querySelector<HTMLElement>('.query-toolbar');
const metrics = page?.querySelector<HTMLElement>('.metric-strip');
if (!page || !toolbar || !metrics) return;
const update = () => {
const gap = Number.parseFloat(getComputedStyle(page).rowGap) || 0;
const top = (Number.parseFloat(getComputedStyle(toolbar).top) || 0) + toolbar.offsetHeight + gap;
const scale = Number.parseFloat(getComputedStyle(document.documentElement).zoom) || 1;
// 小屏幕至少保留一段内容阅读区,避免筛选栏和指标占满视口。
const fits = top + metrics.offsetHeight < window.innerHeight / scale - 160;
page.style.setProperty('--query-metrics-top', `${top}px`);
page.style.setProperty('--query-metrics-gap', `${gap}px`);
page.style.setProperty('--query-metrics-position', fits ? 'sticky' : 'static');
};
update();
const observer = new ResizeObserver(update);
observer.observe(toolbar);
observer.observe(metrics);
window.addEventListener('resize', update);
return () => { observer.disconnect(); window.removeEventListener('resize', update); };
}, []);
return pageRef;
}
+44
View File
@@ -42,3 +42,47 @@ body, .app-shell, .main-column { color: var(--ink); background: var(--background
.workspace-theme-dropdown .ant-dropdown-menu-item { border-radius: calc(var(--control-radius) - 1px); } .workspace-theme-dropdown .ant-dropdown-menu-item { border-radius: calc(var(--control-radius) - 1px); }
:root[data-workspace-theme='dark'] .panel, :root[data-workspace-theme='dark'] .panel,
:root[data-workspace-theme='dark'] .metric-strip { box-shadow: none; } :root[data-workspace-theme='dark'] .metric-strip { box-shadow: none; }
/* 查询表格统一阶段语义配色,亮片沿用原黑片蓝色,综合合格率沿用原亮片绿色。 */
.query-page {
--query-black: #20252b;
--query-bright: var(--blue-dark);
--query-combined: var(--teal);
--table-combined: color-mix(in srgb, var(--query-combined) 5%, var(--surface));
--table-bright-head: color-mix(in srgb, var(--query-bright) 10%, var(--surface));
--table-black-head: color-mix(in srgb, var(--query-black) 7%, var(--surface));
}
:root[data-workspace-theme='dark'] .query-page {
/* 深色底上的黑片使用中性浅灰,保留黑白体系及文字对比度。 */
--query-black: #d5d8de;
}
:root .query-page .metric-table-scroll :is(.stage-heading.black, .rate-cell.black, .rate-cell.black .table-value) { color: var(--query-black); }
:root .query-page .metric-table-scroll :is(.stage-heading.bright, .rate-cell.bright, .rate-cell.bright .table-value) { color: var(--query-bright); }
:root .query-page .metric-table-scroll :is(.combined-column, .combined-value, .combined-column .header-link) { color: var(--query-combined); }
:root .query-page .metric-table-scroll :is(.rate-cell, .combined-column) { font-weight: 600; }
:root .query-page .metric-table-scroll .stage-heading.black i { background: var(--query-black); }
:root .query-page .metric-table-scroll .stage-heading.bright i { background: var(--query-bright); }
:root .query-page .metric-table-scroll .ant-table-thead > tr:first-child > th:has(.stage-heading.black) { background: var(--table-black-head) !important; }
:root .query-page .metric-table-scroll .ant-table-thead > tr:first-child > th:has(.stage-heading.bright) { background: var(--table-bright-head) !important; }
:root .query-page .metric-card.black .metric-value { color: var(--query-black); }
:root .query-page .metric-card.bright .metric-value { color: var(--query-bright); }
:root .query-page .metric-card.primary .metric-value { color: var(--query-combined); }
:root .query-page .metric-card.primary { background: var(--table-combined); }
:root .query-page .metric-card.black .stage-dot { background: var(--query-black); }
:root .query-page .metric-card.bright .stage-dot { background: var(--query-bright); }
/* 右侧冻结区自行绘制起始边框,避免依赖被隐藏的默认阴影。 */
:root .query-page .metric-table-scroll .combined-column.ant-table-cell-fix {
border-inline-start: 1px solid var(--metric-grid) !important;
}
:root .query-page .metric-table-scroll th.combined-column.ant-table-cell-fix {
border-inline-start-color: var(--metric-grid-head) !important;
}
/* 与筛选栏组成连续的顶部冻结区,动态偏移由实际筛选栏高度计算。 */
:root .query-page > .metric-strip {
position: var(--query-metrics-position, static);
top: var(--query-metrics-top, auto);
z-index: 34;
box-shadow: 0 calc(-1 * var(--query-metrics-gap, 11px)) 0 var(--background);
}
+40 -11
View File
@@ -3,6 +3,7 @@ import assert from 'node:assert/strict';
import fs from 'node:fs'; import fs from 'node:fs';
import ts from 'typescript'; import ts from 'typescript';
import React from 'react'; import React from 'react';
import { queryScrapWeight } from '../src/queryMetricValues.ts';
import { defectWeightRate } from '../src/trendMetrics.ts'; import { defectWeightRate } from '../src/trendMetrics.ts';
import { createMetricWorkbook, workbookColumns } from '../src/metricWorkbook.ts'; import { createMetricWorkbook, workbookColumns } from '../src/metricWorkbook.ts';
@@ -10,18 +11,19 @@ const source = fs.readFileSync(new URL('../src/QueryPage.tsx', import.meta.url),
const slice = (start, end) => source.slice(source.indexOf(start), source.indexOf(end, source.indexOf(start))); const slice = (start, end) => source.slice(source.indexOf(start), source.indexOf(end, source.indexOf(start)));
const helpers = slice('function numberText(', 'const SYSTEM_SOURCE_VERSION_KEYS') const helpers = slice('function numberText(', 'const SYSTEM_SOURCE_VERSION_KEYS')
+ slice('function hasStageRows(', 'function fullYearTrend(') + slice('function hasStageRows(', 'function fullYearTrend(')
+ slice('function objectLabel(', 'interface ChartTooltipParam'); + slice('function objectLabel(', 'interface ChartTooltipParam')
+ slice('const totalWeightTitle =', 'export function MetricTable(');
const table = slice('export function MetricTable(', 'function MetricTablePagination(').replace('export function', 'function'); const table = slice('export function MetricTable(', 'function MetricTablePagination(').replace('export function', 'function');
function fixture(props) { function fixture(props) {
let exported, detail = 0, basis = 0; let exported, detail = 0, basis = 0;
const ref = {}; const ref = {};
const render = new Function('React', 'useImperativeHandle', 'defectWeightRate', 'downloadMetricWorkbook', ts.transpileModule(` const render = new Function('React', 'useImperativeHandle', 'defectWeightRate', 'queryScrapWeight', 'downloadMetricWorkbook', ts.transpileModule(`
const MONTHS=Array.from({length:12},(_,i)=>String(i+1).padStart(2,'0')+'月'); const MONTHS=Array.from({length:12},(_,i)=>String(i+1).padStart(2,'0')+'月');
const SUMMARY_PAGE_SIZE=15; const SUMMARY_PAGE_SIZE=15;
const useCompactTable=()=>false, useState=v=>[v,()=>{}], useEffect=()=>{}; const useCompactTable=()=>false, useState=v=>[v,()=>{}], useEffect=()=>{};
const Button='Button', Table='Table', MetricTablePagination='Pagination'; const Button='Button', Table='Table', MetricTablePagination='Pagination', Tooltip='Tooltip', InfoCircleOutlined='Info';
${helpers}\n${table}\nreturn MetricTable; ${helpers}\n${table}\nreturn MetricTable;
`, {compilerOptions:{jsx:ts.JsxEmit.React,target:ts.ScriptTarget.ES2022}}).outputText)(React, (target, create) => Object.assign(target, create()), defectWeightRate, async (filename, columns, rows, value) => { `, {compilerOptions:{jsx:ts.JsxEmit.React,target:ts.ScriptTarget.ES2022}}).outputText)(React, (target, create) => Object.assign(target, create()), defectWeightRate, queryScrapWeight, async (filename, columns, rows, value) => {
exported = { filename, columns, rows, workbook: await createMetricWorkbook(columns, rows, value) }; exported = { filename, columns, rows, workbook: await createMetricWorkbook(columns, rows, value) };
}); });
const tree = render({ref,exportFilename:'验收',period:'month',month:9,quarter:3,rateBasis:'original',fullFields:false,onDetail(){detail++;},onBasis(){basis++;},onDrilldown(){},...props}); const tree = render({ref,exportFilename:'验收',period:'month',month:9,quarter:3,rateBasis:'original',fullFields:false,onDetail(){detail++;},onBasis(){basis++;},onDrilldown(){},...props});
@@ -45,14 +47,18 @@ for (const view of ['overall','department','group','product','projectGroup']) {
const {workbook,columns}=ui.exported; const {workbook,columns}=ui.exported;
const fields=workbookColumns(columns), sheet=workbook.getWorksheet('质量汇总'); const fields=workbookColumns(columns), sheet=workbook.getWorksheet('质量汇总');
if(view==='product')assert.equal(find(columns.find(c=>c.key==='object').render(null,row),n=>n.type==='small'),undefined); if(view==='product')assert.equal(find(columns.find(c=>c.key==='object').render(null,row),n=>n.type==='small'),undefined);
assert.equal(sheet.rowCount,19);assert.equal(sheet.columnCount,fullFields?13:8); assert.equal(sheet.rowCount,19);assert.equal(sheet.columnCount,fullFields?13:10);
assert.deepEqual(sheet.getRow(1).values.slice(1),fields.map(v=>v.header)); assert.deepEqual(sheet.getRow(1).values.slice(1),fields.map(v=>v.header));
assert.equal(sheet.getRow(2).getCell(3).value,1234.567); const at=key=>fields.findIndex(field=>field.key===key)+1;
assert.equal(sheet.getRow(2).getCell(4).value,fullFields?1250:0); assert.equal(sheet.getRow(2).getCell(at('black-qualifiedWeight')).value,1234.567);
assert.equal(sheet.getRow(2).getCell(at('black-totalWeight')).value,1250);
assert.ok(at('black-totalWeight')<at('black-qualifiedWeight'));
assert.ok(at('bright-totalWeight')<at('bright-qualifiedWeight'));
assert.equal(fields.at(-1).key,'compositeRate');
assert.equal(fields.some(f=>f.key.includes('defect-')),fullFields); assert.equal(fields.some(f=>f.key.includes('defect-')),fullFields);
assert.equal(fields.some(f=>f.key.endsWith('headquartersScrapWeight')),fullFields); assert.equal(fields.some(f=>f.key.endsWith('headquartersScrapWeight')),fullFields);
assert.equal(fields.some(f=>f.key==='actions'),false); assert.equal(fields.some(f=>f.key==='actions'),false);
assert.equal(sheet.getColumn(2).numFmt,'0.00%'); assert.equal(sheet.getColumn(at('compositeRate')).numFmt,'0.00%');
assert.equal(sheet.getColumn(3).numFmt,'#,##0.0'); assert.equal(sheet.getColumn(3).numFmt,'#,##0.0');
for (const field of columns.flatMap(c=>c.children||[c]).filter(c=>c.key!=='actions'&&c.key!=='object')) { for (const field of columns.flatMap(c=>c.children||[c]).filter(c=>c.key!=='actions'&&c.key!=='object')) {
const rendered=field.render(null,row); const rendered=field.render(null,row);
@@ -70,14 +76,20 @@ for (const view of ['overall','department','group','product','projectGroup']) {
test('adjusted rates, missing stage and zero weight retain their meaning', async () => { test('adjusted rates, missing stage and zero weight retain their meaning', async () => {
const ui=fixture({rows:[row,{...row,key:'missing',black:{...stage,qualifiedWeight:null,rate:null},coverage:{blackRows:0,brightRows:1}}],view:'product',rateBasis:'withoutHeadquartersScrap'}); const ui=fixture({rows:[row,{...row,key:'missing',black:{...stage,qualifiedWeight:null,rate:null},coverage:{blackRows:0,brightRows:1}}],view:'product',rateBasis:'withoutHeadquartersScrap'});
await ui.ref.exportExcel();const sheet=ui.exported.workbook.getWorksheet('质量汇总'); await ui.ref.exportExcel();const sheet=ui.exported.workbook.getWorksheet('质量汇总');
assert.equal(sheet.getCell('B2').value,0.98);assert.equal(sheet.getCell('H2').value,0.99); const fields=workbookColumns(ui.exported.columns), at=key=>fields.findIndex(field=>field.key===key)+1;
assert.equal(sheet.getCell('E3').value,null);assert.equal(sheet.getCell('C3').value,null);assert.equal(sheet.getCell('D2').value,0); assert.equal(sheet.getRow(2).getCell(at('compositeRate')).value,0.98);
assert.equal(sheet.getRow(2).getCell(at('bright-rate')).value,0.99);
assert.equal(sheet.getRow(3).getCell(at('black-rate')).value,null);
assert.equal(sheet.getRow(3).getCell(at('black-qualifiedWeight')).value,null);
assert.equal(sheet.getRow(2).getCell(at('black-scrapWeight')).value,0);
}); });
test('overall yearly export preserves month labels and leaves unavailable values blank', async () => { test('overall yearly export preserves month labels and leaves unavailable values blank', async () => {
const ui=fixture({rows:[{...row,month:2},{...row,key:'missing',month:3,noData:true,black:{...stage,qualifiedWeight:null,rate:null},bright:{...stage,qualifiedWeight:null,rate:null},coverage:{blackRows:0,brightRows:0}}],view:'overall',period:'year'}); const ui=fixture({rows:[{...row,month:2},{...row,key:'missing',month:3,noData:true,black:{...stage,qualifiedWeight:null,rate:null},bright:{...stage,qualifiedWeight:null,rate:null},coverage:{blackRows:0,brightRows:0}}],view:'overall',period:'year'});
await ui.ref.exportExcel();const sheet=ui.exported.workbook.getWorksheet('质量汇总'); await ui.ref.exportExcel();const sheet=ui.exported.workbook.getWorksheet('质量汇总');
assert.equal(sheet.getCell('A2').value,'02月');assert.equal(sheet.getCell('A3').value,'03月');assert.equal(sheet.getCell('B3').value,null); assert.equal(sheet.getCell('A2').value,'02月');assert.equal(sheet.getCell('A3').value,'03月');
const composite=workbookColumns(ui.exported.columns).findIndex(field=>field.key==='compositeRate')+1;
assert.equal(sheet.getRow(3).getCell(composite).value,null);
}); });
for (const view of ['overall','department','group','product','projectGroup']) test(`${view}: defect-rate mode uses same-stage total and exports numeric percentages`,async()=>{ for (const view of ['overall','department','group','product','projectGroup']) test(`${view}: defect-rate mode uses same-stage total and exports numeric percentages`,async()=>{
@@ -111,3 +123,20 @@ test('single-stage rate mode exports only its stage; missing or zero denominator
assert.equal(sheet.getRow(3).getCell(at('black-defect-裂纹')).value,null); assert.equal(sheet.getRow(3).getCell(at('black-defect-裂纹')).value,null);
assert.equal(sheet.getRow(4).getCell(at('black-scrapWeight')).value,0); assert.equal(sheet.getRow(4).getCell(at('black-scrapWeight')).value,0);
}); });
test('本部报废原口径紧随扩散废,调整口径隐藏并在表格及Excel同步扣减', async () => {
const data={...row,bright:{...stage,scrapWeight:100,headquartersScrapWeight:30,defects:[{name:'扩散废',weight:20},{name:'加工废',weight:40}]}};
const original=fixture({rows:[data],view:'overall',fullFields:true});await original.ref.exportExcel();
const keys=workbookColumns(original.exported.columns).map(f=>f.key);
assert.equal(keys.indexOf('bright-headquartersScrapWeight'),keys.indexOf('bright-defect-扩散废')+1);
for(const fullFields of [false,true]) {
const adjusted=fixture({rows:[data],view:'overall',fullFields,rateBasis:'withoutHeadquartersScrap'});await adjusted.ref.exportExcel();
const fields=workbookColumns(adjusted.exported.columns),at=key=>fields.findIndex(f=>f.key===key)+1;
assert.equal(fields.some(f=>f.key==='bright-headquartersScrapWeight'),false);
const scrapColumn=adjusted.exported.columns.flatMap(c=>c.children||[c]).find(c=>c.key==='bright-scrapWeight');
assert.equal(scrapColumn.render(null,data).props.children,'70.0');
assert.equal(adjusted.exported.workbook.getWorksheet('质量汇总').getRow(2).getCell(at('bright-scrapWeight')).value,70);
assert.equal(adjusted.exported.workbook.getWorksheet('质量汇总').getRow(2).getCell(at('bright-totalWeight')).value,1250);
}
assert.equal(data.bright.scrapWeight,100);
});
@@ -0,0 +1,27 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { queryScrapWeight, queryTotalScrapWeight } from '../src/queryMetricValues.ts';
const metric = { qualifiedWeight: 900, totalWeight: 1000, scrapWeight: 100, headquartersScrapWeight: 25, rate: .9, rateWithoutHeadquartersScrap: .925, defects: [] };
test('调整口径仅扣减亮片报废;原始数据、总重及合格率保持不变', () => {
const before = structuredClone(metric);
assert.equal(queryScrapWeight(metric, 'bright', 'original'), 100);
assert.equal(queryScrapWeight(metric, 'bright', 'withoutHeadquartersScrap'), 75);
assert.equal(queryScrapWeight(metric, 'black', 'withoutHeadquartersScrap'), 100);
assert.deepEqual(metric, before);
});
test('报废总重同步采用扣减后的亮片重量', () => {
const row = { black: { ...metric, scrapWeight: 50 }, bright: metric, coverage: { blackRows: 1, brightRows: 1 } };
assert.equal(queryTotalScrapWeight(row, 'original'), 150);
assert.equal(queryTotalScrapWeight(row, 'withoutHeadquartersScrap'), 125);
});
test('本部报废缺失时不冒充已完成扣减,零值则保留原报废', () => {
assert.equal(queryScrapWeight({ ...metric, headquartersScrapWeight: null }, 'bright', 'withoutHeadquartersScrap'), null);
assert.equal(queryScrapWeight({ ...metric, headquartersScrapWeight: 0 }, 'bright', 'withoutHeadquartersScrap'), 100);
assert.equal(queryScrapWeight({ ...metric, scrapWeight: null }, 'bright', 'withoutHeadquartersScrap'), null);
});
test('缺少阶段来源不计入合计;有来源但无法扣减时不显示误导合计', () => {
const row = { black: metric, bright: { ...metric, headquartersScrapWeight: null }, coverage: { blackRows: 1, brightRows: 0 } };
assert.equal(queryTotalScrapWeight(row, 'withoutHeadquartersScrap'), 100);
assert.equal(queryTotalScrapWeight({ ...row, coverage: { blackRows: 1, brightRows: 1 } }, 'withoutHeadquartersScrap'), null);
});