const assert = require('node:assert/strict'); const fs = require('node:fs'); const path = require('node:path'); const vm = require('node:vm'); const test = require('node:test'); const Vue = require('vue'); const { parse, compileScript, compileTemplate } = require('@vue/compiler-sfc'); const babel = require('@babel/parser'); const filename = path.resolve(__dirname, '../src/views/product/market-opportunity-selection.vue'); const source = fs.readFileSync(filename, 'utf8'); const apiSource = fs.readFileSync(path.resolve(__dirname, '../src/api/studentTrainingAnswer.js'), 'utf8'); const plain = value => JSON.parse(JSON.stringify(value)); async function pageHarness(overrides = {}) { const helper = await import('../src/views/training/numericTableExcel.mjs'); const descriptor = parse(source).descriptor; compileScript(descriptor, { id: 'decimal-weights' }); assert.deepEqual(compileTemplate({ source: descriptor.template.content, filename, id: 'decimal-weights' }).errors, []); let script = descriptor.scriptSetup.content; const nodes = babel.parse(script, { sourceType: 'module' }).program.body; const names = nodes.flatMap(node => node.type === 'VariableDeclaration' ? node.declarations.filter(item => item.id.type === 'Identifier').map(item => item.id.name) : node.type === 'FunctionDeclaration' ? [node.id.name] : []); const context = { ...Vue, onMounted() {}, getCurrentInstance: () => ({ proxy: { $modal: {} } }) }; for (const node of nodes.filter(node => node.type === 'ImportDeclaration')) { for (const specifier of node.specifiers) { context[specifier.local.name] = node.source.value === 'vue' ? Vue[specifier.imported.name] : node.source.value.includes('numericTableExcel') ? helper[specifier.imported.name] : () => ({}); } } for (const node of [...nodes].reverse().filter(node => node.type === 'ImportDeclaration')) { script = script.slice(0, node.start) + script.slice(node.end); } Object.assign(context, overrides); vm.runInNewContext(script + '\nglobalThis.page = {' + names.join(',') + '};', context, { filename }); return context.page; } function demoCheck() { const node = babel.parse(apiSource, { sourceType: 'module' }).program.body.find(node => node.type === 'ExportNamedDeclaration' && node.declaration?.id?.name === 'checkMarketOpportunitySelectionStepTwo'); return vm.runInNewContext('(' + apiSource.slice(node.declaration.start, node.declaration.end) + ')', { isStudentDemo: () => true }); } function fillScreenshot(page) { page.primaryWeights.value = { '市场规模': 40, '市场潜力': 15, '竞争强度': 25, '运营难度': 20 }; page.weights.value = Object.fromEntries(page.indicators.map((item, index) => [item.id, [50, 50, 53.33, 46.67, 36, 32, 32, 60, 40][index]])); page.stepOnePassed.value = true; } function payload(page) { return { primaryWeights: page.categories.map(group => ({ group, weight: page.primaryWeights.value[group] })), dimensionWeights: page.indicators.map(item => ({ id: item.id, weight: page.weights.value[item.id] })), }; } test('截图中的小数权重可以校验、保存、进入下一步并回填', async () => { let saved; const page = await pageHarness({ checkMarketOpportunitySelectionStepTwo: demoCheck(), saveStudentTrainingAnswer: async (key, answer) => { saved = answer; }, }); fillScreenshot(page); assert.equal(page.isStepTwoReady(), true); assert.equal(page.primaryWeightTotal.value, 100); assert.equal(page.correspondingWeightTotal.value, 100); assert.equal(page.dimensionWeightTotal('市场潜力'), 100); await page.saveAndGoToStepThree(); assert.equal(page.currentStep.value, 3); assert.equal(JSON.parse(saved.step2Answer).dimensionWeights['transaction-growth'], 53.33); assert.equal(JSON.parse(saved.step2Answer).correspondingWeights['transaction-growth'], 7.9995); const restored = await pageHarness({ getStudentTrainingAnswer: async () => ({ data: { ...saved, step1Answer: JSON.stringify({ answers: Object.fromEntries(page.indicators.map(item => [item.id, item.group])) }), } }) }); await restored.loadSavedAnswer(); assert.equal(restored.weights.value['transaction-growth'], 53.33); assert.equal(restored.weights.value['category-transaction-growth'], 46.67); assert.equal(restored.stepTwoPassed.value, true); assert.equal(restored.currentStep.value, 3); }); test('一级小数和三项小数合计精确通过,逐项显示舍入不影响总计', async () => { const page = await pageHarness(); fillScreenshot(page); page.primaryWeights.value = { '市场规模': 30.01, '市场潜力': 29.99, '竞争强度': 20, '运营难度': 20 }; for (const [id, value] of [['demand-supply-ratio', 33.33], ['online-products', 33.33], ['online-merchants', 33.34]]) page.weights.value[id] = value; assert.equal(page.isStepTwoReady(), true); assert.equal(page.dimensionWeightTotal('竞争强度'), 100); assert.equal(page.correspondingWeightTotal.value, 100); assert.equal((await demoCheck()(payload(page))).data.valid, true); assert.notEqual(page.indicators.reduce((sum, item) => sum + Number(page.formatWeight(page.correspondingWeight(item))), 0), 100); }); test('前端和演示接口拒绝超精度、越界、空值及合计差 0.01', async () => { const page = await pageHarness(); fillScreenshot(page); page.weights.value['transaction-growth'] = 53.333; page.weights.value['category-transaction-growth'] = 46.667; assert.equal(page.isStepTwoReady(), false); await assert.rejects(demoCheck()(payload(page))); for (const target of ['primary', 'dimension']) { for (const value of [53.333, 0.99, 100.01, null, undefined, '', NaN, Infinity]) { fillScreenshot(page); if (target === 'primary') page.primaryWeights.value['市场规模'] = value; else page.weights.value['transaction-growth'] = value; assert.equal(page.isValidWeight(value), false); assert.equal(page.isStepTwoReady(), false, target + ': ' + value); await assert.rejects(demoCheck()(payload(page))); } fillScreenshot(page); if (target === 'primary') page.primaryWeights.value['市场规模'] = 40.01; else page.weights.value['transaction-growth'] = 53.32; assert.equal(page.isStepTwoReady(), false); await assert.rejects(demoCheck()(payload(page))); } }); test('一级与二级权重 Excel 导入保留两位小数并拒绝三位小数', async () => { const helper = await import('../src/views/training/numericTableExcel.mjs'); const page = await pageHarness(); fillScreenshot(page); page.currentStep.value = 2; for (const table of page.numericExcelTables.value) { const rows = helper.templateRows(table); rows[1][2] = '53.33%'; const imported = helper.parseTableRows(rows, table); table.apply(imported.rows); const values = table.id === 'primary' ? page.primaryWeights.value : page.weights.value; assert.ok(Object.values(plain(values)).includes(53.33)); rows[1][2] = '53.333%'; assert.throws(() => helper.parseTableRows(rows, table), /最多允许 2 位小数/); } }); test('整数权重仍可校验通过', async () => { const page = await pageHarness(); fillScreenshot(page); page.weights.value['transaction-growth'] = 53; page.weights.value['category-transaction-growth'] = 47; assert.equal(page.isStepTwoReady(), true); assert.equal((await demoCheck()(payload(page))).data.valid, true); });