Skip to content

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

Optimize validate_draft_order function to run less queries (#15748)

Marcin Gębalaa9d2e2dcae26
diff --git a/saleor/discount/utils.py b/saleor/discount/utils.py
index 4c21523cfd..8e081480f0 100644
--- a/saleor/discount/utils.py
+++ b/saleor/discount/utils.py
@@ -54,7 +54,7 @@ from .models import (
if TYPE_CHECKING:
from ..account.models import User
from ..checkout.fetch import CheckoutInfo
- from ..order.models import Order
+ from ..order.models import Order, OrderLine
from ..plugins.manager import PluginsManager
from ..product.managers import ProductVariantQueryset
from ..product.models import VariantChannelListingPromotionRule
@@ -283,19 +283,23 @@ def validate_voucher_for_checkout(
)
-def validate_voucher_in_order(order: "Order"):
+def validate_voucher_in_order(
+ order: "Order", lines: Iterable["OrderLine"], channel: "Channel"
+):
if not order.voucher:
return
+ from ..order.utils import get_total_quantity
+
subtotal = order.subtotal
- quantity = order.get_total_quantity()
+ quantity = get_total_quantity(lines)
customer_email = order.get_customer_email()
- tax_configuration = order.channel.tax_configuration
+ tax_configuration = channel.tax_configuration
prices_entered_with_tax = tax_configuration.prices_entered_with_tax
value = subtotal.gross if prices_entered_with_tax else subtotal.net
validate_voucher(
- order.voucher, value, quantity, customer_email, order.channel, order.user
+ order.voucher, value, quantity, customer_email, channel, order.user
)
diff --git a/saleor/graphql/order/mutations/draft_order_complete.py b/saleor/graphql/order/mutations/draft_order_complete.py
index 08c610d654..46e0ca5000 100644
--- a/saleor/graphql/order/mutations/draft_order_complete.py
+++ b/saleor/graphql/order/mutations/draft_order_complete.py
@@ -111,7 +111,7 @@ class DraftOrderComplete(BaseMutation):
cls.validate_order(order)
country = get_order_country(order)
- validate_draft_order(order, country, manager)
+ validate_draft_order(order, order.lines.all(), country, manager)
with traced_atomic_transaction():
cls.update_user_fields(order)
order.status = OrderStatus.UNFULFILLED
diff --git a/saleor/graphql/order/tests/test_draft_order_validate.py b/saleor/graphql/order/tests/test_draft_order_validate.py
index 1a7b5eef41..c5c4943773 100644
--- a/saleor/graphql/order/tests/test_draft_order_validate.py
+++ b/saleor/graphql/order/tests/test_draft_order_validate.py
@@ -1,5 +1,5 @@
from datetime import datetime, timedelta
-from unittest.mock import Mock
+from unittest.mock import patch
import pytest
import pytz
@@ -15,7 +15,10 @@ def test_validate_draft_order(draft_order):
# should not raise any errors
assert (
validate_draft_order(
- draft_order, "US", get_plugins_manager(allow_replica=False)
+ draft_order,
+ draft_order.lines.all(),
+ "US",
+ get_plugins_manager(allow_replica=False),
)
is None
)
@@ -27,7 +30,10 @@ def test_validate_draft_order_without_sku(draft_order):
# should not raise any errors
assert (
validate_draft_order(
- draft_order, "US", get_plugins_manager(allow_replica=False)
+ draft_order,
+ draft_order.lines.all(),
+ "US",
+ get_plugins_manager(allow_replica=False),
)
is None
)
@@ -40,7 +46,9 @@ def test_validate_draft_order_wrong_shipping(draft_order):
shipping_zone.save()
assert order.shipping_address.country.code not in shipping_zone.countries
with pytest.raises(ValidationError) as e:
- validate_draft_order(order, "US", get_plugins_manager(allow_replica=False))
+ validate_draft_order(
+ order, order.lines.all(), "US", get_plugins_manager(allow_replica=False)
+ )
msg = "Shipping method is not valid for chosen shipping address"
assert e.value.error_dict["shipping"][0].message == msg
@@ -48,7 +56,9 @@ def test_validate_draft_order_wrong_shipping(draft_order):
def test_validate_draft_order_no_order_lines(order, shipping_method):
order.shipping_method = shipping_method
with pytest.raises(ValidationError) as e:
- validate_draft_order(order, "US", get_plugins_manager(allow_replica=False))
+ validate_draft_order(
+ order, order.lines.all(), "US", get_plugins_manager(allow_replica=False)
+ )
msg = "Could not create order without any products."
assert e.value.error_dict["lines"][0].message == msg
@@ -62,7 +72,9 @@ def test_validate_draft_order_non_existing_variant(draft_order):
assert line.variant is None
with pytest.raises(ValidationError) as e:
- validate_draft_order(order, "US", get_plugins_manager(allow_replica=False))
+ validate_draft_order(
+ order, order.lines.all(), "US", get_plugins_manager(allow_replica=False)
+ )
msg = "Could not create orders with non-existing products."
assert e.value.error_dict["lines"][0].message == msg
@@ -77,7 +89,9 @@ def test_validate_draft_order_with_unpublished_product(draft_order):
line.refresh_from_db()
with pytest.raises(ValidationError) as e:
- validate_draft_order(order, "US", get_plugins_manager(allow_replica=False))
+ validate_draft_order(
+ order, order.lines.all(), "US", get_plugins_manager(allow_replica=False)
+ )
msg = "Can't finalize draft with unpublished product."
error = e.value.error_dict["lines"][0]
@@ -93,7 +107,9 @@ def test_validate_draft_order_with_unavailable_for_purchase_product(draft_order)
line.refresh_from_db()
with pytest.raises(ValidationError) as e:
- validate_draft_order(order, "US", get_plugins_manager(allow_replica=False))
+ validate_draft_order(
+ order, order.lines.all(), "US", get_plugins_manager(allow_replica=False)
+ )
msg = "Can't finalize draft with product unavailable for purchase."
error = e.value.error_dict["lines"][0]
@@ -113,7 +129,9 @@ def test_validate_draft_order_with_product_available_for_purchase_in_future(
line.refresh_from_db()
with pytest.raises(ValidationError) as e:
- validate_draft_order(order, "US", get_plugins_manager(allow_replica=False))
+ validate_draft_order(
+ order, order.lines.all(), "US", get_plugins_manager(allow_replica=False)
+ )
msg = "Can't finalize draft with product unavailable for purchase."
error = e.value.error_dict["lines"][0]
@@ -131,7 +149,9 @@ def test_validate_draft_order_out_of_stock_variant(draft_order):
stock.save(update_fields=["quantity"])
with pytest.raises(ValidationError) as e:
- validate_draft_order(order, "US", get_plugins_manager(allow_replica=False))
+ validate_draft_order(
+ order, order.lines.all(), "US", get_plugins_manager(allow_replica=False)
+ )
msg = "Insufficient product stock."
assert e.value.error_dict["lines"][0].message == msg
@@ -141,7 +161,9 @@ def test_validate_draft_order_no_shipping_address(draft_order):
order.shipping_address = None
with pytest.raises(ValidationError) as e:
- validate_draft_order(order, "US", get_plugins_manager(allow_replica=False))
+ validate_draft_order(
+ order, order.lines.all(), "US", get_plugins_manager(allow_replica=False)
+ )
error = e.value.error_dict["order"][0]
assert error.message == "Can't finalize draft with no shipping address."
assert error.code == OrderErrorCode.ORDER_NO_SHIPPING_ADDRESS.value
@@ -152,7 +174,9 @@ def test_validate_draft_order_no_billing_address(draft_order):
order.billing_address = None
with pytest.raises(ValidationError) as e:
- validate_draft_order(order, "US", get_plugins_manager(allow_replica=False))
+ validate_draft_order(
+ order, order.lines.all(), "US", get_plugins_manager(allow_replica=False)
+ )
error = e.value.error_dict["order"][0]
assert error.message == "Can't finalize draft with no billing address."
assert error.code == OrderErrorCode.BILLING_ADDRESS_NOT_SET.value
@@ -163,35 +187,44 @@ def test_validate_draft_order_no_shipping_method(draft_order):
order.shipping_method = None
with pytest.raises(ValidationError) as e:
- validate_draft_order(order, "US", get_plugins_manager(allow_replica=False))
+ validate_draft_order(
+ order, order.lines.all(), "US", get_plugins_manager(allow_replica=False)
+ )
error = e.value.error_dict["shipping"][0]
assert error.message == "Shipping method is required."
assert error.code == OrderErrorCode.SHIPPING_METHOD_REQUIRED.value
-def test_validate_draft_order_no_shipping_method_shipping_not_required(draft_order):
+@patch("saleor.graphql.order.utils.is_shipping_required")
+def test_validate_draft_order_no_shipping_method_shipping_not_required(
+ mocked_is_shipping_required, draft_order
+):
order = draft_order
order.shipping_method = None
- required_mock = Mock(return_value=False)
- order.is_shipping_required = required_mock
+ mocked_is_shipping_required.return_value = False
assert (
- validate_draft_order(order, "US", get_plugins_manager(allow_replica=False))
+ validate_draft_order(
+ order, order.lines.all(), "US", get_plugins_manager(allow_replica=False)
+ )
is None
)
+@patch("saleor.graphql.order.utils.is_shipping_required")
def test_validate_draft_order_no_shipping_address_no_method_shipping_not_required(
+ mocked_is_shipping_required,
draft_order,
):
order = draft_order
order.shipping_method = None
order.shipping_address = None
- required_mock = Mock(return_value=False)
- order.is_shipping_required = required_mock
+ mocked_is_shipping_required.return_value = False
assert (
- validate_draft_order(order, "US", get_plugins_manager(allow_replica=False))
+ validate_draft_order(
+ order, order.lines.all(), "US", get_plugins_manager(allow_replica=False)
+ )
is None
)
@@ -203,7 +236,9 @@ def test_validate_draft_order_voucher(draft_order_with_voucher):
# when & then
with pytest.raises(ValidationError) as e:
- validate_draft_order(order, "US", get_plugins_manager(allow_replica=False))
+ validate_draft_order(
+ order, order.lines.all(), "US", get_plugins_manager(allow_replica=False)
+ )
error = e.value.error_dict["voucher"][0]
assert error.code == OrderErrorCode.INVALID_VOUCHER.value
diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.py
index ae7db036ec..d581bc2853 100644
--- a/saleor/graphql/order/types.py
+++ b/saleor/graphql/order/types.py
@@ -1930,21 +1930,26 @@ class Order(ModelObjectType[models.Order]):
def resolve_can_finalize(root: models.Order, info):
if root.status == OrderStatus.DRAFT:
- def _validate_draft_order(manager):
+ @allow_writer_in_context(info.context)
+ def _validate_draft_order(data):
+ lines, manager = data
country = get_order_country(root)
database_connection_name = get_database_connection_name(info.context)
try:
validate_draft_order(
- root,
- country,
- manager,
+ order=root,
+ lines=lines,
+ country=country,
+ manager=manager,
database_connection_name=database_connection_name,
)
except ValidationError:
return False
return True
- return get_plugin_manager_promise(info.context).then(_validate_draft_order)
+ lines = OrderLinesByOrderIdLoader(info.context).load(root.id)
+ manager = get_plugin_manager_promise(info.context)
+ return Promise.all([lines, manager]).then(_validate_draft_order)
return True
@staticmethod
@@ -2158,21 +2163,26 @@ class Order(ModelObjectType[models.Order]):
def resolve_errors(root: models.Order, info):
if root.status == OrderStatus.DRAFT:
- def _validate_order(manager):
+ @allow_writer_in_context(info.context)
+ def _validate_order(data):
+ lines, manager = data
country = get_order_country(root)
database_connection_name = get_database_connection_name(info.context)
try:
validate_draft_order(
- root,
- country,
- manager,
+ order=root,
+ lines=lines,
+ country=country,
+ manager=manager,
database_connection_name=database_connection_name,
)
except ValidationError as e:
return validation_error_to_error_type(e, OrderError)
return []
- return get_plugin_manager_promise(info.context).then(_validate_order)
+ lines = OrderLinesByOrderIdLoader(info.context).load(root.id)
+ manager = get_plugin_manager_promise(info.context)
+ return Promise.all([lines, manager]).then(_validate_order)
return []
diff --git a/saleor/graphql/order/utils.py b/saleor/graphql/order/utils.py
index 53197fc0b8..0113fc487d 100644
--- a/saleor/graphql/order/utils.py
+++ b/saleor/graphql/order/utils.py
@@ -12,7 +12,11 @@ from ...discount.interface import VariantPromotionRuleInfo
from ...discount.models import NotApplicable
from ...discount.utils import validate_voucher_in_order
from ...order.error_codes import OrderErrorCode
-from ...order.utils import get_valid_shipping_methods_for_order
+from ...order.utils import (
+ get_total_quantity,
+ get_valid_shipping_methods_for_order,
+ is_shipping_required,
+)
from ...plugins.manager import PluginsManager
from ...product.models import Product, ProductChannelListing, ProductVariant
from ...shipping.interface import ShippingMethodData
@@ -22,7 +26,7 @@ from ..core.validators import validate_variants_available_in_channel
if TYPE_CHECKING:
from ...channel.models import Channel
- from ...order.models import Order
+ from ...order.models import Order, OrderLine
from dataclasses import dataclass
@@ -39,8 +43,9 @@ class OrderLineData:
rules_info: Optional[Iterable[VariantPromotionRuleInfo]] = None
-def validate_total_quantity(order: "Order", errors: T_ERRORS):
- if order.get_total_quantity() == 0:
+def validate_total_quantity(lines: Iterable["OrderLine"], errors: T_ERRORS):
+ total_quantity = get_total_quantity(lines)
+ if total_quantity == 0:
errors["lines"].append(
ValidationError(
"Could not create order without any products.",
@@ -79,6 +84,7 @@ def get_shipping_method_availability_error(
def validate_shipping_method(
order: "Order",
+ channel: "Channel",
errors: T_ERRORS,
manager: "PluginsManager",
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
@@ -103,7 +109,7 @@ def validate_shipping_method(
code=OrderErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.value,
)
else:
- listing = order.channel.shipping_method_listings.filter(
+ listing = channel.shipping_method_listings.filter(
shipping_method=order.shipping_method
).last()
if not listing:
@@ -145,11 +151,13 @@ def validate_shipping_address(order: "Order", errors: T_ERRORS):
def validate_order_lines(
order: "Order",
+ lines: Iterable["OrderLine"],
+ channel: "Channel",
country: str,
errors: T_ERRORS,
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
):
- for line in order.lines.all():
+ for line in lines:
if line.variant is None:
errors["lines"].append(
ValidationError(
@@ -162,7 +170,7 @@ def validate_order_lines(
check_stock_and_preorder_quantity(
line.variant,
country,
- order.channel.slug,
+ channel.slug,
line.quantity,
order_line=line,
database_connection_name=database_connection_name,
@@ -174,15 +182,16 @@ def validate_order_lines(
def validate_variants_is_available(
- order: "Order",
+ channel: "Channel",
+ lines: Iterable["OrderLine"],
errors: T_ERRORS,
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
):
- variants_ids = {line.variant_id for line in order.lines.all()}
+ variants_ids = {line.variant_id for line in lines}
try:
validate_variants_available_in_channel(
variants_ids,
- order.channel_id,
+ channel.id,
OrderErrorCode.NOT_AVAILABLE_IN_CHANNEL.value,
database_connection_name=database_connection_name,
)
@@ -191,15 +200,16 @@ def validate_variants_is_available(
def validate_product_is_published(
- order: "Order",
+ channel: "Channel",
+ lines: Iterable["OrderLine"],
errors: T_ERRORS,
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
):
- variant_ids = [line.variant_id for line in order.lines.all()]
+ variant_ids = [line.variant_id for line in lines]
unpublished_product = (
Product.objects.using(database_connection_name)
.filter(variants__id__in=variant_ids)
- .not_published(order.channel.slug)
+ .not_published(channel.slug)
)
if unpublished_product.exists():
errors["lines"].append(
@@ -272,18 +282,19 @@ def validate_variant_channel_listings(
def validate_product_is_available_for_purchase(
- order: "Order",
+ channel: "Channel",
+ lines: Iterable["OrderLine"],
errors: T_ERRORS,
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
):
invalid_lines = []
- for line in order.lines.all():
+ for line in lines:
variant = line.variant
if not variant:
continue
product_channel_listing = (
ProductChannelListing.objects.using(database_connection_name)
- .filter(channel_id=order.channel_id, product_id=variant.product_id)
+ .filter(channel_id=channel.id, product_id=variant.product_id)
.first()
)
if not (
@@ -311,10 +322,12 @@ def validate_channel_is_active(channel: "Channel", errors: T_ERRORS):
)
-def _validate_voucher(order: "Order", errors: T_ERRORS):
- if order.channel.include_draft_order_in_voucher_usage:
+def _validate_voucher(
+ order: "Order", lines: Iterable["OrderLine"], channel: "Channel", errors: T_ERRORS
+):
+ if channel.include_draft_order_in_voucher_usage:
try:
- validate_voucher_in_order(order)
+ validate_voucher_in_order(order, lines, channel)
except NotApplicable as e:
errors["voucher"].append(
ValidationError(
@@ -326,6 +339,7 @@ def _validate_voucher(order: "Order", errors: T_ERRORS):
def validate_draft_order(
order: "Order",
+ lines: Iterable["OrderLine"],
country: str,
manager: "PluginsManager",
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
@@ -341,18 +355,26 @@ def validate_draft_order(
Returns a list of errors if any were found.
"""
+ channel = order.channel
+
errors: T_ERRORS = defaultdict(list)
validate_billing_address(order, errors)
- if order.is_shipping_required():
+ if is_shipping_required(lines):
validate_shipping_address(order, errors)
- validate_shipping_method(order, errors, manager, database_connection_name)
- validate_total_quantity(order, errors)
- validate_order_lines(order, country, errors, database_connection_name)
- validate_channel_is_active(order.channel, errors)
- validate_product_is_published(order, errors, database_connection_name)
- validate_product_is_available_for_purchase(order, errors, database_connection_name)
- validate_variants_is_available(order, errors, database_connection_name)
- _validate_voucher(order, errors)
+ validate_shipping_method(
+ order, channel, errors, manager, database_connection_name
+ )
+ validate_total_quantity(lines, errors)
+ validate_order_lines(
+ order, lines, channel, country, errors, database_connection_name
+ )
+ validate_channel_is_active(channel, errors)
+ validate_product_is_published(channel, lines, errors, database_connection_name)
+ validate_product_is_available_for_purchase(
+ channel, lines, errors, database_connection_name
+ )
+ validate_variants_is_available(channel, lines, errors, database_connection_name)
+ _validate_voucher(order, lines, channel, errors)
if errors:
raise ValidationError(errors)
diff --git a/saleor/order/tests/test_order.py b/saleor/order/tests/test_order.py
index 7cc2c18b78..820b01a7c6 100644
--- a/saleor/order/tests/test_order.py
+++ b/saleor/order/tests/test_order.py
@@ -678,7 +678,9 @@ def test_get_voucher_discount_for_order_voucher_validation(
quantity = order_with_lines.get_total_quantity()
customer_email = order_with_lines.get_customer_email()
- validate_voucher_in_order(order_with_lines)
+ validate_voucher_in_order(
+ order_with_lines, order_with_lines.lines.all(), order_with_lines.channel
+ )
mock_validate_voucher.assert_called_once_with(
voucher,
@@ -699,7 +701,9 @@ def test_validate_voucher_in_order_without_voucher(
assert not order_with_lines.voucher
- validate_voucher_in_order(order_with_lines)
+ validate_voucher_in_order(
+ order_with_lines, order_with_lines.lines.all(), order_with_lines.channel
+ )
mock_validate_voucher.assert_not_called()
@@ -745,6 +749,7 @@ def test_value_voucher_order_discount(
billing_address=address_usa,
channel=channel_USD,
)
+ order.lines = Mock(all=Mock(return_value=[]))
discount = get_voucher_discount_for_order(order)
assert discount == Money(expected_value, "USD")
@@ -784,6 +789,7 @@ def test_shipping_voucher_order_discount(
voucher=voucher,
channel=channel_USD,
)
+ order.lines = Mock(all=Mock(return_value=[]))
discount = get_voucher_discount_for_order(order)
assert discount == Money(expected_value, "USD")
@@ -840,6 +846,7 @@ def test_shipping_voucher_checkout_discount_not_applicable_returns_zero(
voucher=voucher,
channel=channel_USD,
)
+ order.lines = Mock(all=Mock(return_value=[]))
with pytest.raises(NotApplicable):
get_voucher_discount_for_order(order)
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index fcbe3e1503..9e88fa5f8e 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -664,6 +664,10 @@ def is_shipping_required(lines: Iterable["OrderLine"]):
return any(line.is_shipping_required for line in lines)
+def get_total_quantity(lines: Iterable["OrderLine"]):
+ return sum([line.quantity for line in lines])
+
+
def get_valid_collection_points_for_order(
lines: Iterable["OrderLine"],
channel_id: int,
@@ -741,7 +745,7 @@ def get_voucher_discount_for_order(order: Order) -> Money:
"""
if not order.voucher:
return zero_money(order.currency)
- validate_voucher_in_order(order)
+ validate_voucher_in_order(order, order.lines.all(), order.channel)
subtotal = order.subtotal
if order.voucher.type == VoucherType.ENTIRE_ORDER:
return order.voucher.get_discount_amount_for(subtotal.gross, order.channel)