|
|
|
|
|
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],
|
|
|
|
|
|
};
|
|
|
|
|
|
|
|
|
|
|
|
async function harness(page, overrides = {}) {
|
|
|
|
|
|
const helper = await helpers;
|
|
|
|
|
|
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 (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('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);
|
|
|
|
|
|
});
|