Sha256: 3525606b0f229c0f846532e615bebf305679f1117c8a28c1efcf219ea147e14f

Contents?: true

Size: 1.98 KB

Versions: 3

Compression:

Stored size: 1.98 KB

Contents

class TbCommerce::Cart < ActiveRecord::Base
  include TbCommerce::BelongsToUserSession

  self.table_name = 'tb_commerce_carts'
  has_many :cart_items, :inverse_of => :cart, :foreign_key => :tb_commerce_cart_id
  has_one :order, :inverse_of => :cart, :foreign_key => :tb_commerce_cart_id

  # has_many :transactions, :inverse_of => :cart, :foreign_key => :tb_commerce_cart_id
  # has_one :captured_transaction, ->{ captured }, :foreign_key => :tb_commerce_cart_id

  scope :completed, ->{ where(:is_completed => true) }
  scope :in_progress, ->{ where(:is_completed => false, :is_abandoned => false) }
  scope :abandoned, ->{ where(:is_abandoned => true) }

  # Look for carts that have outlived the configured TbCommerce.config.cart_lifespan value and mark them as abandoned
  #
  def self.check_abandoned!
    carts = in_progress.where('updated_at < ?', DateTime.now - TbCommerce.config.cart_lifespan)
    return carts.update_all(:is_abandoned => true)
  end

  # Build a short description of the cart contents
  #
  def description
    if cart_items.length == 0
      desc = "This cart is currently empty"
    elsif cart_items.length > 1
      desc = "#{cart_items.first.description} and #{cart_items.length-1} other #{'item'.pluralize(cart_items.length-1)}"
    else
      desc = cart_items.first.description
    end
    return desc
  end

  def sales_tax
    if TbCommerce.config.sales_tax > 0
      return TbCommerce.config.sales_tax * subtotal
    else
      return 0
    end
  end

  def shipping_cost
    if TbCommerce.config.flat_rate_shipping > 0
      quantity = self.cart_items.collect(&:quantity).sum()
      return quantity * TbCommerce.config.flat_rate_shipping
    else
      return 0
    end
  end

  def subtotal
    return self.cart_items.collect(&:total_price).sum()
  end

  def total_price
    return subtotal + sales_tax + shipping_cost
  end

  def cart_is_empty?
    return self.cart_items.count == 0
  end

  def user_full_name
    return self.spud_user.try(:full_name) || 'Guest'
  end

private

end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
tb_commerce-0.0.4 app/models/tb_commerce/cart.rb
tb_commerce-0.0.3 app/models/tb_commerce/cart.rb
tb_commerce-0.0.2 app/models/tb_commerce/cart.rb