支持多商品锁价及待交付修改作废审批

This commit is contained in:
summer committed 2026-11-08 02:22:58 +08:00
1 parent 1cbcdc728c
commit 337b2a709f
28 files changed
+1187 -344

No files matched your search

@@ -0,0 +1,89 @@
'use strict';
// 虚构数据与内存表单;不启动服务、不读取真实账本。
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'),Fees=require('../public/fee-estimates');
const D='2026-11-08',OLD='2026-11-07',ID='11111111-1111-4111-8111-111111111111',A='22222222-2222-4222-8222-222222222222',B='33333333-3333-4333-8333-333333333333';
function node(extra={}){return {value:'',checked:false,disabled:false,required:false,readOnly:false,hidden:false,textContent:'',innerHTML:'',dataset:{},firstChild:{textContent:''},classList:{add(){},remove(){}},closest(){return this.label??=node();},...extra};}
function controls(values){return Object.fromEntries(Object.entries(values).map(([name,value])=>[name,node({name,value:typeof value==='boolean'?'on':String(value),checked:value===true})]));}
function harness(){
const nodes=new Map(),saved=new Map(),posts=[],handlers={},user={id:'multi-ui-owner',name:'麦麦',role:'owner',member:'owner'};
const context=vm.createContext({LedgerCalc:Calc,FeeEstimates:Fees,crypto:{randomUUID},URLSearchParams,setInterval(){},setTimeout(){},clearTimeout(){},console,document:{querySelector:selector=>nodes.get(selector)||null,querySelectorAll:()=>[],addEventListener(type,handler){(handlers[type]??=[]).push(handler);}},window:{scrollTo(){},confirm(){return true;}},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','price-lock-changes-ui.js','material-pools-ui.js','order-edit-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()=>{};finishPendingPriceLockSave=async()=>{};mutate=async(url,data)=>{__posts.push({url,data});return {id:'${ID}',price_lock_id:'${ID}'};};toast=()=>{};`);
for(const key of ['#main','#price-lock-error','#lock-create-total','#lock-sale-estimate'])nodes.set(key,node());
return {nodes,saved,posts,handlers,context,run,json,usePool(pool){context.__pool=pool;run('materialPoolsCache={rolling:{enabled:true,cutover:state.today},current:__pool,rows:[__pool]};materialPoolsCacheUser=state.user.id;priceLockPoolError="";');}};
}
function createForm(h,specs=[{},{}],extra={}){
const fields=controls({date:D,customer:'合成客户',salesperson:'合成开单人',discount:'0',note:'合成备注',received_amount:'1000',payment_verified:true,...extra});
const rows=specs.map((spec,index)=>{
const values=controls({name:'合成黄金'+(index+1),code:'',quantity:'1',goldPrice:'900',laborRate:'20',laborMode:'gram',pieces:'1',material_source:'manual',material_rate:'800',material_payer:index?'assistant':'owner',material_verified:true,material_pool_date:'',material_pool_rate:'',...spec});
const parts=Object.fromEntries(['manual-material','pool-material','material-estimate','pool-material-estimate','pool-material-note','pool-material-payers','sale-estimate'].map(key=>[key,node()]));parts['manual-material'].querySelectorAll=()=>['material_rate','material_payer','material_verified'].map(name=>values[name]);
return node({fields:values,parts,dataset:{lineId:spec.lineId||''},querySelector(selector){const name=selector.match(/\[name="([^"]+)"\]/)?.[1],part=selector.match(/\[data-lock-part="([^"]+)"\]/)?.[1];return name?values[name]||null:part?parts[part]||null:null;},querySelectorAll:()=>[]});
});
const form=node({id:'price-lock-create-form',fields,rows,querySelector(selector){const name=selector.match(/\[name="([^"]+)"\]/)?.[1];return fields[name]||rows[0]?.fields[name]||null;},querySelectorAll(selector){return selector==='[data-price-lock-sale]'?rows:selector==='[name="material_source"]'?rows.map(row=>row.fields.material_source):[];}});
h.nodes.set('#price-lock-create-form',form);h.context.__form=form;return {form,fields,rows};
}
function fixtureLock(){return {id:ID,number:'SJ-SYNTHETIC',date:D,customer:'合成<客户>',salesperson:'合成开单人',note:'合成备注',discount:0,estimated_total:281500,netReceived:281500,status:'pending',revision:2,cash_events:[],credit_card_fees:[],material_source:'manual',material_amount:250000,lines:[{id:A,line_index:0,locked_mg:2000,sell_rate:90000,buy_rate:80000,buy_payer:'owner',material_source:'manual',material_amount:160000,line:{name:'合成手镯',quantity:2000,goldPrice:90000,laborRate:2000,laborMode:'gram',charges:[],sale:184000}},{id:B,line_index:1,locked_mg:1000,sell_rate:95000,buy_rate:90000,buy_payer:'assistant',material_source:'manual',material_amount:90000,line:{name:'合成戒指',quantity:1000,goldPrice:95000,laborRate:2500,laborMode:'gram',charges:[],sale:97500}}]};}
function deliveryForm(h,lock=fixtureLock()){
const values=[{quantity:'1.8',goldPrice:'900',laborRate:'20',pocket:'现货',original_stock:'receive',extra_rate:'',extra_payer:'',extra_stock:'',extra_verified:false,material:'1440.00'},{quantity:'1.2',goldPrice:'950',laborRate:'25',pocket:'金料',original_stock:'stocked',extra_rate:'950',extra_payer:'assistant2',extra_stock:'receive',extra_verified:true,material:'1090.00'}];
const roots=values.map((value,index)=>{
const line={name:lock.lines[index].line.name,unit:'g',quantity:value.quantity,goldPrice:value.goldPrice,laborRate:value.laborRate,laborMode:'gram',pieces:'1',charges:[],pricingMode:'auto',pocket:value.pocket,payer:'owner',costParts:{material:value.material,labor:'10',accessories:'0',other:'0'},costMaterial:{mode:'total'},costLabor:{mode:'total'},costPayers:{material:index?'assistant':'owner',labor:'owner'}};
const fields=controls(value),row=node({__line:line,querySelector(selector){return fields[selector.match(/\[name="([^"]+)"\]/)?.[1]]||null;}});
return node({fields,row,dataset:{lineId:lock.lines[index].id},querySelector(selector){if(selector==='.line-item')return row;return fields[selector.match(/\[name="([^"]+)"\]/)?.[1]]||null;}});
});
const fields=controls({date:D,delivery_note:'合成全单交付',discount:'0',settlement_amount:'11.00',settlement_verified:true,delivery_verified:true}),form=node({id:'price-lock-delivery-form',dataset:{id:lock.id,revision:'2'},querySelector(selector){return fields[selector.match(/\[name="([^"]+)"\]/)?.[1]]||null;},querySelectorAll:selector=>selector==='[data-price-lock-delivery-item]'?roots:[]});
h.nodes.set('#price-lock-delivery-form',form);h.context.__form=form;h.context.__lock=lock;h.run('currentPriceLock=__lock;collectLine=row=>row.__line;readFeeRows=()=>[];syncPriceLockForm=()=>{};');return {form,fields,roots};
}
test('多商品锁价独立采集名称、售价、克工费及付款人,整单只收一次款并只做一次取整',async()=>{
const h=harness(),f=createForm(h,[{name:'合成手镯',quantity:'2',goldPrice:'900',laborRate:'20',material_rate:'800'},{name:'合成戒指',quantity:'1',goldPrice:'950',laborRate:'25',material_rate:'900',material_payer:'assistant2'}]);
h.run('syncPriceLockCreate()');assert.equal(h.nodes.get('#lock-create-total').textContent,'¥2,815');assert.equal(f.rows[0].parts['material-estimate'].textContent,'¥1,600.00');assert.equal(f.rows[1].parts['material-estimate'].textContent,'¥900.00');
const data=h.json('collectPriceLockCreate()');assert.equal(data.lines.length,2);assert.equal(Object.hasOwn(data,'line'),false);assert.equal(Object.hasOwn(data,'material'),false);assert.equal(data.lines[1].material.payer,'assistant2');assert.equal(data.payment.amount,'1000');
await h.run('submitPriceLockForm(__form)');assert.equal(h.posts.length,1);assert.equal(h.posts[0].data.lines.length,2);assert.equal(h.posts[0].url,'/api/price-locks');
});
test('混合手填和料池的多行草稿各自保留隐藏手填成本,料池只占自己的行',()=>{
const h=harness(),f=createForm(h,[{quantity:'1',material_source:'manual',material_rate:'800'},{quantity:'0.001',material_source:'pool',material_rate:'900',material_payer:'assistant2'}]);
h.usePool({id:D,date:D,totalMg:3,totalAmount:2,revision:'p1',usages:[],purchases:[{payer:'owner',amount:2}]});h.run('syncPriceLockCreate()');
assert.deepEqual(h.json('materialLockQuoteInput()').entries,[{lineIndex:1,poolId:D,mg:1}]);assert.equal(f.rows[1].parts['pool-material-estimate'].textContent,'¥0.01');assert.equal(f.rows[0].parts['manual-material'].hidden,false);assert.equal(f.rows[1].parts['manual-material'].hidden,true);
const draft=JSON.parse(h.saved.get('mm-price-lock-draft-multi-ui-owner'));assert.deepEqual(draft.lines[1].material.manual,{rate:'900',payer:'assistant2',verified:true});assert.equal(draft.lines[0].material.rate,'800');
});
test('同单多个池行累计分币且FIFO付款区间连续,合计不足时全部阻止保存',async()=>{
const h=harness(),f=createForm(h,[{quantity:'0.001',material_source:'pool'},{quantity:'0.001',material_source:'pool'}]);h.usePool({id:D,date:D,totalMg:3,totalAmount:2,revision:'p1',usages:[],purchases:[{payer:'owner',amount:1},{payer:'assistant',amount:1}]});h.run('syncPriceLockCreate()');
assert.equal(f.rows[0].parts['pool-material-estimate'].textContent,'¥0.01');assert.equal(f.rows[1].parts['pool-material-estimate'].textContent,'¥0.00');assert.equal(h.json(`priceLockPoolPreview('${D}','0.001',1).allocations`)[0].payer,'assistant');
f.rows[0].fields.quantity.value='0.002';f.rows[1].fields.quantity.value='0.002';await assert.rejects(h.run('submitPriceLockForm(__form)'),/还缺 0\.001g/);assert.equal(h.posts.length,0);
});
test('整单交付保持每行身份与货盘,少重留料和另一行补料不互相抵消,只算一笔11元补款',async()=>{
const h=harness(),f=deliveryForm(h),data=h.json('collectPriceLockDelivery()');assert.equal(data.lines[0].lineId,A);assert.equal(data.lines[1].lineId,B);assert.equal(data.lines[0].inventory.pocket,'现货');assert.equal(data.lines[1].inventory.pocket,'金料');
const short=Calc.priceLockCost({lockedQuantity:'2',quantity:'1.8',buyRate:'800'}),extra=Calc.priceLockCost({lockedQuantity:'1',quantity:'1.2',buyRate:'900',extraBuyRate:'950'});assert.equal(short.leftoverMg,200);assert.equal(extra.extraMg,200);assert.equal(Calc.orderTotal(data.lines.map(line=>Calc.sale(line).sale),0,'yuan').total-281500,1100);
await h.run('submitPriceLockForm(__form)');const posted=h.posts[0].data;assert.equal(posted.lines.length,2);assert.equal(Object.hasOwn(posted,'line'),false);assert.equal(posted.settlement.amount,'11.00');assert.equal(Object.hasOwn(posted.lines[0],'extraMaterial'),false);assert.equal(posted.lines[1].extraMaterial.payer,'assistant2');assert.equal(posted.lines[1].inventory.extra,'receive');assert.equal(Object.hasOwn(posted.lines[0].costParts,'material'),false);
f.roots[1].fields.extra_verified.checked=false;await assert.rejects(h.run('submitPriceLockForm(__form)'),/商品 2.*补重/);assert.equal(h.posts.length,1);
});
test('交付遗漏行、商品顺序失配、第二行漏货盘都不能变成部分交付',async()=>{
const h=harness(),f=deliveryForm(h);f.roots.pop();await assert.rejects(h.run('submitPriceLockForm(__form)'),/全部锁价商品/);assert.equal(h.posts.length,0);
const v=deliveryForm(h);v.roots[0].dataset.lineId=B;assert.throws(()=>h.run('collectPriceLockDelivery()'),/不一致/);v.roots[0].dataset.lineId=A;v.roots[1].row.__line.pocket='';v.roots[1].fields.pocket.value='';await assert.rejects(h.run('submitPriceLockForm(__form)'),/商品 2.*货盘/);
});
test('锁价详情列出所有商品及原锁价,交付后显示逐行最终克重、补料、余料和货盘',()=>{
const h=harness(),lock=fixtureLock();lock.status='delivered';lock.lines[0].delivery={quantity:1800,extra_mg:0,leftover_mg:200,inventory:{pocket:'现货'}};lock.lines[1].delivery={quantity:1200,extra_mg:200,leftover_mg:0,inventory:{pocket:'金料'}};h.context.__lock=lock;
const html=h.run('priceLockFacts(__lock)');for(const text of ['合成手镯','合成戒指','3.000g','900.00/克','950.00/克','1.800g','1.200g','补重 0.200g','剩料留盘 0.200g','货盘 现货','货盘 金料'])assert.ok(html.includes(text),text);assert.doesNotMatch(html,/NaN|undefined/);
});
test('待交付修改独立暂存,保留每行ID;当天助理直存、历史助理走申请,版本冲突禁止保存',()=>{
const h=harness(),f=createForm(h,[{lineId:A},{lineId:B}],{pending_edit_reason:'更正款式',pending_edit_verified:true});f.form.dataset.priceLockEditId=ID;h.context.__lock=fixtureLock();h.run(`priceLockEditEntry={id:'${ID}',user:session.user.id,revision:2,requiresApproval:false,lock:__lock,inputs:collectPriceLockCreate(),reason:'更正款式'};`);h.saved.set('mm-price-lock-draft-multi-ui-owner','普通锁价草稿');h.run('syncPriceLockCreate()');
assert.equal(h.saved.get('mm-price-lock-draft-multi-ui-owner'),'普通锁价草稿');const edit=JSON.parse(h.saved.get('mm-price-lock-edit-multi-ui-owner-'+ID));assert.equal(edit.inputs.lines[1].lineId,B);
h.run("session.user.role='assistant';state.user.role='assistant';");assert.equal(h.run('pendingPriceLockEditPayload(collectPriceLockCreate(),__form).url'),'/api/price-locks/'+ID+'/edit');f.fields.date.value=OLD;assert.equal(h.run('pendingPriceLockEditPayload(collectPriceLockCreate(),__form).data.action'),'edit');assert.match(h.run('pendingPriceLockEditPayload(collectPriceLockCreate(),__form).url'),/change-requests$/);
h.run('priceLockEditEntry.conflicted=true');assert.throws(()=>h.run('pendingPriceLockEditPayload(collectPriceLockCreate(),__form)'),/已有新记录/);
});
test('编辑料池试算无论公共或个人都排除本单,携带各行身份并允许原历史日',()=>{
const h=harness(),f=createForm(h,[{lineId:A,material_source:'pool'}],{date:OLD});f.form.dataset.priceLockEditId=ID;h.context.__lock={...fixtureLock(),date:OLD};h.run(`priceLockEditEntry={id:'${ID}',user:session.user.id,revision:2,requiresApproval:true,lock:__lock,inputs:collectPriceLockCreate()};`);
h.usePool({id:D,date:D,totalMg:1000,totalAmount:80000,revision:'p1',usages:[],purchases:[{payer:'owner',amount:80000}]});
h.context.__quote={result:{entries:[{lineIndex:0,poolId:OLD,mg:1000,amount:80000,allocations:[{payer:'owner',amount:80000}],materialSources:[{kind:'public',quantity:1000,amount:80000,averageRate:80000,allocations:[{payer:'owner',amount:80000}]}]}],pools:[{poolId:OLD,revision:'old-p1',before:{eligibleRemainingMg:1000},eligibleRemainingMg:0}]}};h.run('materialQuoteFor=(form,input)=>{__lastQuote=input;return __quote;};syncPriceLockCreate()');
const input=h.json('__lastQuote');assert.equal(input.priceLockId,ID);assert.equal(input.entries[0].lineId,A);assert.equal(input.date,OLD);assert.equal(f.rows[0].parts['pool-material-estimate'].textContent,'¥800.00');assert.equal(f.rows[0].parts['pool-material'].dataset.ready,'true');
});
test('录错作废仅提交原因核实与版本,历史助理申请不额外登记退款或退料',async()=>{
const h=harness();h.run(`priceLockPendingAction={id:'${ID}',user:session.user.id,revision:2,requiresApproval:true,inputs:{date:'${OLD}'}};session.user.role='assistant';state.user.role='assistant';`);
const fields=controls({reason:'合成录错单',verified:true}),form=node({querySelector:selector=>fields[selector.match(/\[name="([^"]+)"\]/)?.[1]]||null});h.context.__form=form;await h.run('submitPriceLockCancel(__form)');assert.equal(h.posts[0].url,'/api/price-locks/'+ID+'/change-requests');assert.deepEqual(JSON.parse(JSON.stringify(h.posts[0].data)),{revision:2,reason:'合成录错单',verified:true,action:'cancel'});fields.verified.checked=false;await assert.rejects(h.run('submitPriceLockCancel(__form)'),/勾选整单作废/);
});
test('审批按请求锁价版本核实,过期不可批准;驳回必填且所有入口进入幂等恢复白名单',async()=>{
const h=harness(),fields=controls({review_note:'已核实合成数据',verified:true}),form=node({querySelector:selector=>fields[selector.match(/\[name="([^"]+)"\]/)?.[1]]||null});h.context.__form=form;h.run(`priceLockChangeEntry={id:'request',requestId:'request',price_lock_id:'${ID}',status:'pending',revision:9,price_lock_revision:2,stale:false};`);h.context.__button={value:'approve'};
await h.run('submitPriceLockReview(__form,__button)');assert.deepEqual(JSON.parse(JSON.stringify(h.posts[0].data)),{revision:2,verified:true,note:'已核实合成数据'});h.run('priceLockChangeEntry.stale=true');await assert.rejects(h.run('submitPriceLockReview(__form,__button)'),/已有变化/);h.context.__button={value:'reject'};fields.review_note.value='';await assert.rejects(h.run('submitPriceLockReview(__form,__button)'),/驳回原因/);
for(const url of ['/api/price-locks/x/edit','/api/price-locks/x/cancel','/api/price-locks/x/change-requests','/api/price-lock-changes/x/approve','/api/price-lock-changes/x/reject'])assert.equal(h.run(`retryableMutation('${url}')`),true,url);
});