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

66 lines
12 KiB
JavaScript
Raw Normal View History

'use strict';
const {test}=require('node:test'),assert=require('node:assert/strict'),{randomUUID}=require('node:crypto');
const {Ledger,today,day,money,weight,text,fail,ACCOUNTS,ACTIVE_POCKETS}=require('../ledger'),{createUser}=require('../server');
const Rolling=require('../rolling-material-pools'),PriceLocks=require('../price-locks'),Calc=require('../public/calculations');
const D=today(),P=new Date(Date.parse(D+'T12:00:00Z')-86400000).toISOString().slice(0,10);
function fixture(t){
const l=new Ledger(':memory:');t.after(()=>l.close());const actors={};for(const member of ['owner','assistant','assistant2']){const role=member==='owner'?'owner':'assistant',name='合成'+member;actors[member]={id:createUser(l,name,role,'synthetic-pool-lock-password',member),name,role,member};}l.enableTeamMode();
const run=(data,fn,member='owner',key=randomUUID())=>l.scope(actors[member],()=>l.transact(key,actors[member],data,fn));
const env=date=>({day,money,weight,text,fail,accounts:ACCOUNTS,pockets:ACTIVE_POCKETS,selfPockets:ACTIVE_POCKETS,today:()=>date,now:()=>date+'T01:00:00.000Z',orderIdentity:(v,n,max)=>text(v,n,max),pick:(v,choices,n)=>choices.includes(v)?v:fail(n+'无效')});
const buy=(grams,total,payer='owner',date=D)=>{const input={date,grams,total,payer,note:'合成购料'};return run(input,()=>l.createMaterialPurchase(input,actors.owner));};
const enable=(date=D)=>{const e=env(date),p=Rolling.previewEnable(l,{date},actors.owner,e);return run({},()=>Rolling.enable(l,{date,revision:p.revision,verified:true},actors.owner,e));};
const lock=(grams='1.500',date=D,member='assistant')=>{const pool=l.materialPoolDetail(date),input={date,customer:'合成锁价私密客户',salesperson:'合成开单人',line:{name:'足金挂件',unit:'g',quantity:grams,goldPrice:'2000',laborRate:'0',laborMode:'gram'},material:{source:'pool',poolId:date,revision:pool.revision},payment:{amount:String(Number(grams)*2000),account:'助理微信',verified:true}};return run(input,()=>date===D?l.createPriceLock(input,actors[member]):Rolling.withHistorical(l,()=>PriceLocks.create(l,input,actors[member],env(date))),member);};
const deliver=(id,grams,extra={})=>{const lock=l.priceLockDetail(id),total=Calc.orderTotal([Math.round(Number(grams)*200000)],0,'yuan').total,diff=total-lock.netReceived,input={date:D,revision:lock.revision,verified:true,line:{quantity:grams,laborRate:'0',laborMode:'gram',payer:'assistant',costParts:{labor:'0',accessories:'0',other:'0'},costPayers:{material:'owner',labor:'assistant'}},discount:'0',inventory:{pocket:'现货',original:'stocked'},settlement:{amount:(Math.abs(diff)/100).toFixed(2),account:'助理微信',verified:true},fee_items:[],...extra};return run(input,()=>l.deliverPriceLock(id,input,actors.owner));};
const issue=(grams)=>{const input={date:D,customer:'合成普通客户',salesperson:'合成',payment_account:'助理微信',lines:[{name:'足金999',unit:'g',quantity:grams,pocket:'现货',payer:'owner',sale:String(Number(grams)*2000),costParts:{material:'',labor:'0',accessories:'0',other:'0'},costMaterial:{mode:'pool',poolId:D}}],fee_items:[]};return run(input,()=>l.issueOrder(input,actors.owner)).id;};
run({},()=>l.stock({date:P,kind:'opening',pocket:'现货',grams:'100',note:'合成库存'},actors.owner));
return {l,actors,run,env,buy,enable,lock,deliver,issue};
}
function facts(l){return JSON.stringify(l.rows("SELECT name FROM sqlite_master WHERE type='table' AND name NOT LIKE 'sqlite_%' ORDER BY name").map(({name})=>[name,l.rows('SELECT * FROM "'+name+'" ORDER BY rowid')]));}
test('料池锁价真预留、沿FIFO多人付款归属,客户款之外无新增现金、利润或实物,普通单不会越过锁重',t=>{
const f=fixture(t);f.buy('0.8','800','assistant');f.buy('1.2','1200');f.enable();const stock=f.l.rows('SELECT * FROM movements'),lock=f.lock(),d=f.l.priceLockDetail(lock.id),pool=f.l.materialPools().current;
assert.equal(d.material_source,'pool');assert.equal(d.material_amount,150000);assert.deepEqual(d.materialPool.allocations,[{payer:'assistant',amount:80000},{payer:'owner',amount:70000}]);assert.equal(pool.usedMg,1500);assert.equal(pool.remainingMg,500);assert.equal(d.material_events.length,0);
assert.equal(f.l.rows('SELECT * FROM orders').length,0);assert.equal(f.l.rows('SELECT * FROM journal').length,0);assert.deepEqual(f.l.rows('SELECT * FROM movements'),stock);assert.equal(f.l.rows("SELECT * FROM team_fund_cash WHERE source_kind='price_lock' AND kind='outlay'").length,0);
const id=f.issue('0.5');assert.equal(f.l.detail(id).goodsCost,50000);assert.equal(f.l.materialPools().current.remainingMg,0);
const before=facts(f.l);f.l.priceLockDetail(lock.id);f.l.materialPools();assert.equal(facts(f.l),before);
});
test('同日少重交付只耗一次,随后补料同步原锁量、实际成本与利润,反向FIFO和分厘均守恒',t=>{
const f=fixture(t);f.buy('0.8','800','assistant');f.buy('1.2','1200');f.enable();const lock=f.lock(),id=f.deliver(lock.id,'1.000').id;let p=f.l.materialPools().current;
assert.equal(p.usedMg,1000);assert.equal(p.remainingMg,1000);assert.equal(f.l.detail(id).goodsCost,100000);assert.deepEqual(f.l.rows("SELECT mg FROM movements WHERE kind='sale'").map(r=>r.mg),[-1000]);assert.equal(f.l.rows("SELECT * FROM movements WHERE kind='lock_purchase'").length,0);
f.buy('1','2000','assistant2');p=f.l.materialPools().current;const d=f.l.priceLockDetail(lock.id),o=f.l.detail(id);
assert.equal(d.material_amount,200000);assert.equal(o.goodsCost,133333);assert.equal(o.profit,66667);assert.equal(d.delivery.leftover_cost,66667);assert.equal(p.consumedCost,133333);assert.equal(p.remainingCost,266667);assert.equal(p.totalAmount,p.consumedCost+p.remainingCost);
assert.deepEqual(o.lines[0].materialAllocations.filter(a=>a.source==='original').map(a=>[a.payer,a.amount]),[['assistant',80000],['owner',53333]]);assert.equal(f.l.rows("SELECT * FROM team_fund_cash WHERE source_kind='price_lock' AND kind='outlay'").length,0);
});
test('锁价日跨天冻结,少重余料按原成本与付款来源回交付日池,未用原锁重不进入期初',t=>{
const f=fixture(t);f.buy('0.8','800','assistant',P);f.buy('1.2','1200','owner',P);f.enable(P);const lock=f.lock('1.500',P),old=f.l.priceLockDetail(lock.id);f.buy('1','3000');
assert.equal(f.l.priceLockDetail(lock.id).material_amount,old.material_amount);assert.equal(f.l.materialPools().current.opening.mg,500);assert.equal(f.l.materialPools().current.opening.amount,50000);
const id=f.deliver(lock.id,'0.500').id,p=f.l.materialPools().current;assert.equal(f.l.detail(id).goodsCost,50000);assert.equal(p.totalMg,2500);assert.equal(p.totalAmount,450000);assert.equal(p.usedMg,0);assert.equal(p.remainingMg,2500);assert.equal(f.l.priceLockDetail(lock.id).delivery.leftover_cost,100000);
const ret=f.l.rows('SELECT * FROM price_lock_pool_returns WHERE price_lock_id=?',lock.id);assert.equal(ret.length,1);assert.deepEqual(JSON.parse(ret[0].allocations),[{payer:'assistant',amount:30000},{payer:'owner',amount:70000}]);assert.equal(f.l.rows("SELECT * FROM team_fund_cash WHERE source_kind='price_lock' AND kind='outlay'").length,0);
});
test('采购删除造成锁价成本待补,拒绝交付并完整回滚,补料恢复成本和付款归属',t=>{
const f=fixture(t);f.buy('0.8','800','assistant');const b=f.buy('1.2','1200');f.enable();const lock=f.lock();f.run({},()=>f.l.deleteMaterialPurchase(b.id,{revision:1},f.actors.owner));
assert.equal(f.l.priceLockDetail(lock.id).materialPool.amount,null);const before=facts(f.l);assert.throws(()=>f.deliver(lock.id,'1.5'),/成本待补/);assert.equal(facts(f.l),before);
f.buy('1.2','2400','assistant2');assert.equal(f.l.priceLockDetail(lock.id).material_amount,240000);assert.equal(f.deliver(lock.id,'1.5').status,'delivered');
});
test('已交付池锁整单退货回池与料费往来冲回,原现金支出不重复',t=>{
const f=fixture(t);f.buy('0.8','800','assistant');f.buy('1.2','1200');f.enable();const lock=f.lock(),id=f.deliver(lock.id,'1').id;
f.run({},()=>f.l.action(id,'return',{date:D,verified:true,reason:'合成实物退回',returnPockets:['金料']},f.actors.owner));const p=f.l.materialPools().current;
assert.equal(p.usedMg,0);assert.equal(p.remainingMg,2000);assert.equal(p.remainingCost,200000);assert.equal(f.l.detail(id).profit,0);assert.equal(f.l.rows("SELECT * FROM team_fund_cash WHERE source_kind='price_lock' AND kind='outlay'").length,0);
const entries=f.l.rows("SELECT * FROM team_fund_entries WHERE source_kind='price_lock' AND source_id=? AND kind IN ('material_usage','material_return')",lock.id);assert.equal(entries.reduce((n,r)=>n+(r.from_member==='assistant'?r.amount:-r.amount),0),0);
});
test('历史采购更正先试算回滚,批准重算锁价、交付、余料和下游且留存实际流水',t=>{
const f=fixture(t),first=f.buy('0.8','800','assistant',P);f.buy('1.2','1200','owner',P);f.enable(P);const lock=f.lock('1.500',P),delivered=f.deliver(lock.id,'0.500').id,next=f.issue('1.000'),flows={movements:f.l.rows('SELECT * FROM movements'),payments:f.l.rows('SELECT * FROM payments'),events:f.l.rows('SELECT * FROM price_lock_events')};
const before={reservation:f.l.rows('SELECT * FROM price_lock_pool_reservations'),returns:f.l.rows('SELECT * FROM price_lock_pool_returns'),orders:f.l.rows('SELECT * FROM orders'),days:f.l.rows('SELECT * FROM material_rolling_days')},input={action:'edit',revision:1,date:P,grams:'0.8',total:'1600',payer:'assistant',note:'合成核实旧采购',reason:'合成历史更正',verified:true};
assert.throws(()=>f.l.editMaterialPurchase(first.id,input,f.actors.owner),/冻结/);
const request=f.run(input,()=>f.l.requestMaterialPurchaseChange(first.id,input,f.actors.owner));assert.equal(request.preview.relatedPriceLocks[0].id,lock.id);assert.deepEqual(f.l.rows('SELECT * FROM price_lock_pool_reservations'),before.reservation);assert.deepEqual(f.l.rows('SELECT * FROM price_lock_pool_returns'),before.returns);assert.deepEqual(f.l.rows('SELECT * FROM orders'),before.orders);assert.deepEqual(f.l.rows('SELECT * FROM material_rolling_days'),before.days);
f.run({},()=>f.l.approveMaterialPurchaseChange(request.id,{revision:1,verified:true},f.actors.owner));const d=f.l.priceLockDetail(lock.id),pool=f.l.materialPools().current;
assert.equal(d.material_amount,210000);assert.equal(f.l.detail(delivered).goodsCost,70000);assert.equal(d.delivery.leftover_cost,140000);assert.equal(pool.totalMg,1500);assert.equal(pool.totalAmount,210000);assert.equal(f.l.detail(next).goodsCost,140000);assert.equal(pool.remainingCost,70000);
assert.deepEqual(f.l.rows('SELECT * FROM movements'),flows.movements);assert.deepEqual(f.l.rows('SELECT * FROM payments'),flows.payments);assert.deepEqual(f.l.rows('SELECT * FROM price_lock_events'),flows.events);assert.equal(f.l.one('PRAGMA integrity_check').integrity_check,'ok');assert.equal(f.l.rows('PRAGMA foreign_key_check').length,0);
});
test('补重保留手动实际购料,原料池不再扣重或造采购,退货只记非现金回料',t=>{
const f=fixture(t);f.buy('0.8','800','assistant');f.buy('1.2','1200');f.enable();const lock=f.lock('1.500'),id=f.deliver(lock.id,'1.700',{extraMaterial:{rate:'1200',payer:'assistant2',verified:true},inventory:{pocket:'现货',original:'stocked',extra:'receive'}}).id,o=f.l.detail(id);
assert.equal(o.goodsCost,174000);assert.equal(f.l.materialPools().current.usedMg,1500);assert.deepEqual(f.l.rows('SELECT mg FROM movements WHERE order_id=? ORDER BY rowid',id).map(r=>r.mg),[200,-1700]);assert.deepEqual(f.l.priceLockDetail(lock.id).material_events.map(r=>[r.source,r.amount,r.payer]),[['extra',24000,'assistant2']]);
f.run({},()=>f.l.action(id,'return',{date:D,verified:true,reason:'合成补重退回',returnPockets:['金料']},f.actors.owner));const p=f.l.materialPools().current;assert.equal(p.remainingMg,2200);assert.equal(p.remainingCost,224000);assert.equal(f.l.rows("SELECT * FROM team_fund_cash WHERE source_kind='price_lock' AND kind='outlay'").reduce((n,r)=>n+r.amount,0),24000);
});
test('料池必须显式选择且启用统一结转,无料、旧日期、过期版本及重复入库被拒绝',t=>{
const f=fixture(t);f.buy('2','2000');const before=facts(f.l);assert.throws(()=>f.lock(),/启用统一/);assert.equal(facts(f.l),before);f.enable();const lock=f.lock(),snapshot=facts(f.l);assert.throws(()=>f.deliver(lock.id,'1.5',{inventory:{pocket:'现货',original:'receive'}}),/不能重复入库/);assert.equal(facts(f.l),snapshot);
});