Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fix stock validation and allocation for order with local collection point (#10218)
Iga Karbowiaka8b892b774ee
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.pyindex 1ce09ce589..3bd711fd7e 100644--- a/saleor/checkout/complete_checkout.py+++ b/saleor/checkout/complete_checkout.py@@ -332,6 +332,7 @@ def _create_lines_for_order(quantities,checkout_info.channel.slug,global_quantity_limit=None,+ collection_point_pk=checkout_info.delivery_method_info.warehouse_pk,additional_filter_lookup=additional_warehouse_lookup,existing_lines=lines,replace=True,@@ -521,6 +522,7 @@ def _create_order(country_code,checkout_info.channel.slug,manager,+ checkout_info.delivery_method_info.warehouse_pk,additional_warehouse_lookup,check_reservations=is_reservation_enabled(site_settings),checkout_lines=[line.line for line in checkout_lines],@@ -891,6 +893,7 @@ def _handle_allocations_of_order_lines(country_code,checkout_info.channel.slug,manager,+ checkout_info.delivery_method_info.warehouse_pk,additional_warehouse_lookup,check_reservations=reservation_enabled,checkout_lines=[line.line for line in checkout_lines],diff --git a/saleor/graphql/checkout/mutations/utils.py b/saleor/graphql/checkout/mutations/utils.pyindex 12a56b4c82..0009655572 100644--- a/saleor/graphql/checkout/mutations/utils.py+++ b/saleor/graphql/checkout/mutations/utils.py@@ -55,7 +55,6 @@ def clean_delivery_method(],) -> bool:"""Check if current shipping method is valid."""-if not method:# no shipping method was provided, it is validreturn Truediff --git a/saleor/graphql/checkout/tests/benchmark/conftest.py b/saleor/graphql/checkout/tests/benchmark/conftest.pyindex 6abf12d8ac..ec77f6ad8c 100644--- a/saleor/graphql/checkout/tests/benchmark/conftest.py+++ b/saleor/graphql/checkout/tests/benchmark/conftest.py@@ -2,6 +2,7 @@ import pytestfrom .....checkout import calculationsfrom .....checkout.fetch import fetch_checkout_info, fetch_checkout_lines+from .....checkout.models import CheckoutLinefrom .....checkout.utils import add_variant_to_checkout, add_voucher_to_checkoutfrom .....payment import ChargeStatus, TransactionKindfrom .....payment.models import Payment@@ -41,17 +42,18 @@ def checkout_with_variants(@pytest.fixture-def checkout_with_variants_for_cc(- checkout, stocks_for_cc, product_variant_list, product_with_two_variants-):- checkout_info = fetch_checkout_info(checkout, [], [], get_plugins_manager())-- add_variant_to_checkout(checkout_info, product_variant_list[0], 3)- add_variant_to_checkout(checkout_info, product_variant_list[1], 10)- add_variant_to_checkout(checkout_info, product_with_two_variants.variants.last(), 5)-- checkout.save()- return checkout+def checkout_with_variants_for_cc(checkout_for_cc, stocks_for_cc, product_variant_list):+ CheckoutLine.objects.bulk_create(+ [+ CheckoutLine(+ checkout=checkout_for_cc, variant=product_variant_list[0], quantity=1+ ),+ CheckoutLine(+ checkout=checkout_for_cc, variant=product_variant_list[1], quantity=1+ ),+ ]+ )+ return checkout_for_cc@pytest.fixture()diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.pyindex 668b5aaead..df778a8fad 100644--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py@@ -317,66 +317,6 @@ def test_create_checkout(assert checkout_counts + 1 == Checkout.objects.count()[email protected]_queries(autouse=False)-def test_create_checkout_for_cc(- api_client,- graphql_address_data,- channel_USD,- stocks_for_cc,- product_variant_list,- count_queries,-):- query = (- FRAGMENT_CHECKOUT_FOR_CC- + """- mutation CreateCheckout($checkoutInput: CheckoutCreateInput!) {- checkoutCreate(input: $checkoutInput) {- errors {- field- message- }- checkout {- ...Checkout- }- }- }- """- )- checkout_counts = Checkout.objects.count()- variables = {- "checkoutInput": {- "channel": channel_USD.slug,- "email": "[email protected]",- "shippingAddress": graphql_address_data,- "lines": [- {- "quantity": 1,- "variantId": Node.to_global_id(- "ProductVariant", stocks_for_cc[0].product_variant.pk- ),- },- {- "quantity": 2,- "variantId": Node.to_global_id(- "ProductVariant",- product_variant_list[0].pk,- ),- },- {- "quantity": 5,- "variantId": Node.to_global_id(- "ProductVariant",- product_variant_list[1].pk,- ),- },- ],- }- }- get_graphql_content(api_client.post_graphql(query, variables))- assert checkout_counts + 1 == Checkout.objects.count()--@pytest.mark.django_db@pytest.mark.count_queries(autouse=False)def test_create_checkout_with_reservations(@@ -513,8 +453,8 @@ def test_add_shipping_to_checkout(@pytest.mark.count_queries(autouse=False)def test_add_delivery_to_checkout(api_client,- checkout_with_shipping_address_for_cc,- warehouses_for_cc,+ checkout_with_item_for_cc,+ warehouse_for_cc,count_queries,):query = (@@ -538,8 +478,8 @@ def test_add_delivery_to_checkout(""")variables = {- "id": to_global_id_or_none(checkout_with_shipping_address_for_cc),- "deliveryMethodId": Node.to_global_id("Warehouse", warehouses_for_cc[1].pk),+ "id": to_global_id_or_none(checkout_with_item_for_cc),+ "deliveryMethodId": Node.to_global_id("Warehouse", warehouse_for_cc.pk),}response = get_graphql_content(api_client.post_graphql(query, variables))assert not response["data"]["checkoutDeliveryMethodUpdate"]["errors"]diff --git a/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py b/saleor/graphql/checkout/tests/mutations/test_checkout_complete.pyindex 9b0940a6a8..4cf8e3ffee 100644--- a/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py+++ b/saleor/graphql/checkout/tests/mutations/test_checkout_complete.py@@ -1763,23 +1763,25 @@ def test_checkout_complete_0_total_value().exists(), "Checkout should have been deleted"-def test_complete_checkout_for_click_and_collect(- api_client, checkout_with_item_for_cc, payment_dummy, address, warehouse_for_cc+def test_complete_checkout_for_local_click_and_collect(+ api_client,+ checkout_with_item_for_cc,+ payment_dummy,+ address,+ warehouse_for_cc,+ warehouse,):+ # givenorder_count = Order.objects.count()checkout = checkout_with_item_for_cc+ checkout.collection_point = warehouse_for_cc+ checkout.save(update_fields=["collection_point"])+variables = {"id": to_global_id_or_none(checkout),"redirectUrl": "https://www.example.com",}- checkout.billing_address = address- checkout.collection_point = warehouse_for_cc-- checkout.save(- update_fields=["shipping_address", "billing_address", "collection_point"]- )-manager = get_plugins_manager()lines, _ = fetch_checkout_lines(checkout)checkout_info = fetch_checkout_info(checkout, lines, [], manager)@@ -1795,8 +1797,16 @@ def test_complete_checkout_for_click_and_collect(payment.save()assert not payment.transactions.exists()+ assert len(lines) == 1+ variant = lines[0].variant+ # create another stock for the variant with the bigger quantity available+ Stock.objects.create(product_variant=variant, warehouse=warehouse, quantity=15)++ # whenresponse = api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)++ # thencontent = get_graphql_content(response)["data"]["checkoutComplete"]assert not content["errors"]@@ -1808,6 +1818,10 @@ def test_complete_checkout_for_click_and_collect(assert order.shipping_method is Noneassert order.shipping_address == warehouse_for_cc.addressassert order.shipping_price == zero_taxed_money(payment.currency)+ assert order.lines.count() == 1++ # ensure the allocation is made on the correct warehouse+ assert order.lines.first().allocations.first().stock.warehouse == warehouse_for_ccdef test_complete_checkout_raises_error_for_local_stock(diff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.pyindex 9643529402..4a6e0523e3 100644--- a/saleor/graphql/checkout/tests/test_checkout.py+++ b/saleor/graphql/checkout/tests/test_checkout.py@@ -776,6 +776,7 @@ def test_available_collection_points_for_preorders_and_regular_variants_in_checkdef test_checkout_available_collection_points_with_lines_avail_in_1_local_and_1_all(api_client, checkout_with_items_for_cc, stocks_for_cc):+ # givenexpected_collection_points = [{"address": {"streetAddress1": "Tęczowa 7"}, "name": "Warehouse4"},{"address": {"streetAddress1": "Tęczowa 7"}, "name": "Warehouse2"},@@ -783,7 +784,11 @@ def test_checkout_available_collection_points_with_lines_avail_in_1_local_and_1_query = GET_CHECKOUT_AVAILABLE_COLLECTION_POINTSvariables = {"id": to_global_id_or_none(checkout_with_items_for_cc)}++ # whenresponse = api_client.post_graphql(query, variables)++ # thencontent = get_graphql_content(response)received_collection_points = content["data"]["checkout"]["availableCollectionPoints"diff --git a/saleor/graphql/order/tests/test_order.py b/saleor/graphql/order/tests/test_order.pyindex 1b6f1acd33..3af4aaeeca 100644--- a/saleor/graphql/order/tests/test_order.py+++ b/saleor/graphql/order/tests/test_order.py@@ -7869,6 +7869,63 @@ def test_order_query_address_without_order_user(assert order["billingAddress"] is not None+QUERY_ORDER_LINE_STOCKS = """+query OrderQuery($id: ID!) {+ order(id: $id) {+ number+ lines {+ id+ quantity+ quantityFulfilled+ variant {+ id+ name+ sku+ stocks {+ warehouse {+ id+ name+ }+ }+ }+ }+ }+}+"""+++def test_query_order_line_stocks(+ staff_api_client,+ permission_manage_orders,+ order_with_lines_for_cc,+ warehouse,+ warehouse_for_cc,+):+ """Ensure that stocks for normal and click and collect warehouses are returned."""+ # given+ order = order_with_lines_for_cc+ variant = order.lines.first().variant+ variables = {"id": graphene.Node.to_global_id("Order", order.id)}++ # create the variant stock for not click and collect warehouse+ Stock.objects.create(warehouse=warehouse, product_variant=variant, quantity=10)++ # when+ response = staff_api_client.post_graphql(+ QUERY_ORDER_LINE_STOCKS, variables, permissions=(permission_manage_orders,)+ )++ # then+ content = get_graphql_content(response)+ order_data = content["data"]["order"]+ assert order_data+ assert len(order_data["lines"]) == 1+ assert {+ stock["warehouse"]["name"]+ for stock in order_data["lines"][0]["variant"]["stocks"]+ } == {warehouse.name, warehouse_for_cc.name}++MUTATION_ORDER_BULK_CANCEL = """mutation CancelManyOrders($ids: [ID!]!) {orderBulkCancel(ids: $ids) {diff --git a/saleor/graphql/warehouse/dataloaders.py b/saleor/graphql/warehouse/dataloaders.pyindex a43d999df7..61196db708 100644--- a/saleor/graphql/warehouse/dataloaders.py+++ b/saleor/graphql/warehouse/dataloaders.py@@ -10,6 +10,7 @@ from django.utils import timezonefrom ...channel.models import Channelfrom ...product.models import ProductVariantChannelListing+from ...warehouse import WarehouseClickAndCollectOptionfrom ...warehouse.models import (PreorderReservation,Reservation,@@ -231,9 +232,20 @@ class StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChannelLoader(warehouse__shipping_zones__countries__contains=country_code)if channel_slug:+ # click and collect warehouses don't have to be assigned to the shipping+ # zones, the others muststocks = stocks.filter(- warehouse__shipping_zones__channels__slug=channel_slug,- warehouse__channels__slug=channel_slug,+ Q(+ warehouse__shipping_zones__channels__slug=channel_slug,+ warehouse__channels__slug=channel_slug,+ )+ | Q(+ warehouse__channels__slug=channel_slug,+ warehouse__click_and_collect_option__in=[+ WarehouseClickAndCollectOption.LOCAL_STOCK,+ WarehouseClickAndCollectOption.ALL_WAREHOUSES,+ ],+ ))stocks = stocks.annotate_available_quantity()diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex 8985b206cc..eb5db90697 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -3738,6 +3738,7 @@ def order_with_lines_for_cc(warehouse_for_cc,channel_USD,customer_user,+ product_variant_list,):address = customer_user.default_billing_address.get_copy()@@ -3755,6 +3756,36 @@ def order_with_lines_for_cc(order.collection_point_name = warehouse_for_cc.nameorder.save()+ variant = product_variant_list[0]+ channel_listing = variant.channel_listings.get(channel=channel_USD)+ quantity = 1+ net = variant.get_price(product, [], channel_USD, channel_listing)+ currency = net.currency+ gross = Money(amount=net.amount * Decimal(1.23), currency=currency)+ unit_price = TaxedMoney(net=net, gross=gross)+ line = order.lines.create(+ product_name=str(variant.product),+ variant_name=str(variant),+ product_sku=variant.sku,+ product_variant_id=variant.get_global_id(),+ is_shipping_required=variant.is_shipping_required(),+ is_gift_card=variant.is_gift_card(),+ quantity=quantity,+ variant=variant,+ unit_price=unit_price,+ total_price=unit_price * quantity,+ undiscounted_unit_price=unit_price,+ undiscounted_total_price=unit_price * quantity,+ base_unit_price=unit_price.gross,+ undiscounted_base_unit_price=unit_price.gross,+ tax_rate=Decimal("0.23"),+ )+ Allocation.objects.create(+ order_line=line,+ stock=warehouse_for_cc.stock_set.filter(product_variant=variant).first(),+ quantity_allocated=line.quantity,+ )+recalculate_order(order)order.refresh_from_db()@@ -5471,14 +5502,14 @@ def warehouses_for_cc(address, shipping_zones, channel_USD):),])- for shipping_zone in shipping_zones:- shipping_zone.warehouses.add(*warehouses)+ # add to shipping zones only not click and collect warehouses+ warehouses[0].shipping_zones.add(*shipping_zones)channel_USD.warehouses.add(*warehouses)return warehouses@pytest.fixture-def warehouse_for_cc(address, product_variant_list, shipping_zones, channel_USD):+def warehouse_for_cc(address, product_variant_list, channel_USD):warehouse = Warehouse.objects.create(address=address.get_copy(),name="Local Warehouse",@@ -5487,7 +5518,6 @@ def warehouse_for_cc(address, product_variant_list, shipping_zones, channel_USD)is_private=False,click_and_collect_option=WarehouseClickAndCollectOption.LOCAL_STOCK,)- warehouse.shipping_zones.add(shipping_zones[0], shipping_zones[1])warehouse.channels.add(channel_USD)Stock.objects.bulk_create(@@ -5568,7 +5598,7 @@ def stocks_for_cc(warehouses_for_cc, product_variant_list, product_with_two_vari@pytest.fixture-def checkout_for_cc(channel_USD, customer_user, product_variant_list):+def checkout_for_cc(channel_USD, customer_user):return Checkout.objects.create(channel=channel_USD,billing_address=customer_user.default_billing_address,diff --git a/saleor/warehouse/availability.py b/saleor/warehouse/availability.pyindex 7bf9bf0152..6c6b8e6b20 100644--- a/saleor/warehouse/availability.py+++ b/saleor/warehouse/availability.py@@ -121,6 +121,7 @@ def check_stock_and_preorder_quantity_bulk(quantities: Iterable[int],channel_slug: str,global_quantity_limit: Optional[int],+ collection_point_pk: Optional[str] = None,additional_filter_lookup: Optional[Dict[str, Any]] = None,existing_lines: Optional[Iterable["CheckoutLineInfo"]] = None,replace: bool = False,@@ -144,6 +145,7 @@ def check_stock_and_preorder_quantity_bulk(stock_quantities,channel_slug,global_quantity_limit,+ collection_point_pk,additional_filter_lookup,existing_lines,replace,@@ -211,6 +213,7 @@ def check_stock_quantity_bulk(quantities: Iterable[int],channel_slug: str,global_quantity_limit: Optional[int],+ collection_point_pk: Optional[str] = None,additional_filter_lookup: Optional[Dict[str, Any]] = None,existing_lines: Iterable["CheckoutLineInfo"] = None,replace=False,@@ -224,12 +227,16 @@ def check_stock_quantity_bulk(if additional_filter_lookup is not None:filter_lookup.update(additional_filter_lookup)- all_variants_stocks = (- Stock.objects.for_channel_and_country(channel_slug, country_code)- .filter(**filter_lookup)- .annotate_available_quantity()+ # 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))+ all_variants_stocks = stocks.filter(**filter_lookup).annotate_available_quantity()+variant_stocks: Dict[int, List[Stock]] = defaultdict(list)for stock in all_variants_stocks:variant_stocks[stock.product_variant_id].append(stock)diff --git a/saleor/warehouse/management.py b/saleor/warehouse/management.pyindex f92c9ac44f..9c3aee9661 100644--- a/saleor/warehouse/management.py+++ b/saleor/warehouse/management.py@@ -40,6 +40,7 @@ def allocate_stocks(country_code: str,channel_slug: str,manager: PluginsManager,+ collection_point_pk: Optional[str] = None,additional_filter_lookup: Optional[Dict[str, Any]] = None,check_reservations: bool = False,checkout_lines: Optional[Iterable["CheckoutLine"]] = None,@@ -65,9 +66,16 @@ def allocate_stocks(if additional_filter_lookup is not None:filter_lookup.update(additional_filter_lookup)+ # 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)+ )+stocks = list(- Stock.objects.select_for_update(of=("self",))- .for_channel_and_country(channel_slug, country_code)+ stocks.select_for_update(of=("self",)).filter(**filter_lookup).order_by("pk").values("id", "product_variant", "pk", "quantity")diff --git a/saleor/warehouse/models.py b/saleor/warehouse/models.pyindex 54826e94b8..d5c9e00baf 100644--- a/saleor/warehouse/models.py+++ b/saleor/warehouse/models.py@@ -204,6 +204,24 @@ class StockQuerySet(models.QuerySet):))+ def for_channel_and_click_and_collect(self, channel_slug: str):+ """Return the stocks for a given channel for a click and collect.++ The click and collect warehouses don't have to be assigned to the shipping zones+ so all stocks for a given channel are returned.+ """+ WarehouseChannel = Channel.warehouses.through # type: ignore++ 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 for_channel_and_country(self, channel_slug: str, country_code: Optional[str] = None):