import test from 'node:test'; import assert from 'node:assert/strict'; import { buildAnalysisVisualOption, buildAnalysisVisualExportOption, combineStageDefectVisuals, formatVisualValue, parseAnalysisVisuals, renderVisualTableHtml, visualCategoryLabel, visualDonutShares, visualParetoPoints, } from '../src/analysisVisualsModel.ts'; function visual(overrides = {}) { return { id: 'visual-1', type: 'line', title: '月度合格率', subtitle: '正式综合率', unit: 'ratio', categories: [{ key: '2026-08', label: '2026-08' }, { key: '2026-09', label: '2026-09' }], series: [{ key: 'overall', label: '综合', values: [0.82, 0.84] }], evidenceRefs: ['evidence-1'], requiredFields: ['quality.combined_rate'], scope: { department: '工业电机' }, period: { start: '2026-08', end: '2026-09' }, comparisonPeriod: { label: '2026-08' }, metric: 'combined_rate', coverage: { totalRows: 2, returnedRows: 2, truncated: false }, originTurnId: 'turn-1', ...overrides, }; } function donut(overrides = {}) { return visual({ type: 'donut', title: '黑片正式报废类别重量构成', subtitle: '按已列正式类别展示', unit: 'kg', categories: [ { key: 'black_responsibility_scrap', label: '责废' }, { key: 'black_material_scrap', label: '料废' }, { key: 'black_external_scrap', label: '外废' }, ], series: [{ key: 'source_defect_weight', label: '类别重量', values: [0, 2, 8] }], stage: 'black', scope: { department: '工业电机', stage: 'black' }, metric: 'source_defect_weight', coverage: { totalRows: 3, returnedRows: 3, truncated: false, shareBasis: 'displayed_categories' }, ...overrides, }); } function pareto(overrides = {}) { return donut({ type: 'pareto', title: '正式报废类别柏拉图', series: [{ key: 'source_defect_weight', label: '类别重量', values: [8, 2, 0] }], ...overrides, }); } function waterfall(overrides = {}) { return visual({ type: 'waterfall', title: '综合率变化的阶段数学影响', subtitle: '对比两个期间的正式综合率变化', unit: 'pp', categories: [ { key: 'black', label: '黑片贡献' }, { key: 'bright', label: '亮片贡献' }, { key: 'total', label: '综合变化' }, ], series: [{ key: 'composite_impact_pp', label: '综合率阶段影响', values: [1.25, -0.25, 1] }], requiredFields: ['black_good_weight', 'black_total_weight', 'bright_good_weight', 'bright_total_weight'], scope: { department: '工业电机' }, period: { label: '2026-09' }, comparisonPeriod: { label: '2026-08' }, metric: 'composite_impact_pp', note: '数学拆解,不代表生产根因。', ...overrides, }); } test('parser preserves zero and null as different values', () => { const parsed = parseAnalysisVisuals([visual({ series: [{ key: 'a', label: 'A', values: [null, 0] }] })]); assert.equal(parsed.visuals.length, 1); assert.deepEqual(parsed.visuals[0].series[0].values, [null, 0]); const option = buildAnalysisVisualOption(parsed.visuals[0]); assert.deepEqual(option.series[0].data, [null, 0]); assert.equal(option.series[0].connectNulls, false); assert.equal(option.animation, false); }); test('same-scope black and bright defect changes become one stage-colored chart', () => { const defect = (stage, values, product = '规格 A') => visual({ id: `defect-${stage}-${product}`, type: 'bar', title: `${stage}具体缺陷`, subtitle: '来源字段', unit: 'kg', metric: 'source_defect_delta_weight', sectionKey: `defect_${stage}`, dimension: 'defect', stage, scope: { product, stage }, period: { year: 2026, month: 9 }, comparisonPeriod: { year: 2026, month: 8 }, categories: values.map((_, index) => ({ key: `field-${index}`, label: `缺陷 ${index}` })), series: [{ key: 'delta', label: '增减', values }], evidenceRefs: [`ref-${stage}`], requiredFields: values.map((_, index) => `field-${index}`), coverage: { totalRows: values.length, returnedRows: values.length, truncated: false }, }); const [black, bright, other] = parseAnalysisVisuals([ defect('black', [265.85, 0, -12]), defect('bright', [123.42, 0, 39.25]), defect('bright', [9], '规格 B'), ]).visuals; const combined = combineStageDefectVisuals([black, bright, other]); assert.equal(combined.length, 2); assert.equal(combined[0].sectionKey, 'defect_combined'); assert.deepEqual(combined[0].evidenceRefs, ['ref-black', 'ref-bright']); assert.deepEqual(combined[0].categories.map(item => item.label), ['黑片 · 缺陷 0', '亮片 · 缺陷 0', '亮片 · 缺陷 2', '黑片 · 缺陷 2']); assert.deepEqual(combined[0].series[0].values, [265.85, null, null, -12]); assert.deepEqual(combined[0].series[1].values, [null, 123.42, 39.25, null]); assert.equal(combined[0].chartable, true); const chart = buildAnalysisVisualOption(combined[0]); assert.equal(chart.legend.show, false); assert.equal(chart.series[0].stack, chart.series[1].stack); assert.equal(chart.series[0].barWidth, 18); const reportChart = buildAnalysisVisualExportOption(combined[0], 1280, 'report').option; assert.equal(reportChart.legend.show, false); assert.equal(reportChart.series[0].stack, reportChart.series[1].stack); assert.equal(combined[1].scope.product, '规格 B'); assert.equal(combineStageDefectVisuals(combined).length, 2); }); test('ratio charts use 0 to 100 percent and convert raw ratios only for plotting', () => { const parsed = parseAnalysisVisuals([visual()]); const option = buildAnalysisVisualOption(parsed.visuals[0]); assert.equal(option.yAxis.min, 0); assert.equal(option.yAxis.max, 100); assert.deepEqual(option.series[0].data, [82, 84]); assert.equal(formatVisualValue(0.8425, 'ratio'), '84.25%'); }); test('empty subtitle and extra-filter maps survive strict parsing', () => { const parsed = parseAnalysisVisuals([visual({ subtitle: ' ', scope: { extraFilters: { quality_type: ['A级', 'B级'] } } })]); assert.equal(parsed.visuals.length, 1); assert.equal(parsed.visuals[0].subtitle, ''); assert.deepEqual(parsed.visuals[0].scope.extraFilters, { quality_type: ['A级', 'B级'] }); }); test('negative percentage point changes remain signed and keep a zero baseline', () => { const parsed = parseAnalysisVisuals([visual({ type: 'bar', unit: 'pp', comparisonPeriod: undefined, categories: [{ key: 'p1', label: '规格一' }, { key: 'p2', label: '规格二' }], series: [{ key: 'delta', label: '变化', values: [-2.75, 0] }], })]); const option = buildAnalysisVisualOption(parsed.visuals[0]); assert.deepEqual(option.series[0].data, [-2.75, 0]); assert.equal(option.xAxis.scale, false); assert.equal(option.xAxis.max, undefined); assert.equal(formatVisualValue(-2.75, 'pp'), '-2.75 pp'); assert.equal(formatVisualValue(0.5, 'pp'), '+0.5 pp'); }); test('non-finite and out-of-range ratio values degrade to a table while retaining zero and null', () => { const parsed = parseAnalysisVisuals([visual({ series: [{ key: 'r', label: '率', values: [0, Number.NaN] }] })]); assert.equal(parsed.visuals.length, 1); assert.equal(parsed.visuals[0].chartable, false); assert.deepEqual(parsed.visuals[0].series[0].values, [0, null]); assert.deepEqual(parsed.visuals[0].invalidValueCells, ['0:1']); const outOfRange = parseAnalysisVisuals([visual({ series: [{ key: 'r', label: '率', values: [1.02, null] }] })]); assert.equal(outOfRange.visuals[0].chartable, false); assert.deepEqual(outOfRange.visuals[0].series[0].values, [1.02, null]); }); test('business labels remain plain text in tooltip output and data options', () => { const hostile = ' {style|name}'; const parsed = parseAnalysisVisuals([visual({ categories: [{ key: 'x', label: hostile }, { key: 'y', label: '第二项' }], series: [{ key: 's', label: '', values: [0.2, 0.3] }], })]); const option = buildAnalysisVisualOption(parsed.visuals[0]); assert.equal(option.xAxis.data[0], hostile); assert.equal(option.tooltip.renderMode, 'richText'); const tooltip = option.tooltip.formatter([{ dataIndex: 0, seriesIndex: 0 }]); assert.equal(tooltip.includes(''), true); assert.equal(tooltip.includes('{style|name}'), true); assert.equal(tooltip.includes(''), false); }); test('duplicate category labels append keys everywhere while unique labels stay clean', () => { const parsed = parseAnalysisVisuals([visual({ type: 'bar', categories: [ { key: 'part-a', label: '同名规格' }, { key: 'part-b', label: '同名规格' }, { key: 'part-c', label: '独立规格' }, ], series: [{ key: 's', label: '重量', values: [3, 2, 1] }], })]); const model = parsed.visuals[0]; const expected = ['同名规格 · part-a', '同名规格 · part-b', '独立规格']; const option = buildAnalysisVisualOption(model); assert.deepEqual(option.yAxis.data, expected); assert.deepEqual(model.categories.map((_, index) => visualCategoryLabel(model, index)), expected); const tooltip = option.tooltip.formatter([{ dataIndex: 1, seriesIndex: 0 }]); assert.match(tooltip, /同名规格 · part-b/); const table = renderVisualTableHtml(model); assert.match(table, /同名规格 · part-a/); assert.match(table, /同名规格 · part-b/); assert.match(table, /独立规格/); assert.doesNotMatch(table, /独立规格 · part-c/); }); test('static export option includes wrapped title, period, scope, unit, note, evidence and all series', () => { const parsed = parseAnalysisVisuals([visual({ title: '这是一条用于静态导出标题换行检查的较长业务图表标题,完整保留原文并确认不会遗漏任何业务上下文', subtitle: '黑片与亮片合格率对比', note: '说明文本需要进入图片,作为图表下方的静态脚注。', evidenceRefs: ['evidence-black-1', 'evidence-bright-2'], series: [ { key: 'black', label: '黑片', values: [0.82, 0.84] }, { key: 'bright', label: '亮片', values: [0.91, 0.93] }, ], })]); const visualModel = parsed.visuals[0]; const { option, width, height } = buildAnalysisVisualExportOption(visualModel); assert.equal(width, 1280); assert.ok(height > 540); assert.match(option.title.text, /\n/); assert.match(option.title.text, /静态导出标题/); assert.match(option.title.subtext, /期间:2026-08 → 2026-08 至 2026-09/); assert.match(option.title.subtext, /范围:产业部:工业电机/); assert.match(option.title.subtext, /单位:合格率(%)/); assert.equal(option.series.length, 2); assert.deepEqual(option.series.map(series => series.data), [[82, 84], [91, 93]]); assert.deepEqual(Object.values(option.legend.selected), [true, true]); assert.equal(option.tooltip.show, false); const footerText = option.graphic.elements[0].style.text; assert.match(footerText, /说明:说明文本需要进入图片/); assert.match(footerText, /证据引用:evidence-black-1 · evidence-bright-2/); }); test('static export wraps long category labels and keeps the complete value table', () => { const label = '很长的产品规格名称'.repeat(12); const parsed = parseAnalysisVisuals([visual({ categories: [{ key: 'long', label }, { key: 'short', label: '短名称' }] })]); const { option } = buildAnalysisVisualExportOption(parsed.visuals[0]); assert.match(option.xAxis.data[0], /\n/); assert.ok(option.grid.top > 80); assert.match(renderVisualTableHtml(parsed.visuals[0]), new RegExp(label)); }); test('report table markup escapes hostile labels and scripts', () => { const hostile = '&"'; const parsed = parseAnalysisVisuals([visual({ categories: [{ key: 'x', label: hostile }, { key: 'y', label: '二' }], series: [{ key: 's', label: '', values: [0, null] }], })]); const html = renderVisualTableHtml(parsed.visuals[0]); assert.match(html, /<img src=x onerror=alert\(1\)>&"/); assert.match(html, /<script>alert\(1\)<\/script>/); assert.equal(html.includes(''), false); }); test('unknown chart type and schema versions are safely rejected or shown as data tables', () => { const unsupported = parseAnalysisVisuals([visual({ type: 'pie' })]); assert.equal(unsupported.visuals[0].chartable, false); assert.match(unsupported.visuals[0].chartIssue, /数据表/); const unknownVersion = parseAnalysisVisuals({ visualSchemaVersion: 2, visuals: [visual()] }); assert.deepEqual(unknownVersion.visuals, []); assert.match(unknownVersion.issues[0], /版本/); }); test('duplicate ids, malformed values, and over-size payloads do not break neighboring results', () => { const duplicate = parseAnalysisVisuals([visual(), visual({ title: '重复编号' })]); assert.equal(duplicate.visuals.length, 1); assert.ok(duplicate.issues.some(issue => issue.includes('编号重复'))); const malformed = parseAnalysisVisuals([visual({ series: [{ key: 'bad', label: '坏', values: [1] }] }), visual({ id: 'visual-2' })]); assert.equal(malformed.visuals.length, 1); assert.equal(malformed.visuals[0].id, 'visual-2'); const oversized = parseAnalysisVisuals([visual({ title: 'x'.repeat(270_000) })]); assert.deepEqual(oversized.visuals, []); assert.match(oversized.issues[0], /大小限制/); }); test('up to twelve visuals are admitted while later charts stay outside the render', () => { const result = parseAnalysisVisuals(Array.from({ length: 13 }, (_, index) => visual({ id: `visual-${index + 1}` }))); assert.equal(result.visuals.length, 12); assert.ok(result.issues.some(issue => issue.includes('前 12 张'))); }); test('column is vertical, preserves zero and places negative values below their endpoints', () => { const fullLabel = '特长规格名称用于检查轴标签缩短但数据仍保留完整名称'.repeat(2); const model = parseAnalysisVisuals([visual({ type: 'column', unit: 'pp', categories: [{ key: 'negative', label: fullLabel }, { key: 'zero', label: '零变化' }], series: [{ key: 'change', label: '变化', values: [-3.25, 0] }], })]).visuals[0]; assert.equal(model.chartable, true); const option = buildAnalysisVisualOption(model); assert.equal(option.xAxis.type, 'category'); assert.equal(option.yAxis.type, 'value'); assert.equal(option.yAxis.scale, false); assert.deepEqual(option.series[0].data.map(item => item.value), [-3.25, 0]); assert.equal(option.series[0].data[0].label.position, 'bottom'); assert.equal(option.series[0].data[1].label.position, 'top'); assert.doesNotMatch(option.xAxis.data[0], new RegExp(fullLabel)); const tooltip = option.tooltip.formatter([{ dataIndex: 0, seriesIndex: 0 }]); assert.ok(tooltip.includes(fullLabel)); assert.ok(renderVisualTableHtml(model).includes(fullLabel)); const exported = buildAnalysisVisualExportOption(model); assert.equal(exported.option.xAxis.type, 'category'); assert.equal(exported.option.yAxis.type, 'value'); assert.match(exported.option.xAxis.data[0], /\n/); }); test('area is a single filled line series and retains null gaps without stacking', () => { const model = parseAnalysisVisuals([visual({ type: 'area', categories: [{ key: 'a', label: '一月' }, { key: 'b', label: '二月' }, { key: 'c', label: '三月' }], series: [{ key: 'rate', label: '合格率', values: [0.8, null, 0.9] }], })]).visuals[0]; const option = buildAnalysisVisualOption(model); assert.equal(model.chartable, true); assert.equal(option.series[0].type, 'line'); assert.equal(option.series[0].areaStyle.opacity, 0.18); assert.equal(option.series[0].stack, undefined); assert.deepEqual(option.series[0].data, [80, null, 90]); assert.equal(option.series[0].connectNulls, false); const exported = buildAnalysisVisualExportOption(model); assert.equal(exported.option.series[0].type, 'line'); assert.ok(exported.option.series[0].areaStyle); const invalid = parseAnalysisVisuals([visual({ type: 'area', series: [ { key: 'a', label: 'A', values: [0.1, 0.2] }, { key: 'b', label: 'B', values: [0.2, 0.3] }, ] })]).visuals[0]; assert.equal(invalid.chartable, false); assert.match(invalid.chartIssue, /单一序列/); }); test('heatmap omits null cells, plots actual zero, and uses a sign-neutral diverging palette', () => { const model = parseAnalysisVisuals([visual({ type: 'heatmap', unit: 'pp', categories: [{ key: 'missing', label: '缺失期' }, { key: 'zero', label: '零变化' }, { key: 'up', label: '改善' }], series: [{ key: 'delta', label: '百分点变化', values: [null, 0, 2.5] }], })]).visuals[0]; const option = buildAnalysisVisualOption(model); assert.equal(model.chartable, true); assert.equal(option.series[0].type, 'heatmap'); assert.deepEqual(option.series[0].data, [[1, 0, 0], [2, 0, 2.5]]); assert.equal(option.grid.backgroundColor, '#eef1f5'); assert.equal(option.visualMap.min, 0); assert.deepEqual(option.visualMap.inRange.color, ['#e8ebef', '#557fb3']); assert.equal(option.series[0].label.formatter({ data: [1, 0, 0] }), '0.00'); assert.equal(option.series[0].label.formatter({ data: [2, 0, 2.5] }), '2.50'); const signed = parseAnalysisVisuals([visual({ type: 'heatmap', unit: 'pp', series: [{ key: 'delta', label: '变化', values: [-2, 0] }], })]).visuals[0]; const signedOption = buildAnalysisVisualOption(signed); assert.equal(signedOption.visualMap.min, -2); assert.equal(signedOption.visualMap.max, 2); assert.deepEqual(signedOption.visualMap.inRange.color, ['#557fb3', '#f1f3f5', '#c66565']); const exported = buildAnalysisVisualExportOption(signed); assert.equal(exported.option.series[0].type, 'heatmap'); assert.equal(exported.option.visualMap.right, 18); assert.equal(exported.option.xAxis.data[0], '2026-08'); const ratio = parseAnalysisVisuals([visual({ type: 'heatmap' })]).visuals[0]; const ratioOption = buildAnalysisVisualOption(ratio); assert.match(ratioOption.tooltip.formatter({ data: [1, 0, 84] }), /84%/); assert.doesNotMatch(ratioOption.tooltip.formatter({ data: [1, 0, 84] }), /8400/); }); test('heatmap static export suppresses crowded cell labels but preserves all cells and table values', () => { const categories = Array.from({ length: 36 }, (_, index) => ({ key: `2026-${index + 1}`, label: `2026-${String(index + 1).padStart(2, '0')}` })); const model = parseAnalysisVisuals([visual({ type: 'heatmap', unit: 'kg', categories, series: [{ key: 'weight', label: '重量', values: categories.map((_item, index) => index) }], })]).visuals[0]; const exported = buildAnalysisVisualExportOption(model); assert.equal(exported.option.series[0].label.show, false); assert.equal(exported.option.series[0].data.length, 36); assert.ok(exported.height < 900, 'a single indicator stays compact when more months are shown horizontally'); assert.match(renderVisualTableHtml(model), /2026-36/); }); test('donut accepts only a complete official mutually-exclusive category set and uses listed-weight denominator', () => { const parsed = parseAnalysisVisuals([donut()]); const model = parsed.visuals[0]; assert.equal(model.chartable, true); assert.deepEqual(visualDonutShares(model).map(item => item.share), [0, 0.2, 0.8]); const option = buildAnalysisVisualOption(model); assert.equal(option.series[0].type, 'pie'); assert.deepEqual(option.series[0].data.map(item => item.value), [0, 2, 8]); assert.match(option.graphic[0].style.text, /10 kg/); assert.match(option.graphic[1].style.text, /不代表正式总报废占比/); assert.match(option.series[0].label.formatter({ dataIndex: 1 }), /20%/); const table = renderVisualTableHtml(model); assert.match(table, /占比以本图所列类别重量合计为分母/); assert.match(table, /20%/); const exported = buildAnalysisVisualExportOption(model); assert.equal(exported.option.series[0].type, 'pie'); assert.equal(exported.option.grid, undefined); assert.equal(exported.option.legend.show, true); assert.match(exported.option.title.subtext, /不代表正式总报废占比/); assert.match(exported.option.graphic.elements.map(item => item.style.text || '').join('\n'), /责废:0 kg/); assert.match(exported.option.graphic.elements[0].style.text, /10 kg/); assert.equal(exported.option.series[0].center[0], 640); assert.ok(exported.height > 600); const bright = parseAnalysisVisuals([donut({ stage: 'bright', scope: { stage: 'bright' }, categories: [ { key: 'bright_plating_scrap', label: '镀废' }, { key: 'bright_material_scrap', label: '材料废' }, { key: 'bright_processing_scrap', label: '加工废' }, { key: 'bright_diffusion_scrap', label: '扩散废' }, ], series: [{ key: 'source_defect_weight', label: '类别重量', values: [1, 1, 1, 1] }], coverage: { totalRows: 4, returnedRows: 4, truncated: false, shareBasis: 'displayed_categories' }, })]).visuals[0]; assert.equal(bright.chartable, true); }); test('donut rejects source details, ranking, missing values, negative and all-zero denominators', () => { const badCases = [ donut({ categories: [{ key: 'source-defect-crack', label: '裂纹' }, { key: 'black_material_scrap', label: '料废' }, { key: 'black_external_scrap', label: '外废' }] }), donut({ categories: [{ key: 'spec-a', label: '规格甲' }, { key: 'spec-b', label: '规格乙' }, { key: 'spec-c', label: '规格丙' }] }), donut({ stage: undefined, scope: {} }), donut({ stage: 'bright' }), donut({ metric: 'current_scrap_weight' }), donut({ unit: 'count' }), donut({ coverage: { totalRows: 3, returnedRows: 3, truncated: false, shareBasis: 'formal_total' } }), donut({ coverage: { totalRows: 4, returnedRows: 3, truncated: false, shareBasis: 'displayed_categories' } }), donut({ coverage: { totalRows: 3, returnedRows: 3, truncated: true, shareBasis: 'displayed_categories' } }), donut({ scope: { stage: 'bright' } }), donut({ scope: { category: '责废' } }), donut({ series: [{ key: 'source_defect_weight', label: '类别重量', values: [0, null, 8] }] }), donut({ series: [{ key: 'source_defect_weight', label: '类别重量', values: [-1, 2, 8] }] }), donut({ series: [{ key: 'source_defect_weight', label: '类别重量', values: [0, 0, 0] }] }), donut({ series: [{ key: 'source_defect_weight', label: '类别重量', values: [1e308, 1e308, 0] }] }), donut({ series: [{ key: 'source_defect_weight', label: '类别重量', values: [2, 8, 0] }, { key: 'other', label: '其他', values: [1, 2, 3] }] }), ]; for (const malformed of badCases) { const parsed = parseAnalysisVisuals([malformed]); assert.equal(parsed.visuals.length, 1); assert.equal(parsed.visuals[0].chartable, false, JSON.stringify(malformed)); assert.match(parsed.visuals[0].chartIssue, /以下展示原始数据表/); assert.deepEqual(visualDonutShares(parsed.visuals[0]), []); } }); test('all supported chart types export through their own chart family with safe special labels', () => { const cases = [ visual({ type: 'bar' }), visual({ type: 'line' }), visual({ type: 'column', unit: 'count', categories: [{ key: 'x', label: '产品甲' }, { key: 'y', label: '产品乙' }] }), visual({ type: 'area', categories: [{ key: 'x', label: '一月' }, { key: 'y', label: '二月' }] }), visual({ type: 'heatmap', categories: [{ key: 'x', label: '一月' }, { key: 'y', label: '二月' }] }), donut({ title: ' {danger|title}' }), pareto(), ]; const expectedTypes = ['bar', 'line', 'bar', 'line', 'heatmap', 'pie', 'bar']; cases.forEach((item, index) => { const model = parseAnalysisVisuals([item]).visuals[0]; assert.equal(model.chartable, true); const option = buildAnalysisVisualOption(model); const exported = buildAnalysisVisualExportOption(model); assert.ok(exported.option.title.text.length > 0); assert.ok(exported.option.title.subtext.includes('期间:')); assert.equal(exported.option.series[0].type, expectedTypes[index]); assert.equal(exported.option.tooltip.show, false); assert.equal(exported.option.animation, false); }); const hostile = parseAnalysisVisuals([donut({ title: ' {danger|title}' })]).visuals[0]; const exported = buildAnalysisVisualExportOption(hostile); assert.match(exported.option.title.text.replace(/\n/g, ''), /{danger\|title}/); assert.match(exported.option.title.text, //); assert.equal(hostile.chartable, true); }); test('Pareto is an official-category dual-axis chart with computed listed-category shares', () => { const parsed = parseAnalysisVisuals([pareto({ series: [{ key: 'source_defect_weight', label: '报废重量', values: [8, 2, 0] }], })]); const model = parsed.visuals[0]; assert.equal(model.chartable, true); assert.deepEqual(visualParetoPoints(model), [ { categoryIndex: 0, valueKg: 8, share: 0.8, cumulativeShare: 0.8 }, { categoryIndex: 1, valueKg: 2, share: 0.2, cumulativeShare: 1 }, { categoryIndex: 2, valueKg: 0, share: 0, cumulativeShare: 1 }, ]); const option = buildAnalysisVisualOption(model); assert.deepEqual(option.yAxis.map(axis => axis.type), ['value', 'value']); assert.equal(option.yAxis[0].name, '重量(kg)'); assert.equal(option.yAxis[1].max, 100); assert.equal(option.series[0].type, 'bar'); assert.equal(option.series[0].yAxisIndex, 0); assert.deepEqual(option.series[0].data, [8, 2, 0]); assert.equal(option.series[1].type, 'line'); assert.equal(option.series[1].yAxisIndex, 1); assert.deepEqual(option.series[1].data, [80, 100, 100]); assert.equal(option.series[1].label.formatter({ data: 87.571488 }), '87.57%'); const darkOption = buildAnalysisVisualOption(model, { ink: '#eaf0fa' }); assert.equal(darkOption.series[1].lineStyle.color, '#eaf0fa'); assert.match(option.legend.data[1], /累计占本图已列类别合计/); const tooltip = option.tooltip.formatter([ { dataIndex: 1, seriesIndex: 0 }, { dataIndex: 1, seriesIndex: 1 }, ]); assert.match(tooltip, /报废重量:2 kg/); assert.match(tooltip, /本图类别占比:20%/); assert.match(tooltip, /累计占本图已列类别合计:100%/); assert.doesNotMatch(tooltip, /正式总报废/); const exported = buildAnalysisVisualExportOption(model); assert.equal(exported.option.series[0].type, 'bar'); assert.equal(exported.option.series[1].type, 'line'); assert.deepEqual(exported.option.yAxis.map(axis => axis.max), [undefined, 100]); assert.match(exported.option.title.subtext, /不代表正式总报废累计占比/); assert.match(exported.option.graphic.elements[0].style.text, /柏拉图累计占比=累计重量/); assert.equal(exported.option.tooltip.show, false); }); test('Pareto rejects incomplete, negative, ascending, or non-official category data', () => { const badCases = [ pareto({ series: [{ key: 'source_defect_weight', label: '重量', values: [2, 8, 0] }] }), pareto({ series: [{ key: 'source_defect_weight', label: '重量', values: [8, null, 0] }] }), pareto({ series: [{ key: 'source_defect_weight', label: '重量', values: [8, -2, 0] }] }), pareto({ series: [{ key: 'source_defect_weight', label: '重量', values: [0, 0, 0] }] }), pareto({ series: [{ key: 'source_defect_weight', label: '重量', values: [1e308, 1e308, 0] }] }), pareto({ categories: [{ key: 'specific-crack', label: '裂纹' }, { key: 'b', label: '材料废' }, { key: 'c', label: '外废' }] }), pareto({ coverage: { totalRows: 4, returnedRows: 3, truncated: false, shareBasis: 'displayed_categories' } }), pareto({ coverage: { totalRows: 3, returnedRows: 3, truncated: false, shareBasis: 'formal_total' } }), pareto({ metric: 'current_scrap_weight' }), pareto({ unit: 'count' }), pareto({ stage: undefined, scope: {} }), ]; for (const malformed of badCases) { const parsed = parseAnalysisVisuals([malformed]); assert.equal(parsed.visuals[0].chartable, false, JSON.stringify(malformed)); assert.match(parsed.visuals[0].chartIssue, /以下展示原始数据表/); assert.deepEqual(visualParetoPoints(parsed.visuals[0]), []); } }); test('composition legends cannot change the denominator and authorized category subsets remain chartable', () => { const categories = [{ key: 'black_responsibility_scrap', label: '责废' }, { key: 'black_material_scrap', label: '料废' }]; for (const type of ['donut', 'pareto']) { const model = parseAnalysisVisuals([donut({ type, categories, series: [{ key: 'source_defect_weight', label: '类别重量', values: [3, 2] }], coverage: { totalRows: 2, returnedRows: 2, truncated: false, shareBasis: 'displayed_categories' }, })]).visuals[0]; assert.equal(model.chartable, true); assert.equal(buildAnalysisVisualOption(model).legend.selectedMode, false); const points = type === 'donut' ? visualDonutShares(model) : visualParetoPoints(model); assert.deepEqual(points.map(point => point.share), [0.6, 0.4]); } }); test('negative area data is shown as a table rather than filled as a valid trend', () => { const model = parseAnalysisVisuals([visual({ type: 'area', unit: 'kg', series: [{ key: 'current_scrap_weight', label: '重量', values: [10, -2] }], })]).visuals[0]; assert.equal(model.chartable, false); assert.match(model.chartIssue, /负值/); }); test('report export removes duplicated context but standalone export keeps full context', () => { const model = parseAnalysisVisuals([visual({ note: '需在原始表格保持精确值。' })]).visuals[0]; const standalone = buildAnalysisVisualExportOption(model); const report = buildAnalysisVisualExportOption(model, 1280, 'report'); assert.match(standalone.option.title.text, /月度合格率/); assert.match(standalone.option.title.subtext, /期间:2026-08 → 2026-08 至 2026-09/); assert.match(standalone.option.title.subtext, /范围:产业部:工业电机/); assert.equal(report.width, 1280); assert.equal(report.option.title.show, false); assert.equal(report.option.title.text, ''); assert.equal(report.option.title.subtext, ''); assert.ok(report.height < standalone.height); assert.equal(report.option.tooltip.show, false); }); test('section and dimension metadata use fixed enums and unknown visual keys are rejected', () => { const valid = parseAnalysisVisuals([visual({ sectionKey: 'department', dimension: 'department' })]); assert.equal(valid.visuals[0].sectionKey, 'department'); assert.equal(valid.visuals[0].dimension, 'department'); assert.deepEqual(parseAnalysisVisuals([visual({ sectionKey: 'run-code' })]).visuals, []); assert.deepEqual(parseAnalysisVisuals([visual({ dimension: 'anything' })]).visuals, []); assert.deepEqual(parseAnalysisVisuals([visual({ executable: 'alert(1)' })]).visuals, []); assert.deepEqual(parseAnalysisVisuals([visual({ categories: [{ key: 'x', label: 'X', renderer: 'html' }, { key: 'y', label: 'Y' }] })]).visuals, []); }); test('untrusted getters and function-valued metadata never run in the parser', () => { let getterCalled = false; const hostile = visual(); Object.defineProperty(hostile, 'title', { enumerable: true, get() { getterCalled = true; return 'bad'; } }); const getterResult = parseAnalysisVisuals([hostile]); assert.equal(getterCalled, false); assert.deepEqual(getterResult.visuals, []); const functionValue = visual({ callback: () => { getterCalled = true; } }); assert.deepEqual(parseAnalysisVisuals([functionValue]).visuals, []); assert.equal(getterCalled, false); }); test('waterfall validates authorized inputs and renders signed stages from a zero baseline', () => { const model = parseAnalysisVisuals([waterfall()]).visuals[0]; assert.equal(model.chartable, true); const option = buildAnalysisVisualOption(model); assert.equal(option.legend.selectedMode, false); assert.deepEqual(option.legend.data, ['阶段影响', '综合变化']); assert.equal(option.series[0].name, '辅助基线'); assert.equal(option.series[0].stackStrategy, 'all'); assert.deepEqual(option.series[0].data, [0, 1, 0]); assert.deepEqual(option.series[1].data.map(item => item.value), [1.25, 0.25, 0]); assert.deepEqual(option.series[2].data.map(item => item.value), [0, 0, 1]); assert.equal(option.series[1].data[1].itemStyle.color, '#c66565'); assert.equal(option.series[1].label.formatter({ dataIndex: 0 }), '+1.25 pp'); assert.equal(option.series[1].label.formatter({ dataIndex: 1 }), '-0.25 pp'); const tooltip = option.tooltip.formatter([{ dataIndex: 1, seriesIndex: 1 }]); assert.match(tooltip, /亮片贡献/); assert.match(tooltip, /-0.25 pp/); assert.match(tooltip, /不代表生产根因/); const exported = buildAnalysisVisualExportOption(model, 1280, 'report'); assert.equal(exported.option.title.show, false); assert.equal(exported.option.legend.show, false); assert.match(exported.option.graphic.elements[0].style.text, /数学拆解/); assert.match(exported.option.graphic.elements[0].style.text, /不代表生产根因/); assert.equal(exported.option.yAxis.name, '变化(百分点)'); assert.ok(exported.height < 440); }); test('waterfall requires the exact four-field permission, two periods, an overall scope, and a matching sum', () => { const validTolerance = parseAnalysisVisuals([waterfall({ series: [{ key: 'composite_impact_pp', label: '影响', values: [1.25, -0.25, 1.000000009] }] })]).visuals[0]; assert.equal(validTolerance.chartable, true); const badCases = [ waterfall({ requiredFields: ['black_good_weight', 'black_total_weight', 'bright_good_weight'] }), waterfall({ requiredFields: ['black_good_weight', 'black_total_weight', 'bright_good_weight', 'bright_total_weight', 'bright_scrap_weight'] }), waterfall({ scope: { stage: 'black' } }), waterfall({ scope: { category: '责废' } }), waterfall({ scope: { defect: '裂纹' } }), waterfall({ stage: 'black' }), waterfall({ comparisonPeriod: undefined }), waterfall({ period: { label: '2026-08' }, comparisonPeriod: { label: '2026-08' } }), waterfall({ metric: 'combined_rate' }), waterfall({ unit: 'ratio' }), waterfall({ categories: [{ key: 'black', label: '黑片' }, { key: 'total', label: '总计' }, { key: 'bright', label: '亮片' }] }), waterfall({ series: [{ key: 'other', label: '影响', values: [1.25, -0.25, 1] }] }), waterfall({ series: [{ key: 'composite_impact_pp', label: '影响', values: [1.25, -0.25, 1.00000002] }] }), waterfall({ series: [{ key: 'composite_impact_pp', label: '影响', values: [1.25, null, 1] }] }), ]; for (const item of badCases) { const parsed = parseAnalysisVisuals([item]); assert.equal(parsed.visuals.length, 1, JSON.stringify(item)); assert.equal(parsed.visuals[0].chartable, false, JSON.stringify(item)); assert.match(parsed.visuals[0].chartIssue, /表/); } }); test('declining waterfall total remains negative and hides unused total labels', () => { const model = parseAnalysisVisuals([waterfall({series:[{key:'composite_impact_pp',label:'影响',values:[-0.30,-0.15,-0.45]}]})]).visuals[0]; for(const option of [buildAnalysisVisualOption(model),buildAnalysisVisualExportOption(model,900,'report').option]) { assert.equal(option.series[2].data[2].value,-0.45); assert.equal(option.series[2].data[0].label.show,false); assert.equal(option.series[2].data[1].label.show,false); assert.equal(option.series[1].data[2].label.show,false); assert.deepEqual(option.series[0].data,[ -0.3,-0.44999999999999996,0 ]); } }); test('kg and pp chart labels round to two decimals while tooltips and tables keep source precision', () => { const model = parseAnalysisVisuals([visual({ type: 'column', unit: 'pp', categories: [{ key: 'up', label: '改善' }, { key: 'down', label: '下降' }], series: [{ key: 'change', label: '变化', values: [2.34567, -1.23456] }], })]).visuals[0]; const option = buildAnalysisVisualOption(model); assert.equal(option.series[0].data[0].value, 2.34567); assert.equal(option.series[0].label.formatter({ dataIndex: 0 }), '+2.35 pp'); assert.equal(option.series[0].label.formatter({ dataIndex: 1 }), '-1.23 pp'); assert.match(option.tooltip.formatter([{ dataIndex: 0, seriesIndex: 0 }]), /2.34567 pp/); assert.match(renderVisualTableHtml(model), /2\.34567 pp/); const ring = parseAnalysisVisuals([donut({ series: [{ key: 'source_defect_weight', label: '类别重量', values: [2.34567, 3, 4] }] })]).visuals[0]; const ringOption = buildAnalysisVisualOption(ring); assert.match(ringOption.series[0].label.formatter({ dataIndex: 0 }), /2\.35 kg/); assert.match(ringOption.tooltip.formatter([{ dataIndex: 0, seriesIndex: 0 }]), /2.34567 kg/); assert.match(renderVisualTableHtml(ring), /2\.34567 kg/); }); test('report export fully wraps long donut, Pareto, and trend category names', () => { const longName = '很长的业务规格名称'.repeat(16); const ring = parseAnalysisVisuals([donut({ categories: [ { key: 'black_responsibility_scrap', label: longName }, { key: 'black_material_scrap', label: '料废' }, ], series: [{ key: 'source_defect_weight', label: '类别重量', values: [8, 2] }], coverage: { totalRows: 2, returnedRows: 2, truncated: false, shareBasis: 'displayed_categories' }, })]).visuals[0]; const ringExport = buildAnalysisVisualExportOption(ring, 1280, 'report'); assert.ok(ringExport.option.series[0].label.formatter({ dataIndex: 0 }).replaceAll('\n', '').includes(longName)); assert.ok(ringExport.height > 390); const ranked = parseAnalysisVisuals([pareto({ categories: [ { key: 'black_responsibility_scrap', label: longName }, { key: 'black_material_scrap', label: '料废' }, ], series: [{ key: 'source_defect_weight', label: '类别重量', values: [8, 2] }], coverage: { totalRows: 2, returnedRows: 2, truncated: false, shareBasis: 'displayed_categories' }, })]).visuals[0]; const rankedExport = buildAnalysisVisualExportOption(ranked, 1280, 'report'); assert.ok(rankedExport.option.xAxis.data[0].replaceAll('\n', '').includes(longName)); const trend = parseAnalysisVisuals([visual({ type: 'line', categories: [{ key: 'a', label: longName }, { key: 'b', label: '短名称' }], series: [{ key: 'overall', label: '综合', values: [0.82, 0.84] }], })]).visuals[0]; const trendExport = buildAnalysisVisualExportOption(trend, 1280, 'report'); assert.ok(trendExport.option.xAxis.data[0].replaceAll('\n', '').includes(longName)); assert.equal(trendExport.option.xAxis.axisLabel.hideOverlap, false); });