锁价支持手动料价和当日加权料池预留
This commit is contained in:
1 parent
4e5a04a34e
commit
9893ecf037
22 files changed
+622
-94
No files matched your search
+17
-21
@@ -7,6 +7,7 @@ const Rolling=require('./rolling-material-pools');
|
||||
const PARTIES=['owner','assistant','assistant2'];
|
||||
const sum=(rows,key)=>rows.reduce((total,row)=>total+(row[key]??0),0);
|
||||
const LIMIT=100000000000;
|
||||
const LockPools=require('./price-lock-pools');
|
||||
const ALLOCATION_VERSION=2,ALLOCATION_KEY='material-pool-allocation-version';
|
||||
function initialize(ledger){
|
||||
ledger.db.exec(`
|
||||
@@ -53,6 +54,7 @@ function initialize(ledger){
|
||||
});}finally{if(foreignKeys)ledger.db.exec('PRAGMA foreign_keys=ON');}
|
||||
}
|
||||
Rolling.initialize(ledger);
|
||||
LockPools.initialize(ledger);
|
||||
}
|
||||
function atomic(ledger,fn){
|
||||
ledger.db.exec('SAVEPOINT material_pool_action');
|
||||
@@ -74,9 +76,10 @@ function readPool(ledger,id,env,{internal=false}={}){
|
||||
if(Rolling.isDay(ledger,id))return Rolling.readPool(ledger,id,env,{internal});
|
||||
if(!internal&&Rolling.enabled(ledger)){const saved=Rolling.legacySnapshot(ledger,id);if(saved)return visiblePool(ledger,saved);}
|
||||
const date=poolId(id,env),purchases=ledger.rows("SELECT * FROM material_purchases WHERE pool_id=? AND deleted_at='' ORDER BY created,rowid",date);
|
||||
const usages=ledger.rows(`SELECT u.*,u.rowid AS fifo_sequence,o.number,o.customer,o.status AS order_status,o.lines FROM material_pool_usages u JOIN orders o ON o.id=u.order_id WHERE u.pool_id=? ORDER BY u.created,u.rowid`,date)
|
||||
let usages=ledger.rows(`SELECT u.*,u.rowid AS fifo_sequence,o.number,o.customer,o.status AS order_status,o.lines FROM material_pool_usages u JOIN orders o ON o.id=u.order_id WHERE u.pool_id=? ORDER BY u.created,u.rowid`,date)
|
||||
.map(({lines,...row})=>{const third=ledger.one('SELECT assistant2_amount FROM material_usage_parties WHERE usage_id=?',row.id);return {...row,...(third?{assistant2_amount:third.assistant2_amount}:{}),product:JSON.parse(lines)[row.line_index]?.name??''};});
|
||||
purchases.splice(0,purchases.length,...purchases.map(row=>actualPurchase(ledger,row)));
|
||||
const lockReturns=LockPools.returns(ledger,date).filter(r=>!r.sameDay);purchases.push(...lockReturns);usages=LockPools.combined(ledger,date,usages);
|
||||
const settlements=ledger.rows('SELECT * FROM material_pool_settlements WHERE pool_id=? ORDER BY date,created,rowid',date);
|
||||
const active=usages.filter(row=>row.active),totalMg=sum(purchases,'mg'),totalAmount=sum(purchases,'amount'),usedMg=sum(active,'mg');
|
||||
const shortageMg=Math.max(0,usedMg-totalMg),remainingMg=Math.max(0,totalMg-usedMg),pending=shortageMg>0;
|
||||
@@ -101,11 +104,11 @@ function visiblePool(ledger,pool){
|
||||
const permissions=row=>({canEdit:!historical&&!row.recovery_id&&(!row.sourceKind||row.sourceKind==='purchase'),canRequestChange:historical&&!row.recovery_id&&(!row.sourceKind||row.sourceKind==='purchase'),ownerReviewRequired:historical});
|
||||
if(!ledger.actor||ledger.actor.role==='owner'){const purchases=pool.purchases.map(row=>({...row,...permissions(row),...(ledger.entityMember('material_purchase',row.id)?{member:ledger.entityMember('material_purchase',row.id)}:{})}));return {...pool,purchases,...(pool.rolling?{todayPurchases:{...pool.todayPurchases,items:purchases.filter(row=>row.sourceKind==='purchase')}}:{}),legacyReadOnly:true};}
|
||||
const self=ledger.memberFor(ledger.actor),own=(kind,id)=>ledger.entityMember(kind,id)===self;
|
||||
const usages=pool.usages.map(row=>own('order',row.order_id)?{...row,member:self}:{active:row.active,mg:row.mg,amount:row.amount,created:row.created,fifo_sequence:row.fifo_sequence,anonymous:true});
|
||||
const purchases=pool.purchases.map(row=>own('material_purchase',row.id)?{...row,member:self,...permissions(row)}:{id:row.id,date:row.date,mg:row.mg,amount:row.amount,payer:row.payer,shared:true,canEdit:false,canRequestChange:false,...(pool.rolling?{sourceKind:row.sourceKind,allocations:row.allocations,cashAmount:row.cashAmount}:{})});
|
||||
const usages=pool.usages.map(row=>own(row.kind==='priceLock'?'price_lock':'order',row.kind==='priceLock'?row.price_lock_id:row.order_id)?{...row,member:self}:{active:row.active,mg:row.mg,amount:row.amount,created:row.created,fifo_sequence:row.fifo_sequence,anonymous:true});
|
||||
const purchases=pool.purchases.map(row=>own('material_purchase',row.id)?{...row,member:self,...permissions(row)}:{id:row.id,date:row.date,mg:row.mg,amount:row.amount,payer:row.payer,...(row.allocations?{allocations:row.allocations}:{}),shared:true,canEdit:false,canRequestChange:false,...(pool.rolling?{sourceKind:row.sourceKind,allocations:row.allocations,cashAmount:row.cashAmount}:{})});
|
||||
// 全池重量和均价用于共同料池预估;不公开另一成员的客户、单号、产品、备注和历史结算。
|
||||
const {returns,opening,...safePool}=pool;
|
||||
return {...safePool,...(pool.rolling?{opening:{mg:opening.mg,amount:opening.amount,allocations:opening.allocations},todayPurchases:{...pool.todayPurchases,items:purchases.filter(row=>row.sourceKind==='purchase')},returns:(returns||[]).map(row=>own('order',row.order_id)?row:{id:row.id,date:row.date,mg:row.mg,amount:row.amount,sameDay:row.sameDay,allocations:row.allocations,anonymous:true})}:{}),purchases,usages,settlements:[],settlement:{legacyReadOnly:true,pending:pool.settlement.pending,settlementDue:null},legacyReadOnly:true};
|
||||
return {...safePool,...(pool.rolling?{opening:{mg:opening.mg,amount:opening.amount,allocations:opening.allocations},todayPurchases:{...pool.todayPurchases,items:purchases.filter(row=>row.sourceKind==='purchase')},returns:(returns||[]).map(row=>own(row.price_lock_id?'price_lock':'order',row.price_lock_id??row.order_id)?row:{id:row.id,date:row.date,mg:row.mg,amount:row.amount,sameDay:row.sameDay,allocations:row.allocations,anonymous:true})}:{}),purchases,usages,settlements:[],settlement:{legacyReadOnly:true,pending:pool.settlement.pending,settlementDue:null},legacyReadOnly:true};
|
||||
}
|
||||
function internalPool(ledger,id,env){return readPool(ledger,id,env,{internal:true});}
|
||||
function allIds(ledger){return ledger.rows("SELECT pool_id AS id FROM material_purchases WHERE deleted_at='' UNION SELECT pool_id AS id FROM material_pool_usages UNION SELECT pool_id AS id FROM material_pool_settlements ORDER BY id DESC").map(row=>row.id);}
|
||||
@@ -164,18 +167,7 @@ function allocatePayers(purchases,fromAmount,amount){
|
||||
if(skip||left)throw new Error('日购料垫付金额不足,无法分配料费');
|
||||
return {owner_amount:ownerAmount,assistant_amount:assistantAmount,...(includesThird?{assistant2_amount:assistant2Amount}:{}),zero_payer:zeroPayer};
|
||||
}
|
||||
function allocateUsages(pool,usages){
|
||||
const pending=sum(usages,'mg')>pool.totalMg;
|
||||
let cumulativeMg=0,previousAmount=0;
|
||||
return usages.map(usage=>{
|
||||
cumulativeMg+=usage.mg;
|
||||
const cumulativeAmount=pending?null:Calc.poolMaterialAmount(pool.totalAmount,pool.totalMg,cumulativeMg);
|
||||
const amount=pending?null:cumulativeAmount-previousAmount;
|
||||
const allocation=amount===null?{owner_amount:null,assistant_amount:null}:allocatePayers(pool.purchases,previousAmount,amount);
|
||||
previousAmount=cumulativeAmount??0;
|
||||
return {usage,amount,...allocation};
|
||||
});
|
||||
}
|
||||
function allocateUsages(pool,usages){return LockPools.allocate(pool,usages,allocatePayers).map((row,index)=>({usage:row.kind==='priceLock'?row:usages[index],...row}));}
|
||||
function prepareLines(ledger,lines,businessDate,env,{orderId=null}={}){
|
||||
if(Rolling.isDay(ledger,businessDate))return Rolling.prepareLines(ledger,lines,businessDate,env,{orderId});
|
||||
if(Rolling.enabled(ledger)&&lines.some(line=>line.costMaterial?.mode==='pool'))Rolling.assertDate(ledger,businessDate,env);
|
||||
@@ -190,12 +182,12 @@ function prepareLines(ledger,lines,businessDate,env,{orderId=null}={}){
|
||||
});
|
||||
if(!groups.size)return lines;
|
||||
// 整单修改按原行身份替换用量,原 created,rowid 保持原位;新增行与正式交付一样追加。
|
||||
const originals=orderId?ledger.rows('SELECT rowid AS fifo_sequence,* FROM material_pool_usages WHERE order_id=?',orderId):[];
|
||||
const lastSequence=ledger.one('SELECT COALESCE(MAX(rowid),0) AS value FROM material_pool_usages').value,created=env.now();
|
||||
const originals=orderId?LockPools.decorate(ledger,ledger.rows('SELECT rowid AS fifo_sequence,* FROM material_pool_usages WHERE order_id=?',orderId)):[];
|
||||
const lastSequence=ledger.one('SELECT COALESCE(MAX(sequence),0) AS value FROM material_usage_order').value,created=env.now();
|
||||
for(const [id,group] of groups){
|
||||
const pool=internalPool(ledger,id,env);
|
||||
const usages=ledger.rows('SELECT rowid AS fifo_sequence,* FROM material_pool_usages WHERE pool_id=? AND active=1 ORDER BY created,rowid',id)
|
||||
.filter(usage=>usage.order_id!==orderId);
|
||||
const usages=pool.usages.filter(usage=>usage.active)
|
||||
.filter(usage=>!orderId||usage.order_id!==orderId);
|
||||
for(const {line,index} of group){
|
||||
const original=originals.find(usage=>usage.line_index===index);
|
||||
usages.push({...original,mg:consumptionMg(line),created:original?.created??created,fifo_sequence:original?.fifo_sequence??lastSequence+index+1,preview_index:index});
|
||||
@@ -218,6 +210,7 @@ function reconcileInternal(ledger,id,date,actor,env,{skipJournalOrder=null,alloc
|
||||
const beforePool=internalPool(ledger,id,env),active=beforePool.usages.filter(row=>row.active),pending=beforePool.shortageMg>0;
|
||||
const orders=new Map();
|
||||
for(const {usage,amount,owner_amount:ownerAmount,assistant_amount:assistantAmount,assistant2_amount:assistant2Amount,zero_payer} of allocateUsages(beforePool,active)){
|
||||
if(usage.kind==='priceLock'){LockPools.update(ledger,usage,beforePool,actor,env,{skipJournalOrder});continue;}
|
||||
if(allocationOnly&&usage.amount!==amount)env.fail('历史日购料料费与加权成本不一致,升级已撤回,请维护者核对');
|
||||
if(!orders.has(usage.order_id))orders.set(usage.order_id,{order:ledger.rawOrder(usage.order_id),deltas:0,changes:[]});
|
||||
const update=orders.get(usage.order_id),line=update.order.lines[usage.line_index];
|
||||
@@ -408,6 +401,7 @@ function deliver(ledger,order,date,actor,env){
|
||||
if(ledger.one('SELECT id FROM material_pool_usages WHERE order_id=? AND line_index=?',order.id,index))env.fail('本商品已登记日购料消耗,不能重复交付',409);
|
||||
const usage={id:randomUUID(),order_id:order.id,line_index:index,pool_id:id,date,mg:consumptionMg(line),active:1,amount:null,owner_amount:null,assistant_amount:null,revision:1,created:env.now(),updated:env.now()};
|
||||
ledger.run('INSERT INTO material_pool_usages VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)',...Object.values(usage));
|
||||
LockPools.sequence(ledger,'order',usage.id);
|
||||
usageEvent(ledger,usage,null,usageValue(usage),'交付占用',date,actor,env);pools.add(id);
|
||||
});
|
||||
for(const id of pools)reconcile(ledger,id,date,actor,env,{skipJournalOrder:order.id});
|
||||
@@ -421,6 +415,7 @@ function release(ledger,order,date,actor,env,{kind='实物退回释放'}={}){
|
||||
ledger.run('UPDATE material_pool_usages SET active=0,revision=revision+1,updated=? WHERE id=?',env.now(),usage.id);
|
||||
usageEvent(ledger,usage,usageValue(usage),usageValue(next),kind,date,actor,env);pools.add(usage.pool_id);
|
||||
}
|
||||
if(ledger.one('SELECT r.id FROM price_lock_pool_reservations r JOIN price_locks p ON p.id=r.price_lock_id WHERE p.final_order_id=?',order.id))pools.add(date);
|
||||
for(const id of pools)reconcile(ledger,id,date,actor,env);
|
||||
}
|
||||
// 整单修改复用原行的消耗身份;删除、重排、换池和手填成本都留前后事件。
|
||||
@@ -451,6 +446,7 @@ function adjust(ledger,order,date,actor,env){
|
||||
}else{
|
||||
const row={id:randomUUID(),order_id:order.id,line_index:index,pool_id:id,date,mg:line.quantity,active:1,amount:null,owner_amount:null,assistant_amount:null,revision:1,created:env.now(),updated:env.now()};
|
||||
ledger.run('INSERT INTO material_pool_usages VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)',...Object.values(row));
|
||||
LockPools.sequence(ledger,'order',row.id);
|
||||
usageEvent(ledger,row,null,usageValue(row),'整单修改新增消耗',date,actor,env);consumptionChanged=true;
|
||||
}
|
||||
}
|
||||
@@ -505,4 +501,4 @@ function reporting(ledger,query,env){
|
||||
settlements:restricted?[]:ledger.rows('SELECT * FROM material_pool_settlements WHERE date>=? AND date<=? ORDER BY date,created,rowid',from,to),
|
||||
events:ledger.visibleRows('order',ledger.rows('SELECT * FROM material_pool_events WHERE date>=? AND date<=? ORDER BY date,created,rowid',from,to),'order_id').map(row=>({...row,before_value:JSON.parse(row.before_value),after_value:JSON.parse(row.after_value)}))};
|
||||
}
|
||||
module.exports={initialize,allocatePayers,prepareLine,prepareLines,readPool,visiblePool,list,purchase,purchaseDetail,editPurchase,deletePurchase,deliver,release,adjust,reassign,settle,reporting,settlement,allocationStatus,migrateAllocation,actualPurchase};
|
||||
module.exports={initialize,allocatePayers,prepareLine,prepareLines,readPool,visiblePool,list,purchase,purchaseDetail,editPurchase,deletePurchase,deliver,release,adjust,reassign,settle,reporting,settlement,allocationStatus,migrateAllocation,actualPurchase,reconcile};
|
||||
Reference in new issue
Block a user