支持多商品锁价及待交付修改作废审批

This commit is contained in:
summer committed 2026-11-08 02:22:58 +08:00
1 parent 1cbcdc728c
commit 337b2a709f
28 files changed
+1187 -344

No files matched your search

+153 -103
View File
@@ -13,64 +13,87 @@ function lockQuantityMg(value){
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 priceLockLines(lock){
if(!Array.isArray(lock?.lines)||!lock.lines.length)return lock?[lock]:[];
return lock.lines.map((item,index)=>{const row={...lock,...item,id:item.id||item.lineId||item.price_lock_line_id,line:item.line||item,line_index:index,parent_id:lock.id};delete row.lines;return row;});
}
function priceLockCreateRows(form){const rows=[...(form?.querySelectorAll('[data-price-lock-sale]')||[])];return rows.length?rows:form?[form]:[];}
function priceLockPart(root,part){return root?.querySelector?.('[data-lock-part="'+part+'"]')||$('#lock-'+part);}
function priceLockCreateLine(row,date){
const get=name=>lockFormValue(row,name),poolRoot=priceLockPart(row,'pool-material');
const material=get('material_source')==='pool'?{source:'pool',poolId:date,revision:poolRoot?.dataset.revision||''}:{rate:get('material_rate'),payer:get('material_payer'),verified:row.querySelector('[name="material_verified"]')?.checked===true};
return {...(row.dataset.lineId?{lineId:row.dataset.lineId}:{}),name:get('name').trim(),code:get('code').trim(),unit:'g',pricingMode:'auto',quantity:get('quantity'),goldPrice:get('goldPrice'),laborRate:get('laborRate'),laborMode:get('laborMode'),pieces:get('pieces'),charges:lockCharges(row),material};
}
function priceLockCreateLineHTML(line={},index=0){
return `<section class="panel line-item price-lock-create-line" data-price-lock-sale data-line-id="${e(line.lineId||'')}"><div class="line-top"><strong>商品 ${String(index+1).padStart(2,'0')}</strong>${button('移除商品','remove-lock-line','quiet')}</div><div class="grid four">${field('黄金商品名称(可自定义)','name',line.name??'足金999','text','required maxlength="60"')}${field('款号(选填)','code',line.code||'','text','maxlength="40"')}${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><div class="charge-list">${(line.charges||[]).map(chargeHTML).join('')}</div></div><p class="calculation small" data-lock-part="sale-estimate" aria-live="polite"></p>${priceLockCreateMaterialHTML(line.material||{},index)}</section>`;
}
function changePriceLockLines(action,buttonElement){
const form=$('#price-lock-create-form'),list=$('#lock-create-lines');if(!form||!list)return;
const rows=priceLockCreateRows(form);
if(action==='add-lock-line'){if(rows.length>=60)throw new Error('每张锁价单最多填写60件商品。');list.insertAdjacentHTML('beforeend',priceLockCreateLineHTML({},rows.length));}
else{if(rows.length<=1)throw new Error('请至少保留一件锁价商品。');buttonElement.closest('[data-price-lock-sale]')?.remove();}
priceLockCreateRows(form).forEach((row,index)=>{const title=row.querySelector('.line-top strong');if(title)title.textContent='商品 '+String(index+1).padStart(2,'0');});syncPriceLockForm();
}
const priceLockUsesPool=lock=>lock?.material_source==='pool';
const priceLockMaterialPending=lock=>lock?.material_amount===null||priceLockUsesPool(lock)&&(lock.materialPool?.status==='pending'||lock.materialPool?.amount===null);
function priceLockMaterialAmountText(lock){const amount=priceLockUsesPool(lock)&&Number.isSafeInteger(lock.materialPool?.amount)?lock.materialPool.amount:lock.material_amount;return priceLockMaterialPending(lock)||!Number.isSafeInteger(amount)?'料费待补':'¥'+yuan(amount);}
function priceLockMaterialAllocations(lock){return priceLockMaterialPending(lock)?[]: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>`;
function priceLockCreateMaterialHTML(material,index=null){
const manual=material.manual||material,source=material.source==='pool'?'pool':'manual',part=name=>`id="lock-${name}${index===null?'':'-'+index}" data-lock-part="${name}"`;
return `<div class="internal price-lock-material"><h3>原锁金料实际成本</h3><div class="material-source-row">${choice('原锁材料来源','material_source',[['manual','手动填写料价'],['pool','当日加权料价']],source)}<span class="small muted">料池占用本行锁定克重;实物出库在交付时登记。</span></div><div ${part('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 ${part('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 ${part('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 ${part('pool-material-estimate')} class="summary-amount">待填写</div></div></div><p ${part('pool-material-note')} class="material-pool-note small muted" aria-live="polite"></p><div ${part('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></div>`;
}
// 原锁只占用本日料池;金额沿用普通开单的累计分币算法,付款人按同一金额区间取FIFO。
function priceLockPoolPreview(date,quantity){
function priceLockPoolPreview(date,quantity,lineIndex=0,form=$('#price-lock-create-form')){
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(materialPoolHasPersonal(pool)){
const form=$('#price-lock-create-form'),input=materialLockQuoteInput(form),quote=materialQuoteFor(form,input,'lock');if(!quote.result)throw new Error(quote.error||'正在按订单归属核对个人回收料与公共补足,请稍候。');
const row=quote.result.entries.find(row=>row.lineIndex===0),balance=quote.result.pools.find(row=>row.poolId===date),mg=lockQuantityMg(quantity);if(!row||!balance)throw new Error('本次料费来源未完整返回,请刷新料池。');
const remainingMg=balance.before?.eligibleRemainingMg??0,shortageMg=Math.max(0,mg-remainingMg);return {pool:{...pool,revision:balance.revision},mg,amount:row.amount,amounts:{0:row.amount},covered:row.amount!==null,remainingMg,shortageMg,allocations:row.allocations,materialSources:row.materialSources,balance};
const mg=lockQuantityMg(quantity),input=materialLockQuoteInput(form),entries=input.entries.length?input.entries:[{lineIndex,poolId:date,mg}],wantedMg=entries.reduce((sum,row)=>sum+row.mg,0);
if(materialPoolHasPersonal(pool)||typeof editingPendingPriceLock==='function'&&editingPendingPriceLock(form)){
const quote=materialQuoteFor(form,input,'lock');if(!quote.result)throw new Error(quote.error||'正在按订单归属核对个人回收料与公共补足,请稍候。');
const row=quote.result.entries.find(row=>row.lineIndex===lineIndex),balance=quote.result.pools.find(row=>row.poolId===date);if(!row||!balance)throw new Error('本次料费来源未完整返回,请刷新料池。');
const remainingMg=balance.before?.eligibleRemainingMg??0,shortageMg=Math.max(0,wantedMg-remainingMg);return {pool:{...pool,revision:balance.revision},mg,wantedMg,amount:row.amount,amounts:Object.fromEntries(quote.result.entries.map(row=>[row.lineIndex,row.amount])),covered:quote.result.entries.every(row=>row.amount!==null)&&!shortageMg,remainingMg,shortageMg,allocations:row.allocations,materialSources:row.materialSources,balance};
}
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];
const preview=LedgerCalc.poolMaterialPreview(pool,entries,{allUsages:rows.flatMap(value=>value.usages||[])});
const remainingMg=Math.max(0,pool.totalMg-preview.usedMg),shortageMg=Math.max(0,wantedMg-remainingMg),amount=preview.amounts[lineIndex];
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}]);
const prefixMg=preview.usedMg+entries.filter(row=>row.lineIndex<lineIndex).reduce((sum,row)=>sum+row.mg,0);
const fromAmount=LedgerCalc.poolMaterialAmount(pool.totalAmount,pool.totalMg,prefixMg),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(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');
function syncPriceLockMaterial(form,row=form,lineIndex=0){
const source=row.querySelector('[name="material_source"]');if(!source)return;
const poolMode=source.value==='pool',manual=priceLockPart(row,'manual-material'),poolRoot=priceLockPart(row,'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');
const date=lockFormValue(form,'date'),quantity=lockFormValue(row,'quantity'),note=priceLockPart(row,'pool-material-note'),payers=priceLockPart(row,'pool-material-payers'),estimate=priceLockPart(row,'pool-material-estimate'),rate=row.querySelector('[name="material_pool_rate"]');
row.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,materialSources}=preview;
if(date!==state.today&&!(typeof priceLockEditAllowsPoolDate==='function'&&priceLockEditAllowsPoolDate(form,date)))throw new Error('当日加权料池只支持今天锁价;补录其他日期请使用手动填写料价。');
const preview=priceLockPoolPreview(date,quantity,lineIndex,form),{pool,amount,remainingMg,shortageMg,allocations,materialSources}=preview;
rate.value=materialSources?.length?materialSources.map(source=>materialSourceName(source)+' '+(source.averageRate==null?'待补':(source.averageRate/100).toFixed(2))).join(';'):pool.averageRate==null?'':(pool.averageRate/100).toFixed(2);poolRoot.dataset.revision=pool.revision;
note.textContent=preview.balance?`${date} · ${materialPayerName(materialFormMember(form))}先用本人回收料,公共补足;${materialQuoteBalanceText(preview.balance)}本次预留 ${grams(preview.mg)}g。`:`${date} 料池 ${grams(pool.totalMg)}g,已用/预留 ${grams(preview.usedMg)}g,可用 ${grams(remainingMg)}g;本次预留 ${grams(preview.mg)}g。`;
note.textContent=preview.balance?`${date} · ${materialPayerName(materialFormMember(form))}先用本人回收料,公共补足;${materialQuoteBalanceText(preview.balance)}本行预留 ${grams(preview.mg)}g。`:`${date} 料池 ${grams(pool.totalMg)}g,已用/预留 ${grams(preview.usedMg)}g,可用 ${grams(remainingMg)}g;本行预留 ${grams(preview.mg)}g,本单共预留 ${grams(preview.wantedMg??preview.mg)}g。`;
if(shortageMg){note.textContent+=`还缺 ${grams(shortageMg)}g,请先补足购料后再保存锁价。`;note.classList.add('danger-text');return;}
if(amount==null){note.textContent+='材料成本待补齐,请先核对后保存锁价。';note.classList.add('danger-text');return;}
if(amount==null||!preview.covered){note.textContent+='材料成本待补齐,请先核对后保存锁价。';note.classList.add('danger-text');return;}
estimate.textContent='¥'+yuan(amount);payers.innerHTML=(materialSources?.length?materialSourceSegmentsHTML(materialSources):'')+'<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;
@@ -79,36 +102,65 @@ async function loadPriceLockPoolChoices(force=false){
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};
const form=$('#price-lock-create-form'),get=name=>lockFormValue(form,name),rows=priceLockCreateRows(form),lines=rows.map(row=>priceLockCreateLine(row,get('date')));
const data={...(teamMode()?{member:get('member')||currentMember()}:{}),date:get('date'),customer:get('customer').trim(),salesperson:get('salesperson'),note:get('note'),discount:get('discount'),payment:{amount:get('received_amount'),account:readPaymentAccount(form),credit_card_fee_payer:readCreditCardPayer(form),verified:form.querySelector('[name="payment_verified"]').checked}};
if(rows[0]===form){const {material,...line}=lines[0];return {...data,line,material};}return {...data,lines};
}
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>`;
const editing=typeof priceLockEditEntry!=='undefined'&&priceLockEditEntry?.user===session.user.id,edit=editing?priceLockEditEntry:null;
const d=editing?edit.inputs:priceLockReadDraft(priceLockDraftKey())||{},lines=Array.isArray(d.lines)&&d.lines.length?d.lines:[{...d.line,material:d.material||{}}],payment=d.payment||{};
$('#main').innerHTML=heading('GOLD PRICE LOCK',editing?'修改待交付锁价单':'黄金锁价',editing?'原单号 '+e(edit.lock.number)+';按核实后的整单资料更正,尚未交付。':'同一客户可添加多件按克黄金,每件分别锁定售价与原料来源;整单收款、整单交付。保存后暂不出入库、不计利润。',editing?button('退出修改','leave-lock-edit','quiet'):priceLockCreateControls())+`<form id="price-lock-create-form"${editing?` data-price-lock-edit-id="${e(edit.id)}"`: ''}><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(),editing)}</div></section><div id="lock-create-lines">${lines.map(priceLockCreateLineHTML).join('')}</div><div class="lock-add-product">${button('+ 添加商品','add-lock-line')}<span class="small muted">每件商品可自定义名称、克重、售价、工费和原锁成本。</span></div><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>${editing?priceLockPendingEditReviewHTML(edit):''}<section class="panel"><div class="grid two">${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><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" data-lock-create-submit>${editing?(priceLockPendingNeedsApproval(edit)?'提交修改申请':'保存锁价修改'):'保存锁价待交付'}</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='待填写';}
const form=$('#price-lock-create-form');if(!form)return;syncPaymentRecipient(form);syncLockChargeFields(form);
const rows=priceLockCreateRows(form);rows.forEach((row,index)=>{syncPriceLockMaterial(form,row,index);const piece=row.querySelector('[name="pieces"]'),pieceMode=lockFormValue(row,'laborMode')==='piece';piece.closest('label').hidden=!pieceMode;piece.required=pieceMode;});
const d=collectPriceLockCreate(),lines=d.lines||[{...d.line,material:d.material}];
rows.forEach((row,index)=>{
const line=lines[index],saleNote=priceLockPart(row,'sale-estimate');
try{const sale=LedgerCalc.sale(line);if(saleNote&&saleNote!==$('#lock-sale-estimate'))saleNote.textContent='本行商品及附加项目合计 ¥'+yuan(sale.sale);}catch{if(saleNote&&saleNote!==$('#lock-sale-estimate'))saleNote.textContent='填写克重、销售金价与工费后显示本行报价。';}
const estimate=priceLockPart(row,'material-estimate');try{const cost=LedgerCalc.purchaseCosts({unit:'g',quantity:line.quantity,costParts:{material:'0',labor:'0',accessories:'0',other:'0'},costMaterial:{mode:'gram',rate:lockFormValue(row,'material_rate')}});estimate.textContent=cost.total==null?'待填写':'¥'+yuan(cost.total);}catch{estimate.textContent='待填写';}
});
try{const sales=lines.map(line=>LedgerCalc.sale(line).sale),total=LedgerCalc.orderTotal(sales,LedgerCalc.cents(d.discount),'yuan');$('#lock-create-total').textContent=orderAmount(total.total,'yuan');$('#lock-sale-estimate').textContent=`${lines.length}件商品及附加项目合计 ¥${yuan(sales.reduce((sum,value)=>sum+value,0))};`+orderRoundingHint(total);}catch{$('#lock-create-total').textContent='待填写';$('#lock-sale-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}));
const manualFor=row=>({rate:lockFormValue(row,'material_rate'),payer:lockFormValue(row,'material_payer'),verified:row.querySelector('[name="material_verified"]').checked});
const saved=d.lines?{...d,lines:d.lines.map((line,index)=>({...line,material:line.material.source==='pool'?{...line.material,manual:manualFor(rows[index])}:line.material}))}:{...d,material:d.material.source==='pool'?{...d.material,manual:manualFor(form)}:d.material};
if(!(typeof syncPendingPriceLockEditDraft==='function'&&syncPendingPriceLockEditDraft(saved,form)))localStorage.setItem(priceLockDraftKey(),JSON.stringify(saved));
}
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 priceLockItemFactsHTML(lock){
const pool=priceLockUsesPool(lock),material=lock.materialPool,pendingMaterial=priceLockMaterialPending(lock);
return `${lock.status==='cancelled'?'<div class="small danger-text">原录入成本(已撤销记账)</div>':''}<strong>${priceLockMaterialAmountText(lock)}</strong><div class="small muted">${pool?'当日加权料池':'手动独立购料'}${pendingMaterial?';补足购料后自动核算付款来源':pool?` · ${e(material?.date||lock.material_pool_id||lock.date)}<br>${e(priceLockAllocationText(priceLockMaterialAllocations(lock)))}<br>${material?.materialSources?.length?e(materialSourceSegmentsText(material.materialSources))+'<br>':''}${material?.frozen?'已冻结锁价日成本':'当天补料继续加权'},不重复记购料付款。`:` · ${e(priceLockPayerName(lock.buy_payer))}<br>进货料价 ¥${yuan(lock.buy_rate)}/克`}</div>`;
}
function priceLockItemsHTML(lock){
const rows=priceLockLines(lock);
return `<div class="table-wrap price-lock-items"><table aria-label="锁价商品明细"><thead><tr><th>商品</th><th class="number">原锁克重</th><th class="number">原锁销售金价</th><th>工费与附加项目</th><th>原锁料费/付款来源</th>${lock.status==='delivered'?'<th>实际交付</th>':''}</tr></thead><tbody>${rows.map((row,index)=>{const item=row.line||{},delivery=row.delivery;return `<tr><td><strong>${e(item.name||'黄金')}</strong><div class="small muted">商品 ${index+1}${item.code?' · '+e(item.code):''}</div></td><td class="number">${grams(row.locked_mg)}g</td><td class="number">¥${yuan(row.sell_rate)}/克</td><td>${item.laborMode==='piece'?`件工费 ¥${yuan(item.laborRate??0)} × ${e(item.pieces||1)}件`:`克工费 ¥${yuan(item.laborRate??0)}/克`}${(item.charges||[]).map(charge=>`<div class="small muted">${e(charge.name)} ¥${yuan(charge.amount)}</div>`).join('')}</td><td>${priceLockItemFactsHTML(row)}</td>${lock.status==='delivered'?`<td>${delivery?`${grams(delivery.finalMg??delivery.quantity??row.locked_mg)}g${(delivery.extraMg??delivery.extra_mg)?'<br>补重 '+grams((delivery.extraMg??delivery.extra_mg))+'g':''}${(delivery.leftoverMg??delivery.leftover_mg)?'<br>'+ (priceLockUsesPool(row)?'解除预留回池 ':'剩料留盘 ')+grams((delivery.leftoverMg??delivery.leftover_mg))+'g':''}${delivery.inventory?.pocket?'<br>货盘 '+e(delivery.inventory.pocket):delivery.pocket?'<br>货盘 '+e(delivery.pocket):''}`:'详见销售单'}</td>`:''}</tr>`;}).join('')}</tbody></table></div>`;
}
function priceLockDeliveryRows(form){return [...(form?.querySelectorAll('[data-price-lock-delivery-item]')||[])];}
function priceLockDeliveryInventoryHTML(lock,draft={},index=0){
const part=name=>`data-lock-part="${name}"`,pool=priceLockUsesPool(lock);
return `<div class="internal lock-line-inventory"><h3>本件金料与库存确认</h3><div class="grid two">${choice('原锁金料是否已记入本件货盘','original_stock',[['','请选择'],['receive','尚未记入,交付时先入库'],['stocked',pool?'料池已预留,仅出库,不重复入库':'此前已记入,只出库']],pool?'stocked':draft.inventory?.original||'')}<div ${part('material-breakdown')} class="lock-material-breakdown" aria-live="polite"></div></div><div ${part('extra-material')} class="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 ${part('stock-note')} class="note" aria-live="polite"></p></div>`;
}
function priceLockFacts(lock){
const voided=lock.status==='cancelled'?'<div class="note price-lock-voided-note"><strong>这张锁价单已作废</strong><p>客户收款、手填购料和信用卡手续费有效记账已撤销,料池预留已释放。下方原录入克重、售价和成本保留用于追溯,不计当前有效收付。</p></div>':'';
const rows=priceLockLines(lock);
if(rows.length>1){
const mg=rows.reduce((sum,row)=>sum+row.locked_mg,0),pending=rows.some(priceLockMaterialPending),amount=rows.reduce((sum,row)=>sum+(row.material_amount??0),0);
return voided+`<div class="grid three price-lock-facts"><div>锁价日期<strong>${e(lock.date)}</strong></div><div>原锁总克重 · ${rows.length}件<strong>${grams(mg)}g</strong></div><div>${lock.status==='delivered'?'锁价及交付阶段净收款':'客户实际已付净额'}<strong>¥${yuan(lock.netReceived)}</strong></div><div>原锁料费合计<strong>${pending?'料费待补':'¥'+yuan(amount)}</strong></div><div>状态<strong>${lock.status==='pending'?'待交付,不计利润':lock.status==='cancelled'?'已作废':'已交付'}</strong></div></div>${priceLockItemsHTML(lock)}${priceLockCardFeesHTML(lock)}`;
}
lock=rows[0]||lock;
const pool=priceLockUsesPool(lock),material=lock.materialPool,pendingMaterial=priceLockMaterialPending(lock);
const source=pendingMaterial?'<small>关联用料不足,补足购料后自动核算料费与付款来源。</small>':`<small>${pool?material?.materialSources?.length?e(materialSourceSegmentsText(material.materialSources)):`${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>`:''}`;
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>${priceLockMaterialAmountText(lock)}</strong>${source}</div><div>状态<strong>${lock.status==='pending'?'待交付,不计利润':'已交付'}</strong></div></div>`+priceLockCardFeesHTML(lock);
return voided+`<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>${priceLockMaterialAmountText(lock)}</strong>${source}</div><div>状态<strong>${lock.status==='pending'?'待交付,不计利润':lock.status==='cancelled'?'已作废':'已交付'}</strong></div></div>`+priceLockCardFeesHTML(lock);
}
function priceLockSplitMaterialSources(pool,mg){
let left=mg;const taken=[],rest=[];if(!Array.isArray(pool.materialSources)||pool.materialSources.reduce((sum,source)=>sum+source.quantity,0)!==pool.quantity||pool.materialSources.reduce((sum,source)=>sum+source.amount,0)!==pool.amount)throw new Error('原锁分来源克重或成本未完整读到,请重新读取。');
@@ -138,16 +190,16 @@ function priceLockDeliveryCost(lock,quantity,extraBuyRate){
}
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>${priceLockMaterialAmountText(lock)}<div class="small muted">${priceLockMaterialPending(lock)?'补足购料后自动核算付款来源':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>';
const request=++priceLockRequest,user=state.user.id,status=typeof priceLockListStatus==='string'?priceLockListStatus:'pending';
$('#main').innerHTML=heading(status==='cancelled'?'VOIDED PRICE LOCKS':'PENDING DELIVERY',status==='cancelled'?'已作废锁价单':'待交付',status==='cancelled'?'以下为录错作废后保留的原单。收款、手填购料与信用卡手续费记账已撤销,料池预留已释放;原录入成本仅供追溯,不计有效支出。':'显示所有日期的锁价待交付记录。锁价时只记实际收付,交付后才计销售、成本和利润。',button('新增锁价','new-price-lock','primary')+button('修改与作废申请','price-lock-changes-open')+button('刷新','refresh-price-locks'))+`<div class="actions lock-list-filter">${button('待交付','price-lock-list-status',status==='pending'?'primary':'', 'data-status="pending"')}${button('已作废','price-lock-list-status',status==='cancelled'?'primary':'', 'data-status="cancelled"')}</div>`+'<section class="panel"><div id="price-lock-list" aria-live="polite">正在读取待交付记录…</div></section>';
try{const result=await api('/api/price-locks?status='+status);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>${status==='cancelled'?'原录入成本(已撤销记账)':'原料来源/成本'}</th><th>操作</th></tr></thead><tbody>${result.rows.map(lock=>`<tr><td>${e(lock.date)}<br>${e(lock.customer)}</td><td>${priceLockLines(lock).map(row=>e(row.line?.name||'黄金')).join('<br>')}</td><td class="number">${grams(priceLockLines(lock).reduce((sum,row)=>sum+row.locked_mg,0))}g</td><td class="number">${priceLockLines(lock).map(row=>'¥'+yuan(row.sell_rate)+'/克').join('<br>')}</td><td class="number">¥${yuan(lock.netReceived)}</td><td>${priceLockLines(lock).map(row=>priceLockItemFactsHTML(row)).join('<hr class="lock-row-divider">')}</td><td><div class="actions">${button('查看','open-price-lock','',`data-id="${e(lock.id)}"`)}${lock.status==='pending'?button('交付','deliver-price-lock','primary',`data-id="${e(lock.id)}"`)+(typeof priceLockPendingButtonsHTML==='function'?priceLockPendingButtonsHTML(lock):''):''}</div></td></tr>`).join('')}</tbody></table></div>`:(status==='cancelled'?'<div class="empty"><strong>目前没有已作废锁价单</strong>作废后保留的原单会显示在这里。</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>`;
$('#price-lock-detail').innerHTML=`<div class="order-header"><div class="eyebrow">GOLD PRICE LOCK</div><h2>${e(lock.customer)} · ${priceLockLines(lock).length}件黄金锁价</h2></div>${priceLockFacts(lock)}${priceLockLines(lock).length===1?priceLockItemsHTML(lock):''}<p class="small muted">预计报价 ¥${yuan(lock.estimated_total)};交付时按最终克重、工费和附加项目重新结算,销售金价保持原锁价格。</p>${lock.note?`<p>${e(lock.note)}</p>`:''}${lock.status==='cancelled'?`<p class="note">已作废 · ${e(lock.cancelled_reason||'原单记录保留')}<br>${e(lock.cancelled_at||'')}</p>`:''}<div class="actions">${lock.status==='pending'?button('办理交付','deliver-price-lock','primary',`data-id="${e(lock.id)}"`)+(typeof priceLockPendingButtonsHTML==='function'?priceLockPendingButtonsHTML(lock):''):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){
@@ -163,54 +215,54 @@ async function renderPriceLockDelivery(id){
$('#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>`;
const saved=priceLockReadDraft(priceLockDeliveryKey(id)),draft=saved?.revision===lock.revision?saved:{},date=draft.date||state.today,rows=priceLockLines(lock);
const items=rows.map((item,index)=>{const d=draft.lines?.find(row=>row.lineId===item.id)||(rows.length===1&&draft.line?{...draft,line:draft.line}:{}),line=d.line||d.quantity&&d||priceLockLineInputs(item);return `<section class="panel price-lock-delivery-line" data-price-lock-delivery-item data-line-id="${e(item.id||'')}" data-line-index="${index}"><div class="panel-title"><h2>${e(item.line.name)} · 最终商品与实际成本</h2><span class="small muted">原锁 ${grams(item.locked_mg)}g · ¥${yuan(item.sell_rate)}/克</span></div>${lineHTML(line,index+1)}${priceLockDeliveryInventoryHTML(item,d,index)}</section>`;}).join('');
$('#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><div id="lines">${items}</div><section class="panel internal"><h2>整单交付汇总</h2><p id="lock-delivery-summary" 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};
const form=$('#price-lock-delivery-form'),get=name=>lockFormValue(form,name),roots=priceLockDeliveryRows(form),locks=priceLockLines(currentPriceLock);
const items=(roots.length?roots:[form]).map((root,index)=>{const row=root.querySelector('.line-item')||root.querySelector('#lines .line-item'),item=locks[index];if(roots.length&&root.dataset.lineId!==item?.id)throw new Error('交付商品与原锁记录不一致,请重新读取。');const get=name=>lockFormValue(root,name);return {lineId:item?.id,line:collectLine(row),extraMaterial:{rate:get('extra_rate'),payer:get('extra_payer'),verified:root.querySelector('[name="extra_verified"]')?.checked===true},inventory:{pocket:row.querySelector('[name="pocket"]').value,original:priceLockUsesPool(item)?'stocked':get('original_stock'),extra:get('extra_stock')}};});
const data={revision:Number(form.dataset.revision),date:get('date'),note:get('delivery_note'),discount:get('discount'),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};
if(!roots.length)return {...data,line:items[0].line,inventory:items[0].inventory,extraMaterial:items[0].extraMaterial};
return {...data,lines:items.map(({line,...item})=>({...line,...item}))};
}
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?`${costs.materialSources?.length?materialSourceSegmentsText(costs.materialSources):'原锁按 '+(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)+(costs.leftoverMaterialSources?.length?'('+materialSourceSegmentsText(costs.leftoverMaterialSources)+')':''):''}${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 留在该货盘,按原进货价计成本,不重复入库。':''}`:'选择实际货盘和金料入库情况后,显示本次库存动作。';
const roots=priceLockDeliveryRows(form),locks=priceLockLines(lock),allCosts=[];
(roots.length?roots:[form]).forEach((root,index)=>{
const item=locks[index],row=root.querySelector('.line-item')||root.querySelector('#lines .line-item'),get=name=>row.querySelector(`[name="${name}"]`),value=name=>lockFormValue(root,name);
get('goldPrice').value=(item.sell_rate/100).toFixed(2);get('unit').value='g';get('pricingMode').value='auto';get('cost-materialMode').value='total';get('cost-materialPayer').value=priceLockMaterialAllocations(item)[0]?.payer||item.buy_payer||'owner';
let costs=null,extra=false;try{extra=lockQuantityMg(get('quantity').value)>item.locked_mg;}catch{}
const extraRoot=priceLockPart(root,'extra-material');extraRoot.hidden=!extra;for(const input of extraRoot.querySelectorAll('input,select')){input.disabled=!extra;input.required=extra;}
try{costs=priceLockDeliveryCost(item,get('quantity').value,value('extra_rate'));get('cost-material').value=(costs.materialCost/100).toFixed(2);}catch{get('cost-material').value='';}allCosts.push(costs);
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(item),formula=row.querySelector('.purchase-material .purchase-formula');
formula.textContent=costs?poolMode?`${costs.materialSources?.length?materialSourceSegmentsText(costs.materialSources):'原锁按 '+(item.material_pool_id||item.date)+' 料池耗用 '+grams(costs.originalUsedMg)+'g,料费 ¥'+yuan(costs.originalUsedCost)}${costs.extraMg?';补重 '+grams(costs.extraMg)+'g × '+value('extra_rate')+'元/克,料费 ¥'+yuan(costs.extraCost):''};合计 ¥${yuan(costs.materialCost)}`:`原锁使用 ${grams(costs.originalUsedMg)}g × ${yuan(item.buy_rate)}元/克${costs.extraMg?';补重 '+grams(costs.extraMg)+'g × '+value('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(item));}
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=root.querySelector('[name="original_stock"]');originalStock.required=!poolMode;originalStock.disabled=poolMode;if(poolMode)originalStock.value='stocked';
priceLockPart(root,'material-breakdown').textContent=costs?`原锁${poolMode?'预留':'料费已付'} ¥${yuan(item.material_amount)};本件耗用料费 ¥${yuan(costs.materialCost)}${costs.leftoverMg?';'+(poolMode?'解除预留回池 ':'余料 ')+grams(costs.leftoverMg)+'g,成本 ¥'+yuan(costs.leftoverCost)+(costs.leftoverMaterialSources?.length?'('+materialSourceSegmentsText(costs.leftoverMaterialSources)+')':''):''}${poolMode?';已有购料付款不重复登记。':''}`:extra?'请填写本件补重料价,计算实际耗用成本。':'填写本件最终交付克重,自动计算实际耗料。';
const original=originalStock.value,pocket=get('pocket').value;
priceLockPart(root,'stock-note').textContent=costs&&original&&pocket?`${poolMode?'原锁金料已在料池预留,不重复入库;':original==='receive'?'原锁 '+grams(item.locked_mg)+'g 先入库;':'原锁金料此前已入库;'}${costs.extraMg?(value('extra_stock')==='receive'?'补重 '+grams(costs.extraMg)+'g 先入库;':value('extra_stock')==='stocked'?'补重金料此前已入库;':'请选择补重金料是否已入库;'):''}从「${pocket}」出库 ${grams(costs.finalMg)}g。${costs.leftoverMg?poolMode?'少重 '+grams(costs.leftoverMg)+'g 解除预留回到料池,实物留在货盘,不重复入库或扣料。':'余料 '+grams(costs.leftoverMg)+'g 留在该货盘,按原进货价计成本,不重复入库。':''}`:'选择本件实际货盘和金料入库情况后,显示库存动作。';
});
const feeDate=form.querySelector('[name="fees_date"]');feeDate.value=lockFormValue(form,'date');feeDate.readOnly=true;syncFeeRows();const d=collectPriceLockDelivery(),lines=d.lines||[d.line];
const summary=$('#lock-delivery-summary');if(summary){if(allCosts.every(Boolean)){const sum=key=>allCosts.reduce((total,cost)=>total+cost[key],0);summary.textContent=`共 ${lines.length}件,实际交付 ${grams(sum('finalMg'))}g;耗用料费 ¥${yuan(sum('materialCost'))};补重 ${grams(sum('extraMg'))}g,新增料费 ¥${yuan(sum('extraCost'))};剩料/回池 ${grams(sum('leftoverMg'))}g,成本 ¥${yuan(sum('leftoverCost'))}。库存动作按各件所选货盘登记。`;}else summary.textContent='请逐件补齐最终克重和补重料价,再核对整单交付汇总。';}
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;
const total=LedgerCalc.orderTotal(lines.map(line=>LedgerCalc.sale(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()));
}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();
@@ -218,7 +270,7 @@ async function finishPriceLockSave(url,data,result){
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>`;
$('#main').innerHTML=heading('LOCK SAVED','锁价已保存',(data.lines?data.lines.some(line=>line.material?.source==='pool'):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);}
@@ -233,33 +285,31 @@ async function finishPriceLockSave(url,data,result){
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(preview.shortageMg?`当日料池还缺 ${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('请核实客户实际付款与原锁料费实际付款。');
data=validateOrderIdentity(collectPriceLockCreate());url='/api/price-locks';const lines=data.lines||[{...data.line,material:data.material}];
if(!data.customer||!lines.length)throw new Error('请填写客户与黄金商品名称。');
for(const [index,line]of lines.entries()){
if(!line.name)throw new Error(`请填写商品 ${index+1} 的黄金商品名称。`);if(LedgerCalc.isSilver(line.name))throw new Error('锁价仅支持按克黄金,银饰请直接开单。');lockQuantityMg(line.quantity);if(LedgerCalc.cents(line.goldPrice)<=0)throw new Error('销售金价须大于0。');
if(line.material.source==='pool'){
if(data.date!==state.today&&!(typeof priceLockEditAllowsPoolDate==='function'&&priceLockEditAllowsPoolDate(form,data.date)))throw new Error('当日加权料池只支持今天锁价;补录其他日期请使用手动填写料价。');const preview=priceLockPoolPreview(data.date,line.quantity,index,form);if(!preview.covered)throw new Error(preview.shortageMg?`当日料池还缺 ${grams(preview.shortageMg)}g,请先补足购料后再保存锁价。`:'材料成本待补齐,请先核对后保存锁价。');if(!line.material.revision||line.material.revision!==preview.pool.revision)throw new Error('请刷新料池,核对当前成本与自动付款来源后再保存。');
}else{if(LedgerCalc.cents(line.material.rate)<=0)throw new Error('原进货料价须大于0。');if(!line.material.verified)throw new Error('请核实客户实际付款与各件原锁料费实际付款。');}
}
LedgerCalc.cents(data.payment.amount,'客户实际付款');LedgerCalc.orderTotal(lines.map(line=>LedgerCalc.sale(line).sale),LedgerCalc.cents(data.discount),'yuan');if(isCreditCardAccount(data.payment.account)&&!creditCardAvailable())throw new Error('信用卡收款暂未准备好,请刷新后重新核对。');if(!data.payment.verified)throw new Error('请核实客户实际付款与原锁料费实际付款。');
if(typeof editingPendingPriceLock==='function'&&editingPendingPriceLock(form)){const edit=pendingPriceLockEditPayload(data,form);url=edit.url;data=edit.data;}
}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 locks=priceLockLines(lock),items=data.lines||[{...data.line,inventory:data.inventory,extraMaterial:data.extraMaterial}];if(items.length!==locks.length)throw new Error('请逐件填写全部锁价商品后整单交付。');
const costs=items.map((line,index)=>{const item=locks[index];if(data.lines&&line.lineId!==item.id)throw new Error('交付商品与原锁记录不一致,请重新读取。');return priceLockDeliveryCost(item,line.quantity,line.extraMaterial?.rate);});
validateIssueDraft({lines:items,fee_items:data.fee_items,discount:data.discount,rounding_mode:'yuan'},{requireIdentity:false});
items.forEach((line,index)=>{if(!state.pockets.includes(line.inventory.pocket)||!['receive','stocked'].includes(line.inventory.original))throw new Error(`请选择商品 ${index+1} 的实际出库货盘,并确认原锁金料是否已入库。`);if(costs[index].extraMg&&(!['receive','stocked'].includes(line.inventory.extra)||!['owner','assistant','assistant2'].includes(line.extraMaterial?.payer)||!line.extraMaterial?.verified))throw new Error(`请填写商品 ${index+1} 的补重料价、付款人、是否已入库,并确认实际付款。`);});
const total=LedgerCalc.orderTotal(items.map(line=>LedgerCalc.sale(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 actual=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});
if(data.lines)data.lines=items.map((line,index)=>({...actual(line),lineId:line.lineId,inventory:{pocket:line.inventory.pocket,original:line.inventory.original,...(costs[index].extraMg?{extra:line.inventory.extra}:{})},...(costs[index].extraMg?{extraMaterial:line.extraMaterial}:{})}));
else{data.line=actual(data.line);if(!costs[0].extraMg){delete data.extraMaterial;delete data.inventory.extra;}}
delete data.fee_auto_initialized;if(!difference)delete data.settlement;
}
const result=await mutate(url,data);await finishPriceLockSave(url,data,result);
const result=await mutate(url,data);if(typeof priceLockPendingOperation==='function'&&priceLockPendingOperation(url))return finishPendingPriceLockSave(url,data,result);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>`:''}`;