2026-10-22 04:21:26 +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' ), vm = require ( 'node:vm' );
const { Ledger } = require ( '../ledger' ),{ createApp } = require ( '../server' ), Copy = require ( '../public/order-copy' ), Calc = require ( '../public/calculations' ), Fees = require ( '../public/fee-estimates' );
const D = '2026-10-17' , NEXT = '2026-10-18' , owner = { id : 'copy-owner' , name : '测试麦麦' , role : 'owner' };
const snapshot = ledger => JSON . stringify ( ledger . rows ( "SELECT name FROM sqlite_master WHERE type='table' ORDER BY name" ). map (({ name })=>[ name , ledger . rows ( 'SELECT * FROM "' + name + '"' )]));
function fixture ( t ){
const l = new Ledger ( ':memory:' ); t . after (()=> l . close ());
const run = ( input , fn )=> l . transact ( randomUUID (), owner , input , fn );
const issue = input => run ( input ,()=> l . issueOrder ( input , owner )). id ;
const act = ( id , action , input )=> run ({ id , action , input },()=> l . action ( id , action ,{ date : D ,... input }, owner ));
const buy = ( date , total , payer = 'owner' )=>{ const input = { date , grams : '10' , total , payer }; return run ( input ,()=> l . createMaterialPurchase ( input , owner ));};
return { l , run , issue , act , buy };
}
function rich (){
const certificate = randomUUID (), box = randomUUID (), free = randomUUID ();
return { date : D , fees_date : D , customer : '原客户' , salesperson : '原开单人' , payment_account : '麦麦支付宝' , discount : '9.75' , note : '保留这份备注' , rounding_mode : 'cent' , lines : [
{ name : '足金999' , unit : 'g' , quantity : '2.250' , pocket : '' , payer : 'assistant' , pricingMode : 'auto' , goldPrice : '950.25' , laborMode : 'gram' , laborRate : '32.50' , pieces : '1' , charges : [{ id : certificate , name : '证书' , amount : '12.50' },{ id : box , name : '包装' , amount : '11.25' },{ id : free , name : '刻字' , amount : '0' }], costParts : { material : '0' , labor : '0' , accessories : '2.25' , other : '3.50' }, costMaterial : { mode : 'gram' , rate : '898.75' }, costLabor : { mode : 'gram' , rate : '13.25' }, costPayers : { material : 'owner' , labor : 'assistant' }},
{ name : '手工配件' , unit : '件' , quantity : '2' , pocket : '' , payer : 'assistant' , pricingMode : 'manual' , baseSale : '160.49' , priceNote : '两件合计' , charges : [], costParts : { material : '83.25' , labor : '6.50' , accessories : '0' , other : '0' }, costMaterial : { mode : 'total' }, costLabor : { mode : 'total' }, costPayers : { material : 'assistant' , labor : 'owner' }}
], fee_items : [
{ key : 'shipping' , note : '快递费' , amount : '7.40' , payer : 'assistant' , status : 'estimated' , edited : true },
{ key : 'charge:' + certificate , note : '证书' , sourceName : '证书' , amount : '5.25' , payer : 'owner' , status : 'estimated' , edited : true },
{ key : 'charge:' + box , note : '包装' , sourceName : '包装' , amount : '4.50' , payer : 'assistant' , status : 'estimated' , edited : true },
{ key : 'charge:' + free , note : '刻字' , sourceName : '刻字' , amount : '0' , payer : 'owner' , status : 'estimated' , edited : true },
{ key : 'manual:' + randomUUID (), note : '手工处理' , amount : '18.80' , payer : 'assistant' , status : 'estimated' , edited : true }
]};
}
test ( '复制保留全部可填写报价、成本和付款人,清空客户与财务身份,构造草稿不写任何表' , t =>{
const { l , issue , act } = fixture ( t ), id = issue ( rich ()); act ( id , 'expense' ,{ amount : '9.50' , payer : 'owner' , note : '额外加急费' });
act ( id , 'settlement' ,{ amount : '5' , bucket : 'cost' , direction : 'toAssistant' , verified : true , note : '实际交款' });
const before = snapshot ( l ), original = l . detail ( id ), draft = Copy . fromOrder ( original ,{ today : NEXT });
assert . equal ( snapshot ( l ), before ); assert . equal ( draft . customer , '' ); assert . equal ( draft . date , NEXT ); assert . equal ( draft . fees_date , NEXT ); assert . equal ( draft . rounding_mode , 'yuan' );
assert . equal ( draft . salesperson , '原开单人' ); assert . equal ( draft . payment_account , '麦麦支付宝' ); assert . equal ( draft . discount , '9.75' ); assert . equal ( draft . note , '保留这份备注' );
for ( const key of [ 'id' , 'revision' , 'paper_number' , 'paper_date' , 'number' , 'status' , 'created' , 'payments' , 'expenses' , 'settlements' , 'corrections' , 'audit' , 'reviewed_revision' , 'sync' , 'price_lock_id' ]) assert . ok ( ! Object . hasOwn ( draft , key ), key );
const line = draft . lines [ 0 ]; assert . equal ( line . quantity , '2.250' ); assert . equal ( line . goldPrice , '950.25' ); assert . equal ( line . laborRate , '32.50' ); assert . equal ( line . laborMode , 'gram' ); assert . equal ( line . payer , 'assistant' );
assert . deepEqual ( line . costPayers ,{ material : 'owner' , labor : 'assistant' }); assert . deepEqual ( line . costMaterial ,{ mode : 'gram' , rate : '898.75' }); assert . deepEqual ( line . costLabor ,{ mode : 'gram' , rate : '13.25' });
assert . equal ( line . costParts . accessories , '2.25' ); assert . equal ( line . costParts . other , '3.50' );
assert . equal ( draft . lines [ 1 ]. baseSale , '160.49' ); assert . equal ( draft . lines [ 1 ]. quantity , 2 ); assert . equal ( draft . lines [ 1 ]. priceNote , '两件合计' );
const oldIds = new Set ( original . lines . flatMap ( line => line . charges . map ( charge => charge . id )));
for ( const charge of line . charges ) assert . ok ( ! oldIds . has ( charge . id ));
for ( const fee of draft . fee_items ){ assert . equal ( fee . status , 'estimated' ); assert . equal ( fee . edited , true ); assert . ok ( ! Object . hasOwn ( fee , 'id' )); assert . ok ( ! Object . hasOwn ( fee , 'order_id' ));}
assert . equal ( draft . fee_items . length , 6 ); assert . equal ( draft . fee_items . reduce (( sum , fee )=> sum + Calc . cents ( fee . amount ), 0 ), original . directCost );
assert . deepEqual ( Fees . sync ( draft . fee_items , draft . lines ), draft . fee_items );
assert . equal ( draft . fee_items . find ( fee => fee . note === '证书' ). amount , '5.25' ); assert . equal ( draft . fee_items . find ( fee => fee . note === '包装' ). payer , 'assistant' ); assert . equal ( draft . fee_items . find ( fee => fee . note === '刻字' ). amount , '0.00' );
draft . lines [ 0 ]. costParts . accessories = '99' ; assert . equal ( l . detail ( id ). lines [ 0 ]. costParts . accessories , 225 );
});
test ( '改克重重算销售金价、进货料价和克工费,总额销售和总额成本保持原值' , t =>{
const { l , issue } = fixture ( t ), original = l . detail ( issue ( rich ())), draft = Copy . fromOrder ( original ,{ today : NEXT }), line = draft . lines [ 0 ];
line . quantity = '3.125' ; const sale = Calc . sale ( line ), cost = Calc . purchaseCosts ( line );
assert . equal ( sale . sale , Math . round ( 3.125 * ( 950.25 + 32.5 ) * 100 ) + 2375 ); assert . equal ( cost . parts . material , Math . round ( 3.125 * 898.75 * 100 )); assert . equal ( cost . parts . labor , Math . round ( 3.125 * 13.25 * 100 ));
const total = draft . lines [ 1 ]; total . quantity = '9' ; assert . equal ( Calc . sale ( total ). sale , 16049 ); assert . equal ( Calc . purchaseCosts ( total ). parts . material , 8325 ); assert . equal ( Calc . purchaseCosts ( total ). parts . labor , 650 );
line . laborMode = 'piece' ; line . pieces = 2 ; line . laborRate = '25' ; assert . equal ( Calc . sale ( line ). sale , Math . round (( 3.125 * 950.25 + 50 ) * 100 ) + 2375 );
});
test ( '保存复制单只记新单一次,原订单、流水和编号保持原样' , t =>{
const { l , issue } = fixture ( t ), id = issue ( rich ()), original = l . detail ( id ), draft = Copy . fromOrder ( original ,{ today : NEXT });
const before = snapshot ( l ); assert . equal ( Copy . fromOrder ( original ,{ today : NEXT }). id , undefined ); assert . equal ( snapshot ( l ), before );
draft . customer = '新客户' ; draft . lines [ 0 ]. quantity = '3.125' ; const newId = issue ( draft ), saved = l . detail ( newId );
assert . notEqual ( newId , id ); assert . notEqual ( saved . number , original . number ); assert . notEqual ( saved . paper_number , original . paper_number ); assert . equal ( saved . date , NEXT ); assert . equal ( saved . customer , '新客户' ); assert . equal ( saved . payments . length , 1 );
assert . equal ( saved . payments [ 0 ]. amount , saved . total ); assert . equal ( saved . expenses . length , 4 ); assert . equal ( saved . directCost , original . directCost ); assert . deepEqual ( l . detail ( id ), original );
assert . equal ( l . rows ( 'SELECT * FROM orders' ). length , 2 ); assert . equal ( l . rows ( 'SELECT * FROM journal WHERE order_id=?' , newId ). length , 1 );
});
test ( '费用更正后的有效支出只复制一次,冲回与旧模板不回填,改到0不复活默认额' , t =>{
const { l , issue , act } = fixture ( t ), id = issue ( rich ()), original = l . detail ( id ), certificate = original . expenses . find ( item => item . note === '证书' ), box = original . expenses . find ( item => item . note === '包装' );
act ( id , 'correct' ,{ type : 'expense' , target : certificate . id , amount : '8.80' , payer : 'assistant' , verified : true , reason : '证书实际花费' });
const first = l . detail ( id ). expenses . find ( item => item . note === '更正补记:证书实际花费' );
act ( id , 'correct' ,{ type : 'expense' , target : first . id , amount : '9.25' , payer : 'owner' , verified : true , reason : '再次核对' });
act ( id , 'correct' ,{ type : 'expense' , target : box . id , amount : '0' , payer : 'owner' , verified : true , reason : '撤回包装误记' });
const current = l . detail ( id ), draft = Copy . fromOrder ( current ,{ today : NEXT });
assert . equal ( draft . fee_items . reduce (( sum , item )=> sum + Calc . cents ( item . amount ), 0 ), current . directCost );
assert . equal ( draft . fee_items . find ( item => item . note === '证书' ). amount , '0.00' ); assert . equal ( draft . fee_items . find ( item => item . note === '包装' ). amount , '0.00' );
assert . equal ( draft . fee_items . find ( item => item . note === '更正补记:再次核对' ). amount , '9.25' ); assert . ok ( ! draft . fee_items . some ( item => item . note . startsWith ( '更正冲回:' )));
assert . ok ( ! draft . fee_items . some ( item =>[ '8.80' , '5.25' , '4.50' ]. includes ( item . amount ))); assert . deepEqual ( Fees . sync ( draft . fee_items , draft . lines ), draft . fee_items );
2026-10-23 09:49:36 +08:00
draft . customer = '复制新客户' ; const saved = l . detail ( issue ( draft )); assert . equal ( saved . directCost , current . directCost ); assert . deepEqual ( l . detail ( id ), current );
2026-10-22 04:21:26 +08:00
});
test ( '同名同额多项费用及额外费用逐笔保留,150字额外费用名称可以再次保存' , t =>{
const { l , issue , act } = fixture ( t ), input = rich (); input . fee_items . push ({ key : 'manual:' + randomUUID (), note : '手工处理' , amount : '18.80' , payer : 'assistant' , status : 'estimated' });
const id = issue ( input ); act ( id , 'expense' ,{ amount : '18.80' , payer : 'assistant' , note : '手工处理' }); act ( id , 'expense' ,{ amount : '3.20' , payer : 'owner' , note : '长' . repeat ( 150 )});
const source = l . detail ( id ), draft = Copy . fromOrder ( source ,{ today : NEXT }); assert . equal ( draft . fee_items . filter ( item => item . note === '手工处理' ). length , 3 ); assert . equal ( draft . fee_items . find ( item => item . note . length === 150 ). amount , '3.20' );
2026-10-23 09:49:36 +08:00
draft . customer = '复制新客户' ; assert . equal ( l . detail ( issue ( draft )). directCost , source . directCost );
2026-10-22 04:21:26 +08:00
});
test ( '旧单没有费用模板时采用实际支出,已完成且没有花费的附加项明确保留0' , t =>{
const { l , issue , act } = fixture ( t ), id = issue ( rich ()); l . run ( 'UPDATE orders SET fee_items=? WHERE id=?' , '[]' , id ); const source = l . detail ( id ), draft = Copy . fromOrder ( source ,{ today : NEXT });
assert . equal ( draft . fee_items . reduce (( sum , item )=> sum + Calc . cents ( item . amount ), 0 ), source . directCost ); assert . equal ( draft . fee_items . find ( item => item . note === '刻字' ). amount , '0.00' );
assert . equal ( draft . fee_items . find ( item => item . note === '快递费' ). amount , '7.40' ); assert . deepEqual ( Fees . sync ( draft . fee_items , draft . lines ), draft . fee_items );
const zero = source . expenses . find ( item => item . note === '证书' ); act ( id , 'correct' ,{ type : 'expense' , target : zero . id , amount : '0' , payer : 'owner' , verified : true , reason : '撤回' });
const current = l . detail ( id ), next = Copy . fromOrder ( current ,{ today : NEXT }); assert . equal ( next . fee_items . find ( item => item . note === '证书' ). amount , '0.00' ); assert . equal ( next . fee_items . reduce (( sum , item )=> sum + Calc . cents ( item . amount ), 0 ), current . directCost );
});
test ( '未完成旧草稿的空费用、手填0、付款人和原总成本保持待填写语义' , t =>{
const { l , run } = fixture ( t ), input = rich (); input . fee_items [ 1 ]. amount = '' ; input . fee_items [ 2 ]. amount = '0' ; input . lines [ 0 ] = { name : '旧未分项' , unit : 'g' , quantity : '2' , pocket : '' , payer : 'assistant' , pricingMode : 'manual' , baseSale : '100' , cost : '30' , charges : []};
const id = run ( input ,()=> l . saveOrder ( input , owner )). id , source = l . detail ( id ), draft = Copy . fromOrder ( source ,{ today : NEXT });
assert . equal ( draft . fee_items . find ( item => item . note === '证书' ). amount , '' ); assert . equal ( draft . fee_items . find ( item => item . note === '包装' ). amount , '0.00' ); assert . equal ( draft . lines [ 0 ]. cost , '30.00' ); assert . equal ( draft . lines [ 0 ]. payer , 'assistant' );
});
2026-10-23 09:49:36 +08:00
function pooled ( poolId ){ return { date : D , customer : '日购料原单' , salesperson : '合成开单人' , payment_account : '助理微信' , discount : '0' , fee_items : [], lines : [{ name : '足金999' , unit : 'g' , quantity : '2' , pocket : '' , payer : 'owner' , pricingMode : 'auto' , goldPrice : '980' , laborRate : '20' , laborMode : 'gram' , pieces : '1' , costParts : { material : '' , labor : '20' , accessories : '0' , other : '0' }, costMaterial : { mode : 'pool' , poolId }, costLabor : { mode : 'gram' , rate : '10' }, costPayers : { material : 'owner' , labor : 'assistant' }}]};}
2026-10-22 04:21:26 +08:00
test ( '原当日池随新日期切换并重新核算,不继承耗用分摊或旧快照,不提前占料' , t =>{
const { l , issue , buy } = fixture ( t ); buy ( D , '9000' , 'owner' ); buy ( NEXT , '9500' , 'assistant' ); const id = issue ( pooled ( D )), source = l . detail ( id ), before = snapshot ( l ), draft = Copy . fromOrder ( source ,{ today : NEXT }), line = draft . lines [ 0 ];
assert . equal ( snapshot ( l ), before ); assert . deepEqual ( line . costMaterial ,{ mode : 'pool' , poolId : NEXT }); assert . equal ( line . materialPoolDraft . defaultDate , true ); assert . equal ( line . costParts . material , '' ); assert . ok ( ! Object . hasOwn ( line , 'materialPool' )); assert . ok ( ! Object . hasOwn ( line , 'materialAllocations' ));
2026-10-23 09:49:36 +08:00
assert . equal ( Calc . purchaseCosts ( line ). parts . material , null ); line . quantity = '3' ; draft . customer = '复制新客户' ; const result = l . detail ( issue ( draft )); assert . equal ( result . lines [ 0 ]. costParts . material , 285000 ); assert . deepEqual ( result . lines [ 0 ]. materialPool . allocations ,[{ payer : 'assistant' , amount : 285000 }]);
2026-10-22 04:21:26 +08:00
assert . equal ( l . materialPoolDetail ( D ). usedMg , 2000 ); assert . equal ( l . materialPoolDetail ( NEXT ). usedMg , 3000 ); assert . deepEqual ( l . detail ( id ), source );
});
test ( '原来手选以前日期的池保留选择,使用当前池余额,新耗用只新增一份' , t =>{
const { l , issue , buy } = fixture ( t ), old = '2026-10-16' ; buy ( old , '8800' ); const id = issue ( pooled ( old )), source = l . detail ( id ), before = snapshot ( l ), draft = Copy . fromOrder ( source ,{ today : NEXT });
assert . equal ( snapshot ( l ), before ); assert . equal ( draft . lines [ 0 ]. costMaterial . poolId , old ); assert . equal ( draft . lines [ 0 ]. materialPoolDraft . defaultDate , false ); draft . lines [ 0 ]. quantity = '3' ;
2026-10-23 09:49:36 +08:00
draft . customer = '复制新客户' ; const result = l . detail ( issue ( draft )); assert . equal ( result . lines [ 0 ]. costParts . material , 264000 ); assert . equal ( l . materialPoolDetail ( old ). usedMg , 5000 ); assert . equal ( l . rows ( 'SELECT * FROM material_pool_usages' ). length , 2 ); assert . equal ( l . rows ( 'SELECT * FROM material_purchases' ). length , 1 );
2026-10-22 04:21:26 +08:00
});
test ( '锁价交付只复制普通报价,清掉旧关联与锁价备注,必须补料费及付款人,保存不再造锁价入库' , t =>{
2026-10-23 09:49:36 +08:00
const { l , run , issue } = fixture ( t ), creation = { date : D , customer : '原锁价客户' , salesperson : '合成开单人' , note : '原客户备注' , line : { name : '足金999' , quantity : '2' , goldPrice : '980' , laborRate : '20' , laborMode : 'gram' , pieces : '1' , charges : []}, discount : '0' , payment : { amount : '2000' , account : '助理微信' , verified : true }, material : { rate : '900' , payer : 'owner' , verified : true }};
2026-10-22 04:21:26 +08:00
const lock = run ( creation ,()=> l . createPriceLock ( creation , owner ));
const delivery = { date : NEXT , revision : 1 , verified : true , line : { quantity : '2' , laborRate : '20' , laborMode : 'gram' , pieces : '1' , charges : [], payer : 'owner' , costParts : { labor : '20' , accessories : '0' , other : '0' }, costLabor : { mode : 'total' }, costPayers : { material : 'owner' , labor : 'assistant' }}, discount : '0' , inventory : { pocket : '现货' , original : 'receive' }, fee_items : []};
const result = run ( delivery ,()=> l . deliverPriceLock ( lock . id , delivery , owner )), original = l . detail ( result . id ), before = snapshot ( l ), draft = Copy . fromOrder ( original ,{ today : NEXT });
assert . equal ( snapshot ( l ), before ); assert . equal ( draft . copy_kind , 'price-lock' ); assert . equal ( draft . note , '原客户备注' ); assert . equal ( draft . lines [ 0 ]. goldPrice , '980.00' ); assert . equal ( draft . lines [ 0 ]. costParts . material , '' ); assert . equal ( draft . lines [ 0 ]. costPayers . material , '' ); assert . ok ( ! Object . hasOwn ( draft , 'price_lock_id' )); assert . ok ( ! Object . hasOwn ( draft . lines [ 0 ], 'materialAllocations' ));
assert . throws (()=> issue ( draft ), /付款人|料费成本/ ); assert . equal ( snapshot ( l ), before );
2026-10-23 09:49:36 +08:00
draft . customer = '复制新客户' ; draft . lines [ 0 ]. costParts . material = '1700' ; draft . lines [ 0 ]. costPayers . material = 'assistant' ; draft . lines [ 0 ]. pocket = '' ; const copy = l . detail ( issue ( draft ));
2026-10-22 04:21:26 +08:00
assert . ok ( ! copy . price_lock_id ); assert . equal ( l . rows ( 'SELECT * FROM price_locks' ). length , 1 ); assert . equal ( l . rows ( 'SELECT * FROM price_lock_events' ). length , 2 ); assert . equal ( l . rows ( 'SELECT * FROM movements' ). length , 2 ); assert . deepEqual ( l . detail ( original . id ), original );
});
test ( '空白自动草稿无需覆盖提示;填写0、添加项目、改收款人或已有复制草稿都须保护' ,()=>{
const blank = { date : NEXT , salesperson : '助理' , payment_account : '助理微信' , lines : [{ name : '足金999' , unit : 'g' , pocket : '现货' , quantity : '' , goldPrice : '' , laborRate : '' , sale : '' , baseSale : '' , costParts : { material : '' , labor : '' , accessories : '0' , other : '0' }, costPayers : { material : 'owner' , labor : 'owner' }}], fee_items : [{ key : 'shipping' , amount : '6' , payer : 'assistant' , status : 'estimated' , edited : false }]}, options = { today : NEXT , salesperson : '助理' };
assert . equal ( Copy . hasDraftContent ( blank , options ), false );
for ( const patch of [{ customer : '新客户' },{ payment_account : '麦麦微信' },{ copy_kind : 'ordinary' },{ lines : [{... blank . lines [ 0 ], goldPrice : '0' }]},{ lines : [{... blank . lines [ 0 ], charges : [{ name : '证书' , amount : '0' }]}]},{ fee_items : [{... blank . fee_items [ 0 ], amount : '0' , edited : true }]}]) assert . equal ( Copy . hasDraftContent ({... blank ,... patch }, options ), true );
});
function browserHarness ( order ){
const saved = new Map (), calls = [], dialog = { open : true , close (){ this . open = false ;}}, context = vm . createContext ({ OrderCopy : Copy , crypto : { randomUUID }, setInterval (){}, setTimeout (){}, clearTimeout (){}, document : { addEventListener (){}, querySelector ( selector ){ return selector === '#order-dialog' ? dialog : null ;}}, window : { confirm (){ return context . allowConfirm ;}, scrollTo (){}}, localStorage : { getItem : key => saved . get ( key ) ?? null , setItem : ( key , value )=> saved . set ( key , value ), removeItem : key => saved . delete ( key )}, __order : order , __calls : calls , allowConfirm : true });
vm . runInContext ( "let createMode='direct';" , context ); vm . runInContext ( fs . readFileSync ( path . join ( __dirname , '../public/order-templates-ui.js' ), 'utf8' ), context ); vm . runInContext ( fs . readFileSync ( path . join ( __dirname , '../public/app.js' ), 'utf8' ). replace ( /\ninit\(\);\s*$/ , '' ), context );
vm . runInContext ( `session={user:{id:'copy-user',name:'助理'}};state={user:session.user,today:' ${ D } '};tab='orders';api=async function(url,data){__calls.push({url,data});return url==='/api/session'?{user:session.user,today:' ${ NEXT } '}:__order;};render=async function(){};toast=function(){};` , context );
return { context , saved , calls , key : 'mm-draft-copy-user' , copy : ()=> vm . runInContext ( "copyOrder('old-id')" , context )};
}
test ( '复制UI先阻止未确认提交与保存中状态,取消覆盖或只读加载失败不动草稿' , t =>{
const { l , issue } = fixture ( t ), order = l . detail ( issue ( rich ())), h = browserHarness ( order ), previous = JSON . stringify ({ customer : '另一客户' , lines : [{}]}); h . saved . set ( h . key , previous );
h . saved . set ( 'mm-pending-copy-user' , JSON . stringify ({ url : '/api/orders/issue' })); return ( async ()=>{
await assert . rejects ( h . copy (), /恢复原操作/ ); assert . equal ( h . calls . length , 0 ); assert . equal ( h . saved . get ( h . key ), previous ); h . saved . delete ( 'mm-pending-copy-user' );
vm . runInContext ( 'busy=true' , h . context ); await assert . rejects ( h . copy (), /正在处理/ ); assert . equal ( h . calls . length , 0 ); vm . runInContext ( 'busy=false' , h . context );
h . context . allowConfirm = false ; await h . copy (); assert . equal ( h . saved . get ( h . key ), previous ); assert . equal ( vm . runInContext ( 'tab' , h . context ), 'orders' );
vm . runInContext ( "api=async function(){throw new Error('读取失败')}" , h . context ); await assert . rejects ( h . copy (), /读取失败/ ); assert . equal ( h . saved . get ( h . key ), previous ); assert . equal ( vm . runInContext ( 'orderCopyLoading' , h . context ), false );
})();
});
test ( '复制UI只读GET后写入本地新草稿,加载期间出现pending或换页不会覆盖' , async t =>{
const { l , issue } = fixture ( t ), order = l . detail ( issue ( rich ())), h = browserHarness ( order ); await h . copy ();
const draft = JSON . parse ( h . saved . get ( h . key )); assert . equal ( draft . customer , '' ); assert . equal ( draft . date , NEXT ); assert . equal ( vm . runInContext ( 'tab' , h . context ), 'create' ); assert . deepEqual ( h . calls . map ( call => call . url ),[ '/api/orders/old-id' , '/api/session' ]); assert . ok ( h . calls . every ( call => call . data === undefined ));
const other = browserHarness ( order ); other . saved . set ( other . key , '{"customer":"保留","lines":[{}]}' );
vm . runInContext ( "api=async function(url){localStorage.setItem('mm-pending-copy-user','{\"url\":\"/api/orders/issue\"}');return url==='/api/session'?{user:session.user,today:'2026-10-18'}:__order;}" , other . context );
await assert . rejects ( other . copy (), /恢复原操作/ ); assert . equal ( JSON . parse ( other . saved . get ( other . key )). customer , '保留' );
other . saved . delete ( 'mm-pending-copy-user' ); vm . runInContext ( "api=async function(url){tab='stock';return url==='/api/session'?{user:session.user,today:'2026-10-18'}:__order;}" , other . context );
await other . copy (); assert . equal ( JSON . parse ( other . saved . get ( other . key )). customer , '保留' );
});
test ( '新纯helper资源可由隔离服务器提供,浏览器和Node构造一致且无依赖' , async t =>{
const dir = fs . mkdtempSync ( path . join ( os . tmpdir (), 'maimai-copy-http-' )), app = createApp ({ mode : 'demo' , dataDir : dir , 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 )); app . ledger . close (); fs . rmSync ( dir ,{ recursive : true , force : true });});
const base = 'http://127.0.0.1:' + app . server . address (). port , res = await fetch ( base + '/order-copy.js' ); assert . equal ( res . status , 200 ); const script = await res . text (), context = vm . createContext ({});
vm . runInContext ( fs . readFileSync ( path . join ( __dirname , '../public/fee-estimates.js' ), 'utf8' ), context ); vm . runInContext ( script , context );
const original = app . ledger . detail ( app . ledger . one ( 'SELECT id FROM orders' ). id ), factory = ()=>{ let n = 0 ; return ()=> String ( ++ n ). padStart ( 8 , '0' ) + '-0000-4000-8000-000000000000' ;};
assert . equal ( JSON . stringify ( context . OrderCopy . fromOrder ( original ,{ today : NEXT , newId : factory ()})), JSON . stringify ( Copy . fromOrder ( original ,{ today : NEXT , newId : factory ()})));
assert . ok (( await ( await fetch ( base + '/' )). text ()). includes ( 'src="/order-copy.js"' ));
});