2026-10-26 14:44:07 +08:00
'use strict' ;
const { test } = require ( 'node:test' ), assert = require ( 'node:assert/strict' ), fs = require ( 'node:fs' ), path = require ( 'node:path' ), vm = require ( 'node:vm' ),{ randomUUID } = require ( 'node:crypto' );
const Calc = require ( '../public/calculations' ), Card = require ( '../public/credit-card-fees' ),{ Ledger } = require ( '../ledger' ),{ createUser } = require ( '../server' );
const D = '2026-10-25' ;
function harness ( member = 'owner' ){
const nodes = new Map (), saved = new Map (), handlers = {}, posts = [], user = { id : 'synthetic-' + member , name : member === 'owner' ? '合成麦麦' : '合成张' , label : member === 'owner' ? '麦麦' : member === 'assistant' ? '助理1' : '助理2' , member , role : member === 'owner' ? 'owner' : 'assistant' };
const context = vm . createContext ({ console , URLSearchParams , LedgerCalc : Calc , CreditCardFees : Card , crypto : { randomUUID }, setTimeout (){ return 1 ;}, clearTimeout (){}, setInterval (){}, window : { scrollTo (){}, open (){}}, document : { querySelector : q => nodes . get ( q ) || null , querySelectorAll : ()=>[], addEventListener : ( type , fn )=>( handlers [ type ] ??= []). push ( fn )}, FormData : class { constructor ( form ){ return Object . entries ( form . values || {});}}, localStorage : { getItem : k => saved . get ( k ) || null , setItem : ( k , v )=> saved . set ( k , String ( v )), removeItem : k => saved . delete ( k )}, sessionStorage : { getItem (){ return null ;}, setItem (){}}, __user : user , __posts : posts });
const run = code => vm . runInContext ( code , context ), json = code => JSON . parse ( JSON . stringify ( run ( code )));
for ( const file of [ 'material-pools-ui.js' , 'recoveries-ui.js' , 'app.js' ]) run ( fs . readFileSync ( path . join ( __dirname , '../public' , file ), 'utf8' ). replace ( /\ninit\(\);\s*$/ , '' ));
run ( `session={user:__user,mode:'demo'};state={user:__user,members:[{member:'owner'},{member:'assistant'},{member:'assistant2'}],today:' ${ D } ',accounts:['麦麦微信','麦麦支付宝','麦麦现金','麦麦信用卡','助理微信','助理支付宝','助理现金','助理2微信','助理2支付宝','助理2现金'],pockets:['现货','金料','找金','回收旧料','君宝汇']};tab='recoveries';toast=function(){};showPending=function(){};api=async function(url,data,key){__posts.push({url,data,key});return {saved:true};};` );
function draft ( values = {}){ context . __values = values ; return json ( '({...recoveryDefaults(),...__values})' );}
function input ( values = {}, options = {}){ context . __draft = draft ( values ); context . __options = options ; return json ( 'recoveryInput(__draft,__options)' );}
function calculate ( value ){ context . __input = value ; return json ( 'recoveryCalculate(__input)' );}
function form ( values = {}){
const data = draft ( values ), elements = Object . fromEntries ( Object . entries ( data ). map (([ name , value ])=>[ name ,{ value : String ( value ), checked : name === 'verified' && value === true , dataset : {}}]));
elements . namedItem = name => elements [ name ]; return { elements , dataset : Object . fromEntries ([ 'buy_total_manual' , 'depreciation_manual' , 'melted_manual' ]. map ( key =>[ key , String ( data [ key ] === true )]))};
}
return { run , json , context , nodes , saved , handlers , posts , user , draft , input , calculate , form };
}
const base = { customer : '合成客户' , incoming_weight : '20' , melted_weight : '20' , purity : '100' , buy_rate : '900' , verified : true };
const swap = {... base , mode : 'exchange' , new_quantity : '30' , gold_price : '1000' , labor_rate : '20' , material_source : 'manual' , material_rate : '900' , cost_labor_value : '5' };
2026-11-24 21:11:32 +08:00
test ( '旧料入库选择保存草稿与payload,找金不受self限制,计对入库和新货出库各填各的' ,()=>{
const h = harness (); h . run ( `state.pockets.push('合成对数盘');state.pocketCatalog=[{key:'找金',name:'找金<img src=x>',active:true,self:false},{key:'合成对数盘',name:'合成对数盘',active:true,self:true,countUnit:'pair',countSince:' ${ D } '}];` );
assert . equal ( h . draft (). old_pocket , '回收旧料' ); const input = h . input ({... swap , old_pocket : '找金' , old_stock_count : '99' }); assert . equal ( input . old_pocket , '找金' ); assert . equal ( input . old_stock_count , undefined ); assert . equal ( input . exchange . pocket , '现货' ); h . context . __input = input ; assert . doesNotThrow (()=> h . run ( 'validateRecoveryInput(__input)' ));
const counted = h . input ({... swap , old_pocket : '合成对数盘' , old_stock_count : '3' , pocket : '合成对数盘' , stockCount : '2' }); assert . equal ( counted . old_stock_count , '3' ); assert . equal ( counted . exchange . stockCount , '2' ); h . context . __input = counted ; assert . doesNotThrow (()=> h . run ( 'validateRecoveryInput(__input)' )); counted . old_stock_count = null ; assert . throws (()=> h . run ( 'validateRecoveryInput(__input)' ), /旧料入库数量/ );
h . context . __draft = h . draft ({... base , old_pocket : '找金' }); const html = h . run ( 'recoveryFormHTML(__draft)' ); assert . match ( html , /旧料入库货盘/ ); assert . match ( html , /name="old_pocket"/ ); assert . match ( html , /name="old_stock_count"/ ); assert . match ( html , /找金<img src=x>/ ); assert . doesNotMatch ( html , /找金<img/ );
h . context . __form = h . form ({... base , old_pocket : '找金' }); h . run ( 'rememberRecoveryDraft(__form)' ); assert . equal ( JSON . parse ( h . saved . get ( 'mm-recovery-draft-' + h . user . id )). old_pocket , '找金' );
});
2026-10-26 14:44:07 +08:00
test ( '回收入口有两种业务且无最低5克,老板可代录归属,助理固定本人' ,()=>{
const h = harness (); h . context . __draft = h . draft (); const html = h . run ( 'recoveryFormHTML(__draft)' );
for ( const text of [ '直接回收' , '置换' , '客户称呼/代号' , '来料重量' , '熔后重量' , '成色(%) ' , '折后重量' , '内部成本' , '保存后自动编号' ]) assert . ok ( html . includes ( text ));
assert . match ( html , /<select name="member">/ ); assert . match ( html , /name="customer"[^>]*required/ ); assert . match ( html , /name="salesperson"[^>]*required/ ); assert . doesNotMatch ( html , /min="5"|至少5克|5g/ );
assert . equal ( h . run ( 'recoveryDefaults().rounding_mode' ), 'yuan' );
const assistant = harness ( 'assistant2' ); assistant . context . __draft = assistant . draft (); const own = assistant . run ( 'recoveryFormHTML(__draft)' ); assert . doesNotMatch ( own , /<select name="member">/ ); assert . match ( own , /name="member" value="assistant2"/ ); assert . match ( own , /name="salesperson" value="合成张"/ );
const index = fs . readFileSync ( path . join ( __dirname , '../public/index.html' ), 'utf8' ); assert . match ( index , /data-tab="recoveries"/ ); assert . ok ( index . indexOf ( '/recoveries-ui.js' ) < index . indexOf ( '/app.js' ));
});
test ( '订单页回收查看和打印沿用现有回收模块,不走普通销售单操作' , async ()=>{
const h = harness (), opened = [], printed = []; h . context . __opened = opened ; h . context . window . open = (... args )=> printed . push ( args ); h . run ( 'tab="orders";openRecovery=async function(id){__opened.push(id);};' );
for ( const action of [ 'recovery-open' , 'recovery-print' ]){
const node = { disabled : false , dataset : { action , id : 'synthetic-recovery' }};
for ( const handler of h . handlers . click || []) await handler ({ target : { closest : ()=> node }});
}
assert . deepEqual ( opened ,[ 'synthetic-recovery' ]); assert . deepEqual ( printed ,[[ '/print/recoveries/synthetic-recovery' , '_blank' , 'noopener' ]]); assert . deepEqual ( h . posts ,[]);
});
test ( '直接回收按熔后重量乘百分成色,自动金额和手改金额均保留到分' ,()=>{
const h = harness (), input = h . input ({... base , mode : 'direct' , incoming_weight : '1.234' , melted_weight : '1.200' , purity : '99.9' }), q = h . calculate ( input );
assert . equal ( q . oldMg , 1199 ); assert . equal ( q . purchaseAmount , 107910 ); assert . equal ( q . netSettlement , - 107910 ); assert . equal ( q . newMg , 0 ); assert . equal ( q . cashPayment , 107910 ); assert . equal ( q . cashReceipt , 0 );
const manual = h . calculate ( h . input ({... base , mode : 'direct' , incoming_weight : '1.234' , melted_weight : '1.200' , purity : '99.9' , buy_total_manual : true , buy_total : '1079.11' })); assert . equal ( manual . purchaseAmount , 107911 );
});
test ( '20换30只补10克差价,新货30克计工费,默认按20克折旧,不要求回收价' ,()=>{
const h = harness (), input = h . input ({... swap , buy_rate : '' }), q = h . calculate ( input );
assert . equal ( input . buy_rate , '0' ); assert . equal ( input . buy_total , '0' ); assert . equal ( q . differenceMg , 10000 ); assert . equal ( q . matchedMg , 20000 ); assert . equal ( q . surplusMg , 0 ); assert . equal ( q . goldAmount , 1000000 ); assert . equal ( q . laborAmount , 60000 ); assert . equal ( q . depreciationAmount , 20000 ); assert . equal ( q . netSettlement , 1080000 );
h . context . __input = input ; assert . doesNotThrow (()=> h . run ( 'validateRecoveryInput(__input)' ));
const equal = h . calculate ( h . input ({... swap , new_quantity : '20' , buy_rate : '' , gold_price : '0' , labor_rate : '0' , depreciation_rate : '0' , cost_labor_value : '0' })); assert . equal ( equal . netSettlement , 0 ); assert . equal ( equal . purchaseAmount , 0 );
});
test ( '30换20按余10克回收,收正额、付负额和零现金三个方向由同一公式决定' ,()=>{
const h = harness (), negative = h . calculate ( h . input ({... swap , incoming_weight : '30' , melted_weight : '30' , new_quantity : '20' , buy_rate : '850' , payer : 'assistant2' , payout_method : '现金' }));
assert . equal ( negative . surplusMg , 10000 ); assert . equal ( negative . purchaseAmount , 850000 ); assert . equal ( negative . receivable , 60000 ); assert . equal ( negative . netSettlement , - 790000 ); assert . equal ( negative . cashPayment , 790000 );
for ( const [ amount , net , receipt , payment ] of [[ '100' , 50000 , 50000 , 0 ],[ '600' , 0 , 0 , 0 ],[ '1000' , - 40000 , 0 , 40000 ]]){
const input = h . input ({... swap , incoming_weight : '30' , melted_weight : '30' , new_quantity : '20' , buy_total_manual : true , buy_total : amount , payer : 'assistant2' , payout_method : '现金' , payment_recipient : '助理' , payment_method : '微信' }), q = h . calculate ( input );
assert . equal ( q . netSettlement , net ); assert . equal ( q . cashReceipt , receipt ); assert . equal ( q . cashPayment , payment ); assert . equal ( input . payment_account , net > 0 ? '助理微信' : '助理2现金' );
h . context . __input = input ; assert . doesNotThrow (()=> h . run ( 'validateRecoveryInput(__input)' ));
}
});
test ( '30换20及等重置换无需销售金价或差重料费,20换30仍须填写正销售价' , t =>{
const l = new Ledger ( ':memory:' ); t . after (()=> l . close ()); const actor = { id : createUser ( l , '合成麦麦' , 'owner' , 'synthetic-ui-password' , 'owner' ), name : '合成麦麦' , role : 'owner' , member : 'owner' }; l . enableTeamMode (); const h = harness ();
for ( const [ old , newWeight , rate , labor , depreciation , net ] of [[ '30' , '20' , '850' , '20' , '10' , - 790000 ],[ '20' , '20' , '' , '0' , '0' , 0 ]]){
const input = h . input ({... swap , incoming_weight : old , melted_weight : old , new_quantity : newWeight , gold_price : '' , buy_rate : rate , labor_rate : labor , depreciation_rate : depreciation , material_source : 'manual' , material_rate : '' , cost_labor_value : '0' }), q = h . calculate ( input );
assert . equal ( input . exchange . gold_price , '0' ); assert . equal ( input . exchange . cost_material , undefined ); assert . equal ( q . netSettlement , net ); h . context . __input = input ; assert . doesNotThrow (()=> h . run ( 'validateRecoveryInput(__input)' ));
const server = l . scope ( actor ,()=> l . recoveryQuote ( input , actor )); assert . equal ( server . netSettlement , net ); h . context . __calculation = q ; const html = h . run ( 'recoverySettlementHTML(__calculation,__input)' ); assert . match ( html , /无需补金差价/ ); assert . doesNotMatch ( html , /max( |NaN/ ); if ( q . surplusMg ) assert . match ( html , /余料回收:(30.000 − 20.000) / ); else assert . match ( html , /无需余料回收/ );
}
for ( const value of [ '' , '0' ]) assert . throws (()=> h . input ({... swap , gold_price : value }), /当天销售金价/ );
h . context . __input = h . input ( swap ); h . context . __calculation = h . calculate ( h . context . __input ); assert . match ( h . run ( 'recoverySettlementHTML(__calculation,__input)' ), /补金差价:(30.000 − 20.000) / );
});
test ( '表单现值按元素读取成字符串,禁用选项不丢归属、付款人或真实金额' ,()=>{
const h = harness ( 'assistant2' ), form = h . form ({... swap , member : 'owner' , depreciation_manual : true , depreciation_weight : '18.001' , material_source : 'pool' , material_pool_id : D , fee_amount : '8.25' , fee_payer : 'assistant' , verified : true });
form . elements . new_quantity . value = '31.234' ; form . elements . material_payer . disabled = true ; form . elements . payment_recipient . disabled = true ; form . elements . payment_method . value = '信用卡' ; h . context . __form = form ;
const draft = h . json ( 'recoveryFormDraft(__form)' ); assert . equal ( draft . new_quantity , '31.234' ); assert . equal ( draft . member , 'assistant2' ); assert . equal ( draft . verified , true ); assert . equal ( draft . depreciation_manual , true );
h . context . __draft = draft ; const input = h . json ( 'recoveryInput(__draft)' ); assert . equal ( input . payment_account , '麦麦信用卡' ); assert . equal ( input . exchange . quantity , '31.234' ); assert . deepEqual ( input . exchange . cost_material ,{ mode : 'pool' , poolId : D }); assert . equal ( input . exchange . cost_labor . rate , '5' ); assert . equal ( input . exchange . depreciation_weight , '18.001' ); assert . equal ( input . exchange . fee_items [ 0 ]. amount , '8.25' ); assert . equal ( input . exchange . fee_items [ 0 ]. payer , 'assistant' );
h . context . __input = input ; assert . doesNotThrow (()=> h . run ( 'validateRecoveryInput(__input)' ));
});
test ( '所有数字缺失、非法值和超精度均报具体字段错误,不产生NaN或误记零' ,()=>{
const h = harness ();
for ( const value of [ '' , undefined , 'NaN' , 'Infinity' , '1e3' , '-1' , '1,000' , '1.0000' ]) assert . throws (()=> h . calculate ( h . input ({... base , incoming_weight : value , melted_weight : '1' })), undefined );
for ( const values of [{ purity : '100.001' },{ melted_weight : '21' },{ buy_rate : '0' },{ buy_total_manual : true , buy_total : '0' },{... swap , fee_amount : 'NaN' },{... swap , charge_amount : 'NaN' }]) assert . throws (()=> h . calculate ( h . input ({... base ,... values })), undefined );
assert . throws (()=> h . calculate ( h . input ({... base , incoming_weight : '100000000' , melted_weight : '100000000' , buy_rate : '1000000000' })), /超出支持范围/ );
const minimum = h . calculate ( h . input ({... swap , incoming_weight : '0.001' , melted_weight : '0.001' , new_quantity : '0.001' , labor_rate : '0' , depreciation_rate : '0' , buy_rate : '' })); assert . equal ( minimum . oldMg , 1 ); assert . equal ( minimum . netSettlement , 0 ); assert . ok ( Object . values ( minimum ). every ( value => typeof value !== 'number' || Number . isFinite ( value )));
});
test ( '前端金额与只读服务端报价逐分一致:成色、补金、余料、折旧改重和整单取整' , t =>{
const l = new Ledger ( ':memory:' ); t . after (()=> l . close ()); const actor = { id : createUser ( l , '合成麦麦' , 'owner' , 'synthetic-ui-password' , 'owner' ), name : '合成麦麦' , role : 'owner' , member : 'owner' }; l . enableTeamMode (); const h = harness ();
for ( const values of [{... base },{... base , incoming_weight : '1.234' , melted_weight : '1.2' , purity : '99.9' , buy_total_manual : true , buy_total : '1079.11' }, swap ,{... swap , incoming_weight : '30' , melted_weight : '30' , new_quantity : '20' , buy_total_manual : true , buy_total : '100.13' , charge_amount : '7.45' , discount : '2.10' , payment_method : '信用卡' },{... swap , depreciation_manual : true , depreciation_weight : '18.001' , labor_mode : 'total' , labor_rate : '123.45' , rounding_mode : 'cent' },{... swap , new_quantity : '20' , gold_price : '0' , labor_rate : '0' , depreciation_rate : '0' , cost_labor_value : '0' , buy_rate : '' }]){
const input = h . input ( values ), client = h . calculate ( input ), server = l . scope ( actor ,()=> l . recoveryQuote ( input , actor ));
for ( const field of [ 'oldMg' , 'newMg' , 'matchedMg' , 'differenceMg' , 'surplusMg' , 'goldAmount' , 'laborAmount' , 'depreciationMg' , 'depreciationAmount' , 'chargesAmount' , 'discount' , 'receivable' , 'purchaseAmount' , 'netSettlement' , 'cashReceipt' , 'cashPayment' ]) assert . equal ( client [ field ], server [ field ], field + ' ' + JSON . stringify ( values ));
}
});
test ( '已保存详情使用服务端分和mg恢复公式与新货货盘,内部成本可查且不显示NaN' , t =>{
const l = new Ledger ( ':memory:' ); t . after (()=> l . close ()); const actor = { id : createUser ( l , '合成麦麦' , 'owner' , 'synthetic-ui-password' , 'owner' ), name : '合成麦麦' , role : 'owner' , member : 'owner' }; l . enableTeamMode (); const h = harness (); const input = h . input ({... swap , charge_amount : '7.45' , fee_amount : '3.21' , fee_payer : 'assistant2' , payment_method : '信用卡' });
const q = l . scope ( actor ,()=> l . recoveryQuote ( input , actor )); h . context . __detail = {... q , id : 'synthetic-recovery' , number : 'HS202610250001' , order_id : 'synthetic-order' , purchase_id : null }; const html = h . run ( 'recoveryDetailHTML(__detail)' );
for ( const text of [ '合成客户' , '足金999' , '现货' , '1,000.00' , '600.00' , '200.00' , '10,807.00' , '64.84' , '内部记账' , '补金差重料费' ]) assert . ok ( html . includes ( text ), text ); assert . doesNotMatch ( html , /NaN|undefined/ ); assert . match ( html , /data-action="recovery-print"/ ); assert . match ( html , /data-action="recovery-open-order"/ );
const actions = h . run ( 'recoveryLinkedOrderActionsHTML({recovery_id:"r"},{reviewAllowed:true})' ); assert . match ( actions , /麦麦复核/ ); assert . doesNotMatch ( actions , /edit-order|show-return|show-expense|show-correct/ );
});
test ( '置换详情省略已核实的零成本行,待核实null仍保留且不改变原成本利润' ,()=>{
const h = harness (), value = { mode : 'exchange' , materialCost : 0 , laborCost : 0 , cardFee : 0 , profit : 0 , exchange : { costPayers : { material : 'owner' , labor : 'assistant' }, fee_items : [{ note : '零包装成本' , amount : 0 , payer : 'owner' },{ note : '实际费用' , amount : 123 , payer : 'assistant2' }]}};
const before = JSON . stringify ( value ); h . context . __detail = value ; let html = h . run ( 'recoveryDetailCostsHTML(__detail)' ); assert . doesNotMatch ( html , /补金差重料费|新货进货工费|信用卡手续费|零包装成本/ ); assert . match ( html , /实际费用/ ); assert . match ( html , /¥1.23/ ); assert . match ( html , /本单实际利润:<strong>¥0.00/ ); assert . equal ( JSON . stringify ( value ), before );
value . materialCost = null ; value . laborCost = null ; value . cardFee = null ; value . exchange . fee_items [ 0 ]. amount = null ; const unknown = JSON . stringify ( value ); html = h . run ( 'recoveryDetailCostsHTML(__detail)' ); for ( const title of [ '补金差重料费' , '新货进货工费' , '信用卡手续费' , '零包装成本' ]) assert . ok ( html . includes ( title )); assert . equal (( html . match ( /待核实/g ) || []). length , 4 ); assert . equal ( JSON . stringify ( value ), unknown );
});
test ( '客户、开单人、确认和进货工费缺失时阻止保存,非法收款账户不能绕过' ,()=>{
const h = harness ();
for ( const values of [{ customer : '' },{ salesperson : '' },{ verified : false },{ cost_labor_value : '' },{ material_rate : '' },{ material_rate : '0' },{ payment_recipient : '伪造' }]){ h . context . __input = h . input ({... swap ,... values }); assert . throws (()=> h . run ( 'validateRecoveryInput(__input)' ));}
});
test ( '回收提交丢失响应仍保留原幂等操作号,重试不换金额或另开一单' , async ()=>{
const h = harness (), input = h . input ({... base }); h . context . __input = input ; h . run ( 'api=async function(url,data,key){__posts.push({url,data,key});throw new Error("响应丢失");};' );
await assert . rejects ( h . run ( 'mutate("/api/recoveries",__input)' ), /提交结果待确认/ ); const pending = JSON . parse ( h . saved . get ( 'mm-pending-' + h . user . id )); assert . equal ( pending . url , '/api/recoveries' ); assert . deepEqual ( pending . data , input ); assert . ok ( pending . key );
h . context . __pending = pending ; h . run ( 'api=async function(url,data,key){__posts.push({url,data,key});return {id:"saved"};};' ); await h . run ( 'mutate(__pending.url,__pending.data,__pending)' ); assert . equal ( h . posts [ 0 ]. key , h . posts [ 1 ]. key ); assert . equal ( h . saved . has ( 'mm-pending-' + h . user . id ), false );
const source = fs . readFileSync ( path . join ( __dirname , '../public/app.js' ), 'utf8' ); assert . match ( source , /p.url==='\/api\/recoveries'.*finishRecoverySave/ );
});
2026-11-24 21:11:32 +08:00
test ( '多商品新货合计参与补金与余料,外配空值保留,工费按每件独立计算' ,()=>{
const h = harness (), extra = { new_name : '足金外配镯' , new_quantity : '18' , pocket : '' , stockCount : '' , labor_mode : 'gram' , labor_rate : '30' , cost_labor_mode : 'total' , cost_labor_value : '90' , labor_payer : 'assistant2' };
const draft = {... swap , new_quantity : '12' , extra_products : [ extra ], verified : true };
const input = h . input ( draft ), calc = h . calculate ( input ); assert . equal ( input . exchange . products . length , 2 ); assert . equal ( input . exchange . products [ 1 ]. pocket , '' ); assert . equal ( input . exchange . products [ 1 ]. cost_labor . amount , '90' );
assert . equal ( calc . newMg , 30000 ); assert . equal ( calc . differenceMg , 10000 ); assert . equal ( calc . laborAmount , 78000 ); assert . equal ( calc . netSettlement , 1098000 );
h . context . __input = input ; assert . doesNotThrow (()=> h . run ( 'validateRecoveryInput(__input)' ));
2026-11-27 15:48:37 +08:00
h . context . __draft = h . draft ( draft ); const html = h . run ( 'recoveryFormHTML(__draft)' ); assert . match ( html , /recovery-add-product/ ); assert . match ( html , /recovery-remove-product/ ); assert . match ( html , /外配(不扣店内库存)/ ); assert . match ( html , /name="extra_new_quantity" value="18"/ ); assert . match ( html , /本件内部成本/ ); assert . match ( html , /name="cost_labor_value"/ ); assert . match ( html , /name="extra_cost_labor_value"/ );
2026-11-24 21:11:32 +08:00
const surplus = h . input ({... draft , incoming_weight : '40' , melted_weight : '40' , buy_rate : '850' }), back = h . calculate ( surplus ); assert . equal ( back . surplusMg , 10000 ); assert . equal ( back . purchaseAmount , 850000 ); assert . equal ( surplus . exchange . cost_material , undefined );
});
2026-11-24 21:56:05 +08:00
test ( '逐件完整置换分别补金与退余料,整单汇总不沿用第一件回收金额' ,()=>{
const h = harness (), second = {... h . draft (), new_name : '第二件' , incoming_weight : '20' , melted_weight : '20' , new_quantity : '12' , buy_rate : '850' , pocket : '' , labor_rate : '30' , depreciation_rate : '5' , cost_labor_mode : 'total' , cost_labor_value : '60' , labor_payer : 'assistant2' };
const draft = {... swap , independent_products : true , incoming_weight : '10' , melted_weight : '10' , new_quantity : '15' , material_rate : '800' , extra_products : [ second ]}, input = h . input ( draft ), q = h . calculate ( input );
assert . equal ( q . differenceMg , 5000 ); assert . equal ( q . surplusMg , 8000 ); assert . equal ( q . netSettlement , - 98000 ); assert . equal ( q . purchaseAmount , 680000 ); assert . equal ( input . exchange . items [ 1 ]. exchange . pocket , '' );
2026-11-28 01:28:39 +08:00
h . context . __input = input ; assert . doesNotThrow (()=> h . run ( 'validateRecoveryInput(__input)' )); h . context . __draft = h . draft ( draft ); const html = h . run ( 'recoveryItemsFormHTML(__draft)' );
2026-11-24 21:56:05 +08:00
for ( const name of [ 'incoming_weight' , 'melted_weight' , 'purity' , 'old_pocket' , 'buy_rate' , 'buy_total' , 'gold_price' , 'depreciation_rate' , 'depreciation_weight' , 'material_source' , 'material_pool_id' , 'material_rate' , 'material_payer' ]){ assert . ok ( html . includes ( 'name="' + name + '"' )); assert . ok ( html . includes ( 'name="extra_' + name + '"' ));}
assert . equal (( html . match ( /data-recovery-item=/g ) || []). length , 2 );
const discounted = h . calculate ( h . input ({... draft , discount : '5500' })); assert . equal ( discounted . receivable , 32000 ); assert . equal ( discounted . netSettlement , - 648000 );
});
2026-11-26 01:01:18 +08:00
test ( '寄存料按使用克重生成置换旧料,独立商品可混合本次来料,互不串来源' ,()=>{
const h = harness (), extra = {... h . draft (), new_name : '第二件' , incoming_weight : '0.5' , melted_weight : '0.5' , new_quantity : '0.5' , labor_rate : '20' , cost_labor_value : '0' , gold_price : '0' };
const input = h . input ({... swap , independent_products : true , old_source : 'deposit' , deposit_id : 'synthetic-deposit' , deposit_weight : '1' , incoming_weight : '' , melted_weight : '' , new_quantity : '1' , gold_price : '0' , extra_products : [ extra ]});
assert . equal ( input . old_source , undefined ); assert . equal ( input . exchange . items [ 0 ]. deposit_weight , '1' ); assert . equal ( input . exchange . items [ 0 ]. old_lines [ 0 ]. melted_weight , '1' ); assert . equal ( input . exchange . items [ 1 ]. old_source , undefined ); assert . equal ( h . calculate ( input ). oldMg , 1500 ); h . context . __input = input ; assert . doesNotThrow (()=> h . run ( 'validateRecoveryInput(__input)' ));
h . context . __draft = h . draft ({... swap , independent_products : true }); const html = h . run ( 'recoveryFormHTML(__draft)' ); assert . match ( html , /寄存,暂不结算/ ); assert . match ( html , /name="old_source"/ ); assert . match ( html , /name="deposit_id"/ ); assert . match ( html , /name="deposit_weight"/ );
});
2026-11-26 01:15:41 +08:00
test ( '余料处理可选寄存,取消隐藏旧回收款;每件独立选择,不继承第一件寄存' ,()=>{
const h = harness (), draft = {... swap , incoming_weight : '10' , melted_weight : '10' , new_quantity : '8.561' , surplus_mode : 'deposit' , surplus_memo : '袋B' , buy_rate : '' , buy_total : '1100.40' , buy_total_manual : true };
const input = h . input ( draft ), q = h . calculate ( input ); assert . equal ( q . depositMg , 1439 ); assert . equal ( q . purchaseMg , 0 ); assert . equal ( q . purchaseAmount , 0 ); assert . equal ( q . netSettlement , q . receivable ); assert . equal ( input . surplus_memo , '袋B' ); h . context . __q = q ; h . context . __input = input ; assert . match ( h . run ( 'recoverySettlementHTML(__q,__input)' ), /余料寄存:1.439g/ );
h . context . __draft = h . draft ({... draft , independent_products : true , extra_products : [ h . draft ({... swap , incoming_weight : '3' , melted_weight : '3' , new_quantity : '2' , buy_rate : '850' })]});
const mixed = h . json ( 'recoveryInput(__draft)' ), total = h . calculate ( mixed ); assert . equal ( mixed . exchange . items [ 1 ]. surplus_mode , undefined ); assert . equal ( total . depositMg , 1439 ); assert . equal ( total . purchaseMg , 1000 ); assert . equal ( total . purchaseAmount , 85000 );
2026-11-28 01:28:39 +08:00
const html = h . run ( 'recoveryItemsFormHTML(__draft)' ); assert . match ( html , /name="surplus_mode"/ ); assert . match ( html , /name="extra_surplus_mode"/ ); assert . match ( html , /添加到寄存料,暂不结算/ ); assert . match ( html , /data-surplus-buy/ );
2026-11-26 01:15:41 +08:00
});
2026-11-27 15:48:37 +08:00
test ( '新建默认一份旧料换多件新货,旧料和寄存选择只出现一次,工费及货盘逐件完整' ,()=>{
const h = harness (); assert . equal ( h . json ( 'recoveryStoredDraft()' ). independent_products , false ); assert . equal ( h . draft ({ mode : 'exchange' }). independent_products , false );
const extra = h . draft ({ new_name : '足金戒指' , new_quantity : '3' , pocket : '' , labor_rate : '20' , cost_labor_value : '3' , labor_payer : 'assistant' }), draft = h . draft ({... swap , new_quantity : '15' , labor_rate : '25' , surplus_mode : 'deposit' , surplus_memo : '共享旧料余2克' , extra_products : [ extra ]}); h . context . __draft = draft ;
const input = h . json ( 'recoveryInput(__draft)' ), q = h . calculate ( input ); assert . equal ( input . old_lines . length , 1 ); assert . equal ( input . exchange . items , undefined ); assert . equal ( input . exchange . products . length , 2 ); assert . equal ( q . oldMg , 20000 ); assert . equal ( q . newMg , 18000 ); assert . equal ( q . depositMg , 2000 ); assert . equal ( q . receivable , 61500 );
const html = h . run ( 'recoveryFormHTML(__draft)' ); assert . equal (( html . match ( /name="incoming_weight"/g ) || []). length , 1 ); assert . equal (( html . match ( /name="surplus_mode"/g ) || []). length , 1 ); assert . equal (( html . match ( /name="cost_labor_value"/g ) || []). length , 1 ); assert . match ( html , /name="extra_cost_labor_value"/ ); assert . match ( html , /name="extra_pocket"/ ); assert . doesNotMatch ( html , /name="extra_incoming_weight"|recovery-upgrade-items/ ); assert . match ( html , /上方旧料只录一次/ );
h . saved . set ( 'mm-recovery-draft-' + h . user . id , JSON . stringify ({... draft , independent_products : true , extra_products : []})); assert . equal ( h . json ( 'recoveryStoredDraft()' ). independent_products , false );
});
2026-11-28 01:28:39 +08:00
test ( '已缓存的多商品逐件草稿恢复成一份来料,保留新货并备份原草稿,刷新不会再次重复' ,()=>{
const h = harness (), second = h . draft ({... swap , incoming_weight : '20' , melted_weight : '20' , new_name : '足金戒指' , new_quantity : '3' , pocket : '' , labor_rate : '20' , cost_labor_value : '3' }), legacy = h . draft ({... swap , independent_products : true , new_name : '足金手镯' , new_quantity : '15' , surplus_mode : 'deposit' , extra_products : [ second ], verified : true , buy_total_manual : true , buy_total : '999' , depreciation_manual : true });
const key = 'mm-recovery-draft-' + h . user . id ; h . saved . set ( key , JSON . stringify ( legacy )); const converted = h . json ( 'recoveryStoredDraft()' ); assert . equal ( converted . independent_products , false ); assert . equal ( converted . incoming_weight , '20' ); assert . equal ( converted . extra_products [ 0 ]. incoming_weight , undefined ); assert . equal ( converted . extra_products [ 0 ]. new_quantity , '3' ); assert . equal ( converted . extra_products [ 0 ]. pocket , '' ); assert . equal ( converted . verified , false ); assert . equal ( converted . buy_total_manual , false ); assert . equal ( converted . depreciation_manual , false ); assert . deepEqual ( JSON . parse ( h . saved . get ( key + '-before-shared-old' )), legacy );
h . context . __draft = converted ; const input = h . json ( 'recoveryInput(__draft)' ), q = h . calculate ( input ); assert . equal ( input . exchange . items , undefined ); assert . equal ( input . exchange . products . length , 2 ); assert . equal ( q . oldMg , 20000 ); assert . equal ( q . newMg , 18000 ); assert . equal ( q . depositMg , 2000 );
const html = h . run ( 'recoveryFormHTML(__draft)' ); assert . equal (( html . match ( /name="incoming_weight"/g ) || []). length , 1 ); assert . doesNotMatch ( html , /extra_incoming_weight|data-independent-products="true"/ ); assert . match ( html , /置换新货 2/ ); assert . deepEqual ( h . json ( 'recoveryStoredDraft()' ), converted );
});