2026-11-08 02:22:58 +08:00
'use strict' ;
const { test } = require ( 'node:test' ),
assert = require ( 'node:assert/strict' ),
{ randomUUID } = require ( 'node:crypto' ),
fs = require ( 'node:fs' ),
os = require ( 'node:os' ),
path = require ( 'node:path' );
const { Ledger , today } = require ( '../ledger' );
const { createApp } = require ( '../server' );
const D = '2026-11-01' ,
D2 = '2026-11-02' ,
D3 = '2026-11-03' ;
const contents = l =>
JSON . stringify (
2026-12-04 08:58:53 -08:00
l
2026-11-08 02:22:58 +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' )]),
);
const clone = value => JSON . parse ( JSON . stringify ( value ));
function fixture ( t , { team = true } = {}) {
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' ,
};
actors [ member ] = actor ;
l . run ( 'INSERT INTO users VALUES (?,?,?,?,?)' , actor . id , actor . name , actor . role , 'synthetic-salt' , 'synthetic-hash' );
l . bindMemberUser ( actor . id , member );
}
if ( team ) l . enableTeamMode ();
const run = ( payload , fn , member = 'owner' , key = randomUUID ()) =>
l . scope ( actors [ member ], () => l . transact ( key , actors [ member ], payload , fn ));
const at = date => t . mock . timers . setTime ( Date . parse ( date + 'T04:00:00Z' ));
const buy = ( date = D , grams = '5' , total = '4500' , payer = 'owner' ) => {
const p = { date , grams , total , payer , note : '合成公共购料' };
return run ( p , () => l . createMaterialPurchase ( p , actors . owner ));
};
const enable = () => {
const p = l . rollingMaterialPreview ({}, actors . owner );
return run ( p , () => l . enableRollingMaterial ({ date : today (), revision : p . revision , verified : true }, actors . owner ));
};
const create = ( specs = [{}], extra = {}, member = 'assistant' ) => {
const revision = specs . some ( row => row . source === 'pool' ) ? l . materialPoolDetail ( today ()). revision : null ;
const lines = specs . map (( row , index ) => ({
name : '合成锁价黄金' + ( index + 1 ),
2026-12-04 08:58:53 -08:00
unit : 'g' ,
2026-11-08 02:22:58 +08:00
quantity : row . quantity ?? '1' ,
goldPrice : row . sellRate ?? '1000' ,
laborRate : '0' ,
laborMode : 'gram' ,
2026-12-04 08:58:53 -08:00
material :
2026-11-08 02:22:58 +08:00
row . source === 'pool'
? { source : 'pool' , poolId : today (), revision }
: { source : 'manual' , rate : row . rate ?? '850' , payer : row . payer ?? 'owner' , verified : true },
2026-12-04 08:58:53 -08:00
}));
const p = {
2026-11-08 02:22:58 +08:00
date : today (),
customer : '合成待交付客户' ,
salesperson : '合成经办' ,
2026-12-04 08:58:53 -08:00
lines ,
payment : {
2026-11-08 02:22:58 +08:00
amount : lines . reduce (( n , row ) => n + Number ( row . quantity ) * Number ( row . goldPrice ), 0 ). toFixed ( 2 ),
account : '助理微信' ,
verified : true ,
2026-12-04 08:58:53 -08:00
},
... extra ,
};
2026-11-08 02:22:58 +08:00
return run ( p , () => l . createPriceLock ( p , actors [ member ]), member ). id ;
2026-12-04 08:58:53 -08:00
};
2026-11-08 02:22:58 +08:00
const info = ( id , member = 'owner' ) => l . priceLockEdit ( id , actors [ member ]);
const editPayload = ( id , member = 'owner' ) => {
const value = info ( id , member );
return { ... clone ( value . inputs ), revision : value . revision , reason : '合成核对录错单' , verified : true };
2026-12-04 08:58:53 -08:00
};
2026-11-08 02:22:58 +08:00
const edit = ( id , p = editPayload ( id ), member = 'owner' , key = randomUUID ()) =>
run ({ id , p }, () => l . editPriceLock ( id , p , actors [ member ]), member , key );
const cancelPayload = id => ({ revision : l . priceLockDetail ( id ). revision , reason : '合成录错作废' , verified : true });
const cancel = ( id , p = cancelPayload ( id ), member = 'owner' , key = randomUUID ()) =>
run ({ id , p }, () => l . cancelPriceLock ( id , p , actors [ member ]), member , key );
const deliver = ( id , member = 'owner' ) => {
const lock = l . priceLockDetail ( id ),
2026-12-04 08:58:53 -08:00
p = {
2026-11-08 02:22:58 +08:00
date : today (),
revision : lock . revision ,
verified : true ,
lines : lock . lines . map ( row => ({
2026-11-24 21:11:32 +08:00
lineId : row . id ,
2026-11-08 02:22:58 +08:00
quantity : ( row . locked_mg / 1000 ). toFixed ( 3 ),
laborRate : '0' ,
laborMode : 'gram' ,
payer : 'owner' ,
costParts : { labor : '0' , accessories : '0' , other : '0' },
inventory : { pocket : '现货' , original : row . material_source === 'pool' ? 'stocked' : 'receive' },
2026-12-04 08:58:53 -08:00
})),
2026-11-08 02:22:58 +08:00
fee_items : [],
2026-12-04 08:58:53 -08:00
};
2026-11-08 02:22:58 +08:00
return run ({ id , p }, () => l . deliverPriceLock ( id , p , actors [ member ]), member );
2026-12-04 08:58:53 -08:00
};
2026-11-08 02:22:58 +08:00
const request = ( id , p , member = 'assistant' ) =>
run ({ id , p }, () => l . requestPriceLockChange ( id , p , actors [ member ]), member );
const approve = result => {
const p = { revision : result . request . price_lock_revision , verified : true };
return run ({ id : result . requestId , p }, () => l . approvePriceLockChange ( result . requestId , p , actors . owner ));
};
const report = ( date = today (), from = date ) =>
l . asActor ( actors . owner ). reportFor ({ date , from , basis : 'orderDate' }, actors . owner );
const issue = ( date = D2 , quantity = '1' ) => {
const p = {
date ,
member : 'assistant' ,
customer : '合成后续耗料' ,
salesperson : '合成经办' ,
payment_account : '助理微信' ,
fee_items : [],
lines : [
2026-12-04 08:58:53 -08:00
{
2026-11-08 02:22:58 +08:00
name : '合成普通足金' ,
unit : 'g' ,
quantity ,
pocket : '现货' ,
payer : 'owner' ,
sale : String ( Number ( quantity ) * 1000 ),
costParts : { material : '' , labor : '0' , accessories : '0' , other : '0' },
costMaterial : { mode : 'pool' , poolId : date },
2026-12-04 08:58:53 -08:00
},
],
2026-11-08 02:22:58 +08:00
};
return run ( p , () => l . issueOrder ( p , actors . owner )). id ;
2026-12-04 08:58:53 -08:00
};
2026-11-08 02:22:58 +08:00
const stock = () =>
2026-12-04 08:58:53 -08:00
run ({}, () =>
2026-11-08 02:22:58 +08:00
l . stock ({ date : D , kind : 'opening' , pocket : '现货' , grams : '100' , note : '合成开账库存' }, actors . owner ),
);
return {
2026-12-04 08:58:53 -08:00
l ,
2026-11-08 02:22:58 +08:00
actors ,
run ,
2026-12-04 08:58:53 -08:00
at ,
buy ,
enable ,
create ,
info ,
2026-11-08 02:22:58 +08:00
editPayload ,
2026-12-04 08:58:53 -08:00
edit ,
2026-11-24 21:11:32 +08:00
cancelPayload ,
2026-12-04 08:58:53 -08:00
cancel ,
2026-11-08 02:22:58 +08:00
deliver ,
2026-12-04 08:58:53 -08:00
request ,
approve ,
2026-11-08 02:22:58 +08:00
report ,
issue ,
2026-12-04 08:58:53 -08:00
stock ,
2026-11-08 02:22:58 +08:00
};
}
function zeroLockMoney ( f , id , date = D ) {
const lock = f . l . priceLockDetail ( id ),
r = f . report ( date );
assert . equal ( lock . status , 'cancelled' );
assert . equal ( lock . netReceived , 0 );
assert . deepEqual ( lock . cash_events , []);
assert . deepEqual ( lock . material_events , []);
assert . equal ( lock . credit_card_fee_total , 0 );
assert . equal ( r . sales , 0 );
assert . equal ( r . profit , 0 );
assert . equal ( r . receiptsByOrderDate . net , 0 );
assert . equal ( r . receiptsByOrderDate . refund , 0 );
assert . equal ( r . outlayTotal , 0 );
for ( const payer of Object . values ( r . payerCosts )) assert . equal ( payer . total , 0 );
for ( const row of f . l . teamFunds ({ from : D , to : today () }, f . actors . owner ). balances ) {
assert . equal ( row . receipts , 0 );
assert . equal ( row . refunds , 0 );
assert . equal ( row . outlays , 0 );
}
}
test ( '待交付多行录错作废保留原事件,客户款、手填购料和信用卡费全部撤销,不登记退款或销售' , t => {
const f = fixture ( t ),
id = f . create ([{ rate : '850' }, { rate : '820' , payer : 'assistant2' }], {
payment : { amount : '2000' , account : '麦麦信用卡' , credit_card_fee_payer : 'owner' , verified : true },
}),
before = f . l . rows ( 'SELECT * FROM price_lock_events WHERE price_lock_id=? ORDER BY rowid' , id ),
p = f . cancelPayload ( id ),
key = randomUUID ();
assert . equal ( f . report (). outlayTotal , 168200 );
const result = f . cancel ( id , p , 'assistant' , key );
assert . deepEqual ( clone ( f . cancel ( id , p , 'assistant' , key )), clone ( result ));
zeroLockMoney ( f , id );
const events = f . l . rows ( 'SELECT * FROM price_lock_events WHERE price_lock_id=? ORDER BY rowid' , id ),
originalFields = rows => rows . map (({ voided , void_reason , voided_at , ... row }) => row );
assert . equal ( events . length , before . length );
assert . ok ( events . every ( row => row . voided === 1 ));
assert . deepEqual ( originalFields ( events ), originalFields ( before ));
assert . ok ( events . every ( row => row . kind !== 'refund' ));
for ( const table of [ 'orders' , 'payments' , 'expenses' , 'movements' , 'journal' ])
assert . deepEqual ( f . l . rows ( 'SELECT * FROM ' + table ), []);
assert . equal ( f . info ( id ). eligible , false );
assert . equal ( f . l . priceLocks ({ status : 'pending' }). counts . pending , 0 );
assert . throws (
() => f . cancel ( id ),
error => error . status === 409 ,
);
assert . throws (
() => f . edit ( id ),
error => error . status === 409 ,
);
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 , { team : false }),
id = f . create (
[{}],
{ payment : { amount : '1000' , account : '麦麦信用卡' , credit_card_fee_payer : 'owner' , verified : true } },
'owner' ,
);
assert . equal ( f . l . dailyFunds ({ date : D }, f . actors . owner ). sources . total , 85600 );
f . cancel ( id );
const funds = f . l . dailyFunds ({ date : D }, f . actors . owner );
assert . equal ( funds . sources . total , 0 );
assert . deepEqual ( funds . sources . items , []);
assert . equal ( f . report (). receiptsByOrderDate . net , 0 );
assert . equal ( f . report (). outlayTotal , 0 );
assert . ok ( f . l . report ( D ). accounts . every ( row => row . receipt === 0 && row . refund === 0 ));
});
test ( '待交付修改可以更正多行和整单实收,稳定行身份保留且原作废来源不再计账' , t => {
const f = fixture ( t ),
id = f . create ([{ rate : '850' }, { rate : '820' , payer : 'assistant2' }]),
initial = f . l . priceLockDetail ( id ),
p = f . editPayload ( id );
p . lines = p . lines . slice ( 0 , 1 );
p . lines [ 0 ]. quantity = '1.5' ;
p . lines [ 0 ]. goldPrice = '1100' ;
p . lines [ 0 ]. material = { source : 'manual' , rate : '860' , payer : 'assistant2' , verified : true };
p . payment = { amount : '1650' , account : '助理2微信' , verified : true };
f . edit ( id , p , 'assistant' );
const updated = f . l . priceLockDetail ( id ),
r = f . report ();
assert . equal ( updated . id , id );
assert . equal ( updated . number , initial . number );
assert . equal ( updated . created , initial . created );
assert . equal ( updated . lines . length , 1 );
assert . equal ( updated . lines [ 0 ]. id , initial . lines [ 0 ]. id );
assert . equal ( updated . lines [ 0 ]. locked_mg , 1500 );
assert . equal ( updated . lines [ 0 ]. sell_rate , 110000 );
assert . equal ( updated . lines [ 0 ]. material_amount , 129000 );
assert . equal ( updated . netReceived , 165000 );
assert . equal ( r . outlayTotal , 129000 );
assert . equal ( r . receiptsByOrderDate . net , 165000 );
assert . equal ( r . receiptsByOrderDate . refund , 0 );
assert . equal ( f . l . rows ( 'SELECT * FROM orders' ). length , 0 );
assert . equal ( f . l . rows ( 'SELECT * FROM movements' ). length , 0 );
assert . equal ( updated . status , 'pending' );
assert . deepEqual (
f . l . rows (
"SELECT s.source_id FROM team_fund_sources s LEFT JOIN price_locks p ON p.id=s.source_id WHERE s.kind='price_lock' AND p.id IS NULL" ,
),
[],
'内部试算锁价不应留下资金来源' ,
);
});
2026-11-24 21:11:32 +08:00
test ( '历史混合锁价作废原成本回当天料池,保留原日预留事实及公共采购' , t => {
2026-11-08 02:22:58 +08:00
const f = fixture ( t );
f . stock ();
f . buy ( D , '5' , '4500' , 'assistant2' );
f . enable ();
const id = f . create ([{ source : 'pool' , quantity : '1' }, { source : 'pool' , quantity : '1' }, { rate : '850' }]),
purchases = f . l . rows ( 'SELECT * FROM material_purchases ORDER BY rowid' );
f . at ( D2 );
f . buy ( D2 , '1' , '1200' , 'owner' );
const later = f . issue ( D2 , '1' ),
beforeOrder = f . l . detail ( later ),
beforeCash = f . l . rows ( 'SELECT * FROM payments ORDER BY rowid' );
assert . equal ( f . l . materialPoolDetail ( D2 ). remainingMg , 3000 );
2026-11-24 21:11:32 +08:00
f . cancel ( id );
const after = f . l . detail ( later ),
pool = f . l . materialPoolDetail ( D2 );
assert . equal ( f . l . priceLockDetail ( id ). status , 'cancelled' );
assert . equal ( f . l . rows ( 'SELECT * FROM price_lock_pool_reservations WHERE price_lock_id=?' , id ). length , 2 );
assert . deepEqual (
f . l
. rows ( 'SELECT date,mg,amount,kind FROM price_lock_pool_returns WHERE price_lock_id=? ORDER BY line_index' , id )
. map ( row => ({ ... row })),
2026-12-04 08:58:53 -08:00
[
2026-11-24 21:11:32 +08:00
{ date : D2 , mg : 1000 , amount : 90000 , kind : 'cancel' },
{ date : D2 , mg : 1000 , amount : 90000 , kind : 'cancel' },
2026-12-04 08:58:53 -08:00
],
2026-11-24 21:11:32 +08:00
);
assert . equal ( pool . remainingMg , 5000 );
assert . equal ( after . goodsCost , 95000 );
assert . equal ( after . total , beforeOrder . total );
assert . equal ( after . netReceived , beforeOrder . netReceived );
assert . deepEqual ( f . l . rows ( 'SELECT * FROM payments ORDER BY rowid' ), beforeCash );
2026-11-08 02:22:58 +08:00
assert . deepEqual ( f . l . rows ( 'SELECT * FROM material_purchases WHERE date=? ORDER BY rowid' , D ), purchases );
assert . equal ( f . report ( D ). receiptsByOrderDate . net , 0 );
assert . equal ( f . report ( D ). outlayTotal , 450000 );
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 ),
id = f . create ();
f . at ( D2 );
const p = f . cancelPayload ( id ),
before = contents ( f . l );
assert . throws (
() => f . cancel ( id , p , 'assistant' ),
error => error . status === 403 ,
);
assert . equal ( contents ( f . l ), before );
assert . throws (
() => f . l . asActor ( f . actors . assistant2 ). priceLockEdit ( id , f . actors . assistant2 ),
error => error . status === 404 ,
);
const events = f . l . rows ( 'SELECT * FROM price_lock_events ORDER BY rowid' ),
result = f . request ( id , { action : 'cancel' , ... p });
assert . equal ( result . request . status , 'pending' );
assert . deepEqual ( f . l . rows ( 'SELECT * FROM price_lock_events ORDER BY rowid' ), events );
assert . equal ( f . l . priceLockDetail ( id ). status , 'pending' );
assert . equal ( f . l . priceLockChange ( result . requestId , f . actors . owner ). stale , false );
const frozen = contents ( f . l );
assert . throws (
() => f . cancel ( id ),
error => error . status === 409 ,
);
assert . throws (
() => f . deliver ( id ),
error => error . status === 409 ,
);
assert . equal ( contents ( f . l ), frozen );
assert . throws (
() =>
f . run (
{},
() =>
f . l . approvePriceLockChange (
result . requestId ,
{ revision : result . request . price_lock_revision , verified : true },
f . actors . assistant ,
),
'assistant' ,
),
error => error . status === 403 ,
);
f . approve ( result );
zeroLockMoney ( f , id , D );
assert . throws (
() => f . approve ( result ),
error => error . status === 409 ,
);
assert . throws (
() => f . deliver ( id ),
error => error . status === 409 ,
);
assert . throws (
() => f . cancel ( id ),
error => error . status === 409 ,
);
});
test ( '锁价修改确认、版本及料池余额逐项校验,非法行身份与中途异常不留下半张单' , t => {
const f = fixture ( t );
f . buy ();
f . enable ();
const id = f . create ([{ source : 'pool' }, { source : 'manual' }]);
const mutations = [
p => ( p . verified = false ),
p => p . revision -- ,
p => ( p . lines [ 0 ]. lineId = 'not-a-line' ),
p => ( p . lines [ 0 ]. quantity = '99' ),
p => ( p . payment . verified = false ),
p => ( p . lines [ 1 ]. material . verified = false ),
];
for ( const change of mutations ) {
const p = f . editPayload ( id );
change ( p );
const before = contents ( f . l );
assert . throws (() => f . edit ( id , p ));
assert . equal ( contents ( f . l ), before );
}
});
test ( '锁价池来源在待审后变动使申请过期,不能沿旧预览授权新均价' , t => {
const f = fixture ( t );
f . buy ();
f . enable ();
const id = f . create ([{ source : 'pool' }, { source : 'manual' }]),
p = f . cancelPayload ( id ),
result = f . request ( id , { action : 'cancel' , ... p });
assert . equal ( f . l . priceLockChange ( result . requestId , f . actors . owner ). stale , false );
f . buy ( D , '1' , '1200' , 'assistant2' );
assert . equal ( f . l . priceLockChange ( result . requestId , f . actors . owner ). stale , true );
const before = contents ( f . l );
assert . throws (
() => f . approve ( result ),
error => error . status === 409 ,
);
assert . equal ( contents ( f . l ), before );
assert . equal ( f . l . priceLockDetail ( id ). status , 'pending' );
});
test ( '历史修改审批可重排和增删锁行,保留沿用行身份并复算全部成本,其他成员看不到申请' , t => {
const f = fixture ( t ),
id = f . create ([{ rate : '850' }, { rate : '820' }]),
original = f . l . priceLockDetail ( id );
f . at ( D2 );
const p = f . editPayload ( id );
p . lines = [
p . lines [ 1 ],
2026-12-04 08:58:53 -08:00
{
2026-11-08 02:22:58 +08:00
name : '合成新增黄金' ,
unit : 'g' ,
quantity : '0.750' ,
goldPrice : '1200' ,
laborRate : '0' ,
laborMode : 'gram' ,
material : { source : 'manual' , rate : '820' , payer : 'assistant2' , verified : true },
2026-12-04 08:58:53 -08:00
},
2026-11-08 02:22:58 +08:00
];
p . payment = { amount : '1900' , account : '助理2微信' , verified : true };
const beforeEvents = f . l . rows ( 'SELECT * FROM price_lock_events ORDER BY rowid' ),
result = f . request ( id , { action : 'edit' , ... p });
assert . deepEqual ( f . l . rows ( 'SELECT * FROM price_lock_events ORDER BY rowid' ), beforeEvents );
assert . throws (
() => f . l . asActor ( f . actors . assistant2 ). priceLockChange ( result . requestId , f . actors . assistant2 ),
error => error . status === 404 ,
);
f . approve ( result );
const updated = f . l . priceLockDetail ( id );
assert . equal ( updated . lines . length , 2 );
assert . equal ( updated . lines [ 0 ]. id , original . lines [ 1 ]. id );
assert . ok ( updated . lines [ 1 ]. id && ! original . lines . some ( row => row . id === updated . lines [ 1 ]. id ));
assert . deepEqual (
updated . lines . map ( row => row . locked_mg ),
[ 1000 , 750 ],
);
assert . deepEqual (
updated . lines . map ( row => row . material_amount ),
[ 82000 , 61500 ],
);
assert . equal ( updated . netReceived , 190000 );
assert . equal ( updated . estimated_total , 190000 );
assert . equal ( f . report ( D ). outlayTotal , 143500 );
assert . equal ( f . report ( D ). receiptsByOrderDate . net , 190000 );
assert . equal ( f . report ( D ). receiptsByOrderDate . refund , 0 );
});
test ( '历史两池行修改批准后沿稳定商品保留预留及FIFO身份,增重重算后续订单与分厘' , t => {
const f = fixture ( t );
f . stock ();
f . buy ( D , '5' , '4500' , 'assistant2' );
f . enable ();
const id = f . create ([{ source : 'pool' }, { source : 'pool' }]),
original = f . l . priceLockDetail ( id ),
reservations = new Map (
f . l
. rows (
"SELECT r.*,s.sequence FROM price_lock_pool_reservations r JOIN material_usage_order s ON s.kind='priceLock' AND s.source_id=r.id WHERE r.price_lock_id=?" ,
id ,
2026-12-04 08:58:53 -08:00
)
2026-11-08 02:22:58 +08:00
. map ( row => [ original . lines [ row . line_index ]. id , row ]),
);
f . at ( D2 );
f . buy ( D2 , '1' , '1200' , 'owner' );
const later = f . issue ( D2 ),
beforeOrder = f . l . detail ( later ),
p = f . editPayload ( id );
p . lines . reverse ();
p . lines [ 0 ]. quantity = '1.5' ;
p . payment . amount = '2500' ;
assert . equal ( beforeOrder . goodsCost , 97500 );
const before = contents ( f . l ),
result = f . request ( id , { action : 'edit' , ... p });
assert . equal ( f . l . detail ( later ). goodsCost , beforeOrder . goodsCost );
assert . deepEqual (
f . l . priceLockDetail ( id ). lines . map ( row => row . id ),
original . lines . map ( row => row . id ),
);
assert . ok ( contents ( f . l ). length > before . length );
f . approve ( result );
const updated = f . l . priceLockDetail ( id );
assert . deepEqual (
updated . lines . map ( row => row . id ),
original . lines . map ( row => row . id ). reverse (),
);
assert . deepEqual (
updated . lines . map ( row => row . locked_mg ),
[ 1500 , 1000 ],
);
assert . equal ( f . l . detail ( later ). goodsCost , 98571 );
assert . equal ( f . l . detail ( later ). netReceived , beforeOrder . netReceived );
assert . equal ( f . l . materialPoolDetail ( D2 ). remainingMg , 2500 );
for ( const row of f . l . rows (
"SELECT r.*,s.sequence FROM price_lock_pool_reservations r JOIN material_usage_order s ON s.kind='priceLock' AND s.source_id=r.id WHERE r.price_lock_id=?" ,
id ,
)) {
const old = reservations . get ( updated . lines [ row . line_index ]. id );
assert . equal ( row . id , old . id );
assert . equal ( row . sequence , old . sequence );
assert . equal ( row . created , old . created );
}
assert . deepEqual (
f . l . rows (
"SELECT s.source_id FROM team_fund_sources s LEFT JOIN price_locks p ON p.id=s.source_id WHERE s.kind='price_lock' AND p.id IS NULL" ,
),
[],
);
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 . stock ();
f . buy ();
f . enable ();
const id = f . create ([{ source : 'pool' }, {}]);
f . at ( D2 );
f . buy ( D2 , '1' , '1200' );
f . issue ( D2 );
const p = f . editPayload ( id );
p . lines [ 0 ]. quantity = '1.5' ;
p . payment . amount = '2500' ;
const before = contents ( f . l ),
audit = f . l . audit ;
f . l . audit = function ( entity , action , ... rest ) {
const result = audit . call ( this , entity , action , ... rest );
if ( entity === 'price-lock:' + id && [ '修改待交付锁价单' , '录错作废待交付锁价单' ]. includes ( action ))
throw new Error ( '合成锁价更正末尾故障' );
return result ;
};
assert . throws (() => f . edit ( id , p ), /合成锁价更正末尾故障/ );
assert . equal ( contents ( f . l ), before );
assert . throws (() => f . cancel ( id ), /合成锁价更正末尾故障/ );
assert . equal ( contents ( f . l ), before );
assert . equal ( f . l . rollingHistorical , undefined );
assert . equal ( f . l . rollingRebuilding , undefined );
f . l . audit = audit ;
});
test ( 'HTTP待交付修改和作废受登录、CSRF与操作号保护,历史请求只能麦麦批准' , async t => {
const dir = fs . mkdtempSync ( path . join ( os . tmpdir (), 'maimai-pending-lock-http-' )),
app = createApp ({
mode : 'trial' ,
dataDir : dir ,
ledger : new Ledger ( path . join ( dir , 'ledger.sqlite' )),
feishuConfig : { enabled : false },
});
await new Promise ( resolve => app . server . listen ( 0 , '127.0.0.1' , resolve ));
2026-12-04 08:52:50 -08:00
t . after ( async () => {
await new Promise ( resolve => {
app . server . closeAllConnections ();
app . server . close ( resolve );
});
app . ledger . close ();
fs . rmSync ( dir , { recursive : true , force : true });
});
2026-11-08 02:22:58 +08:00
const base = 'http://127.0.0.1:' + app . server . address (). port ;
let cookie = '' ;
const call = ( route , data , key = randomUUID (), origin = base ) =>
fetch ( base + route , {
method : data ? 'POST' : 'GET' ,
headers : {
...( cookie ? { Cookie : cookie } : {}),
...( data
2026-12-04 08:58:53 -08:00
? {
2026-11-08 02:22:58 +08:00
'Content-Type' : 'application/json' ,
Origin : origin ,
'X-Requested-With' : 'maimai-ledger' ,
'Idempotency-Key' : key ,
2026-12-04 08:58:53 -08:00
}
2026-11-08 02:22:58 +08:00
: {}),
},
...( data ? { body : JSON . stringify ( data ) } : {}),
});
const script = await call ( '/price-lock-changes-ui.js' );
assert . equal ( script . status , 200 );
assert . match ( script . headers . get ( 'content-type' ), /javascript/ );
const scriptText = await script . text ();
assert . match ( scriptText , /function priceLockPendingButtonsHTML\(/ );
assert . match ( scriptText , /edit-price-lock/ );
assert . match ( scriptText , /cancel-price-lock/ );
assert . equal (( await call ( '/api/price-lock-changes' )). status , 401 );
const setup = await call ( '/api/setup' , {
ownerPassword : 'synthetic-owner-password' ,
assistantPassword : 'synthetic-assistant-password' ,
});
assert . equal ( setup . status , 200 );
cookie = setup . headers . get ( 'set-cookie' ). split ( ';' )[ 0 ];
const creation = date => ({
date ,
member : 'assistant' ,
customer : '合成HTTP客户' ,
salesperson : '合成经办' ,
line : { name : '合成足金' , unit : 'g' , quantity : '1' , goldPrice : '1000' , laborRate : '0' , laborMode : 'gram' },
material : { source : 'manual' , rate : '850' , payer : 'owner' , verified : true },
payment : { amount : '1000' , account : '助理微信' , verified : true },
});
const old = await ( await call ( '/api/price-locks' , creation ( D ))). json (),
current = await ( await call ( '/api/price-locks' , creation ( today ()))). json (),
login = await call ( '/api/login' , { name : '助理' , password : 'synthetic-assistant-password' });
cookie = login . headers . get ( 'set-cookie' ). split ( ';' )[ 0 ];
const contextResponse = await call ( '/api/price-locks/' + current . id + '/edit-context' );
assert . equal ( contextResponse . status , 200 );
const context = await contextResponse . json (),
p = { ... context . inputs , revision : context . revision , reason : '合成HTTP更正' , verified : true };
p . lines [ 0 ]. material . rate = '860' ;
assert . equal (
( await call ( '/api/price-locks/' + current . id + '/edit' , p , randomUUID (), 'https://invalid.example' )). status ,
403 ,
);
const editKey = randomUUID (),
edits = await Promise . all ([
call ( '/api/price-locks/' + current . id + '/edit' , p , editKey ),
call ( '/api/price-locks/' + current . id + '/edit' , p , editKey ),
]);
assert . deepEqual (
edits . map ( row => row . status ),
[ 200 , 200 ],
);
assert . deepEqual ( await edits [ 0 ]. json (), await edits [ 1 ]. json ());
assert . equal ( app . ledger . priceLockDetail ( current . id ). lines [ 0 ]. buy_rate , 86000 );
const oldInfo = await ( await call ( '/api/price-locks/' + old . id + '/edit-context' )). json (),
cancel = { revision : oldInfo . revision , reason : '合成HTTP作废' , verified : true };
assert . equal (( await call ( '/api/price-locks/' + old . id + '/cancel' , cancel )). status , 403 );
const requested = await call ( '/api/price-locks/' + old . id + '/change-requests' , { action : 'cancel' , ... cancel });
assert . equal ( requested . status , 200 );
const request = await requested . json ();
assert . equal (( await call ( '/api/price-lock-changes/' + request . requestId )). status , 200 );
assert . equal (
2026-12-04 08:58:53 -08:00
(
2026-11-08 02:22:58 +08:00
await call ( '/api/price-lock-changes/' + request . requestId + '/approve' , {
revision : request . request . price_lock_revision ,
verified : true ,
2026-12-04 08:58:53 -08:00
})
2026-11-08 02:22:58 +08:00
). status ,
403 ,
);
const ownerLogin = await call ( '/api/login' , { name : '麦麦' , password : 'synthetic-owner-password' });
cookie = ownerLogin . headers . get ( 'set-cookie' ). split ( ';' )[ 0 ];
assert . equal (( await call ( '/api/price-lock-changes?status=pending' )). status , 200 );
const approval = { revision : request . request . price_lock_revision , verified : true },
key = randomUUID (),
decisions = await Promise . all ([
call ( '/api/price-lock-changes/' + request . requestId + '/approve' , approval , key ),
call ( '/api/price-lock-changes/' + request . requestId + '/approve' , approval , key ),
]);
assert . deepEqual (
decisions . map ( row => row . status ),
[ 200 , 200 ],
2026-12-04 08:58:53 -08:00
);
2026-11-08 02:22:58 +08:00
assert . deepEqual ( await decisions [ 0 ]. json (), await decisions [ 1 ]. json ());
assert . equal ( app . ledger . priceLockDetail ( old . id ). status , 'cancelled' );
assert . equal (( await call ( '/api/price-lock-changes/' + request . requestId + '/approve' , approval )). status , 409 );
});
2026-11-24 21:11:32 +08:00
test ( '跨天作废按冻结原成本回今天参与加权,不改昨天订单、利润、料池及快照,不重复回料' , t => {
const f = fixture ( t );
f . stock ();
f . buy ( D , '10' , '8000' );
f . enable ();
const id = f . create ([{ source : 'pool' , quantity : '8' }]);
f . at ( D2 );
f . buy ( D2 , '10' , '10000' );
const oldOrder = f . issue ( D2 , '10' );
f . at ( D3 );
f . buy ( D3 , '1' , '1000' );
const previousOrder = clone ( f . l . detail ( oldOrder )),
previousPool = clone ( f . l . materialPoolDetail ( D2 )),
previousDay = f . l . one ( 'SELECT * FROM material_rolling_days WHERE date=?' , D2 ),
purchases = clone ( f . l . rows ( 'SELECT * FROM material_purchases ORDER BY rowid' ));
const currentOrder = f . issue ( D3 , '1' ),
before = f . l . detail ( currentOrder ). goodsCost ,
movement = clone ( f . l . rows ( 'SELECT * FROM movements ORDER BY rowid' ));
const payload = f . cancelPayload ( id ),
key = randomUUID (),
result = f . cancel ( id , payload , 'owner' , key ),
pool = f . l . materialPoolDetail ( D3 );
assert . equal ( before , 97778 );
assert . equal ( pool . totalMg , 11000 );
assert . equal ( pool . totalAmount , 933333 );
assert . equal ( pool . averageRate , 84848 );
assert . equal ( f . l . detail ( currentOrder ). goodsCost , 84848 );
assert . deepEqual ( clone ( f . l . detail ( oldOrder )), previousOrder );
assert . deepEqual ( clone ( f . l . materialPoolDetail ( D2 )), previousPool );
assert . deepEqual ( f . l . one ( 'SELECT * FROM material_rolling_days WHERE date=?' , D2 ), previousDay );
assert . equal ( f . l . detail ( oldOrder ). goodsCost , 966667 );
assert . deepEqual ( clone ( f . l . rows ( 'SELECT * FROM material_purchases ORDER BY rowid' )), purchases );
assert . deepEqual ( clone ( f . l . rows ( 'SELECT * FROM movements ORDER BY rowid' )), movement );
const back = result . lock . cancellationReturns ;
assert . equal ( back . length , 1 );
assert . equal ( back [ 0 ]. date , D3 );
assert . equal ( back [ 0 ]. mg , 8000 );
assert . equal ( back [ 0 ]. amount , 640000 );
assert . deepEqual ( back [ 0 ]. allocations , [{ payer : 'owner' , amount : 640000 }]);
assert . deepEqual ( f . cancel ( id , payload , 'owner' , key ), result );
assert . equal ( f . l . rows ( "SELECT * FROM price_lock_pool_returns WHERE price_lock_id=? AND kind='cancel'" , id ). length , 1 );
assert . throws (() => f . cancel ( id ), /待交付/ );
assert . equal (
pool . purchases . filter ( row => row . sourceKind === 'return' ). reduce (( n , row ) => n + row . amount , 0 ),
640000 ,
);
f . at ( '2026-11-04' );
f . buy ( '2026-11-04' , '1' , '1000' );
assert . equal ( f . l . materialPoolDetail ( '2026-11-04' ). opening . amount , pool . remainingCost );
assert . equal ( f . l . materialPoolDetail ( D3 ). remainingCost , pool . remainingCost );
});
test ( '当天作废仅释放预留,多次读取不新增回料,跨天成本待补时不伪造金额' , t => {
const f = fixture ( t );
f . stock ();
f . buy ( D , '10' , '8000' );
f . enable ();
const id = f . create ([{ source : 'pool' , quantity : '8' }]);
f . buy ( D , '10' , '10000' );
f . cancel ( id );
const pool = f . l . materialPoolDetail ( D );
assert . equal ( pool . totalMg , 20000 );
assert . equal ( pool . totalAmount , 1800000 );
assert . equal ( pool . usedMg , 0 );
assert . equal ( f . l . rows ( 'SELECT * FROM price_lock_pool_returns' ). length , 0 );
const next = f . create ([{ source : 'pool' , quantity : '1' }]);
f . at ( D2 );
f . l . run ( 'UPDATE price_lock_pool_reservations SET amount=NULL WHERE price_lock_id=?' , next );
const before = contents ( f . l );
assert . throws (() => f . cancel ( next ), /待核实/ );
assert . equal ( contents ( f . l ), before );
});
test ( '私人和公共混合锁料跨天作废,各回原来源与付款人,不产生新购料现金' , t => {
const f = fixture ( t );
f . stock ();
f . buy ( D , '10' , '9000' , 'owner' );
f . enable ();
const input = {
date : D ,
member : 'assistant' ,
mode : 'direct' ,
customer : '合成私人回料' ,
salesperson : '合成经办' ,
old_lines : [{ name : '旧料' , incoming_weight : '2' , melted_weight : '2' , purity : '100' }],
buy_rate : '800' ,
payer : 'assistant2' ,
payment_account : '助理2微信' ,
verified : true ,
};
f . run ( input , () => f . l . createRecovery ( input , f . actors . owner ));
const id = f . create ([{ source : 'pool' , quantity : '3' }]),
locked = f . l . priceLockDetail ( id );
assert . equal ( locked . material_amount , 250000 );
f . at ( D2 );
f . buy ( D2 , '1' , '1000' );
const cash = clone ( f . l . rows ( "SELECT * FROM team_fund_cash WHERE kind='outlay' ORDER BY rowid" ));
f . cancel ( id );
const pool = f . l . materialPoolDetail ( D2 );
assert . equal ( pool . personalPools . assistant . remainingMg , 2000 );
assert . equal ( pool . personalPools . assistant . remainingCost , 160000 );
assert . equal ( pool . remainingMg , 11000 );
assert . equal ( pool . remainingCost , 1000000 );
const back = f . l . priceLockDetail ( id ). cancellationReturns ;
assert . equal ( back [ 0 ]. amount , 250000 );
assert . deepEqual ( back [ 0 ]. allocations , locked . materialPool . allocations );
assert . deepEqual ( clone ( f . l . rows ( "SELECT * FROM team_fund_cash WHERE kind='outlay' ORDER BY rowid" )), cash );
});
test ( '作废申请只读试算,次日复核按实际批准日回原成本,预览与审批结果一致' , t => {
const f = fixture ( t );
f . stock ();
f . buy ( D , '10' , '8000' );
f . enable ();
const id = f . create ([{ source : 'pool' , quantity : '2' }]);
f . at ( D2 );
const pending = f . request ( id , { ... f . cancelPayload ( id ), action : 'cancel' });
assert . equal ( pending . request . materialReturnDate , D2 );
assert . equal ( f . l . rows ( 'SELECT * FROM price_lock_pool_returns' ). length , 0 );
f . at ( D3 );
const reviewed = f . l . priceLockChange ( pending . requestId , f . actors . owner );
assert . equal ( reviewed . materialReturnDate , D3 );
assert . equal ( reviewed . after . cancellationReturns [ 0 ]. date , D3 );
assert . equal ( f . l . rows ( 'SELECT * FROM price_lock_pool_returns' ). length , 0 );
const result = f . approve ( pending );
assert . equal ( result . lock . cancellationReturns [ 0 ]. date , D3 );
assert . equal ( result . lock . cancellationReturns [ 0 ]. amount , 160000 );
assert . equal ( result . request . materialReturnDate , D3 );
assert . equal ( f . l . rows ( 'SELECT * FROM price_lock_pool_returns WHERE date=?' , D2 ). length , 0 );
});
test ( '回料日没有新增购料也可查询,次日结转不重复计料' , t => {
const f = fixture ( t );
f . buy ( D , '5' , '4500' );
f . enable ();
const id = f . create ([
{ source : 'pool' , quantity : '1' },
{ source : 'pool' , quantity : '2' },
]);
const old = f . l . materialPoolDetail ( D );
f . at ( D2 );
f . cancel ( id );
assert . equal ( f . l . materialPoolDetail ( D ). remainingMg , old . remainingMg );
assert . equal ( f . l . materialPoolDetail ( D ). remainingCost , old . remainingCost );
const returned = f . l . materialPoolDetail ( D2 );
assert . equal ( returned . totalMg , 5000 );
assert . equal ( returned . totalAmount , 450000 );
assert . equal ( returned . remainingMg , 5000 );
f . at ( D3 );
const pool = f . l . materialPools (). current ;
assert . equal ( pool . remainingMg , 5000 );
assert . equal ( pool . remainingCost , 450000 );
});
test ( '回池后当天再补料只重算当天,原回料金额与多人付款份额始终不变' , t => {
const f = fixture ( t );
f . stock ();
f . buy ( D , '1' , '800' , 'assistant2' );
f . buy ( D , '4' , '3200' , 'owner' );
f . enable ();
const id = f . create ([{ source : 'pool' , quantity : '2' }]),
original = clone ( f . l . priceLockDetail ( id ). materialPool );
f . at ( D2 );
f . buy ( D2 , '1' , '1000' );
const order = f . issue ( D2 , '1' );
f . at ( D3 );
f . cancel ( id );
const previous = f . l . detail ( order ). goodsCost ;
f . buy ( D3 , '3' , '3000' );
const returned = f . l . priceLockDetail ( id ). cancellationReturns [ 0 ];
assert . equal ( returned . amount , 160000 );
assert . deepEqual ( returned . allocations , original . allocations );
assert . equal ( f . l . detail ( order ). goodsCost , previous );
assert . equal ( f . l . rows ( "SELECT * FROM price_lock_pool_returns WHERE price_lock_id=? AND kind='cancel'" , id ). length , 1 );
});