2026-10-21 01:32:49 +08:00
'use strict' ;
let createMode = 'direct' , priceLockRequest = 0 , priceLockDeliveryId = '' , currentPriceLock = null ;
const priceLockDraftKey = ()=> `mm-price-lock-draft- ${ session . user . id } ` ;
const priceLockDeliveryKey = id => `mm-price-lock-delivery- ${ session . user . id } - ${ id } ` ;
2026-10-25 14:19:24 +08:00
const priceLockPayerName = payer =>({ owner : '麦麦' , assistant : typeof teamMode === 'function' && teamMode () ? '助理1' : '助理' , assistant2 : '助理2' })[ payer ] || '待补' ;
2026-10-21 01:32:49 +08:00
function priceLockCreateControls (){ return `<div class="create-mode-controls" role="group" aria-label="开单方式"> ${ button ( '直接开单' , 'create-mode' , createMode === 'direct' ? 'primary' : '' , `data-mode="direct"` ) }${ button ( '锁价' , 'create-mode' , createMode === 'lock' ? 'primary' : '' , `data-mode="lock"` ) } </div>` ;}
function invalidatePriceLockViews (){ ++ priceLockRequest ;}
function priceLockReadDraft ( key ){ try { return JSON . parse ( localStorage . getItem ( key ) || 'null' );} catch { return null ;}}
function lockQuantityMg ( value ){
const text = String ( value ?? '' ). trim (); if ( ! /^\d+(?:\.\d{1,3})?$/ . test ( text )) throw new Error ( '克重请填写正数,最多3位小数。' );
const [ whole , part = '' ] = text . split ( '.' ), mg = Number ( whole ) * 1000 + Number ( part . padEnd ( 3 , '0' )); if ( ! Number . isSafeInteger ( mg ) || mg <= 0 ) throw new Error ( '克重请填写大于0的有效数字。' ); return mg ;
}
function lockFormValue ( form , name ){ return form . querySelector ( `[name=" ${ name } "]` ) ? . value ?? '' ;}
function lockCharges ( root ){ return [... root . querySelectorAll ( '.charge-row' )]. map ( row =>{ const value = name => row . querySelector ( `[name=" ${ name } "]` ). value , type = value ( 'chargeType' ), customName = value ( 'chargeName' ); return { id : row . dataset . chargeId , nameType : type , customName , name : type === '其他' ? customName : type , amount : value ( 'chargeAmount' ), chargePrices : JSON . parse ( row . dataset . chargePrices )};});}
function syncLockChargeFields ( root ){ for ( const row of root . querySelectorAll ( '.charge-row' )){ const custom = row . querySelector ( '[name="chargeType"]' ). value === '其他' , input = row . querySelector ( '[name="chargeName"]' ); input . closest ( 'label' ). hidden =! custom ; input . disabled =! custom ; input . required = custom ;}}
function collectPriceLockCreate (){
const form = $ ( '#price-lock-create-form' ), get = name => lockFormValue ( form , name );
2026-10-25 14:19:24 +08:00
return {...( teamMode () ? { member : get ( 'member' ) || currentMember ()} : {}), date : get ( 'date' ), customer : get ( 'customer' ). trim (), salesperson : get ( 'salesperson' ), note : get ( 'note' ), discount : get ( 'discount' ), line : { name : get ( 'name' ). trim (), unit : 'g' , pricingMode : 'auto' , quantity : get ( 'quantity' ), goldPrice : get ( 'goldPrice' ), laborRate : get ( 'laborRate' ), laborMode : get ( 'laborMode' ), pieces : get ( 'pieces' ), charges : lockCharges ( form )}, payment : { amount : get ( 'received_amount' ), account : readPaymentAccount ( form ), credit_card_fee_payer : readCreditCardPayer ( form ), verified : form . querySelector ( '[name="payment_verified"]' ). checked }, material : { rate : get ( 'material_rate' ), payer : get ( 'material_payer' ), verified : form . querySelector ( '[name="material_verified"]' ). checked }};
2026-10-21 01:32:49 +08:00
}
function renderPriceLockCreate (){
const d = priceLockReadDraft ( priceLockDraftKey ()) || {}, line = d . line || {}, payment = d . payment || {}, material = d . material || {};
2026-10-25 14:19:24 +08:00
$ ( '#main' ). innerHTML = heading ( 'GOLD PRICE LOCK' , '黄金锁价' , '每张锁价记录一件按克黄金;多件请分别锁价。保存后进入待交付,暂不出入库、不计利润。' , priceLockCreateControls ()) + `<form id="price-lock-create-form"><section class="panel"><h2>客户与锁价日期</h2><div class="grid four"> ${ field ( '锁价日期' , 'date' , d . date || state . today , 'date' , `required max=" ${ e ( state . today ) } "` ) }${ field ( '客户称呼/代号(必填)' , 'customer' , d . customer || '' , 'text' , 'required maxlength="60"' ) }${ field ( '开单人(必填)' , 'salesperson' , d . salesperson || session . user . name , 'text' , 'required maxlength="30"' ) }${ orderMemberField ( d . member || currentMember ()) }${ field ( '黄金商品' , 'name' , line . name || '足金999' , 'text' , 'required maxlength="60"' ) } </div></section><section class="panel line-item" data-price-lock-sale><h2>锁定售价与预计克重</h2><div class="grid four"> ${ field ( '锁定克重(g) ' , 'quantity' , line . quantity || '' , 'number' , 'required min="0.001" step="0.001"' ) }${ moneyField ( '锁定销售金价(元/克)' , 'goldPrice' , line . goldPrice || '' ) }${ choice ( '销售工费方式' , 'laborMode' ,[[ 'gram' , '克工费' ],[ 'piece' , '件工费' ]], line . laborMode || 'gram' ) }${ moneyField ( '销售工费' , 'laborRate' , line . laborRate ?? '' ) }${ field ( '计工费件数' , 'pieces' , line . pieces || '1' , 'number' , 'required min="1" step="1"' ) } </div><div class="sale-charges"><div class="panel-title"><strong>客户附加项目(选填)</strong> ${ button ( '+ 添加附加项目' , 'add-charge' ) } </div><p class="small muted">沿用直接开单的收费默认值,可按实际修改;交付时会保留这些项目。</p><div class="charge-list"> ${ ( line . charges || []). map ( chargeHTML ). join ( '' ) } </div></div><div class="grid two" style="margin-top:16px"> ${ moneyField ( '整单优惠(元)' , 'discount' , d . discount ?? '0' ) } <label>客户可见备注<textarea name="note" maxlength="170" rows="2"> ${ e ( d . note || '' ) } </textarea></label></div><p id="lock-sale-estimate" class="calculation small" aria-live="polite"></p></section><section class="panel"><h2>客户实际已付款</h2><p class="small muted">填写已经收到的金额,可与预计报价不同;尚未收款填0。</p><div class="grid three"> ${ moneyField ( '实际收款(元)' , 'received_amount' , payment . amount ?? '' ) }${ accountFields ( payment . account ) } </div><label class="check"><input type="checkbox" name="payment_verified" ${ payment . verified ? 'checked' : '' } required>已核实实际收款金额与账户。</label> ${ creditCardPreviewHTML ( 'lock-create-card-fee' , payment . credit_card_fee_payer ) } </section><section class="panel internal"><h2>原锁金料实际成本</h2><div class="grid three"> ${ moneyField ( '原锁进货料价(元/克)' , 'material_rate' , material . rate ?? '' ) }${ choice ( '原锁料费付款人' , 'material_payer' , teamMemberOptions (), material . payer || 'owner' ) } <div><span class="small muted">这批金料已付金额</span><div id="lock-material-estimate" class="summary-amount">待填写</div></div></div><label class="check"><input type="checkbox" name="material_verified" ${ material . verified ? 'checked' : '' } required>已核实原锁金料的实际付款。</label><p class="small muted">此处只记原锁金料付款;工费、快递等在交付时填写实际成本。库存归属也在交付时确认。</p></section><section class="panel"><div class="form-actions"><div><span class="small muted">预计成交额 · 四舍五入到元</span><div id="lock-create-total" class="summary-amount">待填写</div><div class="small muted">待交付,不计利润</div></div><button class="primary" type="submit">保存锁价待交付</button></div><div id="price-lock-error" aria-live="polite"></div></section></form>` ;
2026-10-21 01:32:49 +08:00
syncPriceLockForm ();
}
function syncPriceLockCreate (){
2026-10-25 14:19:24 +08:00
const form = $ ( '#price-lock-create-form' ); if ( ! form ) return ; syncPaymentRecipient ( form ); syncLockChargeFields ( form );
2026-10-21 01:32:49 +08:00
const piece = form . querySelector ( '[name="pieces"]' ), pieceMode = lockFormValue ( form , 'laborMode' ) === 'piece' ; piece . closest ( 'label' ). hidden =! pieceMode ; piece . required = pieceMode ;
const d = collectPriceLockCreate ();
try { const sale = LedgerCalc . sale ( d . line ), total = LedgerCalc . orderTotal ([ sale . sale ], LedgerCalc . cents ( d . discount ), 'yuan' ); $ ( '#lock-create-total' ). textContent = orderAmount ( total . total , 'yuan' ); $ ( '#lock-sale-estimate' ). textContent = '商品及附加项目合计 ¥' + yuan ( sale . sale ) + '; ' + orderRoundingHint ( total );} catch { $ ( '#lock-create-total' ). textContent = '待填写' ; $ ( '#lock-sale-estimate' ). textContent = '填写克重、销售金价与工费后显示预计报价。' ;}
try { const cost = LedgerCalc . purchaseCosts ({ unit : 'g' , quantity : d . line . quantity , costParts : { material : '0' , labor : '0' , accessories : '0' , other : '0' }, costMaterial : { mode : 'gram' , rate : d . material . rate }}); $ ( '#lock-material-estimate' ). textContent = cost . total == null ? '待填写' : '¥' + yuan ( cost . total );} catch { $ ( '#lock-material-estimate' ). textContent = '待填写' ;}
2026-10-23 09:49:36 +08:00
let paymentCents = null ; try { paymentCents = LedgerCalc . cents ( d . payment . amount );} catch {}
syncCreditCardPreview ( $ ( '#lock-create-card-fee' ), d . payment . account , paymentCents );
2026-10-21 01:32:49 +08:00
localStorage . setItem ( priceLockDraftKey (), JSON . stringify ( d ));
}
2026-10-23 09:49:36 +08:00
function priceLockCardFeeTotal ( lock ){ return Number . isSafeInteger ( lock . credit_card_fee_total ) ? lock . credit_card_fee_total : ( lock . credit_card_fees || []). reduce (( sum , item )=> sum + item . amount , 0 );}
function priceLockCardFeesHTML ( lock ){
const fees = lock . credit_card_fees || []; if ( ! fees . length &&! priceLockCardFeeTotal ( lock )) return '' ;
2026-10-25 14:19:24 +08:00
return `<div class="price-lock-card-fees internal"><strong>已记录的信用卡手续费 · ¥ ${ yuan ( priceLockCardFeeTotal ( lock )) } </strong><ul> ${ fees . map ( item => `<li><span> ${ e ( item . date ) } · ${ e ( priceLockPayerName ( item . payer )) } 支付 ${ item . note ? ' · ' + e ( item . note ) : '' } </span><b>¥ ${ yuan ( item . amount ) } </b></li>` ). join ( '' ) } </ul><p class="small muted">已按各笔付款时保存的金额与费率计入内部成本;交付时沿用,不重复收取。退款不冲回已发生的手续费。</p></div>` ;
2026-10-23 09:49:36 +08:00
}
2026-10-21 01:32:49 +08:00
function priceLockDialog (){ let dialog = $ ( '#price-lock-dialog' ); if ( ! dialog ){ dialog = document . createElement ( 'dialog' ); dialog . id = 'price-lock-dialog' ; document . body . append ( dialog );} return dialog ;}
2026-10-23 09:49:36 +08:00
function priceLockFacts ( lock ){ return `<div class="grid three price-lock-facts"><div>锁价日期<strong> ${ e ( lock . date ) } </strong></div><div>原锁克重<strong> ${ grams ( lock . locked_mg ) } g</strong></div><div>锁定销售金价<strong>¥ ${ yuan ( lock . sell_rate ) } /克</strong></div><div> ${ lock . status === 'delivered' ? '锁价及交付阶段净收款' : '客户实际已付净额' } <strong>¥ ${ yuan ( lock . netReceived ) } </strong> ${ lock . status === 'delivered' ? '<small>后续收退款请查看销售单。</small>' : '' } </div><div>原锁料费<strong>¥ ${ yuan ( lock . material_amount ) } </strong><small> ${ e ( priceLockPayerName ( lock . buy_payer )) } 支付,进货料价 ¥ ${ yuan ( lock . buy_rate ) } /克</small></div><div>状态<strong> ${ lock . status === 'pending' ? '待交付,不计利润' : '已交付' } </strong></div></div>` + priceLockCardFeesHTML ( lock );}
2026-10-21 01:32:49 +08:00
async function renderPriceLocks (){
if ( priceLockDeliveryId ) return await renderPriceLockDelivery ( priceLockDeliveryId );
const request =++ priceLockRequest , user = state . user . id ;
$ ( '#main' ). innerHTML = heading ( 'PENDING DELIVERY' , '待交付' , '显示所有日期的锁价待交付记录。锁价时只记实际收付,交付后才计销售、成本和利润。' , button ( '新增锁价' , 'new-price-lock' , 'primary' ) + button ( '刷新' , 'refresh-price-locks' )) + '<section class="panel"><div id="price-lock-list" aria-live="polite">正在读取待交付记录…</div></section>' ;
try { const result = await api ( '/api/price-locks?status=pending' ); if ( request !== priceLockRequest || tab !== 'price-locks' || state . user . id !== user ||! $ ( '#price-lock-list' )) return ; if ( ! Array . isArray ( result . rows )) throw new Error ( '待交付记录未完整返回,请重试。' );
$ ( '#price-lock-list' ). innerHTML = result . rows . length ? `<div class="table-wrap"><table class="price-lock-list"><thead><tr><th>锁价日期/客户</th><th>黄金商品</th><th class="number">锁定克重</th><th class="number">销售金价</th><th class="number">已收净额</th><th>原料付款</th><th>操作</th></tr></thead><tbody> ${ result . rows . map ( lock => `<tr><td> ${ e ( lock . date ) } <br> ${ e ( lock . customer ) } </td><td> ${ e ( lock . line ? . name || lock . product || '黄金' ) } </td><td class="number"> ${ grams ( lock . locked_mg ) } g</td><td class="number">¥ ${ yuan ( lock . sell_rate ) } /克</td><td class="number">¥ ${ yuan ( lock . netReceived ) } </td><td> ${ e ( priceLockPayerName ( lock . buy_payer )) } <br>¥ ${ yuan ( lock . material_amount ) } </td><td><div class="actions"> ${ button ( '查看' , 'open-price-lock' , '' , `data-id=" ${ e ( lock . id ) } "` ) }${ button ( '交付' , 'deliver-price-lock' , 'primary' , `data-id=" ${ e ( lock . id ) } "` ) } </div></td></tr>` ). join ( '' ) } </tbody></table></div>` : '<div class="empty"><strong>目前没有锁价待交付记录</strong>已交付记录会进入订单列表。</div>' ;
} catch ( err ){ if ( request === priceLockRequest && tab === 'price-locks' && $ ( '#price-lock-list' )) $ ( '#price-lock-list' ). innerHTML = `<div class="error"> ${ e ( err . message ) } ${ button ( '重新读取' , 'refresh-price-locks' ) } </div>` ;}
}
async function openPriceLock ( id ){
const request =++ priceLockRequest , user = state . user . id , dialog = priceLockDialog (); dialog . innerHTML = `<button class="dialog-close" data-action="close-price-lock" aria-label="关闭锁价记录">× </button><div id="price-lock-detail">正在读取锁价记录…</div>` ; if ( ! dialog . open ) dialog . showModal ();
try { const lock = await api ( '/api/price-locks/' + encodeURIComponent ( id )); if ( request !== priceLockRequest ||! dialog . open || state . user . id !== user ) return ; currentPriceLock = lock ;
$ ( '#price-lock-detail' ). innerHTML = `<div class="order-header"><div class="eyebrow">GOLD PRICE LOCK</div><h2> ${ e ( lock . customer ) } · ${ e ( lock . line ? . name || '黄金锁价' ) } </h2></div> ${ priceLockFacts ( lock ) } <p class="small muted">预计报价 ¥ ${ yuan ( lock . estimated_total ) } ;交付时按最终克重、工费和附加项目重新结算,销售金价保持原锁价格。</p> ${ lock . note ? `<p> ${ e ( lock . note ) } </p>` : '' } <div class="actions"> ${ lock . status === 'pending' ? button ( '办理交付' , 'deliver-price-lock' , 'primary' , `data-id=" ${ e ( lock . id ) } "` ) : lock . final_order_id ? button ( '查看销售单' , 'open-lock-order' , 'primary' , `data-id=" ${ e ( lock . final_order_id ) } "` ) : '' } </div>` ;
} catch ( err ){ if ( request === priceLockRequest && dialog . open ) $ ( '#price-lock-detail' ). innerHTML = `<div class="error"> ${ e ( err . message ) } </div>` ;}
}
function priceLockLineInputs ( lock ){
const line = lock . line ;
return {... line , quantity : grams ( lock . locked_mg ), goldPrice : ( lock . sell_rate / 100 ). toFixed ( 2 ), laborRate : ( line . laborRate / 100 ). toFixed ( 2 ), sale : ( line . sale / 100 ). toFixed ( 2 ), baseSale : (( line . baseSale ?? line . sale ) / 100 ). toFixed ( 2 ), charges : ( line . charges || []). map ( c =>({... c , amount : ( c . amount / 100 ). toFixed ( 2 )})), payer : lock . buy_payer , costParts : { material : ( lock . material_amount / 100 ). toFixed ( 2 ), labor : '' , accessories : '0' , other : '0' }, costMaterial : { mode : 'total' }, costLabor : { mode : 'total' }, costPayers : { material : lock . buy_payer , labor : 'owner' }};
}
async function renderPriceLockDelivery ( id ){
const request =++ priceLockRequest , user = state . user . id ;
$ ( '#main' ). innerHTML = heading ( 'LOCK DELIVERY' , '办理锁价交付' , '读取原锁价格与付款记录…' , button ( '返回待交付' , 'refresh-price-locks' )) + '<section class="panel" id="price-lock-delivery-loading">正在读取锁价记录…</section>' ;
try {
const lock = await api ( '/api/price-locks/' + encodeURIComponent ( id )); if ( request !== priceLockRequest || tab !== 'price-locks' || priceLockDeliveryId !== id || state . user . id !== user ) return ;
if ( lock . status !== 'pending' ){
$ ( '#main' ). innerHTML = heading ( 'LOCK DELIVERED' , '这张锁价单已交付' , '请查看已生成的销售单,不要重复交付。' , button ( '返回待交付' , 'refresh-price-locks' )) + `<section class="panel"> ${ priceLockFacts ( lock ) }${ lock . final_order_id ? button ( '查看销售单' , 'open-lock-order' , 'primary' , `data-id=" ${ e ( lock . final_order_id ) } "` ) : '' } </section>` ; return ;
}
currentPriceLock = lock ;
const saved = priceLockReadDraft ( priceLockDeliveryKey ( id )), draft = saved ? . revision === lock . revision ? saved : {}, line = draft . line || priceLockLineInputs ( lock ), date = draft . date || state . today ;
2026-10-25 14:19:24 +08:00
$ ( '#main' ). innerHTML = heading ( 'LOCK DELIVERY' , '交付 · ' + e ( lock . customer ), '最终克重全部按原锁销售金价结算;补重只新增进货成本。交付成功后生成正式销售单。' , button ( '返回待交付' , 'refresh-price-locks' )) + `<section class="panel"> ${ priceLockFacts ( lock ) } </section><form id="price-lock-delivery-form" data-id=" ${ e ( id ) } " data-revision=" ${ lock . revision } "><section class="panel"><div class="grid two"> ${ field ( '交付日期' , 'date' , date , 'date' , `required min=" ${ e ( lock . date ) } " max=" ${ e ( state . today ) } "` ) }${ field ( '交付备注(客户可见,选填)' , 'delivery_note' , draft . note ?? lock . note ?? '' , 'text' , 'maxlength="170"' ) } </div></section><section class="panel price-lock-delivery-line"><div class="panel-title"><h2>最终商品与实际成本</h2><span class="small muted">一件黄金,保留原锁附加项目;可按实际增减。</span></div><div id="lines"> ${ lineHTML ( line , 1 ) } </div></section><section class="panel internal"><h2>金料与库存确认</h2><p class="small muted">请选择本次交付所用的实际黄金货盘。已经记过入库的金料只出库,不会重复增加库存。</p><div class="grid two"> ${ choice ( '原锁金料是否已记入这个货盘' , 'original_stock' ,[[ '' , '请选择' ],[ 'receive' , '尚未记入,交付时先入库' ],[ 'stocked' , '此前已记入,只出库' ]], draft . inventory ? . original || '' ) } <div id="lock-material-breakdown" class="lock-material-breakdown" aria-live="polite"></div></div><div id="lock-extra-material" hidden><h3>超出原锁克重的补重金料</h3><div class="grid three"> ${ moneyField ( '补重进货料价(元/克)' , 'extra_rate' , draft . extraMaterial ? . rate ?? '' ) }${ choice ( '补重料费付款人' , 'extra_payer' ,[[ '' , '请选择' ],... teamMemberOptions ()], draft . extraMaterial ? . payer || '' ) }${ choice ( '补重金料是否已记入所选货盘' , 'extra_stock' ,[[ '' , '请选择' ],[ 'receive' , '尚未记入,交付时先入库' ],[ 'stocked' , '此前已记入,只出库' ]], draft . inventory ? . extra || '' ) } </div><label class="check"><input type="checkbox" name="extra_verified" ${ draft . extraMaterial ? . verified ? 'checked' : '' } >已核实补重料费实际付款。</label></div><p id="lock-stock-note" class="note" aria-live="polite"></p></section> ${ feeHTML ({... draft , date , fees_date : date } ,{cardPreview:false})}<section class="panel"><div class="grid two"> ${ moneyField ( '整单优惠(元)' , 'discount' , draft . discount ?? ( lock . discount / 100 ). toFixed ( 2 )) } <div><span class="small muted">最终成交额 · 四舍五入到元</span><div id="lock-final-total" class="summary-amount">待填写</div><p id="lock-rounding-note" class="small muted"></p></div></div><div class="lock-settlement"><h2 id="lock-settlement-title">客户补款/退款</h2><p id="lock-settlement-hint" class="small muted" aria-live="polite"></p><div id="lock-settlement-fields"><div class="grid three"> ${ field ( '本次实际补退款(元)' , 'settlement_amount' , '' , 'number' , 'readonly' ) }${ accountFields ( draft . settlement ? . account || lock . cash_events . find ( event => event . kind === 'receipt' ) ? . account ) } </div><label class="check"><input type="checkbox" name="settlement_verified" ${ draft . settlement ? . verified ? 'checked' : '' } >已核实本次补款到账/退款已实际完成。</label></div></div> ${ creditCardPreviewHTML ( 'lock-delivery-card-fee' , draft . settlement ? . credit_card_fee_payer ) } <label class="check"><input type="checkbox" name="delivery_verified" required>已核对实物、实际成本、出入库来源与客户收付款,确认交付。</label><div class="form-actions"><span class="small muted">保存后才记销售、完整成本和利润,可打印正式客户单据。</span><button type="submit" class="primary">确认交付并生成销售单</button></div><div id="price-lock-error" aria-live="polite"></div></section></form>` ;
2026-10-21 01:32:49 +08:00
syncPriceLockForm ();
} catch ( err ){ if ( request === priceLockRequest && tab === 'price-locks' && $ ( '#price-lock-delivery-loading' )) $ ( '#price-lock-delivery-loading' ). innerHTML = `<div class="error"> ${ e ( err . message ) } </div> ${ button ( '重新读取' , 'deliver-price-lock' , '' , `data-id=" ${ e ( id ) } "` ) } ` ;}
}
function collectPriceLockDelivery (){
const form = $ ( '#price-lock-delivery-form' ), get = name => lockFormValue ( form , name ), row = form . querySelector ( '#lines .line-item' );
2026-10-25 14:19:24 +08:00
return { revision : Number ( form . dataset . revision ), date : get ( 'date' ), note : get ( 'delivery_note' ), line : collectLine ( row ), discount : get ( 'discount' ), extraMaterial : { rate : get ( 'extra_rate' ), payer : get ( 'extra_payer' ), verified : form . querySelector ( '[name="extra_verified"]' ). checked }, inventory : { pocket : row . querySelector ( '[name="pocket"]' ). value , original : get ( 'original_stock' ), extra : get ( 'extra_stock' )}, settlement : { amount : get ( 'settlement_amount' ), account : readPaymentAccount ( form ), credit_card_fee_payer : readCreditCardPayer ( form ), verified : form . querySelector ( '[name="settlement_verified"]' ). checked }, fee_items : readFeeRows (), fee_auto_initialized : true , verified : form . querySelector ( '[name="delivery_verified"]' ). checked };
2026-10-21 01:32:49 +08:00
}
function syncPriceLockDelivery (){
2026-10-25 14:19:24 +08:00
const form = $ ( '#price-lock-delivery-form' ), lock = currentPriceLock ; if ( ! form ||! lock || form . dataset . id !== lock . id ) return ; syncPaymentRecipient ( form );
2026-10-21 01:32:49 +08:00
const row = form . querySelector ( '#lines .line-item' ), get = name => row . querySelector ( `[name=" ${ name } "]` );
get ( 'goldPrice' ). value = ( lock . sell_rate / 100 ). toFixed ( 2 ); get ( 'unit' ). value = 'g' ; get ( 'pricingMode' ). value = 'auto' ; get ( 'cost-materialMode' ). value = 'total' ; get ( 'cost-materialPayer' ). value = lock . buy_payer ;
let costs = null , extra = false ;
try { extra = lockQuantityMg ( get ( 'quantity' ). value ) > lock . locked_mg ;} catch {}
const extraRoot = $ ( '#lock-extra-material' ); extraRoot . hidden =! extra ; for ( const input of extraRoot . querySelectorAll ( 'input,select' )){ input . disabled =! extra ; input . required = extra ;}
try { costs = LedgerCalc . priceLockCost ({ lockedQuantity : grams ( lock . locked_mg ), quantity : get ( 'quantity' ). value , buyRate : ( lock . buy_rate / 100 ). toFixed ( 2 ), extraBuyRate : lockFormValue ( form , 'extra_rate' )}); get ( 'cost-material' ). value = ( costs . materialCost / 100 ). toFixed ( 2 );} catch { get ( 'cost-material' ). value = '' ;}
syncLine ( row );
// 冻结原锁价格及料费;其余销售项目、工费和实际费用仍沿用普通开单表单。
for ( const name of [ 'nameType' , 'customName' , 'unit' , 'pricingMode' , 'goldPrice' , 'cost-materialMode' , 'cost-materialPayer' ]) get ( name ). disabled = true ;
get ( 'cost-material' ). readOnly = true ; row . querySelector ( '.line-top button' ) ? . remove ();
row . querySelector ( '.purchase-material .purchase-original' ). hidden = true ;
row . querySelector ( '.purchase-material .purchase-formula' ). textContent = costs ? `原锁使用 ${ grams ( costs . originalUsedMg ) } g × ${ yuan ( lock . buy_rate ) } 元/克 ${ costs . extraMg ? ';补重 ' + grams ( costs . extraMg ) + 'g × ' + lockFormValue ( form , 'extra_rate' ) + '元/克' : '' } = ${ yuan ( costs . materialCost ) } 元` : '料费按原锁进货价计算;有补重时,请先填写补重进货料价。' ;
get ( 'goldPrice' ). closest ( 'label' ). firstChild . textContent = '原锁销售金价(元/克,固定)' ; get ( 'cost-material' ). closest ( 'label' ). firstChild . textContent = '实际耗用料费合计(元,自动)' ; get ( 'cost-materialPayer' ). closest ( 'label' ). firstChild . textContent = '原锁料费付款人' ; get ( 'cost-materialMode' ). querySelector ( 'option[value="total"]' ). textContent = '原锁+补重自动核算' ; get ( 'pocket' ). required = true ; get ( 'pocket' ). querySelector ( 'option[value=""]' ). textContent = '请选择实际黄金货盘' ;
form . querySelector ( '[name="original_stock"]' ). required = true ;
const feeDate = form . querySelector ( '[name="fees_date"]' ); feeDate . value = lockFormValue ( form , 'date' ); feeDate . readOnly = true ;
syncFeeRows (); const d = collectPriceLockDelivery ();
$ ( '#lock-material-breakdown' ). textContent = costs ? `原锁料费已付 ¥ ${ yuan ( lock . material_amount ) } ;本单耗用料费 ¥ ${ yuan ( costs . materialCost ) }${ costs . leftoverMg ? ';余料 ' + grams ( costs . leftoverMg ) + 'g,成本 ¥' + yuan ( costs . leftoverCost ) : '' } ` : extra ? '请填写补重料价,计算本次实际耗用成本。' : '填写最终交付克重,自动计算实际耗料。' ;
const original = d . inventory . original , pocket = d . inventory . pocket ;
$ ( '#lock-stock-note' ). textContent = costs && original && pocket ? ` ${ original === 'receive' ? '原锁 ' + grams ( lock . locked_mg ) + 'g 先入库;' : '原锁金料此前已入库;' }${ costs . extraMg ? ( d . inventory . extra === 'receive' ? '补重 ' + grams ( costs . extraMg ) + 'g 先入库;' : d . inventory . extra === 'stocked' ? '补重金料此前已入库;' : '请选择补重金料是否已入库;' ) : '' } 从「 ${ pocket } 」出库 ${ grams ( costs . finalMg ) } g。 ${ costs . leftoverMg ? '余料 ' + grams ( costs . leftoverMg ) + 'g 留在该货盘,按原进货价计成本,不重复入库。' : '' } ` : '选择实际货盘和金料入库情况后,显示本次库存动作。' ;
2026-10-23 09:49:36 +08:00
let difference = null ;
2026-10-21 01:32:49 +08:00
try {
2026-10-23 09:49:36 +08:00
const total = LedgerCalc . orderTotal ([ LedgerCalc . sale ( d . line ). sale ], LedgerCalc . cents ( d . discount ), 'yuan' ); difference = total . total - lock . netReceived ;
2026-10-21 01:32:49 +08:00
$ ( '#lock-final-total' ). textContent = orderAmount ( total . total , 'yuan' ); $ ( '#lock-rounding-note' ). textContent = orderRoundingHint ( total );
$ ( '#lock-settlement-title' ). textContent = difference > 0 ? '客户需补款' : difference < 0 ? '应退还客户' : '无需补款或退款' ;
$ ( '#lock-settlement-hint' ). textContent = `已收净额 ¥ ${ yuan ( lock . netReceived ) } ;最终成交 ¥ ${ yuan ( total . total ) }${ difference ? ';本次' + ( difference > 0 ? '补收' : '退款' ) + ' ¥' + yuan ( Math . abs ( difference )) : ',金额已结清' } 。` ;
form . querySelector ( '[name="payment_method"]' ). closest ( 'label' ). firstChild . textContent = difference < 0 ? '退款方式' : '补收款方式' ; form . querySelector ( '[name="payment_recipient"]' ). closest ( 'label' ). firstChild . textContent = difference < 0 ? '退款账户归属' : '收款人' ;
form . querySelector ( '[name="settlement_amount"]' ). value = ( Math . abs ( difference ) / 100 ). toFixed ( 2 ); $ ( '#lock-settlement-fields' ). hidden =! difference ;
for ( const input of $ ( '#lock-settlement-fields' ). querySelectorAll ( 'input,select' )){ input . disabled =! difference ; input . required =!! difference ;}
} catch ( err ){ $ ( '#lock-final-total' ). textContent = '待填写' ; $ ( '#lock-rounding-note' ). textContent = err . message ; $ ( '#lock-settlement-hint' ). textContent = '先填写最终克重、销售工费及优惠,再核对客户补退款。' ; form . querySelector ( '[name="settlement_amount"]' ). value = '' ;}
2026-10-25 14:19:24 +08:00
syncPaymentRecipient ( form );
2026-10-23 09:49:36 +08:00
const cardFee = syncCreditCardPreview ( $ ( '#lock-delivery-card-fee' ), d . settlement . account , difference ,{ enabled : difference === null || difference > 0 });
updateFeeTotal ( readFeeRows (), cardFee === null ? null : priceLockCardFeeTotal ( lock ) + cardFee ,{ knownCardCost : priceLockCardFeeTotal ( lock )});
2026-10-21 01:32:49 +08:00
localStorage . setItem ( priceLockDeliveryKey ( lock . id ), JSON . stringify ( collectPriceLockDelivery ()));
}
function syncPriceLockForm (){ if ( $ ( '#price-lock-create-form' )) syncPriceLockCreate (); else if ( $ ( '#price-lock-delivery-form' )) syncPriceLockDelivery ();}
async function finishPriceLockSave ( url , data , result ){
$ ( '#price-lock-dialog' ) ? . close (); invalidatePriceLockViews ();
if ( url === '/api/price-locks' ){
const id = result . price_lock_id || result . id ;
localStorage . removeItem ( priceLockDraftKey ()); priceLockDeliveryId = '' ; tab = 'price-locks' ;
// POST已成功,立即移除可提交的表单;后续读取失败也不能再次创建。
$ ( '#main' ). innerHTML = heading ( 'LOCK SAVED' , '锁价已保存' , '已经记好实际收款与原锁料款,尚未出入库、不计利润。' ) + `<section class="panel"><p id="lock-saved-status" aria-live="polite">正在读取已保存记录…</p><div class="actions"> ${ button ( '查看已保存锁价单' , 'open-price-lock' , 'primary' , `data-id=" ${ e ( id ) } "` ) }${ button ( '重新读取待交付' , 'refresh-price-locks' ) } </div></section>` ;
document . querySelectorAll ( 'nav button' ). forEach ( b => b . classList . toggle ( 'active' , b . dataset . tab === tab ));
try { await refresh (); await openPriceLock ( id ); toast ( '锁价已保存到待交付,尚未出入库、不计利润' );}
catch { if ( $ ( '#lock-saved-status' )) $ ( '#lock-saved-status' ). textContent = '锁价已经保存,最新页面暂未读到。请重新读取或查看已保存锁价单。' ; toast ( '锁价已经保存,请重新读取查看;不要重复新增。' , true );}
} else {
const id = url . split ( '/' )[ 3 ], orderId = result . order_id || result . id ; localStorage . removeItem ( priceLockDeliveryKey ( id )); priceLockDeliveryId = '' ; const filters = getOrderBookFilters (); filters . mode = 'date' ; filters . date = data . date ; filters . q = '' ; filters . status = '' ; saveOrderBookFilters (); tab = 'orders' ;
$ ( '#main' ). innerHTML = heading ( 'DELIVERY SAVED' , '锁价已交付' , '销售单已经生成,收退款、库存、完整成本与利润已经记账。' ) + `<section class="panel"><p id="lock-saved-status" aria-live="polite">正在读取已生成的销售单…</p><div class="actions"> ${ button ( '查看销售单' , 'open-lock-order' , 'primary' , `data-id=" ${ e ( orderId ) } "` ) }${ button ( '重新读取订单' , 'refresh' ) } </div></section>` ;
document . querySelectorAll ( 'nav button' ). forEach ( b => b . classList . toggle ( 'active' , b . dataset . tab === tab ));
try { await refresh (); await openOrder ( orderId ); toast ( '锁价已交付,收退款、库存、完整成本和利润已记账' );}
catch { if ( $ ( '#lock-saved-status' )) $ ( '#lock-saved-status' ). textContent = '交付已经完成,最新页面暂未读到。请重新读取订单或查看销售单。' ; toast ( '锁价已经交付,请重新读取销售单;不要重复交付。' , true );}
}
}
async function submitPriceLockForm ( form ){
syncPriceLockForm (); $ ( '#price-lock-error' ). innerHTML = '' ; let url , data ;
if ( form . id === 'price-lock-create-form' ){
2026-10-23 09:49:36 +08:00
data = validateOrderIdentity ( collectPriceLockCreate ()); url = '/api/price-locks' ;
2026-10-21 01:32:49 +08:00
if ( ! data . customer ||! data . line . name ) throw new Error ( '请填写客户与黄金商品名称。' );
if ( LedgerCalc . isSilver ( data . line . name )) throw new Error ( '锁价仅支持按克黄金,银饰请直接开单。' );
lockQuantityMg ( data . line . quantity ); if ( LedgerCalc . cents ( data . line . goldPrice ) <= 0 || LedgerCalc . cents ( data . material . rate ) <= 0 ) throw new Error ( '销售金价与原进货料价须大于0。' );
LedgerCalc . cents ( data . payment . amount , '客户实际付款' ); LedgerCalc . orderTotal ([ LedgerCalc . sale ( data . line ). sale ], LedgerCalc . cents ( data . discount ), 'yuan' );
2026-10-23 09:49:36 +08:00
if ( isCreditCardAccount ( data . payment . account ) &&! creditCardAvailable ()) throw new Error ( '信用卡收款暂未准备好,请刷新后重新核对。' );
2026-10-21 01:32:49 +08:00
if ( ! data . payment . verified ||! data . material . verified ) throw new Error ( '请核实客户实际付款与原锁料费实际付款。' );
} else {
const lock = currentPriceLock ; if ( ! lock || form . dataset . id !== lock . id ) throw new Error ( '请重新读取锁价单后办理交付。' ); data = collectPriceLockDelivery (); url = '/api/price-locks/' + encodeURIComponent ( lock . id ) + '/deliver' ;
const costs = LedgerCalc . priceLockCost ({ lockedQuantity : grams ( lock . locked_mg ), quantity : data . line . quantity , buyRate : ( lock . buy_rate / 100 ). toFixed ( 2 ), extraBuyRate : data . extraMaterial . rate });
2026-10-23 09:49:36 +08:00
validateIssueDraft ({ lines : [ data . line ], fee_items : data . fee_items , discount : data . discount , rounding_mode : 'yuan' },{ requireIdentity : false });
2026-10-21 01:32:49 +08:00
if ( ! state . pockets . includes ( data . inventory . pocket ) ||! [ 'receive' , 'stocked' ]. includes ( data . inventory . original )) throw new Error ( '请选择实际出库货盘,并确认原锁金料是否已入库。' );
2026-10-25 14:19:24 +08:00
if ( costs . extraMg && ( ! [ 'receive' , 'stocked' ]. includes ( data . inventory . extra ) ||! [ 'owner' , 'assistant' , 'assistant2' ]. includes ( data . extraMaterial . payer ) ||! data . extraMaterial . verified )) throw new Error ( '请填写补重料价、付款人、是否已入库,并确认实际付款。' );
2026-10-21 01:32:49 +08:00
const total = LedgerCalc . orderTotal ([ LedgerCalc . sale ( data . line ). sale ], LedgerCalc . cents ( data . discount ), 'yuan' ), difference = total . total - lock . netReceived ;
2026-10-23 09:49:36 +08:00
if ( difference > 0 && isCreditCardAccount ( data . settlement . account ) &&! creditCardAvailable ()) throw new Error ( '信用卡收款暂未准备好,请刷新后重新核对。' );
2026-10-21 01:32:49 +08:00
if ( difference &&! data . settlement . verified ) throw new Error ( '请先核实客户补款或退款已实际完成。' );
if ( ! data . verified ) throw new Error ( '请核对实物、实际成本、库存来源与客户收付款后确认交付。' );
const line = data . line ; data . line = { quantity : line . quantity , laborRate : line . laborRate , laborMode : line . laborMode , pieces : line . pieces , charges : line . charges , payer : line . payer , costParts : { labor : line . costParts . labor , accessories : line . costParts . accessories , other : line . costParts . other }, costLabor : line . costLabor , costPayers : line . costPayers };
delete data . fee_auto_initialized ; if ( ! costs . extraMg ){ delete data . extraMaterial ; delete data . inventory . extra ;} if ( ! difference ) delete data . settlement ;
}
const result = await mutate ( url , data ); await finishPriceLockSave ( url , data , result );
}
function priceLockCostLink ( item ){
if ( item . kind === 'afterSale' ) return e ( reportCostIdentity ( item ));
if ( item . price_lock_id ) return `<button class="link-button" data-action="open-price-lock" data-id=" ${ e ( item . price_lock_id ) } "> ${ e ( item . number || '锁价记录' ) } </button> ${ item . customer ? `<div class="small muted"> ${ e ( item . customer ) } </div>` : '' } ` ;
return `<button class="link-button" data-action="open-order" data-id=" ${ e ( item . order_id ) } "> ${ e ( item . paper_number || item . number ) } </button>` ;
}
function priceLockActivityRows ( activity ){
if ( ! activity ) return [];
return [...( activity . customerCash || []),...( activity . orderPayments || [])]. map ( item =>({... item , activityType : item . kind === 'receipt' ? '客户收款' : '客户退款' , who : item . account , activityName : item . product || '客户收退款' })). concat (
( activity . materialOutlays || []). map ( item =>({... item , activityType : item . source === 'extra' ? '补重料费付款' : '原锁料费付款' , who : priceLockPayerName ( item . payer ), activityName : ( item . product || '黄金' ) + ' · ' + grams ( item . quantity ) + 'g × ' + yuan ( item . rate ) + '元/克' })),
( activity . deliveryGoodsOutlays || []). map ( item =>({... item , activityType : '交付货品支出' , who : priceLockPayerName ( item . payer ), activityName : item . name })),
( activity . directOutlays || []). map ( item =>({... item , activityType : '实际费用' , who : priceLockPayerName ( item . payer ), activityName : item . note }))
). sort (( a , b )=> a . date . localeCompare ( b . date ));
}
function priceLockActivityHTML ( activity ){
if ( ! activity ? . summary ? . eventCount ) return '' ;
const s = activity . summary , rows = priceLockActivityRows ( activity );
return `<section class="panel lock-activity"><h2>锁价实际收付</h2><p class="small muted"> ${ e ( activity . from === activity . date ? activity . date : activity . from + ' 至 ' + activity . date ) } 实际发生的锁价收退款与支出。此区不随订单搜索或状态筛选变化;每日对账归集这些收付。待交付不计销售和利润;交付日计入完整订单利润,原锁料款不重复记支出。</p><div class="lock-activity-summary"><span>客户实收<strong>¥ ${ yuan ( s . receipt ) } </strong></span><span>客户实退<strong>¥ ${ yuan ( s . refund ) } </strong></span><span>麦麦实际支出<strong>¥ ${ yuan ( s . ownerOutlay ) } </strong></span><span>助理实际支出<strong>¥ ${ yuan ( s . assistantOutlay ) } </strong></span></div><details><summary>查看 ${ rows . length } 项收付记录</summary><div class="table-wrap"><table class="lock-activity-table"><thead><tr><th>日期/锁价单</th><th>项目/客户</th><th>账户/付款人</th><th class="number">金额</th></tr></thead><tbody> ${ rows . map ( item => `<tr><td> ${ e ( item . date ) } <br><button class="link-button" data-action="open-price-lock" data-id=" ${ e ( item . price_lock_id ) } "> ${ e ( item . number || '锁价记录' ) } </button></td><td> ${ e ( item . activityType ) } · ${ e ( item . activityName ) } <div class="small muted"> ${ e ( item . customer ) } </div></td><td> ${ e ( item . who ) } </td><td class="number"> ${ item . amount == null ? '待补齐' : '¥' + yuan ( item . amount ) } </td></tr>` ). join ( '' ) } </tbody></table></div></details></section>` ;
}
function priceLockActivityText ( activity ){
if ( ! activity ? . summary ? . eventCount ) return [];
const s = activity . summary ; return [ '锁价实际收付(按实际发生日期,不重复计原锁付款;待交付不计销售和利润)' , `客户实收 ¥ ${ yuan ( s . receipt ) } ;客户实退 ¥ ${ yuan ( s . refund ) } ;麦麦实际支出 ¥ ${ yuan ( s . ownerOutlay ) } ;助理实际支出 ¥ ${ yuan ( s . assistantOutlay ) } ` ,... priceLockActivityRows ( activity ). map ( item => ` ${ item . date } / ${ item . number || '锁价记录' } / ${ item . customer } / ${ item . activityType } / ${ item . activityName } / ${ item . who } / ${ item . amount == null ? '待补齐' : '¥' + yuan ( item . amount ) } ` ), '' ];
}
function priceLockInventoryCreditHTML ( order ){
if ( ! order . assistantInventoryCredit ) return '' ;
return `<div class="note">留在自有货盘的金料/退回货品由助理垫付 <strong>¥ ${ yuan ( order . assistantInventoryCredit ) } </strong>,已在货款结算中抵扣。 ${ order . assistantInventoryCreditExplanation ? `<div class="small"> ${ e ( order . assistantInventoryCreditExplanation ) } </div>` : '' } <div class="small">抵扣后货款待结 ¥ ${ yuan ( order . costDue ) } ;利润待结 ¥ ${ yuan ( order . profitDue ) } 。库存垫资只抵扣结算,不重复扣减订单成本或利润。</div></div>` ;
}