Class: SpreeCmCommissioner::VariantAvailability::NonPermanentStockQuery

Inherits:
Object
  • Object
show all
Defined in:
app/queries/spree_cm_commissioner/variant_availability/non_permanent_stock_query.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(variant:, except_line_item_id: nil) ⇒ NonPermanentStockQuery



6
7
8
9
10
# File 'app/queries/spree_cm_commissioner/variant_availability/non_permanent_stock_query.rb', line 6

def initialize(variant:, except_line_item_id: nil)
  @variant = variant
  @except_line_item_id = except_line_item_id
  @error_message = nil
end

Instance Attribute Details

#error_messageObject (readonly)

Returns the value of attribute error_message.



4
5
6
# File 'app/queries/spree_cm_commissioner/variant_availability/non_permanent_stock_query.rb', line 4

def error_message
  @error_message
end

#except_line_item_idObject (readonly)

Returns the value of attribute except_line_item_id.



4
5
6
# File 'app/queries/spree_cm_commissioner/variant_availability/non_permanent_stock_query.rb', line 4

def except_line_item_id
  @except_line_item_id
end

#variantObject (readonly)

Returns the value of attribute variant.



4
5
6
# File 'app/queries/spree_cm_commissioner/variant_availability/non_permanent_stock_query.rb', line 4

def variant
  @variant
end

Instance Method Details

#available?(quantity) ⇒ Boolean



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'app/queries/spree_cm_commissioner/variant_availability/non_permanent_stock_query.rb', line 12

def available?(quantity)
  reserve_variants =
    Spree::LineItem
    .complete
    .select('(SUM(DISTINCT spree_stock_items.count_on_hand) - SUM(spree_line_items.quantity)) AS available_quantity')
    .joins(variant: :stock_items)
    .where(variant_id: variant.id)
    .where.not(id: except_line_item_id)
    .group(:variant_id)

  # there is a case when variant does not have any purchaces yet, it will return empty & always available true.
  # in this case, we check with stock items directly.

  available_quantity = if reserve_variants.any?
                         reserve_variants.sum(&:available_quantity)
                       else
                         variant.stock_items.sum(:count_on_hand)
                       end
  if available_quantity >= quantity
    true
  elsif available_quantity == 1
    @error_message = I18n.t('variant_availability.item_available_instock')
    false
  elsif available_quantity <= 0
    @error_message = I18n.t('variant_availability.items_out_of_stock')
    false
  else
    @error_message = I18n.t('variant_availability.items_available_instock', available_quantity: available_quantity)
    false
  end
end