'use strict'; // 滚动日料池:期初结转不造采购,日终冻结不回写历史订单。 const {randomUUID,createHash}=require('node:crypto'); const Calc=require('./public/calculations'); const KEY='rolling-material-pools-v1',PARTIES=['owner','assistant','assistant2']; 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'); function initialize(l){l.db.exec(` CREATE TABLE IF NOT EXISTS material_rolling_days(date TEXT PRIMARY KEY,opening TEXT NOT NULL,snapshot TEXT NOT NULL DEFAULT '',frozen INTEGER NOT NULL DEFAULT 0,revision INTEGER NOT NULL DEFAULT 1); CREATE TABLE IF NOT EXISTS material_rolling_legacy(pool_id TEXT PRIMARY KEY,snapshot TEXT NOT NULL); CREATE TABLE IF NOT EXISTS material_rolling_source_order(sequence INTEGER PRIMARY KEY AUTOINCREMENT,kind TEXT NOT NULL,source_id TEXT NOT NULL,UNIQUE(kind,source_id)); CREATE TABLE IF NOT EXISTS material_rolling_returns(id TEXT PRIMARY KEY,order_id TEXT NOT NULL,line_index INTEGER NOT NULL,date TEXT NOT NULL,mg INTEGER NOT NULL,amount INTEGER NOT NULL,allocations TEXT NOT NULL,origin_pool_id TEXT NOT NULL,same_day INTEGER NOT NULL,actor TEXT NOT NULL,created TEXT NOT NULL,UNIQUE(order_id,line_index)); `);} function config(l){return l.meta(KEY);} function enabled(l){return !!config(l)?.enabled;} function isDay(l,date){const c=config(l);return !!c?.enabled&&date>=c.cutover;} function withHistorical(l,fn){const previous=l.rollingHistorical;l.rollingHistorical=true;try{return fn();}finally{l.rollingHistorical=previous;}} 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']; 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);} function registerSource(l,kind,id){l.run('INSERT OR IGNORE INTO material_rolling_source_order(kind,source_id) VALUES (?,?)',kind,id);return l.one('SELECT sequence FROM material_rolling_source_order WHERE kind=? AND source_id=?',kind,id).sequence;} function remainingParts(purchases,consumed){ let skip=consumed;const result=[]; for(const p of purchases)for(const part of parts(p)){const taken=Math.min(skip,part.amount);skip-=taken;if(part.amount>taken)result.push({...part,amount:part.amount-taken,source_id:part.source_id??p.id,created:part.created??p.created});} if(skip)throw new Error('料池结转资金不守恒');return result; } function legacyOpening(l,cutover,env){ const ids=l.rows("SELECT DISTINCT pool_id FROM material_purchases WHERE pool_idr.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({pool:p,usages:p.usages.filter(u=>u.active&&l.one('SELECT date FROM orders WHERE id=?',u.order_id).date({mg:v.pool.totalMg-sum(v.usages,'mg')})),'mg'),pending=frozen.some(v=>v.usages.some(u=>u.amount===null)); const grossAmount=pending?null:sum(frozen.map(v=>({amount:v.pool.totalAmount-sum(v.usages,'amount')})),'amount'); const allocations=frozen.flatMap(({pool,usages})=>{ const consumed=Object.fromEntries(PARTIES.map(payer=>[payer,sum(usages,payer+'_amount')])); return pool.purchases.flatMap(p=>parts(p).flatMap(a=>{const take=Math.min(consumed[a.payer],a.amount);consumed[a.payer]-=take;return take===a.amount?[]:[{...a,amount:a.amount-take,source_id:p.id,created:p.created,source_sequence:l.one('SELECT rowid AS n FROM material_purchases WHERE id=?',p.id).n}];})); }).sort((a,b)=>String(a.created).localeCompare(String(b.created))||a.source_sequence-b.source_sequence); // 切换后退回的旧耗用已由当日回料承接,不能再次抬高切换日结转。 const 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 adjusted=allocations.flatMap(a=>{const take=Math.min(reversed[a.payer],a.amount);reversed[a.payer]-=take;return take===a.amount?[]:[{...a,amount:a.amount-take}];}); const mg=grossMg-sum(returned,'mg'),amount=grossAmount===null?null:grossAmount-sum(returned,'amount'); return {mg,amount,allocations:adjusted,pending:pending||mg<0||amount!==null&&amount<0,pools}; } 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}; } 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){ const result=baseEnablePreview(l,query,actor,env);if(!result.canEnable)return result; const before=l.scope(null,()=>finance(l),null);l.db.exec('SAVEPOINT rolling_enable_preview'); try{enableInternal(l,result,actor??{id:'system-preview',name:'切换预览',role:'owner'},env);const after=l.scope(null,()=>finance(l),null),keys=['goodsCost','profit','settlementDue','ownerCost','total','netReceived'],relatedOrders=[]; for(const [id,b] of before){const a=after.get(id);if(keys.some(k=>a[k]!==b[k]))relatedOrders.push({id,number:b.number,date:b.date,member:b.member,before:Object.fromEntries(keys.map(k=>[k,b[k]])),after:Object.fromEntries(keys.map(k=>[k,a[k]]))});} return {...result,relatedOrders,affectedDates:[...new Set(relatedOrders.map(o=>o.date))].sort(),summary:{affectedOrderCount:relatedOrders.length,goodsDelta:relatedOrders.reduce((n,r)=>n+(r.after.goodsCost??0)-(r.before.goodsCost??0),0),profitDelta:relatedOrders.reduce((n,r)=>n+(r.after.profit??0)-(r.before.profit??0),0)}}; }finally{l.db.exec('ROLLBACK TO rolling_enable_preview');l.db.exec('RELEASE rolling_enable_preview');} } function enable(l,input,actor,env){ l.db.exec('SAVEPOINT rolling_material_enable');try{const result=enableAction(l,input,actor,env);l.db.exec('RELEASE rolling_material_enable');return result;}catch(error){l.db.exec('ROLLBACK TO rolling_material_enable');l.db.exec('RELEASE rolling_material_enable');throw error;} } function enableAction(l,input,actor,env){ if(actor?.role!=='owner')env.fail('滚动料池须由麦麦核实后启用',403); const preview=baseEnablePreview(l,input,actor,env);if(!preview.canEnable)env.fail(preview.reason,409); if(input.verified!==true||input.revision!==preview.revision)env.fail('切换依据有变动,请重新预览并确认',409); return enableInternal(l,preview,actor,env); } function enableInternal(l,preview,actor,env){ for(const p of l.rows('SELECT id FROM material_purchases ORDER BY created,rowid'))registerSource(l,'purchase',p.id); const opening=legacyOpening(l,preview.date,env); for(const pool of opening.pools)l.run('INSERT INTO material_rolling_legacy VALUES (?,?)',pool.id,JSON.stringify(pool)); l.setMeta(KEY,{enabled:true,cutover:preview.date,created:env.now(),actor:actor.name}); l.run('INSERT INTO material_rolling_days(date,opening) VALUES (?,?)',preview.date,JSON.stringify(preview.opening)); const migrated=new Set();for(const u of l.rows('SELECT u.* FROM material_pool_usages u JOIN orders o ON o.id=u.order_id WHERE o.date>=? AND u.active=1 ORDER BY u.rowid',preview.date)){ const order=l.rawOrder(u.order_id),line=order.lines[u.line_index],origin=u.pool_id; line.costMaterial={...line.costMaterial,poolId:preview.date}; l.run('UPDATE material_pool_usages SET pool_id=?,revision=revision+1,updated=? WHERE id=?',preview.date,env.now(),u.id); l.run('UPDATE orders SET lines=? WHERE id=?',JSON.stringify(order.lines),order.id); l.run('INSERT INTO material_pool_events VALUES (?,?,?,?,?,?,?,?,?,?)',randomUUID(),preview.date,u.id,u.order_id,preview.date,'切换今日统一料池',JSON.stringify(u),JSON.stringify({...u,pool_id:preview.date,origin_pool_id:origin}),actor.name,env.now()); migrated.add(order.id); } for(const id of migrated)l.touch(id); const current=reconcile(l,preview.date,actor,env);l.audit('system:rolling-material','启用滚动日料池',actor,{...preview,notice:'结转不重复登记采购、现金、实物或历史订单成本'}); return {rolling:status(l,env),current}; } function legacySnapshot(l,id){const r=l.one('SELECT snapshot FROM material_rolling_legacy WHERE pool_id=?',id);return r?JSON.parse(r.snapshot):null;} function status(l,env){const c=config(l),preview=c?.enabled?null:baseEnablePreview(l,{},null,env);return {enabled:!!c?.enabled,cutover:c?.cutover??null,canEnable:preview?.canEnable??false,reason:preview?.reason??''};} function nextOpening(l,date,env){ const previous=l.one('SELECT date FROM material_rolling_days WHERE date({...r,number:r.paper_number||r.number,allocations:JSON.parse(r.allocations),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 严格核对;普通读取不重算、不写入。 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 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 purchases=[...carry,...[...actual,...returned].sort((a,b)=>a.createdb.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)})}; } function readPool(l,date,env,{internal=false,live=false}={}){ 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)); const pending=totalAmount===null||totalMgr.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 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); } 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 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}; } 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});} usages.sort((a,b)=>a.createdb.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(!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); 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); } for(const [id,v] of updates){l.run('UPDATE orders SET lines=? WHERE id=?',JSON.stringify(v.order.lines),id);if(v.changed&&id!==skipJournalOrder){if(v.delta&&v.order.status==='delivered')l.journal(id,v.order.delivered_date||date,'滚动日料池成本调整',0,v.delta,0);if(v.delta&&v.order.status==='returned'&&l.rollingRebuilding){l.journal(id,v.order.delivered_date||date,'复核更正原耗用成本',0,v.delta,0);l.journal(id,v.order.returned_date,'复核更正退货成本冲回',0,-v.delta,0);}l.touch(id);l.dirty(v.order.date);l.audit(id,'滚动日料池自动重算',actor,{date,goodsDelta:v.delta});}} const final=readPool(l,date,env,{internal:true,live:true});l.run('UPDATE material_rolling_days SET snapshot=?,revision=revision+1 WHERE date=?',JSON.stringify(final),date);l.dirty(date);return final; } function recordReturns(l,order,date,input,actor,env){ if(!enabled(l)||datedate)env.fail('开始日期不能晚于结束日期');const c=config(l),current=readPool(l,env.today(),env); const legacyRows=l.rows('SELECT pool_id,snapshot FROM material_rolling_legacy WHERE pool_id>=? AND pool_id<=? ORDER BY pool_id DESC',from,date).map(r=>legacy().visiblePool(l,JSON.parse(r.snapshot))); const days=l.rows('SELECT date FROM material_rolling_days WHERE date>=? AND date<=? ORDER BY date DESC',from,date).map(r=>readPool(l,r.date,env)); const rows=[...days,...legacyRows];return {from,date,rows,current,rolling:status(l,env),summary:{totalMg:current.totalMg,totalAmount:current.totalAmount,usedMg:current.usedMg,remainingMg:current.remainingMg,remainingCost:current.remainingCost,shortageMg:current.shortageMg,pendingCount:current.status==='pending'?1:0,purchaseCount:current.todayPurchases.count},settlement:{legacyReadOnly:true,settlementDue:0,knownSettlementDue:0,pendingCount:current.status==='pending'?1:0,pools:[]}}; } 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); } } function repriceLegacyReturns(l,actor,env){ const c=config(l),origins=l.rows("SELECT DISTINCT origin_pool_id FROM material_rolling_returns WHERE origin_pool_id<>'' AND origin_pool_idr.origin_pool_id); for(const origin of origins){const pool=legacy().readPool(l,origin,env,{internal:true}); const candidates=pool.usages.filter(u=>u.active||l.one('SELECT id FROM material_rolling_returns WHERE order_id=? AND line_index=? AND origin_pool_id=?',u.order_id,u.line_index,origin)); for(const u of allocations(pool,candidates)){ const order=l.rawOrder(u.order_id),line=order.lines[u.line_index],old=line.costParts?.material,oldAlloc=line.materialPool?.allocations;applyLine(line,u,pool);const delta=(u.amount??0)-(old??0); l.run('UPDATE material_pool_usages SET amount=?,owner_amount=?,assistant_amount=?,revision=revision+1,updated=? WHERE id=?',u.amount,u.owner_amount,u.assistant_amount,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); l.run('UPDATE orders SET lines=? WHERE id=?',JSON.stringify(order.lines),order.id); if(delta||JSON.stringify(oldAlloc)!==JSON.stringify(line.materialPool.allocations)){ if(delta){l.journal(order.id,order.delivered_date||order.date,'历史复核金料成本调整',0,delta,0);if(order.status==='returned')l.journal(order.id,order.returned_date,'历史复核退货成本冲回',0,-delta,0);} l.touch(order.id);l.dirty(order.date);l.audit(order.id,'历史复核退货来源重算',actor,{origin,goodsDelta:delta}); } }syncReturnSources(l,origin); } } function rebuild(l,actor,env){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 days=l.rows('SELECT date,frozen FROM material_rolling_days ORDER BY date'); for(let i=0;i