2026-10-21 01:32:49 +08:00
'use strict' ;
const { test } = require ( 'node:test' ), assert = require ( 'node:assert/strict' ),{ randomUUID } = require ( 'node:crypto' );
const { Ledger } = require ( '../ledger' );
const actor = { id : 'pool-report-owner' , name : '测试麦麦' , role : 'owner' };
const D = '2026-09-30' , D2 = '2026-10-01' , D3 = '2026-10-02' ;
const contents = ledger => JSON . stringify ( ledger . rows ( "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name" )
. map (({ name })=>[ name , ledger . rows ( 'SELECT * FROM "' + name + '"' )]));
function fixture ( t ){
const ledger = new Ledger ( ':memory:' ); t . after (()=> ledger . close ());
const run = ( input , fn , key = randomUUID ())=> ledger . transact ( key , actor , input , fn );
const report = ( date = D , from = date )=> ledger . reportByOrderDate ( date , from );
const close = ( date = D )=> run ({ date , basis : 'orderDate' },()=> ledger . closeDay ( date , actor , 'orderDate' ));
const action = ( id , kind , input )=> run ({ id , kind , input },()=> ledger . action ( id , kind , input , actor ));
const purchase = ( extra = {}, key = randomUUID ())=>{
const input = { date : D , grams : '10' , total : '9000' , payer : 'owner' , note : '仅合成测试' ,... extra };
return run ( input ,()=> ledger . createMaterialPurchase ( input , actor ), key );
};
const issue = ( extra = {})=>{
const input = { date : D2 , customer : '合成日料客户' , payment_account : '助理微信' , fee_items : [],
lines : [{ name : '足金挂件' , unit : 'g' , quantity : '3.000' , pocket : '' , payer : 'owner' , sale : '3000' ,
costParts : { material : '' , labor : '0' , accessories : '0' , other : '0' }, costMaterial : { mode : 'pool' , poolId : D }}],... extra };
return run ( input ,()=> ledger . issueOrder ( input , actor )). id ;
};
const settlePool = ( extra = {})=>{
const input = { date : D2 , revision : ledger . materialPoolDetail ( D ). revision , amount : '18120' , direction : 'toAssistant' , verified : true , note : '合成实际转账' ,... extra };
return run ( input ,()=> ledger . settleMaterialPool ( D , input , actor ));
};
return { ledger , run , report , close , action , purchase , issue , settlePool };
}
function totalsAdd ( daily , combined ){
for ( const key of [ 'sales' , 'goods' , 'expense' , 'totalCost' , 'profit' , 'outlayGoods' , 'outlayExpense' , 'outlayTotal' ])
assert . equal ( combined [ key ], daily . reduce (( sum , row )=> sum + row [ key ], 0 ), key );
for ( const payer of [ 'owner' , 'assistant' ]) for ( const key of [ 'goods' , 'paidFees' , 'total' ])
assert . equal ( combined . payerCosts [ payer ][ key ], daily . reduce (( sum , row )=> sum + row . payerCosts [ payer ][ key ], 0 ), payer + ' ' + key );
}
test ( '采购只按采购日与付款人计一次,跨月订单只结转耗用成本,剩余料不进利润' , t =>{
const f = fixture ( t ); f . purchase (); f . purchase ({ grams : '20' , total : '18120' , payer : 'assistant' });
const purchaseRevision = f . report (). reportRevision ; f . close (); const id = f . issue (), order = f . ledger . detail ( id ), pool = f . ledger . materialPoolDetail ( D );
const paid = f . report (), sale = f . report ( D2 ), combined = f . report ( D2 , D );
assert . equal ( paid . outlayGoods , 2712000 ); assert . equal ( paid . outlayTotal , 2712000 ); assert . equal ( paid . sales , 0 ); assert . equal ( paid . totalCost , 0 ); assert . equal ( paid . profit , 0 );
assert . equal ( paid . payerCosts . owner . total , 900000 ); assert . equal ( paid . payerCosts . assistant . total , 1812000 );
assert . equal ( paid . materialPoolActivity . summary . purchaseCount , 2 ); assert . equal ( paid . materialPoolActivity . summary . mg , 30000 );
assert . equal ( paid . reportRevision , purchaseRevision ); assert . equal ( paid . close . stale , false , '后续耗用不改写原采购支出快照' );
assert . equal ( sale . sales , 300000 ); assert . equal ( sale . goods , 271200 ); assert . equal ( sale . totalCost , 271200 ); assert . equal ( sale . profit , 28800 );
assert . equal ( sale . outlayTotal , 0 ); assert . equal ( sale . payerCosts . owner . total , 0 ); assert . equal ( sale . payerCosts . assistant . total , 0 );
2026-10-23 00:14:29 +08:00
assert . equal ( sale . orderPayerCosts . owner . goods , 271200 ); assert . equal ( sale . orderPayerCosts . assistant . goods , 0 );
assert . equal ( order . settlementDue , 300000 ); assert . equal ( sale . settlementDue , - 1512000 );
2026-10-21 01:32:49 +08:00
assert . equal ( sale . settlementDue , 300000 - 1812000 , '全局应结等于助理实收减实际垫付,不把剩余料丢掉' );
assert . equal ( pool . averageRate , 90400 ); assert . equal ( pool . usedMg , 3000 ); assert . equal ( pool . remainingMg , 27000 ); assert . equal ( pool . remainingCost , 2440800 );
2026-10-23 00:14:29 +08:00
assert . deepEqual ( pool . byPayer ,{ owner : { purchased : 900000 , consumed : 271200 , remaining : 628800 }, assistant : { purchased : 1812000 , consumed : 0 , remaining : 1812000 }});
2026-10-21 01:32:49 +08:00
assert . equal ( combined . outlayTotal - combined . totalCost , pool . remainingCost ); totalsAdd ([ paid , sale ], combined );
assert . equal ( f . report ( D , '2026-09-01' ). outlayTotal , 2712000 ); assert . equal ( f . report ( D3 , D2 ). outlayTotal , 0 );
});
test ( '先出单料费待补时只汇总已核算利润,补购与同日加权重算使相关财务快照过期但不动库存' , t =>{
const f = fixture ( t ), l = f . ledger ;
const ordinary = { date : D2 , customer : '合成手填单' , payment_account : '助理微信' , fee_items : [], lines : [{ name : '手填商品' , unit : '件' , quantity : '1' , pocket : '' , payer : 'owner' , sale : '100' , costParts : { material : '40' , labor : '0' , accessories : '0' , other : '0' }}]};
f . run ( ordinary ,()=> l . issueOrder ( ordinary , actor ));
const id = f . issue ({ lines : [{ name : '足金挂件' , unit : 'g' , quantity : '3.000' , pocket : '' , payer : 'owner' , sale : '3000' ,
costParts : { material : '' , labor : '30' , accessories : '5' , other : '1' }, costMaterial : { mode : 'pool' , poolId : D }}],
fee_items : [{ key : 'shipping' , note : '实付运费' , amount : '6' , payer : 'assistant' }]});
let r = f . report ( D2 ), row = r . orderRows . find ( item => item . id === id );
assert . equal ( l . detail ( id ). profit , null ); assert . equal ( l . detail ( id ). settlementDue , null );
assert . equal ( row . material , null ); assert . equal ( row . totalCost , null ); assert . equal ( row . profit , null ); assert . equal ( row . materialCostPending , true );
assert . equal ( row . missingCosts , 1 ); assert . equal ( row . pendingCosts , 0 ); assert . equal ( row . known . totalCost , 4200 );
assert . equal ( r . summary . unknownCostCount , 1 ); assert . equal ( r . summary . unknownProfitCount , 1 ); assert . equal ( r . summary . partial , true );
assert . equal ( r . profit , 6000 , '待补料费订单不贡献看似完整的销售利润' ); assert . equal ( r . totalCost , 8200 );
assert . equal ( r . knownProfit , 6000 ); assert . equal ( r . materialCostPending , true ); assert . equal ( r . pendingMaterialCount , 1 );
assert . ok ( r . journal . filter ( item => item . order_id === id ). every ( item => item . goods === null && item . profit === null && item . materialCostPending ));
assert . equal ( r . orderPayerCosts . owner . missingCount , 1 ); assert . equal ( r . payerCosts . owner . missingCount , 0 );
f . close ( D ); f . close ( D2 ); const physical = contentsOfInventory ( l ), movements = l . rows ( 'SELECT * FROM movements' );
f . purchase (); r = f . report ( D2 ); row = r . orderRows . find ( item => item . id === id );
assert . equal ( row . material , 270000 ); assert . equal ( row . totalCost , 274200 ); assert . equal ( row . profit , 25800 ); assert . equal ( r . profit , 31800 );
assert . equal ( r . summary . unknownProfitCount , 0 ); assert . equal ( r . close . stale , true ); assert . equal ( f . report (). close . stale , true );
assert . equal ( r . outlayTotal , 8200 ); assert . equal ( f . report (). outlayTotal , 900000 );
f . close ( D2 ); f . purchase ({ total : '9200' , payer : 'assistant' }); r = f . report ( D2 ); row = r . orderRows . find ( item => item . id === id );
assert . equal ( row . material , 273000 ); assert . equal ( row . profit , 22800 ); assert . equal ( r . profit , 28800 ); assert . equal ( r . close . stale , true );
2026-10-23 00:14:29 +08:00
assert . equal ( r . orderPayerCosts . owner . goods , 280600 ); assert . equal ( r . orderPayerCosts . assistant . goods , 0 );
2026-10-21 01:32:49 +08:00
assert . equal ( contentsOfInventory ( l ), physical ); assert . deepEqual ( l . rows ( 'SELECT * FROM movements' ), movements );
});
function contentsOfInventory ( ledger ){ return JSON . stringify ( ledger . rows ( 'SELECT date,inventory,stale,revision FROM inventory_snapshots ORDER BY date' ));}
test ( '总耗用超出采购时全部关联单待补,补足后克重与分币守恒且不会重复计采购款' , t =>{
const f = fixture ( t ); f . purchase ();
const first = f . issue ({ lines : [{ name : '先出黄金' , unit : 'g' , quantity : '8.000' , pocket : '' , payer : 'owner' , sale : '8000' , costParts : { material : '' , labor : '0' , accessories : '0' , other : '0' }, costMaterial : { mode : 'pool' , poolId : D }}]});
f . issue ({ lines : [{ name : '后出黄金' , unit : 'g' , quantity : '5.000' , pocket : '' , payer : 'assistant' , sale : '5000' , costParts : { material : '' , labor : '0' , accessories : '0' , other : '0' }, costMaterial : { mode : 'pool' , poolId : D }}]});
let r = f . report ( D2 ), pool = f . ledger . materialPoolDetail ( D );
assert . equal ( f . ledger . detail ( first ). profit , null ); assert . equal ( r . summary . unknownProfitCount , 2 ); assert . equal ( r . profit , 0 ); assert . equal ( r . summary . partial , true );
assert . ok ( r . orderRows . every ( row => row . material === null && row . profit === null )); assert . equal ( pool . shortageMg , 3000 ); assert . equal ( pool . remainingCost , null );
f . purchase ({ grams : '5' , total : '4600' , payer : 'assistant' }); r = f . report ( D2 ); pool = f . ledger . materialPoolDetail ( D );
assert . equal ( r . summary . unknownProfitCount , 0 ); assert . equal ( r . goods , 1178667 ); assert . equal ( r . profit , 121333 ); assert . equal ( r . outlayTotal , 0 );
assert . equal ( pool . usedMg + pool . remainingMg , pool . totalMg ); assert . equal ( pool . consumedCost + pool . remainingCost , pool . totalAmount );
assert . equal ( pool . remainingCost , 181333 ); assert . equal ( f . report (). outlayTotal , 1360000 );
for ( const payer of [ 'owner' , 'assistant' ]) assert . equal ( pool . byPayer [ payer ]. consumed + pool . byPayer [ payer ]. remaining , pool . byPayer [ payer ]. purchased );
});
test ( '先结清剩余料垫款再耗用会产生反向应结,双方真实转账不改变利润快照' , t =>{
2026-10-23 00:14:29 +08:00
const f = fixture ( t ); f . purchase ({ grams : '20' , total : '18120' , payer : 'assistant' }); f . purchase (); f . close ();
2026-10-21 01:32:49 +08:00
f . settlePool ({ date : D }); assert . equal ( f . ledger . materialPoolSettlement (). settlementDue , 0 ); assert . equal ( f . report (). close . stale , false );
f . issue (); f . close ( D2 ); const before = f . report ( D2 ). reportRevision ;
2026-10-23 00:14:29 +08:00
assert . equal ( f . ledger . materialPoolSettlement (). settlementDue , 271200 ); assert . equal ( f . report ( D2 ). settlementDue , 300000 );
f . settlePool ({ amount : '2712' , direction : 'toOwner' });
assert . equal ( f . ledger . materialPoolSettlement (). settlementDue , 0 ); assert . equal ( f . report ( D2 ). settlementDue , 28800 );
2026-10-21 01:32:49 +08:00
assert . equal ( f . report ( D2 ). reportRevision , before ); assert . equal ( f . report ( D2 ). close . stale , false ); assert . equal ( f . report ( D2 ). outlayTotal , 0 );
});
test ( '退回自有货盘释放料重并冲回耗用,采购及已付工费保持真实支出,助理垫资不丢失' , t =>{
const f = fixture ( t ); f . purchase ({ payer : 'assistant' });
const id = f . issue ({ lines : [{ name : '足金挂件' , unit : 'g' , quantity : '2.000' , pocket : '' , payer : 'assistant' , sale : '2100' ,
costParts : { material : '' , labor : '40' , accessories : '5' , other : '1' }, costMaterial : { mode : 'pool' , poolId : D }}],
fee_items : [{ key : 'shipping' , note : '实付运费' , amount : '6' , payer : 'assistant' }]});
const paid = f . report (). outlayTotal , actual = f . report ( D2 ). outlayTotal ;
assert . equal ( actual , 5200 ); assert . equal ( f . report ( D2 ). totalCost , 185200 );
const before = contents ( f . ledger );
assert . throws (()=> f . action ( id , 'return' ,{ date : D3 , reason : '合成退货' , verified : true }), /退回自有货盘/ ); assert . equal ( contents ( f . ledger ), before );
f . action ( id , 'return' ,{ date : D3 , reason : '合成退货' , returnPockets : [ '现货' ], verified : true });
f . action ( id , 'refund' ,{ date : D3 , amount : '2100' , account : '助理微信' , verified : true });
const r = f . report ( D2 ), pool = f . ledger . materialPoolDetail ( D );
assert . equal ( r . sales , 0 ); assert . equal ( r . goods , 0 ); assert . equal ( r . expense , 600 ); assert . equal ( r . profit , - 600 ); assert . equal ( r . outlayTotal , actual );
assert . equal ( f . report (). outlayTotal , paid ); assert . equal ( f . report ( D3 ). outlayTotal , 0 );
assert . equal ( pool . usedMg , 0 ); assert . equal ( pool . remainingMg , 10000 ); assert . equal ( pool . remainingCost , 900000 );
assert . equal ( f . ledger . inventory (). find ( row => row . pocket === '现货' ). mg , 2000 );
assert . equal ( r . settlementDue , - 905200 , '客户全退后仍须归还助理全部实际垫付款' );
assert . equal ( f . ledger . detail ( id ). assistantInventoryCredit , 4600 , '退回工费配件成本单独抵扣,不重复计算金料' );
assert . equal ( f . ledger . rows ( 'SELECT * FROM material_purchases' ). length , 1 );
});
test ( '极小耗用分配到0分仍为已核算,整池最终耗尽时成本不多不少一分' , t =>{
const f = fixture ( t ); f . purchase ({ grams : '1' , total : '0.01' , payer : 'assistant' });
for ( const quantity of [ '0.001' , '0.499' , '0.500' ]) f . issue ({ lines : [{ name : '极小克重黄金' , unit : 'g' , quantity , pocket : '' , payer : 'owner' , sale : '1' , costParts : { material : '' , labor : '0' , accessories : '0' , other : '0' }, costMaterial : { mode : 'pool' , poolId : D }}]});
const r = f . report ( D2 ), pool = f . ledger . materialPoolDetail ( D );
assert . equal ( r . summary . unknownProfitCount , 0 ); assert . equal ( r . summary . missingCosts , 0 ); assert . equal ( r . summary . partial , false );
assert . deepEqual ( r . orderRows . map ( row => row . material ),[ 0 , 1 , 0 ]); assert . equal ( r . goods , 1 ); assert . equal ( r . profit , 299 );
assert . equal ( pool . status , 'exhausted' ); assert . equal ( pool . usedMg , 1000 ); assert . equal ( pool . remainingMg , 0 ); assert . equal ( pool . remainingCost , 0 );
assert . equal ( r . outlayTotal , 0 ); assert . equal ( f . report (). outlayTotal , 1 );
});
test ( '购料重试幂等,重算中途失败完整回滚,日报与订单簿反复读取无写入' , t =>{
const f = fixture ( t ), key = randomUUID (), first = f . purchase ({}, key ); assert . equal ( JSON . stringify ( f . purchase ({}, key )), JSON . stringify ( first ));
assert . equal ( f . ledger . rows ( 'SELECT * FROM material_purchases' ). length , 1 ); assert . equal ( f . ledger . rows ( 'SELECT * FROM operations WHERE id=?' , key ). length , 1 );
f . issue (); const before = contents ( f . ledger ), original = f . ledger . journal ;
f . ledger . journal = function (... args ){ original . apply ( this , args ); throw new Error ( '合成重算故障' );};
try { assert . throws (()=> f . purchase ({ total : '10000' }), /合成重算故障/ );} finally { f . ledger . journal = original ;}
assert . equal ( contents ( f . ledger ), before );
assert . throws (()=> f . purchase ({ total : '1' }, key ), /操作号已用于其他内容/ ); assert . equal ( contents ( f . ledger ), before );
const changes = f . ledger . one ( 'SELECT total_changes() AS count' ). count ;
const r = f . report ( D2 ); assert . deepEqual ( f . report ( D2 ), r ); f . report (); f . report ( D3 , D ); f . ledger . orderBook ({ date : D2 });
assert . equal ( f . ledger . one ( 'SELECT total_changes() AS count' ). count , changes ); assert . equal ( contents ( f . ledger ), before );
});
test ( '没有日料池的历史空日和普通订单财务哈希完全兼容' , t =>{
const f = fixture ( t ), l = f . ledger , created = '2026-09-30T01:00:00.000Z' ;
assert . equal ( f . report (). reportRevision , 'd7ebe7c4ffa6abb6a0f2393fe0a3a5f2f083df906729ef10e4be99cf211053a7' );
const lines = l . validateLines ([{ name : '兼容商品' , unit : 'g' , quantity : '2.000' , pocket : '' , payer : 'owner' , sale : '2200' ,
costParts : { material : '1800' , labor : '40' , accessories : '0' , other : '0' }}]);
l . run ( 'INSERT INTO orders(id,number,date,customer,salesperson,note,paper_number,status,lines,discount,total,created) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)' ,
'legacy-order' , '20260930-001' , D , '合成兼容客户' , '测试麦麦' , '' , '20260930-001' , 'delivered' , JSON . stringify ( lines ), 0 , 220000 , created );
l . run ( 'INSERT INTO payments VALUES (?,?,?,?,?,?,?,?,?)' , 'legacy-receipt' , 'legacy-order' , D , 'receipt' , 220000 , '助理微信' , '' , '测试麦麦' , created );
l . run ( 'INSERT INTO journal VALUES (?,?,?,?,?,?,?,?,?)' , 'legacy-journal' , 'legacy-order' , D , '交付' , 220000 , 184000 , 0 , 36000 , created );
const before = contents ( l ), r = f . report ();
assert . equal ( r . reportRevision , 'ad7404c855412b74203780c06ad6c3f0137a240b94f3bb595ee1dde6dfc64c06' );
assert . equal ( r . profit , 36000 ); assert . equal ( r . totalCost , 184000 ); assert . equal ( r . outlayTotal , 184000 );
assert . equal ( contents ( l ), before );
});
test ( '锁价创建和交付拒绝日料池来源,失败时流水与操作号完整回滚' , t =>{
const f = fixture ( t ), input = { date : D , customer : '合成锁价客户' , line : { name : '足金挂件' , unit : 'g' , quantity : '2.000' , goldPrice : '1000' , laborRate : '20' , laborMode : 'gram' },
material : { rate : '900' , payer : 'owner' , verified : true }, payment : { amount : '1000' , account : '助理微信' , verified : true }};
for ( const source of [{ costMaterial : { mode : 'pool' , poolId : D }},{ materialPool : {}},{ materialPool : null }]){
const attempt = {... input , line : {... input . line ,... source }}, before = contents ( f . ledger );
assert . throws (()=> f . run ( attempt ,()=> f . ledger . createPriceLock ( attempt , actor )), /锁价单使用独立采购料费/ );
assert . equal ( contents ( f . ledger ), before );
}
const id = f . run ( input ,()=> f . ledger . createPriceLock ( input , actor )). id ;
for ( const source of [{ costMaterial : { mode : 'pool' , poolId : D }},{ materialPool : {}},{ materialPool : null }]){
const attempt = { date : D2 , revision : 1 , verified : true , line : { quantity : '2.000' ,... source }}, before = contents ( f . ledger );
assert . throws (()=> f . run ( attempt ,()=> f . ledger . deliverPriceLock ( id , attempt , actor )), /锁价单使用独立采购料费/ );
assert . equal ( contents ( f . ledger ), before );
}
});