Files
weiguang-jewelry-ledger/新账系统/test/price-lock-pool-ui.test.js
T

106 lines
22 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
'use strict';
// 全部为虚构DTO与内存DOM,不读取磁盘账本,也不发出网络请求。
const {test}=require('node:test'),assert=require('node:assert/strict'),fs=require('node:fs'),vm=require('node:vm'),{randomUUID}=require('node:crypto');
const Calc=require('../public/calculations');
const D='2026-11-02',OLD='2026-11-01';
function node(extra={}){const classes=new Set();return {value:'',checked:false,disabled:false,required:false,readOnly:false,hidden:false,textContent:'',innerHTML:'',dataset:{},classList:{add:value=>classes.add(value),remove:value=>classes.delete(value),contains:value=>classes.has(value)},closest(){return this.label??=(node());},...extra};}
function pool(extra={}){return {id:D,date:D,totalMg:20000,totalAmount:1720000,averageRate:86000,remainingMg:20000,usedMg:0,revision:'synthetic-pool-v1',purchases:[{id:'p1',payer:'owner',amount:850000,mg:10000},{id:'p2',payer:'assistant',amount:870000,mg:10000}],usages:[],...extra};}
function harness(){
const nodes=new Map(),saved=new Map(),posts=[],user={id:'lock-pool-owner',name:'麦麦',role:'owner',member:'owner'},context=vm.createContext({LedgerCalc:Calc,crypto:{randomUUID},URLSearchParams,setInterval(){},setTimeout(){},clearTimeout(){},console,document:{querySelector:selector=>nodes.get(selector)||null,querySelectorAll:()=>[],addEventListener(){}},window:{scrollTo(){}},localStorage:{getItem:key=>saved.get(key)||null,setItem:(key,value)=>saved.set(key,String(value)),removeItem:key=>saved.delete(key)},sessionStorage:{getItem(){return null;},setItem(){}},__user:user,__posts:posts});
const run=code=>vm.runInContext(code,context),json=code=>JSON.parse(JSON.stringify(run(code)));
for(const file of ['price-locks-ui.js','material-pools-ui.js','order-changes-ui.js','app.js'])run(fs.readFileSync(require.resolve('../public/'+file),'utf8').replace(/\ninit\(\);\s*$/,''));
run(`session={user:__user};state={user:__user,today:'${D}',pockets:['现货','金料'],accounts:['麦麦微信']};tab='create';readPaymentAccount=()=> '麦麦微信';readCreditCardPayer=()=> 'owner';syncPaymentRecipient=()=>{};syncCreditCardPreview=()=>0;finishPriceLockSave=async()=>{};mutate=async(url,data)=>{__posts.push({url,data});return {id:'synthetic-lock'};};`);
for(const selector of ['#main','#price-lock-error','#lock-create-total','#lock-sale-estimate','#lock-material-estimate','#lock-pool-material-estimate','#lock-pool-material-note','#lock-pool-material-payers'])nodes.set(selector,node());
const fields=Object.fromEntries(Object.entries({date:D,customer:'合成客户',salesperson:'合成开单人',name:'足金999',quantity:'12',goldPrice:'1000',laborRate:'0',laborMode:'gram',pieces:'1',discount:'0',note:'',received_amount:'1000',material_source:'manual',material_rate:'855',material_payer:'assistant2',material_pool_date:'',material_pool_rate:''}).map(([name,value])=>[name,node({value})]));
fields.payment_verified=node({checked:true});fields.material_verified=node({checked:true});
const form=node({id:'price-lock-create-form',querySelector(selector){return fields[selector.match(/\[name="([^"]+)"\]/)?.[1]]||null;},querySelectorAll:()=>[]});
const manual=node({querySelectorAll:()=>['material_rate','material_payer','material_verified'].map(name=>fields[name])}),poolRoot=node();nodes.set('#price-lock-create-form',form);nodes.set('#lock-manual-material',manual);nodes.set('#lock-pool-material',poolRoot);
return {nodes,saved,posts,context,run,json,fields,form,manual,poolRoot,use(value=pool()){context.__pool=value;run('materialPoolsCache={rolling:{enabled:true,cutover:state.today},current:__pool,rows:[__pool]};materialPoolsCacheUser=state.user.id;priceLockPoolError="";');}};
}
function lock(extra={}){return {id:'synthetic-lock',date:D,locked_mg:1000,buy_rate:90667,buy_payer:'owner',material_source:'pool',material_pool_id:D,material_amount:90666,sell_rate:100000,netReceived:100000,status:'pending',credit_card_fees:[],materialPool:{poolId:D,date:D,quantity:1000,amount:90666,averageRate:90667,basisAmount:272000,basisMg:3000,prefixMg:1000,prefixAmount:90667,allocations:[{payer:'owner',amount:40000},{payer:'assistant',amount:50666}],frozen:false},...extra};}
test('原锁来源默认手动,标签清楚区分实际付款与已有料池',()=>{
const h=harness(),html=h.run('priceLockCreateMaterialHTML({})');
assert.match(html,/<option value="manual" selected>手动填写料价/);assert.match(html,/<option value="pool" >当日加权料价/);
assert.match(html,/name="material_rate"/);assert.match(html,/name="material_payer"/);assert.match(html,/已核实原锁金料的实际付款/);assert.match(html,/保存锁价不再登记料费付款/);
});
test('切至料池禁用隐藏手动付款,切回保留料价、付款人和核实,草稿可恢复',()=>{
const h=harness();h.use();h.run('syncPriceLockCreate()');assert.equal(h.nodes.get('#lock-material-estimate').textContent,'¥10,260.00');
h.fields.material_source.value='pool';h.run('syncPriceLockCreate()');
assert.equal(h.manual.hidden,true);assert.equal(h.poolRoot.hidden,false);for(const name of ['material_rate','material_payer','material_verified']){assert.equal(h.fields[name].disabled,true);assert.equal(h.fields[name].required,false);}
assert.equal(h.nodes.get('#lock-pool-material-estimate').textContent,'¥10,320.00');assert.match(h.nodes.get('#lock-pool-material-payers').innerHTML,/麦麦.*8,500\.00.*娜娜.*1,820\.00/);
const data=h.json('collectPriceLockCreate()');assert.deepEqual(data.material,{source:'pool',poolId:D,revision:'synthetic-pool-v1'});assert.equal(Object.hasOwn(data.material,'payer'),false);assert.equal(Object.hasOwn(data.material,'verified'),false);
const draft=JSON.parse(h.saved.get('mm-price-lock-draft-lock-pool-owner'));assert.deepEqual(draft.material.manual,{rate:'855',payer:'assistant2',verified:true});
const restored=h.run('priceLockCreateMaterialHTML('+JSON.stringify(draft.material)+')');assert.match(restored,/name="material_rate" value="855"/);assert.match(restored,/<option value="assistant2" selected>/);
h.fields.material_source.value='manual';h.run('syncPriceLockCreate()');assert.equal(h.manual.hidden,false);assert.equal(h.fields.material_rate.value,'855');assert.equal(h.fields.material_payer.value,'assistant2');assert.equal(h.fields.material_verified.checked,true);assert.equal(h.fields.material_verified.required,true);
});
test('每日料池预览包括匿名锁单占用,修改重量即时按最新可用量和FIFO资金归属计算',()=>{
const h=harness();h.use(pool({usedMg:4000,remainingMg:16000,usages:[{kind:'priceLock',anonymous:true,mg:4000,active:1,fifo_sequence:1,created:D+'T00:00:00Z'}]}));h.fields.material_source.value='pool';
h.run('syncPriceLockCreate()');assert.equal(h.nodes.get('#lock-pool-material-estimate').textContent,'¥10,320.00');assert.match(h.nodes.get('#lock-pool-material-payers').innerHTML,/5,060\.00.*5,260\.00/);assert.match(h.nodes.get('#lock-pool-material-note').textContent,/可用 16\.000g/);
h.fields.quantity.value='17';h.run('syncPriceLockCreate()');assert.equal(h.nodes.get('#lock-pool-material-estimate').textContent,'待确定');assert.equal(h.nodes.get('#lock-pool-material-payers').innerHTML,'');assert.match(h.nodes.get('#lock-pool-material-note').textContent,/还缺 1\.000g/);assert.equal(h.poolRoot.dataset.ready,'false');
h.fields.quantity.value='1';h.run('syncPriceLockCreate()');assert.equal(h.nodes.get('#lock-pool-material-estimate').textContent,'¥860.00');assert.match(h.nodes.get('#lock-pool-material-payers').innerHTML,/麦麦.*860\.00/);
});
test('无池、成本缺失、过往日期与读取失败不能显示零成本或沿用旧预览',async()=>{
const h=harness();h.fields.material_source.value='pool';
for(const [value,message] of [[pool({totalMg:0,totalAmount:0}),/尚无可用材料/],[pool({totalAmount:null}),/成本尚未补齐/]]){h.use(value);h.run('syncPriceLockCreate()');assert.match(h.nodes.get('#lock-pool-material-note').textContent,message);assert.equal(h.nodes.get('#lock-pool-material-estimate').textContent,'待确定');await assert.rejects(h.run('submitPriceLockForm(document.querySelector("#price-lock-create-form"))'),message);}
h.use();h.fields.date.value=OLD;h.run('syncPriceLockCreate()');assert.equal(h.fields.material_pool_date.value,OLD);assert.match(h.nodes.get('#lock-pool-material-note').textContent,/只支持今天锁价/);assert.equal(h.nodes.get('#lock-pool-material-estimate').textContent,'待确定');
h.fields.date.value=D;h.run('priceLockPoolError="每日料池尚未读到:合成读取失败";syncPriceLockCreate()');assert.match(h.nodes.get('#lock-pool-material-note').textContent,/合成读取失败/);assert.equal(h.poolRoot.dataset.revision,'');assert.equal(h.posts.length,0);
});
test('未启用统一料池明确提示并阻止料池锁价,手动实际付款仍可保存',async()=>{
const h=harness();h.use();h.run('materialPoolsCache.rolling={enabled:false}');h.fields.material_source.value='pool';h.run('syncPriceLockCreate()');assert.equal(h.nodes.get('#lock-pool-material-note').textContent,'请先启用统一料池,再选择当日加权料价。');assert.equal(h.poolRoot.dataset.ready,'false');assert.equal(h.nodes.get('#lock-pool-material-estimate').textContent,'待确定');await assert.rejects(h.run('submitPriceLockForm(document.querySelector("#price-lock-create-form"))'),/请先启用统一料池,再选择当日加权料价/);assert.equal(h.posts.length,0);
h.fields.quantity.value='';h.run('syncPriceLockCreate()');assert.equal(h.nodes.get('#lock-pool-material-note').textContent,'请先启用统一料池,再选择当日加权料价。');h.fields.quantity.value='12';h.fields.material_source.value='manual';await h.run('submitPriceLockForm(document.querySelector("#price-lock-create-form"))');assert.deepEqual(JSON.parse(JSON.stringify(h.posts[0].data.material)),{rate:'855',payer:'assistant2',verified:true});
});
test('池满不足不提交,足额料池只传自动来源与版本,手填仍传原实际付款',async()=>{
const h=harness();h.use();h.fields.material_source.value='pool';h.fields.quantity.value='20.001';await assert.rejects(h.run('submitPriceLockForm(document.querySelector("#price-lock-create-form"))'),/还缺 0\.001g/);assert.equal(h.posts.length,0);
h.fields.quantity.value='12';h.fields.material_verified.checked=false;await h.run('submitPriceLockForm(document.querySelector("#price-lock-create-form"))');assert.deepEqual(JSON.parse(JSON.stringify(h.posts[0].data.material)),{source:'pool',poolId:D,revision:'synthetic-pool-v1'});
h.fields.material_source.value='manual';await assert.rejects(h.run('submitPriceLockForm(document.querySelector("#price-lock-create-form"))'),/核实.*料费实际付款/);h.fields.material_verified.checked=true;await h.run('submitPriceLockForm(document.querySelector("#price-lock-create-form"))');assert.deepEqual(JSON.parse(JSON.stringify(h.posts[1].data.material)),{rate:'855',payer:'assistant2',verified:true});
});
test('料池异步读完按表单现有日期与重量重算,已离开原表单不会被旧响应改写',async()=>{
const h=harness();let resolve;h.context.__deferred=new Promise(yes=>{resolve=yes;});h.run('readMaterialPools=async()=>{await __deferred;materialPoolsCache={rolling:{enabled:true,cutover:state.today},current:__pool,rows:[__pool]};materialPoolsCacheUser=state.user.id;};');h.context.__pool=pool();h.fields.material_source.value='pool';
const read=h.run('loadPriceLockPoolChoices(true)');h.fields.quantity.value='1';h.fields.date.value=OLD;resolve();await read;assert.match(h.nodes.get('#lock-pool-material-note').textContent,/只支持今天锁价/);assert.equal(h.fields.material_pool_date.value,OLD);assert.equal(h.nodes.get('#lock-pool-material-estimate').textContent,'待确定');
h.fields.date.value=D;let release;h.context.__deferred=new Promise(yes=>{release=yes;});const stale=h.run('loadPriceLockPoolChoices(true)');h.nodes.delete('#price-lock-create-form');h.nodes.get('#lock-pool-material-note').textContent='已离开原表单';release();await stale;assert.equal(h.nodes.get('#lock-pool-material-note').textContent,'已离开原表单');
});
test('切换账号后迟到的读取失败不能污染下一账号的料池错误状态',async()=>{
const h=harness();let reject;h.context.__deferred=new Promise((yes,no)=>{reject=no;});h.run('readMaterialPools=async()=>await __deferred');const read=h.run('loadPriceLockPoolChoices(true)');h.run('state.user={id:"next-account",role:"assistant",member:"assistant"}');reject(new Error('前一账号合成读取失败'));await read;assert.equal(h.run('priceLockPoolError'),'');
});
test('原料池精确累计分币保留前序尾差,少重按快照回池、多重只新增手填补料',()=>{
const h=harness();h.context.__lock=lock();
const unchanged=h.json('priceLockDeliveryCost(__lock,"1","")');assert.equal(unchanged.materialCost,90666);assert.equal(unchanged.leftoverCost,0);
const less=h.json('priceLockDeliveryCost(__lock,"0.5","")');assert.equal(less.originalUsedCost,45333);assert.equal(less.leftoverCost,45333);assert.deepEqual(less.allocations,[{payer:'owner',amount:40000},{payer:'assistant',amount:5333}]);assert.equal(less.leftoverMg,500);
const extra=h.json('priceLockDeliveryCost(__lock,"1.2","900")');assert.equal(extra.originalUsedCost,90666);assert.equal(extra.extraCost,18000);assert.equal(extra.materialCost,108666);assert.equal(extra.extraMg,200);
assert.throws(()=>h.run('priceLockDeliveryCost(__lock,"1.2","")'),/补重进货料价/);
const raw=JSON.stringify(h.context.__lock);h.run('priceLockDeliveryCost(__lock,"0.5","")');assert.equal(JSON.stringify(h.context.__lock),raw);
});
test('手动原料仍沿用旧每克算法,料池资料缺失不能用展示均价冒算',()=>{
const h=harness();h.context.__lock=lock({material_source:'manual',buy_rate:85000,material_amount:85000});const manual=h.json('priceLockDeliveryCost(__lock,"0.5","")');assert.equal(manual.originalUsedCost,42500);assert.equal(manual.leftoverCost,42500);
h.context.__lock=lock({materialPool:{amount:90666,averageRate:90667,allocations:[{payer:'owner',amount:90666}]}});assert.throws(()=>h.run('priceLockDeliveryCost(__lock,"0.5","")'),/未完整读到/);
});
test('锁价详情与列表来源文案保留多人、冻结信息,不能把buy_payer当作唯一付款人',()=>{
const h=harness();h.context.__lock=lock();let html=h.run('priceLockFacts(__lock)');assert.match(html,/当日加权料池/);assert.match(html,/麦麦 ¥400\.00;娜娜 ¥506\.66/);assert.match(html,/当天补料继续加权/);assert.doesNotMatch(html,/麦麦支付,进货料价/);
h.context.__lock.materialPool.frozen=true;html=h.run('priceLockFacts(__lock)');assert.match(html,/已冻结锁价日成本/);assert.doesNotMatch(html,/当天补料继续加权/);
});
test('审批影响展示关联锁价的前后成本与多人归属,名称转义且缺来源阻止复核',()=>{
const h=harness(),before={materialAmount:860000,usedMaterialAmount:0,leftoverCost:0,allocations:[{payer:'owner',amount:850000},{payer:'assistant',amount:10000}]},after={materialAmount:870000,usedMaterialAmount:0,leftoverCost:0,allocations:[{payer:'owner',amount:850000},{payer:'assistant2',amount:20000}]};h.context.__related=[{id:'lock-related',date:D,number:'合成<锁单>',customer:'客户<script>',before,after}];
const html=h.run('relatedPriceLocksHTML(__related)');assert.match(html,/同时受影响的锁价单(1 张)/);assert.match(html,/8,600\.00/);assert.match(html,/8,700\.00/);assert.match(html,/小昊.*200\.00/);assert.match(html,/合成&lt;锁单&gt;.*客户&lt;script&gt;/);assert.doesNotMatch(html,/<script>/);
h.context.__related[0].after.allocations=[];assert.throws(()=>h.run('relatedPriceLocksHTML(__related)'),/成本影响未完整返回/);
});
test('销售详情把同一原锁料池的多人分摊合并一行,补重保留独立采购计算',()=>{
const h=harness();h.context.__rows=[{kind:'goods',component:'material',name:'料费成本',source:'商品 1 · 足金999 · 原锁料池',priceLockSource:'original',amount:40000,payer:'owner',calculation:{weighted:true,rate:90667,quantity:1000}},{kind:'goods',component:'material',name:'料费成本',source:'商品 1 · 足金999 · 原锁料池',priceLockSource:'original',amount:50666,payer:'assistant',calculation:{weighted:true,rate:90667,quantity:1000}},{kind:'goods',component:'material',name:'料费成本',source:'商品 1 · 足金999 · 补重采购',priceLockSource:'extra',amount:18000,payer:'assistant2',calculation:{rate:90000,quantity:200}}];
const html=h.run('LedgerCalc={...LedgerCalc,orderCosts:()=>({rows:__rows,goodsExcluded:false,total:{goodsMissing:0,goods:108666}})};orderCostsHTML({goodsCost:108666,directCost:0,corrections:[],expenses:[]})');
assert.equal((html.match(/<td>原锁料费/g)||[]).length,1);assert.equal((html.match(/耗用 1\.000g/g)||[]).length,1);assert.match(html,/麦麦 ¥400\.00<br>娜娜 ¥506\.66/);assert.match(html,/0\.200g × 900\.00元\/克/);assert.match(html,/补重料费/);assert.doesNotMatch(html,/1\.000g ×/);
});
test('每日料池明细为锁价提供独立入口,助理只看可见锁单,付款来源缺失不冒充零',()=>{
const h=harness();h.context.__pool=pool({settlement:{legacyReadOnly:true},usages:[{kind:'priceLock',date:D,price_lock_id:'own-lock',member:'assistant',number:'合成可见锁价',customer:'合成客户',product:'足金999',active:1,mg:12000,amount:1032000,allocations:[{payer:'owner',amount:850000},{payer:'assistant',amount:182000}]},{kind:'priceLock',anonymous:true,active:1,mg:1000,amount:86000},{kind:'priceLock',date:D,price_lock_id:'other-lock',member:'assistant2',number:'不应展示他人锁价',active:1,mg:1000,amount:86000}]});
const html=h.run('state.user={id:"synthetic-assistant",role:"assistant",member:"assistant"};materialPoolDetailHTML(__pool)');assert.match(html,/data-action="open-price-lock" data-id="own-lock"/);assert.match(html,/锁价原料 · 足金999/);assert.match(html,/麦麦 ¥8,500\.00 · 娜娜 ¥1,820\.00/);assert.doesNotMatch(html,/不应展示他人锁价|商品 NaN|data-id="undefined"|NaN/);assert.equal(h.run('materialPoolUsagePayersText({})'),'付款来源待补齐');
});
test('锁价混合个人料与公共料短交逐来源切分,跨来源分币与后端快照逐分一致',()=>{
const Allocation=require('../material-pool-allocation'),Locks=require('../price-lock-pools'),p={id:D,date:D,materialGroups:Allocation.groups([{id:'private',mg:3,amount:2,payer:'assistant',materialOwner:'assistant'},{id:'common',mg:2,amount:3,payer:'owner'}])},snapshot=Allocation.allocate(p,[{kind:'priceLock',member:'assistant',mg:5,reserved_mg:5,snapshot:{}}])[0].lockSnapshot,h=harness();h.context.__lock=lock({locked_mg:5,material_amount:snapshot.amount,materialPool:snapshot});
for(const mg of [1,2,3,4,5]){const expected=Locks.split(snapshot,mg),actual=h.json(`priceLockDeliveryCost(__lock,'${(mg/1000).toFixed(3)}','')`);assert.equal(actual.originalUsedCost,expected.amount);assert.equal(actual.leftoverCost,expected.leftoverCost);assert.deepEqual(actual.materialSources.map(source=>[source.kind,source.quantity,source.amount]),expected.materialSources.map(source=>[source.kind,source.quantity,source.amount]));assert.equal(actual.materialSources.reduce((sum,source)=>sum+source.amount,0)+actual.leftoverMaterialSources.reduce((sum,source)=>sum+source.amount,0),snapshot.amount);}
assert.equal(h.json("priceLockDeliveryCost(__lock,'0.002','').originalUsedCost"),1,'不得按整个锁单混合均价把两毫克算成两分');
});
test('个人料锁价按选中归属报价,公共无料仍可用个人料,界面显示分段与用后余量',async()=>{
const h=harness();h.fields.member=node({value:'assistant'});h.fields.material_source.value='pool';h.fields.quantity.value='1.5';h.use(pool({totalMg:2000,totalAmount:200000,averageRate:100000,remainingMg:2000,personalPools:{assistant:{remainingMg:1000}}}));
const own={kind:'personal_recovery',member:'assistant',quantity:1000,amount:85000,averageRate:85000,allocations:[{payer:'assistant',amount:85000}]},common={kind:'public',member:null,quantity:500,amount:50000,averageRate:100000,allocations:[{payer:'owner',amount:50000}]};h.context.__quote={date:D,member:'assistant',entries:[{lineIndex:0,poolId:D,mg:1500,amount:135000,allocations:[...own.allocations,...common.allocations],materialSources:[own,common]}],pools:[{poolId:D,revision:'segmented-v1',personalRemainingMg:0,personalRemainingAmount:0,publicRemainingMg:1500,publicRemainingAmount:150000,eligibleRemainingMg:1500,before:{personalRemainingMg:1000,publicRemainingMg:2000,eligibleRemainingMg:3000}}]};const calls=[];h.context.__api=async(url,input)=>{calls.push({url,input});return h.context.__quote;};h.run('api=__api;syncPriceLockCreate()');assert.equal(h.nodes.get('#lock-pool-material-estimate').textContent,'待确定');assert.match(h.nodes.get('#lock-pool-material-note').textContent,/正在按订单归属核对/);await h.run('loadMaterialQuote()');assert.equal(calls[0].input.member,'assistant');assert.equal(h.nodes.get('#lock-pool-material-estimate').textContent,'¥1,350.00');assert.match(h.nodes.get('#lock-pool-material-payers').innerHTML,/娜娜个人回收料.*1\.000g.*850\.00.*公共料.*0\.500g.*500\.00/);assert.match(h.nodes.get('#lock-pool-material-note').textContent,/本次后余.*个人回收料 0\.000g.*公共料 1\.500g/);assert.equal(h.poolRoot.dataset.ready,'true');
h.fields.quantity.value='1';h.use(pool({totalMg:0,totalAmount:0,averageRate:null,remainingMg:0,personalPools:{assistant:{remainingMg:1000}}}));h.context.__quote.entries=[{lineIndex:0,poolId:D,mg:1000,amount:85000,allocations:own.allocations,materialSources:[own]}];h.context.__quote.pools=[{poolId:D,revision:'private-only-v1',personalRemainingMg:0,personalRemainingAmount:0,publicRemainingMg:0,publicRemainingAmount:0,eligibleRemainingMg:0,before:{personalRemainingMg:1000,publicRemainingMg:0,eligibleRemainingMg:1000}}];h.run('syncPriceLockCreate()');await h.run('loadMaterialQuote()');assert.equal(h.nodes.get('#lock-pool-material-estimate').textContent,'¥850.00');assert.equal(h.poolRoot.dataset.ready,'true');
});