Extensive Namespacing of model code
[merb_mart.git] / app / models / mart / customers / cart.rb
blobd5693740a763cfffd4cb169625a87d2209b204b6
1 module Mart
2   module Customers
3     class Cart
4   
5       attr_reader :items, :shipping_cost, :tax, :total
6   
7       # Initializes the shopping cart
8       def initialize
9         empty!
10       end
11   
12       # Empties or initializes the cart
13       def empty!
14         @items = []
15         @tax = 0.0
16         @total = 0.0
17         @shipping_cost = 0.0
18       end
19   
20       def tax_cost
21         @tax * @total
22       end
23   
24       def empty?
25         @items.length == 0
26       end
27   
28       # Returns the total price of our cart
29       def total
30         @total = 0.0
31         for item in @items
32           @total += (item.quantity * item.unit_price)
33         end
34         return @total
35       end
37       # Defined here because in order we have a line_items_total
38       # That number is the total of items - shipping costs.
39       def line_items_total
40         total
41       end
42   
43       # Adds a product to our shopping cart
44       def add_product(product, quantity=1)
45         item = @items.find { |i| i.product_id == product.id }
46          if item
47            item.quantity += quantity
48            # Always set price, as it might have changed...
49            item.price = product.price
50          else
51            item = OrderLineItem.for_product(product)
52            item.quantity = quantity
53            @items << item
54          end
55       end
56   
57       # Removes all quantities of product from our cart
58       def remove_product(product, quantity=nil)
59         item = @items.find { |i| i.product_id == product.id }
60         if quantity.nil?
61           quantity = item.quantity
62         end
63         if item
64           if item.quantity > quantity then
65             item.quantity -= quantity
66           else
67             @items.delete(item)
68           end
69         end
70       end
71   
72       # Checks inventory of products, and removes them if
73       # they're out of stock.
74       #
75       # Returns an array of items that have been removed.
76       #
77       def check_inventory
78         removed_items = []
79         for oli in @items do
80           # Find the item in the db, because oli.item
81           # is cached.
82           db_item = Item[oli.item_id]
84           if oli.quantity > db_item.quantity
85             removed_items << oli.name.clone
86             @items.delete(oli)
87           end
88         end
89         return removed_items
90       end
91   
92     end
93   end
94 end