Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Refactor line weight calculation to reuse DB queries (#15714)
Marcin Gębala16ba23e9b248
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.pyindex a974813af6..4aaad9f206 100644--- a/saleor/checkout/complete_checkout.py+++ b/saleor/checkout/complete_checkout.py@@ -82,6 +82,7 @@ from .fetch import ()from .models import Checkoutfrom .utils import (+ calculate_checkout_weight,get_checkout_metadata,get_or_create_checkout_metadata,get_voucher_for_checkout_info,@@ -155,7 +156,7 @@ def _process_shipping_data_for_order("shipping_address": shipping_address,"base_shipping_price": base_shipping_price,"shipping_price": shipping_price,- "weight": checkout_info.checkout.get_total_weight(lines),+ "weight": calculate_checkout_weight(lines),**get_shipping_tax_class_kwargs_for_order(tax_class),}result.update(delivery_method_info.delivery_method_order_field)diff --git a/saleor/checkout/fetch.py b/saleor/checkout/fetch.pyindex 4965f0c7ba..c4861ea433 100644--- a/saleor/checkout/fetch.py+++ b/saleor/checkout/fetch.py@@ -671,7 +671,7 @@ def update_delivery_method_lists_for_checkout_info()# Filter shipping methods using sync webhooksexcluded_methods = manager.excluded_shipping_methods_for_checkout(- checkout_info.checkout, all_methods+ checkout_info.checkout, checkout_info.channel, all_methods)initialize_shipping_method_active_status(all_methods, excluded_methods)return all_methodsdiff --git a/saleor/checkout/models.py b/saleor/checkout/models.pyindex 04011e966e..8f4ae38288 100644--- a/saleor/checkout/models.py+++ b/saleor/checkout/models.py@@ -1,10 +1,9 @@"""Checkout-related ORM models."""-from collections.abc import Iterablefrom datetime import datefrom decimal import Decimalfrom operator import attrgetter-from typing import TYPE_CHECKING, Optional, Union+from typing import TYPE_CHECKING, Optionalfrom uuid import uuid4from django.conf import settings@@ -19,19 +18,14 @@ from prices import Moneyfrom ..channel.models import Channelfrom ..core.models import ModelWithMetadatafrom ..core.taxes import zero_money-from ..core.weight import zero_weightfrom ..giftcard.models import GiftCardfrom ..permission.enums import CheckoutPermissionsfrom ..shipping.models import ShippingMethodfrom . import CheckoutAuthorizeStatus, CheckoutChargeStatusif TYPE_CHECKING:- from django_measurement import Weight-- from ..order.fetch import OrderLineInfofrom ..payment.models import Paymentfrom ..product.models import ProductVariant- from .fetch import CheckoutLineInfodef get_default_country():@@ -234,19 +228,6 @@ class Checkout(models.Model):return zero_money(currency=self.currency)return Money(balance, self.currency)- def get_total_weight(- self, lines: Union[Iterable["CheckoutLineInfo"], Iterable["OrderLineInfo"]]- ) -> "Weight":- # FIXME: it does not make sense for this method to live in the Checkout model- # since it's used in the Order model as well. We should move it to a separate- # helper.- weights = zero_weight()- for checkout_line_info in lines:- line = checkout_line_info.line- if line.variant:- weights += line.variant.get_weight() * line.quantity- return weights-def get_line(self, variant: "ProductVariant") -> Optional["CheckoutLine"]:"""Return a line matching the given variant and data if any."""matching_lines = (line for line in self if line.variant.pk == variant.pk)diff --git a/saleor/checkout/tests/test_cart.py b/saleor/checkout/tests/test_cart.pyindex 48747849ff..55011b6f7a 100644--- a/saleor/checkout/tests/test_cart.py+++ b/saleor/checkout/tests/test_cart.py@@ -10,7 +10,11 @@ from ...plugins.manager import get_plugins_managerfrom ...product.models import Categoryfrom .. import calculations, utilsfrom ..models import Checkout-from ..utils import add_variant_to_checkout, calculate_checkout_quantity+from ..utils import (+ add_variant_to_checkout,+ calculate_checkout_quantity,+ calculate_checkout_weight,+)@pytest.fixture@@ -283,4 +287,4 @@ def test_get_total_weight(checkout_with_item):line.quantity = 6line.save()lines, _ = fetch_checkout_lines(checkout_with_item)- assert checkout_with_item.get_total_weight(lines) == Weight(kg=60)+ assert calculate_checkout_weight(lines) == Weight(kg=60)diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex 9d8f97082c..4aa267258d 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -22,6 +22,7 @@ from ..core.utils.promo_code import (promo_code_is_voucher,)from ..core.utils.translations import get_translation+from ..core.weight import zero_weightfrom ..discount import DiscountType, VoucherTypefrom ..discount.interface import VoucherInfo, fetch_voucher_infofrom ..discount.models import (@@ -59,6 +60,8 @@ from .fetch import (from .models import Checkout, CheckoutLine, CheckoutMetadataif TYPE_CHECKING:+ from measurement.measures import Weight+from ..account.models import Addressfrom ..order.models import Orderfrom .fetch import CheckoutInfo, CheckoutLineInfo@@ -865,6 +868,7 @@ def get_valid_internal_shipping_methods_for_checkout(checkout_info.checkout,channel_id=checkout_info.checkout.channel_id,price=subtotal,+ shipping_address=checkout_info.shipping_address,country_code=country_code,lines=lines,)@@ -1024,3 +1028,21 @@ def get_checkout_metadata(checkout: "Checkout"):return checkout.metadata_storageelse:return CheckoutMetadata(checkout=checkout)+++def calculate_checkout_weight(lines: Iterable["CheckoutLineInfo"]) -> "Weight":+ weights = zero_weight()+ for checkout_line_info in lines:+ variant = checkout_line_info.variant+ if variant:+ line_weight = get_checkout_line_weight(checkout_line_info)+ weights += line_weight * checkout_line_info.line.quantity+ return weights+++def get_checkout_line_weight(line_info: "CheckoutLineInfo"):+ return (+ line_info.variant.weight+ or line_info.product.weight+ or line_info.product_type.weight+ )diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.pyindex d112bbcf12..802fbe36d7 100644--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py@@ -562,7 +562,7 @@ def test_create_checkout_with_order_promotion(}# when- with django_assert_num_queries(88):+ with django_assert_num_queries(71):response = user_api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)# thendiff --git a/saleor/graphql/order/tests/queries/test_order.py b/saleor/graphql/order/tests/queries/test_order.pyindex 3b25d60607..20e2890993 100644--- a/saleor/graphql/order/tests/queries/test_order.py+++ b/saleor/graphql/order/tests/queries/test_order.py@@ -349,7 +349,7 @@ def test_order_query(expected_methods = ShippingMethod.objects.applicable_shipping_methods(price=order.subtotal.gross,- weight=order.get_total_weight(),+ weight=order.weight,country_code=order.shipping_address.country.code,channel_id=order.channel_id,)@@ -997,7 +997,7 @@ def test_order_query_in_pln_channel(expected_methods = ShippingMethod.objects.applicable_shipping_methods(price=order.subtotal.gross,- weight=order.get_total_weight(),+ weight=order.weight,country_code=order.shipping_address.country.code,channel_id=order.channel_id,)diff --git a/saleor/order/models.py b/saleor/order/models.pyindex 79ce62b9a0..469dc01659 100644--- a/saleor/order/models.py+++ b/saleor/order/models.py@@ -498,9 +498,6 @@ class Order(ModelWithMetadata, ModelWithExternalReference):def total_balance(self):return self.total_charged - self.total.gross- def get_total_weight(self, _lines=None):- return self.weight-class OrderLineQueryset(models.QuerySet["OrderLine"]):def digital(self):diff --git a/saleor/order/tests/test_order.py b/saleor/order/tests/test_order.pyindex 89c6ad9f3d..7cc2c18b78 100644--- a/saleor/order/tests/test_order.py+++ b/saleor/order/tests/test_order.py@@ -658,12 +658,12 @@ def test_get_order_weight_non_existing_product(app=None,manager=anonymous_plugins,)- old_weight = order.get_total_weight()+ old_weight = order.weightproduct.delete()order.refresh_from_db()- new_weight = order.get_total_weight()+ new_weight = order.weightassert old_weight == new_weightdiff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex ed0317155c..fcbe3e1503 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -611,7 +611,8 @@ def get_all_shipping_methods_for_order(if not order.is_shipping_required():return []- if not order.shipping_address:+ shipping_address = order.shipping_address+ if not shipping_address:return []all_methods = []@@ -622,7 +623,8 @@ def get_all_shipping_methods_for_order(order,channel_id=order.channel_id,price=order.subtotal.gross,- country_code=order.shipping_address.country.code,+ shipping_address=shipping_address,+ country_code=shipping_address.country.code,).prefetch_related("channel_listings"))diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.pyindex ae05b8c464..9ae90c1e61 100644--- a/saleor/plugins/manager.py+++ b/saleor/plugins/manager.py@@ -2164,6 +2164,7 @@ class PluginsManager(PaymentInterface):def excluded_shipping_methods_for_checkout(self,checkout: "Checkout",+ channel: "Channel",available_shipping_methods: list["ShippingMethodData"],) -> list[ExcludedShippingMethod]:return self.__run_method_on_plugins(@@ -2171,7 +2172,7 @@ class PluginsManager(PaymentInterface):[],checkout,available_shipping_methods,- channel_slug=checkout.channel.slug,+ channel_slug=channel.slug,)def perform_mutation(diff --git a/saleor/shipping/models.py b/saleor/shipping/models.pyindex 996aed4275..bebcdc01cc 100644--- a/saleor/shipping/models.py+++ b/saleor/shipping/models.py@@ -24,6 +24,7 @@ from . import PostalCodeRuleInclusionType, ShippingMethodTypefrom .postal_codes import filter_shipping_methods_by_postal_code_rulesif TYPE_CHECKING:+ from ..account.models import Addressfrom ..checkout.fetch import CheckoutLineInfofrom ..checkout.models import Checkoutfrom ..order.fetch import OrderLineInfo@@ -165,32 +166,44 @@ class ShippingMethodQueryset(models.QuerySet["ShippingMethod"]):instance: Union["Checkout", "Order"],channel_id,price: Money,+ shipping_address: Optional["Address"] = None,country_code: Optional[str] = None,lines: Union[Iterable["CheckoutLineInfo"], Iterable["OrderLineInfo"], None] = None,):- if not instance.shipping_address:+ if not shipping_address:return None+if not country_code:- # TODO: country_code should come from argument- country_code = instance.shipping_address.country.code+ country_code = shipping_address.country.code+if lines is None:# TODO: lines should comes from args in get_valid_shipping_methods_for_orderlines = list(instance.lines.prefetch_related("variant__product").all()) # type: ignore[misc] # this is hack # noqa: E501instance_product_ids = {line.variant.product_id for line in lines if line.variant}++ from ..checkout.models import Checkout++ if isinstance(instance, Checkout):+ from ..checkout.utils import calculate_checkout_weight++ weight = calculate_checkout_weight(lines) # type: ignore[arg-type]+ else:+ weight = instance.weight+applicable_methods = self.applicable_shipping_methods(price=price,channel_id=channel_id,- weight=instance.get_total_weight(lines),- country_code=country_code or instance.shipping_address.country.code,+ weight=weight,+ country_code=country_code,product_ids=instance_product_ids,).prefetch_related("postal_code_rules")return filter_shipping_methods_by_postal_code_rules(- applicable_methods, instance.shipping_address+ applicable_methods, shipping_address)