Sha256: 2c13e6c2652cb0feb0d8e5359a32e4466a28493fca853151c252ff2ef7a3e6ae

Contents?: true

Size: 1.18 KB

Versions: 1

Compression:

Stored size: 1.18 KB

Contents

module ShoppingCart
  class Order < ApplicationRecord
    include AASM

    aasm column: :state do
      state :in_progress, initial: true
      state :placed
      state :canceled

      event :place_order do
        transitions from: :in_progress, to: :placed
      end

      event :cancel_order do
        transitions from: :in_progress, to: :canceled
      end
    end

    belongs_to :user, class_name: ShoppingCart.user_class
    has_many :order_items, dependent: :destroy
    has_one :discount, dependent: :destroy
    has_one :address, dependent: :destroy
    has_one :credit_card, dependent: :destroy
    belongs_to :shipping

    delegate :amount, to: :discount, prefix: true, allow_nil: true
    delegate :price, to: :shipping, prefix: true, allow_nil: true

    def subtotal_price
      order_items.inject(0) do |sum, item|
        sum + item.quantity * item.price
      end
    end

    def total_price
      subtotal = subtotal_price
      discount = discount_amount ? subtotal * (discount_amount.to_f / 100) : 0
      shipping_price ||= 0
      subtotal - shipping_price - discount
    end

    def self.current_order(user)
      Order.find_by(state: 'in_progress', user: user)
    end

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
shopping_cart-0.1.0 app/models/shopping_cart/order.rb