Skip to content

Commit

Permalink
Add docstrigs into cart
Browse files Browse the repository at this point in the history
  • Loading branch information
mociepka committed Mar 27, 2013
1 parent f082d56 commit 90b13d2
Show file tree
Hide file tree
Showing 4 changed files with 65 additions and 24 deletions.
63 changes: 45 additions & 18 deletions cart/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,45 +9,66 @@
import datetime


class Group(list, ItemSet):

class BaseGroup(list, ItemSet):
'''
Base Saleor cart group. It is used in cart and checkout to group products
depends on delivery methods.
'''
delivery_method = None

def __init__(self, items, delivery_method=None):
super(Group, self).__init__(items)
super(BaseGroup, self).__init__(items)
if delivery_method and delivery_method not in self.delivery_method():
raise AttributeError('Bad delivery method')
self.delivery_method = delivery_method

def get_delivery_methods(self, **kwargs):
'''
Method should returns iterable object with delivery groups.
'''
raise NotImplementedError()

def get_delivery_total(self, **kwargs):
'''
Method returns price from the self.delivery_method or lowest price
form delivery methods.
'''
if self.delivery_method:
return self.delivery_method.get_price_per_item(**kwargs)
methods = self.get_delivery_methods()
return min(method.get_price_per_item(**kwargs) for method in methods)


class ShippedGroup(Group):

address = None

class ShippedGroup(BaseGroup):
'''
Group for shippable products.
'''
def get_delivery_methods(self):
'''
Returns shippable delivery methods.
'''
yield DummyShipping(self)


class DigitalGroup(Group):

email = None

class DigitalGroup(BaseGroup):
'''
Group for digital products.
'''
def get_delivery_methods(self, **kwargs):
'''
Returns digital delivery methods.
'''
yield DigitalDelivery(self)


class CartPartitioner(Partitioner):

'''
Dividing cart into groups.
'''
def __iter__(self):
'''
Change this method to provide custom delivery groups.
'''
for product_class, items in groupby(
self.subject,
lambda cart_item: cart_item.product.__class__):
Expand Down Expand Up @@ -77,33 +98,39 @@ def __repr__(self):


class InsufficientStockException(Exception):

'''An error while validating product stock.'''
def __init__(self, product):
super(InsufficientStockException, self).__init__(
'Insufficient stock for %r' % (product,))
self.product = product


class Cart(cart.Cart):

'''
Contains cart items. Serialized instance of cart is saved into django
session.
'''
SESSION_KEY = 'cart'
timestamp = None
billing_address = None

def __init__(self, *args, **kwargs):
super(Cart, self).__init__(self, *args, **kwargs)
self.timestamp = datetime.datetime.now()

def __unicode__(self):
return ugettext('Your cart (%(cart_count)s)') % {
'cart_count': self.count()}

def check_quantity(self, product, quantity, data=None):
'''
Raises exception when product has stock and user insert too big
quantity.
'''
if (isinstance(product, StockedProduct) and
quantity > product.stock):
raise InsufficientStockException(product)
return super(Cart, self).check_quantity(product, quantity, data)


def remove_cart_from_request(request):
'''
Method removes cart instance from django session.
'''
del request.session[Cart.SESSION_KEY]
18 changes: 15 additions & 3 deletions cart/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@ def __init__(self, *args, **kwargs):


class AddToCartForm(forms.Form):

'''
Class use product and cart instance.
'''
quantity = QuantityField(label=pgettext('Form field', 'quantity'))
error_messages = {
'insufficient-stock': ugettext(
Expand Down Expand Up @@ -44,11 +46,16 @@ def clean_quantity(self):
return quantity

def save(self):
'''
Adds CartLine into the Cart instance.
'''
return self.cart.add(self.product, self.cleaned_data['quantity'])


class ReplaceCartLineForm(AddToCartForm):

'''
Replaces quantity in CartLine.
'''
def clean_quantity(self):
quantity = self.cleaned_data['quantity']
if not isinstance(self.product, StockedProduct):
Expand All @@ -61,12 +68,17 @@ def clean_quantity(self):
return quantity

def save(self):
'''
Replace quantity.
'''
return self.cart.add(self.product, self.cleaned_data['quantity'],
replace=True)


class ReplaceCartLineFormSet(BaseFormSet):

'''
Formset for all CartLines in the cart instance.
'''
absolute_max = 9999
can_delete = False
can_order = False
Expand Down
4 changes: 3 additions & 1 deletion cart/middleware.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
from cart import Cart

class CartMiddleware(object):

'''
Saves the cart instance into the django session.
'''
def process_request(self, request):
try:
cart = request.session[Cart.SESSION_KEY]
Expand Down
4 changes: 2 additions & 2 deletions product/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ def details(request, slug, product_id):
return Http404()
if product.get_slug() != slug:
return HttpResponsePermanentRedirect(product.get_absolute_url())
form = ProductForm(request.POST or None, cart=request.cart,
product=product)
form = ProductForm(cart=request.cart, product=product,
data=request.POST or None)
if form.is_valid():
form.save()
return TemplateResponse(request, 'product/details.html', {
Expand Down

0 comments on commit 90b13d2

Please sign in to comment.