Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Decouple stock availability from shipping zones (#19066)
Iga Karbowiak2dd70df51c47
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.pyindex 524dd0468a..0f90522cb4 100644--- a/saleor/checkout/complete_checkout.py+++ b/saleor/checkout/complete_checkout.py@@ -572,6 +572,7 @@ def _create_lines_for_order(checkout_info: "CheckoutInfo",lines: list["CheckoutLineInfo"],prices_entered_with_tax: bool,+ site_settings: "SiteSettings",) -> Iterable[OrderLineInfo]:"""Create a lines for the given order.@@ -611,6 +612,7 @@ def _create_lines_for_order(additional_warehouse_lookup = (checkout_info.get_delivery_method_info().get_warehouse_filter_lookup())+ include_shipping_zones = site_settings.use_legacy_shipping_zone_stock_availabilitycheck_stock_and_preorder_quantity_bulk(variants,country_code,@@ -622,6 +624,7 @@ def _create_lines_for_order(existing_lines=lines,replace=True,check_reservations=True,+ include_shipping_zones=include_shipping_zones,)voucher = checkout_info.vouchervoucher_channel_listing = None@@ -656,6 +659,7 @@ def _prepare_order_data(checkout_info: "CheckoutInfo",lines: list["CheckoutLineInfo"],prices_entered_with_tax: bool,+ site_settings: "SiteSettings",) -> dict:"""Run checks and return all the data from a given checkout to create an order.@@ -707,6 +711,7 @@ def _prepare_order_data(checkout_info,lines,prices_entered_with_tax,+ site_settings=site_settings,)undiscounted_total = (sum(@@ -840,8 +845,9 @@ def _create_order(country_code,checkout_info.channel,manager,- checkout_info.get_delivery_method_info().warehouse_pk,- additional_warehouse_lookup,+ include_shipping_zones=site_settings.use_legacy_shipping_zone_stock_availability,+ collection_point_pk=checkout_info.get_delivery_method_info().warehouse_pk,+ additional_filter_lookup=additional_warehouse_lookup,check_reservations=True,checkout_lines=[line.line for line in checkout_lines],)@@ -1026,6 +1032,7 @@ def _get_order_data(checkout_info=checkout_info,lines=lines,prices_entered_with_tax=prices_entered_with_tax,+ site_settings=site_settings,)except InsufficientStock as e:error = prepare_insufficient_stock_checkout_validation_error(e)@@ -1237,12 +1244,14 @@ def _create_order_lines_from_checkout_lines(manager: "PluginsManager",order_pk: str | UUID,prices_entered_with_tax: bool,+ site_settings: "SiteSettings",) -> list[OrderLineInfo]:order_lines_info = _create_lines_for_order(manager,checkout_info,lines,prices_entered_with_tax,+ site_settings=site_settings,)order_lines = []order_line_discounts: list[OrderLineDiscount] = []@@ -1265,6 +1274,7 @@ def _handle_allocations_of_order_lines(order_lines_info: list[OrderLineInfo],manager: "PluginsManager",reservation_enabled: bool,+ include_shipping_zones: bool,):country_code = checkout_info.get_country()additional_warehouse_lookup = (@@ -1275,8 +1285,9 @@ def _handle_allocations_of_order_lines(country_code,checkout_info.channel,manager,- checkout_info.get_delivery_method_info().warehouse_pk,- additional_warehouse_lookup,+ include_shipping_zones=include_shipping_zones,+ collection_point_pk=checkout_info.get_delivery_method_info().warehouse_pk,+ additional_filter_lookup=additional_warehouse_lookup,check_reservations=True,checkout_lines=[line.line for line in checkout_lines],)@@ -1485,6 +1496,7 @@ def _create_order_from_checkout(manager=manager,order_pk=order.pk,prices_entered_with_tax=prices_entered_with_tax,+ site_settings=site_settings,)# update undiscounted order total@@ -1514,6 +1526,7 @@ def _create_order_from_checkout(order_lines_info=order_lines_info,manager=manager,reservation_enabled=reservation_enabled,+ include_shipping_zones=site_settings.use_legacy_shipping_zone_stock_availability,)# giftcards@@ -1853,6 +1866,7 @@ def complete_checkout_with_payment(checkout_info = fetch_checkout_info(checkout, lines, manager)assign_checkout_user(user, checkout_info)+ site_settings = site_settings or Site.objects.get_current().settingspayment, customer_id, order_data = complete_checkout_pre_payment_part(manager=manager,checkout_info=checkout_info,@@ -1862,7 +1876,11 @@ def complete_checkout_with_payment(redirect_url=redirect_url,)- _reserve_stocks_without_availability_check(checkout_info, lines)+ _reserve_stocks_without_availability_check(+ checkout_info,+ lines,+ site_settings.use_legacy_shipping_zone_stock_availability,+ )# Process payments out of transaction to unlock stock rows for another user,# who potentially can order the same product variants.@@ -1954,6 +1972,7 @@ def complete_checkout_with_payment(def _reserve_stocks_without_availability_check(checkout_info: CheckoutInfo,lines: list[CheckoutLineInfo],+ include_shipping_zones: bool,):"""Add additional temporary reservation for stock.@@ -1961,10 +1980,11 @@ def _reserve_stocks_without_availability_check(ordering the same product, in the same time, which is out of stock."""variants = [line.variant for line in lines]- stocks = Stock.objects.get_variants_stocks_for_country(- country_code=checkout_info.get_country(),+ stocks = Stock.objects.get_variants_stocks(channel_slug=checkout_info.channel.slug,products_variants=variants,+ country_code=checkout_info.get_country(),+ include_shipping_zones=include_shipping_zones,)variants_stocks_map = {stock.product_variant_id: stock for stock in stocks}diff --git a/saleor/checkout/tests/test_checkout_complete.py b/saleor/checkout/tests/test_checkout_complete.pyindex 0e48dd9011..2ba6c1b553 100644--- a/saleor/checkout/tests/test_checkout_complete.py+++ b/saleor/checkout/tests/test_checkout_complete.py@@ -84,6 +84,7 @@ def test_create_order_captured_payment_creates_expected_events(checkout_info=checkout_info,lines=lines,prices_entered_with_tax=True,+ site_settings=site_settings,),user=customer_user,app=None,@@ -247,6 +248,7 @@ def test_create_order_captured_payment_creates_expected_events_anonymous_user(checkout_info=checkout_info,lines=lines,prices_entered_with_tax=True,+ site_settings=site_settings,),user=None,app=None,@@ -405,6 +407,7 @@ def test_create_order_preauth_payment_creates_expected_events(checkout_info=checkout_info,lines=lines,prices_entered_with_tax=True,+ site_settings=site_settings,),user=customer_user,app=None,@@ -520,6 +523,7 @@ def test_create_order_preauth_payment_creates_expected_events_anonymous_user(checkout_info=checkout_info,lines=lines,prices_entered_with_tax=True,+ site_settings=site_settings,),user=None,app=None,@@ -590,7 +594,7 @@ def test_create_order_preauth_payment_creates_expected_events_anonymous_user(def test_create_order_insufficient_stock(- checkout, customer_user, product_without_shipping+ checkout, customer_user, product_without_shipping, site_settings):variant = product_without_shipping.variants.get()manager = get_plugins_manager(allow_replica=False)@@ -610,12 +614,14 @@ def test_create_order_insufficient_stock(checkout_info=checkout_info,lines=lines,prices_entered_with_tax=True,+ site_settings=site_settings,)def test_create_order_doesnt_duplicate_order(checkout_with_item,customer_user,+ site_settings,):checkout = checkout_with_itemcheckout.user = customer_user@@ -633,6 +639,7 @@ def test_create_order_doesnt_duplicate_order(checkout_info=checkout_info,lines=lines,prices_entered_with_tax=True,+ site_settings=site_settings,)order_1 = _create_order(@@ -658,7 +665,7 @@ def test_create_order_doesnt_duplicate_order(@pytest.mark.parametrize("is_anonymous_user", [True, False])def test_create_order_with_gift_card(- checkout_with_gift_card, customer_user, is_anonymous_user+ checkout_with_gift_card, customer_user, is_anonymous_user, site_settings):checkout_user = None if is_anonymous_user else customer_usercheckout = checkout_with_gift_card@@ -698,6 +705,7 @@ def test_create_order_with_gift_card(checkout_info=checkout_info,lines=lines,prices_entered_with_tax=True,+ site_settings=site_settings,),user=customer_user if not is_anonymous_user else None,app=None,@@ -717,6 +725,7 @@ def test_create_order_with_gift_card_partial_use(checkout_with_item,gift_card_used,customer_user,+ site_settings,):checkout = checkout_with_itemcheckout.user = customer_user@@ -749,6 +758,7 @@ def test_create_order_with_gift_card_partial_use(checkout_info=checkout_info,lines=lines,prices_entered_with_tax=True,+ site_settings=site_settings,),user=customer_user,app=None,@@ -774,6 +784,7 @@ def test_create_order_with_many_gift_cards(gift_card_created_by_staff,gift_card,customer_user,+ site_settings,):checkout = checkout_with_itemcheckout.user = customer_user@@ -810,6 +821,7 @@ def test_create_order_with_many_gift_cards(checkout_info=checkout_info,lines=lines,prices_entered_with_tax=True,+ site_settings=site_settings,),user=customer_user,app=None,@@ -838,6 +850,7 @@ def test_create_order_with_many_gift_cards(def test_create_order_gift_card_bought(send_notification_mock,checkout_with_gift_card_items,+ site_settings,payment_txn_captured,customer_user,is_anonymous_user,@@ -898,6 +911,7 @@ def test_create_order_gift_card_bought(checkout_info=checkout_info,lines=lines,prices_entered_with_tax=True,+ site_settings=site_settings,),user=customer_user if not is_anonymous_user else None,app=None,@@ -931,6 +945,7 @@ def test_create_order_gift_card_bought(def test_create_order_gift_card_bought_order_not_captured_gift_cards_not_sent(send_notification_mock,checkout_with_gift_card_items,+ site_settings,customer_user,is_anonymous_user,django_capture_on_commit_callbacks,@@ -974,6 +989,7 @@ def test_create_order_gift_card_bought_order_not_captured_gift_cards_not_sent(checkout_info=checkout_info,lines=lines,prices_entered_with_tax=True,+ site_settings=site_settings,),user=customer_user if not is_anonymous_user else None,app=None,@@ -994,6 +1010,7 @@ def test_create_order_gift_card_bought_only_shippable_gift_card(shippable_gift_card_product,customer_user,is_anonymous_user,+ site_settings,):checkout_user = None if is_anonymous_user else customer_usercheckout_info = fetch_checkout_info(@@ -1035,6 +1052,7 @@ def test_create_order_gift_card_bought_only_shippable_gift_card(checkout_info=checkout_info,lines=lines,prices_entered_with_tax=True,+ site_settings=site_settings,),user=customer_user if not is_anonymous_user else None,app=None,@@ -1093,6 +1111,7 @@ def test_create_order_gift_card_bought_do_not_fulfill_gift_cards_automatically(checkout_info=checkout_info,lines=lines,prices_entered_with_tax=True,+ site_settings=site_settings,),user=customer_user if not is_anonymous_user else None,app=None,@@ -1103,7 +1122,9 @@ def test_create_order_gift_card_bought_do_not_fulfill_gift_cards_automatically(assert not GiftCard.objects.all()-def test_note_in_created_order(checkout_with_item, address, customer_user):+def test_note_in_created_order(+ checkout_with_item, address, customer_user, site_settings+):checkout_with_item.shipping_address = addresscheckout_with_item.note = "test_note"checkout_with_item.tracking_code = "tracking_code"@@ -1120,6 +1141,7 @@ def test_note_in_created_order(checkout_with_item, address, customer_user):checkout_info=checkout_info,lines=lines,prices_entered_with_tax=True,+ site_settings=site_settings,),user=customer_user,app=None,@@ -1129,7 +1151,7 @@ def test_note_in_created_order(checkout_with_item, address, customer_user):def test_create_order_with_variant_tracking_false(- checkout, customer_user, variant_without_inventory_tracking+ checkout, customer_user, variant_without_inventory_tracking, site_settings):variant = variant_without_inventory_trackingcheckout.user = customer_user@@ -1148,6 +1170,7 @@ def test_create_order_with_variant_tracking_false(checkout_info=checkout_info,lines=lines,prices_entered_with_tax=True,+ site_settings=site_settings,)order_1 = _create_order(@@ -1165,6 +1188,7 @@ def test_create_order_with_variant_tracking_false(def test_create_order_use_translations(checkout_with_item,customer_user,+ site_settings,):translated_product_name = "French name"translated_variant_name = "French variant name"@@ -1201,6 +1225,7 @@ def test_create_order_use_translations(checkout_info=checkout_info,lines=lines,prices_entered_with_tax=True,+ site_settings=site_settings,)order_line = order_data["lines"][0].line@@ -1992,7 +2017,9 @@ def test_process_user_data_for_order_do_not_store_customer_address_saving_addresassert not customer_user.addresses.filter(**new_address_data).exists()-def test_create_order_update_display_gross_prices(checkout_with_item, customer_user):+def test_create_order_update_display_gross_prices(+ checkout_with_item, customer_user, site_settings+):# givencheckout = checkout_with_itemchannel = checkout.channel@@ -2010,6 +2037,7 @@ def test_create_order_update_display_gross_prices(checkout_with_item, customer_ucheckout_info=checkout_info,lines=lines,prices_entered_with_tax=True,+ site_settings=site_settings,)# when@@ -2027,7 +2055,7 @@ def test_create_order_update_display_gross_prices(checkout_with_item, customer_udef test_create_order_store_shipping_prices(- checkout_with_items_and_shipping, customer_user+ checkout_with_items_and_shipping, customer_user, site_settings):# givencheckout = checkout_with_items_and_shipping@@ -2059,6 +2087,7 @@ def test_create_order_store_shipping_prices(checkout_info=checkout_info,lines=lines,prices_entered_with_tax=True,+ site_settings=site_settings,),user=customer_user,app=None,@@ -2085,6 +2114,7 @@ def test_create_order_store_shipping_prices(def test_create_order_store_shipping_prices_with_free_shipping_voucher(checkout_with_voucher_free_shipping,customer_user,+ site_settings,):# givencheckout = checkout_with_voucher_free_shipping@@ -2114,6 +2144,7 @@ def test_create_order_store_shipping_prices_with_free_shipping_voucher(checkout_info=checkout_info,lines=lines,prices_entered_with_tax=True,+ site_settings=site_settings,),user=customer_user,app=None,diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex 3fdffc7c18..a26243e1a3 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -7,6 +7,7 @@ from uuid import UUIDimport graphenefrom django.conf import settings+from django.contrib.sites.models import Sitefrom django.core.exceptions import ValidationErrorfrom django.db import transactionfrom django.db.models import prefetch_related_objects@@ -196,13 +197,15 @@ def check_variant_in_stock()if new_quantity > 0 and check_quantity:+ include_shipping_zones = Site.objects.get_current().settings.use_legacy_shipping_zone_stock_availabilitycheck_stock_and_preorder_quantity(variant,checkout.get_country(),channel_slug,new_quantity,- checkout_lines,- check_reservations,+ include_shipping_zones=include_shipping_zones,+ checkout_lines=checkout_lines,+ check_reservations=check_reservations,)return new_quantity, line@@ -300,6 +303,8 @@ def add_variants_to_checkout(replace_reservations=False,reservation_length: int | None = None,raise_error_for_missing_lines=False,+ *,+ include_shipping_zones,):"""Add variants to checkout.@@ -396,6 +401,7 @@ def add_variants_to_checkout(country_code,channel,reservation_length,+ include_shipping_zones=include_shipping_zones,replace=replace_reservations,)diff --git a/saleor/discount/tests/test_utils/test_create_or_update_discount_objects_from_promotion_for_checkout.py b/saleor/discount/tests/test_utils/test_create_or_update_discount_objects_from_promotion_for_checkout.pyindex 6a79bf292c..c8330b8b78 100644--- a/saleor/discount/tests/test_utils/test_create_or_update_discount_objects_from_promotion_for_checkout.py+++ b/saleor/discount/tests/test_utils/test_create_or_update_discount_objects_from_promotion_for_checkout.py@@ -2352,3 +2352,41 @@ def test_create_checkout_line_discount_objects_for_catalogue_promotions_race_con# thenassert CheckoutLineDiscount.objects.count() == 1+++def test_get_best_gift_reward_warehouse_without_shipping_zones(+ gift_promotion_rule, channel_USD, warehouse, site_settings+):+ # given+ assert site_settings.use_legacy_shipping_zone_stock_availability is True+ warehouse.shipping_zones.clear()++ rules = [gift_promotion_rule]+ country = "US"++ # when+ rule, listing = _get_best_gift_reward(rules, channel_USD, country)++ # then - legacy: warehouse has no shipping zones, gift not available+ assert rule is None+ assert listing is None+++def test_get_best_gift_reward_warehouse_without_shipping_zones_excluded_from_stock_calculations(+ gift_promotion_rule, channel_USD, warehouse, site_settings+):+ # given+ site_settings.use_legacy_shipping_zone_stock_availability = False+ site_settings.save(update_fields=["use_legacy_shipping_zone_stock_availability"])++ warehouse.shipping_zones.clear()++ rules = [gift_promotion_rule]+ country = "US"++ # when+ rule, listing = _get_best_gift_reward(rules, channel_USD, country)++ # then - shipping zones excluded: gift is available+ assert rule == gift_promotion_rule+ assert listing is not Nonediff --git a/saleor/discount/utils/promotion.py b/saleor/discount/utils/promotion.pyindex 52e6a4461e..ccf9c7c740 100644--- a/saleor/discount/utils/promotion.py+++ b/saleor/discount/utils/promotion.py@@ -9,6 +9,7 @@ from uuid import UUIDimport graphenefrom django.conf import settings+from django.contrib.sites.models import Sitefrom django.db import transactionfrom django.db.models import Exists, OuterRef, QuerySetfrom prices import Money@@ -335,6 +336,9 @@ def _get_best_gift_reward(if not variants:return None, None+ include_shipping_zones = (+ Site.objects.get_current().settings.use_legacy_shipping_zone_stock_availability+ )try:check_stock_quantity_bulk(variants,@@ -343,6 +347,7 @@ def _get_best_gift_reward(channel.slug,None,database_connection_name=database_connection_name,+ include_shipping_zones=include_shipping_zones,)except InsufficientStock as error:variant_ids_with_insufficient_stock = {diff --git a/saleor/giftcard/utils.py b/saleor/giftcard/utils.pyindex 398f326d82..5b8be2ce13 100644--- a/saleor/giftcard/utils.py+++ b/saleor/giftcard/utils.py@@ -137,7 +137,7 @@ def fulfill_gift_card_lines({"order_line": line, "quantity": quantity})else:- stock = line.variant.stocks.for_channel_and_country(channel_slug).first()+ stock = line.variant.stocks.for_channel(channel_slug).first()if not stock:raise GiftCardNotApplicable(message="Lack of gift card stock for checkout channel.",diff --git a/saleor/graphql/checkout/dataloaders/problems.py b/saleor/graphql/checkout/dataloaders/problems.pyindex a2691ba048..1eb1b89bc0 100644--- a/saleor/graphql/checkout/dataloaders/problems.py+++ b/saleor/graphql/checkout/dataloaders/problems.py@@ -20,7 +20,9 @@ from ...core.dataloaders import DataLoaderfrom ...product.dataloaders import (ProductChannelListingByProductIdAndChannelSlugLoader,)+from ...site.dataloaders import get_site_promisefrom ...warehouse.dataloaders import (+ StocksWithAvailableQuantityByProductVariantIdAndChannelSlugLoader,StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChannelLoader,)from .checkout_delivery import CheckoutDeliveryByIdLoader@@ -37,14 +39,12 @@ class CheckoutLinesProblemsByCheckoutIdLoader(context_key = "checkout_lines_problems_by_checkout_id"def batch_load(self, keys):- stock_dataloader = (- StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChannelLoader(- self.context- )- )-def _resolve_problems(data):- checkout_infos, checkout_lines = data+ checkout_infos, checkout_lines, site = data++ include_shipping_zones = (+ site.settings.use_legacy_shipping_zone_stock_availability+ )variant_data_set: set[tuple[VARIANT_ID,@@ -115,12 +115,32 @@ class CheckoutLinesProblemsByCheckoutIdLoader()return [problems.get(key, []) for key in keys]- variant_stocks = stock_dataloader.load_many(- [- (variant_id, country_code, channel_slug)- for variant_id, channel_slug, country_code in variant_data_list- ]+ stock_dataloader: (+ StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChannelLoader+ | StocksWithAvailableQuantityByProductVariantIdAndChannelSlugLoader)+ if include_shipping_zones:+ stock_dataloader = StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChannelLoader( # noqa: E501+ self.context+ )+ variant_stocks = stock_dataloader.load_many(+ [+ (variant_id, country_code, channel_slug)+ for variant_id, channel_slug, country_code in variant_data_list+ ]+ )+ else:+ stock_dataloader = (+ StocksWithAvailableQuantityByProductVariantIdAndChannelSlugLoader(+ self.context+ )+ )+ variant_stocks = stock_dataloader.load_many(+ [+ (variant_id, channel_slug)+ for variant_id, channel_slug, _country_code in variant_data_list+ ]+ )product_channel_listings = (ProductChannelListingByProductIdAndChannelSlugLoader(self.context@@ -133,7 +153,8 @@ class CheckoutLinesProblemsByCheckoutIdLoader(checkout_infos = CheckoutInfoByCheckoutTokenLoader(self.context).load_many(keys)lines = CheckoutLinesInfoByCheckoutTokenLoader(self.context).load_many(keys)- return Promise.all([checkout_infos, lines]).then(_resolve_problems)+ site = get_site_promise(self.context)+ return Promise.all([checkout_infos, lines, site]).then(_resolve_problems)class CheckoutProblemsByCheckoutIdDataloader(diff --git a/saleor/graphql/checkout/mutations/checkout_create.py b/saleor/graphql/checkout/mutations/checkout_create.pyindex a33f1b4ba7..9d43442291 100644--- a/saleor/graphql/checkout/mutations/checkout_create.py+++ b/saleor/graphql/checkout/mutations/checkout_create.py@@ -280,6 +280,9 @@ class CheckoutCreate(DeprecatedModelMutation, I18nMixin):variants, checkout_lines_data)+ use_legacy_shipping_zone_stock_availability = (+ site.settings.use_legacy_shipping_zone_stock_availability+ )check_lines_quantity(variants,quantities,@@ -287,6 +290,7 @@ class CheckoutCreate(DeprecatedModelMutation, I18nMixin):channel.slug,site.settings.limit_quantity_per_checkout,check_reservations=is_reservation_enabled(site.settings),+ calculate_stocks_with_shipping_zones=use_legacy_shipping_zone_stock_availability,)return variants, checkout_lines_data@@ -494,6 +498,7 @@ class CheckoutCreate(DeprecatedModelMutation, I18nMixin):reservation_length=get_reservation_length(site=site, user=info.context.user),+ include_shipping_zones=site.settings.use_legacy_shipping_zone_stock_availability,)# Save addressesdiff --git a/saleor/graphql/checkout/mutations/checkout_create_from_order.py b/saleor/graphql/checkout/mutations/checkout_create_from_order.pyindex 67fcf1c898..f52b08e1fa 100644--- a/saleor/graphql/checkout/mutations/checkout_create_from_order.py+++ b/saleor/graphql/checkout/mutations/checkout_create_from_order.py@@ -327,6 +327,7 @@ class CheckoutCreateFromOrder(BaseMutation):order.channel.slug,site.settings.limit_quantity_per_checkout,check_reservations=is_reservation_enabled(site.settings),+ include_shipping_zones=site.settings.use_legacy_shipping_zone_stock_availability,)valid_order_lines = available_order_linesexcept InsufficientStock as e:@@ -419,6 +420,7 @@ class CheckoutCreateFromOrder(BaseMutation):reservation_length=get_reservation_length(site=site, user=info.context.user),+ include_shipping_zones=site.settings.use_legacy_shipping_zone_stock_availability,)apply_gift_reward_if_applicable_on_checkout_creation(checkout)return CheckoutCreateFromOrder(diff --git a/saleor/graphql/checkout/mutations/checkout_lines_add.py b/saleor/graphql/checkout/mutations/checkout_lines_add.pyindex 301b3d8926..a105f7aa5a 100644--- a/saleor/graphql/checkout/mutations/checkout_lines_add.py+++ b/saleor/graphql/checkout/mutations/checkout_lines_add.py@@ -106,6 +106,7 @@ class CheckoutLinesAdd(BaseMutation):delivery_method_info=delivery_method_info,existing_lines=lines,check_reservations=is_reservation_enabled(site.settings),+ calculate_stocks_with_shipping_zones=site.settings.use_legacy_shipping_zone_stock_availability,)@classmethod@@ -133,6 +134,7 @@ class CheckoutLinesAdd(BaseMutation):site=site, user=info.context.user),raise_error_for_missing_lines=raise_error_for_missing_lines,+ include_shipping_zones=site.settings.use_legacy_shipping_zone_stock_availability,)except NonExistingCheckout as e:graphql_id = graphene.Node.to_global_id("Checkout", e.checkout_token)diff --git a/saleor/graphql/checkout/mutations/checkout_lines_update.py b/saleor/graphql/checkout/mutations/checkout_lines_update.pyindex a9476d8d68..d2f4b00924 100644--- a/saleor/graphql/checkout/mutations/checkout_lines_update.py+++ b/saleor/graphql/checkout/mutations/checkout_lines_update.py@@ -134,6 +134,7 @@ class CheckoutLinesUpdate(CheckoutLinesAdd):existing_lines=lines,replace=True,check_reservations=is_reservation_enabled(site.settings),+ calculate_stocks_with_shipping_zones=site.settings.use_legacy_shipping_zone_stock_availability,)@classmethoddiff --git a/saleor/graphql/checkout/mutations/checkout_shipping_address_update.py b/saleor/graphql/checkout/mutations/checkout_shipping_address_update.pyindex 622f38bc8f..1ce3d77f0e 100644--- a/saleor/graphql/checkout/mutations/checkout_shipping_address_update.py+++ b/saleor/graphql/checkout/mutations/checkout_shipping_address_update.py@@ -121,6 +121,7 @@ class CheckoutShippingAddressUpdate(AddressMetadataMixin, BaseMutation, I18nMixireplace=True,existing_lines=lines,check_reservations=is_reservation_enabled(site.settings),+ calculate_stocks_with_shipping_zones=site.settings.use_legacy_shipping_zone_stock_availability,)@classmethoddiff --git a/saleor/graphql/checkout/mutations/utils.py b/saleor/graphql/checkout/mutations/utils.pyindex df56c3a6d2..35fdd9fd03 100644--- a/saleor/graphql/checkout/mutations/utils.py+++ b/saleor/graphql/checkout/mutations/utils.py@@ -94,6 +94,8 @@ def check_lines_quantity(country,channel_slug,global_quantity_limit,+ *,+ calculate_stocks_with_shipping_zones: bool,delivery_method_info=None,allow_zero_quantity=False,existing_lines=None,@@ -139,6 +141,7 @@ def check_lines_quantity(existing_lines=existing_lines,replace=replace,check_reservations=check_reservations,+ include_shipping_zones=calculate_stocks_with_shipping_zones,)except InsufficientStock as e:errors = [diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.pyindex 3cc47f9b25..31a51bf51c 100644--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py@@ -822,6 +822,7 @@ def test_update_checkout_lines_with_reservations(channel_USD,replace_reservations=True,reservation_length=5,+ include_shipping_zones=True,)user_api_client.ensure_access_token()@@ -1320,7 +1321,7 @@ def test_add_checkout_lines_gift_discount_applies(# whenuser_api_client.ensure_access_token()- with django_assert_num_queries(140):+ with django_assert_num_queries(142):response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)# thendiff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.pyindex f1494c9130..2f9359e6cb 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_payment.py@@ -6282,3 +6282,114 @@ def test_complete_refreshes_shipping_methods_when_stale_and_invalid(assert Order.objects.count() == 0assert mocked_get_or_fetch_checkout_deliveries.called+++def test_checkout_complete_warehouse_without_shipping_zones(+ user_api_client,+ checkout_with_gift_card,+ gift_card,+ payment_dummy,+ address,+ checkout_delivery,+ warehouse,+ site_settings,+):+ """When warehouse has no shipping zones, stock is not found (legacy behavior)."""+ # given+ checkout = checkout_with_gift_card+ checkout.shipping_address = address+ checkout.assigned_delivery = checkout_delivery(checkout)+ checkout.billing_address = address+ checkout.save()++ assert site_settings.use_legacy_shipping_zone_stock_availability is True++ # Clear shipping zones from warehouse, not from channel+ warehouse.shipping_zones.clear()+ assert checkout.channel.shipping_zones.exists()++ manager = get_plugins_manager(allow_replica=False)+ lines, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, manager)+ total = calculations.calculate_checkout_total_with_gift_cards(+ manager, checkout_info, lines, address+ )+ payment = payment_dummy+ payment.is_active = True+ payment.order = None+ payment.total = total.gross.amount+ payment.currency = total.gross.currency+ payment.checkout = checkout+ payment.save()++ variables = {+ "id": to_global_id_or_none(checkout),+ "redirectUrl": "https://www.example.com",+ }++ # when+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)++ # then - legacy: warehouse has no shipping zones, stock not found+ content = get_graphql_content(response)+ data = content["data"]["checkoutComplete"]+ assert len(data["errors"]) == 1+ assert data["errors"][0]["code"] == CheckoutErrorCode.INSUFFICIENT_STOCK.name+++@patch("saleor.order.calculations._recalculate_with_plugins")+@patch("saleor.plugins.manager.PluginsManager.order_confirmed")+def test_checkout_complete_warehouse_without_shipping_zones_excluded_from_stock_calculations(+ order_confirmed_mock,+ recalculate_with_plugins_mock,+ user_api_client,+ checkout_with_gift_card,+ gift_card,+ payment_dummy,+ address,+ checkout_delivery,+ warehouse,+ site_settings,+):+ """When flag is disabled, warehouse shipping zones don't matter for stock."""+ # given+ site_settings.use_legacy_shipping_zone_stock_availability = False+ site_settings.save(update_fields=["use_legacy_shipping_zone_stock_availability"])++ checkout = checkout_with_gift_card+ checkout.shipping_address = address+ checkout.assigned_delivery = checkout_delivery(checkout)+ checkout.billing_address = address+ checkout.save()++ # Clear shipping zones from warehouse, not from channel+ warehouse.shipping_zones.clear()+ assert checkout.channel.shipping_zones.exists()++ manager = get_plugins_manager(allow_replica=False)+ lines, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, manager)+ total = calculations.calculate_checkout_total_with_gift_cards(+ manager, checkout_info, lines, address+ )+ payment = payment_dummy+ payment.is_active = True+ payment.order = None+ payment.total = total.gross.amount+ payment.currency = total.gross.currency+ payment.checkout = checkout+ payment.save()++ variables = {+ "id": to_global_id_or_none(checkout),+ "redirectUrl": "https://www.example.com",+ }++ # when+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)++ # then - flag disabled: order created despite warehouse having no shipping zones+ content = get_graphql_content(response)+ data = content["data"]["checkoutComplete"]+ assert not data["errors"]+ assert data["order"]diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.pyindex a3eee9f0f7..f52991ce7a 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete_with_transactions.py@@ -4,6 +4,7 @@ from unittest.mock import ANY, patchimport grapheneimport pytest+from django.contrib.sites.models import Sitefrom django.db import transactionfrom django.db.models.aggregates import Sumfrom django.test import override_settings@@ -6000,3 +6001,118 @@ def test_complete_refreshes_shipping_methods_when_stale_and_invalid(assert Order.objects.count() == 0assert mocked_get_or_fetch_checkout_deliveries.called+++def test_checkout_complete_with_transaction_warehouse_without_shipping_zones(+ user_api_client,+ checkout_with_gift_card,+ gift_card,+ transaction_item_generator,+ address,+ checkout_delivery,+ shipping_method,+ warehouse,+ site_settings,+):+ """When warehouse has no shipping zones, stock is not found (legacy behavior)."""+ # given+ checkout = checkout_with_gift_card+ checkout.shipping_address = address+ checkout.assigned_delivery = checkout_delivery(checkout, shipping_method)+ checkout.billing_address = address+ checkout.save()++ assert site_settings.use_legacy_shipping_zone_stock_availability is True++ # Clear shipping zones from warehouse, not from channel+ warehouse.shipping_zones.clear()+ assert checkout.channel.shipping_zones.exists()++ manager = get_plugins_manager(allow_replica=False)+ lines, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, manager)+ total = calculations.calculate_checkout_total_with_gift_cards(+ manager, checkout_info, lines, address+ )++ transaction_item_generator(+ checkout_id=checkout.pk, authorized_value=total.gross.amount+ )+ update_checkout_payment_statuses(+ checkout=checkout,+ checkout_total_gross=total.gross,+ checkout_has_lines=bool(lines),+ )++ variables = {+ "id": to_global_id_or_none(checkout),+ "redirectUrl": "https://www.example.com",+ }++ # when+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)++ # then - legacy: warehouse has no shipping zones, stock not found+ content = get_graphql_content(response)+ data = content["data"]["checkoutComplete"]+ assert len(data["errors"]) == 1+ assert data["errors"][0]["code"] == CheckoutErrorCode.INSUFFICIENT_STOCK.name+++def test_checkout_complete_with_transaction_warehouse_without_shipping_zones_excluded_from_stock_calculations(+ user_api_client,+ checkout_with_gift_card,+ transaction_item_generator,+ address,+ customer_user,+ checkout_delivery,+ shipping_method,+ warehouse,+ site_settings,+):+ """When flag is disabled, warehouse shipping zones don't matter for stock."""+ # given+ site_settings.use_legacy_shipping_zone_stock_availability = False+ site_settings.save(update_fields=["use_legacy_shipping_zone_stock_availability"])+ Site.objects.clear_cache()++ checkout = checkout_with_gift_card+ checkout.shipping_address = address+ checkout.assigned_delivery = checkout_delivery(checkout, shipping_method)+ checkout.billing_address = address+ checkout.user = customer_user+ checkout.save()++ # Clear shipping zones from warehouse, not from channel+ warehouse.shipping_zones.clear()+ assert checkout.channel.shipping_zones.exists()++ manager = get_plugins_manager(allow_replica=False)+ lines, _ = fetch_checkout_lines(checkout)+ checkout_info = fetch_checkout_info(checkout, lines, manager)+ total = calculations.calculate_checkout_total_with_gift_cards(+ manager, checkout_info, lines, address+ )++ transaction_item_generator(+ checkout_id=checkout.pk, authorized_value=total.gross.amount+ )+ update_checkout_payment_statuses(+ checkout=checkout,+ checkout_total_gross=total.gross,+ checkout_has_lines=bool(lines),+ )++ variables = {+ "id": to_global_id_or_none(checkout),+ "redirectUrl": "https://www.example.com",+ }++ # when+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)++ # then - flag disabled: order created despite warehouse having no shipping zones+ content = get_graphql_content(response)+ data = content["data"]["checkoutComplete"]+ assert not data["errors"]+ assert data["order"]diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_create.py b/saleor/graphql/checkout/tests/mutations/test_checkout_create.pyindex b8ba45db31..3247d8bd6e 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_create.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_create.py@@ -1107,6 +1107,37 @@ def test_checkout_create_no_channel_shipping_zones(assert errors[0]["field"] == "quantity"+def test_checkout_create_no_channel_shipping_zones_excluded_from_stock_calculations(+ api_client, stock, graphql_address_data, channel_USD, site_settings+):+ # given+ site_settings.use_legacy_shipping_zone_stock_availability = False+ site_settings.save(update_fields=["use_legacy_shipping_zone_stock_availability"])++ channel_USD.shipping_zones.clear()+ variant = stock.product_variant+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)+ test_email = "[email protected]"+ shipping_address = graphql_address_data+ variables = {+ "checkoutInput": {+ "channel": channel_USD.slug,+ "lines": [{"quantity": 1, "variantId": variant_id}],+ "email": test_email,+ "shippingAddress": shipping_address,+ }+ }++ # when+ response = api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)+ content = get_graphql_content(response)["data"]["checkoutCreate"]++ # then - no INSUFFICIENT_STOCK error when flag is disabled+ errors = content["errors"]+ assert not errors+ assert content["checkout"]++def test_checkout_create_multiple_warehouse(api_client, variant_with_many_stocks, graphql_address_data, channel_USD):diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_create_from_order.py b/saleor/graphql/checkout/tests/mutations/test_checkout_create_from_order.pyindex ff38880307..fa83aaddd4 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_create_from_order.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_create_from_order.py@@ -852,3 +852,51 @@ def test_checkout_create_from_order_with_the_same_variant_in_multiple_lines(_assert_checkout_lines(order_lines_map, checkout_lines, checkout_lines_from_response_map)+++def test_checkout_create_from_order_channel_without_shipping_zones(+ user_api_client, order_with_lines+):+ # given+ order_with_lines.user = user_api_client.user+ order_with_lines.save()+ Stock.objects.update(quantity=10)+ order_with_lines.channel.shipping_zones.clear()++ variables = {"id": graphene.Node.to_global_id("Order", order_with_lines.pk)}++ # when+ response = user_api_client.post_graphql(+ MUTATION_CHECKOUT_CREATE_FROM_ORDER, variables+ )++ # then - legacy: all variants reported as unavailable+ content = get_graphql_content(response)+ data = content["data"]["checkoutCreateFromOrder"]+ assert len(data["unavailableVariants"]) == order_with_lines.lines.count()+++def test_checkout_create_from_order_channel_without_shipping_zones_excluded_from_stock_calculations(+ user_api_client, order_with_lines, site_settings+):+ # given+ site_settings.use_legacy_shipping_zone_stock_availability = False+ site_settings.save(update_fields=["use_legacy_shipping_zone_stock_availability"])++ order_with_lines.user = user_api_client.user+ order_with_lines.save()+ Stock.objects.update(quantity=10)+ order_with_lines.channel.shipping_zones.clear()++ variables = {"id": graphene.Node.to_global_id("Order", order_with_lines.pk)}++ # when+ response = user_api_client.post_graphql(+ MUTATION_CHECKOUT_CREATE_FROM_ORDER, variables+ )++ # then - flag disabled: all variants available despite no shipping zones+ content = get_graphql_content(response)+ data = content["data"]["checkoutCreateFromOrder"]+ assert not data["unavailableVariants"]+ assert data["checkout"] is not Nonediff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.pyindex 225bb8e6fb..a61da03f3d 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_add.py@@ -1715,8 +1715,13 @@ def test_checkout_lines_add_with_reserved_insufficient_stock(],)def test_checkout_lines_for_click_and_collect_insufficient_stock(- user_api_client, checkout_with_item_for_cc, warehouse_for_cc, cc_option+ user_api_client,+ checkout_with_item_for_cc,+ warehouse_for_cc,+ cc_option,+ site_settings,):+ assert site_settings.use_legacy_shipping_zone_stock_availability is Truecheckout = checkout_with_item_for_cccheckout.collection_point = warehouse_for_cc@@ -1760,9 +1765,10 @@ def test_checkout_lines_add_with_zero_quantity(assert errors[0]["field"] == "quantity"-def test_checkout_lines_add_no_channel_shipping_zones(- user_api_client, checkout_with_item, stock+def test_checkout_lines_add_no_channel_shipping_zones_included_in_stock_calculations(+ user_api_client, checkout_with_item, stock, site_settings):+ assert site_settings.use_legacy_shipping_zone_stock_availability is Truevariant = stock.product_variantcheckout = checkout_with_itemcheckout.channel.shipping_zones.clear()@@ -1785,6 +1791,34 @@ def test_checkout_lines_add_no_channel_shipping_zones(assert errors[0]["field"] == "quantity"+def test_checkout_lines_add_no_channel_shipping_zones_excluded_from_stock_calculations(+ user_api_client, checkout_with_item, stock, site_settings+):+ # given+ site_settings.use_legacy_shipping_zone_stock_availability = False+ site_settings.save(update_fields=["use_legacy_shipping_zone_stock_availability"])++ variant = stock.product_variant+ checkout = checkout_with_item++ checkout.channel.shipping_zones.clear()+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_id, "quantity": 1}],+ "channelSlug": checkout.channel.slug,+ }++ # when+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_ADD, variables)+ content = get_graphql_content(response)++ # then - no INSUFFICIENT_STOCK error when flag is disabled+ data = content["data"]["checkoutLinesAdd"]+ assert not data["errors"]++def test_checkout_lines_add_with_unpublished_product(user_api_client, checkout_with_item, stock, channel_USD):diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.pyindex 84629bbaaf..169c85a7bd 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py@@ -1198,6 +1198,33 @@ def test_checkout_lines_update_channel_without_shipping_zones(assert errors[0]["field"] == "quantity"+def test_checkout_lines_update_channel_without_shipping_zones_excluded_from_stock_calculations(+ user_api_client, checkout_with_item, site_settings+):+ # given+ site_settings.use_legacy_shipping_zone_stock_availability = False+ site_settings.save(update_fields=["use_legacy_shipping_zone_stock_availability"])++ checkout = checkout_with_item+ checkout.channel.shipping_zones.clear()+ line = checkout.lines.first()+ variant = line.variant+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ variables = {+ "id": to_global_id_or_none(checkout),+ "lines": [{"variantId": variant_id, "quantity": 1}],+ }++ # when+ response = user_api_client.post_graphql(MUTATION_CHECKOUT_LINES_UPDATE, variables)+ content = get_graphql_content(response)++ # then - no INSUFFICIENT_STOCK error when flag is disabled+ data = content["data"]["checkoutLinesUpdate"]+ assert not data["errors"]++def test_checkout_lines_update_variant_quantity_over_avability_stock(user_api_client, checkout_with_item):diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_address_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_address_update.pyindex 5d0aee6329..7d40cf55ce 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_address_update.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_shipping_address_update.py@@ -501,6 +501,36 @@ def test_checkout_shipping_address_update_channel_without_shipping_zones(assert checkout.last_change == previous_last_change+def test_checkout_shipping_address_update_channel_without_shipping_zones_excluded_from_stock_calculations(+ user_api_client,+ checkout_with_item,+ graphql_address_data,+ site_settings,+):+ # given+ site_settings.use_legacy_shipping_zone_stock_availability = False+ site_settings.save(update_fields=["use_legacy_shipping_zone_stock_availability"])++ checkout = checkout_with_item+ checkout.channel.shipping_zones.clear()++ shipping_address = graphql_address_data+ variables = {+ "id": to_global_id_or_none(checkout),+ "shippingAddress": shipping_address,+ }++ # when+ response = user_api_client.post_graphql(+ MUTATION_CHECKOUT_SHIPPING_ADDRESS_UPDATE, variables+ )+ content = get_graphql_content(response)++ # then - no INSUFFICIENT_STOCK error when flag is disabled+ data = content["data"]["checkoutShippingAddressUpdate"]+ assert not data["errors"]++def test_checkout_shipping_address_with_invalid_phone_number_returns_error(user_api_client, checkout_with_item, graphql_address_data):diff --git a/saleor/graphql/checkout/tests/test_checkout_problems.py b/saleor/graphql/checkout/tests/test_checkout_problems.pyindex f392f14e36..3bf41d722c 100644--- a/saleor/graphql/checkout/tests/test_checkout_problems.py+++ b/saleor/graphql/checkout/tests/test_checkout_problems.py@@ -4,7 +4,7 @@ from django.utils import timezonefrom freezegun import freeze_timefrom ....product.models import ProductChannelListing, ProductVariantChannelListing-from ....warehouse.models import Allocation, Reservation+from ....warehouse.models import Allocation, Reservation, Warehousefrom ...core.utils import to_global_id_or_nonefrom ...tests.utils import get_graphql_content@@ -563,3 +563,53 @@ def test_checkout_problems_without_delivery_method(content = get_graphql_content(response)assert content["data"]["checkout"]["id"] == checkout_idassert len(content["data"]["checkout"]["problems"]) == 0+++def test_checkout_problem_insufficient_stock_warehouse_without_shipping_zones(+ api_client, checkout_with_items_and_shipping, site_settings+):+ # given+ checkout = checkout_with_items_and_shipping+ checkout_id = to_global_id_or_none(checkout)++ assert site_settings.use_legacy_shipping_zone_stock_availability is True++ # Clear shipping zones from warehouses+ Warehouse.shipping_zones.through.objects.all().delete()++ variables = {"id": checkout_id, "channel": checkout.channel.slug}++ # when+ response = api_client.post_graphql(QUERY_CHECKOUT_WITH_PROBLEMS, variables)++ # then - legacy: warehouse has no shipping zones, stock not found+ content = get_graphql_content(response)+ assert content["data"]["checkout"]["id"] == checkout_id+ problems = content["data"]["checkout"]["problems"]+ assert len(problems) == checkout.lines.count()+ problem_types = {problem["__typename"] for problem in problems}+ assert problem_types == {"CheckoutLineProblemInsufficientStock"}+++def test_checkout_problem_no_insufficient_stock_warehouse_without_shipping_zones_excluded_from_stock_calculations(+ api_client, checkout_with_items_and_shipping, site_settings+):+ # given+ site_settings.use_legacy_shipping_zone_stock_availability = False+ site_settings.save(update_fields=["use_legacy_shipping_zone_stock_availability"])++ checkout = checkout_with_items_and_shipping+ checkout_id = to_global_id_or_none(checkout)++ # Clear shipping zones from warehouses+ Warehouse.shipping_zones.through.objects.all().delete()++ variables = {"id": checkout_id, "channel": checkout.channel.slug}++ # when+ response = api_client.post_graphql(QUERY_CHECKOUT_WITH_PROBLEMS, variables)++ # then - flag disabled: no insufficient stock problems+ content = get_graphql_content(response)+ assert content["data"]["checkout"]["id"] == checkout_id+ assert not content["data"]["checkout"]["problems"]diff --git a/saleor/graphql/order/mutations/draft_order_complete.py b/saleor/graphql/order/mutations/draft_order_complete.pyindex ce70f4bd2b..5790327957 100644--- a/saleor/graphql/order/mutations/draft_order_complete.py+++ b/saleor/graphql/order/mutations/draft_order_complete.py@@ -204,7 +204,7 @@ class DraftOrderComplete(BaseMutation):line=line, quantity=line.quantity, variant=line.variant)order_lines_info.append(line_data)- site = get_site_promise(info.context).get()+ site_settings = get_site_promise(info.context).get().settingstry:with traced_atomic_transaction():allocate_stocks(@@ -213,14 +213,15 @@ class DraftOrderComplete(BaseMutation):channel,manager,check_reservations=is_reservation_enabled(- site.settings+ site_settings),+ include_shipping_zones=site_settings.use_legacy_shipping_zone_stock_availability,)allocate_preorders([line_data],channel.slug,check_reservations=is_reservation_enabled(- site.settings+ site_settings),)except InsufficientStock as e:diff --git a/saleor/graphql/order/mutations/draft_order_create.py b/saleor/graphql/order/mutations/draft_order_create.pyindex 0ed9692d0d..7f3c3efaae 100644--- a/saleor/graphql/order/mutations/draft_order_create.py+++ b/saleor/graphql/order/mutations/draft_order_create.py@@ -41,6 +41,7 @@ from ...meta.inputs import MetadataInput, MetadataInputDescriptionfrom ...plugins.dataloaders import get_plugin_manager_promisefrom ...product.types import ProductVariantfrom ...shipping.utils import get_shipping_model_by_object_id+from ...site.dataloaders import get_site_promisefrom ..types import Orderfrom ..utils import (OrderLineData,@@ -369,7 +370,7 @@ class DraftOrderCreate(cleaned_input["lines_data"] = grouped_lines_data@staticmethod- def _save_lines(info, instance, lines_data, app, manager):+ def _save_lines(info, instance, lines_data, app, manager, site_settings):lines = []if lines_data:for line_data in lines_data:@@ -377,6 +378,7 @@ class DraftOrderCreate(instance,line_data,manager,+ site_settings,)lines.append(new_line)@@ -392,6 +394,7 @@ class DraftOrderCreate(def save(cls, info: ResolveInfo, instance, cleaned_input, instance_tracker=None):manager = get_plugin_manager_promise(info.context).get()app = get_app_promise(info.context).get()+ site = get_site_promise(info.context).get()with traced_atomic_transaction():# Process addresses@@ -400,7 +403,12 @@ class DraftOrderCreate(try:# Process any lines to addcls._save_lines(- info, instance, cleaned_input.get("lines_data"), app, manager+ info,+ instance,+ cleaned_input.get("lines_data"),+ app,+ manager,+ site.settings,)except TaxError as e:raise ValidationError(diff --git a/saleor/graphql/order/mutations/order_line_update.py b/saleor/graphql/order/mutations/order_line_update.pyindex a69f514750..8319ec6afd 100644--- a/saleor/graphql/order/mutations/order_line_update.py+++ b/saleor/graphql/order/mutations/order_line_update.py@@ -18,6 +18,7 @@ from ...core.context import SyncWebhookControlContextfrom ...core.mutations import ModelWithRestrictedChannelAccessMutationfrom ...core.types import OrderErrorfrom ...plugins.dataloaders import get_plugin_manager_promise+from ...site.dataloaders import get_site_promisefrom ..types import Order, OrderLinefrom .draft_order_create import OrderLineInputfrom .utils import EditableOrderValidationMixin, call_event_by_order_status@@ -73,6 +74,7 @@ class OrderLineUpdate(@classmethoddef save(cls, info: ResolveInfo, instance, cleaned_input, instance_tracker=None):manager = get_plugin_manager_promise(info.context).get()+ site = get_site_promise(info.context).get()order_is_unconfirmed = instance.order.is_unconfirmed()line_allocation = instance.allocations.first()@@ -99,6 +101,7 @@ class OrderLineUpdate(instance.quantity,order,manager,+ site.settings,allocate_stock=order_is_unconfirmed,)except InsufficientStock as e:diff --git a/saleor/graphql/order/mutations/order_lines_create.py b/saleor/graphql/order/mutations/order_lines_create.pyindex b7dedbe5e1..d6c02a2086 100644--- a/saleor/graphql/order/mutations/order_lines_create.py+++ b/saleor/graphql/order/mutations/order_lines_create.py@@ -20,6 +20,7 @@ from ....order.utils import (from ....permission.enums import OrderPermissionsfrom ....plugins.manager import PluginsManagerfrom ....product import models as product_models+from ....site.models import SiteSettingsfrom ...app.dataloaders import get_app_promisefrom ...core import ResolveInfofrom ...core.context import SyncWebhookControlContext@@ -28,6 +29,7 @@ from ...core.mutations import BaseMutationfrom ...core.types import NonNullList, OrderErrorfrom ...plugins.dataloaders import get_plugin_manager_promisefrom ...product.types import ProductVariant+from ...site.dataloaders import get_site_promisefrom ..types import Order, OrderLinefrom ..utils import (OrderLineData,@@ -151,6 +153,7 @@ class OrderLinesCreate(EditableOrderValidationMixin, BaseMutation):user: User | None,app: App | None,manager: PluginsManager,+ site_settings: SiteSettings,):added_lines: list[order_models.OrderLine] = []try:@@ -161,6 +164,7 @@ class OrderLinesCreate(EditableOrderValidationMixin, BaseMutation):user,app,manager,+ site_settings,allocate_stock=order.is_unconfirmed(),)added_lines.append(line)@@ -193,6 +197,7 @@ class OrderLinesCreate(EditableOrderValidationMixin, BaseMutation):cls.validate_variants(order, variants)app = get_app_promise(info.context).get()manager = get_plugin_manager_promise(info.context).get()+ site = get_site_promise(info.context).get()with traced_atomic_transaction():added_lines = cls.add_lines_to_order(order,@@ -200,6 +205,7 @@ class OrderLinesCreate(EditableOrderValidationMixin, BaseMutation):info.context.user,app,manager,+ site.settings,)# Create the products added eventdiff --git a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py b/saleor/graphql/order/tests/mutations/test_draft_order_complete.pyindex 01158cf694..d06a11b146 100644--- a/saleor/graphql/order/tests/mutations/test_draft_order_complete.py+++ b/saleor/graphql/order/tests/mutations/test_draft_order_complete.py@@ -669,7 +669,7 @@ def test_draft_order_complete_with_unavailable_variant(assert data["errors"][0]["variants"] == [variant_id]-def test_draft_order_complete_channel_without_shipping_zones(+def test_draft_order_complete_channel_without_shipping_zones_assigned(staff_api_client,permission_group_manage_orders,staff_user,@@ -704,6 +704,40 @@ def test_draft_order_complete_channel_without_shipping_zones(assert {error["field"] for error in data["errors"]} == {"shipping", "lines"}+def test_draft_order_complete_channel_with_shipping_zones_excluded_from_stock_calculation(+ staff_api_client,+ permission_group_manage_orders,+ staff_user,+ draft_order,+ site_settings,+):+ # given+ site_settings.use_legacy_shipping_zone_stock_availability = False+ site_settings.save(update_fields=["use_legacy_shipping_zone_stock_availability"])++ permission_group_manage_orders.user_set.add(staff_api_client.user)+ order = draft_order+ order.channel.shipping_zones.clear()++ assert not OrderEvent.objects.exists()+ assert not Allocation.objects.filter(order_line__order=order).exists()++ order_id = graphene.Node.to_global_id("Order", order.id)+ variables = {"id": order_id}++ # when+ response = staff_api_client.post_graphql(DRAFT_ORDER_COMPLETE_MUTATION, variables)++ # then - INSUFFICIENT_STOCK is not raised, only SHIPPING_METHOD_NOT_APPLICABLE+ content = get_graphql_content(response)+ data = content["data"]["draftOrderComplete"]++ assert len(data["errors"]) == 1+ assert (+ data["errors"][0]["code"] == OrderErrorCode.SHIPPING_METHOD_NOT_APPLICABLE.name+ )++def test_draft_order_complete_product_without_inventory_tracking(staff_api_client,shipping_method,diff --git a/saleor/graphql/order/tests/mutations/test_order_fulfill.py b/saleor/graphql/order/tests/mutations/test_order_fulfill.pyindex ad723d896b..bd52ec86e6 100644--- a/saleor/graphql/order/tests/mutations/test_order_fulfill.py+++ b/saleor/graphql/order/tests/mutations/test_order_fulfill.py@@ -1153,6 +1153,47 @@ def test_order_fulfill_channel_without_shipping_zones(assert error["code"] == OrderErrorCode.INSUFFICIENT_STOCK.name+def test_order_fulfill_channel_without_shipping_zones_excluded_from_stock_calculations(+ staff_api_client,+ order_with_lines,+ permission_group_manage_orders,+ warehouse,+ site_settings,+):+ # given+ site_settings.use_legacy_shipping_zone_stock_availability = False+ site_settings.save(update_fields=["use_legacy_shipping_zone_stock_availability"])++ order = order_with_lines+ order.channel.shipping_zones.clear()+ permission_group_manage_orders.user_set.add(staff_api_client.user)+ query = ORDER_FULFILL_MUTATION+ order_id = graphene.Node.to_global_id("Order", order.id)+ order_line = order.lines.first()+ order_line_id = graphene.Node.to_global_id("OrderLine", order_line.id)+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)+ variables = {+ "order": order_id,+ "input": {+ "notifyCustomer": True,+ "lines": [+ {+ "orderLineId": order_line_id,+ "stocks": [{"quantity": 3, "warehouse": warehouse_id}],+ },+ ],+ },+ }++ # when+ response = staff_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)++ # then - no INSUFFICIENT_STOCK error when flag is disabled+ data = content["data"]["orderFulfill"]+ assert not data["errors"]++@patch("saleor.graphql.order.mutations.order_fulfill.create_fulfillments")def test_order_fulfill_fulfilled_order(mock_create_fulfillments,diff --git a/saleor/graphql/order/utils.py b/saleor/graphql/order/utils.pyindex 2cf1a456a5..4f95604b31 100644--- a/saleor/graphql/order/utils.py+++ b/saleor/graphql/order/utils.py@@ -5,6 +5,7 @@ from typing import TYPE_CHECKING, Optional, Unionimport graphenefrom django.conf import settings+from django.contrib.sites.models import Sitefrom django.core.exceptions import ValidationErrorfrom promise import Promise@@ -176,6 +177,8 @@ def validate_order_lines(channel: "Channel",country: str,errors: T_ERRORS,+ *,+ include_shipping_zones: bool,database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,):for line in lines:@@ -195,6 +198,7 @@ def validate_order_lines(line.quantity,order_line=line,database_connection_name=database_connection_name,+ include_shipping_zones=include_shipping_zones,)except InsufficientStock as exc:errors["lines"].extend(@@ -393,8 +397,17 @@ def validate_draft_order(allow_sync_webhooks=allow_sync_webhooks,)validate_total_quantity(lines, errors)+ include_shipping_zones = (+ Site.objects.get_current().settings.use_legacy_shipping_zone_stock_availability+ )validate_order_lines(- order, lines, channel, country, errors, database_connection_name+ order,+ lines,+ channel,+ country,+ errors,+ include_shipping_zones=include_shipping_zones,+ database_connection_name=database_connection_name,)validate_channel_is_active(channel, errors)validate_product_is_published(channel, lines, errors, database_connection_name)diff --git a/saleor/graphql/product/filters/product_helpers.py b/saleor/graphql/product/filters/product_helpers.pyindex 16299f6d76..9928071299 100644--- a/saleor/graphql/product/filters/product_helpers.py+++ b/saleor/graphql/product/filters/product_helpers.py@@ -1,5 +1,6 @@import datetime+from django.contrib.sites.models import Sitefrom django.db.models import Exists, OuterRef, Q, Subquery, Sumfrom django.db.models.expressions import ExpressionWrapperfrom django.db.models.fields import IntegerField@@ -116,11 +117,8 @@ def filter_products_by_stock_availability(qs, stock_availability, channel_slug):.values_list(Sum("quantity_reserved")))reservation_subquery = Subquery(queryset=reservations, output_field=IntegerField())- warehouse_pks = list(- Warehouse.objects.using(qs.db)- .for_channel_with_active_shipping_zone_or_cc(channel_slug)- .values_list("pk", flat=True)- )++ warehouse_pks = get_available_warehouse_pks_for_product(qs, channel_slug)stocks = (Stock.objects.using(qs.db).filter(@@ -143,6 +141,31 @@ def filter_products_by_stock_availability(qs, stock_availability, channel_slug):return qs+def get_available_warehouse_pks_for_product(qs, channel_slug):+ include_shipping_zones = (+ Site.objects.get_current().settings.use_legacy_shipping_zone_stock_availability+ )++ if include_shipping_zones:+ warehouse_pks = list(+ Warehouse.objects.using(qs.db)+ .for_channel_with_active_shipping_zone_or_cc(channel_slug)+ .values_list("pk", flat=True)+ )+ else:+ channel = Channel.objects.using(qs.db).filter(slug=channel_slug).first()+ warehouse_pks = (+ list(+ Warehouse.objects.using(qs.db)+ .for_channel(channel.id)+ .values_list("pk", flat=True)+ )+ if channel+ else []+ )+ return warehouse_pks++def filter_categories(qs, _, value):if value:_, category_pks = resolve_global_ids_to_primary_keys(diff --git a/saleor/graphql/product/tests/queries/test_products_query_with_filter.py b/saleor/graphql/product/tests/queries/test_products_query_with_filter.pyindex cbd41db5ee..055f4fb449 100644--- a/saleor/graphql/product/tests/queries/test_products_query_with_filter.py+++ b/saleor/graphql/product/tests/queries/test_products_query_with_filter.py@@ -1614,14 +1614,20 @@ def test_products_query_with_is_published_filter_one_variant_without_price(assert len(products) == 1[email protected]("include_shipping_zones", [True, False])def test_products_query_with_filter_stock_availability_as_staff(+ include_shipping_zones,staff_api_client,product_list,order_line,permission_manage_products,channel_USD,+ site_settings,):# given+ site_settings.use_legacy_shipping_zone_stock_availability = include_shipping_zones+ site_settings.save(update_fields=["use_legacy_shipping_zone_stock_availability"])+for product in product_list:stock = product.variants.first().stocks.first()Allocation.objects.create(@@ -1647,7 +1653,9 @@ def test_products_query_with_filter_stock_availability_as_staff(assert len(products) == 3[email protected]("include_shipping_zones", [True, False])def test_products_query_with_filter_stock_availability_including_reservations(+ include_shipping_zones,staff_api_client,product_list,order_line,@@ -1656,8 +1664,12 @@ def test_products_query_with_filter_stock_availability_including_reservations(channel_USD,warehouse_JPY,stock,+ site_settings,):# given+ site_settings.use_legacy_shipping_zone_stock_availability = include_shipping_zones+ site_settings.save(update_fields=["use_legacy_shipping_zone_stock_availability"])+stocks = [product.variants.first().stocks.first() for product in product_list]stock.quantity = 50stock.product_variant = stocks[2].product_variant@@ -1707,14 +1719,20 @@ def test_products_query_with_filter_stock_availability_including_reservations()[email protected]("include_shipping_zones", [True, False])def test_products_query_with_filter_stock_availability_as_user(+ include_shipping_zones,user_api_client,product_list,order_line,permission_manage_products,channel_USD,+ site_settings,):# given+ site_settings.use_legacy_shipping_zone_stock_availability = include_shipping_zones+ site_settings.save(update_fields=["use_legacy_shipping_zone_stock_availability"])+for product in product_list:stock = product.variants.first().stocks.first()Allocation.objects.create(@@ -1772,14 +1790,50 @@ def test_products_query_with_filter_stock_availability_channel_without_shipping_assert products[0]["node"]["id"] == product_id+def test_products_filter_stock_availability_without_shipping_zones_excluded_from_stock_calculations(+ staff_api_client,+ product,+ permission_manage_products,+ channel_USD,+ site_settings,+):+ # given+ site_settings.use_legacy_shipping_zone_stock_availability = False+ site_settings.save(update_fields=["use_legacy_shipping_zone_stock_availability"])++ channel_USD.shipping_zones.clear()+ variables = {+ "filter": {"stockAvailability": "IN_STOCK"},+ "channel": channel_USD.slug,+ }+ staff_api_client.user.user_permissions.add(permission_manage_products)++ # when+ response = staff_api_client.post_graphql(QUERY_PRODUCTS_WITH_FILTER, variables)+ content = get_graphql_content(response)++ # then - with flag disabled, product is still in stock despite no shipping zones+ products = content["data"]["products"]["edges"]+ product_id = graphene.Node.to_global_id("Product", product.id)++ assert len(products) == 1+ assert products[0]["node"]["id"] == product_id++[email protected]("include_shipping_zones", [True, False])def test_products_query_with_filter_stock_availability_only_stock_in_cc_warehouse(+ include_shipping_zones,user_api_client,product,order_line,channel_USD,warehouse_for_cc,+ site_settings,):# given+ site_settings.use_legacy_shipping_zone_stock_availability = include_shipping_zones+ site_settings.save(update_fields=["use_legacy_shipping_zone_stock_availability"])+variant = product.variants.first()variant.stocks.all().delete()diff --git a/saleor/graphql/product/tests/queries/test_products_query_with_where.py b/saleor/graphql/product/tests/queries/test_products_query_with_where.pyindex 04e24b9b76..5e8cfd73a3 100644--- a/saleor/graphql/product/tests/queries/test_products_query_with_where.py+++ b/saleor/graphql/product/tests/queries/test_products_query_with_where.py@@ -1385,7 +1385,9 @@ def test_products_filter_by_stock_availability(assert returned_slugs == {product_list[index].slug for index in indexes}[email protected]("include_shipping_zones", [True, False])def test_products_filter_by_stock_availability_including_reservations(+ include_shipping_zones,api_client,product_list,order_line,@@ -1393,8 +1395,12 @@ def test_products_filter_by_stock_availability_including_reservations(channel_USD,warehouse_JPY,stock,+ site_settings,):# given+ site_settings.use_legacy_shipping_zone_stock_availability = include_shipping_zones+ site_settings.save(update_fields=["use_legacy_shipping_zone_stock_availability"])+stocks = [product.variants.first().stocks.first() for product in product_list]stock.quantity = 50stock.product_variant = stocks[2].product_variant@@ -1443,13 +1449,19 @@ def test_products_filter_by_stock_availability_including_reservations()[email protected]("include_shipping_zones", [True, False])def test_products_filter_by_stock_availability_as_user(+ include_shipping_zones,user_api_client,product_list,order_line,channel_USD,+ site_settings,):# given+ site_settings.use_legacy_shipping_zone_stock_availability = include_shipping_zones+ site_settings.save(update_fields=["use_legacy_shipping_zone_stock_availability"])+for product in product_list:stock = product.variants.first().stocks.first()Allocation.objects.create(@@ -1505,14 +1517,48 @@ def test_products_filter_by_stock_availability_channel_without_shipping_zones(assert products[0]["node"]["id"] == product_id+def test_products_filter_by_stock_availability_channel_without_shipping_zones_excluded_from_stock_calculations(+ api_client,+ product,+ channel_USD,+ site_settings,+):+ # given+ site_settings.use_legacy_shipping_zone_stock_availability = False+ site_settings.save(update_fields=["use_legacy_shipping_zone_stock_availability"])++ channel_USD.shipping_zones.clear()+ variables = {+ "where": {"stockAvailability": "IN_STOCK"},+ "channel": channel_USD.slug,+ }++ # when+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)+ content = get_graphql_content(response)++ # then - with flag disabled, product is still in stock despite no shipping zones+ products = content["data"]["products"]["edges"]+ product_id = graphene.Node.to_global_id("Product", product.id)++ assert len(products) == 1+ assert products[0]["node"]["id"] == product_id++[email protected]("include_shipping_zones", [True, False])def test_products_filter_by_stock_availability_only_stock_in_cc_warehouse(+ include_shipping_zones,api_client,product,order_line,channel_USD,warehouse_for_cc,+ site_settings,):# given+ site_settings.use_legacy_shipping_zone_stock_availability = include_shipping_zones+ site_settings.save(update_fields=["use_legacy_shipping_zone_stock_availability"])+variant = product.variants.first()variant.stocks.all().delete()@@ -1539,6 +1585,46 @@ def test_products_filter_by_stock_availability_only_stock_in_cc_warehouse()+def test_products_filter_by_stock_availability_as_user_shipping_zones_excluded_from_stock_calculations(+ user_api_client,+ product_list,+ order_line,+ channel_USD,+ site_settings,+):+ # given+ site_settings.use_legacy_shipping_zone_stock_availability = False+ site_settings.save(update_fields=["use_legacy_shipping_zone_stock_availability"])++ for product in product_list:+ stock = product.variants.first().stocks.first()+ Allocation.objects.create(+ order_line=order_line, stock=stock, quantity_allocated=stock.quantity+ )+ product = product_list[0]+ product.variants.first().channel_listings.filter(channel=channel_USD).update(+ price_amount=None+ )+ variables = {+ "where": {"stockAvailability": "OUT_OF_STOCK"},+ "channel": channel_USD.slug,+ }++ # when+ response = user_api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)+ content = get_graphql_content(response)++ # then - same result as with flag enabled: allocations make products out of stock+ product_id = graphene.Node.to_global_id("Product", product_list[1].id)+ second_product_id = graphene.Node.to_global_id("Product", product_list[2].id)++ products = content["data"]["products"]["edges"]++ assert len(products) == 2+ assert products[0]["node"]["id"] == product_id+ assert products[1]["node"]["id"] == second_product_id++@pytest.mark.parametrize(("quantity_input", "warehouse_indexes", "count", "indexes_of_products_in_result"),[diff --git a/saleor/graphql/product/tests/queries/test_variant_query.py b/saleor/graphql/product/tests/queries/test_variant_query.pyindex f5dcfd287d..bd3c1bc1ba 100644--- a/saleor/graphql/product/tests/queries/test_variant_query.py+++ b/saleor/graphql/product/tests/queries/test_variant_query.py@@ -1046,3 +1046,100 @@ def test_stock_quantity_is_sum_of_quantities_from_warehouses_that_support_countrcontent = get_graphql_content(response)assert content["data"]["productVariant"]["quantityAvailable"] == sum_quantities+++def test_quantity_available_ignores_shipping_zones_excluded_from_stock_calculations(+ api_client,+ channel_USD,+ variant_with_many_stocks_different_shipping_zones,+ site_settings,+):+ # When use_legacy_shipping_zone_stock_availability is False, quantityAvailable+ # returns the sum of all stocks from channel warehouses, ignoring shipping zones+ # and country code.++ # given+ site_settings.use_legacy_shipping_zone_stock_availability = False+ site_settings.save(update_fields=["use_legacy_shipping_zone_stock_availability"])++ query = """+ query ProductVariant($id: ID!, $channel: String!, $country: CountryCode) {+ productVariant(id: $id, channel: $channel) {+ quantityWithCountry: quantityAvailable(address: { country: $country })+ quantityWithoutCountry: quantityAvailable+ }+ }+ """++ variant = variant_with_many_stocks_different_shipping_zones+ total_quantity = sum(stock.quantity for stock in variant.stocks.all())++ variables = {+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),+ "channel": channel_USD.slug,+ "country": "PL",+ }++ # when+ response = api_client.post_graphql(query, variables)+ content = get_graphql_content(response)++ # then - both return the same total, country is ignored+ assert content["data"]["productVariant"]["quantityWithCountry"] == total_quantity+ assert content["data"]["productVariant"]["quantityWithoutCountry"] == total_quantity+++def test_stocks_resolver_ignores_shipping_zones_excluded_from_stock_calculations(+ staff_api_client,+ channel_USD,+ variant_with_many_stocks_different_shipping_zones,+ site_settings,+ permission_manage_products,+):+ # When use_legacy_shipping_zone_stock_availability is False, stocks resolver+ # returns stocks from all channel warehouses regardless of shipping zones or address.+ # given+ site_settings.use_legacy_shipping_zone_stock_availability = False+ site_settings.save(update_fields=["use_legacy_shipping_zone_stock_availability"])++ query = """+ query ProductVariant($id: ID!, $channel: String!, $country: CountryCode) {+ productVariant(id: $id, channel: $channel) {+ stocksWithCountry: stocks(address: { country: $country }) {+ quantity+ warehouse {+ slug+ }+ }+ stocksWithoutCountry: stocks {+ quantity+ warehouse {+ slug+ }+ }+ }+ }+ """++ variant = variant_with_many_stocks_different_shipping_zones+ expected_stock_count = variant.stocks.filter(+ warehouse__channels=channel_USD+ ).count()++ variables = {+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),+ "channel": channel_USD.slug,+ "country": "PL",+ }++ # when+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products]+ )+ content = get_graphql_content(response)++ # then - both return the same stocks, address is ignored+ stocks_with_country = content["data"]["productVariant"]["stocksWithCountry"]+ stocks_without_country = content["data"]["productVariant"]["stocksWithoutCountry"]+ assert len(stocks_with_country) == expected_stock_count+ assert len(stocks_without_country) == expected_stock_countdiff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.pyindex a4956e6a5d..353d756358 100644--- a/saleor/graphql/product/types/products.py+++ b/saleor/graphql/product/types/products.py@@ -124,9 +124,11 @@ from ...translations.types import ProductTranslation, ProductVariantTranslationfrom ...utils import get_user_or_app_from_contextfrom ...utils.filters import reporting_period_to_datefrom ...warehouse.dataloaders import (+ AvailableQuantityByProductVariantIdAndChannelSlugLoader,AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader,PreorderQuantityReservedByVariantChannelListingIdLoader,StocksByProductVariantIdLoader,+ StocksWithAvailableQuantityByProductVariantIdAndChannelSlugLoader,StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChannelLoader,)from ...warehouse.types import Stock@@ -179,6 +181,20 @@ destination_address_argument = graphene.Argument(),)+deprecated_destination_address_argument = graphene.Argument(+ account_types.AddressInput,+ description=(+ "Destination address used to find warehouses where stock availability "+ "for this product is checked. If address is empty, uses "+ "`Shop.companyAddress` or fallbacks to server's "+ "`settings.DEFAULT_COUNTRY` configuration. "+ "When `Shop.useLegacyShippingZoneStockAvailability` is disabled, "+ "this argument is ignored — stock availability is determined by the "+ "direct warehouse-channel link instead of shipping zones."+ + DEPRECATED_IN_3X_INPUT+ ),+)+class BasePricingInfo(BaseObjectType):on_sale = graphene.Boolean(description="Whether it is in sale or not.")@@ -408,7 +424,7 @@ class ProductVariant(ChannelContextType[models.ProductVariant]):stocks = PermissionsField(NonNullList(Stock),description="Stocks for the product variant.",- address=destination_address_argument,+ address=deprecated_destination_address_argument,country_code=graphene.Argument(CountryCodeEnum,description=(@@ -429,7 +445,7 @@ class ProductVariant(ChannelContextType[models.ProductVariant]):"no `limitQuantityPerCheckout` in global settings has been set, and ""`productVariant` stocks are not tracked."),- address=destination_address_argument,+ address=deprecated_destination_address_argument,country_code=graphene.Argument(CountryCodeEnum,description=(@@ -476,20 +492,30 @@ class ProductVariant(ChannelContextType[models.ProductVariant]):return root.channel_slug@staticmethod+ @load_site_callbackdef resolve_stocks(root: ChannelContext[models.ProductVariant],info,+ site,address=None,country_code=None,):if address is not None:country_code = address.country- channle_slug = root.channel_slug- if channle_slug or country_code:+ channel_slug = root.channel_slug+ if not channel_slug and not country_code:+ return StocksByProductVariantIdLoader(info.context).load(root.node.id)++ include_shipping_zones = (+ site.settings.use_legacy_shipping_zone_stock_availability+ )+ if include_shipping_zones:return StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChannelLoader( # noqa: E501info.context).load((root.node.id, country_code, root.channel_slug))- return StocksByProductVariantIdLoader(info.context).load(root.node.id)+ return StocksWithAvailableQuantityByProductVariantIdAndChannelSlugLoader(+ info.context+ ).load((root.node.id, str(channel_slug)))@staticmethod@load_site_callback@@ -606,9 +632,16 @@ class ProductVariant(ChannelContextType[models.ProductVariant]):if not root.node.track_inventory:return global_quantity_limit_per_checkout- return AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader(+ include_shipping_zones = (+ site.settings.use_legacy_shipping_zone_stock_availability+ )+ if include_shipping_zones:+ return AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader(+ info.context+ ).load((root.node.id, country_code, channel_slug))+ return AvailableQuantityByProductVariantIdAndChannelSlugLoader(info.context- ).load((root.node.id, country_code, channel_slug))+ ).load((root.node.id, channel_slug))@classmethoddef resolve_assigned_attribute(@@ -934,7 +967,7 @@ class Product(ChannelContextType[models.Product]):),)is_available = graphene.Boolean(- address=destination_address_argument,+ address=deprecated_destination_address_argument,description=("Whether the product is in stock, set as available for purchase in the ""given channel, and published."@@ -1304,8 +1337,9 @@ class Product(ChannelContextType[models.Product]):@staticmethod@traced_resolver+ @load_site_callbackdef resolve_is_available(- root: ChannelContext[models.Product], info, *, address=None+ root: ChannelContext[models.Product], info, site, *, address=None):if not root.channel_slug:return None@@ -1325,11 +1359,24 @@ class Product(ChannelContextType[models.Product]):return Truereturn False+ include_shipping_zones = (+ site.settings.use_legacy_shipping_zone_stock_availability+ )+def load_variants_availability(variants):- keys = [(variant.id, country_code, channel_slug) for variant in variants]- return AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader(+ if include_shipping_zones:+ country_keys = [+ (variant.id, country_code, channel_slug) for variant in variants+ ]+ return (+ AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader(+ info.context+ ).load_many(country_keys)+ )+ channel_keys = [(variant.id, channel_slug) for variant in variants]+ return AvailableQuantityByProductVariantIdAndChannelSlugLoader(info.context- ).load_many(keys)+ ).load_many(channel_keys)def check_variant_availability():if has_required_permissions and not channel_slug:diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 095591860f..4f2a351f74 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -6825,9 +6825,9 @@ type Product implements Node & ObjectWithMetadata & ObjectWithAttributes @doc(ca"""isAvailable("""- Destination address used to find warehouses where stock availability for this product is checked. If address is empty, uses `Shop.companyAddress` or fallbacks to server's `settings.DEFAULT_COUNTRY` configuration.+ Destination address used to find warehouses where stock availability for this product is checked. If address is empty, uses `Shop.companyAddress` or fallbacks to server's `settings.DEFAULT_COUNTRY` configuration. When `Shop.useLegacyShippingZoneStockAvailability` is disabled, this argument is ignored — stock availability is determined by the direct warehouse-channel link instead of shipping zones."""- address: AddressInput+ address: AddressInput @deprecated): Boolean"""A type of tax. Assigned by enabled tax gateway"""@@ -8767,9 +8767,9 @@ type ProductVariant implements Node & ObjectWithMetadata & ObjectWithAttributes"""stocks("""- Destination address used to find warehouses where stock availability for this product is checked. If address is empty, uses `Shop.companyAddress` or fallbacks to server's `settings.DEFAULT_COUNTRY` configuration.+ Destination address used to find warehouses where stock availability for this product is checked. If address is empty, uses `Shop.companyAddress` or fallbacks to server's `settings.DEFAULT_COUNTRY` configuration. When `Shop.useLegacyShippingZoneStockAvailability` is disabled, this argument is ignored — stock availability is determined by the direct warehouse-channel link instead of shipping zones."""- address: AddressInput+ address: AddressInput @deprecated"""Two-letter ISO 3166-1 country code."""countryCode: CountryCode @deprecated(reason: "Use `address` argument instead.")@@ -8780,9 +8780,9 @@ type ProductVariant implements Node & ObjectWithMetadata & ObjectWithAttributes"""quantityAvailable("""- Destination address used to find warehouses where stock availability for this product is checked. If address is empty, uses `Shop.companyAddress` or fallbacks to server's `settings.DEFAULT_COUNTRY` configuration.+ Destination address used to find warehouses where stock availability for this product is checked. If address is empty, uses `Shop.companyAddress` or fallbacks to server's `settings.DEFAULT_COUNTRY` configuration. When `Shop.useLegacyShippingZoneStockAvailability` is disabled, this argument is ignored — stock availability is determined by the direct warehouse-channel link instead of shipping zones."""- address: AddressInput+ address: AddressInput @deprecated"""Two-letter ISO 3166-1 country code. When provided, the exact quantity from a warehouse operating in shipping zones that contain this country will be returned. Otherwise, it will return the maximum quantity from all shipping zones.@@ -15068,6 +15068,13 @@ type Shop implements ObjectWithMetadata {"""Charge taxes on shipping."""chargeTaxesOnShipping: Boolean! @deprecated(reason: "Use `ShippingMethodType.taxClass` to determine whether taxes are calculated for shipping methods; if a tax class is set, the taxes will be calculated, otherwise no tax rate will be applied.")+ """+ When enabled, stock availability is filtered by shipping zones and the destination address (legacy behavior). When disabled, stock availability is determined only by the direct warehouse-channel link, ignoring shipping zones.++ Added in Saleor 3.23.+ """+ useLegacyShippingZoneStockAvailability: Boolean!+"""Use legacy update webhook emission. When enabled, update webhooks (e.g. `customerUpdated`,`productVariantUpdated`) are sent even when only metadata changes. When disabled, update webhooks are not sent for metadata-only changes; only metadata-specific webhooks (e.g., `customerMetadataUpdated`, `productVariantMetadataUpdated`) are sent.@@ -22993,6 +23000,13 @@ input ShopSettingsInput {"""passwordLoginMode: PasswordLoginModeEnum+ """+ When enabled, stock availability is filtered by shipping zones and the destination address (legacy behavior). When disabled, stock availability is determined only by the direct warehouse-channel link, ignoring shipping zones.++ Added in Saleor 3.23.+ """+ useLegacyShippingZoneStockAvailability: Boolean+"""Include taxes in prices."""includeTaxesInPrices: Boolean @deprecated(reason: "Use `taxConfigurationUpdate` mutation to configure this setting per channel or country.")diff --git a/saleor/graphql/shop/mutations/shop_settings_update.py b/saleor/graphql/shop/mutations/shop_settings_update.pyindex 50ce31a92d..f519a17ed5 100644--- a/saleor/graphql/shop/mutations/shop_settings_update.py+++ b/saleor/graphql/shop/mutations/shop_settings_update.py@@ -97,6 +97,14 @@ class ShopSettingsInput(graphene.InputObjectType):description="Controls whether password-based authentication is allowed."+ ADDED_IN_323,)+ use_legacy_shipping_zone_stock_availability = graphene.Boolean(+ description=(+ "When enabled, stock availability is filtered by shipping zones "+ "and the destination address (legacy behavior). "+ "When disabled, stock availability is determined only by the direct "+ "warehouse-channel link, ignoring shipping zones." + ADDED_IN_323+ ),+ )# deprecatedinclude_taxes_in_prices = graphene.Boolean(diff --git a/saleor/graphql/shop/tests/mutations/test_shop_settings_update.py b/saleor/graphql/shop/tests/mutations/test_shop_settings_update.pyindex b4270d5bd9..7b01bb35d5 100644--- a/saleor/graphql/shop/tests/mutations/test_shop_settings_update.py+++ b/saleor/graphql/shop/tests/mutations/test_shop_settings_update.py@@ -24,6 +24,7 @@ SHOP_SETTINGS_UPDATE_MUTATION = """allowLoginWithoutConfirmationuseLegacyUpdateWebhookEmissionpreserveAllAddressFields+ useLegacyShippingZoneStockAvailability}errors {field@@ -78,6 +79,8 @@ def test_shop_settings_mutation(assert site_settings.enable_account_confirmation_by_email is Falseassert site_settings.allow_login_without_confirmation is Trueassert site_settings.use_legacy_update_webhook_emission is False+ assert site_settings.preserve_all_address_fields is False+ assert site_settings.use_legacy_shipping_zone_stock_availability is Truedef test_shop_reservation_settings_mutation(@@ -335,6 +338,95 @@ def test_shop_settings_update_preserve_all_address_fields_disable(assert site_settings.preserve_all_address_fields is False+MUTATION_UPDATE_use_legacy_shipping_zone_stock_availability = """+ mutation updateSettings($input: ShopSettingsInput!) {+ shopSettingsUpdate(input: $input) {+ shop {+ useLegacyShippingZoneStockAvailability+ }+ errors {+ field+ message+ code+ }+ }+ }+"""+++def test_shop_settings_update_use_legacy_shipping_zone_stock_availability_disable(+ staff_api_client, site_settings, permission_manage_settings+):+ # given+ use_legacy_shipping_zone_stock_availability_value = False+ assert (+ site_settings.use_legacy_shipping_zone_stock_availability+ is not use_legacy_shipping_zone_stock_availability_value+ )+ variables = {+ "input": {+ "useLegacyShippingZoneStockAvailability": use_legacy_shipping_zone_stock_availability_value+ }+ }++ # when+ response = staff_api_client.post_graphql(+ MUTATION_UPDATE_use_legacy_shipping_zone_stock_availability,+ variables,+ permissions=[permission_manage_settings],+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["shopSettingsUpdate"]+ assert not data["errors"]+ assert (+ data["shop"]["useLegacyShippingZoneStockAvailability"]+ is use_legacy_shipping_zone_stock_availability_value+ )+ site_settings.refresh_from_db()+ assert (+ site_settings.use_legacy_shipping_zone_stock_availability+ == use_legacy_shipping_zone_stock_availability_value+ )+++def test_shop_settings_update_use_legacy_shipping_zone_stock_availability_enable(+ staff_api_client, site_settings, permission_manage_settings+):+ # given+ use_legacy_shipping_zone_stock_availability_value = True+ site_settings.use_legacy_shipping_zone_stock_availability = False+ site_settings.save(update_fields=["use_legacy_shipping_zone_stock_availability"])++ variables = {+ "input": {+ "useLegacyShippingZoneStockAvailability": use_legacy_shipping_zone_stock_availability_value+ }+ }++ # when+ response = staff_api_client.post_graphql(+ MUTATION_UPDATE_use_legacy_shipping_zone_stock_availability,+ variables,+ permissions=[permission_manage_settings],+ )+ content = get_graphql_content(response)++ # then+ data = content["data"]["shopSettingsUpdate"]+ assert not data["errors"]+ assert (+ data["shop"]["useLegacyShippingZoneStockAvailability"]+ == use_legacy_shipping_zone_stock_availability_value+ )+ site_settings.refresh_from_db()+ assert (+ site_settings.use_legacy_shipping_zone_stock_availability+ == use_legacy_shipping_zone_stock_availability_value+ )++MUTATION_UPDATE_DEFAULT_MAIL_SENDER_SETTINGS = """mutation updateDefaultSenderSettings($input: ShopSettingsInput!) {shopSettingsUpdate(input: $input) {diff --git a/saleor/graphql/shop/types.py b/saleor/graphql/shop/types.pyindex f4c4d131a3..07b7bd1e4d 100644--- a/saleor/graphql/shop/types.py+++ b/saleor/graphql/shop/types.py@@ -392,6 +392,15 @@ class Shop(graphene.ObjectType):"the taxes will be calculated, otherwise no tax rate will be applied.",required=True,)+ use_legacy_shipping_zone_stock_availability = graphene.Boolean(+ description=(+ "When enabled, stock availability is filtered by shipping zones "+ "and the destination address (legacy behavior). "+ "When disabled, stock availability is determined only by the direct "+ "warehouse-channel link, ignoring shipping zones." + ADDED_IN_323+ ),+ required=True,+ )# legacy settingsuse_legacy_update_webhook_emission = graphene.Boolean(@@ -674,6 +683,11 @@ class Shop(graphene.ObjectType):def resolve_password_login_mode(_, _info, site):return site.settings.password_login_mode+ @staticmethod+ @load_site_callback+ def resolve_use_legacy_shipping_zone_stock_availability(_, _info, site):+ return site.settings.use_legacy_shipping_zone_stock_availability+@staticmethod@load_site_callbackdef resolve_use_legacy_update_webhook_emission(_, _info, site):diff --git a/saleor/graphql/warehouse/dataloaders.py b/saleor/graphql/warehouse/dataloaders.pyindex 9160ea0713..beafaa6c6a 100644--- a/saleor/graphql/warehouse/dataloaders.py+++ b/saleor/graphql/warehouse/dataloaders.py@@ -567,6 +567,149 @@ class StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChannelLoader(return warehouse_ids_by_country_and_channel_map+VariantIdChannelSlug = tuple[int, str]+++class AvailableQuantityByProductVariantIdAndChannelSlugLoader(+ DataLoader[VariantIdChannelSlug, int]+):+ """Calculate available variant quantity for a variant and channel.++ Sums stock quantities from channel warehouses, subtracts reservations,+ and caps the result by the site's maximum quantity per checkout.+ """++ context_key = "available_quantity_by_productvariant_and_channel"++ def prepare_stocks_reservations_map(self, variant_ids, site):+ """Prepare stock id to quantity reserved map for provided variant ids."""+ stocks_reservations: defaultdict[int, int] = defaultdict(int)+ if is_reservation_enabled(site.settings):+ reservations_qs = (+ Stock.objects.using(self.database_connection_name)+ .filter(product_variant_id__in=variant_ids)+ .annotate_reserved_quantity()+ .order_by("pk")+ .values_list("id", "reserved_quantity")+ )+ for stock_id, quantity_reserved in reservations_qs:+ stocks_reservations[stock_id] = quantity_reserved+ return stocks_reservations++ def batch_load(self, keys: Iterable[VariantIdChannelSlug]):+ def with_stocks_and_site(data):+ stocks_per_key, site = data++ all_variant_ids = list({variant_id for variant_id, _ in keys})+ stocks_reservations = self.prepare_stocks_reservations_map(+ all_variant_ids, site+ )++ global_quantity_limit = site.settings.limit_quantity_per_checkout++ results = []+ for stocks in stocks_per_key:+ total = 0+ for stock in stocks:+ reserved = stocks_reservations[stock.id]+ quantity = stock.available_quantity - reserved+ if stock.available_quantity > 0:+ quantity = max(0, quantity)+ total += quantity++ results.append(+ max(+ 0,+ min(total, global_quantity_limit or sys.maxsize),+ )+ )+ return results++ stocks_promise = (+ StocksWithAvailableQuantityByProductVariantIdAndChannelSlugLoader(+ self.context+ ).load_many(keys)+ )+ site_promise = get_site_promise(self.context)+ return Promise.all([stocks_promise, site_promise]).then(with_stocks_and_site)+++class StocksWithAvailableQuantityByProductVariantIdAndChannelSlugLoader(+ DataLoader[VariantIdChannelSlug, Iterable[Stock]]+):+ """Return stocks with available quantity using only the channel-warehouse link.++ For each variant and channel return stocks with available quantity.+ """++ context_key = "stocks_with_available_quantity_by_productvariant_and_channel"++ def batch_load(self, keys: Iterable[VariantIdChannelSlug]):+ channel_slugs = list({channel_slug for _, channel_slug in keys})++ def with_channels(channels):+ def with_warehouses(warehouses_by_channel):+ warehouses_by_channel_map = {+ channel.slug: {warehouse.id for warehouse in warehouses}+ for channel, warehouses in zip(+ channels, warehouses_by_channel, strict=False+ )+ }++ all_warehouse_ids = {+ warehouse_id+ for warehouse_ids in warehouses_by_channel_map.values()+ for warehouse_id in warehouse_ids+ }+ all_variant_ids = list({variant_id for variant_id, _ in keys})++ stocks_qs = (+ Stock.objects.using(self.database_connection_name)+ .filter(+ product_variant_id__in=all_variant_ids,+ warehouse_id__in=all_warehouse_ids,+ )+ .annotate_available_quantity()+ .order_by("pk")+ )++ all_stocks = list(stocks_qs)+ stocks_by_variant_and_warehouse: defaultdict[tuple, list] = defaultdict(+ list+ )+ for stock in all_stocks:+ stocks_by_variant_and_warehouse[+ (stock.product_variant_id, stock.warehouse_id)+ ].append(stock)++ results = []+ for variant_id, channel_slug in keys:+ warehouse_ids = warehouses_by_channel_map.get(channel_slug, set())+ stocks = []+ for warehouse_id in warehouse_ids:+ stocks.extend(+ stocks_by_variant_and_warehouse.get(+ (variant_id, warehouse_id), []+ )+ )+ results.append(stocks)++ return results++ channel_ids = [channel.id for channel in channels]+ return (+ WarehousesByChannelIdLoader(self.context)+ .load_many(channel_ids)+ .then(with_warehouses)+ )++ return (+ ChannelBySlugLoader(self.context)+ .load_many(channel_slugs)+ .then(with_channels)+ )++class StocksReservationsByCheckoutTokenLoader(DataLoader):context_key = "stock_reservations_by_checkout_token"diff --git a/saleor/order/actions.py b/saleor/order/actions.pyindex e84bc53756..c869ac1da3 100644--- a/saleor/order/actions.py+++ b/saleor/order/actions.py@@ -1075,6 +1075,8 @@ def _create_fulfillment_lines(channel_slug: str,gift_card_lines_info: list[GiftCardLineData],manager: "PluginsManager",+ *,+ include_shipping_zones: bool,should_decrease_stock: bool = True,allow_stock_to_be_exceeded: bool = False,) -> list[FulfillmentLine]:@@ -1099,6 +1101,9 @@ def _create_fulfillment_lines(should_decrease_stock (Bool): Stocks will get decreased if this is True.allow_stock_to_be_exceeded (bool): If `True` then stock quantity could exceed.Default value is set to `False`.+ include_shipping_zones (bool): If `True`, stock is filtered by shipping+ zones (legacy behavior). If `False`, all warehouse stocks in the+ channel are used regardless of shipping zones.Return:List[FulfillmentLine]: Unsaved fulfillment lines created for this fulfillment@@ -1111,7 +1116,9 @@ def _create_fulfillment_lines(lines = [line_data["order_line"] for line_data in lines_data]variants = [line.variant for line in lines if line.variant]stocks = (- Stock.objects.for_channel_and_country(channel_slug)+ Stock.objects.for_channel_or_country(+ channel_slug, include_shipping_zones=include_shipping_zones+ ).filter(warehouse_id=warehouse_pk, product_variant__in=variants).select_related("product_variant"))@@ -1280,6 +1287,7 @@ def create_fulfillments(manager,should_decrease_stock=auto_approved,allow_stock_to_be_exceeded=allow_stock_to_be_exceeded,+ include_shipping_zones=site_settings.use_legacy_shipping_zone_stock_availability,))if tracking_number:diff --git a/saleor/order/tests/test_notifications.py b/saleor/order/tests/test_notifications.pyindex 189999bb16..d23acdec0b 100644--- a/saleor/order/tests/test_notifications.py+++ b/saleor/order/tests/test_notifications.py@@ -469,6 +469,7 @@ def test_send_confirmation_emails_without_addresses_for_payment(user=None,app=None,manager=anonymous_plugins,+ site_settings=site_settings,)order.shipping_address = None@@ -527,6 +528,7 @@ def test_send_confirmation_emails_without_addresses_for_order(user=None,app=None,manager=anonymous_plugins,+ site_settings=site_settings,)order.shipping_address = Nonediff --git a/saleor/order/tests/test_order.py b/saleor/order/tests/test_order.pyindex 530ff1de68..2f9254f94f 100644--- a/saleor/order/tests/test_order.py+++ b/saleor/order/tests/test_order.py@@ -85,6 +85,7 @@ def test_add_variant_to_order_adds_line_for_new_variant(order_with_lines,product,anonymous_plugins,+ site_settings,):order = order_with_linesvariant = product.variants.get()@@ -97,6 +98,7 @@ def test_add_variant_to_order_adds_line_for_new_variant(user=None,app=None,manager=anonymous_plugins,+ site_settings=site_settings,)line = order.lines.last()@@ -117,6 +119,7 @@ def test_add_variant_to_order_adds_line_for_new_variant_on_promotion(product,anonymous_plugins,catalogue_promotion_without_rules,+ site_settings,):# givenorder = order_with_lines@@ -169,6 +172,7 @@ def test_add_variant_to_order_adds_line_for_new_variant_on_promotion(user=None,app=None,manager=anonymous_plugins,+ site_settings=site_settings,)# then@@ -195,6 +199,7 @@ def test_add_variant_to_draft_order_adds_line_for_variant_with_price_0(order_with_lines,product,anonymous_plugins,+ site_settings,):# givenorder = order_with_lines@@ -216,6 +221,7 @@ def test_add_variant_to_draft_order_adds_line_for_variant_with_price_0(user=None,app=None,manager=anonymous_plugins,+ site_settings=site_settings,)# then@@ -232,6 +238,7 @@ def test_add_variant_to_order_not_allocates_stock_for_new_variant(order_with_lines,product,anonymous_plugins,+ site_settings,):variant = product.variants.get()stock = Stock.objects.get(product_variant=variant)@@ -245,6 +252,7 @@ def test_add_variant_to_order_not_allocates_stock_for_new_variant(user=None,app=None,manager=anonymous_plugins,+ site_settings=site_settings,)stock.refresh_from_db()@@ -252,7 +260,9 @@ def test_add_variant_to_order_not_allocates_stock_for_new_variant(def test_add_variant_to_order_edits_line_for_existing_variant(- order_with_lines, anonymous_plugins+ order_with_lines,+ anonymous_plugins,+ site_settings,):existing_line = order_with_lines.lines.first()variant = existing_line.variant@@ -268,6 +278,7 @@ def test_add_variant_to_order_edits_line_for_existing_variant(user=None,app=None,manager=anonymous_plugins,+ site_settings=site_settings,)existing_line.refresh_from_db()@@ -278,7 +289,7 @@ def test_add_variant_to_order_edits_line_for_existing_variant(def test_add_variant_to_order_not_allocates_stock_for_existing_variant(- order_with_lines, anonymous_plugins+ order_with_lines, anonymous_plugins, site_settings):existing_line = order_with_lines.lines.first()variant = existing_line.variant@@ -296,6 +307,7 @@ def test_add_variant_to_order_not_allocates_stock_for_existing_variant(user=None,app=None,manager=anonymous_plugins,+ site_settings=site_settings,)stock.refresh_from_db()@@ -306,9 +318,7 @@ def test_add_variant_to_order_not_allocates_stock_for_existing_variant(def test_add_variant_to_order_adds_line_empty_product_translation(- order_with_lines,- product,- anonymous_plugins,+ order_with_lines, product, anonymous_plugins, site_settings):# givenorder = order_with_lines@@ -324,6 +334,7 @@ def test_add_variant_to_order_adds_line_empty_product_translation(user=None,app=None,manager=anonymous_plugins,+ site_settings=site_settings,)# then@@ -648,7 +659,9 @@ def test_calculate_order_weight(order_with_lines):assert calculated_weight == order_weight-def test_order_weight_add_more_variant(order_with_lines, anonymous_plugins):+def test_order_weight_add_more_variant(+ order_with_lines, anonymous_plugins, site_settings+):variant = order_with_lines.lines.first().variantline_data = OrderLineData(variant_id=str(variant.id), variant=variant, quantity=2)@@ -658,6 +671,7 @@ def test_order_weight_add_more_variant(order_with_lines, anonymous_plugins):user=None,app=None,manager=anonymous_plugins,+ site_settings=site_settings,)order_with_lines.refresh_from_db()@@ -670,6 +684,7 @@ def test_order_weight_add_new_variant(order_with_lines,product,anonymous_plugins,+ site_settings,):variant = product.variants.first()line_data = OrderLineData(variant_id=str(variant.id), variant=variant, quantity=2)@@ -680,6 +695,7 @@ def test_order_weight_add_new_variant(user=None,app=None,manager=anonymous_plugins,+ site_settings=site_settings,)order_with_lines.refresh_from_db()@@ -688,7 +704,7 @@ def test_order_weight_add_new_variant()-def test_order_weight_change_line_quantity(staff_user, lines_info):+def test_order_weight_change_line_quantity(staff_user, lines_info, site_settings):app = Noneline_info = lines_info[0]new_quantity = line_info.quantity + 2@@ -701,6 +717,7 @@ def test_order_weight_change_line_quantity(staff_user, lines_info):line_info.quantity,order,get_plugins_manager(allow_replica=False),+ site_settings,)assert order.weight == _calculate_order_weight_from_lines(order)@@ -716,6 +733,7 @@ def test_get_order_weight_non_existing_product(order_with_lines,product,anonymous_plugins,+ site_settings,):# Removing product should not affect order's weightorder = order_with_lines@@ -728,6 +746,7 @@ def test_get_order_weight_non_existing_product(user=None,app=None,manager=anonymous_plugins,+ site_settings=site_settings,)old_weight = order.weight@@ -778,7 +797,9 @@ def test_validate_voucher_in_order_without_voucher(mock_validate_voucher.assert_not_called()-def test_ordered_item_change_quantity(staff_user, transactional_db, lines_info):+def test_ordered_item_change_quantity(+ staff_user, transactional_db, lines_info, site_settings+):app = Noneorder = lines_info[0].line.orderassert not order.events.count()@@ -790,6 +811,7 @@ def test_ordered_item_change_quantity(staff_user, transactional_db, lines_info):0,order,get_plugins_manager(allow_replica=False),+ site_settings,)change_order_line_quantity(staff_user,@@ -799,12 +821,13 @@ def test_ordered_item_change_quantity(staff_user, transactional_db, lines_info):0,order,get_plugins_manager(allow_replica=False),+ site_settings,)assert order.get_total_quantity() == 0def test_change_order_line_quantity_changes_total_prices(- staff_user, transactional_db, lines_info+ staff_user, transactional_db, lines_info, site_settings):app = Noneorder = lines_info[0].line.order@@ -819,6 +842,7 @@ def test_change_order_line_quantity_changes_total_prices(new_quantity,order,get_plugins_manager(allow_replica=False),+ site_settings,)assert line_info.line.total_price == line_info.line.unit_price * new_quantity@@ -1146,6 +1170,7 @@ def test_add_variant_to_order_adds_line_for_new_variant_on_promotion_with_customproduct,anonymous_plugins,catalogue_promotion_without_rules,+ site_settings,):# givenorder = order_with_lines@@ -1200,6 +1225,7 @@ def test_add_variant_to_order_adds_line_for_new_variant_on_promotion_with_customuser=None,app=None,manager=anonymous_plugins,+ site_settings=site_settings,)# then@@ -1227,6 +1253,7 @@ def test_add_variant_to_order_adds_line_with_custom_price_for_new_variant(order_with_lines,product,anonymous_plugins,+ site_settings,):# givenorder = order_with_lines@@ -1247,6 +1274,7 @@ def test_add_variant_to_order_adds_line_with_custom_price_for_new_variant(user=None,app=None,manager=anonymous_plugins,+ site_settings=site_settings,)# then@@ -1276,6 +1304,7 @@ def test_add_variant_to_order_adds_translations_in_order_language(variant_translation_fr,settings,anonymous_plugins,+ site_settings,):# givenlanguage_code = "fr"@@ -1294,6 +1323,7 @@ def test_add_variant_to_order_adds_translations_in_order_language(user=None,app=None,manager=anonymous_plugins,+ site_settings=site_settings,)# thendiff --git a/saleor/order/tests/test_order_utils.py b/saleor/order/tests/test_order_utils.pyindex 7a58a0e668..a04648922b 100644--- a/saleor/order/tests/test_order_utils.py+++ b/saleor/order/tests/test_order_utils.py@@ -49,6 +49,7 @@ def test_change_quantity_generates_proper_event(removed_count,order_with_lines,staff_user,+ site_settings,):assert not OrderEvent.objects.exists()order_with_lines.status = status@@ -76,6 +77,7 @@ def test_change_quantity_generates_proper_event(new_quantity,order_with_lines,get_plugins_manager(allow_replica=False),+ site_settings,allocate_stock=order_with_lines.is_unconfirmed(),)@@ -106,8 +108,7 @@ def test_change_quantity_generates_proper_event(def test_change_quantity_update_line_fields(- order_with_lines,- staff_user,+ order_with_lines, staff_user, site_settings):# givenline = order_with_lines.lines.last()@@ -129,6 +130,7 @@ def test_change_quantity_update_line_fields(new_quantity,order_with_lines,get_plugins_manager(allow_replica=False),+ site_settings,)# then@@ -183,6 +185,7 @@ def test_add_variant_to_order(customer_user,variant,catalogue_promotion_with_single_rule,+ site_settings,):# givenmanager = get_plugins_manager(allow_replica=False)@@ -216,6 +219,7 @@ def test_add_variant_to_order(customer_user,None,manager,+ site_settings,)# thendiff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex 07dcd5f705..49d462933c 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -73,6 +73,7 @@ if TYPE_CHECKING:from ..graphql.order.utils import OrderLineDatafrom ..payment.models import Payment, TransactionItemfrom ..plugins.manager import PluginsManager+ from ..site.models import SiteSettingslogger = logging.getLogger(__name__)@@ -230,6 +231,7 @@ def create_order_line(order,line_data,manager,+ site_settings,allocate_stock=False,) -> OrderLine:channel = order.channel@@ -336,6 +338,9 @@ def create_order_line(],channel,manager=manager,+ include_shipping_zones=(+ site_settings.use_legacy_shipping_zone_stock_availability+ ),)if is_line_level_voucher(order.voucher):@@ -353,6 +358,7 @@ def add_variant_to_order(user: Optional["User"],app: Optional["App"],manager: "PluginsManager",+ site_settings: "SiteSettings",allocate_stock: bool = False,) -> OrderLine:"""Add total_quantity of variant to order.@@ -380,6 +386,7 @@ def add_variant_to_order(new_quantity,order,manager=manager,+ site_settings=site_settings,send_event=False,update_fields=update_fields,allocate_stock=allocate_stock,@@ -394,6 +401,7 @@ def add_variant_to_order(order,line_data,manager,+ site_settings,allocate_stock,)@@ -523,6 +531,7 @@ def _update_allocations_for_line(new_quantity: int,channel: "Channel",manager: "PluginsManager",+ site_settings: "SiteSettings",):if old_quantity == new_quantity:return@@ -531,7 +540,12 @@ def _update_allocations_for_line(if not get_order_lines_with_track_inventory([line_info]):returnline_info.quantity = new_quantity - old_quantity- increase_allocations([line_info], channel, manager)+ include_shipping_zones = (+ site_settings.use_legacy_shipping_zone_stock_availability+ )+ increase_allocations(+ [line_info], channel, manager, include_shipping_zones=include_shipping_zones+ )else:line_info.quantity = old_quantity - new_quantitydecrease_allocations([line_info], manager)@@ -545,6 +559,7 @@ def change_order_line_quantity(new_quantity: int,order: "Order",manager: "PluginsManager",+ site_settings: "SiteSettings",send_event: bool = True,update_fields: list[str] | None = None,allocate_stock: bool = False,@@ -556,7 +571,7 @@ def change_order_line_quantity(if new_quantity:if allocate_stock:_update_allocations_for_line(- line_info, old_quantity, new_quantity, channel, manager+ line_info, old_quantity, new_quantity, channel, manager, site_settings)line.quantity = new_quantitytotal_price_net_amount = line.quantity * line.unit_price_net_amountdiff --git a/saleor/site/migrations/0048_sitesettings_include_shipping_zones_in_stock_availability.py b/saleor/site/migrations/0048_sitesettings_include_shipping_zones_in_stock_availability.pynew file mode 100644index 0000000000..4a5021f74a--- /dev/null+++ b/saleor/site/migrations/0048_sitesettings_include_shipping_zones_in_stock_availability.py@@ -0,0 +1,17 @@+# Generated by Django 5.2.11 on 2026-03-31 09:01++from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("site", "0047_merge_20260320_1308"),+ ]++ operations = [+ migrations.AddField(+ model_name="sitesettings",+ name="use_legacy_shipping_zone_stock_availability",+ field=models.BooleanField(db_default=True, default=False),+ ),+ ]diff --git a/saleor/site/models.py b/saleor/site/models.pyindex 97484a9ee6..146f8a32bb 100644--- a/saleor/site/models.py+++ b/saleor/site/models.py@@ -133,6 +133,10 @@ class SiteSettings(ModelWithMetadata):"`productVariantMetadataUpdated`) are sent."),)+ use_legacy_shipping_zone_stock_availability = models.BooleanField(+ default=False,+ db_default=True,+ )class Meta:permissions = (diff --git a/saleor/site/tests/fixtures/site_settings.py b/saleor/site/tests/fixtures/site_settings.pyindex c55b456f9d..21c38a1e6c 100644--- a/saleor/site/tests/fixtures/site_settings.py+++ b/saleor/site/tests/fixtures/site_settings.py@@ -32,6 +32,7 @@ def site_settings(db, settings) -> SiteSettings:)[0]obj.top_menu = main_menuobj.bottom_menu = secondary_menu+ obj.use_legacy_shipping_zone_stock_availability = Trueobj.save()return objdiff --git a/saleor/warehouse/availability.py b/saleor/warehouse/availability.pyindex 7cb8a62ac1..3adc167210 100644--- a/saleor/warehouse/availability.py+++ b/saleor/warehouse/availability.py@@ -65,6 +65,8 @@ def check_stock_and_preorder_quantity(country_code: str,channel_slug: str,quantity: int,+ *,+ include_shipping_zones: bool,checkout_lines: list["CheckoutLine"] | None = None,check_reservations: bool = False,order_line: Optional["OrderLine"] = None,@@ -90,10 +92,11 @@ def check_stock_and_preorder_quantity(country_code,channel_slug,quantity,- checkout_lines,- check_reservations,- order_line,- database_connection_name,+ include_shipping_zones=include_shipping_zones,+ checkout_lines=checkout_lines,+ check_reservations=check_reservations,+ order_line=order_line,+ database_connection_name=database_connection_name,)@@ -102,20 +105,25 @@ def check_stock_quantity(country_code: str,channel_slug: str,quantity: int,+ *,+ include_shipping_zones: bool,checkout_lines: list["CheckoutLine"] | None = None,check_reservations: bool = False,order_line: Optional["OrderLine"] = None,database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,):- """Validate if there is stock available for given variant in given country.+ """Validate if there is stock available for given variant in given channel.If so - returns None. If there is less stock then required raise InsufficientStockexception."""if variant.track_inventory:- stocks = Stock.objects.using(- database_connection_name- ).get_variant_stocks_for_country(country_code, channel_slug, variant)+ stocks = Stock.objects.using(database_connection_name).get_variant_stocks(+ channel_slug,+ variant,+ country_code=country_code,+ include_shipping_zones=include_shipping_zones,+ )if not stocks:raise InsufficientStock([@@ -144,6 +152,8 @@ def check_stock_and_preorder_quantity_bulk(quantities: Iterable[int],channel_slug: str,global_quantity_limit: int | None,+ *,+ include_shipping_zones: bool,delivery_method_info: Optional["DeliveryMethodBase"] = None,additional_filter_lookup: dict[str, Any] | None = None,existing_lines: list["CheckoutLineInfo"] | None = None,@@ -168,11 +178,12 @@ def check_stock_and_preorder_quantity_bulk(stock_quantities,channel_slug,global_quantity_limit,- delivery_method_info,- additional_filter_lookup,- existing_lines,- replace,- check_reservations,+ include_shipping_zones=include_shipping_zones,+ delivery_method_info=delivery_method_info,+ additional_filter_lookup=additional_filter_lookup,+ existing_lines=existing_lines,+ replace=replace,+ check_reservations=check_reservations,)if preorder_variants:check_preorder_threshold_bulk(@@ -236,6 +247,8 @@ def check_stock_quantity_bulk(quantities: Iterable[int],channel_slug: str,global_quantity_limit: int | None,+ *,+ include_shipping_zones: bool,delivery_method_info: Optional["DeliveryMethodBase"] = None,additional_filter_lookup: dict[str, Any] | None = None,existing_lines: list["CheckoutLineInfo"] | None = None,@@ -251,26 +264,35 @@ def check_stock_quantity_bulk(if additional_filter_lookup is not None:filter_lookup.update(additional_filter_lookup)- # in case when the delivery method is not set yet, we should check the stock- # quantity in standard warehouses available in a given channel and country, and- # in the collection point warehouses for the channel- include_cc_warehouses = (- not delivery_method_info.delivery_method if delivery_method_info else True- )- # in case of click and collect order, we need to check local or global stock- # regardless of the country code- collection_point = (- delivery_method_info.warehouse_pk if delivery_method_info else None- )- stocks = (- Stock.objects.using(database_connection_name).for_channel_and_click_and_collect(- channel_slug+ if include_shipping_zones:+ # in case when the delivery method is not set yet, we should check the stock+ # quantity in standard warehouses available in a given channel and country, and+ # in the collection point warehouses for the channel+ include_cc_warehouses = (+ not delivery_method_info.delivery_method if delivery_method_info else True)- if collection_point- else Stock.objects.using(database_connection_name).for_channel_and_country(- channel_slug, country_code, include_cc_warehouses+ # in case of click and collect order, we need to check local or global stock+ # regardless of the country code+ collection_point = (+ delivery_method_info.warehouse_pk if delivery_method_info else None+ )+ stocks = (+ Stock.objects.using(+ database_connection_name+ ).for_channel_and_click_and_collect(channel_slug)+ if collection_point+ else Stock.objects.using(database_connection_name).for_channel_or_country(+ channel_slug,+ country_code,+ include_shipping_zones=True,+ include_cc_warehouses=include_cc_warehouses,+ )+ )+ else:+ stocks = Stock.objects.using(database_connection_name).for_channel_or_country(+ channel_slug,+ include_shipping_zones=include_shipping_zones,)- )all_variants_stocks = stocks.filter(**filter_lookup).annotate_available_quantity()@@ -522,12 +544,17 @@ def get_available_quantity(variant: "ProductVariant",country_code: str,channel_slug: str,+ *,+ include_shipping_zones: bool,checkout_lines: list["CheckoutLine"] | None = None,check_reservations: bool = False,) -> int:- """Return available quantity for given product in given country."""- stocks = Stock.objects.get_variant_stocks_for_country(- country_code, channel_slug, variant+ """Return available quantity for given product in given channel."""+ stocks = Stock.objects.get_variant_stocks(+ channel_slug,+ variant,+ country_code=country_code,+ include_shipping_zones=include_shipping_zones,)if not stocks:return 0@@ -535,11 +562,17 @@ def get_available_quantity(def is_product_in_stock(- product: "Product", country_code: str, channel_slug: str+ product: "Product",+ country_code: str,+ channel_slug: str,+ include_shipping_zones: bool,) -> bool:- """Check if there is any variant of given product available in given country."""- stocks = Stock.objects.get_product_stocks_for_country_and_channel(- country_code, channel_slug, product+ """Check if there is any variant of given product available in given channel."""+ stocks = Stock.objects.get_product_stocks(+ channel_slug,+ product,+ country_code=country_code,+ include_shipping_zones=include_shipping_zones,).annotate_available_quantity()return any(stocks.values_list("available_quantity", flat=True))diff --git a/saleor/warehouse/management.py b/saleor/warehouse/management.pyindex b5febccb79..031babc541 100644--- a/saleor/warehouse/management.py+++ b/saleor/warehouse/management.py@@ -83,6 +83,8 @@ def allocate_stocks(country_code: str,channel: "Channel",manager: PluginsManager,+ *,+ include_shipping_zones: bool,collection_point_pk: UUID | None = None,additional_filter_lookup: dict[str, Any] | None = None,check_reservations: bool = False,@@ -113,11 +115,14 @@ def allocate_stocks(# in case of click and collect order, we need to check local or global stock# regardless of the country code- stocks = (- Stock.objects.for_channel_and_click_and_collect(channel_slug)- if collection_point_pk- else Stock.objects.for_channel_and_country(channel_slug, country_code)- )+ if collection_point_pk:+ stocks = Stock.objects.for_channel_and_click_and_collect(channel_slug)+ else:+ stocks = Stock.objects.for_channel_or_country(+ channel_slug,+ country_code,+ include_shipping_zones=include_shipping_zones,+ )stocks = list(stock_select_for_update_for_existing_qs(stocks)@@ -458,7 +463,10 @@ def _reduce_quantity_allocated_for_stocks(@traced_atomic_transaction()def increase_allocations(- lines_info: list["OrderLineInfo"], channel: "Channel", manager: PluginsManager+ lines_info: list["OrderLineInfo"],+ channel: "Channel",+ manager: PluginsManager,+ include_shipping_zones: bool,):"""Increase allocation for order lines with appropriate quantity."""line_pks = [info.line.pk for info in lines_info]@@ -496,6 +504,7 @@ def increase_allocations(country_code,channel,manager,+ include_shipping_zones=include_shipping_zones,)diff --git a/saleor/warehouse/models.py b/saleor/warehouse/models.pyindex 570cf51758..5adb20cf15 100644--- a/saleor/warehouse/models.py+++ b/saleor/warehouse/models.py@@ -437,35 +437,86 @@ class StockQuerySet(models.QuerySet["Stock"]):| Exists(cc_warehouses.filter(id=OuterRef("warehouse_id"))))- def get_variant_stocks_for_country(- self, country_code: str, channel_slug: str, product_variant: ProductVariant- ):- """Return the stock information about the a stock for a given country.+ def for_channel(self, channel_slug: str):+ """Return stocks for all warehouses assigned to the given channel."""+ WarehouseChannel = Channel.warehouses.through- Note it will raise a 'Stock.DoesNotExist' exception if no such stock is found.- """- return self.for_channel_and_country(channel_slug, country_code).filter(- product_variant=product_variant+ channels = Channel.objects.filter(slug=channel_slug).values("pk")++ warehouse_channels = WarehouseChannel.objects.filter(+ Exists(channels.filter(pk=OuterRef("channel_id")))+ ).values("warehouse_id")++ return self.select_related("product_variant").filter(+ Exists(warehouse_channels.filter(warehouse_id=OuterRef("warehouse_id"))))- def get_variants_stocks_for_country(+ def for_channel_or_country(self,- country_code: str,channel_slug: str,- products_variants: Iterable[ProductVariant],+ country_code: str | None = None,+ *,+ include_shipping_zones: bool,+ include_cc_warehouses: bool = False,):- """Return the stock information about the a stock for a given country.+ """Get stocks based on the include_shipping_zones flag.- Note it will raise a 'Stock.DoesNotExist' exception if no such stock is found.+ When include_shipping_zones is True, filters through shipping zones+ and country (legacy behavior). When False, returns all stocks from+ warehouses linked to the channel."""- return self.for_channel_and_country(channel_slug, country_code).filter(+ if include_shipping_zones:+ return self.for_channel_and_country(+ channel_slug, country_code, include_cc_warehouses+ )+ return self.for_channel(channel_slug)++ def get_variant_stocks(+ self,+ channel_slug: str,+ product_variant: ProductVariant,+ country_code: str | None = None,+ *,+ include_shipping_zones: bool,+ ):+ """Return stock information for a variant, respecting the shipping zone flag."""+ if include_shipping_zones:+ return self.for_channel_and_country(channel_slug, country_code).filter(+ product_variant=product_variant+ )+ return self.for_channel(channel_slug).filter(product_variant=product_variant)++ def get_variants_stocks(+ self,+ channel_slug: str,+ products_variants: Iterable[ProductVariant],+ country_code: str | None = None,+ *,+ include_shipping_zones: bool,+ ):+ """Return stock information for multiple variants, respecting the flag."""+ if include_shipping_zones:+ return self.for_channel_and_country(channel_slug, country_code).filter(+ product_variant__in=products_variants+ )+ return self.for_channel(channel_slug).filter(product_variant__in=products_variants)- def get_product_stocks_for_country_and_channel(- self, country_code: str, channel_slug: str, product: Product+ def get_product_stocks(+ self,+ channel_slug: str,+ product: Product,+ country_code: str | None = None,+ *,+ include_shipping_zones: bool,):- return self.for_channel_and_country(channel_slug, country_code).filter(+ """Return stock information for all variants of a product."""+ if include_shipping_zones:+ return self.for_channel_and_country(channel_slug, country_code).filter(+ product_variant__product_id=product.pk+ )+ return self.for_channel(channel_slug).filter(product_variant__product_id=product.pk)diff --git a/saleor/warehouse/reservations.py b/saleor/warehouse/reservations.pyindex a204d52898..8c83134820 100644--- a/saleor/warehouse/reservations.py+++ b/saleor/warehouse/reservations.py@@ -34,6 +34,7 @@ def reserve_stocks_and_preorders(channel: "Channel",length_in_minutes: int,*,+ include_shipping_zones: bool,replace: bool = True,):stock_variants, stock_lines = [], []@@ -61,6 +62,7 @@ def reserve_stocks_and_preorders(channel,reserved_until,replace=replace,+ include_shipping_zones=include_shipping_zones,)# Refresh reserved_until for already existing lines@@ -94,6 +96,7 @@ def reserve_stocks(reserved_until: datetime.datetime,*,replace: bool = True,+ include_shipping_zones: bool,):"""Reserve stocks for given `checkout_lines` in given country."""variants_ids = [line.variant_id for line in checkout_lines]@@ -108,7 +111,12 @@ def reserve_stocks(stocks = list(stock_qs_select_for_update()- .get_variants_stocks_for_country(country_code, channel.slug, variants)+ .get_variants_stocks(+ channel.slug,+ variants,+ country_code=country_code,+ include_shipping_zones=include_shipping_zones,+ ).order_by("pk").values("id", "product_variant", "pk", "quantity", "warehouse_id"))diff --git a/saleor/warehouse/tests/test_preorder_availability.py b/saleor/warehouse/tests/test_preorder_availability.pyindex d11906d215..73fca7afe5 100644--- a/saleor/warehouse/tests/test_preorder_availability.py+++ b/saleor/warehouse/tests/test_preorder_availability.py@@ -26,11 +26,17 @@ def test_check_stock_and_preorder_quantity(preorder_variant_channel_threshold,channel_USD,):- check_stock_and_preorder_quantity(variant, "US", channel_USD.slug, 1)+ check_stock_and_preorder_quantity(+ variant, "US", channel_USD.slug, 1, include_shipping_zones=True+ )mock_check_stock_quantity.assert_called_once()check_stock_and_preorder_quantity(- preorder_variant_channel_threshold, "US", channel_USD.slug, 1+ preorder_variant_channel_threshold,+ "US",+ channel_USD.slug,+ 1,+ include_shipping_zones=True,)mock_check_preorder_threshold.assert_called_once()assert (@@ -68,6 +74,7 @@ def test_check_stock_and_preorder_quantity_bulk([stock_variant_quantity, preorder_quantity, stock_variant_quantity],channel_USD.slug,global_quantity_limit=global_quantity_limit,+ include_shipping_zones=True,)mock_check_stock_quantity_bulk.assert_called_once()diff --git a/saleor/warehouse/tests/test_stock.py b/saleor/warehouse/tests/test_stock.pyindex c1007e0751..14ef2568c7 100644--- a/saleor/warehouse/tests/test_stock.py+++ b/saleor/warehouse/tests/test_stock.py@@ -1,15 +1,57 @@+import pytest+from ..models import StockCOUNTRY_CODE = "US"+def variant_with_stocks_in_two_channels(+ variant, warehouses, shipping_zone, channel_USD, channel_PLN+):+ """Variant with stocks in warehouses across two channels.++ - warehouse_usd (warehouses[0]): linked to channel_USD and shipping_zone,+ has stock qty=10+ - warehouse_pln (warehouses[1]): linked to channel_PLN, no shipping zone,+ has stock qty=5+ """+ warehouse_usd = warehouses[0]+ warehouse_pln = warehouses[1]++ warehouse_usd.channels.set([channel_USD])+ warehouse_usd.shipping_zones.set([shipping_zone])++ warehouse_pln.channels.set([channel_PLN])+ warehouse_pln.shipping_zones.clear()++ Stock.objects.bulk_create(+ [+ Stock(+ warehouse=warehouse_usd,+ product_variant=variant,+ quantity=10,+ ),+ Stock(+ warehouse=warehouse_pln,+ product_variant=variant,+ quantity=5,+ ),+ ]+ )+ return variant++def test_stocks_for_country(variant_with_many_stocks, channel_USD):+ # when[stock1, stock2] = (Stock.objects.filter(product_variant=variant_with_many_stocks).for_channel_and_country(channel_USD.slug, COUNTRY_CODE).order_by("pk").all())++ # thenwarehouse1 = stock1.warehousewarehouse2 = stock2.warehouseassert stock1.quantity == 4@@ -19,22 +61,28 @@ def test_stocks_for_country(variant_with_many_stocks, channel_USD):def test_stock_for_country_does_not_exists(product, warehouse, channel_PLN):+ # givenshipping_zone = warehouse.shipping_zones.first()shipping_zone.countries = [COUNTRY_CODE]shipping_zone.save(update_fields=["countries"])warehouse.refresh_from_db()fake_country_code = "PL"assert fake_country_code not in warehouse.countries++ # whenstock_qs = Stock.objects.for_channel_and_country(channel_PLN.slug,fake_country_code,)++ # thenassert not stock_qs.exists()def test_stocks_for_country_warehouse_with_given_channel_do_not_exist(variant_with_many_stocks, channel_PLN):+ # whenstock_qs = (Stock.objects.filter(product_variant=variant_with_many_stocks).for_channel_and_country(channel_PLN.slug, COUNTRY_CODE)@@ -42,4 +90,230 @@ def test_stocks_for_country_warehouse_with_given_channel_do_not_exist(.all())+ # thenassert not stock_qs.exists()+++def test_for_channel_returns_stocks_from_channel_warehouses(+ variant_with_stocks_in_two_channels, channel_USD+):+ # given+ variant = variant_with_stocks_in_two_channels++ # when+ result = list(+ Stock.objects.filter(product_variant=variant)+ .for_channel(channel_USD.slug)+ .all()+ )++ # then+ assert len(result) == 1+ assert result[0].quantity == 10+++def test_for_channel_excludes_stocks_from_other_channel(+ variant_with_stocks_in_two_channels, channel_PLN+):+ # given+ variant = variant_with_stocks_in_two_channels++ # when+ result = list(+ Stock.objects.filter(product_variant=variant)+ .for_channel(channel_PLN.slug)+ .all()+ )++ # then+ assert len(result) == 1+ assert result[0].quantity == 5+++def test_for_channel_not_available(variant_with_stocks_in_two_channels, channel_JPY):+ # given+ variant = variant_with_stocks_in_two_channels++ # when+ result = list(+ Stock.objects.filter(product_variant=variant)+ .for_channel(channel_JPY.slug)+ .all()+ )++ # then+ assert not result+++# Tests for get_variant_stocks+++def test_get_variant_stocks_with_shipping_zones(+ variant_with_stocks_in_two_channels, channel_USD+):+ # given+ variant = variant_with_stocks_in_two_channels++ # when+ result = list(+ Stock.objects.get_variant_stocks(+ channel_USD.slug,+ variant,+ country_code=COUNTRY_CODE,+ include_shipping_zones=True,+ )+ )++ # then+ assert len(result) == 1+ assert result[0].quantity == 10+ assert result[0].product_variant == variant+++def test_get_variant_stocks_with_shipping_zones_no_zone_match(+ variant_with_stocks_in_two_channels, channel_USD, shipping_zone+):+ # given - restrict shipping zone to only one country, then query another+ variant = variant_with_stocks_in_two_channels+ shipping_zone.countries = ["PL"]+ shipping_zone.save(update_fields=["countries"])+ non_matching_country = "DE"++ # when+ result = list(+ Stock.objects.get_variant_stocks(+ channel_USD.slug,+ variant,+ country_code=non_matching_country,+ include_shipping_zones=True,+ )+ )++ # then - shipping zone only covers PL, so DE returns no stocks+ assert len(result) == 0+++def test_get_variant_stocks_without_shipping_zones(+ variant_with_stocks_in_two_channels, channel_USD+):+ # given - clear shipping zones to prove they don't matter+ variant = variant_with_stocks_in_two_channels+ for warehouse in variant.stocks.all():+ warehouse = warehouse.warehouse+ warehouse.shipping_zones.clear()++ # when+ result = list(+ Stock.objects.get_variant_stocks(+ channel_USD.slug, variant, include_shipping_zones=False+ )+ )++ # then - still returned because only channel link matters+ assert len(result) == 1+ assert result[0].quantity == 10+ assert result[0].product_variant == variant+++# Tests for get_variants_stocks+++def test_get_variants_stocks_with_shipping_zones(+ variant_with_stocks_in_two_channels, channel_USD+):+ # given+ variant = variant_with_stocks_in_two_channels++ # when+ result = list(+ Stock.objects.get_variants_stocks(+ channel_USD.slug,+ [variant],+ country_code=COUNTRY_CODE,+ include_shipping_zones=True,+ )+ )++ # then+ assert len(result) == 1+ assert result[0].product_variant == variant+ assert result[0].quantity == 10+++def test_get_variants_stocks_without_shipping_zones(+ variant_with_stocks_in_two_channels, channel_USD+):+ # given - clear shipping zones to prove they don't matter+ variant = variant_with_stocks_in_two_channels+ for stock in variant.stocks.all():+ stock.warehouse.shipping_zones.clear()++ # when+ result = list(+ Stock.objects.get_variants_stocks(+ channel_USD.slug, [variant], include_shipping_zones=False+ )+ )++ # then - still returned because only channel link matters+ assert len(result) == 1+ assert result[0].product_variant == variant+ assert result[0].quantity == 10+++# Tests for get_product_stocks+++def test_get_product_stocks_with_shipping_zones(+ variant_with_stocks_in_two_channels, channel_USD+):+ # given+ variant = variant_with_stocks_in_two_channels+ product = variant.product++ expected_count = Stock.objects.filter(+ product_variant__product=product,+ warehouse__channels=channel_USD,+ ).count()++ # when+ result = list(+ Stock.objects.get_product_stocks(+ channel_USD.slug,+ product,+ country_code=COUNTRY_CODE,+ include_shipping_zones=True,+ )+ )++ # then+ assert len(result) == expected_count+ for stock in result:+ assert stock.product_variant.product_id == product.pk+++def test_get_product_stocks_without_shipping_zones(+ variant_with_stocks_in_two_channels, channel_USD+):+ # given - clear shipping zones to prove they don't matter+ variant = variant_with_stocks_in_two_channels+ product = variant.product+ for stock in variant.stocks.all():+ stock.warehouse.shipping_zones.clear()++ expected_count = Stock.objects.filter(+ product_variant__product=product,+ warehouse__channels=channel_USD,+ ).count()++ # when+ result = list(+ Stock.objects.get_product_stocks(+ channel_USD.slug, product, include_shipping_zones=False+ )+ )++ # then - still returned because only channel link matters+ assert len(result) == expected_count+ for stock in result:+ assert stock.product_variant.product_id == product.pkdiff --git a/saleor/warehouse/tests/test_stock_availability.py b/saleor/warehouse/tests/test_stock_availability.pyindex 0279bf7616..11f715a0d0 100644--- a/saleor/warehouse/tests/test_stock_availability.py+++ b/saleor/warehouse/tests/test_stock_availability.py@@ -4,9 +4,11 @@ from ...checkout.fetch import fetch_checkout_linesfrom ...core.exceptions import InsufficientStockfrom ..availability import (_get_available_quantity,+ check_stock_and_preorder_quantity,check_stock_quantity,check_stock_quantity_bulk,get_available_quantity,+ is_product_in_stock,)from ..models import Allocation@@ -16,7 +18,11 @@ COUNTRY_CODE = "US"def test_check_stock_quantity(variant_with_many_stocks, channel_USD):assert (check_stock_quantity(- variant_with_many_stocks, COUNTRY_CODE, channel_USD.slug, 7+ variant_with_many_stocks,+ COUNTRY_CODE,+ channel_USD.slug,+ 7,+ include_shipping_zones=True,)is None)@@ -25,7 +31,11 @@ def test_check_stock_quantity(variant_with_many_stocks, channel_USD):def test_check_stock_quantity_out_of_stock(variant_with_many_stocks, channel_USD):with pytest.raises(InsufficientStock):check_stock_quantity(- variant_with_many_stocks, COUNTRY_CODE, channel_USD.slug, 8+ variant_with_many_stocks,+ COUNTRY_CODE,+ channel_USD.slug,+ 8,+ include_shipping_zones=True,)@@ -37,7 +47,11 @@ def test_check_stock_quantity_with_allocations():assert (check_stock_quantity(- variant_with_many_stocks, COUNTRY_CODE, channel_USD.slug, 3+ variant_with_many_stocks,+ COUNTRY_CODE,+ channel_USD.slug,+ 3,+ include_shipping_zones=True,)is None)@@ -48,7 +62,11 @@ def test_check_stock_quantity_with_allocations_out_of_stock():with pytest.raises(InsufficientStock):check_stock_quantity(- variant_with_many_stocks, COUNTRY_CODE, channel_USD.slug, 5+ variant_with_many_stocks,+ COUNTRY_CODE,+ channel_USD.slug,+ 5,+ include_shipping_zones=True,)@@ -64,6 +82,7 @@ def test_check_stock_quantity_with_reservations(COUNTRY_CODE,channel_USD.slug,2,+ include_shipping_zones=True,check_reservations=True,)is None@@ -82,10 +101,11 @@ def test_check_stock_quantity_with_reservations_excluding_given_checkout_lines(COUNTRY_CODE,channel_USD.slug,7,- [+ checkout_lines=[checkout_line_with_reservation_in_many_stocks,checkout_line_with_one_reservation,],+ include_shipping_zones=True,check_reservations=True,)is None@@ -96,7 +116,11 @@ def test_check_stock_quantity_without_stocks(variant_with_many_stocks, channel_Uvariant_with_many_stocks.stocks.all().delete()with pytest.raises(InsufficientStock):check_stock_quantity(- variant_with_many_stocks, COUNTRY_CODE, channel_USD.slug, 1+ variant_with_many_stocks,+ COUNTRY_CODE,+ channel_USD.slug,+ 1,+ include_shipping_zones=True,)@@ -104,7 +128,11 @@ def test_check_stock_quantity_without_one_stock(variant_with_many_stocks, channevariant_with_many_stocks.stocks.get(quantity=3).delete()assert (check_stock_quantity(- variant_with_many_stocks, COUNTRY_CODE, channel_USD.slug, 4+ variant_with_many_stocks,+ COUNTRY_CODE,+ channel_USD.slug,+ 4,+ include_shipping_zones=True,)is None)@@ -112,7 +140,10 @@ def test_check_stock_quantity_without_one_stock(variant_with_many_stocks, channedef test_get_available_quantity(variant_with_many_stocks, channel_USD):available_quantity = get_available_quantity(- variant_with_many_stocks, COUNTRY_CODE, channel_USD.slug+ variant_with_many_stocks,+ COUNTRY_CODE,+ channel_USD.slug,+ include_shipping_zones=True,)assert available_quantity == 7@@ -120,7 +151,10 @@ def test_get_available_quantity(variant_with_many_stocks, channel_USD):def test_get_available_quantity_without_allocation(order_line, stock, channel_USD):assert not Allocation.objects.filter(order_line=order_line, stock=stock).exists()available_quantity = get_available_quantity(- order_line.variant, COUNTRY_CODE, channel_USD.slug+ order_line.variant,+ COUNTRY_CODE,+ channel_USD.slug,+ include_shipping_zones=True,)assert available_quantity == stock.quantity@@ -132,7 +166,10 @@ def test_get_available_quantity_with_allocations(channel_USD,):available_quantity = get_available_quantity(- variant_with_many_stocks, COUNTRY_CODE, channel_USD.slug+ variant_with_many_stocks,+ COUNTRY_CODE,+ channel_USD.slug,+ include_shipping_zones=True,)assert available_quantity == 3@@ -147,6 +184,7 @@ def test_get_available_quantity_with_reservations(variant_with_many_stocks,COUNTRY_CODE,channel_USD.slug,+ include_shipping_zones=True,check_reservations=True,)assert available_quantity == 2@@ -162,6 +200,7 @@ def test_get_available_quantity_with_allocations_and_reservations(variant_with_many_stocks,COUNTRY_CODE,channel_USD.slug,+ include_shipping_zones=True,check_reservations=True,)assert available_quantity == 4@@ -177,10 +216,11 @@ def test_get_available_quantity_with_reservations_excluding_given_checkout_linesvariant_with_many_stocks,COUNTRY_CODE,channel_USD.slug,- [+ checkout_lines=[checkout_line_with_reservation_in_many_stocks,checkout_line_with_one_reservation,],+ include_shipping_zones=True,check_reservations=True,)assert available_quantity == 7@@ -189,7 +229,10 @@ def test_get_available_quantity_with_reservations_excluding_given_checkout_linesdef test_get_available_quantity_without_stocks(variant_with_many_stocks, channel_USD):variant_with_many_stocks.stocks.all().delete()available_quantity = get_available_quantity(- variant_with_many_stocks, COUNTRY_CODE, channel_USD.slug+ variant_with_many_stocks,+ COUNTRY_CODE,+ channel_USD.slug,+ include_shipping_zones=True,)assert available_quantity == 0@@ -208,6 +251,7 @@ def test_check_stock_quantity_bulk(variant_with_many_stocks, channel_USD):[available_quantity],channel_USD.slug,global_quantity_limit,+ include_shipping_zones=True,)is None)@@ -220,6 +264,7 @@ def test_check_stock_quantity_bulk(variant_with_many_stocks, channel_USD):[available_quantity + 1],channel_USD,global_quantity_limit,+ include_shipping_zones=True,)# test that it raises an error if no stocks are found@@ -231,6 +276,7 @@ def test_check_stock_quantity_bulk(variant_with_many_stocks, channel_USD):[available_quantity],channel_USD.slug,global_quantity_limit,+ include_shipping_zones=True,)# test that it doesn't raise an error if variant.track_inventory is False@@ -242,12 +288,14 @@ def test_check_stock_quantity_bulk(variant_with_many_stocks, channel_USD):[available_quantity],channel_USD.slug,global_quantity_limit,+ include_shipping_zones=True,)def test_check_stock_quantity_bulk_no_channel_shipping_zones(variant_with_many_stocks, channel_USD):+ # givenvariant = variant_with_many_stockscountry_code = "US"available_quantity = _get_available_quantity(variant.stocks.all())@@ -255,6 +303,7 @@ def test_check_stock_quantity_bulk_no_channel_shipping_zones(channel_USD.shipping_zones.clear()+ # when / then - with legacy flag, clearing shipping zones makes stock unavailablewith pytest.raises(InsufficientStock):check_stock_quantity_bulk([variant_with_many_stocks],@@ -262,9 +311,35 @@ def test_check_stock_quantity_bulk_no_channel_shipping_zones([available_quantity],channel_USD.slug,global_quantity_limit,+ include_shipping_zones=True,)+def test_check_stock_quantity_bulk_no_channel_shipping_zones_excluded_from_stock_calculations(+ variant_with_many_stocks, channel_USD+):+ # given+ variant = variant_with_many_stocks+ country_code = "US"+ available_quantity = _get_available_quantity(variant.stocks.all())+ global_quantity_limit = 50++ channel_USD.shipping_zones.clear()++ # when / then - with flag disabled, shipping zones don't affect availability+ assert (+ check_stock_quantity_bulk(+ [variant_with_many_stocks],+ country_code,+ [available_quantity],+ channel_USD.slug,+ global_quantity_limit,+ include_shipping_zones=False,+ )+ is None+ )++def test_check_stock_quantity_bulk_with_reservations(variant_with_many_stocks,checkout_line_with_reservation_in_many_stocks,@@ -277,6 +352,7 @@ def test_check_stock_quantity_bulk_with_reservations(variant,country_code,channel_USD.slug,+ include_shipping_zones=True,check_reservations=True,)global_quantity_limit = 50@@ -289,6 +365,7 @@ def test_check_stock_quantity_bulk_with_reservations([available_quantity],channel_USD.slug,global_quantity_limit,+ include_shipping_zones=True,check_reservations=True,)is None@@ -302,6 +379,7 @@ def test_check_stock_quantity_bulk_with_reservations([available_quantity + 1],channel_USD.slug,global_quantity_limit,+ include_shipping_zones=True,check_reservations=True,)@@ -316,8 +394,205 @@ def test_check_stock_quantity_bulk_with_reservations([available_quantity + 1],channel_USD.slug,global_quantity_limit,+ include_shipping_zones=True,existing_lines=checkout_lines,check_reservations=True,)is None)+++def test_check_stock_quantity_no_shipping_zones_included(+ variant_with_many_stocks, channel_USD+):+ # given+ include_shipping_zones = True+ channel_USD.shipping_zones.clear()++ # when / then - legacy behavior: no shipping zones means no stock+ with pytest.raises(InsufficientStock):+ check_stock_quantity(+ variant_with_many_stocks,+ COUNTRY_CODE,+ channel_USD.slug,+ 1,+ include_shipping_zones=include_shipping_zones,+ )+++def test_check_stock_quantity_no_shipping_zones_excluded_from_stock_calculations(+ variant_with_many_stocks, channel_USD+):+ # given+ include_shipping_zones = False+ channel_USD.shipping_zones.clear()++ # when / then - flag disabled: shipping zones ignored, stock found+ assert (+ check_stock_quantity(+ variant_with_many_stocks,+ COUNTRY_CODE,+ channel_USD.slug,+ 7,+ include_shipping_zones=include_shipping_zones,+ )+ is None+ )+++def test_get_available_quantity_no_shipping_zones_included(+ variant_with_many_stocks, channel_USD+):+ # given+ include_shipping_zones = True+ channel_USD.shipping_zones.clear()++ # when+ available_quantity = get_available_quantity(+ variant_with_many_stocks,+ COUNTRY_CODE,+ channel_USD.slug,+ include_shipping_zones=include_shipping_zones,+ )++ # then - legacy behavior: no shipping zones means no stock+ assert available_quantity == 0+++def test_get_available_quantity_no_shipping_zones_excluded_from_stock_calculations(+ variant_with_many_stocks, channel_USD+):+ # given+ include_shipping_zones = False+ channel_USD.shipping_zones.clear()++ # when+ available_quantity = get_available_quantity(+ variant_with_many_stocks,+ COUNTRY_CODE,+ channel_USD.slug,+ include_shipping_zones=include_shipping_zones,+ )++ # then - flag disabled: shipping zones ignored, stock found+ assert available_quantity == 7+++def test_check_stock_quantity_country_not_in_zone_include_shipping_zones(+ variant_with_many_stocks, channel_USD, shipping_zone+):+ # given - restrict shipping zone to PL only+ include_shipping_zones = True+ shipping_zone.countries = ["PL"]+ shipping_zone.save(update_fields=["countries"])+ non_matching_country = "DE"++ # when / then - legacy behavior: country not in zone means no stock+ with pytest.raises(InsufficientStock):+ check_stock_quantity(+ variant_with_many_stocks,+ non_matching_country,+ channel_USD.slug,+ 1,+ include_shipping_zones=include_shipping_zones,+ )+++def test_check_stock_quantity_country_not_in_zone_shipping_zones_excluded_from_stock_calculations(+ variant_with_many_stocks, channel_USD, shipping_zone+):+ # given - restrict shipping zone to PL only+ include_shipping_zones = False+ shipping_zone.countries = ["PL"]+ shipping_zone.save(update_fields=["countries"])+ non_matching_country = "DE"++ # when / then - flag disabled: country/zone ignored, stock found+ assert (+ check_stock_quantity(+ variant_with_many_stocks,+ non_matching_country,+ channel_USD.slug,+ 7,+ include_shipping_zones=include_shipping_zones,+ )+ is None+ )+++def test_check_stock_and_preorder_quantity_no_shipping_zones_included(+ variant_with_many_stocks, channel_USD+):+ # given+ include_shipping_zones = True+ channel_USD.shipping_zones.clear()++ # when / then - legacy: no shipping zones means no stock+ with pytest.raises(InsufficientStock):+ check_stock_and_preorder_quantity(+ variant_with_many_stocks,+ COUNTRY_CODE,+ channel_USD.slug,+ 1,+ include_shipping_zones=include_shipping_zones,+ )+++def test_check_stock_and_preorder_quantity_no_shipping_zones_excluded_from_stock_calculations(+ variant_with_many_stocks, channel_USD+):+ # given+ include_shipping_zones = False+ channel_USD.shipping_zones.clear()++ # when / then - flag disabled: shipping zones ignored, stock found+ assert (+ check_stock_and_preorder_quantity(+ variant_with_many_stocks,+ COUNTRY_CODE,+ channel_USD.slug,+ 7,+ include_shipping_zones=include_shipping_zones,+ )+ is None+ )+++def test_is_product_in_stock_no_shipping_zones_included(+ variant_with_many_stocks, channel_USD+):+ # given+ include_shipping_zones = True+ channel_USD.shipping_zones.clear()+ product = variant_with_many_stocks.product++ # when+ result = is_product_in_stock(+ product,+ COUNTRY_CODE,+ channel_USD.slug,+ include_shipping_zones=include_shipping_zones,+ )++ # then - legacy: no shipping zones means not in stock+ assert result is False+++def test_is_product_in_stock_no_shipping_zones_excluded_from_stock_calculations(+ variant_with_many_stocks, channel_USD+):+ # given+ include_shipping_zones = False+ channel_USD.shipping_zones.clear()+ product = variant_with_many_stocks.product++ # when+ result = is_product_in_stock(+ product,+ COUNTRY_CODE,+ channel_USD.slug,+ include_shipping_zones=include_shipping_zones,+ )++ # then - flag disabled: shipping zones ignored, product in stock+ assert result is Truediff --git a/saleor/warehouse/tests/test_stock_management.py b/saleor/warehouse/tests/test_stock_management.pyindex 8c24293bed..7fb231871c 100644--- a/saleor/warehouse/tests/test_stock_management.py+++ b/saleor/warehouse/tests/test_stock_management.py@@ -36,6 +36,7 @@ def test_allocate_stocks(order_line, stock, channel_USD):COUNTRY_CODE,channel_USD,manager=get_plugins_manager(allow_replica=False),+ include_shipping_zones=True,)stock.refresh_from_db()@@ -76,6 +77,7 @@ def test_allocate_stocks_multiple_lines_the_highest_stock_strategy(COUNTRY_CODE,channel_USD,manager=get_plugins_manager(allow_replica=False),+ include_shipping_zones=True,)stock.refresh_from_db()@@ -100,6 +102,7 @@ def test_allocate_stock_many_stocks_the_highest_stock_strategy(COUNTRY_CODE,channel_USD,manager=get_plugins_manager(allow_replica=False),+ include_shipping_zones=True,)allocations = Allocation.objects.filter(order_line=order_line, stock__in=stocks)@@ -132,6 +135,7 @@ def test_allocate_stocks_the_highest_stock_strategy_with_collection_point(COUNTRY_CODE,channel_USD,manager=get_plugins_manager(allow_replica=False),+ include_shipping_zones=True,collection_point_pk=warehouse_for_cc.pk,)@@ -172,6 +176,7 @@ def test_allocate_stock_many_stocks_prioritize_sorting_order_strategy(COUNTRY_CODE,channel_USD,manager=get_plugins_manager(allow_replica=False),+ include_shipping_zones=True,)# then@@ -233,6 +238,7 @@ def test_allocate_stock_prioritize_sorting_order_strategy_with_collection_point(COUNTRY_CODE,channel_USD,manager=get_plugins_manager(allow_replica=False),+ include_shipping_zones=True,collection_point_pk=warehouse_for_cc.pk,)@@ -258,6 +264,7 @@ def test_allocate_stock_with_reservations_the_highest_stock_strategy(COUNTRY_CODE,channel_USD,manager=get_plugins_manager(allow_replica=False),+ include_shipping_zones=True,check_reservations=True,)@@ -304,6 +311,7 @@ def test_allocate_stock_with_reservations_prioritize_sorting_order_strategy(COUNTRY_CODE,channel_USD,manager=get_plugins_manager(allow_replica=False),+ include_shipping_zones=True,check_reservations=True,)@@ -334,6 +342,7 @@ def test_allocate_stock_insufficient_stock_due_to_reservations(COUNTRY_CODE,channel_USD,manager=get_plugins_manager(allow_replica=False),+ include_shipping_zones=True,check_reservations=True,)@@ -363,6 +372,7 @@ def test_allocate_stock_many_stocks_partially_allocated(COUNTRY_CODE,channel_USD,manager=get_plugins_manager(allow_replica=False),+ include_shipping_zones=True,)# then@@ -392,6 +402,7 @@ def test_allocate_stock_partially_allocated_insufficient_stocks(COUNTRY_CODE,channel_USD,manager=get_plugins_manager(allow_replica=False),+ include_shipping_zones=True,)assert not Allocation.objects.filter(@@ -400,21 +411,46 @@ def test_allocate_stock_partially_allocated_insufficient_stocks(def test_allocate_stocks_no_channel_shipping_zones(order_line, stock, channel_USD):+ # givenchannel_USD.shipping_zones.clear()stock.quantity = 100stock.save(update_fields=["quantity"])line_data = OrderLineInfo(line=order_line, variant=order_line.variant, quantity=50)++ # when / then - with legacy flag, clearing shipping zones makes allocation failwith pytest.raises(InsufficientStock):allocate_stocks([line_data],COUNTRY_CODE,channel_USD,manager=get_plugins_manager(allow_replica=False),+ include_shipping_zones=True,)+def test_allocate_stocks_no_channel_shipping_zones_excluded_from_stock_calculations(+ order_line, stock, channel_USD+):+ # given+ channel_USD.shipping_zones.clear()++ stock.quantity = 100+ stock.save(update_fields=["quantity"])++ line_data = OrderLineInfo(line=order_line, variant=order_line.variant, quantity=50)++ # when / then - with flag disabled, shipping zones don't affect allocation+ allocate_stocks(+ [line_data],+ COUNTRY_CODE,+ channel_USD,+ manager=get_plugins_manager(allow_replica=False),+ include_shipping_zones=False,+ )++def test_allocate_stock_insufficient_stocks(order_line, variant_with_many_stocks, channel_USD):@@ -428,6 +464,7 @@ def test_allocate_stock_insufficient_stocks(COUNTRY_CODE,channel_USD,manager=get_plugins_manager(allow_replica=False),+ include_shipping_zones=True,)assert not Allocation.objects.filter(@@ -466,6 +503,7 @@ def test_allocate_stock_insufficient_stocks_for_multiple_lines(COUNTRY_CODE,channel_USD,manager=get_plugins_manager(allow_replica=False),+ include_shipping_zones=True,)assert {item.variant for item in exc._excinfo[1].items} == {variant, variant_2}@@ -644,6 +682,7 @@ def test_increase_allocations(quantity, allocation):[order_line_info],order_line.order.channel,manager=get_plugins_manager(allow_replica=False),+ include_shipping_zones=True,)stock.refresh_from_db()@@ -708,6 +747,7 @@ def test_increase_allocations_with_multiple_allocations_for_the_same_stock([first_order_line_info, second_order_line_info],first_order_line.order.channel,manager=get_plugins_manager(allow_replica=False),+ include_shipping_zones=True,)stock.refresh_from_db()@@ -749,6 +789,7 @@ def test_increase_allocation_insufficient_stock(allocation):[order_line_info],order_line.order.channel,manager=get_plugins_manager(allow_replica=False),+ include_shipping_zones=True,)stock.refresh_from_db()diff --git a/saleor/warehouse/tests/test_stock_reservations_management.py b/saleor/warehouse/tests/test_stock_reservations_management.pyindex 2081348db1..5fe3903795 100644--- a/saleor/warehouse/tests/test_stock_reservations_management.py+++ b/saleor/warehouse/tests/test_stock_reservations_management.py@@ -27,6 +27,7 @@ def test_reserve_stocks(checkout_line, channel_USD):COUNTRY_CODE,channel_USD,timezone.now() + datetime.timedelta(minutes=RESERVATION_LENGTH),+ include_shipping_zones=True,)stock.refresh_from_db()@@ -47,6 +48,7 @@ def test_stocks_reservation_skips_prev_reservation_delete_if_replace_is_disabledchannel_USD,timezone.now() + datetime.timedelta(minutes=RESERVATION_LENGTH),replace=False,+ include_shipping_zones=True,)with assert_num_queries(4):@@ -56,6 +58,7 @@ def test_stocks_reservation_skips_prev_reservation_delete_if_replace_is_disabledCOUNTRY_CODE,channel_USD,timezone.now() + datetime.timedelta(minutes=RESERVATION_LENGTH),+ include_shipping_zones=True,)@@ -89,6 +92,7 @@ def test_multiple_stocks_reserved_if_single_stock_is_not_enough_highest_stock_stCOUNTRY_CODE,channel_USD,timezone.now() + datetime.timedelta(minutes=RESERVATION_LENGTH),+ include_shipping_zones=True,)stock.refresh_from_db()@@ -158,6 +162,7 @@ def test_multiple_stocks_reserved_if_single_stock_is_not_enough_sorting_order_stCOUNTRY_CODE,channel_USD,timezone.now() + datetime.timedelta(minutes=RESERVATION_LENGTH),+ include_shipping_zones=True,)# then@@ -200,6 +205,7 @@ def test_stocks_reservation_removes_previous_reservations_for_checkout(COUNTRY_CODE,channel_USD,timezone.now() + datetime.timedelta(minutes=RESERVATION_LENGTH),+ include_shipping_zones=True,)with pytest.raises(Reservation.DoesNotExist):@@ -223,6 +229,7 @@ def test_stock_reservation_fails_if_there_is_not_enough_stock_available(COUNTRY_CODE,channel_USD,timezone.now() + datetime.timedelta(minutes=RESERVATION_LENGTH),+ include_shipping_zones=True,)@@ -239,6 +246,7 @@ def test_stock_reservation_fails_if_there_is_no_stock(checkout_line, channel_USDCOUNTRY_CODE,channel_USD,RESERVATION_LENGTH,+ include_shipping_zones=True,)@@ -263,6 +271,7 @@ def test_stock_reservation_accounts_for_order_allocations(COUNTRY_CODE,channel_USD,timezone.now() + datetime.timedelta(minutes=RESERVATION_LENGTH),+ include_shipping_zones=True,)@@ -305,4 +314,56 @@ def test_stock_reservation_accounts_for_order_allocations_and_reservations(COUNTRY_CODE,channel_USD,timezone.now() + datetime.timedelta(minutes=RESERVATION_LENGTH),+ include_shipping_zones=True,)+++def test_reserve_stocks_no_shipping_zones_included(checkout_line, channel_USD):+ # given+ checkout_line.quantity = 5+ checkout_line.save()++ stock = Stock.objects.get(product_variant=checkout_line.variant)+ stock.quantity = 10+ stock.save(update_fields=["quantity"])++ channel_USD.shipping_zones.clear()++ # when / then - legacy: no shipping zones means no stock to reserve+ with pytest.raises(InsufficientStock):+ reserve_stocks(+ [checkout_line],+ [checkout_line.variant],+ COUNTRY_CODE,+ channel_USD,+ timezone.now() + datetime.timedelta(minutes=RESERVATION_LENGTH),+ include_shipping_zones=True,+ )+++def test_reserve_stocks_no_shipping_zones_excluded_from_stock_calculations(+ checkout_line, channel_USD+):+ # given+ checkout_line.quantity = 5+ checkout_line.save()++ stock = Stock.objects.get(product_variant=checkout_line.variant)+ stock.quantity = 10+ stock.save(update_fields=["quantity"])++ channel_USD.shipping_zones.clear()++ # when - flag disabled: shipping zones ignored+ reserve_stocks(+ [checkout_line],+ [checkout_line.variant],+ COUNTRY_CODE,+ channel_USD,+ timezone.now() + datetime.timedelta(minutes=RESERVATION_LENGTH),+ include_shipping_zones=False,+ )++ # then - reservation created+ reservation = Reservation.objects.get(checkout_line=checkout_line, stock=stock)+ assert reservation.quantity_reserved == 5diff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.pyindex 64d3dee8b6..ee21c73c41 100644--- a/saleor/webhook/payloads.py+++ b/saleor/webhook/payloads.py@@ -7,6 +7,7 @@ from decimal import Decimalfrom typing import TYPE_CHECKING, Any, Optional, Unionimport graphene+from django.contrib.sites.models import Sitefrom django.db.models import F, QuerySet, Sumfrom django.utils import timezonefrom graphene.utils.str_converters import to_camel_case@@ -551,10 +552,16 @@ def generate_checkout_payload(# todo use the most appropriate warehousewarehouse = None- if checkout.shipping_address:- warehouse = Warehouse.objects.for_country_and_channel(- checkout.shipping_address.country.code, checkout.channel_id- ).first()+ include_shipping_zones = (+ Site.objects.get_current().settings.use_legacy_shipping_zone_stock_availability+ )+ if include_shipping_zones:+ if checkout.shipping_address:+ warehouse = Warehouse.objects.for_country_and_channel(+ checkout.shipping_address.country.code, checkout.channel_id+ ).first()+ else:+ warehouse = Warehouse.objects.for_channel(checkout.channel_id).first()shipping_method = Noneif checkout.assigned_delivery and not checkout.assigned_delivery.is_external:@@ -1003,9 +1010,13 @@ def generate_fulfillment_payload(if fulfillment_line and fulfillment_line.stock:warehouse = fulfillment_line.stock.warehouseelse:- warehouse = Warehouse.objects.for_country_and_channel(- order_country, order.channel_id- ).first()+ include_shipping_zones = Site.objects.get_current().settings.use_legacy_shipping_zone_stock_availability+ if include_shipping_zones:+ warehouse = Warehouse.objects.for_country_and_channel(+ order_country, order.channel_id+ ).first()+ else:+ warehouse = Warehouse.objects.for_channel(order.channel_id).first()fulfillment_data = serializer.serialize([fulfillment],fields=fulfillment_fields,diff --git a/saleor/webhook/tests/test_webhook_payloads.py b/saleor/webhook/tests/test_webhook_payloads.pyindex 5ec729beb4..85a9c1ffdb 100644--- a/saleor/webhook/tests/test_webhook_payloads.py+++ b/saleor/webhook/tests/test_webhook_payloads.py@@ -8,6 +8,7 @@ from unittest.mock import ANY, patch, sentinelimport grapheneimport pytest+from django.contrib.sites.models import Sitefrom django.core.serializers.json import DjangoJSONEncoderfrom freezegun import freeze_timefrom prices import Money@@ -2489,3 +2490,35 @@ def test_generate_product_media_payload(product_media_image):# thenassert payload == expected_payload+++def test_generate_checkout_payload_warehouse_without_shipping_zones(+ checkout_with_prices, customer_user, site_settings+):+ # given+ checkout = checkout_with_prices+ checkout.channel.shipping_zones.clear()++ # when+ payload = json.loads(generate_checkout_payload(checkout, customer_user))[0]++ # then - legacy behavior: no shipping zones means no warehouse+ assert payload["warehouse_address"] is None+++def test_generate_checkout_payload_warehouse_without_shipping_zones_excluded_from_stock_calculations(+ checkout_with_prices, customer_user, site_settings+):+ # given+ site_settings.use_legacy_shipping_zone_stock_availability = False+ site_settings.save(update_fields=["use_legacy_shipping_zone_stock_availability"])+ Site.objects.clear_cache()++ checkout = checkout_with_prices+ checkout.channel.shipping_zones.clear()++ # when+ payload = json.loads(generate_checkout_payload(checkout, customer_user))[0]++ # then - flag disabled: warehouse found via channel link despite no shipping zones+ assert payload["warehouse_address"] is not None