@@ -10,13 +10,13 @@ class DiscountAndQuantity(object):
def __init__(self, discount, clause, quantity):
self.discount = discount
self.clause = clause
self.quantity = quantity
def __repr__(self):
print "(discount=%s, clause=%s, quantity=%d)" % (
return "(discount=%s, clause=%s, quantity=%d)" % (
self.discount, self.clause, self.quantity,
)
def available_discounts(user, categories, products):
''' Returns all discounts available to this user for the given categories
@@ -34,25 +34,35 @@ def available_discounts(user, categories, products):
# discounts that match categories for provided products
product_category_discounts = rego.DiscountForCategory.objects.filter(
category__in=(product.category for product in products)
# (Not relevant: discounts that match products in provided categories)
product_discounts = product_discounts.select_related(
"product",
"product__category",
all_category_discounts = category_discounts | product_category_discounts
all_category_discounts = all_category_discounts.select_related(
"category",
# The set of all potential discounts
potential_discounts = set(itertools.chain(
product_discounts,
category_discounts,
product_category_discounts,
all_category_discounts,
))
discounts = []
# Markers so that we don't need to evaluate given conditions more than once
accepted_discounts = set()
failed_discounts = set()
for discount in potential_discounts:
real_discount = rego.DiscountBase.objects.get_subclass(
pk=discount.discount.pk,
cond = ConditionController.for_condition(real_discount)
@@ -60,13 +70,13 @@ def available_discounts(user, categories, products):
# If this user has exceeded the limit for the clause, this clause
# is not available any more.
past_uses = rego.DiscountItem.objects.filter(
cart__user=user,
cart__active=False, # Only past carts count
cart__released=False, # You can reuse refunded discounts
discount=discount.discount,
discount=real_discount,
agg = past_uses.aggregate(Sum("quantity"))
past_use_count = agg["quantity__sum"]
if past_use_count is None:
past_use_count = 0