Prettify the Purchase system
[cs356-p2-videostore.git] / app / controllers / coitem_controller.rb
1 class CoitemController < ApplicationController
2   layout "admin"
3
4   # Make sure that the user has logged in before they can take any
5   # action on checked out items
6   before_filter :authorize
7
8   def index
9     render :action => 'index'
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   # We should never create new checked out items via the web interface, so remove
25   # the new and create methods.
26
27   def edit
28     @coitem = Coitem.find(params[:id])
29   end
30
31   def update
32     @coitem = Coitem.find(params[:id])
33     if @coitem.update_attributes(params[:coitem])
34       flash[:notice] = 'Coitem was successfully updated.'
35       redirect_to :action => 'show', :id => @coitem
36     else
37       render :action => 'edit'
38     end
39   end
40
41   # We should never delete a checked out item directly via the web interface, so
42   # remove the destroy method.
43
44   # Awesome, paginating overdue list, ordered by customer
45   def overdue
46     @coitem_pages, @coitems = paginate :coitems, :per_page => 50, :conditions => ["due_date < ?", Time.now.to_date], :order => "customer_id"
47     render :action => 'overdue'
48   end
49
50   def return
51     if request.post?
52       rentable_id = params[:rentable_id]
53       @rentable = Rentable.find_by_id(rentable_id)
54
55       if @rentable.nil?
56         flash[:notice] = "Unable to find this rentable"
57         redirect_to :action => :return
58         return
59       end
60
61       @coitem = Coitem.find_by_rentable_id(rentable_id)
62       if @coitem.nil?
63         flash[:notice] = "This item is not checked out!"
64         redirect_to :action => :return
65         return
66       end
67
68       # Check if the item is overdue
69       if @coitem.overdue?
70         @coitem.customer.debt += @coitem.late_fee
71         @coitem.customer.save
72       end
73
74       # Delete the row
75       @coitem.destroy
76
77       flash[:notice] = "Successfully returned item"
78       redirect_to :action => :return, :method => :get
79     else
80       render :action => 'return'
81     end
82   end
83 end