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:

  • variants (Array<Spree::Variant>)

    variants to check stock of

  • stock_locations (Array<Spree::StockLocation>) (defaults to: Spree::StockLocation.active)

    stock_locations to check for stock in



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

Get the backorderable stock quantities

Returns:

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

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



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_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



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