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); }); const productTable = ({ product = '16.33X15.5X3.75+T', ref = 'Q9594C354', stage = '', delta = '+758.76', change = '下降1.95个百分点', weight = '1,286.11', rate = '97.11%→95.16%', input = '黑片投入17,361.74→26,276.07 kg;亮片投入19,009.25→26,288.80 kg', order = '报废增量' } = {}) => { const name = stage ? `${stage}合格率` : '综合率'; return `### ${stage}${order === '合格率降幅' ? '产品率变化线索' : '重点产品'}(按${order},本次返回前5)\n\n| 规格 | 本期报废 / 增量(kg) | ${name}:比较期→本期 / 变化 | 阶段投入:比较期→本期(kg) |\n| --- | --- | --- | --- |\n| ${product.replaceAll('|', '\\|')} | ${weight} / ${delta} | ${rate};${change} | ${input} |\n\n[${ref}] 查询共有3566个对象,保留分阶段投入。`; }; const productFact = ({ product = '16.33X15.5X3.75+T', ref = 'Q9594C354', delta = '+758.76', change = '下降1.95个百分点', stage = '', input = '黑片投入17,361.74→26,276.07 kg;亮片投入19,009.25→26,288.80 kg' } = {}) => `- ${product}:${stage}报废527.35→1,286.11 kg,增量${delta} kg;${stage ? `${stage}合格率` : '综合率'}97.11%→95.16%,${change};${input}。[${ref}]`; test('selected product facts become a cited comparison immediately after the overview without recalculation', () => { const first = { product: 'A', ref: 'Q11111111', delta: '+758.76' }; const second = { product: 'B', ref: 'Q22222222', delta: '+757.56', change: '下降0.68个百分点' }; const source = `整体下降。[Q1234ABCD]\n\n${productTable(first)}\n\n${productTable(second)}\n\n### 重点关注\n\n${productFact(second)}\n${productFact(first)}\n\n范围:当前授权范围,默认不含未分类。`; const model = buildAnalysisNarrative(source, [visual()]); assert.equal(model.sections[0].kind, 'overview'); const focused = model.sections[1]; assert.equal(focused.id, 'focus-product-summary'); assert.deepEqual(focused.focusProducts.map(row => [row.product, row.scrapDelta, row.rateChange, row.basis]), [ ['B', '+757.56', '下降0.68个百分点', '按报废增量排序'], ['A', '+758.76', '下降1.95个百分点', '按报废增量排序'], ]); assert.equal(focused.focusProducts[0].detail, productFact(second).slice(2)); assert.match(focused.focusProducts[0].detail, /黑片投入17,361.74→26,276.07 kg/); assert.equal(model.sections.filter(section => section.narrative.includes('B:')).length, 0); assert.ok(model.sections.some(section => section.narrative.includes('默认不含未分类'))); assert.equal(model.sections.flatMap(section => section.tables).length, 2); assert.equal(model.sections.flatMap(section => section.visuals).length, 1); assert.equal(model.evidenceLabels.Q22222222, '依据 3'); }); test('unrecognized old product reports and uncited focus prose remain intact', () => { for (const focus of ['- A:这是旧格式的分析。', '- 另一规格:增量+758.76 kg,下降1.95个百分点。[Q9594C354]', '- 16.33X15.5X3.75+T:增量+758.76 kg,下降1.95个百分点。[Q00000000]']) { const model = buildAnalysisNarrative(`${productTable()}\n\n### 重点关注\n\n${focus}`, []); assert.ok(!model.sections.some(section => section.focusProducts)); assert.equal(model.sections.at(-1).narrative, focus); } }); test('missing values are retained as unavailable and never converted to zero', () => { const data = { delta: '—', weight: '—', rate: '—→—', change: '不可比', input: '黑片投入—→— kg;亮片投入—→— kg' }; const model = buildAnalysisNarrative(`总体比较。\n\n${productTable(data)}\n\n### 重点关注\n\n${productFact(data)}`, []); const row = model.sections.find(section => section.focusProducts).focusProducts[0]; assert.equal(row.scrapDelta, '—'); assert.equal(row.rateChange, '不可比'); assert.match(row.detail, /黑片投入—→— kg/); }); test('stage and ordering context follow the exact cited row, including rate-only leads', () => { const black = { product: 'A', ref: 'Q11111111', stage: '黑片', delta: '+20.00', change: '下降5.00个百分点', order: '合格率降幅' }; const bright = { product: 'A', ref: 'Q22222222', stage: '亮片', delta: '+40.00', change: '下降2.00个百分点', order: '当前报废重量' }; const model = buildAnalysisNarrative(`概况。\n\n${productTable(black)}\n\n${productTable(bright)}\n\n### 重点关注\n\n${productFact(black)}\n${productFact(bright)}`, []); const rows = model.sections.find(section => section.focusProducts).focusProducts; assert.deepEqual(rows.map(row => row.rateLabel), ['黑片合格率', '亮片合格率']); assert.deepEqual(rows.map(row => row.basis), ['黑片 · 按合格率降幅排序,仅作率变化线索', '亮片 · 按当前报废重量排序']); assert.deepEqual(rows.map(row => row.evidenceRefs[0]), ['Q11111111', 'Q22222222']); }); test('ambiguous references, changed numbers, and unknown table fields fall back to full original prose', () => { const fact = productFact(); const cases = [ `${productTable()}\n\n${productTable()}`, productTable({ delta: '+999.99' }), productTable().replace('阶段投入:比较期→本期(kg)', '其他数据'), ]; for (const tables of cases) { const model = buildAnalysisNarrative(`${tables}\n\n### 重点关注\n\n${fact}`, []); assert.ok(!model.sections.some(section => section.focusProducts)); assert.equal(model.sections.at(-1).narrative, fact); } }); test('mixed focus items and fenced examples are retained while recognized products move', () => { const other = '- 核对责废分类是否完整。[Q1234ABCD]'; const code = `\`\`\`text\n${productFact()}\n\`\`\``; const model = buildAnalysisNarrative(`${productTable()}\n\n### 重点关注\n\n${productFact()}\n${other}\n\n${code}`, []); assert.equal(model.sections.find(section => section.focusProducts).focusProducts.length, 1); assert.equal(model.sections.at(-1).kind, 'action'); assert.ok(model.sections.at(-1).narrative.includes(other)); assert.ok(model.sections.at(-1).narrative.includes(code)); }); test('long specifications and escaped Markdown delimiters remain literal product data', () => { const product = 'R127.985X57.516X15.786X75.485X32.232°X5.5|'; const model = buildAnalysisNarrative(`${productTable({ product })}\n\n### 重点关注\n\n${productFact({ product })}`, []); const row = model.sections.find(section => section.focusProducts).focusProducts[0]; assert.equal(row.product, product); assert.equal(row.detail, productFact({ product }).slice(2)); }); test('more than five selected products remain available in original order for expanded details', () => { const data = Array.from({ length: 6 }, (_, index) => ({ product: `规格${index + 1}`, ref: `Q1111111${index}` })); const model = buildAnalysisNarrative(`总体变化。\n\n${data.map(item => productTable(item)).join('\n\n')}\n\n### 重点关注\n\n${data.map(item => productFact(item)).join('\n')}`, []); const rows = model.sections.find(section => section.focusProducts).focusProducts; assert.equal(rows.length, 6); assert.deepEqual(rows.map(row => row.product), data.map(item => item.product)); assert.equal(model.evidence.length, 6); });