Skip to content

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

Legacy shipping zone stock availability improvements (#19065) (#19090)

Iga Karbowiakee2e28dd2114
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index 0f90522cb4..5edfbc5e21 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -845,7 +845,7 @@ def _create_order(
country_code,
checkout_info.channel,
manager,
- include_shipping_zones=site_settings.use_legacy_shipping_zone_stock_availability,
+ calculate_stocks_with_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,
@@ -1274,7 +1274,7 @@ def _handle_allocations_of_order_lines(
order_lines_info: list[OrderLineInfo],
manager: "PluginsManager",
reservation_enabled: bool,
- include_shipping_zones: bool,
+ calculate_stocks_with_shipping_zones: bool,
):
country_code = checkout_info.get_country()
additional_warehouse_lookup = (
@@ -1285,7 +1285,7 @@ def _handle_allocations_of_order_lines(
country_code,
checkout_info.channel,
manager,
- include_shipping_zones=include_shipping_zones,
+ calculate_stocks_with_shipping_zones=calculate_stocks_with_shipping_zones,
collection_point_pk=checkout_info.get_delivery_method_info().warehouse_pk,
additional_filter_lookup=additional_warehouse_lookup,
check_reservations=True,
@@ -1526,7 +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,
+ calculate_stocks_with_shipping_zones=site_settings.use_legacy_shipping_zone_stock_availability,
)
# giftcards
@@ -1972,7 +1972,7 @@ def complete_checkout_with_payment(
def _reserve_stocks_without_availability_check(
checkout_info: CheckoutInfo,
lines: list[CheckoutLineInfo],
- include_shipping_zones: bool,
+ calculate_stocks_with_shipping_zones: bool,
):
"""Add additional temporary reservation for stock.
@@ -1984,7 +1984,7 @@ def _reserve_stocks_without_availability_check(
channel_slug=checkout_info.channel.slug,
products_variants=variants,
country_code=checkout_info.get_country(),
- include_shipping_zones=include_shipping_zones,
+ include_shipping_zones=calculate_stocks_with_shipping_zones,
)
variants_stocks_map = {stock.product_variant_id: stock for stock in stocks}
diff --git a/saleor/checkout/tests/fixtures/checkout.py b/saleor/checkout/tests/fixtures/checkout.py
index d9284f1810..57e36be0d3 100644
--- a/saleor/checkout/tests/fixtures/checkout.py
+++ b/saleor/checkout/tests/fixtures/checkout.py
@@ -8,7 +8,7 @@ from ....plugins.manager import get_plugins_manager
from ....product.models import ProductVariantChannelListing
from ...fetch import fetch_checkout_info, fetch_checkout_lines
from ...models import Checkout, CheckoutDelivery, CheckoutLine, CheckoutMetadata
-from ...utils import add_variant_to_checkout
+from ..utils import add_variant_to_checkout
@pytest.fixture
diff --git a/saleor/checkout/tests/fixtures/checkout_line.py b/saleor/checkout/tests/fixtures/checkout_line.py
index e275b14b90..71a75f9806 100644
--- a/saleor/checkout/tests/fixtures/checkout_line.py
+++ b/saleor/checkout/tests/fixtures/checkout_line.py
@@ -6,7 +6,7 @@ from django.utils import timezone
from ....plugins.manager import get_plugins_manager
from ....warehouse.models import PreorderReservation, Reservation
from ...fetch import fetch_checkout_info
-from ...utils import add_variant_to_checkout
+from ..utils import add_variant_to_checkout
@pytest.fixture
diff --git a/saleor/checkout/tests/fixtures/checkout_with_discount.py b/saleor/checkout/tests/fixtures/checkout_with_discount.py
index 4ff8d10ed7..946c3bf057 100644
--- a/saleor/checkout/tests/fixtures/checkout_with_discount.py
+++ b/saleor/checkout/tests/fixtures/checkout_with_discount.py
@@ -10,7 +10,8 @@ from ....plugins.manager import get_plugins_manager
from ....product.models import ProductVariantChannelListing
from ...fetch import fetch_checkout_info, fetch_checkout_lines
from ...models import CheckoutLine
-from ...utils import add_variant_to_checkout, add_voucher_to_checkout
+from ...utils import add_voucher_to_checkout
+from ..utils import add_variant_to_checkout
@pytest.fixture
diff --git a/saleor/checkout/tests/fixtures/checkout_with_payment.py b/saleor/checkout/tests/fixtures/checkout_with_payment.py
index 5f8cce0625..e15c366682 100644
--- a/saleor/checkout/tests/fixtures/checkout_with_payment.py
+++ b/saleor/checkout/tests/fixtures/checkout_with_payment.py
@@ -5,7 +5,7 @@ from ....payment.models import Payment
from ....plugins.manager import get_plugins_manager
from ... import calculations
from ...fetch import fetch_checkout_info, fetch_checkout_lines
-from ...utils import add_variant_to_checkout
+from ..utils import add_variant_to_checkout
@pytest.fixture
diff --git a/saleor/checkout/tests/test_cart.py b/saleor/checkout/tests/test_cart.py
index 4090f6673d..6918db7743 100644
--- a/saleor/checkout/tests/test_cart.py
+++ b/saleor/checkout/tests/test_cart.py
@@ -11,10 +11,10 @@ from ...product.models import Category
from .. import calculations, utils
from ..models import Checkout
from ..utils import (
- add_variant_to_checkout,
calculate_checkout_quantity,
calculate_checkout_weight,
)
+from .utils import add_variant_to_checkout
@pytest.fixture
diff --git a/saleor/checkout/tests/test_checkout_complete.py b/saleor/checkout/tests/test_checkout_complete.py
index 2ba6c1b553..d808d86815 100644
--- a/saleor/checkout/tests/test_checkout_complete.py
+++ b/saleor/checkout/tests/test_checkout_complete.py
@@ -42,7 +42,8 @@ from ..complete_checkout import (
from ..fetch import fetch_checkout_info, fetch_checkout_lines
from ..models import Checkout
from ..payment_utils import update_checkout_payment_statuses
-from ..utils import add_variant_to_checkout, add_voucher_to_checkout
+from ..utils import add_voucher_to_checkout
+from .utils import add_variant_to_checkout
@mock.patch("saleor.plugins.manager.PluginsManager.notify")
diff --git a/saleor/checkout/tests/test_order_from_checkout.py b/saleor/checkout/tests/test_order_from_checkout.py
index e300bcf355..58c77fbdd3 100644
--- a/saleor/checkout/tests/test_order_from_checkout.py
+++ b/saleor/checkout/tests/test_order_from_checkout.py
@@ -28,7 +28,8 @@ from ...tests import race_condition
from .. import CheckoutAuthorizeStatus, calculations
from ..complete_checkout import create_order_from_checkout
from ..fetch import fetch_checkout_info, fetch_checkout_lines
-from ..utils import add_variant_to_checkout, add_voucher_to_checkout
+from ..utils import add_voucher_to_checkout
+from .utils import add_variant_to_checkout
def test_create_order_insufficient_stock(
diff --git a/saleor/checkout/tests/test_search_indexing.py b/saleor/checkout/tests/test_search_indexing.py
index 82e5b091a2..cc72b0aaaf 100644
--- a/saleor/checkout/tests/test_search_indexing.py
+++ b/saleor/checkout/tests/test_search_indexing.py
@@ -21,7 +21,7 @@ from ..search.loaders import (
CheckoutLineData,
TransactionData,
)
-from ..utils import add_variant_to_checkout
+from .utils import add_variant_to_checkout
@pytest.fixture
diff --git a/saleor/checkout/tests/utils.py b/saleor/checkout/tests/utils.py
new file mode 100644
index 0000000000..1464004192
--- /dev/null
+++ b/saleor/checkout/tests/utils.py
@@ -0,0 +1,128 @@
+from decimal import Decimal
+from typing import Optional
+
+from django.utils import timezone
+
+from ...core.exceptions import ProductNotPublished
+from ...product import models as product_models
+from ...warehouse.availability import check_stock_and_preorder_quantity
+from ..fetch import CheckoutInfo
+from ..models import Checkout, CheckoutLine
+
+
+def add_variant_to_checkout(
+ checkout_info: "CheckoutInfo",
+ variant: product_models.ProductVariant,
+ quantity: int = 1,
+ price_override: Optional["Decimal"] = None,
+ replace: bool = False,
+ check_quantity: bool = True,
+ force_new_line: bool = False,
+ calculate_stocks_with_shipping_zones: bool = True,
+):
+ """Add a product variant to checkout.
+
+ If `replace` is truthy then any previous quantity is discarded instead
+ of added to.
+
+ This function is not used outside of test suite.
+ """
+ checkout = checkout_info.checkout
+ channel_slug = checkout_info.channel.slug
+
+ product_channel_listing = product_models.ProductChannelListing.objects.filter(
+ channel_id=checkout.channel_id, product_id=variant.product_id
+ ).first()
+ if not product_channel_listing or not product_channel_listing.is_published:
+ raise ProductNotPublished()
+
+ variant_channel_listing = product_models.ProductVariantChannelListing.objects.get(
+ channel_id=checkout.channel_id, variant_id=variant.id
+ )
+ variant_price_amount = variant.get_base_price(
+ variant_channel_listing, price_override
+ ).amount
+ variant_prior_price_amount = variant.get_prior_price_amount(variant_channel_listing)
+
+ new_quantity, line = check_variant_in_stock(
+ checkout,
+ variant,
+ channel_slug,
+ quantity=quantity,
+ replace=replace,
+ check_quantity=check_quantity,
+ calculate_stocks_with_shipping_zones=calculate_stocks_with_shipping_zones,
+ )
+
+ if force_new_line:
+ checkout.lines.create(
+ variant=variant,
+ quantity=quantity,
+ price_override=price_override,
+ undiscounted_unit_price_amount=variant_price_amount,
+ prior_unit_price_amount=variant_prior_price_amount,
+ )
+ return checkout
+
+ if line is None:
+ line = checkout.lines.filter(variant=variant).first()
+
+ if new_quantity == 0:
+ if line is not None:
+ line.delete()
+ elif line is None:
+ checkout.lines.create(
+ variant=variant,
+ quantity=new_quantity,
+ currency=checkout.currency,
+ price_override=price_override,
+ undiscounted_unit_price_amount=variant_price_amount,
+ prior_unit_price_amount=variant_prior_price_amount,
+ )
+ elif new_quantity > 0:
+ line.quantity = new_quantity
+ line.save(update_fields=["quantity"])
+
+ # invalidate calculated prices
+ price_expiration = timezone.now()
+ checkout.price_expiration = price_expiration
+ checkout.discount_expiration = price_expiration
+
+ return checkout
+
+
+def check_variant_in_stock(
+ checkout: Checkout,
+ variant: product_models.ProductVariant,
+ channel_slug: str,
+ quantity: int = 1,
+ *,
+ calculate_stocks_with_shipping_zones: bool,
+ replace: bool = False,
+ check_quantity: bool = True,
+ checkout_lines: list["CheckoutLine"] | None = None,
+ check_reservations: bool = False,
+) -> tuple[int, CheckoutLine | None]:
+ """Check if a given variant is in stock and return the new quantity + line."""
+ line = checkout.lines.filter(variant=variant).first()
+ line_quantity = 0 if line is None else line.quantity
+
+ new_quantity = quantity if replace else (quantity + line_quantity)
+
+ if new_quantity < 0:
+ raise ValueError(
+ f"{quantity!r} is not a valid quantity (results in {new_quantity!r})"
+ )
+
+ if new_quantity > 0 and check_quantity:
+ check_stock_and_preorder_quantity(
+ variant,
+ checkout.get_country(),
+ channel_slug,
+ new_quantity,
+ include_shipping_zones=calculate_stocks_with_shipping_zones,
+ checkout_lines=checkout_lines,
+ check_reservations=check_reservations,
+ )
+
+ return new_quantity, line
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index a26243e1a3..0e2f157d0c 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -7,7 +7,6 @@ from uuid import UUID
import graphene
from django.conf import settings
-from django.contrib.sites.models import Site
from django.core.exceptions import ValidationError
from django.db import transaction
from django.db.models import prefetch_related_objects
@@ -19,7 +18,6 @@ from ..core.db.connection import allow_writer
from ..core.exceptions import (
NonExistingCheckout,
NonExistingCheckoutLines,
- ProductNotPublished,
)
from ..core.taxes import zero_taxed_money
from ..core.utils.metadata_manager import (
@@ -56,7 +54,6 @@ from ..giftcard.utils import (
from ..payment.models import Payment
from ..plugins.manager import PluginsManager
from ..product import models as product_models
-from ..warehouse.availability import check_stock_and_preorder_quantity
from ..warehouse.reservations import reserve_stocks_and_preorders
from . import AddressType, base_calculations, calculations
from .delivery_context import is_shipping_required
@@ -175,121 +172,6 @@ def get_user_checkout(
return checkout_queryset.filter(user=user, channel__is_active=True).first()
-def check_variant_in_stock(
- checkout: Checkout,
- variant: product_models.ProductVariant,
- channel_slug: str,
- quantity: int = 1,
- replace: bool = False,
- check_quantity: bool = True,
- checkout_lines: list["CheckoutLine"] | None = None,
- check_reservations: bool = False,
-) -> tuple[int, CheckoutLine | None]:
- """Check if a given variant is in stock and return the new quantity + line."""
- line = checkout.lines.filter(variant=variant).first()
- line_quantity = 0 if line is None else line.quantity
-
- new_quantity = quantity if replace else (quantity + line_quantity)
-
- if new_quantity < 0:
- raise ValueError(
- f"{quantity!r} is not a valid quantity (results in {new_quantity!r})"
- )
-
- if new_quantity > 0 and check_quantity:
- include_shipping_zones = Site.objects.get_current().settings.use_legacy_shipping_zone_stock_availability
- check_stock_and_preorder_quantity(
- variant,
- checkout.get_country(),
- channel_slug,
- new_quantity,
- include_shipping_zones=include_shipping_zones,
- checkout_lines=checkout_lines,
- check_reservations=check_reservations,
- )
-
- return new_quantity, line
-
-
-def add_variant_to_checkout(
- checkout_info: "CheckoutInfo",
- variant: product_models.ProductVariant,
- quantity: int = 1,
- price_override: Optional["Decimal"] = None,
- replace: bool = False,
- check_quantity: bool = True,
- force_new_line: bool = False,
-):
- """Add a product variant to checkout.
-
- If `replace` is truthy then any previous quantity is discarded instead
- of added to.
-
- This function is not used outside of test suite.
- """
- checkout = checkout_info.checkout
- channel_slug = checkout_info.channel.slug
-
- product_channel_listing = product_models.ProductChannelListing.objects.filter(
- channel_id=checkout.channel_id, product_id=variant.product_id
- ).first()
- if not product_channel_listing or not product_channel_listing.is_published:
- raise ProductNotPublished()
-
- variant_channel_listing = product_models.ProductVariantChannelListing.objects.get(
- channel_id=checkout.channel_id, variant_id=variant.id
- )
- variant_price_amount = variant.get_base_price(
- variant_channel_listing, price_override
- ).amount
- variant_prior_price_amount = variant.get_prior_price_amount(variant_channel_listing)
-
- new_quantity, line = check_variant_in_stock(
- checkout,
- variant,
- channel_slug,
- quantity=quantity,
- replace=replace,
- check_quantity=check_quantity,
- )
-
- if force_new_line:
- checkout.lines.create(
- variant=variant,
- quantity=quantity,
- price_override=price_override,
- undiscounted_unit_price_amount=variant_price_amount,
- prior_unit_price_amount=variant_prior_price_amount,
- )
- return checkout
-
- if line is None:
- line = checkout.lines.filter(variant=variant).first()
-
- if new_quantity == 0:
- if line is not None:
- line.delete()
- elif line is None:
- checkout.lines.create(
- variant=variant,
- quantity=new_quantity,
- currency=checkout.currency,
- price_override=price_override,
- undiscounted_unit_price_amount=variant_price_amount,
- prior_unit_price_amount=variant_prior_price_amount,
- )
- elif new_quantity > 0:
- line.quantity = new_quantity
- line.save(update_fields=["quantity"])
-
- # invalidate calculated prices
- price_expiration = timezone.now()
- checkout.price_expiration = price_expiration
- checkout.discount_expiration = price_expiration
-
- return checkout
-
-
def calculate_checkout_quantity(lines: list["CheckoutLineInfo"]):
return sum([line_info.line.quantity for line_info in lines])
@@ -304,7 +186,7 @@ def add_variants_to_checkout(
reservation_length: int | None = None,
raise_error_for_missing_lines=False,
*,
- include_shipping_zones,
+ calculate_stocks_with_shipping_zones: bool,
):
"""Add variants to checkout.
@@ -401,7 +283,7 @@ def add_variants_to_checkout(
country_code,
channel,
reservation_length,
- include_shipping_zones=include_shipping_zones,
+ calculate_stocks_with_shipping_zones=calculate_stocks_with_shipping_zones,
replace=replace_reservations,
)
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.py
index 3acf33b048..2d25ebaa46 100644
--- a/saleor/core/utils/random_data.py
+++ b/saleor/core/utils/random_data.py
@@ -45,7 +45,7 @@ from ...channel.models import Channel
from ...checkout import AddressType
from ...checkout.fetch import fetch_checkout_info
from ...checkout.models import Checkout
-from ...checkout.utils import add_variant_to_checkout
+from ...checkout.tests.utils import add_variant_to_checkout
from ...core.weight import zero_weight
from ...discount import DiscountValueType, RewardValueType, VoucherType
from ...discount.models import (
diff --git a/saleor/discount/tests/test_rounding_issue.py b/saleor/discount/tests/test_rounding_issue.py
index ddbda390a0..200733e8fc 100644
--- a/saleor/discount/tests/test_rounding_issue.py
+++ b/saleor/discount/tests/test_rounding_issue.py
@@ -3,7 +3,7 @@ from decimal import Decimal
import pytest
from ...checkout.fetch import fetch_checkout_info, fetch_checkout_lines
-from ...checkout.utils import add_variant_to_checkout
+from ...checkout.tests.utils import add_variant_to_checkout
from ...discount.models import PromotionRule
from ...plugins.manager import get_plugins_manager
from ...product.models import Product, ProductVariantChannelListing
diff --git a/saleor/discount/utils/promotion.py b/saleor/discount/utils/promotion.py
index ccf9c7c740..ac9e516789 100644
--- a/saleor/discount/utils/promotion.py
+++ b/saleor/discount/utils/promotion.py
@@ -339,6 +339,7 @@ def _get_best_gift_reward(
include_shipping_zones = (
Site.objects.get_current().settings.use_legacy_shipping_zone_stock_availability
)
+
try:
check_stock_quantity_bulk(
variants,
diff --git a/saleor/graphql/checkout/dataloaders/problems.py b/saleor/graphql/checkout/dataloaders/problems.py
index 1eb1b89bc0..e490517162 100644
--- a/saleor/graphql/checkout/dataloaders/problems.py
+++ b/saleor/graphql/checkout/dataloaders/problems.py
@@ -42,9 +42,6 @@ class CheckoutLinesProblemsByCheckoutIdLoader(
def _resolve_problems(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,32 +112,7 @@ class CheckoutLinesProblemsByCheckoutIdLoader(
)
return [problems.get(key, []) for key in keys]
- 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
- ]
- )
+ variant_stocks = self.get_variants_stocks(site, variant_data_list)
product_channel_listings = (
ProductChannelListingByProductIdAndChannelSlugLoader(
self.context
@@ -156,6 +128,32 @@ class CheckoutLinesProblemsByCheckoutIdLoader(
site = get_site_promise(self.context)
return Promise.all([checkout_infos, lines, site]).then(_resolve_problems)
+ def get_variants_stocks(
+ self,
+ site,
+ variant_data_list: list[tuple[VARIANT_ID, CHANNEL_SLUG, COUNTRY_CODE]],
+ ) -> Promise[list[Iterable[Stock]]]:
+ calculate_stocks_with_shipping_zones = (
+ site.settings.use_legacy_shipping_zone_stock_availability
+ )
+ if calculate_stocks_with_shipping_zones:
+ return StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChannelLoader(
+ self.context
+ ).load_many(
+ [
+ (variant_id, country_code, channel_slug)
+ for variant_id, channel_slug, country_code in variant_data_list
+ ]
+ )
+ return StocksWithAvailableQuantityByProductVariantIdAndChannelSlugLoader(
+ self.context
+ ).load_many(
+ [
+ (variant_id, channel_slug)
+ for variant_id, channel_slug, _country_code in variant_data_list
+ ]
+ )
+
class CheckoutProblemsByCheckoutIdDataloader(
DataLoader[str, dict[str, list[CHECKOUT_PROBLEM_TYPE]]]
diff --git a/saleor/graphql/checkout/mutations/checkout_create.py b/saleor/graphql/checkout/mutations/checkout_create.py
index 9d43442291..a4ef237400 100644
--- a/saleor/graphql/checkout/mutations/checkout_create.py
+++ b/saleor/graphql/checkout/mutations/checkout_create.py
@@ -498,7 +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,
+ calculate_stocks_with_shipping_zones=site.settings.use_legacy_shipping_zone_stock_availability,
)
# Save addresses
diff --git a/saleor/graphql/checkout/mutations/checkout_create_from_order.py b/saleor/graphql/checkout/mutations/checkout_create_from_order.py
index f52b08e1fa..c98a2d6c32 100644
--- a/saleor/graphql/checkout/mutations/checkout_create_from_order.py
+++ b/saleor/graphql/checkout/mutations/checkout_create_from_order.py
@@ -420,7 +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,
+ calculate_stocks_with_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.py
index a105f7aa5a..33a229e93f 100644
--- a/saleor/graphql/checkout/mutations/checkout_lines_add.py
+++ b/saleor/graphql/checkout/mutations/checkout_lines_add.py
@@ -134,7 +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,
+ calculate_stocks_with_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/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
index 31a51bf51c..0537e6ead8 100644
--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
@@ -822,7 +822,7 @@ def test_update_checkout_lines_with_reservations(
channel_USD,
replace_reservations=True,
reservation_length=5,
- include_shipping_zones=True,
+ calculate_stocks_with_shipping_zones=True,
)
user_api_client.ensure_access_token()
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py b/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py
index c4cba85413..b8801724ec 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_add_promo_code.py
@@ -13,9 +13,7 @@ from .....checkout import base_calculations, calculations
from .....checkout.actions import call_checkout_info_event
from .....checkout.error_codes import CheckoutErrorCode
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
-from .....checkout.utils import (
- add_variant_to_checkout,
-)
+from .....checkout.tests.utils import add_variant_to_checkout
from .....core.models import EventDelivery
from .....discount import DiscountValueType, VoucherType
from .....plugins.manager import get_plugins_manager
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_line_delete.py b/saleor/graphql/checkout/tests/mutations/test_checkout_line_delete.py
index ca5e05ea7d..d49dd37c8d 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_line_delete.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_line_delete.py
@@ -11,8 +11,8 @@ from .....checkout import base_calculations
from .....checkout.actions import call_checkout_info_event
from .....checkout.error_codes import CheckoutErrorCode
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
+from .....checkout.tests.utils import add_variant_to_checkout
from .....checkout.utils import (
- add_variant_to_checkout,
add_voucher_to_checkout,
calculate_checkout_quantity,
invalidate_checkout,
diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py
index 169c85a7bd..280a7de863 100644
--- a/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py
+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_lines_update.py
@@ -17,8 +17,8 @@ from .....checkout.calculations import (
from .....checkout.error_codes import CheckoutErrorCode
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....checkout.models import Checkout, CheckoutLine
+from .....checkout.tests.utils import add_variant_to_checkout
from .....checkout.utils import (
- add_variant_to_checkout,
add_variants_to_checkout,
calculate_checkout_quantity,
invalidate_checkout,
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.py
index 7d40cf55ce..f6b74127ff 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
@@ -11,8 +11,8 @@ from .....checkout.actions import call_checkout_info_event
from .....checkout.error_codes import CheckoutErrorCode
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from .....checkout.models import Checkout
+from .....checkout.tests.utils import add_variant_to_checkout
from .....checkout.utils import (
- add_variant_to_checkout,
add_voucher_to_checkout,
invalidate_checkout,
)
diff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.py
index db1519b611..96a8a5e72f 100644
--- a/saleor/graphql/checkout/tests/test_checkout.py
+++ b/saleor/graphql/checkout/tests/test_checkout.py
@@ -30,8 +30,8 @@ from ....checkout.delivery_context import PRIVATE_META_APP_SHIPPING_ID
from ....checkout.error_codes import CheckoutErrorCode
from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
from ....checkout.models import Checkout
+from ....checkout.tests.utils import add_variant_to_checkout
from ....checkout.utils import (
- add_variant_to_checkout,
add_voucher_to_checkout,
)
from ....core.db.connection import allow_writer
diff --git a/saleor/graphql/order/mutations/draft_order_complete.py b/saleor/graphql/order/mutations/draft_order_complete.py
index 5790327957..ea4ee7f690 100644
--- a/saleor/graphql/order/mutations/draft_order_complete.py
+++ b/saleor/graphql/order/mutations/draft_order_complete.py
@@ -123,6 +123,7 @@ class DraftOrderComplete(BaseMutation):
requestor = app or user
manager = get_plugin_manager_promise(info.context).get()
+ site_settings = get_site_promise(info.context).get().settings
order = cls.get_node_or_error(
info,
id,
@@ -143,7 +144,11 @@ class DraftOrderComplete(BaseMutation):
country = get_order_country(order)
validate_draft_order(
- order, order.lines.all(), country, requestor=requestor
+ order,
+ order.lines.all(),
+ country,
+ requestor=requestor,
+ calculate_stocks_with_shipping_zones=site_settings.use_legacy_shipping_zone_stock_availability,
).get()
with traced_atomic_transaction():
update_fields = [
@@ -204,7 +209,6 @@ class DraftOrderComplete(BaseMutation):
line=line, quantity=line.quantity, variant=line.variant
)
order_lines_info.append(line_data)
- site_settings = get_site_promise(info.context).get().settings
try:
with traced_atomic_transaction():
allocate_stocks(
@@ -215,7 +219,7 @@ class DraftOrderComplete(BaseMutation):
check_reservations=is_reservation_enabled(
site_settings
),
- include_shipping_zones=site_settings.use_legacy_shipping_zone_stock_availability,
+ calculate_stocks_with_shipping_zones=site_settings.use_legacy_shipping_zone_stock_availability,
)
allocate_preorders(
[line_data],
diff --git a/saleor/graphql/order/mutations/fulfillment_cancel.py b/saleor/graphql/order/mutations/fulfillment_cancel.py
index c8794ba598..06fee82ba5 100644
--- a/saleor/graphql/order/mutations/fulfillment_cancel.py
+++ b/saleor/graphql/order/mutations/fulfillment_cancel.py
@@ -16,6 +16,7 @@ from ...core.doc_category import DOC_CATEGORY_ORDERS
from ...core.mutations import BaseMutation
from ...core.types import BaseInputObjectType, OrderError
from ...plugins.dataloaders import get_plugin_manager_promise
+from ...site.dataloaders import get_site_promise
from ...warehouse.types import Warehouse
from ..types import Fulfillment, Order
@@ -112,7 +113,18 @@ class FulfillmentCancel(BaseMutation):
app = get_app_promise(info.context).get()
manager = get_plugin_manager_promise(info.context).get()
- fulfillment = cancel_fulfillment(fulfillment, user, app, warehouse, manager)
+ site_settings = get_site_promise(info.context).get().settings
+ calculate_stocks_with_shipping_zones = (
+ site_settings.use_legacy_shipping_zone_stock_availability
+ )
+ fulfillment = cancel_fulfillment(
+ fulfillment,
+ user,
+ app,
+ warehouse,
+ manager,
+ calculate_stocks_with_shipping_zones=calculate_stocks_with_shipping_zones,
+ )
fulfillment_response = SyncWebhookControlContext(node=fulfillment)
order.refresh_from_db(fields=["status"])
return FulfillmentCancel(
diff --git a/saleor/graphql/order/tests/mutations/test_fulfillment_approve.py b/saleor/graphql/order/tests/mutations/test_fulfillment_approve.py
index a9feb23275..afd572e340 100644
--- a/saleor/graphql/order/tests/mutations/test_fulfillment_approve.py
+++ b/saleor/graphql/order/tests/mutations/test_fulfillment_approve.py
@@ -73,7 +73,7 @@ def test_fulfillment_approve(
event = events[0]
assert event.type == OrderEvents.FULFILLMENT_FULFILLED_ITEMS
assert event.user == staff_api_client.user
- mock_fulfillment_approved.assert_called_once_with(fulfillment, True)
+ mock_fulfillment_approved.assert_called_once_with(fulfillment, True, True)
def test_fulfillment_approve_by_user_no_channel_access(
@@ -136,7 +136,7 @@ def test_fulfillment_approve_by_app(
assert event.type == OrderEvents.FULFILLMENT_FULFILLED_ITEMS
assert event.app == app_api_client.app
assert event.user is None
- mock_fulfillment_approved.assert_called_once_with(fulfillment, True)
+ mock_fulfillment_approved.assert_called_once_with(fulfillment, True, True)
@patch("saleor.order.actions.send_fulfillment_confirmation_to_customer", autospec=True)
@@ -442,7 +442,7 @@ def test_fulfillment_approve_partial_order_fulfill(
assert mock_email_fulfillment.call_count == 0
mock_fulfillment_approved.assert_called_once_with(
- partial_fulfillment_awaiting_approval, False
+ partial_fulfillment_awaiting_approval, False, True
)
diff --git a/saleor/graphql/order/tests/test_draft_order_validate.py b/saleor/graphql/order/tests/test_draft_order_validate.py
index 8a83c60877..d8771c7081 100644
--- a/saleor/graphql/order/tests/test_draft_order_validate.py
+++ b/saleor/graphql/order/tests/test_draft_order_validate.py
@@ -18,6 +18,7 @@ def test_validate_draft_order(draft_order):
draft_order.lines.all(),
"US",
get_plugins_manager(allow_replica=False),
+ calculate_stocks_with_shipping_zones=True,
).get()
is None
)
@@ -33,6 +34,7 @@ def test_validate_draft_order_without_sku(draft_order):
draft_order.lines.all(),
"US",
get_plugins_manager(allow_replica=False),
+ calculate_stocks_with_shipping_zones=True,
).get()
is None
)
@@ -46,7 +48,11 @@ def test_validate_draft_order_wrong_shipping(draft_order):
assert order.shipping_address.country.code not in shipping_zone.countries
with pytest.raises(ValidationError) as e:
validate_draft_order(
- order, order.lines.all(), "US", get_plugins_manager(allow_replica=False)
+ order,
+ order.lines.all(),
+ "US",
+ get_plugins_manager(allow_replica=False),
+ calculate_stocks_with_shipping_zones=True,
).get()
msg = "Shipping method is not valid for chosen shipping address"
assert e.value.error_dict["shipping"][0].message == msg
@@ -56,7 +62,11 @@ def test_validate_draft_order_no_order_lines(order, shipping_method):
order.shipping_method = shipping_method
with pytest.raises(ValidationError) as e:
validate_draft_order(
- order, order.lines.all(), "US", get_plugins_manager(allow_replica=False)
+ order,
+ order.lines.all(),
+ "US",
+ get_plugins_manager(allow_replica=False),
+ calculate_stocks_with_shipping_zones=True,
).get()
msg = "Could not create order without any products."
assert e.value.error_dict["lines"][0].message == msg
@@ -72,7 +82,11 @@ def test_validate_draft_order_non_existing_variant(draft_order):
with pytest.raises(ValidationError) as e:
validate_draft_order(
- order, order.lines.all(), "US", get_plugins_manager(allow_replica=False)
+ order,
+ order.lines.all(),
+ "US",
+ get_plugins_manager(allow_replica=False),
+ calculate_stocks_with_shipping_zones=True,
).get()
msg = "Could not create orders with non-existing products."
assert e.value.error_dict["lines"][0].message == msg
@@ -89,7 +103,11 @@ def test_validate_draft_order_with_unpublished_product(draft_order):
with pytest.raises(ValidationError) as e:
validate_draft_order(
- order, order.lines.all(), "US", get_plugins_manager(allow_replica=False)
+ order,
+ order.lines.all(),
+ "US",
+ get_plugins_manager(allow_replica=False),
+ calculate_stocks_with_shipping_zones=True,
).get()
msg = "Can't finalize draft with unpublished product."
error = e.value.error_dict["lines"][0]
@@ -107,7 +125,11 @@ def test_validate_draft_order_with_unavailable_for_purchase_product(draft_order)
with pytest.raises(ValidationError) as e:
validate_draft_order(
- order, order.lines.all(), "US", get_plugins_manager(allow_replica=False)
+ order,
+ order.lines.all(),
+ "US",
+ get_plugins_manager(allow_replica=False),
+ calculate_stocks_with_shipping_zones=True,
).get()
msg = "Can't finalize draft with product unavailable for purchase."
error = e.value.error_dict["lines"][0]
@@ -130,7 +152,11 @@ def test_validate_draft_order_with_product_available_for_purchase_in_future(
with pytest.raises(ValidationError) as e:
validate_draft_order(
- order, order.lines.all(), "US", get_plugins_manager(allow_replica=False)
+ order,
+ order.lines.all(),
+ "US",
+ get_plugins_manager(allow_replica=False),
+ calculate_stocks_with_shipping_zones=True,
).get()
msg = "Can't finalize draft with product unavailable for purchase."
error = e.value.error_dict["lines"][0]
@@ -150,7 +176,11 @@ def test_validate_draft_order_out_of_stock_variant(draft_order):
with pytest.raises(ValidationError) as e:
validate_draft_order(
- order, order.lines.all(), "US", get_plugins_manager(allow_replica=False)
+ order,
+ order.lines.all(),
+ "US",
+ get_plugins_manager(allow_replica=False),
+ calculate_stocks_with_shipping_zones=True,
).get()
msg = "Insufficient product stock."
assert e.value.error_dict["lines"][0].message == msg
@@ -162,7 +192,11 @@ def test_validate_draft_order_no_shipping_address(draft_order):
with pytest.raises(ValidationError) as e:
validate_draft_order(
- order, order.lines.all(), "US", get_plugins_manager(allow_replica=False)
+ order,
+ order.lines.all(),
+ "US",
+ get_plugins_manager(allow_replica=False),
+ calculate_stocks_with_shipping_zones=True,
).get()
error = e.value.error_dict["order"][0]
assert error.message == "Can't finalize draft with no shipping address."
@@ -175,7 +209,11 @@ def test_validate_draft_order_no_billing_address(draft_order):
with pytest.raises(ValidationError) as e:
validate_draft_order(
- order, order.lines.all(), "US", get_plugins_manager(allow_replica=False)
+ order,
+ order.lines.all(),
+ "US",
+ get_plugins_manager(allow_replica=False),
+ calculate_stocks_with_shipping_zones=True,
).get()
error = e.value.error_dict["order"][0]
assert error.message == "Can't finalize draft with no billing address."
@@ -188,7 +226,11 @@ def test_validate_draft_order_no_shipping_method(draft_order):
with pytest.raises(ValidationError) as e:
validate_draft_order(
- order, order.lines.all(), "US", get_plugins_manager(allow_replica=False)
+ order,
+ order.lines.all(),
+ "US",
+ get_plugins_manager(allow_replica=False),
+ calculate_stocks_with_shipping_zones=True,
).get()
error = e.value.error_dict["shipping"][0]
assert error.message == "Shipping method is required."
@@ -205,7 +247,11 @@ def test_validate_draft_order_no_shipping_method_shipping_not_required(
assert (
validate_draft_order(
- order, order.lines.all(), "US", get_plugins_manager(allow_replica=False)
+ order,
+ order.lines.all(),
+ "US",
+ get_plugins_manager(allow_replica=False),
+ calculate_stocks_with_shipping_zones=True,
).get()
is None
)
@@ -223,7 +269,11 @@ def test_validate_draft_order_no_shipping_address_no_method_shipping_not_require
assert (
validate_draft_order(
- order, order.lines.all(), "US", get_plugins_manager(allow_replica=False)
+ order,
+ order.lines.all(),
+ "US",
+ get_plugins_manager(allow_replica=False),
+ calculate_stocks_with_shipping_zones=True,
).get()
is None
)
@@ -237,7 +287,11 @@ def test_validate_draft_order_voucher(draft_order_with_voucher):
# when & then
with pytest.raises(ValidationError) as e:
validate_draft_order(
- order, order.lines.all(), "US", get_plugins_manager(allow_replica=False)
+ order,
+ order.lines.all(),
+ "US",
+ get_plugins_manager(allow_replica=False),
+ calculate_stocks_with_shipping_zones=True,
).get()
error = e.value.error_dict["voucher"][0]
diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.py
index 095c7a144e..3daa67adaa 100644
--- a/saleor/graphql/order/types.py
+++ b/saleor/graphql/order/types.py
@@ -143,6 +143,7 @@ from ..shipping.dataloaders import (
ShippingMethodChannelListingByShippingMethodIdAndChannelSlugLoader,
)
from ..shipping.types import ShippingMethod
+from ..site.dataloaders import load_site_callback
from ..tax.dataloaders import (
TaxClassByIdLoader,
TaxConfigurationByChannelId,
@@ -2455,8 +2456,9 @@ class Order(SyncWebhookControlContextModelObjectType[ModelObjectType[models.Orde
return root.node.get_status_display()
@staticmethod
+ @load_site_callback
@traced_resolver
- def resolve_can_finalize(root: SyncWebhookControlContext[models.Order], info):
+ def resolve_can_finalize(root: SyncWebhookControlContext[models.Order], info, site):
order = root.node
if order.status == OrderStatus.DRAFT:
@@ -2472,6 +2474,9 @@ class Order(SyncWebhookControlContextModelObjectType[ModelObjectType[models.Orde
requestor=get_user_or_app_from_context(info.context),
database_connection_name=database_connection_name,
allow_sync_webhooks=root.allow_sync_webhooks,
+ calculate_stocks_with_shipping_zones=(
+ site.settings.use_legacy_shipping_zone_stock_availability
+ ),
)
.then(lambda _: True)
.catch(lambda _: False)
@@ -2730,8 +2735,9 @@ class Order(SyncWebhookControlContextModelObjectType[ModelObjectType[models.Orde
return graphene.Node.to_global_id("Order", root.node.original_id)
@staticmethod
+ @load_site_callback
@traced_resolver
- def resolve_errors(root: SyncWebhookControlContext[models.Order], info):
+ def resolve_errors(root: SyncWebhookControlContext[models.Order], info, site):
order = root.node
if order.status == OrderStatus.DRAFT:
@@ -2747,6 +2753,9 @@ class Order(SyncWebhookControlContextModelObjectType[ModelObjectType[models.Orde
requestor=get_user_or_app_from_context(info.context),
database_connection_name=database_connection_name,
allow_sync_webhooks=root.allow_sync_webhooks,
+ calculate_stocks_with_shipping_zones=(
+ site.settings.use_legacy_shipping_zone_stock_availability
+ ),
)
.then(lambda _: [])
.catch(
diff --git a/saleor/graphql/order/utils.py b/saleor/graphql/order/utils.py
index 4f95604b31..eac5ad42d7 100644
--- a/saleor/graphql/order/utils.py
+++ b/saleor/graphql/order/utils.py
@@ -5,7 +5,6 @@ from typing import TYPE_CHECKING, Optional, Union
import graphene
from django.conf import settings
-from django.contrib.sites.models import Site
from django.core.exceptions import ValidationError
from promise import Promise
@@ -178,7 +177,7 @@ def validate_order_lines(
country: str,
errors: T_ERRORS,
*,
- include_shipping_zones: bool,
+ calculate_stocks_with_shipping_zones: bool,
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
):
for line in lines:
@@ -198,7 +197,7 @@ def validate_order_lines(
line.quantity,
order_line=line,
database_connection_name=database_connection_name,
- include_shipping_zones=include_shipping_zones,
+ include_shipping_zones=calculate_stocks_with_shipping_zones,
)
except InsufficientStock as exc:
errors["lines"].extend(
@@ -367,6 +366,8 @@ def validate_draft_order(
lines: Iterable["OrderLine"],
country: str,
requestor: Union["App", "User", None],
+ *,
+ calculate_stocks_with_shipping_zones: bool,
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
allow_sync_webhooks: bool = True,
) -> Promise[None]:
@@ -397,16 +398,13 @@ 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,
- include_shipping_zones=include_shipping_zones,
+ calculate_stocks_with_shipping_zones=calculate_stocks_with_shipping_zones,
database_connection_name=database_connection_name,
)
validate_channel_is_active(channel, errors)
diff --git a/saleor/graphql/payment/tests/mutations/test_checkout_payment_create.py b/saleor/graphql/payment/tests/mutations/test_checkout_payment_create.py
index da3b74795c..859c6564bc 100644
--- a/saleor/graphql/payment/tests/mutations/test_checkout_payment_create.py
+++ b/saleor/graphql/payment/tests/mutations/test_checkout_payment_create.py
@@ -8,7 +8,7 @@ from django.utils import timezone
from .....checkout import calculations
from .....checkout.error_codes import CheckoutErrorCode
from .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
-from .....checkout.utils import add_variant_to_checkout
+from .....checkout.tests.utils import add_variant_to_checkout
from .....payment import StorePaymentMethod
from .....payment.error_codes import PaymentErrorCode
from .....payment.interface import StorePaymentMethodEnum
diff --git a/saleor/graphql/product/filters/product_helpers.py b/saleor/graphql/product/filters/product_helpers.py
index 9928071299..39536ccaeb 100644
--- a/saleor/graphql/product/filters/product_helpers.py
+++ b/saleor/graphql/product/filters/product_helpers.py
@@ -142,6 +142,8 @@ def filter_products_by_stock_availability(qs, stock_availability, channel_slug):
def get_available_warehouse_pks_for_product(qs, channel_slug):
+ # refetch the site to make sure that we have the latest settings
+ Site.objects.clear_cache()
include_shipping_zones = (
Site.objects.get_current().settings.use_legacy_shipping_zone_stock_availability
)
diff --git a/saleor/graphql/product/tests/mutations/test_product_channel_listing_update.py b/saleor/graphql/product/tests/mutations/test_product_channel_listing_update.py
index b0f8fd22c2..776efc604f 100644
--- a/saleor/graphql/product/tests/mutations/test_product_channel_listing_update.py
+++ b/saleor/graphql/product/tests/mutations/test_product_channel_listing_update.py
@@ -6,7 +6,7 @@ from django.utils import timezone
from freezegun import freeze_time
from .....checkout.fetch import fetch_checkout_info
-from .....checkout.utils import add_variant_to_checkout
+from .....checkout.tests.utils import add_variant_to_checkout
from .....plugins.manager import get_plugins_manager
from .....product.error_codes import ProductErrorCode
from .....product.models import ProductVariant, ProductVariantChannelListing
diff --git a/saleor/graphql/product/tests/test_bulk_delete.py b/saleor/graphql/product/tests/test_bulk_delete.py
index 416ae72764..9c3df1bbe5 100644
--- a/saleor/graphql/product/tests/test_bulk_delete.py
+++ b/saleor/graphql/product/tests/test_bulk_delete.py
@@ -9,7 +9,8 @@ from prices import Money, TaxedMoney
from ....attribute.models import AttributeValue
from ....attribute.utils import associate_attribute_values_to_instance
from ....checkout.fetch import fetch_checkout_info, fetch_checkout_lines
-from ....checkout.utils import add_variant_to_checkout, calculate_checkout_quantity
+from ....checkout.tests.utils import add_variant_to_checkout
+from ....checkout.utils import calculate_checkout_quantity
from ....discount.utils.promotion import get_active_catalogue_promotion_rules
from ....order import OrderEvents, OrderStatus
from ....order.models import OrderEvent, OrderLine
diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.py
index 353d756358..6d7fef66e2 100644
--- a/saleor/graphql/product/types/products.py
+++ b/saleor/graphql/product/types/products.py
@@ -506,10 +506,10 @@ class ProductVariant(ChannelContextType[models.ProductVariant]):
if not channel_slug and not country_code:
return StocksByProductVariantIdLoader(info.context).load(root.node.id)
- include_shipping_zones = (
+ calculate_stocks_with_shipping_zones = (
site.settings.use_legacy_shipping_zone_stock_availability
)
- if include_shipping_zones:
+ if calculate_stocks_with_shipping_zones:
return StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChannelLoader( # noqa: E501
info.context
).load((root.node.id, country_code, root.channel_slug))
diff --git a/saleor/order/actions.py b/saleor/order/actions.py
index c869ac1da3..ad382e838b 100644
--- a/saleor/order/actions.py
+++ b/saleor/order/actions.py
@@ -583,8 +583,16 @@ def order_fulfilled(
auto=auto,
)
webhook_events = [WebhookEventAsyncType.ORDER_UPDATED]
+ calculate_stocks_with_shipping_zones = (
+ site_settings.use_legacy_shipping_zone_stock_availability
+ )
for fulfillment in fulfillments:
- call_event(manager.fulfillment_created, fulfillment, notify_customer)
+ call_event(
+ manager.fulfillment_created,
+ fulfillment,
+ notify_customer,
+ calculate_stocks_with_shipping_zones,
+ )
order_fulfilled = order.status == OrderStatus.FULFILLED
if order_fulfilled:
@@ -592,7 +600,12 @@ def order_fulfilled(
if order_fulfilled or manually_approved:
for fulfillment in fulfillments:
- call_event(manager.fulfillment_approved, fulfillment, notify_customer)
+ call_event(
+ manager.fulfillment_approved,
+ fulfillment,
+ notify_customer,
+ calculate_stocks_with_shipping_zones,
+ )
call_order_events(
manager,
@@ -796,6 +809,8 @@ def cancel_fulfillment(
app: Optional["App"],
warehouse: Optional["Warehouse"],
manager: "PluginsManager",
+ *,
+ calculate_stocks_with_shipping_zones: bool,
):
"""Cancel fulfillment.
@@ -821,7 +836,11 @@ def cancel_fulfillment(
fulfillment.status = FulfillmentStatus.CANCELED
fulfillment.save(update_fields=["status"])
update_order_status(fulfillment.order)
- call_event(manager.fulfillment_canceled, fulfillment)
+ call_event(
+ manager.fulfillment_canceled,
+ fulfillment,
+ calculate_stocks_with_shipping_zones,
+ )
call_order_event(
manager,
WebhookEventAsyncType.ORDER_UPDATED,
@@ -1076,7 +1095,7 @@ def _create_fulfillment_lines(
gift_card_lines_info: list[GiftCardLineData],
manager: "PluginsManager",
*,
- include_shipping_zones: bool,
+ calculate_stocks_with_shipping_zones: bool,
should_decrease_stock: bool = True,
allow_stock_to_be_exceeded: bool = False,
) -> list[FulfillmentLine]:
@@ -1101,8 +1120,8 @@ 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
+ calculate_stocks_with_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:
@@ -1117,7 +1136,7 @@ def _create_fulfillment_lines(
variants = [line.variant for line in lines if line.variant]
stocks = (
Stock.objects.for_channel_or_country(
- channel_slug, include_shipping_zones=include_shipping_zones
+ channel_slug, include_shipping_zones=calculate_stocks_with_shipping_zones
)
.filter(warehouse_id=warehouse_pk, product_variant__in=variants)
.select_related("product_variant")
@@ -1287,7 +1306,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,
+ calculate_stocks_with_shipping_zones=site_settings.use_legacy_shipping_zone_stock_availability,
)
)
if tracking_number:
diff --git a/saleor/order/tests/fixtures/order.py b/saleor/order/tests/fixtures/order.py
index 5ececfcf42..914d06cfdb 100644
--- a/saleor/order/tests/fixtures/order.py
+++ b/saleor/order/tests/fixtures/order.py
@@ -1071,6 +1071,7 @@ def fulfilled_order_with_all_cancelled_fulfillments(
None,
warehouse,
get_plugins_manager(allow_replica=False),
+ calculate_stocks_with_shipping_zones=True,
)
return fulfilled_order
diff --git a/saleor/order/tests/test_fulfillments_actions.py b/saleor/order/tests/test_fulfillments_actions.py
index 8b3b48bef4..73c05fa6d4 100644
--- a/saleor/order/tests/test_fulfillments_actions.py
+++ b/saleor/order/tests/test_fulfillments_actions.py
@@ -80,7 +80,11 @@ def test_create_fulfillments(
mock_email_fulfillment.assert_called_once_with(
order, order.fulfillments.get(), staff_user, None, manager
)
- mock_fulfillment_approved.assert_called_once_with(fulfillment, notify_customer)
+ mock_fulfillment_approved.assert_called_once_with(
+ fulfillment,
+ notify_customer,
+ site_settings.use_legacy_shipping_zone_stock_availability,
+ )
@patch("saleor.plugins.manager.PluginsManager.fulfillment_approved")
diff --git a/saleor/order/tests/test_order_actions.py b/saleor/order/tests/test_order_actions.py
index f323301ea5..f3652ed682 100644
--- a/saleor/order/tests/test_order_actions.py
+++ b/saleor/order/tests/test_order_actions.py
@@ -513,7 +513,12 @@ def test_cancel_fulfillment(fulfilled_order, warehouse):
line_1, line_2 = fulfillment.lines.all()
cancel_fulfillment(
- fulfillment, None, None, warehouse, get_plugins_manager(allow_replica=False)
+ fulfillment,
+ None,
+ None,
+ warehouse,
+ get_plugins_manager(allow_replica=False),
+ calculate_stocks_with_shipping_zones=True,
)
fulfillment.refresh_from_db()
@@ -541,6 +546,7 @@ def test_cancel_fulfillment_waiting_for_approval(fulfilled_order):
None,
warehouse,
manager=get_plugins_manager(allow_replica=False),
+ calculate_stocks_with_shipping_zones=True,
)
# then
@@ -562,7 +568,12 @@ def test_cancel_fulfillment_variant_without_inventory_tracking(
stock_quantity_before = stock.quantity
cancel_fulfillment(
- fulfillment, None, None, warehouse, get_plugins_manager(allow_replica=False)
+ fulfillment,
+ None,
+ None,
+ warehouse,
+ get_plugins_manager(allow_replica=False),
+ calculate_stocks_with_shipping_zones=True,
)
fulfillment.refresh_from_db()
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index 49d462933c..91ef901b59 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -338,7 +338,7 @@ def create_order_line(
],
channel,
manager=manager,
- include_shipping_zones=(
+ calculate_stocks_with_shipping_zones=(
site_settings.use_legacy_shipping_zone_stock_availability
),
)
@@ -540,11 +540,14 @@ def _update_allocations_for_line(
if not get_order_lines_with_track_inventory([line_info]):
return
line_info.quantity = new_quantity - old_quantity
- include_shipping_zones = (
+ calculate_stocks_with_shipping_zones = (
site_settings.use_legacy_shipping_zone_stock_availability
)
increase_allocations(
- [line_info], channel, manager, include_shipping_zones=include_shipping_zones
+ [line_info],
+ channel,
+ manager,
+ calculate_stocks_with_shipping_zones=calculate_stocks_with_shipping_zones,
)
else:
line_info.quantity = old_quantity - new_quantity
diff --git a/saleor/plugins/avatax/tests/test_avatax.py b/saleor/plugins/avatax/tests/test_avatax.py
index 530dd969d6..30e03dc5fb 100644
--- a/saleor/plugins/avatax/tests/test_avatax.py
+++ b/saleor/plugins/avatax/tests/test_avatax.py
@@ -14,7 +14,7 @@ from requests_hardened import HTTPSession
from ....account.models import Address
from ....checkout.fetch import CheckoutInfo, fetch_checkout_info, fetch_checkout_lines
-from ....checkout.utils import add_variant_to_checkout
+from ....checkout.tests.utils import add_variant_to_checkout
from ....core.prices import quantize_price
from ....core.taxes import (
TaxDataErrorMessage,
diff --git a/saleor/plugins/base_plugin.py b/saleor/plugins/base_plugin.py
index 255531c37c..8cedf2862d 100644
--- a/saleor/plugins/base_plugin.py
+++ b/saleor/plugins/base_plugin.py
@@ -670,7 +670,7 @@ class BasePlugin:
#
# Note: This method is deprecated and will be removed in a future release.
# Webhook-related functionality will be moved from the plugin to core modules.
- fulfillment_created: Callable[["Fulfillment", bool, Any], Any]
+ fulfillment_created: Callable[["Fulfillment", bool, Any, Any], Any]
# Trigger when fulfillment is cancelled.
#
@@ -679,7 +679,7 @@ class BasePlugin:
#
# Note: This method is deprecated and will be removed in a future release.
# Webhook-related functionality will be moved from the plugin to core modules.
- fulfillment_canceled: Callable[["Fulfillment", Any], Any]
+ fulfillment_canceled: Callable[["Fulfillment", Any, Any], Any]
# Trigger when fulfillment is approved.
#
@@ -688,7 +688,7 @@ class BasePlugin:
#
# Note: This method is deprecated and will be removed in a future release.
# Webhook-related functionality will be moved from the plugin to core modules.
- fulfillment_approved: Callable[["Fulfillment", Any], Any]
+ fulfillment_approved: Callable[["Fulfillment", Any, Any], Any]
# Trigger when fulfillment metadata is updated.
#
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index f1d780de6b..dbd627ba9f 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -1287,7 +1287,10 @@ class PluginsManager(PaymentInterface):
# Note: this method is deprecated and will be removed in a future release.
# Webhook-related functionality will be moved from plugin to core modules.
def fulfillment_created(
- self, fulfillment: "Fulfillment", notify_customer: bool | None = True
+ self,
+ fulfillment: "Fulfillment",
+ notify_customer: bool | None = True,
+ calculate_stocks_with_shipping_zones: bool = True,
):
default_value = None
return self.__run_method_on_plugins(
@@ -1296,23 +1299,32 @@ class PluginsManager(PaymentInterface):
fulfillment,
channel_slug=fulfillment.order.channel.slug,
notify_customer=notify_customer,
+ calculate_stocks_with_shipping_zones=calculate_stocks_with_shipping_zones,
)
# Note: this method is deprecated and will be removed in a future release.
# Webhook-related functionality will be moved from plugin to core modules.
- def fulfillment_canceled(self, fulfillment: "Fulfillment"):
+ def fulfillment_canceled(
+ self,
+ fulfillment: "Fulfillment",
+ calculate_stocks_with_shipping_zones: bool = True,
+ ):
default_value = None
return self.__run_method_on_plugins(
"fulfillment_canceled",
default_value,
fulfillment,
channel_slug=fulfillment.order.channel.slug,
+ calculate_stocks_with_shipping_zones=calculate_stocks_with_shipping_zones,
)
# Note: this method is deprecated and will be removed in a future release.
# Webhook-related functionality will be moved from plugin to core modules.
def fulfillment_approved(
- self, fulfillment: "Fulfillment", notify_customer: bool | None = True
+ self,
+ fulfillment: "Fulfillment",
+ notify_customer: bool | None = True,
+ calculate_stocks_with_shipping_zones: bool = True,
):
default_value = None
return self.__run_method_on_plugins(
@@ -1321,6 +1333,7 @@ class PluginsManager(PaymentInterface):
fulfillment,
channel_slug=fulfillment.order.channel.slug,
notify_customer=notify_customer,
+ calculate_stocks_with_shipping_zones=calculate_stocks_with_shipping_zones,
)
# Note: this method is deprecated and will be removed in a future release.
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index c67119a557..a0738dedcb 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -1539,6 +1539,7 @@ class WebhookPlugin(BasePlugin):
self,
fulfillment: "Fulfillment",
notify_customer: bool = True,
+ calculate_stocks_with_shipping_zones: bool = True,
previous_value: None = None,
) -> None:
if not self.active:
@@ -1546,7 +1547,10 @@ class WebhookPlugin(BasePlugin):
event_type = WebhookEventAsyncType.FULFILLMENT_CREATED
if webhooks := get_webhooks_for_event(event_type):
fulfillment_data_generator = partial(
- generate_fulfillment_payload, fulfillment, self.requestor
+ generate_fulfillment_payload,
+ fulfillment,
+ self.requestor,
+ calculate_stocks_with_shipping_zones,
)
self.trigger_webhooks_async(
None,
@@ -1562,14 +1566,20 @@ class WebhookPlugin(BasePlugin):
return previous_value
def fulfillment_canceled(
- self, fulfillment: "Fulfillment", previous_value: None
+ self,
+ fulfillment: "Fulfillment",
+ calculate_stocks_with_shipping_zones: bool = True,
+ previous_value: None = None,
) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.FULFILLMENT_CANCELED
if webhooks := get_webhooks_for_event(event_type):
fulfillment_data_generator = partial(
- generate_fulfillment_payload, fulfillment, self.requestor
+ generate_fulfillment_payload,
+ fulfillment,
+ self.requestor,
+ calculate_stocks_with_shipping_zones,
)
self.trigger_webhooks_async(
None,
@@ -1585,6 +1595,7 @@ class WebhookPlugin(BasePlugin):
self,
fulfillment: "Fulfillment",
notify_customer: bool | None = True,
+ calculate_stocks_with_shipping_zones: bool = True,
previous_value: None = None,
) -> None:
if not self.active:
@@ -1592,7 +1603,10 @@ class WebhookPlugin(BasePlugin):
event_type = WebhookEventAsyncType.FULFILLMENT_APPROVED
if webhooks := get_webhooks_for_event(event_type):
fulfillment_data_generator = partial(
- generate_fulfillment_payload, fulfillment, self.requestor
+ generate_fulfillment_payload,
+ fulfillment,
+ self.requestor,
+ calculate_stocks_with_shipping_zones,
)
self.trigger_webhooks_async(
None,
@@ -1618,13 +1632,18 @@ class WebhookPlugin(BasePlugin):
return previous_value
def tracking_number_updated(
- self, fulfillment: "Fulfillment", previous_value: None
+ self,
+ fulfillment: "Fulfillment",
+ calculate_stocks_with_shipping_zones: bool = True,
+ previous_value: None = None,
) -> None:
if not self.active:
return previous_value
event_type = WebhookEventAsyncType.FULFILLMENT_TRACKING_NUMBER_UPDATED
if webhooks := get_webhooks_for_event(event_type):
- fulfillment_data = generate_fulfillment_payload(fulfillment, self.requestor)
+ fulfillment_data = generate_fulfillment_payload(
+ fulfillment, self.requestor, calculate_stocks_with_shipping_zones
+ )
self.trigger_webhooks_async(
fulfillment_data,
event_type,
diff --git a/saleor/tax/tests/test_checkout_calculations.py b/saleor/tax/tests/test_checkout_calculations.py
index 08e9442956..e0bdf028e4 100644
--- a/saleor/tax/tests/test_checkout_calculations.py
+++ b/saleor/tax/tests/test_checkout_calculations.py
@@ -6,7 +6,7 @@ from prices import Money, TaxedMoney
from ...checkout import calculations
from ...checkout.fetch import fetch_checkout_info, fetch_checkout_lines
-from ...checkout.utils import add_variant_to_checkout
+from ...checkout.tests.utils import add_variant_to_checkout
from ...core.prices import quantize_price
from ...core.taxes import zero_taxed_money
from ...discount.utils.checkout import (
diff --git a/saleor/warehouse/availability.py b/saleor/warehouse/availability.py
index 3adc167210..c45ffef268 100644
--- a/saleor/warehouse/availability.py
+++ b/saleor/warehouse/availability.py
@@ -545,7 +545,7 @@ def get_available_quantity(
country_code: str,
channel_slug: str,
*,
- include_shipping_zones: bool,
+ calculate_stocks_with_shipping_zones: bool,
checkout_lines: list["CheckoutLine"] | None = None,
check_reservations: bool = False,
) -> int:
@@ -554,7 +554,7 @@ def get_available_quantity(
channel_slug,
variant,
country_code=country_code,
- include_shipping_zones=include_shipping_zones,
+ include_shipping_zones=calculate_stocks_with_shipping_zones,
)
if not stocks:
return 0
@@ -565,14 +565,14 @@ def is_product_in_stock(
product: "Product",
country_code: str,
channel_slug: str,
- include_shipping_zones: bool,
+ calculate_stocks_with_shipping_zones: bool,
) -> bool:
"""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,
+ include_shipping_zones=calculate_stocks_with_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.py
index 031babc541..0b98e9a285 100644
--- a/saleor/warehouse/management.py
+++ b/saleor/warehouse/management.py
@@ -84,7 +84,7 @@ def allocate_stocks(
channel: "Channel",
manager: PluginsManager,
*,
- include_shipping_zones: bool,
+ calculate_stocks_with_shipping_zones: bool,
collection_point_pk: UUID | None = None,
additional_filter_lookup: dict[str, Any] | None = None,
check_reservations: bool = False,
@@ -121,7 +121,7 @@ def allocate_stocks(
stocks = Stock.objects.for_channel_or_country(
channel_slug,
country_code,
- include_shipping_zones=include_shipping_zones,
+ include_shipping_zones=calculate_stocks_with_shipping_zones,
)
stocks = list(
@@ -466,7 +466,7 @@ def increase_allocations(
lines_info: list["OrderLineInfo"],
channel: "Channel",
manager: PluginsManager,
- include_shipping_zones: bool,
+ calculate_stocks_with_shipping_zones: bool,
):
"""Increase allocation for order lines with appropriate quantity."""
line_pks = [info.line.pk for info in lines_info]
@@ -504,7 +504,7 @@ def increase_allocations(
country_code,
channel,
manager,
- include_shipping_zones=include_shipping_zones,
+ calculate_stocks_with_shipping_zones=calculate_stocks_with_shipping_zones,
)
diff --git a/saleor/warehouse/reservations.py b/saleor/warehouse/reservations.py
index 8c83134820..b539f5d3f9 100644
--- a/saleor/warehouse/reservations.py
+++ b/saleor/warehouse/reservations.py
@@ -34,7 +34,7 @@ def reserve_stocks_and_preorders(
channel: "Channel",
length_in_minutes: int,
*,
- include_shipping_zones: bool,
+ calculate_stocks_with_shipping_zones: bool,
replace: bool = True,
):
stock_variants, stock_lines = [], []
@@ -62,7 +62,7 @@ def reserve_stocks_and_preorders(
channel,
reserved_until,
replace=replace,
- include_shipping_zones=include_shipping_zones,
+ calculate_stocks_with_shipping_zones=calculate_stocks_with_shipping_zones,
)
# Refresh reserved_until for already existing lines
@@ -96,7 +96,7 @@ def reserve_stocks(
reserved_until: datetime.datetime,
*,
replace: bool = True,
- include_shipping_zones: bool,
+ calculate_stocks_with_shipping_zones: bool,
):
"""Reserve stocks for given `checkout_lines` in given country."""
variants_ids = [line.variant_id for line in checkout_lines]
@@ -115,7 +115,7 @@ def reserve_stocks(
channel.slug,
variants,
country_code=country_code,
- include_shipping_zones=include_shipping_zones,
+ include_shipping_zones=calculate_stocks_with_shipping_zones,
)
.order_by("pk")
.values("id", "product_variant", "pk", "quantity", "warehouse_id")
diff --git a/saleor/warehouse/tests/test_stock_availability.py b/saleor/warehouse/tests/test_stock_availability.py
index 11f715a0d0..060859d13e 100644
--- a/saleor/warehouse/tests/test_stock_availability.py
+++ b/saleor/warehouse/tests/test_stock_availability.py
@@ -143,7 +143,7 @@ def test_get_available_quantity(variant_with_many_stocks, channel_USD):
variant_with_many_stocks,
COUNTRY_CODE,
channel_USD.slug,
- include_shipping_zones=True,
+ calculate_stocks_with_shipping_zones=True,
)
assert available_quantity == 7
@@ -154,7 +154,7 @@ def test_get_available_quantity_without_allocation(order_line, stock, channel_US
order_line.variant,
COUNTRY_CODE,
channel_USD.slug,
- include_shipping_zones=True,
+ calculate_stocks_with_shipping_zones=True,
)
assert available_quantity == stock.quantity
@@ -169,7 +169,7 @@ def test_get_available_quantity_with_allocations(
variant_with_many_stocks,
COUNTRY_CODE,
channel_USD.slug,
- include_shipping_zones=True,
+ calculate_stocks_with_shipping_zones=True,
)
assert available_quantity == 3
@@ -184,7 +184,7 @@ def test_get_available_quantity_with_reservations(
variant_with_many_stocks,
COUNTRY_CODE,
channel_USD.slug,
- include_shipping_zones=True,
+ calculate_stocks_with_shipping_zones=True,
check_reservations=True,
)
assert available_quantity == 2
@@ -200,7 +200,7 @@ def test_get_available_quantity_with_allocations_and_reservations(
variant_with_many_stocks,
COUNTRY_CODE,
channel_USD.slug,
- include_shipping_zones=True,
+ calculate_stocks_with_shipping_zones=True,
check_reservations=True,
)
assert available_quantity == 4
@@ -220,7 +220,7 @@ def test_get_available_quantity_with_reservations_excluding_given_checkout_lines
checkout_line_with_reservation_in_many_stocks,
checkout_line_with_one_reservation,
],
- include_shipping_zones=True,
+ calculate_stocks_with_shipping_zones=True,
check_reservations=True,
)
assert available_quantity == 7
@@ -232,7 +232,7 @@ def test_get_available_quantity_without_stocks(variant_with_many_stocks, channel
variant_with_many_stocks,
COUNTRY_CODE,
channel_USD.slug,
- include_shipping_zones=True,
+ calculate_stocks_with_shipping_zones=True,
)
assert available_quantity == 0
@@ -352,7 +352,7 @@ def test_check_stock_quantity_bulk_with_reservations(
variant,
country_code,
channel_USD.slug,
- include_shipping_zones=True,
+ calculate_stocks_with_shipping_zones=True,
check_reservations=True,
)
global_quantity_limit = 50
@@ -452,7 +452,7 @@ def test_get_available_quantity_no_shipping_zones_included(
variant_with_many_stocks,
COUNTRY_CODE,
channel_USD.slug,
- include_shipping_zones=include_shipping_zones,
+ calculate_stocks_with_shipping_zones=include_shipping_zones,
)
# then - legacy behavior: no shipping zones means no stock
@@ -471,7 +471,7 @@ def test_get_available_quantity_no_shipping_zones_excluded_from_stock_calculatio
variant_with_many_stocks,
COUNTRY_CODE,
channel_USD.slug,
- include_shipping_zones=include_shipping_zones,
+ calculate_stocks_with_shipping_zones=include_shipping_zones,
)
# then - flag disabled: shipping zones ignored, stock found
@@ -571,7 +571,7 @@ def test_is_product_in_stock_no_shipping_zones_included(
product,
COUNTRY_CODE,
channel_USD.slug,
- include_shipping_zones=include_shipping_zones,
+ calculate_stocks_with_shipping_zones=include_shipping_zones,
)
# then - legacy: no shipping zones means not in stock
@@ -591,7 +591,7 @@ def test_is_product_in_stock_no_shipping_zones_excluded_from_stock_calculations(
product,
COUNTRY_CODE,
channel_USD.slug,
- include_shipping_zones=include_shipping_zones,
+ calculate_stocks_with_shipping_zones=include_shipping_zones,
)
# then - flag disabled: shipping zones ignored, product in stock
diff --git a/saleor/warehouse/tests/test_stock_management.py b/saleor/warehouse/tests/test_stock_management.py
index 7fb231871c..7a3ccac8ab 100644
--- a/saleor/warehouse/tests/test_stock_management.py
+++ b/saleor/warehouse/tests/test_stock_management.py
@@ -36,7 +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,
+ calculate_stocks_with_shipping_zones=True,
)
stock.refresh_from_db()
@@ -77,7 +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,
+ calculate_stocks_with_shipping_zones=True,
)
stock.refresh_from_db()
@@ -102,7 +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,
+ calculate_stocks_with_shipping_zones=True,
)
allocations = Allocation.objects.filter(order_line=order_line, stock__in=stocks)
@@ -135,7 +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,
+ calculate_stocks_with_shipping_zones=True,
collection_point_pk=warehouse_for_cc.pk,
)
@@ -176,7 +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,
+ calculate_stocks_with_shipping_zones=True,
)
# then
@@ -238,7 +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,
+ calculate_stocks_with_shipping_zones=True,
collection_point_pk=warehouse_for_cc.pk,
)
@@ -264,7 +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,
+ calculate_stocks_with_shipping_zones=True,
check_reservations=True,
)
@@ -311,7 +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,
+ calculate_stocks_with_shipping_zones=True,
check_reservations=True,
)
@@ -342,7 +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,
+ calculate_stocks_with_shipping_zones=True,
check_reservations=True,
)
@@ -372,7 +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,
+ calculate_stocks_with_shipping_zones=True,
)
# then
@@ -402,7 +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,
+ calculate_stocks_with_shipping_zones=True,
)
assert not Allocation.objects.filter(
@@ -426,7 +426,7 @@ def test_allocate_stocks_no_channel_shipping_zones(order_line, stock, channel_US
COUNTRY_CODE,
channel_USD,
manager=get_plugins_manager(allow_replica=False),
- include_shipping_zones=True,
+ calculate_stocks_with_shipping_zones=True,
)
@@ -447,7 +447,7 @@ def test_allocate_stocks_no_channel_shipping_zones_excluded_from_stock_calculati
COUNTRY_CODE,
channel_USD,
manager=get_plugins_manager(allow_replica=False),
- include_shipping_zones=False,
+ calculate_stocks_with_shipping_zones=False,
)
@@ -464,7 +464,7 @@ def test_allocate_stock_insufficient_stocks(
COUNTRY_CODE,
channel_USD,
manager=get_plugins_manager(allow_replica=False),
- include_shipping_zones=True,
+ calculate_stocks_with_shipping_zones=True,
)
assert not Allocation.objects.filter(
@@ -503,7 +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,
+ calculate_stocks_with_shipping_zones=True,
)
assert {item.variant for item in exc._excinfo[1].items} == {variant, variant_2}
@@ -682,7 +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,
+ calculate_stocks_with_shipping_zones=True,
)
stock.refresh_from_db()
@@ -747,7 +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,
+ calculate_stocks_with_shipping_zones=True,
)
stock.refresh_from_db()
@@ -789,7 +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,
+ calculate_stocks_with_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.py
index 5fe3903795..92a4f506a3 100644
--- a/saleor/warehouse/tests/test_stock_reservations_management.py
+++ b/saleor/warehouse/tests/test_stock_reservations_management.py
@@ -27,7 +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,
+ calculate_stocks_with_shipping_zones=True,
)
stock.refresh_from_db()
@@ -48,7 +48,7 @@ def test_stocks_reservation_skips_prev_reservation_delete_if_replace_is_disabled
channel_USD,
timezone.now() + datetime.timedelta(minutes=RESERVATION_LENGTH),
replace=False,
- include_shipping_zones=True,
+ calculate_stocks_with_shipping_zones=True,
)
with assert_num_queries(4):
@@ -58,7 +58,7 @@ def test_stocks_reservation_skips_prev_reservation_delete_if_replace_is_disabled
COUNTRY_CODE,
channel_USD,
timezone.now() + datetime.timedelta(minutes=RESERVATION_LENGTH),
- include_shipping_zones=True,
+ calculate_stocks_with_shipping_zones=True,
)
@@ -92,7 +92,7 @@ def test_multiple_stocks_reserved_if_single_stock_is_not_enough_highest_stock_st
COUNTRY_CODE,
channel_USD,
timezone.now() + datetime.timedelta(minutes=RESERVATION_LENGTH),
- include_shipping_zones=True,
+ calculate_stocks_with_shipping_zones=True,
)
stock.refresh_from_db()
@@ -162,7 +162,7 @@ def test_multiple_stocks_reserved_if_single_stock_is_not_enough_sorting_order_st
COUNTRY_CODE,
channel_USD,
timezone.now() + datetime.timedelta(minutes=RESERVATION_LENGTH),
- include_shipping_zones=True,
+ calculate_stocks_with_shipping_zones=True,
)
# then
@@ -205,7 +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,
+ calculate_stocks_with_shipping_zones=True,
)
with pytest.raises(Reservation.DoesNotExist):
@@ -229,7 +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,
+ calculate_stocks_with_shipping_zones=True,
)
@@ -246,7 +246,7 @@ def test_stock_reservation_fails_if_there_is_no_stock(checkout_line, channel_USD
COUNTRY_CODE,
channel_USD,
RESERVATION_LENGTH,
- include_shipping_zones=True,
+ calculate_stocks_with_shipping_zones=True,
)
@@ -271,7 +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,
+ calculate_stocks_with_shipping_zones=True,
)
@@ -314,7 +314,7 @@ 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,
+ calculate_stocks_with_shipping_zones=True,
)
@@ -337,7 +337,7 @@ def test_reserve_stocks_no_shipping_zones_included(checkout_line, channel_USD):
COUNTRY_CODE,
channel_USD,
timezone.now() + datetime.timedelta(minutes=RESERVATION_LENGTH),
- include_shipping_zones=True,
+ calculate_stocks_with_shipping_zones=True,
)
@@ -361,7 +361,7 @@ def test_reserve_stocks_no_shipping_zones_excluded_from_stock_calculations(
COUNTRY_CODE,
channel_USD,
timezone.now() + datetime.timedelta(minutes=RESERVATION_LENGTH),
- include_shipping_zones=False,
+ calculate_stocks_with_shipping_zones=False,
)
# then - reservation created
diff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.py
index ee21c73c41..d6215437f7 100644
--- a/saleor/webhook/payloads.py
+++ b/saleor/webhook/payloads.py
@@ -552,10 +552,14 @@ def generate_checkout_payload(
# todo use the most appropriate warehouse
warehouse = None
- include_shipping_zones = (
- Site.objects.get_current().settings.use_legacy_shipping_zone_stock_availability
+
+ # refetch the site to make sure that we have the latest settings
+ Site.objects.clear_cache()
+ site = Site.objects.get_current()
+ calculate_stocks_with_shipping_zones = (
+ site.settings.use_legacy_shipping_zone_stock_availability
)
- if include_shipping_zones:
+ if calculate_stocks_with_shipping_zones:
if checkout.shipping_address:
warehouse = Warehouse.objects.for_country_and_channel(
checkout.shipping_address.country.code, checkout.channel_id
@@ -985,7 +989,9 @@ def generate_fulfillment_lines_payload(fulfillment: Fulfillment):
@allow_writer()
@traced_payload_generator
def generate_fulfillment_payload(
- fulfillment: Fulfillment, requestor: Optional["RequestorOrLazyObject"] = None
+ fulfillment: Fulfillment,
+ requestor: Optional["RequestorOrLazyObject"] = None,
+ calculate_stocks_with_shipping_zones: bool = True,
):
serializer = PayloadSerializer()
@@ -1010,8 +1016,7 @@ def generate_fulfillment_payload(
if fulfillment_line and fulfillment_line.stock:
warehouse = fulfillment_line.stock.warehouse
else:
- include_shipping_zones = Site.objects.get_current().settings.use_legacy_shipping_zone_stock_availability
- if include_shipping_zones:
+ if calculate_stocks_with_shipping_zones:
warehouse = Warehouse.objects.for_country_and_channel(
order_country, order.channel_id
).first()