Merge branch 'master' of https://github.com/senaduka/ribica
This commit is contained in:
@@ -1,14 +1,50 @@
|
||||
class Cart < ActiveRecord::Base
|
||||
has_many :item_in_carts, -> { order "created_at" }
|
||||
belongs_to :delivery_destination
|
||||
|
||||
|
||||
def self.find_or_create(anonymous_id, user_id)
|
||||
cart = Cart.where(user_id: user_id).where(ordered: false).first
|
||||
cart ||= Cart.where(anonymous_id_string: anonymous_id).where(ordered: false).first
|
||||
safe_user_id = (user_id > 0) ? user_id : nil
|
||||
cart ||= Cart.create!(anonymous_id_string: anonymous_id, user_id: safe_user_id, ordered: false )
|
||||
cart.delivery_destination ||= DeliveryDestination.create_from_last(anonymous_id, safe_user_id);
|
||||
cart.save!
|
||||
cart = nil
|
||||
ActiveRecord::Base.transaction do
|
||||
|
||||
logged_in_user_cart = Cart.where(user_id: user_id).where(ordered: false).first
|
||||
anonymous_user_cart = Cart.where(anonymous_id_string: anonymous_id).where(ordered: false).first
|
||||
|
||||
safe_user_id = (user_id > 0) ? user_id : nil
|
||||
if safe_user_id.nil?
|
||||
cart = anonymous_user_cart || Cart.create!(anonymous_id_string: anonymous_id, user_id: safe_user_id, ordered: false )
|
||||
else
|
||||
cart = logged_in_user_cart || Cart.create!(anonymous_id_string: nil, user_id: safe_user_id, ordered: false )
|
||||
logged_in_user_cart = cart
|
||||
end
|
||||
|
||||
# add the contents of anonymous cart
|
||||
# to the logged in one on login
|
||||
if logged_in_user_cart and anonymous_user_cart
|
||||
logged_in_items = logged_in_user_cart.item_in_carts
|
||||
anonymous_user_cart.item_in_carts.each do |a_item|
|
||||
item_exists = false
|
||||
|
||||
logged_in_items.each do |l_item|
|
||||
if a_item.item_id == l_item.item_id
|
||||
l_item.count += a_item.count
|
||||
l_item.save!
|
||||
a_item.destroy
|
||||
item_exists = true
|
||||
break
|
||||
end
|
||||
end
|
||||
|
||||
unless item_exists
|
||||
a_item.cart_id = logged_in_user_cart.id
|
||||
a_item.save!
|
||||
end
|
||||
end
|
||||
|
||||
end
|
||||
cart.delivery_destination ||= DeliveryDestination.create_from_last(anonymous_id, safe_user_id);
|
||||
cart.save!
|
||||
|
||||
end
|
||||
return cart
|
||||
end
|
||||
|
||||
@@ -17,4 +53,4 @@ class Cart < ActiveRecord::Base
|
||||
cart ||= Cart.where(anonymous_id_string: anonymous_id).where(ordered: false).first
|
||||
return cart
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
Reference in New Issue
Block a user