Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Optimize discount calculations

Patryk Zawadzkif0e6d9427b54
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index aa9ac379e2..6826118626 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -48,7 +48,7 @@ from .forms import (
AnonymousUserShippingForm,
BillingAddressChoiceForm,
)
-from .models import Checkout, CheckoutLine
+from .models import Checkout
COOKIE_NAME = "checkout"
@@ -1046,7 +1046,7 @@ def prepare_order_data(
discounts=discounts,
taxes=taxes,
)
- for line in checkout # type: CheckoutLine
+ for line in checkout
]
# validate checkout gift cards
diff --git a/saleor/core/middleware.py b/saleor/core/middleware.py
index 6221233bb3..862110a95c 100644
--- a/saleor/core/middleware.py
+++ b/saleor/core/middleware.py
@@ -1,5 +1,6 @@
+import datetime
import logging
-from datetime import date
+from collections import defaultdict
from functools import wraps
from typing import Callable
@@ -21,7 +22,9 @@ from django.utils.functional import SimpleLazyObject
from django.utils.translation import get_language
from django_countries.fields import Country
+from ..discount import DiscountInfo
from ..discount.models import Sale
+from ..product.models import Category
from . import analytics
from .utils import get_client_ip, get_country_by_ip, get_currency_for_country
from .utils.taxes import get_taxes_for_country
@@ -105,10 +108,59 @@ def google_analytics(get_response):
def discounts(get_response):
"""Assign active discounts to `request.discounts`."""
+ def fetch_categories(sale_pks):
+ categories = Sale.categories.through.objects.filter(
+ sale_id__in=sale_pks
+ ).values_list("sale_id", "category_id")
+ category_map = defaultdict(set)
+ for sale_pk, category_pk in categories:
+ category_map[sale_pk].add(category_pk)
+ subcategory_map = defaultdict(set)
+ for sale_pk, category_pks in category_map.items():
+ subcategory_map[sale_pk] = set(
+ Category.tree.filter(pk__in=category_pks)
+ .get_descendants(include_self=True)
+ .values_list("pk", flat=True)
+ )
+ return subcategory_map
+
+ def fetch_collections(sale_pks):
+ collections = Sale.collections.through.objects.filter(
+ sale_id__in=sale_pks
+ ).values_list("sale_id", "collection_id")
+ collection_map = defaultdict(set)
+ for sale_pk, collection_pk in collections:
+ collection_map[sale_pk].add(collection_pk)
+ return collection_map
+
+ def fetch_products(sale_pks):
+ products = Sale.products.through.objects.filter(
+ sale_id__in=sale_pks
+ ).values_list("sale_id", "product_id")
+ product_map = defaultdict(set)
+ for sale_pk, product_pk in products:
+ product_map[sale_pk].add(product_pk)
+ return product_map
+
+ def get_discounts():
+ sales = list(Sale.objects.active(datetime.date.today()))
+ pks = {s.pk for s in sales}
+ collections = fetch_collections(pks)
+ products = fetch_products(pks)
+ categories = fetch_categories(pks)
+
+ return [
+ DiscountInfo(
+ sale=sale,
+ category_ids=categories[sale.pk],
+ collection_ids=collections[sale.pk],
+ product_ids=products[sale.pk],
+ )
+ for sale in sales
+ ]
+
def middleware(request):
- request.discounts = Sale.objects.active(date.today()).prefetch_related(
- "products", "categories", "collections"
- )
+ request.discounts = SimpleLazyObject(get_discounts)
return get_response(request)
return middleware
diff --git a/saleor/discount/__init__.py b/saleor/discount/__init__.py
index f6f6b3d865..b852a5c833 100644
--- a/saleor/discount/__init__.py
+++ b/saleor/discount/__init__.py
@@ -1,3 +1,6 @@
+from dataclasses import dataclass
+from typing import Any, List
+
from django.conf import settings
from django.utils.translation import pgettext_lazy
@@ -32,3 +35,11 @@ class VoucherType:
),
(SHIPPING, pgettext_lazy("Voucher: discount for", "Shipping")),
]
+
+
+@dataclass
+class DiscountInfo:
+ sale: Any
+ product_ids: List[int]
+ category_ids: List[int]
+ collection_ids: List[int]
diff --git a/saleor/discount/utils.py b/saleor/discount/utils.py
index 1a0ce61abf..dbfaa645d5 100644
--- a/saleor/discount/utils.py
+++ b/saleor/discount/utils.py
@@ -1,7 +1,10 @@
+from typing import Iterable
+
from django.db.models import F
from django.utils.translation import pgettext
from ..core.utils.taxes import ZERO_MONEY, ZERO_TAXED_MONEY
+from . import DiscountInfo
from .models import NotApplicable
@@ -17,46 +20,37 @@ def decrease_voucher_usage(voucher):
voucher.save(update_fields=["used"])
-def are_product_collections_on_sale(product, sale):
- """Checks if any collection is on sale."""
- discounted_collections = set(sale.collections.all())
- product_collections = set(product.collections.all())
- return set(product_collections).intersection(discounted_collections)
-
-
-def is_category_on_sale(category, sale):
- """Check if category is descendant of one of categories on sale."""
- discounted_categories = set(sale.categories.all())
- return any(
- [category.is_descendant_of(c, include_self=True) for c in discounted_categories]
- )
+def are_product_collections_on_sale(product, discount: DiscountInfo):
+ """Check if any collection is on sale."""
+ discounted_collections = discount.collection_ids
+ product_collections = set(c.id for c in product.collections.all())
+ return product_collections.intersection(discounted_collections)
-def get_product_discount_on_sale(sale, product):
+def get_product_discount_on_sale(product, discount: DiscountInfo):
"""Return discount value if product is on sale or raise NotApplicable."""
- discounted_products = {p.pk for p in sale.products.all()}
is_product_on_sale = (
- product.pk in discounted_products
- or is_category_on_sale(product.category, sale)
- or are_product_collections_on_sale(product, sale)
+ product.id in discount.product_ids
+ or product.category_id in discount.category_ids
+ or are_product_collections_on_sale(product, discount)
)
if is_product_on_sale:
- return sale.get_discount()
+ return discount.sale.get_discount()
raise NotApplicable(
pgettext("Voucher not applicable", "Discount not applicable for this product")
)
-def get_product_discounts(product, discounts):
+def get_product_discounts(product, discounts: Iterable[DiscountInfo]):
"""Return discount values for all discounts applicable to a product."""
for discount in discounts:
try:
- yield get_product_discount_on_sale(discount, product)
+ yield get_product_discount_on_sale(product, discount)
except NotApplicable:
pass
-def calculate_discounted_price(product, price, discounts):
+def calculate_discounted_price(product, price, discounts: Iterable[DiscountInfo]):
"""Return minimum product's price of all prices with discounts applied."""
if discounts:
discounts = list(get_product_discounts(product, discounts))
diff --git a/saleor/settings.py b/saleor/settings.py
index f45cae9075..9b8559dba5 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -292,7 +292,7 @@ LOGGING = {
"formatters": {
"verbose": {
"format": (
- "%(levelname)s %(name)s %(message)s" " [PID:%(process)d:%(threadName)s]"
+ "%(levelname)s %(name)s %(message)s [PID:%(process)d:%(threadName)s]"
)
},
"simple": {"format": "%(levelname)s %(message)s"},
diff --git a/tests/api/test_checkout_promo_codes.py b/tests/api/test_checkout_promo_codes.py
index 0c72d1f9af..b0dd43dfe8 100644
--- a/tests/api/test_checkout_promo_codes.py
+++ b/tests/api/test_checkout_promo_codes.py
@@ -8,6 +8,8 @@ from tests.api.test_checkout import (
from tests.api.utils import get_graphql_content
from saleor.checkout.utils import add_voucher_to_checkout
+from saleor.discount import DiscountInfo
+
MUTATION_CHECKOUT_UPDATE_VOUCHER = """
mutation($checkoutId: ID!, $voucherCode: String) {
@@ -182,7 +184,14 @@ def test_checkout_totals_use_discounts(api_client, checkout_with_item, sale):
content = get_graphql_content(response)
data = content["data"]["checkout"]
- discounts = [sale]
+ discounts = [
+ DiscountInfo(
+ sale=sale,
+ product_ids={product.id},
+ category_ids=set(),
+ collection_ids=set(),
+ )
+ ]
assert (
data["totalPrice"]["gross"]["amount"]
== checkout.get_total(discounts=discounts).gross.amount
diff --git a/tests/conftest.py b/tests/conftest.py
index 9285b40cdd..d88835633a 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -22,7 +22,7 @@ from saleor.checkout.models import Checkout
from saleor.checkout.utils import add_variant_to_checkout
from saleor.core.utils.taxes import DEFAULT_TAX_RATE_NAME
from saleor.dashboard.menu.utils import update_menu
-from saleor.discount import VoucherType
+from saleor.discount import DiscountInfo, VoucherType
from saleor.discount.models import Sale, Voucher, VoucherTranslation
from saleor.giftcard.models import GiftCard
from saleor.menu.models import Menu, MenuItem
@@ -166,7 +166,7 @@ def customer_user(address): # pylint: disable=W0613
return user
def user_checkout(customer_user):
return Checkout.objects.get_or_create(user=customer_user)[0]
@@ -197,13 +197,13 @@ def order(customer_user):
)
def admin_user(db):
"""Return a Django admin user."""
return User.objects.create_superuser("[email protected]", "password")
def admin_client(admin_user):
"""Return a Django test client logged in as an admin user."""
client = Client()
@@ -211,7 +211,7 @@ def admin_client(admin_user):
return client
def staff_user(db):
"""Return a staff member."""
return User.objects.create_user(
@@ -222,14 +222,14 @@ def staff_user(db):
)
def staff_client(client, staff_user):
"""Return a Django test client logged in as an staff member."""
client.login(username=staff_user.email, password="password")
return client
def authorized_client(client, customer_user):
client.login(username=customer_user.email, password="password")
return client
@@ -622,7 +622,7 @@ def voucher_shipping_type():
)
def order_line(order, variant, vatlayer):
taxes = vatlayer
return order.lines.create(
@@ -660,7 +660,7 @@ def gift_card_created_by_staff(staff_user):
)
def order_with_lines(order, product_type, category, shipping_zone, vatlayer):
taxes = vatlayer
product = Product.objects.create(
@@ -722,13 +722,13 @@ def order_with_lines(order, product_type, category, shipping_zone, vatlayer):
return order
def order_events(order):
for event_type, _ in OrderEvents.CHOICES:
OrderEvent.objects.create(type=event_type, order=order)
def fulfilled_order(order_with_lines):
order = order_with_lines
fulfillment = order.fulfillments.create()
@@ -743,7 +743,7 @@ def fulfilled_order(order_with_lines):
return order
def fulfilled_order_with_cancelled_fulfillment(fulfilled_order):
fulfillment = fulfilled_order.fulfillments.create()
line_1 = fulfilled_order.lines.first()
@@ -767,7 +767,7 @@ def draft_order(order_with_lines):
return order_with_lines
def payment_txn_preauth(order_with_lines, payment_dummy):
order = order_with_lines
payment = payment_dummy
@@ -783,7 +783,7 @@ def payment_txn_preauth(order_with_lines, payment_dummy):
return payment
def payment_txn_captured(order_with_lines, payment_dummy):
order = order_with_lines
payment = payment_dummy
@@ -801,7 +801,7 @@ def payment_txn_captured(order_with_lines, payment_dummy):
return payment
def payment_txn_refunded(order_with_lines, payment_dummy):
order = order_with_lines
payment = payment_dummy
@@ -819,14 +819,14 @@ def payment_txn_refunded(order_with_lines, payment_dummy):
return payment
def payment_not_authorized(payment_dummy):
payment_dummy.is_active = False
payment_dummy.save()
return payment_dummy
def sale(category, collection):
sale = Sale.objects.create(name="Sale", value=5)
sale.categories.add(category)
@@ -834,6 +834,16 @@ def sale(category, collection):
return sale
+def discount_info(category, collection, sale):
+ return DiscountInfo(
+ sale=sale,
+ product_ids=set(),
+ category_ids={category.id}, # assumes this category does not have children
+ collection_ids={collection.id},
+ )
+
+
@pytest.fixture
def authorization_backend_name():
return AuthenticationBackends.FACEBOOK
@@ -1187,11 +1197,11 @@ def digital_content(category, media_root):
return d_content
def digital_content_url(digital_content, order_line):
return DigitalContentUrl.objects.create(content=digital_content, line=order_line)
def media_root(tmpdir, settings):
settings.MEDIA_ROOT = str(tmpdir.mkdir("media"))
diff --git a/tests/test_cart.py b/tests/test_cart.py
index 7f6e6a4cdb..4db2862a40 100644
--- a/tests/test_cart.py
+++ b/tests/test_cart.py
@@ -563,11 +563,10 @@ def test_checkout_summary_page_empty_checkout(client, request_checkout):
def test_checkout_line_total_with_discount_and_taxes(
- sale, request_checkout_with_item, taxes
+ discount_info, request_checkout_with_item, taxes
):
- sales = Sale.objects.all()
line = request_checkout_with_item.lines.first()
- assert line.get_total(discounts=sales, taxes=taxes) == TaxedMoney(
+ assert line.get_total(discounts=[discount_info], taxes=taxes) == TaxedMoney(
net=Money("4.07", "USD"), gross=Money("5.00", "USD")
)
@@ -699,8 +698,12 @@ def test_get_checkout_context_no_shipping(request_checkout_with_item, vatlayer):
assert checkout_data["total_with_shipping"].start == checkout_total
-def test_checkout_total_with_discount(request_checkout_with_item, sale, vatlayer):
- total = request_checkout_with_item.get_total(discounts=(sale,), taxes=vatlayer)
+def test_checkout_total_with_discount(
+ request_checkout_with_item, discount_info, vatlayer
+):
+ total = request_checkout_with_item.get_total(
+ discounts=[discount_info], taxes=vatlayer
+ )
assert total == TaxedMoney(net=Money("4.07", "USD"), gross=Money("5.00", "USD"))
diff --git a/tests/test_discounts.py b/tests/test_discounts.py
index ba084b0000..c921603157 100644
--- a/tests/test_discounts.py
+++ b/tests/test_discounts.py
@@ -5,7 +5,7 @@ from prices import Money, TaxedMoney
import pytest
from saleor.checkout.utils import get_voucher_discount_for_checkout
-from saleor.discount import DiscountValueType, VoucherType
+from saleor.discount import DiscountInfo, DiscountValueType, VoucherType
from saleor.discount.models import NotApplicable, Sale, Voucher
from saleor.discount.utils import (
decrease_voucher_usage,
@@ -43,13 +43,25 @@ def test_valid_voucher_min_amount_spent(settings, min_amount_spent, value):
@pytest.mark.django_db(transaction=True)
def test_variant_discounts(product):
variant = product.variants.get()
- low_discount = Sale.objects.create(type=DiscountValueType.FIXED, value=5)
- low_discount.products.add(product)
- discount = Sale.objects.create(type=DiscountValueType.FIXED, value=8)
- discount.products.add(product)
- high_discount = Sale.objects.create(type=DiscountValueType.FIXED, value=50)
- high_discount.products.add(product)
- final_price = variant.get_price(discounts=Sale.objects.all())
+ low_sale = Sale(type=DiscountValueType.FIXED, value=5)
+ low_discount = DiscountInfo(
+ sale=low_sale,
+ product_ids={product.id},
+ category_ids=set(),
+ collection_ids=set(),
+ )
+ sale = Sale(type=DiscountValueType.FIXED, value=8)
+ discount = DiscountInfo(
+ sale=sale, product_ids={product.id}, category_ids=set(), collection_ids=set()
+ )
+ high_sale = Sale(type=DiscountValueType.FIXED, value=50)
+ high_discount = DiscountInfo(
+ sale=high_sale,
+ product_ids={product.id},
+ category_ids=set(),
+ collection_ids=set(),
+ )
+ final_price = variant.get_price(discounts=[low_discount, discount, high_discount])
assert final_price.gross == Money(0, "USD")
@@ -57,8 +69,10 @@ def test_variant_discounts(product):
@pytest.mark.django_db(transaction=True)
def test_percentage_discounts(product):
variant = product.variants.get()
- discount = Sale.objects.create(type=DiscountValueType.PERCENTAGE, value=50)
- discount.products.add(product)
+ sale = Sale(type=DiscountValueType.PERCENTAGE, value=50)
+ discount = DiscountInfo(
+ sale=sale, product_ids={product.id}, category_ids=set(), collection_ids={}
+ )
final_price = variant.get_price(discounts=[discount])
assert final_price.gross == Money(5, "USD")
@@ -71,7 +85,7 @@ def test_voucher_queryset_active(voucher):
@pytest.mark.parametrize(
- "prices, discount_value, discount_type, " "apply_once_per_order, expected_value",
+ "prices, discount_value, discount_type, apply_once_per_order, expected_value",
[
([10], 10, DiscountValueType.FIXED, True, 10),
([5], 10, DiscountValueType.FIXED, True, 5),
@@ -83,7 +97,6 @@ def test_voucher_queryset_active(voucher):
],
)
def test_products_voucher_checkout_discount_not(
- settings,
monkeypatch,
prices,
discount_value,
@@ -130,14 +143,15 @@ def test_sale_applies_to_correct_products(product_type, category):
category=category,
)
sec_variant = ProductVariant.objects.create(product=product2, sku="secvar", pk=111)
- sale = Sale.objects.create(name="Test sale", value=3, type=DiscountValueType.FIXED)
- sale.products.add(product)
- assert product2 not in sale.products.all()
- product_discount = get_product_discount_on_sale(sale, variant.product)
+ sale = Sale(name="Test sale", value=3, type=DiscountValueType.FIXED)
+ discount = DiscountInfo(
+ sale=sale, product_ids={product.id}, category_ids=set(), collection_ids=set()
+ )
+ product_discount = get_product_discount_on_sale(variant.product, discount)
discounted_price = product_discount(product.price)
assert discounted_price == Money(7, "USD")
with pytest.raises(NotApplicable):
- get_product_discount_on_sale(sale, sec_variant.product)
+ get_product_discount_on_sale(sec_variant.product, discount)
def test_increase_voucher_usage():
diff --git a/tests/test_product.py b/tests/test_product.py
index 9aca76917c..a8b617c3c8 100644
--- a/tests/test_product.py
+++ b/tests/test_product.py
@@ -18,7 +18,6 @@ from saleor.checkout import utils
from saleor.checkout.models import Checkout
from saleor.checkout.utils import add_variant_to_checkout
from saleor.dashboard.menu.utils import update_menu
-from saleor.discount.models import Sale
from saleor.menu.models import MenuItemTranslation
from saleor.product import ProductAvailabilityStatus, models
from saleor.product.models import DigitalContentUrl
@@ -534,7 +533,7 @@ def test_get_price(
product_type,
category,
taxes,
- sale,
+ discount_info,
product_price,
include_taxes_in_prices,
include_taxes,
@@ -552,7 +551,7 @@ def test_get_price(
price = variant.get_price(
taxes=taxes if include_taxes else None,
- discounts=Sale.objects.all() if include_discounts else None,
+ discounts=[discount_info] if include_discounts else [],
)
assert price == TaxedMoney(
@@ -624,7 +623,9 @@ def test_product_get_price_range_no_variants(
assert price == TaxedMoneyRange(start=expected_price, stop=expected_price)
-def test_product_get_price_do_not_charge_taxes(product_type, category, taxes, sale):
+def test_product_get_price_do_not_charge_taxes(
+ product_type, category, taxes, discount_info
+):
product = models.Product.objects.create(
product_type=product_type,
category=category,
@@ -633,13 +634,13 @@ def test_product_get_price_do_not_charge_taxes(product_type, category, taxes, sa
)
variant = product.variants.create()
- price = variant.get_price(taxes=taxes, discounts=Sale.objects.all())
+ price = variant.get_price(taxes=taxes, discounts=[discount_info])
assert price == TaxedMoney(net=Money("5.00", "USD"), gross=Money("5.00", "USD"))
def test_product_get_price_range_do_not_charge_taxes(
- product_type, category, taxes, sale
+ product_type, category, taxes, discount_info
):
product = models.Product.objects.create(
product_type=product_type,
@@ -648,7 +649,7 @@ def test_product_get_price_range_do_not_charge_taxes(
charge_taxes=False,
)
- price = product.get_price_range(taxes=taxes, discounts=Sale.objects.all())
+ price = product.get_price_range(taxes=taxes, discounts=[discount_info])
expected_price = TaxedMoney(net=Money("5.00", "USD"), gross=Money("5.00", "USD"))
assert price == TaxedMoneyRange(start=expected_price, stop=expected_price)