From 383253451477a9fdbb9a95200cb2425076eef70e Mon Sep 17 00:00:00 2001 From: Diego Medeiros Date: Tue, 1 Dec 2015 18:37:56 -0300 Subject: [PATCH] Performance improvements on package generation Right now, when Solidus tries to create the packages on Coordinator, it iterates over each one of the active stock locations and skip those without the requested variants in stock. Let's suppose we have 100 different stock locations (which is my case) and the current user has 5 items on his cart. Once it tries to create the packages it triggers 500 different queries to the database. Here I try to address this issue, iterating over just the stock locations with the requested variants in stock. --- core/app/models/spree/stock/coordinator.rb | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/core/app/models/spree/stock/coordinator.rb b/core/app/models/spree/stock/coordinator.rb index 0a0d9d6b420..d19c7800742 100644 --- a/core/app/models/spree/stock/coordinator.rb +++ b/core/app/models/spree/stock/coordinator.rb @@ -55,9 +55,8 @@ def build_location_configured_packages(packages = Array.new) # # Returns an array of Package instances def build_packages(packages = Array.new) - StockLocation.active.each do |stock_location| + stock_locations_with_requested_variants.each do |stock_location| units_for_location = unallocated_inventory_units.select { |unit| stock_location.stock_item(unit.variant) } - next unless units_for_location.any? packer = build_packer(stock_location, units_for_location) packages += packer.packages end @@ -70,6 +69,15 @@ def unallocated_inventory_units inventory_units - @preallocated_inventory_units end + def stock_locations_with_requested_variants + Spree::StockLocation.active.joins(:stock_items). + where(spree_stock_items: { variant_id: unallocated_variant_ids }).uniq + end + + def unallocated_variant_ids + unallocated_inventory_units.map(&:variant_id).uniq + end + def prioritize_packages(packages) prioritizer = Prioritizer.new(inventory_units, packages) prioritizer.prioritized_packages