锁价交付补重支持当日料池,内部备注移至客户名旁
This commit is contained in:
1 parent
ac9073471d
commit
c5883351c1
20 files changed
+196
-66
No files matched your search
@@ -233,3 +233,11 @@ button.order-copy-button:focus-visible{outline:3px solid var(--gold);outline-off
|
||||
|
||||
/* 客户结算价带入按钮放在单价下方,同行金额保持顶部对齐。 */
|
||||
#recovery-form .recovery-row:has(>.recovery-customer-rate){align-items:start}#recovery-form .recovery-customer-rate{min-width:0}#recovery-form .recovery-customer-rate>button{margin-top:6px}#recovery-form [data-rate-status]{margin:4px 0 0;line-height:1.6}
|
||||
|
||||
/* 内部备注紧邻客户名;仅用于内部订单详情,不进入销售单打印模板。 */
|
||||
.order-detail-title{display:flex;align-items:flex-start;gap:24px;min-width:0;flex-wrap:wrap}
|
||||
.order-detail-title>h2{flex:0 1 auto;max-width:100%;min-width:0;margin:0}
|
||||
.order-detail-title .detail-internal-note{flex:1 1 200px;min-width:0;max-width:680px;padding:8px 14px;border-left:3px solid #d8bc85;border-radius:0 6px 6px 0;background:#f2eddf}
|
||||
.detail-internal-note-label{display:block;color:#807050;font-size:11px;line-height:1.5;margin-bottom:3px}
|
||||
.detail-internal-note p{margin:0;color:#624a26;font-size:16px;font-weight:600;line-height:1.6;overflow-wrap:anywhere}
|
||||
@media(max-width:650px){.order-detail-title{flex-direction:column;gap:10px}.order-detail-title .detail-internal-note{flex:none;width:100%;max-width:none}.detail-internal-note p{font-size:15px}}
|
||||
+2
-2
@@ -417,7 +417,7 @@ async function loadOrderNoteTags(){
|
||||
catch{if(request===orderNoteTagsRequest&&container===document.querySelector('[data-order-note-tags]'))container.textContent='快捷标签暂未读取成功,可直接填写备注。';}
|
||||
}
|
||||
function orderInternalNoteHTML(order){
|
||||
return `<section class="panel internal detail-internal-note" aria-label="内部备注(客户不可见)"><h2>内部备注(客户不可见)</h2><p>${order.internal_note?e(order.internal_note).replace(/\r\n?|\n/g,'<br>'):'<span class="muted">未填写</span>'}</p></section>`;
|
||||
return `<aside class="detail-internal-note" aria-label="内部备注(客户不可见)"><span class="detail-internal-note-label">内部备注 · 客户不可见</span><p>${order.internal_note?e(order.internal_note).replace(/\r\n?|\n/g,'<br>'):'<span class="muted">未填写</span>'}</p></aside>`;
|
||||
}
|
||||
function renderCreate(){
|
||||
if(tab==='order-edit')return renderOrderEditForm();
|
||||
@@ -1258,7 +1258,7 @@ function renderDetail(){
|
||||
if(o.recovery_id&&typeof recoveryLinkedOrderActionsHTML==='function')actions=recoveryLinkedOrderActionsHTML(o,{reviewAllowed:owner&&!approvalPending&&o.reviewed_revision!==o.revision});
|
||||
const costs=orderDetailCostSummary(o);
|
||||
const reviewSeal=!approvalPending&&orderIsReviewed(o)?'<div class="order-review-seal" role="status" aria-label="已审批,麦麦已复核"><svg viewBox="0 0 24 24" aria-hidden="true" focusable="false"><circle cx="12" cy="12" r="10"/><path d="m7 12 3.2 3.2L17 8.5"/></svg><strong>已审批</strong><small>麦麦已复核</small></div>':'';
|
||||
$('#order-content').innerHTML=`<div id="order-detail-navigation" class="order-detail-navigation" ${orderDetailNavigationHTML()?'':'hidden'} aria-busy="${!!orderDetailLoad}">${orderDetailNavigationHTML()}</div><div class="order-header order-detail-header"><div class="eyebrow">ORDER DETAIL</div><div class="order-detail-heading"><h2>${e(String(o.customer??'').trim()||'未填客户称呼')}</h2>${reviewSeal}</div><p class="small muted order-detail-identifiers">纸单号 ${e(o.paper_number||'未分配')} · 系统单号 ${e(o.number)} · 收款账户 ${e(accountDisplayName(o.payment_account))}</p>${badge(o)}${o.member?`<span class="badge member-badge">${e(teamMemberName(o.member))}的订单</span>`:''}${typeof orderOwnershipActionHTML==='function'?orderOwnershipActionHTML(o):''}<span class="muted small">业务日期 ${e(o.date)} · 开单人 ${e(o.salesperson)}</span>${orderEntryTimeHTML(o)}</div>${materialPoolOrderNoticeHTML(o)}${typeof recoveryLinkedOrderNoticeHTML==='function'?recoveryLinkedOrderNoticeHTML(o):''}${!done?`<div class="note">${o.status==='draft'?'这是尚未开单的旧草稿,继续填写后生成销售单据。':'这张旧单尚未完成销售记账。请按实际情况补齐款项、货品成本和费用,再点“补齐旧单账务”;保存时一并记费用、扣库存和计算利润。'}</div>`:''}<div class="actions detail-actions">${actions}</div>${typeof orderCancellationDetailHTML==='function'?orderCancellationDetailHTML(o):''}${typeof orderChangeDetailHTML==='function'?orderChangeDetailHTML(o):''}${typeof orderOwnershipDetailHTML==='function'?orderOwnershipDetailHTML(o):''}<div id="detail-form" class="detail-form"></div><div id="detail-error"></div>${typeof orderAfterSaleDetailHTML==='function'?orderAfterSaleDetailHTML(o):''}${orderInternalNoteHTML(o)}<div class="order-detail-breakdown">${orderSalesHTML(o,{voided})}${orderCostsHTML(o,costs,{voided})}</div>${orderProfitHTML(o,costs,{voided})}${orderProductTraceHTML(o)}${o.funds_mode==='team'?orderTeamFundsHTML(o):`<details class="panel detail-settlement"><summary>${teamMode()?'历史两人结算(只供追溯,不计入团队往来)':'与娜娜的结算'}</summary><div class="grid three"><div>麦麦垫资应回收 <strong>¥${yuan(o.ownerCost)}</strong><br><small class="muted">实际已交净额 ¥${yuan(o.costTransferred)}</small></div><div>已记账订单利润 <strong>${done?(o.profit==null?(o.materialCostPending?'料费待补':'成本未补齐'):'¥'+yuan(o.profit)):'旧单待补齐'}</strong><br><small class="muted">实际已交净额 ¥${yuan(o.profitTransferred)}</small></div><div>${o.settlementDue<0?'麦麦待转回娜娜':'娜娜待交麦麦'} <strong>${o.settlementDue==null?'料费待补':'¥'+yuan(Math.abs(o.settlementDue))}</strong><br><small class="muted">${o.materialCostPending?'补足购料后自动计算;当前不能登记交款':done?'含本单货款与利润,该日购料结算另行核对':'旧单完成销售记账后形成应交款'}</small></div></div>${priceLockInventoryCreditHTML(o)}${o.ownerDirect?afterSaleDone?`<div class="note">麦麦账户实际留存客户款 ¥${yuan(o.ownerDirect)},已纳入售后扣留款与最终利润,请按实际账户核对结算。</div>`:`<div class="note">麦麦直接收客户净额 ¥${yuan(o.ownerDirect)},${o.status==='delivered'?'已从总待结金额扣除,货款/利润拆分需单独复核。':o.price_lock_id&&o.status==='returned'&&o.netReceived===0?'客户已退清;跨账户收退款形成的差额已计入双方结算。':'这部分属于客户款,取消/退货后须从原账户退客户,不算应返助理。'}</div>`:''}<p class="small muted" style="margin:14px 0 0">开单后按单交货款,利润月底交。退货返款单独记录,不抵下一笔。这里记录实际转账,不会发起付款。</p></details>`}<details class="panel"><summary>收退款与费用记录</summary>${transactionTable(o)}<details><summary>操作记录</summary><ul class="timeline">${o.audit.map(a=>`<li>${e(actionName[a.action]||a.action)} · ${e(a.actor)}<small>${e(new Date(a.created).toLocaleString('zh-CN'))}</small>${a.detail.reason?e(a.detail.reason):''}</li>`).join('')}</ul></details></details>`;
|
||||
$('#order-content').innerHTML=`<div id="order-detail-navigation" class="order-detail-navigation" ${orderDetailNavigationHTML()?'':'hidden'} aria-busy="${!!orderDetailLoad}">${orderDetailNavigationHTML()}</div><div class="order-header order-detail-header"><div class="eyebrow">ORDER DETAIL</div><div class="order-detail-heading"><div class="order-detail-title"><h2>${e(String(o.customer??'').trim()||'未填客户称呼')}</h2>${orderInternalNoteHTML(o)}</div>${reviewSeal}</div><p class="small muted order-detail-identifiers">纸单号 ${e(o.paper_number||'未分配')} · 系统单号 ${e(o.number)} · 收款账户 ${e(accountDisplayName(o.payment_account))}</p>${badge(o)}${o.member?`<span class="badge member-badge">${e(teamMemberName(o.member))}的订单</span>`:''}${typeof orderOwnershipActionHTML==='function'?orderOwnershipActionHTML(o):''}<span class="muted small">业务日期 ${e(o.date)} · 开单人 ${e(o.salesperson)}</span>${orderEntryTimeHTML(o)}</div>${materialPoolOrderNoticeHTML(o)}${typeof recoveryLinkedOrderNoticeHTML==='function'?recoveryLinkedOrderNoticeHTML(o):''}${!done?`<div class="note">${o.status==='draft'?'这是尚未开单的旧草稿,继续填写后生成销售单据。':'这张旧单尚未完成销售记账。请按实际情况补齐款项、货品成本和费用,再点“补齐旧单账务”;保存时一并记费用、扣库存和计算利润。'}</div>`:''}<div class="actions detail-actions">${actions}</div>${typeof orderCancellationDetailHTML==='function'?orderCancellationDetailHTML(o):''}${typeof orderChangeDetailHTML==='function'?orderChangeDetailHTML(o):''}${typeof orderOwnershipDetailHTML==='function'?orderOwnershipDetailHTML(o):''}<div id="detail-form" class="detail-form"></div><div id="detail-error"></div>${typeof orderAfterSaleDetailHTML==='function'?orderAfterSaleDetailHTML(o):''}<div class="order-detail-breakdown">${orderSalesHTML(o,{voided})}${orderCostsHTML(o,costs,{voided})}</div>${orderProfitHTML(o,costs,{voided})}${orderProductTraceHTML(o)}${o.funds_mode==='team'?orderTeamFundsHTML(o):`<details class="panel detail-settlement"><summary>${teamMode()?'历史两人结算(只供追溯,不计入团队往来)':'与娜娜的结算'}</summary><div class="grid three"><div>麦麦垫资应回收 <strong>¥${yuan(o.ownerCost)}</strong><br><small class="muted">实际已交净额 ¥${yuan(o.costTransferred)}</small></div><div>已记账订单利润 <strong>${done?(o.profit==null?(o.materialCostPending?'料费待补':'成本未补齐'):'¥'+yuan(o.profit)):'旧单待补齐'}</strong><br><small class="muted">实际已交净额 ¥${yuan(o.profitTransferred)}</small></div><div>${o.settlementDue<0?'麦麦待转回娜娜':'娜娜待交麦麦'} <strong>${o.settlementDue==null?'料费待补':'¥'+yuan(Math.abs(o.settlementDue))}</strong><br><small class="muted">${o.materialCostPending?'补足购料后自动计算;当前不能登记交款':done?'含本单货款与利润,该日购料结算另行核对':'旧单完成销售记账后形成应交款'}</small></div></div>${priceLockInventoryCreditHTML(o)}${o.ownerDirect?afterSaleDone?`<div class="note">麦麦账户实际留存客户款 ¥${yuan(o.ownerDirect)},已纳入售后扣留款与最终利润,请按实际账户核对结算。</div>`:`<div class="note">麦麦直接收客户净额 ¥${yuan(o.ownerDirect)},${o.status==='delivered'?'已从总待结金额扣除,货款/利润拆分需单独复核。':o.price_lock_id&&o.status==='returned'&&o.netReceived===0?'客户已退清;跨账户收退款形成的差额已计入双方结算。':'这部分属于客户款,取消/退货后须从原账户退客户,不算应返助理。'}</div>`:''}<p class="small muted" style="margin:14px 0 0">开单后按单交货款,利润月底交。退货返款单独记录,不抵下一笔。这里记录实际转账,不会发起付款。</p></details>`}<details class="panel"><summary>收退款与费用记录</summary>${transactionTable(o)}<details><summary>操作记录</summary><ul class="timeline">${o.audit.map(a=>`<li>${e(actionName[a.action]||a.action)} · ${e(a.actor)}<small>${e(new Date(a.created).toLocaleString('zh-CN'))}</small>${a.detail.reason?e(a.detail.reason):''}</li>`).join('')}</ul></details></details>`;
|
||||
}
|
||||
function transactionTable(o){const rows=[...o.payments.map(p=>({date:p.date,type:String(p.reference||'').startsWith('更正冲回:取消审批作废;')?'作废冲回'+(p.kind==='receipt'?'收款':'退款'):p.kind==='receipt'?'客户收款':'客户退款',amount:p.amount,who:accountDisplayName(p.account),note:p.reference})),...o.expenses.map(x=>({date:x.date,type:String(x.note||'').startsWith('更正冲回:取消审批作废;')?'作废冲回费用':'直接费用',amount:x.amount,who:teamMemberName(x.payer)+'支付',note:x.note})),...o.settlements.map(s=>({date:s.date,type:(s.amount<0?'麦麦返娜娜':'娜娜交麦麦')+' · '+(s.bucket==='cost'?'货款':'利润'),amount:Math.abs(s.amount),who:s.actor,note:s.note}))].sort((a,b)=>a.date.localeCompare(b.date));return rows.length?`<div class="table-wrap"><table><thead><tr><th>日期</th><th>业务</th><th>金额</th><th>账户/经办人</th><th>说明</th></tr></thead><tbody>${rows.map(r=>`<tr><td>${r.date}</td><td>${r.type}</td><td>¥${yuan(r.amount)}</td><td>${e(r.who)}</td><td>${e(r.note)}</td></tr>`).join('')}</tbody></table></div>`:'<p class="muted">还没有收退款、费用或交款记录。</p>';}
|
||||
function showAction(action){
|
||||
|
||||
@@ -185,7 +185,7 @@
|
||||
const payers=costPayers(line.costPayers);
|
||||
const parts=line.costParts?Object.entries(costLabels).map(([key,name])=>({key,name,amount:line.costParts[key]??null})):[{key:'total',name:'货品成本(原单未分项)',amount:line.cost??null}];
|
||||
for(const part of parts){
|
||||
if(part.key==='material'&&line.priceLockPool&&part.amount===null){add({kind:'goods',component:'material',name:part.name,source:'锁价料池成本待补',amount:null,payer:payers?.material??line.payer,excluded:goodsExcluded,materialPoolId:line.priceLockPool.poolId,poolPending:true,calculation:null});
|
||||
if(part.key==='material'&&(line.priceLockPool||line.priceLockExtraPool)&&part.amount===null){add({kind:'goods',component:'material',name:part.name,source:'锁价料池成本待补',amount:null,payer:payers?.material??line.payer,excluded:goodsExcluded,materialPoolId:(line.priceLockExtraPool?.amount===null?line.priceLockExtraPool:line.priceLockPool||line.priceLockExtraPool).poolId,poolPending:true,calculation:null});
|
||||
}else if(part.key==='material'&&line.costMaterial?.mode==='pool'){
|
||||
const pool=line.materialPool,allocations=pool?.allocations;
|
||||
if(part.amount===null||!allocations?.length){
|
||||
@@ -197,7 +197,7 @@
|
||||
}else if(part.key==='material'&&line.materialAllocations){
|
||||
const allocations=line.materialAllocations;
|
||||
if(!Array.isArray(allocations)||!allocations.length||allocations.some(item=>!['original','extra'].includes(item.source)||!['owner','assistant','assistant2'].includes(item.payer)||!Number.isSafeInteger(item.amount)||item.amount<0||!Number.isSafeInteger(item.quantity)||item.quantity<=0||!Number.isSafeInteger(item.rate)||item.rate<=0)||allocations.reduce((total,item)=>total+item.amount,0)!==part.amount)throw new Error('锁价分项料费记录无效');
|
||||
for(const item of allocations)add({kind:'goods',component:'material',name:part.name,source:`商品 ${i+1} · ${line.name} · ${item.source==='original'?(item.weighted?'原锁日料池':'原锁价采购'):'补重采购'}`,amount:item.amount,payer:item.payer,excluded:goodsExcluded,
|
||||
for(const item of allocations)add({kind:'goods',component:'material',name:part.name,source:`商品 ${i+1} · ${line.name} · ${item.source==='original'?(item.weighted?'原锁日料池':'原锁价采购'):(item.weighted?'交付日补重料池':'补重采购')}`,amount:item.amount,payer:item.payer,excluded:goodsExcluded,
|
||||
priceLockSource:item.source,...(item.poolId?{materialPoolId:item.poolId}:{}),calculation:{rate:item.rate,quantity:item.quantity,...(item.weighted?{weighted:true}:{} )}});
|
||||
}else add({kind:'goods',name:part.name,source:`商品 ${i+1} · ${line.name}`+(part.key==='labor'&&line.returnedStock?' · 退回现货继承工费':''),amount:part.amount,payer:payers?.[part.key]??line.payer,excluded:goodsExcluded,...(part.key==='labor'&&line.returnedStock?{inheritedStockCost:true,returnedStockId:line.returnedStockId}:{}),
|
||||
calculation:part.key==='material'&&line.recovery_id&&line.costMaterial?.rate!==undefined?{rate:line.costMaterial.rate,quantity:line.recoveryMaterialMg}:part.key==='material'&&line.costMaterial?.mode==='gram'?{rate:line.costMaterial.rate,quantity:line.quantity}:part.key==='labor'&&line.costLabor?.mode==='gram'?{rate:line.costLabor.rate,quantity:line.quantity}:null});
|
||||
|
||||
@@ -31,7 +31,7 @@ function materialLockQuoteInput(form=$('#price-lock-create-form')){
|
||||
else{const mg=materialPoolMg(form?.querySelector('[name="quantity"]')?.value);if(mg)entries.push({lineIndex:0,poolId:date,mg});}
|
||||
return {date,member:materialFormMember(form),...(form?.dataset.priceLockEditId?{priceLockId:form.dataset.priceLockEditId}:{}),entries};
|
||||
}
|
||||
function materialQuoteCurrent(kind){const form=$(kind==='lock'?'#price-lock-create-form':'#order-form');return {form,input:kind==='lock'?materialLockQuoteInput(form):materialOrderQuoteInput(form)};}
|
||||
function materialQuoteCurrent(kind){if(kind==='lockExtra'){const form=$('#price-lock-delivery-form');return {form,input:materialLockExtraQuoteInput(form)};}const form=$(kind==='lock'?'#price-lock-create-form':'#order-form');return {form,input:kind==='lock'?materialLockQuoteInput(form):materialOrderQuoteInput(form)};}
|
||||
function validateMaterialQuote(result,input){
|
||||
const integer=value=>Number.isSafeInteger(value)&&value>=0,amount=value=>value===null||integer(value);
|
||||
if(!result||result.date!==input.date||result.member!==input.member||!Array.isArray(result.entries)||result.entries.length!==input.entries.length||!Array.isArray(result.pools))throw new Error('分来源料费未完整返回,请刷新料价。');
|
||||
@@ -48,7 +48,7 @@ function materialQuoteFor(form,input,kind='order'){
|
||||
async function loadMaterialQuote(entry=materialQuoteEntry){
|
||||
if(!entry||entry!==materialQuoteEntry)return;if(entry.promise)return entry.promise;clearTimeout(materialQuoteTimer);
|
||||
const active=()=>{if(entry!==materialQuoteEntry||entry.request!==materialQuoteRequest||entry.user!==state.user.id)return false;const current=materialQuoteCurrent(entry.kind);return current.form===entry.form&&JSON.stringify(current.input)===entry.signature;};
|
||||
entry.promise=(async()=>{try{const result=await api('/api/material-pools/quote',entry.input);if(!active())return;entry.result=validateMaterialQuote(result,entry.input);entry.error='';}catch(err){if(!active())return;entry.result=null;entry.error=err.name==='AbortError'?'分来源料费核对超时,请刷新料价。':err.message;}if(active()){if(entry.kind==='lock')syncPriceLockForm();else updateTotal();}})();try{await entry.promise;}finally{entry.promise=null;}
|
||||
entry.promise=(async()=>{try{const result=await api('/api/material-pools/quote',entry.input);if(!active())return;entry.result=validateMaterialQuote(result,entry.input);entry.error='';}catch(err){if(!active())return;entry.result=null;entry.error=err.name==='AbortError'?'分来源料费核对超时,请刷新料价。':err.message;}if(active()){if(entry.kind==='lock'||entry.kind==='lockExtra')syncPriceLockForm();else updateTotal();}})();try{await entry.promise;}finally{entry.promise=null;}
|
||||
}
|
||||
function materialPoolMg(value){const text=String(value??'').trim();if(!/^\d+(?:\.\d{1,3})?$/.test(text))return null;const [whole,fraction='']=text.split('.'),mg=BigInt(whole)*1000n+BigInt(fraction.padEnd(3,'0'));return mg>0n&&mg<=100000000000n?Number(mg):null;}
|
||||
function materialPoolRate(value){return value==null?'待补采购':yuan(value);}
|
||||
|
||||
@@ -28,7 +28,7 @@ function collectMultiPriceLockOrderEdit(form,entry){
|
||||
function priceLockEditFinancialValue(input){
|
||||
if(input?.lines?.length>1)return {date:input.date,fees_date:input.fees_date,fee_cost_mode:input.fee_cost_mode||'legacy',lines:input.lines.map((line,index)=>({lineId:line.lineId,...priceLockEditFinancialValue({lines:[line],price_lock_material:priceLockOrderEditMaterial(input,index),price_lock_extra_material:priceLockOrderEditExtra(input,index),fee_items:[]})})),fees:priceLockEditFinancialValue({...input,lines:[]}).fees};
|
||||
const line=input?.lines?.[0]||{},material=input?.price_lock_material||{},extra=input?.price_lock_extra_material;
|
||||
return {date:input?.date,fees_date:input?.fees_date,fee_cost_mode:input?.fee_cost_mode||'legacy',material:material.source==='pool'?{source:'pool'}:{source:material.source,rate:priceLockEditAmount(material.rate),payer:material.payer},extra:extra?{rate:priceLockEditAmount(extra.rate),payer:extra.payer}:null,
|
||||
return {date:input?.date,fees_date:input?.fees_date,fee_cost_mode:input?.fee_cost_mode||'legacy',material:material.source==='pool'?{source:'pool'}:{source:material.source,rate:priceLockEditAmount(material.rate),payer:material.payer},extra:extra?{...(extra.source==='pool'?{source:'pool'}:{}),rate:priceLockEditAmount(extra.rate),payer:extra.payer}:null,
|
||||
costs:{labor:priceLockEditAmount(line.costParts?.labor),accessories:priceLockEditAmount(line.costParts?.accessories),other:priceLockEditAmount(line.costParts?.other),payer:line.payer,laborPayer:line.costPayers?.labor,laborMode:line.costLabor?.mode||'total',...(line.costLabor?.mode==='gram'?{laborRate:priceLockEditAmount(line.costLabor.rate)}:{})},
|
||||
fees:(input?.fee_items||[]).map(fee=>({key:fee.key,expense_id:fee.expense_id||'',date:fee.date||input.fees_date,note:fee.note,payer:fee.payer,amount:priceLockEditAmount(fee.amount),funding:fee.funding??null})).sort((a,b)=>String(a.key).localeCompare(String(b.key)))};
|
||||
}
|
||||
@@ -41,7 +41,7 @@ function collectPriceLockOrderEdit(form,entry=orderEditEntry){
|
||||
const material=original.price_lock_material||{},extra=original.price_lock_extra_material;
|
||||
return {...original,date:get('date',original.date),customer:get('customer',original.customer),salesperson:get('salesperson',original.salesperson),note:get('note',original.note),internal_note:get('internal_note',original.internal_note||''),fees_date:get('fees_date',original.fees_date),
|
||||
price_lock_material:{...material,source:get('lock_material_source',material.source),rate:get('lock_material_rate',material.rate),payer:get('lock_material_payer',material.payer),verified:form.querySelector('[name="lock_material_verified"]')?.checked??(material.verified===true)},
|
||||
...(extra?{price_lock_extra_material:{...extra,rate:get('lock_extra_rate',extra.rate),payer:get('lock_extra_payer',extra.payer),verified:form.querySelector('[name="lock_extra_verified"]')?.checked??(extra.verified===true)}}:{}),
|
||||
...(extra?{price_lock_extra_material:{...extra,source:get('lock_extra_source',extra.source||'manual'),rate:get('lock_extra_rate',extra.rate),payer:get('lock_extra_payer',extra.payer),verified:form.querySelector('[name="lock_extra_verified"]')?.checked??(extra.verified===true)}}:{}),
|
||||
lines:[{...line,payer:get('lock_cost_payer',line.payer),costLabor:{mode:laborMode,...(laborMode==='gram'?{rate:get('lock_cost_labor_rate',line.costLabor?.rate??'')}:{})},costParts:{...line.costParts,labor,accessories:get('lock_cost_accessories',line.costParts?.accessories??'0'),other:get('lock_cost_other',line.costParts?.other??'0')},costPayers:{...line.costPayers,labor:get('lock_cost_labor_payer',line.costPayers?.labor)}}],
|
||||
fee_cost_mode:$('#fee-rows')?.dataset?.feeCostMode||original.fee_cost_mode,fee_items:$('#fee-rows')?readFeeRows():original.fee_items};
|
||||
}
|
||||
@@ -145,7 +145,7 @@ function multiPriceLockOrderEditHTML(entry){
|
||||
function priceLockOrderEditHTML(entry){
|
||||
if(entry.inputs.lines.length>1)return multiPriceLockOrderEditHTML(entry);
|
||||
const draft=entry.inputs,lock=entry.priceLock,line=draft.lines[0],material=draft.price_lock_material,extra=draft.price_lock_extra_material,raw=entry.order.lines[0],sourceOptions=lock.materialSource==='pool'?[['pool','保留原锁料池'],...(lock.canSwitchToManual?[['manual','改为手填原锁料价']]:[])]:[['manual','手填原锁料价']];
|
||||
return `<div class="note" id="order-edit-save-intro">更正交付日期与实际成本,原锁日期、销售金价、克重和收付款保留。</div>${orderEditConflictHTML(entry)}<form id="order-edit-meta-form" data-price-lock-edit="true"><section class="panel"><div class="panel-title"><h2>交付与客户资料</h2><span class="small muted">原单号 ${e(entry.order.paper_number||entry.order.number)}</span></div><div class="grid three">${field('交付日期','date',draft.date,'date',`required min="${e(lock.date)}" max="${e(state.today)}"`)}${field('客户称呼/代号(必填)','customer',draft.customer||'','text','required maxlength="60"')}${field('开单人(必填)','salesperson',draft.salesperson||'','text','required maxlength="30"')}</div><p class="small muted">原锁日期 ${e(lock.date)} · ${e(raw.name)} · ${grams(raw.quantity)}g · 原锁销售金价 ¥${yuan(raw.goldPrice??0)}/克 · 成交 ${orderAmount(entry.order.total,entry.order.rounding_mode)}</p><label>客户单备注<textarea name="note" maxlength="240" rows="2">${e(draft.note||'')}</textarea></label>${orderInternalNoteField(draft.internal_note||'')}</section><section class="panel internal price-lock-edit-costs"><h2>原锁金料与补重</h2>${choice('原锁料费来源','lock_material_source',sourceOptions,material.source)}<p id="lock-edit-material-note" class="note" aria-live="polite"></p><div id="lock-edit-manual-material"><div class="grid two">${moneyField('原锁进货料价(元/克)','lock_material_rate',material.rate??'')}${choice('原锁料费实际付款人','lock_material_payer',[['','请选择'],...teamMemberOptions()],material.payer||'')}</div><label class="check"><input type="checkbox" name="lock_material_verified" ${material.verified?'checked':''}>已核实手填原锁料费和实际付款人。</label></div>${extra?`<div class="lock-edit-extra"><h3>补重金料 ${grams(lock.extraMg)}g</h3><div class="grid two">${moneyField('补重进货料价(元/克)','lock_extra_rate',extra.rate??'')}${choice('补重料费实际付款人','lock_extra_payer',[['','请选择'],...teamMemberOptions()],extra.payer||'')}</div><label class="check"><input type="checkbox" name="lock_extra_verified" ${extra.verified?'checked':''}>已核实补重料费和实际付款人。</label></div>`:''}</section><section class="panel internal price-lock-edit-costs"><h2>交付进货成本</h2><div class="grid three">${choice('进货工费方式','lock_cost_labor_mode',[['total','总工费'],['gram','克工费']],line.costLabor?.mode||'total')}${moneyField('进货克工费(元/克)','lock_cost_labor_rate',line.costLabor?.rate??'')}${moneyField('进货总工费(元)','lock_cost_labor_total',line.costParts?.labor??'')}${choice('进货工费付款人','lock_cost_labor_payer',[['','请选择'],...teamMemberOptions()],line.costPayers?.labor||'')}${moneyField('配件成本(元)','lock_cost_accessories',line.costParts?.accessories??'0')}${moneyField('其他货品成本(元)','lock_cost_other',line.costParts?.other??'0')}${choice('配件及其他成本付款人','lock_cost_payer',[['','请选择'],...teamMemberOptions()],line.payer||'')}</div></section>${feeHTML(draft,{cardPreview:false})}<section class="panel"><h2>更正后成本预览</h2><div id="lock-edit-cost-preview" class="lock-edit-cost-preview" aria-live="polite"></div><p class="small muted">按本页成本预估,保存或复核同意后按原账更新利润。</p></section>${orderEditReviewHTML(entry)}</form>`;
|
||||
return `<div class="note" id="order-edit-save-intro">更正交付日期与实际成本,原锁日期、销售金价、克重和收付款保留。</div>${orderEditConflictHTML(entry)}<form id="order-edit-meta-form" data-price-lock-edit="true"><section class="panel"><div class="panel-title"><h2>交付与客户资料</h2><span class="small muted">原单号 ${e(entry.order.paper_number||entry.order.number)}</span></div><div class="grid three">${field('交付日期','date',draft.date,'date',`required min="${e(lock.date)}" max="${e(state.today)}"`)}${field('客户称呼/代号(必填)','customer',draft.customer||'','text','required maxlength="60"')}${field('开单人(必填)','salesperson',draft.salesperson||'','text','required maxlength="30"')}</div><p class="small muted">原锁日期 ${e(lock.date)} · ${e(raw.name)} · ${grams(raw.quantity)}g · 原锁销售金价 ¥${yuan(raw.goldPrice??0)}/克 · 成交 ${orderAmount(entry.order.total,entry.order.rounding_mode)}</p><label>客户单备注<textarea name="note" maxlength="240" rows="2">${e(draft.note||'')}</textarea></label>${orderInternalNoteField(draft.internal_note||'')}</section><section class="panel internal price-lock-edit-costs"><h2>原锁金料与补重</h2>${choice('原锁料费来源','lock_material_source',sourceOptions,material.source)}<p id="lock-edit-material-note" class="note" aria-live="polite"></p><div id="lock-edit-manual-material"><div class="grid two">${moneyField('原锁进货料价(元/克)','lock_material_rate',material.rate??'')}${choice('原锁料费实际付款人','lock_material_payer',[['','请选择'],...teamMemberOptions()],material.payer||'')}</div><label class="check"><input type="checkbox" name="lock_material_verified" ${material.verified?'checked':''}>已核实手填原锁料费和实际付款人。</label></div>${extra?`<div class="lock-edit-extra"><h3>补重金料 ${grams(lock.extraMg)}g</h3>${raw.priceLockExtraPool?choice('补重料费来源','lock_extra_source',[['pool','保留交付料池'],['manual','改为手填补重料价']],extra.source):''}<div class="grid two">${moneyField('补重进货料价(元/克)','lock_extra_rate',extra.rate??'')}${choice('补重料费实际付款人','lock_extra_payer',[['','请选择'],...teamMemberOptions()],extra.payer||'')}</div><label class="check"><input type="checkbox" name="lock_extra_verified" ${extra.verified?'checked':''}>已核实补重料费和实际付款人。</label></div>`:''}</section><section class="panel internal price-lock-edit-costs"><h2>交付进货成本</h2><div class="grid three">${choice('进货工费方式','lock_cost_labor_mode',[['total','总工费'],['gram','克工费']],line.costLabor?.mode||'total')}${moneyField('进货克工费(元/克)','lock_cost_labor_rate',line.costLabor?.rate??'')}${moneyField('进货总工费(元)','lock_cost_labor_total',line.costParts?.labor??'')}${choice('进货工费付款人','lock_cost_labor_payer',[['','请选择'],...teamMemberOptions()],line.costPayers?.labor||'')}${moneyField('配件成本(元)','lock_cost_accessories',line.costParts?.accessories??'0')}${moneyField('其他货品成本(元)','lock_cost_other',line.costParts?.other??'0')}${choice('配件及其他成本付款人','lock_cost_payer',[['','请选择'],...teamMemberOptions()],line.payer||'')}</div></section>${feeHTML(draft,{cardPreview:false})}<section class="panel"><h2>更正后成本预览</h2><div id="lock-edit-cost-preview" class="lock-edit-cost-preview" aria-live="polite"></div><p class="small muted">按本页成本预估,保存或复核同意后按原账更新利润。</p></section>${orderEditReviewHTML(entry)}</form>`;
|
||||
}
|
||||
function priceLockEditGramCost(mg,rate){return LedgerCalc.purchaseCosts({unit:'g',quantity:grams(mg),costParts:{material:'0',labor:'0',accessories:'0',other:'0'},costMaterial:{mode:'gram',rate},costLabor:{mode:'total'}}).parts.material;}
|
||||
function priceLockOrderEditPreview(input,entry=orderEditEntry){
|
||||
@@ -153,12 +153,13 @@ function priceLockOrderEditPreview(input,entry=orderEditEntry){
|
||||
const costs={material:0,labor:0,accessories:0,other:0,fees:input.fee_items.reduce((sum,fee)=>sum+LedgerCalc.cents(fee.amount,'实际费用'),0)};
|
||||
input.lines.forEach((line,index)=>{const old=entry.originalInputs,meta=priceLockOrderEditMeta(entry,index),singleInput={...input,lines:[line],price_lock_material:priceLockOrderEditMaterial(input,index),price_lock_extra_material:priceLockOrderEditExtra(input,index),fee_items:[]},singleEntry={...entry,originalInputs:{...old,lines:[old.lines[index]],price_lock_material:priceLockOrderEditMaterial(old,index),price_lock_extra_material:priceLockOrderEditExtra(old,index)},priceLock:{...entry.priceLock,...meta},order:{...entry.order,lines:[entry.order.lines[index]]}};const value=priceLockOrderEditPreview(singleInput,singleEntry);for(const key of ['material','labor','accessories','other'])costs[key]+=value[key];});costs.total=Object.values(costs).reduce((sum,value)=>sum+value,0);costs.profit=entry.order.total-costs.total;return costs;
|
||||
}
|
||||
const original=entry.originalInputs,line=input.lines[0],extraMg=entry.priceLock.extraMg,usedMg=entry.order.lines[0].quantity-extraMg,oldExtra=extraMg?priceLockEditGramCost(extraMg,original.price_lock_extra_material.rate):0;
|
||||
const originalMaterial=input.price_lock_material.source==='pool'?LedgerCalc.cents(original.lines[0].costParts.material,'原料费')-oldExtra:priceLockEditGramCost(usedMg,input.price_lock_material.rate),extra=extraMg?priceLockEditGramCost(extraMg,input.price_lock_extra_material.rate):0;
|
||||
const original=entry.originalInputs,line=input.lines[0],extraMg=entry.priceLock.extraMg,usedMg=entry.order.lines[0].quantity-extraMg,oldExtra=extraMg?(original.price_lock_extra_material.source==='pool'?original.price_lock_extra_material.amount:priceLockEditGramCost(extraMg,original.price_lock_extra_material.rate)):0;
|
||||
const originalMaterial=input.price_lock_material.source==='pool'?LedgerCalc.cents(original.lines[0].costParts.material,'原料费')-oldExtra:priceLockEditGramCost(usedMg,input.price_lock_material.rate),extra=extraMg?(input.price_lock_extra_material.source==='pool'?original.price_lock_extra_material.amount:priceLockEditGramCost(extraMg,input.price_lock_extra_material.rate)):0;
|
||||
if(!Number.isSafeInteger(originalMaterial)||originalMaterial<0||!Number.isSafeInteger(extra))throw new Error('原锁料费尚未完整,请核对原料价与补重料价。');
|
||||
const costs={material:originalMaterial+extra,labor:LedgerCalc.cents(line.costParts.labor,'进货工费'),accessories:LedgerCalc.cents(line.costParts.accessories,'配件成本'),other:LedgerCalc.cents(line.costParts.other,'其他货品成本'),fees:input.fee_items.reduce((total,fee)=>total+LedgerCalc.cents(fee.amount,'实际费用'),0)};costs.total=Object.values(costs).reduce((total,amount)=>total+amount,0);costs.profit=entry.order.total-costs.total;return costs;
|
||||
}
|
||||
function syncMultiPriceLockOrderEdit(changed='',target=null){
|
||||
syncLockExtraEditControls(orderEditForm());
|
||||
const entry=orderEditEntry,form=orderEditForm(),roots=[...form.querySelectorAll('[data-lock-edit-line]')];
|
||||
roots.forEach((root,index)=>{
|
||||
const meta=priceLockOrderEditMeta(entry,index),get=name=>root.querySelector('[name="'+name+'"]'),manual=get('lock_material_source').value==='manual',affected=!target||target.closest('[data-lock-edit-line]')===root;
|
||||
@@ -175,6 +176,7 @@ function syncMultiPriceLockOrderEdit(changed='',target=null){
|
||||
updateOrderEditApprovalMode();
|
||||
}
|
||||
function syncPriceLockOrderEdit(changed='',target=null){
|
||||
syncLockExtraEditControls(orderEditForm());
|
||||
if(priceLockOrderEditable()&&orderEditEntry.inputs.lines.length>1)return syncMultiPriceLockOrderEdit(changed,target);
|
||||
if(!priceLockOrderEditable())return;const form=orderEditForm();if(!form||form.dataset.priceLockEdit!=='true')return;
|
||||
const get=name=>form.querySelector('[name="'+name+'"]'),source=get('lock_material_source')?.value||orderEditEntry.inputs.price_lock_material.source,manual=source==='manual';
|
||||
@@ -322,3 +324,7 @@ function rememberOrderEditChange(event){
|
||||
}
|
||||
document.addEventListener('input',rememberOrderEditChange);
|
||||
document.addEventListener('change',rememberOrderEditChange);
|
||||
|
||||
function syncLockExtraEditControls(form){
|
||||
for(const select of form?.querySelectorAll('[name="lock_extra_source"]')||[]){const area=select.closest('.lock-edit-extra'),pooled=select.value==='pool';for(const name of ['lock_extra_rate','lock_extra_payer','lock_extra_verified']){const control=area.querySelector('[name="'+name+'"]');if(control){control.disabled=pooled;control.closest('label').hidden=pooled;}}let note=area.querySelector('[data-extra-pool-note]');if(!note){note=document.createElement('p');note.dataset.extraPoolNote='true';note.className='note';area.append(note);}note.hidden=!pooled;note.textContent='沿用交付料池的成本和付款来源,不重复登记付款;更改交付日期时按对应日期料池重新核算。';}
|
||||
}
|
||||
@@ -95,6 +95,7 @@ function syncPriceLockMaterial(form,row=form,lineIndex=0){
|
||||
}
|
||||
|
||||
async function loadPriceLockPoolChoices(force=false){
|
||||
if($('#price-lock-delivery-form')){materialQuoteEntry=null;++materialQuoteRequest;syncPriceLockDelivery();return;}
|
||||
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;
|
||||
@@ -146,9 +147,25 @@ function priceLockItemsHTML(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(pocketLabel(delivery.inventory.pocket)):delivery.pocket?'<br>货盘 '+e(pocketLabel(delivery.pocket)):''}`:'详见销售单'}</td>`:''}</tr>`;}).join('')}</tbody></table></div>`;
|
||||
}
|
||||
function priceLockDeliveryRows(form){return [...(form?.querySelectorAll('[data-price-lock-delivery-item]')||[])];}
|
||||
function materialLockExtraQuoteInput(form=$('#price-lock-delivery-form')){
|
||||
const date=lockFormValue(form,'date'),locks=priceLockLines(currentPriceLock),entries=[];
|
||||
priceLockDeliveryRows(form).forEach((root,lineIndex)=>{if(lockFormValue(root,'extra_source')!=='pool')return;const mg=materialPoolMg(root.querySelector('.line-item [name="quantity"]')?.value);const extra=mg?mg-locks[lineIndex].locked_mg:0;if(extra>0)entries.push({lineIndex,poolId:date,mg:extra});});
|
||||
return {date,member:currentPriceLock?.member||materialFormMember(form),entries};
|
||||
}
|
||||
function priceLockExtraPreview(form,index){
|
||||
const input=materialLockExtraQuoteInput(form);if(input.date!==state.today)throw new Error('补重使用当日料池,请选择今天的交付日期。');
|
||||
const quote=materialQuoteFor(form,input,'lockExtra');if(!quote.result)throw new Error(quote.error||'正在读取交付当日料池…');
|
||||
const entry=quote.result.entries.find(row=>row.lineIndex===index),pool=quote.result.pools.find(row=>row.poolId===input.date);
|
||||
if(!entry||!pool||entry.amount===null)throw new Error('当日料池不足或成本待补,请核实购料。');return {...entry,revision:pool.revision};
|
||||
}
|
||||
function priceLockDeliveryRowCost(item,quantity,extra,index,form){
|
||||
if(extra?.source!=='pool'||lockQuantityMg(quantity)<=item.locked_mg)return priceLockDeliveryCost(item,quantity,extra?.rate);
|
||||
const preview=priceLockExtraPreview(form,index),costs=priceLockDeliveryCost(item,quantity,'1');
|
||||
costs.extraCost=preview.amount;costs.materialCost=costs.originalUsedCost+preview.amount;costs.extraPool=preview;return costs;
|
||||
}
|
||||
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 data-lock-count-source hidden>${choice('成品来源','count_source',[['stocked','已在货盘'],['receive','本次新入库']],draft.inventory?.countSource||'stocked')}<p class="small muted">只确认本次交付成品的实际对数。选本次新入库时,对数先入库一次再销售出库;原锁及补重金料的克重另行核对。</p></div><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>`;
|
||||
return `<div class="internal lock-line-inventory"><h3>本件金料与库存确认</h3><div data-lock-count-source hidden>${choice('成品来源','count_source',[['stocked','已在货盘'],['receive','本次新入库']],draft.inventory?.countSource||'stocked')}<p class="small muted">只确认本次交付成品的实际对数。选本次新入库时,对数先入库一次再销售出库;原锁及补重金料的克重另行核对。</p></div><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>${choice('补重料费来源','extra_source',[['manual','手动填写料价'],['pool','交付当日加权料池']],draft.extraMaterial?.source||'manual')}<div data-lock-extra-pool class="note" hidden></div>${button('刷新补重料池','reload-price-lock-pool','quiet')}<div data-lock-extra-manual 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>${(lock.cancellationReturns||[]).map(row=>`<p>商品 ${row.line_index+1} · ${e(row.date)} 按原成本回池:<strong>${grams(row.mg)}g / ¥${yuan(row.amount)}</strong>,参与回池当天加权;原料池日期 ${e(row.origin_pool_id)}。</p>`).join('')}</div>`:'';
|
||||
@@ -224,7 +241,7 @@ async function renderPriceLockDelivery(id){
|
||||
|
||||
function collectPriceLockDelivery(){
|
||||
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'),...(pocketCountsEnabled(row.querySelector('[name="pocket"]').value)?{countSource:get('count_source')}: {})}};});
|
||||
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:{source:get('extra_source')||'manual',...(get('extra_source')==='pool'?{poolId:lockFormValue(form,'date'),revision:materialQuoteEntry?.result?.pools?.find(p=>p.poolId===lockFormValue(form,'date'))?.revision}:{}),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_source')==='pool'?'stocked':get('extra_stock'),...(pocketCountsEnabled(row.querySelector('[name="pocket"]').value)?{countSource:get('count_source')}: {})}};});
|
||||
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}))};
|
||||
@@ -238,21 +255,26 @@ function syncPriceLockDelivery(){
|
||||
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);
|
||||
const extraPooled=extra&&value('extra_source')==='pool',extraNote=root.querySelector('[data-lock-extra-pool]');
|
||||
const manual=root.querySelector('[data-lock-extra-manual]');if(manual)manual.hidden=extraPooled;
|
||||
for(const name of ['extra_rate','extra_payer','extra_stock','extra_verified']){const input=root.querySelector('[name="'+name+'"]');if(input){input.disabled=!extra||extraPooled;input.required=extra&&!extraPooled;if(name==='extra_verified')input.closest('label').hidden=extraPooled;}}
|
||||
if(extraNote){extraNote.hidden=!extraPooled;if(extraPooled){try{const preview=priceLockExtraPreview(form,index);extraNote.innerHTML='<strong>'+e(materialSourceSegmentsText(preview.materialSources))+'</strong><br>'+priceLockAllocationHTML(preview.allocations)+'<br>只耗用补重金料,不再登记购料付款;当天补料跟随加权,跨天固定。';}catch(error){extraNote.textContent=error.message;}}}
|
||||
try{costs=priceLockDeliveryRowCost(item,get('quantity').value,{source:extraPooled?'pool':'manual',rate:value('extra_rate')},index,form);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(costs?.extraPool)formula.textContent='原锁耗用 '+grams(costs.originalUsedMg)+'g,料费 ¥'+yuan(costs.originalUsedCost)+';补重 '+materialSourceSegmentsText(costs.extraPool.materialSources)+';合计 ¥'+yuan(costs.materialCost);
|
||||
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,countSource=root.querySelector('[data-lock-count-source]'),countControl=root.querySelector('[name="count_source"]');if(countSource){countSource.hidden=!pocketCountsEnabled(pocket);if(countControl){countControl.disabled=!pocketCountsEnabled(pocket);countControl.required=pocketCountsEnabled(pocket);}}
|
||||
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'?'补重金料此前已入库;':'请选择补重金料是否已入库;'):''}从「${pocketLabel(pocket)}」出库 ${grams(costs.finalMg)}g${pocketCountsEnabled(pocket)?' / '+stockCountText(Number(get('stockCount')?.value)||null):''}。${costs.leftoverMg?poolMode?'少重 '+grams(costs.leftoverMg)+'g 解除预留回到料池,实物留在货盘,不重复入库或扣料。':'余料 '+grams(costs.leftoverMg)+'g 留在该货盘,按原进货价计成本,不重复入库。':''}`:'选择本件实际货盘和金料入库情况后,显示库存动作。';
|
||||
priceLockPart(root,'stock-note').textContent=costs&&original&&pocket?`${poolMode?'原锁金料已在料池预留,不重复入库;':original==='receive'?'原锁 '+grams(item.locked_mg)+'g 先入库;':'原锁金料此前已入库;'}${costs.extraMg?(extraPooled?'补重从交付当日料池耗用,不重复入库;':value('extra_stock')==='receive'?'补重 '+grams(costs.extraMg)+'g 先入库;':value('extra_stock')==='stocked'?'补重金料此前已入库;':'请选择补重金料是否已入库;'):''}从「${pocketLabel(pocket)}」出库 ${grams(costs.finalMg)}g${pocketCountsEnabled(pocket)?' / '+stockCountText(Number(get('stockCount')?.value)||null):''}。${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='请逐件补齐最终克重和补重料价,再核对整单交付汇总。';}
|
||||
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(lines.map(line=>LedgerCalc.sale(line).sale),LedgerCalc.cents(d.discount),'yuan');difference=total.total-lock.netReceived;
|
||||
@@ -299,9 +321,9 @@ async function submitPriceLockForm(form){
|
||||
}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 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);});
|
||||
const costs=items.map((line,index)=>{const item=locks[index];if(data.lines&&line.lineId!==item.id)throw new Error('交付商品与原锁记录不一致,请重新读取。');return priceLockDeliveryRowCost(item,line.quantity,line.extraMaterial,index,form);});
|
||||
validateIssueDraft({lines:items,fee_items:data.fee_items,discount:data.discount,rounding_mode:'yuan'},{requireIdentity:false});
|
||||
items.forEach((line,index)=>{if(pocketCountsEnabled(line.inventory.pocket)&&!['stocked','receive'].includes(line.inventory.countSource))throw new Error('请选择商品 '+(index+1)+' 的成品来源。');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} 的补重料价、付款人、是否已入库,并确认实际付款。`);});
|
||||
items.forEach((line,index)=>{if(pocketCountsEnabled(line.inventory.pocket)&&!['stocked','receive'].includes(line.inventory.countSource))throw new Error('请选择商品 '+(index+1)+' 的成品来源。');if(!state.pockets.includes(line.inventory.pocket)||!['receive','stocked'].includes(line.inventory.original))throw new Error(`请选择商品 ${index+1} 的实际出库货盘,并确认原锁金料是否已入库。`);if(costs[index].extraMg&&line.extraMaterial?.source!=='pool'&&(!['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,...(pocketCountsEnabled(line.inventory?.pocket||line.pocket)?{stockCount:stockCountValue(line.stockCount)}:{}),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,...(pocketCountsEnabled(line.inventory.pocket)?{countSource:line.inventory.countSource}:{}),...(costs[index].extraMg?{extra:line.inventory.extra}:{})},...(costs[index].extraMg?{extraMaterial:line.extraMaterial}:{})}));
|
||||
|
||||
Reference in new issue
Block a user