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('