class Cart < ActiveRecord::Base attr_reader :currency include ActionView::Helpers::NumberHelper has_many :cart_items # Because 'has_many :cart_items, :as => :items' does not appear to work def items ; self.cart_items ; end def purchased? self.purchased_at.present? end # Add n number of this product to our cart (addition) def add(product, quantity=1) self.alter_cart_item_quantity(:add, product, quantity.to_i) end # Remove a product no matter what the quantity def remove(product) self.alter_cart_item_quantity(:set, product, 0) end # Set the total number of this product in our cart to quantity. Setting to 0 will remove the item def set_item_quantity(product, quantity) self.alter_cart_item_quantity(:set, product, quantity) end def alter_cart_item_quantity(change_type, product, quantity) item = self.items.detect{|item| item.product_id == product.id} if item if quantity >= 1 case change_type when :add then item.increment_quantity(quantity) when :set then item.quantity = quantity end else item.remove_from_cart! end else item = self.items.build(:product_id => product.id, :quantity => quantity) end item.save! end def totalf Cart.format_price(self.total()) end def total self.items.inject(0) { |sum, cart_item| sum + cart_item.price } end def shipping_weight self.items.inject(0) { |sum, cart_item| sum + cart_item.shipping_weight } end def empty? self.items.empty? end def empty! self.items.each{ |cart_item| cart_item.remove_from_cart! } end def item_count count = 0 self.items.each{|item| count += item.quantity} count end # https://cms.paypal.com/cms_content/en_US/files/developer/PP_OrderMgmt_IntegrationGuide.pdf # https://cms.paypal.com/us/cgi-bin/?cmd=_render-content&content_ID=developer/e_howto_html_Appx_websitestandard_htmlvariables def paypal_encrypted(return_url, notify_url) values = { :invoice => self.id, :notify_url => notify_url, :business => ECO['paypal']['email'], :cert_id => ECO['paypal']['cert_id'], :cmd => '_cart', :upload => 1, :weight => self.shipping_weight } self.items.each_with_index do |item, index| values.merge!({ "amount_#{index+1}" => item.unit_price, "item_name_#{index+1}" => item.name, "item_number_#{index+1}" => item.id, "quantity_#{index+1}" => item.quantity }) end encrypt_for_paypal(values) end protected def encrypt_for_paypal(values) signed = OpenSSL::PKCS7::sign(OpenSSL::X509::Certificate.new(APP_CERT_PEM), OpenSSL::PKey::RSA.new(APP_KEY_PEM, ''), values.map { |k, v| "#{k}=#{v}" }.join("\n"), [], OpenSSL::PKCS7::BINARY) OpenSSL::PKCS7::encrypt([OpenSSL::X509::Certificate.new(PAYPAL_CERT_PEM)], signed.to_der, OpenSSL::Cipher::Cipher::new("DES3"), OpenSSL::PKCS7::BINARY).to_s.gsub("\n", "") end def self.format_price(price) # WTF?! # undefined method `number_to_currency' for #