feat(training): add WBS Excel import and place table import controls

dev-QQq
chenyuan 1 month ago
parent 7fbf5c00c7
commit e621f212f3

@ -35,8 +35,7 @@
"0") }}</span><span class="step-copy"><b class="step-name">{{ step }}</b></span></button><span
v-if="index < trainingSteps.length - 1" class="step-connector"
aria-hidden="true" /></template></nav>
<TrainingExcelTools :tables="numericExcelTables" :context-key="currentStep" :disabled="saving" />
<TrainingExcelTools v-if="currentStep !== 1" :tables="numericExcelTables" :context-key="currentStep" :disabled="saving" />
<template v-if="currentStep === 1">
<header class="step-heading">
@ -56,6 +55,9 @@
<span>链路节点和行业均值固定,中间渠道可按案例数据增加或删除。</span>
<button type="button" class="table-button" @click="addFunnelChannel">增加渠道</button>
</div>
<TrainingExcelTools :tables="numericExcelTables.filter(table => table.id === 'funnel')"
:context-key="currentStep" :disabled="saving" />
<div class="table-wrap">
<table class="funnel-table">
<thead>
@ -128,6 +130,9 @@
@click="addAnomalyRow">增加一行</button><button type="button" class="table-button ghost"
:disabled="anomalyRows.length <= 1" @click="removeAnomalyRow">删除一行</button></div>
</div>
<TrainingExcelTools :tables="numericExcelTables.filter(table => table.id === 'anomaly')"
:context-key="currentStep" :disabled="saving" />
<div class="table-wrap">
<table class="diagnosis-table">
<thead>

@ -36,8 +36,7 @@
</button>
</template>
</nav>
<TrainingExcelTools :tables="numericExcelTables" :context-key="currentStep" :disabled="saving" />
<TrainingExcelTools v-if="currentStep !== 2" :tables="numericExcelTables" :context-key="currentStep" :disabled="saving" />
<template v-if="currentStep === 1">
<section class="supplier-step-card">
@ -97,6 +96,8 @@
<p>试产加权总分 = Σ(评分 × 试产权重) · 量产加权总分 = Σ(评分 × 量产权重)</p>
</div>
</div>
<TrainingExcelTools :tables="numericExcelTables" :context-key="currentStep" :disabled="saving" />
<div class="table-scroll">
<table class="training-table score-table merged-score-table">
<thead>

