Class: SpreeCmCommissioner::InventoryItem

Inherits:
Base
  • Object
show all
Includes:
ProductType
Defined in:
app/models/spree_cm_commissioner/inventory_item.rb

Constant Summary

Constants included from ProductType

ProductType::PERMANENT_STOCK_PRODUCT_TYPES, ProductType::PRE_INVENTORY_DAYS, ProductType::PRODUCT_TYPES

Instance Method Summary collapse

Methods included from ProductType

#permanent_stock?, #pre_inventory_days

Instance Method Details

#active?Boolean

Returns:

  • (Boolean)


59
60
61
# File 'app/models/spree_cm_commissioner/inventory_item.rb', line 59

def active?
  inventory_date.nil? || inventory_date >= Time.zone.today
end

#adjust_quantity!(quantity) ⇒ Object

This method is only used when admin update stock



21
22
23
24
25
26
27
28
29
30
31
# File 'app/models/spree_cm_commissioner/inventory_item.rb', line 21

def adjust_quantity!(quantity)
  with_lock do
    self.max_capacity = [max_capacity + quantity, 0].max
    self.quantity_available = [quantity_available + quantity, 0].max
    save!

    # When user has been searched or booked a product, it has cached the quantity in redis,
    # So we need to update redis cache if inventory key has been created in redis
    adjust_quantity_in_redis(quantity)
  end
end

#adjust_quantity_in_redis(quantity) ⇒ Object



37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'app/models/spree_cm_commissioner/inventory_item.rb', line 37

def adjust_quantity_in_redis(quantity)
  SpreeCmCommissioner.redis_pool.with do |redis|
    cached_quantity_available = redis.get(redis_key)
    # ignore if redis doesn't exist
    return if cached_quantity_available.nil? # rubocop:disable Lint/NonLocalExitFromIterator

    script = <<~LUA
      local key = KEYS[1]
      local increment = tonumber(ARGV[1])
      local current = tonumber(redis.call('GET', key) or 0)
      local new_value = current + increment
      if new_value < 0 then
        new_value = 0
      end
      redis.call('SET', key, new_value)
      return new_value
    LUA

    redis.eval(script, keys: [redis_key], argv: [quantity])
  end
end

#redis_expired_inObject



63
64
65
66
67
# File 'app/models/spree_cm_commissioner/inventory_item.rb', line 63

def redis_expired_in
  expired_in = 31_536_000 # 1 year for normal stock
  expired_in = Time.parse(inventory_date.to_s).end_of_day.to_i - Time.zone.now.to_i if inventory_date.present?
  [expired_in, 0].max
end

#redis_keyObject



33
34
35
# File 'app/models/spree_cm_commissioner/inventory_item.rb', line 33

def redis_key
  "inventory:#{id}"
end