支持回收单修改取消、按归属人优先用料及锁价交付改单

This commit is contained in:
summer committed 2026-11-04 22:18:56 +08:00
1 parent 0e146739bc
commit 19b1b0263c
41 files changed
+1814 -203

No files matched your search

+57 -27
View File
@@ -3,7 +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 LockPools=require('./price-lock-pools'),Allocation=require('./material-pool-allocation');
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');
@@ -20,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 name FROM sqlite_master WHERE type='table' AND name='recovery_material_batches'")&&l.one('SELECT purchase_id FROM recovery_material_batches LIMIT 1'))tables.push('recovery_material_batches','material_usage_sources','material_return_sources');
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')});
}
@@ -34,6 +35,15 @@ function legacyOpening(l,cutover,env){
const ids=l.rows("SELECT DISTINCT pool_id FROM material_purchases WHERE pool_id<? AND deleted_at='' UNION SELECT DISTINCT pool_id FROM material_pool_usages WHERE pool_id<? ORDER BY pool_id",cutover,cutover).map(r=>r.pool_id);
const pools=ids.map(id=>legacy().readPool(l,id,env,{internal:true}));
const returned=l.rows('SELECT * FROM material_rolling_returns WHERE origin_pool_id<>? AND origin_pool_id<? AND same_day=0','',cutover);
if(pools.some(pool=>pool.materialGroups)){
const balances=pools.flatMap(pool=>Allocation.balances({...pool,materialGroups:pool.materialGroups??Allocation.groups(pool.purchases)},pool.usages.filter(u=>u.active&&l.one('SELECT date FROM orders WHERE id=?',u.order_id)?.date<cutover)));
const common=balances.filter(g=>g.kind==='public'),personal=balances.filter(g=>g.kind==='personal_recovery'),pending=balances.some(g=>g.status==='pending');
const mg=sum(common,'remainingMg')-sum(returned,'mg'),amount=pending?null:sum(common,'remainingCost')-sum(returned,'amount'),remaining=common.flatMap(g=>g.remainingAllocations),reversed=Object.fromEntries(PARTIES.map(p=>[p,0]));
for(const r of returned)for(const a of JSON.parse(r.allocations))reversed[a.payer]+=a.amount;
const allocations=remaining.flatMap(a=>{const n=Math.min(a.amount,reversed[a.payer]);reversed[a.payer]-=n;return a.amount===n?[]:[{...a,amount:a.amount-n}];});
const materialGroups=[{kind:'public',member:null,mg,amount,allocations,batches:common.flatMap(g=>g.remainingBatches)},...PARTIES.flatMap(member=>{const own=personal.filter(g=>g.member===member);return own.length?[{kind:'personal_recovery',member,mg:sum(own,'remainingMg'),amount:own.some(g=>g.remainingCost===null)?null:sum(own,'remainingCost'),allocations:own.flatMap(g=>g.remainingAllocations),batches:own.flatMap(g=>g.remainingBatches)}]:[];})];
return {mg,amount,allocations,materialGroups,pending:pending||mg<0||amount!==null&&amount<0,pools};
}
// 今日旧耗用会迁入新池;期初只扣冻结的历史耗用,不能先扣今日用量再迁入扣第二次。
const frozen=pools.map(p=>({pool:p,usages:p.usages.filter(u=>u.active&&l.one('SELECT date FROM orders WHERE id=?',u.order_id).date<cutover)}));
const grossMg=sum(frozen.map(v=>({mg:v.pool.totalMg-sum(v.usages,'mg')})),'mg'),pending=frozen.some(v=>v.usages.some(u=>u.amount===null));
@@ -52,7 +62,7 @@ function baseEnablePreview(l,query,actor,env){
const date=env.day(query.date??env.today()),c=config(l),opening=legacyOpening(l,date,env);
const affected=l.rows('SELECT DISTINCT u.order_id FROM material_pool_usages u JOIN orders o ON o.id=u.order_id WHERE o.date>=? AND u.active=1',date);
const reason=c?.enabled?'滚动料池已经启用':date!==env.today()?'请从当前营业日启用':opening.pending||opening.amount===null?'历史料池存在待补成本或负余料,请先核实后切换':'';
return {date,revision:dependency(l),canEnable:!reason,reason,opening:{mg:opening.mg,amount:opening.amount,allocations:opening.allocations},affectedOrderCount:affected.length};
return {date,revision:dependency(l),canEnable:!reason,reason,opening:{mg:opening.mg,amount:opening.amount,allocations:opening.allocations,...(opening.materialGroups?{materialGroups:opening.materialGroups}:{})},affectedOrderCount:affected.length};
}
function finance(l){return new Map(l.rows('SELECT id FROM orders ORDER BY rowid').map(({id})=>{const o=l.detail(id);return [id,{id,number:o.paper_number||o.number,date:o.date,member:o.member,goodsCost:o.goodsCost,profit:o.profit,settlementDue:o.settlementDue,ownerCost:o.ownerCost,total:o.total,netReceived:o.netReceived}];}));}
function previewEnable(l,query,actor,env){
@@ -96,7 +106,7 @@ function nextOpening(l,date,env){
const previous=l.one('SELECT date FROM material_rolling_days WHERE date<? ORDER BY date DESC LIMIT 1',date);
if(!previous)return legacyOpening(l,config(l).cutover,env);
const pool=readPool(l,previous.date,env,{internal:true});
return {mg:pool.remainingMg,amount:pool.remainingCost,allocations:pool.remainingAllocations,pending:pool.status==='pending'};
return {mg:pool.remainingMg,amount:pool.remainingCost,allocations:pool.remainingAllocations,pending:pool.status==='pending',...(pool.remainingMaterialGroups?{materialGroups:pool.remainingMaterialGroups}:{})};
}
function ensureDay(l,date,env){
const current=l.one('SELECT * FROM material_rolling_days WHERE date=?',date);if(current)return current;
@@ -105,7 +115,7 @@ function ensureDay(l,date,env){
if(previous){const pool=readPool(l,previous.date,env,{internal:true});l.run('UPDATE material_rolling_days SET snapshot=?,frozen=1 WHERE date=?',JSON.stringify(pool),previous.date);}
l.run('INSERT INTO material_rolling_days(date,opening) VALUES (?,?)',date,JSON.stringify(opening));return l.one('SELECT * FROM material_rolling_days WHERE date=?',date);
}
function returnsFor(l,date){return l.rows("SELECT r.*,s.sequence AS source_sequence,o.number,o.paper_number,o.date AS order_date FROM material_rolling_returns r JOIN orders o ON o.id=r.order_id LEFT JOIN material_rolling_source_order s ON s.kind='return' AND s.source_id=r.id WHERE r.date=? ORDER BY r.created,r.rowid",date).map(r=>({...r,number:r.paper_number||r.number,allocations:JSON.parse(r.allocations),sameDay:!!r.same_day,cashAmount:0}));}
function returnsFor(l,date){return l.rows("SELECT r.*,s.sequence AS source_sequence,o.number,o.paper_number,o.date AS order_date FROM material_rolling_returns r JOIN orders o ON o.id=r.order_id LEFT JOIN material_rolling_source_order s ON s.kind='return' AND s.source_id=r.id WHERE r.date=? ORDER BY r.created,r.rowid",date).map(r=>({...r,number:r.paper_number||r.number,allocations:JSON.parse(r.allocations),...(Allocation.returnSources(l,'order',r.id)?{materialSources:Allocation.returnSources(l,'order',r.id)}:{}),sameDay:!!r.same_day,cashAmount:0}));}
function consumed(l,u,date){return !!u.active||!!l.rollingRebuilding&&!!l.one('SELECT id FROM material_rolling_returns WHERE order_id=? AND line_index=? AND origin_pool_id=? AND date>? AND same_day=0',u.order_id,u.line_index,date,date);}
// 重算只读取采购、结转、回料及用量事实,不能先用旧耗用金额扣除已经更正的新资金。
// 最终余额与归属仍由 readPool 严格核对;普通读取不重算、不写入。
@@ -113,47 +123,54 @@ function readSources(l,date,env,saved=l.one('SELECT * FROM material_rolling_days
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),...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:r.note??'退货回料',canEdit:false}));
const carry=Allocation.carrySources(opening,date)??(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.flatMap(r=>Allocation.expandSource(r)).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=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 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),member:l.entityMember('order',r.order_id),...(Allocation.usageSources(l,r.id)?{materialSources:Allocation.usageSources(l,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)})};
const materialGroups=Allocation.groups(purchases),segmented=materialGroups.some(g=>g.kind==='personal_recovery'),publicGroup=materialGroups.find(g=>g.kind==='public');
return {id:date,date,rolling:true,opening,actual:segmented?actual.filter(p=>!p.materialOwner):actual,returns,netReturns,purchases:segmented?publicGroup.purchases:purchases,usages,totalMg:segmented?publicGroup.totalMg:totalMg,totalAmount:segmented?publicGroup.totalAmount:totalAmount,usedMg,averageRate:segmented?publicGroup.averageRate:totalAmount!==null&&totalMg?Calc.poolMaterialAmount(totalAmount,totalMg,1000):null,...(segmented?{materialGroups}:{}),revision:hash({opening,actual,returns,usages:usages.map(({lines,...r})=>r)})};
}
function readPool(l,date,env,{internal=false,live=false}={}){
function readPool(l,date,env,{internal=false,live=false,member=null}={}){
const saved=l.one('SELECT * FROM material_rolling_days WHERE date=?',date);
if(saved?.frozen&&saved.snapshot&&!live){const pool={...JSON.parse(saved.snapshot),frozen:true};return internal?pool:legacy().visiblePool(l,pool);}
const {opening,actual,returns,netReturns,purchases,usages,totalMg,totalAmount,usedMg,averageRate,revision}=readSources(l,date,env,saved),active=usages.filter(r=>consumed(l,r,date));
if(saved?.frozen&&saved.snapshot&&!live){let pool={...JSON.parse(saved.snapshot),frozen:true};if(member)pool=Allocation.eligible(pool,member);return internal?pool:legacy().visiblePool(l,pool);}
const source=readSources(l,date,env,saved),{opening,actual,returns,netReturns,purchases,usages,totalMg,totalAmount,usedMg,averageRate,revision}=source,active=usages.filter(r=>consumed(l,r,date));
const pending=totalAmount===null||totalMg<usedMg||active.some(r=>r.amount===null),consumedCost=pending?null:sum(active,'amount'),remainingCost=pending?null:totalAmount-consumedCost;
const funding=purchases.filter(p=>p.amount>0),remainingAllocations=pending?[]:remainingParts(funding,consumedCost);
const funding=purchases.filter(p=>p.amount>0),remainingAllocations=Allocation.enabled(source)||pending?[]:remainingParts(funding,consumedCost);
const byPayer=Object.fromEntries(PARTIES.map(payer=>{const purchased=sum(funding.flatMap(parts).filter(a=>a.payer===payer),'amount'),consumed=pending?null:sum(active,payer+'_amount');return [payer,{purchased,consumed,remaining:pending?null:purchased-consumed}];}));
const pool={id:date,date,rolling:true,frozen:!!saved?.frozen,totalMg,totalAmount,usedMg,remainingMg:Math.max(0,totalMg-usedMg),shortageMg:Math.max(0,usedMg-totalMg),consumedCost,remainingCost,remainingAllocations,byPayer,
averageRate,status:pending?'pending':!usedMg?'unused':usedMg===totalMg?'exhausted':'using',
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);
if(Allocation.enabled(source)){
const groups=Allocation.balances(source,active),common=groups.find(g=>g.kind==='public');
Object.assign(pool,{usedMg:common.usedMg,remainingMg:common.remainingMg,shortageMg:common.shortageMg,consumedCost:common.consumedCost,remainingCost:common.remainingCost,remainingAllocations:common.remainingAllocations,byPayer:common.byPayer,status:common.status,materialGroups:source.materialGroups,personalPools:Object.fromEntries(groups.filter(g=>g.kind==='personal_recovery').map(g=>[g.member,{...g,date,id:date}])),remainingMaterialGroups:Allocation.remainingGroups(source,active)});
pool.settlement.pending=common.status==='pending';
}
const result=member?Allocation.eligible(pool,member):pool;return internal?result:legacy().visiblePool(l,result);
}
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');
line.materialPool={poolId:pool.id,date:pool.date,status:row.amount===null?'pending':'allocated',amount:row.amount,quantity:row.mg,averageRate:pool.averageRate,allocations:a,revision:pool.revision,rolling:true};
line.materialPool={...(row.materialSources?{materialSources:row.materialSources}:{}),poolId:pool.id,date:pool.date,status:row.amount===null?'pending':'allocated',amount:row.amount,quantity:row.mg,averageRate:row.materialSources?(row.amount===null?null:Calc.poolMaterialAmount(row.amount,row.mg,1000)):pool.averageRate,allocations:a,revision:pool.revision,rolling:true};
}
function prepareLines(l,lines,businessDate,env,{orderId=null}={}){
function prepareLines(l,lines,businessDate,env,{orderId=null,member=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=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});}
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,member:member??(orderId?l.entityMember('order',orderId):null)??l.memberFor(l.actor),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}={}){
function reconcileInternal(l,date,actor,env,{skipJournalOrder=null,preservePriceLockIds=[]}={}){
assertDate(l,date,env);ensureDay(l,date,env);const pool=readSources(l,date,env),updates=new Map();
const preserved=new Set(preservePriceLockIds);
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(u.kind==='priceLock'){if(!preserved.has(u.price_lock_id))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;
applyLine(line,u,pool);v.delta+=(u.amount??0)-(before??0);v.changed=v.changed||before!==u.amount||oldRate!==pool.averageRate||JSON.stringify(oldAlloc)!==JSON.stringify(line.materialPool.allocations);
const before=line.costParts?.material,oldAlloc=line.materialPool?.allocations,oldRate=line.materialPool?.averageRate,oldSources=line.materialPool?.materialSources;
applyLine(line,u,pool);Allocation.saveUsage(l,u.id,u.materialSources);v.delta+=(u.amount??0)-(before??0);v.changed=v.changed||before!==u.amount||oldRate!==pool.averageRate||JSON.stringify(oldAlloc)!==JSON.stringify(line.materialPool.allocations)||JSON.stringify(oldSources)!==JSON.stringify(line.materialPool.materialSources);
l.run('UPDATE material_pool_usages SET amount=?,owner_amount=?,assistant_amount=?,revision=revision+?,updated=? WHERE id=?',u.amount,u.owner_amount,u.assistant_amount,v.changed?1:0,env.now(),u.id);
if(u.assistant2_amount!==undefined)l.run('INSERT INTO material_usage_parties VALUES (?,?) ON CONFLICT(usage_id) DO UPDATE SET assistant2_amount=excluded.assistant2_amount',u.id,u.assistant2_amount);else l.run('DELETE FROM material_usage_parties WHERE usage_id=?',u.id);
}
@@ -168,7 +185,7 @@ function recordReturns(l,order,date,input,actor,env){
const amount=line.costParts?.material;if(!Number.isSafeInteger(amount)||amount<0)env.fail('原商品金料成本尚未核实,不能将未知金额记为退货回料',409);
const usage=l.one('SELECT * FROM material_pool_usages WHERE order_id=? AND line_index=?',order.id,index),old=line.materialPool?.allocations;
const allocations=old?.length?old:[{payer:line.costPayers?.material??line.payer,amount}];if(sum(allocations,'amount')!==amount)env.fail('退货回料金料成本归属不守恒');
const id=randomUUID();l.run('INSERT INTO material_rolling_returns VALUES (?,?,?,?,?,?,?,?,?,?,?)',id,order.id,index,date,line.quantity,amount,JSON.stringify(allocations),usage?.pool_id??'',usage?.pool_id===date?1:0,actor.name,env.now());registerSource(l,'return',id);
const id=randomUUID();l.run('INSERT INTO material_rolling_returns VALUES (?,?,?,?,?,?,?,?,?,?,?)',id,order.id,index,date,line.quantity,amount,JSON.stringify(allocations),usage?.pool_id??'',usage?.pool_id===date?1:0,actor.name,env.now());registerSource(l,'return',id);Allocation.saveReturn(l,'order',id,line.materialPool?.materialSources);
}
}
function release(l,order,date,actor,env,{kind='实物退回释放'}={}){
@@ -188,7 +205,7 @@ function syncReturnSources(l,origin){
for(const r of l.rows('SELECT * FROM material_rolling_returns WHERE origin_pool_id=?',origin)){
const o=l.rawOrder(r.order_id),line=o.lines[r.line_index],amount=line.costParts?.material,allocations=line.materialPool?.allocations;
if(!Number.isSafeInteger(amount)||!allocations||sum(allocations,'amount')!==amount)throw new Error('复核后的退货回料来源无法核对');
l.run('UPDATE material_rolling_returns SET amount=?,allocations=? WHERE id=?',amount,JSON.stringify(allocations),r.id);
l.run('UPDATE material_rolling_returns SET amount=?,allocations=? WHERE id=?',amount,JSON.stringify(allocations),r.id);Allocation.saveReturn(l,'order',r.id,line.materialPool?.materialSources);
}
}
function repriceLegacyReturns(l,actor,env){
@@ -207,12 +224,25 @@ function repriceLegacyReturns(l,actor,env){
}syncReturnSources(l,origin);
}
}
function rebuild(l,actor,env){return withHistorical(l,()=>{
function rebuild(l,actor,env,{fromDate=null,skipJournalOrder=null,preservePriceLockIds=[],ensureDates=[]}={}){return withHistorical(l,()=>{
const previous=l.rollingRebuilding;l.rollingRebuilding=true;try{
const c=config(l);if(!c?.enabled)return;repriceLegacyReturns(l,actor,env);const opening=legacyOpening(l,c.cutover,env);l.run('UPDATE material_rolling_days SET opening=? WHERE date=?',JSON.stringify(opening),c.cutover);
for(const p of opening.pools)l.run('INSERT INTO material_rolling_legacy VALUES (?,?) ON CONFLICT(pool_id) DO UPDATE SET snapshot=excluded.snapshot',p.id,JSON.stringify(p));
const c=config(l);if(!c?.enabled)return;
if(!fromDate||fromDate<=c.cutover){
repriceLegacyReturns(l,actor,env);const opening=legacyOpening(l,c.cutover,env);l.run('UPDATE material_rolling_days SET opening=? WHERE date=?',JSON.stringify(opening),c.cutover);
for(const p of opening.pools)l.run('INSERT INTO material_rolling_legacy VALUES (?,?) ON CONFLICT(pool_id) DO UPDATE SET snapshot=excluded.snapshot',p.id,JSON.stringify(p));
}
for(const date of [...new Set(ensureDates)].sort())if(date>=c.cutover){
const existed=l.one('SELECT date FROM material_rolling_days WHERE date=?',date);ensureDay(l,date,env);
if(!existed&&date<env.today())l.run('UPDATE material_rolling_days SET frozen=1 WHERE date=?',date);
}
const days=l.rows('SELECT date,frozen FROM material_rolling_days ORDER BY date');
for(let i=0;i<days.length;i++){const d=days[i];if(i){const prev=readPool(l,days[i-1].date,env,{internal:true,live:true});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'}),d.date);}reconcile(l,d.date,actor,env);syncReturnSources(l,d.date);}
for(let i=0;i<days.length;i++){
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);}
reconcile(l,d.date,actor,env,{skipJournalOrder,preservePriceLockIds});syncReturnSources(l,d.date);
}
}finally{l.rollingRebuilding=previous;}
});}
module.exports={initialize,config,enabled,isDay,withHistorical,assertDate,dependency,previewEnable,enable,status,legacySnapshot,readPool,prepareLines,reconcile,recordReturns,release,list,rebuild,registerSource};
// 调用方必须先取得历史复核权限;局部重建本身不能绕过冻结检查。
function rebuildFrom(l,date,actor,env,options={}){assertDate(l,date,env);return rebuild(l,actor,env,{...options,fromDate:date});}
module.exports={initialize,config,enabled,isDay,withHistorical,assertDate,dependency,previewEnable,enable,status,legacySnapshot,readPool,prepareLines,reconcile,recordReturns,release,list,rebuild,rebuildFrom,registerSource};