Class: Spree::Stock::Availability

Inherits:
Object
  • Object
show all
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

Constructor Details

#initialize(variants:, stock_locations: Spree::StockLocation.active) ⇒ Availability

Returns a new instance of Availability

Parameters:



11
12
13
14
15
# File 'app/models/spree/stock/availability.rb', line 11

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_idHash<Integer=>Spree::StockQuantities>

Get the on_hand stock quantities

Returns:

  • (Hash<Integer=>Spree::StockQuantities>)

    A map of stock_location_ids to the stock quantities available in that location



36
37
38
39
40
41
42
43
44
45
# File 'app/models/spree/stock/availability.rb', line 36

def backorderable_by_stock_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
end

#on_hand_by_stock_location_idHash<Integer=>Spree::StockQuantities>

Get the on_hand stock quantities

Returns:

  • (Hash<Integer=>Spree::StockQuantities>)

    A map of stock_location_ids to the stock quantities available in that location



19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'app/models/spree/stock/availability.rb', line 19

def on_hand_by_stock_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
end