Class: Spree::Stock::Availability
- Inherits:
-
Object
- Object
- Spree::Stock::Availability
- Defined in:
- app/models/spree/stock/availability.rb
Overview
This class manages checking stock availability efficiently for a set of Variants and StockLocations.
This serves a similar role to Spree::Stock::Quantifier, but is more efficient by checking multiple variants at once.
Instance Method Summary collapse
-
#backorderable_by_stock_location_id ⇒ Hash<Integer=>Spree::StockQuantities>
Get the backorderable stock quantities.
-
#initialize(variants:, stock_locations: Spree::StockLocation.active) ⇒ Availability
constructor
A new instance of Availability.
-
#on_hand_by_stock_location_id ⇒ Hash<Integer=>Spree::StockQuantities>
Get the on_hand stock quantities.
Constructor Details
#initialize(variants:, stock_locations: Spree::StockLocation.active) ⇒ Availability
Returns a new instance of Availability.
13 14 15 16 17 |
# File 'app/models/spree/stock/availability.rb', line 13 def initialize(variants:, stock_locations: Spree::StockLocation.active) @variants = variants @variant_map = variants.index_by(&:id) @stock_locations = stock_locations end |
Instance Method Details
#backorderable_by_stock_location_id ⇒ Hash<Integer=>Spree::StockQuantities>
Get the backorderable stock quantities
39 40 41 42 43 44 45 46 47 48 49 |
# File 'app/models/spree/stock/availability.rb', line 39 def backorderable_by_stock_location_id quantities_by_location_id = backorderables.group_by(&:second).transform_values do |variant_ids| Spree::StockQuantities.new( variant_ids.map do |variant_id, _| variant = @variant_map[variant_id] [variant, Float::INFINITY] end.to_h ) end restore_location_order(quantities_by_location_id) end |
#on_hand_by_stock_location_id ⇒ Hash<Integer=>Spree::StockQuantities>
Get the on_hand stock quantities
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
# File 'app/models/spree/stock/availability.rb', line 21 def on_hand_by_stock_location_id quantities_by_location_id = counts_on_hand.to_a.group_by do |(_, stock_location_id), _| stock_location_id end.transform_values do |values| Spree::StockQuantities.new( values.map do |(variant_id, _), count| variant = @variant_map[variant_id] count = Float::INFINITY if !variant.should_track_inventory? count = 0 if count < 0 [variant, count] end.to_h ) end restore_location_order(quantities_by_location_id) end |