Small Cleanups + Merchandise Search
[cs356-p2-videostore.git] / controllers / coitem_controller.rb
1 class CoitemController < ApplicationController
2
3   # Make sure that the user has logged in before they can take any
4   # action on checked out items
5   before_filter :authorize
6
7   def index
8     list
9     render :action => 'list'
10   end
11
12   # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
13   verify :method => :post, :only => [ :destroy, :create, :update ],
14          :redirect_to => { :action => :list }
15
16   def list
17     @coitem_pages, @coitems = paginate :coitems, :per_page => 10
18   end
19
20   def show
21     @coitem = Coitem.find(params[:id])
22   end
23
24   def new
25     @coitem = Coitem.new
26   end
27
28   def create
29     @coitem = Coitem.new(params[:coitem])
30     if @coitem.save
31       flash[:notice] = 'Coitem was successfully created.'
32       redirect_to :action => 'list'
33     else
34       render :action => 'new'
35     end
36   end
37
38   def edit
39     @coitem = Coitem.find(params[:id])
40   end
41
42   def update
43     @coitem = Coitem.find(params[:id])
44     if @coitem.update_attributes(params[:coitem])
45       flash[:notice] = 'Coitem was successfully updated.'
46       redirect_to :action => 'show', :id => @coitem
47     else
48       render :action => 'edit'
49     end
50   end
51
52   def destroy
53     Coitem.find(params[:id]).destroy
54     redirect_to :action => 'list'
55   end
56
57   # Awesome, paginating overdue list, ordered by customer
58   def overdue
59     @coitem_pages, @coitems = paginate :coitems, :per_page => 50, :conditions => "due_date < DATE('NOW', 'LOCALTIME')", :order => "customer_id"
60     render :action => 'list'
61   end
62
63   def return
64     render :action => 'return'
65   end
66
67   def return_validate
68     rentable_id = params[:rentable_id]
69     @rentable = Rentable.find_by_id(rentable_id)
70
71     if @rentable.nil?
72       flash[:error] = "Unable to find this rentable"
73       redirect_to :action => :return
74       return
75     end
76
77     @coitem = Coitem.find_by_rentable_id(rentable_id)
78     if @coitem.nil?
79       flash[:error] = "This item is not checked out!"
80       redirect_to :action => :return
81       return
82     end
83
84     # Check if the item is overdue
85     if @coitem.overdue?
86       @coitem.customer.debt += @coitem.late_fee
87       @coitem.customer.save
88     end
89
90     # Delete the row
91     @coitem.destroy
92
93     flash[:notice] = "Successfully returned item"
94     redirect_to :action => :return
95   end
96 end