锁价交付补重支持当日料池,内部备注移至客户名旁
This commit is contained in:
1 parent
ac9073471d
commit
c5883351c1
20 files changed
+196
-66
No files matched your search
+2
-2
@@ -317,7 +317,7 @@ class Ledger {
|
|||||||
if(recovery){o.recovery_id=recovery.id;o.recovery_mode='exchange';o.recovery_immutable_reason=Recoveries.IMMUTABLE_REASON;o.nonCashOffset=recovery.offsetAmount;o.cashPaid=recovery.cashPayment;o.netSettlement=recovery.netSettlement;o.balance=o.total-o.netReceived-o.nonCashOffset;}
|
if(recovery){o.recovery_id=recovery.id;o.recovery_mode='exchange';o.recovery_immutable_reason=Recoveries.IMMUTABLE_REASON;o.nonCashOffset=recovery.offsetAmount;o.cashPaid=recovery.cashPayment;o.netSettlement=recovery.netSettlement;o.balance=o.total-o.netReceived-o.nonCashOffset;}
|
||||||
o.rounding_adjustment=o.rounding_mode==='yuan'?o.total-(sum(o.lines,'sale')-o.discount):0;
|
o.rounding_adjustment=o.rounding_mode==='yuan'?o.total-(sum(o.lines,'sale')-o.discount):0;
|
||||||
o.goodsCost=o.lines.some(l=>l.cost===null)?null:sum(o.lines,'cost');o.directCost=sum(o.expenses,'amount');
|
o.goodsCost=o.lines.some(l=>l.cost===null)?null:sum(o.lines,'cost');o.directCost=sum(o.expenses,'amount');
|
||||||
o.materialCostPending=!['returned','cancelled'].includes(o.status)&&o.lines.some(l=>(l.costMaterial?.mode==='pool'||l.priceLockPool)&&l.costParts?.material==null);
|
o.materialCostPending=!['returned','cancelled'].includes(o.status)&&o.lines.some(l=>(l.costMaterial?.mode==='pool'||l.priceLockPool||l.priceLockExtraPool)&&l.costParts?.material==null);
|
||||||
o.knownGoodsCost=sum(o.lines,l=>l.cost??sum(Object.values(l.costParts||{}).map(amount=>({amount:amount??0})),'amount'));
|
o.knownGoodsCost=sum(o.lines,l=>l.cost??sum(Object.values(l.costParts||{}).map(amount=>({amount:amount??0})),'amount'));
|
||||||
o.pendingFees=['draft','confirmed'].includes(o.status)?o.fee_items.filter(f=>f.status!=='recorded'&&(o.status==='draft'||f.status==='estimated')):[];
|
o.pendingFees=['draft','confirmed'].includes(o.status)?o.fee_items.filter(f=>f.status!=='recorded'&&(o.status==='draft'||f.status==='estimated')):[];
|
||||||
o.draftFees=sum(o.pendingFees,f=>f.amount||0);
|
o.draftFees=sum(o.pendingFees,f=>f.amount||0);
|
||||||
@@ -329,7 +329,7 @@ class Ledger {
|
|||||||
const pooled=new Set(LockPools.findAll(this,priceLock.id).map(row=>row.line_index)),manual=LockLines.lines(priceLock).filter(row=>!pooled.has(row.line_index)),sources=[];
|
const pooled=new Set(LockPools.findAll(this,priceLock.id).map(row=>row.line_index)),manual=LockLines.lines(priceLock).filter(row=>!pooled.has(row.line_index)),sources=[];
|
||||||
const leftoverRows=['delivered','returned'].includes(o.status)?manual.filter(row=>row.buy_payer==='assistant').map(row=>LockLines.deliveryAt(priceLock,row.line_index)).filter(Boolean):[],leftover=sum(leftoverRows,'leftover_cost');
|
const leftoverRows=['delivered','returned'].includes(o.status)?manual.filter(row=>row.buy_payer==='assistant').map(row=>LockLines.deliveryAt(priceLock,row.line_index)).filter(Boolean):[],leftover=sum(leftoverRows,'leftover_cost');
|
||||||
if(leftover)sources.push({kind:'leftover',amount:leftover,quantity:sum(leftoverRows,'leftover_mg'),explanation:'助理垫付的剩余金料进入自有货盘,按原采购成本抵扣货款待结'});
|
if(leftover)sources.push({kind:'leftover',amount:leftover,quantity:sum(leftoverRows,'leftover_mg'),explanation:'助理垫付的剩余金料进入自有货盘,按原采购成本抵扣货款待结'});
|
||||||
const returned=o.status==='returned'&&manual.length?Calc.orderCosts({...o,lines:manual.map(row=>o.lines[row.line_index]),status:'delivered'}).byPayer.assistant.goods:0;
|
const returned=o.status==='returned'&&manual.length?sum(Calc.orderCosts({...o,lines:manual.map(row=>o.lines[row.line_index]),status:'delivered'}).rows.filter(row=>row.kind==='goods'&&row.payer==='assistant'&&!row.materialPoolId),'amount'):0;
|
||||||
if(returned)sources.push({kind:'returnedGoods',amount:returned,explanation:'退回自有货盘的商品由助理垫付的货品成本,抵扣货款待结'});
|
if(returned)sources.push({kind:'returnedGoods',amount:returned,explanation:'退回自有货盘的商品由助理垫付的货品成本,抵扣货款待结'});
|
||||||
if(manual.length){o.assistantInventoryCredit=leftover+returned;o.assistantInventoryCreditSources=sources;o.assistantInventoryCreditExplanation=sources.map(source=>source.explanation).join(';');}
|
if(manual.length){o.assistantInventoryCredit=leftover+returned;o.assistantInventoryCreditSources=sources;o.assistantInventoryCreditExplanation=sources.map(source=>source.explanation).join(';');}
|
||||||
}
|
}
|
||||||
|
|||||||
+2
-2
@@ -26,8 +26,8 @@ function lineType(line,pocketLabel=key=>key){
|
|||||||
|
|
||||||
function orderRow(order,pocketLabel){
|
function orderRow(order,pocketLabel){
|
||||||
const draft=order.status==='draft',excluded=['returned','cancelled'].includes(order.status);
|
const draft=order.status==='draft',excluded=['returned','cancelled'].includes(order.status);
|
||||||
const materialPoolIds=[...new Set(order.lines.flatMap(line=>[line.costMaterial?.mode==='pool'?line.costMaterial.poolId:null,line.priceLockPool?.poolId].filter(Boolean)))];
|
const materialPoolIds=[...new Set(order.lines.flatMap(line=>[line.costMaterial?.mode==='pool'?line.costMaterial.poolId:null,line.priceLockPool?.poolId,line.priceLockExtraPool?.poolId].filter(Boolean)))];
|
||||||
const materialCostPending=!draft&&!excluded&&Boolean(order.materialCostPending||order.lines.some(line=>line.materialPool?.status==='pending'||line.materialPool?.amount===null||line.priceLockPool?.status==='pending'||line.priceLockPool?.amount===null));
|
const materialCostPending=!draft&&!excluded&&Boolean(order.materialCostPending||order.lines.some(line=>line.materialPool?.status==='pending'||line.materialPool?.amount===null||line.priceLockPool?.status==='pending'||line.priceLockPool?.amount===null||line.priceLockExtraPool?.amount===null));
|
||||||
const costs=Calc.orderCosts(order);
|
const costs=Calc.orderCosts(order);
|
||||||
const costItems=draft?[]:costs.rows.filter(item=>!item.excluded&&item.kind!=='pending').map(item=>({...item,component:component(item)}));
|
const costItems=draft?[]:costs.rows.filter(item=>!item.excluded&&item.kind!=='pending').map(item=>({...item,component:component(item)}));
|
||||||
const pendingCostItems=draft?[]:costs.rows.filter(item=>item.kind==='pending').map(item=>({...item,component:'fee'}));
|
const pendingCostItems=draft?[]:costs.rows.filter(item=>item.kind==='pending').map(item=>({...item,component:'fee'}));
|
||||||
|
|||||||
@@ -44,7 +44,7 @@ function summary(order){return Object.fromEntries(['total','netReceived','goodsC
|
|||||||
function actionLabel(action,payload){return action==='return'&&payload?.afterSale?'订单售后':ACTION_LABELS[action||'edit'];}
|
function actionLabel(action,payload){return action==='return'&&payload?.afterSale?'订单售后':ACTION_LABELS[action||'edit'];}
|
||||||
function afterSaleModule(){return require('./order-after-sales');}
|
function afterSaleModule(){return require('./order-after-sales');}
|
||||||
function descriptor(order,payload){return {
|
function descriptor(order,payload){return {
|
||||||
pools:[...new Set([...order.lines,...(Array.isArray(payload.lines)?payload.lines:[]),...(Array.isArray(payload.costs)?payload.costs.filter(row=>row&&typeof row==='object'):[])].map(line=>line.costMaterial?.mode==='pool'?line.costMaterial.poolId:line.priceLockPool?.poolId).concat(payload.afterSale?[payload.date]:[]).filter(Boolean))].sort(),
|
pools:[...new Set([...order.lines,...(Array.isArray(payload.lines)?payload.lines:[]),...(Array.isArray(payload.costs)?payload.costs.filter(row=>row&&typeof row==='object'):[])].flatMap(line=>[line.costMaterial?.mode==='pool'?line.costMaterial.poolId:line.priceLockPool?.poolId,line.priceLockExtraPool?.poolId]).concat(payload.afterSale?[payload.date]:[]).filter(Boolean))].sort(),
|
||||||
pockets:[...new Set([...order.lines,...(Array.isArray(payload.lines)?payload.lines:[]),...(Array.isArray(payload.afterSale?.lines)?payload.afterSale.lines:[])].map(line=>line.pocket).concat(Object.values(payload.returnPockets||{})).filter(Boolean))].sort(),
|
pockets:[...new Set([...order.lines,...(Array.isArray(payload.lines)?payload.lines:[]),...(Array.isArray(payload.afterSale?.lines)?payload.afterSale.lines:[])].map(line=>line.pocket).concat(Object.values(payload.returnPockets||{})).filter(Boolean))].sort(),
|
||||||
...(payload.afterSale||order.orderAfterSale||order.lines.some(line=>line.returnedStockId)||(Array.isArray(payload.lines)&&payload.lines.some(line=>line?.returnedStockId))?{orderAfterSale:true}:{}),
|
...(payload.afterSale||order.orderAfterSale||order.lines.some(line=>line.returnedStockId)||(Array.isArray(payload.lines)&&payload.lines.some(line=>line?.returnedStockId))?{orderAfterSale:true}:{}),
|
||||||
...([...order.lines,...(Array.isArray(payload.lines)?payload.lines:[])].some(line=>line?.returnedStockId)?{returnedStockIds:[...new Set([...order.lines,...(Array.isArray(payload.lines)?payload.lines:[])].map(line=>line?.returnedStockId).filter(Boolean))].sort()}:{}),
|
...([...order.lines,...(Array.isArray(payload.lines)?payload.lines:[])].some(line=>line?.returnedStockId)?{returnedStockIds:[...new Set([...order.lines,...(Array.isArray(payload.lines)?payload.lines:[])].map(line=>line?.returnedStockId).filter(Boolean))].sort()}:{}),
|
||||||
|
|||||||
+15
-9
@@ -15,7 +15,7 @@ const same=(a,b)=>JSON.stringify(a)===JSON.stringify(b);
|
|||||||
const CreditCardFees=require('./public/credit-card-fees');
|
const CreditCardFees=require('./public/credit-card-fees');
|
||||||
const CreditCardRates=require('./credit-card-rates');
|
const CreditCardRates=require('./credit-card-rates');
|
||||||
const isCardFee=item=>item?.system==='credit_card'||String(item?.key||'').startsWith('card_fee:');
|
const isCardFee=item=>item?.system==='credit_card'||String(item?.key||'').startsWith('card_fee:');
|
||||||
const COST_FIELDS=['payer','costPayers','costFundings','cost','costParts','costMaterial','costLabor','materialAllocations','priceLockPool','returnedStockId','returnedStock'];
|
const COST_FIELDS=['payer','costPayers','costFundings','cost','costParts','costMaterial','costLabor','materialAllocations','priceLockPool','priceLockExtraPool','returnedStockId','returnedStock'];
|
||||||
const SALE_FIELDS=['name','code','unit','quantity','pocket','stockCount','sale','baseSale','charges','pricingMode','goldPrice','laborRate','laborMode','pieces','priceNote'];
|
const SALE_FIELDS=['name','code','unit','quantity','pocket','stockCount','sale','baseSale','charges','pricingMode','goldPrice','laborRate','laborMode','pieces','priceNote'];
|
||||||
function editFeeCostMode(order,input,env){
|
function editFeeCostMode(order,input,env){
|
||||||
const mode=env.pick(input.fee_cost_mode===undefined?order.fee_cost_mode??'legacy':input.fee_cost_mode,['legacy','checkboxes'],'费用录入方式');
|
const mode=env.pick(input.fee_cost_mode===undefined?order.fee_cost_mode??'legacy':input.fee_cost_mode,['legacy','checkboxes'],'费用录入方式');
|
||||||
@@ -90,7 +90,7 @@ function detail(ledger,id,actor,env){
|
|||||||
const line=inputs.lines[row.line_index],extra=lock.material_events.find(event=>event.source==='extra'&&(event.line_index??0)===row.line_index),delivery=row.delivery??LockLines.deliveryAt(lock,row.line_index);
|
const line=inputs.lines[row.line_index],extra=lock.material_events.find(event=>event.source==='extra'&&(event.line_index??0)===row.line_index),delivery=row.delivery??LockLines.deliveryAt(lock,row.line_index);
|
||||||
line.lineId=row.id;
|
line.lineId=row.id;
|
||||||
line.price_lock_material={source:row.material_source,rate:yuan(row.buy_rate),payer:row.buy_payer,verified:true};
|
line.price_lock_material={source:row.material_source,rate:yuan(row.buy_rate),payer:row.buy_payer,verified:true};
|
||||||
if(delivery?.extra_mg)line.price_lock_extra_material={rate:yuan(extra?.rate),payer:extra?.payer,verified:true};
|
if(delivery?.extra_mg){const pool=order.lines[row.line_index].priceLockExtraPool;line.price_lock_extra_material={...(pool?{source:'pool',amount:pool.amount}:{}),rate:yuan(pool?.averageRate??extra?.rate),payer:pool?.allocations?.[0]?.payer??extra?.payer,verified:true};}
|
||||||
}
|
}
|
||||||
if(inputs.lines.length===1){
|
if(inputs.lines.length===1){
|
||||||
inputs.price_lock_material=inputs.lines[0].price_lock_material;
|
inputs.price_lock_material=inputs.lines[0].price_lock_material;
|
||||||
@@ -219,7 +219,7 @@ function editDeliveredLock(ledger,info,input,metadata,actor,env){
|
|||||||
const rawLine=data.lines[index],originalLine=order.lines[index],delivery=locked.delivery??LockLines.deliveryAt(lock,index);
|
const rawLine=data.lines[index],originalLine=order.lines[index],delivery=locked.delivery??LockLines.deliveryAt(lock,index);
|
||||||
if(!rawLine||typeof rawLine!=='object'||Array.isArray(rawLine)||!delivery)env.fail(unchanged);
|
if(!rawLine||typeof rawLine!=='object'||Array.isArray(rawLine)||!delivery)env.fail(unchanged);
|
||||||
if((lockedRows.length>1||rawLine.lineId!==undefined)&&rawLine.lineId!==locked.id)env.fail('锁价商品来源或顺序已变化,请重新打开订单',409);
|
if((lockedRows.length>1||rawLine.lineId!==undefined)&&rawLine.lineId!==locked.id)env.fail('锁价商品来源或顺序已变化,请重新打开订单',409);
|
||||||
if(rawLine.materialAllocations!==undefined||rawLine.materialPool!==undefined||rawLine.priceLockPool!==undefined)env.fail(unchanged);
|
if(rawLine.materialAllocations!==undefined||rawLine.materialPool!==undefined||rawLine.priceLockPool!==undefined||rawLine.priceLockExtraPool!==undefined)env.fail(unchanged);
|
||||||
const material=materialInput(rawLine,index,'price_lock_material');
|
const material=materialInput(rawLine,index,'price_lock_material');
|
||||||
if(!material||typeof material!=='object'||Array.isArray(material))env.fail('请完整带入每件商品的原锁价料费后再修改');
|
if(!material||typeof material!=='object'||Array.isArray(material))env.fail('请完整带入每件商品的原锁价料费后再修改');
|
||||||
const source=env.pick(material.source,['pool','manual'],'原锁料费来源'),originalSource=locked.material_source;
|
const source=env.pick(material.source,['pool','manual'],'原锁料费来源'),originalSource=locked.material_source;
|
||||||
@@ -230,15 +230,19 @@ function editDeliveredLock(ledger,info,input,metadata,actor,env){
|
|||||||
const materialChanged=source!==originalSource||rate!==locked.buy_rate||payer!==locked.buy_payer;
|
const materialChanged=source!==originalSource||rate!==locked.buy_rate||payer!==locked.buy_payer;
|
||||||
if(materialChanged&&material.verified!==true)env.fail('请确认更正后的原料款和付款人已经核实');
|
if(materialChanged&&material.verified!==true)env.fail('请确认更正后的原料款和付款人已经核实');
|
||||||
const previousExtra=lock.material_events.find(row=>row.source==='extra'&&(row.line_index??0)===index),extra=materialInput(rawLine,index,'price_lock_extra_material');
|
const previousExtra=lock.material_events.find(row=>row.source==='extra'&&(row.line_index??0)===index),extra=materialInput(rawLine,index,'price_lock_extra_material');
|
||||||
|
const extraReservation=LockPools.find(ledger,lock.id,LockPools.extraIndex(index)),extraSource=extra?.source??(extraReservation?'pool':'manual');
|
||||||
|
env.pick(extraSource,['pool','manual'],'补重料费来源');if(extraSource==='pool'&&!extraReservation)env.fail('手填补重不能直接改为料池来源');
|
||||||
let extraRate=null,extraPayer=null;
|
let extraRate=null,extraPayer=null;
|
||||||
if(delivery.extra_mg){
|
if(delivery.extra_mg){
|
||||||
if(!extra||typeof extra!=='object'||Array.isArray(extra))env.fail('请完整带入补重料费和付款人后再修改');
|
if(!extra||typeof extra!=='object'||Array.isArray(extra))env.fail('请完整带入补重料费和付款人后再修改');
|
||||||
extraRate=env.money(extra.rate,'补重进货料价');extraPayer=env.pick(extra.payer,['owner','assistant','assistant2'],'补重料费付款人');
|
extraRate=env.money(extra.rate,'补重进货料价');extraPayer=env.pick(extra.payer,['owner','assistant','assistant2'],'补重料费付款人');
|
||||||
if(extraRate<=0)env.fail('补重进货料价必须大于0');
|
if(extraRate<=0)env.fail('补重进货料价必须大于0');
|
||||||
if((extraRate!==previousExtra?.rate||extraPayer!==previousExtra?.payer)&&extra.verified!==true)env.fail('请确认更正后的补重料款和付款人已经核实');
|
if(extraSource==='pool'&&(extraRate!==extraReservation.snapshot.averageRate||extraPayer!==extraReservation.allocations[0]?.payer))env.fail('补重料池成本由料池维护,手填前请选择独立采购');
|
||||||
|
if(extraSource==='manual'&&(extraRate!==previousExtra?.rate||extraPayer!==previousExtra?.payer)&&extra.verified!==true)env.fail('请确认更正后的补重料款和付款人已经核实');
|
||||||
}else if(extra!==undefined)env.fail('本商品没有补重采购,不能新增补重料费');
|
}else if(extra!==undefined)env.fail('本商品没有补重采购,不能新增补重料费');
|
||||||
const extraChanged=delivery.extra_mg&&(extraRate!==previousExtra?.rate||extraPayer!==previousExtra?.payer);
|
const extraChanged=delivery.extra_mg&&(extraReservation?extraSource!=='pool':extraRate!==previousExtra?.rate||extraPayer!==previousExtra?.payer);
|
||||||
const costs=Calc.priceLockCost({lockedQuantity:(locked.locked_mg/1000).toFixed(3),quantity:(originalLine.quantity/1000).toFixed(3),buyRate:yuan(rate),extraBuyRate:extraRate===null?undefined:yuan(extraRate)});
|
const costs=Calc.priceLockCost({lockedQuantity:(locked.locked_mg/1000).toFixed(3),quantity:(originalLine.quantity/1000).toFixed(3),buyRate:yuan(rate),extraBuyRate:extraRate===null?undefined:yuan(extraRate)});
|
||||||
|
if(extraSource==='pool'){if(extraReservation.amount==null)env.fail('补重料池成本待补,请核实后修改',409);costs.extraCost=extraReservation.amount;costs.materialCost=costs.originalUsedCost+costs.extraCost;}
|
||||||
const reservation=source==='pool'?LockPools.find(ledger,lock.id,index):null,part=reservation?LockPools.split(reservation.snapshot,delivery.original_used_mg):null;
|
const reservation=source==='pool'?LockPools.find(ledger,lock.id,index):null,part=reservation?LockPools.split(reservation.snapshot,delivery.original_used_mg):null;
|
||||||
if(source==='pool'&&(!part||part.amount===null))env.fail('原锁料池成本待补,请先核实料池后再更正交付成本',409);
|
if(source==='pool'&&(!part||part.amount===null))env.fail('原锁料池成本待补,请先核实料池后再更正交付成本',409);
|
||||||
if(part)Object.assign(costs,{originalPurchase:reservation.amount,originalUsedCost:part.amount,leftoverCost:part.leftoverCost,materialCost:part.amount+costs.extraCost});
|
if(part)Object.assign(costs,{originalPurchase:reservation.amount,originalUsedCost:part.amount,leftoverCost:part.leftoverCost,materialCost:part.amount+costs.extraCost});
|
||||||
@@ -250,9 +254,10 @@ function editDeliveredLock(ledger,info,input,metadata,actor,env){
|
|||||||
if(SALE_FIELDS.some(field=>!same(saleValue(line,field),saleValue(originalLine,field))))env.fail(unchanged);
|
if(SALE_FIELDS.some(field=>!same(saleValue(line,field),saleValue(originalLine,field))))env.fail(unchanged);
|
||||||
if(originalLine.lineId!==undefined||lockedRows.length>1)line.lineId=locked.id;
|
if(originalLine.lineId!==undefined||lockedRows.length>1)line.lineId=locked.id;
|
||||||
line.materialAllocations=reservation?LockPools.materialAllocations(reservation.snapshot,delivery.original_used_mg):[{source:'original',quantity:delivery.original_used_mg,rate,amount:costs.originalUsedCost,payer}];
|
line.materialAllocations=reservation?LockPools.materialAllocations(reservation.snapshot,delivery.original_used_mg):[{source:'original',quantity:delivery.original_used_mg,rate,amount:costs.originalUsedCost,payer}];
|
||||||
if(delivery.extra_mg)line.materialAllocations.push({source:'extra',quantity:delivery.extra_mg,rate:extraRate,amount:costs.extraCost,payer:extraPayer});
|
if(extraSource==='pool'){line.priceLockExtraPool={...originalLine.priceLockExtraPool};line.materialAllocations.push(...LockPools.materialAllocations(extraReservation.snapshot,delivery.extra_mg).map(a=>({...a,source:'extra'})));}
|
||||||
|
else if(delivery.extra_mg)line.materialAllocations.push({source:'extra',quantity:delivery.extra_mg,rate:extraRate,amount:costs.extraCost,payer:extraPayer});
|
||||||
if(reservation)line.priceLockPool={...originalLine.priceLockPool};
|
if(reservation)line.priceLockPool={...originalLine.priceLockPool};
|
||||||
return {locked,index,line,delivery,source,originalSource,rate,payer,extraRate,extraPayer,materialChanged,extraChanged,costs,reservation};
|
return {locked,index,line,delivery,source,originalSource,rate,payer,extraRate,extraPayer,materialChanged,extraChanged,costs,reservation,extraSource,extraReservation};
|
||||||
});
|
});
|
||||||
const lines=states.map(row=>row.line);
|
const lines=states.map(row=>row.line);
|
||||||
if(!Array.isArray(data.fee_items))env.fail('请完整带入本单所有实际费用后再修改,不能遗漏额外费用');
|
if(!Array.isArray(data.fee_items))env.fail('请完整带入本单所有实际费用后再修改,不能遗漏额外费用');
|
||||||
@@ -275,7 +280,7 @@ function editDeliveredLock(ledger,info,input,metadata,actor,env){
|
|||||||
storedRows[index]={...storedRows[index],material_source:'manual',buy_rate:rate,buy_payer:payer,material_amount:costs.originalPurchase,line:lockedLine};
|
storedRows[index]={...storedRows[index],material_source:'manual',buy_rate:rate,buy_payer:payer,material_amount:costs.originalPurchase,line:lockedLine};
|
||||||
PriceLocks.reviseMaterial(ledger,lock,'original',{line_index:index,rate,payer,quantity:locked.locked_mg,amount:costs.originalPurchase},actor,env);
|
PriceLocks.reviseMaterial(ledger,lock,'original',{line_index:index,rate,payer,quantity:locked.locked_mg,amount:costs.originalPurchase},actor,env);
|
||||||
}
|
}
|
||||||
if(delivery.extra_mg)PriceLocks.reviseMaterial(ledger,lock,'extra',{line_index:index,rate:extraRate,payer:extraPayer,quantity:delivery.extra_mg,amount:costs.extraCost},actor,env);
|
if(delivery.extra_mg&&state.extraSource!=='pool')PriceLocks.reviseMaterial(ledger,lock,'extra',{line_index:index,rate:extraRate,payer:extraPayer,quantity:delivery.extra_mg,amount:costs.extraCost},actor,env);
|
||||||
}
|
}
|
||||||
if(states.some(row=>row.source==='manual'))LockLines.save(ledger,storedLock,storedRows);
|
if(states.some(row=>row.source==='manual'))LockLines.save(ledger,storedLock,storedRows);
|
||||||
const recorded=replaceExpenses(ledger,order,fees,data.fee_items,feesDate,actor,reason,env);
|
const recorded=replaceExpenses(ledger,order,fees,data.fee_items,feesDate,actor,reason,env);
|
||||||
@@ -296,7 +301,8 @@ function editDeliveredLock(ledger,info,input,metadata,actor,env){
|
|||||||
ledger.run('UPDATE price_locks SET delivery=? WHERE id=?',JSON.stringify(originalDateDelivery),lock.id);
|
ledger.run('UPDATE price_locks SET delivery=? WHERE id=?',JSON.stringify(originalDateDelivery),lock.id);
|
||||||
for(const row of releases)poolChanges.push(LockPools.releaseForOrderEdit(ledger,lock.id,actor,env,{lineIndex:row.index,skipJournalOrder:id,preservePriceLockIds:[lock.id]}));
|
for(const row of releases)poolChanges.push(LockPools.releaseForOrderEdit(ledger,lock.id,actor,env,{lineIndex:row.index,skipJournalOrder:id,preservePriceLockIds:[lock.id]}));
|
||||||
}
|
}
|
||||||
if(states.some(row=>row.reservation)&&date!==lock.delivery.date)poolChanges.push(LockPools.moveDeliveryDate(ledger,lock.id,date,actor,env,{skipJournalOrder:id}));
|
for(const row of states.filter(row=>row.extraReservation&&row.extraSource==='manual'))poolChanges.push(LockPools.releaseForOrderEdit(ledger,lock.id,actor,env,{lineIndex:LockPools.extraIndex(row.index),skipJournalOrder:id,preservePriceLockIds:[lock.id]}));
|
||||||
|
if(states.some(row=>row.reservation||row.extraSource==='pool')&&date!==lock.delivery.date)poolChanges.push(LockPools.moveDeliveryDate(ledger,lock.id,date,actor,env,{skipJournalOrder:id}));
|
||||||
ledger.run('UPDATE price_locks SET delivery=?,revision=revision+1,updated=? WHERE id=?',JSON.stringify(nextDelivery),env.now(),lock.id);
|
ledger.run('UPDATE price_locks SET delivery=?,revision=revision+1,updated=? WHERE id=?',JSON.stringify(nextDelivery),env.now(),lock.id);
|
||||||
const next=ledger.rawOrder(id);replaceInventory(ledger,order,next,date,actor,reason);
|
const next=ledger.rawOrder(id);replaceInventory(ledger,order,next,date,actor,reason);
|
||||||
const expensesChanged=before.expenses.length!==ledger.one('SELECT COUNT(*) AS count FROM expenses WHERE order_id=?',id).count;
|
const expensesChanged=before.expenses.length!==ledger.one('SELECT COUNT(*) AS count FROM expenses WHERE order_id=?',id).count;
|
||||||
|
|||||||
@@ -61,7 +61,7 @@ function poolMaterialCosts(ledger,rows,group){
|
|||||||
for(const row of rows){
|
for(const row of rows){
|
||||||
if(row.kind==='afterSale'||row.status!=='delivered'||!row.costItems.some(item=>item.materialPoolId&&item.component==='material'))continue;
|
if(row.kind==='afterSale'||row.status!=='delivered'||!row.costItems.some(item=>item.materialPoolId&&item.component==='material'))continue;
|
||||||
const order=OrderAfterSaleReporting.originalOrder(ledger,ledger.rawOrder(row.id));
|
const order=OrderAfterSaleReporting.originalOrder(ledger,ledger.rawOrder(row.id));
|
||||||
for(const line of order.lines){
|
for(const line of order.lines.flatMap(line=>line.priceLockExtraPool?[{...line,priceLockExtraPool:undefined,materialAllocations:line.materialAllocations.filter(a=>a.source==='original'),costParts:{...line.costParts,material:line.priceLockPool?line.priceLockPool.amount:sum(line.materialAllocations.filter(a=>a.source==='original'),a=>a.amount)}},{...line,priceLockPool:line.priceLockExtraPool,priceLockExtraPool:undefined,materialAllocations:line.materialAllocations.filter(a=>a.source==='extra'),costParts:{...line.costParts,material:line.priceLockExtraPool.amount}}]:[line])){
|
||||||
const pool=line.costMaterial?.mode==='pool'?line.materialPool:line.priceLockPool;
|
const pool=line.costMaterial?.mode==='pool'?line.materialPool:line.priceLockPool;
|
||||||
const poolId=line.costMaterial?.mode==='pool'?line.costMaterial.poolId:pool?.poolId;
|
const poolId=line.costMaterial?.mode==='pool'?line.costMaterial.poolId:pool?.poolId;
|
||||||
if(!poolId)continue;
|
if(!poolId)continue;
|
||||||
|
|||||||
@@ -34,8 +34,8 @@ function financeInternal(ledger){
|
|||||||
const state=rows(ledger),result=new Map();
|
const state=rows(ledger),result=new Map();
|
||||||
for(const reservation of state.reservations){
|
for(const reservation of state.reservations){
|
||||||
const lock=ledger.one('SELECT * FROM price_locks WHERE id=?',reservation.price_lock_id);if(!lock)continue;
|
const lock=ledger.one('SELECT * FROM price_locks WHERE id=?',reservation.price_lock_id);if(!lock)continue;
|
||||||
const delivery=LockLines.deliveryAt(lock,reservation.line_index),order=lock.final_order_id?ledger.rawOrder(lock.final_order_id):null;
|
const extra=reservation.line_index<0,index=extra?-reservation.line_index-1:reservation.line_index,delivery=extra?null:LockLines.deliveryAt(lock,index),order=lock.final_order_id?ledger.rawOrder(lock.final_order_id):null;
|
||||||
const original=order?.lines[reservation.line_index]?.materialAllocations?.filter(part=>part.source==='original');
|
const original=order?.lines[index]?.materialAllocations?.filter(part=>part.source===(extra?'extra':'original'));
|
||||||
const row={lineIndex:reservation.line_index,materialAmount:reservation.amount,usedMaterialAmount:original?.length?original.reduce((sum,part)=>sum+part.amount,0):reservation.amount,leftoverCost:delivery?(delivery.leftover_cost??null):0,allocations:allocations(reservation.allocations)};
|
const row={lineIndex:reservation.line_index,materialAmount:reservation.amount,usedMaterialAmount:original?.length?original.reduce((sum,part)=>sum+part.amount,0):reservation.amount,leftoverCost:delivery?(delivery.leftover_cost??null):0,allocations:allocations(reservation.allocations)};
|
||||||
const previous=result.get(lock.id);
|
const previous=result.get(lock.id);
|
||||||
if(previous){
|
if(previous){
|
||||||
|
|||||||
+37
-12
@@ -24,6 +24,8 @@ function substitution(l,kind,id,quantity,reserved){
|
|||||||
function decorate(l,rows){return rows.map(r=>({...r,fifo_sequence:l.one("SELECT sequence FROM material_usage_order WHERE kind='order' AND source_id=?",r.id)?.sequence??r.fifo_sequence,...substitution(l,'order',r.id,r.mg)}));}
|
function decorate(l,rows){return rows.map(r=>({...r,fifo_sequence:l.one("SELECT sequence FROM material_usage_order WHERE kind='order' AND source_id=?",r.id)?.sequence??r.fifo_sequence,...substitution(l,'order',r.id,r.mg)}));}
|
||||||
function decode(r){return r?{...r,allocations:JSON.parse(r.allocations),snapshot:JSON.parse(r.snapshot)}:null;}
|
function decode(r){return r?{...r,allocations:JSON.parse(r.allocations),snapshot:JSON.parse(r.snapshot)}:null;}
|
||||||
function find(l,id,lineIndex=0){return decode(l.one('SELECT * FROM price_lock_pool_reservations WHERE price_lock_id=? AND line_index=?',id,lineIndex));}
|
function find(l,id,lineIndex=0){return decode(l.one('SELECT * FROM price_lock_pool_reservations WHERE price_lock_id=? AND line_index=?',id,lineIndex));}
|
||||||
|
// 原锁预留用非负商品行号;交付补重用 -行号-1,独立保存日期、成本和来源。
|
||||||
|
const extraIndex=index=>-index-1, itemIndex=index=>index<0?-index-1:index;
|
||||||
function findAll(l,id){return l.rows('SELECT * FROM price_lock_pool_reservations WHERE price_lock_id=? ORDER BY line_index',id).map(decode);}
|
function findAll(l,id){return l.rows('SELECT * FROM price_lock_pool_reservations WHERE price_lock_id=? ORDER BY line_index',id).map(decode);}
|
||||||
function splitParts(parts,amount){let left=amount;const taken=[],rest=[];for(const part of parts){const n=Math.min(left,part.amount);if(n)taken.push({payer:part.payer,amount:n});if(part.amount>n)rest.push({payer:part.payer,amount:part.amount-n});left-=n;}if(left)throw new Error('锁价料池付款归属不足');if(!amount&&!taken.length)taken.push({payer:parts[0]?.payer??'owner',amount:0});return {taken,rest};}
|
function splitParts(parts,amount){let left=amount;const taken=[],rest=[];for(const part of parts){const n=Math.min(left,part.amount);if(n)taken.push({payer:part.payer,amount:n});if(part.amount>n)rest.push({payer:part.payer,amount:part.amount-n});left-=n;}if(left)throw new Error('锁价料池付款归属不足');if(!amount&&!taken.length)taken.push({payer:parts[0]?.payer??'owner',amount:0});return {taken,rest};}
|
||||||
function split(snapshot,used){
|
function split(snapshot,used){
|
||||||
@@ -34,13 +36,13 @@ function split(snapshot,used){
|
|||||||
}
|
}
|
||||||
function detail(l,id,env,lineIndex=0){const r=find(l,id,lineIndex);if(!r)return null;return {...r.snapshot,revision:r.revision,frozen:r.pool_id!==env.today()};}
|
function detail(l,id,env,lineIndex=0){const r=find(l,id,lineIndex);if(!r)return null;return {...r.snapshot,revision:r.revision,frozen:r.pool_id!==env.today()};}
|
||||||
function reservations(l,date){return l.rows(`SELECT r.*,s.sequence AS fifo_sequence,p.number,p.customer,p.line,p.lines AS lock_lines,p.status,p.delivery,p.final_order_id,o.status AS order_status,o.returned_date FROM price_lock_pool_reservations r JOIN price_locks p ON p.id=r.price_lock_id LEFT JOIN material_usage_order s ON s.kind='priceLock' AND s.source_id=r.id LEFT JOIN orders o ON o.id=p.final_order_id WHERE r.pool_id=? ORDER BY r.created,r.rowid`,date).map(r=>{
|
function reservations(l,date){return l.rows(`SELECT r.*,s.sequence AS fifo_sequence,p.number,p.customer,p.line,p.lines AS lock_lines,p.status,p.delivery,p.final_order_id,o.status AS order_status,o.returned_date FROM price_lock_pool_reservations r JOIN price_locks p ON p.id=r.price_lock_id LEFT JOIN material_usage_order s ON s.kind='priceLock' AND s.source_id=r.id LEFT JOIN orders o ON o.id=p.final_order_id WHERE r.pool_id=? ORDER BY r.created,r.rowid`,date).map(r=>{
|
||||||
const snapshot=JSON.parse(r.snapshot),delivery=LockLines.deliveryLines(r.delivery)[r.line_index],entry=LockLines.lines({...r,id:r.price_lock_id,lines:r.lock_lines})[r.line_index];
|
const snapshot=JSON.parse(r.snapshot),delivery=LockLines.deliveryLines(r.delivery)[itemIndex(r.line_index)],entry=LockLines.lines({...r,id:r.price_lock_id,lines:r.lock_lines})[itemIndex(r.line_index)];
|
||||||
let mg=r.mg;if(delivery?.date===date)mg=delivery.original_used_mg;if(r.order_status==='returned'&&r.returned_date===date)mg=0;
|
let mg=r.mg;if(delivery?.date===date)mg=r.line_index<0?delivery.extra_mg:delivery.original_used_mg;if(r.order_status==='returned'&&r.returned_date===date)mg=0;
|
||||||
const effective=snapshot.amount===undefined?{amount:null,allocations:[]}:mg===r.mg?{amount:r.amount,allocations:JSON.parse(r.allocations),...(snapshot.materialSources?{materialSources:snapshot.materialSources}:{})}:split(snapshot,mg);
|
const effective=snapshot.amount===undefined?{amount:null,allocations:[]}:mg===r.mg?{amount:r.amount,allocations:JSON.parse(r.allocations),...(snapshot.materialSources?{materialSources:snapshot.materialSources}:{})}:split(snapshot,mg);
|
||||||
return {...r,kind:'priceLock',member:l.entityMember('price_lock',r.price_lock_id),...(effective.materialSources?{materialSources:effective.materialSources}:{}),date,price_lock_id:r.price_lock_id,order_id:r.final_order_id,reserved_mg:r.mg,mg,...substitution(l,'priceLock',r.id,mg,r.mg),active:mg>0?1:0,amount:effective.amount,snapshot,allocations:effective.allocations,product:entry?.line.name??JSON.parse(r.line).name,...Object.fromEntries(PARTIES.map(p=>[p+'_amount',effective.amount===null?null:sum(effective.allocations.filter(a=>a.payer===p),'amount')]))};
|
return {...r,kind:'priceLock',member:l.entityMember('price_lock',r.price_lock_id),...(effective.materialSources?{materialSources:effective.materialSources}:{}),date,price_lock_id:r.price_lock_id,order_id:r.final_order_id,reserved_mg:r.mg,mg,...substitution(l,'priceLock',r.id,mg,r.mg),active:mg>0?1:0,amount:effective.amount,snapshot,allocations:effective.allocations,product:entry?.line.name??JSON.parse(r.line).name,...Object.fromEntries(PARTIES.map(p=>[p+'_amount',effective.amount===null?null:sum(effective.allocations.filter(a=>a.payer===p),'amount')]))};
|
||||||
});}
|
});}
|
||||||
function combined(l,date,rows){return [...decorate(l,rows),...reservations(l,date)].sort((a,b)=>a.created<b.created?-1:a.created>b.created?1:a.fifo_sequence-b.fifo_sequence);}
|
function combined(l,date,rows){return [...decorate(l,rows),...reservations(l,date)].sort((a,b)=>a.created<b.created?-1:a.created>b.created?1:a.fifo_sequence-b.fifo_sequence);}
|
||||||
function returns(l,date){return l.rows('SELECT r.*,p.number,p.customer,p.line,p.lines AS lock_lines FROM price_lock_pool_returns r JOIN price_locks p ON p.id=r.price_lock_id WHERE r.date=? ORDER BY r.created,r.rowid',date).map(r=>({...r,allocations:JSON.parse(r.allocations),...(Allocation.returnSources(l,'lock',r.id)?{materialSources:Allocation.returnSources(l,'lock',r.id)}:{}),product:LockLines.product({...r,id:r.price_lock_id,lines:r.lock_lines},r.line_index),sourceKind:'return',cashAmount:0,payer:JSON.parse(r.allocations)[0]?.payer??'owner',sameDay:!!r.same_day,note:r.kind==='cancel'?'锁价作废回料(原成本)':r.kind==='leftover'?'锁价余料回池':'锁价退货回料',source_sequence:l.one("SELECT sequence FROM material_rolling_source_order WHERE kind='lock_return' AND source_id=?",r.id)?.sequence??0}));}
|
function returns(l,date){return l.rows('SELECT r.*,p.number,p.customer,p.line,p.lines AS lock_lines FROM price_lock_pool_returns r JOIN price_locks p ON p.id=r.price_lock_id WHERE r.date=? ORDER BY r.created,r.rowid',date).map(r=>({...r,allocations:JSON.parse(r.allocations),...(Allocation.returnSources(l,'lock',r.id)?{materialSources:Allocation.returnSources(l,'lock',r.id)}:{}),product:LockLines.product({...r,id:r.price_lock_id,lines:r.lock_lines},itemIndex(r.line_index)),sourceKind:'return',cashAmount:0,payer:JSON.parse(r.allocations)[0]?.payer??'owner',sameDay:!!r.same_day,note:r.kind==='cancel'?'锁价作废回料(原成本)':r.kind==='leftover'?'锁价余料回池':'锁价退货回料',source_sequence:l.one("SELECT sequence FROM material_rolling_source_order WHERE kind='lock_return' AND source_id=?",r.id)?.sequence??0}));}
|
||||||
function fundingParts(purchases,start,amount){let skip=start,left=amount;const result=[];for(const p of purchases)for(const part of (p.allocations??[{payer:p.payer,amount:p.amount}])){if(skip>=part.amount){skip-=part.amount;continue;}const n=Math.min(left,part.amount-skip);if(n)result.push({payer:part.payer,amount:n});left-=n;skip=0;}if(left)throw new Error('锁价料池来源金额不足');return result;}
|
function fundingParts(purchases,start,amount){let skip=start,left=amount;const result=[];for(const p of purchases)for(const part of (p.allocations??[{payer:p.payer,amount:p.amount}])){if(skip>=part.amount){skip-=part.amount;continue;}const n=Math.min(left,part.amount-skip);if(n)result.push({payer:part.payer,amount:n});left-=n;skip=0;}if(left)throw new Error('锁价料池来源金额不足');return result;}
|
||||||
function allocate(pool,rows,allocatePayers){
|
function allocate(pool,rows,allocatePayers){
|
||||||
if(Allocation.enabled(pool)||rows.some(row=>row.publicSubstitutionMg>0||row.reservedPublicSubstitutionMg>0))return Allocation.allocate({...pool,materialGroups:pool.materialGroups??Allocation.groups(pool.purchases)},rows);
|
if(Allocation.enabled(pool)||rows.some(row=>row.publicSubstitutionMg>0||row.reservedPublicSubstitutionMg>0))return Allocation.allocate({...pool,materialGroups:pool.materialGroups??Allocation.groups(pool.purchases)},rows);
|
||||||
@@ -81,13 +83,14 @@ function update(l,row,pool,actor,env,{skipJournalOrder=null}={}){
|
|||||||
const snapshot=row.lockSnapshot,old=row.snapshot,changed=JSON.stringify(snapshot)!==JSON.stringify(old);if(!changed)return;
|
const snapshot=row.lockSnapshot,old=row.snapshot,changed=JSON.stringify(snapshot)!==JSON.stringify(old);if(!changed)return;
|
||||||
const revision=row.revision+1;l.run('UPDATE price_lock_pool_reservations SET amount=?,allocations=?,snapshot=?,revision=?,updated=? WHERE id=?',snapshot.amount,JSON.stringify(snapshot.allocations),JSON.stringify(snapshot),revision,env.now(),row.id);
|
const revision=row.revision+1;l.run('UPDATE price_lock_pool_reservations SET amount=?,allocations=?,snapshot=?,revision=?,updated=? WHERE id=?',snapshot.amount,JSON.stringify(snapshot.allocations),JSON.stringify(snapshot),revision,env.now(),row.id);
|
||||||
l.run('UPDATE price_locks SET revision=revision+1,updated=? WHERE id=?',env.now(),row.price_lock_id);
|
l.run('UPDATE price_locks SET revision=revision+1,updated=? WHERE id=?',env.now(),row.price_lock_id);
|
||||||
|
if(row.line_index<0){updateExtra(l,row,snapshot,actor,env,skipJournalOrder);return;}
|
||||||
const lock=l.one('SELECT * FROM price_locks WHERE id=?',row.price_lock_id),lockedLines=LockLines.lines(lock),entry=lockedLines[row.line_index],lockedLine=entry.line;
|
const lock=l.one('SELECT * FROM price_locks WHERE id=?',row.price_lock_id),lockedLines=LockLines.lines(lock),entry=lockedLines[row.line_index],lockedLine=entry.line;
|
||||||
entry.material_amount=snapshot.amount;entry.buy_rate=snapshot.averageRate;entry.material_source='pool';lockedLine.costParts={...lockedLine.costParts,material:snapshot.amount};lockedLine.cost=Object.values(lockedLine.costParts).some(v=>v===null)?null:sum(Object.values(lockedLine.costParts).map(amount=>({amount})),'amount');LockLines.save(l,lock,lockedLines);
|
entry.material_amount=snapshot.amount;entry.buy_rate=snapshot.averageRate;entry.material_source='pool';lockedLine.costParts={...lockedLine.costParts,material:snapshot.amount};lockedLine.cost=Object.values(lockedLine.costParts).some(v=>v===null)?null:sum(Object.values(lockedLine.costParts).map(amount=>({amount})),'amount');LockLines.save(l,lock,lockedLines);
|
||||||
if(lock.status==='cancelled'){const returned=l.one("SELECT * FROM price_lock_pool_returns WHERE price_lock_id=? AND line_index=? AND kind='cancel'",lock.id,row.line_index);if(returned)returnRow(l,{...lock,line_index:row.line_index},'cancel',returned.date,row.mg,snapshot.amount,snapshot.allocations,snapshot.poolId,actor,env,snapshot.materialSources??null);}
|
if(lock.status==='cancelled'){const returned=l.one("SELECT * FROM price_lock_pool_returns WHERE price_lock_id=? AND line_index=? AND kind='cancel'",lock.id,row.line_index);if(returned)returnRow(l,{...lock,line_index:row.line_index},'cancel',returned.date,row.mg,snapshot.amount,snapshot.allocations,snapshot.poolId,actor,env,snapshot.materialSources??null);}
|
||||||
if(lock.final_order_id){
|
if(lock.final_order_id){
|
||||||
const order=l.rawOrder(lock.final_order_id),line=order.lines[row.line_index],deliveries=LockLines.deliveryLines(lock.delivery),delivery=deliveries[row.line_index],part=split(snapshot,delivery.original_used_mg),before=line.costParts.material,lineLock={...lock,line_index:row.line_index};
|
const order=l.rawOrder(lock.final_order_id),line=order.lines[row.line_index],deliveries=LockLines.deliveryLines(lock.delivery),delivery=deliveries[row.line_index],part=split(snapshot,delivery.original_used_mg),before=line.costParts.material,lineLock={...lock,line_index:row.line_index};
|
||||||
const extra=(line.materialAllocations??[]).filter(a=>a.source==='extra');line.materialAllocations=[...materialAllocations(snapshot,delivery.original_used_mg),...extra];line.priceLockPool={...snapshot,quantity:delivery.original_used_mg,amount:part.amount,allocations:part.allocations,...(part.materialSources?{materialSources:part.materialSources}:{}),priceLockId:lock.id,lineId:entry.id,line_index:row.line_index};
|
const extra=(line.materialAllocations??[]).filter(a=>a.source==='extra');line.materialAllocations=[...materialAllocations(snapshot,delivery.original_used_mg),...extra];line.priceLockPool={...snapshot,quantity:delivery.original_used_mg,amount:part.amount,allocations:part.allocations,...(part.materialSources?{materialSources:part.materialSources}:{}),priceLockId:lock.id,lineId:entry.id,line_index:row.line_index};
|
||||||
line.costParts.material=part.amount===null?null:part.amount+sum(extra,'amount');line.cost=Object.values(line.costParts).some(v=>v===null)?null:sum(Object.values(line.costParts).map(amount=>({amount})),'amount');
|
line.costParts.material=part.amount===null||line.priceLockExtraPool?.amount===null?null:part.amount+sum(extra,'amount');line.cost=Object.values(line.costParts).some(v=>v===null)?null:sum(Object.values(line.costParts).map(amount=>({amount})),'amount');
|
||||||
l.run('UPDATE orders SET lines=? WHERE id=?',JSON.stringify(order.lines),order.id);
|
l.run('UPDATE orders SET lines=? WHERE id=?',JSON.stringify(order.lines),order.id);
|
||||||
deliveries[row.line_index]={...delivery,leftover_cost:part.leftoverCost};l.run('UPDATE price_locks SET delivery=? WHERE id=?',JSON.stringify(LockLines.aggregateDelivery(JSON.parse(lock.delivery),deliveries)),lock.id);
|
deliveries[row.line_index]={...delivery,leftover_cost:part.leftoverCost};l.run('UPDATE price_locks SET delivery=? WHERE id=?',JSON.stringify(LockLines.aggregateDelivery(JSON.parse(lock.delivery),deliveries)),lock.id);
|
||||||
returnRow(l,lineLock,'leftover',delivery.date,part.leftoverMg,part.leftoverCost,part.leftoverAllocations,snapshot.poolId,actor,env,part.leftoverMaterialSources);
|
returnRow(l,lineLock,'leftover',delivery.date,part.leftoverMg,part.leftoverCost,part.leftoverAllocations,snapshot.poolId,actor,env,part.leftoverMaterialSources);
|
||||||
@@ -103,15 +106,35 @@ function reserve(l,lock,pool,actor,env){
|
|||||||
}
|
}
|
||||||
function prepareDelivery(l,lock,date,used,actor,env){const reservation=find(l,lock.id,lock.line_index??0);if(!reservation)return null;const snapshot=reservation.snapshot;if(snapshot.amount===null||snapshot.amount===undefined)env.fail('锁价原料池成本待补,请先核实购料后交付',409);const part=split(snapshot,used);return {...part,snapshot};}
|
function prepareDelivery(l,lock,date,used,actor,env){const reservation=find(l,lock.id,lock.line_index??0);if(!reservation)return null;const snapshot=reservation.snapshot;if(snapshot.amount===null||snapshot.amount===undefined)env.fail('锁价原料池成本待补,请先核实购料后交付',409);const part=split(snapshot,used);return {...part,snapshot};}
|
||||||
function finishDelivery(l,lock,delivery,actor,env){const r=find(l,lock.id,lock.line_index??0);if(!r)return;const part=split(r.snapshot,delivery.original_used_mg);returnRow(l,lock,'leftover',delivery.date,part.leftoverMg,part.leftoverCost,part.leftoverAllocations,r.pool_id,actor,env,part.leftoverMaterialSources);}
|
function finishDelivery(l,lock,delivery,actor,env){const r=find(l,lock.id,lock.line_index??0);if(!r)return;const part=split(r.snapshot,delivery.original_used_mg);returnRow(l,lock,'leftover',delivery.date,part.leftoverMg,part.leftoverCost,part.leftoverAllocations,r.pool_id,actor,env,part.leftoverMaterialSources);}
|
||||||
|
function updateExtra(l,row,snapshot,actor,env,skipJournalOrder){
|
||||||
|
const lock=l.one('SELECT * FROM price_locks WHERE id=?',row.price_lock_id),index=itemIndex(row.line_index);
|
||||||
|
if(lock.final_order_id){
|
||||||
|
const order=l.rawOrder(lock.final_order_id),line=order.lines[index],before=line.costParts.material;
|
||||||
|
line.priceLockExtraPool={...snapshot,priceLockId:lock.id,line_index:index};
|
||||||
|
line.materialAllocations=[...(line.materialAllocations??[]).filter(a=>a.source==='original'),...materialAllocations(snapshot,row.mg).map(a=>({...a,source:'extra'}))];
|
||||||
|
line.costParts.material=snapshot.amount===null||line.priceLockPool?.amount===null?null:sum(line.materialAllocations,'amount');
|
||||||
|
line.cost=Object.values(line.costParts).some(v=>v===null)?null:Object.values(line.costParts).reduce((a,b)=>a+b,0);
|
||||||
|
l.run('UPDATE orders SET lines=? WHERE id=?',JSON.stringify(order.lines),order.id);
|
||||||
|
if(order.status==='returned')returnRow(l,{...lock,line_index:row.line_index},'goods',order.returned_date,row.reserved_mg,snapshot.amount,snapshot.allocations,snapshot.poolId,actor,env,snapshot.materialSources);
|
||||||
|
const delta=(line.costParts.material??0)-(before??0);
|
||||||
|
if(order.id!==skipJournalOrder){if(delta)l.journal(order.id,order.delivered_date,'锁价补重料池成本调整',0,delta,0);if(delta&&order.status==='returned')l.journal(order.id,order.returned_date,'锁价补重退货成本冲回',0,-delta,0);l.touch(order.id);l.dirty(order.date);}
|
||||||
|
}
|
||||||
|
l.dirty(row.pool_id);l.audit('price-lock:'+lock.id,'交付补重料池加权更新',actor,{line_index:index,poolId:row.pool_id,before:row.snapshot,after:snapshot});
|
||||||
|
}
|
||||||
function recordReturn(l,order,date,input,actor,env){
|
function recordReturn(l,order,date,input,actor,env){
|
||||||
const lock=l.one('SELECT * FROM price_locks WHERE final_order_id=?',order.id),rows=lock?findAll(l,lock.id):[];if(!rows.length)return false;
|
const lock=l.one('SELECT * FROM price_locks WHERE final_order_id=?',order.id),rows=lock?findAll(l,lock.id):[];if(!rows.length)return false;
|
||||||
for(const r of rows){
|
const indices=[...new Set(rows.map(r=>itemIndex(r.line_index)))];
|
||||||
const index=r.line_index,line=order.lines[index],destination=input.returnPockets?.[index]??line.pocket;if(!env.selfPockets?.includes(destination))env.fail('料池锁价黄金须退回自有货盘');
|
for(const index of indices){
|
||||||
const delivery=LockLines.deliveryAt(lock,index),part=split(r.snapshot,delivery.original_used_mg),lineLock={...lock,line_index:index};if(part.amount===null)env.fail('锁价原料池成本待补,不能退货回料',409);
|
const line=order.lines[index],destination=input.returnPockets?.[index]??line.pocket;if(!env.selfPockets?.includes(destination))env.fail('料池锁价黄金须退回自有货盘');
|
||||||
returnRow(l,lineLock,'goods',date,delivery.original_used_mg,part.amount,part.allocations,r.pool_id,actor,env,part.materialSources);
|
const delivery=LockLines.deliveryAt(lock,index);
|
||||||
const extra=(line.materialAllocations??[]).filter(a=>a.source==='extra');if(delivery.extra_mg)returnRow(l,lineLock,'extra',date,delivery.extra_mg,sum(extra,'amount'),extra.map(a=>({payer:a.payer,amount:a.amount})),'',actor,env);
|
for(const source of ['original','extra']){
|
||||||
|
const mg=source==='original'?delivery.original_used_mg:delivery.extra_mg;if(!mg)continue;
|
||||||
|
const key=source==='original'?index:extraIndex(index),r=rows.find(r=>r.line_index===key),lineLock={...lock,line_index:key};
|
||||||
|
if(r){const part=split(r.snapshot,mg);if(part.amount===null)env.fail('锁价料池成本待补,不能退货回料',409);returnRow(l,lineLock,'goods',date,mg,part.amount,part.allocations,r.pool_id,actor,env,part.materialSources);}
|
||||||
|
else {const parts=(line.materialAllocations??[]).filter(a=>a.source===source);returnRow(l,{...lock,line_index:index},source==='extra'?'extra':'manual_original',date,mg,sum(parts,'amount'),parts.map(a=>({payer:a.payer,amount:a.amount})),'',actor,env);}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
return rows.map(row=>row.line_index);
|
return indices;
|
||||||
}
|
}
|
||||||
function atomicEdit(l,fn){
|
function atomicEdit(l,fn){
|
||||||
l.db.exec('SAVEPOINT price_lock_pool_order_edit');
|
l.db.exec('SAVEPOINT price_lock_pool_order_edit');
|
||||||
@@ -178,9 +201,11 @@ function moveDeliveryDate(l,value,nextDate,actor,env,{skipJournalOrder=null}={})
|
|||||||
// 两个交付日都跨过原锁日时,原预留占用完全相同;只从余料实际变动的最早日重建。
|
// 两个交付日都跨过原锁日时,原预留占用完全相同;只从余料实际变动的最早日重建。
|
||||||
const rows=l.rows('SELECT * FROM price_lock_pool_returns WHERE price_lock_id=? ORDER BY rowid',lock.id),dates=[...new Set([delivery.date,date])].sort();
|
const rows=l.rows('SELECT * FROM price_lock_pool_returns WHERE price_lock_id=? ORDER BY rowid',lock.id),dates=[...new Set([delivery.date,date])].sort();
|
||||||
assertEditDates(l,dates,actor,env);
|
assertEditDates(l,dates,actor,env);
|
||||||
|
for(const row of reservations.filter(row=>row.line_index<0))l.run('UPDATE price_lock_pool_reservations SET pool_id=? WHERE id=?',date,row.id);
|
||||||
const updated=LockLines.aggregateDelivery({...delivery,date},LockLines.deliveryLines(delivery).map(row=>({...row,date})));l.run('UPDATE price_locks SET delivery=?,updated=? WHERE id=?',JSON.stringify(updated),env.now(),lock.id);
|
const updated=LockLines.aggregateDelivery({...delivery,date},LockLines.deliveryLines(delivery).map(row=>({...row,date})));l.run('UPDATE price_locks SET delivery=?,updated=? WHERE id=?',JSON.stringify(updated),env.now(),lock.id);
|
||||||
for(const row of rows.filter(row=>row.kind==='leftover'))l.run('UPDATE price_lock_pool_returns SET date=?,same_day=? WHERE id=?',date,row.origin_pool_id===date?1:0,row.id);
|
for(const row of rows.filter(row=>row.kind==='leftover'))l.run('UPDATE price_lock_pool_returns SET date=?,same_day=? WHERE id=?',date,row.origin_pool_id===date?1:0,row.id);
|
||||||
rebuildAffected(l,dates,actor,env,{skipJournalOrder,preservePriceLockIds:[lock.id]});
|
rebuildAffected(l,dates,actor,env,{skipJournalOrder,preservePriceLockIds:[lock.id],repriceExtraPriceLockIds:[lock.id]});
|
||||||
|
for(const row of findAll(l,lock.id).filter(row=>row.line_index<0))if(row.amount===null)env.fail('更改交付日期后补重料池不足或成本待补,请先核实料源',409);
|
||||||
const rolling=require('./rolling-material-pools');
|
const rolling=require('./rolling-material-pools');
|
||||||
if(rolling.enabled(l))for(const row of l.rows('SELECT date FROM material_rolling_days WHERE date>=? ORDER BY date',dates[0])){
|
if(rolling.enabled(l))for(const row of l.rows('SELECT date FROM material_rolling_days WHERE date>=? ORDER BY date',dates[0])){
|
||||||
const pool=rolling.readPool(l,row.date,env,{internal:true});if(pool.shortageMg>0)env.fail('调整交付日期后,'+row.date+'料池短料;原日余料已被其他订单使用,请先核实金料来源后再改交付日期',409);
|
const pool=rolling.readPool(l,row.date,env,{internal:true});if(pool.shortageMg>0)env.fail('调整交付日期后,'+row.date+'料池短料;原日余料已被其他订单使用,请先核实金料来源后再改交付日期',409);
|
||||||
@@ -188,4 +213,4 @@ function moveDeliveryDate(l,value,nextDate,actor,env,{skipJournalOrder=null}={})
|
|||||||
for(const date of dates)l.dirty(date);
|
for(const date of dates)l.dirty(date);
|
||||||
return {moved:true,affectedDates:dates,earliestDate:dates[0],delivery:updated};
|
return {moved:true,affectedDates:dates,earliestDate:dates[0],delivery:updated};
|
||||||
});}
|
});}
|
||||||
module.exports={initialize,sequence,decorate,find,findAll,detail,reservations,combined,returns,allocate,update,reserve,split,materialAllocations,prepareDelivery,finishDelivery,recordReturn,releaseForOrderEdit,cancelReservations,moveDeliveryDate};
|
module.exports={extraIndex,itemIndex,initialize,sequence,decorate,find,findAll,detail,reservations,combined,returns,allocate,update,reserve,split,materialAllocations,prepareDelivery,finishDelivery,recordReturn,releaseForOrderEdit,cancelReservations,moveDeliveryDate};
|
||||||
+24
-10
@@ -51,11 +51,11 @@ function detail(ledger,id,env){
|
|||||||
const cash_events=events.filter(event=>event.kind!=='material'),material_events=events.filter(event=>event.kind==='material');
|
const cash_events=events.filter(event=>event.kind!=='material'),material_events=events.filter(event=>event.kind==='material');
|
||||||
const received=cash_events.filter(event=>event.kind==='receipt').reduce((sum,event)=>sum+event.amount,0),refunded=cash_events.filter(event=>event.kind==='refund').reduce((sum,event)=>sum+event.amount,0);
|
const received=cash_events.filter(event=>event.kind==='receipt').reduce((sum,event)=>sum+event.amount,0),refunded=cash_events.filter(event=>event.kind==='refund').reduce((sum,event)=>sum+event.amount,0);
|
||||||
const credit_card_fees=events.filter(event=>event.card_fee_amount!==null).map(event=>({key:'card_fee:'+event.id,system:'credit_card',source_kind:'price_lock',source_id:event.id,date:event.date,amount:event.card_fee_amount,payer:event.card_fee_payer,note:cardFeeNote(event),...(event.card_fee_rate?{rate_permille:event.card_fee_rate}:{}),...(event.card_fee_expense_id?{expense_id:event.card_fee_expense_id}:{})}));
|
const credit_card_fees=events.filter(event=>event.card_fee_amount!==null).map(event=>({key:'card_fee:'+event.id,system:'credit_card',source_kind:'price_lock',source_id:event.id,date:event.date,amount:event.card_fee_amount,payer:event.card_fee_payer,note:cardFeeNote(event),...(event.card_fee_rate?{rate_permille:event.card_fee_rate}:{}),...(event.card_fee_expense_id?{expense_id:event.card_fee_expense_id}:{})}));
|
||||||
const reservations=LockPools.findAll(ledger,id),byIndex=new Map(reservations.map(r=>[r.line_index,r]));
|
const reservations=LockPools.findAll(ledger,id).filter(r=>r.line_index>=0),byIndex=new Map(reservations.map(r=>[r.line_index,r]));
|
||||||
const lines=row.lines.map(item=>{const reservation=byIndex.get(item.line_index);return {...item,material_source:reservation?'pool':'manual',...(reservation?{material_amount:reservation.snapshot.amount??null,buy_rate:reservation.snapshot.averageRate??null,material_pool_id:reservation.pool_id,materialPool:LockPools.detail(ledger,id,env,item.line_index)}:{}),delivery:LockLines.deliveryAt(row,item.line_index)};});
|
const lines=row.lines.map(item=>{const reservation=byIndex.get(item.line_index);return {...item,material_source:reservation?'pool':'manual',...(reservation?{material_amount:reservation.snapshot.amount??null,buy_rate:reservation.snapshot.averageRate??null,material_pool_id:reservation.pool_id,materialPool:LockPools.detail(ledger,id,env,item.line_index)}:{}),delivery:LockLines.deliveryAt(row,item.line_index)};});
|
||||||
const cancellationReturns=ledger.rows("SELECT line_index,date,mg,amount,allocations,origin_pool_id FROM price_lock_pool_returns WHERE price_lock_id=? AND kind='cancel' ORDER BY line_index",id).map(value=>({...value,allocations:JSON.parse(value.allocations)}));
|
const cancellationReturns=ledger.rows("SELECT line_index,date,mg,amount,allocations,origin_pool_id FROM price_lock_pool_returns WHERE price_lock_id=? AND kind='cancel' ORDER BY line_index",id).map(value=>({...value,allocations:JSON.parse(value.allocations)}));
|
||||||
const material_source=reservations.length===0?'manual':reservations.length===lines.length?'pool':'mixed',material_amount=lines.some(line=>line.material_amount===null)?null:lines.reduce((sum,line)=>sum+line.material_amount,0);
|
const material_source=reservations.length===0?'manual':reservations.length===lines.length?'pool':'mixed',material_amount=lines.some(line=>line.material_amount===null)?null:lines.reduce((sum,line)=>sum+line.material_amount,0);
|
||||||
return {...row,...(cancellationReturns.length?{cancellationReturns}:{}),credit_card_rate_permille:CreditCardRates.read(ledger,'price_lock',id),lines,line:lines[0].line,locked_mg:lines.reduce((sum,line)=>sum+line.locked_mg,0),buy_rate:lines[0].buy_rate,buy_payer:lines[0].buy_payer,material_source,material_amount,...(lines.length===1&&lines[0].materialPool?{material_pool_id:lines[0].material_pool_id,materialPool:lines[0].materialPool}:{}),cash_events,material_events,voided_events:allEvents.filter(event=>event.voided),received,refunded,netReceived:received-refunded,credit_card_fees,credit_card_fee_total:credit_card_fees.reduce((total,fee)=>total+fee.amount,0)};
|
return {...row,member:ledger.entityMember('price_lock',id),...(cancellationReturns.length?{cancellationReturns}:{}),credit_card_rate_permille:CreditCardRates.read(ledger,'price_lock',id),lines,line:lines[0].line,locked_mg:lines.reduce((sum,line)=>sum+line.locked_mg,0),buy_rate:lines[0].buy_rate,buy_payer:lines[0].buy_payer,material_source,material_amount,...(lines.length===1&&lines[0].materialPool?{material_pool_id:lines[0].material_pool_id,materialPool:lines[0].materialPool}:{}),cash_events,material_events,voided_events:allEvents.filter(event=>event.voided),received,refunded,netReceived:received-refunded,credit_card_fees,credit_card_fee_total:credit_card_fees.reduce((total,fee)=>total+fee.amount,0)};
|
||||||
}
|
}
|
||||||
function list(ledger,query,env){
|
function list(ledger,query,env){
|
||||||
const date=env.day(query.date??query.to??env.today()),from=env.day(query.from??(query.date||query.to?date:'2000-01-01'));
|
const date=env.day(query.date??query.to??env.today()),from=env.day(query.from??(query.date||query.to?date:'2000-01-01'));
|
||||||
@@ -173,19 +173,31 @@ function deliver(ledger,id,input,actor,env){return atomic(ledger,()=>{
|
|||||||
if(lock.lines.some(row=>row.material_source==='pool'&&row.materialPool?.amount==null))env.fail('锁价原料池成本待补,请先核实购料后交付',409);
|
if(lock.lines.some(row=>row.material_source==='pool'&&row.materialPool?.amount==null))env.fail('锁价原料池成本待补,请先核实购料后交付',409);
|
||||||
if(input.verified!==true)env.fail('请核对实物、实际成本及客户补退款后确认交付');
|
if(input.verified!==true)env.fail('请核对实物、实际成本及客户补退款后确认交付');
|
||||||
const date=env.day(input.date,lock.date),inputs=deliveryInputs(input,lock,env),actualLines=[],results=[];
|
const date=env.day(input.date,lock.date),inputs=deliveryInputs(input,lock,env),actualLines=[],results=[];
|
||||||
|
const extraSelections=inputs.map((row,index)=>({row,index,mg:Math.max(0,env.weight(row.quantity,'交付克重')-lock.lines[index].locked_mg)})).filter(item=>item.mg&&item.row.extraMaterial?.source==='pool');
|
||||||
|
if(extraSelections.length){
|
||||||
|
if(!Rolling.enabled(ledger))env.fail('请先启用统一滚动料池');
|
||||||
|
if(date!==env.today())env.fail('补重使用交付当日料池,请选择当前营业日');
|
||||||
|
const pool=MaterialPools.readPool(ledger,date,env,{internal:true,member:ledger.entityMember('price_lock',id)});
|
||||||
|
for(const {row} of extraSelections)if(row.extraMaterial.poolId!==date||row.extraMaterial.revision!==pool.revision)env.fail('补重料池已有变动,请刷新料价后交付',409);
|
||||||
|
if(extraSelections.reduce((n,r)=>n+r.mg,0)>pool.eligibleRemainingMg||pool.eligibleStatus==='pending')env.fail('当日料池可用克重不足或成本待补,请先核实购料');
|
||||||
|
for(const {index,mg} of extraSelections)LockPools.reserve(ledger,{id,line_index:LockPools.extraIndex(index),locked_mg:mg},pool,actor,env);
|
||||||
|
MaterialPools.reconcile(ledger,date,date,actor,env);
|
||||||
|
}
|
||||||
for(const [index,entry] of lock.lines.entries()){
|
for(const [index,entry] of lock.lines.entries()){
|
||||||
const lineInput=inputs[index];if(lineInput.costMaterial?.mode==='pool'||lineInput.materialPool!==undefined)env.fail('锁价单使用独立采购料费,不能关联日料池');
|
const lineInput=inputs[index],extraPool=LockPools.find(ledger,id,LockPools.extraIndex(index));if(lineInput.costMaterial?.mode==='pool'||lineInput.materialPool!==undefined)env.fail('锁价单使用独立采购料费,不能关联日料池');
|
||||||
if(lineInput.goldPrice!==undefined&&env.money(lineInput.goldPrice,'销售金价')!==entry.sell_rate)env.fail('锁价销售金价不能修改');
|
if(lineInput.goldPrice!==undefined&&env.money(lineInput.goldPrice,'销售金价')!==entry.sell_rate)env.fail('锁价销售金价不能修改');
|
||||||
if(lineInput.unit!==undefined&&lineInput.unit!=='g')env.fail('锁价交付必须按实际克重');
|
if(lineInput.unit!==undefined&&lineInput.unit!=='g')env.fail('锁价交付必须按实际克重');
|
||||||
const costs=Calc.priceLockCost({lockedQuantity:grams(entry.locked_mg),quantity:lineInput.quantity,buyRate:yuan(entry.buy_rate),extraBuyRate:lineInput.extraMaterial?.rate}),pooled=LockPools.prepareDelivery(ledger,{...entry,id},date,costs.originalUsedMg,actor,env);
|
const costs=Calc.priceLockCost({lockedQuantity:grams(entry.locked_mg),quantity:lineInput.quantity,buyRate:yuan(entry.buy_rate),extraBuyRate:extraPool?yuan(extraPool.snapshot.averageRate):lineInput.extraMaterial?.rate}),pooled=LockPools.prepareDelivery(ledger,{...entry,id},date,costs.originalUsedMg,actor,env);
|
||||||
|
if(extraPool){if(extraPool.amount==null)env.fail('补重料池成本待补',409);costs.extraCost=extraPool.amount;costs.materialCost=costs.originalUsedCost+costs.extraCost;}
|
||||||
if(pooled)Object.assign(costs,{originalPurchase:pooled.snapshot.amount,originalUsedCost:pooled.amount,leftoverCost:pooled.leftoverCost,materialCost:pooled.amount+costs.extraCost});
|
if(pooled)Object.assign(costs,{originalPurchase:pooled.snapshot.amount,originalUsedCost:pooled.amount,leftoverCost:pooled.leftoverCost,materialCost:pooled.amount+costs.extraCost});
|
||||||
const pocket=ledger.validatePocket(lineInput.inventory?.pocket,{name:'交付货盘'}),originalStock=env.pick(lineInput.inventory?.original,['receive','stocked'],'原锁定黄金库存来源');if(pooled&&originalStock!=='stocked')env.fail('料池锁价使用已有黄金,原锁料不能重复入库');
|
const pocket=ledger.validatePocket(lineInput.inventory?.pocket,{name:'交付货盘'}),originalStock=env.pick(lineInput.inventory?.original,['receive','stocked'],'原锁定黄金库存来源');if(pooled&&originalStock!=='stocked')env.fail('料池锁价使用已有黄金,原锁料不能重复入库');
|
||||||
const stockCount=ledger.validateStockCount(pocket,lineInput.stockCount),countSource=ledger.pocket(pocket)?.countUnit==='pair'?env.pick(lineInput.inventory?.countSource,['receive','stocked'],'成品来源'):null;
|
const stockCount=ledger.validateStockCount(pocket,lineInput.stockCount),countSource=ledger.pocket(pocket)?.countUnit==='pair'?env.pick(lineInput.inventory?.countSource,['receive','stocked'],'成品来源'):null;
|
||||||
let extraStock=null,extraPayer=null,extraRate=null;
|
let extraStock=null,extraPayer=null,extraRate=null;
|
||||||
if(costs.extraMg){extraStock=env.pick(lineInput.inventory?.extra,['receive','stocked'],'补重黄金库存来源');extraPayer=env.pick(lineInput.extraMaterial?.payer,['owner','assistant','assistant2'],'补重料费付款人');extraRate=env.money(lineInput.extraMaterial.rate,'补重进货料价');if(lineInput.extraMaterial?.verified!==true)env.fail('请确认补重原料款已实际支付');}
|
if(costs.extraMg&&extraPool){if(lineInput.inventory?.extra!=='stocked')env.fail('补重使用已有料池,不可重复入库');extraStock='stocked';extraRate=extraPool.snapshot.averageRate;}
|
||||||
|
else if(costs.extraMg){env.pick(lineInput.extraMaterial?.source??'manual',['manual'],'补重料费来源');extraStock=env.pick(lineInput.inventory?.extra,['receive','stocked'],'补重黄金库存来源');extraPayer=env.pick(lineInput.extraMaterial?.payer,['owner','assistant','assistant2'],'补重料费付款人');extraRate=env.money(lineInput.extraMaterial.rate,'补重进货料价');if(lineInput.extraMaterial?.verified!==true)env.fail('请确认补重原料款已实际支付');}
|
||||||
const payers=Calc.costPayers(lineInput.costPayers);if(!pooled&&payers&&payers.material!==entry.buy_payer)env.fail('原锁价料费付款人不能修改');
|
const payers=Calc.costPayers(lineInput.costPayers);if(!pooled&&payers&&payers.material!==entry.buy_payer)env.fail('原锁价料费付款人不能修改');
|
||||||
actualLines.push({...lineInput,stockCount,name:entry.line.name,code:entry.line.code,unit:'g',pocket,pricingMode:'auto',goldPrice:yuan(entry.sell_rate),costParts:{...lineInput.costParts,material:yuan(costs.materialCost)},costMaterial:{mode:'total'},costPayers:{material:entry.buy_payer,labor:payers?.labor??lineInput.payer}});
|
actualLines.push({...lineInput,stockCount,name:entry.line.name,code:entry.line.code,unit:'g',pocket,pricingMode:'auto',goldPrice:yuan(entry.sell_rate),costParts:{...lineInput.costParts,material:yuan(costs.materialCost)},costMaterial:{mode:'total'},costPayers:{material:entry.buy_payer,labor:payers?.labor??lineInput.payer}});
|
||||||
results.push({entry,costs,pooled,pocket,stockCount,countSource,originalStock,extraStock,extraPayer,extraRate});
|
results.push({entry,costs,pooled,extraPool,pocket,stockCount,countSource,originalStock,extraStock,extraPayer,extraRate});
|
||||||
}
|
}
|
||||||
const discount=env.money(input.discount??'0','整单优惠'),lines=ledger.validateLines(actualLines,[],date,{member:ledger.entityMember('price_lock',id)??ledger.memberFor(actor)}),fees=ledger.validateFees((input.fee_items??[]).map(fee=>({...fee,status:'estimated'})));
|
const discount=env.money(input.discount??'0','整单优惠'),lines=ledger.validateLines(actualLines,[],date,{member:ledger.entityMember('price_lock',id)??ledger.memberFor(actor)}),fees=ledger.validateFees((input.fee_items??[]).map(fee=>({...fee,status:'estimated'})));
|
||||||
ledger.validateCompletedCosts(lines,fees);
|
ledger.validateCompletedCosts(lines,fees);
|
||||||
@@ -197,10 +209,12 @@ function deliver(ledger,id,input,actor,env){return atomic(ledger,()=>{
|
|||||||
const finalId=env.saveDeliveryOrder(normal).id,storedLines=ledger.rawOrder(finalId).lines,deliveryRows=[],group=randomUUID();
|
const finalId=env.saveDeliveryOrder(normal).id,storedLines=ledger.rawOrder(finalId).lines,deliveryRows=[],group=randomUUID();
|
||||||
CreditCardRates.capture(ledger,'order',finalId,lock.credit_card_rate_permille);
|
CreditCardRates.capture(ledger,'order',finalId,lock.credit_card_rate_permille);
|
||||||
for(const [index,result] of results.entries()){
|
for(const [index,result] of results.entries()){
|
||||||
const {entry,costs,pooled,pocket,stockCount,countSource,originalStock,extraStock,extraPayer,extraRate}=result,allocations=pooled?LockPools.materialAllocations(pooled.snapshot,costs.originalUsedMg):[{source:'original',quantity:costs.originalUsedMg,rate:entry.buy_rate,amount:costs.originalUsedCost,payer:entry.buy_payer}];
|
const {entry,costs,pooled,extraPool,pocket,stockCount,countSource,originalStock,extraStock,extraPayer,extraRate}=result,allocations=pooled?LockPools.materialAllocations(pooled.snapshot,costs.originalUsedMg):[{source:'original',quantity:costs.originalUsedMg,rate:entry.buy_rate,amount:costs.originalUsedCost,payer:entry.buy_payer}];
|
||||||
if(costs.extraMg)allocations.push({source:'extra',quantity:costs.extraMg,rate:extraRate,amount:costs.extraCost,payer:extraPayer});
|
if(extraPool)allocations.push(...LockPools.materialAllocations(extraPool.snapshot,costs.extraMg).map(a=>({...a,source:'extra'})));
|
||||||
|
else if(costs.extraMg)allocations.push({source:'extra',quantity:costs.extraMg,rate:extraRate,amount:costs.extraCost,payer:extraPayer});
|
||||||
const storedLine=storedLines[index];storedLine.lineId=entry.id;storedLine.materialAllocations=allocations;if(pooled)storedLine.priceLockPool={...pooled.snapshot,priceLockId:id,lineId:entry.id,line_index:index,quantity:costs.originalUsedMg,amount:pooled.amount,allocations:pooled.allocations,...(pooled.materialSources?{materialSources:pooled.materialSources}:{})};
|
const storedLine=storedLines[index];storedLine.lineId=entry.id;storedLine.materialAllocations=allocations;if(pooled)storedLine.priceLockPool={...pooled.snapshot,priceLockId:id,lineId:entry.id,line_index:index,quantity:costs.originalUsedMg,amount:pooled.amount,allocations:pooled.allocations,...(pooled.materialSources?{materialSources:pooled.materialSources}:{})};
|
||||||
if(costs.extraMg)event(ledger,lock,{date,kind:'material',source:'extra',line_index:index,amount:costs.extraCost,payer:extraPayer,quantity:costs.extraMg,rate:extraRate},actor,env);
|
if(extraPool)storedLine.priceLockExtraPool={...extraPool.snapshot,priceLockId:id,lineId:entry.id,line_index:index};
|
||||||
|
if(costs.extraMg&&!extraPool)event(ledger,lock,{date,kind:'material',source:'extra',line_index:index,amount:costs.extraCost,payer:extraPayer,quantity:costs.extraMg,rate:extraRate},actor,env);
|
||||||
if(originalStock==='receive')ledger.move({group,order:finalId,date,pocket,mg:entry.locked_mg,kind:'lock_purchase',note:lock.number+' '+entry.line.name+' 原锁定黄金入库',cost:entry.material_amount},actor);
|
if(originalStock==='receive')ledger.move({group,order:finalId,date,pocket,mg:entry.locked_mg,kind:'lock_purchase',note:lock.number+' '+entry.line.name+' 原锁定黄金入库',cost:entry.material_amount},actor);
|
||||||
if(extraStock==='receive')ledger.move({group,order:finalId,date,pocket,mg:costs.extraMg,kind:'lock_purchase',note:lock.number+' '+entry.line.name+' 补重黄金入库',cost:costs.extraCost},actor);
|
if(extraStock==='receive')ledger.move({group,order:finalId,date,pocket,mg:costs.extraMg,kind:'lock_purchase',note:lock.number+' '+entry.line.name+' 补重黄金入库',cost:costs.extraCost},actor);
|
||||||
// 原锁料和补重只增加黄金重量;成品对数由明确选择的来源单独入库一次。
|
// 原锁料和补重只增加黄金重量;成品对数由明确选择的来源单独入库一次。
|
||||||
@@ -214,7 +228,7 @@ function deliver(ledger,id,input,actor,env){return atomic(ledger,()=>{
|
|||||||
const delivery=LockLines.aggregateDelivery({date,total,difference},deliveryRows);
|
const delivery=LockLines.aggregateDelivery({date,total,difference},deliveryRows);
|
||||||
ledger.run("UPDATE price_locks SET status='delivered',delivery=? WHERE id=?",JSON.stringify(delivery),id);
|
ledger.run("UPDATE price_locks SET status='delivered',delivery=? WHERE id=?",JSON.stringify(delivery),id);
|
||||||
for(const result of results)if(result.pooled)LockPools.finishDelivery(ledger,{...result.entry,id},deliveryRows[result.entry.line_index],actor,env);
|
for(const result of results)if(result.pooled)LockPools.finishDelivery(ledger,{...result.entry,id},deliveryRows[result.entry.line_index],actor,env);
|
||||||
if(results.some(result=>result.pooled))MaterialPools.reconcile(ledger,date,date,actor,env,{skipJournalOrder:finalId});
|
if(results.some(result=>result.pooled||result.extraPool))MaterialPools.reconcile(ledger,date,date,actor,env,{skipJournalOrder:finalId});
|
||||||
env.completeNewOrder(finalId,date);
|
env.completeNewOrder(finalId,date);
|
||||||
// 同日加权重算可能更新行级余料分厘,保留重算后的交付快照。
|
// 同日加权重算可能更新行级余料分厘,保留重算后的交付快照。
|
||||||
const finalDelivery=ledger.one('SELECT delivery FROM price_locks WHERE id=?',id).delivery;
|
const finalDelivery=ledger.one('SELECT delivery FROM price_locks WHERE id=?',id).delivery;
|
||||||
|
|||||||
@@ -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}
|
#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='快捷标签暂未读取成功,可直接填写备注。';}
|
catch{if(request===orderNoteTagsRequest&&container===document.querySelector('[data-order-note-tags]'))container.textContent='快捷标签暂未读取成功,可直接填写备注。';}
|
||||||
}
|
}
|
||||||
function orderInternalNoteHTML(order){
|
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(){
|
function renderCreate(){
|
||||||
if(tab==='order-edit')return renderOrderEditForm();
|
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});
|
if(o.recovery_id&&typeof recoveryLinkedOrderActionsHTML==='function')actions=recoveryLinkedOrderActionsHTML(o,{reviewAllowed:owner&&!approvalPending&&o.reviewed_revision!==o.revision});
|
||||||
const costs=orderDetailCostSummary(o);
|
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>':'';
|
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 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){
|
function showAction(action){
|
||||||
|
|||||||
@@ -185,7 +185,7 @@
|
|||||||
const payers=costPayers(line.costPayers);
|
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}];
|
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){
|
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'){
|
}else if(part.key==='material'&&line.costMaterial?.mode==='pool'){
|
||||||
const pool=line.materialPool,allocations=pool?.allocations;
|
const pool=line.materialPool,allocations=pool?.allocations;
|
||||||
if(part.amount===null||!allocations?.length){
|
if(part.amount===null||!allocations?.length){
|
||||||
@@ -197,7 +197,7 @@
|
|||||||
}else if(part.key==='material'&&line.materialAllocations){
|
}else if(part.key==='material'&&line.materialAllocations){
|
||||||
const allocations=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('锁价分项料费记录无效');
|
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}:{} )}});
|
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}:{}),
|
}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});
|
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});}
|
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};
|
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){
|
function validateMaterialQuote(result,input){
|
||||||
const integer=value=>Number.isSafeInteger(value)&&value>=0,amount=value=>value===null||integer(value);
|
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('分来源料费未完整返回,请刷新料价。');
|
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){
|
async function loadMaterialQuote(entry=materialQuoteEntry){
|
||||||
if(!entry||entry!==materialQuoteEntry)return;if(entry.promise)return entry.promise;clearTimeout(materialQuoteTimer);
|
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;};
|
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 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);}
|
function materialPoolRate(value){return value==null?'待补采购':yuan(value);}
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ function collectMultiPriceLockOrderEdit(form,entry){
|
|||||||
function priceLockEditFinancialValue(input){
|
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};
|
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;
|
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)}:{})},
|
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)))};
|
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;
|
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),
|
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)},
|
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)}}],
|
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};
|
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){
|
function priceLockOrderEditHTML(entry){
|
||||||
if(entry.inputs.lines.length>1)return multiPriceLockOrderEditHTML(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','手填原锁料价']];
|
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 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){
|
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)};
|
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;
|
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 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?priceLockEditGramCost(extraMg,input.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('原锁料费尚未完整,请核对原料价与补重料价。');
|
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;
|
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){
|
function syncMultiPriceLockOrderEdit(changed='',target=null){
|
||||||
|
syncLockExtraEditControls(orderEditForm());
|
||||||
const entry=orderEditEntry,form=orderEditForm(),roots=[...form.querySelectorAll('[data-lock-edit-line]')];
|
const entry=orderEditEntry,form=orderEditForm(),roots=[...form.querySelectorAll('[data-lock-edit-line]')];
|
||||||
roots.forEach((root,index)=>{
|
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;
|
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();
|
updateOrderEditApprovalMode();
|
||||||
}
|
}
|
||||||
function syncPriceLockOrderEdit(changed='',target=null){
|
function syncPriceLockOrderEdit(changed='',target=null){
|
||||||
|
syncLockExtraEditControls(orderEditForm());
|
||||||
if(priceLockOrderEditable()&&orderEditEntry.inputs.lines.length>1)return syncMultiPriceLockOrderEdit(changed,target);
|
if(priceLockOrderEditable()&&orderEditEntry.inputs.lines.length>1)return syncMultiPriceLockOrderEdit(changed,target);
|
||||||
if(!priceLockOrderEditable())return;const form=orderEditForm();if(!form||form.dataset.priceLockEdit!=='true')return;
|
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';
|
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('input',rememberOrderEditChange);
|
||||||
document.addEventListener('change',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){
|
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;
|
const form=$('#price-lock-create-form');if(!form?.querySelector('[name="material_source"]')||typeof readMaterialPools!=='function')return;
|
||||||
if(priceLockPoolRead?.form===form)return priceLockPoolRead.promise;
|
if(priceLockPoolRead?.form===form)return priceLockPoolRead.promise;
|
||||||
const user=state.user.id;
|
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>`;
|
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 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){
|
function priceLockDeliveryInventoryHTML(lock,draft={},index=0){
|
||||||
const part=name=>`data-lock-part="${name}"`,pool=priceLockUsesPool(lock);
|
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){
|
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>`:'';
|
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(){
|
function collectPriceLockDelivery(){
|
||||||
const form=$('#price-lock-delivery-form'),get=name=>lockFormValue(form,name),roots=priceLockDeliveryRows(form),locks=priceLockLines(currentPriceLock);
|
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};
|
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};
|
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}))};
|
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';
|
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{}
|
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;}
|
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);
|
syncLine(row);
|
||||||
for(const name of ['nameType','customName','unit','pricingMode','goldPrice','cost-materialMode','cost-materialPayer'])get(name).disabled=true;
|
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;
|
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');
|
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?'原锁料费沿用料池实际分币金额;有补重时,请填写补重进货料价。':'料费按原锁进货价计算;有补重时,请先填写补重进货料价。';
|
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));}
|
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;
|
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';
|
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?'请填写本件补重料价,计算实际耗用成本。':'填写本件最终交付克重,自动计算实际耗料。';
|
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);}}
|
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 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;
|
let difference=null;
|
||||||
try{
|
try{
|
||||||
const total=LedgerCalc.orderTotal(lines.map(line=>LedgerCalc.sale(line).sale),LedgerCalc.cents(d.discount),'yuan');difference=total.total-lock.netReceived;
|
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{
|
}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 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 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});
|
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 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});
|
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}:{})}));
|
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}:{})}));
|
||||||
|
|||||||
@@ -175,11 +175,11 @@ function prepareLines(l,lines,businessDate,env,{orderId=null,member=null}={}){
|
|||||||
usages.sort((a,b)=>a.created<b.created?-1:a.created>b.created?1:a.fifo_sequence-b.fifo_sequence);for(const u of allocations(pool,usages,l))if(u.preview_index!==undefined)applyLine(lines[u.preview_index],u,pool);return lines;
|
usages.sort((a,b)=>a.created<b.created?-1:a.created>b.created?1:a.fifo_sequence-b.fifo_sequence);for(const u of allocations(pool,usages,l))if(u.preview_index!==undefined)applyLine(lines[u.preview_index],u,pool);return lines;
|
||||||
}
|
}
|
||||||
function reconcile(l,...args){return l.scope(null,()=>reconcileInternal(l,...args),null);}
|
function reconcile(l,...args){return l.scope(null,()=>reconcileInternal(l,...args),null);}
|
||||||
function reconcileInternal(l,date,actor,env,{skipJournalOrder=null,preservePriceLockIds=[]}={}){
|
function reconcileInternal(l,date,actor,env,{skipJournalOrder=null,preservePriceLockIds=[],repriceExtraPriceLockIds=[]}={}){
|
||||||
assertDate(l,date,env);ensureDay(l,date,env);const pool=readSources(l,date,env),updates=new Map();
|
assertDate(l,date,env);ensureDay(l,date,env);const pool=readSources(l,date,env),updates=new Map();
|
||||||
const preserved=new Set(preservePriceLockIds);
|
const preserved=new Set(preservePriceLockIds);
|
||||||
for(const u of allocations(pool,pool.usages.filter(u=>consumed(l,u,date)||u.kind==='priceLock'&&u.reservedPublicSubstitutionMg>0),l)){
|
for(const u of allocations(pool,pool.usages.filter(u=>consumed(l,u,date)||u.kind==='priceLock'&&u.reservedPublicSubstitutionMg>0),l)){
|
||||||
if(u.kind==='priceLock'){if(!preserved.has(u.price_lock_id))LockPools.update(l,u,pool,actor,env,{skipJournalOrder});continue;}
|
if(u.kind==='priceLock'){if(!preserved.has(u.price_lock_id)||u.line_index<0&&repriceExtraPriceLockIds.includes(u.price_lock_id))LockPools.update(l,u,pool,actor,env,{skipJournalOrder});continue;}
|
||||||
if(require('./order-after-sales').read(l,u.order_id))continue;
|
if(require('./order-after-sales').read(l,u.order_id))continue;
|
||||||
if(!updates.has(u.order_id))updates.set(u.order_id,{order:l.rawOrder(u.order_id),delta:0,changed:false});const v=updates.get(u.order_id),line=v.order.lines[u.line_index];
|
if(!updates.has(u.order_id))updates.set(u.order_id,{order:l.rawOrder(u.order_id),delta:0,changed:false});const v=updates.get(u.order_id),line=v.order.lines[u.line_index];
|
||||||
if(!line||line.costMaterial?.poolId!==date)env.fail('滚动料池与商品来源不一致',409);
|
if(!line||line.costMaterial?.poolId!==date)env.fail('滚动料池与商品来源不一致',409);
|
||||||
@@ -242,7 +242,7 @@ function repriceLegacyReturns(l,actor,env){
|
|||||||
}syncReturnSources(l,origin);
|
}syncReturnSources(l,origin);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
function rebuild(l,actor,env,{fromDate=null,skipJournalOrder=null,preservePriceLockIds=[],ensureDates=[]}={}){return withHistorical(l,()=>{
|
function rebuild(l,actor,env,{fromDate=null,skipJournalOrder=null,preservePriceLockIds=[],repriceExtraPriceLockIds=[],ensureDates=[]}={}){return withHistorical(l,()=>{
|
||||||
const previous=l.rollingRebuilding;l.rollingRebuilding=true;try{
|
const previous=l.rollingRebuilding;l.rollingRebuilding=true;try{
|
||||||
const c=config(l);if(!c?.enabled)return;
|
const c=config(l);if(!c?.enabled)return;
|
||||||
if(!fromDate||fromDate<=c.cutover){
|
if(!fromDate||fromDate<=c.cutover){
|
||||||
@@ -257,7 +257,7 @@ function rebuild(l,actor,env,{fromDate=null,skipJournalOrder=null,preservePriceL
|
|||||||
for(let i=0;i<days.length;i++){
|
for(let i=0;i<days.length;i++){
|
||||||
const d=days[i];if(fromDate&&d.date<fromDate)continue;
|
const d=days[i];if(fromDate&&d.date<fromDate)continue;
|
||||||
if(i){const prev=readPool(l,days[i-1].date,env,{internal:true,live:!fromDate||days[i-1].date>=fromDate});l.run('UPDATE material_rolling_days SET opening=? WHERE date=?',JSON.stringify({mg:prev.remainingMg,amount:prev.remainingCost,allocations:prev.remainingAllocations,pending:prev.status==='pending',...(prev.remainingMaterialGroups?{materialGroups:prev.remainingMaterialGroups}:{})}),d.date);}
|
if(i){const prev=readPool(l,days[i-1].date,env,{internal:true,live:!fromDate||days[i-1].date>=fromDate});l.run('UPDATE material_rolling_days SET opening=? WHERE date=?',JSON.stringify({mg:prev.remainingMg,amount:prev.remainingCost,allocations:prev.remainingAllocations,pending:prev.status==='pending',...(prev.remainingMaterialGroups?{materialGroups:prev.remainingMaterialGroups}:{})}),d.date);}
|
||||||
reconcile(l,d.date,actor,env,{skipJournalOrder,preservePriceLockIds});syncReturnSources(l,d.date);
|
reconcile(l,d.date,actor,env,{skipJournalOrder,preservePriceLockIds,repriceExtraPriceLockIds});syncReturnSources(l,d.date);
|
||||||
}
|
}
|
||||||
}finally{l.rollingRebuilding=previous;}
|
}finally{l.rollingRebuilding=previous;}
|
||||||
});}
|
});}
|
||||||
|
|||||||
+1
-1
@@ -117,7 +117,7 @@ function priceLockSnapshot(ledger,id){
|
|||||||
const snapshot=empty(),liable=entityMember(ledger,'price_lock',id);if(!liable)return snapshot;
|
const snapshot=empty(),liable=entityMember(ledger,'price_lock',id);if(!liable)return snapshot;
|
||||||
const reservations=LockPools.findAll(ledger,id);for(const reserved of reservations){
|
const reservations=LockPools.findAll(ledger,id);for(const reserved of reservations){
|
||||||
if(reserved.amount===null)snapshot.pending.push({member:liable,project:'锁价料池成本待补'});
|
if(reserved.amount===null)snapshot.pending.push({member:liable,project:'锁价料池成本待补'});
|
||||||
else for(const part of reserved.allocations)obligation(snapshot,'pool-lock:'+reserved.id+':'+part.payer,ledger.one('SELECT date FROM price_locks WHERE id=?',id).date,'material_usage','锁价料池预留',liable,part.payer,part.amount);
|
else for(const part of reserved.allocations)obligation(snapshot,'pool-lock:'+reserved.id+':'+part.payer,reserved.line_index<0?reserved.pool_id:ledger.one('SELECT date FROM price_locks WHERE id=?',id).date,'material_usage',reserved.line_index<0?'锁价交付补重料池':'锁价料池预留',liable,part.payer,part.amount);
|
||||||
}
|
}
|
||||||
if(reservations.length)for(const returned of ledger.rows('SELECT * FROM price_lock_pool_returns WHERE price_lock_id=? ORDER BY rowid',id)){
|
if(reservations.length)for(const returned of ledger.rows('SELECT * FROM price_lock_pool_returns WHERE price_lock_id=? ORDER BY rowid',id)){
|
||||||
if(returned.amount===null){snapshot.pending.push({member:liable,project:'锁价回料成本待补'});continue;}
|
if(returned.amount===null){snapshot.pending.push({member:liable,project:'锁价回料成本待补'});continue;}
|
||||||
|
|||||||
@@ -194,8 +194,10 @@ test('名称、备注和来源转义,助理保留申请动作且读取不会
|
|||||||
assert.match(html,/>申请修改<\/button>/);assert.match(html,/>申请补记费用<\/button>/);assert.match(html,/>申请整单退货<\/button>/);assert.match(html,/data-action="print"/);
|
assert.match(html,/>申请修改<\/button>/);assert.match(html,/>申请补记费用<\/button>/);assert.match(html,/>申请整单退货<\/button>/);assert.match(html,/data-action="print"/);
|
||||||
});
|
});
|
||||||
|
|
||||||
test('内部备注单独显眼展示并转义换行,不进入客户销售计算区',()=>{
|
test('内部备注在客户名旁只显示一次并转义换行,不进入客户销售计算区',()=>{
|
||||||
const {html}=render(order({internal_note:'内部尺寸跟进\n<img src=x onerror=1>'}),'assistant'),internal=panel(html,'内部备注(客户不可见)');
|
const note=html=>{const match=html.match(/<aside[^>]*aria-label="内部备注(客户不可见)"[^>]*>([\s\S]*?)<\/aside>/);assert.ok(match);return match[1];};
|
||||||
|
const {html}=render(order({internal_note:'内部尺寸跟进\n<img src=x onerror=1>'}),'assistant'),internal=note(html);
|
||||||
|
assert.equal((html.match(/class="detail-internal-note"/g)||[]).length,1);assert.ok(html.indexOf('detail-internal-note')>html.indexOf('order-detail-title'));assert.ok(html.indexOf('detail-internal-note')<html.indexOf('order-detail-identifiers'));
|
||||||
assert.match(internal,/内部尺寸跟进<br><img src=x onerror=1>/);assert.doesNotMatch(internal,/<img/);assert.doesNotMatch(panel(html,'销售计算'),/内部尺寸跟进|internal_note/);
|
assert.match(internal,/内部尺寸跟进<br><img src=x onerror=1>/);assert.doesNotMatch(internal,/<img/);assert.doesNotMatch(panel(html,'销售计算'),/内部尺寸跟进|internal_note/);
|
||||||
assert.match(panel(render(order()).html,'内部备注(客户不可见)'),/未填写/);
|
assert.match(note(render(order()).html),/未填写/);
|
||||||
});
|
});
|
||||||
@@ -21,7 +21,7 @@ function harness(initial=response()){
|
|||||||
function form(kind='full',values={}){
|
function form(kind='full',values={}){
|
||||||
const fieldValues={customer:'修改客户',internal_note:'测试内部备注',salesperson:'张',note:'修改后的备注',edit_reason:'核对实物后更正',edit_verified:true,...values};
|
const fieldValues={customer:'修改客户',internal_note:'测试内部备注',salesperson:'张',note:'修改后的备注',edit_reason:'核对实物后更正',edit_verified:true,...values};
|
||||||
const fields=Object.fromEntries(Object.entries(fieldValues).map(([name,value])=>[name,{name,value:typeof value==='boolean'?'on':value,checked:value===true,disabled:false,dataset:{}}]));
|
const fields=Object.fromEntries(Object.entries(fieldValues).map(([name,value])=>[name,{name,value:typeof value==='boolean'?'on':value,checked:value===true,disabled:false,dataset:{}}]));
|
||||||
const controls=Object.values(fields),submit={disabled:false,dataset:{}},retry={disabled:false,dataset:{action:'retry'}},f={id:kind==='full'?'order-form':'order-edit-meta-form',dataset:kind==='full'?{orderEdit:'true'}:kind==='lock'?{priceLockEdit:'true'}:{},querySelector(selector){if(selector==='[data-order-edit-submit]')return submit;const name=selector.match(/\[name="([^"]+)"\]/)?.[1];return fields[name]||null;},querySelectorAll(selector){if(selector.startsWith('button['))return [retry];return selector.includes('button')?[...controls,submit,retry]:controls;}};
|
const controls=Object.values(fields),submit={disabled:false,dataset:{}},retry={disabled:false,dataset:{action:'retry'}},f={id:kind==='full'?'order-form':'order-edit-meta-form',dataset:kind==='full'?{orderEdit:'true'}:kind==='lock'?{priceLockEdit:'true'}:{},querySelector(selector){if(selector==='[data-order-edit-submit]')return submit;const name=selector.match(/\[name="([^"]+)"\]/)?.[1];return fields[name]||null;},querySelectorAll(selector){if(selector==='[name="lock_extra_source"]')return [];if(selector.startsWith('button['))return [retry];return selector.includes('button')?[...controls,submit,retry]:controls;}};
|
||||||
nodes.delete('#order-form[data-order-edit="true"]');nodes.delete('#order-form');nodes.delete('#order-edit-meta-form');if(kind==='full')nodes.set('#order-form',f);nodes.set(kind==='full'?'#order-form[data-order-edit="true"]':'#order-edit-meta-form',f);context.__form=f;
|
nodes.delete('#order-form[data-order-edit="true"]');nodes.delete('#order-form');nodes.delete('#order-edit-meta-form');if(kind==='full')nodes.set('#order-form',f);nodes.set(kind==='full'?'#order-form[data-order-edit="true"]':'#order-edit-meta-form',f);context.__form=f;
|
||||||
return {f,fields,submit,retry};
|
return {f,fields,submit,retry};
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -53,3 +53,27 @@ test('混合整单退货保留手填原料与补重的不同付款人,不把
|
|||||||
const f=fixture(t);f.buy();f.enable();const pool=f.l.materialPoolDetail(D),id=f.create([f.line('合成手填补重','1','1000','0',{source:'manual',rate:'850',payer:'owner',verified:true}),f.line('合成日池黄金','1','1000','0',{source:'pool',poolId:D,revision:pool.revision})],'2000'),orderId=f.deliver(id,[{quantity:'1.2',extraMaterial:{rate:'900',payer:'assistant2',verified:true}},{quantity:'1'}],'200');
|
const f=fixture(t);f.buy();f.enable();const pool=f.l.materialPoolDetail(D),id=f.create([f.line('合成手填补重','1','1000','0',{source:'manual',rate:'850',payer:'owner',verified:true}),f.line('合成日池黄金','1','1000','0',{source:'pool',poolId:D,revision:pool.revision})],'2000'),orderId=f.deliver(id,[{quantity:'1.2',extraMaterial:{rate:'900',payer:'assistant2',verified:true}},{quantity:'1'}],'200');
|
||||||
f.run({},()=>f.l.action(orderId,'return',{date:D,verified:true,reason:'合成退回原料',returnPockets:['现货','现货']},f.actors.owner));const returned=f.l.one('SELECT allocations,amount FROM material_rolling_returns WHERE order_id=? AND line_index=0',orderId);assert.equal(returned.amount,103000);assert.deepEqual(JSON.parse(returned.allocations),[{payer:'owner',amount:85000},{payer:'assistant2',amount:18000}]);
|
f.run({},()=>f.l.action(orderId,'return',{date:D,verified:true,reason:'合成退回原料',returnPockets:['现货','现货']},f.actors.owner));const returned=f.l.one('SELECT allocations,amount FROM material_rolling_returns WHERE order_id=? AND line_index=0',orderId);assert.equal(returned.amount,103000);assert.deepEqual(JSON.parse(returned.allocations),[{payer:'owner',amount:85000},{payer:'assistant2',amount:18000}]);
|
||||||
});
|
});
|
||||||
|
test('跨日多件补重仅用交付日池,原锁冻结,个人先用、公共补足,次日冻结并回池守恒',t=>{
|
||||||
|
const f=fixture(t);f.buy('4','4000');f.enable();const originalPool=f.l.materialPoolDetail(D);
|
||||||
|
const lockId=f.create([f.line('手填原锁','1','2000','0',{source:'manual',rate:'800',payer:'assistant',verified:true}),f.line('公共原锁','1','2000','0',{source:'pool',poolId:D,revision:originalPool.revision})],'4000');
|
||||||
|
f.at(D2);const p={mode:'direct',date:D2,member:'assistant',customer:'补重测试回收',salesperson:'测试',old_lines:[{name:'旧金',incoming_weight:'0.5',melted_weight:'0.5',purity:'100'}],buy_rate:'600',buy_total:'300',payer:'assistant2',payment_account:'助理2微信',verified:true};
|
||||||
|
f.run(p,()=>f.l.createRecovery(p,f.actors.owner));const pool=f.l.materialPoolDetail(D2),extra={source:'pool',poolId:D2,revision:pool.revision};
|
||||||
|
const id=f.deliver(lockId,[{quantity:'1.5',extraMaterial:extra,inventory:{pocket:'现货',original:'receive',extra:'stocked'}},{quantity:'1.5',extraMaterial:extra,inventory:{pocket:'现货',original:'stocked',extra:'stocked'}}],'2000');
|
||||||
|
let order=f.l.detail(id);assert.deepEqual(order.lines.map(line=>line.costParts.material),[110000,150000]);assert.deepEqual(order.lines.map(line=>line.priceLockExtraPool.materialSources[0].kind),['personal_recovery','public']);
|
||||||
|
assert.equal(f.l.materialPoolDetail(D2).usedMg,500);assert.equal(f.l.materialPoolDetail(D2).personalPools.assistant.usedMg,500);assert.equal(f.l.priceLockDetail(lockId).material_events.length,1);
|
||||||
|
f.buy('1','2000');order=f.l.detail(id);assert.deepEqual(order.lines.map(line=>line.costParts.material),[110000,162500]);assert.equal(f.l.priceLockDetail(lockId).lines[1].material_amount,100000);
|
||||||
|
const own=f.l.asActor(f.actors.assistant).reportFor({date:D2,basis:'orderDate'},f.actors.assistant).ownershipBusiness.assistant;
|
||||||
|
assert.equal(own.poolMaterial.mg,2000);assert.equal(own.poolMaterial.amount,192500);
|
||||||
|
f.at(D3);f.buy('1','3000');assert.deepEqual(f.l.detail(id).lines.map(line=>line.costParts.material),[110000,162500]);
|
||||||
|
f.run({},()=>f.l.action(id,'return',{date:D3,verified:true,reason:'补重退回',returnPockets:['现货','现货']},f.actors.owner));
|
||||||
|
assert.equal(f.l.materialPoolDetail(D3).remainingMg,7000);assert.equal(f.l.materialPoolDetail(D3).remainingCost,980000);
|
||||||
|
assert.equal(f.l.rows("SELECT * FROM price_lock_events WHERE source='extra'").length,0);
|
||||||
|
});
|
||||||
|
test('改交付日把补重占用移到新日而保留原锁,重新核算并保持收付不重复',t=>{
|
||||||
|
const f=fixture(t);f.buy('4','4000');f.enable();const lockId=f.create([f.line('补重移日测试','1','2000','0',{source:'manual',rate:'800',payer:'owner',verified:true})],'2000'),pool=f.l.materialPoolDetail(D);
|
||||||
|
const id=f.deliver(lockId,[{quantity:'2',extraMaterial:{source:'pool',poolId:D,revision:pool.revision},inventory:{pocket:'现货',original:'receive',extra:'stocked'}}],'2000');
|
||||||
|
f.at(D2);f.buy('4','8000');const cash=clone(f.l.rows('SELECT * FROM price_lock_events'));
|
||||||
|
const info=f.l.orderEdit(id,f.actors.owner),input={...info.inputs,date:D2,fees_date:D2,revision:info.revision,reason:'测试交付日期更正',verified:true};
|
||||||
|
f.run(input,()=>f.l.editOrder(id,input,f.actors.owner));
|
||||||
|
const order=f.l.detail(id);assert.equal(order.lines[0].priceLockExtraPool.poolId,D2);assert.equal(order.goodsCost,230000);assert.equal(order.profit,170000);assert.equal(f.l.materialPoolDetail(D).usedMg,0);assert.equal(f.l.materialPoolDetail(D2).usedMg,1000);assert.deepEqual(clone(f.l.rows('SELECT * FROM price_lock_events')),cash);
|
||||||
|
});
|
||||||
@@ -69,3 +69,26 @@ test('补重保留手动实际购料,原料池不再扣重或造采购,退
|
|||||||
test('料池必须显式选择且启用统一结转,无料、旧日期、过期版本及重复入库被拒绝',t=>{
|
test('料池必须显式选择且启用统一结转,无料、旧日期、过期版本及重复入库被拒绝',t=>{
|
||||||
const f=fixture(t);f.buy('2','2000');const before=facts(f.l);assert.throws(()=>f.lock(),/启用统一/);assert.equal(facts(f.l),before);f.enable();const lock=f.lock(),snapshot=facts(f.l);assert.throws(()=>f.deliver(lock.id,'1.5',{inventory:{pocket:'现货',original:'receive'}}),/不能重复入库/);assert.equal(facts(f.l),snapshot);
|
const f=fixture(t);f.buy('2','2000');const before=facts(f.l);assert.throws(()=>f.lock(),/启用统一/);assert.equal(facts(f.l),before);f.enable();const lock=f.lock(),snapshot=facts(f.l);assert.throws(()=>f.deliver(lock.id,'1.5',{inventory:{pocket:'现货',original:'receive'}}),/不能重复入库/);assert.equal(facts(f.l),snapshot);
|
||||||
});
|
});
|
||||||
|
test('交付补重可使用当日料池,仅扣差重、不新增现金,同日加权及退货守恒',t=>{
|
||||||
|
const f=fixture(t);f.buy('4','4000');f.enable();const lock=f.lock('1.5');
|
||||||
|
const pool=f.l.materialPoolDetail(D),id=f.deliver(lock.id,'2',{extraMaterial:{source:'pool',poolId:D,revision:pool.revision},inventory:{pocket:'现货',original:'stocked',extra:'stocked'}}).id;
|
||||||
|
assert.equal(f.l.detail(id).goodsCost,200000);assert.equal(f.l.materialPools().current.usedMg,2000);
|
||||||
|
assert.equal(f.l.priceLockDetail(lock.id).material_events.length,0);assert.equal(f.l.rows("SELECT * FROM movements WHERE kind='lock_purchase'").length,0);
|
||||||
|
f.buy('2','4000','assistant2');const order=f.l.detail(id);assert.equal(order.goodsCost,266667);assert.equal(order.lines[0].priceLockExtraPool.quantity,500);
|
||||||
|
const own=f.l.asActor(f.actors.assistant).reportFor({date:D,basis:'orderDate'},f.actors.assistant).ownershipBusiness.assistant;
|
||||||
|
assert.equal(own.poolMaterial.mg,2000);assert.equal(own.poolMaterial.amount,266667);
|
||||||
|
f.run({},()=>f.l.action(id,'return',{date:D,verified:true,reason:'补重池料退回',returnPockets:['金料']},f.actors.owner));
|
||||||
|
assert.equal(f.l.materialPools().current.remainingMg,6000);assert.equal(f.l.materialPools().current.remainingCost,800000);
|
||||||
|
});
|
||||||
|
test('补重料池不足与过期预览不得留下预留、现金或库存',t=>{
|
||||||
|
const f=fixture(t);f.buy('2','2000');f.enable();const lock=f.lock('1.5'),before=facts(f.l),pool=f.l.materialPoolDetail(D);
|
||||||
|
assert.throws(()=>f.deliver(lock.id,'3',{extraMaterial:{source:'pool',poolId:D,revision:pool.revision},inventory:{pocket:'现货',original:'stocked',extra:'stocked'}}),/不足/);assert.equal(facts(f.l),before);
|
||||||
|
assert.throws(()=>f.deliver(lock.id,'2',{extraMaterial:{source:'pool',poolId:D,revision:pool.revision-1},inventory:{pocket:'现货',original:'stocked',extra:'stocked'}}),/变动/);assert.equal(facts(f.l),before);
|
||||||
|
});
|
||||||
|
test('补重池料改单保留分币和来源,切换手填释放差重且只记一次实际付款',t=>{
|
||||||
|
const f=fixture(t);f.buy('3','2700');f.enable();const lock=f.lock('1'),pool=f.l.materialPoolDetail(D),id=f.deliver(lock.id,'1.5',{extraMaterial:{source:'pool',poolId:D,revision:pool.revision},inventory:{pocket:'现货',original:'stocked',extra:'stocked'}}).id;
|
||||||
|
let info=f.l.orderEdit(id,f.actors.owner),input={...info.inputs,revision:info.revision,reason:'测试保留补重料池',verified:true};input.lines[0].costParts.labor='10';
|
||||||
|
f.run(input,()=>f.l.editOrder(id,input,f.actors.owner));assert.equal(f.l.detail(id).goodsCost,136000);assert.equal(f.l.priceLockDetail(lock.id).material_events.length,0);assert.equal(f.l.materialPools().current.usedMg,1500);
|
||||||
|
info=f.l.orderEdit(id,f.actors.owner);input={...info.inputs,revision:info.revision,reason:'测试切换独立购料',verified:true};input.price_lock_extra_material={source:'manual',rate:'1000',payer:'assistant2',verified:true};
|
||||||
|
f.run(input,()=>f.l.editOrder(id,input,f.actors.owner));assert.equal(f.l.detail(id).goodsCost,141000);assert.equal(f.l.detail(id).lines[0].priceLockExtraPool,undefined);assert.equal(f.l.materialPools().current.usedMg,1000);assert.equal(f.l.priceLockDetail(lock.id).material_events.filter(r=>r.source==='extra').length,1);
|
||||||
|
});
|
||||||
Reference in new issue
Block a user