锁价交付补重支持当日料池,内部备注移至客户名旁

This commit is contained in:
summer committed 2026-11-30 16:40:30 +08:00
1 parent ac9073471d
commit c5883351c1
20 files changed
+196 -66

No files matched your search

+37 -12
View File
@@ -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 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));}
// 原锁预留用非负商品行号;交付补重用 -行号-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 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){
@@ -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 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];
let mg=r.mg;if(delivery?.date===date)mg=delivery.original_used_mg;if(r.order_status==='returned'&&r.returned_date===date)mg=0;
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=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);
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 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 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);
@@ -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 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);
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;
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.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 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);
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);
@@ -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 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){
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 index=r.line_index,line=order.lines[index],destination=input.returnPockets?.[index]??line.pocket;if(!env.selfPockets?.includes(destination))env.fail('料池锁价黄金须退回自有货盘');
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);
returnRow(l,lineLock,'goods',date,delivery.original_used_mg,part.amount,part.allocations,r.pool_id,actor,env,part.materialSources);
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);
const indices=[...new Set(rows.map(r=>itemIndex(r.line_index)))];
for(const index of indices){
const line=order.lines[index],destination=input.returnPockets?.[index]??line.pocket;if(!env.selfPockets?.includes(destination))env.fail('料池锁价黄金须退回自有货盘');
const delivery=LockLines.deliveryAt(lock,index);
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){
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();
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);
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');
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);
@@ -188,4 +213,4 @@ function moveDeliveryDate(l,value,nextDate,actor,env,{skipJournalOrder=null}={})
for(const date of dates)l.dirty(date);
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};