2026-10-23 09:49:36 +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 } = require ( '../ledger' ),{ createApp , createUser } = require ( '../server' );
const D0 = '2026-10-16' , D = '2026-10-17' , D2 = '2026-10-18' ;
const owner = { id : 'action-owner' , name : '测试麦麦' , role : 'owner' }, assistant = { id : 'action-assistant' , name : '测试助理' , role : 'assistant' };
const line = ( extra = {})=>({ name : '足金999' , unit : 'g' , quantity : '2' , pocket : '现货' , payer : 'owner' , pricingMode : 'manual' , sale : '2000' , costParts : { material : '1700' , labor : '20' , accessories : '0' , other : '0' },... extra });
const input = ( extra = {})=>({ date : D , customer : '原客户' , salesperson : '助理' , note : '原备注' , discount : '0' , rounding_mode : 'yuan' , payment_account : '助理微信' , fee_items : [{ key : 'shipping' , amount : '6' , payer : 'assistant' , note : '快递费' }], lines : [ line ()],... extra });
const all = l => l . rows ( "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name" ). map (({ name })=>[ name , l . rows ( 'SELECT * FROM "' + name + '"' )]);
const business = l => Object . fromEntries ([ 'orders' , 'payments' , 'expenses' , 'settlements' , 'journal' , 'movements' , 'corrections' , 'sync' , 'closes' , 'inventory_snapshots' , 'material_purchases' , 'material_pool_usages' , 'material_pool_events' , 'material_pool_settlements' , 'price_locks' , 'price_lock_events' , 'meta' ]. map ( table =>[ table , l . rows ( 'SELECT * FROM ' + table )]));
function fixture ( t ){
const l = new Ledger ( ':memory:' ); t . after (()=> l . close ());
const run = ( p , fn , actor = assistant , key = randomUUID ())=> l . transact ( key , actor , p , fn );
run ({ stock : true },()=> l . stock ({ kind : 'opening' , date : D0 , pocket : '现货' , grams : '20' , note : '合成库存' }, owner ), owner );
const issue = ( p = input ())=> run ( p ,()=> l . issueOrder ( p , assistant )). id ;
const request = ( id , action , data = {}, actor = assistant , key = randomUUID ())=>{ const p = { action , date : D , revision : l . detail ( id ). revision , verified : true , reason : '已核对实际经营凭据' ,... data }; return run ({ id , p },()=> l . requestOrderChange ( id , p , actor ), actor , key );};
const approve = ( r , data = {}, actor = owner , key = randomUUID ())=>{ const p = { revision : r . request . order_revision , verified : true , note : '复核原凭据后批准' ,... data }; return run ({ id : r . requestId , p },()=> l . approveOrderChange ( r . requestId , p , actor ), actor , key );};
const reject = ( r , note = '资料不符,请核实后重申' , actor = owner )=> run ({ reject : r . requestId , note },()=> l . rejectOrderChange ( r . requestId ,{ note }, actor ), actor );
const act = ( id , action , data = {}, actor = assistant )=> run ({ id , action , data },()=> l . action ( id , action ,{ date : D ,... data }, actor ), actor );
const buy = ( grams = '10' , total = '9000' , payer = 'owner' )=> run ({ grams , total , payer },()=> l . createMaterialPurchase ({ date : D , grams , total , payer , note : '合成采购' }, assistant ));
return { l , run , issue , request , approve , reject , act , buy };
}
test ( '所有已开订单费用退款退货成本直写只允许owner;输入flags无法模拟新单内部权限' , t =>{
const f = fixture ( t ), id = f . issue (), before = all ( f . l );
for ( const action of [ 'expense' , 'fees' , 'refund' , 'return' , 'cost' ]) for ( const flags of [{},{ newOrder : true , internal : true , approved : true },{ context : 'newOrderAction' , role : 'owner' , verified : true }]){
assert . throws (()=> f . act ( id , action , flags ), e => e . status === 403 && /复核申请/ . test ( e . message )); assert . deepEqual ( all ( f . l ), before );
}
assert . throws (()=> f . l . recordFees ( f . l . detail ( id ),[], D , assistant ), e => e . status === 403 ); assert . deepEqual ( all ( f . l ), before );
f . act ( id , 'expense' ,{ amount : '2' , payer : 'assistant' , note : '麦麦核实入账' }, owner ); assert . equal ( f . l . detail ( id ). directCost , 800 );
});
test ( '费用补记申请、驳回不改账;审批只追加一次真实费用,金额付款人日期和原因可复核' , t =>{
const f = fixture ( t ), id = f . issue (); f . run ({ close : D },()=> f . l . closeDay ( D , owner , 'orderDate' ), owner );
const original = business ( f . l ), data = { date : D2 , amount : '8.88' , payer : 'owner' , note : '另付证书费' , untrusted : '不会保存' }, key = randomUUID (), r = f . request ( id , 'expense' , data , assistant , key );
assert . equal ( JSON . stringify ( f . request ( id , 'expense' , data , assistant , key )), JSON . stringify ( r )); assert . deepEqual ( business ( f . l ), original );
assert . equal ( r . request . action , 'expense' ); assert . equal ( r . request . action_label , '费用补记' ); assert . equal ( r . request . action_input . amount , '8.88' ); assert . equal ( r . request . action_input . untrusted , undefined ); assert . equal ( r . request . summary . after . directCost , 1488 ); assert . equal ( r . request . summary . after . profit , 26512 ); assert . deepEqual ( r . request . summary . inventory . changes ,[]);
f . reject ( r ); assert . deepEqual ( business ( f . l ), original ); const next = f . request ( id , 'expense' , data ), approveKey = randomUUID (), accepted = f . approve ( next ,{}, owner , approveKey );
assert . equal ( JSON . stringify ( f . approve ( next ,{}, owner , approveKey )), JSON . stringify ( accepted )); assert . equal ( f . l . detail ( id ). directCost , 1488 ); assert . equal ( f . l . rows ( 'SELECT * FROM expenses WHERE order_id=?' , id ). length , 2 ); assert . equal ( f . l . report ( D2 ). expense , 888 ); assert . equal ( f . l . one ( 'SELECT stale FROM closes WHERE date=?' , D ). stale , 0 );
for ( const row of original . expenses ) assert . deepEqual ( f . l . one ( 'SELECT * FROM expenses WHERE id=?' , row . id ), row ); assert . deepEqual ( f . l . rows ( 'SELECT * FROM payments' ), original . payments ); assert . deepEqual ( f . l . rows ( 'SELECT * FROM movements' ), original . movements );
assert . throws (()=> f . approve ( next ), e => e . status === 409 );
});
test ( '退货批准后才恢复库存冲回销售成本,退款必须另申,原实际费用不撤回且原账户余额校验保留' , t =>{
const f = fixture ( t ), id = f . issue (), before = business ( f . l ), r = f . request ( id , 'return' ,{ returnPockets : [ '现货' ], reason : '实物已收回并核实' });
assert . deepEqual ( business ( f . l ), before ); assert . equal ( r . request . after . status , 'returned' ); assert . equal ( r . request . after . netReceived , 200000 ); assert . equal ( r . request . after . directCost , 600 ); assert . equal ( r . request . summary . after . profit , - 600 ); assert . deepEqual ( r . request . summary . inventory . changes ,[{ date : D , pocket : '现货' , mg : 2000 }]);
assert . throws (()=> f . request ( id , 'refund' ,{ amount : '2000' , account : '助理微信' }), e => e . status === 409 ); f . approve ( r ); assert . equal ( f . l . inventory (). find ( row => row . pocket === '现货' ). mg , 20000 ); assert . equal ( f . l . detail ( id ). netReceived , 200000 ); assert . equal ( f . l . detail ( id ). status , 'returned' );
const returned = business ( f . l ); assert . throws (()=> f . request ( id , 'refund' ,{ amount : '2000' , account : '助理支付宝' }), /原收款账户/ ); assert . deepEqual ( business ( f . l ), returned );
const refund = f . request ( id , 'refund' ,{ amount : '1500' , account : '助理微信' , reference : '实际退款原凭据' }); assert . deepEqual ( business ( f . l ), returned ); assert . equal ( refund . request . after . netReceived , 50000 ); assert . deepEqual ( refund . request . summary . inventory . changes ,[]);
f . reject ( refund ); assert . deepEqual ( business ( f . l ), returned ); f . approve ( f . request ( id , 'refund' ,{ amount : '2000' , account : '助理微信' , reference : '实际退款原凭据' })); assert . equal ( f . l . detail ( id ). netReceived , 0 ); assert . equal ( f . l . detail ( id ). profit , - 600 );
assert . equal ( f . l . orderChange ( id , assistant ). actions . refund . eligible , false ); assert . equal ( f . l . rows ( "SELECT * FROM journal WHERE kind='整单退货' AND order_id=?" , id ). length , 1 ); assert . equal ( f . l . rows ( "SELECT * FROM payments WHERE kind='refund' AND order_id=?" , id ). length , 1 );
});
test ( '日购料退货审批展示FIFO关联影响,申请及驳回不释放,批准保留采购和实际交款' , t =>{
const f = fixture ( t ); f . buy ( '4' , '3600' , 'owner' ); f . buy ( '6' , '5400' , 'assistant' );
const pooled = quantity => line ({ quantity , pocket : '' , costMaterial : { mode : 'pool' , poolId : D }, costParts : { material : '' , labor : '10' , accessories : '0' , other : '0' }});
const id = f . issue ( input ({ fee_items : [], lines : [ pooled ( '4' )]})), other = f . issue ( input ({ fee_items : [], lines : [ pooled ( '3' )]})), before = business ( f . l ), r = f . request ( id , 'return' ,{ returnPockets : [ '现货' ]});
assert . deepEqual ( business ( f . l ), before ); assert . ok ( r . request . relatedOrders . some ( row => row . id === other )); assert . equal ( f . l . materialPoolDetail ( D ). usedMg , 7000 );
f . approve ( r ); assert . equal ( f . l . materialPoolDetail ( D ). usedMg , 3000 ); assert . equal ( f . l . detail ( other ). settlementDue , r . request . relatedOrders . find ( row => row . id === other ). after . settlementDue );
for ( const table of [ 'material_purchases' , 'material_pool_settlements' , 'settlements' , 'payments' , 'expenses' ]) assert . deepEqual ( f . l . rows ( 'SELECT * FROM ' + table ), before [ table ]); assert . equal ( f . l . detail ( id ). status , 'returned' );
});
test ( '旧confirmed补成本和核实费用均先批,confirm及complete不能隐式补记,费用批准后助理正常交付' , t =>{
const f = fixture ( t ), p = input ({ lines : [ line ({ costParts : { material : '' , labor : '' , accessories : '' , other : '' }})], fee_items : [{ key : 'shipping' , amount : '6' , payer : 'assistant' , note : '快递费' , status : 'estimated' }]}), id = f . l . saveOrder ( p , assistant ). id ;
const draft = all ( f . l ); assert . throws (()=> f . act ( id , 'confirm' ,{ feesVerified : true }), e => e . status === 403 ); assert . deepEqual ( all ( f . l ), draft ); f . act ( id , 'confirm' );
f . act ( id , 'receipt' ,{ amount : '2000' , account : '助理微信' , verified : true }); const before = all ( f . l ); assert . throws (()=> f . act ( id , 'complete' ,{ verified : true }), e => e . status === 403 && /旧费用核实申请/ . test ( e . message )); assert . deepEqual ( all ( f . l ), before );
const cost = f . request ( id , 'cost' ,{ costs : [{ parts : { material : '1700' , labor : '20' , accessories : '0' , other : '0' }}]}); assert . equal ( cost . request . after . goodsCost , 172000 ); assert . equal ( f . l . detail ( id ). goodsCost , null ); f . approve ( cost ); assert . equal ( f . l . detail ( id ). goodsCost , 172000 );
const fee = f . request ( id , 'fees' ,{ fee_items : [{ key : 'shipping' , amount : '8' , payer : 'owner' , note : '快递费' }]}); assert . equal ( fee . request . action_label , '旧费用核实' ); assert . equal ( fee . request . after . directCost , 800 ); assert . equal ( f . l . detail ( id ). expenses . length , 0 ); f . approve ( fee );
assert . equal ( f . l . detail ( id ). pendingFees . length , 0 ); assert . equal ( f . l . detail ( id ). expenses . length , 1 ); f . act ( id , 'complete' ,{ verified : true }); assert . equal ( f . l . detail ( id ). status , 'delivered' ); assert . equal ( f . l . detail ( id ). directCost , 800 ); assert . equal ( f . l . detail ( id ). profit , 27200 );
const status = f . l . orderChange ( id , assistant ); assert . equal ( status . actions . cost . eligible , false ); assert . equal ( status . actions . fees . eligible , false ); assert . equal ( status . actions . return . eligible , true );
});
function lockOrder ( f , quantity = '1' , fees = []){
const lock = f . l . createPriceLock ({ date : D , customer : '锁价客户' , salesperson : '合成开单人' , line : { name : '足金999' , quantity : '1' , goldPrice : '1000' , laborRate : '0' , laborMode : 'gram' }, payment : { amount : '1000' , account : '助理微信' , verified : true }, material : { rate : '900' , payer : 'assistant' , verified : true }}, assistant );
const p = { date : D2 , revision : 1 , verified : true , line : { quantity , laborRate : '0' , laborMode : 'gram' , payer : 'owner' , costParts : { labor : '0' , accessories : '0' , other : '0' }}, inventory : { pocket : '现货' , original : 'receive' }, fee_items : fees };
if ( quantity === '0.9' ) p . settlement = { amount : '100' , account : '助理微信' , verified : true };
return f . l . deliverPriceLock ( lock . id , p , assistant ). id ;
}
test ( '首次普通及锁价交付仍自动记费用/补退款;已交付锁价退货退款直写被挡且复用统一审批' , t =>{
const f = fixture ( t ), normal = f . issue (); assert . equal ( f . l . detail ( normal ). expenses . length , 1 );
const id = lockOrder ( f , '0.9' ,[{ key : 'shipping' , amount : '6' , payer : 'assistant' , note : '快递费' }]), lock = f . l . detail ( id ), events = f . l . rows ( 'SELECT * FROM price_lock_events' );
assert . equal ( lock . status , 'delivered' ); assert . equal ( lock . netReceived , 90000 ); assert . equal ( lock . refunded , 10000 ); assert . equal ( lock . directCost , 600 ); assert . ok ( events . some ( row => row . kind === 'refund' && row . amount === 10000 ));
const before = all ( f . l ); assert . throws (()=> f . act ( id , 'return' ,{ date : D2 , verified : true , reason : '退货' }), e => e . status === 403 ); assert . throws (()=> f . act ( id , 'refund' ,{ date : D2 , amount : '900' , account : '助理微信' , verified : true }), e => e . status === 403 ); assert . deepEqual ( all ( f . l ), before );
f . approve ( f . request ( id , 'return' ,{ date : D2 , returnPockets : [ '现货' ]})); const returned = business ( f . l ), refund = f . request ( id , 'refund' ,{ date : D2 , amount : '900' , account : '助理微信' , reference : '实际退款' }); assert . deepEqual ( business ( f . l ), returned ); f . approve ( refund );
assert . equal ( f . l . detail ( id ). netReceived , 0 ); assert . deepEqual ( f . l . rows ( 'SELECT * FROM price_lock_events' ), events ); assert . equal ( f . l . rows ( 'SELECT * FROM payments WHERE order_id=?' , id ). length , 1 );
});
test ( '动作申请冻结其它入口且与取消互斥,凭据变动过期;批准后置故障与效果不符全部撤回' , t =>{
const f = fixture ( t ), id = f . issue (), r = f . request ( id , 'expense' ,{ amount : '2' , payer : 'assistant' , note : '盒子' }), before = all ( f . l );
for ( const actor of [ assistant , owner ]){
for ( const action of [ 'expense' , 'refund' , 'return' , 'cost' , 'fees' , 'receipt' , 'settlement' ]) assert . throws (()=> f . act ( id , action ,{}, actor ), e => e . status === 409 && /待审批/ . test ( e . message ));
assert . throws (()=> f . approve ( r ,{}, assistant ), e => e . status === 403 ); assert . throws (()=> f . reject ( r , '越权' , assistant ), e => e . status === 403 );
}
assert . throws (()=> f . l . requestOrderCancellation ( id ,{ revision : f . l . detail ( id ). revision , reason : '另一个申请' }, assistant ), e => e . status === 409 ); assert . deepEqual ( all ( f . l ), before );
f . l . run ( 'UPDATE payments SET account=? WHERE order_id=?' , '麦麦现金' , id ); const stale = all ( f . l ); assert . equal ( f . l . orderChangeRequest ( r . requestId , owner ). stale , true ); assert . throws (()=> f . approve ( r ), e => e . status === 409 ); assert . deepEqual ( all ( f . l ), stale ); f . reject ( r );
const next = f . request ( id , 'return' ,{ returnPockets : [ '现货' ]}), pending = all ( 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 . approve ( next ), /最后一步失败/ ); assert . deepEqual ( all ( f . l ), pending ); f . l . audit = audit ; f . approve ( next ); assert . equal ( f . l . detail ( id ). status , 'returned' );
});
test ( '旧审批表自动增加action默认edit,既有申请可继续批准且业务原记录不改写' , t =>{
const dir = fs . mkdtempSync ( path . join ( os . tmpdir (), 'maimai-action-upgrade-' )), filename = path . join ( dir , 'ledger.sqlite' ); t . after (()=> fs . rmSync ( dir ,{ recursive : true , force : true }));
const l = new Ledger ( filename ), id = l . issueOrder ( input ({ lines : [ line ({ pocket : '' })]}), assistant ). id , p = {... l . orderEdit ( id , assistant ). inputs , revision : l . detail ( id ). revision , reason : '旧版本申请' , verified : true , customer : '旧申请新客户' }, request = l . requestOrderChange ( id , p , assistant );
l . db . exec ( 'ALTER TABLE order_changes DROP COLUMN action' ); const before = business ( l ); l . close (); const reopened = new Ledger ( filename ); t . after (()=> reopened . close ());
assert . deepEqual ( business ( reopened ), before ); assert . equal ( reopened . orderChangeRequest ( request . requestId , owner ). action , 'edit' ); reopened . approveOrderChange ( request . requestId ,{ revision : p . revision , verified : true }, owner ); assert . equal ( reopened . detail ( id ). customer , '旧申请新客户' );
});
test ( '动作HTTP申请与审批登录CSRF权限幂等和版本保护,全局混合动作保留原单与历史' , async t =>{
const dir = fs . mkdtempSync ( path . join ( os . tmpdir (), 'maimai-action-http-' )), l = new Ledger ( path . join ( dir , 'ledger.sqlite' )); createUser ( l , '麦麦' , 'owner' , 'synthetic-owner-password' ); createUser ( l , '助理' , 'assistant' , 'synthetic-assistant-password' );
const app = createApp ({ mode : 'trial' , port : 0 , dataDir : dir , ledger : l , 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 )); l . close (); fs . rmSync ( dir ,{ recursive : true , force : true });});
const base = 'http://127.0.0.1:' + app . server . address (). port , cookies = {};
const call = ( who , route , body , key = randomUUID (), extra = {})=> fetch ( base + route ,{ method : body === undefined ? 'GET' : 'POST' , headers : {...( cookies [ who ] ? { Cookie : cookies [ who ]} : {}),...( body === undefined ? {} : { 'Content-Type' : 'application/json' , 'X-Requested-With' : 'maimai-ledger' , Origin : base , 'Idempotency-Key' : key }),... extra },...( body === undefined ? {} : { body : JSON . stringify ( body )})});
for ( const [ who , name ] of [[ 'owner' , '麦麦' ],[ 'assistant' , '助理' ]]){ const r = await call ( who , '/api/login' ,{ name , password : who === 'owner' ? 'synthetic-owner-password' : 'synthetic-assistant-password' }); cookies [ who ] = r . headers . get ( 'set-cookie' ). split ( ';' )[ 0 ];}
2026-10-25 14:19:24 +08:00
const id = l . issueOrder ( input ({ lines : [ line ({ pocket : '' })]}), l . one ( "SELECT id,name,role FROM users WHERE role='assistant'" )). id , route = '/api/orders/' + id , p = { action : 'expense' , date : D , revision : l . detail ( id ). revision , reason : '真实包装支出' , verified : true , amount : '3.21' , payer : 'assistant' , note : '包装盒' };
2026-10-23 09:49:36 +08:00
assert . equal (( await call ( 'assistant' , route + '/expense' , p )). status , 403 ); assert . equal (( await call ( 'none' , route + '/change' , p )). status , 401 ); assert . equal (( await call ( 'assistant' , route + '/change' , p , undefined ,{ Origin : 'https://evil.example' })). status , 403 );
const key = randomUUID (), rs = await Promise . all ([ call ( 'assistant' , route + '/change' , p , key ), call ( 'assistant' , route + '/change' , p , key )]); assert . deepEqual ( rs . map ( r => r . status ),[ 200 , 200 ]); const [ r , retry ] = await Promise . all ( rs . map ( r => r . json ())); assert . equal ( r . requestId , retry . requestId ); assert . equal ( r . request . action , 'expense' ); assert . equal ( l . detail ( id ). directCost , 600 );
const requestPath = '/api/order-changes/' + r . requestId , decision = { revision : p . revision , verified : true }; assert . equal (( await call ( 'assistant' , requestPath + '/approve' , decision )). status , 403 ); assert . equal (( await call ( 'owner' , requestPath + '/approve' ,{... decision , revision : 0 })). status , 409 );
assert . equal (( await ( await call ( 'owner' , '/api/order-changes' )). json ()). requests [ 0 ]. action_label , '费用补记' ); assert . equal (( await ( await call ( 'assistant' , route + '/change' )). json ()). actions . return . eligible , false );
const approveKey = randomUUID (), approved = await Promise . all ([ call ( 'owner' , requestPath + '/approve' , decision , approveKey ), call ( 'owner' , requestPath + '/approve' , decision , approveKey )]); assert . deepEqual ( approved . map ( r => r . status ),[ 200 , 200 ]); assert . equal ( l . detail ( id ). directCost , 921 ); assert . equal ( l . rows ( 'SELECT * FROM orders' ). length , 1 ); assert . equal ( l . rows ( "SELECT * FROM audit WHERE action='同意修改订单'" ). length , 1 );
});