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=? ORDER BY r.rowid",lockId))
if(exists(l,'material_usage_sources'))for(constrowofl.rows('SELECT u.order_id,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))
if(exists(l,'price_lock_pool_reservations'))for(constrowofl.rows('SELECT 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):[];
constreservation=l.one('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);