取消已用回收单时将关联用料转入公共料池

This commit is contained in:
summer committed 2026-11-05 00:04:01 +08:00
1 parent 19b1b0263c
commit dec01a3dca
18 files changed
+380 -56

No files matched your search

+7 -4
View File
@@ -14,7 +14,9 @@ function lockFormValue(form,name){return form.querySelector(`[name="${name}"]`)?
function lockCharges(root){return [...root.querySelectorAll('.charge-row')].map(row=>{const value=name=>row.querySelector(`[name="${name}"]`).value,type=value('chargeType'),customName=value('chargeName');return {id:row.dataset.chargeId,nameType:type,customName,name:type==='其他'?customName:type,amount:value('chargeAmount'),chargePrices:JSON.parse(row.dataset.chargePrices)};});}
function syncLockChargeFields(root){for(const row of root.querySelectorAll('.charge-row')){const custom=row.querySelector('[name="chargeType"]').value==='其他',input=row.querySelector('[name="chargeName"]');input.closest('label').hidden=!custom;input.disabled=!custom;input.required=custom;}}
const priceLockUsesPool=lock=>lock?.material_source==='pool';
function priceLockMaterialAllocations(lock){return priceLockUsesPool(lock)?lock.materialPool?.allocations||[]:[{payer:lock.buy_payer,amount:lock.material_amount}];}
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){
@@ -104,8 +106,9 @@ function priceLockCardFeesHTML(lock){
}
function priceLockDialog(){let dialog=$('#price-lock-dialog');if(!dialog){dialog=document.createElement('dialog');dialog.id='price-lock-dialog';document.body.append(dialog);}return dialog;}
function priceLockFacts(lock){
const pool=priceLockUsesPool(lock),material=lock.materialPool;
return `<div class="grid three price-lock-facts"><div>锁价日期<strong>${e(lock.date)}</strong></div><div>原锁克重<strong>${grams(lock.locked_mg)}g</strong></div><div>锁定销售金价<strong>¥${yuan(lock.sell_rate)}/克</strong></div><div>${lock.status==='delivered'?'锁价及交付阶段净收款':'客户实际已付净额'}<strong>¥${yuan(lock.netReceived)}</strong>${lock.status==='delivered'?'<small>后续收退款请查看销售单。</small>':''}</div><div>原锁料费 · ${pool?'当日加权料池':'手动独立购料'}<strong>¥${yuan(lock.material_amount)}</strong><small>${pool?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>`:''}</div><div>状态<strong>${lock.status==='pending'?'待交付,不计利润':'已交付'}</strong></div></div>`+priceLockCardFeesHTML(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);
}
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,7 +141,7 @@ async function renderPriceLocks(){
const request=++priceLockRequest,user=state.user.id;
$('#main').innerHTML=heading('PENDING DELIVERY','待交付','显示所有日期的锁价待交付记录。锁价时只记实际收付,交付后才计销售、成本和利润。',button('新增锁价','new-price-lock','primary')+button('刷新','refresh-price-locks'))+'<section class="panel"><div id="price-lock-list" aria-live="polite">正在读取待交付记录…</div></section>';
try{const result=await api('/api/price-locks?status=pending');if(request!==priceLockRequest||tab!=='price-locks'||state.user.id!==user||!$('#price-lock-list'))return;if(!Array.isArray(result.rows))throw new Error('待交付记录未完整返回,请重试。');
$('#price-lock-list').innerHTML=result.rows.length?`<div class="table-wrap"><table class="price-lock-list"><thead><tr><th>锁价日期/客户</th><th>黄金商品</th><th class="number">锁定克重</th><th class="number">销售金价</th><th class="number">已收净额</th><th>原料来源/成本</th><th>操作</th></tr></thead><tbody>${result.rows.map(lock=>`<tr><td>${e(lock.date)}<br>${e(lock.customer)}</td><td>${e(lock.line?.name||lock.product||'黄金')}</td><td class="number">${grams(lock.locked_mg)}g</td><td class="number">¥${yuan(lock.sell_rate)}/克</td><td class="number">¥${yuan(lock.netReceived)}</td><td><strong>${priceLockUsesPool(lock)?'当日加权料池':'手动独立购料'}</strong><br>¥${yuan(lock.material_amount)}<div class="small muted">${e(priceLockAllocationText(priceLockMaterialAllocations(lock)))}</div></td><td><div class="actions">${button('查看','open-price-lock','',`data-id="${e(lock.id)}"`)}${button('交付','deliver-price-lock','primary',`data-id="${e(lock.id)}"`)}</div></td></tr>`).join('')}</tbody></table></div>`:'<div class="empty"><strong>目前没有锁价待交付记录</strong>已交付记录会进入订单列表。</div>';
$('#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>';
}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){
+6 -5
View File
@@ -18,9 +18,10 @@ function recoveryDetailChangeActionsHTML(value){
return (info.permissions.canEdit?button('修改','recovery-edit-open','',`data-id="${e(value.id)}"`):'')+(info.permissions.canCancel?button('取消这笔记录','recovery-edit-cancel','','data-id="'+e(value.id)+'"'):'');
}
function recoveryMaterialBatchHTML(batch){return batch?`<div class="note"><strong>${e(teamMemberName(batch.member))}个人回收专用料</strong><p class="small">原回收 ${grams(batch.mg)}g · 已用/锁价预留 ${grams(batch.usedMg)}g · 剩余 ${grams(batch.remainingMg)}g。仅供本人所属订单先用,已有占用须先核对关联订单或锁价。</p></div>`:'';}
function recoveryBlockedHTML(rows){return rows.length?`<div class="note"><strong>关联金料已有用料</strong><ul>${rows.map(row=>`<li>${row.anonymous?'其他成员用料':e(row.number||'关联用料')} · ${Number.isSafeInteger(row.mg)?grams(row.mg)+'g':'克重待核对'}${!row.anonymous&&row.priceLockId?' '+button('查看锁价单','recovery-change-open-lock','link-button',`data-id="${e(row.priceLockId)}"`):!row.anonymous&&row.orderId?' '+button('查看订单','recovery-change-open-order','link-button',`data-id="${e(row.orderId)}"`):''}</li>`).join('')}</ul><p class="small">不能取消,不能移走或减少到低于已用量。</p></div>`:'';}
function recoveryCancellationMaterialHTML(){return '<div class="note"><strong>取消后的关联用料</strong><p class="small">取消生效时,关联订单和锁价预留的用料会自动重新分配,公共料按可用量补足,并重算料费、利润和待结金额。公共料不足仍可取消,缺料的关联单显示“料费待补”,补足购料后自动核算。</p></div>';}
function recoveryBlockedHTML(rows,editing=true){return rows.length?`<div class="note"><strong>关联金料已用/锁价预留</strong><ul>${rows.map(row=>`<li>${row.anonymous?'其他成员用料':e(row.number||'关联用料')} · ${Number.isSafeInteger(row.mg)?grams(row.mg)+'g':'克重待核对'}${!row.anonymous&&row.priceLockId?' '+button('查看锁价单','recovery-change-open-lock','link-button',`data-id="${e(row.priceLockId)}"`):!row.anonymous&&row.orderId?' '+button('查看订单','recovery-change-open-order','link-button',`data-id="${e(row.orderId)}"`):''}</li>`).join('')}</ul>${editing?'<p class="small">修改时不能更换金料日期,也不能将金料减至低于已用/预留量。</p>':''}</div>`:'';}
function recoveryEditPanelHTML(data){
return `${data.status==='cancelled'?'<div class="note">本单已取消,原记录和更正历史保留。</div>':''}${data.permissions.reason?`<p class="small muted">${e(data.permissions.reason)}</p>`:''}${recoveryMaterialBatchHTML(data.record.materialBatch)}${recoveryBlockedHTML(data.blockedUsages)}${data.pending?`<section class="panel recovery-change-pending"><h3>待麦麦复核</h3><p class="small muted">原记录仍生效,申请尚未记账。</p>${recoveryChangeComparisonHTML(data.pending)}${button(state.user.role==='owner'?'查看并复核':'查看申请','recovery-change-open','',`data-id="${e(data.pending.id)}"`)}</section>`:''}${data.history.length?`<details><summary>更正与取消记录(${data.history.length})</summary><ul class="timeline">${data.history.map(row=>`<li>${e(recoveryChangeStatus(row))} · ${e(row.requesterName||'未提供')}${row.reviewerName?' · '+e(row.reviewerName)+'复核':''}${row.note?'<p>'+e(row.note)+'</p>':''}${button('查看前后内容','recovery-change-open','quiet',`data-id="${e(row.id)}"`)}</li>`).join('')}</ul></details>`:''}`;
return `${data.status==='cancelled'?'<div class="note">本单已取消,原记录和更正历史保留。</div>':''}${data.permissions.reason?`<p class="small muted">${e(data.permissions.reason)}</p>`:''}${recoveryMaterialBatchHTML(data.record.materialBatch)}${recoveryBlockedHTML(data.blockedUsages)}${data.permissions.canCancel&&data.blockedUsages.length?recoveryCancellationMaterialHTML():''}${data.pending?`<section class="panel recovery-change-pending"><h3>待麦麦复核</h3><p class="small muted">原记录仍生效,申请尚未记账。</p>${recoveryChangeComparisonHTML(data.pending)}${button(state.user.role==='owner'?'查看并复核':'查看申请','recovery-change-open','',`data-id="${e(data.pending.id)}"`)}</section>`:''}${data.history.length?`<details><summary>更正与取消记录(${data.history.length})</summary><ul class="timeline">${data.history.map(row=>`<li>${e(recoveryChangeStatus(row))} · ${e(row.requesterName||'未提供')}${row.reviewerName?' · '+e(row.reviewerName)+'复核':''}${row.note?'<p>'+e(row.note)+'</p>':''}${button('查看前后内容','recovery-change-open','quiet',`data-id="${e(row.id)}"`)}</li>`).join('')}</ul></details>`:''}`;
}
function recoveryEditDraft(input){
const first=input.old_lines[0],x=input.exchange||{},charge=x.charges?.[0],fee=x.fee_items?.[0],account=input.payment_account||'',recipient=account.startsWith('麦麦')?'麦麦':account.startsWith('助理2')?'助理2':'助理',method=account.replace(/^(麦麦|助理2|助理1|助理)/,'');
@@ -74,7 +75,7 @@ function recoveryChangeComparisonHTML(raw){
let rows=pair('业务日期',before.date,after?.date||'取消原记录')+pair('客户',before.customer,after?.customer)+pair('开单人',before.salesperson,after?.salesperson)+pair('归属',teamMemberName(before.member),after?teamMemberName(after.member):'沿用原身份留档')+pair('旧料逐项称重',old(before),after?old(after):'冲正原库存及关联购料')+pair('回收单价(元/克)',before.buy_rate,after?.buy_rate)+pair('回收结算额(元)',before.buy_total,after?.buy_total)+pair('实际收付款账户',accountDisplayName(before.payment_account),after?accountDisplayName(after.payment_account):'冲正原收付记录')+pair('付款人',teamMemberName(before.payer),after?teamMemberName(after.payer):'原付款流水保留')+pair('备注',before.note,after?.note);
if(before.mode==='exchange')rows+=pair('置换新货',x.name,y.name)+pair('新货克重(g)',x.quantity,y.quantity)+pair('实际货盘',x.pocket,y.pocket)+pair('销售金价(元/克)',x.gold_price,y.gold_price)+pair('销售工费',x.labor_rate+'元/'+(x.labor_mode==='gram'?'克':'总额'),after?y.labor_rate+'元/'+(y.labor_mode==='gram'?'克':'总额'):'取消')+pair('折旧计费克重/单价',x.depreciation_weight+'g × '+x.depreciation_rate+'元/克',after?y.depreciation_weight+'g × '+y.depreciation_rate+'元/克':'取消')+pair('附加收费',charges(before),after?charges(after):'取消')+pair('优惠(元)',x.discount,y.discount)+pair('取整方式',x.rounding_mode==='yuan'?'四舍五入到元':'保留到分',after?(y.rounding_mode==='yuan'?'四舍五入到元':'保留到分'):'取消')+pair('补金差重进货来源',material(x.cost_material),after?material(y.cost_material):'释放原耗用')+pair('料费付款人',teamMemberName(x.cost_material_payer),after?teamMemberName(y.cost_material_payer):'原来源留档')+pair('进货工费',labor(x.cost_labor),after?labor(y.cost_labor):'取消')+pair('工费付款人',teamMemberName(x.cost_labor_payer),after?teamMemberName(y.cost_labor_payer):'原来源留档')+pair('实际费用',fees(before),after?fees(after):'冲正原费用');
const a=request.summary.before||{},b=request.summary.after||{};rows+=[['实际收客户','cashReceipt'],['实际付客户','cashPayment'],['购料成本','purchaseAmount'],['订单货品成本','goodsCost'],['实际费用','directCost'],['原账利润','profit']].map(([title,key])=>pair(title,a[key]==null?'待核实':'¥'+yuan(a[key]),after?(b[key]==null?'待核实':'¥'+yuan(b[key])):'取消后冲正')).join('');
return `<div class="table-wrap recovery-change-comparison"><table class="order-change-table" aria-label="回收更正原值与申请值"><thead><tr><th>核对项目</th><th>原值</th><th>${request.action==='cancel'?'取消后':'申请值'}</th></tr></thead><tbody>${rows}</tbody></table></div>`;
return `<div class="table-wrap recovery-change-comparison"><table class="order-change-table" aria-label="回收更正原值与申请值"><thead><tr><th>核对项目</th><th>原值</th><th>${request.action==='cancel'?'取消后':'申请值'}</th></tr></thead><tbody>${rows}</tbody></table></div>${request.action==='cancel'?recoveryBlockedHTML(request.summary.blockedUsages||[],false)+recoveryCancellationMaterialHTML():''}`;
}
function recoveryChangesEntryHTML(){return button(state.user.role==='owner'?'回收更正复核(…)':'回收更正申请(…)','recovery-changes-open','','id="recovery-changes-entry"');}
async function loadRecoveryChangeCount(){const node=$('#recovery-changes-entry');if(!node)return;const user=recoveryChangeUser(),title=state.user.role==='owner'?'回收更正复核':'回收更正申请';try{const data=await api('/api/recovery-changes?status=pending');if(!Number.isSafeInteger(data.counts?.pending)||data.counts.pending<0)throw new Error('数量未完整返回');if(node===$('#recovery-changes-entry')&&user===recoveryChangeUser())node.textContent=title+'('+data.counts.pending+')';}catch{if(node===$('#recovery-changes-entry')&&user===recoveryChangeUser())node.textContent=title+'(读取失败)';}}
@@ -89,8 +90,8 @@ async function openRecoveryCancel(id){
if(busy||pending())throw new Error('请先恢复未确认的操作。');closeRecoveryDetail();const dialog=recoveryChangesDialog(),request=++recoveryReviewRequest,user=recoveryChangeUser();recoveryReviewEntry=null;
dialog.innerHTML=`${button('关闭','recovery-changes-close','dialog-close','aria-label="关闭取消回收记录"')}<h2 id="recovery-change-title">取消回收/置换记录</h2><p>正在读取…</p>`;if(!dialog.open)dialog.showModal();
try{
const response=await api('/api/recoveries/'+encodeURIComponent(id)+'/edit');if(request!==recoveryReviewRequest||user!==recoveryChangeUser()||!dialog.open)return;const data=validateRecoveryEditDetail(response,id);if(!data.permissions.canCancel||data.pending)throw new Error(data.permissions.reason||'已有用料或待审批申请,当前不能取消。');recoveryReviewEntry={user,data,kind:'cancel',invalid:false};
dialog.innerHTML=`${button('关闭','recovery-changes-close','dialog-close','aria-label="关闭取消回收记录"')}<h2 id="recovery-change-title">取消这笔${e(recoveryModeNames[data.inputs.mode])}记录</h2><p>${e(data.record.number)} · ${e(data.inputs.date)} · ${e(data.inputs.customer)}</p><p class="small muted">取消后冲正整套关联收付款、购料与库存,原身份和更正记录保留。系统不会发起真实退款。</p><form id="recovery-cancel-form"><label>取消原因<textarea name="reason" required maxlength="200" rows="2"></textarea></label><label class="check"><input type="checkbox" name="verified" required>已核实这笔记录需要取消,并核对关联金料与实际收付款。</label><div id="recovery-cancel-error" aria-live="polite"></div><div class="form-actions">${button('返回','recovery-changes-close','quiet')}<button class="primary" type="submit">${data.permissions.requiresApproval?'提交取消申请':'确认取消记录'}</button></div></form>`;
const response=await api('/api/recoveries/'+encodeURIComponent(id)+'/edit');if(request!==recoveryReviewRequest||user!==recoveryChangeUser()||!dialog.open)return;const data=validateRecoveryEditDetail(response,id);if(!data.permissions.canCancel||data.pending)throw new Error(data.permissions.reason||'记录已取消或有待审批申请,当前不能取消。');recoveryReviewEntry={user,data,kind:'cancel',invalid:false};
dialog.innerHTML=`${button('关闭','recovery-changes-close','dialog-close','aria-label="关闭取消回收记录"')}<h2 id="recovery-change-title">取消这笔${e(recoveryModeNames[data.inputs.mode])}记录</h2><p>${e(data.record.number)} · ${e(data.inputs.date)} · ${e(data.inputs.customer)}</p><p class="small muted">取消后冲正整套关联收付款、购料与库存,原身份和更正记录保留。系统不会发起真实退款。</p>${recoveryMaterialBatchHTML(data.record.materialBatch)}${recoveryBlockedHTML(data.blockedUsages,false)}${recoveryCancellationMaterialHTML()}<form id="recovery-cancel-form"><label>取消原因<textarea name="reason" required maxlength="200" rows="2"></textarea></label><label class="check"><input type="checkbox" name="verified" required>已核实这笔记录需要取消,并核对关联用料自动重算与实际收付款。</label><div id="recovery-cancel-error" aria-live="polite"></div><div class="form-actions">${button('返回','recovery-changes-close','quiet')}<button class="primary" type="submit">${data.permissions.requiresApproval?'提交取消申请':'确认取消记录'}</button></div></form>`;
}catch(err){if(request===recoveryReviewRequest&&user===recoveryChangeUser()&&dialog.open)dialog.innerHTML=`${button('关闭','recovery-changes-close','dialog-close')}<h2 id="recovery-change-title">暂不能取消</h2><div class="error">${e(err.message)}</div>${button('重新读取','recovery-edit-cancel','',`data-id="${e(id)}"`)}`;}
}
async function submitRecoveryCancel(form){const entry=recoveryReviewEntry,data=entry?.data;if(!entry||entry.invalid||entry.kind!=='cancel'||entry.user!==recoveryChangeUser()||!data.permissions.canCancel||data.pending)throw new Error('请重新读取回收记录后核对取消。');const reason=recoveryText(form.querySelector('[name="reason"]')?.value);if(!reason||reason.length>200)throw new Error('取消原因请填写1~200字。');if(!form.querySelector('[name="verified"]')?.checked)throw new Error('请核实取消记录及关联账务,并勾选确认。');const input={revision:data.revision,reason,verified:true},url='/api/recoveries/'+encodeURIComponent(data.id)+'/cancel',view=captureRecoveryChangeView();try{const result=await mutate(url,input);await finishRecoveryChangeSave(url,input,result,view);}catch(err){if(view.user===recoveryChangeUser())recoveryChangeError(err,{kind:'cancel',id:data.id});}}