import test from 'node:test'; import assert from 'node:assert/strict'; import { buildAnalysisVisualOption, buildAnalysisVisualExportOption, combineStageDefectVisuals, formatVisualValue, distinctAnalysisVisuals, parseAnalysisVisuals, renderVisualTableHtml, visualCategoryLabel, visualDonutShares, visualParetoPoints, columnFilterSummary, visualScopeSummary, visualUnitLabel, } from '../src/analysisVisualsModel.ts'; import { buildAnalysisNarrative } from '../src/analysisReportModel.ts'; import { buildConclusionDocument, checkedConclusionComparison } from '../src/analysisConclusionModel.ts'; import { analysisChartReferences } from '../src/analysisChartReferences.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, }); } function scrapRate(stage = 'black', values = [0.82, 0.84], overrides = {}) { const metric = `${stage}_scrap_rate`; const weight = `${stage}_scrap_weight`; const total = `${stage}_total_weight`; return visual({ title: `${stage === 'black' ? '黑片' : '亮片'}正式报废率`, subtitle: '正式报废重量÷投入重量', unit: 'ratio', stage, metric, requiredFields: [weight, total], scope: { department: '工业电机', stage }, series: [{ key: metric, label: '报废率', values }], ...overrides, }); } test('Top product Pareto uses all-product total and does not force the last share to 100%', () => { const input = pareto({metric:'bright_total_weight',stage:'bright',dimension:'product', requiredFields:['bright_total_weight'],comparisonPeriod:undefined, categories:[{key:'p1',label:'A'},{key:'p2',label:'B'}], series:[{key:'bright_total_weight',label:'亮片投入重量',values:[80,60]}], coverage:{totalRows:3,returnedRows:2,truncated:true,shareBasis:'all_scope_weight',denominator:150}}); const model = parseAnalysisVisuals([input]).visuals[0]; assert.equal(model.chartable,true); const points = visualParetoPoints(model); assert.equal(points[0].share,80/150); assert.equal(points[1].cumulativeShare,140/150); assert.ok(points[1].cumulativeShare<1); const option = buildAnalysisVisualOption(model); assert.equal(option.series[1].name,'累计占全部重量'); for (const denominator of [0,-1,100,NaN]) { const invalid=parseAnalysisVisuals([{...input,coverage:{...input.coverage,denominator}}]); assert.ok(!invalid.visuals.length || !invalid.visuals[0].chartable); } }); test('weight ranking export retains the all-scope denominator label and readable full product names', () => { const names=Array.from({length:10},(_,i)=>`52HR-L0.385XR26.46XR26.46X2.888+R+Z-${i}`); const input=pareto({metric:'bright_total_weight',stage:'bright',dimension:'product',requiredFields:['bright_total_weight'],comparisonPeriod:undefined, categories:names.map((label,i)=>({key:'p'+i,label})),series:[{key:'bright_total_weight',label:'亮片投入重量',values:[100,90,80,70,60,50,40,30,20,10]}], coverage:{totalRows:20,returnedRows:10,truncated:true,shareBasis:'all_scope_weight',denominator:1000}}); const model=parseAnalysisVisuals([input]).visuals[0]; const live=buildAnalysisVisualOption(model); assert.equal(live.yAxis[1].name,'累计占全部重量'); const report=buildAnalysisVisualExportOption(model,900,'report').option; assert.equal(report.legend.data[1],'累计占全部重量'); assert.equal(report.yAxis[1].name,'累计占全部重量'); assert.deepEqual(report.xAxis.data.map(name=>name.replaceAll('\n','')),names); assert.equal(report.xAxis.axisLabel.rotate,0); assert.ok(report.grid.height>=240); assert.equal(report.series[1].label.formatter({dataIndex:9,data:55}),'55.00%'); assert.deepEqual(report.series[0].data,input.series[0].values); }); test('historical stage decomposition labels omit the requested wording', () => { const model=parseAnalysisVisuals([waterfall({title:'综合率变化的数学影响拆解', categories:[{key:'black',label:'黑片数学影响'},{key:'bright',label:'亮片数学影响'},{key:'total',label:'合计'}]})]).visuals[0]; assert.equal(model.title,'综合率变化的影响拆解'); assert.equal(model.categories[0].label,'黑片影响'); }); 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 trends adapt to their data and convert raw ratios only for plotting', () => { const parsed = parseAnalysisVisuals([visual()]); const option = buildAnalysisVisualOption(parsed.visuals[0]); assert.ok(option.yAxis.min < 82 && option.yAxis.min > 80); assert.ok(option.yAxis.max > 84 && option.yAxis.max < 86); assert.deepEqual(option.series[0].data, [82, 84]); assert.equal(formatVisualValue(0.8425, 'ratio'), '84.25%'); }); test('stage scrap rates preserve values above 100 percent and expand every ratio value axis', () => { for (const stage of ['black', 'bright']) { const parsed = parseAnalysisVisuals([scrapRate(stage, [1.23, 0.94])]); assert.equal(parsed.visuals[0].chartable, true); assert.deepEqual(parsed.visuals[0].series[0].values, [1.23, 0.94]); assert.equal(buildAnalysisVisualOption(parsed.visuals[0]).series[0].data[0], 123); assert.ok(buildAnalysisVisualOption(parsed.visuals[0]).yAxis.max > 123); assert.ok(buildAnalysisVisualExportOption(parsed.visuals[0], 1280, 'standalone').option.yAxis.max > 123); assert.ok(buildAnalysisVisualExportOption(parsed.visuals[0], 1280, 'report').option.yAxis.max > 123); assert.equal(formatVisualValue(1.23, 'ratio'), '123.00%'); } const horizontal = parseAnalysisVisuals([scrapRate('black', [1.23, 0.94], { type: 'bar' })]).visuals[0]; assert.ok(buildAnalysisVisualOption(horizontal).xAxis.max > 123); assert.ok(buildAnalysisVisualExportOption(horizontal, 1280, 'report').option.xAxis.max > 123); const below100 = parseAnalysisVisuals([scrapRate('black', [0.91, 0.84])]).visuals[0]; assert.ok(buildAnalysisVisualOption(below100).yAxis.max > 91); assert.equal(buildAnalysisVisualExportOption(below100, 1280, 'report').option.yAxis.max, buildAnalysisVisualOption(below100).yAxis.max); }); test('formal black and composite rates above 100 percent remain visible in live and exported charts', () => { const products = [ { name: '42.1X42.1X35异形+Z', composite: 1.2430959504537282, black: 1.277660594439118 }, { name: 'R43X38.1X9.5X60+Q', composite: 1.0601991884176734, black: 1.1147540983606556 }, ]; const composite = visual({ type: 'column', title: '综合合格率', metric: 'composite_rate', dimension: 'product', requiredFields: ['black_good_weight', 'black_total_weight', 'bright_good_weight', 'bright_total_weight'], categories: products.map((item, index) => ({ key: `product-${index}`, label: item.name })), series: [{ key: 'composite_rate', label: '综合合格率', values: products.map(item => item.composite) }], scope: { year: 2026, month: 9, releaseId: 'release-a' }, period: { year: 2026, month: 9 }, comparisonPeriod: undefined, }); const parsed = parseAnalysisVisuals([composite]).visuals[0]; assert.equal(parsed.chartable, true); assert.deepEqual(parsed.series[0].values, products.map(item => item.composite)); const option = buildAnalysisVisualOption(parsed); assert.deepEqual(option.series[0].data.map(item => typeof item === 'number' ? item : item.value), products.map(item => item.composite * 100).map(value => Number(value.toFixed(7)))); assert.ok(option.yAxis.max > 124.3); assert.ok(buildAnalysisVisualExportOption(parsed, 1280, 'standalone').option.yAxis.max > 124.3); assert.ok(buildAnalysisVisualExportOption(parsed, 1280, 'report').option.yAxis.max > 124.3); assert.match(formatVisualValue(products[0].composite, 'ratio'), /124\.3/); const black = parseAnalysisVisuals([visual({ type: 'column', title: '黑片合格率', metric: 'black_rate', stage: 'black', requiredFields: ['black_good_weight', 'black_total_weight'], categories: products.map((item, index) => ({ key: `product-${index}`, label: item.name })), series: [{ key: 'black_rate', label: '黑片合格率', values: products.map(item => item.black) }], scope: { year: 2026, month: 9, releaseId: 'release-a', stage: 'black' }, period: { year: 2026, month: 9 }, comparisonPeriod: undefined, })]).visuals[0]; assert.equal(black.chartable, true); assert.ok(buildAnalysisVisualOption(black).yAxis.max > products[0].black * 100); const compositeWithoutHeadquarters = parseAnalysisVisuals([visual({ title: '综合合格率(不含总部报废)', metric: 'composite_rate_without_headquarters_scrap', requiredFields: ['black_good_weight', 'black_total_weight', 'bright_good_weight', 'bright_total_weight'], series: [{ key: 'composite_rate_without_headquarters_scrap', label: '综合合格率', values: [1.04, 1.02] }], })]).visuals[0]; assert.equal(compositeWithoutHeadquarters.chartable, true); assert.ok(buildAnalysisVisualOption(compositeWithoutHeadquarters).yAxis.max > 104); const horizontal = parseAnalysisVisuals([{ ...composite, type: 'bar' }]).visuals[0]; assert.equal(horizontal.chartable, true); assert.ok(buildAnalysisVisualOption(horizontal).xAxis.max > 124.3); assert.ok(buildAnalysisVisualExportOption(horizontal, 1280, 'report').option.xAxis.max > 124.3); }); test('only official adjusted-denominator rates accept above-one ratios', () => { for (const input of [ visual({ series: [{ key: 'r', label: '率', values: [1.02, null] }] }), visual({ metric: 'bright_rate', stage: 'bright', requiredFields: ['bright_good_weight', 'bright_total_weight'], series: [{ key: 'r', label: '亮片合格率', values: [1.02, null] }] }), scrapRate('black', [1.02, 0.8], { requiredFields: ['bright_scrap_weight', 'bright_total_weight'] }), scrapRate('black', [1.02, 0.8], { unit: 'kg' }), ]) { const parsed = parseAnalysisVisuals([input]).visuals[0]; assert.equal(parsed.chartable, false); } const negative = parseAnalysisVisuals([scrapRate('bright', [-0.01, 1.02])]).visuals[0]; assert.equal(negative.chartable, false); assert.deepEqual(negative.invalidValueCells, ['0:0']); for (const value of [-0.01, Number.NaN, Number.POSITIVE_INFINITY]) { const official = parseAnalysisVisuals([visual({ metric: 'composite_rate', series: [{ key: 'r', label: '综合合格率', values: [value, 0.95] }] })]).visuals[0]; assert.equal(official.chartable, false); assert.deepEqual(official.invalidValueCells, ['0:0']); } }); 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.50 pp'); }); test('legacy rate-drop charts normalize once and chat tables and exports use current minus prior', () => { const legacy = visual({ id: 'legacy-rate-drop', type: 'bar', title: '业务分组合格率降幅线索', subtitle: '8月 → 9月', unit: 'pp', metric: 'rate_drop_pp', dimension: 'group', sectionKey: 'group', categories: [{ key: 'g1', label: '分组一' }, { key: 'g2', label: '分组二' }], series: [{ key: 'rate_drop_pp', label: '合格率变化(pp)', values: [2.5, -4] }], evidenceRefs: ['evidence-1'], requiredFields: ['black_good_weight', 'black_total_weight'], scope: { department: '工业电机' }, period: { label: '2026-09' }, comparisonPeriod: { label: '2026-08' }, coverage: { totalRows: 2, returnedRows: 2, truncated: false }, note: '条形末端显示具体变化:正值为下降,负值为改善,单位是百分点。本图只按率降幅排序,未纳入投入规模。', }); const model = parseAnalysisVisuals([legacy], 1).visuals[0]; assert.deepEqual(model.series[0].values, [-2.5, 4]); assert.match(model.note, /本期减比较期/); assert.match(model.note, /仍按率降幅排序|只按率降幅排序/); assert.deepEqual(parseAnalysisVisuals([model], 1).visuals[0].series[0].values, [-2.5, 4]); const legacyNotes = [ '正值表示合格率下降,负值表示改善;百分点取自正式分组率差。', '正值表示综合合格率下降,负值表示改善;按正式综合率比较,不作为生产根因。', undefined, ]; for (const [index, note] of legacyNotes.entries()) { const snapshot = { ...legacy, id: `legacy-rate-drop-${index}`, note }; const normalized = parseAnalysisVisuals([snapshot], 1).visuals[0]; assert.deepEqual(normalized.series[0].values, [-2.5, 4]); assert.match(normalized.note, /本期减比较期/); assert.deepEqual(parseAnalysisVisuals([normalized], 1).visuals[0].series[0].values, [-2.5, 4]); } const chart = buildAnalysisVisualOption(model); assert.deepEqual(chart.series[0].data, [-2.5, 4]); const table = renderVisualTableHtml(legacy); assert.match(table, /-2\.50 pp/); assert.match(table, /\+4\.00 pp/); const exported = buildAnalysisVisualExportOption(model, 1280, 'report'); assert.deepEqual(exported.option.series[0].data, [-2.5, 4]); const modern = { ...legacy, id: 'current-rate-drop', note: '正值表示本期合格率上升,负值表示下降;变化值为本期减比较期。', series: [{ ...legacy.series[0], values: [-2.5, 4] }] }; assert.deepEqual(parseAnalysisVisuals([modern], 1).visuals[0].series[0].values, [-2.5, 4]); const reading = { lead: '分组变化', evidence: [], notices: [], evidenceRefs: ['evidence-1'], hasAppendix: false, fullAnswer: '### 业务分组变化\n\n合格率有变化。[evidence-1]', visualCount: 1 }; const conclusion = buildConclusionDocument(reading, [model]); assert.deepEqual(conclusion.sections.find(section => section.title === '业务分组变化').visuals[0].series[0].values, [-2.5, 4]); }); test('checked conclusion comparisons give declines negative pp and increases positive pp', () => { const down = checkedConclusionComparison('9月综合合格率95.13%,较8月的95.57%下降0.44个百分点。'); const up = checkedConclusionComparison('9月综合合格率95.57%,较8月的95.13%上升0.44个百分点。'); assert.equal(down.change, '-0.44'); assert.equal(up.change, '+0.44'); assert.equal(down.direction, '下降'); assert.equal(up.direction, '上升'); assert.equal(checkedConclusionComparison('9月综合合格率95.13%,较8月的95.57%上升0.44个百分点。'), null); }); 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\.00%/); 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\.00 kg/); assert.match(option.graphic[1].style.text, /不代表正式总报废占比/); assert.match(option.series[0].label.formatter({ dataIndex: 1 }), /20\.00%/); const table = renderVisualTableHtml(model); assert.match(table, /占比以本图所列类别重量合计为分母/); assert.match(table, /20\.00%/); 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\.00 kg/); assert.match(exported.option.graphic.elements[0].style.text, /10\.00 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\.00 kg/); assert.match(tooltip, /本图类别占比:20\.00%/); assert.match(tooltip, /累计占本图已列类别合计:100\.00%/); 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.doesNotMatch(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 labels tooltips and tables show two decimals while source data retains 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\.35 pp/); assert.match(renderVisualTableHtml(model), /2\.35 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\.35 kg/); assert.match(renderVisualTableHtml(ring), /2\.35 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); }); test('source column filters preserve stage and literal values in chart scope', () => { const rule={field:'src_any',stages:['bright'],operator:'in',values:['000123']}; const value=visual({scope:{columnFilters:[rule],columnLabels:{src_any:'任意业务列'}}}); const parsed=parseAnalysisVisuals([value]); assert.equal(parsed.visuals.length,1); assert.deepEqual(parsed.visuals[0].scope.columnFilters,[rule]); assert.deepEqual(columnFilterSummary(parsed.visuals[0].scope.columnFilters,parsed.visuals[0].scope.columnLabels),['亮片 任意业务列为000123']); assert.equal(parseAnalysisVisuals([visual({scope:{columnFilters:[{...rule,stages:['other']}]}})]).visuals.length,0); }); test('canonical exclusions and source-column not-in filters survive chart, report, and HTML export context', () => { const scope = { exclusions: { product: ['MIMO-V14', ' 保留空格 '], group: ['海外组'] }, columnFilters: [{ field: 'customerCode', stages: ['black', 'bright'], operator: 'not_in', values: ['000123', 'C-09'] }], columnLabels: { customerCode: '客户代码' }, extraFilters: { factory: ['一厂'] }, }; const parsed = parseAnalysisVisuals([visual({ scope })]); assert.equal(parsed.visuals.length, 1); const chart = parsed.visuals[0]; assert.deepEqual(chart.scope.exclusions, scope.exclusions); assert.deepEqual(chart.scope.columnFilters, scope.columnFilters); const summary = visualScopeSummary(chart.scope); assert.match(summary, /排除业务分组:海外组/); assert.match(summary, /排除产品:MIMO-V14、 保留空格 /); assert.match(summary, /黑片、亮片 客户代码排除000123、C-09/); assert.match(summary, /额外筛选 1 项/); assert.match(renderVisualTableHtml(chart), /排除产品:MIMO-V14、 保留空格 /); const report = buildAnalysisNarrative('', [chart]); assert.equal(report.scope, summary); assert.match(report.evidence[0].context, /黑片、亮片 客户代码排除000123、C-09/); }); test('visual parsing rejects malformed exclusions and malformed source-column filters', () => { for (const exclusions of [ { customerCode: ['000123'] }, { product: [] }, { group: [' '] }, { product: ['A', 4] }, { product: Array.from({ length: 51 }, (_, index) => `P${index}`) }, ]) { assert.equal(parseAnalysisVisuals([visual({ scope: { exclusions } })]).visuals.length, 0); } assert.equal(parseAnalysisVisuals([visual({ scope: { columnFilters: [{ field: 'customerCode', stages: ['black'], operator: 'not_in', values: [] }] } })]).visuals.length, 0); }); test('scrap-rate data and export unit labels preserve the requested indicator', () => { const visual = { unit: 'ratio', metric: 'black_scrap_rate' }; assert.equal(visualUnitLabel(visual), '报废率(%)'); assert.equal(visualUnitLabel({ ...visual, metric: 'bright_scrap_rate' }), '报废率(%)'); assert.equal(visualUnitLabel({ ...visual, metric: 'composite_rate' }), '合格率(%)'); }); test('low scrap-rate trends adapt within their range without changing values', () => { const item = parseAnalysisVisuals([scrapRate('black', [.03657, .02995])]).visuals[0]; const option = buildAnalysisVisualOption(item); assert.ok(option.yAxis.min >= 0 && option.yAxis.min < 2.995); assert.ok(option.yAxis.max > 3.657 && option.yAxis.max < 20); assert.deepEqual(item.series[0].values, [.03657, .02995]); assert.equal(buildAnalysisVisualExportOption(item, 1280, 'report').option.yAxis.max, option.yAxis.max); const zero = parseAnalysisVisuals([scrapRate('bright', [0, 0])]).visuals[0]; assert.ok(buildAnalysisVisualOption(zero).yAxis.max > 0); const goodRate = parseAnalysisVisuals([visual({ metric: 'black_rate', stage: 'black', requiredFields: ['black_good_weight', 'black_total_weight'], series: [{ key: 'black_rate', label: '黑片合格率', values: [.03657, .02995] }] })]).visuals[0]; assert.ok(buildAnalysisVisualOption(goodRate).yAxis.max > 3.657 && buildAnalysisVisualOption(goodRate).yAxis.max < 5); }); test('chart references bind only authorized current-turn visuals and never guess among multiple trends', () => { const item = visual({ sectionKey: 'trend' }); assert.deepEqual(analysisChartReferences([item], 'turn-1'), { 'chart:visual-1': 'visual-1', 'chart:quality-trend-turn-1': 'visual-1' }); assert.deepEqual(analysisChartReferences([item], 'other-turn'), {}); const pair = analysisChartReferences([item, { ...item, id: 'second', series: [{ key: 'other', label: '另一指标', values: [.99, .98] }] }], 'turn-1'); assert.equal(pair['chart:quality-trend-turn-1'], undefined); assert.equal(pair['chart:second'], 'second'); const duplicate = { ...item, id: 'repeated', evidenceRefs: ['another-proof'] }; const parsed = parseAnalysisVisuals([item, duplicate]).visuals; assert.equal(distinctAnalysisVisuals(parsed).length, 1); assert.equal(analysisChartReferences([item, duplicate], 'turn-1')['chart:repeated'], 'visual-1'); assert.equal(distinctAnalysisVisuals(parseAnalysisVisuals([item, { ...duplicate, scope: { department: '不同产业部' } }]).visuals).length, 2); }); test('adaptive trends cover every series, preserve missing values, and keep non-trend bars zero based', () => { for (const values of [[.9517, .9670], [.98, .98], [0, 0], [1, 1], [1.24, 1.27], [null, .97]]) { const item = parseAnalysisVisuals([visual({ metric: 'composite_rate', series: [{ key: 'rate', label: '率', values }] })]).visuals[0]; const before = JSON.stringify(item.series); const live = buildAnalysisVisualOption(item).yAxis; for (const context of ['standalone', 'report', 'agent-document']) { const exported = buildAnalysisVisualExportOption(item, 1280, context).option.yAxis; assert.equal(exported.min, live.min); assert.equal(exported.max, live.max); } assert.ok(live.max > live.min); for (const value of values.filter(value => value !== null)) assert.ok(live.min <= value * 100 && live.max >= value * 100); assert.equal(JSON.stringify(item.series), before); } const item = parseAnalysisVisuals([visual({ series: [{ key: 'a', label: '甲', values: [.95, null] }, { key: 'b', label: '乙', values: [.99, .98] }] })]).visuals[0]; const option = buildAnalysisVisualOption(item); assert.ok(option.yAxis.min <= 95 && option.yAxis.max >= 99); assert.equal(option.yAxis.axisLabel.formatter(96.5), '96.50%'); const bar = parseAnalysisVisuals([visual({ type: 'bar' })]).visuals[0]; assert.equal(buildAnalysisVisualOption(bar).xAxis.min, 0); assert.equal(formatVisualValue(.9639601707533932, 'ratio'), '96.40%'); assert.equal(formatVisualValue(3, 'kg'), '3.00 kg'); }); test('contains keywords survive analysis scope and display as substring filters',()=>{ const rule={field:'src_any',stages:['bright'],operator:'contains',values:['日立','%_']}; const parsed=parseAnalysisVisuals([visual({scope:{columnFilters:[rule],columnLabels:{src_any:'客户'}}})]); assert.equal(parsed.visuals.length,1); assert.deepEqual(parsed.visuals[0].scope.columnFilters,[rule]); assert.match(columnFilterSummary([rule],{src_any:'客户'})[0],/包含.*日立/); assert.equal(parseAnalysisVisuals([visual({scope:{columnFilters:[{...rule,values:[]}]}})]).visuals.length,0); });