Decoupled carts and orders
[depot.git] / app / controllers / store_controller.rb
1 class StoreController < ApplicationController
2 def index
3 @products = Product.find_products_for_sale
4 @cart = find_cart
5 end
6
7 def add_to_cart
8 product = Product.find(params[:id])
9 @cart = find_cart
10 @current_item = @cart.add_product(product)
11 respond_to do |format|
12 format.js if request.xhr?
13 format.html {redirect_to_index}
14 end
15 rescue ActiveRecord::RecordNotFound
16 logger.error("Attempt to access invalid product #{params[:id]}" )
17 redirect_to_index('Invalid product')
18 end
19
20 def empty_cart
21 session[:cart] = nil
22 redirect_to_index unless request.xhr?
23 end
24
25 def checkout
26 @cart = find_cart
27 if @cart.items.empty?
28 redirect_to_index("Your cart is empty" )
29 else
30 @order = Order.new
31 @during_checkout = true
32 respond_to do |format|
33 format.js if request.xhr?
34 format.html
35 end
36 end
37 end
38
39 def save_order
40 @cart = find_cart
41 @order = Order.new(params[:order])
42 # @order.add_line_items_from_cart(@cart)
43 @cart.items.each do |item|
44 li = LineItem.new
45 li.product = item.product
46 li.quantity = item.quantity
47 li.total_price = item.price
48 @order.line_items << li
49 end
50 if @order.save
51 session[:cart] = nil
52 redirect_to_index("Thank you for your order")
53 else
54 render :action => 'checkout'
55 end
56 @during_checkout = false
57 end
58
59
60 private
61
62 def find_cart
63 session[:cart] ||= Cart.new
64 end
65
66 def redirect_to_index(msg = nil)
67 flash[:notice] = msg if msg
68 redirect_to :action => 'index'
69 end
70
71 end