2026-10-17 19:50:24 +08:00
'use strict' ;
2026-10-23 00:38:04 +08:00
const { historicalAction } = require ( './fixtures/legacy-cancellation.cjs' );
2026-10-17 19:50:24 +08:00
const { test } = require ( 'node:test' ), assert = require ( 'node:assert/strict' );
const { randomUUID } = require ( 'node:crypto' ), fs = require ( 'node:fs' ), os = require ( 'node:os' ), path = require ( 'node:path' );
const { Ledger } = require ( '../ledger' ), Calc = require ( '../public/calculations' ),{ createApp } = require ( '../server' ),{ FeishuSync } = require ( '../sync' );
const owner = { id : 'component-owner' , name : '测试麦麦' , role : 'owner' }, D = '2026-09-30' , D2 = '2026-10-01' ;
const line = ( extra = {})=>({ name : '合成商品' , unit : 'g' , quantity : '2.200' , pocket : '现货' , payer : 'owner' , sale : '2300' ,
costParts : { material : '9999' , labor : '999' , accessories : '5' , other : '1' }, costMaterial : { mode : 'gram' , rate : '900' }, costLabor : { mode : 'gram' , rate : '20' },... extra });
2026-11-30 15:40:40 +08:00
const payload = ( extra = {})=>({ date : D , customer : '合成客户' , internal_note : '测试内部备注' , salesperson : '合成开单人' , payment_account : '助理微信' , lines : [ line ()],
2026-10-17 19:50:24 +08:00
fee_items : [{ key : 'shipping' , note : '快递费' , amount : '6' , payer : 'assistant' },{ key : 'box' , note : '包装' , amount : '3' , payer : 'owner' }],... extra });
function fixture ( t ){
const ledger = new Ledger ( ':memory:' ); t . after (()=> ledger . close ());
const run = ( input , fn , key = randomUUID ())=> ledger . transact ( key , owner , input , fn );
run ({ stock : true },()=> ledger . stock ({ kind : 'opening' , date : D , pocket : '现货' , grams : '20' , note : '合成库存' }, owner ));
const save = ( input = payload (), issue = false )=> run ( input ,()=> issue ? ledger . issueOrder ( input , owner ) : ledger . saveOrder ( input , owner )). id ;
2026-10-23 00:38:04 +08:00
const action = ( id , kind , extra = {})=>{ const input = { date : D ,... extra }; return run ({ id , kind , input },()=> historicalAction ( ledger , id , kind , input , owner ));};
2026-10-17 19:50:24 +08:00
return { ledger , run , save , action };
}
const snapshot = ledger => JSON . stringify ( ledger . rows ( "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name" ). map (({ name })=>[ name , ledger . rows ( 'SELECT * FROM "' + name + '"' )]));
test ( '料费和克工费可相反或同人支付,配件其他仍按共享付款人,成本利润与库存不变' , t =>{
const f = fixture ( t ), cases = [
{ payer : 'owner' , costPayers : { material : 'assistant' , labor : 'owner' }, ownerGoods : 5000 , assistantGoods : 198000 },
{ payer : 'assistant' , costPayers : { material : 'owner' , labor : 'assistant' }, ownerGoods : 198000 , assistantGoods : 5000 },
{ payer : 'assistant' , costPayers : { material : 'owner' , labor : 'owner' }, ownerGoods : 202400 , assistantGoods : 600 },
{ payer : 'owner' , costPayers : { material : 'assistant' , labor : 'assistant' }, ownerGoods : 600 , assistantGoods : 202400 }
];
for ( const entry of cases ){
const id = f . save ( payload ({ lines : [ line ( entry )]}), true ), o = f . ledger . detail ( id ), costs = Calc . orderCosts ( o ), row = f . ledger . orderBook ({ date : D }). rows . find ( row => row . id === id );
assert . deepEqual ( o . lines [ 0 ]. costPayers , entry . costPayers ); assert . equal ( costs . byPayer . owner . goods , entry . ownerGoods ); assert . equal ( costs . byPayer . assistant . goods , entry . assistantGoods );
assert . equal ( o . goodsCost , 203000 ); assert . equal ( o . profit , 26100 ); assert . equal ( o . total , 230000 ); assert . equal ( o . ownerCost , entry . ownerGoods + 300 ); assert . equal ( o . costDue , o . ownerCost ); assert . equal ( o . settlementDue , o . ownerCost + 26100 );
assert . equal ( costs . rows . find ( row => row . name === '料费成本' ). payer , entry . costPayers . material ); assert . equal ( costs . rows . find ( row => row . name === '进货工费' ). payer , entry . costPayers . labor );
assert . ok ( costs . rows . filter ( row =>[ '配件成本' , '其他货品成本' ]. includes ( row . name )). every ( row => row . payer === entry . payer ));
assert . equal ( row . ownerCost , entry . ownerGoods + 300 ); assert . equal ( row . assistantCost , entry . assistantGoods + 600 ); assert . equal ( row . totalCost , 203900 );
}
const book = f . ledger . orderBook ({ date : D }), r = f . ledger . reportByOrderDate ( D );
assert . equal ( book . summary . totalCost , 815600 ); assert . equal ( book . summary . profit , 104400 ); assert . deepEqual ( r . summary , book . summary );
assert . equal ( r . payerCosts . owner . total , book . summary . ownerCost ); assert . equal ( r . payerCosts . assistant . total , book . summary . assistantCost ); assert . equal ( r . goods , 812000 ); assert . equal ( r . expense , 3600 );
assert . equal ( f . ledger . inventory (). find ( row => row . pocket === '现货' ). mg , 11200 );
});
test ( '每克料价和总工费各按一次金额分账,实际结算仅回收麦麦支付的分项' , t =>{
const f = fixture ( t ), id = f . save ( payload ({ lines : [ line ({ costPayers : { material : 'assistant' , labor : 'owner' }, costMaterial : { mode : 'gram' , rate : '900.01' }, costLabor : { mode : 'total' }, costParts : { material : '0' , labor : '17.34' , accessories : '5' , other : '1' }})]}), true );
const o = f . ledger . detail ( id ), costs = Calc . orderCosts ( o ); assert . equal ( o . lines [ 0 ]. costParts . material , 198002 ); assert . equal ( o . lines [ 0 ]. costParts . labor , 1734 ); assert . equal ( o . goodsCost , 200336 ); assert . equal ( o . profit , 28764 );
assert . equal ( o . ownerCost , 2634 ); assert . equal ( o . costDue , 2634 ); assert . equal ( o . settlementDue , 31398 ); assert . equal ( costs . byPayer . assistant . total , 198602 );
assert . deepEqual ( costs . rows . find ( row => row . name === '料费成本' ). calculation ,{ rate : 90001 , quantity : 2200 }); assert . equal ( costs . rows . find ( row => row . name === '进货工费' ). calculation , null );
assert . throws (()=> f . action ( id , 'settlement' ,{ amount : '26.35' , bucket : 'cost' , direction : 'toOwner' , note : '超过分项垫资' , verified : true }), /超过/ );
f . action ( id , 'settlement' ,{ amount : '26.34' , bucket : 'cost' , direction : 'toOwner' , note : '已转实际货款' , verified : true }); assert . equal ( f . ledger . detail ( id ). costDue , 0 ); assert . equal ( f . ledger . detail ( id ). settlementDue , 28764 );
f . action ( id , 'settlement' ,{ amount : '287.64' , bucket : 'profit' , direction : 'toOwner' , note : '已转利润' , verified : true }); assert . equal ( f . ledger . detail ( id ). settlementDue , 0 );
});
test ( '麦麦直接收款时按分项垫资算净待返助理金额,同步副本使用相同结算和内部明细' , t =>{
const f = fixture ( t ), id = f . save ( payload ({ payment_account : '麦麦微信' , lines : [ line ({ costPayers : { material : 'assistant' , labor : 'owner' }})]}), true ), o = f . ledger . detail ( id );
assert . equal ( o . ownerCost , 5300 ); assert . equal ( o . ownerDirect , 230000 ); assert . equal ( o . settlementDue , - 198600 );
const sync = new FeishuSync ( f . ledger ,{ enabled : false },()=>{ throw new Error ( '禁止网络' );}), fields = sync . fields ( 'order:' + id , o . revision ), details = JSON . parse ( fields [ '明细' ]);
assert . equal ( fields [ '待结算' ], - 1986 ); assert . equal ( details . ownerCost , 5300 ); assert . deepEqual ( details . lines [ 0 ]. costPayers ,{ material : 'assistant' , labor : 'owner' });
});
test ( '旧分项和未分项记录按原payer回退,读取不补写;相同归属的显式元数据不改变财务哈希' , t =>{
const f = fixture ( t ), id = f . save ( payload (), true ), legacy = f . save ( payload ({ lines : [ line ({ unit : '件' , quantity : '1' , pocket : '' , payer : 'assistant' , costParts : undefined , costMaterial : undefined , costLabor : undefined , cost : '12.34' , sale : '50' })], fee_items : []}), true );
const before = snapshot ( f . ledger ), report = f . ledger . reportByOrderDate ( D );
assert . ok ( ! Object . hasOwn ( f . ledger . detail ( id ). lines [ 0 ], 'costPayers' )); assert . ok ( ! Object . hasOwn ( f . ledger . detail ( legacy ). lines [ 0 ], 'costPayers' ));
const originalCosts = Calc . orderCosts ( f . ledger . detail ( id )); assert . equal ( originalCosts . byPayer . owner . goods , 203000 ); assert . equal ( originalCosts . byPayer . assistant . goods , 0 );
const legacyCosts = Calc . orderCosts ( f . ledger . detail ( legacy )); assert . equal ( legacyCosts . rows [ 0 ]. name , '货品成本(原单未分项)' ); assert . equal ( legacyCosts . byPayer . assistant . goods , 1234 );
f . ledger . orderBook ({ date : D }); f . ledger . reportByOrderDate ( D ); assert . equal ( snapshot ( f . ledger ), before );
// 只在内存模拟等价的新格式,确认新增字段不会迫使未变动的旧财务快照过期。
const raw = f . ledger . rawOrder ( id ); raw . lines [ 0 ]. costPayers = { material : 'owner' , labor : 'owner' }; f . ledger . run ( 'UPDATE orders SET lines=? WHERE id=?' , JSON . stringify ( raw . lines ), id );
assert . deepEqual ( Calc . orderCosts ( f . ledger . detail ( id )), originalCosts ); assert . equal ( f . ledger . reportByOrderDate ( D ). reportRevision , report . reportRevision );
});
test ( '草稿保存再编辑及旧客户端缺省字段均保留已有分项付款人,显式修改才更新' , t =>{
const f = fixture ( t ), first = payload ({ lines : [ line ({ costPayers : { material : 'assistant' , labor : 'owner' }})], fee_items : []}), id = f . save ( first ), paper = f . ledger . detail ( id ). paper_number ;
const edit = {... first , id , revision : f . ledger . detail ( id ). revision , lines : [{... first . lines [ 0 ], quantity : '3.000' }]}; f . save ( edit );
let row = f . ledger . detail ( id ). lines [ 0 ]; assert . equal ( row . costParts . material , 270000 ); assert . equal ( row . costParts . labor , 6000 ); assert . deepEqual ( row . costPayers ,{ material : 'assistant' , labor : 'owner' });
const { costPayers ,... oldClientLine } = edit . lines [ 0 ]; f . save ({... edit , revision : f . ledger . detail ( id ). revision , lines : [{... oldClientLine , payer : 'assistant' }]});
row = f . ledger . detail ( id ). lines [ 0 ]; assert . deepEqual ( row . costPayers ,{ material : 'assistant' , labor : 'owner' }); assert . equal ( row . payer , 'assistant' ); assert . equal ( f . ledger . detail ( id ). paper_number , paper );
f . save ({... edit , revision : f . ledger . detail ( id ). revision , lines : [{... oldClientLine , costPayers : { material : 'owner' , labor : 'assistant' }}]}); assert . deepEqual ( f . ledger . detail ( id ). lines [ 0 ]. costPayers ,{ material : 'owner' , labor : 'assistant' });
});
test ( '旧单后补成本保留缺省分项付款人,可分别更新分项和配件其他付款人,交付后锁定' , t =>{
const f = fixture ( t ), id = f . save ( payload ({ lines : [ line ({ costParts : { material : '' , labor : '0' , accessories : '5' , other : '1' }, costMaterial : { mode : 'total' }, costPayers : { material : 'assistant' , labor : 'owner' }})], fee_items : []})); f . action ( id , 'confirm' );
const parts = { material : '1980' , labor : '44' , accessories : '5' , other : '1' }; f . action ( id , 'cost' ,{ costs : [{ parts , payer : 'assistant' }]});
let row = f . ledger . detail ( id ). lines [ 0 ]; assert . deepEqual ( row . costPayers ,{ material : 'assistant' , labor : 'owner' }); assert . equal ( row . payer , 'assistant' ); assert . equal ( Calc . orderCosts ( f . ledger . detail ( id )). byPayer . owner . goods , 4400 );
f . action ( id , 'cost' ,{ costs : [{ parts , costPayers : { material : 'owner' , labor : 'assistant' }}]}); row = f . ledger . detail ( id ). lines [ 0 ]; assert . equal ( row . payer , 'assistant' ); assert . deepEqual ( row . costPayers ,{ material : 'owner' , labor : 'assistant' });
f . action ( id , 'receipt' ,{ amount : '2300' , account : '助理微信' , verified : true }); f . action ( id , 'deliver' ,{ verified : true }); assert . equal ( f . ledger . detail ( id ). ownerCost , 198000 ); assert . equal ( f . ledger . detail ( id ). settlementDue , 225000 );
assert . throws (()=> f . action ( id , 'cost' ,{ costs : [{ parts , costPayers : { material : 'assistant' , labor : 'owner' }}]}), /交付前/ );
const old = f . save ( payload ({ lines : [ line ({ costParts : { material : '' , labor : '0' , accessories : '0' , other : '0' }, costMaterial : { mode : 'total' }})], fee_items : []})); f . action ( old , 'confirm' ); f . action ( old , 'cost' ,{ costs : [ parts ]});
assert . ok ( ! Object . hasOwn ( f . ledger . detail ( old ). lines [ 0 ], 'costPayers' )); assert . equal ( Calc . orderCosts ( f . ledger . detail ( old )). byPayer . owner . goods , 203000 );
});
test ( '显式无效分项付款人一律拒绝,新建编辑后补均完整回滚,不能擦掉已有值' , t =>{
const f = fixture ( t ), invalid = [ null , '' ,[],{}, 'owner' ,{ material : 'owner' },{ labor : 'assistant' },{ material : 'owner' , labor : '' },{ material : null , labor : 'owner' },{ material : 'invalid' , labor : 'assistant' },{ material : 'owner' , labor : 'assistant' , accessories : 'owner' }];
const first = payload ({ lines : [ line ({ costPayers : { material : 'assistant' , labor : 'owner' }})], fee_items : []}), id = f . save ( first );
for ( const value of invalid ){
let before = snapshot ( f . ledger ); assert . throws (()=> f . save ( payload ({ lines : [ line ({ costPayers : value })]})), /付款人/ ); assert . equal ( snapshot ( f . ledger ), before );
assert . throws (()=> f . save ({... first , id , revision : f . ledger . detail ( id ). revision , lines : [ line ({ costPayers : value })]}), /付款人/ ); assert . equal ( snapshot ( f . ledger ), before );
}
f . action ( id , 'confirm' ); const before = snapshot ( f . ledger ), parts = { material : '1980' , labor : '44' , accessories : '5' , other : '1' };
for ( const costPayers of invalid ){ assert . throws (()=> f . action ( id , 'cost' ,{ costs : [{ parts , costPayers }]}), /付款人/ ); assert . equal ( snapshot ( f . ledger ), before );}
assert . throws (()=> f . action ( id , 'cost' ,{ costs : [{ parts , payer : 'invalid' }]}), /垫资人/ ); assert . equal ( snapshot ( f . ledger ), before );
assert . throws (()=> Calc . costPayers ({ material : 'owner' , labor : null }), /付款人/ ); assert . deepEqual ( f . ledger . detail ( id ). lines [ 0 ]. costPayers ,{ material : 'assistant' , labor : 'owner' });
});
test ( '退货和取消不计货品分项垫资,原实际费用保留,货款返还只冲原麦麦货品成本' , t =>{
const f = fixture ( t ), p = payload ({ lines : [ line ({ costPayers : { material : 'assistant' , labor : 'owner' }})]}), id = f . save ( p , true );
f . action ( id , 'settlement' ,{ amount : '53' , bucket : 'cost' , direction : 'toOwner' , note : '原货款已交' , verified : true }); f . action ( id , 'return' ,{ date : D2 , reason : '合成退货' , verified : true });
let o = f . ledger . detail ( id ), costs = Calc . orderCosts ( o ); assert . equal ( o . ownerCost , 300 ); assert . equal ( o . costDue , - 5000 ); assert . equal ( o . profit , - 900 ); assert . equal ( costs . byPayer . owner . goods , 0 ); assert . equal ( costs . byPayer . assistant . goods , 0 ); assert . ok ( costs . rows . filter ( row => row . kind === 'goods' ). every ( row => row . excluded ));
assert . equal ( costs . byPayer . owner . paidFees , 300 ); assert . equal ( costs . byPayer . assistant . paidFees , 600 );
const cancelled = f . save ( p ); f . action ( cancelled , 'confirm' ,{ feesVerified : true }); f . action ( cancelled , 'cancel' ,{ date : D2 , reason : '合成取消' }); o = f . ledger . detail ( cancelled ); costs = Calc . orderCosts ( o );
assert . equal ( o . ownerCost , 300 ); assert . equal ( o . costDue , 300 ); assert . equal ( o . profit , - 900 ); assert . equal ( o . settlementDue , - 600 ); assert . equal ( costs . total . goods , 0 );
const report = f . ledger . reportByOrderDate ( D ); assert . equal ( report . goods , 0 ); assert . equal ( report . expense , 1800 ); assert . equal ( report . payerCosts . owner . goods , 0 ); assert . equal ( report . payerCosts . assistant . goods , 0 );
});
test ( 'HTTP保存分项付款人并正确分账,客户接口与打印隔离,显式无效请求不写入' , async t =>{
const dir = fs . mkdtempSync ( path . join ( os . tmpdir (), 'maimai-cost-payers-http-' )), app = createApp ({ mode : 'demo' , dataDir : dir , ledger : new Ledger ( ':memory:' ), feishuConfig : { enabled : false }});
await new Promise ( resolve => app . server . listen ( 0 , '127.0.0.1' , resolve )); t . after ( async ()=>{ await new Promise ( resolve => app . server . close ( resolve )); app . ledger . close (); fs . rmSync ( dir ,{ recursive : true , force : true });});
const base = 'http://127.0.0.1:' + app . server . address (). port ; let cookie = '' ;
const call = ( route , data )=> fetch ( base + route ,{ method : data ? 'POST' : 'GET' , headers : {...( cookie ? { Cookie : cookie } : {}),...( data ? { 'Content-Type' : 'application/json' , Origin : base , 'X-Requested-With' : 'maimai-ledger' , 'Idempotency-Key' : randomUUID ()} : {} )},...( data ? { body : JSON . stringify ( data )} : {})});
const login = await call ( '/api/demo-login' ,{ role : 'assistant' }); cookie = login . headers . get ( 'set-cookie' ). split ( ';' )[ 0 ];
const p = payload ({ lines : [ line ({ pocket : '' , costPayers : { material : 'assistant' , labor : 'owner' }})]}), issue = await call ( '/api/orders/issue' , p ); assert . equal ( issue . status , 200 ); const { id } = await issue . json ();
2026-10-25 14:19:24 +08:00
const detail = await ( await call ( '/api/orders/' + id )). json (); assert . deepEqual ( detail . lines [ 0 ]. costPayers , p . lines [ 0 ]. costPayers ); assert . equal ( detail . ownerCost , 5300 ); assert . equal ( detail . funds_mode , 'team' ); assert . equal ( detail . settlementDue , 0 );
2026-10-17 19:50:24 +08:00
const book = await ( await call ( '/api/order-book?date=' + D )). json (), report = await ( await call ( '/api/report?date=' + D + '&basis=orderDate' )). json (); assert . equal ( book . summary . ownerCost , 5300 ); assert . equal ( report . payerCosts . owner . total , 5300 ); assert . equal ( report . payerCosts . assistant . total , 198600 );
const customer = JSON . stringify ( await ( await call ( '/api/orders/' + id + '/public' )). json ()), html = await ( await call ( '/print/' + id )). text (); for ( const key of [ 'costPayers' , 'costParts' , 'costMaterial' , 'costLabor' , 'payer' , 'ownerCost' ]){ assert . ok ( ! customer . includes ( '"' + key + '"' )); assert . ok ( ! html . includes ( key ));}
const before = snapshot ( app . ledger ); assert . equal (( await call ( '/api/orders/issue' ,{... p , lines : [{... p . lines [ 0 ], costPayers : { material : 'owner' , labor : 'invalid' }}]})). status , 400 ); assert . equal ( snapshot ( app . ledger ), before );
});