Class: SpreeCmCommissioner::InventoryItems::Reset

Inherits:
Object
  • Object
show all
Extended by:
ServiceModuleThrowable
Includes:
Spree::ServiceModule::Base
Defined in:
app/services/spree_cm_commissioner/inventory_items/reset.rb

Instance Method Summary collapse

Methods included from ServiceModuleThrowable

call!

Instance Method Details

#call(inventory_item:) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'app/services/spree_cm_commissioner/inventory_items/reset.rb', line 7

def call(inventory_item:)
  max_capacity = variant_total_inventory(inventory_item)
  total_purchases = variant_total_purchases(inventory_item)
  quantity_available = [max_capacity - total_purchases, 0].max
  quantity_on_hold = variant_total_on_hold(inventory_item)

  updated = inventory_item.update(max_capacity: max_capacity, quantity_available: quantity_available, quantity_on_hold: quantity_on_hold)
  return failure(nil, :failed_to_update_inventory_item) unless updated

  reset_redis_inventory(inventory_item)

  success(nil)
end

#variant_total_inventory(inventory_item) ⇒ Object



21
22
23
24
25
26
27
28
29
# File 'app/services/spree_cm_commissioner/inventory_items/reset.rb', line 21

def variant_total_inventory(inventory_item)
  # 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(inventory_item)
  else
    inventory_item.variant.total_on_hand.to_i
  end
end

#variant_total_on_hold(inventory_item) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'app/services/spree_cm_commissioner/inventory_items/reset.rb', line 41

def variant_total_on_hold(inventory_item)
  active_hold_order_ids = SpreeCmCommissioner::InventoryHold.active_or_payment_locked.pluck(:order_id)
  return 0 if active_hold_order_ids.empty?

  scope = Spree::LineItem
          .where(order_id: active_hold_order_ids)
          .joins(variant: :inventory_items)
          .where(cm_inventory_items: { id: inventory_item.id })

  if inventory_item.permanent_stock?
    scope = scope.where('? BETWEEN spree_line_items.from_date AND spree_line_items.to_date', inventory_item.inventory_date)
  end

  scope.sum(:quantity).to_i
end

#variant_total_purchases(inventory_item) ⇒ Object



31
32
33
34
35
36
37
38
39
# File 'app/services/spree_cm_commissioner/inventory_items/reset.rb', line 31

def variant_total_purchases(inventory_item)
  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