锁价支持手动料价和当日加权料池预留

This commit is contained in:
summer committed 2026-11-02 19:30:28 +08:00
1 parent 4e5a04a34e
commit 9893ecf037
22 files changed
+622 -94

No files matched your search

+12 -12
View File
@@ -3,6 +3,7 @@
const {randomUUID,createHash}=require('node:crypto');
const Calc=require('./public/calculations');
const KEY='rolling-material-pools-v1',PARTIES=['owner','assistant','assistant2'];
const LockPools=require('./price-lock-pools');
const sum=(rows,key)=>rows.reduce((n,row)=>n+(row[key]??0),0);
const hash=value=>createHash('sha256').update(JSON.stringify(value)).digest('hex');
const legacy=()=>require('./material-pools');
@@ -19,6 +20,7 @@ function withHistorical(l,fn){const previous=l.rollingHistorical;l.rollingHistor
function assertDate(l,date,env){if(enabled(l)&&!l.rollingHistorical&&date!==env.today())env.fail('已结转日期的料池已冻结,历史更正须提交麦麦复核',409);}
function dependency(l){
const tables=['material_purchases','material_purchase_shares','material_purchase_payment_origins','recovery_purchase_sources','material_pool_usages','material_usage_parties','material_rolling_days','material_rolling_returns','material_rolling_legacy','material_rolling_source_order'];
if(l.one('SELECT id FROM price_lock_pool_reservations LIMIT 1'))tables.push('price_lock_pool_reservations','price_lock_pool_returns','price_locks','material_usage_order');
return hash({config:config(l),tables:tables.map(table=>[table,l.rows('SELECT * FROM '+table+' ORDER BY rowid')]),orders:l.rows('SELECT id,revision,status,lines FROM orders ORDER BY rowid')});
}
function parts(p){return (p.allocations??[{payer:p.payer,amount:p.amount}]).filter(a=>a.amount>0);}
@@ -110,13 +112,13 @@ function consumed(l,u,date){return !!u.active||!!l.rollingRebuilding&&!!l.one('S
function readSources(l,date,env,saved=l.one('SELECT * FROM material_rolling_days WHERE date=?',date)){
const opening=saved?JSON.parse(saved.opening):nextOpening(l,date,env);
const actual=l.rows("SELECT p.*,s.sequence AS source_sequence FROM material_purchases p LEFT JOIN material_rolling_source_order s ON s.kind='purchase' AND s.source_id=p.id WHERE p.date=? AND p.deleted_at='' ORDER BY p.created,p.rowid",date).map(r=>({...legacy().actualPurchase(l,r),sourceKind:'purchase'}));
const returns=returnsFor(l,date),netReturns=returns.filter(r=>!r.sameDay);
const returns=[...returnsFor(l,date),...LockPools.returns(l,date)],netReturns=returns.filter(r=>!r.sameDay);
const carry=opening.mg?[{id:'carry:'+date,date,mg:opening.mg,amount:opening.amount,payer:opening.allocations?.[0]?.payer??'owner',allocations:opening.allocations??[],created:date+'T00:00:00.000Z',note:'以前结转',sourceKind:'carry',cashAmount:0,canEdit:false}]:[];
const returned=netReturns.map(r=>({...r,id:'return:'+r.id,payer:r.allocations[0]?.payer??'owner',sourceKind:'return',note:'退货回料',canEdit:false}));
const returned=netReturns.map(r=>({...r,id:'return:'+r.id,payer:r.allocations[0]?.payer??'owner',sourceKind:'return',note:r.note??'退货回料',canEdit:false}));
const purchases=[...carry,...[...actual,...returned].sort((a,b)=>a.created<b.created?-1:a.created>b.created?1:a.source_sequence-b.source_sequence)];
const usages=l.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,...r})=>({...r,...l.one('SELECT assistant2_amount FROM material_usage_parties WHERE usage_id=?',r.id),product:JSON.parse(lines)[r.line_index]?.name??''}));
const totalMg=opening.mg+sum(actual,'mg')+sum(netReturns,'mg'),totalAmount=opening.amount===null?null:opening.amount+sum(actual,'amount')+sum(netReturns,'amount'),active=usages.filter(r=>consumed(l,r,date)),usedMg=sum(active,'mg');
return {id:date,date,opening,actual,returns,netReturns,purchases,usages,totalMg,totalAmount,usedMg,averageRate:totalAmount!==null&&totalMg?Calc.poolMaterialAmount(totalAmount,totalMg,1000):null,revision:hash({opening,actual,returns,usages:usages.map(({lines,...r})=>r)})};
const usages=LockPools.combined(l,date,l.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,...r})=>({...r,...l.one('SELECT assistant2_amount FROM material_usage_parties WHERE usage_id=?',r.id),product:JSON.parse(lines)[r.line_index]?.name??''})));
const totalMg=opening.mg+sum(actual,'mg')+sum(netReturns,'mg'),totalAmount=opening.amount===null||netReturns.some(r=>r.amount===null)?null:opening.amount+sum(actual,'amount')+sum(netReturns,'amount'),active=usages.filter(r=>consumed(l,r,date)),usedMg=sum(active,'mg');
return {id:date,date,rolling:true,opening,actual,returns,netReturns,purchases,usages,totalMg,totalAmount,usedMg,averageRate:totalAmount!==null&&totalMg?Calc.poolMaterialAmount(totalAmount,totalMg,1000):null,revision:hash({opening,actual,returns,usages:usages.map(({lines,...r})=>r)})};
}
function readPool(l,date,env,{internal=false,live=false}={}){
const saved=l.one('SELECT * FROM material_rolling_days WHERE date=?',date);
@@ -130,11 +132,7 @@ function readPool(l,date,env,{internal=false,live=false}={}){
revision,opening,todayPurchases:{mg:sum(actual,'mg'),amount:sum(actual,'amount'),count:actual.length,items:actual},todayReturns:{mg:sum(netReturns,'mg'),amount:sum(netReturns,'amount'),count:netReturns.length,grossMg:sum(returns,'mg'),grossAmount:sum(returns,'amount'),grossCount:returns.length},returns,purchases,usages,settlements:[],settlement:{legacyReadOnly:true,settlementDue:0,assistantInventoryCredit:0,transferred:0,pending}};
return internal?pool:legacy().visiblePool(l,pool);
}
function allocations(pool,usages){
const missing=pool.totalAmount===null||sum(usages,'mg')>pool.totalMg;let mg=0,previous=0;
return usages.map(u=>{mg+=u.mg;const accumulated=missing?null:Calc.poolMaterialAmount(pool.totalAmount,pool.totalMg,mg),amount=accumulated===null?null:accumulated-previous;
const paid=amount===null?{owner_amount:null,assistant_amount:null,assistant2_amount:null}:legacy().allocatePayers(pool.purchases.filter(p=>p.amount>0),previous,amount);previous=accumulated??0;return {...u,amount,...paid};});
}
function allocations(pool,usages){return LockPools.allocate(pool,usages,legacy().allocatePayers);}
function applyLine(line,row,pool){
const a=PARTIES.map(p=>({payer:p,amount:row[p+'_amount']??0})).filter(p=>p.amount>0);if(row.amount===0&&!a.length)a.push({payer:row.zero_payer??'owner',amount:0});
line.costParts={...line.costParts,material:row.amount};line.cost=Object.values(line.costParts).some(v=>v===null)?null:sum(Object.values(line.costParts).map(amount=>({amount})),'amount');
@@ -143,14 +141,15 @@ function applyLine(line,row,pool){
function prepareLines(l,lines,businessDate,env,{orderId=null}={}){
const selected=lines.flatMap((line,index)=>line.costMaterial?.mode==='pool'?[{line,index}]:[]);if(!selected.length)return lines;assertDate(l,businessDate,env);
for(const {line} of selected){if(line.costMaterial.poolId!==businessDate)env.fail('滚动日料池须使用订单当天日期');if(line.unit!=='g'||Calc.isSilver(line.name))env.fail('日购料成本只支持按克黄金商品');}
const pool=readPool(l,businessDate,env,{internal:true}),original=l.rows('SELECT rowid AS fifo_sequence,* FROM material_pool_usages WHERE order_id=?',orderId??''),last=l.one('SELECT COALESCE(MAX(rowid),0) AS n FROM material_pool_usages').n;
const usages=pool.usages.filter(u=>u.active&&u.order_id!==orderId);for(const {line,index} of selected){const before=original.find(u=>u.line_index===index);usages.push({...before,mg:line.costMaterial?.consumptionMg??line.quantity,preview_index:index,created:before?.created??env.now(),fifo_sequence:before?.fifo_sequence??last+index+1});}
const pool=readPool(l,businessDate,env,{internal:true}),original=LockPools.decorate(l,l.rows('SELECT rowid AS fifo_sequence,* FROM material_pool_usages WHERE order_id=?',orderId??'')),last=l.one('SELECT COALESCE(MAX(sequence),0) AS n FROM material_usage_order').n;
const usages=pool.usages.filter(u=>u.active&&(!orderId||u.order_id!==orderId));for(const {line,index} of selected){const before=original.find(u=>u.line_index===index);usages.push({...before,mg:line.costMaterial?.consumptionMg??line.quantity,preview_index:index,created:before?.created??env.now(),fifo_sequence:before?.fifo_sequence??last+index+1});}
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))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 reconcileInternal(l,date,actor,env,{skipJournalOrder=null}={}){
assertDate(l,date,env);ensureDay(l,date,env);const pool=readSources(l,date,env),updates=new Map();
for(const u of allocations(pool,pool.usages.filter(u=>consumed(l,u,date)))){
if(u.kind==='priceLock'){LockPools.update(l,u,pool,actor,env,{skipJournalOrder});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(!line||line.costMaterial?.poolId!==date)env.fail('滚动料池与商品来源不一致',409);
const before=line.costParts?.material,oldAlloc=line.materialPool?.allocations,oldRate=line.materialPool?.averageRate;
@@ -163,6 +162,7 @@ function reconcileInternal(l,date,actor,env,{skipJournalOrder=null}={}){
}
function recordReturns(l,order,date,input,actor,env){
if(!enabled(l)||date<config(l).cutover)return;assertDate(l,date,env);ensureDay(l,date,env);
if(LockPools.recordReturn(l,order,date,input,actor,env))return;
for(const [index,line] of order.lines.entries()){
const destination=input.returnPockets?.[index]??line.pocket;if(!env.selfPockets?.includes(destination)||line.unit!=='g'||Calc.isSilver(line.name))continue;
const amount=line.costParts?.material;if(!Number.isSafeInteger(amount)||amount<0)env.fail('原商品金料成本尚未核实,不能将未知金额记为退货回料',409);