Files
weiguang-jewelry-ledger/新账系统/public/price-locks-ui.js
T

266 lines
47 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
'use strict';
let createMode='direct',priceLockRequest=0,priceLockDeliveryId='',currentPriceLock=null,priceLockPoolRead=null,priceLockPoolError='';
const priceLockDraftKey=()=>`mm-price-lock-draft-${session.user.id}`;
const priceLockDeliveryKey=id=>`mm-price-lock-delivery-${session.user.id}-${id}`;
const priceLockPayerName=payer=>({owner:'麦麦',assistant:typeof teamMode==='function'&&teamMode()?'助理1':'助理',assistant2:'助理2'})[payer]||'待补';
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;}}
const priceLockUsesPool=lock=>lock?.material_source==='pool';
function priceLockMaterialAllocations(lock){return priceLockUsesPool(lock)?lock.materialPool?.allocations||[]:[{payer:lock.buy_payer,amount:lock.material_amount}];}
function priceLockAllocationText(allocations){return allocations.map(part=>priceLockPayerName(part.payer)+' ¥'+yuan(part.amount)).join(';');}
function priceLockAllocationHTML(allocations){return allocations.map(part=>`<span>${e(priceLockPayerName(part.payer))} <b>¥${yuan(part.amount)}</b></span>`).join('');}
function priceLockCreateMaterialHTML(material){
const manual=material.manual||material,source=material.source==='pool'?'pool':'manual';
return `<section class="panel internal price-lock-material"><h2>原锁金料实际成本</h2><div class="material-source-row">${choice('原锁材料来源','material_source',[['manual','手动填写料价'],['pool','当日加权料价']],source)}<span class="small muted">料池占用锁定克重;实物出库在交付时登记。</span></div><div id="lock-manual-material"><div class="grid three">${moneyField('原锁进货料价(元/克)','material_rate',manual.rate??'')}${choice('原锁料费付款人','material_payer',teamMemberOptions(),manual.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" ${manual.verified?'checked':''} required>已核实原锁金料的实际付款。</label><p class="small muted">独立记录这批原锁金料的实际付款;工费、快递等在交付时填写实际成本。库存归属也在交付时确认。</p></div><div id="lock-pool-material" hidden><div class="grid three">${field('料池日期(随锁价日期)','material_pool_date','','text','readonly')}${field('加权进货料价(元/克,自动)','material_pool_rate','','text','readonly')}<div><span class="small muted">本次预留料费(元,自动)</span><div id="lock-pool-material-estimate" class="summary-amount">待填写</div></div></div><p id="lock-pool-material-note" class="material-pool-note small muted" aria-live="polite"></p><div id="lock-pool-material-payers" class="price-lock-material-payers small" aria-live="polite"></div><div class="actions">${button('刷新料池','reload-price-lock-pool','quiet')}</div><p class="small muted">使用已登记购料,按购料付款顺序自动归属,可涉及多人;保存锁价不再登记料费付款。锁价当天补料仍参与加权,跨天后保留锁价日成本。</p></div></section>`;
}
// 原锁只占用本日料池;金额沿用普通开单的累计分币算法,付款人按同一金额区间取FIFO。
function priceLockPoolPreview(date,quantity){
const known=typeof materialPoolsCache!=='undefined'&&materialPoolsCacheUser===state.user.id&&!!materialPoolsCache;
const rows=known?materialPoolRows():[],pool=rows.find(value=>value.id===date);
if(priceLockPoolError||!known)throw new Error(priceLockPoolError||'正在读取每日料池,请稍候。');
if(!currentMaterialRolling())throw new Error('请先启用统一料池,再选择当日加权料价。');
if(!pool||!pool.totalMg)throw new Error(date+' 尚无可用材料。请先登记购料,再保存锁价。');
if(pool.totalAmount==null)throw new Error('料池成本尚未补齐,请先核对材料记录,再保存锁价。');
const mg=lockQuantityMg(quantity);
const preview=LedgerCalc.poolMaterialPreview(pool,[{lineIndex:0,mg}],{allUsages:rows.flatMap(value=>value.usages||[])});
const remainingMg=Math.max(0,pool.totalMg-preview.usedMg),shortageMg=Math.max(0,mg-remainingMg),amount=preview.amounts[0];
if(!preview.covered||amount==null)return {pool,mg,...preview,amount:null,remainingMg,shortageMg,allocations:[]};
const fromAmount=LedgerCalc.poolMaterialAmount(pool.totalAmount,pool.totalMg,preview.usedMg),allocations=[],parts=(pool.purchases||[]).flatMap(purchase=>purchase.allocations||[{payer:purchase.payer,amount:purchase.amount}]);
let skip=fromAmount,left=amount,zeroPayer='';
for(const part of parts){
if(!['owner','assistant','assistant2'].includes(part.payer)||!Number.isSafeInteger(part.amount)||part.amount<=0)throw new Error('料池付款来源未完整读到,请刷新料池。');
if(skip>=part.amount){skip-=part.amount;continue;}
zeroPayer||=part.payer;const value=Math.min(left,part.amount-skip),saved=allocations.find(item=>item.payer===part.payer);
if(value){if(saved)saved.amount+=value;else allocations.push({payer:part.payer,amount:value});}left-=value;skip=0;
if(!left)break;
}
if(skip||left)throw new Error('料池付款来源不足,请刷新并核对购料。');
if(!amount)allocations.push({payer:zeroPayer||parts.at(-1)?.payer||'owner',amount:0});
return {pool,mg,...preview,amount,remainingMg,shortageMg,allocations};
}
function syncPriceLockMaterial(form){
const source=form.querySelector('[name="material_source"]');if(!source)return;
const poolMode=source.value==='pool',manual=$('#lock-manual-material'),poolRoot=$('#lock-pool-material');
manual.hidden=poolMode;poolRoot.hidden=!poolMode;
for(const control of manual.querySelectorAll('input,select')){control.disabled=poolMode;control.required=!poolMode;}
if(!poolMode)return;
const date=lockFormValue(form,'date'),quantity=lockFormValue(form,'quantity'),note=$('#lock-pool-material-note'),payers=$('#lock-pool-material-payers'),estimate=$('#lock-pool-material-estimate'),rate=form.querySelector('[name="material_pool_rate"]');
form.querySelector('[name="material_pool_date"]').value=date;rate.value='';estimate.textContent='待确定';payers.innerHTML='';poolRoot.dataset.revision='';poolRoot.dataset.ready='false';note.classList.remove('danger-text');
try{
if(date!==state.today)throw new Error('当日加权料池只支持今天锁价;补录其他日期请使用手动填写料价。');
const preview=priceLockPoolPreview(date,quantity),{pool,amount,remainingMg,shortageMg,allocations}=preview;
rate.value=pool.averageRate==null?'':(pool.averageRate/100).toFixed(2);poolRoot.dataset.revision=pool.revision;
note.textContent=`${date} 料池 ${grams(pool.totalMg)}g,已用/预留 ${grams(preview.usedMg)}g,可用 ${grams(remainingMg)}g;本次预留 ${grams(preview.mg)}g。`;
if(shortageMg){note.textContent+=`还缺 ${grams(shortageMg)}g,请先补足购料后再保存锁价。`;note.classList.add('danger-text');return;}
estimate.textContent='¥'+yuan(amount);payers.innerHTML='<strong>自动来源:</strong>'+priceLockAllocationHTML(allocations);poolRoot.dataset.ready='true';
}catch(err){note.textContent=err.message;note.classList.add('danger-text');}
}
async function loadPriceLockPoolChoices(force=false){
const form=$('#price-lock-create-form');if(!form?.querySelector('[name="material_source"]')||typeof readMaterialPools!=='function')return;
if(priceLockPoolRead?.form===form)return priceLockPoolRead.promise;
const user=state.user.id;
const promise=(async()=>{priceLockPoolError='';let readError='';try{await readMaterialPools(force);}catch(err){readError='每日料池尚未读到:'+(err.name==='AbortError'?'读取超时,请刷新料池。':err.message);}if(form===$('#price-lock-create-form')&&state.user.id===user){priceLockPoolError=readError;syncPriceLockForm();}})();
priceLockPoolRead={form,promise};try{await promise;}finally{if(priceLockPoolRead?.promise===promise)priceLockPoolRead=null;}
}
function collectPriceLockCreate(){
const form=$('#price-lock-create-form'),get=name=>lockFormValue(form,name);
const material=get('material_source')==='pool'?{source:'pool',poolId:get('date'),revision:$('#lock-pool-material')?.dataset.revision||''}:{rate:get('material_rate'),payer:get('material_payer'),verified:form.querySelector('[name="material_verified"]').checked};
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};
}
function renderPriceLockCreate(){
const d=priceLockReadDraft(priceLockDraftKey())||{},line=d.line||{},payment=d.payment||{},material=d.material||{};
$('#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>${priceLockCreateMaterialHTML(material)}<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>`;
syncPriceLockForm();loadPriceLockPoolChoices(true);
}
function syncPriceLockCreate(){
const form=$('#price-lock-create-form');if(!form)return;syncPaymentRecipient(form);syncLockChargeFields(form);syncPriceLockMaterial(form);
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='待填写';}
let paymentCents=null;try{paymentCents=LedgerCalc.cents(d.payment.amount);}catch{}
syncCreditCardPreview($('#lock-create-card-fee'),d.payment.account,paymentCents);
const manual={rate:lockFormValue(form,'material_rate'),payer:lockFormValue(form,'material_payer'),verified:form.querySelector('[name="material_verified"]').checked};
localStorage.setItem(priceLockDraftKey(),JSON.stringify({...d,material:d.material.source==='pool'?{...d.material,manual}:d.material}));
}
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 '';
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>`;
}
function priceLockDialog(){let dialog=$('#price-lock-dialog');if(!dialog){dialog=document.createElement('dialog');dialog.id='price-lock-dialog';document.body.append(dialog);}return dialog;}
function priceLockFacts(lock){
const pool=priceLockUsesPool(lock),material=lock.materialPool;
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>原锁料费 · ${pool?'当日加权料池':'手动独立购料'}<strong>¥${yuan(lock.material_amount)}</strong><small>${pool?`${e(material?.date||lock.material_pool_id||lock.date)}料池,加权均价约 ¥${yuan(material?.averageRate??lock.buy_rate)}/克`:`${e(priceLockPayerName(lock.buy_payer))}支付,进货料价 ¥${yuan(lock.buy_rate)}/克`}</small>${pool?`<small>${e(priceLockAllocationText(priceLockMaterialAllocations(lock)))}</small><small>${material?.frozen?'已冻结锁价日成本':'当天补料继续加权'},不重复记购料付款。</small>`:''}</div><div>状态<strong>${lock.status==='pending'?'待交付,不计利润':'已交付'}</strong></div></div>`+priceLockCardFeesHTML(lock);
}
function priceLockDeliveryCost(lock,quantity,extraBuyRate){
if(!priceLockUsesPool(lock))return LedgerCalc.priceLockCost({lockedQuantity:grams(lock.locked_mg),quantity,buyRate:(lock.buy_rate/100).toFixed(2),extraBuyRate});
const pool=lock.materialPool,finalMg=lockQuantityMg(quantity),originalUsedMg=Math.min(finalMg,lock.locked_mg),extraMg=Math.max(0,finalMg-lock.locked_mg),leftoverMg=lock.locked_mg-originalUsedMg;
if(!pool||!['basisAmount','basisMg','prefixMg','prefixAmount','amount'].every(key=>Number.isSafeInteger(pool[key])&&pool[key]>=0)||!pool.basisMg)throw new Error('原锁料池成本来源未完整读到,请重新读取锁价单。');
const originalUsedCost=LedgerCalc.poolMaterialAmount(pool.basisAmount,pool.basisMg,pool.prefixMg+originalUsedMg)-pool.prefixAmount;
const extraRate=extraMg?LedgerCalc.cents(extraBuyRate,'补重进货料价'):0;if(extraMg&&!extraRate)throw new Error('补重进货料价必须大于0。');
const extraCost=extraMg?Number((BigInt(extraMg)*BigInt(extraRate)+500n)/1000n):0;
let left=originalUsedCost;const allocations=[];
for(const part of priceLockMaterialAllocations(lock)){const amount=Math.min(left,part.amount);if(amount||!originalUsedCost&&!allocations.length)allocations.push({payer:part.payer,amount});left-=amount;}
if(left||originalUsedCost<0||originalUsedCost>pool.amount)throw new Error('原锁料池成本分摊不完整,请重新读取锁价单。');
return {lockedMg:lock.locked_mg,finalMg,originalUsedMg,extraMg,leftoverMg,originalPurchase:pool.amount,originalUsedCost,extraCost,materialCost:originalUsedCost+extraCost,leftoverCost:pool.amount-originalUsedCost,allocations};
}
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><strong>${priceLockUsesPool(lock)?'当日加权料池':'手动独立购料'}</strong><br>¥${yuan(lock.material_amount)}<div class="small muted">${e(priceLockAllocationText(priceLockMaterialAllocations(lock)))}</div></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,payer=priceLockMaterialAllocations(lock)[0]?.payer||lock.buy_payer||'owner';
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,costParts:{material:(lock.material_amount/100).toFixed(2),labor:'',accessories:'0',other:'0'},costMaterial:{mode:'total'},costLabor:{mode:'total'},costPayers:{material: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;
$('#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',priceLockUsesPool(lock)?'料池已预留,仅出库,不重复入库':'此前已记入,只出库']],priceLockUsesPool(lock)?'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>`;
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');
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:priceLockUsesPool(currentPriceLock)?'stocked':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};
}
function syncPriceLockDelivery(){
const form=$('#price-lock-delivery-form'),lock=currentPriceLock;if(!form||!lock||form.dataset.id!==lock.id)return;syncPaymentRecipient(form);
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=priceLockMaterialAllocations(lock)[0]?.payer||lock.buy_payer||'owner';
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=priceLockDeliveryCost(lock,get('quantity').value,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;
const poolMode=priceLockUsesPool(lock),formula=row.querySelector('.purchase-material .purchase-formula');
formula.textContent=costs?poolMode?`原锁按 ${lock.material_pool_id||lock.date} 料池耗用 ${grams(costs.originalUsedMg)}g,料费 ¥${yuan(costs.originalUsedCost)}${costs.extraMg?';补重 '+grams(costs.extraMg)+'g × '+lockFormValue(form,'extra_rate')+'元/克,料费 ¥'+yuan(costs.extraCost):''};合计 ¥${yuan(costs.materialCost)}`:`原锁使用 ${grams(costs.originalUsedMg)}g × ${yuan(lock.buy_rate)}元/克${costs.extraMg?';补重 '+grams(costs.extraMg)+'g × '+lockFormValue(form,'extra_rate')+'元/克':''} = ${yuan(costs.materialCost)}元`:poolMode?'原锁料费沿用料池实际分币金额;有补重时,请填写补重进货料价。':'料费按原锁进货价计算;有补重时,请先填写补重进货料价。';
if(poolMode){let payers=row.querySelector('.lock-pool-delivery-payers');if(!payers){formula.insertAdjacentHTML('afterend','<div class="lock-pool-delivery-payers price-lock-material-payers small"></div>');payers=row.querySelector('.lock-pool-delivery-payers');}payers.innerHTML='<strong>原锁耗用来源:</strong>'+priceLockAllocationHTML(costs?.allocations||priceLockMaterialAllocations(lock));}
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='请选择实际黄金货盘';
get('cost-materialPayer').closest('label').hidden=poolMode;
const originalStock=form.querySelector('[name="original_stock"]');originalStock.required=!poolMode;originalStock.disabled=poolMode;if(poolMode)originalStock.value='stocked';
const feeDate=form.querySelector('[name="fees_date"]');feeDate.value=lockFormValue(form,'date');feeDate.readOnly=true;
syncFeeRows();const d=collectPriceLockDelivery();
$('#lock-material-breakdown').textContent=costs?`原锁${poolMode?'预留':'料费已付'} ¥${yuan(lock.material_amount)};本单耗用料费 ¥${yuan(costs.materialCost)}${costs.leftoverMg?';'+(poolMode?'解除预留回池 ':'余料 ')+grams(costs.leftoverMg)+'g,成本 ¥'+yuan(costs.leftoverCost):''}${poolMode?';已有购料付款不重复登记。':''}`:extra?'请填写补重料价,计算本次实际耗用成本。':'填写最终交付克重,自动计算实际耗料。';
const original=d.inventory.original,pocket=d.inventory.pocket;
$('#lock-stock-note').textContent=costs&&original&&pocket?`${poolMode?'原锁金料已在料池预留,不重复入库;':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?poolMode?'少重 '+grams(costs.leftoverMg)+'g 解除预留回到料池,实物留在货盘,不重复入库或扣料。':'余料 '+grams(costs.leftoverMg)+'g 留在该货盘,按原进货价计成本,不重复入库。':''}`:'选择实际货盘和金料入库情况后,显示本次库存动作。';
let difference=null;
try{
const total=LedgerCalc.orderTotal([LedgerCalc.sale(d.line).sale],LedgerCalc.cents(d.discount),'yuan');difference=total.total-lock.netReceived;
$('#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='';}
syncPaymentRecipient(form);
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)});
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(typeof invalidateMaterialPools==='function')invalidateMaterialPools();
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','锁价已保存',data.material?.source==='pool'?'已经记好实际收款并预留料池克重,料费没有重复付款;尚未出入库、不计利润。':'已经记好实际收款与原锁料款,尚未出入库、不计利润。')+`<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'){
data=validateOrderIdentity(collectPriceLockCreate());url='/api/price-locks';
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)throw new Error('销售金价须大于0。');
if(data.material.source==='pool'){
if(data.date!==state.today)throw new Error('当日加权料池只支持今天锁价;补录其他日期请使用手动填写料价。');
const preview=priceLockPoolPreview(data.date,data.line.quantity);if(!preview.covered)throw new Error(`当日料池还缺 ${grams(preview.shortageMg)}g,请先补足购料后再保存锁价。`);
if(!data.material.revision||data.material.revision!==preview.pool.revision)throw new Error('请刷新料池,核对当前成本与自动付款来源后再保存。');
}else if(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');
if(isCreditCardAccount(data.payment.account)&&!creditCardAvailable())throw new Error('信用卡收款暂未准备好,请刷新后重新核对。');
if(!data.payment.verified||data.material.source!=='pool'&&!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=priceLockDeliveryCost(lock,data.line.quantity,data.extraMaterial.rate);
validateIssueDraft({lines:[data.line],fee_items:data.fee_items,discount:data.discount,rounding_mode:'yuan'},{requireIdentity:false});
if(!state.pockets.includes(data.inventory.pocket)||!['receive','stocked'].includes(data.inventory.original))throw new Error('请选择实际出库货盘,并确认原锁金料是否已入库。');
if(costs.extraMg&&(!['receive','stocked'].includes(data.inventory.extra)||!['owner','assistant','assistant2'].includes(data.extraMaterial.payer)||!data.extraMaterial.verified))throw new Error('请填写补重料价、付款人、是否已入库,并确认实际付款。');
const total=LedgerCalc.orderTotal([LedgerCalc.sale(data.line).sale],LedgerCalc.cents(data.discount),'yuan'),difference=total.total-lock.netReceived;
if(difference>0&&isCreditCardAccount(data.settlement.account)&&!creditCardAvailable())throw new Error('信用卡收款暂未准备好,请刷新后重新核对。');
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>`;
}