Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add category discount logic
Artur Smętfe0070b8d854
diff --git a/saleor/core/middleware.py b/saleor/core/middleware.pyindex 3eaef95d25..4f2b0409ee 100644--- a/saleor/core/middleware.py+++ b/saleor/core/middleware.py@@ -26,7 +26,7 @@ class GoogleAnalytics(object):class DiscountMiddleware(object):def process_request(self, request):discounts = Discount.objects.all()- discounts = discounts.prefetch_related('products')+ discounts = discounts.prefetch_related('products', 'categories')request.discounts = discountsdiff --git a/saleor/product/models/discounts.py b/saleor/product/models/discounts.pyindex f5285c562e..d8b46fed84 100644--- a/saleor/product/models/discounts.py+++ b/saleor/product/models/discounts.py@@ -46,10 +46,24 @@ class Discount(models.Model):return percentage_discount(value=self.value, name=self.name)raise NotImplementedError('Unknown discount type')+ def _product_has_category_discount(self, product, discounted_categories):+ for category in product.categories.all():+ for discounted_category in discounted_categories:+ if category.is_descendant_of(discounted_category,+ include_self=True):+ return True+ return False+def modifier_for_variant(self, variant):check_price = variant.get_price_per_item()- if variant.product not in self.products.all():+ discounted_products = [p.pk for p in self.products.all()]+ discounted_categories = list(self.categories.all())+ if discounted_products and variant.pk not in discounted_products:raise NotApplicable('Discount not applicable for this product')+ if (discounted_categories and not+ self._product_has_category_discount(+ variant.product, discounted_categories)):+ raise NotApplicable('Discount too high for this product')discount = self.get_discount()after_discount = discount.apply(check_price)if after_discount.gross <= 0: