123 lines
18 KiB
JavaScript
123 lines
18 KiB
JavaScript
'use strict';
|
|||
|
|
const {test}=require('node:test'),assert=require('node:assert/strict'),{randomUUID,createHash}=require('node:crypto');
|
||
|
|
const fs=require('node:fs'),os=require('node:os'),path=require('node:path');
|
||
|
|
const {Ledger,today}=require('../ledger'),{createApp,createUser}=require('../server');
|
||
|
|
const RecoveryChanges=require('../recovery-changes');
|
||
|
|
const owner={id:'synthetic-pair-integration-owner',name:'合成对数经办',role:'owner'},D=today();
|
||
|
|
const contents=l=>JSON.stringify(l.rows("SELECT name FROM sqlite_master WHERE type='table' ORDER BY name").map(({name})=>[name,l.rows('SELECT * FROM "'+name+'" ORDER BY rowid')]));
|
||
|
|
function fixture(t){
|
||
|
|
const l=new Ledger(':memory:'),cleanups=[];t.after(async()=>{for(const cleanup of cleanups.reverse())await cleanup();l.close();});
|
||
|
|
const run=(input,fn,actor=owner,key=randomUUID())=>l.transact(key,actor,input,fn);
|
||
|
|
const normal=run({},()=>l.createPocket({name:'合成成品盘'},owner)).pocket;
|
||
|
|
run({},()=>l.stock({kind:'increase',date:D,pocket:normal.key,grams:'20',note:'合成历史重量'},owner));
|
||
|
|
const enable=(initialCount=5)=>run({},()=>l.updatePocket(normal.key,{revision:l.pocket(normal.key).revision,countUnit:'pair',initialCount,countVerified:true},owner)).pocket;
|
||
|
|
const inv=()=>l.inventory().find(row=>row.pocket===normal.key);
|
||
|
|
const lock=()=>{const value={date:D,customer:'合成锁价客户',salesperson:'合成经办',line:{name:'足金合成成品',quantity:'2',goldPrice:'1000',laborMode:'gram',laborRate:'0',pieces:'7'},material:{rate:'900',payer:'owner',verified:true},payment:{amount:'2000',account:'麦麦微信',verified:true},discount:'0'};return run(value,()=>l.createPriceLock(value,owner));};
|
||
|
|
const delivery=(id,extra={})=>{const value={date:D,revision:l.priceLockDetail(id).revision,verified:true,line:{quantity:'2.200',stockCount:'2',laborMode:'piece',laborRate:'0',pieces:'7',charges:[],payer:'owner',costParts:{labor:'0',accessories:'0',other:'0'},costPayers:{material:'owner',labor:'owner'}},inventory:{pocket:normal.key,original:'receive',extra:'receive',countSource:'receive'},extraMaterial:{rate:'900',payer:'owner',verified:true},settlement:{amount:'200',account:'麦麦微信',verified:true},fee_items:[],...extra};return run({id,value},()=>l.deliverPriceLock(id,value,owner));};
|
||
|
|
const recovery=(extra={},line={})=>{const value={date:D,mode:'exchange',customer:'合成置换客户',salesperson:'合成经办',old_lines:[{name:'合成旧料',incoming_weight:'1',melted_weight:'1',purity:'100'}],buy_rate:'900',payer:'owner',payment_account:'麦麦微信',verified:true,exchange:{name:'足金合成新货',quantity:'3',pocket:normal.key,stockCount:'2',gold_price:'1000',labor_rate:'0',labor_mode:'gram',depreciation_rate:'10',cost_material:{mode:'gram',rate:'900'},cost_labor:{mode:'total',amount:'0'},cost_payer:'owner',discount:'0',rounding_mode:'cent',...line},...extra};return run(value,()=>l.createRecovery(value,owner));};
|
||
|
|
const update=(id,extra={})=>{const edit=l.recoveryEdit(id,owner),value={...edit.inputs,revision:edit.revision,reason:'合成更正',...extra};return run({id,value},()=>l.updateRecovery(id,value,owner));};
|
||
|
|
const cancel=(id,extra={})=>{const value={revision:l.recoveryEdit(id,owner).revision,reason:'合成作废',verified:true,...extra};return run({id,value},()=>l.cancelRecovery(id,value,owner));};
|
||
|
|
return {l,run,pocket:normal.key,enable,inv,lock,delivery,recovery,update,cancel,cleanups};
|
||
|
|
}
|
||
|
|
|
||
|
|
test('锁价原锁料与补重只入黄金,显式本次新入库成品只加一次对数,每行销售准确扣除',t=>{
|
||
|
|
const f=fixture(t);f.enable();const lock=f.lock(),input={};const result=f.delivery(lock.id,input),order=f.l.detail(result.id),rows=f.l.rows('SELECT * FROM movements WHERE order_id=? ORDER BY rowid',result.id);
|
||
|
|
assert.equal(order.lines[0].stockCount,2);assert.equal(order.lines[0].pieces,7);assert.equal(f.inv().count,5);assert.equal(f.inv().mg,20000);
|
||
|
|
assert.deepEqual(rows.filter(row=>row.kind==='lock_purchase').map(row=>[row.mg,f.l.movementStockCount(row.id)]),[[2000,null],[200,null]]);
|
||
|
|
assert.deepEqual(rows.filter(row=>row.kind==='lock_finished').map(row=>[row.mg,f.l.movementStockCount(row.id)]),[[0,2]]);
|
||
|
|
assert.deepEqual(rows.filter(row=>row.kind==='sale').map(row=>[row.mg,f.l.movementStockCount(row.id)]),[[-2200,-2]]);
|
||
|
|
const delivered=f.l.priceLockDetail(lock.id);assert.equal(delivered.lines[0].delivery.stockCount,2);assert.equal(delivered.lines[0].delivery.inventory.countSource,'receive');
|
||
|
|
assert.equal(order.total,220000);assert.equal(order.netReceived,220000);assert.equal(order.goodsCost,198000);assert.equal(order.profit,22000);
|
||
|
|
const dto=f.l.publicOrder(result.id);assert.ok(!JSON.stringify(dto).includes('stockCount'));assert.ok(!JSON.stringify(dto).includes('countSource'));
|
||
|
|
const before=contents(f.l);assert.throws(()=>f.delivery(lock.id),/已交付/);assert.equal(contents(f.l),before);
|
||
|
|
});
|
||
|
|
|
||
|
|
test('锁价已有成品只扣对数,库存不足、缺成品来源和工费件数不能代替对数时整笔回滚',t=>{
|
||
|
|
const f=fixture(t);f.enable(1);const lock=f.lock(),before=contents(f.l);
|
||
|
|
const line={quantity:'2',stockCount:'2',laborMode:'gram',laborRate:'0',pieces:'99',payer:'owner',costParts:{labor:'0',accessories:'0',other:'0'},costPayers:{material:'owner',labor:'owner'}};
|
||
|
|
assert.throws(()=>f.delivery(lock.id,{line,inventory:{pocket:f.pocket,original:'stocked',countSource:'stocked'},settlement:undefined,extraMaterial:undefined}),/对数不足/);assert.equal(contents(f.l),before);
|
||
|
|
assert.throws(()=>f.delivery(lock.id,{inventory:{pocket:f.pocket,original:'receive',extra:'receive'}}),/成品来源/);assert.equal(contents(f.l),before);
|
||
|
|
assert.throws(()=>f.delivery(lock.id,{line:{...line,stockCount:undefined}}),/库存对数/);assert.equal(contents(f.l),before);
|
||
|
|
const result=f.delivery(lock.id,{line:{...line,stockCount:'1'},inventory:{pocket:f.pocket,original:'stocked',countSource:'stocked'},settlement:undefined,extraMaterial:undefined});
|
||
|
|
assert.equal(f.inv().count,0);assert.equal(f.inv().mg,18000);assert.equal(f.l.rows("SELECT * FROM movements WHERE order_id=? AND kind='lock_finished'",result.id).length,0);
|
||
|
|
});
|
||
|
|
|
||
|
|
test('两行锁价分别扣各自行对数;成品来源独立选择且整单只记一次客户收款',t=>{
|
||
|
|
const f=fixture(t);f.enable(5);const line={name:'足金合成成品',quantity:'1',goldPrice:'1000',laborMode:'gram',laborRate:'0',material:{rate:'900',payer:'owner',verified:true}};
|
||
|
|
const value={date:D,customer:'合成多行锁价',salesperson:'合成经办',lines:[line,{...line,name:'足金合成另一款'}],payment:{amount:'2000',account:'麦麦微信',verified:true}},lock=f.run(value,()=>f.l.createPriceLock(value,owner));
|
||
|
|
const actual={quantity:'1',laborRate:'0',laborMode:'gram',pieces:'8',charges:[],payer:'owner',costParts:{labor:'0',accessories:'0',other:'0'},costPayers:{material:'owner',labor:'owner'}};
|
||
|
|
const ids=f.l.priceLockDetail(lock.id).lines.map(line=>line.id),input={date:D,revision:lock.revision,verified:true,lines:[{...actual,lineId:ids[0],stockCount:2,inventory:{pocket:f.pocket,original:'stocked',countSource:'stocked'}},{...actual,lineId:ids[1],stockCount:3,inventory:{pocket:f.pocket,original:'receive',countSource:'receive'}}],fee_items:[]},result=f.run(input,()=>f.l.deliverPriceLock(lock.id,input,owner));
|
||
|
|
assert.deepEqual(f.l.detail(result.id).lines.map(line=>line.stockCount),[2,3]);assert.equal(f.inv().count,3);assert.equal(f.inv().mg,19000);
|
||
|
|
assert.deepEqual(f.l.rows("SELECT id FROM movements WHERE order_id=? AND kind='sale' ORDER BY rowid",result.id).map(row=>f.l.movementStockCount(row.id)),[-2,-3]);assert.equal(f.l.priceLockDetail(lock.id).cash_events.length,1);
|
||
|
|
});
|
||
|
|
|
||
|
|
test('置换新货出库、更正对数和取消保持双库存守恒,回收旧料不产生对数,客户单无内部字段',t=>{
|
||
|
|
const f=fixture(t);f.enable(5);const recovery=f.recovery(),number=f.l.detail(recovery.order_id).number;
|
||
|
|
assert.equal(f.inv().count,3);assert.equal(f.inv().mg,17000);assert.equal(recovery.newProduct.stockCount,2);assert.equal(f.l.recoveryEdit(recovery.id,owner).inputs.exchange.stockCount,2);
|
||
|
|
assert.ok(f.l.rows("SELECT id FROM movements WHERE pocket='回收旧料'").every(row=>f.l.movementStockCount(row.id)===null));assert.ok(!JSON.stringify(f.l.publicRecovery(recovery.id,owner)).includes('stockCount'));
|
||
|
|
const originalMovements=JSON.stringify(f.l.rows('SELECT * FROM movements ORDER BY rowid')),originalCounts=JSON.stringify(f.l.rows('SELECT * FROM movement_counts ORDER BY rowid'));
|
||
|
|
f.update(recovery.id,{customer:'合成称呼更正'});assert.equal(JSON.stringify(f.l.rows('SELECT * FROM movements ORDER BY rowid')),originalMovements);assert.equal(JSON.stringify(f.l.rows('SELECT * FROM movement_counts ORDER BY rowid')),originalCounts);
|
||
|
|
const changed={...f.l.recoveryEdit(recovery.id,owner).inputs.exchange,quantity:'4',stockCount:3};f.update(recovery.id,{exchange:changed});assert.equal(f.inv().count,2);assert.equal(f.inv().mg,16000);assert.equal(f.l.detail(recovery.order_id).number,number);assert.equal(f.l.detail(recovery.order_id).lines[0].stockCount,3);
|
||
|
|
const before=contents(f.l);assert.throws(()=>f.update(recovery.id,{exchange:{...changed,quantity:'1',stockCount:6}}),/对数不足/);assert.equal(contents(f.l),before);
|
||
|
|
f.cancel(recovery.id);assert.equal(f.inv().count,5);assert.equal(f.inv().mg,20000);assert.equal(f.l.inventory().find(row=>row.pocket==='回收旧料').mg,0);assert.equal(f.l.detail(recovery.order_id).status,'cancelled');assert.equal(f.l.detail(recovery.order_id).profit,0);
|
||
|
|
assert.equal(f.l.one('SELECT SUM(c.stock_count) AS count FROM movement_counts c JOIN movements m ON m.id=c.movement_id WHERE m.order_id=?',recovery.order_id).count,0);assert.deepEqual(f.l.rows('PRAGMA foreign_key_check'),[]);
|
||
|
|
});
|
||
|
|
|
||
|
|
test('置换未知历史数值不默认一对,启用实物基准不改旧账,取消须确认且不撤销基准',t=>{
|
||
|
|
const f=fixture(t),recovery=f.recovery({}, {stockCount:undefined}),orders=f.l.rows('SELECT * FROM orders ORDER BY rowid'),financial=f.l.rows('SELECT * FROM journal ORDER BY rowid');f.enable(4);
|
||
|
|
assert.deepEqual(f.l.rows('SELECT * FROM orders ORDER BY rowid'),orders);assert.deepEqual(f.l.rows('SELECT * FROM journal ORDER BY rowid'),financial);assert.equal(f.inv().count,4);assert.ok(!Object.hasOwn(f.l.detail(recovery.order_id).lines[0],'stockCount'));
|
||
|
|
const info=f.l.recoveryEdit(recovery.id,owner);assert.equal(info.permissions.requiresLegacyCountVerified,true);assert.match(info.permissions.legacyCountNotice,/基准/);assert.ok(!Object.hasOwn(info.inputs.exchange,'stockCount'));
|
||
|
|
f.update(recovery.id,{customer:'合成旧单称呼更正'});assert.equal(f.inv().count,4);
|
||
|
|
const before=contents(f.l);assert.throws(()=>f.cancel(recovery.id),/确认/);assert.equal(contents(f.l),before);
|
||
|
|
assert.throws(()=>f.update(recovery.id,{exchange:{...f.l.recoveryEdit(recovery.id,owner).inputs.exchange,stockCount:2},legacyCountVerified:true}),/不能补旧单对数/);assert.equal(contents(f.l),before);
|
||
|
|
f.cancel(recovery.id,{legacyCountVerified:true});assert.equal(f.inv().count,4);assert.equal(f.inv().mg,20000);assert.equal(f.l.rows('SELECT c.* FROM movement_counts c JOIN movements m ON m.id=c.movement_id WHERE m.order_id=?',recovery.order_id).length,0);
|
||
|
|
});
|
||
|
|
|
||
|
|
test('锁价实物退回原盘恢复对数,退回金料只恢复黄金重量',t=>{
|
||
|
|
const f=fixture(t);f.enable(5);const first=f.delivery(f.lock().id),second=f.delivery(f.lock().id,{inventory:{pocket:f.pocket,original:'stocked',extra:'stocked',countSource:'stocked'}});
|
||
|
|
assert.equal(f.inv().count,3);
|
||
|
|
f.run({},()=>f.l.action(first.id,'return',{date:D,verified:true,reason:'合成成品退回',returnPockets:[f.pocket]},owner));assert.equal(f.inv().count,5);
|
||
|
|
f.run({},()=>f.l.action(second.id,'return',{date:D,verified:true,reason:'合成金料退回',returnPockets:['金料']},owner));assert.equal(f.inv().count,5);
|
||
|
|
const metal=f.l.rows("SELECT id FROM movements WHERE order_id=? AND kind='return' AND pocket='金料'",second.id);assert.equal(metal.length,1);assert.equal(f.l.movementStockCount(metal[0].id),null);
|
||
|
|
});
|
||
|
|
|
||
|
|
test('置换反复更正净额守恒且流水线性增加,末尾错误将对数、财务和审计一起撤回',t=>{
|
||
|
|
const f=fixture(t);f.enable(5);const recovery=f.recovery();
|
||
|
|
for(let index=0;index<10;index++){const count=index%2?2:3;f.update(recovery.id,{exchange:{...f.l.recoveryEdit(recovery.id,owner).inputs.exchange,stockCount:count}});assert.equal(f.inv().count,5-count);assert.equal(f.inv().mg,17000);}
|
||
|
|
assert.ok(f.l.rows('SELECT * FROM movements WHERE order_id=?',recovery.order_id).length<=42);assert.ok(f.l.rows('SELECT c.* FROM movement_counts c JOIN movements m ON m.id=c.movement_id WHERE m.order_id=?',recovery.order_id).length<=21);
|
||
|
|
const before=contents(f.l),audit=f.l.audit;f.l.audit=function(entity,action,...rest){if(action==='修改回收/置换记录')throw new Error('合成对数末尾异常');return audit.call(this,entity,action,...rest);};
|
||
|
|
try{assert.throws(()=>f.update(recovery.id,{exchange:{...f.l.recoveryEdit(recovery.id,owner).inputs.exchange,stockCount:3}}),/合成对数末尾异常/);assert.equal(contents(f.l),before);}finally{f.l.audit=audit;}
|
||
|
|
f.cancel(recovery.id);assert.equal(f.inv().count,5);assert.equal(f.inv().mg,20000);
|
||
|
|
});
|
||
|
|
|
||
|
|
test('置换审批纳入独立对数依赖,预览不改库存,数量依据变动后不能沿旧预览批准',t=>{
|
||
|
|
const f=fixture(t);f.enable(5);const recovery=f.recovery({member:'assistant'}),assistant={id:'synthetic-pair-approval-assistant',name:'合成申请人',role:'assistant'};
|
||
|
|
// 将审批业务日模拟为次日,基准与交易仍使用真实的同一日期;不回填真实业务库。
|
||
|
|
const nextDay=new Date(Date.parse(D+'T00:00:00Z')+86400000).toISOString().slice(0,10),env={...f.l.businessEnv(),today:()=>nextDay},edit=f.l.recoveryEdit(recovery.id,owner),input={...edit.inputs,revision:edit.revision,reason:'合成对数审批',exchange:{...edit.inputs.exchange,stockCount:3},verified:true};
|
||
|
|
const before=JSON.stringify({movements:f.l.rows('SELECT * FROM movements'),counts:f.l.rows('SELECT * FROM movement_counts')}),result=f.run(input,()=>RecoveryChanges.update(f.l,recovery.id,input,assistant,env),assistant);
|
||
|
|
assert.equal(result.pending,true);assert.equal(JSON.stringify({movements:f.l.rows('SELECT * FROM movements'),counts:f.l.rows('SELECT * FROM movement_counts')}),before);assert.equal(f.inv().count,3);
|
||
|
|
const baseline=f.l.one('SELECT movement_id FROM inventory_count_baselines WHERE pocket=?',f.pocket).movement_id;
|
||
|
|
f.l.run('UPDATE movement_counts SET stock_count=stock_count+1 WHERE movement_id=?',baseline);assert.equal(RecoveryChanges.read(f.l,result.request.id,owner,env).stale,true);
|
||
|
|
const afterChange=contents(f.l),approval={revision:result.request.revision,verified:true};assert.throws(()=>f.run(approval,()=>RecoveryChanges.approve(f.l,result.request.id,approval,owner,env)),/过期/);assert.equal(contents(f.l),afterChange);
|
||
|
|
f.l.run('UPDATE movement_counts SET stock_count=stock_count-1 WHERE movement_id=?',baseline);f.run(approval,()=>RecoveryChanges.approve(f.l,result.request.id,approval,owner,env));assert.equal(f.inv().count,2);assert.equal(f.l.detail(recovery.order_id).lines[0].stockCount,3);
|
||
|
|
});
|
||
|
|
|
||
|
|
test('未启用对数的回收更正保留升级前快照指纹,不因新增空计数结构让旧申请过期',t=>{
|
||
|
|
const f=fixture(t),recovery=f.recovery({member:'assistant'},{stockCount:undefined}),assistant={id:'synthetic-legacy-approval-assistant',name:'合成旧模式申请人',role:'assistant'},nextDay=new Date(Date.parse(D+'T00:00:00Z')+86400000).toISOString().slice(0,10),env={...f.l.businessEnv(),today:()=>nextDay};
|
||
|
|
const edit=f.l.recoveryEdit(recovery.id,owner),input={...edit.inputs,revision:edit.revision,reason:'合成旧模式更正',customer:'合成更正称呼',verified:true},result=f.run(input,()=>RecoveryChanges.update(f.l,recovery.id,input,assistant,env),assistant),saved=f.l.one('SELECT * FROM recovery_changes WHERE id=?',result.request.id),snapshot=JSON.parse(saved.snapshot);
|
||
|
|
assert.ok(!Object.hasOwn(snapshot,'movementCounts'));
|
||
|
|
const legacyDependency={snapshot,pool:require('../rolling-material-pools').dependency(f.l),inventory:f.l.rows('SELECT id,date,pocket,mg FROM movements ORDER BY rowid')};
|
||
|
|
assert.equal(saved.dependency,createHash('sha256').update(JSON.stringify(legacyDependency)).digest('hex'));assert.equal(RecoveryChanges.read(f.l,saved.id,owner,env).stale,false);
|
||
|
|
});
|
||
|
|
|
||
|
|
test('HTTP库存API与CSV导出两种库存,三人共享流水对数而打印保持现有客户字段',async t=>{
|
||
|
|
const f=fixture(t);f.enable(5);const result=f.delivery(f.lock().id),dir=fs.mkdtempSync(path.join(os.tmpdir(),'maimai-pair-api-'));
|
||
|
|
createUser(f.l,'合成接口老板','owner','synthetic-pair-api-password');createUser(f.l,'合成接口助理','assistant','synthetic-pair-api-password');
|
||
|
|
const app=createApp({mode:'trial',port:0,dataDir:dir,ledger:f.l,feishuConfig:{enabled:false}});await new Promise(resolve=>app.server.listen(0,'127.0.0.1',resolve));f.cleanups.push(async()=>{await new Promise(resolve=>app.server.close(resolve));fs.rmSync(dir,{recursive:true,force:true});});
|
||
|
|
const base='http://127.0.0.1:'+app.server.address().port;
|
||
|
|
const login=async name=>{const res=await fetch(base+'/api/login',{method:'POST',headers:{'Content-Type':'application/json','X-Requested-With':'maimai-ledger',Origin:base},body:JSON.stringify({name,password:'synthetic-pair-api-password'})});assert.equal(res.status,200);return res.headers.get('set-cookie').split(';')[0];};
|
||
|
|
const ownerCookie=await login('合成接口老板'),assistantCookie=await login('合成接口助理'),call=(route,cookie=ownerCookie)=>fetch(base+route,{headers:{Cookie:cookie}});
|
||
|
|
for(const cookie of [ownerCookie,assistantCookie]){const state=await (await call('/api/inventory',cookie)).json(),inventory=state.current.find(row=>row.pocket===f.pocket);assert.equal(inventory.countUnit,'pair');assert.equal(inventory.count,5);const rows=await (await call('/api/inventory/movements?pocket='+encodeURIComponent(f.pocket),cookie)).json();assert.ok(rows.movements.some(row=>row.stockCount===-2&&row.mg===-2200));}
|
||
|
|
const csv=await (await call('/api/export/inventory')).text();assert.match(csv,/账面对数,已占用对数,可用对数/);assert.match(csv,/"合成成品盘",20\.000,0\.000,20\.000,对,5,0,5/);assert.equal((await call('/api/export/inventory',assistantCookie)).status,403);
|
||
|
|
const printable=await (await call('/print/'+result.id)).text();assert.doesNotMatch(printable,/stockCount|countSource|锁价成品入库|对数盘点基准/);
|
||
|
|
});
|