2026-10-23 11:58:19 +08:00
'use strict' ;
const { test } = require ( 'node:test' ), assert = require ( 'node:assert/strict' ),{ randomUUID } = 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 D = '2026-10-22' , Y = '2026-10-21' , owner = { id : 'day-action-owner' , name : '合成麦麦' , role : 'owner' }, assistant = { id : 'day-action-assistant' , name : '合成助理' , role : 'assistant' };
const input = ( extra = {})=>({ date : D , customer : '合成当日操作' , salesperson : '合成开单人' , payment_account : '助理信用卡' , rounding_mode : 'cent' , discount : '0' , fee_items : [], lines : [{ name : '银饰合成' , unit : '件' , quantity : '1' , pocket : '' , payer : 'assistant' , cost : '80' , sale : '100' }],... extra });
const all = l => JSON . stringify ( l . rows ( "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name" ). map (({ name })=>[ name , l . rows ( 'SELECT * FROM "' + name + '"' )]));
function fixture ( t ){
t . mock . timers . enable ({ apis : [ 'Date' ], now : Date . parse ( '2026-10-22T15:58:00Z' )}); assert . equal ( today (), D ); const l = new Ledger ( ':memory:' ); t . after (()=> l . close ());
const run = ( p , fn , actor = assistant , key = randomUUID ())=> l . transact ( key , actor , p , fn ), issue = ( p = input ())=> run ( p ,()=> l . issueOrder ( p , assistant )). id ;
const actionInput = ( id , extra = {})=>({ date : D , revision : l . detail ( id ). revision , reason : '核对当天实际凭据' , verified : true ,... extra });
const act = ( id , kind , p = actionInput ( id ), key = randomUUID (), actor = assistant )=> run ({ id , kind , p },()=> l . action ( id , kind , p , actor ), actor , key );
const cancel = ( id , p = actionInput ( id ), key = randomUUID (), actor = assistant )=> run ({ id , p },()=> l . cancelOrderToday ( id , p , actor ), actor , key );
return { l , run , issue , actionInput , act , cancel };
}
test ( '当天补费用直接入账且复核失效,同操作号只记一次,真实退货退款保留实际卡费和费用' , t =>{
const f = fixture ( t ), id = f . issue (); f . act ( id , 'review' ,{ date : D , revision : f . l . detail ( id ). revision }, randomUUID (), owner );
2026-10-25 14:19:24 +08:00
const p = f . actionInput ( id ,{ amount : '1' , payer : 'assistant' , note : '真实邮费' }), key = randomUUID (); f . act ( id , 'expense' , p , key ); const saved = all ( f . l ); f . act ( id , 'expense' , p , key ); assert . equal ( all ( f . l ), saved ); assert . equal ( f . l . detail ( id ). reviewed_revision , 0 ); assert . equal ( f . l . detail ( id ). directCost , 160 ); assert . equal ( f . l . rows ( 'SELECT * FROM order_changes' ). length , 0 ); assert . equal ( f . l . orderChange ( id , assistant ). actions . return . directToday , true );
f . act ( id , 'return' ); assert . equal ( f . l . detail ( id ). profit , - 160 ); const refund = f . actionInput ( id ,{ amount : '100' , account : '助理信用卡' }), refundKey = randomUUID (); f . act ( id , 'refund' , refund , refundKey ); const after = all ( f . l ); f . act ( id , 'refund' , refund , refundKey ); assert . equal ( all ( f . l ), after ); assert . equal ( f . l . detail ( id ). netReceived , 0 ); assert . equal ( f . l . detail ( id ). directCost , 160 ); assert . ok ( f . l . detail ( id ). audit . filter ( row =>[ 'expense' , 'return' , 'refund' ]. includes ( row . action )). every ( row => row . actor === assistant . name && row . detail . direct === true ));
2026-10-23 11:58:19 +08:00
});
test ( '当天旧费用须显式核实,confirm或complete不能绕过,核实后继续履约不重复入账' , t =>{
const f = fixture ( t ), p = input ({ fee_items : [{ key : 'shipping' , note : '快递费' , amount : '6' , payer : 'assistant' , status : 'estimated' }]}), id = f . run ( p ,()=> f . l . saveOrder ( p , owner ), owner ). id ;
const before = all ( f . l ); assert . throws (()=> f . act ( id , 'confirm' ,{ date : D , feesVerified : true }), error => error . status === 403 ); assert . equal ( all ( f . l ), before ); f . act ( id , 'confirm' ,{ date : D }); const confirmed = all ( f . l ); assert . throws (()=> f . act ( id , 'complete' , f . actionInput ( id )), error => error . status === 403 ); assert . equal ( all ( f . l ), confirmed );
const fees = f . actionInput ( id ,{ fee_items : p . fee_items }), key = randomUUID (); f . act ( id , 'fees' , fees , key ); const rows = f . l . rows ( 'SELECT * FROM expenses' ); f . act ( id , 'fees' , fees , key ); assert . deepEqual ( f . l . rows ( 'SELECT * FROM expenses' ), rows ); f . act ( id , 'receipt' ,{ date : D , amount : '100' , account : '助理微信' , verified : true }); f . act ( id , 'complete' , f . actionInput ( id )); assert . equal ( f . l . detail ( id ). profit , 1400 ); assert . equal ( f . l . detail ( id ). expenses . length , 1 );
});
test ( '旧单改操作日到今天、今天改旧操作日仍403,版本确认原因必填,pending阻止全部直做' , t =>{
const f = fixture ( t ), old = f . issue ( input ({ date : Y })), current = f . issue ();
for ( const [ id , date ] of [[ old , D ],[ old , Y ],[ current , Y ]]){ const p = f . actionInput ( id ,{ date , amount : '1' , payer : 'assistant' , note : '不能绕过' }), before = all ( f . l ); assert . throws (()=> f . act ( id , 'expense' , p ), error => error . status === 403 ); assert . equal ( all ( f . l ), before ); assert . throws (()=> f . cancel ( id , p ), error => error . status === 403 ); assert . equal ( all ( f . l ), before );}
for ( const patch of [{ revision : undefined },{ revision : 0 },{ verified : false },{ reason : '' }]){ const p = f . actionInput ( current ,{ amount : '1' , payer : 'assistant' , note : '缺确认' ,... patch }), before = all ( f . l ); assert . throws (()=> f . act ( current , 'expense' , p )); assert . equal ( all ( f . l ), before ); assert . throws (()=> f . cancel ( current , p )); assert . equal ( all ( f . l ), before );}
const p = f . actionInput ( current ,{ action : 'expense' , amount : '1' , payer : 'assistant' , note : '先申请待审' }); f . run ( p ,()=> f . l . requestOrderChange ( current , p , assistant )); const before = all ( f . l ); for ( const kind of [ 'expense' , 'return' ]) assert . throws (()=> f . act ( current , kind , f . actionInput ( current ,{ amount : '1' , payer : 'assistant' , note : '不可绕过待审' })), error => error . status === 409 ); assert . throws (()=> f . cancel ( current ), error => error . status === 409 ); assert . equal ( all ( f . l ), before ); assert . equal ( f . l . orderCancellation ( current , assistant ). directToday , false );
});
test ( '同日取消复用作废核心且不伪造审批人,信用卡费用销售收款库存全冲,双方真实转账保留' , t =>{
2026-10-25 14:19:24 +08:00
const f = fixture ( t ); f . run ({ opening : true },()=> f . l . stock ({ kind : 'opening' , date : Y , pocket : '现货' , grams : '10' , note : '合成库存' }, owner ), owner ); const p = input ({ lines : [{ name : '足金999' , unit : 'g' , quantity : '1' , pocket : '现货' , payer : 'assistant' , cost : '80' , sale : '100' }]}), id = f . issue ( p ); f . act ( id , 'settlement' ,{ date : D , bucket : 'cost' , amount : '10' , direction : 'toAssistant' , note : '真实转账' , verified : true }, randomUUID (), owner ); const settlements = f . l . detail ( id ). settlements , info = f . l . orderCancellation ( id , assistant ); assert . equal ( info . directToday , true ); assert . equal ( info . summary . inventory [ 0 ]. mg , 1000 );
2026-10-23 11:58:19 +08:00
const q = f . actionInput ( id ), key = randomUUID (), r = f . cancel ( id , q , key ), saved = all ( f . l ); assert . deepEqual ( f . cancel ( id , q , key ), JSON . parse ( JSON . stringify ( r ))); assert . equal ( all ( f . l ), saved ); const o = f . l . detail ( id ); assert . equal ( o . status , 'cancelled' ); assert . equal ( o . netReceived , 0 ); assert . equal ( o . directCost , 0 ); assert . equal ( o . profit , 0 ); assert . equal ( o . reviewed_revision , 0 ); assert . deepEqual ( o . settlements , settlements ); assert . equal ( f . l . inventory (). find ( row => row . pocket === '现货' ). mg , 10000 );
assert . equal ( r . request . direct , true ); assert . equal ( r . request . operator_name , assistant . name ); assert . equal ( r . request . reviewer_id , null ); assert . equal ( r . request . reviewer_name , null ); assert . equal ( r . request . reviewed , null ); assert . equal ( o . cancellationApproved . direct , true ); assert . equal ( f . l . orderCancellations ({ status : 'approved' }, owner ). requests [ 0 ]. direct , true ); assert . equal ( o . audit . filter ( row => row . action === '当天直接取消订单(录错作废)' ). length , 1 ); assert . ok ( ! o . audit . some ( row => row . action === '同意取消订单(录错作废)' )); assert . throws (()=> f . cancel ( id ), error => error . status === 409 ); assert . throws (()=> f . act ( id , 'cancel' ,{ date : D , reason : '原接口仍封禁' }), error => error . status === 409 );
const own = f . issue (); assert . equal ( f . cancel ( own , f . actionInput ( own ), randomUUID (), owner ). request . operator_name , owner . name );
});
test ( '当日取消释放料池耗用但保留真实采购与交款;锁价取消仍不支持,其他owner权限不扩展' , t =>{
const f = fixture ( t ), buy = { date : D , grams : '1' , total : '80' , payer : 'owner' }; f . run ( buy ,()=> f . l . createMaterialPurchase ( buy , owner ), owner ); const p = input ({ lines : [{ name : '足金999' , unit : 'g' , quantity : '1' , pocket : '' , payer : 'owner' , sale : '100' , costParts : { material : '' , labor : '0' , accessories : '0' , other : '0' }, costMaterial : { mode : 'pool' , poolId : D }, costPayers : { material : 'owner' , labor : 'owner' }}]}), id = f . issue ( p ), purchase = f . l . rows ( 'SELECT * FROM material_purchases' ); f . cancel ( id ); assert . deepEqual ( f . l . rows ( 'SELECT * FROM material_purchases' ), purchase ); assert . equal ( f . l . materialPoolDetail ( D ). usedMg , 0 );
const lock = { date : D , customer : '合成锁价' , salesperson : '合成助理' , line : { name : '足金999' , quantity : '1' , goldPrice : '100' , laborRate : '0' , laborMode : 'gram' }, payment : { amount : '100' , account : '助理信用卡' , verified : true }, material : { rate : '80' , payer : 'owner' , verified : true }}, created = f . run ( lock ,()=> f . l . createPriceLock ( lock , assistant )); const delivery = { date : D , revision : 1 , verified : true , line : { quantity : '1' , laborRate : '0' , laborMode : 'gram' , payer : 'owner' , costParts : { labor : '0' , accessories : '0' , other : '0' }, costPayers : { material : 'owner' , labor : 'owner' }}, inventory : { pocket : '现货' , original : 'receive' }, fee_items : []}, delivered = f . run ( delivery ,()=> f . l . deliverPriceLock ( created . id , delivery , assistant )); const before = all ( f . l ); assert . throws (()=> f . cancel ( delivered . id ), /锁价/ ); assert . equal ( all ( f . l ), before );
assert . throws (()=> f . act ( delivered . id , 'correct' ,{ date : D , type : 'expense' , target : f . l . detail ( delivered . id ). expenses [ 0 ]. id , amount : '0' , verified : true , reason : 'correct不扩权' }), error => error . status === 403 ); assert . equal ( all ( f . l ), before );
});
test ( '跨午夜新动作和取消403,同操作号恢复已成功的当天动作不重记,末尾故障全回滚' , t =>{
const f = fixture ( t ), id = f . issue (), p = f . actionInput ( id ,{ amount : '1' , payer : 'assistant' , note : '午夜前费用' }), key = randomUUID (), result = f . act ( id , 'expense' , p , key ), other = f . issue (), cancelInput = f . actionInput ( other ); const audit = f . l . audit , before = all ( f . l ); f . l . audit = ()=>{ throw new Error ( '模拟最后审计失败' );}; assert . throws (()=> f . cancel ( other , cancelInput ), /审计失败/ ); assert . equal ( all ( f . l ), before ); f . l . audit = audit ;
t . mock . timers . tick ( 180000 ); assert . equal ( today (), '2026-10-23' ); const saved = all ( f . l ); assert . throws (()=> f . act ( id , 'expense' , f . actionInput ( id ,{ date : D , amount : '2' , payer : 'assistant' , note : '跨夜' })), error => error . status === 403 ); assert . throws (()=> f . cancel ( other , cancelInput ), error => error . status === 403 ); assert . equal ( all ( f . l ), saved ); assert . deepEqual ( f . act ( id , 'expense' , p , key ), JSON . parse ( JSON . stringify ( result ))); assert . equal ( all ( f . l ), saved );
});
test ( '真实HTTP同日费用与取消走直做路由并幂等,旧日403及现有审批入口保持' , async t =>{
const f = fixture ( t ), dir = fs . mkdtempSync ( path . join ( os . tmpdir (), 'weiguang-today-actions-http-' )); createUser ( f . l , '合成助理' , 'assistant' , 'isolated-actions-password' ); const app = createApp ({ mode : 'trial' , ledger : f . l , dataDir : dir , port : 0 , feishuConfig : {}}); await new Promise ( resolve => app . server . listen ( 0 , '127.0.0.1' , resolve )); t . after ( 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 ; let cookie = '' ; const call = ( url , p , key = randomUUID ())=> fetch ( base + url ,{ method : p ? 'POST' : 'GET' , headers : { Cookie : cookie ,...( p ? { 'Content-Type' : 'application/json' , Origin : base , 'X-Requested-With' : 'maimai-ledger' , 'Idempotency-Key' : key } : {})},...( p ? { body : JSON . stringify ( p )} : {})}); const login = await call ( '/api/login' ,{ name : '合成助理' , password : 'isolated-actions-password' }); cookie = login . headers . get ( 'set-cookie' ). split ( ';' )[ 0 ];
2026-10-25 14:19:24 +08:00
const liveAssistant = f . l . one ( "SELECT id,name,role FROM users WHERE role='assistant'" ), id = f . l . issueOrder ( input (), liveAssistant ). id , old = f . l . issueOrder ( input ({ date : Y }), liveAssistant ). id , p = f . actionInput ( id ,{ amount : '1' , payer : 'assistant' , note : 'HTTP费用' }), key = randomUUID (), results = await Promise . all ([ call ( '/api/orders/' + id + '/expense' , p , key ), call ( '/api/orders/' + id + '/expense' , p , key )]); assert . deepEqual ( results . map ( row => row . status ),[ 200 , 200 ]); assert . equal ( f . l . detail ( id ). expenses . length , 2 );
2026-10-23 11:58:19 +08:00
const cancel = f . actionInput ( id ), r = await call ( '/api/orders/' + id + '/canceltoday' , cancel ); assert . equal ( r . status , 200 ); assert . equal (( await r . json ()). request . direct , true ); assert . equal (( await call ( '/api/orders/' + old + '/canceltoday' , f . actionInput ( old ))). status , 403 ); assert . equal (( await call ( '/api/orders/' + old + '/expense' , f . actionInput ( old ,{ amount : '1' , payer : 'assistant' , note : '旧日' }))). status , 403 ); assert . equal (( await call ( '/api/orders/' + old + '/cancellation' ,{ revision : f . l . detail ( old ). revision , reason : '历史仍申请' })). status , 200 );
});