2026-10-26 14:44:07 +08:00
'use strict' ;
let recoveryListRequest = 0 , recoveryQuoteRequest = 0 , recoveryQuoteTimer = null , recoveryDetailRequest = 0 , recoveryDetail = null , recoveryFilters = null , recoveryFilterUser = '' ;
const recoveryModeNames = { direct : '� 湔𦻖� 墧𤣰' , exchange : '蝵格揢' };
2026-11-28 01:28:39 +08:00
const recoveryDraftFields = [ 'shared_old_notice' , 'surplus_mode' , 'surplus_memo' , 'old_source' , 'deposit_id' , 'deposit_weight' , 'mode' , 'date' , 'customer' , 'salesperson' , 'member' , 'old_name' , 'incoming_weight' , 'melted_weight' , 'purity' , 'old_pocket' , 'old_stock_count' , 'buy_rate' , 'buy_total' , 'new_name' , 'new_quantity' , 'pocket' , 'stockCount' , 'gold_price' , 'labor_mode' , 'labor_rate' , 'depreciation_weight' , 'depreciation_rate' , 'charge_name' , 'charge_amount' , 'discount' , 'rounding_mode' , 'material_source' , 'material_pool_id' , 'material_rate' , 'material_payer' , 'cost_labor_mode' , 'cost_labor_value' , 'labor_payer' , 'fee_note' , 'fee_amount' , 'fee_payer' , 'payment_method' , 'payment_recipient' , 'payout_method' , 'payer' , 'note' ];
2026-10-26 14:44:07 +08:00
const recoveryText = value => String ( value ?? '' ). trim ();
const recoveryDraftKey = ()=> `mm-recovery-draft- ${ state . user . id } ` ;
const recoveryUser = ()=> state ? . user ? . id || '' ;
const recoveryPrefix = member =>({ owner : '暻阡漲' , assistant : '� 拍� ' , assistant2 : '� 拍� 2' })[ member ] || '暻阡漲' ;
const recoveryMoney = value => value == null ? '敺� ‵ � � ' : '瞼' + yuan ( value );
function recoveryUnits ( value , places , title ,{ zero = true } = {}){
const raw = recoveryText ( value ), pattern = new RegExp ( '^\\d+(?:\\.\\d{1,' + places + '})?$' );
if ( ! pattern . test ( raw )) throw new Error ( ` ${ title } 霂瑕‵� � ${ zero ? '銝滚� 鈭� 0' : '憭找� 0' } � � 㺭摮梹� � � 憭帋� � � ${ places } 雿滚� � 啜� � );
const [whole,fraction='']=raw.split('.'),units=BigInt(whole)*10n**BigInt(places)+BigInt(fraction.padEnd(places,'0'));
if(units>100000000000n||!zero&&units===0n)throw new Error(` $ { title } 頞 � 枂 � � 凒 � 硋 � � 芸 ‵ � 踺 � � );
return Number ( units );
}
function recoveryLimit ( value , title = '� 墧𤣰嚗讐蔭� W � 霈� ' ){ if ( ! Number . isSafeInteger ( value ) || Math . abs ( value ) > 100000000000 ) throw new Error ( title + '頞� 枂� 舀� � � 凒嚗諹窈� 詨笆� � ' ); return value ;}
function recoveryMul ( weight , rate ){ return recoveryLimit ( Number (( BigInt ( weight ) * BigInt ( rate ) + 500 n ) / 1000 n ));}
2026-11-16 23:03:36 +08:00
function recoveryCardRate (){ return typeof recoveryEditEntry !== 'undefined' && recoveryEditEntry ? recoveryEditEntry . data ? . record ? . credit_card_rate_permille ?? configuredCreditCardRate () : configuredCreditCardRate ();}
2026-11-24 21:11:32 +08:00
const recoveryProductFields = [ 'new_name' , 'new_quantity' , 'pocket' , 'stockCount' , 'labor_mode' , 'labor_rate' , 'cost_labor_mode' , 'cost_labor_value' , 'labor_payer' ];
function recoveryProductInput ( draft ){ return { name : draft . new_name , quantity : draft . new_quantity , pocket : draft . pocket ,...( pocketCountsEnabled ( draft . pocket ) ? { stockCount : draft . stockCount || null } : {}), labor_mode : draft . labor_mode , labor_rate : draft . labor_rate ,...( draft . cost_labor_value !== '' ? { cost_labor : draft . cost_labor_mode === 'total' ? { mode : 'total' , amount : draft . cost_labor_value } : { mode : 'gram' , rate : draft . cost_labor_value }} : {}), cost_labor_payer : draft . labor_payer };}
function recoveryProductDraft ( row ){ return { new_name : row . name , new_quantity : row . quantity , pocket : row . pocket , stockCount : row . stockCount ?? '' , labor_mode : row . labor_mode , labor_rate : row . labor_rate , cost_labor_mode : row . cost_labor ? . mode || 'total' , cost_labor_value : row . cost_labor ? . mode === 'gram' ? row . cost_labor . rate : row . cost_labor ? . amount ?? '' , labor_payer : row . cost_labor_payer };}
function recoveryNewWeight ( draft ){ return [ draft ,...( draft . extra_products || [])]. reduce (( n , row )=> recoveryLimit ( n + recoveryUnits ( row . new_quantity , 3 , '� 啗揮� 钅� ' ,{ zero : false })), 0 );}
2026-11-24 21:56:05 +08:00
// 蝚砌� 隞嗡� � 啣� � � � � 梁鍂� � � 摮埈挾嚗䔶� � � � 䠷� 匧� 蝘啜� � 揮� 睃� 霈∟晶� 厰★銝� � 氬� �
function recoveryProductFieldsHTML ( row ,{ prefix = '' , original = null } = {}){
const name = key => prefix + key ;
return `<div class="recovery-row recovery-new-fields"><label>� 啗揮� � � <input name=" ${ name ( 'new_name' ) } " value=" ${ e ( row . new_name ) } " list="recovery-product-names" maxlength="60" required></label> ${ recoveryNumberField ( '� 啗揮� 钅� 嚗ā嚗� ' , name ( 'new_quantity' ), row . new_quantity , 3 , 'required' ) }${ pocketChoice ( '� 箄揮韐抒� ' , name ( 'pocket' ), row . pocket ,{ blank : '憭㚚� 嚗� � � � � � � � 摮矋� ' , historical :!! original && original . pocket === row . pocket } )} ${ stockCountField ( row . pocket , row . stockCount ,{ name : name ( 'stockCount' ), help : '' , optional :!! original && original . stockCount == null } )} ${ choice ( '� � � 桀極韐寞䲮撘� ' , name ( 'labor_mode' ),[[ 'gram' , '� 匧� ' ],[ 'total' , '� 駁� ' ]], row . labor_mode ) }${ recoveryNumberField ( row . labor_mode === 'total' ? '� � � 桀極韐對� � � � ' : '� � � 桀極韐對� � � � g嚗� ' , name ( 'labor_rate' ), row . labor_rate , 2 , 'required' ) } </div>` ;
}
function recoveryProductLaborHTML ( row ,{ prefix = '' } = {}){
return `<div class="recovery-row"> ${ choice ( '餈𥡝揮撌亥晶� 孵� ' , prefix + 'cost_labor_mode' ,[[ 'gram' , '� 㗇𧋦隞嗆鰵韐批� � � ' ],[ 'total' , '� 駁� ' ]], row . cost_labor_mode ) }${ recoveryNumberField ( row . cost_labor_mode === 'total' ? '餈𥡝揮撌亥晶嚗� � 嚗� ' : '餈𥡝揮撌亥晶嚗� � 嚗𣲵嚗� ' , prefix + 'cost_labor_value' , row . cost_labor_value , 2 , 'required placeholder="瘝⊥� � 𤑳� 霂瑕‵0"' ) }${ choice ( '撌亥晶隞䀹狡鈭� ' , prefix + 'labor_payer' , teamMemberOptions (), row . labor_payer ) } </div>` ;
}
2026-11-24 21:11:32 +08:00
function recoveryExtraProductHTML ( row , index ){
const original = typeof recoveryEditEntry !== 'undefined' ? recoveryEditEntry ? . data ? . inputs ? . exchange ? . products ? .[ index + 1 ] : null ;
2026-11-28 01:28:39 +08:00
return `<section class="recovery-new-product" data-recovery-product=" ${ index } "><div class="panel-title"><h3>蝵格揢� 啗揮 ${ index + 2 } </h3> ${ button ( '蝘駁膄� � � ' , 'recovery-remove-product' , 'quiet' , `data-index=" ${ index } "` ) } </div> ${ recoveryProductFieldsHTML ( row ,{ prefix : 'extra_' , original } )}<div class="internal recovery-product-cost"><h4>� 砌辣� � � � 鞉𧋦</h4> ${ recoveryProductLaborHTML ( row ,{ prefix : 'extra_' } )}</div></section>` ;
2026-11-24 21:11:32 +08:00
}
2026-10-26 14:44:07 +08:00
function recoveryDefaults ( mode = 'direct' ){
const member = currentMember ();
2026-11-27 15:48:37 +08:00
return { independent_products : false , surplus_mode : 'buy' , surplus_memo : '' , old_source : 'incoming' , deposit_id : '' , deposit_weight : '' , mode , date : state . today , customer : '' , salesperson : defaultSalesperson (), member , old_name : 'Au� 扳� ' , incoming_weight : '' , melted_weight : '' , purity : '100' , old_pocket : '� 墧𤣰� 扳� ' , old_stock_count : '' , buy_rate : '' , buy_total : '' , new_name : '頞喲� 999' , new_quantity : '' , pocket : '� 啗揮' , stockCount : '' , gold_price : '' , labor_mode : 'gram' , labor_rate : '' , depreciation_weight : '' , depreciation_rate : '10' , charge_name : '� 嗡� � 嗉晶' , charge_amount : '0' , discount : '0' , rounding_mode : 'yuan' , material_source : 'pool' , material_pool_id : state . today , material_rate : '' , material_payer : member , cost_labor_mode : 'gram' , cost_labor_value : '' , labor_payer : member , fee_note : '� 嗡� 韐寧鍂' , fee_amount : '0' , fee_payer : member , payment_method : '敺桐縑' , payment_recipient : recoveryPrefix ( member ), payout_method : '敺桐縑' , payer : member , note : '' , buy_total_manual : false , depreciation_manual : false , melted_manual : false };
2026-10-26 14:44:07 +08:00
}
function recoveryStoredDraft (){
let value ; try { value = JSON . parse ( localStorage . getItem ( recoveryDraftKey ()) || 'null' );} catch {}
2026-11-28 01:28:39 +08:00
let draft = {... recoveryDefaults (),...( value && typeof value === 'object' ? value : {})};
if ( draft . independent_products ){
try { if ( ! localStorage . getItem ( recoveryDraftKey () + '-before-shared-old' )) localStorage . setItem ( recoveryDraftKey () + '-before-shared-old' , JSON . stringify ( draft ));} catch {}
draft = recoverySharedOldDraft ( draft );
try { localStorage . setItem ( recoveryDraftKey (), JSON . stringify ( draft ));} catch {}
}
2026-10-26 14:44:07 +08:00
if ( ! Object . hasOwn ( recoveryModeNames , draft . mode )) draft . mode = 'direct' ;
if ( state . user . role !== 'owner' ) draft . member = currentMember ();
return draft ;
}
2026-11-28 01:28:39 +08:00
// � 啣遣� 厩阮蝏煺� � 芯� � 嗘� � 嫣� 隞賣䔉� 辷� � 𡒊賒銵䔶� 靽萘� � 啗揮摮埈挾� �
function recoverySharedOldDraft ( draft ){
if ( ! draft . independent_products ) return draft ;
return {... draft , independent_products : false , extra_products : ( draft . extra_products || []). map ( row => Object . fromEntries ( recoveryProductFields . map ( k =>[ k , row [ k ]]))),...( draft . extra_products ? . length ? { buy_total_manual : false , buy_total : '' , depreciation_manual : false } : {}), verified : false , shared_old_notice : draft . extra_products ? . length ? '撌脫� 憭滢蛹銝� 隞賣䔉� 辷� 瘝輻鍂銝𦠜䲮蝚砌� 隞賣䔉� 辷� 霂瑟瓲撖孵� � � � 餃� � 溻� � ' : '' };
}
2026-10-26 14:44:07 +08:00
function recoveryField ( form , name ){ return form ? . elements ? . namedItem ? .( name ) || form ? . elements ? .[ name ] || form ? . querySelector ? .( `[name=" ${ name } "]` );}
function recoveryFormDraft ( form ){
2026-11-24 21:56:05 +08:00
if ( form ? . dataset ? . independentProducts === 'true' ) return recoveryItemsFormDraft ( form );
2026-10-26 14:44:07 +08:00
const draft = Object . fromEntries ( recoveryDraftFields . map ( name =>[ name , recoveryText ( recoveryField ( form , name ) ? . value )]));
for ( const name of [ 'buy_total_manual' , 'depreciation_manual' , 'melted_manual' ]) draft [ name ] = form . dataset [ name ] === 'true' ;
2026-11-24 21:56:05 +08:00
draft . verified =!! recoveryField ( form , 'verified' ) ? . checked ; if ( form . dataset . independentDefault === 'true' ) draft . independent_products = true ;
2026-11-24 21:11:32 +08:00
draft . extra_products = [...( form . querySelectorAll ? .( '[data-recovery-product]' ) || [])]. map ( row => Object . fromEntries ( recoveryProductFields . map ( name =>[ name , recoveryText ( row . querySelector ( '[name="extra_' + name + '"]' ) ? . value )])));
2026-10-26 14:44:07 +08:00
if ( state . user . role !== 'owner' ) draft . member = currentMember ();
2026-11-04 22:18:56 +08:00
if ( form . dataset ? . recoveryEdit === 'true' && typeof recoveryEditFormDraft === 'function' ) return recoveryEditFormDraft ( form , draft );
2026-10-26 14:44:07 +08:00
return draft ;
}
2026-11-04 22:18:56 +08:00
function rememberRecoveryDraft ( form = $ ( '#recovery-form' )){ if ( form ? . dataset ? . recoveryEdit === 'true' && typeof rememberRecoveryEditDraft === 'function' ) return rememberRecoveryEditDraft ( form ); if ( form ) try { localStorage . setItem ( recoveryDraftKey (), JSON . stringify ( recoveryFormDraft ( form )));} catch {}}
2026-10-26 14:44:07 +08:00
function recoveryInput ( draft ,{ quote = false } = {}){
2026-11-24 21:56:05 +08:00
if ( draft . mode === 'exchange' && draft . independent_products ) return recoveryItemsInput ( draft ,{ quote });
2026-11-26 01:01:18 +08:00
if ( draft . mode === 'exchange' && draft . old_source === 'deposit' ) draft = {... draft , old_lines : customerMaterialOldLines ( draft )};
2026-10-26 14:44:07 +08:00
const member = state . user . role === 'owner' ? draft . member : currentMember ();
2026-11-24 21:11:32 +08:00
const input = { mode : draft . mode , date : draft . date , customer : draft . customer , salesperson : draft . salesperson , member , note : draft . note , old_pocket : draft . old_pocket ?? '� 墧𤣰� 扳� ' ,...( pocketCountsEnabled ( draft . old_pocket ) ? { old_stock_count : recoveryText ( draft . old_stock_count ) || null } : {}), old_lines : Array . isArray ( draft . old_lines ) ? draft . old_lines : [{ name : draft . old_name || 'Au� 扳� ' , incoming_weight : draft . incoming_weight , melted_weight : draft . melted_weight , purity : draft . purity }], buy_rate : draft . buy_rate , payer : draft . payer || member , payment_account : recoveryPrefix ( draft . payer || member ) + ( draft . payout_method || '敺桐縑' ), verified :! quote && draft . verified === true };
2026-11-26 01:01:18 +08:00
if ( draft . mode === 'exchange' && draft . old_source === 'deposit' ) Object . assign ( input ,{ old_source : 'deposit' , deposit_id : draft . deposit_id , deposit_weight : draft . deposit_weight });
2026-10-26 14:44:07 +08:00
if ( draft . buy_total_manual && draft . buy_total !== '' ) input . buy_total = draft . buy_total ;
2026-11-26 01:15:41 +08:00
if ( draft . mode === 'exchange' && draft . surplus_mode === 'deposit' ) Object . assign ( input ,{ surplus_mode : 'deposit' , surplus_memo : draft . surplus_memo || '' , buy_rate : '0' , buy_total : '0' });
2026-10-26 14:44:07 +08:00
if ( draft . mode === 'exchange' ){
const costLabor = draft . cost_labor_value === '' ? undefined : draft . cost_labor_mode === 'total' ? { mode : 'total' , amount : draft . cost_labor_value } : { mode : 'gram' , rate : draft . cost_labor_value };
const costMaterial = draft . material_source === 'pool' ? { mode : 'pool' , poolId : draft . material_pool_id || draft . date } : draft . material_rate === '' ? undefined : { mode : 'gram' , rate : draft . material_rate };
2026-11-08 15:47:07 +08:00
input . exchange = { name : draft . new_name , quantity : draft . new_quantity , pocket : draft . pocket ,...( pocketCountsEnabled ( draft . pocket ) ? { stockCount : draft . stockCount == null || String ( draft . stockCount ). trim () === '' ? null : draft . stockCount } : {}), gold_price : draft . gold_price , labor_mode : draft . labor_mode , labor_rate : draft . labor_rate , depreciation_rate : draft . depreciation_rate || '0' ,...( draft . depreciation_manual ? { depreciation_weight : draft . depreciation_weight } : {}),...( costMaterial ? { cost_material : costMaterial } : {}),...( costLabor ? { cost_labor : costLabor } : {}), cost_payer : draft . cost_payer || draft . labor_payer || member , cost_material_payer : draft . material_payer || member , cost_labor_payer : draft . labor_payer || member , charges : Array . isArray ( draft . charges ) ? draft . charges : recoveryText ( draft . charge_amount ) && recoveryUnits ( draft . charge_amount , 2 , '� 嗡� � 嗉晶' ) > 0 ? [{ name : draft . charge_name || '� 嗡� � 嗉晶' , amount : draft . charge_amount }] : [], fee_items : Array . isArray ( draft . fee_items ) ? draft . fee_items : recoveryText ( draft . fee_amount ) && recoveryUnits ( draft . fee_amount , 2 , '� 嗡� � � � 韐寧鍂' ) > 0 ? [{ key : 'other' , note : draft . fee_note || '� 嗡� 韐寧鍂' , amount : draft . fee_amount , payer : draft . fee_payer || member }] : [], discount : draft . discount || '0' , rounding_mode : draft . rounding_mode || 'yuan' };
2026-11-24 21:11:32 +08:00
if ( draft . extra_products ? . length ) input . exchange . products = [ draft ,... draft . extra_products ]. map ( recoveryProductInput );
const old = recoveryCalculate ({... input , mode : 'direct' , buy_rate : '1' , buy_total : '1' }), newMg = recoveryNewWeight ( draft );
2026-10-26 14:44:07 +08:00
if ( newMg >= old . oldMg ){ input . buy_rate = '0' ; input . buy_total = '0' ;}
if ( newMg <= old . oldMg ){ input . exchange . gold_price = '0' ; delete input . exchange . cost_material ;}
const calculation = recoveryCalculate ( input );
if ( calculation . netSettlement > 0 ) input . payment_account = draft . payment_method === '靽∠鍂� � ' ? '暻阡漲靽∠鍂� � ' : ( draft . payment_recipient || recoveryPrefix ( member )) + ( draft . payment_method || '敺桐縑' );
}
return input ;
}
function recoveryCalculate ( input ){
2026-11-24 21:56:05 +08:00
if ( input . mode === 'exchange' && input . exchange ? . items ) return recoveryItemsCalculate ( input );
2026-10-26 14:44:07 +08:00
if ( ! Object . hasOwn ( recoveryModeNames , input . mode )) throw new Error ( '霂琿� 㗇𥋘� 湔𦻖� 墧𤣰� 𣇉蔭� U� � ' );
const oldLines = ( input . old_lines || []). map ( line =>{
const incomingMg = recoveryUnits ( line . incoming_weight , 3 , '� 交� � 漤� ' ,{ zero : false }), meltedMg = recoveryUnits ( line . melted_weight , 3 , '� 𥪜� � 漤� ' ,{ zero : false }), purity = recoveryUnits ( line . purity , 3 , '� 鞱𠧧' ,{ zero : false });
if ( meltedMg > incomingMg ) throw new Error ( '� 𥪜� � 漤� 銝滩� 憭找� � 交� � 漤� 嚗諹窈� 詨笆� � ' );
if ( purity > 100000 ) throw new Error ( '� 鞱𠧧霂瑕‵� � 0� � 100銋钅𡢿� � 蓡� � 㺭嚗䔶� 憒� 99銵函內99%� � ' );
const foldedMg = Number (( BigInt ( meltedMg ) * BigInt ( purity ) + 50000 n ) / 100000 n );
if ( foldedMg <= 0 ) throw new Error ( '� 睃� � 漤� 憿餉秐撠睲蛹0.001g嚗諹窈� 詨笆� 漤� � 峕� � 脯� � ' );
return {... line , incomingMg , meltedMg , purity : purity / 1000 , foldedMg };
});
if ( ! oldLines . length ) throw new Error ( '霂瑕‵� 蹱唂� 䠷� � 譌� � ' );
const oldMg = recoveryLimit ( oldLines . reduce (( sum , line )=> sum + line . foldedMg , 0 ), '� 扳� � 駁� � � ' ), buyRate = recoveryUnits ( input . buy_rate , 2 , '� 墧𤣰� 蓥遠' );
let newMg = 0 , matchedMg = 0 , differenceMg = 0 , surplusMg = oldMg , goldAmount = 0 , laborAmount = 0 , depreciationMg = 0 , depreciationAmount = 0 , chargesAmount = 0 , discount = 0 , receivable = 0 , roundingAdjustment = 0 ;
if ( input . mode === 'exchange' ){
2026-11-24 21:11:32 +08:00
const x = input . exchange || {}; newMg = x . products ? recoveryLimit ( x . products . reduce (( n , row )=> n + recoveryUnits ( row . quantity , 3 , '� 啗揮� 钅� ' ,{ zero : false }), 0 )) : recoveryUnits ( x . quantity , 3 , '� 啗揮� 钅� ' ,{ zero : false }); matchedMg = Math . min ( oldMg , newMg ); differenceMg = Math . max ( 0 , newMg - oldMg ); surplusMg = Math . max ( 0 , oldMg - newMg );
2026-10-26 14:44:07 +08:00
const goldPrice = differenceMg > 0 ? recoveryUnits ( x . gold_price , 2 , '敶枏予� � � 桅� 隞� ' ) : 0 , laborRate = recoveryUnits ( x . labor_rate , 2 , '� � � 桀極韐� ' ), depreciationRate = recoveryUnits ( x . depreciation_rate ?? '10' , 2 , '� 䀹唂韐孵� 隞� ' );
if ( differenceMg > 0 && goldPrice <= 0 ) throw new Error ( '� 㕑‘� 穃榆� 齿𧒄嚗諹窈憛怠� 憭找� 0� � � 憭拚� � 桅� 隞瑯� � ' );
2026-11-24 21:11:32 +08:00
goldAmount = recoveryMul ( differenceMg , goldPrice ); laborAmount = x . products ? recoveryLimit ( x . products . reduce (( n , row )=>{ const rate = recoveryUnits ( row . labor_rate , 2 , '� � � 桀極韐� ' ); return n + ( row . labor_mode === 'total' ? rate : recoveryMul ( recoveryUnits ( row . quantity , 3 , '� 啗揮� 钅� ' ), rate ));}, 0 )) : x . labor_mode === 'total' ? laborRate : recoveryMul ( newMg , laborRate );
2026-10-26 14:44:07 +08:00
depreciationMg = x . depreciation_weight == null ? matchedMg : recoveryUnits ( x . depreciation_weight , 3 , '� 䀹唂韐寡恣韐孵� � � ' ); depreciationAmount = recoveryMul ( depreciationMg , depreciationRate );
chargesAmount = recoveryLimit (( x . charges || []). reduce (( sum , row )=> sum + recoveryUnits ( row . amount , 2 , '� 嗡� � 嗉晶' ), 0 )); discount = recoveryUnits ( x . discount || '0' , 2 , '隡䀹� � 煾� ' );
const before = recoveryLimit ( goldAmount + laborAmount + depreciationAmount + chargesAmount ) - discount ; if ( before < 0 ) throw new Error ( '隡䀹� � 煾� 銝滩� 憭找� � 祆活蝵格揢韐寧鍂� � ' );
receivable = x . rounding_mode === 'yuan' ? Math . floor (( before + 50 ) / 100 ) * 100 : before ; roundingAdjustment = receivable - before ;
}
2026-11-26 01:15:41 +08:00
const depositMg = input . mode === 'exchange' && input . surplus_mode === 'deposit' ? surplusMg : 0 , purchaseMg = surplusMg - depositMg ;
if ( purchaseMg > 0 && buyRate <= 0 ) throw new Error ( '� 匧� � 嗆唂� 蹱� 雿蹱� � 塚� 霂瑕‵� 坔之鈭� 0� � � � 嗅� 隞瑯� � ' );
const defaultPurchaseAmount = recoveryMul ( purchaseMg , buyRate ), purchaseAmount = depositMg ? 0 : input . buy_total == null ? defaultPurchaseAmount : recoveryUnits ( input . buy_total , 2 , input . mode === 'direct' ? '� 墧𤣰蝏梶� 憸� ' : '雿蹱� � 墧𤣰甈� ' );
if ( purchaseMg > 0 && purchaseAmount <= 0 ) throw new Error ( '� 墧𤣰蝏梶� � 煾� 憿餃之鈭� 0嚗諹窈� 詨笆� � ' );
2026-10-26 14:44:07 +08:00
if ( ! surplusMg && purchaseAmount ) throw new Error ( '� 祆活瘝⊥� 雿蹱� 嚗䔶� � 坔� � 嗆狡摨𥪯蛹0� � ' );
const netSettlement = recoveryLimit ( receivable - purchaseAmount );
2026-11-26 01:15:41 +08:00
return { mode : input . mode , old_lines : oldLines , oldMg , newMg , matchedMg , differenceMg , surplusMg , depositMg , purchaseMg , goldAmount , laborAmount , depreciationMg , depreciationAmount , chargesAmount , discount , receivable , purchaseAmount , defaultPurchaseAmount , roundingAdjustment , netSettlement , cashReceipt : Math . max ( 0 , netSettlement ), cashPayment : Math . max ( 0 , - netSettlement )};
2026-10-26 14:44:07 +08:00
}
2026-11-24 21:56:05 +08:00
function recoveryValidationOriginal ( input ){ const source = recoveryEditEntry ? . data ? . inputs , item = source ? . exchange ? . items ? .[ input . _recoveryItemIndex ]; return item ? {... source ,... item } : source ;}
2026-10-26 14:44:07 +08:00
function validateRecoveryInput ( input ){
2026-11-24 21:56:05 +08:00
if ( input . exchange ? . items ){ for ( const [ index , row ] of input . exchange . items . entries ()) validateRecoveryInput ({... input ,... row , _recoveryItemIndex : index , buy_total : row . buy_total , buy_rate : row . buy_rate , exchange : row . exchange , payment_account : recoveryPrefix ( input . payer ) + '敺桐縑' }); if ( ! state . accounts . includes ( input . payment_account )) throw new Error ( '霂琿� 㗇𥋘� 㗇� � 嗡� 甈曇揭� � ' ); return input ;}
2026-10-26 14:44:07 +08:00
if ( ! validOrderDate ( input . date ) || input . date > state . today ) throw new Error ( '銝𡁜𦛚� 交� 霂琿� 㗇𥋘隞𠰴予� 碶� � 滨� � 㗇� � 交� � � ' );
if ( ! input . customer || input . customer . length > 60 ) throw new Error ( '霂瑕‵� � 1嚚� 60摮㛖� 摰X� 蝘啣鐤� 碶誨� 瑯� � ' );
if ( ! input . salesperson || input . salesperson . length > 30 ) throw new Error ( '霂瑕‵� � 1嚚� 30摮㛖� 撘� � 蓥犖� � ' );
if ( input . note . length > 240 ) throw new Error ( '憭� 釣� � 憭𡁜‵� � 240摮𨰜� � ' );
if ( ! teamMemberKeys . includes ( input . member ) ||! teamMemberKeys . includes ( input . payer )) throw new Error ( '霂琿� 㗇𥋘敶鍦� � 𣂼� � � � � � � 甈曆犖� � ' );
const calculation = recoveryCalculate ( input );
2026-11-08 03:30:58 +08:00
const editing = typeof recoveryEditEntry !== 'undefined' && recoveryEditEntry && $ ( '#recovery-form' ) ? . dataset . recoveryEdit === 'true' ;
2026-11-24 21:56:05 +08:00
const oldPocket = input . old_pocket ?? '� 墧𤣰� 扳� ' , oldOriginal = editing ? recoveryValidationOriginal ( input ) : null ;
2026-11-24 21:11:32 +08:00
if ( ! activePocketKeys (). includes ( oldPocket ) &&! ( oldOriginal && ( oldOriginal . old_pocket ?? '� 墧𤣰� 扳� ' ) === oldPocket )) throw new Error ( '霂琿� 㗇𥋘� 扳� 摰鮋� � 亙� � � 歇� 舐鍂韐抒� � � ' );
if ( pocketCountsEnabled ( oldPocket )){
stockCountValue ( input . old_stock_count ,{ optional :!! oldOriginal && oldOriginal . old_stock_count == null && ( oldOriginal . old_pocket ?? '� 墧𤣰� 扳� ' ) === oldPocket , title : '� 扳� � 亙� � 圈� 嚗� 笆嚗� ' });
const since = state . pocketCatalog ? . find ( row => row . key === oldPocket ) ? . countSince ; if ( input . old_stock_count != null && String ( input . old_stock_count ). trim () !== '' && since && input . date < since ) throw new Error ( '� 扳� � 亙� � 交� 銝滩� � 拐� ' + since + '撖寞㺭� 条� � 箏� � � ' );
}
2026-11-26 01:01:18 +08:00
if ( input . old_source === 'deposit' ){ if ( ! input . deposit_id ) throw new Error ( '霂琿� 㗇𥋘撖� � 霈啣� ' ); if ( recoveryUnits ( input . deposit_weight , 3 , '雿輻鍂撖� � � 钅� ' ,{ zero : false }) > calculation . newMg ) throw new Error ( '� 祆活撖� � � 券� 銝滩� 頞� � � 啗揮� 钅� 嚗� � 雿嗵誧蝏剖� 摮� ' );}
2026-10-26 14:44:07 +08:00
if ( input . mode === 'exchange' ){
2026-11-24 21:56:05 +08:00
const x = input . exchange , original = editing ? recoveryValidationOriginal ( input ) ? . exchange : null ; if ( pocketCountsEnabled ( x . pocket )) stockCountValue ( x . stockCount ,{ optional :!! original && original . stockCount == null && original . pocket === x . pocket && Number ( original . quantity ) === Number ( x . quantity ), title : '� 啗揮� 箏� � 圈� 嚗� 笆嚗� ' }); if ( ! x . name || x . name . length > 60 ) throw new Error ( '霂瑕‵� � 1嚚� 60摮㛖� � 啗揮� � � � 滨妍� � ' );
if ( x . pocket !== '' &&! activePocketKeys (). includes ( x . pocket ) &&! ( editing && recoveryValidationOriginal ( input ) ? . exchange ? . pocket === x . pocket )) throw new Error ( '霂琿� 㗇𥋘� 啗揮摰鮋� � 箏� � � 歇� 舐鍂韐抒� � � ' );
2026-11-24 21:11:32 +08:00
for ( const [ index , row ] of ( x . products || []). entries ()){
const original = editing ? ( recoveryEditEntry . data . inputs . exchange ? . products ?? [ recoveryEditEntry . data . inputs . exchange ])[ index ] : null ;
if ( ! row . name || row . name . length > 60 || LedgerCalc . isSilver ( row . name )) throw new Error ( '霂琿� 𣂷辣憛怠� 暺� � � � � � 滨妍� � ' );
if ( row . pocket !== '' &&! activePocketKeys (). includes ( row . pocket ) && row . pocket !== original ? . pocket ) throw new Error ( '霂琿� 㗇𥋘撌脣鍳� 刻揮� 䀹� 憭㚚� � � ' );
if ( pocketCountsEnabled ( row . pocket )) stockCountValue ( row . stockCount ,{ optional :!! original && original . stockCount == null && original . pocket === row . pocket && original . quantity === row . quantity });
if ( ! row . cost_labor ) throw new Error ( '霂琿� 𣂷辣憛怠� 餈𥡝揮撌亥晶嚗峕瓷� 匧� � 笔‵0� � ' );
recoveryUnits ( row . cost_labor . mode === 'gram' ? row . cost_labor . rate : row . cost_labor . amount , 2 , '餈𥡝揮撌亥晶' );
if ( ! teamMemberKeys . includes ( row . cost_labor_payer )) throw new Error ( '霂琿� 㗇𥋘撌亥晶隞䀹狡鈭箝� � ' );
}
2026-10-26 14:44:07 +08:00
if ( ! x . cost_labor ) throw new Error ( '霂瑕‵� 躰� 韐批極韐對� 瘝⊥� � 𤑳� 霂瑟� 蝖桀‵0� � ' );
recoveryUnits ( x . cost_labor . mode === 'total' ? x . cost_labor . amount : x . cost_labor . rate , 2 , '餈𥡝揮撌亥晶' );
if ( calculation . differenceMg > 0 ){ if ( ! x . cost_material ) throw new Error ( '霂瑕‵� 坔榆� 滩� 韐扳� 隞瘀� � 㚚� 㗇𥋘瘥𤩺𠯫� 蹱� � � ' ); if ( x . cost_material . mode === 'gram' ){ if ( recoveryUnits ( x . cost_material . rate , 2 , '撌桅� 餈𥡝揮� 嗘遠' ) <= 0 ) throw new Error ( '撌桅� 餈𥡝揮� 嗘遠憿餃之鈭� 0� � ' );} else if ( ! validOrderDate ( x . cost_material . poolId ) || x . cost_material . poolId > input . date ) throw new Error ( '� 蹱� � 交� 銝滩� � 帋� 銝𡁜𦛚� 交� � � ' );}
for ( const payer of [ x . cost_material_payer , x . cost_labor_payer ,... x . fee_items . map ( row => row . payer )]) if ( ! teamMemberKeys . includes ( payer )) throw new Error ( '霂琿� 㗇𥋘� � � � 鞉𧋦� � � � � � 甈曆犖� � ' );
}
if ( calculation . netSettlement < 0 && isCreditCardAccount ( input . payment_account )) throw new Error ( '� 穃恥� 瑚� 甈曆� � 賭蝙� 其縑� 典㨃� 嗆狡韐行� � � ' );
if ( ! state . accounts . includes ( input . payment_account )) throw new Error ( '霂琿� 㗇𥋘� 㗇� � � 𤣰隞䀹狡� 孵� � � ' );
if ( input . verified !== true ) throw new Error ( '霂瑟瓲摰鮋� � 譌� � � 蝞烾� 憸嘥� 摰鮋� � 嗡� 甈曉� 嚗� 㗲� 厩&霈文� 靽嘥� � � ' );
return input ;
}
2026-11-30 15:40:40 +08:00
function recoveryCustomerRateField ( title , name , value ,{ daily = true } = {}){
return `<div class="recovery-customer-rate"> ${ recoveryNumberField ( title , name , value , 2 , 'required' ) }${ daily ? button ( '雿輻鍂敶𤘪𠯫� 䭾� � 嗘遠' , 'recovery-use-daily-rate' , 'quiet' , `data-rate-field=" ${ e ( name ) } "` ) + `<p class="small muted" data-rate-status></p>` : '' } </div>` ;
}
async function recoveryUseDailyRate ( node ){
const form = $ ( '#recovery-form' ); if ( ! form || busy || pending ()) return ;
const section = node . closest ( '[data-recovery-item]' ) || form , name = node . dataset . rateField ;
if ( ! [ 'gold_price' , 'buy_rate' , 'extra_gold_price' , 'extra_buy_rate' ]. includes ( name )) return ;
const field = recoveryField ( section , name ); if ( ! field || field . disabled ) return ;
const date = recoveryField ( form , 'date' ). value , member = recoveryField ( form , 'member' ). value , user = recoveryUser (), previous = field . value , status = node . closest ( '.recovery-customer-rate' ) ? . querySelector ( '[data-rate-status]' );
const active = ()=> ! busy &&! pending () && form === $ ( '#recovery-form' ) && user === recoveryUser () && recoveryField ( form , 'date' ). value === date && recoveryField ( form , 'member' ). value === member && section . contains ( field ) &&! field . disabled && field . value === previous ;
node . disabled = true ; if ( status ) status . textContent = '甇� 銁霂餃� 敶𤘪𠯫� 䭾� � 嗘遠� � ' ;
try {
const pool = await api ( '/api/material-pools/' + encodeURIComponent ( date ) + '?member=' + encodeURIComponent ( member ));
if ( ! active ()){ if ( status && form === $ ( '#recovery-form' )) status . textContent = '銵典� 撌脣� � 吔� 霂琿� � 啁� � 餃蒂� 交� 隞瑯� � ' ; return ;}
if ( pool ? . id !== date || pool . date !== date ||! Number . isSafeInteger ( pool . averageRate ) || pool . averageRate <= 0 ||! Number . isSafeInteger ( pool . totalMg ) || pool . totalMg <= 0 ||! Number . isSafeInteger ( pool . totalAmount )) throw new Error ( date + ' � � � � 舐鍂� � � � 勗� � � � 隞瘀� 霂瑟� 憛急� � � ‘敶閗揚� 踺� � ' );
field . value = ( pool . averageRate / 100 ). toFixed ( 2 );
if ( name . endsWith ( 'buy_rate' )) section . dataset . buy_total_manual = 'false' ;
const verified = recoveryField ( form , 'verified' ); if ( verified ) verified . checked = false ;
syncRecoveryForm ( form ); rememberRecoveryDraft ( form );
if ( status ) status . textContent = `撌脣蒂� � ${ date } � 砍� � 䭾� 瞼 ${ field . value } /� 页� � 舐誧蝏剜� � 嫘� � ;
}catch(err){if(active()){if(status)status.textContent='� 芸蒂� 伐� � 煺遠� 潔� � 踺� � '+err.message;throw err;}}
finally{if(form===$('#recovery-form'))node.disabled=busy||!!pending()||field.disabled;}
}
2026-10-26 14:44:07 +08:00
function recoveryNumberField(title,name,value,places=2,extra=''){
return field(title,name,value,'number',` min = "0" step = "${places===3?'0.001':'0.01'}" inputmode = "decimal" $ { extra } `);
}
function recoveryMemberField(draft){
return state.user.role==='owner'?choice('敶鍦� � 𣂼� ','member',teamMemberOptions(),draft.member):` < label > 敶鍦 � � 𣂼 � < input value = "${e(teamMemberName(currentMember()))}" readonly >< input type = "hidden" name = "member" value = "${e(currentMember())}" >< /label>`;
}
function recoveryFormHTML ( draft ){
2026-11-28 01:28:39 +08:00
if ( draft . mode === 'exchange' && draft . independent_products ){ if ( typeof recoveryEditEntry !== 'undefined' && recoveryEditEntry ? . data ? . inputs ? . exchange ? . items ? . length > 1 ) return recoveryItemsFormHTML ( draft ); draft = recoverySharedOldDraft ( draft );}
2026-10-26 14:44:07 +08:00
const exchange = draft . mode === 'exchange' , members = teamMemberOptions (), recipients = members . map (([ member , name ])=>[ recoveryPrefix ( member ), name ]);
2026-11-24 21:11:32 +08:00
const oldPocket = draft . old_pocket ?? '� 墧𤣰� 扳� ' , oldOriginal = typeof recoveryEditEntry !== 'undefined' ? recoveryEditEntry ? . data ? . inputs : null ;
2026-11-30 15:40:40 +08:00
return `<form id="recovery-form" data-independent-default=" ${ !! draft . independent_products } " data-buy_total_manual=" ${ !! draft . buy_total_manual } " data-depreciation_manual=" ${ !! draft . depreciation_manual } " data-melted_manual=" ${ !! draft . melted_manual } "><input name="mode" type="hidden" value=" ${ e ( draft . mode ) } "><input name="shared_old_notice" type="hidden" value=" ${ e ( draft . shared_old_notice || '' ) } "><div class="recovery-mode-switch" aria-label="銝𡁜𦛚蝐餃� "> ${ Object . entries ( recoveryModeNames ). map (([ mode , name ])=> button ( e ( name ), 'recovery-mode' , draft . mode === mode ? 'active' : '' , `data-mode=" ${ mode } " aria-pressed=" ${ draft . mode === mode } "` )). join ( '' ) }${ button ( '撖� � 嚗峕� 銝滨� 蝞� ' , 'customer-material-new' ) } </div><section class="panel"><div class="panel-title"><h2>摰X� 銝𤾸� � � </h2><span class="small muted">靽嘥� � 舘䌊� 函� � � </span></div><div class="recovery-row recovery-identity"> ${ field ( '銝𡁜𦛚� 交� ' , 'date' , draft . date , 'date' , `max=" ${ e ( state . today ) } " required` ) }${ field ( '摰X� 蝘啣鐤嚗譍誨� � ' , 'customer' , draft . customer , 'text' , 'maxlength="60" required placeholder="敹� ‵ "' ) }${ field ( '撘� � 蓥犖' , 'salesperson' , draft . salesperson , 'text' , 'maxlength="30" required' ) }${ recoveryMemberField ( draft ) } </div></section><section class="panel"><div class="panel-title"><h2>� 扳� 蝘圈� </h2><span class="small muted">� 鞱𠧧� 厩蓡� � 㺭憛怠� 嚗䔶� 憒� 99銵函內99%</span></div> ${ draft . shared_old_notice ? '<p class="note">' + e ( draft . shared_old_notice ) + '</p>' : '' }${ exchange ? customerMaterialSourceHTML ( draft ) : '' } <div class="recovery-row recovery-old-fields"> ${ field ( '� 扳� � 滨妍' , 'old_name' , draft . old_name , 'text' , 'maxlength="60" required' ) }${ recoveryNumberField ( '� 交� � 漤� 嚗ā嚗� ' , 'incoming_weight' , draft . incoming_weight , 3 , 'required' ) }${ recoveryNumberField ( '� 𥪜� � 漤� 嚗ā嚗� ' , 'melted_weight' , draft . melted_weight , 3 , 'required' ) }${ recoveryNumberField ( '� 鞱𠧧嚗� %嚗� ' , 'purity' , draft . purity , 3 , 'max="100" required' ) }${ recoveryNumberField ( '� 睃� � 漤� 嚗ā嚗諹䌊� 剁� ' , 'folded_weight' , '' , 3 , 'readonly tabindex="-1"' ) } </div><p class="small muted recovery-formula" id="recovery-folded-formula" aria-live="polite">� 睃� � 漤� = � 𥪜� � 漤� � � 鞱𠧧 繩 100� � </p><div class="recovery-row"> ${ pocketChoice ( '� 扳� � 亙� 韐抒� ' , 'old_pocket' , oldPocket ,{ blank : null , historical :!! oldOriginal && ( oldOriginal . old_pocket ?? '� 墧𤣰� 扳� ' ) === oldPocket } )} ${ stockCountField ( oldPocket , draft . old_stock_count ,{ name : 'old_stock_count' , title : '� 扳� � 亙� � 圈� 嚗� 笆嚗� ' , help : '' , optional :!! oldOriginal && oldOriginal . old_stock_count == null && ( oldOriginal . old_pocket ?? '� 墧𤣰� 扳� ' ) === oldPocket } )}</div><p class="small muted">撌脩� 蝞㛖� � 扳� � 交� � 㕑揮� 矋� � � � 雿蹱� � 閧𡠺霈啣� 摰X� 撖� � � 踺� � 蔭� X鰵韐扳� � 箄揮韐抒� � � � � � </p></section><section class="panel recovery-exchange" data-recovery-exchange ${ exchange ? '' : 'hidden' } ><div class="panel-title"><h2>蝵格揢� 啗揮</h2><span class="small muted">瘥譍辣� 啗揮� � � 憛怠� 撌亥晶� � � � 砍� 韐抒� </span></div><div class="note">銝𦠜䲮� 扳� � 芸� 銝� 甈∴� 靘𥕢� � X� � 㗇鰵韐批� � 峕𠽌� � � � ‘� 㻫� � � � 批� 雿蹱� � 㗇㟲� 閧� 銝� 蝏梶� � � </div><p class="small" id="recovery-new-total" aria-live="polite"></p><section class="recovery-new-product" data-recovery-first-product><div class="panel-title"><h3>蝵格揢� 啗揮 1</h3></div><datalist id="recovery-product-names"> ${ productNames . filter ( name => ! LedgerCalc . isSilver ( name )). map ( name => `<option value=" ${ e ( name ) } "></option>` ). join ( '' ) } </datalist> ${ recoveryProductFieldsHTML ( draft ,{ original : oldOriginal ? . exchange ? . products ? .[ 0 ] ?? oldOriginal ? . exchange } )}<div class="internal recovery-product-cost"><h4>� 砌辣� � � � 鞉𧋦</h4> ${ recoveryProductLaborHTML ( draft ) } </div></section> ${ ( draft . extra_products || []). map ( recoveryExtraProductHTML ). join ( '' ) } <div class="form-actions"> ${ button ( '嚗� 瘛餃� 蝵格揢� 啗揮' , 'recovery-add-product' ) } <span class="small muted">銵仿� � � � � 批� 雿蹱� � 㗇鰵韐扳� 餃� � 滨� 蝞梹� 瘥譍辣� 舫� 劐� � 諹揮� 䀹� 憭㚚� � � </span></div><section class="recovery-common-pricing"><h3>� 游� 撌桅� 銝擧� � � </h3><div class="recovery-row recovery-price-fields"> ${ recoveryCustomerRateField ( '銵仿� � � � 桀� 隞瘀� � � � g嚗
2026-10-26 14:44:07 +08:00
}
function recoverySettlementHTML(value,input){
2026-11-24 21:56:05 +08:00
if(value.exchangeItems){const items=input?.exchange?.items;return value.exchangeItems.map((p,i)=>' < h3 > 蝵格揢 � � � '+(i+1)+' 嚗 � '+e(p.newProduct?.name||items?.[i]?.exchange?.name||'')+' < /h3>'+recoverySettlementHTML(p,items?{...items[i],mode:'exchange'}:recoveryDetailInput(p))).join('')+recoveryItemsSummaryHTML(value,input);}
2026-10-26 14:44:07 +08:00
const x = input ? . exchange || value . exchange || { } ,direct=(input?.mode||value.mode)==='direct';
const defaultAmount=value.defaultPurchaseAmount??value.calculatedPurchaseAmount??value.purchaseAmount,adjustment=value.roundingAdjustment??value.rounding_adjustment??0;
const goldLine=value.differenceMg>0?` < p > 銵仿 � 撌桐遠嚗𡄯 � $ { grams ( value . newMg )} � � $ { grams ( value . oldMg )} 嚗斉 � $ { recoveryMoney ( recoveryUnits ( x . gold_price ?? '0' , 2 , '敶枏予� � � 桅� 隞� ' ))} 嚗𣲵 = < strong > $ { recoveryMoney ( value . goldAmount )} < /strong></p>`:'<p>� 𣳇� 銵仿� 撌桐遠� � </p>';
2026-11-26 01:15:41 +08:00
const surplusLine = value . depositMg > 0 ? `<p><strong>雿蹱� 撖� � 嚗� ${ grams ( value . depositMg ) } g嚗峕� 銝滨� 蝞𨰜� � </strong>靽嘥� � 𤾸� � 亙恥� 瑕� 摮䀹� 嚗� 虾靘𥕢� 甈∠蔭� V蝙� 具� � </p>` : value . surplusMg > 0 ? `<p>雿蹱� � 墧𤣰嚗𡄯� ${ grams ( value . oldMg ) } � � ${ grams ( value . newMg ) } 嚗斉 � ${ recoveryMoney ( recoveryUnits ( input ? . buy_rate ?? '0' , 2 , '� 墧𤣰� 蓥遠' )) } 嚗𣲵 ${ value . purchaseAmount !== defaultAmount ? '嚗峕� � 詨� � 煾� ' : '' } = <strong> ${ recoveryMoney ( value . purchaseAmount ) } </strong></p>` : '<p>� 𣳇� 雿蹱� � 墧𤣰� � </p>' ;
2026-11-24 21:11:32 +08:00
const formulas = direct ? `<p>� 墧𤣰� 煾� 嚗� ${ grams ( value . oldMg ) } g � ${ recoveryMoney ( recoveryUnits ( input ? . buy_rate ?? '0' , 2 , '� 墧𤣰� 蓥遠' )) } 嚗𣲵 = <strong> ${ recoveryMoney ( defaultAmount ) } </strong></p> ${ defaultAmount !== value . purchaseAmount ? `<p>� 詨� � 𤾸� � � � � 嗆狡嚗� <strong> ${ recoveryMoney ( value . purchaseAmount ) } </strong></p>` : '' } ` : ` ${ goldLine } <p>� 啗揮撌亥晶嚗� ${ x . products ? '� � 辣撌亥晶� � 恣' : x . labor_mode === 'total' ? '� 㗇� 駁� ' : grams ( value . newMg ) + 'g � ' + recoveryMoney ( recoveryUnits ( x . labor_rate ?? '0' , 2 , '� � � 桀極韐� ' )) + '嚗𣲵' } = <strong> ${ recoveryMoney ( value . laborAmount ) } </strong></p><p>� 䀹唂韐對� ${ grams ( value . depreciationMg ) } g � ${ recoveryMoney ( recoveryUnits ( x . depreciation_rate ?? '10' , 2 , '� 䀹唂韐孵� 隞� ' )) } 嚗𣲵 = <strong> ${ recoveryMoney ( value . depreciationAmount ) } </strong></p> ${ value . chargesAmount ? `<p>� 嗡� � 嗉晶嚗� ${ recoveryMoney ( value . chargesAmount ) } </p>` : '' }${ value . discount ? `<p>隡䀹� 嚗尠� ${ recoveryMoney ( value . discount ) } </p>` : '' }${ adjustment ? `<p>韐寧鍂� 𡝗㟲靚� 㟲嚗� ${ adjustment > 0 ? '+' : '� � ' }${ recoveryMoney ( Math . abs ( adjustment )) } </p>` : '' } <p>� 祆活蝵格揢韐寧鍂嚗� <strong> ${ recoveryMoney ( value . receivable ) } </strong></p> ${ surplusLine } ` ;
2026-10-26 14:44:07 +08:00
const title = value . netSettlement > 0 ? '摰X� 銵交狡' : value . netSettlement < 0 ? '摨烾� 隞䀹狡' : '� 𣳇� � 圈� � 嗡� ' ;
return `<div class="recovery-equations"> ${ formulas } </div><div class="recovery-net ${ value . netSettlement < 0 ? 'is-payment' : '' } "><span> ${ title } </span><strong> ${ recoveryMoney ( Math . abs ( value . netSettlement )) } </strong></div> ${ direct ? '' : `<p class="small muted recovery-net-formula">� � 蝏� � 蝞� = 蝵格揢韐寧鍂 ${ recoveryMoney ( value . receivable ) } � � 雿蹱� � 墧𤣰甈� ${ recoveryMoney ( value . purchaseAmount ) } � � ${ value . netSettlement === 0 ? '� 祆活� 𣳇� � 圈� � 嗡� 甈整� � ' : '' } </p>` } ` ;
}
function recoverySyncFieldModes ( form , exchange ){
for ( const section of form . querySelectorAll ( '[data-recovery-exchange]' )){
section . hidden =! exchange ; for ( const control of section . querySelectorAll ( 'input,select,textarea,button' )) control . disabled =! exchange ;
}
2026-11-26 01:01:18 +08:00
customerMaterialSyncFields ( form , recoveryFormDraft ( form ));
2026-10-26 14:44:07 +08:00
const source = recoveryField ( form , 'material_source' ) ? . value || 'pool' ;
for ( const group of form . querySelectorAll ( '[data-recovery-pool],[data-recovery-manual]' )){
const active = exchange && ( group . hasAttribute ( 'data-recovery-pool' ) ? source === 'pool' : source === 'manual' ); group . hidden =! active ; for ( const control of group . querySelectorAll ( 'input,select' )) control . disabled =! active ;
}
}
function recoverySetLabel ( form , name , title ){ const control = recoveryField ( form , name ), label = control ? . closest ( 'label' ); if ( label ? . firstChild ) label . firstChild . textContent = title ;}
function syncRecoveryForm ( form = $ ( '#recovery-form' ),{ quote = true } = {}){
2026-11-24 21:56:05 +08:00
if ( form ? . dataset ? . independentProducts === 'true' ) return syncRecoveryItems ( form ,{ quote });
2026-10-26 14:44:07 +08:00
if ( ! form ) return null ;
2026-11-26 01:01:18 +08:00
const draft = recoveryFormDraft ( form ), exchange = draft . mode === 'exchange' ; if ( exchange && draft . old_source === 'deposit' ) draft . old_lines = customerMaterialOldLines ( draft ); recoverySyncFieldModes ( form , exchange ); const original = typeof recoveryEditEntry !== 'undefined' && form . dataset . recoveryEdit === 'true' ? recoveryEditEntry ? . data ? . inputs ? . exchange : null ; syncStockCountField ( form ,{ pocket : draft . pocket , visible : exchange && pocketCountsEnabled ( draft . pocket ), optional :!! original && original . stockCount == null && original . pocket === draft . pocket && Number ( original . quantity ) === Number ( draft . new_quantity )});
2026-11-24 21:11:32 +08:00
for ( const row of form . querySelectorAll ( '[data-recovery-product]' )){ const index = Number ( row . dataset . recoveryProduct ), product = draft . extra_products [ index ]; syncStockCountField ( row ,{ name : 'extra_stockCount' , pocket : product . pocket , visible : exchange && pocketCountsEnabled ( product . pocket ), optional :!! original ? . products ? .[ index + 1 ] && original . products [ index + 1 ]. stockCount == null }); recoverySetLabel ( row , 'extra_labor_rate' , product . labor_mode === 'total' ? '� � � 桀極韐對� � � � ' : '� � � 桀極韐對� � � � g嚗� ' ); recoverySetLabel ( row , 'extra_cost_labor_value' , product . cost_labor_mode === 'total' ? '餈𥡝揮撌亥晶嚗� � 嚗� ' : '餈𥡝揮撌亥晶嚗� � 嚗𣲵嚗� ' );}
const oldPocket = draft . old_pocket ?? '� 墧𤣰� 扳� ' , oldOriginal = typeof recoveryEditEntry !== 'undefined' && form . dataset . recoveryEdit === 'true' ? recoveryEditEntry ? . data ? . inputs : null ;
syncStockCountField ( form ,{ pocket : oldPocket , name : 'old_stock_count' , optional :!! oldOriginal && oldOriginal . old_stock_count == null && ( oldOriginal . old_pocket ?? '� 墧𤣰� 扳� ' ) === oldPocket });
2026-11-26 01:15:41 +08:00
const buyHelp = $ ( '#recovery-buy-help' ); if ( buyHelp ) buyHelp . textContent = exchange ? '雿蹱� � 舀� 隞瑕� � 塚� 銋笔虾撖� � � � � 蝏梶� ' : '靽嘥� � 舘䌊� 刻扇韐剜� 銝� ' + pocketLabel ( oldPocket ) + '摨枏� ' ;
2026-10-26 14:44:07 +08:00
recoverySetLabel ( form , 'labor_rate' , draft . labor_mode === 'total' ? '� � � 桀極韐對� � � � ' : '� � � 桀極韐對� � � � g嚗� ' );
recoverySetLabel ( form , 'cost_labor_value' , draft . cost_labor_mode === 'total' ? '餈𥡝揮撌亥晶嚗� � 嚗� ' : '餈𥡝揮撌亥晶嚗� � 嚗𣲵嚗� ' );
let calculation = null , input = null , error = '' , old = null , newMg = null ;
try {
const oldInput = {... draft , mode : 'direct' , buy_rate : draft . buy_rate || '0' , buy_total_manual : false };
oldInput . buy_rate = '1' ; oldInput . buy_total_manual = true ; oldInput . buy_total = '1' ; old = recoveryCalculate ( recoveryInput ( oldInput ,{ quote : true })); recoveryField ( form , 'folded_weight' ). value = grams ( old . oldMg );
2026-11-04 22:18:56 +08:00
$ ( '#recovery-folded-formula' ). textContent = draft . old_lines ? . length > 1 ? ` ${ draft . old_lines . length } 憿寞唂� 蹱� � 擧� 駁� ${ grams ( old . oldMg ) } g嚗屸� 鞾★� 厩� � 𡡞� � 譍� � 鞱𠧧� 貊� � � :` � 睃 � � 漤 � = $ { draft . melted_weight } g � $ { draft . purity } % = $ { grams ( old . oldMg )} g � � ;
2026-10-26 14:44:07 +08:00
} catch { recoveryField ( form , 'folded_weight' ). value = '' ; $ ( '#recovery-folded-formula' ). textContent = '� 睃� � 漤� = � 𥪜� � 漤� � � 鞱𠧧 繩 100� � ' ;}
2026-11-24 21:11:32 +08:00
try { if ( exchange ) newMg = recoveryNewWeight ( draft );} catch {}
2026-11-27 15:48:37 +08:00
const newTotal = form . querySelector ( '#recovery-new-total' ); if ( newTotal ) newTotal . textContent = `� 啗揮� � ${ 1 + ( draft . extra_products ? . length || 0 ) } 隞� 繚 � � 恣 ${ newMg === null ? '敺� ‵ � � ' : grams ( newMg ) + 'g' }${ old ? ' 繚 � 梁鍂� 睃� � 扳� ' + grams ( old . oldMg ) + 'g' : '' } ` ;
2026-10-26 14:44:07 +08:00
if ( exchange && old && newMg !== null &&! draft . depreciation_manual ){ draft . depreciation_weight = grams ( Math . min ( old . oldMg , newMg )); recoveryField ( form , 'depreciation_weight' ). value = draft . depreciation_weight ;}
const hasPurchase =! exchange ||!! ( old && newMg !== null && old . oldMg > newMg ), buyPanel = form . querySelector ( '.recovery-buy-panel' );
if ( buyPanel ){ buyPanel . hidden =! hasPurchase ; for ( const control of buyPanel . querySelectorAll ( 'input,select,button' )) control . disabled =! hasPurchase ;}
2026-11-26 01:15:41 +08:00
recoverySurplusSync ( form , draft , hasPurchase , exchange );
2026-10-26 14:44:07 +08:00
if ( exchange &&! hasPurchase ){ draft . buy_total_manual = false ; draft . buy_total = '0' ; form . dataset . buy_total_manual = 'false' ; recoveryField ( form , 'buy_total' ). value = '0.00' ;}
const hasDifference = exchange &&!! ( old && newMg !== null && newMg > old . oldMg ), goldPrice = recoveryField ( form , 'gold_price' ), materialFields = form . querySelector ( '.recovery-material-cost .recovery-row' );
2026-11-30 15:40:40 +08:00
if ( goldPrice ){ goldPrice . disabled =! hasDifference ; goldPrice . required = hasDifference ;( goldPrice . closest ( '.recovery-customer-rate' ) || goldPrice . closest ( 'label' )). hidden =! hasDifference ;}
2026-10-26 14:44:07 +08:00
if ( materialFields ){ materialFields . hidden =! hasDifference ; if ( ! hasDifference ) for ( const control of materialFields . querySelectorAll ( 'input,select,button' )) control . disabled = true ;}
try {
input = recoveryInput ( draft ,{ quote : true }); calculation = recoveryCalculate ( input );
if ( ! draft . buy_total_manual ){ recoveryField ( form , 'buy_total' ). value = ( calculation . defaultPurchaseAmount / 100 ). toFixed ( 2 ); draft . buy_total = recoveryField ( form , 'buy_total' ). value ;}
$ ( '#recovery-calculation' ). innerHTML = recoverySettlementHTML ( calculation , input );
2026-11-26 01:15:41 +08:00
$ ( '#recovery-buy-formula' ). textContent = calculation . depositMg ? `雿蹱� ${ grams ( calculation . depositMg ) } g � 惩� 摰X� 撖� � � 辷� � � � 蝏梶� 嚗䔶� 霈∪� � 嗆狡� � :` $ { exchange ? '雿蹱� ' : '� 睃� ' } $ { grams ( calculation . surplusMg )} g � $ { draft . buy_rate } � � � g = $ {( calculation . defaultPurchaseAmount / 100 ). toFixed ( 2 )} � � $ { draft . buy_total_manual ? '嚗𥟇𧋦� 閖� � 冽� � 冽瓲摰鮋� 憸腈� � ' : '� � ' } `;
2026-10-26 14:44:07 +08:00
}catch(err){error=err.message;$('#recovery-calculation').innerHTML=` < p class = "muted" > $ { e ( error )} < /p>`;$('#recovery-buy-formula').textContent='� 㗇� � 𡡞� � 譍� � 墧𤣰� 蓥遠� 芸𢆡霈∠� 嚗� � � � � 蝞埈� 靚� 㟲� 嗅虾靽格㺿� 煾� � � ';}
const net = calculation ? . netSettlement ?? ( exchange ? 0 :- 1 ), card = net > 0 && draft . payment_method === '靽∠鍂� � ' ;
for ( const [ selector , active ] of [[ '.recovery-cash-in' , net > 0 ],[ '.recovery-cash-out' , net < 0 ]]) for ( const group of form . querySelectorAll ( selector )){ group . hidden =! active ; for ( const control of group . querySelectorAll ( 'input,select' )) control . disabled =! active ;}
const recipient = recoveryField ( form , 'payment_recipient' ); if ( card ){ if ( recipient . dataset . cardLocked !== 'true' ) recipient . dataset . previousRecipient = recipient . value ; recipient . value = '暻阡漲' ; recipient . dataset . cardLocked = 'true' ; recipient . disabled = true ;} else if ( recipient . dataset . cardLocked === 'true' ){ recipient . value = recipient . dataset . previousRecipient || recoveryPrefix ( draft . member ); recipient . dataset . cardLocked = 'false' ; recipient . disabled = net <= 0 ;}
$ ( '#recovery-card-owner' ). hidden =! card ; $ ( '#recovery-card-fee' ). hidden =! card ;
2026-11-16 23:03:36 +08:00
if ( card ){ const rate = recoveryCardRate (); $ ( '#recovery-card-fee' ). textContent = `� � � 靽∠鍂� ⊥� 蝏剛晶嚗� ${ recoveryMoney ( calculation . netSettlement ) } � ${ rate } � � = ${ recoveryMoney ( CreditCardFees . amount ( calculation . netSettlement , rate )) } 嚗𣬚眏暻阡漲� 踵� � � 恥� 瑞� 蝞烾� 憸苷� � 塩� � ;}
2026-10-26 14:44:07 +08:00
recoverySyncInternal(form,draft,calculation);
rememberRecoveryDraft(form);
if(quote){++recoveryQuoteRequest;clearTimeout(recoveryQuoteTimer);$('#recovery-quote-status').textContent=error?'':'甇� 銁� 詨笆蝏梶� � � ';if(input&&!error)recoveryQuoteTimer=setTimeout(()=>loadRecoveryQuote(form),350);}
return calculation;
}
function recoverySyncInternal(form,draft,calculation){
const materialNote=$('#recovery-material-note'),preview=$('#recovery-internal-preview');if(!materialNote||!preview)return;
if(!calculation||draft.mode!=='exchange'){materialNote.textContent='憛怠� � 唳唂� 钅� � 擧遬蝷箏榆� 齿� 韐嫘� � ';preview.textContent='';return;}
const mg=calculation.differenceMg,matched=calculation.matchedMg;
if(!mg)materialNote.textContent=` 蝑厰 � 鈭斗揢 $ { grams ( matched )} g嚗 � 蘨霈啣 � � 抬 � � 㰘 ‘ � 穃榆 � 㵪 � 銝滩 � 㛖鍂瘥𤩺𠯫 � 蹱 � � � ;
else if ( draft . material_source === 'pool' ){
const pool = materialPoolsCacheUser === recoveryUser () ? materialPoolsCache ? . rows ? . find ( value => value . id === ( draft . material_pool_id || draft . date )) : null ;
2026-11-04 22:18:56 +08:00
const editing = form . dataset ? . recoveryEdit === 'true' , personal = typeof materialPoolHasPersonal === 'function' && materialPoolHasPersonal ( pool ); let cost = null ; try { if ( pool &&! editing &&! personal ) cost = LedgerCalc . poolMaterialPreview ( pool ,[{ lineIndex : 0 , mg }]). amounts [ 0 ];} catch {}
materialNote . textContent = `� 芣瓲蝞𡑒‘� 穃榆� � ${ grams ( mg ) } g嚗𣬚� � 滢漱� � ${ grams ( matched ) } g銝齿緍� 蹱� � � ${ personal ? '� � 鍂' + teamMemberName ( draft . member ) + '銝芯犖� 墧𤣰� 辷� � 砍� 銵亥雲嚗𥟇迤� 冽瓲撖孵� � 交� � 躰晶� � ' : editing ? '� 湔迤� 躰晶� 朞� � 笔� � 詨笆嚗峕� � 文� � 㕑� 㛖鍂� � ' : cost == null ? '敶枏� � 躰晶敺� 瓲蝞梹� 韐剜� 銝滩雲� 嗡� � 坔� 銵亦𠶖� � � � ' : '敶枏� 憸� 摯� 躰晶 ' + recoveryMoney ( cost ) + '嚗峕� � 蠘揚� 躰扇敶訫� 撅硺� 甈曆犖� � ' } ` ;
2026-10-26 14:44:07 +08:00
} else { let amount = null ; try { amount = recoveryMul ( mg , recoveryUnits ( draft . material_rate , 2 , '撌桅� 餈𥡝揮� 嗘遠' ));} catch {} materialNote . textContent = `� 芾恣蝞𡑒‘� 穃榆� � ${ grams ( mg ) } g � � � 韐對� ${ amount == null ? '敺� ‵餈𥡝揮� 嗘遠' : grams ( mg ) + 'g � ' + draft . material_rate + '� � � g = ' + recoveryMoney ( amount ) } � � � � 漤� � � � 餈𥕦枂� 蹱� � � ;}
2026-11-24 21:11:32 +08:00
let labor=null;try{const amount=recoveryUnits(draft.cost_labor_value,2,'餈𥡝揮撌亥晶');labor=draft.cost_labor_mode==='total'?amount:recoveryMul(recoveryUnits(draft.new_quantity,3,'� 啗揮� 钅� '),amount);for(const row of draft.extra_products||[]){const rate=recoveryUnits(row.cost_labor_value,2,'餈𥡝揮撌亥晶');labor+=row.cost_labor_mode==='total'?rate:recoveryMul(recoveryUnits(row.new_quantity,3,'� 啗揮� 钅� '),rate);}}catch{}
2026-11-04 22:18:56 +08:00
let extra=null;try{extra=Array.isArray(draft.fee_items)?draft.fee_items.reduce((total,row)=>total+recoveryUnits(row.amount,2,'� 嗡� 摰鮋� � 鞉𧋦'),0):recoveryUnits(draft.fee_amount||'0',2,'� 嗡� 摰鮋� � 鞉𧋦');}catch{}
2026-11-27 15:48:37 +08:00
preview.textContent=` � 啗揮餈𥡝揮撌亥晶 $ { recoveryMoney ( labor )} 嚗 � $ { draft . extra_products ? . length ? '� � 辣� 㗇� � 劐� 甈曆犖� 臭� ' : teamMemberName ( draft . labor_payer ) + '� 臭� ' } 嚗𥕦 � 隞硋 � � � � � � $ { recoveryMoney ( extra )} $ { extra ? ( draft . fee_items ? . length > 1 ? '嚗峕� � � ★摰鮋� 隞䀹狡鈭箸瓲蝞� ' : '嚗� ' + teamMemberName ( draft . fee_payer ) + '� 臭� ' ) : '' } � � $ { calculation . depositMg ? '摰鮋� 雿蹱� ' + grams ( calculation . depositMg ) + 'g � 芸𢆡撖� � 嚗峕� 銝滨� 蝞梹� 銝滨蒈霈啗揚� 踺� � ' : calculation . surplusMg ? '摰鮋� 雿蹱� ' + grams ( calculation . surplusMg ) + 'g 銝𤾸� � 嗆狡撠� 䌊� 函蒈霈啗揚� 踺� � ' : '� 祆活瘝⊥� 憸嘥� 雿蹱� 韐剜� � � ' } `;
2026-10-26 14:44:07 +08:00
}
function applyRecoveryRestrictions(){
2026-11-04 22:18:56 +08:00
const form=$('#recovery-form');if(!form){if(typeof applyRecoveryChangeRestrictions==='function')applyRecoveryChangeRestrictions();return;}syncRecoveryForm(form,{quote:false});
2026-10-26 14:44:07 +08:00
if(busy||pending())for(const node of form.querySelectorAll('button'))node.disabled=true;
2026-11-04 22:18:56 +08:00
if(typeof applyRecoveryChangeRestrictions==='function')applyRecoveryChangeRestrictions();
2026-10-26 14:44:07 +08:00
}
async function loadRecoveryQuote(form=$('#recovery-form')){
if(!form||tab!=='recoveries')return;
2026-11-04 22:18:56 +08:00
const editing=form.dataset?.recoveryEdit==='true',entry=editing&&typeof recoveryEditEntry!=='undefined'?recoveryEditEntry:null;
if(editing&&(!entry||entry.invalid||entry.user!==recoveryChangeUser()))return;
2026-10-26 14:44:07 +08:00
let input;try{input=recoveryInput(recoveryFormDraft(form),{quote:true});recoveryCalculate(input);}catch{return;}
2026-11-04 22:18:56 +08:00
const payload=entry?{...input,revision:entry.revision}:input,url=entry?'/api/recoveries/'+encodeURIComponent(entry.id)+'/quote':'/api/recoveries/quote',request=++recoveryQuoteRequest,user=recoveryUser(),signature=JSON.stringify(payload);
2026-10-26 14:44:07 +08:00
try{
2026-11-04 22:18:56 +08:00
const result=await api(url,payload);
2026-10-26 14:44:07 +08:00
if(request!==recoveryQuoteRequest||user!==recoveryUser()||tab!=='recoveries'||form!==$('#recovery-form'))return;
2026-11-04 22:18:56 +08:00
if(editing&&(entry!==recoveryEditEntry||entry.invalid||entry.user!==recoveryChangeUser()))return;
let fresh;try{const current=recoveryInput(recoveryFormDraft(form),{quote:true});fresh=JSON.stringify(entry?{...current,revision:entry.revision}:current);}catch{return;}if(fresh!==signature)return;
2026-10-26 14:44:07 +08:00
const local=recoveryCalculate(input);if(!Number.isSafeInteger(result.netSettlement)||result.netSettlement!==local.netSettlement)throw new Error('蝏梶� 閫� � 撌脫凒� 堆� 霂琿� � 啗粉� 㚚△� W� � 詨笆� � ');
2026-11-04 22:18:56 +08:00
const sources=result.exchange?.costMaterial?.materialSources;
if(sources?.length&&input.exchange?.cost_material?.mode==='pool'){
if(result.member!==input.member||sources.some(source=>source.kind==='personal_recovery'&&source.member!==input.member)||sources.reduce((sum,source)=>sum+source.quantity,0)!==local.differenceMg||result.materialCost!==null&&sources.reduce((sum,source)=>sum+source.amount,0)!==result.materialCost)throw new Error('蝵格揢� 冽� � 交� 銝𤾸� � 滚� 撅硺� 銝� � 湛� 霂琿� � 唳瓲撖嫘� � ');
const quoteInput={date:input.date,member:input.member,...(entry?.data.record.order_id?{orderId:entry.data.record.order_id}:{}),entries:[{lineIndex:0,poolId:input.exchange.cost_material.poolId,mg:local.differenceMg}]};
let balanceText='';try{const quote=validateMaterialQuote(await api('/api/material-pools/quote',quoteInput),quoteInput);balanceText=materialQuoteBalanceText(quote.pools[0]);}catch{balanceText='銝芯犖銝𤾸� � 曹� � 𤩺� � 芾粉� 堆� 霂瑕� � 唳瓲撖嫘� � ';}
if(request!==recoveryQuoteRequest||user!==recoveryUser()||form!==$('#recovery-form')||editing&&(entry!==recoveryEditEntry||entry.invalid))return;const current=recoveryInput(recoveryFormDraft(form),{quote:true});if(JSON.stringify(entry?{...current,revision:entry.revision}:current)!==signature)return;
$('#recovery-material-note').textContent=materialSourceSegmentsText(sources)+'嚗� '+balanceText+(editing?'� 笔� � 㛖鍂撌脫� � 扎� � ':'');
}else if(editing&&input.exchange?.cost_material?.mode==='pool'&&$('#recovery-material-note'))$('#recovery-material-note').textContent=` � 湔迤 � 𦒘 � $ { input . exchange . cost_material . poolId } � 蹱 � � � 榆 � � $ { grams ( local . differenceMg )} g嚗 � � � 閗 � 㛖鍂撌脫 � � 扎 � � $ { result . materialCost == null ? '� 躰晶敺� ‘朣鞱揚� 坔� � 貊� � � ' : '� 祆活憸� 摯� 躰晶 ' + recoveryMoney ( result . materialCost ) + '嚗峕� � 蠘揚� 蹱䔉皞鞉瓲蝞𦯀� 甈曆犖� � ' } `;
2026-11-24 21:56:05 +08:00
if(result.exchangeItems)for(const [i,p] of result.exchangeItems.entries()){const node=form.querySelector('[data-recovery-item="'+i+'"] [data-item-cost]');if(node)node.textContent='� 砌辣撌桅� � 躰晶 '+recoveryMoney(p.materialCost)+'嚗𥡝� 韐批極韐� '+recoveryMoney(p.laborCost)+(p.exchange.costMaterial.materialSources?'嚗� '+materialSourceSegmentsText(p.exchange.costMaterial.materialSources):'');}
2026-10-26 14:44:07 +08:00
$('#recovery-quote-status').textContent='蝏梶� 撌脫瓲撖對� 靽嘥� � 嗆� � � � 啗揭� ∟扇敶閧&霈扎� � ';
}catch(err){if(request===recoveryQuoteRequest&&user===recoveryUser()&&form===$('#recovery-form'))$('#recovery-quote-status').textContent=err.name==='AbortError'?'蝏梶� � 詨笆頞� 𧒄嚗䔶� 摮䀹𧒄撠� � 甈⊥瓲撉䎚� � ':'蝏梶� � 詨笆嚗� '+err.message;}
}
function recoveryGetFilters(){
const user=recoveryUser();if(!recoveryFilters||recoveryFilterUser!==user){recoveryFilters={from:state.today,date:state.today,mode:'',member:''};recoveryFilterUser=user;}return recoveryFilters;
}
function recoveryFilterHTML(){const filters=recoveryGetFilters();return ` < form id = "recovery-filter-form" class = "recovery-list-filters" > $ { field ( '撘� 憪𧢲𠯫� � ' , 'from' , filters . from , 'date' , `required max=" ${ e ( state . today ) } "` )} $ { field ( '蝏𤘪� � 交� ' , 'date' , filters . date , 'date' , `required max=" ${ e ( state . today ) } "` )} $ { choice ( '銝𡁜𦛚蝐餃� ' , 'mode' ,[[ '' , '� 券� ' ],[ 'direct' , '� 湔𦻖� 墧𤣰' ],[ 'exchange' , '蝵格揢' ]], filters . mode )} $ { state . user . role === 'owner' ? choice ( '敶鍦� � 𣂼� ' , 'member' ,[[ '' , '� 券� � 𣂼� ' ],... teamMemberOptions ()], filters . member ) : '' } < button type = "submit" > � 亥砭 < /button></form>`;}
function recoveryListHTML ( result ){
if ( ! result . rows . length ) return '<div class="empty"><strong>餈嗘葵� 交� � � 凒餈䀹瓷� 匧� � 塚� 蝵格揢� � </strong>靽嘥� � 𤾸虾� 刻� � 峕䰻� 见� � 枏㫲� � </div>' ;
return `<div class="table-wrap"><table class="recovery-list-table"><thead><tr><th>� 交� 嚗誩� � � </th><th>摰X� 嚗誩� � 蓥犖</th><th>蝐餃� 嚗誩� 撅� </th><th class="number">� 睃� � 折� </th><th class="number">� 啗揮� 钅� </th><th class="number">摰鮋� � 嗡� </th><th>� 滢� </th></tr></thead><tbody> ${ result . rows . map ( row => `<tr><td> ${ e ( row . date ) } <div class="small muted"> ${ e ( row . number ) } </div></td><td><strong> ${ e ( row . customer ) } </strong><div class="small muted"> ${ e ( row . salesperson ) } </div></td><td> ${ e ( recoveryModeNames [ row . mode ] || row . mode ) } <div class="small muted"> ${ e ( teamMemberName ( row . member )) } </div></td><td class="number"> ${ grams ( row . oldMg ) } g</td><td class="number"> ${ row . mode === 'exchange' ? grams ( row . newMg ) + 'g' : '� � ' } </td><td class="number"> ${ row . netSettlement > 0 ? '摰X� 銵交狡' : row . netSettlement < 0 ? '摨烾� 隞䀹狡' : '� 𣳇� � 圈� ' } <div><strong> ${ recoveryMoney ( Math . abs ( row . netSettlement )) } </strong></div></td><td><div class="actions"> ${ button ( '� 亦� ' , 'recovery-open' , 'quiet' , `data-id=" ${ e ( row . id ) } "` ) }${ button ( '� 枏㫲' , 'recovery-print' , 'quiet' , `data-id=" ${ e ( row . id ) } "` ) } </div></td></tr>` ). join ( '' ) } </tbody></table></div>` ;
}
async function loadRecoveries (){
const filters = recoveryGetFilters (), request =++ recoveryListRequest , user = recoveryUser (), container = $ ( '#recovery-list' ); if ( ! container ) return ;
if ( ! validOrderDate ( filters . from ) ||! validOrderDate ( filters . date ) || filters . from > filters . date || filters . date > state . today ) throw new Error ( '� 亥砭� 交� 霂琿� 㗇𥋘隞𠰴予� 碶� � 滨� � 㗇� � � 凒� � ' );
container . innerHTML = '<p class="muted" aria-live="polite">甇� 銁霂餃� � 墧𤣰嚗讐蔭� Z扇敶𨰝� � </p>' ;
try { const result = await api ( '/api/recoveries?' + new URLSearchParams ( filters )); if ( request !== recoveryListRequest || user !== recoveryUser () || tab !== 'recoveries' || container !== $ ( '#recovery-list' )) return ; if ( ! Array . isArray ( result . rows )) throw new Error ( '� 墧𤣰嚗讐蔭� Z扇敶閙𧊋摰峕㟲餈𥪜� 嚗諹窈� 滩� � � ' ); container . innerHTML = recoveryListHTML ( result );}
catch ( err ){ if ( request === recoveryListRequest && user === recoveryUser () && container === $ ( '#recovery-list' )) container . innerHTML = `<div class="error"> ${ e ( err . name === 'AbortError' ? '霂餃� 頞� 𧒄嚗諹窈� 滩� � � ' : err . message ) } ${ button ( '� 齿鰵霂餃� ' , 'recovery-refresh-list' ) } </div>` ;}
}
async function loadRecoveryPools ( form = $ ( '#recovery-form' )){
if ( ! form || recoveryField ( form , 'mode' ) ? . value !== 'exchange' ) return ; const user = recoveryUser ();
try { await readMaterialPools (); if ( form !== $ ( '#recovery-form' ) || user !== recoveryUser () || tab !== 'recoveries' ) return ; recoveryPoolOptions ( form ); syncRecoveryForm ( form );}
catch ( err ){ if ( form === $ ( '#recovery-form' ) && user === recoveryUser ()) $ ( '#recovery-material-note' ). textContent = '瘥𤩺𠯫� 蹱� 撠𡁏𧊋霂餃� 嚗� ' + err . message ;}
}
function recoveryPoolOptions ( form ){
2026-11-24 21:56:05 +08:00
if ( form ? . dataset ? . independentProducts === 'true' ) return recoveryItemsPoolOptions ( form );
2026-10-26 14:44:07 +08:00
const date = recoveryField ( form , 'date' ). value , select = recoveryField ( form , 'material_pool_id' ); let selected = select . value || date ; if ( selected > date ) selected = date ;
2026-11-04 22:18:56 +08:00
const member = recoveryField ( form , 'member' ) ? . value || currentMember (), rows = materialPoolsCacheUser === recoveryUser () ? ( typeof materialPoolRows === 'function' ? materialPoolRows () : materialPoolsCache ? . rows || []) : [], remaining = pool => pool . remainingMg + ( pool . personalPools ? .[ member ] ? . remainingMg || 0 ), available = rows . filter ( pool => pool . date <= date && ( remaining ( pool ) > 0 || pool . id === selected || pool . id === date ));
2026-10-26 14:44:07 +08:00
if ( ! available . some ( pool => pool . id === date )) available . push ({ id : date , date , remainingMg : 0 , totalMg : 0 });
if ( selected &&! available . some ( pool => pool . id === selected )) available . push ({ id : selected , date : selected , remainingMg : 0 , totalMg : 0 });
2026-11-04 22:18:56 +08:00
select . innerHTML = opts ( available . sort (( a , b )=> b . date . localeCompare ( a . date )). map ( pool =>[ pool . id , pool . date + ' 繚 ' + ( pool . personalPools ? '銝芯犖雿� ' + grams ( pool . personalPools [ member ] ? . remainingMg || 0 ) + 'g嚗誩� � 曹� ' + grams ( pool . remainingMg ) + 'g' : pool . totalMg ? '雿� ' + grams ( pool . remainingMg ) + 'g' : '敺� ‘ � � 揚' )]), selected ); select . value = selected ;
2026-10-26 14:44:07 +08:00
}
async function renderRecoveries (){
2026-11-26 01:01:18 +08:00
if ( customerMaterialPage &&! ( typeof recoveryEditEntry !== 'undefined' && recoveryEditEntry )) return renderCustomerMaterials ();
2026-11-04 22:18:56 +08:00
if ( typeof recoveryEditEntry !== 'undefined' && recoveryEditEntry && typeof renderRecoveryEdit === 'function' ) return renderRecoveryEdit ();
2026-10-26 14:44:07 +08:00
++ recoveryQuoteRequest ; clearTimeout ( recoveryQuoteTimer ); const draft = recoveryStoredDraft ();
2026-11-26 01:01:18 +08:00
$ ( '#main' ). innerHTML = heading ( 'RECOVERY & EXCHANGE' , '� 墧𤣰嚗讐蔭� � ' , '蝘圈� � � � 蝞𨰜� � � 摮䀝� 韐剜� 銝� 甈∩� 摮塩� � ' , button ( '� 亦� 霈啣� ' , 'recovery-scroll-list' , 'quiet' ) + ( typeof recoveryChangesEntryHTML === 'function' ? recoveryChangesEntryHTML () : '' )) + recoveryFormHTML ( draft ) + customerMaterialPanelHTML () + `<section class="panel" id="recovery-history"><div class="panel-title"><h2>� 墧𤣰嚗讐蔭� Z扇敶� </h2> ${ button ( '� 瑟鰵霈啣� ' , 'recovery-refresh-list' , 'quiet' ) } </div> ${ recoveryFilterHTML () } <div id="recovery-list"></div></section>` ;
syncRecoveryForm (); await Promise . allSettled ([ loadCustomerMaterials (), loadRecoveries (), loadRecoveryPools (), typeof loadRecoveryChangeCount === 'function' ? loadRecoveryChangeCount () : Promise . resolve ()]);
2026-10-26 14:44:07 +08:00
}
function recoveryDialog (){
let dialog = $ ( '#recovery-dialog' ); if ( ! dialog ){ dialog = document . createElement ( 'dialog' ); dialog . id = 'recovery-dialog' ; dialog . setAttribute ( 'aria-labelledby' , 'recovery-detail-title' ); dialog . addEventListener ( 'cancel' , event =>{ event . preventDefault (); closeRecoveryDetail ();}); document . body . append ( dialog );} return dialog ;
}
2026-11-04 22:18:56 +08:00
function closeRecoveryDetail (){ ++ recoveryDetailRequest ; recoveryDetail = null ; if ( typeof clearRecoveryEditDetail === 'function' ) clearRecoveryEditDetail (); const dialog = $ ( '#recovery-dialog' ); if ( dialog ){ dialog . close (); dialog . replaceChildren ();}}
2026-10-26 14:44:07 +08:00
function recoveryDetailInput ( value ){
const input = {... value , mode : value . mode , old_lines : value . old_lines || [], buy_rate : ( value . buyRate / 100 ). toFixed ( 2 ), exchange : {...( value . exchange || {}), gold_price : ( value . goldRate / 100 ). toFixed ( 2 ), labor_rate : ( value . laborRate / 100 ). toFixed ( 2 ), labor_mode : value . laborMode , depreciation_rate : ( value . depreciationRate / 100 ). toFixed ( 2 ), pocket : value . newProduct ? . pocket }};
return input ;
}
function recoveryDetailCostsHTML ( value ){
if ( value . mode !== 'exchange' ) return '<p class="small">� 祆活� 墧𤣰甈曉歇� 匧� � � � 甈曆犖� 餉扇嚗諹揚� 嗘� 摨枏� � � 扇銝� 甈~� � </p>' ;
const costs = value . exchange ? . costPayers || {}, fees = value . exchange ? . fee_items || [];
const costMoney = amount => amount == null ? '敺� 瓲摰� ' : recoveryMoney ( amount );
2026-11-24 21:56:05 +08:00
const material = value . exchangeItems ? value . exchangeItems . map (( p , i )=> p . materialCost === 0 ? '' : `<p>� � � ${ i + 1 } ${ e ( p . newProduct . name ) } 銵仿� ${ grams ( p . differenceMg ) } g � 躰晶嚗� <strong> ${ costMoney ( p . materialCost ) } </strong> 繚 ${ p . exchange . costMaterial . mode === 'pool' ? '� 㗇� � 㗇� 瘙删� 韐剜� 隞䀹狡� 交� ' : e ( teamMemberName ( p . exchange . costPayers . material )) + '� 臭� ' } </p>` ). join ( '' ) : value . materialCost === 0 ? '' : `<p>銵仿� 撌桅� � 躰晶嚗� <strong> ${ costMoney ( value . materialCost ) } </strong> ${ value . exchange ? . costMaterial ? . mode === 'pool' ? ' 繚 � 㗇� � 交� 瘙㰘揚� 䠷◇摨𤩺瓲蝞𦯀� 甈曆犖' : ' 繚 ' + e ( teamMemberName ( costs . material )) + '� 臭� ' } </p>` ;
2026-11-24 21:11:32 +08:00
const labor = value . newProducts ? value . newProducts . filter ( row => row . laborCost !== 0 ). map ( row => `<p> ${ e ( row . name ) } 餈𥡝揮撌亥晶嚗� <strong> ${ costMoney ( row . laborCost ) } </strong> 繚 ${ e ( teamMemberName ( row . laborPayer )) } � 臭� </p>`). join ( '' ) : value . laborCost === 0 ? '' : `<p>� 啗揮餈𥡝揮撌亥晶嚗� <strong> ${ costMoney ( value . laborCost ) } </strong> 繚 ${ e ( teamMemberName ( costs . labor )) } � 臭� </p>`;
2026-10-26 14:44:07 +08:00
const card = Object . hasOwn ( value , 'cardFee' ) && value . cardFee !== 0 ? `<p>靽∠鍂� ⊥� 蝏剛晶嚗� <strong> ${ costMoney ( value . cardFee ) } </strong> 繚 暻阡漲� 臭� </p>` : '' ;
return `<div class="recovery-detail-costs"> ${ material }${ labor }${ fees . filter ( fee => fee . amount !== 0 ). map ( fee => `<p> ${ e ( fee . note ) } 嚗� <strong> ${ costMoney ( fee . amount ) } </strong> 繚 ${ e ( teamMemberName ( fee . payer )) } � 臭� </p>`). join ( '' ) }${ card } <p>� 砍� 摰鮋� � 拇隋嚗� <strong> ${ recoveryMoney ( value . profit ) } </strong> ${ value . materialCostPending ? ' 繚 � 躰晶敺� ‘嚗諹‘頞唾揚� 坔� � 芸𢆡� 貊� ' : '' } </p></div>` ;
}
function recoveryDetailHTML ( value ){
2026-11-26 01:01:18 +08:00
const deposits = ( value . exchangeItems ?? [ value ]). filter ( p => p . customerDeposit ). map ( p => '<p class="small">雿輻鍂撖� � 霈啣� ' + e ( p . customerDeposit . number ) + ' 繚 ' + grams ( p . customerDeposit . mg ) + 'g</p>' ). join ( '' );
2026-11-24 21:11:32 +08:00
const input = recoveryDetailInput ( value ), exchange = value . mode === 'exchange' , rows = value . old_lines || [], oldPocket = value . oldPocket ?? '� 墧𤣰� 扳� ' ;
2026-11-26 01:15:41 +08:00
const oldInventory = value . exchangeItems ? value . exchangeItems . map (( p , i )=> `� � � ${ i + 1 } � 睃� � 扳� ${ grams ( p . oldMg - ( p . depositMg || 0 )) } g � � ${ e ( pocketLabel ( p . oldPocket )) } � � ).join(''):`$ { value . depositMg ? '撌脩� 蝞埈唂� � ' : '� 睃� � 扳� ' } $ { grams ( value . oldMg - ( value . depositMg || 0 ))} g$ { pocketCountsEnabled ( oldPocket ) ? ' / ' + stockCountText ( value . oldStockCount ) : '' } � � $ { e ( pocketLabel ( oldPocket ))} 摨枏 � � � ;
const inventory = value . status === 'cancelled' ? `� 砍� 撌脣� 瘨� � � � ${ e ( pocketLabel ( oldPocket )) } � 扳� � 亙� � � ${ exchange ? '� 啗揮� 箏� � � ' : '' } � 唾� 韐剜� 撌脣� � 𠺶� � :oldInventory+(exchange?`蝑厰 � 鈭斗揢 $ { grams ( value . matchedMg )} g � 芾扇摰䂿 � 嚗𥟇鰵韐 � $ { grams ( value . newMg )} g 隞 � $ { value . newProducts ? '� � 辣撖孵� 韐抒� 嚗� � � 滢� � � � 摮矋� ' : value . newProduct ? . pocket ? e ( pocketLabel ( value . newProduct . pocket )) : '憭㚚� 嚗� � � � � � � � 摮矋� ' } � 箏 � � � $ { value . purchaseMg ? '憸嘥� � 墧𤣰雿蹱� ' + grams ( value . purchaseMg ) + 'g嚗� 歇� 餉扇韐剜� � � ' : '瘝⊥� 憸嘥� 雿蹱� 韐剜� � � ' } $ { value . depositMg ? '摰X� 撖� � 雿蹱� ' + grams ( value . depositMg ) + 'g嚗峕� 銝滨� 蝞𨰜� � ' : '' } $ { value . differenceMg ? '銵仿� 撌桅� ' + grams ( value . differenceMg ) + 'g � 匧歇� 㗇� � 祆䔉皞鞉瓲蝞𨰜� � ' : '' } `:'撌脰䌊� 函蒈霈啣� � 磰揚� 辷� � 𣳇� � 血� � � ');
2026-11-26 01:01:18 +08:00
return ` < button class = "dialog-close" data - action = "recovery-close" aria - label = "� 喲𡡒� 墧𤣰蝵格揢� � " > � < /button><div class="eyebrow">${exchange?'EXCHANGE':'RECOVERY'} DETAIL</div><h2 id="recovery-detail-title">${e(value.customer)}</h2><p class="small muted">${e(recoveryModeNames[value.mode])} 繚 ${e(value.number)} 繚 ${e(value.date)} 繚 撘� � 蓥犖 ${e(value.salesperson)} 繚 ${e(teamMemberName(value.member))}</p><div class="actions recovery-detail-actions">${typeof recoveryDetailChangeActionsHTML==='function'?recoveryDetailChangeActionsHTML(value):''}${button('摰X� 憸� � 嚗𤩺� � � ','recovery-print','primary',`data-id="${e(value.id)}"`)}${value.order_id?button('� 亦� � 唾� � � � 桀� ','recovery-open-order','',`data-id="${e(value.order_id)}"`):''}</div><section class="panel"><h3>� 扳� 蝘圈� </h3>${deposits}<div class="table-wrap"><table><thead><tr><th>� 扳� </th><th class="number">� 交� 嚗ā嚗� </th><th class="number">� 𥪜� 嚗ā嚗� </th><th class="number">� 鞱𠧧</th><th class="number">� 睃� 嚗ā嚗� </th></tr></thead><tbody>${rows.map(row=>`<tr><td>${e(row.name||'Au� 扳� ')}</td><td class="number">${grams(row.incomingMg)}</td><td class="number">${grams(row.meltedMg)}</td><td class="number">${e(row.purity)}%</td><td class="number">${grams(row.foldedMg)}</td></tr>`).join('')}</tbody></table></div></section><section class="panel recovery-calculation">${exchange?`${(value.newProducts||[value.newProduct]).map((product,index)=>`<h3>� 啗揮 ${index+1}嚗� ${e(product.name)} 繚 ${grams(product.quantity)}g${pocketCountsEnabled(product.pocket)?' / '+stockCountText(product.stockCount):''} 繚 ${e(pocketLabel(product.pocket)||'憭㚚� ')}</h3>${product.laborAmount!==undefined?'<p>� � � 桀極韐對� '+recoveryMoney(product.laborAmount)+'</p>':''}`).join('')}`:''}${recoverySettlementHTML(value,input)}<p class="small">${value.netSettlement>0?'摰鮋� � 嗆狡韐行� ':value.netSettlement<0?'摰鮋� 隞䀹狡':'� 𣳇� � 圈� � 嗡� '}${value.netSettlement?`嚗� ${e(accountDisplayName(value.payment_account))}${value.netSettlement<0?' 繚 '+e(teamMemberName(value.payer))+'隞䀹狡':''}`:''}</p>${value.note?`<p class="recovery-detail-note">${e(value.note)}</p>`:''}</section><div class="note">${inventory}</div><section class="panel internal recovery-detail-internal"><h3>� � � 霈啗揭</h3><p class="small">${value.purchase_id?'撌脩� � 𣂼� � 磰揚� 躰扇敶𨰻� � ':'� 砍� � 𣳇� 憭𤥁揚� 踺� � '}${value.order_id?'撌脩� � 𣂼� � 娪� � 桀� 嚗� 恥� 瑁揮甈暹𠽌� � � 摰鮋� � � 憸嘥� � 怨扇韐艾� � ':''}</p>${recoveryDetailCostsHTML(value)}${value.order_id?'<p class="small muted">� � � � 鞉𧋦� � � 甈曆犖銝𤾸⏚瘨血虾� 典� � 娪� � 桀� � 詨笆嚗� 恥� 瑟� � 唬� � 曄內� � </p>':''}</section>`;
2026-10-26 14:44:07 +08:00
}
async function openRecovery ( id , saved = null ){
const dialog = recoveryDialog (), request =++ recoveryDetailRequest , user = recoveryUser (); recoveryDetail = null ;
dialog . innerHTML = '<button class="dialog-close" data-action="recovery-close" aria-label="� 喲𡡒� 墧𤣰蝵格揢� � ">� </button><h2 id="recovery-detail-title">� 墧𤣰嚗讐蔭� W � </h2><p aria-live="polite">甇� 銁霂餃� � 閙旿� � </p>' ; if ( ! dialog . open ) dialog . showModal ();
2026-11-04 22:18:56 +08:00
try { const edit = typeof validateRecoveryEditDetail === 'function' ? validateRecoveryEditDetail ( await api ( '/api/recoveries/' + encodeURIComponent ( id ) + '/edit' ), id ) : null , value = edit ? . record || saved || await api ( '/api/recoveries/' + encodeURIComponent ( id )); if ( request !== recoveryDetailRequest || user !== recoveryUser ()) return ; if ( edit ) recoveryDetailEdit = edit ; if ( value . id !== id ) throw new Error ( '餈𥪜� � � � � 桐� � � � 匧� � 桐� 銝� � 湛� 霂琿� 霂𨰻� � ' ); recoveryDetail = value ; dialog . innerHTML = recoveryDetailHTML ( value ) + ( edit ? recoveryEditPanelHTML ( edit ) : '' ); dialog . scrollTop = 0 ;}
2026-10-26 14:44:07 +08:00
catch ( err ){ if ( request === recoveryDetailRequest && user === recoveryUser ()) dialog . innerHTML = `<button class="dialog-close" data-action="recovery-close" aria-label="� 喲𡡒� 墧𤣰蝵格揢� � ">� </button><h2 id="recovery-detail-title">� 閙旿� � 𧊋霂餃� </h2><div class="error"> ${ e ( err . name === 'AbortError' ? '霂餃� 頞� 𧒄嚗諹窈� 滩� � � ' : err . message ) } </div> ${ button ( '� 齿鰵霂餃� 餈坔� � � ' , 'recovery-open' , '' , `data-id=" ${ e ( id ) } "` ) } ` ;}
}
async function finishRecoverySave ( input , result ){
2026-11-26 01:01:18 +08:00
customerMaterialCache = null ;
2026-10-26 14:44:07 +08:00
localStorage . removeItem ( recoveryDraftKey ()); ++ recoveryQuoteRequest ; clearTimeout ( recoveryQuoteTimer ); invalidateMaterialPools (); invalidateReport (); tab = 'recoveries' ;
const filters = recoveryGetFilters (); Object . assign ( filters ,{ from : input . date , date : input . date , mode : '' , member : '' });
document . querySelectorAll ( 'nav button' ). forEach ( node => node . classList . toggle ( 'active' , node . dataset . tab === tab ));
2026-11-08 03:30:58 +08:00
$ ( '#main' ). innerHTML = heading ( 'SAVED' , recoveryModeNames [ input . mode ] + '� 訫歇靽嘥� ' , e ( input . customer ) + ' 繚 ' + e ( result . number || '撌脰䌊� 函� � � ' )) + `<section class="panel"><div id="recovery-saved-status" aria-live="polite">蝘圈� 銝𡒊� 蝞堒歇霈啗揭� � ${ input . mode === 'direct' ? '韐剜� � � ' + e ( pocketLabel ( '� 墧𤣰� 扳� ' )) + '摨枏� 撌脩� 銝� 撟嗥蒈霈啜� � ' : '蝑厰� 摰䂿� � � ‘� 穃榆� 滚� 雿蹱� 撌脫� � 砍� 蝏梶� � 餉扇� � ' } </div><div class="actions recovery-saved-actions"> ${ button ( '� 亦� 撌脖� 摮睃� � � ' , 'recovery-open' , 'primary' , `data-id=" ${ e ( result . id ) } "` ) }${ button ( '摰X� 憸� � 嚗𤩺� � � ' , 'recovery-print' , '' , `data-id=" ${ e ( result . id ) } "` ) }${ button ( '蝏抒賒撘� � 虫� � � ' , 'recovery-new' , '' , `data-mode=" ${ e ( input . mode ) } "` ) } </div></section><section class="panel" id="recovery-history"><h2>� 墧𤣰嚗讐蔭� Z扇敶� </h2> ${ recoveryFilterHTML () } <div id="recovery-list"></div></section>` ;
2026-10-26 14:44:07 +08:00
await openRecovery ( result . id , result );
const results = await Promise . allSettled ([ refresh ( false ), loadRecoveries ()]); if ( results . some ( value => value . status === 'rejected' ) && $ ( '#recovery-saved-status' )) $ ( '#recovery-saved-status' ). textContent = '� 閙旿撌脩� 靽嘥� 嚗峕� � 唳� � 餅� � 芾粉� 啜� � 虾� 亦� � 𡝗� � 啣歇靽嘥� � 閙旿嚗𥕢� 閬� � 憭滚� � 𨰻� � ' ;
toast ( recoveryModeNames [ input . mode ] + '� 訫歇靽嘥� ' );
}
async function submitRecovery ( form ){
2026-11-04 22:18:56 +08:00
if ( form . dataset ? . recoveryEdit === 'true' && typeof submitRecoveryEdit === 'function' ) return submitRecoveryEdit ( form );
2026-10-26 14:44:07 +08:00
syncRecoveryForm ( form ,{ quote : false }); const input = validateRecoveryInput ( recoveryInput ( recoveryFormDraft ( form ))); $ ( '#recovery-form-error' ). innerHTML = '' ;
const result = await mutate ( '/api/recoveries' , input ); return await finishRecoverySave ( input , result );
}
function recoveryLinkedOrderActionsHTML ( order ,{ reviewAllowed = false } = {}){
return button ( '� 亦� 蝵格揢蝏梶� � � ' , 'recovery-open' , 'primary' , `data-id=" ${ e ( order . recovery_id ) } "` ) + button ( '摰X� 憸� � 嚗𤩺� � � ' , 'recovery-print' , '' , `data-id=" ${ e ( order . recovery_id ) } "` ) + ( reviewAllowed ? button ( '暻阡漲憭齿瓲' , 'show-review' ) : '' );
}
2026-11-04 22:18:56 +08:00
function recoveryLinkedOrderNoticeHTML ( order ){ return order . recovery_id ? '<div class="note">餈坔� � � � 桀� � 梁蔭� Y� 蝞𡑒䌊� 函� � 僐� � � � 譌� � 𠽌� � � � 嗡� 甈曇窈� 典� � 𠉛蔭� W� � 詨笆嚗𥕢耨� 寞� � 𡝗� 霂瑚� � 唾� 蝵格揢� 閗� � 伐� � 游� � 嗡� 甈整� � 揚� 嗘� 摨枏� 銝� 韏瑟凒甇� � � </div>' : '' ;}
2026-10-26 14:44:07 +08:00
document . addEventListener ( 'input' , event =>{
const form = event . target . closest ? .( '#recovery-form' ); if ( ! form ) return ;
2026-11-24 21:56:05 +08:00
if ( form . dataset . independentProducts === 'true' ) return recoveryItemEvent ( event , form );
2026-10-26 14:44:07 +08:00
if ( event . target . name === 'incoming_weight' && form . dataset . melted_manual !== 'true' ) recoveryField ( form , 'melted_weight' ). value = event . target . value ;
if ( event . target . name === 'melted_weight' ) form . dataset . melted_manual = 'true' ;
if ( event . target . name === 'buy_total' ) form . dataset . buy_total_manual = 'true' ;
if ( event . target . name === 'depreciation_weight' ) form . dataset . depreciation_manual = 'true' ;
syncRecoveryForm ( form );
});
document . addEventListener ( 'change' , event =>{
const form = event . target . closest ? .( '#recovery-form' ); if ( ! form ) return ;
2026-11-24 21:56:05 +08:00
if ( form . dataset . independentProducts === 'true' ) return recoveryItemEvent ( event , form );
2026-10-26 14:44:07 +08:00
if ( event . target . name === 'member' ){
const member = event . target . value ; recoveryField ( form , 'payer' ). value = member ;
for ( const name of [ 'material_payer' , 'labor_payer' , 'fee_payer' ]) recoveryField ( form , name ). value = member ;
const recipient = recoveryField ( form , 'payment_recipient' ); recipient . dataset . previousRecipient = recoveryPrefix ( member ); if ( recoveryField ( form , 'payment_method' ). value !== '靽∠鍂� � ' ) recipient . value = recoveryPrefix ( member );
}
if ( event . target . name === 'date' ){ const pool = recoveryField ( form , 'material_pool_id' ); if ( ! pool . value || pool . value > event . target . value ){ pool . innerHTML = opts ([[ event . target . value , event . target . value ]], event . target . value );} recoveryPoolOptions ( form );}
syncRecoveryForm ( form );
});
document . addEventListener ( 'click' , async event =>{
const node = event . target . closest ? .( 'button' ), action = node ? . dataset . action ; if ( ! action ? . startsWith ( 'recovery-' ) || node . disabled ) return ;
try {
2026-11-30 15:40:40 +08:00
if ( action === 'recovery-use-daily-rate' ) return await recoveryUseDailyRate ( node );
2026-11-24 21:56:05 +08:00
if ( action === 'recovery-item-reset-buy' || action === 'recovery-item-reset-depreciation' ){ const form = $ ( '#recovery-form' ), row = form . querySelector ( '[data-recovery-item="' + node . dataset . index + '"]' ); row . dataset [ action === 'recovery-item-reset-buy' ? 'buy_total_manual' : 'depreciation_manual' ] = 'false' ; return syncRecoveryItems ( form );}
2026-11-24 21:11:32 +08:00
if ( action === 'recovery-add-product' || action === 'recovery-remove-product' ){
const form = $ ( '#recovery-form' ); if ( busy || pending ()) return ; rememberRecoveryDraft ( form ); const draft = recoveryFormDraft ( form ); draft . extra_products ??= [];
if ( action === 'recovery-add-product' ){ if ( draft . extra_products . length >= 59 ) throw new Error ( '瘥誩� � � 憭� 60隞嗆鰵韐扼� � ' ); draft . extra_products . push ({... recoveryDefaults ( 'exchange' ), labor_rate : '0' , cost_labor_value : '0' , labor_payer : draft . member });}
else draft . extra_products . splice ( Number ( node . dataset . index ), 1 );
if ( form . dataset . recoveryEdit === 'true' ){ recoveryEditEntry . draft = draft ; form . outerHTML = recoveryEditingFormHTML ( recoveryEditEntry );} else form . outerHTML = recoveryFormHTML ( draft );
recoveryPoolOptions ( $ ( '#recovery-form' )); syncRecoveryForm (); return ;
}
2026-10-26 14:44:07 +08:00
if ( action === 'recovery-mode' ){
const form = $ ( '#recovery-form' ), draft = recoveryFormDraft ( form ); draft . mode = node . dataset . mode ; draft . buy_total_manual = false ; draft . buy_total = '' ; rememberRecoveryDraft ( form ); localStorage . setItem ( recoveryDraftKey (), JSON . stringify ( draft )); return await renderRecoveries ();
}
if ( action === 'recovery-reset-buy' ){ const form = $ ( '#recovery-form' ); form . dataset . buy_total_manual = 'false' ; return syncRecoveryForm ( form );}
if ( action === 'recovery-reset-depreciation' ){ const form = $ ( '#recovery-form' ); form . dataset . depreciation_manual = 'false' ; return syncRecoveryForm ( form );}
if ( action === 'recovery-refresh-list' ) return await loadRecoveries ();
if ( action === 'recovery-scroll-list' ) return $ ( '#recovery-history' ) ? . scrollIntoView ({ behavior : 'smooth' , block : 'start' });
if ( action === 'recovery-open' ) return await openRecovery ( node . dataset . id );
if ( action === 'recovery-close' ) return closeRecoveryDetail ();
if ( action === 'recovery-print' ){ window . open ( '/print/recoveries/' + encodeURIComponent ( node . dataset . id ), '_blank' , 'noopener' ); return toast ( '摰X� � 枏㫲憿萄歇� 枏� 嚗𥡝𥅾� 芸枂� 堆� 霂瑕� 霈豢迨蝵𤑳� � 枏� � 啁� � � ' );}
if ( action === 'recovery-open-order' ){ closeRecoveryDetail (); return await openOrder ( node . dataset . id );}
2026-11-27 15:48:37 +08:00
if ( action === 'recovery-new' ){ customerMaterialPage = false ; localStorage . setItem ( recoveryDraftKey (), JSON . stringify ({... recoveryDefaults ( node . dataset . mode || 'direct' ), independent_products : false })); return await renderRecoveries ();}
2026-10-26 14:44:07 +08:00
} catch ( err ){ toast ( err . message , true );}
});
document . addEventListener ( 'submit' , async event =>{
const form = event . target ; if ( ! [ 'recovery-form' , 'recovery-filter-form' ]. includes ( form . id )) return ; event . preventDefault ();
try { if ( form . id === 'recovery-filter-form' ){ const data = Object . fromEntries ( new FormData ( form )); Object . assign ( recoveryGetFilters (),{ from : data . from , date : data . date , mode : data . mode || '' , member : state . user . role === 'owner' ? data . member || '' : '' }); return await loadRecoveries ();} await submitRecovery ( form );}
catch ( err ){ if ( form . id === 'recovery-form' && $ ( '#recovery-form-error' )) $ ( '#recovery-form-error' ). innerHTML = `<div class="error"> ${ e ( err . message ) } </div>` ; toast ( err . message , true );}
});
2026-11-24 21:56:05 +08:00
// � 啁� 瘥譍辣摰峕㟲蝵格揢嚗𥟇唂� � � � 冽唂� 嗵� � 閙旿隞滩粥� 蠘”� 訫� 蝞埈� � �
2026-11-26 01:15:41 +08:00
const recoveryItemFields = [ 'surplus_mode' , 'surplus_memo' , 'old_source' , 'deposit_id' , 'deposit_weight' , 'old_name' , 'incoming_weight' , 'melted_weight' , 'purity' , 'old_pocket' , 'old_stock_count' , 'buy_rate' , 'buy_total' ,... recoveryProductFields , 'gold_price' , 'depreciation_weight' , 'depreciation_rate' , 'material_source' , 'material_pool_id' , 'material_rate' , 'material_payer' ];
2026-11-24 21:56:05 +08:00
function recoveryItemsInput ( draft ,{ quote = false } = {}){
const common = { mode : 'exchange' , date : draft . date , customer : draft . customer , salesperson : draft . salesperson , member : draft . member , payer : draft . payer , payment_method : draft . payment_method , payment_recipient : draft . payment_recipient , payout_method : draft . payout_method , note : draft . note , verified : draft . verified };
const items = [ draft ,...( draft . extra_products || [])]. map ( row =>{
const single = recoveryInput ({... recoveryDefaults ( 'exchange' ),... row ,... common , independent_products : false , extra_products : [], charges : [], fee_items : [], charge_amount : '0' , fee_amount : '0' , discount : '0' , rounding_mode : 'cent' },{ quote });
2026-11-26 01:15:41 +08:00
return {...( single . surplus_mode ? { surplus_mode : single . surplus_mode , surplus_memo : single . surplus_memo } : {}),...( single . old_source ? { old_source : single . old_source , deposit_id : single . deposit_id , deposit_weight : single . deposit_weight } : {}), old_lines : single . old_lines , old_pocket : single . old_pocket ,...( single . old_stock_count == null ? {} : { old_stock_count : single . old_stock_count }), buy_rate : single . buy_rate ,...( single . buy_total == null ? {} : { buy_total : single . buy_total }), exchange : single . exchange };
2026-11-24 21:56:05 +08:00
});
const first = recoveryInput ({... draft , independent_products : false , extra_products : [], discount : '0' , rounding_mode : 'cent' },{ quote : true }), input = {... first , old_lines : items . flatMap ( row => row . old_lines ), verified :! quote && draft . verified === true , exchange : { items , charges : first . exchange . charges , fee_items : first . exchange . fee_items , discount : draft . discount || '0' , rounding_mode : draft . rounding_mode || 'yuan' }};
2026-11-26 01:15:41 +08:00
delete input . old_source ; delete input . deposit_id ; delete input . deposit_weight ; delete input . surplus_mode ; delete input . surplus_memo ;
2026-11-24 21:56:05 +08:00
const q = recoveryCalculate ( input ); input . payment_account = q . netSettlement > 0 ? ( draft . payment_method === '靽∠鍂� � ' ? '暻阡漲靽∠鍂� � ' : ( draft . payment_recipient || recoveryPrefix ( draft . member )) + ( draft . payment_method || '敺桐縑' )) : recoveryPrefix ( draft . payer || draft . member ) + ( draft . payout_method || '敺桐縑' ); return input ;
}
function recoveryItemsCalculate ( input ){
2026-11-26 01:15:41 +08:00
const parts = input . exchange . items . map ( row => recoveryCalculate ({... input ,... row , buy_total : row . buy_total , buy_rate : row . buy_rate , surplus_mode : row . surplus_mode , surplus_memo : row . surplus_memo , mode : 'exchange' , exchange : row . exchange }));
2026-11-24 21:56:05 +08:00
const q = { mode : 'exchange' , old_lines : parts . flatMap ( p => p . old_lines ), exchangeItems : parts };
2026-11-26 01:15:41 +08:00
for ( const key of [ 'oldMg' , 'newMg' , 'matchedMg' , 'differenceMg' , 'surplusMg' , 'depositMg' , 'purchaseMg' , 'goldAmount' , 'laborAmount' , 'depreciationMg' , 'depreciationAmount' , 'purchaseAmount' , 'defaultPurchaseAmount' ]) q [ key ] = recoveryLimit ( parts . reduce (( n , p )=> n + p [ key ], 0 ));
2026-11-24 21:56:05 +08:00
q . chargesAmount = recoveryLimit (( input . exchange . charges || []). reduce (( n , r )=> n + recoveryUnits ( r . amount , 2 , '� 嗡� � 嗉晶' ), 0 )); q . discount = recoveryUnits ( input . exchange . discount || '0' , 2 , '� 游� 隡䀹� ' );
const before = recoveryLimit ( q . goldAmount + q . laborAmount + q . depreciationAmount + q . chargesAmount ) - q . discount ; if ( before < 0 ) throw new Error ( '隡䀹� � 煾� 銝滩� 憭找� 蝵格揢韐寧鍂' ); q . receivable = input . exchange . rounding_mode === 'yuan' ? Math . floor (( before + 50 ) / 100 ) * 100 : before ; q . roundingAdjustment = q . receivable - before ; q . netSettlement = q . receivable - q . purchaseAmount ; q . cashReceipt = Math . max ( 0 , q . netSettlement ); q . cashPayment = Math . max ( 0 , - q . netSettlement ); return q ;
}
function recoveryItemsFormDraft ( form ){
const read = ( scope , name )=> recoveryText ( recoveryField ( scope , name ) ? . value ), flat = Object . fromEntries ( recoveryDraftFields . map ( k =>[ k , read ( form , k )]));
const rows = [... form . querySelectorAll ( '[data-recovery-item]' )]. map (( row , i )=>{
const prefix = i ? 'extra_' : '' ; return {... Object . fromEntries ( recoveryItemFields . map ( k =>[ k , read ( row , prefix + k )])),... Object . fromEntries ([ 'buy_total_manual' , 'depreciation_manual' , 'melted_manual' ]. map ( k =>[ k , row . dataset [ k ] === 'true' ]))};
});
const draft = {... flat ,... rows [ 0 ], extra_products : rows . slice ( 1 ), independent_products : true , verified :!! recoveryField ( form , 'verified' ) ? . checked }; if ( state . user . role !== 'owner' ) draft . member = currentMember (); if ( form . dataset . recoveryEdit === 'true' && typeof recoveryEditFormDraft === 'function' ) return recoveryEditFormDraft ( form , draft ); return draft ;
}
function recoveryItemHTML ( row , index , date ){
const prefix = index ? 'extra_' : '' , name = k => prefix + k , members = teamMemberOptions ();
const existing = typeof recoveryEditEntry !== 'undefined' ? recoveryEditEntry ? . data ? . inputs ? . exchange ? . items ? .[ index ] : null ;
2026-11-30 15:40:40 +08:00
return `<section class="panel" data-recovery-item=" ${ index } " ${ index ? `data-recovery-product=" ${ index - 1 } "` : '' } data-buy_total_manual=" ${ !! row . buy_total_manual } " data-depreciation_manual=" ${ !! row . depreciation_manual } " data-melted_manual=" ${ !! row . melted_manual } "><div class="panel-title"><h2>蝵格揢� � � ${ index + 1 } </h2> ${ index ? button ( '蝘駁膄� � � ' , 'recovery-remove-product' , 'quiet' , `data-index=" ${ index - 1 } "` ) : '' } </div> ${ customerMaterialSourceHTML ( row , prefix ) } <h3>� 砌辣� 扳� 蝘圈� </h3><div class="recovery-row"> ${ field ( '� 扳� � 滨妍' , name ( 'old_name' ), row . old_name || 'Au� 扳� ' , 'text' , 'maxlength="60" required' ) }${ recoveryNumberField ( '� 交� � 漤� 嚗ā嚗� ' , name ( 'incoming_weight' ), row . incoming_weight , 3 , 'required' ) }${ recoveryNumberField ( '� 𥪜� � 漤� 嚗ā嚗� ' , name ( 'melted_weight' ), row . melted_weight , 3 , 'required' ) }${ recoveryNumberField ( '� 鞱𠧧嚗� %嚗� ' , name ( 'purity' ), row . purity , 3 , 'max="100" required' ) }${ pocketChoice ( '� 扳� � 亙� 韐抒� ' , name ( 'old_pocket' ), row . old_pocket ?? '� 墧𤣰� 扳� ' ,{ blank : null , historical :!! existing && existing . old_pocket === row . old_pocket } )} ${ stockCountField ( row . old_pocket , row . old_stock_count ,{ name : name ( 'old_stock_count' ), title : '� 扳� � 亙� � 圈� 嚗� 笆嚗� ' , help : '' , optional :!! existing && existing . old_stock_count == null } )}</div><p class="small muted" data-item-folded></p><h3>� 砌辣� W枂� 啗揮</h3> ${ recoveryProductFieldsHTML ( row ,{ prefix , original : existing ? . exchange } )}<div class="recovery-row"> ${ recoveryCustomerRateField ( '銵仿� � � � 桀� 隞瘀� � � � g嚗� ' , name ( 'gold_price' ), row . gold_price ) }${ recoveryNumberField ( '� 䀹唂韐孵� 隞瘀� � � � g嚗� ' , name ( 'depreciation_rate' ), row . depreciation_rate , 2 , 'required' ) }${ recoveryNumberField ( '� 䀹唂霈∟晶� 钅� 嚗ā嚗� 虾� 對� ' , name ( 'depreciation_weight' ), row . depreciation_weight , 3 , 'required' ) } </div> ${ button ( '� W � � 砌辣暺䁅恕� 䀹唂� 钅� ' , 'recovery-item-reset-depreciation' , 'quiet' , `data-index=" ${ index } "` ) } <div data-item-buy><h3>� 砌辣雿蹱� 憭� � </h3> ${ recoverySurplusFieldsHTML ( row , prefix ) } <div data-surplus-buy><div class="recovery-row"> ${ recoveryCustomerRateField ( '� 墧𤣰� 蓥遠嚗� � 嚗𣲵嚗� ' , name ( 'buy_rate' ), row . buy_rate ) }${ recoveryNumberField ( '雿蹱� � 墧𤣰甈橘� � � � � 舀㺿嚗� ' , name ( 'buy_total' ), row . buy_total , 2 , 'required' ) } </div> ${ button ( '� W � � 砌辣� 芸𢆡� 墧𤣰甈� ' , 'recovery-item-reset-buy' , 'quiet' , `data-index=" ${ index } "` ) } </div></div><div class="internal"><h3>� 砌辣� � � � 鞉𧋦</h3><div data-item-material><div class="recovery-row"> ${ choice ( '撌桅� � 躰晶� 交� ' , name ( 'material_source' ),[[ 'pool' , '瘥𤩺𠯫� 蹱� ' ],[ 'manual' , '� 见𢆡餈𥡝揮� 嗘遠' ]], row . material_source ) } <label data-item-pool>� 蹱� � 交� <select name=" ${ name ( 'material_pool_id' ) } "> ${ opts ([[ row . material_pool_id || date , row . material_pool_id || date ]], row . material_pool_id || date ) } </select></label><div data-item-manual> ${ recoveryNumberField ( '撌桅� 餈𥡝揮� 嗘遠嚗� � 嚗𣲵嚗� ' , name ( 'material_rate' ), row . material_rate ) }${ choice ( '� 躰晶隞䀹狡鈭� ' , name ( 'material_payer' ), members , row . material_payer ) } </div></div></div> ${ recoveryProductLaborHTML ( row ,{ prefix } )}<p class="small" data-item-cost></p></div><div class="recovery-calculation" data-item-formula></div></section>` ;
2026-11-24 21:56:05 +08:00
}
function recoveryItemsFormHTML ( draft ){
const base = recoveryFormHTML ({... draft , independent_products : false , extra_products : []}), start = base . indexOf ( '<section class="panel"><div class="panel-title"><h2>� 扳� 蝘圈� ' ), calc = base . indexOf ( '<section class="panel recovery-calculation" aria-label=' ), internal = base . indexOf ( '<section class="panel internal recovery-internal"' ), save = base . indexOf ( '<section class="panel recovery-save-panel">' );
const shared = `<section class="panel"><h3>� 游� � 嗉晶銝舘晶� � </h3><div class="recovery-row"> ${ field ( '� 嗡� � 嗉晶� 滨妍' , 'charge_name' , draft . charge_name , 'text' , 'maxlength="60"' ) }${ recoveryNumberField ( '� 嗡� � 嗉晶嚗� � 嚗� ' , 'charge_amount' , draft . charge_amount ) }${ recoveryNumberField ( '� 游� 隡䀹� 嚗� � 嚗� ' , 'discount' , draft . discount ) }${ choice ( '� 游� � 𡝗㟲' , 'rounding_mode' ,[[ 'yuan' , '� 𥡝� 鈭𥪜� � 啣� ' ],[ 'cent' , '靽萘� � 啣� ' ]], draft . rounding_mode ) } </div><div class="internal"><div class="recovery-row"> ${ field ( '� 嗡� � 鞉𧋦� 滨妍' , 'fee_note' , draft . fee_note , 'text' , 'maxlength="100"' ) }${ recoveryNumberField ( '� 嗡� 摰鮋� � 鞉𧋦嚗� � 嚗� ' , 'fee_amount' , draft . fee_amount ) }${ choice ( '韐寧鍂隞䀹狡鈭� ' , 'fee_payer' , teamMemberOptions (), draft . fee_payer ) } </div></div><p class="small" id="recovery-material-note">瘥譍辣� 扳� � 芸‵� 嗘� 甈∴� 銵仿� � 䔶� � 坔� � 急� � 砌辣� 蓥遠霈∠� � � </p></section>` ;
2026-11-28 01:28:39 +08:00
return base . slice ( 0 , start ). replace ( '<form id="recovery-form"' , '<form id="recovery-form" data-independent-products="true"' ) + `<datalist id="recovery-product-names"> ${ productNames . filter ( n => ! LedgerCalc . isSilver ( n )). map ( n => `<option value=" ${ e ( n ) } "></option>` ). join ( '' ) } </datalist>` + [ draft ,...( draft . extra_products || [])]. map (( row , i )=> recoveryItemHTML ( row , i , draft . date )). join ( '' ) + `<div class="form-actions"> ${ button ( '嚗� 瘛餃� 蝵格揢� 啗揮' , 'recovery-add-product' ) } </div>` + shared + base . slice ( calc , internal ) + base . slice ( save );
2026-11-24 21:56:05 +08:00
}
function recoveryItemsPoolOptions ( form ){
const date = recoveryField ( form , 'date' ). value , member = recoveryField ( form , 'member' ). value , rows = typeof materialPoolRows === 'function' ? materialPoolRows () : materialPoolsCache ? . rows || [];
for ( const [ i , section ] of [... form . querySelectorAll ( '[data-recovery-item]' )]. entries ()){
const select = recoveryField ( section ,( i ? 'extra_' : '' ) + 'material_pool_id' ), selected = select . value && select . value <= date ? select . value : date , available = rows . filter ( p => p . date <= date ); if ( ! available . some ( p => p . id === selected )) available . push ({ id : selected , date : selected , remainingMg : 0 });
select . innerHTML = opts ( available . map ( p =>[ p . id , p . date + ' 繚 � 砍� 雿� ' + grams ( p . remainingMg ) + 'g' + ( p . personalPools ? '嚗譍葵鈭箔� ' + grams ( p . personalPools [ member ] ? . remainingMg || 0 ) + 'g' : '' )]), selected );
}
}
function syncRecoveryItems ( form ,{ quote = true } = {}){
const draft = recoveryItemsFormDraft ( form ); let error = '' , input = null , total = null ;
const toggle = ( node , enabled )=>{ if ( ! node ) return ; node . hidden =! enabled ; for ( const c of node . querySelectorAll ( 'input,select,button' )) c . disabled =! enabled ;};
for ( const [ i , section ] of [... form . querySelectorAll ( '[data-recovery-item]' )]. entries ()){
const row = i ? draft . extra_products [ i - 1 ] : draft , prefix = i ? 'extra_' : '' , control = k => recoveryField ( section , prefix + k );
2026-11-26 01:01:18 +08:00
customerMaterialSyncFields ( section , row , prefix );
let oldMg = null , newMg = null ; try { oldMg = recoveryCalculate ({ mode : 'direct' , old_lines : row . old_source === 'deposit' ? customerMaterialOldLines ( row ) : [{ name : row . old_name , incoming_weight : row . incoming_weight , melted_weight : row . melted_weight , purity : row . purity }], buy_rate : '1' }). oldMg ; newMg = recoveryUnits ( row . new_quantity , 3 , '� 啗揮� 钅� ' ,{ zero : false });} catch {}
2026-11-24 21:56:05 +08:00
section . querySelector ( '[data-item-folded]' ). textContent = oldMg === null ? '� 睃� � 漤� = � 𥪜� � 漤� � � 鞱𠧧 繩 100� � ' : '� 睃� � 扳� ' + grams ( oldMg ) + 'g� � ' ;
if ( oldMg !== null && newMg !== null &&! row . depreciation_manual ) control ( 'depreciation_weight' ). value = row . depreciation_weight = grams ( Math . min ( oldMg , newMg ));
const difference = oldMg !== null && newMg !== null && newMg > oldMg , surplus = oldMg !== null && newMg !== null && oldMg > newMg ;
2026-11-30 15:40:40 +08:00
toggle ( control ( 'gold_price' ). closest ( '.recovery-customer-rate' ) || control ( 'gold_price' ). closest ( 'label' ), difference ); toggle ( section . querySelector ( '[data-item-buy]' ), surplus ); toggle ( section . querySelector ( '[data-item-material]' ), difference ); toggle ( section . querySelector ( '[data-item-pool]' ), difference && row . material_source === 'pool' ); toggle ( section . querySelector ( '[data-item-manual]' ), difference && row . material_source === 'manual' );
2026-11-26 01:15:41 +08:00
recoverySurplusSync ( section , row , surplus , true , prefix );
2026-11-24 21:56:05 +08:00
if ( ! surplus ){ control ( 'buy_total' ). value = row . buy_total = '0' ; section . dataset . buy_total_manual = 'false' ; row . buy_total_manual = false ;}
const existing = typeof recoveryEditEntry !== 'undefined' ? recoveryEditEntry ? . data ? . inputs ? . exchange ? . items ? .[ i ] : null ;
syncStockCountField ( section ,{ name : prefix + 'stockCount' , pocket : row . pocket , optional :!! existing && existing . exchange . stockCount == null }); syncStockCountField ( section ,{ name : prefix + 'old_stock_count' , pocket : row . old_pocket , optional :!! existing && existing . old_stock_count == null });
recoverySetLabel ( section , prefix + 'labor_rate' , row . labor_mode === 'total' ? '� � � 桀極韐對� � � � ' : '� � � 桀極韐對� � � � g嚗� ' ); recoverySetLabel ( section , prefix + 'cost_labor_value' , row . cost_labor_mode === 'total' ? '餈𥡝揮撌亥晶嚗� � 嚗� ' : '餈𥡝揮撌亥晶嚗� � 嚗𣲵嚗� ' );
try { const v = recoveryInput ({... draft ,... row , mode : 'exchange' , independent_products : false , extra_products : [], charges : [], fee_items : [], charge_amount : '0' , fee_amount : '0' , discount : '0' , rounding_mode : 'cent' },{ quote : true }), q = recoveryCalculate ( v ); if ( ! row . buy_total_manual ) control ( 'buy_total' ). value = ( q . defaultPurchaseAmount / 100 ). toFixed ( 2 ); section . querySelector ( '[data-item-formula]' ). innerHTML = recoverySettlementHTML ( q , v );}
catch ( err ){ section . querySelector ( '[data-item-formula]' ). innerHTML = `<p class="muted"> ${ e ( err . message ) } </p>` ;}
}
try { input = recoveryInput ( recoveryItemsFormDraft ( form ),{ quote : true }); total = recoveryCalculate ( input ); $ ( '#recovery-calculation' ). innerHTML = recoveryItemsSummaryHTML ( total , input );} catch ( err ){ error = err . message ; $ ( '#recovery-calculation' ). innerHTML = `<p class="muted"> ${ e ( error ) } </p>` ;}
const net = total ? . netSettlement ?? 0 , card = net > 0 && draft . payment_method === '靽∠鍂� � ' ; for ( const [ selector , on ] of [[ '.recovery-cash-in' , net > 0 ],[ '.recovery-cash-out' , net < 0 ]]) for ( const node of form . querySelectorAll ( selector )) toggle ( node , on );
const recipient = recoveryField ( form , 'payment_recipient' ); if ( card ){ if ( recipient . dataset . cardLocked !== 'true' ) recipient . dataset . previousRecipient = recipient . value ; recipient . value = '暻阡漲' ; recipient . dataset . cardLocked = 'true' ; recipient . disabled = true ;} else if ( recipient . dataset . cardLocked === 'true' ){ recipient . value = recipient . dataset . previousRecipient || recoveryPrefix ( draft . member ); recipient . dataset . cardLocked = 'false' ;}
$ ( '#recovery-card-owner' ). hidden =! card ; $ ( '#recovery-card-fee' ). hidden =! card ; if ( card ) $ ( '#recovery-card-fee' ). textContent = '靽∠鍂� ⊥� 蝏剛晶 ' + recoveryMoney ( CreditCardFees . amount ( net , recoveryCardRate ())) + '嚗屸漲暻虫� 甈整� � ' ;
rememberRecoveryDraft ( form ); if ( quote ){ ++ recoveryQuoteRequest ; clearTimeout ( recoveryQuoteTimer ); $ ( '#recovery-quote-status' ). textContent = error ? '' : '甇� 銁� 詨笆蝏梶� � � ' ; if ( input &&! error ) recoveryQuoteTimer = setTimeout (()=> loadRecoveryQuote ( form ), 350 );} return total ;
}
2026-11-26 01:15:41 +08:00
function recoveryItemsSummaryHTML ( q , input ){ return `<p>� 𣂷辣銵仿� � � 恣 ${ grams ( q . differenceMg ) } g嚗� ${ recoveryMoney ( q . goldAmount ) } </p><p>� 啗揮撌亥晶� � 恣嚗� ${ recoveryMoney ( q . laborAmount ) } 嚗𥟇� � 扯晶� � 恣嚗� ${ recoveryMoney ( q . depreciationAmount ) } </p><p>雿蹱� � 墧𤣰� � 恣 ${ grams ( q . surplusMg - ( q . depositMg || 0 )) } g嚗� ${ recoveryMoney ( q . purchaseAmount ) } </p> ${ q . depositMg ? '<p><strong>雿蹱� 撖� � � � 恣 ' + grams ( q . depositMg ) + 'g嚗峕� 銝滨� 蝞𨰜� � </strong></p>' : '' } <p>� 嗡� � 嗉晶 ${ recoveryMoney ( q . chargesAmount ) } � � � 游� 隡䀹� ${ recoveryMoney ( q . discount ) } 嚗𥕦� � 渲� � � ${ recoveryMoney ( q . roundingAdjustment ?? q . rounding_adjustment ?? 0 ) } </p><p>� � 蝏� � 蝞� = 蝵格揢韐寧鍂 ${ recoveryMoney ( q . receivable ) } � � 雿蹱� � 墧𤣰甈� ${ recoveryMoney ( q . purchaseAmount ) } </p><div class="recovery-net"><span> ${ q . netSettlement > 0 ? '摰X� 銵交狡' : q . netSettlement < 0 ? '摨烾� 隞䀹狡' : '� 𣳇� � 圈� � 嗡� ' } </span><strong> ${ recoveryMoney ( Math . abs ( q . netSettlement )) } </strong></div>` ;}
2026-11-24 21:56:05 +08:00
function recoveryItemEvent ( event , form ){
const section = event . target . closest ( '[data-recovery-item]' ), key = event . target . name ? . replace ( /^extra_/ , '' );
if ( section ){ const prefix = section . dataset . recoveryItem === '0' ? '' : 'extra_' ; if ( key === 'incoming_weight' && section . dataset . melted_manual !== 'true' ) recoveryField ( section , prefix + 'melted_weight' ). value = event . target . value ; for ( const [ field , flag ] of [[ 'melted_weight' , 'melted_manual' ],[ 'buy_total' , 'buy_total_manual' ],[ 'depreciation_weight' , 'depreciation_manual' ]]) if ( key === field ) section . dataset [ flag ] = 'true' ;}
if ( key === 'member' ){ const member = event . target . value ; recoveryField ( form , 'payer' ). value = member ; recoveryField ( form , 'fee_payer' ). value = member ; recoveryField ( form , 'payment_recipient' ). value = recoveryPrefix ( member ); for ( const row of form . querySelectorAll ( '[data-recovery-item]' )){ const prefix = row . dataset . recoveryItem === '0' ? '' : 'extra_' ; for ( const field of [ 'material_payer' , 'labor_payer' ]) recoveryField ( row , prefix + field ). value = member ;}}
if ( key === 'date' || key === 'member' ) recoveryItemsPoolOptions ( form ); syncRecoveryItems ( form );
}
2026-11-26 01:01:18 +08:00
let customerMaterialCache = null , customerMaterialCacheUser = '' , customerMaterialPage = false , customerMaterialRequest = 0 ;
function customerMaterialOwnUsage ( id ){ const value = typeof recoveryEditEntry !== 'undefined' ? recoveryEditEntry ? . data ? . record : null ; return ( value ? . exchangeItems ?? ( value ? [ value ] : [])). reduce (( n , p )=> n + ( p . customerDeposit ? . id === id ? p . customerDeposit . mg : 0 ), 0 );}
function customerMaterialOptions ( selected = '' ){
const rows = customerMaterialCacheUser === recoveryUser () ? customerMaterialCache ? . rows || [] : [], choices = [[ '' , '霂琿� 㗇𥋘撖� � 霈啣� ' ],... rows . filter ( r => r . remainingMg > 0 || r . id === selected || customerMaterialOwnUsage ( r . id ) > 0 ). map ( r =>[ r . id , ` ${ r . date } 繚 ${ r . number } 繚 � 舐鍂 ${ grams ( r . remainingMg + customerMaterialOwnUsage ( r . id )) } g 繚 ${ r . memo } ` ])];
if ( selected &&! choices . some (([ id ])=> id === selected )) choices . push ([ selected , '甇� 銁霂餃� � � � 匧� 摮䁅扇敶𨰝� � ' ]); return choices ;
}
function customerMaterialSourceHTML ( row , prefix = '' ){ return `<div class="recovery-row"> ${ choice ( '� 扳� � 交� ' , prefix + 'old_source' ,[[ 'incoming' , '� 祆活鈭斗䔉� � 唂� � ' ],[ 'deposit' , '雿輻鍂撖� � � � ' ]], row . old_source || 'incoming' ) } <div data-customer-deposit-fields> ${ choice ( '� 㗇𥋘撖� � 霈啣� ' , prefix + 'deposit_id' , customerMaterialOptions ( row . deposit_id ), row . deposit_id || '' ) }${ recoveryNumberField ( '� 祆活雿輻鍂撖� � � 钅� 嚗ā嚗� ' , prefix + 'deposit_weight' , row . deposit_weight || '' , 3 , 'required' ) } <p class="small muted">� 芣緍� 祆活雿輻鍂� 钅� 嚗� � 雿嗵誧蝏剖� 摮塩� � � � 䔶� 憛怠� � 墧𤣰� 睲遠� � </p></div></div>` ;}
function customerMaterialSyncFields ( scope , row , prefix = '' ){
const using = row . old_source === 'deposit' , group = scope . querySelector ( '[data-customer-deposit-fields]' ); if ( group ){ group . hidden =! using ; for ( const c of group . querySelectorAll ( 'input,select' )) c . disabled =! using ;}
for ( const name of [ 'old_name' , 'incoming_weight' , 'melted_weight' , 'purity' ]){ const control = recoveryField ( scope , prefix + name ); if ( control ){ control . disabled = using ; control . closest ( 'label' ). hidden = using ;}}
}
function customerMaterialOldLines ( draft ){ return [{ name : '摰X� 撖� � � � ' , incoming_weight : draft . deposit_weight , melted_weight : draft . deposit_weight , purity : '100' }];}
function customerMaterialPanelHTML (){ return `<section class="panel" id="customer-material-panel"><div class="panel-title"><h2>摰X� 撖� � � � </h2><div class="actions"> ${ button ( '撖� � 嚗峕� 銝滨� 蝞� ' , 'customer-material-new' ) }${ button ( '� 瑟鰵撖� � 霈啣� ' , 'customer-material-refresh' , 'quiet' ) } </div></div><p class="small muted">� 砍� 撖� � � 啗揭嚗䔶� � 匧� � 滚� 憭� � 霈啣� 嚗𥕢� 霈∪� � 芣� 摨枏� � � 揚� 蹱� � 祆� � 舐鍂� 蹱� � � </p><div id="customer-material-list">甇� 銁霂餃� 撖� � 霈啣� � � </div></section>` ;}
2026-11-26 01:15:41 +08:00
function customerMaterialListHTML ( data ){ return `<div class="stats"><div><span>撖� � 雿蹱� </span><strong> ${ grams ( data . remainingMg ) } g</strong></div><div><span>蝝航恣撖� � </span><strong> ${ grams ( data . totalMg ) } g</strong></div><div><span>撌脩鍂鈭𡒊蔭� � </span><strong> ${ grams ( data . usedMg ) } g</strong></div></div><div class="table-wrap"><table><thead><tr><th>� 交� 嚗誩� 摮睃噡</th><th>憭� � </th><th>撖� � </th><th>撌脩鍂</th><th>� 拐� </th><th>蝏誩� 鈭綽� 霈啣� </th></tr></thead><tbody> ${ data . rows . map ( row => `<tr><td> ${ e ( row . date ) } <div class="small muted"> ${ e ( row . number ) } </div></td><td> ${ e ( row . memo ) }${ row . voided ? '<span class="small">嚗� 歇� 文� 嚗� </span>' : '' } </td><td> ${ grams ( row . mg ) } g</td><td> ${ grams ( row . usedMg ) } g</td><td><strong> ${ grams ( row . remainingMg ) } g</strong></td><td> ${ e ( row . actor ) }${ row . events . length ? `<details><summary>雿輻鍂嚗誯� � � 噼扇敶� </summary> ${ row . events . map ( event => `<p class="small"> ${ e ( event . date ) } 繚 ${ e ( event . memo ) } 繚 ${ event . deltaMg > 0 ? '+' : '� � ' }${ grams ( Math . abs ( event . deltaMg )) } g 繚 ${ e ( event . actor ) } </p>` ). join ( '' ) } </details>` : '' } </td></tr>` ). join ( '' ) || '<tr><td colspan="6">� � � 撖� � 霈啣� </td></tr>' } </tbody></table></div>` ;}
2026-11-26 01:01:18 +08:00
async function loadCustomerMaterials (){
const user = recoveryUser (), request =++ customerMaterialRequest ; try { const data = await api ( '/api/customer-materials' ); if ( user !== recoveryUser () || request !== customerMaterialRequest ) return ; if ( ! Array . isArray ( data . rows ) ||! Number . isSafeInteger ( data . remainingMg ) || data . rows . some ( r => ! Number . isSafeInteger ( r . remainingMg ) || r . remainingMg < 0 ||! Array . isArray ( r . events ))) throw new Error ( '撖� � 韏� � � 芸� � 渲� � � ' ); customerMaterialCache = data ; customerMaterialCacheUser = user ; if ( $ ( '#customer-material-list' )) $ ( '#customer-material-list' ). innerHTML = customerMaterialListHTML ( data );
const form = $ ( '#recovery-form' ); if ( form ){ for ( const select of form . querySelectorAll ( '[name="deposit_id"],[name="extra_deposit_id"]' )) select . innerHTML = opts ( customerMaterialOptions ( select . value ), select . value ); syncRecoveryForm ( form );}
} catch ( err ){ if ( user === recoveryUser () && request === customerMaterialRequest && $ ( '#customer-material-list' )) $ ( '#customer-material-list' ). innerHTML = `<div class="error"> ${ e ( err . message ) } ${ button ( '� 齿鰵霂餃� ' , 'customer-material-refresh' ) } </div>` ;}
}
async function renderCustomerMaterials (){
++ recoveryQuoteRequest ; clearTimeout ( recoveryQuoteTimer ); const saved = (()=>{ try { return JSON . parse ( localStorage . getItem ( 'mm-customer-material-' + recoveryUser ()) || 'null' );} catch { return null ;}})() || {};
$ ( '#main' ). innerHTML = heading ( 'CUSTOMER MATERIAL' , '撖� � 嚗峕� 銝滨� 蝞� ' , '� 芾扇撌脩&霈文� � 滢� 憭� � 嚗䔶� � 匧� 憭拚� 隞瑞� 蝞𨰜� � ' , button ( '餈𥪜� � 墧𤣰嚗讐蔭� � ' , 'customer-material-back' , 'quiet' )) + `<form id="customer-material-form" class="panel"><div class="recovery-row"> ${ field ( '撖� � � 交� ' , 'date' , saved . date || state . today , 'date' , `max=" ${ e ( state . today ) } " required` ) }${ recoveryNumberField ( '撖� � � 钅� 嚗ā嚗� ' , 'grams' , saved . grams || '' , 3 , 'required' ) }${ field ( '憭� � ' , 'memo' , saved . memo || '' , 'text' , 'required maxlength="240" placeholder="靘见� 嚗朞� � 瑯� � 恥� 瑚誨� 瑟� � 西扇� � � � � "' ) } <label>蝏誩� 鈭� <input value=" ${ e ( teamMemberName ( currentMember ())) } " readonly></label></div><label class="check"><input type="checkbox" name="verified" required>撌脩&霈文� 摮睃� � 滚� 憭� � 嚗峕𧋦甈∩� 蝏梶� </label><div id="customer-material-error" aria-live="polite"></div><div class="form-actions"><button type="submit" class="primary">靽嘥� 撖� � 霈啣� </button></div></form>` + customerMaterialPanelHTML (); await loadCustomerMaterials ();
}
async function finishCustomerMaterialSave (){ localStorage . removeItem ( 'mm-customer-material-' + recoveryUser ()); customerMaterialPage = true ; await renderCustomerMaterials (); toast ( '撖� � 霈啣� 撌脖� 摮矋� � 芰� � 鞱揚� 蹱� � 嗡� 甈� ' );}
document . addEventListener ( 'click' , async event =>{
const node = event . target . closest ? .( 'button' ), action = node ? . dataset . action ; if ( ! action ? . startsWith ( 'customer-material-' ) || node . disabled ) return ;
try { if ( busy || pending ()) throw new Error ( '霂瑕� 摰峕� � 𡝗� 憭齿迤� 其� 摮条� � 滢� ' ); if ( action === 'customer-material-refresh' ) return await loadCustomerMaterials (); if ( action === 'customer-material-new' ){ rememberRecoveryDraft (); customerMaterialPage = true ; return await renderCustomerMaterials ();} if ( action === 'customer-material-back' ){ customerMaterialPage = false ; return await renderRecoveries ();}} catch ( err ){ toast ( err . message , true );}
});
document . addEventListener ( 'input' , event =>{ const form = event . target . closest ? .( '#customer-material-form' ); if ( form ) try { localStorage . setItem ( 'mm-customer-material-' + recoveryUser (), JSON . stringify ( Object . fromEntries ( new FormData ( form ))));} catch {}});
document . addEventListener ( 'submit' , async event =>{
const form = event . target ; if ( form . id !== 'customer-material-form' ) return ; event . preventDefault (); const user = recoveryUser ();
try { const input = { date : form . elements . date . value , grams : form . elements . grams . value , memo : form . elements . memo . value . trim (), verified : form . elements . verified . checked }; recoveryUnits ( input . grams , 3 , '撖� � � 钅� ' ,{ zero : false }); if ( ! input . memo ) throw new Error ( '霂瑕‵� 坔� 敹� ' ); const result = await mutate ( '/api/customer-materials' , input ); if ( user !== recoveryUser ()) return ; if ( ! result . id ) throw new Error ( '撖� � 靽嘥� 蝏𤘪� � 芸� � 渲� � 痹� 霂瑟瓲撖孵� � 齿� 雿� ' ); await finishCustomerMaterialSave ();} catch ( err ){ if ( user === recoveryUser () && $ ( '#customer-material-error' )) $ ( '#customer-material-error' ). innerHTML = `<div class="error"> ${ e ( err . message ) } </div>` ;}
});
2026-11-26 01:15:41 +08:00
function recoverySurplusFieldsHTML ( row , prefix = '' ){
return `<div class="recovery-row"> ${ choice ( '雿蹱� 憭� � � 孵� ' , prefix + 'surplus_mode' ,[[ 'buy' , '� 匧� � 嗡遠蝏梶� ' ],[ 'deposit' , '瘛餃� � 啣� 摮䀹� 嚗峕� 銝滨� 蝞� ' ]], row . surplus_mode || 'buy' ) } <div data-surplus-deposit> ${ field ( '撖� � 憭� � 嚗� � 匧‵嚗� ' , prefix + 'surplus_memo' , row . surplus_memo || '' , 'text' , 'maxlength="160" placeholder="靘见� 嚗朞� � 瑯� � 恥� 瑚誨� � "' ) } <p class="small muted">� 拐� � 钅� � 芸𢆡� 惩� 摰X� 撖� � � 辷� 銝齿� 蝞堒� � 嗆狡嚗䔶� 銝滚� � 亥揚� 蹱� � � </p></div></div>` ;
}
function recoverySurplusSync ( scope , row , hasSurplus , exchange , prefix = '' ){
const storing = exchange && row . surplus_mode === 'deposit' ;
for ( const [ selector , show ] of [[ '[data-surplus-buy]' , hasSurplus &&! storing ],[ '[data-surplus-deposit]' , hasSurplus && storing ]]){
const node = scope . querySelector ( selector ); if ( ! node ) continue ; node . hidden =! show ; for ( const c of node . querySelectorAll ( 'input,select,button' )) c . disabled =! show ;
}
}