You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
dianshang-qianduan/tests/numeric-training-excel.test...

873 lines
55 KiB
JavaScript

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 Vue = require('vue');
const XLSX = require('xlsx');
const { parse, compileScript, compileTemplate } = require('@vue/compiler-sfc');
const babel = require('@babel/parser');
const helperPath = path.resolve(__dirname, '../src/views/training/numericTableExcel.mjs');
const helpers = import(require('node:url').pathToFileURL(helperPath).href);
const plain = value => JSON.parse(JSON.stringify(value));
const pages = {
'channel/index': [1, 3, 4], 'channel/supplier': [1, 2],
'product/hardware-cost': [1, 2, 3], 'product/price': [1, 2, 3, 4],
'test/index': [1, 2, 4], 'test/promotion': [1, 3],
'demand/feature-conversion': [2], 'assessment/diagnosis': [1, 3],
'demand/business-feasibility': [1], 'product/market-opportunity-selection': [2, 3, 5],
'assessment/index': [1], 'training/GenericTrainingPage': [2, 4, 6, 7, 8, 9],
'portraitModel/components/funnelAnalysis': [1],
'digitalMarketingAlgorithms/components/descriptiveStatistics': [1],
};
test('numeric Excel pricing accepts teacher markups and enforces the raised channel limits', async () => {
const h = await helpers;
const state = await harness('product/price');
state.unitCost.value = '112';
const table = state.numericExcelTables.value[0];
const rows = h.templateRows(table);
const column = table.columns.findIndex(item => item.key === 'markupRate') + 1;
['20%', '160%', '260%'].forEach((rate, index) => { rows[index + 1][column] = rate; });
table.apply(h.parseTableRows(rows, table).rows);
assert.equal(state.validateStepOne(), '');
assert.deepEqual(plain(state.pricingRows.value.map(row => state.formatMoney(state.salePrice(row)))), ['134.40', '291.20', '403.20']);
const saved = plain(state.buildStepOneProgress());
const restored = await harness('product/price');
restored.applyStepOneProgress(saved);
assert.equal(restored.validateStepOne(), '');
assert.equal(restored.pricingRows.value[1].markupRate, '160');
assert.equal(restored.pricingRows.value[2].markupRate, '260');
assert.match(restored.rateHint(restored.pricingRows.value[1]), /40%-200%/);
assert.match(restored.rateHint(restored.pricingRows.value[2]), /70%-300%/);
for (const rates of [[20, 40, 70], [25, 200, 300], [20, 199.99, 299.99]]) {
rates.forEach((rate, index) => { restored.pricingRows.value[index].markupRate = String(rate); });
assert.equal(restored.validateStepOne(), '');
}
for (const [index, rate] of [[0, 14.99], [0, 25.01], [1, 39.99], [1, 200.01], [2, 69.99], [2, 300.01]]) {
[20, 160, 260].forEach((valid, i) => { restored.pricingRows.value[i].markupRate = String(valid); });
restored.pricingRows.value[index].markupRate = String(rate);
assert.notEqual(restored.validateStepOne(), '');
}
});
test('pricing demo uses the same raised markup limits and sale price calculation', async () => {
const source = fs.readFileSync(path.resolve(__dirname, '../src/api/studentTrainingAnswer.js'), 'utf8');
const fn = babel.parse(source, { sourceType: 'module' }).program.body
.find(node => node.type === 'ExportNamedDeclaration' && node.declaration?.id?.name === 'validateProductPricingStepOne').declaration;
const context = { isStudentDemo: () => true };
vm.runInNewContext(source.slice(fn.start, fn.end), context);
const payload = rates => ({ unitCost: 112, pricingRows: ['dealer', 'direct-retail', 'premium-brand'].map((id, index) => ({ id, markupRate: rates[index] })) });
const result = await context.validateProductPricingStepOne(payload([20, 160, 260]));
assert.deepEqual(plain(result.data.pricingRows.map(row => row.salePrice)), [134.4, 291.2, 403.2]);
assert.equal((await context.validateProductPricingStepOne(payload([25, 200, 300]))).data.valid, true);
for (const rates of [[26, 160, 260], [20, 200.01, 260], [20, 160, 300.01]]) {
await assert.rejects(context.validateProductPricingStepOne(payload(rates)));
}
});
async function harness(page, overrides = {}) {
const helper = await helpers;
const stepAnswers = await import("../src/views/training/trainingStepAnswers.mjs");
const filename = path.resolve(__dirname, '../src/views/' + page + '.vue');
const descriptor = parse(fs.readFileSync(filename, 'utf8')).descriptor;
compileScript(descriptor, { id: 'numeric-excel' });
assert.deepEqual(compileTemplate({ source: descriptor.template.content, filename, id: 'numeric-excel' }).errors, []);
let script = descriptor.scriptSetup.content;
const nodes = babel.parse(script, { sourceType: 'module' }).program.body;
const names = [];
const context = { ...Vue, console, setTimeout, clearTimeout,
onMounted() {}, onBeforeUnmount() {}, onUnmounted() {}, watch() {}, watchEffect() {},
getCurrentInstance: () => ({ proxy: { $modal: {} } }),
useRoute: () => ({ meta: { pageKey: 'comprehensive-case-training' }, params: {} }),
defineProps: () => ({ previewTaskKey: '' }),
};
for (const node of nodes) {
if (node.type === 'ImportDeclaration') {
for (const specifier of node.specifiers) {
const local = specifier.local.name;
const imported = specifier.imported?.name;
if (node.source.value === 'vue') context[local] = context[imported];
else if (node.source.value.includes('numericTableExcel')) context[local] = helper[imported];
else if (node.source.value.includes('trainingStepAnswers')) context[local] = stepAnswers[imported];
else if (local === 'getUserInfo') context[local] = () => '{}';
else if (local === 'useAlgorithmStore') context[local] = () => ({userDataLabel: []});
else if (local === 'getStudentTrainingPage') context[local] = () => ({ fields: [], tableRows: [], processRows: [], title: '综合实训' });
else if (local === 'parseTrainingArray') context[local] = (value, fallback = []) => Array.isArray(value) && value.length ? value : fallback;
else context[local] = () => ({});
}
} else if (node.type === 'VariableDeclaration') {
for (const item of node.declarations) if (item.id.type === 'Identifier') names.push(item.id.name);
} else if (node.type === 'FunctionDeclaration') names.push(node.id.name);
}
for (const node of [...nodes].reverse()) if (node.type === 'ImportDeclaration') script = script.slice(0, node.start) + script.slice(node.end);
Object.assign(context, overrides);
script = script.replaceAll('import.meta.env.VITE_APP_BASE_API', "'/api'").replaceAll("await import('xlsx')", 'XLSX_IMPORT');
vm.runInNewContext(script + '\nglobalThis.page = {' + names.join(',') + '};', context, { filename });
return context.page;
}
for (const [page, steps] of Object.entries(pages)) test('numeric Excel round trip ' + page, async () => {
const h = await helpers;
const state = await harness(page);
if (page === 'product/market-opportunity-selection') for (const name of ['stepOnePassed','stepTwoPassed','stepFourPassed']) state[name].value = true;
if (page === 'product/hardware-cost') state.syncStepTwoRows(state.rows.value);
if (page === 'test/index') { state.syncScoreRows(); state.syncRankingRows(); }
if (page === 'test/promotion') { state.addBudgetRow(); state.budgetRows.value[0].channel = '天猫'; state.availableChannels.value = ['天猫']; state.syncPerformanceRows(); }
for (const step of steps) {
if (state.currentStep) state.currentStep.value = step;
else if (state.activeStep) state.activeStep.value = step;
else if (page === 'demand/feature-conversion') state.form.value.activeStep = step;
const tables = state.numericExcelTables.value;
assert.ok(tables.length, page + ' step ' + step);
for (const table of tables) {
assert.ok(table.rows.length, table.title + ' has rows');
table.columns.filter(column => column.readonly).forEach(column => table.rows.forEach(row => assert.notEqual(h.cellValue(row, column), undefined, table.title + ' / ' + column.label + ' exists')));
const data = h.templateRows(table);
for (let index = 1; index <= table.rows.length; index++) {
table.columns.forEach((column, ci) => {
if (column.type === 'number') data[index][ci + 1] = column.min > 0 ? column.min : 1;
});
}
// Export with the same first-sheet format as the toolbar, then read real XLS/XLSX bytes.
for (const bookType of ['xls', 'xlsx']) {
const book = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(book, XLSX.utils.aoa_to_sheet(data), '填写数据');
const read = XLSX.read(XLSX.write(book, { type: 'buffer', bookType }), { type: 'buffer' });
const rows = XLSX.utils.sheet_to_json(read.Sheets[read.SheetNames[0]], { header: 1, raw: false, defval: '', range: 0 });
const before = plain(table.rows);
const imported = h.parseTableRows(rows, table);
assert.equal(imported.count, table.rows.length, table.title);
table.apply(imported.rows);
table.columns.filter(c => c.type === 'number').forEach(column => {
const current = state.numericExcelTables.value.find(t => t.id === table.id);
current.rows.forEach(row => assert.equal(Number(h.cellValue(row, column)), column.min > 0 ? column.min : 1, table.title + ' / ' + column.label));
});
// Fields excluded from the import schema (IDs, narrative, derived classification) survive.
for (let i = 0; i < before.length; i++) {
const after = state.numericExcelTables.value.find(t => t.id === table.id).rows[i];
if ('id' in before[i]) assert.equal(after.id, before[i].id);
}
}
}
}
});
test('promotion restores latest third-step ROI instead of stale evaluation ROI and submits it', async () => {
const channels=['抖音','天猫','唯品会'],rois=[1.3,1.68,1.8],writes=[],errors=[];
const evaluation=channels.map((channel,index)=>({channel,roi:index<2?1:1.8,achievement:index===0?'不达标':'达标',problemDiagnosis:index===0?'获客成本过高':'',optimizationAction:index===0?'优化素材与出价':''}));
const answer={currentStep:4,step1Answer:JSON.stringify({totalBudget:150000,rows:channels.map(channel=>({channel}))}),
step3Answer:JSON.stringify({grossMargin:68,breakEvenRoi:1.47,rows:[...channels.map((channel,index)=>({channel,actualRoi:rois[index]})),{channel:'合计',actualRoi:1.45}]}),
step4Answer:JSON.stringify({rows:evaluation,optimizationDecision:'优先优化抖音渠道'})};
const state=await harness('test/promotion',{
getStudentTrainingAnswer:async()=>({data:answer}),
validatePromotionEffectOptimizationStepFour:async payload=>{assert.deepEqual(plain(payload.rows.map(row=>row.roi)),rois);},
saveStudentTrainingAnswer:async(key,payload)=>writes.push({key,payload}),
ElMessage:{success(){},error:message=>errors.push(message)},
});
await state.loadProgress();
assert.deepEqual(plain(state.evaluationRows.value.map(row=>row.roi)),rois);
assert.equal(state.evaluationRows.value[0].problemDiagnosis,evaluation[0].problemDiagnosis);
assert.equal(state.evaluationRows.value[0].optimizationAction,evaluation[0].optimizationAction);
assert.equal(state.evaluationRows.value[1].achievement,'达标');
assert.equal(state.optimizationDecision.value,'优先优化抖音渠道');
await state.submitTask();
assert.deepEqual(errors,[]);assert.equal(writes.length,1);
assert.equal(writes[0].payload.saveAction,'SUBMIT');
assert.deepEqual(JSON.parse(writes[0].payload.step4Answer).rows.map(row=>row.roi),rois);
});
test('promotion revalidating third step refreshes ROI while keeping evaluation answers', async () => {
const writes=[];
const state=await harness('test/promotion',{
validatePromotionEffectOptimizationStepThree:async()=>({}),
saveStudentTrainingAnswer:async(key,payload)=>writes.push(payload),
ElMessage:{success(){},error:message=>assert.fail(message)},
});
state.performanceRows.value=[{channel:'抖音',actualRoi:1.3},{channel:'天猫',actualRoi:1.68},{channel:'合计',actualRoi:1.45}];
state.evaluationRows.value=[{channel:'天猫',roi:1,achievement:'达标'}, {channel:'抖音',roi:1,achievement:'不达标',problemDiagnosis:'成本过高',optimizationAction:'优化出价'}];
await state.validatePerformance();
assert.equal(state.activeStep.value,4);
assert.equal(writes.length,1);assert.ok(writes[0].step3Answer);
assert.deepEqual(plain(state.evaluationRows.value.map(row=>row.roi)),[1.3,1.68]);
assert.equal(state.evaluationRows.value[0].problemDiagnosis,'成本过高');
assert.equal(state.evaluationRows.value[1].achievement,'达标');
});
test('promotion evaluation payload follows current channels and preserves zero ROI', async () => {
const state=await harness('test/promotion');
state.performanceRows.value=[{channel:'天猫',actualRoi:0},{channel:'京东',actualRoi:undefined},{channel:'合计',actualRoi:1}];
state.evaluationRows.value=[{channel:'天猫',roi:9,achievement:'不达标',problemDiagnosis:'无成交',optimizationAction:'调整素材'},{channel:'京东',roi:2},{channel:'旧渠道',roi:3}];
const payload=state.evaluationPayload();
assert.deepEqual(plain(payload.rows.map(row=>row.channel)),['天猫','京东']);
assert.equal(payload.rows[0].roi,0);assert.equal(payload.rows[1].roi,undefined);
assert.equal(payload.rows[0].problemDiagnosis,'无成交');
});
test('numeric Excel validates the entire file before mutation', async () => {
const h = await helpers;
const rows = [{ id: 'a', name: '天猫', count: 4, rate: 6, note: '保留' }, { id: 'b', name: '京东', count: 8, rate: 9 }];
const table = h.excelTable('x', '数据', rows, [h.fixedColumn('name', '渠道'), h.numberColumn('count', '数量', {precision: 0}), h.rateColumn('rate', '占比(%)', {precision: 2})]);
const before = JSON.stringify(rows);
const header = ['序号','渠道','数量','占比(%)'];
for (const bad of ['abc', '-1', '1.2', '1e3', '1,2', '=1+2']) {
assert.throws(() => h.parseTableRows([header,[1,'天猫',12,25],[2,'京东',bad,15]], table));
assert.equal(JSON.stringify(rows), before);
}
for (const invalid of [
[header,[1,'天猫',1,'101%']], [header,[1,'天猫',1,'1.001']],
[header,[1,'天猫',1,5],[1,'天猫',2,6]], [header,[3,'未知',1,5]],
[header,[1,'已改名',1,5]], [['序号','渠道','数量'],[1,'天猫',1]],
[['序号','渠道','数量','数量','占比(%)'],[1,'天猫',1,2,5]],
]) assert.throws(() => h.parseTableRows(invalid, table));
const accepted = h.parseTableRows([[], ['占比(%)','数量','渠道','序号'], ['25%','1,200','京东',2], [], ['0','0','天猫',1]], table);
table.apply(accepted.rows);
assert.equal(rows[1].count,1200); assert.equal(rows[1].rate,25); assert.equal(rows[0].count,0);
assert.equal(rows[0].note,'保留'); assert.equal(rows[0].id,'a');
});
test('numeric Excel cancel and stale imports preserve current work', async () => {
const h = await helpers;
const rows = [{ name:'物料', amount:3 }];
const table = h.excelTable('x','物料',rows,[h.textColumn('name','名称'),h.numberColumn('amount','金额')]);
const file = {name:'data.xlsx',size:10};
const readWorkbook = async () => [['序号','名称','金额'],[1,'物料',99]];
await assert.rejects(h.importTableFile(file,table,{readWorkbook,confirm:async()=>{throw Error('cancel');},isCurrent:()=>true}));
assert.equal(rows[0].amount,3);
await assert.rejects(h.importTableFile(file,table,{readWorkbook,confirm:async()=>{},isCurrent:()=>false}),/已变化/);
assert.equal(rows[0].amount,3);
await assert.rejects(h.importTableFile(file,table,{readWorkbook,confirm:async()=>{rows[0].amount=8;},isCurrent:()=>true}),/已变化/);
assert.equal(rows[0].amount,8);
await assert.rejects(h.importTableFile({...file,name:'data.csv'},table,{readWorkbook}),/xls/);
await assert.rejects(h.importTableFile({...file,size:6*1024*1024},table,{readWorkbook}),/5MB/);
});
test('numeric Excel adds BOM rows without importing computed values', async () => {
const h = await helpers;
const state = await harness('product/hardware-cost');
const table = state.numericExcelTables.value[0];
const rows = h.templateRows(table);
assert.equal(rows.length,11);
assert.ok(!rows[0].includes('金额(元)'));
for (let i=1;i<=10;i++) rows[i]=[i,'物料'+i,'规格',i===1?'1,200.50':'2',2];
const result=h.parseTableRows(rows,table); table.apply(result.rows);
assert.equal(state.rows.value.length,10);
assert.equal(state.rowAmount(state.rows.value[0]),2401);
const bad=h.templateRows(table); bad.push([41,'超行','规格',1,1]);
assert.throws(()=>h.parseTableRows(bad,table));
assert.equal(state.rows.value.length,10);
});
test('numeric Excel toolbar downloads a blank workbook and imports through confirmation', async () => {
const h = await helpers;
const rows = [{id:'keep-id',name:'天猫',rate:66,note:'原有分析'}];
const tables = [h.excelTable('rates','渠道占比',rows,[h.fixedColumn('name','渠道'),h.rateColumn('rate','占比(%)')])];
const props = Vue.reactive({tables,contextKey:1,disabled:false});
const downloads=[], errors=[], successes=[];
let confirm=true;
const component = await harness('components/TrainingExcelTools',{
defineProps:()=>props,
XLSX_IMPORT:{...XLSX,writeFile:(workbook,name)=>downloads.push({workbook,name})},
ElMessage:{error:m=>errors.push(m),success:m=>successes.push(m)},
ElMessageBox:{confirm:async()=>{if(!confirm)throw 'cancel';}},
});
await component.downloadTemplate();
assert.equal(downloads.length,1);
const book=downloads[0].workbook;
const sheet=book.Sheets[book.SheetNames[0]];
assert.deepEqual(XLSX.utils.sheet_to_json(sheet,{header:1,defval:''}),[['序号','渠道','占比(%)'],[1,'天猫','']]);
sheet.C2={t:'s',v:'25%'};
const bytes=XLSX.write(book,{type:'buffer',bookType:'xlsx'});
const event=()=>({target:{value:'file',files:[{name:'rates.xlsx',size:bytes.length,arrayBuffer:async()=>bytes}]}});
confirm=false; await component.importFile(event()); assert.equal(rows[0].rate,66);
confirm=true; const input=event(); await component.importFile(input);
assert.equal(input.target.value,''); assert.equal(rows[0].rate,25);
assert.equal(rows[0].id,'keep-id'); assert.equal(rows[0].note,'原有分析');
assert.equal(successes.length,1); assert.deepEqual(errors,[]);
props.disabled=true; await component.importFile(event()); assert.equal(successes.length,1);
});
test('numeric Excel preserves percentage semantics and clears existing scalar rows', async () => {
const h=await helpers;
const state=await harness('training/GenericTrainingPage'); state.currentStep.value=4;
const table=state.numericExcelTables.value[0];
const rows=h.templateRows(table);
rows[1]=[1,'功能',1,1,'1%',1];
table.apply(h.parseTableRows(rows,table).rows);
assert.equal(state.comprehensiveStepFour.value.riceRows[0].confidence,'0.01');
assert.equal(state.comprehensiveRiceScore(state.comprehensiveStepFour.value.riceRows[0]),'0.0');
const scalar=[{value:8}];
const scalarTable=h.excelTable('scalar','数值',scalar,[h.numberColumn('value','数值')]);
scalarTable.apply(h.parseTableRows([['序号','数值'],[1,'']],scalarTable).rows);
assert.equal(scalar[0].value,undefined);
const efficacy=await harness('assessment/index');
const weight=efficacy.numericExcelTables.value[1];
const input=h.templateRows(weight); input[1]=[1,'商品采购合格率','30%',24];
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.directive('trainingFillHints', {});
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(toolbar<html.indexOf('class="bom-table-wrap"'));
assert.equal((html.match(/data-test-excel=/g)||[]).length,1);
assert.match(html,/单价(元)/); assert.match(html,/金额(元)/);
const batch=await render(2);
const batchTools=batch.indexOf('data-test-excel="batch"');
assert.ok(batchTools>batch.indexOf('100 台与 10000 台单台成本'));
assert.ok(batchTools<batch.indexOf('class="bom-table-wrap"'));
assert.match(batch,/小批量 100 台(元\/台)/); assert.match(batch,/大批量 10000 台(元\/台)/);
for (const step of [2,3]) assert.equal(((await render(step)).match(/data-test-excel=/g)||[]).length,1);
});
test('numeric Excel BOM batch costs import 16 materials and save without changing constraints or step one', async () => {
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.directive('trainingFillHints', {});
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<html.indexOf('class="table-scroll"'));
assert.equal((html.match(/data-test-excel=/g)||[]).length,1);
assert.match(html,/维度评分(0–10 分)/);
assert.equal(((await render(1)).match(/data-test-excel=/g)||[]).length,1);
assert.equal(((await render(3)).match(/data-test-excel=/g)||[]).length,0);
});
test('numeric Excel ignores a pending import after its table controls unmount', async () => {
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 editable 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.equal(state.numericExcelTables.value[0].columns[0].readonly, undefined);
const instructions=XLSX.utils.sheet_to_json(workbook.Sheets['填写说明'],{header:1,defval:''});
assert.equal(instructions.find(row=>row[0]==='价格区间')[1],'填写文本');
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 importedRanges=['≤599元','599~699元','699~799元','799~899元','899~999元','≥999元'];
const data=[template[0],...values.map((r,i)=>[i+1,importedRanges[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,importedRanges[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);
assert.deepEqual(plain(restored.psmRows.value.map(row=>row.priceRange)), importedRanges);
}
});
test('numeric Excel PSM rejects invalid percentages and accepts changed price ranges atomically', 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);
}
const edited=h.parseTableRows([header,[1,'399~599元',5,6,7,8]],table);
assert.equal(edited.rows[0].priceRange,'399~599元');
assert.equal(JSON.stringify(state.psmRows.value),before);
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('pricing demo accepts editable PSM ranges and still rejects blank or duplicate ranges', async () => {
const source=fs.readFileSync(path.resolve(__dirname,'../src/api/studentTrainingAnswer.js'),'utf8');
const fn=babel.parse(source,{sourceType:'module'}).program.body
.find(node=>node.type==='ExportNamedDeclaration' && node.declaration?.id?.name==='validateProductPricingStepFour').declaration;
const context={isStudentDemo:()=>true};
vm.runInNewContext(source.slice(fn.start,fn.end),context);
const state=await harness('product/price');
const psmRows=plain(state.psmRows.value).map((row,index)=>({...row,priceRange:`${500+index*100}~${600+index*100}元`,tooExpensive:20,tooCheap:30,expensiveAcceptable:40,cheapValue:50}));
const payload={psmRows,pricePoints:{optimalPrice:599,acceptablePrice:699,acceptableRange:'499~799元'}};
const result=await context.validateProductPricingStepFour(payload);
assert.deepEqual(plain(result.data.psmRows.map(row=>row.priceRange)),psmRows.map(row=>row.priceRange));
for(const label of ['',psmRows[1].priceRange]) {
const invalid=plain(payload);invalid.psmRows[0].priceRange=label;
await assert.rejects(context.validateProductPricingStepFour(invalid));
}
const invalid=plain(payload);invalid.psmRows[0].tooExpensive=100.01;
await assert.rejects(context.validateProductPricingStepFour(invalid));
});
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.directive('trainingFillHints', {});
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<html.indexOf('class="table-scroll"'));
assert.equal((html.match(/data-test-excel=/g)||[]).length,1);
assert.match(html,/价格(元)/); assert.match(html,/累计占比(%)/);
assert.equal((html.match(/aria-label="价格(元)"/g)||[]).length,6);
state.psmRows.value[0].priceRange='≤599元';
assert.ok((await render(4)).includes('value="≤599元"'));
for(const step of [1,2,3]) assert.equal(((await render(step)).match(/data-test-excel=/g)||[]).length,1);
});
test('numeric Excel diagnosis imports current channel rates and industry averages through save and validation', async () => {
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.directive('trainingFillHints', {});
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(funnel<html.indexOf('class="table-wrap"'));
assert.ok(anomaly>html.indexOf('定位异常节点'));
assert.ok(anomaly<html.indexOf('class="diagnosis-table"'));
assert.equal((html.match(/data-test-excel=/g)||[]).length,2);
assert.match(html,/class="unit">%/);
assert.equal(((await render(2)).match(/data-test-excel=/g)||[]).length,0);
assert.match(await render(3),/data-test-excel="ab"/);
});