2014-12-04 19:50:02 +01:00
|
|
|
# == Schema Information
|
|
|
|
#
|
|
|
|
# Table name: orders
|
|
|
|
#
|
2015-03-19 16:22:55 +01:00
|
|
|
# id :integer not null, primary key
|
|
|
|
# user_id :integer
|
|
|
|
# price_cents :integer
|
|
|
|
# created_at :datetime not null
|
|
|
|
# updated_at :datetime not null
|
|
|
|
# cancelled :boolean default("f")
|
2014-12-04 19:50:02 +01:00
|
|
|
#
|
|
|
|
|
2014-11-09 22:53:39 +01:00
|
|
|
class Order < ActiveRecord::Base
|
2015-01-15 00:39:34 +01:00
|
|
|
include ActionView::Helpers::TextHelper
|
|
|
|
|
2015-06-30 22:30:34 +02:00
|
|
|
after_create { self.user.increment!(:debt_cents, price_cents) }
|
2014-12-04 19:50:02 +01:00
|
|
|
|
2014-12-10 13:21:06 +01:00
|
|
|
belongs_to :user, counter_cache: true
|
2015-02-09 17:06:24 +01:00
|
|
|
has_many :order_items, dependent: :destroy
|
|
|
|
has_many :products, through: :order_items
|
2014-11-25 14:27:27 +01:00
|
|
|
|
2015-03-10 11:37:48 +01:00
|
|
|
scope :active, -> { where(cancelled: false) }
|
|
|
|
|
2014-12-04 19:50:02 +01:00
|
|
|
validates :user, presence: true
|
2015-02-09 17:06:24 +01:00
|
|
|
validates :order_items, presence: true, in_stock: true
|
2014-12-04 19:50:02 +01:00
|
|
|
|
2015-02-09 17:06:24 +01:00
|
|
|
accepts_nested_attributes_for :order_items, reject_if: proc { |oi| oi[:count].to_i <= 0 }
|
2014-11-25 02:01:57 +01:00
|
|
|
|
2015-03-12 13:25:11 +01:00
|
|
|
def price_cents
|
2015-02-09 17:06:24 +01:00
|
|
|
self.order_items.map{ |oi| oi.count * oi.product.price_cents }.sum
|
2014-12-09 10:57:38 +01:00
|
|
|
end
|
|
|
|
|
2015-03-12 13:25:11 +01:00
|
|
|
def price
|
|
|
|
self.price_cents / 100.0
|
|
|
|
end
|
|
|
|
|
2015-03-10 11:37:48 +01:00
|
|
|
def price=(_)
|
2015-03-12 13:25:11 +01:00
|
|
|
write_attribute(:price_cents, price_cents)
|
2015-03-10 11:37:48 +01:00
|
|
|
end
|
|
|
|
|
|
|
|
def cancel
|
|
|
|
return if self.cancelled
|
2015-03-19 16:22:55 +01:00
|
|
|
user.decrement!(:debt_cents, price_cents)
|
2015-03-10 11:37:48 +01:00
|
|
|
User.decrement_counter(:orders_count, user.id)
|
|
|
|
update_attribute(:cancelled, true)
|
2015-03-19 16:22:55 +01:00
|
|
|
self.order_items.each(&:cancel)
|
2015-03-10 11:37:48 +01:00
|
|
|
end
|
|
|
|
|
2015-01-15 00:39:34 +01:00
|
|
|
def to_sentence
|
2015-02-09 17:06:24 +01:00
|
|
|
self.order_items.map {
|
2015-04-04 03:38:29 +02:00
|
|
|
|oi| pluralize(oi.count, oi.product.name)
|
2015-01-15 00:39:34 +01:00
|
|
|
}.to_sentence
|
|
|
|
end
|
2015-02-12 14:39:58 +01:00
|
|
|
|
2015-03-12 13:25:11 +01:00
|
|
|
def g_order_items(products)
|
2015-02-12 14:39:58 +01:00
|
|
|
products.each do |p|
|
|
|
|
if (oi = self.order_items.select { |t| t.product == p }).size > 0
|
|
|
|
oi.first.count = [oi.first.product.stock, oi.first.count].min
|
|
|
|
else
|
|
|
|
self.order_items.build(product: p)
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|
2014-11-09 22:53:39 +01:00
|
|
|
end
|