diff --git a/src/views/assessment/diagnosis.vue b/src/views/assessment/diagnosis.vue index 3fee487..2f266e8 100644 --- a/src/views/assessment/diagnosis.vue +++ b/src/views/assessment/diagnosis.vue @@ -35,8 +35,7 @@ "0") }}{{ step }} - - + @@ -56,6 +55,9 @@ 链路节点和行业均值固定,中间渠道可按案例数据增加或删除。 增加渠道 + + @@ -128,6 +130,9 @@ @click="addAnomalyRow">增加一行删除一行 + + diff --git a/src/views/channel/supplier.vue b/src/views/channel/supplier.vue index 8dd3a16..390c6d4 100644 --- a/src/views/channel/supplier.vue +++ b/src/views/channel/supplier.vue @@ -36,8 +36,7 @@ - - + @@ -97,6 +96,8 @@ 试产加权总分 = Σ(评分 × 试产权重) · 量产加权总分 = Σ(评分 × 量产权重) + + diff --git a/src/views/components/TrainingExcelTools.vue b/src/views/components/TrainingExcelTools.vue index 50add18..92cffb6 100644 --- a/src/views/components/TrainingExcelTools.vue +++ b/src/views/components/TrainingExcelTools.vue @@ -12,13 +12,15 @@ diff --git a/tests/numeric-training-excel.test.cjs b/tests/numeric-training-excel.test.cjs index c90a127..64f0fd6 100644 --- a/tests/numeric-training-excel.test.cjs +++ b/tests/numeric-training-excel.test.cjs @@ -208,3 +208,534 @@ test('numeric Excel preserves percentage semantics and clears existing scalar ro weight.apply(h.parseTableRows(input,weight).rows); assert.equal(efficacy.parsePercentage(efficacy.data.value[0].currentWeight),0.3); }); + +test('numeric Excel BOM imports 16 rows through workbook controls and saves the calculated total', async () => { + for (const bookType of ['xls','xlsx']) { + const saved=[], checks=[]; + const state=await harness('product/hardware-cost',{ + validateHardwareCostStepOne:async payload=>{checks.push(plain(payload));return {data:{}};}, + saveStudentTrainingAnswer:async (key,payload)=>saved.push({key,payload}), + }); + const props=Vue.reactive({get tables(){return state.numericExcelTables.value;},get contextKey(){return state.currentStep.value;},disabled:false}); + const downloads=[], errors=[]; + const tools=await harness('components/TrainingExcelTools',{ + defineProps:()=>props, + XLSX_IMPORT:{...XLSX,writeFile:(workbook,name)=>downloads.push({workbook,name})}, + ElMessage:{success(){},error:message=>errors.push(message)},ElMessageBox:{confirm:async()=>{}}, + }); + await tools.downloadTemplate(); + const workbook=downloads[0].workbook; + const data=[['序号','物料名称','选型规格参数','单价(元)','数量'],...Array.from({length:16},(_,i)=>[i+1,'元器件'+(i+1),'规格'+(i+1),(i+1)+0.5,2])]; + workbook.Sheets[workbook.SheetNames[0]]=XLSX.utils.aoa_to_sheet(data); + const bytes=XLSX.write(workbook,{type:'buffer',bookType}); + const input={target:{value:'bom',files:[{name:'BOM.'+bookType,size:bytes.length,arrayBuffer:async()=>bytes}]}}; + await tools.importFile(input); + assert.deepEqual(errors,[]); + assert.equal(input.target.value,''); + assert.equal(saved.length,0,'import updates the form until the student saves'); + assert.equal(state.rows.value.length,16); + assert.equal(state.rows.value[15].materialName,'元器件16'); + assert.equal(state.rows.value[15].specification,'规格16'); + assert.equal(state.totalAmount.value,288); + await state.saveStepOne(false); + assert.equal(checks.length,1); + assert.equal(checks[0].items.length,16); + assert.equal(saved.length,1); + assert.equal(saved[0].key,'hardware-cost'); + const answer=JSON.parse(saved[0].payload.step1Answer); + assert.equal(answer.items.length,16); assert.equal(answer.totalAmount,'288.00'); + assert.equal(answer.items[15].unitPrice,16.5); assert.equal(answer.items[15].quantity,2); + assert.equal(state.costRows.value.length,16,'saved materials continue into step two'); + } +}); + +test('numeric Excel BOM supports 40 rows and rejects excess rows or invalid quantities atomically', async () => { + const h=await helpers; + const state=await harness('product/hardware-cost'); + const table=state.numericExcelTables.value[0]; + const data=[h.templateRows(table)[0],...Array.from({length:40},(_,i)=>[i+1,'元器件'+(i+1),'规格',1.25,2])]; + table.apply(h.parseTableRows(data,table).rows); + assert.equal(state.rows.value.length,40); assert.equal(state.totalAmount.value,100); + const before=JSON.stringify(state.rows.value); + assert.throws(()=>h.parseTableRows([...data,[41,'多余物料','规格',1,1]],state.numericExcelTables.value[0]),/范围/); + for (const quantity of [0,-1,1.5,10000,'abc']) { + const bad=data.map(row=>[...row]); bad[2][4]=quantity; + assert.throws(()=>h.parseTableRows(bad,state.numericExcelTables.value[0])); + assert.equal(JSON.stringify(state.rows.value),before); + } +}); + +test('numeric Excel BOM first and second steps render import controls directly above their tables', async () => { + const filename=path.resolve(__dirname,'../src/views/product/hardware-cost.vue'); + const descriptor=parse(fs.readFileSync(filename,'utf8')).descriptor; + const {code}=require('@vue/compiler-ssr').compile(descriptor.template.content); + const ssrRender=new Function('require',code)(require); + const state=await harness('product/hardware-cost'); + const render=async step=>{ + state.currentStep.value=step; + const app=Vue.createSSRApp({setup:()=>state,ssrRender}); + app.component('TrainingExcelTools',{props:['tables'],setup:props=>()=>props.tables?.length?Vue.h('div',{'data-test-excel':props.tables[0].id},'下载 Excel 模板 / 导入 Excel'):null}); + for(const name of ['TrainingTaskToolbar','TrainingAiSidebar','ElInput','ElInputNumber','ElIcon','ArrowLeft','ArrowRight','CircleCheck','DataAnalysis']) app.component(name,{render:()=>null}); + app.config.warnHandler=()=>{}; + return require('@vue/server-renderer').renderToString(app); + }; + const html=await render(1); + const toolbar=html.indexOf('data-test-excel="bom"'); + assert.ok(toolbar>html.indexOf('第一行是可编辑示例')); + assert.ok(toolbarbatch.indexOf('100 台与 10000 台单台成本')); + assert.ok(batchTools { + for (const bookType of ['xls','xlsx']) { + const saved=[], validations=[], errors=[], downloads=[]; + const state=await harness('product/hardware-cost',{ + validateHardwareCostStepTwo:async payload=>{ + validations.push(plain(payload)); + return {data:{...payload,valid:true, + smallBatchTotal:payload.items.reduce((sum,r)=>sum+r.smallBatchUnitCost,0), + largeBatchTotal:payload.items.reduce((sum,r)=>sum+r.largeBatchUnitCost,0)}}; + }, + saveStudentTrainingAnswer:async (key,payload)=>saved.push({key,payload}), + }); + state.rows.value=Array.from({length:16},(_,i)=>({...state.createBlankRow(),materialName:'物料'+(i+1),specification:'规格'+(i+1),unitPrice:'1',quantity:1})); + const original=plain(state.rows.value); + state.savedStepOneItems.value=state.stepOnePayload().items; + state.syncStepTwoRows(); state.currentStep.value=2; + state.stepTwo.smallBatchConstraint='210'; state.stepTwo.largeBatchConstraint='150'; + const props=Vue.reactive({get tables(){return state.numericExcelTables.value;},get contextKey(){return state.currentStep.value;},disabled:false}); + const tools=await harness('components/TrainingExcelTools',{ + defineProps:()=>props, + XLSX_IMPORT:{...XLSX,writeFile:(workbook,name)=>downloads.push({workbook,name})}, + ElMessage:{success(){},error:m=>errors.push(m)},ElMessageBox:{confirm:async()=>{}}, + }); + await tools.downloadTemplate(); + const workbook=downloads[0].workbook; + const sheet=workbook.Sheets[workbook.SheetNames[0]]; + const data=XLSX.utils.sheet_to_json(sheet,{header:1,defval:''}); + assert.equal(data.length,17); + assert.ok(data.slice(1).every(r=>r[2]===''&&r[3]==='')); + assert.deepEqual(data.slice(1).map(r=>r[1]),original.map(r=>r.materialName)); + const filled=data.map((row,index)=>index===0?row:[...row.slice(0,2),index===1?0:index,index===1?0:index/2]); + // Keep each row's serial when changing the row order in Excel. + workbook.Sheets[workbook.SheetNames[0]]=XLSX.utils.aoa_to_sheet([filled[0],...filled.slice(1).reverse()]); + const bytes=XLSX.write(workbook,{type:'buffer',bookType}); + await tools.importFile({target:{value:'batch',files:[{name:'成本.'+bookType,size:bytes.length,arrayBuffer:async()=>bytes}]}}); + assert.deepEqual(errors,[]); assert.equal(saved.length,0); + assert.equal(state.costRows.value.length,16); + assert.equal(state.costRows.value[0].smallBatchUnitCost,'0'); + assert.equal(state.costRows.value[15].largeBatchUnitCost,'8'); + assert.equal(state.smallBatchTotal.value,135); assert.equal(state.largeBatchTotal.value,67.5); + assert.equal(state.stepTwo.smallBatchConstraint,'210'); assert.equal(state.stepTwo.largeBatchConstraint,'150'); + assert.deepEqual(plain(state.rows.value),original); + await state.saveStepTwo(); + assert.equal(validations.length,1); assert.equal(saved.length,1); + assert.equal(saved[0].key,'hardware-cost'); + assert.equal(saved[0].payload.currentStep,2); + const answer=JSON.parse(saved[0].payload.step2Answer); + assert.equal(answer.items.length,16); assert.equal(answer.smallBatchTotal,135); assert.equal(answer.largeBatchTotal,67.5); + assert.equal(answer.smallBatchConstraint,210); assert.equal(answer.largeBatchConstraint,150); + assert.equal(state.stepTwoSaved.value,true); + assert.deepEqual(plain(state.rows.value),original); + } +}); + +test('numeric Excel BOM batch costs reject renamed materials and bad costs without partial updates', async () => { + const h=await helpers; + const state=await harness('product/hardware-cost'); + state.rows.value=Array.from({length:3},(_,i)=>({...state.createBlankRow(),materialName:'物料'+(i+1)})); + state.syncStepTwoRows(state.rows.value); state.currentStep.value=2; + state.stepTwo.smallBatchConstraint='210'; state.stepTwo.largeBatchConstraint='150'; + const table=state.numericExcelTables.value[0]; + const header=h.templateRows(table)[0]; + const before=JSON.stringify(state.costRows.value); + for (const bad of [[2,'改名物料',2,1],[2,'物料2',-1,1],[2,'物料2','abc',1],[4,'物料4',2,1],[1,'物料1',2,1]]) { + assert.throws(()=>h.parseTableRows([header,[1,'物料1',1,0.5],bad],table)); + assert.equal(JSON.stringify(state.costRows.value),before); + } + const file={name:'成本.xlsx',size:100}; + await assert.rejects(h.importTableFile(file,table,{ + readWorkbook:async()=>[header,[2,'物料2',22,11]], + confirm:async()=>{throw Error('cancel');},isCurrent:()=>true, + })); + assert.equal(JSON.stringify(state.costRows.value),before); + table.apply(h.parseTableRows([header,[2,'物料2',22,11]],table).rows); + assert.equal(state.costRows.value[0].smallBatchUnitCost,''); + assert.equal(state.costRows.value[1].smallBatchUnitCost,'22'); + assert.equal(state.costRows.value[1].largeBatchUnitCost,'11'); + assert.equal(state.costRows.value[2].smallBatchUnitCost,''); + assert.equal(state.stepTwo.smallBatchConstraint,'210'); assert.equal(state.stepTwo.largeBatchConstraint,'150'); +}); + +test('numeric Excel supplier scores import five channels and save both weighted scenarios without changing weights', async () => { + for (const bookType of ['xls','xlsx']) { + const saved=[], downloads=[], errors=[]; + let state; + state=await harness('channel/supplier',{ + ElMessage:{success(){},error:m=>errors.push(m),warning:m=>errors.push(m)}, + validateSupplierEvaluationStepTwo:async payload=>{ + const total=(r,scenario)=>Number(r.scores.reduce((sum,d)=>sum+d.score*state.rows.value.find(w=>w.name===d.dimension)[scenario+'Weight']/100,0).toFixed(2)); + return {data:{valid:true,weights:state.buildStepOnePayload().items, + smallBatchChannels:payload.smallBatchChannels.map(r=>({...r,weightedTotal:total(r,'smallBatch')})), + largeBatchChannels:payload.largeBatchChannels.map(r=>({...r,weightedTotal:total(r,'largeBatch')}))}}; + }, + saveStudentTrainingAnswer:async(key,payload)=>saved.push({key,payload}), + }); + const small=[15,25,20,25,15], large=[40,15,25,10,10]; + state.rows.value.forEach((r,i)=>{r.smallBatchWeight=small[i];r.largeBatchWeight=large[i];}); + state.stepOneSaved.value=true; state.currentStep.value=2; + const weights=plain(state.rows.value), ids=state.channelRows.value.map(r=>r.id); + state.channelRows.value.forEach(r=>{r.smallWeightedTotal=99;r.largeWeightedTotal=99;}); + const props=Vue.reactive({get tables(){return state.numericExcelTables.value;},get contextKey(){return state.currentStep.value;},disabled:false}); + const tools=await harness('components/TrainingExcelTools',{ + defineProps:()=>props, + XLSX_IMPORT:{...XLSX,writeFile:(workbook,name)=>downloads.push({workbook,name})}, + ElMessage:{success(){},error:m=>errors.push(m)},ElMessageBox:{confirm:async()=>{}}, + }); + await tools.downloadTemplate(); + const workbook=downloads[0].workbook; + const template=XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]],{header:1,defval:''}); + assert.deepEqual(template[0],['序号','渠道','采购成本','交货周期','品质可靠性','采购灵活性','服务支持']); + assert.equal(template.length,6); + assert.ok(template.slice(1).every(r=>r.slice(2).every(v=>v===''))); + const scores=[[9,7,10,6,7],[7,9,8,9,8],[4,5,4,8,5],[9,8,8,6,10],[0,3,9,5,10]]; + const data=[template[0],...scores.map((r,i)=>[i+1,'渠道'+(i+1),...r]).reverse()]; + workbook.Sheets[workbook.SheetNames[0]]=XLSX.utils.aoa_to_sheet(data); + const bytes=XLSX.write(workbook,{type:'buffer',bookType}); + await tools.importFile({target:{value:'scores',files:[{name:'供应渠道评分.'+bookType,size:bytes.length,arrayBuffer:async()=>bytes}]}}); + assert.deepEqual(errors,[]); assert.equal(saved.length,0); + assert.deepEqual(plain(state.rows.value),weights); + assert.deepEqual(state.channelRows.value.map(r=>r.id),ids); + state.channelRows.value.forEach((row,i)=>{ + assert.equal(row.channel,'渠道'+(i+1)); + state.rows.value.forEach((dimension,j)=>assert.equal(row.scores[dimension.key],scores[i][j])); + assert.equal(row.smallWeightedTotal,null); assert.equal(row.largeWeightedTotal,null); + const expected=weights=>scores[i].reduce((sum,value,j)=>sum+value*weights[j]/100,0).toFixed(2); + assert.equal(state.weightedScore(row,'smallBatch'),expected(small)); + assert.equal(state.weightedScore(row,'largeBatch'),expected(large)); + }); + assert.equal(await state.saveStepTwo(),true); + assert.equal(saved.length,1); assert.equal(saved[0].key,'supplier-evaluation'); + const answer=JSON.parse(saved[0].payload.step2Answer); + assert.equal(answer.smallBatchChannels.length,5); assert.equal(answer.largeBatchChannels.length,5); + assert.equal(answer.smallBatchChannels[0].weightedTotal,7.65); + assert.equal(answer.largeBatchChannels[0].weightedTotal,8.45); + assert.deepEqual(plain(state.rows.value),weights); + assert.equal(state.stepTwoSaved.value,true); + } +}); + +test('numeric Excel supplier scores reject invalid scores and preserve unlisted channels or cancellation', async () => { + const h=await helpers; + const state=await harness('channel/supplier'); state.currentStep.value=2; + const table=state.numericExcelTables.value[0]; + const header=h.templateRows(table)[0]; + const before=JSON.stringify(state.channelRows.value), weights=JSON.stringify(state.rows.value); + for(const score of [-1,11,1.5,'abc']) { + assert.throws(()=>h.parseTableRows([header,[1,'有效渠道',1,2,3,4,5],[2,'无效渠道',score,2,3,4,5]],table)); + assert.equal(JSON.stringify(state.channelRows.value),before); + } + assert.throws(()=>h.parseTableRows([header,[6,'超出五行',1,2,3,4,5]],table)); + assert.throws(()=>h.parseTableRows([header,[1,'重复1',1,2,3,4,5],[1,'重复2',1,2,3,4,5]],table)); + assert.throws(()=>h.parseTableRows([[...header,'试产加权总分'],[1,'渠道',1,2,3,4,5,9]],table)); + await assert.rejects(h.importTableFile({name:'评分.xlsx',size:100},table,{ + readWorkbook:async()=>[header,[2,'渠道2',10,0,3,4,5]],confirm:async()=>{throw Error('cancel');},isCurrent:()=>true, + })); + assert.equal(JSON.stringify(state.channelRows.value),before); + table.apply(h.parseTableRows([header,[2,'渠道2',10,0,3,4,5]],table).rows); + assert.equal(state.channelRows.value[0].channel,''); + assert.equal(state.channelRows.value[1].channel,'渠道2'); + assert.equal(state.channelRows.value[1].scores.procurementCost,10); + assert.equal(state.channelRows.value[1].scores.deliveryCycle,0); + assert.equal(state.channelRows.value[2].channel,''); + assert.equal(JSON.stringify(state.rows.value),weights); +}); + +test('numeric Excel supplier step two renders one import toolbar inside the scoring section', async () => { + const filename=path.resolve(__dirname,'../src/views/channel/supplier.vue'); + const descriptor=parse(fs.readFileSync(filename,'utf8')).descriptor; + const {code}=require('@vue/compiler-ssr').compile(descriptor.template.content); + const ssrRender=new Function('require',code)(require); + const state=await harness('channel/supplier'); + const render=async step=>{ + state.currentStep.value=step; + const app=Vue.createSSRApp({setup:()=>state,ssrRender}); + app.component('TrainingExcelTools',{props:['tables'],setup:props=>()=>props.tables?.length?Vue.h('div',{'data-test-excel':props.tables[0].id},'下载 Excel 模板 / 导入 Excel'):null}); + for(const name of ['TrainingTaskToolbar','TrainingAiSidebar','ElInput','ElInputNumber','ElIcon','ArrowLeft','ArrowRight','CircleCheck','Plus','Delete']) app.component(name,{render:()=>null}); + app.directive('loading',{}); app.config.warnHandler=()=>{}; + return require('@vue/server-renderer').renderToString(app); + }; + const html=await render(2); + const toolbar=html.indexOf('data-test-excel="scores"'); + assert.ok(toolbar>html.indexOf('供应渠道评分与加权对比')); + assert.ok(toolbar { + const h=await helpers; + const state=await harness('channel/supplier'); state.currentStep.value=2; + const before=JSON.stringify(state.channelRows.value); + const table=state.numericExcelTables.value[0]; + let unmount; + const errors=[]; + const tools=await harness('components/TrainingExcelTools',{ + defineProps:()=>({tables:[table],contextKey:2,disabled:false}), + onBeforeUnmount:callback=>{unmount=callback;}, + XLSX_IMPORT:XLSX, + ElMessage:{success(){throw Error('Unmounted controls must not apply the import');},error:m=>errors.push(m)}, + ElMessageBox:{confirm:async()=>{state.currentStep.value=1;unmount();}}, + }); + const book=XLSX.utils.book_new(); + XLSX.utils.book_append_sheet(book,XLSX.utils.aoa_to_sheet([h.templateRows(table)[0],[1,'不应回填的渠道',1,2,3,4,5]]),'填写数据'); + const bytes=XLSX.write(book,{type:'buffer',bookType:'xlsx'}); + await tools.importFile({target:{value:'file',files:[{name:'评分.xlsx',size:bytes.length,arrayBuffer:async()=>bytes}]}}); + assert.equal(JSON.stringify(state.channelRows.value),before); + assert.equal(errors.length,1); assert.match(errors[0],/已变化/); +}); + +test('numeric Excel PSM imports six price ranges and saves percentages without changing chart or price points', async () => { + for(const bookType of ['xls','xlsx']) { + const saved=[], validations=[], errors=[], downloads=[]; + const state=await harness('product/price',{ + validateProductPricingStepFour:async payload=>{validations.push(plain(payload));return {data:payload};}, + saveStudentTrainingAnswer:async (key,payload)=>saved.push({key,payload}), + }); + state.currentStep.value=4; + const ranges=['≤399元','399~499元','499~599元','599~699元','699~799元','≥799元']; + state.psmRows.value.forEach((r,i)=>{r.priceRange=ranges[i];}); + Object.assign(state.psmPricePoints,{optimalPrice:'599',acceptablePrice:'699',acceptableRange:'499~699元'}); + Object.assign(state.psmChart,{url:'/file/existing-chart.png',name:'已有折线图.png'}); + state.unitCost.value='99'; state.validationMessage.value='旧的校验提示'; + const ids=state.psmRows.value.map(r=>r.id), chart=plain(state.psmChart), points=plain(state.psmPricePoints); + const props=Vue.reactive({get tables(){return state.numericExcelTables.value;},get contextKey(){return state.currentStep.value;},disabled:false}); + const tools=await harness('components/TrainingExcelTools',{ + defineProps:()=>props, + XLSX_IMPORT:{...XLSX,writeFile:(workbook,name)=>downloads.push({workbook,name})}, + ElMessage:{success(){},error:m=>errors.push(m)},ElMessageBox:{confirm:async()=>{}}, + }); + await tools.downloadTemplate(); + const workbook=downloads[0].workbook; + const template=XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]],{header:1,defval:''}); + assert.equal(template.length,7); + assert.deepEqual(template.slice(1).map(r=>r[1]),ranges); + assert.ok(template.slice(1).every(r=>r.slice(2).every(v=>v===''))); + const values=[[0,100,3,100],[3,60,11.5,50],[9,30,29,18],[29,14,71,8],[67,6,91,3],[100,2,100,1]]; + const data=[template[0],...values.map((r,i)=>[i+1,ranges[i],...r]).reverse()]; + const sheet=XLSX.utils.aoa_to_sheet(data); + sheet.E2={t:'n',v:1,z:'0%'}; // A genuine Excel percentage cell, displayed as 100%. + sheet.E6={t:'s',v:'11.5%'}; + workbook.Sheets[workbook.SheetNames[0]]=sheet; + const bytes=XLSX.write(workbook,{type:'buffer',bookType}); + await tools.importFile({target:{value:'psm',files:[{name:'PSM.'+bookType,size:bytes.length,arrayBuffer:async()=>bytes}]}}); + assert.deepEqual(errors,[]); assert.equal(saved.length,0); + assert.deepEqual(plain(state.psmRows.value.map(r=>r.id)),plain(ids)); + state.psmRows.value.forEach((row,i)=>{ + assert.equal(row.priceRange,ranges[i]); + ['tooExpensive','tooCheap','expensiveAcceptable','cheapValue'].forEach((field,j)=>assert.equal(Number(row[field]),values[i][j])); + }); + assert.equal(state.validationMessage.value,''); + assert.equal(state.unitCost.value,'99'); + assert.deepEqual(plain(state.psmChart),chart); assert.deepEqual(plain(state.psmPricePoints),points); + assert.equal(await state.saveStepFour(),true); + assert.equal(validations.length,1); assert.equal(saved.length,1); + assert.equal(saved[0].key,'product-pricing'); assert.equal(saved[0].payload.currentStep,4); + const answer=JSON.parse(saved[0].payload.step4Answer); + assert.equal(answer.psmRows.length,6); assert.equal(answer.psmRows[1].expensiveAcceptable,11.5); + assert.equal(answer.psmRows[5].tooExpensive,100); + assert.equal(answer.chart.url,chart.url); assert.equal(answer.pricePoints.optimalPrice,599); + const restored=await harness('product/price'); restored.applyStepFourProgress(answer); + assert.equal(restored.psmRows.value[1].expensiveAcceptable,11.5); + } +}); + +test('numeric Excel PSM rejects invalid percentages and changed price ranges without overwriting existing rows', async () => { + const h=await helpers; + const state=await harness('product/price'); state.currentStep.value=4; + state.psmRows.value.forEach(r=>{r.tooExpensive='1';r.tooCheap='2';r.expensiveAcceptable='3';r.cheapValue='4';}); + const table=state.numericExcelTables.value[0]; + const header=h.templateRows(table)[0], before=JSON.stringify(state.psmRows.value); + const first=state.psmRows.value[0].priceRange, second=state.psmRows.value[1].priceRange; + for(const bad of [-1,100.01,'abc','1.2.3']) { + assert.throws(()=>h.parseTableRows([header,[1,first,5,6,7,8],[2,second,bad,2,3,4]],table)); + assert.equal(JSON.stringify(state.psmRows.value),before); + } + assert.throws(()=>h.parseTableRows([header,[1,'改动了价格区间',5,6,7,8]],table)); + assert.throws(()=>h.parseTableRows([header,[1,first,5,6,7,8],[1,first,5,6,7,8]],table)); + await assert.rejects(h.importTableFile({name:'PSM.xlsx',size:100},table,{ + readWorkbook:async()=>[header,[2,second,'25%',2,3,4]],confirm:async()=>{throw Error('cancel');},isCurrent:()=>true, + })); + assert.equal(JSON.stringify(state.psmRows.value),before); + state.validationMessage.value='旧提示'; + table.apply(h.parseTableRows([header,[2,second,'25%',2,3,4]],table).rows); + assert.equal(state.psmRows.value[0].tooExpensive,'1'); + assert.equal(state.psmRows.value[1].tooExpensive,'25'); + assert.equal(state.psmRows.value[2].tooExpensive,'1'); + assert.equal(state.validationMessage.value,''); +}); + +test('numeric Excel PSM import controls render above the fourth step table with original units', async () => { + const filename=path.resolve(__dirname,'../src/views/product/price.vue'); + const descriptor=parse(fs.readFileSync(filename,'utf8')).descriptor; + const {code}=require('@vue/compiler-ssr').compile(descriptor.template.content); + const ssrRender=new Function('require',code)(require); + const state=await harness('product/price'); + const render=async step=>{ + state.currentStep.value=step; + const app=Vue.createSSRApp({setup:()=>state,ssrRender}); + app.component('TrainingExcelTools',{props:['tables'],setup:props=>()=>props.tables?.length?Vue.h('div',{'data-test-excel':props.tables[0].id},'下载 Excel 模板 / 导入 Excel'):null}); + for(const name of ['TrainingTaskToolbar','TrainingAiSidebar','ElInput','ElButton','ElSelect','ElOption','ElImage','ElIcon','ArrowLeft','ArrowRight','CircleCheck']) app.component(name,{render:()=>null}); + app.config.warnHandler=()=>{}; + return require('@vue/server-renderer').renderToString(app); + }; + const html=await render(4); + const toolbar=html.indexOf('data-test-excel="psm"'); + assert.ok(toolbar>html.indexOf('class="psm-toolbar"')); + assert.ok(toolbar { + for(const bookType of ['xls','xlsx']) { + const saved=[], validations=[], downloads=[], errors=[]; + const state=await harness('assessment/diagnosis',{ + saveStudentTrainingAnswer:async(key,payload)=>saved.push({key,payload}), + validateProductDiagnosisIterationStepOne:async data=>{validations.push(plain(data));return {data:{valid:true}};}, + }); + state.addFunnelChannel(); state.channels.value[4].name='唯品会'; + Object.assign(state.funnelChart.value,{url:'/file/existing-funnel.png',name:'已有漏斗图.png'}); + Object.assign(state.anomalyRows.value[0],{channelId:'tmall',channel:'天猫',linkNode:state.nodes[0],storeConversionRate:5,industryAverageConversionRate:6,anomalyAnalysis:'保留分析'}); + const channels=plain(state.channels.value), anomaly=plain(state.anomalyRows.value), chart=plain(state.funnelChart.value); + const props=Vue.reactive({get tables(){return state.numericExcelTables.value.filter(t=>t.id==='funnel');},get contextKey(){return state.currentStep.value;},disabled:false}); + const tools=await harness('components/TrainingExcelTools',{ + defineProps:()=>props, + XLSX_IMPORT:{...XLSX,writeFile:(workbook,name)=>downloads.push({workbook,name})}, + ElMessage:{success(){},error:m=>errors.push(m)},ElMessageBox:{confirm:async()=>{}}, + }); + await tools.downloadTemplate(); + const workbook=downloads[0].workbook; + const template=XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]],{header:1,defval:''}); + assert.equal(template.length,6); assert.equal(template[0].length,8); + assert.deepEqual(template[0].slice(2,-1),channels.map(c=>c.name+'转化率(%)')); + assert.equal(template[0].at(-1),'行业平均值(%)'); + assert.ok(template.slice(1).every(r=>r.slice(2).every(v=>v===''))); + const values=state.nodes.map((_,i)=>channels.map((_,j)=>i===0&&j===0?0:i===4&&j===4?100:i*10+j+0.25)); + const industry=[3.5,8.5,32,90.5,4.8]; + const rows=[template[0],...state.nodes.map((node,i)=>[i+1,node,...values[i],industry[i]]).reverse()]; + const sheet=XLSX.utils.aoa_to_sheet(rows); + sheet.G2={t:'n',v:1,z:'0%'}; sheet.H2={t:'n',v:0.048,z:'0.00%'}; + workbook.Sheets[workbook.SheetNames[0]]=sheet; + const bytes=XLSX.write(workbook,{type:'buffer',bookType}); + await tools.importFile({target:{value:'funnel',files:[{name:'转化率.'+bookType,size:bytes.length,arrayBuffer:async()=>bytes}]}}); + assert.deepEqual(errors,[]); assert.equal(saved.length,0); + assert.deepEqual(plain(state.channels.value),channels); + assert.deepEqual(plain(state.anomalyRows.value),anomaly); assert.deepEqual(plain(state.funnelChart.value),chart); + state.conversionRates.value.forEach((row,i)=>{ + assert.equal(row.linkNode,state.nodes[i]); assert.equal(row.industryAverage,industry[i]); + channels.forEach((channel,j)=>assert.equal(row.channelRates[channel.id],values[i][j])); + }); + assert.equal(state.funnelRatesComplete.value,true); + await state.persistStepOne(false); + assert.equal(saved[0].key,'product-diagnosis-iteration'); + assert.equal(saved[0].payload.currentStep,1); + const answer=JSON.parse(saved[0].payload.step1Answer); + assert.equal(answer.channels.length,5); assert.equal(answer.conversionRates.length,5); + assert.equal(answer.conversionRates[4].industryAverage,4.8); + assert.equal(answer.funnelChartUrl,chart.url); assert.equal(answer.anomalyRows[0].anomalyAnalysis,'保留分析'); + await state.validateStepOne(); + assert.equal(validations.length,1); assert.equal(state.currentStep.value,2); + assert.equal(saved.at(-1).payload.currentStep,2); + } +}); + +test('numeric Excel diagnosis rejects invalid rates and wrong channel or node templates atomically', async () => { + const h=await helpers; + const state=await harness('assessment/diagnosis'); + state.conversionRates.value.forEach(row=>{row.industryAverage=7;state.channels.value.forEach(c=>{row.channelRates[c.id]=8;});}); + const table=state.numericExcelTables.value.find(t=>t.id==='funnel'), header=h.templateRows(table)[0]; + const valid=[1,state.nodes[0],1,2,3,4,5], before=JSON.stringify(state.conversionRates.value); + for(const value of [-1,100.01,1.001,'abc']) { + const bad=[2,state.nodes[1],value,2,3,4,5]; + assert.throws(()=>h.parseTableRows([header,valid,bad],table)); + assert.equal(JSON.stringify(state.conversionRates.value),before); + } + const changedHeader=[...header]; changedHeader[2]='其他渠道转化率(%)'; + assert.throws(()=>h.parseTableRows([changedHeader,valid],table)); + assert.throws(()=>h.parseTableRows([header,[1,'未知节点',1,2,3,4,5]],table)); + assert.throws(()=>h.parseTableRows([header,valid,valid],table)); + await assert.rejects(h.importTableFile({name:'转化率.xlsx',size:100},table,{ + readWorkbook:async()=>[header,valid],confirm:async()=>{throw Error('cancel');},isCurrent:()=>true, + })); + assert.equal(JSON.stringify(state.conversionRates.value),before); + table.apply(h.parseTableRows([header,valid],table).rows); + assert.equal(state.conversionRates.value[0].channelRates.tmall,1); + assert.equal(state.conversionRates.value[1].channelRates.tmall,8); + assert.equal(state.conversionRates.value[1].industryAverage,7); +}); + +test('numeric Excel diagnosis stops pending imports when channel names or columns change', async () => { + const h=await helpers; + for(const change of ['rename','add','remove']) { + const errors=[]; + const state=await harness('assessment/diagnosis'); + state.conversionRates.value.forEach(row=>state.channels.value.forEach(c=>{row.channelRates[c.id]=7;})); + const props=Vue.reactive({get tables(){return state.numericExcelTables.value.filter(t=>t.id==='funnel');},contextKey:1,disabled:false}); + const table=props.tables[0]; + const tools=await harness('components/TrainingExcelTools',{ + defineProps:()=>props,XLSX_IMPORT:XLSX, + ElMessage:{success(){throw Error('Changed channel configuration must reject import');},error:m=>errors.push(m)}, + ElMessageBox:{confirm:async()=>{ + if(change==='rename')state.channels.value[0].name='新的渠道名称'; + if(change==='add')state.addFunnelChannel(); + if(change==='remove')state.removeFunnelChannel('tmall'); + }}, + }); + const book=XLSX.utils.book_new(); + XLSX.utils.book_append_sheet(book,XLSX.utils.aoa_to_sheet([h.templateRows(table)[0],[1,state.nodes[0],99,99,99,99,99]]),'填写数据'); + const bytes=XLSX.write(book,{type:'buffer',bookType:'xlsx'}); + await tools.importFile({target:{value:'funnel',files:[{name:'转化率.xlsx',size:bytes.length,arrayBuffer:async()=>bytes}]}}); + assert.equal(state.conversionRates.value[0].channelRates.jd,7); + assert.equal(state.conversionRates.value[0].industryAverage,null); + assert.equal(errors.length,1); assert.match(errors[0],/已变化/); + if(change==='rename')assert.equal(state.channels.value[0].name,'新的渠道名称'); + if(change==='add')assert.equal(state.channels.value.length,5); + if(change==='remove')assert.equal(state.channels.value.some(c=>c.id==='tmall'),false); + } +}); + +test('numeric Excel diagnosis first step renders separate controls above the funnel and anomaly tables', async () => { + const filename=path.resolve(__dirname,'../src/views/assessment/diagnosis.vue'); + const descriptor=parse(fs.readFileSync(filename,'utf8')).descriptor; + const {code}=require('@vue/compiler-ssr').compile(descriptor.template.content); + const ssrRender=new Function('require',code)(require); + const state=await harness('assessment/diagnosis'); + const render=async step=>{ + state.currentStep.value=step; + const app=Vue.createSSRApp({setup:()=>state,ssrRender}); + app.component('TrainingExcelTools',{props:['tables'],setup:props=>()=>props.tables?.length?Vue.h('div',{'data-test-excel':props.tables.map(t=>t.id).join(',')},'下载 Excel 模板 / 导入 Excel'):null}); + for(const name of ['TrainingTaskToolbar','TrainingAiSidebar','ElInput','ElInputNumber','ElSelect','ElOption','ElImage','ElIcon','ArrowLeft','ArrowRight','CircleCheck']) app.component(name,{render:()=>null}); + app.config.warnHandler=()=>{}; + return require('@vue/server-renderer').renderToString(app); + }; + const html=await render(1), funnel=html.indexOf('data-test-excel="funnel"'), anomaly=html.indexOf('data-test-excel="anomaly"'); + assert.ok(funnel>html.indexOf('计算各节点转化率')); + assert.ok(funnelhtml.indexOf('定位异常节点')); + assert.ok(anomaly%/); + assert.equal(((await render(2)).match(/data-test-excel=/g)||[]).length,0); + assert.match(await render(3),/data-test-excel="ab"/); +}); diff --git a/tests/process-schedule-excel.test.cjs b/tests/process-schedule-excel.test.cjs new file mode 100644 index 0000000..ef77de3 --- /dev/null +++ b/tests/process-schedule-excel.test.cjs @@ -0,0 +1,195 @@ +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); +const { pathToFileURL } = require('node:url'); +const Vue = require('vue'); +const XLSX = require('xlsx'); +const babel = require('@babel/parser'); +const { parse, compileScript, compileTemplate } = require('@vue/compiler-sfc'); +const filename = path.resolve(__dirname, '../src/views/foundation/product-development-process.vue'); +const source = fs.readFileSync(filename, 'utf8'); +const helpers = import(pathToFileURL(path.resolve(__dirname, '../src/views/foundation/processScheduleExcel.mjs')).href); +const plain = value => JSON.parse(JSON.stringify(value)); + +async function harness(options = {}) { + const helper = await helpers; + let script = parse(source).descriptor.scriptSetup.content; + const ast = babel.parse(script, { sourceType: 'module' }).program.body; + for (const node of [...ast].reverse()) if (node.type === 'ImportDeclaration') script = script.slice(0, node.start) + script.slice(node.end); + const saved = [], downloads = [], messages = [], validations = []; + const context = { ...Vue, ...helper, onMounted() {}, watch() {}, + getCurrentInstance: () => ({ proxy: { $modal: { msgSuccess: m => messages.push(m), msgError: m => messages.push(m), msgWarning: m => messages.push(m) } } }), + useUserStore: () => ({ userInfo: { userId: 'local-test' } }), + localStorage: { removeItem() {}, getItem: () => null, setItem() {} }, + parseTrainingArray: (value, fallback) => Array.isArray(value) && value.length ? value : fallback, + XLSX: { ...XLSX, writeFile: (workbook, name) => downloads.push({ workbook, name }) }, + ElMessageBox: { confirm: async () => { if (options.confirm) await options.confirm(); } }, + saveStudentTrainingAnswer: async (key, payload) => saved.push({ key, payload }), + checkProductDevelopmentProcessStepTwo: async items => validations.push(plain(items)), + }; + vm.runInNewContext(script + '\nglobalThis.page={processRows,currentStep,stepOnePassed,stepTwoPassed,importingSchedule,checking,saving,downloadScheduleTemplate,importScheduleExcel,exportScheduleList,saveCurrentProgress,saveAndGoToStepThree,buildStepTwoOutcome,restoreStepTwoOutcome,getStepTwoValidationMessage};', context); + const page = context.page; + page.currentStep.value = 2; + page.stepOnePassed.value = true; + page.processRows.value.forEach((row, index) => { row.classification = index % 2 ? '非关键任务' : '关键任务'; }); + return { page, saved, downloads, messages, validations }; +} + +function workbookBytes(rows, bookType = 'xlsx', date1904 = false) { + const workbook = XLSX.utils.book_new(); + XLSX.utils.book_append_sheet(workbook, XLSX.utils.aoa_to_sheet(rows), 'WBS排期表'); + workbook.Workbook = { WBProps: { date1904 } }; + return XLSX.write(workbook, { type: 'buffer', bookType }); +} +function event(bytes, name = '排期.xlsx') { + return { target: { value: name, files: [{ name, size: bytes.length, arrayBuffer: async () => bytes }] } }; +} +const headers = ['任务编号', '开始时间', '完成时间', '项目依赖关系']; + +test('WBS Excel imports real xls and xlsx dates by task number and saves existing payloads', async () => { + for (const bookType of ['xls', 'xlsx']) { + const { page, saved, validations } = await harness(); + const before = plain(page.processRows.value); + const data = [['完成时间', '是否关键任务', '任务编号', '项目依赖关系', '开始时间'], + ...before.map((row, index) => [index === 0 ? 46325 : '2026/10/29', '修改分类也不生效', row.taskNo, '开始-开始(SS)', index === 0 ? 46315 : '2026年10月20日']).reverse()]; + const input = event(workbookBytes(data, bookType), '排期.' + bookType); + await page.importScheduleExcel(input); + assert.equal(input.target.value, ''); + assert.equal(saved.length, 0, 'Import does not submit answers'); + assert.equal(page.currentStep.value, 2); + assert.equal(page.processRows.value[0].startDate, '2026-10-20'); + assert.equal(page.processRows.value[0].endDate, '2026-10-30'); + assert.equal(page.getStepTwoValidationMessage(), ''); + page.processRows.value.forEach((row, index) => { + assert.equal(row.classification, before[index].classification); + assert.equal(row.task, before[index].task); + assert.equal(row.stage, before[index].stage); + assert.equal(row.taskNo, before[index].taskNo); + }); + await page.saveCurrentProgress(); + const payload = saved[0]; + assert.equal(payload.key, 'product-development-process'); + assert.equal(payload.payload.currentStep, 2); + const restored = await harness(); + restored.page.restoreStepTwoOutcome(payload.payload.step2Answer); + assert.equal(restored.page.processRows.value[0].startDate, '2026-10-20'); + assert.equal(restored.page.processRows.value[0].dependency, '开始-开始(SS)'); + await page.saveAndGoToStepThree(); + assert.equal(validations.length, 1); + assert.equal(validations[0].length, 19); + assert.equal(page.currentStep.value, 3); + } +}); + +test('WBS Excel template is blank and the existing exported list can be imported', async () => { + const { page, downloads } = await harness(); + page.processRows.value[0].startDate = '2026-10-20'; + page.processRows.value[0].endDate = '2026-10-21'; + page.processRows.value[0].dependency = '无前置任务'; + page.downloadScheduleTemplate(); + const template = downloads[0].workbook; + assert.deepEqual(template.SheetNames, ['WBS排期表', '填写说明']); + const rows = XLSX.utils.sheet_to_json(template.Sheets.WBS排期表, { header: 1, defval: '' }); + assert.equal(rows.length, 20); + assert.deepEqual(rows[0], ['阶段','任务编号','具体工作任务','是否关键任务','开始时间','完成时间','项目依赖关系']); + assert.ok(rows.slice(1).every(row => row.slice(4).every(value => value === ''))); + assert.equal(rows[1][3], '关键任务'); + page.exportScheduleList(); + const bytes = XLSX.write(downloads[1].workbook, { type: 'buffer', bookType: 'xlsx' }); + page.processRows.value[0].startDate = '2026-09-01'; + await page.importScheduleExcel(event(bytes)); + assert.equal(page.processRows.value[0].startDate, '2026-10-20'); + assert.equal(page.processRows.value[0].dependency, '无前置任务'); +}); + +test('WBS Excel rejects bad rows atomically and preserves tasks not imported', async () => { + const { page } = await harness(); + page.processRows.value[1].startDate = '2026-09-01'; + const before = plain(page.processRows.value); + const invalid = [ + [headers, ['1.1','2026-02-29','2026-03-01','SS']], + [headers, ['1.1','2026-10-22','2026-10-20','SS']], + [headers, ['9.9','2026-10-20','2026-10-21','SS']], + [headers, ['1.1','2026-10-20','2026-10-21','SS'], ['1.1','','','']], + [headers, ['1.1','20/10/2026','','']], + [headers, ['1.1','2026-10-20','','x'.repeat(101)]], + [headers, ['','2026-10-20','','']], + [['任务编号','开始时间','开始日期','完成时间','项目依赖关系'], ['1.1','','','','']], + [['任务编号','开始时间','完成时间'], ['1.1','','']], + [headers], + ]; + for (const bad of invalid) { + const rows = bad[0] === headers ? [headers, ['1.2','2026-10-20','2026-10-21','SS'], ...bad.slice(1)] : bad; + // Header-only file should also be rejected rather than importing the valid prefix. + await page.importScheduleExcel(event(workbookBytes(bad.length === 1 ? bad : rows))); + assert.deepEqual(plain(page.processRows.value), before); + } + await page.importScheduleExcel(event(workbookBytes([[], ['完成日期','任务编号','开始日期','项目依赖关系'], [], ['2026.10.21',1.1,'2026-10-20','无前置任务']]))); + assert.equal(page.processRows.value[0].startDate, '2026-10-20'); + assert.deepEqual(plain(page.processRows.value[1]), before[1]); + await page.importScheduleExcel(event(workbookBytes([headers, ['1.1','','','']]))); + assert.equal(page.processRows.value[0].startDate, ''); +}); + +test('WBS Excel cancellation, prerequisite and concurrent edit guards preserve the page', async () => { + const bytes = workbookBytes([headers, ['1.1','2026-10-20','2026-10-21','SS']]); + const cancel = await harness({ confirm: async () => { throw 'cancel'; } }); + const original = plain(cancel.page.processRows.value); + await cancel.page.importScheduleExcel(event(bytes)); + assert.deepEqual(plain(cancel.page.processRows.value), original); + assert.deepEqual(cancel.messages, []); + const options = {}; + const state = await harness(options); + options.confirm = async () => { state.page.processRows.value[0].dependency = '用户刚填写'; }; + await state.page.importScheduleExcel(event(bytes)); + assert.equal(state.page.processRows.value[0].dependency, '用户刚填写'); + assert.equal(state.page.processRows.value[0].startDate, ''); + options.confirm = async () => { state.page.currentStep.value = 3; }; + await state.page.importScheduleExcel(event(bytes)); + assert.equal(state.page.processRows.value[0].startDate, ''); + state.page.currentStep.value = 2; + state.page.stepOnePassed.value = false; + options.confirm = async () => { throw Error('Prerequisite guard did not run'); }; + const blocked = event(bytes); blocked.target.files[0].arrayBuffer = async () => { throw Error('File should not be read'); }; + await state.page.importScheduleExcel(blocked); + assert.equal(blocked.target.value, ''); + state.page.stepOnePassed.value = true; + const invalidFile = event(bytes, 'data.csv'); + await state.page.importScheduleExcel(invalidFile); + const oversized = event(bytes); oversized.target.files[0].size = 6 * 1024 * 1024; + await state.page.importScheduleExcel(oversized); + assert.equal(state.page.processRows.value[0].startDate, ''); + assert.equal(state.page.importingSchedule.value, false); +}); + +test('WBS Excel accepts leap dates and both Excel date systems without timezone shifts', async () => { + const { parseScheduleDate } = await helpers; + const options = { parseDateCode: XLSX.SSF.parse_date_code }; + assert.equal(parseScheduleDate('2028-2-29','日期:',options), '2028-02-29'); + assert.equal(parseScheduleDate(46315,'日期:',options), '2026-10-20'); + assert.equal(parseScheduleDate(0,'日期:',{...options,date1904:true}), '1904-01-01'); + assert.throws(() => parseScheduleDate(60,'日期:',options), /日期不存在/); + assert.throws(() => parseScheduleDate(46315.5,'日期:',options), /不要包含时间/); + for (const value of ['2026-04-31','2026-13-01','0000-01-01','2026-00-00','not-a-date']) assert.throws(() => parseScheduleDate(value,'日期:',options)); + for (const date1904 of [false,true]) { + const state = await harness(); + const start = 46315 - (date1904 ? 1462 : 0); + await state.page.importScheduleExcel(event(workbookBytes([headers,['1.1',start,start+1,'SS']], 'xlsx', date1904))); + assert.equal(state.page.processRows.value[0].startDate, '2026-10-20'); + } +}); + +test('WBS Excel controls compile inside step two with the prerequisite restriction', () => { + const descriptor = parse(source).descriptor; + compileScript(descriptor, { id: 'wbs-excel' }); + assert.deepEqual(compileTemplate({ source: descriptor.template.content, filename, id: 'wbs-excel' }).errors, []); + const start = source.indexOf(''); + const end = source.indexOf(''); + for (const handler of ['downloadScheduleTemplate','importScheduleExcel']) { + const index = source.indexOf(handler); + assert.ok(index > start && index < end); + } + assert.match(source.slice(start,end), /:disabled="!hasCompletedStepOne \|\| checking \|\| saving \|\| importingSchedule"/); +});
试产加权总分 = Σ(评分 × 试产权重) · 量产加权总分 = Σ(评分 × 量产权重)