feat: drill defect trends into detailed rates and preserve query context
This commit is contained in:
+75
-28
@@ -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;
|
||||
|
||||
|
||||
@@ -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}>
|
||||
|
||||
@@ -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 });
|
||||
},
|
||||
|
||||
@@ -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
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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;}
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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};
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import ts from 'typescript';
|
||||
import React from 'react';
|
||||
import { defectScope,defectCell,defectRateLabel } from '../src/defectDrilldown.ts';
|
||||
const read=name=>fs.readFileSync(new URL(`../src/${name}`,import.meta.url),'utf8');
|
||||
const transpile=code=>ts.transpileModule(code,{compilerOptions:{target:ts.ScriptTarget.ES2022,jsx:ts.JsxEmit.React}}).outputText;
|
||||
const deferred=()=>{let resolve,reject;const promise=new Promise((r,j)=>{resolve=r;reject=j;});return {promise,resolve,reject};};
|
||||
const tick=()=>new Promise(resolve=>setImmediate(resolve));
|
||||
function fixture() {
|
||||
const slots=[],effects=[],requests=[],catalog=[];let index=0,dirty=false,queue=[],output;
|
||||
const props={active:true,mode:'defects',stage:'bright',query:{year:2026,view:'product',releaseId:'r',product:'P'},trendQuery:{year:2026,view:'product',releaseId:'r',product:'P',trendGranularity:'month'},tableQuery:{year:2026,view:'product',releaseId:'r',product:'P'},tableDimension:'product',tableGranularity:'month',onUnauthorized:()=>false,refreshKey:0,display:'weight',onDisplay:v=>props.display=v};
|
||||
const hooks={
|
||||
useState(initial){const n=index++;if(!(n in slots))slots[n]=initial;return [slots[n],v=>{const next=typeof v==='function'?v(slots[n]):v;if(!Object.is(slots[n],next)){slots[n]=next;dirty=true;}}];},
|
||||
useRef(initial){const n=index++;return slots[n]??(slots[n]={current:initial});},
|
||||
useMemo(fn){index++;return fn();},
|
||||
useEffect(fn,deps){const n=index++,old=effects[n];if(!old||deps.some((d,i)=>!Object.is(d,old.deps[i])))queue.push(()=>{old?.cleanup?.();effects[n]={deps,cleanup:fn()};});},
|
||||
};
|
||||
const api={fineDefectCatalog(params,signal){const d=deferred();catalog.push({...d,params,signal});return d.promise;},defectDrilldown(params,signal){const d=deferred();requests.push({...d,params,signal});return d.promise;}};
|
||||
const code=read('useDefectDrilldown.tsx').slice(read('useDefectDrilldown.tsx').indexOf('export function')).replace('export function','function');
|
||||
const hook=new Function('React','hooks','api','defectScope',transpile(`const {useState,useRef,useEffect,useMemo}=hooks;const Alert='Alert',Button='Button',Spin='Spin';${code};return useDefectDrilldown;`))(React,hooks,api,defectScope);
|
||||
return {props,requests,catalog,render(){let count=0;do{dirty=false;index=0;queue=[];output=hook(props);queue.forEach(fn=>fn());assert.ok(++count<15);}while(dirty);return output;},unmount(){effects.forEach(e=>e?.cleanup?.());}};
|
||||
}
|
||||
const catalogData={categories:[{stage:'bright',category:'加工废',available:true},{stage:'bright',category:'外废',available:false}],fields:[{stage:'bright',key:'加工缺角重量',label:'加工缺角重量',category:'加工废',available:true}]};
|
||||
const response={releaseId:'r',stage:'bright',category:'加工废',fields:[],groups:[]};
|
||||
test('drilldown batches trend and object queries, ignores late old-year replies, keeps the category across years and restores display on return',async()=>{
|
||||
const f=fixture();f.render();f.catalog[0].resolve(catalogData);await tick();let ui=f.render();
|
||||
ui.choose('外废');assert.equal(f.render().category,null);
|
||||
ui.choose('加工废');ui=f.render();assert.equal(f.props.display,'rate');assert.equal(ui.pending,true);assert.equal(f.requests.length,2);
|
||||
assert.equal(f.requests[0].params.dimension,'period');assert.equal(f.requests[1].params.dimension,'product');
|
||||
f.props.query={...f.props.query,year:2025};f.props.trendQuery={...f.props.trendQuery,year:2025};f.props.tableQuery={...f.props.tableQuery,year:2025};
|
||||
ui=f.render();assert.equal(ui.category,'加工废');assert.equal(f.requests[0].signal.aborted,true);
|
||||
f.requests[0].resolve(response);f.requests[1].resolve(response);await tick();assert.equal(f.render().table,undefined);
|
||||
f.requests[2].resolve({...response,dimension:'period'});f.requests[3].resolve({...response,dimension:'product'});await tick();ui=f.render();assert.equal(ui.pending,false);assert.equal(ui.table.dimension,'product');
|
||||
f.props.refreshKey=1;ui=f.render();assert.equal(ui.pending,true);assert.equal(ui.table,undefined);assert.equal(f.requests.length,6);
|
||||
ui.clear();assert.equal(f.render().category,null);assert.equal(f.props.display,'weight');f.unmount();
|
||||
});
|
||||
test('current failures expose retry without presenting old-scope data as the selected result; stage switch exits drilldown',async()=>{
|
||||
const f=fixture();f.render();f.catalog[0].resolve(catalogData);await tick();f.render().choose('加工废');f.render();
|
||||
f.requests[0].reject(Error('offline'));await tick();let ui=f.render();assert.equal(ui.error,'offline');assert.equal(ui.table,undefined);
|
||||
f.props.stage='black';assert.equal(f.render().category,null);assert.equal(f.props.display,'weight');f.unmount();
|
||||
});
|
||||
test('defect curves and x-axis never select a month; only available category curves drill, and production clicks keep month selection',()=>{
|
||||
const source=read('QueryPage.tsx'),start=source.indexOf(" instance.on('click', params => {",source.indexOf('export function TrendChart'));
|
||||
const code=source.slice(start,source.indexOf(' const observer =',start));
|
||||
const clicked=[],months=[];let handler;
|
||||
const modeRef={current:'defects'},drillRef={current:{drilled:false,drillableCategories:['加工废'],onDefect:v=>clicked.push(v)}};
|
||||
new Function('instance','modeRef','drillRef','rowsRef','onMonthRef','setLineSelectedPeriod',transpile(code))({on:(_,fn)=>handler=fn},modeRef,drillRef,{current:[{month:'2026-02'}]},{current:v=>months.push(v)},()=>{});
|
||||
handler({componentType:'series',seriesType:'line',seriesName:'加工废',dataIndex:0});handler({componentType:'xAxis',dataIndex:0});handler({componentType:'series',seriesName:'外废',dataIndex:0});
|
||||
assert.deepEqual(clicked,['加工废']);assert.deepEqual(months,[]);
|
||||
drillRef.current.drilled=true;handler({componentType:'series',seriesName:'加工废',dataIndex:0});assert.equal(clicked.length,1);
|
||||
modeRef.current='production';handler({componentType:'series',seriesType:'line',dataIndex:0});assert.deepEqual(months,['2026-02']);
|
||||
});
|
||||
test('period keys, unassigned source keys and missing values preserve their exact meaning',()=>{
|
||||
const data={dimension:'period',groups:[{key:'2025-Q2',children:[{key:'缺角重量',rate:0,weight:0}]}]};
|
||||
assert.equal(defectCell(data,{period:'2025-Q2'},'缺角重量','rate'),0);assert.equal(defectCell(data,{period:'2026-Q2'},'缺角重量','rate'),null);
|
||||
assert.equal(defectRateLabel('加工缺角重量'),'加工缺角废率');assert.equal(defectRateLabel('加工废'),'加工废率');
|
||||
assert.deepEqual(defectScope({year:2026,view:'product',trendGranularity:'month',columnFilters:[{field:'a'}]}),{year:2026,columnFilters:[{field:'a'}]});
|
||||
});
|
||||
|
||||
test('empty and NULL product groups keep separate formal denominators',()=>{
|
||||
const data={dimension:'product',groups:[{key:'',children:[{key:'x',rate:.04}]},{key:'__UNASSIGNED__',children:[{key:'x',rate:.01}]}]};
|
||||
assert.equal(defectCell(data,{key:'display-fallback',sourceMetricKey:''},'x','rate'),.04);
|
||||
assert.equal(defectCell(data,{key:'__UNASSIGNED__'},'x','rate'),.01);
|
||||
});
|
||||
|
||||
test('new fine values cannot be overlaid on retained rows from a previous formal query',()=>{
|
||||
for(const file of ['QueryPage.tsx','StageProductPage.tsx']) {
|
||||
const code=read(file),expression=code.match(/<MetricTable[^]*?defectDrilldown=\{([^}]+)\}/)?.[1]||code.match(/defectDrilldown=\{(tableReady[^}]+)\}/)[1];
|
||||
const bind=new Function('tableReady','queryBusy','defectDrill',`return ${expression}`),data={table:{groups:[]}};
|
||||
assert.equal(bind(false,false,data),undefined);assert.equal(bind(true,true,data),undefined);assert.equal(bind(true,false,data),data.table);
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,31 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import ts from 'typescript';
|
||||
|
||||
const read=name=>fs.readFileSync(new URL(`../src/${name}`,import.meta.url),'utf8');
|
||||
function fixture(code) {
|
||||
let dependencies,selected='';
|
||||
const useEffect=(fn,deps)=>{if(!dependencies||deps.some((v,i)=>!Object.is(v,dependencies[i]))){dependencies=deps;fn();}};
|
||||
const render=new Function('input','useEffect','setDrilledProduct',ts.transpileModule(`
|
||||
const {year,view,department,group,product,projectGroup,extraFilters,includeUnassigned,sourceFilters}=input;
|
||||
${code}
|
||||
`,{compilerOptions:{target:ts.ScriptTarget.ES2022}}).outputText);
|
||||
return {render:input=>render(input,useEffect,v=>selected=v),drill:()=>selected='产品A',get selected(){return selected;}};
|
||||
}
|
||||
const base={year:2026,view:'product',department:[],group:[],product:[],projectGroup:[],extraFilters:{},sourceFilters:[],includeUnassigned:true};
|
||||
|
||||
test('product summary keeps drilldown when only the year changes and resets it for object-scope changes',()=>{
|
||||
const source=read('QueryPage.tsx'),start=source.indexOf(' const drilldownContextKey =');
|
||||
const code=source.slice(start,source.indexOf(' const metricParams',start));
|
||||
const ui=fixture(code);ui.render(base);ui.drill();ui.render({...base,year:2025});
|
||||
assert.equal(ui.selected,'产品A');
|
||||
ui.render({...base,year:2025,group:['另一业务组']});assert.equal(ui.selected,'');
|
||||
});
|
||||
|
||||
test('both single-stage pages keep drilldown across years while organization/source changes reset it',()=>{
|
||||
const code=read('StageProductPage.tsx').match(/useEffect\(\(\)=>\{setDrilledProduct\(''\);\},\[[^\]]+\]\);/)[0];
|
||||
const ui=fixture(code);ui.render(base);ui.drill();ui.render({...base,year:2025});
|
||||
assert.equal(ui.selected,'产品A');
|
||||
ui.render({...base,year:2025,sourceFilters:[{field:'customer'}]});assert.equal(ui.selected,'');
|
||||
});
|
||||
@@ -101,6 +101,39 @@ test('the actual summary click stores release A and filters until a new detail i
|
||||
ui.openRecords(null,'black');assert.equal(ui.get().releaseId,'release-B');assert.equal(ui.get().month,2);
|
||||
});
|
||||
|
||||
test('product monthly drilldown keeps the product and clicked month for source requests and export',async()=>{
|
||||
const source=read('QueryPage.tsx'),start=source.indexOf(' const openRecords = useCallback');
|
||||
const callback=source.slice(start,source.indexOf(' const summaryMetricsError',start));
|
||||
const query={year:2026,quarter:1,view:'product',department:'产业部',group:'业务分组',product:'18X15X4+T',extraFilters:{customer:['001']}};
|
||||
const ui=new Function('freezeSourceRecordsQuery','query',transpile(`
|
||||
const summaryMetricsData={release:{id:'release-A'}},queryParams={...query,product:undefined},defectQueryParams=query;
|
||||
const drilledProduct='18X15X4+T',view='product',message={info(){}},useCallback=fn=>fn;
|
||||
let snapshot;
|
||||
const setRecordQuerySnapshot=value=>snapshot=value,setSelectedRecord=()=>{},setRecordStage=()=>{},setRecordMonth=()=>{},setRecordsOpen=()=>{};
|
||||
${callback}
|
||||
return {openRecords,get:()=>snapshot};
|
||||
`))(freezeSourceRecordsQuery,query);
|
||||
for(const month of [1,2]) {
|
||||
const key=`2026-0${month}`;
|
||||
ui.openRecords({key,label:key,month:key,product:null},'black',month);
|
||||
const frozen=ui.get();
|
||||
assert.equal(frozen.product,'18X15X4+T');assert.equal(frozen.month,month);assert.equal(frozen.quarter,undefined);
|
||||
assert.equal(frozen.department,query.department);assert.equal(frozen.group,query.group);
|
||||
assert.deepEqual(frozen.extraFilters,query.extraFilters);assert.equal(frozen.releaseId,'release-A');
|
||||
const drawer=drawerFixture();drawer.props.query=frozen;
|
||||
for(const stage of ['black','bright']) {
|
||||
drawer.props.stage=stage;drawer.render();const request=drawer.requests.at(-1);
|
||||
assert.equal(request.params.product,'18X15X4+T');assert.equal(request.params.month,month);assert.equal(request.params.stage,stage);
|
||||
request.resolve({rows:[{id:stage,raw:{规格:'18X15X4+T'}}],total:1,pageSize:20,page:1});await tick();
|
||||
}
|
||||
const tree=drawer.render();
|
||||
await find(tree,n=>n.type==='Button'&&textOf(n)==='导出明细 Excel').props.onClick();
|
||||
assert.equal(drawer.exports[0].params.product,'18X15X4+T');assert.equal(drawer.exports[0].params.month,month);
|
||||
assert.equal(drawer.exports[0].params.releaseId,'release-A');drawer.unmount();
|
||||
}
|
||||
assert.equal(query.quarter,1);assert.equal(query.month,undefined);
|
||||
});
|
||||
|
||||
function drawerFixture() {
|
||||
const source=read('QueryPage.tsx');const code=source.slice(source.indexOf('function RecordsDrawer(')).replace(/export \{ fullYearTrend \};/, '');
|
||||
const requests=[],exports=[];let downloaded=0,refreshKey=0;
|
||||
@@ -119,6 +152,26 @@ function drawerFixture() {
|
||||
return {requests,exports,props,render:()=>renderer.render(props),unmount:()=>renderer.unmount(),invalidate(){refreshKey++;},get downloaded(){return downloaded;}};
|
||||
}
|
||||
|
||||
test('single-stage detail callback freezes the clicked quarterly/yearly row instead of selecting unassigned product',()=>{
|
||||
const source=read('StageProductPage.tsx'),start=source.indexOf(' const openDetail=');
|
||||
const callback=source.slice(start,source.indexOf(' const runExport=',start));
|
||||
for(const stage of ['black','bright']) {
|
||||
const ui=new Function('freezeSourceRecordsQuery','stage',transpile(`
|
||||
const applied={year:2026,month:10,product:'产品A',stage,columnFilters:[{field:'customer',stages:[stage],operator:'in',values:['001']}]};
|
||||
const current={release:{id:'release-A'}},drilledProduct='产品A';let records;
|
||||
const setRecordVisible=()=>{},setRecords=value=>records=value;
|
||||
${callback}
|
||||
return {openDetail,get:()=>records};
|
||||
`))(freezeSourceRecordsQuery,stage);
|
||||
for(const period of ['2026-Q2','2025']) {
|
||||
ui.openDetail({key:period,month:period,period,product:null},stage);
|
||||
const query=ui.get().query;assert.equal(query.product,'产品A');assert.equal(query.month,undefined);
|
||||
assert.equal(query.year,period==='2025'?2025:2026);assert.equal(query.quarter,period==='2025'?undefined:2);
|
||||
assert.equal(query.columnFilters[0].stages[0],stage);assert.equal(query.releaseId,'release-A');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('actual drawer retains prior rows without enabling stale actions and retries the same frozen release',async()=>{
|
||||
const ui=drawerFixture();ui.render();assert.equal(ui.requests[0].params.page,1);assert.equal(ui.requests[0].params.releaseId,'release-A');
|
||||
ui.requests[0].resolve({rows:[{id:'A-1',raw:{field:'value'}}],total:45,pageSize:20,page:1});await tick();let tree=ui.render();
|
||||
|
||||
@@ -6,7 +6,21 @@ import React from 'react';
|
||||
import { queryScrapWeight } from '../src/queryMetricValues.ts';
|
||||
import { defectWeightRate } from '../src/trendMetrics.ts';
|
||||
import { metricStageColumnPlan } from '../src/metricColumnPlan.ts';
|
||||
import { createMetricWorkbook, workbookColumns } from '../src/metricWorkbook.ts';
|
||||
import { createMetricWorkbook, metricWorkbookPalette, workbookColumns } from '../src/metricWorkbook.ts';
|
||||
import { defectCell, defectRateLabel as fineDefectRateLabel } from '../src/defectDrilldown.ts';
|
||||
import { freezeSourceRecordsQuery } from '../src/sourceRecordsContext.ts';
|
||||
|
||||
test('drilled period labels and source actions preserve quarter and year instead of interpreting them as months',async()=>{
|
||||
for(const [period,label,expected] of [['2026-Q2','第2季度',{year:2026,quarter:2}],['2025','2025年',{year:2025}]]) {
|
||||
const data={...row,key:period,label:period,product:null,month:period,period,periodLabel:label,granularity:period.includes('Q')?'quarter':'year'};
|
||||
let detail;
|
||||
const ui=fixture({rows:[data],view:'overall',period:'year',onDetail:(r,s,m)=>detail=freezeSourceRecordsQuery({year:2026,month:10,product:'产品A'},'release','overall',r,m)});
|
||||
const tableNode=find(ui.tree,n=>n.type==='Table');
|
||||
tableNode.props.columns.find(c=>c.key==='actions').render(null,data).props.onClick();
|
||||
assert.equal(detail.year,expected.year);assert.equal(detail.quarter,expected.quarter);assert.equal(detail.month,undefined);assert.equal(detail.product,'产品A');
|
||||
await ui.ref.exportExcel();assert.equal(ui.exported.workbook.getWorksheet('质量汇总').getCell('A3').value,label);
|
||||
}
|
||||
});
|
||||
|
||||
const source = fs.readFileSync(new URL('../src/QueryPage.tsx', import.meta.url), 'utf8');
|
||||
const slice = (start, end) => source.slice(source.indexOf(start), source.indexOf(end, source.indexOf(start)));
|
||||
@@ -18,13 +32,13 @@ const table = slice('export function MetricTable(', 'function MetricTablePaginat
|
||||
function fixture(props) {
|
||||
let exported, detail = 0, basis = 0;
|
||||
const ref = {};
|
||||
const render = new Function('React', 'useImperativeHandle', 'defectWeightRate', 'queryScrapWeight', 'metricStageColumnPlan', 'downloadMetricWorkbook', ts.transpileModule(`
|
||||
const render = new Function('defectCell','fineDefectRateLabel','React', 'useImperativeHandle', 'defectWeightRate', 'queryScrapWeight', 'metricStageColumnPlan', 'downloadMetricWorkbook', ts.transpileModule(`
|
||||
const MONTHS=Array.from({length:12},(_,i)=>String(i+1).padStart(2,'0')+'月');
|
||||
const SUMMARY_PAGE_SIZE=15;
|
||||
const useCompactTable=()=>false, useState=v=>[v,()=>{}], useEffect=()=>{};
|
||||
const AnimatedMetricText='AnimatedMetricText', Button='Button', Table='Table', MetricTablePagination='Pagination', Tooltip='Tooltip', InfoCircleOutlined='Info';
|
||||
${helpers}\n${table}\nreturn MetricTable;
|
||||
`, {compilerOptions:{jsx:ts.JsxEmit.React,target:ts.ScriptTarget.ES2022}}).outputText)(React, (target, create) => Object.assign(target, create()), defectWeightRate, queryScrapWeight, metricStageColumnPlan, async (filename, columns, rows, value) => {
|
||||
`, {compilerOptions:{jsx:ts.JsxEmit.React,target:ts.ScriptTarget.ES2022}}).outputText)(defectCell,fineDefectRateLabel,React, (target, create) => Object.assign(target, create()), defectWeightRate, queryScrapWeight, metricStageColumnPlan, async (filename, 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});
|
||||
@@ -48,11 +62,14 @@ for (const view of ['overall','department','group','product','projectGroup']) {
|
||||
const {workbook,columns}=ui.exported;
|
||||
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);
|
||||
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.equal(sheet.rowCount,20);assert.equal(sheet.columnCount,fullFields?13:10);
|
||||
assert.equal(sheet.getCell('A1').value,fields[0].header);
|
||||
assert.equal(sheet.getCell('B1').value,'黑片');
|
||||
assert.equal(sheet.getCell('B2').value,'总重量\n(kg)');
|
||||
assert.equal(sheet.views[0].ySplit,2);
|
||||
const at=key=>fields.findIndex(field=>field.key===key)+1;
|
||||
assert.equal(sheet.getRow(2).getCell(at('black-qualifiedWeight')).value,1234.567);
|
||||
assert.equal(sheet.getRow(2).getCell(at('black-totalWeight')).value,1250);
|
||||
assert.equal(sheet.getRow(3).getCell(at('black-qualifiedWeight')).value,1234.567);
|
||||
assert.equal(sheet.getRow(3).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');
|
||||
@@ -69,8 +86,8 @@ for (const view of ['overall','department','group','product','projectGroup']) {
|
||||
action.props.onClick();assert.equal(ui.detail,1);
|
||||
const reread=await createMetricWorkbook([],[],()=>null);
|
||||
await reread.xlsx.load(await workbook.xlsx.writeBuffer());
|
||||
assert.equal(reread.getWorksheet('质量汇总').rowCount,19);
|
||||
if(view==='product')assert.equal(reread.getWorksheet('质量汇总').getCell('A2').value,'=1+2');
|
||||
assert.equal(reread.getWorksheet('质量汇总').rowCount,20);
|
||||
if(view==='product')assert.equal(reread.getWorksheet('质量汇总').getCell('A3').value,'=1+2');
|
||||
});
|
||||
}
|
||||
|
||||
@@ -78,19 +95,19 @@ 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'});
|
||||
await ui.ref.exportExcel();const sheet=ui.exported.workbook.getWorksheet('质量汇总');
|
||||
const fields=workbookColumns(ui.exported.columns), at=key=>fields.findIndex(field=>field.key===key)+1;
|
||||
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);
|
||||
assert.equal(sheet.getRow(3).getCell(at('compositeRate')).value,0.98);
|
||||
assert.equal(sheet.getRow(3).getCell(at('bright-rate')).value,0.99);
|
||||
assert.equal(sheet.getRow(4).getCell(at('black-rate')).value,null);
|
||||
assert.equal(sheet.getRow(4).getCell(at('black-qualifiedWeight')).value,null);
|
||||
assert.equal(sheet.getRow(3).getCell(at('black-scrapWeight')).value,0);
|
||||
});
|
||||
|
||||
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'});
|
||||
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('A3').value,'02月');assert.equal(sheet.getCell('A4').value,'03月');
|
||||
const composite=workbookColumns(ui.exported.columns).findIndex(field=>field.key==='compositeRate')+1;
|
||||
assert.equal(sheet.getRow(3).getCell(composite).value,null);
|
||||
assert.equal(sheet.getRow(4).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()=>{
|
||||
@@ -99,20 +116,20 @@ for (const view of ['overall','department','group','product','projectGroup']) te
|
||||
await ui.ref.exportExcel();
|
||||
const fields=workbookColumns(ui.exported.columns),sheet=ui.exported.workbook.getWorksheet('质量汇总');
|
||||
const at=key=>fields.findIndex(field=>field.key===key)+1;
|
||||
assert.equal(sheet.getRow(2).getCell(at('black-defect-责废')).value,.12);
|
||||
assert.equal(sheet.getRow(2).getCell(at('bright-defect-责废')).value,.04);
|
||||
assert.equal(sheet.getRow(2).getCell(at('black-scrapWeight')).value,.2);
|
||||
assert.equal(sheet.getRow(2).getCell(at('bright-headquartersScrapWeight')).value,.015);
|
||||
assert.equal(sheet.getRow(3).getCell(at('black-defect-责废')).value,.12);
|
||||
assert.equal(sheet.getRow(3).getCell(at('bright-defect-责废')).value,.04);
|
||||
assert.equal(sheet.getRow(3).getCell(at('black-scrapWeight')).value,.2);
|
||||
assert.equal(sheet.getRow(3).getCell(at('bright-headquartersScrapWeight')).value,.015);
|
||||
assert.equal(sheet.getColumn(at('black-defect-责废')).numFmt,'0.00%');
|
||||
assert.equal(fields[at('black-defect-责废')-1].header,'黑片 / 责废率');
|
||||
assert.equal(fields[at('bright-headquartersScrapWeight')-1].header,'亮片 / 本部报废率');
|
||||
assert.match(fields[at('black-totalWeight')-1].header,/总重量 \/ kg$/);
|
||||
assert.equal(sheet.getRow(2).getCell(at('black-totalWeight')).value,1000);
|
||||
assert.equal(sheet.getRow(3).getCell(at('black-totalWeight')).value,1000);
|
||||
const rendered=ui.exported.columns.flatMap(column=>column.children||[column]).find(column=>column.key==='black-defect-责废').render(null,data);
|
||||
assert.equal(rendered.props.children.props.value,'12.00%');
|
||||
const restored=fixture({rows:[data],view,fullFields:true,defectDisplay:'weight'});await restored.ref.exportExcel();
|
||||
const originalFields=workbookColumns(restored.exported.columns),index=originalFields.findIndex(field=>field.key==='black-defect-责废')+1;
|
||||
assert.equal(restored.exported.workbook.getWorksheet('质量汇总').getRow(2).getCell(index).value,120);
|
||||
assert.equal(restored.exported.workbook.getWorksheet('质量汇总').getRow(3).getCell(index).value,120);
|
||||
assert.equal(data.black.defects[0].weight,120);
|
||||
});
|
||||
test('single-stage rate mode exports only its stage; missing or zero denominator stays blank and zero defect stays zero',async()=>{
|
||||
@@ -120,9 +137,9 @@ test('single-stage rate mode exports only its stage; missing or zero denominator
|
||||
const ui=fixture({rows,view:'product',fullFields:true,onlyStage:'black',defectDisplay:'rate'});await ui.ref.exportExcel();
|
||||
const fields=workbookColumns(ui.exported.columns),sheet=ui.exported.workbook.getWorksheet('质量汇总'),at=key=>fields.findIndex(f=>f.key===key)+1;
|
||||
assert.equal(fields.some(f=>f.key.startsWith('bright-')),false);
|
||||
assert.equal(sheet.getRow(2).getCell(at('black-scrapWeight')).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(3).getCell(at('black-scrapWeight')).value,null);
|
||||
assert.equal(sheet.getRow(4).getCell(at('black-defect-裂纹')).value,null);
|
||||
assert.equal(sheet.getRow(5).getCell(at('black-scrapWeight')).value,0);
|
||||
});
|
||||
|
||||
test('本部报废原口径紧随扩散废,调整口径隐藏并在表格及Excel同步扣减', async () => {
|
||||
@@ -136,8 +153,8 @@ test('本部报废原口径紧随扩散废,调整口径隐藏并在表格及Ex
|
||||
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.props.value,'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(adjusted.exported.workbook.getWorksheet('质量汇总').getRow(3).getCell(at('bright-scrapWeight')).value,70);
|
||||
assert.equal(adjusted.exported.workbook.getWorksheet('质量汇总').getRow(3).getCell(at('bright-totalWeight')).value,1250);
|
||||
}
|
||||
assert.equal(data.bright.scrapWeight,100);
|
||||
});
|
||||
@@ -154,3 +171,80 @@ test('合格率说明图标仅在去本部报废口径下显示,黑片总重
|
||||
assert.ok(find(leaves.find(c=>c.key==='black-totalWeight').title,n=>n.type==='Info'));
|
||||
}
|
||||
});
|
||||
|
||||
test('导出保留分组、合并表头、语义文字颜色、综合率底色与隔行填充,保存后格式不丢失', async () => {
|
||||
const ui=fixture({rows:[row,row],view:'product'});await ui.ref.exportExcel();
|
||||
const workbook=ui.exported.workbook;
|
||||
await workbook.xlsx.load(await workbook.xlsx.writeBuffer());
|
||||
const sheet=workbook.getWorksheet('质量汇总'), palette=metricWorkbookPalette();
|
||||
assert.deepEqual(sheet.model.merges.sort(),['A1:A2','B1:E1','F1:I1','J1:J2'].sort());
|
||||
assert.equal(sheet.getCell('F1').value,'亮片');
|
||||
assert.equal(sheet.getCell('J1').value,'综合合格率');
|
||||
assert.equal(sheet.getCell('B1').fill.fgColor.argb,palette.blackHead);
|
||||
assert.equal(sheet.getCell('F1').fill.fgColor.argb,palette.brightHead);
|
||||
for(const address of ['J1','J3','J4']) {
|
||||
assert.equal(sheet.getCell(address).fill.fgColor.argb,palette.combinedFill);
|
||||
assert.equal(sheet.getCell(address).font.color.argb,palette.combined);
|
||||
}
|
||||
assert.equal(sheet.getCell('E3').font.color.argb,palette.black);
|
||||
assert.equal(sheet.getCell('I3').font.color.argb,palette.bright);
|
||||
assert.equal(sheet.getCell('B3').fill.fgColor.argb,palette.surface);
|
||||
assert.equal(sheet.getCell('B4').fill.fgColor.argb,palette.alternate);
|
||||
assert.equal(sheet.getCell('B3').border.bottom.color.argb,palette.grid);
|
||||
assert.equal(sheet.getCell('B2').border.bottom.color.argb,palette.headGrid);
|
||||
assert.equal(sheet.getCell('A3').font.name,'微软雅黑');
|
||||
assert.equal(sheet.getCell('B3').font.name,'Arial');
|
||||
assert.equal(sheet.getCell('J3').font.bold,true);
|
||||
assert.equal(sheet.getCell('B3').alignment.horizontal,'center');
|
||||
assert.equal(sheet.views[0].xSplit,1);assert.equal(sheet.views[0].ySplit,2);
|
||||
assert.equal(sheet.pageSetup.printTitlesRow,'1:2');
|
||||
assert.equal(sheet.pageSetup.orientation,'landscape');
|
||||
assert.ok(sheet.getColumn(1).width>sheet.getColumn(2).width);
|
||||
});
|
||||
|
||||
test('午夜黑主题默认导出与浅蓝完全一致,其余浅色主题保留各自配色', async () => {
|
||||
const columns=[{key:'object',title:'产品规格'},{key:'stage-bright',title:'亮片',children:[{key:'bright-rate',title:'合格率'}]}];
|
||||
const light=await createMetricWorkbook(columns,[row],key=>key==='object'?'示例产品':.98765,'light');
|
||||
const previous=globalThis.window;
|
||||
try {
|
||||
globalThis.window={localStorage:{getItem:()=> 'dark'}};
|
||||
const dark=await createMetricWorkbook(columns,[row],key=>key==='object'?'示例产品':.98765);
|
||||
assert.deepEqual(dark.getWorksheet('质量汇总').model,light.getWorksheet('质量汇总').model);
|
||||
} finally { if(previous===undefined)delete globalThis.window;else globalThis.window=previous; }
|
||||
assert.deepEqual(metricWorkbookPalette('dark'),metricWorkbookPalette('light'));
|
||||
for(const theme of ['soft','deep','bright','classic']) {
|
||||
const book=await createMetricWorkbook(columns,[row],()=>.98,theme);
|
||||
assert.equal(book.getWorksheet('质量汇总').getCell('B3').font.color.argb,metricWorkbookPalette(theme).bright);
|
||||
assert.notEqual(metricWorkbookPalette(theme).bright,metricWorkbookPalette('light').bright);
|
||||
}
|
||||
});
|
||||
|
||||
test('调整口径注释分行、长文字自动换行,缺失和非有限值为空且零值仍为数值', async () => {
|
||||
const ui=fixture({rows:[row],view:'product',rateBasis:'withoutHeadquartersScrap'});await ui.ref.exportExcel();
|
||||
assert.equal(ui.exported.workbook.getWorksheet('质量汇总').getCell('J1').value,'综合合格率\n(去本部报废)');
|
||||
const columns=[{key:'object',title:'产品规格',width:120},{key:'black-totalWeight',title:'总重量'}];
|
||||
const workbook=await createMetricWorkbook(columns,[Infinity,NaN,0,null],(key,row)=>key==='object'?'很长的中文产品规格需要完整显示且能够自动换行\n第二行':row);
|
||||
const sheet=workbook.getWorksheet('质量汇总');
|
||||
assert.equal(sheet.getCell('B2').value,null);assert.equal(sheet.getCell('B3').value,null);
|
||||
assert.equal(sheet.getCell('B4').value,0);assert.equal(sheet.getCell('B5').value,null);
|
||||
assert.ok(sheet.getRow(2).height>26.25);assert.equal(sheet.getCell('A2').alignment.wrapText,true);
|
||||
const empty=await createMetricWorkbook([{key:'actions',title:'操作'},{key:'empty',children:[]}],[],()=>null);
|
||||
assert.equal(empty.getWorksheet('质量汇总').columnCount,0);
|
||||
await empty.xlsx.writeBuffer();
|
||||
});
|
||||
|
||||
test('fine defect expansion and Excel share authorized parent/child values, preserve zero/missing, and leave the other stage compact',async()=>{
|
||||
const data={releaseId:'r',stage:'bright',category:'加工废',dimension:'product',granularity:'month',fields:[{key:'加工缺角重量',label:'加工缺角重量',category:'加工废'}],groups:[{key:'p',parentRate:.1,parentWeight:10,children:[{key:'加工缺角重量',weight:0,rate:0}],reconciliationStatus:'RECONCILED'}]};
|
||||
const rows=[{...row,key:'p'},{...row,key:'missing'}];
|
||||
const ui=fixture({rows,view:'product',fullFields:true,defectDisplay:'rate',defectDrilldown:data});
|
||||
await ui.ref.exportExcel();const fields=workbookColumns(ui.exported.columns),sheet=ui.exported.workbook.getWorksheet('质量汇总');
|
||||
const at=key=>fields.findIndex(f=>f.key===key)+1;
|
||||
assert.ok(at('bright-fine-parent')>0);assert.ok(at('bright-fine-加工缺角重量')>0);
|
||||
assert.equal(fields[at('bright-fine-加工缺角重量')-1].header,'亮片 / 加工缺角废率');
|
||||
assert.equal(sheet.getRow(3).getCell(at('bright-fine-加工缺角重量')).value,0);
|
||||
assert.equal(sheet.getRow(4).getCell(at('bright-fine-加工缺角重量')).value,null);
|
||||
assert.equal(sheet.getRow(3).getCell(at('bright-fine-parent')).value,.1);
|
||||
assert.equal(sheet.getColumn(at('bright-fine-parent')).numFmt,'0.00%');
|
||||
assert.equal(fields.some(f=>f.key.startsWith('black-defect-')||f.key.startsWith('black-fine-')),false);
|
||||
assert.equal(data.groups[0].children[0].rate,0);
|
||||
});
|
||||
|
||||
@@ -22,7 +22,7 @@ test('failed drilled trends cannot ready a replacement table or enable stale exp
|
||||
assert.equal(stageReady({},'B',{key:'B'},'B',false,''),true);
|
||||
assert.equal(stageReady({},'',null,'B',false,'offline'),true);
|
||||
const exportExpression=query.match(/exporting=\{summaryExporting\} exportDisabled=\{([^\n]+)\}/)[1];
|
||||
const disabled=new Function('queryBusy','summaryBusy','tableReady','summaryMetricsData','drilledProduct','trendLoading','currentTrendError','drilledTrendData','visibleRows',`return ${exportExpression}`);
|
||||
const disabled=new Function('queryBusy','summaryBusy','tableReady','summaryMetricsData','drilledProduct','trendLoading','currentTrendError','drilledTrendData','visibleRows',`const defectDrill={category:null};return ${exportExpression}`);
|
||||
assert.equal(disabled(false,false,false,{},'B',false,'offline',Array(12).fill({}),[]),true);
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { freezeSourceRecordsQuery } from '../src/sourceRecordsContext.ts';
|
||||
|
||||
test('period rows bind their own year/month/quarter and keep the selected object',()=>{
|
||||
const query={year:2026,month:10,monthStart:1,monthEnd:9,product:'产品A',department:'部门A',extraFilters:{customer:['001']}};
|
||||
for(const [period,expected] of [['2026-02',{year:2026,month:2}],['2026-Q2',{year:2026,quarter:2}],['2025',{year:2025}]]) {
|
||||
const result=freezeSourceRecordsQuery(query,'release','overall',{key:period,label:period,month:period,period,product:null});
|
||||
assert.equal(result.product,query.product);assert.equal(result.department,query.department);
|
||||
assert.deepEqual(Object.fromEntries(['year','month','quarter','monthStart','monthEnd'].filter(k=>result[k]!==undefined).map(k=>[k,result[k]])),expected);
|
||||
assert.equal(result.releaseId,'release');
|
||||
}
|
||||
assert.equal(query.month,10);assert.equal(query.monthEnd,9);
|
||||
});
|
||||
|
||||
test('clicking a month clears the parent range; object rows retain their original period',()=>{
|
||||
const query={year:2026,monthStart:1,monthEnd:9,product:'产品A'};
|
||||
const monthly=freezeSourceRecordsQuery(query,'release','overall',{key:'2026-02',month:'2026-02'},2);
|
||||
assert.equal(monthly.month,2);assert.equal(monthly.monthStart,undefined);assert.equal(monthly.monthEnd,undefined);
|
||||
for(const view of ['department','group','product','projectGroup']) {
|
||||
for(const key of ['__UNASSIGNED__','',' ']) {
|
||||
const object=freezeSourceRecordsQuery(query,'release',view,{key,[view]:null});
|
||||
assert.equal(object[view],'__UNASSIGNED__');assert.equal(object.monthStart,1);assert.equal(object.monthEnd,9);
|
||||
}
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user