@ -12,13 +12,15 @@
</template>
<script setup>
import { computed, ref, watch } from 'vue';
import { computed, onBeforeUnmount, ref, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { importTableFile, templateRows } from '@/views/training/numericTableExcel.mjs';
const props = defineProps({ tables: { type: Array, default: () => [] }, contextKey: { type: [String, Number], default: '' }, disabled: Boolean });
const selectedId = ref('');
const fileInput = ref(null);
const busy = ref(false);
let mounted = true;
onBeforeUnmount(() => { mounted = false; });
const activeTable = computed(() => props.tables.find((table) => table.id === selectedId.value) || props.tables[0]);
watch(() => [props.contextKey, ...props.tables.map((table) => table.id)], () => { selectedId.value = activeTable.value?.id || ''; }, { immediate: true });
@ -49,6 +51,7 @@ async function importFile(event) {
const table = activeTable.value;
if (!file || !table || props.disabled || busy.value) return;
const context = props.contextKey;
const columns = JSON.stringify(table.columns);
busy.value = true;
try {
const count = await importTableFile(file, { ...table, apply: (next) => activeTable.value.apply(next) }, {
@ -61,7 +64,7 @@ async function importFile(event) {
return XLSX.utils.sheet_to_json(sheet, { header: 1, raw: false, defval: '', blankrows: true, range: 0 });
},
confirm: (message) => ElMessageBox.confirm(message, '确认导入', { type: 'warning', confirmButtonText: '导入', cancelButtonText: '取消' }),
isCurrent: () => !props.disabled && props.contextKey === context && activeTable.value?.id === table.id && JSON.stringify(activeTable.value.rows) === JSON.stringify(table.rows),
isCurrent: () => mounted && !props.disabled && props.contextKey === context && activeTable.value?.id === table.id && JSON.stringify(activeTable.value.columns) === columns && JSON.stringify(activeTable.value.rows) === JSON.stringify(table.rows),
});
ElMessage.success(`已导入 ${count} 行,请保存本步骤`);
} catch (error) {

@ -0,0 +1,68 @@
export const scheduleExcelHeaders = ['阶段', '任务编号', '具体工作任务', '是否关键任务', '开始时间', '完成时间', '项目依赖关系'];
export function scheduleTemplateRows(rows) {
return [scheduleExcelHeaders, ...rows.map(row => [row.stage, row.taskNo, row.task, row.classification, '', '', ''])];
}
function validDate(year, month, day, location) {
const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
const days = [31, leap ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
if (year < 1 || year > 9999 || month < 1 || month > 12 || day < 1 || day > days[month - 1]) {
throw new Error(`${location}日期不存在`);
}
return `${String(year).padStart(4, '0')}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;
}
export function parseScheduleDate(value, location, { date1904 = false, parseDateCode } = {}) {
if (value == null || String(value).trim() === '') return '';
if (typeof value === 'number') {
if (!Number.isInteger(value) || value < 0 || value > 2958465) throw new Error(`${location}请填写有效日期,不要包含时间`);
const date = parseDateCode?.(value, { date1904 });
if (!date) throw new Error(`${location}Excel 日期无效`);
return validDate(date.y, date.m, date.d, location);
}
const text = String(value).trim();
const match = /^(\d{4})([-/.])(\d{1,2})\2(\d{1,2})$/.exec(text) || /^(\d{4})年(\d{1,2})月(\d{1,2})日$/.exec(text);
if (!match) throw new Error(`${location}请使用 YYYY-MM-DD 日期格式或 Excel 日期单元格`);
const [, year, separatorOrMonth, monthOrDay, day] = match;
return day === undefined
? validDate(Number(year), Number(separatorOrMonth), Number(monthOrDay), location)
: validDate(Number(year), Number(monthOrDay), Number(day), location);
}
export function parseScheduleRows(sheetRows, currentRows, options = {}) {
const blank = value => value == null || String(value).trim() === '';
const headerIndex = sheetRows.findIndex(row => row.some(value => !blank(value)));
if (headerIndex < 0) throw new Error('Excel 中没有表头');
const aliases = { 开始日期: '开始时间', 完成日期: '完成时间', 结束日期: '完成时间', 结束时间: '完成时间' };
const headers = sheetRows[headerIndex].map(value => {
const label = String(value ?? '').replace(/\s/g, '');
return aliases[label] || label;
});
const populated = headers.filter(Boolean);
if (new Set(populated).size !== populated.length) throw new Error('Excel 表头有重复列');
const required = ['任务编号', '开始时间', '完成时间', '项目依赖关系'];
const missing = required.filter(label => !headers.includes(label));
if (missing.length) throw new Error(`缺少列:${missing.join('、')},请使用 WBS 排期模板`);
if (populated.some(label => !scheduleExcelHeaders.includes(label))) throw new Error('包含不属于 WBS 排期表的列,请使用本步骤模板');
const positions = Object.fromEntries(required.map(label => [label, headers.indexOf(label)]));
const existing = new Map(currentRows.map(row => [String(row.taskNo), row]));
const updates = new Map();
for (let index = headerIndex + 1; index < sheetRows.length; index += 1) {
const cells = sheetRows[index];
if (cells.every(blank)) continue;
if (cells.some((value, column) => !blank(value) && !headers[column])) throw new Error(`第 ${index + 1} 行包含无表头的数据`);
const taskNo = String(cells[positions['任务编号']] ?? '').trim();
if (!taskNo) throw new Error(`第 ${index + 1} 行缺少任务编号`);
if (!existing.has(taskNo)) throw new Error(`第 ${index + 1} 行任务编号 ${taskNo} 不存在`);
if (updates.has(taskNo)) throw new Error(`第 ${index + 1} 行任务编号 ${taskNo} 重复`);
const startDate = parseScheduleDate(cells[positions['开始时间']], `第 ${index + 1} 行任务 ${taskNo} 的开始时间:`, options);
const endDate = parseScheduleDate(cells[positions['完成时间']], `第 ${index + 1} 行任务 ${taskNo} 的完成时间:`, options);
if (startDate && endDate && startDate > endDate) throw new Error(`第 ${index + 1} 行任务 ${taskNo} 的完成时间不能早于开始时间`);
const dependency = String(cells[positions['项目依赖关系']] ?? '').trim();
if (dependency.length > 100) throw new Error(`第 ${index + 1} 行任务 ${taskNo} 的项目依赖关系最多 100 个字符`);
updates.set(taskNo, { startDate, endDate, dependency });
}
if (!updates.size) throw new Error('没有可导入的排期数据');
return { count: updates.size, rows: currentRows.map(row => ({ ...row, ...(updates.get(String(row.taskNo)) || {}) })) };
}

@ -95,6 +95,12 @@
<h3>{{ trainingSteps[1] }}</h3>
</div>
<div class="step-title-actions">
<button type="button" class="outline-action schedule-export-action" :disabled="importingSchedule"
@click="downloadScheduleTemplate">下载 Excel 模板</button>
<button type="button" class="outline-action schedule-export-action"
:disabled="!hasCompletedStepOne || checking || saving || importingSchedule"
@click="scheduleExcelInput?.click()">{{ importingSchedule ? '导入中…' : '导入 Excel' }}</button>
<input ref="scheduleExcelInput" type="file" hidden accept=".xls,.xlsx" @change="importScheduleExcel" />
<button type="button" class="outline-action schedule-export-action"
@click="exportScheduleList"><el-icon>
<Download />
@ -104,6 +110,7 @@
</div>
<p class="process-intro">将开发一款互联网产品的模糊目标,拆解为可执行的具体工作任务。根据案例信息,填写参考工期和项目依赖关系。</p>
<p v-if="!hasCompletedStepOne" class="step-warning">请先完成第 1 步并判题通过;关键任务结果会自动带入本表。</p>
<p class="schedule-import-hint">支持导入填写后的模板或导出列表,按任务编号匹配。日期可填写 YYYY-MM-DD 或使用 Excel 日期格式;导入后请保存。</p>
<div class="training-table-wrap">
<table class="process-table schedule-table">
<thead>
@ -204,7 +211,7 @@
</el-icon>
上一步
</button>
<button type="button" class="btn-nav btn-save" :disabled="saving || uploadingGantt"
<button type="button" class="btn-nav btn-save" :disabled="saving || uploadingGantt || importingSchedule"
@click="saveCurrentProgress">
<el-icon>
<CircleCheck />
@ -216,7 +223,7 @@
<span class="step-progress">Step {{ String(currentStep).padStart(2, '0') }} / {{
String(trainingSteps.length).padStart(2, '0') }}</span>
<button v-if="currentStep < trainingSteps.length" type="button" class="btn-nav btn-primary"
:disabled="checking || saving || uploadingGantt" @click="nextStep">
:disabled="checking || saving || uploadingGantt || importingSchedule" @click="nextStep">
{{ checking ? '判题中…' : '下一步' }}
<el-icon>
<ArrowRight />
@ -234,8 +241,10 @@
</template>
<script setup>
import { ArrowLeft, ArrowRight, CircleCheck, Operation, RefreshLeft, Upload } from "@element-plus/icons-vue"
import { ArrowLeft, ArrowRight, CircleCheck, Download, Operation, RefreshLeft, Upload } from "@element-plus/icons-vue"
import * as XLSX from "xlsx"
import { ElMessageBox } from "element-plus"
import { parseScheduleRows, scheduleTemplateRows } from "./processScheduleExcel.mjs"
import { checkProductDevelopmentProcessStepOne, checkProductDevelopmentProcessStepTwo, checkProductDevelopmentProcessStepThree, checkProductDevelopmentProcessStepFour, getStudentTrainingAnswer, saveStudentTrainingAnswer, uploadStudentTrainingFile } from "@/api/studentTrainingAnswer"
import { getTrainingTaskByKey } from "@/api/trainingTask"
import { parseTrainingArray } from "@/views/training/taskKeyMap"
@ -269,6 +278,8 @@ const currentStep = ref(1)
const briefOpen = ref(true)
const checking = ref(false)
const saving = ref(false)
const scheduleExcelInput = ref(null)
const importingSchedule = ref(false)
const draftReady = ref(false)
const checkResult = ref(null)
const stepOnePassed = ref(false)
@ -628,6 +639,52 @@ function downloadBuiltInFile(url, filename) {
document.body.removeChild(link)
}
function downloadScheduleTemplate() {
const workbook = XLSX.utils.book_new()
const worksheet = XLSX.utils.aoa_to_sheet(scheduleTemplateRows(processRows.value))
worksheet['!cols'] = [{ wch: 12 }, { wch: 10 }, { wch: 36 }, { wch: 14 }, { wch: 16 }, { wch: 16 }, { wch: 30 }]
XLSX.utils.book_append_sheet(workbook, worksheet, 'WBS排期表')
XLSX.utils.book_append_sheet(workbook, XLSX.utils.aoa_to_sheet([
['填写说明'], ['在第一个工作表填写开始时间、完成时间和项目依赖关系。'],
['按任务编号匹配,可调整行或列的顺序;未导入的任务保持不变。'],
['阶段、具体工作任务和是否关键任务仅供参考,导入不会修改第一步分类结果。'],
['日期填写 YYYY-MM-DD(如 2026-10-20),也支持 YYYY/M/D、YYYY.M.D、YYYY年M月D日和 Excel 日期单元格。'],
['完成时间不能早于开始时间;导入行的空白日期或依赖关系会清空对应字段。'],
['导入后点击保存;下一步仍按原有规则检查全部任务的排期。'],
]), '填写说明')
XLSX.writeFile(workbook, '产品开发WBS排期-导入模板.xlsx')
}
async function importScheduleExcel(event) {
const file = event.target?.files?.[0]
if (event.target) event.target.value = ''
if (!file || currentStep.value !== 2 || !hasCompletedStepOne.value || checking.value || saving.value || importingSchedule.value) return
importingSchedule.value = true
const currentRows = processRows.value
const snapshot = JSON.stringify(currentRows)
try {
if (!/\.(xls|xlsx)$/i.test(file.name)) throw new Error('请选择 .xls 或 .xlsx 文件')
if (file.size > 5 * 1024 * 1024) throw new Error('Excel 文件不能超过 5MB')
const workbook = XLSX.read(await file.arrayBuffer(), { type: 'array', cellDates: false })
if (!workbook.SheetNames.length) throw new Error('Excel 中没有工作表')
const sheet = workbook.Sheets[workbook.SheetNames[0]]
const range = XLSX.utils.decode_range(sheet['!ref'] || 'A1')
if (range.e.r > 10000 || range.e.c > 50) throw new Error('工作表范围过大,请仅保留 WBS 排期数据')
const rows = XLSX.utils.sheet_to_json(sheet, { header: 1, raw: true, defval: '', blankrows: true, range: 0 })
const result = parseScheduleRows(rows, currentRows, { date1904: !!workbook.Workbook?.WBProps?.date1904, parseDateCode: XLSX.SSF.parse_date_code })
await ElMessageBox.confirm(`将更新 ${result.count} 个任务的开始时间、完成时间和项目依赖关系。导入行的空白字段会清空对应输入,未导入的任务和第一步分类结果保持不变。是否继续?`, '确认导入排期', { type: 'warning', confirmButtonText: '导入', cancelButtonText: '取消' })
if (currentStep.value !== 2 || !hasCompletedStepOne.value || checking.value || saving.value || processRows.value !== currentRows || JSON.stringify(currentRows) !== snapshot) {
throw new Error('当前步骤或排期已变化,请重新导入')
}
processRows.value = result.rows
proxy?.$modal?.msgSuccess?.(`已导入 ${result.count} 个任务的排期,请保存本步骤`)
} catch (error) {
if (error !== 'cancel' && error !== 'close') proxy?.$modal?.msgError?.(error?.message || '导入失败,请检查 Excel 文件')
} finally {
importingSchedule.value = false
}
}
function exportScheduleList() {
const rows = processRows.value.map((row) => ({
阶段: row.stage,
@ -910,6 +967,13 @@ async function nextStep() {
gap: 8px;
}
.schedule-import-hint {
margin: 0 0 12px;
color: #6b7280;
font-size: var(--student-fs-body-sm);
line-height: 1.6;
}
/* 标题行内联导出:次按钮的紧凑小号(继承 .outline-action 描边与圆角语言) */
.schedule-export-action {
min-height: 36px;

@ -41,8 +41,8 @@
<span v-if="index < trainingSteps.length - 1" class="step-connector" aria-hidden="true" />
</template>
</nav>
<TrainingExcelTools :tables="numericExcelTables" :context-key="currentStep" :disabled="saving || savingStepTwo || savingStepThree || savingStepFour" />
<TrainingExcelTools v-if="currentStep > 2" :tables="numericExcelTables" :context-key="currentStep"
:disabled="saving || savingStepTwo || savingStepThree || savingStepFour" />
<section v-if="currentStep === 1" class="step-card hardware-step-card">
<section class="cost-brief">
@ -68,6 +68,9 @@
</div>
</div>
<TrainingExcelTools :tables="numericExcelTables" :context-key="currentStep"
:disabled="saving || savingStepTwo || savingStepThree || savingStepFour" />
<div class="bom-table-wrap">
<table class="bom-table">
<thead>
@ -149,6 +152,9 @@
</div>
<span class="step-chip">{{ costRows.length }} 项物料同步自第一步</span>
</div>
<TrainingExcelTools :tables="numericExcelTables" :context-key="currentStep"
:disabled="saving || savingStepTwo || savingStepThree || savingStepFour" />
<div class="bom-table-wrap">
<table class="bom-table batch-cost-table">
<thead>

@ -40,8 +40,7 @@
class="step-connector" aria-hidden="true"></span>
</template>
</nav>
<TrainingExcelTools :tables="numericExcelTables" :context-key="currentStep" :disabled="saving" />
<TrainingExcelTools v-if="currentStep !== 4" :tables="numericExcelTables" :context-key="currentStep" :disabled="saving" />
<section class="step-card">
<header class="step-title-row">
@ -203,6 +202,8 @@
</div>
</div>
<TrainingExcelTools :tables="numericExcelTables" :context-key="currentStep" :disabled="saving" />
<div class="table-scroll">
<table class="price-table psm-table">
<thead>
@ -1602,7 +1603,7 @@ const money = (key, label) => nc(key, label, {string: true});
if (currentStep.value === 1) return [et('markup', '成本加成定价', pricingRows.value, [fc('channel', '销售渠道'), nc('markupRate', '成本加成比例(%)', {percent: true, string: true})])];
if (currentStep.value === 2) return [et('competitors', '竞争定价分析', competitorRows.value, [tc('productType', '竞品类型'), tc('brand', '品牌'), money('ecommercePrice', '电商售价(元)'), tc('differentiator', '差异化优势')])];
if (currentStep.value === 3) return [et('value', '用户感知价值', perceivedValueItems.value, [tc('name', '价值感知项'), money('perceivedValue', '感知价值(元)')], {maxRows: 10000, createRow: () => createPerceivedValueItem()})];
if (currentStep.value === 4) return [et('psm', 'PSM价格敏感度', psmRows.value, [fc('priceRange', '价格区间'), ...[['tooExpensive','太贵'], ['tooCheap','太便宜'], ['expensiveAcceptable','贵但可接受'], ['cheapValue','便宜划算']].map(([k,l]) => rc(k, l + '(%)', {string: true}))])];
if (currentStep.value === 4) return [et('psm', 'PSM价格敏感度', psmRows.value, [fc('priceRange', '价格区间'), ...[['tooExpensive','太贵'], ['tooCheap','太便宜'], ['expensiveAcceptable','贵但可接受'], ['cheapValue','便宜划算']].map(([k,l]) => rc(k, l + '(%)', {string: true}))], {apply: next => {psmRows.value = next; clearValidation();}})];
return [];
});
</script>

@ -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(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.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 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<html.indexOf('class="table-scroll"'));
assert.equal((html.match(/data-test-excel=/g)||[]).length,1);
assert.match(html,/价格(元)/); assert.match(html,/累计占比(%)/);
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.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"/);
});

@ -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('<template v-else-if="currentStep === 2">');
const end = source.indexOf('<template v-else-if="currentStep === 3">');
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"/);
});
Loading…
Cancel
Save