From 9d288bde92f08600ae46bd535543b30978dcfd97 Mon Sep 17 00:00:00 2001 From: chenyuan Date: Wed, 28 Oct 2026 10:10:28 +0800 Subject: [PATCH] fix(training): correct pricing ranges, ROI synchronization and form layouts --- src/api/studentTrainingAnswer.js | 6 +- src/views/assessment/optimization.vue | 10 ++ src/views/channel/supplier.vue | 2 +- .../product-development-process.vue | 10 +- src/views/product/price.vue | 12 +- src/views/test/promotion.vue | 4 +- tests/numeric-training-excel.test.cjs | 135 +++++++++++++++++- 7 files changed, 160 insertions(+), 19 deletions(-) diff --git a/src/api/studentTrainingAnswer.js b/src/api/studentTrainingAnswer.js index 409c7fd..e3d224a 100644 --- a/src/api/studentTrainingAnswer.js +++ b/src/api/studentTrainingAnswer.js @@ -101,7 +101,7 @@ export function validateProductPricingStepOne(payload) { const value = payload || {}; const rows = Array.isArray(value.pricingRows) ? value.pricingRows : []; if (isStudentDemo()) { - const ranges = { dealer: [15, 25], "direct-retail": [40, 60], "premium-brand": [70, 80] }; + const ranges = { dealer: [15, 25], "direct-retail": [40, 200], "premium-brand": [70, 300] }; const unitCost = Number(value.unitCost); if (!Number.isFinite(unitCost) || unitCost <= 0) return Promise.reject(new Error("单台综合成本必须大于 0")); if (rows.length !== 3) return Promise.reject(new Error("请填写三个渠道的加成率")); @@ -195,8 +195,7 @@ export function validateProductPricingStepFour(payload) { const pricePoints = value.pricePoints || {}; if (isStudentDemo()) { try { - const requiredRanges = ["≤100元", "100~150元", "150~200元", "200~250元", "250~300元", "≥300元"]; - if (psmRows.length < requiredRanges.length) throw new Error("请完整填写 6 个固定价格区间的 PSM 累计占比"); + if (psmRows.length < 6) throw new Error("请至少填写 6 个价格区间的 PSM 累计占比"); const seenIds = new Set(); const seenRanges = new Set(); const normalizedRows = psmRows.map((row, index) => { @@ -213,7 +212,6 @@ export function validateProductPricingStepFour(payload) { }); return normalized; }); - if (!requiredRanges.every((range) => seenRanges.has(range))) throw new Error("请保留并填写 6 个固定价格区间"); const optimalPrice = Number(pricePoints.optimalPrice); const acceptablePrice = Number(pricePoints.acceptablePrice); const acceptableRange = String(pricePoints.acceptableRange || "").trim(); diff --git a/src/views/assessment/optimization.vue b/src/views/assessment/optimization.vue index fb80462..ec76e91 100644 --- a/src/views/assessment/optimization.vue +++ b/src/views/assessment/optimization.vue @@ -1346,6 +1346,16 @@ button:disabled { /* ===== 策略表格 ===== */ .strategy-table { min-width: 1120px; + table-layout: fixed; +} + +.strategy-table th:first-child, +.strategy-table th:nth-child(4) { + width: 200px; +} + +.strategy-table th:nth-child(2) { + width: 140px; } .strategy-table td { diff --git a/src/views/channel/supplier.vue b/src/views/channel/supplier.vue index 48eaeeb..ffd9cce 100644 --- a/src/views/channel/supplier.vue +++ b/src/views/channel/supplier.vue @@ -1330,7 +1330,7 @@ return []; .default-risk-row :deep(.el-textarea__inner), .default-risk-row :deep(.el-select__selected-item) { color: var(--student-text-secondary); - font-style: italic; + font-style: normal; } /* ===== 响应式(仅基础断点) ===== */ diff --git a/src/views/foundation/product-development-process.vue b/src/views/foundation/product-development-process.vue index 14ceaec..1cfa90f 100644 --- a/src/views/foundation/product-development-process.vue +++ b/src/views/foundation/product-development-process.vue @@ -57,7 +57,7 @@

- +
@@ -1031,6 +1031,14 @@ async function nextStep() { table-layout: fixed; } +.classification-table th:first-child { + width: 140px; +} + +.classification-table th:nth-child(2) { + width: 110px; +} + .process-table th { padding: 9px 10px; border-bottom: 1px solid #e5e7eb; diff --git a/src/views/product/price.vue b/src/views/product/price.vue index 4b2c795..80f1091 100644 --- a/src/views/product/price.vue +++ b/src/views/product/price.vue @@ -218,9 +218,9 @@
阶段
- {{ row.priceRange }} - + 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}))], {apply: next => {psmRows.value = next; clearValidation();}})]; +if (currentStep.value === 4) return [et('psm', 'PSM价格敏感度', psmRows.value, [tc('priceRange', '价格区间'), ...[['tooExpensive','太贵'], ['tooCheap','太便宜'], ['expensiveAcceptable','贵但可接受'], ['cheapValue','便宜划算']].map(([k,l]) => rc(k, l + '(%)', {string: true}))], {apply: next => {psmRows.value = next; clearValidation();}})]; return []; }); diff --git a/src/views/test/promotion.vue b/src/views/test/promotion.vue index ccb269e..10a5051 100644 --- a/src/views/test/promotion.vue +++ b/src/views/test/promotion.vue @@ -421,10 +421,10 @@ function goToStepFromTab(step) { } function openStepThree() { syncPerformanceRows(performanceRows.value); activeStep.value = 3 } function displayFixed(value) { return Number.isFinite(Number(value)) ? Number(value).toFixed(2) : "—" } -function evaluationPayload() { return { rows: evaluationRows.value.map((row) => ({ channel: row.channel, roi: row.roi, achievement: row.achievement, problemDiagnosis: row.problemDiagnosis, optimizationAction: row.optimizationAction })), optimizationDecision: optimizationDecision.value } } +function evaluationPayload() { syncEvaluationRows(evaluationRows.value); return { rows: evaluationRows.value.map((row) => ({ channel: row.channel, roi: row.roi, achievement: row.achievement, problemDiagnosis: row.problemDiagnosis, optimizationAction: row.optimizationAction })), optimizationDecision: optimizationDecision.value } } function syncEvaluationRows(savedRows = []) { const saved = new Map(savedRows.map((row) => [row?.channel, row])) - evaluationRows.value = performanceRows.value.filter((row) => row.channel && row.channel !== "合计").map((row) => makeEvaluationRow({ channel: row.channel, roi: row.actualRoi, ...saved.get(row.channel) })) + evaluationRows.value = performanceRows.value.filter((row) => row.channel && row.channel !== "合计").map((row) => makeEvaluationRow({ ...saved.get(row.channel), channel: row.channel, roi: row.actualRoi })) } function openStepFour() { syncEvaluationRows(evaluationRows.value); activeStep.value = 4 } async function saveAnswer(currentStep, fields) { await saveStudentTrainingAnswer(TASK_KEY, { saveAction: "SAVE", currentStep, ...fields }) } diff --git a/tests/numeric-training-excel.test.cjs b/tests/numeric-training-excel.test.cjs index 48adee3..0990b26 100644 --- a/tests/numeric-training-excel.test.cjs +++ b/tests/numeric-training-excel.test.cjs @@ -21,6 +21,51 @@ const pages = { '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"); @@ -108,6 +153,57 @@ for (const [page, steps] of Object.entries(pages)) test('numeric Excel round tri } }); +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 }]; @@ -508,7 +604,7 @@ test('numeric Excel ignores a pending import after its table controls unmount', 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 () => { +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',{ @@ -533,9 +629,13 @@ test('numeric Excel PSM imports six price ranges and saves percentages without c 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 data=[template[0],...values.map((r,i)=>[i+1,ranges[i],...r]).reverse()]; + 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%'}; @@ -545,7 +645,7 @@ test('numeric Excel PSM imports six price ranges and saves percentages without c 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]); + 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,''); @@ -560,10 +660,11 @@ test('numeric Excel PSM imports six price ranges and saves percentages without c 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 changed price ranges without overwriting existing rows', async () => { +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';}); @@ -574,7 +675,9 @@ test('numeric Excel PSM rejects invalid percentages and changed price ranges wit 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)); + 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, @@ -588,6 +691,25 @@ test('numeric Excel PSM rejects invalid percentages and changed price ranges wit 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; @@ -609,6 +731,9 @@ test('numeric Excel PSM import controls render above the fourth step table with assert.ok(toolbar