import test from 'node:test'; import assert from 'node:assert/strict'; import fs from 'node:fs'; import ts from 'typescript'; import React from 'react'; import { queryScrapWeight } from '../src/queryMetricValues.ts'; import { defectWeightRate } from '../src/trendMetrics.ts'; import { createMetricWorkbook, workbookColumns } from '../src/metricWorkbook.ts'; const source = fs.readFileSync(new URL('../src/QueryPage.tsx', import.meta.url), 'utf8'); const slice = (start, end) => source.slice(source.indexOf(start), source.indexOf(end, source.indexOf(start))); const helpers = slice('function numberText(', 'const SYSTEM_SOURCE_VERSION_KEYS') + slice('function hasStageRows(', 'function fullYearTrend(') + slice('function objectLabel(', 'interface ChartTooltipParam') + slice('const totalWeightTitle =', 'export function MetricTable('); const table = slice('export function MetricTable(', 'function MetricTablePagination(').replace('export function', 'function'); function fixture(props) { let exported, detail = 0, basis = 0; const ref = {}; const render = new Function('React', 'useImperativeHandle', 'defectWeightRate', 'queryScrapWeight', 'downloadMetricWorkbook', ts.transpileModule(` const MONTHS=Array.from({length:12},(_,i)=>String(i+1).padStart(2,'0')+'月'); const SUMMARY_PAGE_SIZE=15; const useCompactTable=()=>false, useState=v=>[v,()=>{}], useEffect=()=>{}; const Button='Button', Table='Table', MetricTablePagination='Pagination', Tooltip='Tooltip', InfoCircleOutlined='Info'; ${helpers}\n${table}\nreturn MetricTable; `, {compilerOptions:{jsx:ts.JsxEmit.React,target:ts.ScriptTarget.ES2022}}).outputText)(React, (target, create) => Object.assign(target, create()), defectWeightRate, queryScrapWeight, async (filename, columns, rows, value) => { exported = { filename, columns, rows, workbook: await createMetricWorkbook(columns, rows, value) }; }); const tree = render({ref,exportFilename:'验收',period:'month',month:9,quarter:3,rateBasis:'original',fullFields:false,onDetail(){detail++;},onBasis(){basis++;},onDrilldown(){},...props}); return {tree, ref, get exported(){return exported;}, get detail(){return detail;}, get basis(){return basis;}}; } function find(node, predicate) { if (!node || typeof node !== 'object') return; if (predicate(node)) return node; for (const child of React.Children.toArray(node.props?.children)) { const hit=find(child,predicate);if(hit)return hit; } } const stage = {qualifiedWeight:1234.567,scrapWeight:0,totalWeight:1250,headquartersScrapWeight:3,rate:0.987654,rateWithoutHeadquartersScrap:0.99,defects:[{name:'裂纹',weight:12.345,rate:0.01}]}; const row = {key:'p',label:'=1+2',product:'=1+2',department:'产业部',group:'业务分组',projectGroup:'项目组',compositeRate:0.975,compositeRateWithoutHeadquartersScrap:0.98,black:stage,bright:stage,coverage:{blackRows:1,brightRows:1}}; for (const view of ['overall','department','group','product','projectGroup']) { for (const fullFields of [false,true]) test(`${view}: ${fullFields?'full':'key'} export uses all rows and exactly the visible data columns`, async () => { const rows=Array.from({length:18},(_,i)=>({...row,key:String(i)})); const ui=fixture({rows,view,fullFields}); const table=find(ui.tree,n=>n.type==='Table'); assert.equal(table.props.dataSource.length,15); await ui.ref.exportExcel(); const {workbook,columns}=ui.exported; const fields=workbookColumns(columns), sheet=workbook.getWorksheet('质量汇总'); if(view==='product')assert.equal(find(columns.find(c=>c.key==='object').render(null,row),n=>n.type==='small'),undefined); assert.equal(sheet.rowCount,19);assert.equal(sheet.columnCount,fullFields?13:10); assert.deepEqual(sheet.getRow(1).values.slice(1),fields.map(v=>v.header)); const at=key=>fields.findIndex(field=>field.key===key)+1; assert.equal(sheet.getRow(2).getCell(at('black-qualifiedWeight')).value,1234.567); assert.equal(sheet.getRow(2).getCell(at('black-totalWeight')).value,1250); assert.ok(at('black-totalWeight')f.key.includes('defect-')),fullFields); assert.equal(fields.some(f=>f.key.endsWith('headquartersScrapWeight')),fullFields); assert.equal(fields.some(f=>f.key==='actions'),false); assert.equal(sheet.getColumn(at('compositeRate')).numFmt,'0.00%'); assert.equal(sheet.getColumn(3).numFmt,'#,##0.0'); for (const field of columns.flatMap(c=>c.children||[c]).filter(c=>c.key!=='actions'&&c.key!=='object')) { const rendered=field.render(null,row); assert.equal(rendered.type,field.key==='compositeRate'?'button':'Button');assert.equal(rendered.props.onClick,undefined); } const action=columns.find(c=>c.key==='actions').render(null,row); action.props.onClick();assert.equal(ui.detail,1); const reread=await createMetricWorkbook([],[],()=>null); await reread.xlsx.load(await workbook.xlsx.writeBuffer()); assert.equal(reread.getWorksheet('质量汇总').rowCount,19); if(view==='product')assert.equal(reread.getWorksheet('质量汇总').getCell('A2').value,'=1+2'); }); } test('adjusted rates, missing stage and zero weight retain their meaning', async () => { const ui=fixture({rows:[row,{...row,key:'missing',black:{...stage,qualifiedWeight:null,rate:null},coverage:{blackRows:0,brightRows:1}}],view:'product',rateBasis:'withoutHeadquartersScrap'}); await ui.ref.exportExcel();const sheet=ui.exported.workbook.getWorksheet('质量汇总'); const fields=workbookColumns(ui.exported.columns), at=key=>fields.findIndex(field=>field.key===key)+1; assert.equal(sheet.getRow(2).getCell(at('compositeRate')).value,0.98); assert.equal(sheet.getRow(2).getCell(at('bright-rate')).value,0.99); assert.equal(sheet.getRow(3).getCell(at('black-rate')).value,null); assert.equal(sheet.getRow(3).getCell(at('black-qualifiedWeight')).value,null); assert.equal(sheet.getRow(2).getCell(at('black-scrapWeight')).value,0); }); test('overall yearly export preserves month labels and leaves unavailable values blank', async () => { const ui=fixture({rows:[{...row,month:2},{...row,key:'missing',month:3,noData:true,black:{...stage,qualifiedWeight:null,rate:null},bright:{...stage,qualifiedWeight:null,rate:null},coverage:{blackRows:0,brightRows:0}}],view:'overall',period:'year'}); await ui.ref.exportExcel();const sheet=ui.exported.workbook.getWorksheet('质量汇总'); assert.equal(sheet.getCell('A2').value,'02月');assert.equal(sheet.getCell('A3').value,'03月'); const composite=workbookColumns(ui.exported.columns).findIndex(field=>field.key==='compositeRate')+1; assert.equal(sheet.getRow(3).getCell(composite).value,null); }); for (const view of ['overall','department','group','product','projectGroup']) test(`${view}: defect-rate mode uses same-stage total and exports numeric percentages`,async()=>{ const data={...row,black:{...stage,totalWeight:1000,scrapWeight:200,defects:[{name:'责废',weight:120,rate:.99}]},bright:{...stage,totalWeight:2000,scrapWeight:100,headquartersScrapWeight:30,defects:[{name:'责废',weight:80,rate:.99}]}}; const ui=fixture({rows:[data],view,fullFields:true,defectDisplay:'rate'}); await ui.ref.exportExcel(); const fields=workbookColumns(ui.exported.columns),sheet=ui.exported.workbook.getWorksheet('质量汇总'); const at=key=>fields.findIndex(field=>field.key===key)+1; assert.equal(sheet.getRow(2).getCell(at('black-defect-责废')).value,.12); assert.equal(sheet.getRow(2).getCell(at('bright-defect-责废')).value,.04); assert.equal(sheet.getRow(2).getCell(at('black-scrapWeight')).value,.2); assert.equal(sheet.getRow(2).getCell(at('bright-headquartersScrapWeight')).value,.015); assert.equal(sheet.getColumn(at('black-defect-责废')).numFmt,'0.00%'); assert.equal(fields[at('black-defect-责废')-1].header,'黑片 / 责废率'); assert.equal(fields[at('bright-headquartersScrapWeight')-1].header,'亮片 / 本部报废率'); assert.match(fields[at('black-totalWeight')-1].header,/总重量 \/ kg$/); assert.equal(sheet.getRow(2).getCell(at('black-totalWeight')).value,1000); const rendered=ui.exported.columns.flatMap(column=>column.children||[column]).find(column=>column.key==='black-defect-责废').render(null,data); assert.equal(rendered.props.children,'12.00%'); const restored=fixture({rows:[data],view,fullFields:true,defectDisplay:'weight'});await restored.ref.exportExcel(); const originalFields=workbookColumns(restored.exported.columns),index=originalFields.findIndex(field=>field.key==='black-defect-责废')+1; assert.equal(restored.exported.workbook.getWorksheet('质量汇总').getRow(2).getCell(index).value,120); assert.equal(data.black.defects[0].weight,120); }); test('single-stage rate mode exports only its stage; missing or zero denominator stays blank and zero defect stays zero',async()=>{ const rows=[{...row,key:'zero',black:{...stage,totalWeight:0}}, {...row,key:'null',black:{...stage,totalWeight:null}}, {...row,key:'valid',black:{...stage,totalWeight:100,scrapWeight:0}}]; const ui=fixture({rows,view:'product',fullFields:true,onlyStage:'black',defectDisplay:'rate'});await ui.ref.exportExcel(); const fields=workbookColumns(ui.exported.columns),sheet=ui.exported.workbook.getWorksheet('质量汇总'),at=key=>fields.findIndex(f=>f.key===key)+1; assert.equal(fields.some(f=>f.key.startsWith('bright-')),false); assert.equal(sheet.getRow(2).getCell(at('black-scrapWeight')).value,null); assert.equal(sheet.getRow(3).getCell(at('black-defect-裂纹')).value,null); assert.equal(sheet.getRow(4).getCell(at('black-scrapWeight')).value,0); }); test('本部报废原口径紧随扩散废,调整口径隐藏并在表格及Excel同步扣减', async () => { const data={...row,bright:{...stage,scrapWeight:100,headquartersScrapWeight:30,defects:[{name:'扩散废',weight:20},{name:'加工废',weight:40}]}}; const original=fixture({rows:[data],view:'overall',fullFields:true});await original.ref.exportExcel(); const keys=workbookColumns(original.exported.columns).map(f=>f.key); assert.equal(keys.indexOf('bright-headquartersScrapWeight'),keys.indexOf('bright-defect-扩散废')+1); for(const fullFields of [false,true]) { const adjusted=fixture({rows:[data],view:'overall',fullFields,rateBasis:'withoutHeadquartersScrap'});await adjusted.ref.exportExcel(); const fields=workbookColumns(adjusted.exported.columns),at=key=>fields.findIndex(f=>f.key===key)+1; assert.equal(fields.some(f=>f.key==='bright-headquartersScrapWeight'),false); const scrapColumn=adjusted.exported.columns.flatMap(c=>c.children||[c]).find(c=>c.key==='bright-scrapWeight'); assert.equal(scrapColumn.render(null,data).props.children,'70.0'); assert.equal(adjusted.exported.workbook.getWorksheet('质量汇总').getRow(2).getCell(at('bright-scrapWeight')).value,70); assert.equal(adjusted.exported.workbook.getWorksheet('质量汇总').getRow(2).getCell(at('bright-totalWeight')).value,1250); } assert.equal(data.bright.scrapWeight,100); });