cirandas.net

ref: master

plugins/orders_cycle/models/orders_cycle_plugin/item.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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
class OrdersCyclePlugin::Item < OrdersPlugin::Item

  has_one :supplier, through: :product

  # see also: repeat_product
  attr_accessor :repeat_cycle

  # OVERRIDE OrdersPlugin::Item
  belongs_to :order, class_name: '::OrdersCyclePlugin::Order', foreign_key: :order_id, touch: true
  belongs_to :sale, class_name: '::OrdersCyclePlugin::Sale', foreign_key: :order_id, touch: true
  belongs_to :purchase, class_name: '::OrdersCyclePlugin::Purchase', foreign_key: :order_id, touch: true

  # WORKAROUND for direct relationship
  belongs_to :offered_product, foreign_key: :product_id, class_name: 'OrdersCyclePlugin::OfferedProduct'
  has_many :from_products, through: :offered_product
  has_one :from_product, through: :offered_product
  has_many :to_products, through: :offered_product
  has_one :to_product, through: :offered_product
  has_many :sources_supplier_products, through: :offered_product
  has_one :sources_supplier_product, through: :offered_product
  has_many :supplier_products, through: :offered_product
  has_one :supplier_product, through: :offered_product
  has_many :suppliers, through: :offered_product
  has_one :supplier, through: :offered_product

  after_save :update_order
  after_save :change_purchase, if: :cycle
  before_destroy :remove_purchase_item, if: :cycle

  def cycle
    return nil unless defined? self.order.cycle
    self.order.cycle
  end

  # what items were selled from this item
  def selled_items
    self.order.cycle.selled_items.where(profile_id: self.consumer.id, orders_plugin_item: {product_id: self.product_id})
  end
  # what items were purchased from this item
  def purchased_items
    self.order.cycle.purchases.where(consumer_id: self.profile.id)
  end

  # override
  def repeat_product
    distributed_product = self.from_product
    return unless self.repeat_cycle and distributed_product
    self.repeat_cycle.products.where(from_products_products: {id: distributed_product.id}).first
  end

  def update_order
    self.order.create_transaction
  end

  protected

  def change_purchase
    # if we've already passed through purchases, don't change purchases
    return unless self.cycle.status == 'orders'
    # when it's draft, it handled by sale#change_purchases
    return if self.order.status == 'draft'

    if id_changed?
      self.sale.add_purchase_item self
    elsif defined? quantity_consumer_ordered_was or defined? quantity_supplier_accepted_was
      self.sale.update_purchase_item self
    end
  end

  def remove_purchase_item
    self.sale.remove_purchase_item self
  end

end