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 : 'change-owner' , name : '测试麦麦' , role : 'owner' }, assistant = { id : 'change-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 });
2026-11-30 15:40:40 +08:00
const input = ( extra = {})=>({ date : D , customer : '原客户' , internal_note : '测试内部备注' , salesperson : '助理' , note : '原备注' , discount : '0' , rounding_mode : 'yuan' , payment_account : '助理微信' , fee_items : [{ key : 'shipping' , amount : '6' , payer : 'assistant' , note : '快递费' }], lines : [ line ()],... extra });
2026-10-23 09:49:36 +08:00
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 );
for ( const pocket of [ '现货' , '金料' ]) run ({ pocket },()=> l . stock ({ kind : 'opening' , date : D0 , pocket , grams : '20' , note : '合成库存' }, owner ), owner );
const issue = ( p = input ())=> run ( p ,()=> l . issueOrder ( p , assistant )). id ;
const payload = ( id , extra = {})=>({... l . orderEdit ( id , assistant ). inputs , revision : l . detail ( id ). revision , reason : '原凭据核实后修改' , verified : true ,... extra });
const request = ( id , p = payload ( id ), actor = assistant , key = randomUUID ())=> run ({ id , p },()=> l . requestOrderChange ( id , p , actor ), actor , key );
const approve = ( r , p = {}, actor = owner , key = randomUUID ())=> run ({ approve : r . requestId , p },()=> l . approveOrderChange ( r . requestId ,{ revision : r . request . order_revision , verified : true ,... 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 , kind , p = {}, actor = assistant )=> run ({ id , kind , p },()=> l . action ( id , kind ,{ date : D ,... p }, actor ), actor );
const buy = ( date = D , grams = '10' , total = '9000' , payer = 'owner' )=> run ({ date , grams , total , payer },()=> l . createMaterialPurchase ({ date , grams , total , payer , note : '合成采购' }, assistant ));
return { l , run , issue , payload , request , approve , reject , act , buy };
}
test ( '助理直接修改包括metadata被拒;申请和驳回完全不改业务、快照和版本,保存服务器前后试算' , t =>{
const f = fixture ( t ), id = f . issue (); f . run ({ close : D },()=> f . l . closeDay ( D , owner , 'orderDate' ), owner );
const p = f . payload ( id ,{ customer : '新客户' }); p . lines [ 0 ]. quantity = '3' ; p . lines [ 0 ]. sale = '3000' ; p . lines [ 0 ]. baseSale = '3000' ; p . lines [ 0 ]. costParts . material = '2600' ; p . fee_items [ 0 ]. amount = '8' ;
const before = business ( f . l ), state = all ( f . l );
assert . equal ( f . l . orderEdit ( id , assistant ). requiresApproval , true ); assert . equal ( f . l . orderEdit ( id , owner ). requiresApproval , false );
for ( const extra of [{},{ approval : true },{ role : 'owner' },{ approved : true , verified : true }]){ assert . throws (()=> f . l . editOrder ( id ,{... p ,... extra }, assistant ), e => e . status === 403 ); assert . deepEqual ( all ( f . l ), state );}
const key = randomUUID (), r = f . request ( id , p , assistant , key ); assert . equal ( JSON . stringify ( f . request ( id , p , assistant , key )), JSON . stringify ( r )); assert . deepEqual ( business ( f . l ), before );
assert . equal ( r . request . before . total , 200000 ); assert . equal ( r . request . after . total , 300000 ); assert . equal ( r . request . after . netReceived , 300000 ); assert . equal ( r . request . after . goodsCost , 262000 ); assert . equal ( r . request . after . directCost , 800 ); assert . equal ( r . request . summary . after . profit , 37200 );
assert . equal ( r . request . before . revision , p . revision ); assert . equal ( f . l . detail ( id ). revision , p . revision ); assert . equal ( f . l . detail ( id ). changePending . id , r . requestId );
assert . ok ( r . request . changes . some ( row => row . field === 'customer' )); assert . equal ( r . request . stale , false ); assert . equal ( f . l . orderChanges ({}, owner ). counts . pending , 1 ); assert . equal ( f . l . orderChange ( id , owner ). eligible , false );
assert . throws (()=> f . approve ( r ,{}, assistant ), e => e . status === 403 ); assert . throws (()=> f . reject ( r , '不允许助理审批' , assistant ), e => e . status === 403 ); assert . deepEqual ( business ( f . l ), before );
f . reject ( r ); assert . deepEqual ( business ( f . l ), before ); assert . equal ( f . l . orderChange ( id , assistant ). pending , null ); assert . equal ( f . l . orderChanges ({ status : 'all' }, owner ). counts . rejected , 1 );
assert . notEqual ( f . request ( id , p ). requestId , r . requestId );
});
test ( '批准只更正同一张单一次,保留原流水与双方实际交款,冲回重记金额库存利润一致' , t =>{
const f = fixture ( t ), id = f . issue (); f . act ( id , 'settlement' ,{ amount : '1000' , bucket : 'cost' , direction : 'toOwner' , verified : true , note : '原实际交款' });
2026-11-30 15:40:40 +08:00
const original = f . l . detail ( id ), before = business ( f . l ), p = f . payload ( id ,{ date : D2 , customer : '修改客户' , internal_note : '测试内部备注' , salesperson : '麦麦' , note : '新备注' , payment_account : '麦麦支付宝' , discount : '1.23' , rounding_mode : 'cent' });
2026-10-23 09:49:36 +08:00
p . lines = [ line ({ quantity : '3.001' , pocket : '金料' , sale : '3100.67' , payer : 'assistant' , costPayers : { material : 'assistant' , labor : 'owner' }, costParts : { material : '2600.01' , labor : '30.02' , accessories : '4.03' , other : '5.04' }})]; p . fee_items [ 0 ]. amount = '8.88' ; p . fee_items [ 0 ]. payer = 'owner' ;
const r = f . request ( id , p ), key = randomUUID (), approved = f . approve ( r ,{ note : '已对原凭据' }, owner , key ); assert . equal ( JSON . stringify ( f . approve ( r ,{ note : '已对原凭据' }, owner , key )), JSON . stringify ( approved ));
const order = f . l . detail ( id ); assert . equal ( order . id , id ); assert . equal ( f . l . rows ( 'SELECT * FROM orders' ). length , 1 ); for ( const field of [ 'id' , 'number' , 'paper_number' , 'created' ]) assert . equal ( order [ field ], original [ field ]);
assert . equal ( order . customer , p . customer ); assert . equal ( order . total , 309944 ); assert . equal ( order . netReceived , 309944 ); assert . equal ( order . goodsCost , 263910 ); assert . equal ( order . directCost , 888 ); assert . equal ( order . profit , 45146 ); assert . equal ( order . revision , p . revision + 1 ); assert . equal ( order . changePending , null ); assert . equal ( order . changeApproved . id , r . requestId );
assert . deepEqual ( f . l . rows ( 'SELECT * FROM settlements' ), before . settlements );
for ( const table of [ 'payments' , 'expenses' , 'movements' , 'journal' ]) for ( const row of before [ table ]) assert . deepEqual ( f . l . one ( 'SELECT * FROM ' + table + ' WHERE id=?' , row . id ), row );
assert . equal ( f . l . inventory (). find ( row => row . pocket === '现货' ). mg , 20000 ); assert . equal ( f . l . inventory (). find ( row => row . pocket === '金料' ). mg , 16999 );
assert . equal ( f . l . report ( D ). sales , 0 ); assert . equal ( f . l . report ( D2 ). sales , 309944 ); assert . equal ( f . l . reportByOrderDate ( D2 ). orderRows [ 0 ]. profit , 45146 );
assert . equal ( order . audit . filter ( row => row . action === '同意修改订单' ). length , 1 ); assert . ok ( order . audit . some ( row => row . action === '整单账务修改' && row . actor === owner . name ));
assert . throws (()=> f . approve ( r ), e => e . status === 409 ); assert . throws (()=> f . reject ( r ), e => e . status === 409 );
});
test ( '修改与取消互斥;pending期间owner及assistant全部metadata和账务入口冻结' , t =>{
const f = fixture ( t ), id = f . issue (), p = f . payload ( id ), r = f . request ( id , p ), before = all ( f . l );
for ( const actor of [ owner , assistant ]){
for ( const [ kind , body ] of [[ 'cost' ,{}],[ 'fees' ,{}],[ 'expense' ,{}],[ 'receipt' ,{}],[ 'refund' ,{}],[ 'return' ,{}],[ 'material' ,{}],[ 'complete' ,{}],[ 'deliver' ,{}],[ 'settlement' ,{}],[ 'correct' ,{ type : 'payment' }],[ 'review' ,{ revision : p . revision }]]){
assert . throws (()=> f . act ( id , kind , body , actor ), e => e . status === 409 && /待审批/ . test ( e . message )); assert . deepEqual ( all ( f . l ), before );
}
assert . throws (()=> f . l . editOrder ( id ,{... p , customer : '不能先改' }, actor ), e =>[ 403 , 409 ]. includes ( e . status ));
assert . throws (()=> f . l . requestOrderCancellation ( id ,{ revision : p . revision , reason : '另一个申请' }, actor ), e => e . status === 409 && /修改申请/ . test ( e . message ));
}
assert . equal ( f . l . orderCancellation ( id , assistant ). eligible , false ); assert . equal ( f . l . orderEdit ( id , owner ). eligible , false ); assert . throws (()=> f . request ( id ), e => e . status === 409 );
f . reject ( r ); const cancellation = f . l . requestOrderCancellation ( id ,{ revision : f . l . detail ( id ). revision , reason : '录错' }, assistant ), state = all ( f . l );
assert . throws (()=> f . request ( id ), e => e . status === 409 && /取消申请/ . test ( e . message )); assert . throws (()=> f . l . editOrder ( id , p , owner ), e => e . status === 409 && /待审批/ . test ( e . message )); assert . deepEqual ( all ( f . l ), state );
f . l . rejectOrderCancellation ( cancellation . requestId ,{ note : '继续修改' }, owner ); assert . equal ( f . request ( id ). request . stale , false );
});
test ( '直接流水变化或相关料池采购/FIFO变化使审批过期,无关单和无关库存不使原提议过期' , t =>{
const f = fixture ( t ), id = f . issue (), r = f . request ( id , f . payload ( id ,{ customer : '已审核内容' }));
f . issue ( input ({ customer : '另一个无关单' , lines : [ line ({ pocket : '金料' })]}));
f . run ({ stock : true },()=> f . l . stock ({ kind : 'increase' , date : D0 , pocket : '现货' , grams : '10' , note : '独立库存' }, owner ), owner );
assert . equal ( f . l . orderChangeRequest ( r . requestId , owner ). stale , false ); f . approve ( r );
const second = f . request ( id ); f . l . run ( 'UPDATE payments SET account=? WHERE order_id=?' , '麦麦现金' , id ); const before = all ( f . l );
assert . equal ( f . l . orderChangeRequest ( second . requestId , owner ). stale , true ); assert . throws (()=> f . approve ( second ), e => e . status === 409 && /已过期/ . test ( e . message )); assert . deepEqual ( all ( f . l ), before ); f . reject ( second );
f . buy (); const pooled = f . issue ( input ({ fee_items : [], lines : [ line ({ pocket : '' , costMaterial : { mode : 'pool' , poolId : D }})]})), request = f . request ( pooled , f . payload ( pooled ,{ customer : '池订单' }));
f . buy ( D , '1' , '1000' , 'assistant' ); assert . equal ( f . l . orderChangeRequest ( request . requestId , owner ). stale , true ); assert . throws (()=> f . approve ( request ), e => e . status === 409 && /已过期/ . test ( e . message )); f . reject ( request );
});
test ( '全量试算及批准包含关联FIFO影响,原采购真实交款保留,新增消耗身份不因预览随机值误报过期' , t =>{
const f = fixture ( t ); f . buy ( D , '4' , '3600' , 'owner' ); f . buy ( D , '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' )]}));
const p = f . payload ( id ); p . lines = [ pooled ( '2' ), pooled ( '1' )]; const before = business ( f . l ), r = f . request ( id , p );
assert . deepEqual ( business ( f . l ), before ); assert . ok ( r . request . relatedOrders . some ( row => row . id === other )); assert . equal ( r . request . after . goodsCost , 272000 );
f . approve ( r ); assert . equal ( f . l . detail ( id ). goodsCost , r . request . after . goodsCost ); assert . equal ( f . l . detail ( other ). settlementDue , r . request . relatedOrders . find ( row => row . id === other ). after . settlementDue );
assert . deepEqual ( f . l . rows ( 'SELECT * FROM material_purchases' ), before . material_purchases ); assert . deepEqual ( f . l . rows ( 'SELECT * FROM material_pool_settlements' ), before . material_pool_settlements );
assert . equal ( f . l . rows ( 'SELECT * FROM material_pool_usages WHERE order_id=?' , id ). length , 2 ); assert . equal ( f . l . detail ( id ). netReceived , f . l . detail ( id ). total );
});
test ( '新增商品、无id附加项目、证书销售与实际费用,换料池审批结果不受新流水随机ID影响' , t =>{
const f = fixture ( t ); f . buy ( D , '10' , '9000' , 'owner' ); f . buy ( D2 , '10' , '9500' , 'assistant' );
const id = f . issue ( input ({ date : D2 , lines : [ line ({ pocket : '' , costMaterial : { mode : 'pool' , poolId : D }})]})), charge = randomUUID (), p = f . payload ( id );
p . lines = [ line ({ pocket : '' , quantity : '1.001' , costMaterial : { mode : 'pool' , poolId : D2 }, charges : [{ id : charge , name : '证书' , amount : '10' },{ name : '额外包装' , amount : '1' }]}),
{ name : '纯银925' , unit : '件' , quantity : '1' , pocket : '' , payer : 'assistant' , sale : '99' , costParts : { material : '50' , labor : '0' , accessories : '0' , other : '0' }}];
p . fee_items . push ({ key : 'charge:' + charge , note : '证书' , amount : '8' , payer : 'owner' , date : D2 }); p . fee_items . push ({ key : 'manual:' + randomUUID (), note : '新增真实包装' , amount : '2' , payer : 'assistant' , date : D });
const before = business ( f . l ), r = f . request ( id , p ); assert . deepEqual ( business ( f . l ), before ); assert . equal ( r . request . after . lines . length , 2 ); assert . equal ( r . request . after . directCost , 1600 );
f . approve ( r ); assert . equal ( f . l . detail ( id ). total , r . request . after . total ); assert . equal ( f . l . detail ( id ). goodsCost , r . request . after . goodsCost ); assert . equal ( f . l . detail ( id ). directCost , 1600 );
assert . equal ( f . l . detail ( id ). lines [ 0 ]. costMaterial . poolId , D2 ); assert . deepEqual ( f . l . rows ( 'SELECT * FROM material_purchases' ), before . material_purchases );
});
test ( 'metadata在锁价、已退货、审批作废、草稿及旧confirmed单也必须申请,批准不改财务和状态' , t =>{
const f = fixture ( t ), returned = f . issue (); f . act ( returned , 'return' ,{ reason : '真实退货' , verified : true }, owner );
const cancelled = f . issue (), cancellation = f . l . requestOrderCancellation ( cancelled ,{ revision : f . l . detail ( cancelled ). revision , reason : '录错作废' }, assistant ); f . l . approveOrderCancellation ( cancellation . requestId ,{ revision : cancellation . request . order_revision , verified : true }, owner );
const draft = f . l . saveOrder ( input (), assistant ). id , confirmed = f . l . saveOrder ( input (), assistant ). id ; f . act ( confirmed , 'confirm' ,{ feesVerified : true }, owner );
2026-11-30 15:40:40 +08:00
const lockInput = { date : D , customer : '锁价客户' , internal_note : '测试内部备注' , 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 }};
2026-10-23 09:49:36 +08:00
const lock = f . l . createPriceLock ( lockInput , assistant ), locked = f . l . deliverPriceLock ( lock . id ,{ date : D2 , revision : 1 , verified : true , line : { quantity : '1' , laborRate : '0' , laborMode : 'gram' , payer : 'owner' , costParts : { labor : '0' , accessories : '0' , other : '0' }}, inventory : { pocket : '现货' , original : 'receive' }, fee_items : []}, assistant ). id ;
for ( const id of [ returned , cancelled , draft , confirmed , locked ]){
2026-11-30 15:40:40 +08:00
const original = f . l . detail ( id ), before = business ( f . l ), p = f . payload ( id ,{ customer : '核对后的客户' , internal_note : '测试内部备注' , salesperson : '麦麦' , note : '资料备注' });
2026-11-04 22:18:56 +08:00
assert . equal ( f . l . orderEdit ( id , assistant ). financialEditable , id === locked ); assert . throws (()=> f . l . editOrder ( id , p , assistant ), e => e . status === 403 );
2026-10-23 09:49:36 +08:00
const r = f . request ( id , p ); assert . deepEqual ( business ( f . l ), before ); f . approve ( r ); const after = f . l . detail ( id );
assert . equal ( after . customer , '核对后的客户' ); assert . equal ( after . status , original . status ); for ( const field of [ 'total' , 'netReceived' , 'goodsCost' , 'directCost' , 'profit' ]) assert . equal ( after [ field ], original [ field ]);
for ( const table of [ 'payments' , 'expenses' , 'settlements' , 'journal' , 'movements' , 'material_purchases' , 'price_lock_events' ]) assert . deepEqual ( f . l . rows ( 'SELECT * FROM ' + table ), before [ table ]);
f . l . editOrder ( id , f . payload ( id ,{ customer : '麦麦直接资料更正' }), owner ); assert . equal ( f . l . detail ( id ). customer , '麦麦直接资料更正' );
}
});
test ( '旧save/issue/cost/fees/material不能绕过;旧confirmed成本与费用先批,之后继续履约' , t =>{
const f = fixture ( t ), p = input (), draft = f . l . saveOrder ( p , assistant ). id , revision = f . l . detail ( draft ). revision , before = all ( f . l );
for ( const action of [()=> f . l . saveOrder ({... p , id : draft , revision }, assistant ),()=> f . l . issueOrder ({... p , id : draft , revision }, assistant )]){ assert . throws ( action , e => e . status === 403 ); assert . deepEqual ( all ( f . l ), before );}
f . run ({ ownerSave : true },()=> f . l . saveOrder ({... p , id : draft , revision , customer : '麦麦调整草稿' }, owner ), owner ); assert . equal ( f . l . detail ( draft ). customer , '麦麦调整草稿' );
const blank = input ({ lines : [ line ({ costParts : { material : '' , labor : '' , accessories : '' , other : '' }})], fee_items : [{ key : 'shipping' , amount : '' , payer : 'assistant' , note : '快递费' , status : 'estimated' }]}), id = f . l . saveOrder ( blank , assistant ). id ; f . act ( id , 'confirm' );
const costs = { action : 'cost' , costs : [{ parts : { material : '1700' , labor : '20' , accessories : '0' , other : '0' }}]}; assert . throws (()=> f . act ( id , 'cost' , costs ), e => e . status === 403 );
f . approve ( f . request ( id ,{ revision : f . l . detail ( id ). revision , verified : true , reason : '成本凭据核实' , date : D ,... costs }));
const costState = all ( f . l ); assert . throws (()=> f . act ( id , 'cost' ,{ costs : [{ parts : { material : '1701' , labor : '20' , accessories : '0' , other : '0' }}]}), e => e . status === 403 ); assert . deepEqual ( all ( f . l ), costState );
f . approve ( f . request ( id ,{ action : 'fees' , date : D , revision : f . l . detail ( id ). revision , verified : true , reason : '费用凭据核实' , fee_items : [{ key : 'shipping' , amount : '6' , payer : 'assistant' , note : '快递费' }]}));
f . act ( id , 'receipt' ,{ amount : '2000' , account : '助理微信' , verified : true }); f . act ( id , 'complete' ,{ verified : true }); assert . equal ( f . l . detail ( id ). status , 'delivered' );
const completed = all ( f . l ); assert . throws (()=> f . act ( id , 'cost' ,{ costs : [ '1' ]})); assert . throws (()=> f . act ( id , 'material' ,{ revision : f . l . detail ( id ). revision , pools : [ null ]}), e => e . status === 403 ); assert . throws (()=> f . act ( id , 'correct' ,{ type : 'payment' }), e => e . status === 403 ); assert . deepEqual ( all ( f . l ), completed );
for ( const data of [{ action : 'expense' , amount : '2' , payer : 'assistant' , note : '新增真实支出' },{ action : 'return' },{ action : 'refund' , amount : '2000' , account : '助理微信' }]) f . approve ( f . request ( id ,{ date : D , revision : f . l . detail ( id ). revision , verified : true , reason : '真实经营凭据核实' ,... data })); assert . equal ( f . l . detail ( id ). netReceived , 0 );
});
test ( '版本确认和输入失败无副作用,批准库存不足或末尾故障全量回滚,tampered提议不被静默批准' , t =>{
const f = fixture ( t ), id = f . issue (), p = f . payload ( id ), before = all ( f . l );
for ( const extra of [{ revision : 0 },{ revision : String ( p . revision )},{ reason : '' },{ verified : false },{ lines : [ line ({ quantity : '-1' })]}]){ assert . throws (()=> f . request ( id ,{... p ,... extra })); assert . deepEqual ( all ( f . l ), before );}
p . lines [ 0 ]. quantity = '15' ; const r = f . request ( id , p ); f . issue ( input ({ lines : [ line ({ quantity : '10' })], fee_items : []})); assert . equal ( f . l . orderChangeRequest ( r . requestId , owner ). stale , false );
const pendingState = all ( f . l ); assert . throws (()=> f . approve ( r ), /库存不足/ ); assert . deepEqual ( all ( f . l ), pendingState ); f . reject ( r );
const next = f . request ( id , f . payload ( id ,{ customer : '审批后才生效' })), state = 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 ), state ); assert . throws (()=> f . l . approveOrderChange ( next . requestId ,{ revision : next . request . order_revision , verified : true }, owner ), /模拟审批末尾/ ); assert . deepEqual ( all ( f . l ), state ); f . l . audit = audit ;
f . l . run ( 'UPDATE order_changes SET effect_hash=? WHERE id=?' , 'tampered' , next . requestId ); const corrupt = all ( f . l ); assert . throws (()=> f . approve ( next ), /试算结果/ ); assert . deepEqual ( all ( f . l ), corrupt );
});
test ( 'HTTP登录CSRF权限、全局待审和版本受保护,同操作号并发只审批一次,隔离临时库重开保留审批' , async t =>{
const dir = fs . mkdtempSync ( path . join ( os . tmpdir (), 'maimai-change-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 )})});
assert . equal (( await call ( 'none' , '/api/order-changes' )). status , 401 );
for ( const [ who , name ] of [[ 'owner' , '麦麦' ],[ 'assistant' , '助理' ]]){ const response = await call ( who , '/api/login' ,{ name , password : who === 'owner' ? 'synthetic-owner-password' : 'synthetic-assistant-password' }); cookies [ who ] = response . headers . get ( 'set-cookie' ). split ( ';' )[ 0 ];}
const issued = await ( await call ( 'assistant' , '/api/orders/issue' , input ({ lines : [ line ({ pocket : '' })]}))). json (), id = issued . id , route = '/api/orders/' + id ;
const info = await ( await call ( 'assistant' , route + '/edit' )). json (), body = {... info . inputs , revision : info . revision , reason : 'HTTP修改申请' , verified : true , customer : 'HTTP新客户' };
assert . equal ( info . requiresApproval , true ); assert . equal (( await call ( 'assistant' , route + '/edit' , body )). status , 403 ); assert . equal (( await call ( 'assistant' , route + '/change' , body , undefined ,{ Origin : 'https://evil.example' })). status , 403 );
const key = randomUUID (), requests = await Promise . all ([ call ( 'assistant' , route + '/change' , body , key ), call ( 'assistant' , route + '/change' , body , key )]); assert . deepEqual ( requests . map ( r => r . status ),[ 200 , 200 ]); const [ application , retry ] = await Promise . all ( requests . map ( r => r . json ())); assert . equal ( application . requestId , retry . requestId );
const requestPath = '/api/order-changes/' + application . requestId , decision = { revision : info . revision , verified : true , note : '凭据已核对' };
assert . equal (( await call ( 'assistant' , requestPath + '/approve' , decision )). status , 403 ); assert . equal (( await call ( 'assistant' , requestPath + '/reject' ,{ note : '无权' })). status , 403 ); assert . equal (( await call ( 'owner' , route + '/edit' , body )). status , 409 );
const list = await ( await call ( 'owner' , '/api/order-changes' )). json (); assert . equal ( list . counts . pending , 1 ); assert . equal ( list . requests [ 0 ]. order_date , D ); assert . equal (( await ( await call ( 'owner' , requestPath )). json ()). after . customer , 'HTTP新客户' );
assert . equal (( await ( await call ( 'assistant' , route + '/change' )). json ()). pending . id , application . requestId ); assert . equal (( await call ( 'owner' , requestPath + '/approve' ,{... decision , revision : 0 })). status , 409 );
const approveKey = randomUUID (), responses = await Promise . all ([ call ( 'owner' , requestPath + '/approve' , decision , approveKey ), call ( 'owner' , requestPath + '/approve' , decision , approveKey )]); assert . deepEqual ( responses . map ( r => r . status ),[ 200 , 200 ]); assert . equal ( l . detail ( id ). customer , 'HTTP新客户' ); assert . equal ( l . rows ( "SELECT * FROM audit WHERE action='同意修改订单'" ). length , 1 ); assert . equal ( l . rows ( 'SELECT * FROM orders' ). length , 1 );
assert . equal (( await call ( 'owner' , requestPath + '/approve' , decision )). status , 409 ); const printable = await ( await call ( 'assistant' , route + '/public' )). json (); assert . ok ( ! JSON . stringify ( printable ). includes ( 'changeApproved' ));
const reloaded = new Ledger ( path . join ( dir , 'ledger.sqlite' )); assert . equal ( reloaded . orderChange ( id , owner ). requests [ 0 ]. status , 'approved' ); reloaded . close ();
});