Class: ReturnAuthorization

Inherits:
ActiveRecord::Base
  • Object
show all
Defined in:
app/models/return_authorization.rb

Instance Method Summary collapse

Instance Method Details

#add_variant(variant_id, quantity) ⇒ Object



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
# File 'app/models/return_authorization.rb', line 22

def add_variant(variant_id, quantity)
  order_units = self.order.inventory_units.group_by(&:variant_id)
  returned_units = self.inventory_units.group_by(&:variant_id)

  count = 0

  if returned_units[variant_id].nil? || returned_units[variant_id].size < quantity
    count = returned_units[variant_id].nil? ? 0 : returned_units[variant_id].size

    order_units[variant_id].each do |inventory_unit|
      next unless inventory_unit.return_authorization.nil? && count < quantity

      inventory_unit.return_authorization = self
      inventory_unit.save!

      count += 1
    end
  elsif returned_units[variant_id].size > quantity
    (returned_units[variant_id].size - quantity).times do |i|
      returned_units[variant_id][i].return_authorization_id = nil
      returned_units[variant_id][i].save!
    end
  end

  self.order.authorize_return! if self.inventory_units.reload.size > 0 && !self.order.awaiting_return?
end