2016-04-22 05:06:24 +00:00
|
|
|
from registrasion.models import commerce
|
|
|
|
from registrasion.models import inventory
|
2016-04-02 00:56:03 +00:00
|
|
|
|
2016-04-02 03:03:25 +00:00
|
|
|
from django.db.models import Sum
|
|
|
|
|
2016-04-02 02:29:53 +00:00
|
|
|
|
2016-04-02 00:56:03 +00:00
|
|
|
class AllProducts(object):
|
|
|
|
pass
|
|
|
|
|
2016-04-02 02:29:53 +00:00
|
|
|
|
2016-04-02 00:56:03 +00:00
|
|
|
class CategoryController(object):
|
|
|
|
|
2016-04-02 03:03:25 +00:00
|
|
|
def __init__(self, category):
|
|
|
|
self.category = category
|
|
|
|
|
2016-04-02 00:56:03 +00:00
|
|
|
@classmethod
|
|
|
|
def available_categories(cls, user, products=AllProducts):
|
|
|
|
''' Returns the categories available to the user. Specify `products` if
|
|
|
|
you want to restrict to just the categories that hold the specified
|
|
|
|
products, otherwise it'll do all. '''
|
|
|
|
|
2016-04-02 03:03:25 +00:00
|
|
|
# STOPGAP -- this needs to be elsewhere tbqh
|
|
|
|
from product import ProductController
|
|
|
|
|
2016-04-02 00:56:03 +00:00
|
|
|
if products is AllProducts:
|
2016-04-22 05:06:24 +00:00
|
|
|
products = inventory.Product.objects.all().select_related(
|
|
|
|
"category",
|
|
|
|
)
|
2016-04-02 00:56:03 +00:00
|
|
|
|
|
|
|
available = ProductController.available_products(
|
|
|
|
user,
|
|
|
|
products=products,
|
|
|
|
)
|
|
|
|
|
|
|
|
return set(i.category for i in available)
|
2016-04-02 03:03:25 +00:00
|
|
|
|
|
|
|
def user_quantity_remaining(self, user):
|
|
|
|
''' Returns the number of items from this category that the user may
|
|
|
|
add in the current cart. '''
|
|
|
|
|
|
|
|
cat_limit = self.category.limit_per_user
|
|
|
|
|
|
|
|
if cat_limit is None:
|
|
|
|
# We don't need to waste the following queries
|
|
|
|
return 99999999
|
|
|
|
|
2016-04-22 05:06:24 +00:00
|
|
|
carts = commerce.Cart.objects.filter(
|
2016-04-02 03:03:25 +00:00
|
|
|
user=user,
|
2016-04-25 04:31:25 +00:00
|
|
|
status=commerce.Cart.STATUS_PAID,
|
2016-04-02 03:03:25 +00:00
|
|
|
)
|
|
|
|
|
2016-04-22 05:06:24 +00:00
|
|
|
items = commerce.ProductItem.objects.filter(
|
2016-04-02 03:03:25 +00:00
|
|
|
cart__in=carts,
|
|
|
|
product__category=self.category,
|
|
|
|
)
|
|
|
|
|
|
|
|
cat_count = items.aggregate(Sum("quantity"))["quantity__sum"] or 0
|
2016-04-03 05:25:39 +00:00
|
|
|
return cat_limit - cat_count
|