constpurchase=l.one('SELECT id,created FROM material_purchases WHERE id=?',purchaseId),recovery=l.one('SELECT id,member FROM recoveries WHERE id=?',recoveryId);
if(exists(l,'material_return_sources'))for(constreturnedofl.rows("SELECT s.sources FROM material_return_sources s JOIN price_lock_pool_returns r ON s.return_kind='lock' AND s.return_id=r.id WHERE r.price_lock_id=? AND r.line_index=? ORDER BY r.rowid",lockId,lineIndex))
if(exists(l,'material_usage_sources'))for(constrowofl.rows('SELECT u.order_id,u.line_index,o.number,s.sources FROM material_usage_sources s JOIN material_pool_usages u ON u.id=s.usage_id JOIN orders o ON o.id=u.order_id WHERE u.active=1 AND instr(s.sources,?)>0 ORDER BY u.created,u.rowid',purchaseId)){
letmg=batches(row.sources).get(purchaseId)||0;
// 一体售后保留原耗用以锁定历史成本;实物已回流的批次不能仍作为第二份已用量。
if(exists(l,'order_after_sales')&&l.one('SELECT order_id FROM order_after_sales WHERE order_id=?',row.order_id))for(constreturnedofl.rows("SELECT s.sources FROM material_return_sources s JOIN material_rolling_returns r ON s.return_kind='order' AND s.return_id=r.id WHERE r.order_id=? AND r.line_index=?",row.order_id,row.line_index))mg-=batches(returned.sources).get(purchaseId)||0;
if(exists(l,'price_lock_pool_reservations'))for(constrowofl.rows('SELECT r.id AS reservation_id,r.line_index,r.snapshot,p.id,p.final_order_id,p.number FROM price_lock_pool_reservations r JOIN price_locks p ON p.id=r.price_lock_id WHERE instr(r.snapshot,?)>0 ORDER BY r.created,r.rowid',purchaseId))
for(constrowofl.rows('SELECT u.id,s.sources FROM material_usage_sources s JOIN material_pool_usages u ON u.id=s.usage_id WHERE instr(s.sources,?)>0 ORDER BY u.rowid',purchaseId))
returncreateHash('sha256').update(JSON.stringify(names.map(name=>[name,l.rows('SELECT * FROM '+name+' ORDER BY rowid')]))).digest('hex');
}
functionownershipReason(l,order,target=null,env){
if(!exists(l,'recovery_material_batches')||!l.one('SELECT purchase_id FROM recovery_material_batches LIMIT 1'))return'';
constusages=exists(l,'material_usage_sources')?l.rows('SELECT u.pool_id,s.sources FROM material_pool_usages u JOIN material_usage_sources s ON s.usage_id=u.id WHERE u.order_id=? AND u.active=1',order.id):[];
constreservations=l.rows('SELECT r.*,p.id AS lock_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);