2012-04-16 08:48:01 +02:00
|
|
|
# encoding: utf-8
|
2009-02-06 16:26:35 +01:00
|
|
|
class StockArticle < Article
|
2013-03-16 17:53:24 +01:00
|
|
|
|
2009-02-06 16:26:35 +01:00
|
|
|
has_many :stock_changes
|
|
|
|
|
2014-02-20 15:04:53 +01:00
|
|
|
scope :available, -> { undeleted.where('quantity > 0') }
|
2009-02-06 16:26:35 +01:00
|
|
|
|
2016-05-20 21:30:56 +02:00
|
|
|
validates :quantity, presence: true, numericality: {greater_than_or_equal_to: 0}
|
|
|
|
|
2009-02-12 18:32:20 +01:00
|
|
|
before_destroy :check_quantity
|
|
|
|
|
2018-10-13 16:21:37 +02:00
|
|
|
ransack_alias :quantity_available, :quantity # in-line with {StockArticleSerializer}
|
|
|
|
|
|
|
|
def self.ransackable_attributes(auth_object = nil)
|
|
|
|
super(auth_object) - %w(supplier_id) + %w(quantity)
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.ransackable_associations(auth_object = nil)
|
|
|
|
super(auth_object) - %w(supplier)
|
|
|
|
end
|
|
|
|
|
2009-02-06 16:26:35 +01:00
|
|
|
# Update the quantity of items in stock
|
|
|
|
def update_quantity!
|
|
|
|
update_attribute :quantity, stock_changes.collect(&:quantity).sum
|
|
|
|
end
|
|
|
|
|
|
|
|
# Check for unclosed orders and substract its ordered quantity
|
2012-07-31 17:37:32 +02:00
|
|
|
def quantity_available
|
2013-12-06 22:43:36 +01:00
|
|
|
quantity - quantity_ordered
|
|
|
|
end
|
|
|
|
|
|
|
|
def quantity_ordered
|
|
|
|
OrderArticle.where(article_id: id).
|
2021-02-03 20:57:53 +01:00
|
|
|
joins(:order).where(orders: {state: %w[open finished received]}).sum(:units_to_order)
|
2009-02-06 16:26:35 +01:00
|
|
|
end
|
2013-12-06 22:43:36 +01:00
|
|
|
|
2013-07-09 21:46:04 +02:00
|
|
|
def quantity_history
|
|
|
|
stock_changes.reorder('stock_changes.created_at ASC').map{|s| s.quantity}.cumulative_sum
|
|
|
|
end
|
2009-02-12 18:32:20 +01:00
|
|
|
|
2009-08-04 13:41:28 +02:00
|
|
|
def self.stock_value
|
|
|
|
available.collect { |a| a.quantity * a.gross_price }.sum
|
|
|
|
end
|
|
|
|
|
2013-03-16 17:53:24 +01:00
|
|
|
def mark_as_deleted
|
|
|
|
check_quantity
|
|
|
|
super
|
|
|
|
end
|
|
|
|
|
2009-02-12 18:32:20 +01:00
|
|
|
protected
|
|
|
|
|
|
|
|
def check_quantity
|
2013-02-11 23:37:52 +01:00
|
|
|
raise I18n.t('stockit.check.not_empty', :name => name) unless quantity == 0
|
2009-02-12 18:32:20 +01:00
|
|
|
end
|
2009-05-17 16:26:31 +02:00
|
|
|
|
|
|
|
# Overwrite Price history of Article. For StockArticles isn't it necessary.
|
|
|
|
def update_price_history
|
|
|
|
true
|
|
|
|
end
|
2009-02-06 16:26:35 +01:00
|
|
|
end
|