Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Optimize memory collection for plugin manager (#15910)
Marcin Gębalabc09204055dd
diff --git a/saleor/checkout/fetch.py b/saleor/checkout/fetch.pyindex c4861ea433..8f874b1fcd 100644--- a/saleor/checkout/fetch.py+++ b/saleor/checkout/fetch.py@@ -1,7 +1,7 @@import itertoolsfrom collections.abc import Iterable-from dataclasses import dataclass-from functools import singledispatch+from dataclasses import dataclass, field+from functools import cached_property, singledispatchfrom typing import (TYPE_CHECKING,Any,@@ -13,7 +13,6 @@ from uuid import UUIDfrom django.conf import settings-from ..core.utils.lazyobjects import lazy_no_retryfrom ..discount import DiscountType, VoucherTypefrom ..discount.interface import fetch_variant_rules_info, fetch_voucher_infofrom ..shipping.interface import ShippingMethodData@@ -79,19 +78,87 @@ class CheckoutLineInfo:@dataclassclass CheckoutInfo:+ manager: "PluginsManager" = field(compare=False)checkout: "Checkout"user: Optional["User"]channel: "Channel"billing_address: Optional["Address"]shipping_address: Optional["Address"]- delivery_method_info: "DeliveryMethodBase"- all_shipping_methods: list["ShippingMethodData"]tax_configuration: "TaxConfiguration"- valid_pick_up_points: list["Warehouse"]discounts: list["CheckoutDiscount"]+ lines: Iterable[CheckoutLineInfo]+ shipping_channel_listings: list["ShippingMethodChannelListing"]+ shipping_method: Optional["ShippingMethod"] = None+ collection_point: Optional["Warehouse"] = Nonevoucher: Optional["Voucher"] = Nonevoucher_code: Optional["VoucherCode"] = None+ @cached_property+ def all_shipping_methods(self) -> list["ShippingMethodData"]:+ all_methods = get_all_shipping_methods_list(+ self,+ self.shipping_address,+ self.lines,+ self.shipping_channel_listings,+ self.manager,+ )+ # Filter shipping methods using sync webhooks+ excluded_methods = self.manager.excluded_shipping_methods_for_checkout(+ self.checkout,+ self.channel,+ all_methods,+ )+ initialize_shipping_method_active_status(all_methods, excluded_methods)+ return all_methods++ @cached_property+ def valid_pick_up_points(self) -> Iterable["Warehouse"]:+ from .utils import get_valid_collection_points_for_checkout++ return list(+ get_valid_collection_points_for_checkout(+ self.lines, self.channel.id, quantity_check=False+ )+ )++ @property+ def delivery_method_info(self) -> "DeliveryMethodBase":+ from ..webhook.transport.shipping import convert_to_app_id_with_identifier+ from .utils import get_external_shipping_id++ delivery_method: Optional[Union[ShippingMethodData, Warehouse, Callable]] = None++ if self.shipping_method:+ # Find listing for the currently selected shipping method+ shipping_channel_listing = None+ for listing in self.shipping_channel_listings:+ if listing.shipping_method_id == self.shipping_method.id:+ shipping_channel_listing = listing+ break++ if shipping_channel_listing:+ delivery_method = convert_to_shipping_method_data(+ self.shipping_method, shipping_channel_listing+ )++ elif external_shipping_method_id := get_external_shipping_id(self.checkout):++ def _resolve_external_method():+ methods = {method.id: method for method in self.all_shipping_methods}+ if method := methods.get(external_shipping_method_id):+ return method+ new_shipping_method_id = convert_to_app_id_with_identifier(+ external_shipping_method_id+ )+ return methods.get(new_shipping_method_id)++ delivery_method = _resolve_external_method++ else:+ delivery_method = self.collection_point++ return get_delivery_method_info(delivery_method, self.shipping_address)+@propertydef valid_shipping_methods(self) -> list["ShippingMethodData"]:return [method for method in self.all_shipping_methods if method.active]@@ -432,7 +499,6 @@ def fetch_checkout_info(shipping_channel_listings: Optional[Iterable["ShippingMethodChannelListing"]] = None,- fetch_delivery_methods=True,voucher: Optional["Voucher"] = None,voucher_code: Optional["VoucherCode"] = None,database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,@@ -453,113 +519,25 @@ def fetch_checkout_info(database_connection_name=database_connection_name,)- delivery_method_info = get_delivery_method_info(None, shipping_address)checkout_info = CheckoutInfo(checkout=checkout,user=checkout.user,channel=channel,billing_address=checkout.billing_address,shipping_address=shipping_address,- delivery_method_info=delivery_method_info,tax_configuration=tax_configuration,- all_shipping_methods=[],- valid_pick_up_points=[],discounts=list(checkout.discounts.all()),+ lines=lines,+ manager=manager,+ shipping_channel_listings=list(shipping_channel_listings),+ shipping_method=checkout.shipping_method,+ collection_point=checkout.collection_point,voucher=voucher,voucher_code=voucher_code,)- if fetch_delivery_methods:- update_delivery_method_lists_for_checkout_info(- checkout_info,- checkout.shipping_method,- checkout.collection_point,- shipping_address,- lines,- manager,- shipping_channel_listings,- database_connection_name=database_connection_name,- )-return checkout_info-def update_checkout_info_delivery_method_info(- checkout_info: CheckoutInfo,- shipping_method: Optional[ShippingMethod],- collection_point: Optional[Warehouse],- shipping_channel_listings: Iterable[ShippingMethodChannelListing],-):- """Update delivery_method_attribute for CheckoutInfo.-- The attribute is lazy-evaluated avoid external API calls unless accessed.- """- from ..webhook.transport.shipping import convert_to_app_id_with_identifier- from .utils import get_external_shipping_id-- delivery_method: Optional[Union[ShippingMethodData, Warehouse, Callable]] = None- checkout = checkout_info.checkout- if shipping_method:- # Find listing for the currently selected shipping method- shipping_channel_listing = None- for listing in shipping_channel_listings:- if listing.shipping_method_id == shipping_method.id:- shipping_channel_listing = listing- break-- if shipping_channel_listing:- delivery_method = convert_to_shipping_method_data(- shipping_method, shipping_channel_listing- )-- elif external_shipping_method_id := get_external_shipping_id(checkout):- # A local function is used to delay evaluation- # of the lazy `all_shipping_methods` attribute- def _resolve_external_method():- methods = {- method.id: method for method in checkout_info.all_shipping_methods- }- if method := methods.get(external_shipping_method_id):- return method- new_shipping_method_id = convert_to_app_id_with_identifier(- external_shipping_method_id- )- return methods.get(new_shipping_method_id)-- delivery_method = _resolve_external_method-- else:- delivery_method = collection_point-- checkout_info.delivery_method_info = lazy_no_retry(- lambda: get_delivery_method_info(- delivery_method,- checkout_info.shipping_address,- )- ) # type: ignore[assignment] # using SimpleLazyObject breaks protocol---def update_checkout_info_shipping_address(- checkout_info: CheckoutInfo,- address: Optional["Address"],- lines: Iterable[CheckoutLineInfo],- manager: "PluginsManager",- shipping_channel_listings: Iterable["ShippingMethodChannelListing"],- database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,-):- checkout_info.shipping_address = address-- update_delivery_method_lists_for_checkout_info(- checkout_info,- checkout_info.checkout.shipping_method,- checkout_info.checkout.collection_point,- address,- lines,- manager,- shipping_channel_listings,- database_connection_name=database_connection_name,- )--def get_valid_internal_shipping_method_list_for_checkout_info(checkout_info: "CheckoutInfo",shipping_address: Optional["Address"],@@ -605,17 +583,6 @@ def get_valid_internal_shipping_method_list_for_checkout_info(return valid_shipping_methods-def get_valid_external_shipping_method_list_for_checkout_info(- checkout_info: "CheckoutInfo",- shipping_address: Optional["Address"],- lines: Iterable[CheckoutLineInfo],- manager: "PluginsManager",-) -> list["ShippingMethodData"]:- return manager.list_shipping_methods_for_checkout(- checkout=checkout_info.checkout, channel_slug=checkout_info.channel.slug- )--def get_all_shipping_methods_list(checkout_info,shipping_address,@@ -633,8 +600,8 @@ def get_all_shipping_methods_list(shipping_channel_listings,database_connection_name=database_connection_name,),- get_valid_external_shipping_method_list_for_checkout_info(- checkout_info, shipping_address, lines, manager+ manager.list_shipping_methods_for_checkout(+ checkout=checkout_info.checkout, channel_slug=checkout_info.channel.slug),))@@ -646,75 +613,27 @@ def update_delivery_method_lists_for_checkout_info(collection_point: Optional["Warehouse"],shipping_address: Optional["Address"],lines: Iterable[CheckoutLineInfo],- manager: "PluginsManager",shipping_channel_listings: Iterable[ShippingMethodChannelListing],database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,):- """Update the list of shipping methods for checkout info.-- Shipping methods excluded by Saleor's own business logic are not present- in the result list.-- Availability of shipping methods according to plugins is indicated- by the `active` field.- """-- def _resolve_all_shipping_methods():- # Fetch all shipping method from all sources, including sync webhooks- all_methods = get_all_shipping_methods_list(- checkout_info,- shipping_address,- lines,- shipping_channel_listings,- manager,- database_connection_name=database_connection_name,- )- # Filter shipping methods using sync webhooks- excluded_methods = manager.excluded_shipping_methods_for_checkout(- checkout_info.checkout, checkout_info.channel, all_methods- )- initialize_shipping_method_active_status(all_methods, excluded_methods)- return all_methods-- checkout_info.all_shipping_methods = lazy_no_retry(_resolve_all_shipping_methods) # type: ignore[assignment] # using lazy object breaks protocol- checkout_info.valid_pick_up_points = lazy_no_retry(- lambda: (- get_valid_collection_points_for_checkout_info(- lines, checkout_info, database_connection_name=database_connection_name- )- )- ) # type: ignore[assignment] # using lazy object breaks protocol- update_checkout_info_delivery_method_info(- checkout_info,- shipping_method,- collection_point,- shipping_channel_listings,- )---def get_valid_collection_points_for_checkout_info(- lines: Iterable[CheckoutLineInfo],- checkout_info: CheckoutInfo,- database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,-):- from .utils import get_valid_collection_points_for_checkout-- valid_collection_points = get_valid_collection_points_for_checkout(- lines,- checkout_info.channel.id,- quantity_check=False,- database_connection_name=database_connection_name,- )- return list(valid_collection_points)-+ # Update checkout info fields with new data+ checkout_info.shipping_method = shipping_method+ checkout_info.collection_point = collection_point+ checkout_info.shipping_address = shipping_address+ checkout_info.lines = lines+ checkout_info.shipping_channel_listings = list(shipping_channel_listings)++ # Clear cached properties if they were already calculated, so they can be+ # recalculated.+ try:+ del checkout_info.all_shipping_methods+ except AttributeError:+ pass-def update_checkout_info_delivery_method(- checkout_info: CheckoutInfo,- delivery_method: Optional[Union["ShippingMethodData", "Warehouse"]],-):- checkout_info.delivery_method_info = get_delivery_method_info(- delivery_method, checkout_info.shipping_address- )+ try:+ del checkout_info.valid_pick_up_points+ except AttributeError:+ passdef find_checkout_line_info(diff --git a/saleor/checkout/tests/test_checkout.py b/saleor/checkout/tests/test_checkout.pyindex d2b0b5d508..baa1ff931f 100644--- a/saleor/checkout/tests/test_checkout.py+++ b/saleor/checkout/tests/test_checkout.py@@ -39,7 +39,6 @@ from ..fetch import (DeliveryMethodBase,fetch_checkout_info,fetch_checkout_lines,- get_delivery_method_info,)from ..models import Checkout, CheckoutLinefrom ..utils import (@@ -324,18 +323,7 @@ def test_get_discount_for_checkout_value_entire_order_voucher("saleor.checkout.base_calculations.base_checkout_subtotal",lambda *args: subtotal,)- checkout_info = CheckoutInfo(- checkout=checkout,- shipping_address=None,- billing_address=None,- channel=channel_USD,- user=None,- tax_configuration=channel_USD.tax_configuration,- valid_pick_up_points=[],- delivery_method_info=get_delivery_method_info(None, None),- all_shipping_methods=[],- discounts=[],- )+ manager = get_plugins_manager(allow_replica=False)lines = [CheckoutLineInfo(line=line,@@ -350,7 +338,18 @@ def test_get_discount_for_checkout_value_entire_order_voucher()for line in checkout_with_items.lines.all()]- manager = get_plugins_manager(allow_replica=False)+ checkout_info = CheckoutInfo(+ checkout=checkout,+ shipping_address=None,+ billing_address=None,+ channel=channel_USD,+ user=None,+ tax_configuration=channel_USD.tax_configuration,+ manager=manager,+ lines=lines,+ shipping_channel_listings=[],+ discounts=[],+ )# whendiscount = get_voucher_discount_for_checkout(@@ -489,18 +488,6 @@ def test_get_discount_for_checkout_value_specific_product_voucher("saleor.checkout.base_calculations.base_checkout_subtotal",lambda *args: subtotal,)- checkout_info = CheckoutInfo(- checkout=checkout,- shipping_address=None,- billing_address=None,- channel=channel_USD,- user=None,- tax_configuration=channel_USD.tax_configuration,- valid_pick_up_points=[],- delivery_method_info=get_delivery_method_info(None, None),- all_shipping_methods=[],- discounts=[],- )lines = [CheckoutLineInfo(line=line,@@ -516,6 +503,18 @@ def test_get_discount_for_checkout_value_specific_product_voucher(for line in checkout_with_items.lines.all()]manager = get_plugins_manager(allow_replica=False)+ checkout_info = CheckoutInfo(+ checkout=checkout,+ shipping_address=None,+ billing_address=None,+ channel=channel_USD,+ user=None,+ tax_configuration=channel_USD.tax_configuration,+ manager=manager,+ lines=lines,+ shipping_channel_listings=[],+ discounts=[],+ )# whendiscount = get_voucher_discount_for_checkout(@@ -605,19 +604,19 @@ def test_get_discount_for_checkout_entire_order_voucher_not_applicable("saleor.checkout.base_calculations.base_checkout_subtotal",lambda *args: subtotal,)+ manager = get_plugins_manager(allow_replica=False)checkout_info = CheckoutInfo(checkout=checkout,- delivery_method_info=None,shipping_address=None,billing_address=None,channel=channel_USD,user=None,tax_configuration=channel_USD.tax_configuration,- valid_pick_up_points=[],- all_shipping_methods=[],+ manager=manager,+ lines=[],+ shipping_channel_listings=[],discounts=[],)- manager = get_plugins_manager(allow_replica=False)with pytest.raises(NotApplicable):get_voucher_discount_for_checkout(manager, voucher, checkout_info, [], None)@@ -787,14 +786,14 @@ def test_get_discount_for_checkout_specific_products_voucher_not_applicable(checkout = Mock(quantity=total_quantity, spec=Checkout, channel=channel_USD)checkout_info = CheckoutInfo(checkout=checkout,- delivery_method_info=get_delivery_method_info(None, None),shipping_address=None,billing_address=None,channel=channel_USD,user=None,tax_configuration=channel_USD.tax_configuration,- valid_pick_up_points=[],- all_shipping_methods=[],+ manager=manager,+ lines=[],+ shipping_channel_listings=[],discounts=[],)with pytest.raises(NotApplicable):@@ -855,7 +854,6 @@ def test_get_discount_for_checkout_shipping_voucher(monkeypatch,channel_USD,shipping_method,- shipping_method_data,):manager = get_plugins_manager(allow_replica=False)tax = Decimal("1.23")@@ -894,15 +892,14 @@ def test_get_discount_for_checkout_shipping_voucher(checkout_info = CheckoutInfo(checkout=checkout,shipping_address=shipping_address,- delivery_method_info=get_delivery_method_info(- shipping_method_data, shipping_address- ),billing_address=None,channel=channel_USD,user=None,tax_configuration=channel_USD.tax_configuration,- valid_pick_up_points=[],- all_shipping_methods=[],+ manager=manager,+ shipping_method=shipping_method,+ lines=[],+ shipping_channel_listings=shipping_method.channel_listings.all(),discounts=[],)@@ -913,7 +910,7 @@ def test_get_discount_for_checkout_shipping_voucher(def test_get_discount_for_checkout_shipping_voucher_all_countries(- monkeypatch, channel_USD, shipping_method, shipping_method_data+ monkeypatch, channel_USD, shipping_method):subtotal = Money(100, "USD")monkeypatch.setattr(@@ -948,14 +945,15 @@ def test_get_discount_for_checkout_shipping_voucher_all_countries(manager = get_plugins_manager(allow_replica=False)checkout_info = CheckoutInfo(checkout=checkout,- delivery_method_info=get_delivery_method_info(shipping_method_data),shipping_address=Mock(spec=Address, country=Mock(code="PL")),billing_address=None,channel=channel_USD,user=None,tax_configuration=channel_USD.tax_configuration,- valid_pick_up_points=[],- all_shipping_methods=[],+ shipping_method=shipping_method,+ shipping_channel_listings=shipping_method.channel_listings.all(),+ manager=manager,+ lines=[],discounts=[],)discount = get_voucher_discount_for_checkout(@@ -993,19 +991,19 @@ def test_get_discount_for_checkout_shipping_voucher_limited_countries(discount=Money(50, channel_USD.currency_code),)+ manager = get_plugins_manager(allow_replica=False)checkout_info = CheckoutInfo(checkout=checkout,- delivery_method_info=get_delivery_method_info(None, None),shipping_address=Mock(spec=Address, country=Mock(code="PL")),billing_address=None,channel=channel_USD,user=None,tax_configuration=channel_USD.tax_configuration,- valid_pick_up_points=[],- all_shipping_methods=[],+ manager=manager,+ lines=[],+ shipping_channel_listings=[],discounts=[],)- manager = get_plugins_manager(allow_replica=False)with pytest.raises(NotApplicable):get_voucher_discount_for_checkout(manager,@@ -1126,6 +1124,13 @@ def test_get_discount_for_checkout_shipping_voucher_not_applicable(monkeypatch.setattr("saleor.checkout.utils.is_shipping_required", lambda lines: is_shipping_required)++ if shipping_method_data:+ shipping_channel_listings = shipping_method.channel_listings.all()+ else:+ shipping_method = None+ shipping_channel_listings = []+checkout = Mock(is_shipping_required=Mock(return_value=is_shipping_required),shipping_method=shipping_method,@@ -1133,6 +1138,7 @@ def test_get_discount_for_checkout_shipping_voucher_not_applicable(quantity=total_quantity,spec=Checkout,channel=channel_USD,+ get_value_from_private_metadata=Mock(return_value=None),)voucher = Voucher.objects.create(@@ -1151,14 +1157,15 @@ def test_get_discount_for_checkout_shipping_voucher_not_applicable()checkout_info = CheckoutInfo(checkout=checkout,- delivery_method_info=get_delivery_method_info(shipping_method_data),shipping_address=Mock(spec=Address, country=Mock(code="PL")),billing_address=None,channel=channel_USD,user=None,tax_configuration=channel_USD.tax_configuration,- valid_pick_up_points=[],- all_shipping_methods=[],+ manager=manager,+ lines=[],+ shipping_method=shipping_method,+ shipping_channel_listings=shipping_channel_listings,discounts=[],)with pytest.raises(NotApplicable) as e:@@ -1819,6 +1826,43 @@ def test_change_address_in_checkout_from_user_address_to_other(assert checkout_info.shipping_address == other_address+def test_change_address_in_checkout_invalidates_shipping_methods(+ checkout_with_items, address, shipping_method, shipping_zone+):+ # given+ checkout = checkout_with_items++ manager = get_plugins_manager(allow_replica=False)+ lines, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(+ checkout=checkout,+ lines=lines,+ manager=manager,+ shipping_channel_listings=shipping_method.channel_listings.all(),+ )++ all_shipping_methods = checkout_info.all_shipping_methods+ assert all_shipping_methods == []++ # when+ shipping_updated_fields = change_shipping_address_in_checkout(+ checkout_info,+ address,+ lines,+ manager,+ checkout.channel.shipping_method_listings.all(),+ )+ billing_updated_fields = change_billing_address_in_checkout(checkout, address)+ checkout.save(update_fields=shipping_updated_fields + billing_updated_fields)+ checkout.refresh_from_db()++ # then+ assert checkout.shipping_address == address+ assert checkout.billing_address == address+ assert checkout_info.shipping_address == address+ assert checkout_info.all_shipping_methods++def test_add_voucher_to_checkout(checkout_with_item, voucher):assert checkout_with_item.voucher_code is Nonemanager = get_plugins_manager(allow_replica=False)diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex ed90f3574d..0640f033f6 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -13,6 +13,7 @@ from django.utils import timezonefrom prices import Moneyfrom ..account.models import User+from ..checkout.fetch import update_delivery_method_lists_for_checkout_infofrom ..core.db.connection import allow_writerfrom ..core.exceptions import ProductNotPublishedfrom ..core.taxes import zero_taxed_money@@ -53,10 +54,6 @@ from ..warehouse.models import Warehousefrom ..warehouse.reservations import reserve_stocks_and_preordersfrom . import AddressType, base_calculations, calculationsfrom .error_codes import CheckoutErrorCode-from .fetch import (- update_checkout_info_delivery_method,- update_checkout_info_shipping_address,-)from .models import Checkout, CheckoutLine, CheckoutMetadataif TYPE_CHECKING:@@ -411,8 +408,13 @@ def change_shipping_address_in_checkout(if remove and checkout.shipping_address:checkout.shipping_address.delete()checkout.shipping_address = address- update_checkout_info_shipping_address(- checkout_info, address, lines, manager, shipping_channel_listings+ update_delivery_method_lists_for_checkout_info(+ checkout_info=checkout_info,+ shipping_method=checkout_info.checkout.shipping_method,+ collection_point=checkout_info.checkout.collection_point,+ shipping_address=address,+ lines=lines,+ shipping_channel_listings=shipping_channel_listings,)updated_fields = ["shipping_address", "last_change"]return updated_fields@@ -931,7 +933,17 @@ def clear_delivery_method(checkout_info: "CheckoutInfo"):checkout = checkout_info.checkoutcheckout.collection_point = Nonecheckout.shipping_method = None- update_checkout_info_delivery_method(checkout_info, None)+ checkout_info.shipping_method = None++ update_delivery_method_lists_for_checkout_info(+ checkout_info=checkout_info,+ shipping_method=None,+ collection_point=None,+ shipping_address=checkout_info.shipping_address,+ lines=checkout_info.lines,+ shipping_channel_listings=checkout_info.shipping_channel_listings,+ )+delete_external_shipping_id(checkout=checkout)checkout.save(update_fields=[diff --git a/saleor/graphql/checkout/dataloaders.py b/saleor/graphql/checkout/dataloaders.pyindex 80c44df819..b3e2a8b5e4 100644--- a/saleor/graphql/checkout/dataloaders.py+++ b/saleor/graphql/checkout/dataloaders.py@@ -8,8 +8,6 @@ from ...checkout.fetch import (CheckoutInfo,CheckoutLineInfo,apply_voucher_to_checkout_line,- get_delivery_method_info,- update_delivery_method_lists_for_checkout_info,)from ...checkout.models import Checkout, CheckoutLine, CheckoutMetadatafrom ...checkout.problems import (@@ -525,11 +523,15 @@ class CheckoutInfoByCheckoutTokenLoader(DataLoader[str, CheckoutInfo]):collection_point = collection_points_map.get(checkout.collection_point_id)- shipping_address = address_map.get(checkout.shipping_address_id)- delivery_method_info = get_delivery_method_info(- None, shipping_address- )voucher_code = voucher_code_map.get(checkout.voucher_code)++ shipping_channel_listings = [+ listing+ for channel_listings in listings_for_channels+ for listing in channel_listings+ if listing.channel_id == channel.id+ ]+checkout_info = CheckoutInfo(checkout=checkout,user=user_map.get(checkout.user_id),@@ -540,33 +542,18 @@ class CheckoutInfoByCheckoutTokenLoader(DataLoader[str, CheckoutInfo]):shipping_address=address_map.get(checkout.shipping_address_id),- delivery_method_info=delivery_method_info,tax_configuration=tax_configuration_by_channel_map[channel.id],- valid_pick_up_points=[],- all_shipping_methods=[],discounts=discounts,+ lines=checkout_lines,+ manager=manager,+ shipping_channel_listings=shipping_channel_listings,+ shipping_method=shipping_method,+ collection_point=collection_point,voucher=voucher_code.voucher if voucher_code else None,voucher_code=voucher_code,)- shipping_method_listings = [- listing- for channel_listings in listings_for_channels- for listing in channel_listings- if listing.channel_id == channel.id- ]- with allow_writer_in_context(self.context):- update_delivery_method_lists_for_checkout_info(- checkout_info,- shipping_method,- collection_point,- shipping_address,- checkout_lines,- manager,- shipping_method_listings,- database_connection_name=self.database_connection_name,- )checkout_info_map[key] = checkout_inforeturn [checkout_info_map[key] for key in keys]diff --git a/saleor/graphql/checkout/mutations/checkout_add_promo_code.py b/saleor/graphql/checkout/mutations/checkout_add_promo_code.pyindex 3382d91bb9..2300db2835 100644--- a/saleor/graphql/checkout/mutations/checkout_add_promo_code.py+++ b/saleor/graphql/checkout/mutations/checkout_add_promo_code.py@@ -104,13 +104,12 @@ class CheckoutAddPromoCode(BaseMutation):)update_delivery_method_lists_for_checkout_info(- checkout_info,- checkout_info.checkout.shipping_method,- checkout_info.checkout.collection_point,- checkout_info.shipping_address,- lines,- manager,- shipping_channel_listings,+ checkout_info=checkout_info,+ shipping_method=checkout_info.checkout.shipping_method,+ collection_point=checkout_info.checkout.collection_point,+ shipping_address=checkout_info.shipping_address,+ lines=lines,+ shipping_channel_listings=shipping_channel_listings,)update_checkout_shipping_method_if_invalid(checkout_info, lines)diff --git a/saleor/graphql/checkout/mutations/checkout_lines_add.py b/saleor/graphql/checkout/mutations/checkout_lines_add.pyindex 0d86735a1d..9baadc1404 100644--- a/saleor/graphql/checkout/mutations/checkout_lines_add.py+++ b/saleor/graphql/checkout/mutations/checkout_lines_add.py@@ -165,13 +165,12 @@ class CheckoutLinesAdd(BaseMutation):lines, _ = fetch_checkout_lines(checkout)shipping_channel_listings = checkout.channel.shipping_method_listings.all()update_delivery_method_lists_for_checkout_info(- checkout_info,- checkout_info.checkout.shipping_method,- checkout_info.checkout.collection_point,- checkout_info.shipping_address,- lines,- manager,- shipping_channel_listings,+ checkout_info=checkout_info,+ shipping_method=checkout_info.checkout.shipping_method,+ collection_point=checkout_info.checkout.collection_point,+ shipping_address=checkout_info.shipping_address,+ lines=lines,+ shipping_channel_listings=shipping_channel_listings,)return linesdiff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.pyindex 5d0c084f38..134f9b134b 100644--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py@@ -821,7 +821,7 @@ def test_update_checkout_lines_with_reservations(reservation_length=5,)- with django_assert_num_queries(91):+ with django_assert_num_queries(93):variant_id = graphene.Node.to_global_id("ProductVariant", variants[0].pk)variables = {"id": to_global_id_or_none(checkout),@@ -835,7 +835,7 @@ def test_update_checkout_lines_with_reservations(assert not data["errors"]# Updating multiple lines in checkout has same query count as updating one- with django_assert_num_queries(91):+ with django_assert_num_queries(93):variables = {"id": to_global_id_or_none(checkout),"lines": [],@@ -1080,7 +1080,7 @@ def test_add_checkout_lines_with_reservations(new_lines.append({"quantity": 2, "variantId": variant_id})# Adding multiple lines to checkout has same query count as adding one- with django_assert_num_queries(90):+ with django_assert_num_queries(92):variables = {"id": Node.to_global_id("Checkout", checkout.pk),"lines": [new_lines[0]],@@ -1093,7 +1093,7 @@ def test_add_checkout_lines_with_reservations(checkout.lines.exclude(id=line.id).delete()- with django_assert_num_queries(90):+ with django_assert_num_queries(92):variables = {"id": Node.to_global_id("Checkout", checkout.pk),"lines": new_lines,@@ -1143,7 +1143,7 @@ def test_add_checkout_lines_catalogue_discount_applies(}# when- with django_assert_num_queries(82):+ with django_assert_num_queries(84):response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)# then@@ -1228,7 +1228,7 @@ def test_add_checkout_lines_multiple_catalogue_discount_applies(}# when- with django_assert_num_queries(82):+ with django_assert_num_queries(84):response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)# then@@ -1263,7 +1263,7 @@ def test_add_checkout_lines_order_discount_applies(}# when- with django_assert_num_queries(85):+ with django_assert_num_queries(87):response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)# then@@ -1297,7 +1297,7 @@ def test_add_checkout_lines_gift_discount_applies(}# when- with django_assert_num_queries(112):+ with django_assert_num_queries(114):response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)# thendiff --git a/saleor/graphql/checkout/tests/deprecated/test_checkout_shipping_method_update.py b/saleor/graphql/checkout/tests/deprecated/test_checkout_shipping_method_update.pyindex 36b2a19bc8..a7fc4a6107 100644--- a/saleor/graphql/checkout/tests/deprecated/test_checkout_shipping_method_update.py+++ b/saleor/graphql/checkout/tests/deprecated/test_checkout_shipping_method_update.py@@ -6,7 +6,6 @@ from .....checkout.error_codes import CheckoutErrorCodefrom .....checkout.fetch import (fetch_checkout_info,fetch_checkout_lines,- get_delivery_method_info,)from .....plugins.manager import get_plugins_managerfrom .....shipping.utils import convert_to_shipping_method_data@@ -45,7 +44,6 @@ def test_checkout_shipping_method_update_by_id(checkout_with_item_and_shipping_method,):checkout = checkout_with_item_and_shipping_method- old_shipping_method = checkout.shipping_methodquery = MUTATION_UPDATE_SHIPPING_METHODmock_clean_shipping.return_value = True@@ -62,12 +60,6 @@ def test_checkout_shipping_method_update_by_id(manager = get_plugins_manager(allow_replica=False)lines, _ = fetch_checkout_lines(checkout)checkout_info = fetch_checkout_info(checkout, lines, manager)- checkout_info.delivery_method_info = get_delivery_method_info(- convert_to_shipping_method_data(- old_shipping_method, old_shipping_method.channel_listings.first()- ),- None,- )mock_clean_shipping.assert_called_once_with(checkout_info=checkout_info,@@ -93,7 +85,6 @@ def test_checkout_shipping_method_update_by_token(checkout_with_item_and_shipping_method,):checkout = checkout_with_item_and_shipping_method- old_shipping_method = checkout.shipping_methodquery = MUTATION_UPDATE_SHIPPING_METHODmock_clean_shipping.return_value = True@@ -110,12 +101,7 @@ def test_checkout_shipping_method_update_by_token(manager = get_plugins_manager(allow_replica=False)lines, _ = fetch_checkout_lines(checkout)checkout_info = fetch_checkout_info(checkout, lines, manager)- checkout_info.delivery_method_info = get_delivery_method_info(- convert_to_shipping_method_data(- old_shipping_method, old_shipping_method.channel_listings.first()- ),- None,- )+mock_clean_shipping.assert_called_once_with(checkout_info=checkout_info,lines=lines,@@ -189,7 +175,6 @@ def test_checkout_shipping_method_update_by_id_no_checkout_metadata():# givencheckout = checkout_with_item_and_shipping_method- old_shipping_method = checkout.shipping_methodquery = MUTATION_UPDATE_SHIPPING_METHODmock_clean_shipping.return_value = True@@ -211,12 +196,6 @@ def test_checkout_shipping_method_update_by_id_no_checkout_metadata(manager = get_plugins_manager(allow_replica=False)lines, _ = fetch_checkout_lines(checkout)checkout_info = fetch_checkout_info(checkout, lines, manager)- checkout_info.delivery_method_info = get_delivery_method_info(- convert_to_shipping_method_data(- old_shipping_method, old_shipping_method.channel_listings.first()- ),- None,- )mock_clean_shipping.assert_called_once_with(checkout_info=checkout_info,diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.pyindex 9f950db075..4e129b0942 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_method_update.py@@ -9,7 +9,6 @@ from .....checkout.error_codes import CheckoutErrorCodefrom .....checkout.fetch import (fetch_checkout_info,fetch_checkout_lines,- get_delivery_method_info,)from .....checkout.utils import PRIVATE_META_APP_SHIPPING_ID, invalidate_checkoutfrom .....plugins.base_plugin import ExcludedShippingMethod@@ -73,12 +72,6 @@ def test_checkout_shipping_method_update(manager = get_plugins_manager(allow_replica=False)lines, _ = fetch_checkout_lines(checkout)checkout_info = fetch_checkout_info(checkout, lines, manager)- checkout_info.delivery_method_info = get_delivery_method_info(- convert_to_shipping_method_data(- old_shipping_method, old_shipping_method.channel_listings.first()- ),- None,- )mock_clean_shipping.assert_called_once_with(checkout_info=checkout_info,lines=lines,diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.pyindex e39fe12800..ca0ba8341e 100644--- a/saleor/graphql/checkout/types.py+++ b/saleor/graphql/checkout/types.py@@ -14,7 +14,6 @@ from ...checkout.calculations import fetch_checkout_datafrom ...checkout.utils import get_valid_collection_points_for_checkoutfrom ...core.db.connection import allow_writer_in_contextfrom ...core.taxes import zero_money, zero_taxed_money-from ...core.utils.lazyobjects import unwrap_lazyfrom ...graphql.core.context import get_database_connection_namefrom ...payment.interface import ListStoredPaymentMethodsRequestDatafrom ...permission.auth_filters import AuthorizationFilters@@ -860,7 +859,7 @@ class Checkout(ModelObjectType[models.Checkout]):def resolve_shipping_methods(root: models.Checkout, info: ResolveInfo):@allow_writer_in_context(info.context)def with_checkout_info(checkout_info):- return unwrap_lazy(checkout_info.all_shipping_methods)+ return checkout_info.all_shipping_methodsreturn (CheckoutInfoByCheckoutTokenLoader(info.context)diff --git a/saleor/graphql/context.py b/saleor/graphql/context.pyindex 79702cbcd2..f50d02e241 100644--- a/saleor/graphql/context.py+++ b/saleor/graphql/context.py@@ -26,6 +26,10 @@ def get_context_value(request: HttpRequest) -> SaleorContext:return request+def clear_context(context: SaleorContext):+ context.dataloaders.clear()++class RequestWithUser(HttpRequest):_cached_user: Optional[User]app: Optional[App]diff --git a/saleor/graphql/core/dataloaders.py b/saleor/graphql/core/dataloaders.pyindex 329470986c..8942a59f96 100644--- a/saleor/graphql/core/dataloaders.py+++ b/saleor/graphql/core/dataloaders.py@@ -40,6 +40,11 @@ class DataLoader(BaseLoader, Generic[K, R]):self.database_connection_name = get_database_connection_name(context)super().__init__()+ def __del__(self):+ self._promise_cache.clear()+ self._queue.clear()+ self._scheduler = None+def batch_load_fn( # pylint: disable=method-hiddenself, keys: Iterable[K]) -> Promise[list[R]]:diff --git a/saleor/graphql/core/tests/test_view.py b/saleor/graphql/core/tests/test_view.pyindex fca7fd88b5..725c58376e 100644--- a/saleor/graphql/core/tests/test_view.py+++ b/saleor/graphql/core/tests/test_view.py@@ -1,3 +1,4 @@+import jsonfrom unittest import mockimport graphene@@ -6,10 +7,11 @@ from django.test import override_settingsfrom graphql.execution.base import ExecutionResultfrom .... import __version__ as saleor_version+from ....graphql.api import backend, schemafrom ....graphql.utils import INTERNAL_ERROR_MESSAGEfrom ...tests.fixtures import API_PATHfrom ...tests.utils import get_graphql_content, get_graphql_content_from_response-from ...views import generate_cache_key+from ...views import GraphQLView, generate_cache_keydef test_batch_queries(category, product, api_client, channel_USD):@@ -325,3 +327,23 @@ def test_introspection_query_is_not_cached_in_debug_mode(def test_generate_cache_key_use_saleor_version():cache_key = generate_cache_key(INTROSPECTION_QUERY)assert saleor_version in cache_key+++def test_graphql_view_clears_context(rf, staff_user, product):+ # given+ product_id = graphene.Node.to_global_id("Product", product.pk)+ data = {"query": '{ product(id: "%s") { name category { name } } }' % product_id}+ request = rf.post(path="/", data=data, content_type="application/json")+ request.app = None+ request.user = staff_user++ # when+ view = GraphQLView.as_view(backend=backend, schema=schema)+ response = view(request)++ # then+ json_data = json.loads(response.content)+ assert json_data["data"]["product"]["name"] == product.name+ assert json_data["data"]["product"]["category"]["name"] == product.category.name+ assert response.status_code == 200+ assert request.dataloaders == {}diff --git a/saleor/graphql/plugins/tests/test_mutation_plugin_update.py b/saleor/graphql/plugins/tests/test_mutation_plugin_update.pyindex 5ef7f1a17c..2b010f23f9 100644--- a/saleor/graphql/plugins/tests/test_mutation_plugin_update.py+++ b/saleor/graphql/plugins/tests/test_mutation_plugin_update.py@@ -326,9 +326,9 @@ def test_cannot_update_configuration_of_hidden_plugin(settings.PLUGINS = ["saleor.plugins.tests.sample_plugins.PluginSample"]plugin_id = PluginSample.PLUGIN_ID- original_config = (- get_plugins_manager(allow_replica=False).get_plugin(plugin_id).configuration- )+ manager = get_plugins_manager(allow_replica=False)+ plugin = manager.get_plugin(plugin_id)+ original_config = plugin.configurationvariables = {"id": plugin_id,@@ -347,7 +347,7 @@ def test_cannot_update_configuration_of_hidden_plugin(]# Hidden plugin should be untouched- plugin = get_plugins_manager(allow_replica=False).get_plugin(plugin_id)+ plugin = manager.get_plugin(plugin_id)assert plugin.active is Trueassert plugin.configuration == original_config@@ -370,11 +370,9 @@ def test_cannot_update_configuration_of_hidden_multichannel_plugin(settings.PLUGINS = ["saleor.plugins.tests.sample_plugins.ChannelPluginSample"]plugin_id = ChannelPluginSample.PLUGIN_ID- original_config = (- get_plugins_manager(allow_replica=False)- .get_plugin(plugin_id, channel_slug=channel_USD.slug)- .configuration- )+ manager = get_plugins_manager(allow_replica=False)+ plugin = manager.get_plugin(plugin_id, channel_slug=channel_USD.slug)+ original_config = plugin.configurationvariables = {"id": plugin_id,@@ -393,9 +391,7 @@ def test_cannot_update_configuration_of_hidden_multichannel_plugin(]# Hidden plugin should be untouched- plugin = get_plugins_manager(allow_replica=False).get_plugin(- plugin_id, channel_slug=channel_USD.slug- )+ plugin = manager.get_plugin(plugin_id, channel_slug=channel_USD.slug)assert plugin.active is Trueassert plugin.configuration == original_configdiff --git a/saleor/graphql/tests/test_context.py b/saleor/graphql/tests/test_context.pyindex 81bfccb84d..6c5d0b592a 100644--- a/saleor/graphql/tests/test_context.py+++ b/saleor/graphql/tests/test_context.py@@ -3,7 +3,7 @@ from unittest import mockimport graphenefrom django.utils import timezone-from ..context import get_context_value+from ..context import clear_context, get_context_valuefrom .utils import get_graphql_contentQUERY_ORDER_BY_ID = """@@ -71,3 +71,15 @@ def test_get_context_value_uses_request_time_if_passed_already(rf):# thenassert context.request_time == request_time+++def test_clear_context(rf):+ # given+ context = get_context_value(rf.request())+ context.dataloaders = {"key": "value"} # type: ignore++ # when+ clear_context(context)++ # then+ assert context.dataloaders == {}diff --git a/saleor/graphql/views.py b/saleor/graphql/views.pyindex 4528fff96d..24adc05c22 100644--- a/saleor/graphql/views.py+++ b/saleor/graphql/views.py@@ -24,7 +24,7 @@ from ..core.exceptions import PermissionDeniedfrom ..core.utils import is_valid_ipv4, is_valid_ipv6from ..webhook import observabilityfrom .api import API_PATH, schema-from .context import get_context_value+from .context import clear_context, get_context_valuefrom .core.validators.query_cost import validate_query_costfrom .query_cost_map import COST_MAPfrom .utils import format_error, query_fingerprint, query_identifier@@ -350,6 +350,8 @@ class GraphQLView(View):if str(e).startswith(INT_ERROR_MSG) or isinstance(e, ValueError):e = GraphQLError(str(e))return ExecutionResult(errors=[e], invalid=True)+ finally:+ clear_context(context)@staticmethoddef parse_body(request: HttpRequest):diff --git a/saleor/graphql/webhook/resolvers.py b/saleor/graphql/webhook/resolvers.pyindex c4f49e29ff..e0a538593b 100644--- a/saleor/graphql/webhook/resolvers.py+++ b/saleor/graphql/webhook/resolvers.py@@ -75,7 +75,6 @@ def resolve_shipping_methods_for_checkout(lines,manager,shipping_channel_listings,- fetch_delivery_methods=False,database_connection_name=database_connection_name,)all_shipping_methods = get_all_shipping_methods_list(diff --git a/saleor/plugins/avatax/tests/cassettes/test_avatax/test_get_checkout_line_tax_rate_for_product_with_charge_taxes_set_to_false.yaml b/saleor/plugins/avatax/tests/cassettes/test_avatax/test_get_checkout_line_tax_rate_for_product_with_charge_taxes_set_to_false.yamlnew file mode 100644index 0000000000..4e30746339--- /dev/null+++ b/saleor/plugins/avatax/tests/cassettes/test_avatax/test_get_checkout_line_tax_rate_for_product_with_charge_taxes_set_to_false.yaml@@ -0,0 +1,74 @@+interactions:+- request:+ body: '{"createTransactionModel": {"companyCode": "DEFAULT", "type": "SalesOrder",+ "lines": [{"quantity": 3, "amount": "30.00", "taxCode": "NT", "taxIncluded":+ false, "itemCode": "123", "discounted": false, "description": "Test product",+ "ref1": "123"}, {"quantity": 1, "amount": "10.000", "taxCode": "FR000000", "taxIncluded":+ false, "itemCode": "Shipping", "discounted": false, "description": null}], "code":+ "db304eb2-b138-47fc-b9ee-ec979e3328dd", "date": "2024-04-23", "customerCode":+ 0, "discount": null, "addresses": {"shipFrom": {"line1": "Teczowa 7", "line2":+ "", "city": "Wroclaw", "region": "", "country": "PL", "postalCode": "53-601"},+ "shipTo": {"line1": "T\u0119czowa 7", "line2": "", "city": "WROC\u0141AW", "region":+ "", "country": "PL", "postalCode": "53-601"}}, "commit": false, "currencyCode":+ "USD", "email": "[email protected]"}}'+ headers:+ Accept:+ - '*/*'+ Accept-Encoding:+ - gzip, deflate, br+ Authorization:+ - Basic Og==+ Connection:+ - keep-alive+ Content-Length:+ - '839'+ User-Agent:+ - Saleor/3.18+ method: POST+ uri: https://sandbox-rest.avatax.com/api/v2/transactions/createoradjust+ response:+ body:+ string: '{"id":0,"code":"db304eb2-b138-47fc-b9ee-ec979e3328dd","companyId":7799660,"date":"2024-04-23","paymentDate":"2024-04-23","status":"Temporary","type":"SalesOrder","batchCode":"","currencyCode":"USD","exchangeRateCurrencyCode":"USD","customerUsageType":"","entityUseCode":"","customerVendorCode":"0","customerCode":"0","exemptNo":"","reconciled":false,"locationCode":"","reportingLocationCode":"","purchaseOrderNo":"","referenceCode":"","salespersonCode":"","totalAmount":40.0,"totalExempt":30.0,"totalDiscount":0.0,"totalTax":2.3,"totalTaxable":10.0,"totalTaxCalculated":2.3,"adjustmentReason":"NotAdjusted","locked":false,"version":1,"exchangeRateEffectiveDate":"2024-04-23","exchangeRate":1.0,"email":"[email protected]","modifiedDate":"2024-04-23T12:05:15.612755Z","modifiedUserId":6479978,"taxDate":"2024-04-23","lines":[{"id":0,"transactionId":0,"lineNumber":"1","customerUsageType":"","entityUseCode":"","description":"Test+ product","discountAmount":0.0,"exemptAmount":30.0,"exemptCertId":0,"exemptNo":"","isItemTaxable":false,"itemCode":"123","lineAmount":30.0,"quantity":3.0,"ref1":"123","ref2":"","reportingDate":"2024-04-23","sourcing":"Origin","tax":0.0,"taxableAmount":0.0,"taxCalculated":0.0,"taxCode":"NT","taxCodeId":16740,"taxDate":"2024-04-23","taxIncluded":false,"details":[{"id":0,"transactionLineId":0,"transactionId":0,"country":"PL","region":"PL","stateFIPS":"PL","exemptAmount":0.0,"jurisCode":"PL","jurisName":"POLAND","jurisdictionId":200102,"stateAssignedNo":"","jurisType":"CNT","jurisdictionType":"Country","nonTaxableAmount":30.0,"rate":0.230000,"sourcing":"Origin","tax":0.0,"taxableAmount":0.0,"taxType":"Output","taxSubTypeId":"O","taxName":"Standard+ Rate","taxAuthorityTypeId":45,"taxCalculated":0.0,"rateType":"Standard","rateTypeCode":"S","taxableUnits":0.0000,"nonTaxableUnits":30.0000,"exemptUnits":0.0000,"unitOfBasis":"PerCurrencyUnit","isNonPassThru":false,"isFee":false,"reportingTaxableUnits":0.0,"reportingNonTaxableUnits":30.0,"reportingExemptUnits":0.0,"reportingTax":0.0,"reportingTaxCalculated":0.0,"avtUserBIN":"","liabilityType":"Seller","chargedTo":"Buyer"}],"nonPassthroughDetails":[],"hsCode":"","costInsuranceFreight":0.0,"vatCode":"PLSL230C","vatNumberTypeId":0},{"id":0,"transactionId":0,"lineNumber":"2","customerUsageType":"","entityUseCode":"","discountAmount":0.0,"exemptAmount":0.0,"exemptCertId":0,"exemptNo":"","isItemTaxable":true,"itemCode":"Shipping","lineAmount":10.0,"quantity":1.0,"ref1":"","ref2":"","reportingDate":"2024-04-23","sourcing":"Destination","tax":2.3,"taxableAmount":10.0,"taxCalculated":2.3,"taxCode":"FR000000","taxCodeId":8550,"taxDate":"2024-04-23","taxIncluded":false,"details":[{"id":0,"transactionLineId":0,"transactionId":0,"country":"PL","region":"PL","stateFIPS":"PL","exemptAmount":0.0,"jurisCode":"PL","jurisName":"POLAND","jurisdictionId":200102,"stateAssignedNo":"","jurisType":"CNT","jurisdictionType":"Country","nonTaxableAmount":0.0,"rate":0.230000,"sourcing":"Destination","tax":2.3,"taxableAmount":10.0,"taxType":"Output","taxSubTypeId":"O","taxName":"Standard+ Rate","taxAuthorityTypeId":45,"taxCalculated":2.3,"rateType":"Standard","rateTypeCode":"S","taxableUnits":10.0000,"nonTaxableUnits":0.0000,"exemptUnits":0.0000,"unitOfBasis":"PerCurrencyUnit","isNonPassThru":false,"isFee":false,"reportingTaxableUnits":10.0,"reportingNonTaxableUnits":0.0,"reportingExemptUnits":0.0,"reportingTax":2.3,"reportingTaxCalculated":2.3,"liabilityType":"Seller","chargedTo":"Buyer"}],"nonPassthroughDetails":[],"hsCode":"","costInsuranceFreight":0.0,"vatCode":"PLS-230D","vatNumberTypeId":0}],"addresses":[{"id":0,"transactionId":0,"boundaryLevel":"Zip5","line1":"Teczowa+ 7","line2":"","line3":"","city":"WROCLAW","region":"","postalCode":"53-601","country":"PL","taxRegionId":205102,"latitude":"","longitude":""},{"id":0,"transactionId":0,"boundaryLevel":"Zip5","line1":"Teczowa+ 7","line2":"","line3":"","city":"Wroclaw","region":"","postalCode":"53-601","country":"PL","taxRegionId":205102,"latitude":"","longitude":""}],"summary":[{"country":"PL","region":"PL","jurisType":"Country","jurisCode":"PL","jurisName":"POLAND","taxAuthorityType":45,"stateAssignedNo":"","taxType":"Output","taxSubType":"O","taxName":"Standard+ Rate","rateType":"Standard","taxable":10.0,"rate":0.230000,"tax":2.3,"taxCalculated":2.3,"nonTaxable":30.0,"exemption":0.0}]}'+ headers:+ Connection:+ - keep-alive+ Content-Type:+ - application/json; charset=utf-8+ Date:+ - Tue, 23 Apr 2024 12:05:15 GMT+ Location:+ - /api/v2/companies/7799660/transactions/0+ ServerDuration:+ - '00:00:00.0214048'+ Transfer-Encoding:+ - chunked+ X-Content-Type-Options:+ - nosniff+ api-supported-versions:+ - '2.0'+ cache-control:+ - private, no-cache, no-store+ referrer-policy:+ - same-origin+ strict-transport-security:+ - max-age=31536000; includeSubdomains+ x-avalara-uid:+ - da7eea91-8b85-4703-a667-686f1ca2c3d9+ x-correlation-id:+ - da7eea91-8b85-4703-a667-686f1ca2c3d9+ x-frame-options:+ - sameorigin+ x-permitted-cross-domain-policies:+ - none+ x-xss-protection:+ - 1; mode=block+ status:+ code: 201+ message: Created+version: 1diff --git a/saleor/plugins/avatax/tests/conftest.py b/saleor/plugins/avatax/tests/conftest.pyindex e964fe4e91..594d03319e 100644--- a/saleor/plugins/avatax/tests/conftest.py+++ b/saleor/plugins/avatax/tests/conftest.py@@ -3,9 +3,9 @@ import osimport pytestfrom ....account.models import Address-from ....checkout.fetch import CheckoutInfo, get_delivery_method_info+from ....checkout.fetch import CheckoutInfo, fetch_checkout_linesfrom ....shipping.models import ShippingMethodChannelListing-from ....shipping.utils import convert_to_shipping_method_data+from ...manager import get_plugins_managerfrom ...models import PluginConfigurationfrom .. import AvataxConfigurationfrom ..plugin import AvataxPlugin@@ -109,20 +109,20 @@ def checkout_with_items_and_shipping_info(checkout_with_items_and_shipping):channel=channel,shipping_method=shipping_method,)+ manager = get_plugins_manager(allow_replica=False)+ lines, _ = fetch_checkout_lines(checkout)checkout_info = CheckoutInfo(checkout=checkout,user=checkout.user,channel=channel,billing_address=checkout.billing_address,shipping_address=shipping_address,- delivery_method_info=get_delivery_method_info(- convert_to_shipping_method_data(shipping_method, shipping_channel_listing),- shipping_address,- ),+ shipping_method=shipping_method,+ shipping_channel_listings=[shipping_channel_listing],tax_configuration=channel.tax_configuration,- valid_pick_up_points=[],- all_shipping_methods=[],discounts=[],+ manager=manager,+ lines=lines,)return checkout_infodiff --git a/saleor/plugins/avatax/tests/test_avatax.py b/saleor/plugins/avatax/tests/test_avatax.pyindex eb76f92509..6d8ffd72e3 100644--- a/saleor/plugins/avatax/tests/test_avatax.py+++ b/saleor/plugins/avatax/tests/test_avatax.py@@ -16,8 +16,6 @@ from ....checkout.fetch import (CheckoutInfo,fetch_checkout_info,fetch_checkout_lines,- get_delivery_method_info,- update_delivery_method_lists_for_checkout_info,)from ....checkout.utils import add_variant_to_checkoutfrom ....core.prices import quantize_price@@ -32,7 +30,6 @@ from ....product import ProductTypeKindfrom ....product.models import Product, ProductTypefrom ....product.utils.variant_prices import update_discounted_prices_for_promotionfrom ....product.utils.variants import fetch_variants_for_promotion_rules-from ....shipping.utils import convert_to_shipping_method_datafrom ....tax import TaxCalculationStrategyfrom ....tax.models import TaxClassfrom ...manager import get_plugins_manager@@ -2271,15 +2268,6 @@ def test_calculate_checkout_subtotal_for_product_without_tax(lines, _ = fetch_checkout_lines(checkout)assert len(lines) == 1- update_delivery_method_lists_for_checkout_info(- checkout_info,- checkout_info.checkout.shipping_method,- checkout_info.checkout.collection_point,- ship_to_pl_address,- lines,- manager,- checkout.channel.shipping_method_listings.all(),- )total = manager.calculate_checkout_subtotal(checkout_info, lines, address)total = quantize_price(total, total.currency)@@ -3779,26 +3767,21 @@ def test_get_checkout_line_tax_rate(checkout_with_item.shipping_address = addresscheckout_with_item.shipping_method = shipping_zone.shipping_methods.get()checkout_with_item.save(update_fields=["shipping_address", "shipping_method"])- delivery_method = checkout_with_item.shipping_method+ lines, _ = fetch_checkout_lines(checkout_with_item)+ shipping_method = checkout_with_item.shipping_methodcheckout_info = CheckoutInfo(checkout=checkout_with_item,- delivery_method_info=get_delivery_method_info(- convert_to_shipping_method_data(- delivery_method,- delivery_method.channel_listings.first(),- ),- address,- ),shipping_address=address,billing_address=None,channel=checkout_with_item.channel,user=None,tax_configuration=checkout_with_item.channel.tax_configuration,- valid_pick_up_points=[],- all_shipping_methods=[],discounts=[],+ manager=manager,+ lines=lines,+ shipping_method=shipping_method,+ shipping_channel_listings=shipping_method.channel_listings.all(),)- lines, _ = fetch_checkout_lines(checkout_with_item)checkout_line_info = lines[0]# when@@ -3845,26 +3828,22 @@ def test_get_checkout_line_tax_rate_for_product_with_charge_taxes_set_to_false(checkout_with_item.shipping_address = addresscheckout_with_item.shipping_method = shipping_zone.shipping_methods.get()checkout_with_item.save(update_fields=["shipping_address", "shipping_method"])- delivery_method = checkout_with_item.shipping_method+ lines, _ = fetch_checkout_lines(checkout_with_item)+ shipping_method = checkout_with_item.shipping_methodcheckout_info = CheckoutInfo(checkout=checkout_with_item,- delivery_method_info=get_delivery_method_info(- convert_to_shipping_method_data(- delivery_method,- delivery_method.channel_listings.first(),- )- ),shipping_address=address,billing_address=None,channel=checkout_with_item.channel,user=None,tax_configuration=checkout_with_item.channel.tax_configuration,- valid_pick_up_points=[],- all_shipping_methods=[],discounts=[],+ manager=manager,+ lines=lines,+ shipping_method=shipping_method,+ shipping_channel_listings=shipping_method.channel_listings.all(),)- lines, _ = fetch_checkout_lines(checkout_with_item)checkout_line_info = lines[0]product = checkout_line_info.productproduct.tax_class = tax_class_zero_rates@@ -3918,26 +3897,23 @@ def test_get_checkout_line_tax_rate_for_product_type_with_non_taxable_product(checkout_with_item.shipping_address = addresscheckout_with_item.shipping_method = shipping_zone.shipping_methods.get()checkout_with_item.save(update_fields=["shipping_address", "shipping_method"])- delivery_method = checkout_with_item.shipping_method++ lines, _ = fetch_checkout_lines(checkout_with_item)+ shipping_method = checkout_with_item.shipping_methodvariant2 = product2.variants.first()checkout_info = CheckoutInfo(checkout=checkout_with_item,- delivery_method_info=get_delivery_method_info(- convert_to_shipping_method_data(- delivery_method,- delivery_method.channel_listings.first(),- ),- address,- ),shipping_address=address,billing_address=None,channel=checkout_with_item.channel,user=None,tax_configuration=checkout_with_item.channel.tax_configuration,- valid_pick_up_points=[],- all_shipping_methods=[],discounts=[],+ manager=manager,+ shipping_method=shipping_method,+ shipping_channel_listings=shipping_method.channel_listings.all(),+ lines=lines,)add_variant_to_checkout(checkout_info, variant2, 1)diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.pyindex 0d65d718d3..e9f4bdd83f 100644--- a/saleor/plugins/base_plugin.py+++ b/saleor/plugins/base_plugin.py@@ -155,6 +155,12 @@ class BasePlugin:self.db_config = db_configself.allow_replica = allow_replica+ def __del__(self) -> None:+ self.channel = None+ self.db_config = None+ self.configuration.clear()+ self.requestor = None+def __str__(self):return self.PLUGIN_NAMEdiff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.pyindex 6d55093223..b5a1235269 100644--- a/saleor/plugins/manager.py+++ b/saleor/plugins/manager.py@@ -144,6 +144,14 @@ class PluginsManager(PaymentInterface):self.loaded_global = Falseself.requestor_getter = requestor_getter+ def __del__(self) -> None:+ # remove references to plugins+ self.all_plugins.clear()+ self.global_plugins.clear()+ for c in self.plugins_per_channel.values():+ c.clear()+ self.loaded_channels.clear()+def _ensure_channel_plugins_loaded(self, channel_slug: Optional[str], channel: Optional[Channel] = None):diff --git a/saleor/tests/e2e/checkout/shipping/test_checkout_invalidate_price_based_shipping_on_voucher_add.py b/saleor/tests/e2e/checkout/shipping/test_checkout_invalidate_price_based_shipping_on_voucher_add.pynew file mode 100644index 0000000000..f7d3fd5407--- /dev/null+++ b/saleor/tests/e2e/checkout/shipping/test_checkout_invalidate_price_based_shipping_on_voucher_add.py@@ -0,0 +1,197 @@+import pytest++from ...product.utils.preparing_product import prepare_product+from ...shop.utils.preparing_shop import prepare_shop+from ...utils import assign_permissions+from ...vouchers.utils import create_voucher, create_voucher_channel_listing+from ..utils import (+ checkout_complete,+ checkout_create,+ checkout_delivery_method_update,+ checkout_dummy_payment_create,+ checkout_lines_add,+ raw_checkout_add_promo_code,+)+++def prepare_entire_order_voucher(e2e_staff_api_client, channel_id, voucher_amount):+ voucher_code = "ENTIRE_ORDER"+ input = {+ "name": "Entire order voucher",+ "addCodes": [voucher_code],+ "applyOncePerCustomer": False,+ "applyOncePerOrder": False,+ "onlyForStaff": False,+ "discountValueType": "FIXED",+ "endDate": None,+ "minCheckoutItemsQuantity": 0,+ "startDate": None,+ "type": "ENTIRE_ORDER",+ "usageLimit": None,+ "singleUse": False,+ }+ voucher_data = create_voucher(e2e_staff_api_client, input)+ voucher_id = voucher_data["id"]+ channel_listing = [+ {+ "channelId": channel_id,+ "discountValue": voucher_amount,+ },+ ]+ create_voucher_channel_listing(+ e2e_staff_api_client,+ voucher_id,+ channel_listing,+ )++ return voucher_code+++def test_checkout_should_invalidate_shipping_methods_when_adding_entire_order_voucher_0116(+ e2e_not_logged_api_client,+ e2e_staff_api_client,+ permission_manage_products,+ permission_manage_channels,+ permission_manage_shipping,+ permission_manage_product_types_and_attributes,+ permission_manage_discounts,+ permission_manage_settings,+):+ # Before+ permissions = [+ permission_manage_products,+ permission_manage_channels,+ permission_manage_shipping,+ permission_manage_product_types_and_attributes,+ permission_manage_discounts,+ permission_manage_settings,+ ]+ assign_permissions(e2e_staff_api_client, permissions)++ shop_data, _ = prepare_shop(+ e2e_staff_api_client,+ channels=[+ {+ "shipping_zones": [+ {+ "shipping_methods": [+ {"add_channels": {"minimum_order_price": 18.0}}+ ],+ },+ ],+ "order_settings": {},+ }+ ],+ shop_settings={},+ )+ channel_id = shop_data[0]["id"]+ channel_slug = shop_data[0]["slug"]+ warehouse_id = shop_data[0]["warehouse_id"]+ shipping_method_id = shop_data[0]["shipping_zones"][0]["shipping_methods"][0]["id"]++ (+ _product_id,+ product_variant_id,+ product_variant_price,+ ) = prepare_product(+ e2e_staff_api_client,+ warehouse_id,+ channel_id,+ variant_price=18,+ )++ voucher_amount = 1+ voucher_code = prepare_entire_order_voucher(+ e2e_staff_api_client, channel_id, voucher_amount+ )++ # Step 1 - Create checkout for product+ lines = [+ {+ "variantId": product_variant_id,+ "quantity": 1,+ },+ ]+ checkout_data = checkout_create(+ e2e_not_logged_api_client,+ lines,+ channel_slug,+ email="[email protected]",+ set_default_billing_address=True,+ set_default_shipping_address=True,+ )+ checkout_id = checkout_data["id"]+ checkout_lines = checkout_data["lines"][0]+ shipping_method_id = checkout_data["shippingMethods"][0]["id"]++ assert checkout_data["isShippingRequired"] is True+ assert checkout_lines["unitPrice"]["gross"]["amount"] == float(+ product_variant_price+ )+ assert checkout_lines["undiscountedUnitPrice"]["amount"] == product_variant_price++ # Step 2 - Set DeliveryMethod for checkout.+ checkout_data = checkout_delivery_method_update(+ e2e_not_logged_api_client,+ checkout_id,+ shipping_method_id,+ )+ assert checkout_data["deliveryMethod"]["id"] == shipping_method_id++ # Step 3 Add voucher code to checkout. Selected delivery method should be unset as+ # the price is lower than the minimum total price for this method.+ checkout_data = raw_checkout_add_promo_code(+ e2e_not_logged_api_client, checkout_id, voucher_code+ )++ assert checkout_data["checkout"]["voucherCode"] == voucher_code+ assert checkout_data["checkout"]["discount"]["amount"] == voucher_amount+ assert checkout_data["checkout"]["deliveryMethod"] is None++ # Step 4 Add lines to the checkout to increase the total amount+ lines_add = [+ {+ "variantId": product_variant_id,+ "quantity": 2,+ },+ ]+ checkout_data = checkout_lines_add(+ e2e_staff_api_client,+ checkout_id,+ lines_add,+ )+ checkout_lines = checkout_data["lines"][0]+ assert checkout_lines["quantity"] == 3+ subtotal_amount = float(product_variant_price) * 3 - voucher_amount+ assert checkout_lines["totalPrice"]["gross"]["amount"] == subtotal_amount++ # Step 5 Add shipping method again.+ checkout_data = checkout_delivery_method_update(+ e2e_not_logged_api_client,+ checkout_id,+ shipping_method_id,+ )+ assert checkout_data["deliveryMethod"]["id"] == shipping_method_id+ shipping_price = float(checkout_data["shippingPrice"]["gross"]["amount"])+ total_gross_amount = checkout_data["totalPrice"]["gross"]["amount"]++ # Step 6 - Create payment for checkout.+ checkout_dummy_payment_create(+ e2e_not_logged_api_client,+ checkout_id,+ total_gross_amount,+ )++ # Step 7 - Complete checkout.+ order_data = checkout_complete(+ e2e_not_logged_api_client,+ checkout_id,+ )+ assert order_data["status"] == "UNFULFILLED"+ assert order_data["discounts"][0]["type"] == "VOUCHER"+ assert order_data["discounts"][0]["value"] == voucher_amount+ assert order_data["voucher"]["code"] == voucher_code+ assert order_data["total"]["gross"]["amount"] == total_gross_amount+ assert order_data["deliveryMethod"]["id"] == shipping_method_id+ assert order_data["shippingPrice"]["gross"]["amount"] == shipping_pricediff --git a/saleor/tests/e2e/checkout/utils/checkout_add_promo_code.py b/saleor/tests/e2e/checkout/utils/checkout_add_promo_code.pyindex 346f67cd91..f18d9c60b7 100644--- a/saleor/tests/e2e/checkout/utils/checkout_add_promo_code.py+++ b/saleor/tests/e2e/checkout/utils/checkout_add_promo_code.py@@ -20,6 +20,16 @@ mutation AddCheckoutPromoCode($checkoutId: ID!, $promoCode: String!) {amount}}+ shippingMethods {+ id+ name+ }+ deliveryMethod {+ ... on ShippingMethod {+ id+ name+ }+ }voucherCodediscount {amountdiff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex 0ee1eb7b4d..c25837c309 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -8034,7 +8034,7 @@ def checkout_with_prices(channel = checkout_with_items.channellines = checkout_with_items.lines.all()lines_info, _ = fetch_checkout_lines(checkout_with_items)- checkout_info = fetch_checkout_info(checkout_with_items, lines, manager)+ checkout_info = fetch_checkout_info(checkout_with_items, lines_info, manager)for line, line_info in zip(lines, lines_info):line.total_price_net_amount = base_calculations.calculate_base_line_total_price(