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,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));
l.db.exec('INSERT INTO material_rolling_returns_pending_upgrade(rowid,id,order_id,line_index,date,mg,amount,allocations,origin_pool_id,same_day,actor,created) SELECT rowid,* FROM material_rolling_returns');
l.db.exec('DROP TABLE material_rolling_returns;ALTER TABLE material_rolling_returns_pending_upgrade RENAME TO material_rolling_returns');for(constrofindexes)l.db.exec(r.sql);
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');
returnhash({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')});
functionregisterSource(l,kind,id){l.run('INSERT OR IGNORE INTO material_rolling_source_order(kind,source_id) VALUES (?,?)',kind,id);returnl.one('SELECT sequence FROM material_rolling_source_order WHERE kind=? AND source_id=?',kind,id).sequence;}
constids=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<? UNION SELECT date AS pool_id FROM material_rolling_returns WHERE date<? AND order_id IN (SELECT order_id FROM order_after_sales) ORDER BY pool_id",cutover,cutover,cutover).map(r=>r.pool_id);
constreturned=l.rows('SELECT * FROM material_rolling_returns WHERE origin_pool_id<>? AND origin_pool_id<? AND same_day=0 AND order_id NOT IN (SELECT order_id FROM order_after_sales)','',cutover);
constbalances=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)));
returnpool.purchases.flatMap(p=>parts(p).flatMap(a=>{consttake=Math.min(consumed[a.payer],a.amount);consumed[a.payer]-=take;returntake===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??p.source_sequence??0}];}));
functionfinance(l){returnnewMap(l.rows('SELECT id FROM orders ORDER BY rowid').map(({id})=>{consto=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}];}));}
l.run('INSERT INTO material_rolling_days(date,opening) VALUES (?,?)',preview.date,JSON.stringify(preview.opening));
constmigrated=newSet();for(constuofl.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)){
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());
if(previous){constpool=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));returnl.one('SELECT * FROM material_rolling_days WHERE date=?',date);
functionreturnsFor(l,date){returnl.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}));}
functionconsumed(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);}
constactual=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'}));
constusages=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??''})));
constpool=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;
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);elsel.run('DELETE FROM material_usage_parties WHERE usage_id=?',u.id);
}
for(const[id,v]ofupdates){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});}}
constfinal=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);returnfinal;
constusage=l.one('SELECT * FROM material_pool_usages WHERE order_id=? AND line_index=?',order.id,index),old=line.materialPool?.allocations??(line.materialAllocations?PARTIES.map(payer=>({payer,amount:sum(line.materialAllocations.filter(part=>part.payer===payer),'amount')})).filter(part=>part.amount>0):null);
constid=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);
for(constuofl.rows('SELECT * FROM material_pool_usages WHERE order_id=? AND active=1',order.id)){l.run('UPDATE material_pool_usages SET active=0,revision=revision+1,updated=? WHERE id=?',env.now(),u.id);l.run('INSERT INTO material_pool_events VALUES (?,?,?,?,?,?,?,?,?,?)',randomUUID(),u.pool_id,u.id,order.id,date,kind,JSON.stringify(u),JSON.stringify({...u,active:0}),actor.name,env.now());}
constlegacyRows=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)));
constdays=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));
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);
constc=config(l),origins=l.rows("SELECT DISTINCT origin_pool_id FROM material_rolling_returns WHERE origin_pool_id<>'' AND origin_pool_id<?",c.cutover).map(r=>r.origin_pool_id);
constcandidates=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));
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);elsel.run('DELETE FROM material_usage_parties WHERE usage_id=?',u.id);
repriceLegacyReturns(l,actor,env);constopening=legacyOpening(l,c.cutover,env);l.run('UPDATE material_rolling_days SET opening=? WHERE date=?',JSON.stringify(opening),c.cutover);
for(constpofopening.pools)l.run('INSERT INTO material_rolling_legacy VALUES (?,?) ON CONFLICT(pool_id) DO UPDATE SET snapshot=excluded.snapshot',p.id,JSON.stringify(p));
if(i){constprev=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);}