优化:按分析章节整合图表解读与完整报告导出

This commit is contained in:
2026-10-23 21:36:28 +08:00
parent 13695da433
commit ec71609343
21 changed files with 1607 additions and 259 deletions
+103
View File
@@ -0,0 +1,103 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { buildAnalysisNarrative, narrativeParts, isRateComparison, useCompactRateComparison } from '../src/analysisReportModel.ts';
const visual = (overrides = {}) => ({
id: 'chart-1', type: 'column', title: '综合合格率期间比较', subtitle: '2026-08 → 2026-09', unit: 'ratio',
categories: [{ key: 'comparison', label: '2026-08' }, { key: 'current', label: '2026-09' }],
series: [{ key: 'composite_rate', label: '综合合格率', values: [0.9557, 0.9513] }],
evidenceRefs: ['Q1234ABCD'], requiredFields: ['black_good_weight','black_total_weight','bright_good_weight','bright_total_weight'],
scope: { year: 2026, month: 9, releaseId: 'release-a' }, period: { year: 2026, month: 9 }, comparisonPeriod: { year: 2026, month: 8 },
metric: 'composite_rate', coverage: { totalRows: 2, returnedRows: 2, truncated: false }, originTurnId: 'turn-1', ...overrides,
});
test('paragraphs and exact tables are retained with charts next to their semantic chapter', () => {
const source = '综合率下降。[Q1234ABCD]\n\n### 产业部变化\n重点组织发生变化。\n\n| 组织 | 变化 |\n| --- | --- |\n| 电机 | -0.24 |\n\n### 优先核查\n核对投入。';
const model = buildAnalysisNarrative(source, [visual(), visual({ id: 'department', type: 'bar', unit: 'pp', metric: 'rate_drop_pp', title: '产业部合格率变化', categories: [{key:'motor',label:'电机'},{key:'consumer',label:'消费电子'}], series: [{key:'rate_drop_pp',label:'下降百分点',values:[0.24,-0.34]}], evidenceRefs: ['Q5678ABCD'] })], '分析合格率下降原因');
assert.equal(model.sections[0].visuals[0].id, 'chart-1');
const department = model.sections.find(section => section.kind === 'department');
assert.equal(department.visuals[0].id, 'department');
assert.match(department.narrative, /重点组织发生变化/);
assert.match(department.tables[0], /电机 \| -0.24/);
assert.equal(model.sections.at(-1).kind, 'action');
assert.equal(model.sections.flatMap(section => section.visuals).length, 2);
assert.equal(model.evidenceLabels.Q1234ABCD, '依据 1');
});
test('scoped defect crosscheck stays with its own evidence instead of the global defect chapter', () => {
const v = visual({ id:'scoped',type:'bar',unit:'kg',metric:'source_defect_delta_weight',stage:'black',title:'黑片来源具体缺陷报废增减',scope:{year:2026,month:9,releaseId:'release-a',group:'汽车交通-国内',stage:'black'},evidenceRefs:['Q5678ABCD'],requiredFields:['责废缺角重量'],series:[{key:'source_defect_delta_weight',label:'缺陷增量',values:[200,100]}] });
const model = buildAnalysisNarrative('### 黑片来源具体缺陷\n全公司缺角变化。[Q1234ABCD]\n### 已核对的组织与缺陷联系\n汽车交通-国内的缺角增加。[Q5678ABCD]',[v]);
assert.equal(model.sections.find(section=>section.kind==='defect').visuals.length,0);
assert.equal(model.sections.find(section=>section.kind==='crosscheck').visuals[0].id,'scoped');
});
test('opposite stages are never placed together by a shared evidence reference', () => {
const v=visual({id:'bright',type:'bar',unit:'kg',stage:'bright',metric:'source_defect_delta_weight',title:'亮片来源具体缺陷',requiredFields:['加工缺角重量'],series:[{key:'source_defect_delta_weight',label:'重量',values:[2,3]}]});
const model=buildAnalysisNarrative('### 黑片来源具体缺陷\n[Q1234ABCD]\n### 亮片来源具体缺陷\n[Q1234ABCD]',[v]);
assert.equal(model.sections[0].visuals.length,0);assert.equal(model.sections[1].visuals.length,1);
});
test('headings inside fences and unknown narrative content are preserved',()=>{
const source='普通回答。\n\n```text\n### 代码内标题\n| a | b |\n|---|---|\n```\n\n### 特别说明\n内容不得丢失。';
const model=buildAnalysisNarrative(source,[]);
assert.equal(model.sections.length,2);assert.match(model.sections[0].markdown,/### 代码内标题/);assert.match(model.sections[1].markdown,/内容不得丢失/);
assert.equal(narrativeParts(model.sections[0].markdown).tables.length,0);
});
test('single-value answers, text-only and old turns remain complete without invented figures',()=>{
const m=buildAnalysisNarrative('9月综合合格率95.13%。',undefined,'9月合格率是多少');
assert.equal(m.sections.length,1);assert.equal(m.sections[0].markdown,'9月综合合格率95.13%。');assert.equal(m.sections[0].title,'');assert.equal(m.sections[0].visuals.length,0);
});
test('unmatched chart is retained once under a separately named chapter',()=>{
const m=buildAnalysisNarrative('### 下一步\n继续核查。',[visual()]);
assert.equal(m.sections.flatMap(s=>s.visuals).length,1);assert.equal(m.sections.find(s=>s.visuals.length).kind,'overview');
});
test('compact comparison is limited to valid two-period stage-rate snapshots',()=>{
const m=buildAnalysisNarrative('两期比较',[visual()]);assert.equal(isRateComparison(m.sections.flatMap(s=>s.visuals)[0]),true);
const missing=buildAnalysisNarrative('两期比较',[visual({series:[{key:'composite_rate',label:'率',values:[null,0.95]}]})]);assert.equal(isRateComparison(missing.sections.flatMap(s=>s.visuals)[0]),false);
});
test('combined black and bright chapter retains both stage comparisons',()=>{
const stages=['black','bright'].map(stage=>visual({id:stage,sectionKey:'stage',stage,metric:`${stage}_rate`,series:[{key:`${stage}_rate`,label:stage,values:[0.97,0.96]}]}));
const model=buildAnalysisNarrative('### 黑片与亮片阶段变化\n阶段均有变化。[Q1234ABCD]',stages);
assert.equal(model.sections.length,1);
assert.deepEqual(model.sections[0].visuals.map(v=>v.id),['black','bright']);
});
test('explicit bar or column requests keep charts while default rate comparisons stay compact',()=>{
const v=buildAnalysisNarrative('两期比较',[visual()]).sections.flatMap(s=>s.visuals)[0];
assert.equal(useCompactRateComparison(v,'比较合格率'),true);
for(const request of ['用柱状图比较','用横条图比较','用条形图比较','用柱形图比较']) assert.equal(useCompactRateComparison(v,request),false);
});
test('a short answer without headings keeps its requested chart next to the cited prose',()=>{
const v=visual({id:'trend',type:'area',sectionKey:'trend',title:'产品趋势'});
const m=buildAnalysisNarrative('该规格两期正式值如下。[Q1234ABCD]\n\n| 期间 | 值 |\n| --- | --- |\n| 8月 | 95.57% |\n| 9月 | 95.13% |',[v]);
assert.equal(m.sections.length,1);assert.equal(m.sections[0].visuals[0].id,'trend');assert.equal(m.sections[0].tables.length,1);
});
test('long plotting instructions become a concise report title with the full question retained by the caller',()=>{
const question='请用纵向柱状图展示消费电子业务分组本月与上月的正式综合合格率,只需要两个期间和正式数值,简短回答,不查询其他范围';
const model=buildAnalysisNarrative('两期比较。[Q1234ABCD]',[visual()],question);
assert.equal(model.title,'2026-08 → 2026-09 质量变化分析');assert.ok(model.title.length<40);
});
test('table-specific citation and coverage remain with the full table details',()=>{
const part=narrativeParts('本节结论。[Q1234ABCD]\n\n| 对象 | 重量 |\n| --- | --- |\n| A | 12 |\n\n[Q1234ABCD] 共20项,本节展示1项。\n\n后续说明。');
assert.match(part.narrative,/本节结论/);assert.match(part.narrative,/后续说明/);
assert.doesNotMatch(part.narrative,/共20项/);assert.match(part.tables[0],/共20项,本节展示1项/);
});
test('scoped comparisons cannot enter a global overview or stage chapter',()=>{
const product='16.33X15.5X3.75+T';
const local=visual({id:'product-rate',scope:{year:2026,month:9,releaseId:'release-a',product},evidenceRefs:['Q9999ABCD']});
const stage=visual({...local,id:'product-black',sectionKey:'stage',stage:'black',metric:'black_rate',series:[{key:'black_rate',label:'黑片',values:[0.98,0.97]}]});
const m=buildAnalysisNarrative('总体变化。[Q1234ABCD]\n\n### 总体与阶段\n全局阶段。',[local,visual(),stage]);
assert.equal(m.sections[0].visuals.length,1);assert.equal(m.sections[0].visuals[0].id,'chart-1');
assert.equal(m.sections[1].visuals.length,0);
assert.ok(m.sections.filter(s=>s.visuals.some(v=>v.id.startsWith('product-'))).every(s=>s.title.includes(product)));
const matched=buildAnalysisNarrative(`总体变化。[Q1234ABCD]\n\n### 重点产品\n${product} 的变化。`,[visual(),local,stage]);
assert.equal(matched.sections.find(s=>s.kind==='product').visuals.length,2);
});
+184 -4
View File
@@ -61,6 +61,28 @@ function pareto(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);
@@ -124,6 +146,7 @@ test('business labels remain plain text in tooltip output and data options', ()
assert.equal(option.tooltip.renderMode, 'richText');
const tooltip = option.tooltip.formatter([{ dataIndex: 0, seriesIndex: 0 }]);
assert.equal(tooltip.includes('<script>alert(1)</script>'), true);
assert.equal(tooltip.includes('{style|name}'), true);
assert.equal(tooltip.includes('<br'), false);
assert.equal(tooltip.includes('<strong>'), false);
});
@@ -226,10 +249,10 @@ test('duplicate ids, malformed values, and over-size payloads do not break neigh
assert.match(oversized.issues[0], /大小限制/);
});
test('only three visuals are admitted to a chat render', () => {
const result = parseAnalysisVisuals([visual(), visual({ id: 'visual-2' }), visual({ id: 'visual-3' }), visual({ id: 'visual-4' })]);
assert.equal(result.visuals.length, 3);
assert.ok(result.issues.some(issue => issue.includes('前 3 张')));
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', () => {
@@ -511,3 +534,160 @@ test('negative area data is shown as a table rather than filled as a valid trend
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);
});