同步:完善质量分析工作台并更新主题字体

同步已上线的智能分析执行协议、来源查询、图表报告与管理页面配套代码。
补齐数据库迁移、运行依赖和回归测试,保留原有指标计算口径。
统一午夜黑及其他主题的控件细节、中文和业务数字字体。
排除本地业务数据、凭据、预览、发布与验收产物。

验证:生产构建通过,320项前端回归通过;本轮仅同步Git,不再次部署。
This commit is contained in:
2026-10-30 22:40:58 +08:00
parent edef747e3b
commit ff7bbe3e46
393 changed files with 62999 additions and 1783 deletions
+215 -41
View File
@@ -1,10 +1,14 @@
import type { EChartsCoreOption } from 'echarts/core';
import { analysisPeriodLabel, isValidAnalysisPeriodContext, parseAnalysisPeriod } from './analysisPeriodModel.ts';
export type AnalysisVisualUnit = 'ratio' | 'kg' | 'pp' | 'count';
export type AnalysisVisualStage = 'black' | 'bright';
export type AnalysisVisualSectionKey = 'overview' | 'stage' | 'department' | 'group' | 'product' | 'category_black' | 'category_bright' | 'defect_black' | 'defect_bright' | 'defect_combined' | 'trend' | 'composition';
export type AnalysisVisualDimension = 'department' | 'group' | 'product' | 'category' | 'defect';
export type AnalysisVisualContextValue = string | number | boolean | Array<string | number | boolean> | Record<string, string[]>;
export type AnalysisExclusionDimension = 'department' | 'group' | 'product' | 'projectGroup';
export type AnalysisExclusions = Partial<Record<AnalysisExclusionDimension, string[]>>;
export interface SourceColumnFilter { field: string; stages: Array<'black' | 'bright'>; operator: 'in' | 'not_in' | 'is_empty' | 'not_empty'; values?: string[] }
export type AnalysisVisualContextValue = string | number | boolean | Array<string | number | boolean> | Record<string, string[]> | Record<string, string> | SourceColumnFilter[] | AnalysisExclusions;
export type AnalysisVisualContext = Record<string, AnalysisVisualContextValue>;
export interface AnalysisVisualSeries {
@@ -33,6 +37,7 @@ export interface AnalysisVisual {
returnedRows: number;
truncated: boolean;
shareBasis?: string;
denominator?: number;
};
note?: string;
originTurnId: string;
@@ -68,14 +73,38 @@ const DIMENSIONS = new Set<AnalysisVisualDimension>(['department', 'group', 'pro
const VISUAL_KEYS = new Set(['id', 'type', 'title', 'subtitle', 'unit', 'categories', 'series', 'evidenceRefs', 'requiredFields', 'scope', 'period', 'comparisonPeriod', 'stage', 'metric', 'coverage', 'note', 'originTurnId', 'sectionKey', 'dimension']);
const CATEGORY_KEYS = new Set(['key', 'label']);
const SERIES_KEYS = new Set(['key', 'label', 'values']);
const COVERAGE_KEYS = new Set(['totalRows', 'returnedRows', 'truncated', 'shareBasis']);
const COVERAGE_KEYS = new Set(['totalRows', 'returnedRows', 'truncated', 'shareBasis', 'denominator']);
const PARSED_VISUALS = new WeakSet<object>();
const DONUT_CATEGORY_KEYS: Record<AnalysisVisualStage, Set<string>> = {
black: new Set(['black_responsibility_scrap', 'black_material_scrap', 'black_external_scrap']),
bright: new Set(['bright_plating_scrap', 'bright_material_scrap', 'bright_processing_scrap', 'bright_diffusion_scrap']),
};
const SCRAP_RATE_REQUIRED_FIELDS: Record<string, { stage: AnalysisVisualStage; fields: string[] }> = {
black_scrap_rate: { stage: 'black', fields: ['black_scrap_weight', 'black_total_weight'] },
bright_scrap_rate: { stage: 'bright', fields: ['bright_scrap_weight', 'bright_total_weight'] },
};
const DEFAULT_COLORS = ['#607ae1', '#008f7d', '#d58c35', '#8b68c5'];
function isScrapRateMetric(metric: string): boolean {
return Object.hasOwn(SCRAP_RATE_REQUIRED_FIELDS, metric);
}
function ratioAxisMax(visual: AnalysisVisual): number | undefined {
if (visual.unit !== 'ratio') return undefined;
if (!isScrapRateMetric(visual.metric)) return 100;
const highest = Math.max(0, ...visual.series.flatMap(series => series.values.filter((value): value is number => value !== null && Number.isFinite(value))));
if (highest <= 1) {
if (highest === 0) return 1;
const targetPercent = highest * 100 * 1.15;
const magnitude = 10 ** Math.floor(Math.log10(targetPercent));
const factor = [1, 2, 5, 10].find(value => value * magnitude >= targetPercent) || 10;
return Math.min(100, factor * magnitude);
}
const highestPercent = highest * 100;
if (!Number.isFinite(highestPercent)) return undefined;
return Math.ceil((highestPercent + Math.max(10, highestPercent * 0.08)) / 10) * 10;
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value);
}
@@ -137,7 +166,7 @@ function copyJsonData(value: unknown, seen = new Set<object>(), budget = { nodes
function boundedText(value: unknown, maxLength = 200): string | null {
if (typeof value !== 'string') return null;
const text = value.trim();
const text = value.trim().replace(/数学/g, '');
if (!text || text.length > maxLength) return null;
return text;
}
@@ -153,12 +182,50 @@ function safeTextList(value: unknown, maxItems = 40): string[] | null {
return list;
}
function safeExclusions(value: unknown): AnalysisExclusions | null {
if (!isRecord(value) || Object.keys(value).length > 4) return null;
const result: AnalysisExclusions = {};
for (const [dimension, rawValues] of Object.entries(value)) {
if (!['department', 'group', 'product', 'projectGroup'].includes(dimension)
|| !Array.isArray(rawValues) || rawValues.length < 1 || rawValues.length > 50
|| rawValues.some(item => typeof item !== 'string' || !item.trim() || item.length > 256)) return null;
Object.defineProperty(result, dimension, { value: [...rawValues], enumerable: true, configurable: true, writable: true });
}
return result;
}
export function isValidAnalysisExclusions(value: unknown): boolean {
return safeExclusions(value) !== null;
}
function safeContext(value: unknown): AnalysisVisualContext | null {
if (!isRecord(value) || Object.keys(value).length > 32) return null;
const result: AnalysisVisualContext = {};
for (const [key, raw] of Object.entries(value)) {
if (!/^[\w.-]{1,64}$/.test(key)) return null;
if (key === 'extraFilters') {
if (key === 'exclusions') {
const exclusions = safeExclusions(raw);
if (!exclusions) return null;
Object.defineProperty(result, key, { value: exclusions, enumerable: true, configurable: true, writable: true });
} else if (key === 'columnFilters') {
if (!Array.isArray(raw) || raw.length > 20) return null;
const filters: SourceColumnFilter[] = [];
for (const rule of raw) {
if (!isRecord(rule) || Object.keys(rule).some(key => !['field', 'stages', 'operator', 'values'].includes(key))
|| typeof rule.field !== 'string' || !/^[A-Za-z0-9_]{1,64}$/.test(rule.field)
|| !Array.isArray(rule.stages) || !rule.stages.length || rule.stages.length > 2 || new Set(rule.stages).size !== rule.stages.length
|| rule.stages.some(stage => stage !== 'black' && stage !== 'bright')
|| !['in', 'not_in', 'is_empty', 'not_empty'].includes(String(rule.operator))) return null;
const needsValues = rule.operator === 'in' || rule.operator === 'not_in';
if (needsValues && (!Array.isArray(rule.values) || !rule.values.length || rule.values.length > 50 || rule.values.some(value => typeof value !== 'string' || !value.trim() || value.length > 256))) return null;
if (!needsValues && rule.values !== undefined) return null;
filters.push({ field: rule.field, stages: [...rule.stages] as SourceColumnFilter['stages'], operator: rule.operator as SourceColumnFilter['operator'], ...(needsValues ? { values: [...rule.values as string[]] } : {}) });
}
result[key] = filters;
} else if (key === 'columnLabels') {
if (!isRecord(raw) || Object.keys(raw).length > 25 || Object.entries(raw).some(([name, label]) => !/^[A-Za-z0-9_]{1,64}$/.test(name) || typeof label !== 'string' || label.length > 160)) return null;
result[key] = Object.fromEntries(Object.entries(raw)) as Record<string, string>;
} else if (key === 'extraFilters') {
if (!isRecord(raw) || Object.keys(raw).length > 20) return null;
const filters: Record<string, string[]> = {};
for (const [filterKey, filterValues] of Object.entries(raw)) {
@@ -208,11 +275,13 @@ function parseVisual(value: unknown, index: number, issues: string[]): AnalysisV
&& Number(coverage.returnedRows) <= Number(coverage.totalRows)
&& typeof coverage.truncated === 'boolean'
&& (coverage.shareBasis === undefined || boundedText(coverage.shareBasis, 128) !== null)
&& (coverage.denominator === undefined || typeof coverage.denominator === 'number' && Number.isFinite(coverage.denominator) && coverage.denominator > 0 && coverage.shareBasis === 'all_scope_weight')
? {
totalRows: Number(coverage.totalRows),
returnedRows: Number(coverage.returnedRows),
truncated: coverage.truncated,
...(coverage.shareBasis === undefined ? {} : { shareBasis: String(coverage.shareBasis) }),
...(coverage.denominator === undefined ? {} : { denominator: Number(coverage.denominator) }),
}
: null;
@@ -247,7 +316,7 @@ function parseVisual(value: unknown, index: number, issues: string[]): AnalysisV
invalidValueCells.push(`${seriesIndex}:${valueIndex}`);
return null;
}
if (unit === 'ratio' && (item < 0 || item > 1)) invalidValueCells.push(`${seriesIndex}:${valueIndex}`);
if (unit === 'ratio' && (item < 0 || (!isScrapRateMetric(metric || '') && item > 1))) invalidValueCells.push(`${seriesIndex}:${valueIndex}`);
return item;
});
series.push({ key, label, values });
@@ -256,7 +325,8 @@ function parseVisual(value: unknown, index: number, issues: string[]): AnalysisV
const validSeries = !!rawSeries && !!validCategories && series.length === rawSeries.length;
const valid = !!id && !!type && !!title && subtitle !== null && UNIT_VALUES.has(unit as AnalysisVisualUnit)
&& !!metric && !!originTurnId && !!scope && !!period && (value.comparisonPeriod === undefined || !!comparisonPeriod)
&& !!metric && !!originTurnId && !!scope && isValidAnalysisPeriodContext(scope)
&& !!period && isValidAnalysisPeriodContext(period) && (value.comparisonPeriod === undefined || !!comparisonPeriod && isValidAnalysisPeriodContext(comparisonPeriod))
&& !!evidenceRefs && !!requiredFields && (value.note === undefined || note !== null)
&& (stage === undefined || stage === 'black' || stage === 'bright')
&& (sectionKey === undefined || SECTION_KEYS.has(sectionKey as AnalysisVisualSectionKey))
@@ -297,12 +367,20 @@ function parseVisual(value: unknown, index: number, issues: string[]): AnalysisV
}
function visualSemanticIssue(visual: AnalysisVisual): string | undefined {
const scrapRate = SCRAP_RATE_REQUIRED_FIELDS[visual.metric];
if (scrapRate) {
if (visual.unit !== 'ratio') return '阶段报废率必须使用比例单位';
if (visual.requiredFields.length !== scrapRate.fields.length || new Set(visual.requiredFields).size !== scrapRate.fields.length
|| scrapRate.fields.some(field => !visual.requiredFields.includes(field))) return '阶段报废率缺少对应重量字段权限';
if ((visual.stage !== undefined && visual.stage !== scrapRate.stage)
|| (visual.scope.stage !== undefined && visual.scope.stage !== scrapRate.stage)) return '报废率阶段与查询范围不一致';
}
if (visual.type === 'area' && visual.series.length !== 1) return '面积趋势图仅支持单一序列';
if (visual.type === 'area' && visual.series.some(series => series.values.some(value => value !== null && value < 0))) return '面积趋势图不支持负值';
if (visual.type === 'waterfall') {
const allowedFields = new Set(['black_good_weight', 'black_total_weight', 'bright_good_weight', 'bright_total_weight']);
const actualFields = visual.requiredFields;
if (visual.metric !== 'composite_impact_pp' || visual.unit !== 'pp') return '瀑布图仅支持综合率阶段数学影响(百分点)';
if (visual.metric !== 'composite_impact_pp' || visual.unit !== 'pp') return '瀑布图仅支持综合率阶段影响(百分点)';
if (visual.categories.length !== 3 || visual.categories.map(item => item.key).join('|') !== 'black|bright|total') return '瀑布图类别必须依次为黑片、亮片和综合变化';
if (visual.series.length !== 1 || visual.series[0].key !== 'composite_impact_pp') return '瀑布图仅支持综合阶段影响序列';
if (actualFields.length !== allowedFields.size || new Set(actualFields).size !== allowedFields.size || actualFields.some(field => !allowedFields.has(field))) {
@@ -322,6 +400,18 @@ function visualSemanticIssue(visual: AnalysisVisual): string | undefined {
}
if (visual.type !== 'donut' && visual.type !== 'pareto') return undefined;
const chartName = visual.type === 'donut' ? '环形图' : '柏拉图';
if (visual.type === 'pareto' && visual.coverage.shareBasis === 'all_scope_weight') {
const values = visual.series[0]?.values || [];
const total = visual.coverage.denominator;
if (visual.unit !== 'kg' || !/^(?:black|bright)_(?:total|scrap)_weight$/.test(visual.metric)
|| !visual.stage || !visual.metric.startsWith(`${visual.stage}_`) || visual.comparisonPeriod
|| !['product','department','group'].includes(visual.dimension || '')
|| visual.categories.length < 1 || visual.categories.length > 10 || visual.series.length !== 1
|| visual.coverage.returnedRows !== visual.categories.length || typeof total !== 'number' || !(total > 0)
|| values.some((v,i) => v === null || !Number.isFinite(v) || v < 0 || i > 0 && v > (values[i-1] as number))) return '分组重量柏拉图缺少全范围总量或有效排名';
if (values.reduce<number>((sum,v)=>sum+(v as number),0) > total + Math.max(0.00001,total*1e-10)) return 'Top重量不能大于全范围总量';
return undefined;
}
if (visual.unit !== 'kg' || visual.metric !== 'source_defect_weight') return `${chartName}仅支持来源类别重量`;
if (visual.stage !== 'black' && visual.stage !== 'bright') return `${chartName}必须明确黑片或亮片阶段`;
if (visual.scope.stage !== undefined && visual.scope.stage !== visual.stage) return `${chartName}阶段与查询范围不一致`;
@@ -479,6 +569,12 @@ function formatChartValue(value: number | null, unit: AnalysisVisualUnit, showPo
return unit === 'kg' ? `${signed} kg` : unit === 'pp' ? `${signed} pp` : signed;
}
function paretoWeightLabel(value: number | null, allScopeWeight: boolean): string {
const text = formatChartValue(value, 'kg');
return allScopeWeight ? text.replace(/ kg$/, '') : text;
}
export function visualCategoryLabel(visual: AnalysisVisual, categoryIndex: number): string {
const category = visual.categories[categoryIndex];
if (!category) return '';
@@ -514,7 +610,8 @@ export function visualParetoPoints(visual: AnalysisVisual): AnalysisVisualPareto
if (visual.type !== 'pareto' || visualSemanticIssue(visual)) return [];
const values = visual.series[0]?.values;
if (!values) return [];
const total = values.reduce<number>((sum, value) => sum + (value as number), 0);
const fullPopulation = visual.coverage.shareBasis === 'all_scope_weight';
const total = fullPopulation ? visual.coverage.denominator! : values.reduce<number>((sum, value) => sum + (value as number), 0);
let cumulative = 0;
return values.map((value, categoryIndex) => {
cumulative += value as number;
@@ -522,7 +619,7 @@ export function visualParetoPoints(visual: AnalysisVisual): AnalysisVisualPareto
categoryIndex,
valueKg: value as number,
share: (value as number) / total,
cumulativeShare: categoryIndex === values.length - 1 ? 1 : cumulative / total,
cumulativeShare: !fullPopulation && categoryIndex === values.length - 1 ? 1 : cumulative / total,
};
});
}
@@ -582,8 +679,8 @@ export function buildAnalysisVisualOption(visual: AnalysisVisual, theme: VisualC
return [
plainRichText(visualCategoryLabel(visual, dataIndex)),
`${plainRichText(visual.series[0].label)}:${formatVisualValue(point.valueKg, 'kg')}`,
`本图类别占比:${visualDonutShareText(point.share)}`,
`累计占本图已列类别合计:${visualDonutShareText(point.cumulativeShare)}`,
`${visual.coverage.shareBasis === 'all_scope_weight' ? '占全部重量' : '本图类别占比'}:${visualDonutShareText(point.share)}`,
`${visual.coverage.shareBasis === 'all_scope_weight' ? '累计占全部重量' : '累计占本图已列类别合计'}:${visualDonutShareText(point.cumulativeShare)}`,
].join('\n');
}
if (visual.type === 'waterfall') {
@@ -592,7 +689,7 @@ export function buildAnalysisVisualOption(visual: AnalysisVisual, theme: VisualC
return [
plainRichText(visualCategoryLabel(visual, dataIndex)),
plainRichText(`期间:${plainPeriod(visual.comparisonPeriod || {})} → ${plainPeriod(visual.period)}`),
`阶段数学影响:${formatVisualValue(value, 'pp')}`,
`阶段影响:${formatVisualValue(value, 'pp')}`,
...(dataIndex === 2 ? ['黑片与亮片影响之和构成综合率变化。'] : []),
'该拆解不代表生产根因。',
].join('\n');
@@ -738,21 +835,22 @@ export function buildAnalysisVisualOption(visual: AnalysisVisual, theme: VisualC
if (visual.type === 'pareto') {
const points = visualParetoPoints(visual);
const cumulativeName = '累计占本图已列类别合计';
const allScopeWeight = visual.coverage.shareBasis === 'all_scope_weight';
const cumulativeName = allScopeWeight ? '累计占全部重量' : '累计占本图已列类别合计';
return {
animation: false,
color: [colors[0], '#435d7a'],
tooltip: { trigger: 'axis', renderMode: 'richText', backgroundColor: theme.surface || '#ffffff', borderColor: line, textStyle: { color: ink }, axisPointer: { type: 'shadow' }, formatter },
legend: { show: true, selectedMode: false, type: 'plain', top: 6, left: 12, data: [plainRichText(visual.series[0].label), cumulativeName], textStyle: { color: mutedInk, fontSize: 10 } },
grid: { left: 56, right: 66, top: 36, bottom: 70, containLabel: true },
xAxis: { type: 'category', data: categories, axisLabel: { color: ink, fontSize: 10, interval: 0, rotate: categories.length > 3 ? 34 : 0, width: 160, overflow: 'break', hideOverlap: false, lineHeight: 13 }, axisLine: { lineStyle: { color: line } }, axisTick: { show: false } },
xAxis: { type: 'category', data: categories, axisLabel: { color: ink, fontSize: 10, interval: 0, rotate: allScopeWeight ? 0 : categories.length > 3 ? 34 : 0, width: allScopeWeight ? 80 : 160, overflow: 'break', hideOverlap: false, lineHeight: 13, ...(allScopeWeight ? { formatter: (name: string) => wrapAxisLabel(name, 80, 10, 5).join('\n') } : {}) }, axisLine: { lineStyle: { color: line } }, axisTick: { show: false } },
yAxis: [
{ type: 'value', min: 0, name: '重量(kg)', nameTextStyle: { color: mutedInk, fontSize: 10 }, axisLabel: { color: mutedInk, formatter: (value: number) => formatChartValue(value, 'kg') }, axisLine: { show: false }, splitLine: { lineStyle: { color: line, type: 'dashed' } } },
{ type: 'value', min: 0, max: 100, position: 'right', name: '累计占比', nameTextStyle: { color: mutedInk, fontSize: 10 }, axisLabel: { color: mutedInk, formatter: (value: number) => `${chartNumber(value)}%` }, axisLine: { show: false }, splitLine: { show: false } },
{ type: 'value', min: 0, max: 100, position: 'right', name: allScopeWeight ? cumulativeName : '累计占比', nameTextStyle: { color: mutedInk, fontSize: 10 }, axisLabel: { color: mutedInk, formatter: (value: number) => `${chartNumber(value)}%` }, axisLine: { show: false }, splitLine: { show: false } },
],
series: [
{ name: plainRichText(visual.series[0].label), type: 'bar', yAxisIndex: 0, data: visual.series[0].values, barMaxWidth: 48, itemStyle: { color: colors[0] }, label: { show: true, position: 'top', color: ink, fontSize: 10, formatter: (params: { dataIndex: number }) => formatChartValue(points[params.dataIndex]?.valueKg ?? null, 'kg') }, emphasis: { disabled: true } },
{ name: cumulativeName, type: 'line', yAxisIndex: 1, data: points.map(point => chartNumber(point.cumulativeShare * 100)), symbol: 'circle', symbolSize: 7, lineStyle: { width: 2.2, color: ink }, itemStyle: { color: ink }, label: { show: true, position: 'top', color: ink, fontSize: 10, formatter: (params: { data?: number }) => visualDonutShareText((params.data || 0) / 100) }, emphasis: { disabled: true } },
{ name: plainRichText(visual.series[0].label), type: 'bar', yAxisIndex: 0, data: visual.series[0].values, barMaxWidth: 48, itemStyle: { color: colors[0] }, label: { show: true, position: 'top', color: ink, fontSize: 10, formatter: (params: { dataIndex: number }) => paretoWeightLabel(points[params.dataIndex]?.valueKg ?? null, allScopeWeight) }, ...(allScopeWeight ? { labelLayout: { hideOverlap: true } } : {}), emphasis: { disabled: true } },
{ name: cumulativeName, type: 'line', yAxisIndex: 1, data: points.map(point => chartNumber(point.cumulativeShare * 100)), symbol: 'circle', symbolSize: 7, lineStyle: { width: 2.2, color: ink }, itemStyle: { color: ink }, label: { show: true, position: allScopeWeight ? 'bottom' : 'top', distance: 7, color: ink, fontSize: 10, formatter: (params: { data?: number; dataIndex?: number }) => allScopeWeight && params.dataIndex !== points.length - 1 ? '' : visualDonutShareText((params.data || 0) / 100) }, ...(allScopeWeight ? { labelLayout: { hideOverlap: true } } : {}), emphasis: { disabled: true } },
],
aria: { enabled: true, decal: { show: false } },
};
@@ -795,7 +893,7 @@ export function buildAnalysisVisualOption(visual: AnalysisVisual, theme: VisualC
const valueAxis = {
type: 'value' as const,
min: visual.unit === 'ratio' ? 0 : undefined,
max: visual.unit === 'ratio' ? 100 : undefined,
max: ratioAxisMax(visual),
scale: visual.unit !== 'ratio' ? false : undefined,
splitNumber: 3,
axisLabel: { color: mutedInk, formatter: numberAxisLabel, hideOverlap: true },
@@ -848,8 +946,38 @@ function wrapLines(value: string, maxChars: number, maxLines = Number.POSITIVE_I
return lines;
}
function unitLabel(unit: AnalysisVisualUnit): string {
if (unit === 'ratio') return '合格率(%)';
/** Use the same font and column width as the axis so export height includes every rendered line. */
function wrapAxisLabel(value: string, width: number, fontSize: number, maxLines = Number.POSITIVE_INFINITY): string[] {
const text = plainRichText(value).replace(/\s+/g, ' ').trim();
if (!text) return [];
let context: CanvasRenderingContext2D | null = null;
if (typeof document !== 'undefined') {
try { context = document.createElement('canvas').getContext('2d'); } catch { /* Conservative SSR fallback below. */ }
}
if (context) context.font = `${fontSize}px sans-serif`;
const measure = (line: string) => context ? context.measureText(line).width : Array.from(line).length * fontSize;
const lines: string[] = [];
let line = '';
for (const char of Array.from(text)) {
if (line && measure(line + char) > width - 2) {
lines.push(line);
line = '';
if (lines.length >= maxLines) {
let tail = lines[lines.length - 1];
while (tail && measure(tail + '…') > width - 2) tail = Array.from(tail).slice(0, -1).join('');
lines[lines.length - 1] = tail + '…';
return lines;
}
}
line += char;
}
if (line) lines.push(line);
return lines;
}
export function visualUnitLabel(visual: AnalysisVisual): string {
const unit = visual.unit;
if (unit === 'ratio') return isScrapRateMetric(visual.metric) ? '报废率(%)' : '合格率(%)';
if (unit === 'kg') return '重量(kg)';
if (unit === 'pp') return '变化(百分点)';
return '数量';
@@ -871,14 +999,14 @@ export function buildAnalysisVisualExportOption(visual: AnalysisVisual, width =
visual.subtitle,
`期间:${visualPeriodSummary(visual)}`,
`范围:${visualScopeSummary(visual.scope) || '按本轮查询条件'}`,
`单位:${unitLabel(visual.unit)}`,
`单位:${visualUnitLabel(visual)}`,
...(visual.stage ? [`阶段:${visual.stage === 'black' ? '黑片' : '亮片'}`] : []),
visual.coverage.truncated
? `本图展示 ${visual.coverage.returnedRows} / 共 ${visual.coverage.totalRows} 项`
: `覆盖:共 ${visual.coverage.totalRows} 项`,
...(visual.type === 'donut'
? ['占比口径:仅以本图已列类别重量合计为分母;不代表正式总报废占比']
: visual.type === 'pareto' ? ['累计占比口径:仅以本图已列类别重量合计为分母;不代表正式总报废累计占比']
: visual.type === 'pareto' ? [visual.coverage.shareBasis === 'all_scope_weight' ? '累计占比口径:以同范围全部重量为分母,Top末项可以低于100%' : '累计占比口径:仅以本图已列类别重量合计为分母;不代表正式总报废累计占比']
: visual.coverage.shareBasis ? [`占比口径:${visual.coverage.shareBasis}`] : []),
].filter(Boolean);
const headerLines = headerParts.flatMap(part => wrapLines(part, 96, 4));
@@ -886,24 +1014,37 @@ export function buildAnalysisVisualExportOption(visual: AnalysisVisual, width =
const footerParts = [
...(!reportMode && visual.type === 'donut' ? visualDonutShares(visual).map(({ categoryIndex, valueKg, share }) =>
`${visualCategoryLabel(visual, categoryIndex)}:${formatChartValue(valueKg, 'kg')}(占本图已列类别重量合计 ${visualDonutShareText(share)})`) : []),
...(visual.type === 'pareto' ? ['柏拉图累计占比=累计重量÷本图已列类别重量合计;不代表正式总报废累计占比'] : []),
...(visual.type === 'waterfall' ? ['阶段影响是对综合合格率变化的数学拆解,不代表生产根因。'] : []),
...(visual.type === 'pareto' ? [visual.coverage.shareBasis === 'all_scope_weight' ? '累计占比=所列累计重量÷同范围全部重量;Top未覆盖全量时不补足100%' : '柏拉图累计占比=累计重量÷本图已列类别重量合计;不代表正式总报废累计占比'] : []),
...(visual.type === 'waterfall' ? ['阶段影响是对综合合格率变化的拆解,不代表生产根因。'] : []),
...(!reportMode && visual.note ? [`说明:${visual.note}`] : []),
...(!reportMode && visual.evidenceRefs.length ? [`证据引用:${visual.evidenceRefs.join(' · ')}`] : []),
];
const footerLines = footerParts.flatMap(part => wrapLines(part, 124));
const chartBottom = footerLines.length ? footerLines.length * 15 + (reportMode ? 20 : 28) : (reportMode ? 10 : 24);
const wrappedCategories = visual.categories.map((_category, index) => wrapLines(visualCategoryLabel(visual, index), 14));
const allScopeWeight = visual.type === 'pareto' && visual.coverage.shareBasis === 'all_scope_weight';
const rankingLabelWidth = Math.max(16, (width - 174) / Math.max(1, visual.categories.length) - 8);
const wrappedCategories = visual.categories.map((_category, index) => allScopeWeight
? wrapAxisLabel(visualCategoryLabel(visual, index), rankingLabelWidth, reportMode ? 14 : 10)
: wrapLines(visualCategoryLabel(visual, index), 14));
const categoryLabelHeight = wrappedCategories.reduce((total, lines) => total + Math.max(28, lines.length * 14 + 8), 0);
const maxCategoryLines = Math.max(1, ...wrappedCategories.map(lines => lines.length));
const combinedDefects = visual.sectionKey === 'defect_combined' && visual.type === 'bar';
const reportCartesian = reportMode && ['column', 'line', 'area'].includes(visual.type);
const reportRotation = visual.type === 'column' ? (visual.categories.length > 5 ? 42 : 0)
: (visual.categories.length > 12 ? 42 : 0);
const reportLabelWidth = Math.min(160, Math.max(1, ...wrappedCategories.flatMap(lines => lines.map(line => Array.from(line).length * 14))));
const reportLabelHeight = Math.ceil(Math.sin(reportRotation * Math.PI / 180) * reportLabelWidth
+ Math.cos(reportRotation * Math.PI / 180) * maxCategoryLines * 18) + 22;
const reportLegendHeight = visual.series.length > 1 ? 30 : 0;
const reportPlotHeight = 230;
const chartHeight = visual.type === 'donut' ? (reportMode ? Math.max(390, 290 + maxCategoryLines * 20) : Math.max(600, 300 + maxCategoryLines * 20))
: visual.type === 'waterfall' ? (reportMode ? 300 : 480)
: visual.type === 'heatmap' ? Math.max(reportMode ? 180 : 240, visual.series.length * (reportMode ? 62 : 90))
: visual.type === 'pareto' ? (reportMode ? Math.max(300, 170 + maxCategoryLines * 18) : Math.max(480, categoryLabelHeight))
: visual.type === 'pareto' ? (allScopeWeight ? 330 + maxCategoryLines * (reportMode ? 18 : 14) : reportMode ? Math.max(300, 170 + maxCategoryLines * 18) : Math.max(480, categoryLabelHeight))
: combinedDefects ? Math.max(reportMode ? 350 : 410, visual.categories.length * (reportMode ? 42 : 46))
: reportMode ? visual.type === 'bar' ? Math.max(230, categoryLabelHeight * 1.3) : Math.max(230, 165 + maxCategoryLines * 20) : Math.max(480, categoryLabelHeight);
: reportCartesian ? reportPlotHeight + reportLabelHeight + reportLegendHeight
: reportMode ? visual.type === 'bar' ? Math.max(230, categoryLabelHeight * 1.3) : Math.max(230, 165 + maxCategoryLines * 20) : Math.max(480, categoryLabelHeight);
const height = chartTop + chartHeight + chartBottom;
const base = buildAnalysisVisualOption(visual, { ink: '#263c5a', mutedInk: '#65748b', line: '#dfe5ef', surface: '#ffffff' });
const categories = wrappedCategories.map(lines => lines.join('\n'));
@@ -934,7 +1075,7 @@ export function buildAnalysisVisualExportOption(visual: AnalysisVisual, width =
type: 'plain' as const,
top: reportMode ? chartTop + 2 : chartTop - 26,
left: 56,
data: [plainRichText(visual.series[0].label), '累计占本图已列类别合计'],
data: [plainRichText(visual.series[0].label), allScopeWeight ? '累计占全部重量' : '累计占本图已列类别合计'],
textStyle: { color: '#65748b', fontSize: 11 },
}
: {
@@ -1024,19 +1165,19 @@ export function buildAnalysisVisualExportOption(visual: AnalysisVisual, width =
}
: visual.type === 'pareto'
? {
grid: { left: 78, right: 78, top: chartTop, bottom: chartBottom + 96, containLabel: true },
grid: allScopeWeight ? { left: 78, right: 96, top: chartTop + 48, height: 260, containLabel: false } : { left: 78, right: 78, top: chartTop, bottom: chartBottom + 96, containLabel: true },
xAxis: {
type: 'category', data: categories, boundaryGap: true,
axisLabel: { color: '#263c5a', fontSize: 10, lineHeight: 12, rotate: categories.length > 3 ? 20 : 0, width: 190, overflow: 'break', interval: 0 },
axisLabel: { color: '#263c5a', fontSize: 10, lineHeight: 12, rotate: allScopeWeight ? 0 : categories.length > 3 ? 20 : 0, width: allScopeWeight ? rankingLabelWidth : 190, overflow: 'break', interval: 0, ...(allScopeWeight ? { fontFamily: 'sans-serif' } : {}) },
axisLine: { lineStyle: { color: '#dfe5ef' } }, axisTick: { show: false },
},
yAxis: [
{ type: 'value', min: 0, name: '重量(kg)', nameTextStyle: { color: '#65748b', fontSize: 10 }, axisLabel: { color: '#65748b', formatter: (value: number) => formatChartValue(value, 'kg') }, axisLine: { show: false }, splitLine: { lineStyle: { color: '#dfe5ef', type: 'dashed' } } },
{ type: 'value', min: 0, max: 100, position: 'right', name: '累计占比(本图已列类别)', nameTextStyle: { color: '#65748b', fontSize: 10 }, axisLabel: { color: '#65748b', formatter: (value: number) => `${chartNumber(value)}%` }, axisLine: { show: false }, splitLine: { show: false } },
{ type: 'value', min: 0, max: 100, position: 'right', name: allScopeWeight ? '累计占全部重量' : '累计占比(本图已列类别)', nameTextStyle: { color: '#65748b', fontSize: 10 }, axisLabel: { color: '#65748b', formatter: (value: number) => `${chartNumber(value)}%` }, axisLine: { show: false }, splitLine: { show: false } },
],
series: [
{ name: plainRichText(visual.series[0].label), type: 'bar', yAxisIndex: 0, data: visual.series[0].values, barMaxWidth: 48, itemStyle: { color: '#607ae1' }, label: { show: true, position: 'top', color: '#263c5a', fontSize: 10, formatter: (params: { dataIndex: number }) => formatChartValue(visualParetoPoints(visual)[params.dataIndex]?.valueKg ?? null, 'kg') } },
{ name: '累计占本图已列类别合计', type: 'line', yAxisIndex: 1, data: visualParetoPoints(visual).map(point => chartNumber(point.cumulativeShare * 100)), symbol: 'circle', symbolSize: 7, lineStyle: { width: 2.2, color: '#435d7a' }, itemStyle: { color: '#435d7a' }, label: { show: true, position: 'top', color: '#435d7a', fontSize: 10, formatter: (params: { data?: number }) => visualDonutShareText((params.data || 0) / 100) } },
{ name: plainRichText(visual.series[0].label), type: 'bar', yAxisIndex: 0, data: visual.series[0].values, barMaxWidth: 48, itemStyle: { color: '#607ae1' }, label: { show: true, position: 'top', color: '#263c5a', fontSize: 10, formatter: (params: { dataIndex: number }) => paretoWeightLabel(visualParetoPoints(visual)[params.dataIndex]?.valueKg ?? null, allScopeWeight) }, ...(allScopeWeight ? { labelLayout: { hideOverlap: true } } : {}) },
{ name: visual.coverage.shareBasis === 'all_scope_weight' ? '累计占全部重量' : '累计占本图已列类别合计', type: 'line', yAxisIndex: 1, data: visualParetoPoints(visual).map(point => chartNumber(point.cumulativeShare * 100)), symbol: 'circle', symbolSize: 7, lineStyle: { width: 2.2, color: '#435d7a' }, itemStyle: { color: '#435d7a' }, label: { show: true, position: allScopeWeight ? 'bottom' : 'top', distance: 8, color: '#435d7a', fontSize: 10, formatter: (params: { data?: number; dataIndex?: number }) => allScopeWeight && params.dataIndex !== visual.categories.length - 1 ? '' : visualDonutShareText((params.data || 0) / 100) }, ...(allScopeWeight ? { labelLayout: { hideOverlap: true } } : {}) },
],
}
: visual.type === 'waterfall'
@@ -1061,7 +1202,7 @@ export function buildAnalysisVisualExportOption(visual: AnalysisVisual, width =
xAxis: {
type: 'value',
min: visual.unit === 'ratio' ? 0 : undefined,
max: visual.unit === 'ratio' ? 100 : undefined,
max: ratioAxisMax(visual),
scale: visual.unit !== 'ratio' ? false : undefined,
axisLabel: { color: '#65748b', formatter: valueAxisLabel },
axisLine: { show: false },
@@ -1082,20 +1223,24 @@ export function buildAnalysisVisualExportOption(visual: AnalysisVisual, width =
type: 'category',
data: categories,
boundaryGap: visual.type === 'column',
axisLabel: { color: '#263c5a', fontSize: 10, lineHeight: 13, rotate: categories.length > 5 ? 42 : 0, width: 160, overflow: 'break', interval: 0, hideOverlap: false },
axisLabel: { color: '#263c5a', fontSize: 10, lineHeight: 13, rotate: reportCartesian ? reportRotation : categories.length > 5 ? 42 : 0, width: 160, overflow: 'break', interval: 0, hideOverlap: false },
axisLine: { lineStyle: { color: '#dfe5ef' } },
axisTick: { show: false },
},
yAxis: {
type: 'value',
min: visual.unit === 'ratio' ? 0 : undefined,
max: visual.unit === 'ratio' ? 100 : undefined,
max: ratioAxisMax(visual),
scale: visual.unit !== 'ratio' ? false : undefined,
axisLabel: { color: '#65748b', formatter: valueAxisLabel },
axisLine: { show: false },
splitLine: { lineStyle: { color: '#dfe5ef', type: 'dashed' } },
},
grid: { left: 64, right: 42, top: chartTop, bottom: chartBottom + (visual.type === 'column' ? 80 : reportMode ? 110 : 68), containLabel: true },
// Keep a real plot rectangle; containLabel may otherwise subtract all available
// height for the fixed-width rotated category labels and flatten the series.
grid: reportCartesian
? { left: 64, right: 42, top: chartTop + reportLegendHeight, height: reportPlotHeight, containLabel: false }
: { left: 64, right: 42, top: chartTop, bottom: chartBottom + (visual.type === 'column' ? 80 : 68), containLabel: true },
}),
};
if (reportMode) {
@@ -1115,6 +1260,11 @@ export function buildAnalysisVisualExportOption(visual: AnalysisVisual, width =
}
function plainPeriod(period: Record<string, unknown>): string {
const numeric = parseAnalysisPeriod(period);
if (numeric?.monthStart !== undefined && numeric.monthEnd !== undefined) return analysisPeriodLabel(period);
if (numeric?.year && numeric.month !== undefined) return `${numeric.year}-${String(numeric.month).padStart(2, '0')}`;
if (numeric?.year && numeric.quarter !== undefined) return `${numeric.year}年第${numeric.quarter}季度`;
if (numeric?.year) return `${numeric.year} 年`;
const label = typeof period.label === 'string' ? period.label : null;
if (label) return label;
const start = ['start', 'from', 'startMonth', 'begin'].map(key => period[key]).find(value => typeof value === 'string');
@@ -1122,10 +1272,6 @@ function plainPeriod(period: Record<string, unknown>): string {
if (typeof start === 'string' && typeof end === 'string') return start === end ? start : `${start} 至 ${end}`;
if (typeof start === 'string') return start;
if (typeof end === 'string') return end;
const year = period.year;
const month = period.month;
if (typeof year === 'number' && typeof month === 'number') return `${year}-${String(month).padStart(2, '0')}`;
if (typeof year === 'number') return `${year} 年`;
return '当前期间';
}
@@ -1141,9 +1287,37 @@ export function visualScopeSummary(scope: AnalysisVisual['scope']): string {
: value === true ? '是' : Array.isArray(value) ? value.join('、') : String(value)}`);
const filters = scope.extraFilters;
if (filters && typeof filters === 'object' && !Array.isArray(filters) && Object.keys(filters).length > 0) parts.push(`额外筛选 ${Object.keys(filters).length} 项`);
parts.push(...analysisExclusionSummary(scope.exclusions));
parts.push(...columnFilterSummary(scope.columnFilters, scope.columnLabels));
return parts.join(' · ');
}
export function analysisExclusionSummary(value: unknown): string[] {
const exclusions = safeExclusions(value);
if (!exclusions) return [];
const labels: Record<AnalysisExclusionDimension, string> = {
department: '产业部', group: '业务分组', product: '产品', projectGroup: '项目组',
};
return (['department', 'group', 'product', 'projectGroup'] as const).flatMap(dimension => {
const values = exclusions[dimension];
return values?.length ? [`排除${labels[dimension]}:${values.join('、')}`] : [];
});
}
export function columnFilterSummary(value: unknown, labelValue: unknown): string[] {
if (!Array.isArray(value)) return [];
const labels = isRecord(labelValue) ? labelValue : {};
return value.flatMap(rule => {
if (!isRecord(rule) || typeof rule.field !== 'string' || !Array.isArray(rule.stages)) return [];
const stage = rule.stages.map(item => item === 'black' ? '黑片' : item === 'bright' ? '亮片' : '').filter(Boolean).join('、');
const label = typeof labels[rule.field] === 'string' ? labels[rule.field] : '来源字段';
const operation = ({ in: '为', not_in: '排除', is_empty: '为空', not_empty: '不为空' } as Record<string, string>)[String(rule.operator)];
if (!operation) return [];
const values = Array.isArray(rule.values) ? rule.values.filter(item => typeof item === 'string').join('、') : '';
return [`${stage} ${label}${operation}${values}`.trim()];
});
}
export function visualPeriodSummary(visual: AnalysisVisual): string {
return visual.comparisonPeriod
? `${plainPeriod(visual.comparisonPeriod)} → ${plainPeriod(visual.period)}`