2026-11-05 00:04:01 +08:00
'use strict' ;
const { test } = require ( 'node:test' ),
assert = require ( 'node:assert/strict' ),
{ randomUUID } = require ( 'node:crypto' );
2026-12-04 13:01:19 -08:00
const { Ledger } = require ( '../core/ledger' ),
RecoveryMaterial = require ( '../domains/recoveries/recovery-material' );
2026-11-05 00:04:01 +08:00
const D = '2026-11-02' ,
D2 = '2026-11-03' ,
D3 = '2026-11-04' ;
function fixture (
t ,
{
publicGrams = '10' ,
publicTotal = '10000' ,
recoveryGrams = '2' ,
recoveryTotal = '1600' ,
priorPersonal = false ,
} = {},
2026-12-04 08:58:53 -08:00
) {
2026-11-05 00:04:01 +08:00
t . mock . timers . enable ({ apis : [ 'Date' ], now : Date . parse ( D + 'T04:00:00Z' ) });
const l = new Ledger ( ':memory:' ),
actors = {};
t . after (() => l . close ());
for ( const member of [ 'owner' , 'assistant' , 'assistant2' ]) {
const actor = {
id : randomUUID (),
name : '合成取消锁价-' + member ,
role : member === 'owner' ? 'owner' : 'assistant' ,
};
l . run ( 'INSERT INTO users VALUES (?,?,?,?,?)' , actor . id , actor . name , actor . role , 'synthetic-salt' , 'synthetic-hash' );
l . bindMemberUser ( actor . id , member );
actors [ member ] = actor ;
}
l . enableTeamMode ();
const run = ( p , fn , member = 'owner' ) =>
l . scope ( actors [ member ], () => l . transact ( randomUUID (), actors [ member ], p , fn ));
const at = date => t . mock . timers . setTime ( Date . parse ( date + 'T04:00:00Z' ));
run ({}, () => l . stock ({ date : D , kind : 'opening' , pocket : '现货' , grams : '100' , note : '合成库存' }, actors . owner ));
const buy = ( date = D , grams = publicGrams , total = publicTotal ) => {
const p = { date , grams , total , payer : 'owner' , note : '合成真实公共购料' };
return run ( p , () => l . createMaterialPurchase ( p , actors . owner ));
};
if ( Number ( publicGrams ) > 0 ) buy ();
const preview = l . rollingMaterialPreview ({ date : D }, actors . owner );
run ( preview , () => l . enableRollingMaterial ({ date : D , revision : preview . revision , verified : true }, actors . owner ));
const p = {
mode : 'direct' ,
2026-12-04 08:58:53 -08:00
date : D ,
2026-11-05 00:04:01 +08:00
member : 'assistant' ,
customer : '合成回收客户' ,
salesperson : '合成经办' ,
old_lines : [{ name : '合成旧料' , incoming_weight : recoveryGrams , melted_weight : recoveryGrams , purity : '100' }],
buy_rate : '800' ,
buy_total : recoveryTotal ,
payer : 'assistant2' ,
payment_account : '助理2微信' ,
verified : true ,
};
const prior = priorPersonal
? run ( p , () => l . createRecovery ({ ... p , customer : '合成前序有效回收' }, actors . owner ))
2026-12-04 08:58:53 -08:00
: null ;
2026-11-05 00:04:01 +08:00
const recovery = run ( p , () => l . createRecovery ( p , actors . owner ));
const lockInput = {
2026-12-04 08:58:53 -08:00
date : D ,
2026-11-05 00:04:01 +08:00
member : 'assistant' ,
customer : '合成锁价客户' ,
salesperson : '合成经办' ,
line : { name : '合成足金' , unit : 'g' , quantity : '2' , goldPrice : '2000' , laborRate : '0' , laborMode : 'gram' },
material : { source : 'pool' , poolId : D , revision : l . materialPoolDetail ( D ). revision },
payment : { amount : '4000' , account : '助理微信' , verified : true },
};
const lock = run ( lockInput , () => l . createPriceLock ( lockInput , actors . owner ));
const deliver = ( date = D2 , grams = '1' ) => {
const original = l . priceLockDetail ( lock . id ),
difference = Math . round ( Number ( grams ) * 200000 ) - original . netReceived ;
2026-12-04 08:58:53 -08:00
const p = {
date ,
2026-11-05 00:04:01 +08:00
revision : original . revision ,
verified : true ,
2026-12-04 08:58:53 -08:00
line : {
2026-11-05 00:04:01 +08:00
quantity : grams ,
laborRate : '0' ,
laborMode : 'gram' ,
payer : 'owner' ,
costParts : { labor : '0' , accessories : '0' , other : '0' },
2026-12-04 08:58:53 -08:00
},
2026-11-05 00:04:01 +08:00
inventory : { pocket : '现货' , original : 'stocked' },
settlement : { amount : ( Math . abs ( difference ) / 100 ). toFixed ( 2 ), account : '助理微信' , verified : true },
fee_items : [],
};
return run ( p , () => l . deliverPriceLock ( lock . id , p , actors . owner )). id ;
2026-12-04 08:58:53 -08:00
};
2026-11-05 00:04:01 +08:00
const issue = ( date = D2 , grams = '0.5' ) => {
2026-12-04 08:58:53 -08:00
const p = {
date ,
2026-11-05 00:04:01 +08:00
member : 'assistant' ,
customer : '合成下游客户' ,
salesperson : '合成经办' ,
payment_account : '助理微信' ,
fee_items : [],
2026-12-04 08:58:53 -08:00
lines : [
{
2026-11-05 00:04:01 +08:00
name : '合成足金' ,
2026-12-04 08:58:53 -08:00
unit : 'g' ,
2026-11-05 00:04:01 +08:00
quantity : grams ,
pocket : '现货' ,
payer : 'owner' ,
sale : String ( Number ( grams ) * 2000 ),
costParts : { material : '' , labor : '0' , accessories : '0' , other : '0' },
costMaterial : { mode : 'pool' , poolId : date },
2026-12-04 08:58:53 -08:00
},
],
};
2026-11-05 00:04:01 +08:00
return run ( p , () => l . issueOrder ( p , actors . owner )). id ;
2026-12-04 08:58:53 -08:00
};
2026-11-05 00:04:01 +08:00
const cancel = ( member = 'owner' ) => {
2026-12-04 08:58:53 -08:00
const p = {
2026-11-05 00:04:01 +08:00
revision : l . recoveryEdit ( recovery . id , actors [ member ]). revision ,
reason : '合成取消录错回收' ,
verified : true ,
2026-12-04 08:58:53 -08:00
};
2026-11-05 00:04:01 +08:00
return run ( p , () => l . cancelRecovery ( recovery . id , p , actors [ member ]), member );
};
const returned = ( id , date = D3 ) => {
const p = { date , verified : true , reason : '合成真实退货' , returnPockets : [ '金料' ] };
return run ( p , () => l . action ( id , 'return' , p , actors . owner ));
2026-12-04 08:58:53 -08:00
};
2026-11-05 00:04:01 +08:00
return { l , actors , run , at , buy , recovery , prior , lock , deliver , issue , cancel , returned };
}
function sourceRows ( l , lock ) {
const reservation = l . one ( 'SELECT snapshot FROM price_lock_pool_reservations WHERE price_lock_id=?' , lock );
return [
JSON . parse ( reservation . snapshot ),
... l
. rows (
"SELECT s.sources FROM material_return_sources s JOIN price_lock_pool_returns r ON s.return_kind='lock' AND s.return_id=r.id WHERE r.price_lock_id=? ORDER BY r.rowid" ,
lock ,
2026-12-04 08:58:53 -08:00
)
2026-11-05 00:04:01 +08:00
. map ( r => JSON . parse ( r . sources )),
];
}
function noCancelledBatch ( f ) {
assert . deepEqual ( RecoveryMaterial . blockedUsages ( f . l , f . recovery . purchase_id ), []);
assert . ok (
! JSON . stringify ( sourceRows ( f . l , f . lock . id )). includes ( f . recovery . purchase_id ),
'锁价与回料不得继续指向取消的私料批次' ,
);
}
const unchangedFlows = l =>
Object . fromEntries (
[ 'payments' , 'price_lock_events' , 'team_fund_transfers' ]. map ( table => [
table ,
l . rows ( 'SELECT * FROM ' + table + ' ORDER BY rowid' ),
]),
);
const facts = l =>
JSON . stringify (
2026-12-04 08:58:53 -08:00
l
2026-11-05 00:04:01 +08:00
. rows ( "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name" )
. map (({ name }) => [ name , l . rows ( 'SELECT * FROM "' + name + '" ORDER BY rowid' )]),
2026-12-04 08:58:53 -08:00
);
2026-11-05 00:04:01 +08:00
test ( '取消跨日冻结锁价已用回收批次,公共料重估原锁快照且保持客户锁价与真实收付款' , t => {
const f = fixture ( t ),
original = f . l . priceLockDetail ( f . lock . id );
assert . equal ( original . material_amount , 160000 );
f . at ( D2 );
f . buy ( D2 , '1' , '2000' );
assert . equal ( f . l . one ( 'SELECT frozen FROM material_rolling_days WHERE date=?' , D ). frozen , 1 );
const flows = unchangedFlows ( f . l ),
result = f . cancel (),
lock = f . l . priceLockDetail ( f . lock . id );
assert . equal ( result . recovery . status , 'cancelled' );
assert . equal ( lock . material_amount , 200000 );
assert . equal ( lock . buy_rate , 100000 );
assert . equal ( lock . materialPool . status , 'allocated' );
for ( const key of [ 'id' , 'number' , 'date' , 'customer' , 'sell_rate' , 'locked_mg' , 'netReceived' , 'status' ])
assert . deepEqual ( lock [ key ], original [ key ], key );
assert . equal ( lock . materialPool . frozen , true );
assert . deepEqual ( unchangedFlows ( f . l ), flows );
noCancelledBatch ( f );
const id = f . deliver ( D2 , '2' );
assert . equal ( f . l . detail ( id ). goodsCost , 200000 );
assert . equal ( f . l . detail ( id ). lines [ 0 ]. priceLockPool . materialSources [ 0 ]. kind , 'public' );
assert . equal ( f . l . one ( 'PRAGMA integrity_check' ). integrity_check , 'ok' );
assert . deepEqual ( f . l . rows ( 'PRAGMA foreign_key_check' ), []);
});
test ( '取消短交锁价来源同时改写余料及下游来源,后续退货只回公共料,不复活已取消批次' , t => {
const f = fixture ( t );
f . at ( D2 );
const id = f . deliver (),
later = f . issue (),
original = f . l . detail ( id ),
flows = unchangedFlows ( f . l );
assert . equal ( original . goodsCost , 80000 );
assert . equal ( f . l . detail ( later ). goodsCost , 40000 );
f . at ( D3 );
f . cancel ();
const lock = f . l . priceLockDetail ( f . lock . id ),
order = f . l . detail ( id ),
after = f . l . detail ( later );
assert . equal ( order . goodsCost , 100000 );
assert . equal ( after . goodsCost , 50000 );
assert . equal ( lock . delivery . leftover_cost , 100000 );
assert . deepEqual ( unchangedFlows ( f . l ), flows );
assert . equal ( order . netReceived , original . netReceived );
assert . equal ( order . total , original . total );
assert . equal (
order . lines [ 0 ]. materialAllocations . filter ( p => p . source === 'original' ). reduce (( n , p ) => n + p . amount , 0 ),
100000 ,
);
const leftover = f . l . one (
"SELECT * FROM price_lock_pool_returns WHERE price_lock_id=? AND kind='leftover'" ,
f . lock . id ,
);
assert . equal ( leftover . amount , 100000 );
assert . equal ( leftover . mg , 1000 );
noCancelledBatch ( f );
f . returned ( id );
const goods = f . l . one ( "SELECT * FROM price_lock_pool_returns WHERE price_lock_id=? AND kind='goods'" , f . lock . id );
assert . equal ( goods . amount , 100000 );
assert . equal ( goods . mg , 1000 );
noCancelledBatch ( f );
assert . equal ( f . l . detail ( id ). profit , 0 );
assert . equal ( f . l . materialPools (). current . personalPools ? . assistant ? . remainingMg ?? 0 , 0 );
});
test ( '公共料不足也能取消已交付锁价,料费与余料待补且保留业务状态,补足原日公共料后恢复' , t => {
const f = fixture ( t , { publicGrams : '0.5' , publicTotal : '500' });
f . at ( D2 );
const id = f . deliver (),
original = f . l . detail ( id );
f . at ( D3 );
const flows = unchangedFlows ( f . l );
f . cancel ();
const pending = f . l . priceLockDetail ( f . lock . id ),
order = f . l . detail ( id );
assert . equal ( pending . status , 'delivered' );
assert . equal ( pending . materialPool . amount , null );
assert . equal ( pending . materialPool . status , 'pending' );
assert . equal ( pending . material_amount , null );
assert . equal ( pending . buy_rate , null );
assert . equal ( order . status , 'delivered' );
assert . equal ( order . lines [ 0 ]. costParts . material , null );
assert . equal ( order . lines [ 0 ]. priceLockPool . status , 'pending' );
assert . equal ( order . goodsCost , null );
assert . equal ( order . profit , null );
assert . equal ( order . total , original . total );
assert . equal ( order . netReceived , original . netReceived );
assert . equal ( pending . delivery . leftover_cost , null );
assert . equal (
f . l . one ( "SELECT amount FROM price_lock_pool_returns WHERE price_lock_id=? AND kind='leftover'" , f . lock . id ). amount ,
null ,
);
assert . deepEqual ( unchangedFlows ( f . l ), flows );
noCancelledBatch ( f );
// 当前日补料不能重写原锁日;用正式历史购料复核入口补齐原日来源。
const b = f . l . one ( "SELECT * FROM material_purchases WHERE date=? AND deleted_at=''" , D ),
request = {
action : 'edit' ,
revision : b . revision ,
date : D ,
grams : '2.5' ,
total : '2500' ,
payer : 'owner' ,
note : '合成补齐原日实际公共料' ,
reason : '合成核实原日公共料' ,
verified : true ,
};
const queued = f . run ( request , () => f . l . requestMaterialPurchaseChange ( b . id , request , f . actors . owner ));
f . run ({}, () => f . l . approveMaterialPurchaseChange ( queued . id , { revision : 1 , verified : true }, f . actors . owner ));
const restored = f . l . priceLockDetail ( f . lock . id );
assert . equal ( restored . material_amount , 200000 );
assert . equal ( restored . buy_rate , 100000 );
assert . equal ( restored . delivery . leftover_cost , 100000 );
assert . equal ( f . l . detail ( id ). goodsCost , 100000 );
assert . equal ( f . l . detail ( id ). profit , 100000 );
noCancelledBatch ( f );
});
test ( '待交付池锁取消后成本待补拒绝交付,失败调用不改变快照、流水或版本' , t => {
const f = fixture ( t , { publicGrams : '0.5' , publicTotal : '500' });
f . at ( D2 );
f . cancel ();
const pending = f . l . priceLockDetail ( f . lock . id ),
before = facts ( f . l );
assert . equal ( pending . status , 'pending' );
assert . equal ( pending . material_amount , null );
assert . equal ( pending . line . costParts . material , null );
assert . throws (() => f . deliver ( D2 , '2' ), /成本待补/ );
assert . equal ( facts ( f . l ), before );
noCancelledBatch ( f );
});
test ( '锁价和余料都已退回后再取消回收,也清理历史回料身份且下游仅按公共料重算' , t => {
const f = fixture ( t );
f . at ( D2 );
const id = f . deliver ();
f . returned ( id , D2 );
const downstream = f . issue ( D2 , '1.5' );
f . at ( D3 );
const flows = unchangedFlows ( f . l );
f . cancel ();
assert . equal ( f . l . detail ( id ). status , 'returned' );
assert . equal ( f . l . detail ( id ). profit , 0 );
assert . equal ( f . l . detail ( downstream ). goodsCost , 150000 );
assert . deepEqual ( unchangedFlows ( f . l ), flows );
noCancelledBatch ( f );
const returned = f . l
. rows ( 'SELECT kind,mg,amount FROM price_lock_pool_returns WHERE price_lock_id=? ORDER BY kind' , f . lock . id )
. map ( row => ({ ... row }));
assert . deepEqual ( returned , [
{ kind : 'goods' , mg : 1000 , amount : 100000 },
{ kind : 'leftover' , mg : 1000 , amount : 100000 },
]);
});
test ( '只取消短交尾段批次时保留头段有效私料,不把尾段公共替代错放进已交付克重' , t => {
const f = fixture ( t , { recoveryGrams : '1' , recoveryTotal : '800' , priorPersonal : true }),
id = f . deliver ( D , '1' ),
later = f . issue ( D , '0.5' );
assert . equal ( f . l . detail ( id ). goodsCost , 80000 );
assert . equal ( f . l . detail ( later ). goodsCost , 40000 );
f . at ( D2 );
f . cancel ();
const lock = f . l . priceLockDetail ( f . lock . id );
assert . equal ( f . l . detail ( id ). goodsCost , 80000 );
assert . equal ( lock . material_amount , 180000 );
assert . equal ( lock . delivery . leftover_cost , 100000 );
assert . equal ( f . l . detail ( later ). goodsCost , 50000 );
assert . equal ( RecoveryMaterial . purchaseStatus ( f . l , f . prior . purchase_id ). usedMg , 1000 );
assert . equal ( f . l . detail ( id ). lines [ 0 ]. priceLockPool . materialSources [ 0 ]. kind , 'personal_recovery' );
noCancelledBatch ( f );
});
test ( '锁价取消末尾写入失败时替代标记、冻结快照、余料及下游重算一并回滚' , t => {
const f = fixture ( t );
f . at ( D2 );
f . deliver ();
f . issue ();
f . at ( D3 );
const before = facts ( f . l ),
audit = f . l . audit ;
f . l . audit = function ( entity , action , ... args ) {
if ( action === '取消回收/置换记录' ) throw new Error ( '合成锁价取消末尾故障' );
return audit . call ( this , entity , action , ... args );
};
assert . throws (() => f . cancel (), /合成锁价取消末尾故障/ );
assert . equal ( facts ( f . l ), before );
f . l . audit = audit ;
f . cancel ();
noCancelledBatch ( f );
});
test ( '锁价同日已全退且零有效占用时取消回收,历史锁价与两类回料也不遗留被取消私料' , t => {
const f = fixture ( t ),
id = f . deliver ( D , '1' );
f . returned ( id , D );
assert . deepEqual ( RecoveryMaterial . blockedUsages ( f . l , f . recovery . purchase_id ), []);
f . at ( D2 );
f . cancel ();
assert . equal ( f . l . detail ( id ). status , 'returned' );
assert . equal ( f . l . detail ( id ). profit , 0 );
noCancelledBatch ( f );
});