cirandas.net

ref: master

plugins/stock/lib/ext/products_plugin/product.rb


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
require_dependency 'products_plugin/product'

module ProductsPlugin
  class Product

    attr_accessible :stored, :use_stock, :initial_stock

    has_many :stock_allocations, class_name: 'StockPlugin::Allocation'
    has_many :stock_places, through: :stock_allocations, source: :place

    scope :from_products_in_stock, -> {where("from_products_products.use_stock is ? or from_products_products.use_stock = ? or (from_products_products.stored > 0)", nil, false)}
    scope :in_stock, -> {where("products.use_stock is ? or products.use_stock = ? or (products.stored > 0)", nil, false)}

    extend CurrencyFields::ClassMethods
    has_number_with_locale :stored

    def in_stock?
      !use_stock or (stored.present? && stored > 0)
    end

    def update_stored
      self.stored = self.stock_allocations.sum(:quantity)
      save
    end

    def initial_stock= quantity
      if self.use_stock && self.stock_allocations.count == 0
        allocation = self.stock_allocations.build quantity: quantity
        allocation.save!
      end
    end
  end
end