Class: SpreeCmCommissioner::Stock::InventoryItemResetter

Inherits:
BaseInteractor
  • Object
show all
Defined in:
app/interactors/spree_cm_commissioner/stock/inventory_item_resetter.rb

Instance Method Summary collapse

Instance Method Details

#callObject



6
7
8
9
10
11
12
13
14
15
# File 'app/interactors/spree_cm_commissioner/stock/inventory_item_resetter.rb', line 6

def call
  max_capacity = variant_total_inventory
  total_purchases = variant_total_purchases
  quantity_available = [max_capacity - total_purchases, 0].max

  updated = inventory_item.update(max_capacity: max_capacity, quantity_available: quantity_available)
  return context.fail!(message: 'Failed to update inventory item', errors: inventory_item.errors.full_messages) unless updated

  clear_inventory_cache
end

#clear_inventory_cacheObject



37
38
39
40
41
# File 'app/interactors/spree_cm_commissioner/stock/inventory_item_resetter.rb', line 37

def clear_inventory_cache
  SpreeCmCommissioner.redis_pool.with do |redis|
    redis.del(inventory_item.redis_key)
  end
end

#variant_total_inventoryObject



17
18
19
20
21
22
23
24
25
# File 'app/interactors/spree_cm_commissioner/stock/inventory_item_resetter.rb', line 17

def variant_total_inventory
  # for shipment, total_on_hand is not orignal stock. shipment does subtract the stock.
  # to get desire result, we need to add to total_purchase.
  if inventory_item.variant.delivery_required?
    inventory_item.variant.total_on_hand.to_i + variant_total_purchases
  else
    inventory_item.variant.total_on_hand.to_i
  end
end

#variant_total_purchasesObject



27
28
29
30
31
32
33
34
35
# File 'app/interactors/spree_cm_commissioner/stock/inventory_item_resetter.rb', line 27

def variant_total_purchases
  scope = inventory_item.variant.complete_line_items

  if inventory_item.permanent_stock?
    scope.where('? BETWEEN from_date AND to_date', inventory_item.inventory_date).sum(:quantity).to_i
  else
    scope.sum(:quantity).to_i
  end
end