Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fix fetching available collection points (#16745)
Iga Karbowiakddc56dbc423d
diff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.pyindex 00091f151a..03c884621c 100644--- a/saleor/graphql/checkout/tests/test_checkout.py+++ b/saleor/graphql/checkout/tests/test_checkout.py@@ -5,7 +5,6 @@ from unittest import mockimport grapheneimport pytestfrom django.core.exceptions import ValidationError-from django.db.models import Sumfrom django.utils import timezonefrom django.utils.dateparse import parse_datetimefrom django_countries.fields import Country@@ -888,15 +887,27 @@ def test_available_collection_points_for_preorders_and_regular_variants_in_checkapi_client,staff_api_client,checkout_with_preorders_and_regular_variant,+ preorder_variant_with_end_date,warehouses_for_cc,):- expected_collection_points = [{"name": warehouses_for_cc[1].name}]+ # given+ warehouse = warehouses_for_cc[1]+ Stock.objects.create(+ warehouse=warehouse,+ product_variant=preorder_variant_with_end_date,+ quantity=10,+ )+ expected_collection_points = [{"name": warehouse.name}]++ # wneresponse = staff_api_client.post_graphql(QUERY_GET_ALL_COLLECTION_POINTS_FROM_CHECKOUT,variables={"id": to_global_id_or_none(checkout_with_preorders_and_regular_variant)},)++ # thenresponse_content = get_graphql_content(response)assert (expected_collection_points@@ -980,27 +991,77 @@ def test_checkout_available_collection_points_two_lines_for_same_checkout(assert all(c in expected_collection_points for c in received_collection_points)-def test_checkout_avail_collect_points_exceeded_quantity_shows_only_all_warehouse(- api_client, checkout_with_items_for_cc, stocks_for_cc+def test_checkout_avail_collect_points_only_all_warehouse_quantity_collected(+ api_client, checkout_with_item_for_cc, warehouses_for_cc):+ # givenquery = GET_CHECKOUT_AVAILABLE_COLLECTION_POINTS- line = checkout_with_items_for_cc.lines.last()- line.quantity = (- Stock.objects.filter(product_variant=line.variant)- .aggregate(total_quantity=Sum("quantity"))- .get("total_quantity")- + 1+ line = checkout_with_item_for_cc.lines.first()+ line.quantity = 5+ line.save(update_fields=["quantity"])++ all_warehouse = warehouses_for_cc[1]+ local_warehouse_1 = warehouses_for_cc[2]+ local_warehouse_2 = warehouses_for_cc[3]++ Stock.objects.bulk_create(+ [+ Stock(warehouse=all_warehouse, product_variant=line.variant, quantity=0),+ Stock(+ warehouse=local_warehouse_1, product_variant=line.variant, quantity=2+ ),+ Stock(+ warehouse=local_warehouse_2, product_variant=line.variant, quantity=4+ ),+ ])++ variables = {"id": to_global_id_or_none(checkout_with_item_for_cc)}++ # when+ response = api_client.post_graphql(query, variables)++ # then+ content = get_graphql_content(response)+ data = content["data"]["checkout"]++ assert data["availableCollectionPoints"] == [+ {"address": {"streetAddress1": "Tęczowa 7"}, "name": all_warehouse.name}+ ]+++def test_checkout_avail_collect_points_all_warehouse_quantity_from_disabled_warehouse(+ api_client, checkout_with_item_for_cc, warehouses_for_cc+):+ # given+ query = GET_CHECKOUT_AVAILABLE_COLLECTION_POINTS+ line = checkout_with_item_for_cc.lines.first()+ line.quantity = 5line.save(update_fields=["quantity"])- checkout_with_items_for_cc.refresh_from_db()- variables = {"id": to_global_id_or_none(checkout_with_items_for_cc)}+ all_warehouse = warehouses_for_cc[1]+ disabled_warehouse = warehouses_for_cc[0]++ Stock.objects.bulk_create(+ [+ Stock(warehouse=all_warehouse, product_variant=line.variant, quantity=0),+ Stock(+ warehouse=disabled_warehouse, product_variant=line.variant, quantity=10+ ),+ ]+ )++ variables = {"id": to_global_id_or_none(checkout_with_item_for_cc)}++ # whenresponse = api_client.post_graphql(query, variables)++ # thencontent = get_graphql_content(response)data = content["data"]["checkout"]assert data["availableCollectionPoints"] == [- {"address": {"streetAddress1": "Tęczowa 7"}, "name": "Warehouse2"}+ {"address": {"streetAddress1": "Tęczowa 7"}, "name": all_warehouse.name}]diff --git a/saleor/graphql/order/tests/queries/test_order.py b/saleor/graphql/order/tests/queries/test_order.pyindex 9bb37a33fa..bb7241bcd6 100644--- a/saleor/graphql/order/tests/queries/test_order.py+++ b/saleor/graphql/order/tests/queries/test_order.py@@ -20,7 +20,7 @@ from .....order.utils import (from .....payment import ChargeStatus, TransactionActionfrom .....payment.models import TransactionEvent, TransactionItemfrom .....shipping.models import ShippingMethod, ShippingMethodChannelListing-from .....warehouse.models import Warehouse+from .....warehouse.models import Stock, Warehousefrom ....order.enums import OrderAuthorizeStatusEnum, OrderChargeStatusEnumfrom ....payment.types import PaymentChargeStatusEnumfrom ....tests.utils import (@@ -363,7 +363,7 @@ def test_order_query(channel_id=order.channel_id,)expected_collection_points = Warehouse.objects.applicable_for_click_and_collect(- lines_qs=order.lines, channel_id=order.channel.id+ lines_qs=order.lines.all(), channel_id=order.channel.id)assert len(order_data["availableShippingMethods"]) == (expected_methods.count())@@ -495,6 +495,45 @@ def test_order_query_total_price_is_0()+def test_order_avail_collect_points_all_warehouse_quantity_from_disabled_warehouse(+ staff_api_client,+ permission_group_manage_orders,+ permission_group_manage_shipping,+ order_line,+ warehouses_for_cc,+):+ # given+ order = order_line.order+ permission_group_manage_orders.user_set.add(staff_api_client.user)+ permission_group_manage_shipping.user_set.add(staff_api_client.user)++ line = order.lines.first()+ line.quantity = 5+ line.save(update_fields=["quantity"])++ all_warehouse = warehouses_for_cc[1]+ disabled_warehouse = warehouses_for_cc[0]++ Stock.objects.bulk_create(+ [+ Stock(warehouse=all_warehouse, product_variant=line.variant, quantity=0),+ Stock(+ warehouse=disabled_warehouse, product_variant=line.variant, quantity=10+ ),+ ]+ )++ # when+ response = staff_api_client.post_graphql(ORDERS_FULL_QUERY)+ content = get_graphql_content(response)++ # then+ order_data = content["data"]["orders"]["edges"][0]["node"]+ order_line = order_data["lines"][0]+ assert len(order_data["availableCollectionPoints"]) == 1+ assert order_data["availableCollectionPoints"][0]["name"] == all_warehouse.name++def test_order_query_shows_non_draft_orders(staff_api_client, permission_group_manage_orders, orders):diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex 948902afa5..1043c61458 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -1452,6 +1452,7 @@ def order_generator(customer_user, channel_USD):private_metadata=private_metadata,checkout_token=checkout_token,status=status,+ undiscounted_base_shipping_price_amount=Decimal("0.0"),)if search_vector_class:search_vector = search_vector_class(@@ -4586,6 +4587,7 @@ def order_line_with_allocation_in_many_stocks(user=customer_user,channel=channel_USD,origin=OrderOrigin.CHECKOUT,+ undiscounted_base_shipping_price_amount=Decimal("0.0"),)product = variant.productdiff --git a/saleor/warehouse/migrations/0034_warehouse_click_and_collect_option_idx.py b/saleor/warehouse/migrations/0034_warehouse_click_and_collect_option_idx.pynew file mode 100644index 0000000000..52d895dfd5--- /dev/null+++ b/saleor/warehouse/migrations/0034_warehouse_click_and_collect_option_idx.py@@ -0,0 +1,22 @@+# Generated by Django 3.2.25 on 2024-09-19 10:44++import django.contrib.postgres.indexes+from django.contrib.postgres.operations import AddIndexConcurrently+from django.db import migrations+++class Migration(migrations.Migration):+ atomic = False++ dependencies = [+ ("warehouse", "0033_warehouse_external_reference"),+ ]++ operations = [+ AddIndexConcurrently(+ model_name="warehouse",+ index=django.contrib.postgres.indexes.BTreeIndex(+ fields=["click_and_collect_option"], name="click_and_collect_option_idx"+ ),+ ),+ ]diff --git a/saleor/warehouse/models.py b/saleor/warehouse/models.pyindex c18bc39371..fed0dd9f2d 100644--- a/saleor/warehouse/models.py+++ b/saleor/warehouse/models.py@@ -1,5 +1,6 @@import itertoolsimport uuid+from collections import defaultdictfrom collections.abc import Iterablefrom typing import (TYPE_CHECKING,@@ -10,8 +11,16 @@ from typing import (cast,)+from django.contrib.postgres.indexes import BTreeIndexfrom django.db import models-from django.db.models import Count, Exists, F, OuterRef, Prefetch, Q, Sum+from django.db.models import (+ Exists,+ F,+ OuterRef,+ Prefetch,+ Q,+ Sum,+)from django.db.models.expressions import Subqueryfrom django.db.models.functions import Coalescefrom django.db.models.query import QuerySet@@ -33,9 +42,16 @@ if TYPE_CHECKING:class WithAvailableQuantity(TypedDict):available_quantity: int+ class WithTotalAvailableQuantity(TypedDict):+ available_quantity: int+StockWithAvailableQuantity = WithAnnotations["Stock", WithAvailableQuantity]+ StockWithTotalAvailableQuantity = WithAnnotations[+ "Stock", WithTotalAvailableQuantity+ ]else:StockWithAvailableQuantity = "Stock"+ StockWithTotalAvailableQuantity = "Stock"class WarehouseQueryset(models.QuerySet["Warehouse"]):@@ -95,11 +111,37 @@ class WarehouseQueryset(models.QuerySet["Warehouse"]):):return self._for_channel_click_and_collect(channel_id)+ warehouses_for_channel = self.for_channel(channel_id)stocks_qs = Stock.objects.filter(- product_variant__id__in=lines_qs.values("variant_id"),- ).select_related("product_variant")+ product_variant_id__in=lines_qs.values("variant_id"),+ ).order_by()+ warehouses_with_stock_available = (+ warehouses_for_channel._cc_points_for_stocks(stocks_qs)+ .order_by()+ .only("id")+ )- return self._for_channel_lines_and_stocks(lines_qs, stocks_qs, channel_id)+ number_of_variants = len(+ set(lines_qs.order_by().values_list("variant_id", flat=True))+ )+ # Find out warehouses that can cover the order from a single warehouse+ warehouse_ids = []+ for warehouse in warehouses_with_stock_available:+ # the `warehouses_with_stock_available` contains prefetched stocks+ # that contains only stocks for the given variants (from the `stocks_qs`)+ if warehouse.stock_set.count() == number_of_variants:+ warehouse_ids.append(warehouse.id)++ lookup = Q(id__in=warehouse_ids)+ # if the stocks can cover the all variants, all C&C warehouses with+ # `ALL_WAREHOUSES` option should be returned, as there is an option+ # to ship the products to this point from another warehouse+ stocks_count = len(set(stocks_qs.values_list("product_variant_id", flat=True)))+ if stocks_count == number_of_variants:+ lookup |= Q(+ click_and_collect_option=WarehouseClickAndCollectOption.ALL_WAREHOUSES+ )+ return warehouses_for_channel.filter(lookup)def applicable_for_click_and_collect(self,@@ -109,59 +151,87 @@ class WarehouseQueryset(models.QuerySet["Warehouse"]):"""Return Warehouses which support click and collect.Note additional check of stocks quantity for given `CheckoutLine`s.- For `WarehouseClickAndCollect.LOCAL` all `CheckoutLine`s must be available from- a single warehouse.++ For WarehouseClickAndCollect.LOCAL, all CheckoutLine items must be available for+ collection from a single warehouse.+ For WarehouseClickAndCollect.ALL, each CheckoutLine item must be available+ for collection from any warehouse. Variants may be collected from different+ warehouses, and the quantity of a single variant can be split across multiple+ warehouses."""+ warehouse_cc_option_enum = WarehouseClickAndCollectOptionif all(line.variant.is_preorder_active() if line.variant else Falsefor line in lines_qs.select_related("variant").only("variant_id")):return self._for_channel_click_and_collect(channel_id)- lines_quantity = (- lines_qs.filter(variant_id=OuterRef("product_variant_id"))- .order_by("variant_id")- .values("variant_id")- .annotate(prod_sum=Sum("quantity"))- .values("prod_sum")- )+ # prepare the mapping of variant_id to total quantity of this variant+ # in the order+ line_variant_id_to_total_qty: dict[Optional[int], int] = defaultdict(int)+ for line in lines_qs:+ line_variant_id_to_total_qty[line.variant_id] += line.quantity++ number_of_variants = len(line_variant_id_to_total_qty)+ warehouses_for_channel = self.for_channel(channel_id)+ # Fetch the stocks for the variants in the orderstocks_qs = (Stock.objects.using(self.db)+ .filter(Exists(lines_qs.filter(variant_id=OuterRef("product_variant_id")))).annotate_available_quantity()- .annotate(line_quantity=F("available_quantity") - Subquery(lines_quantity))- .order_by("line_quantity")- .filter(- product_variant__id__in=lines_qs.values("variant_id"),- line_quantity__gte=0,- )- .select_related("product_variant"))- return self._for_channel_lines_and_stocks(lines_qs, stocks_qs, channel_id)+ stock_ids = []+ variant_id_to_total_stock_qty: dict[Optional[int], int] = defaultdict(int)+ # Filter out the stocks that have enough quantity to fulfill the order+ # Prepare the mapping of variant_id to the sum of total available quantity of+ # the given variant from all stocks+ for stock in stocks_qs:+ if (+ stock.available_quantity+ >= line_variant_id_to_total_qty[stock.product_variant_id]+ ):+ stock_ids.append(stock.id)+ variant_id_to_total_stock_qty[stock.product_variant_id] += (+ stock.available_quantity+ )- def _for_channel_lines_and_stocks(- self,- lines_qs: Union[QuerySet[CheckoutLine], QuerySet[OrderLine]],- stocks_qs: QuerySet["Stock"],- channel_id: int,- ) -> QuerySet["Warehouse"]:- warehouse_cc_option_enum = WarehouseClickAndCollectOption+ if stock_ids:+ # Find out warehouses that can cover the order from a single warehouse+ stocks = Stock.objects.filter(id__in=stock_ids)+ warehouses = warehouses_for_channel._cc_points_for_stocks(stocks).only("id")+ warehouse_ids = []+ for warehouse in warehouses:+ if warehouse.stock_set.count() == number_of_variants:+ warehouse_ids.append(warehouse.id)++ # if there is any valid local warehouse it means that it is possible+ # to ship products to any warehouse with `all warehouses` option+ if warehouse_ids:+ return warehouses_for_channel.filter(+ Q(id__in=warehouse_ids)+ | Q(+ click_and_collect_option=warehouse_cc_option_enum.ALL_WAREHOUSES+ )+ )- number_of_variants = (- lines_qs.order_by("variant_id").distinct("variant_id").count()- )+ # Check if the ordered line quantities can be fulfilled using stock from+ # different warehouses.+ if len(variant_id_to_total_stock_qty) == number_of_variants and all(+ variant_id_to_total_stock_qty[variant_id] >= variant_total_qty+ for variant_id, variant_total_qty in line_variant_id_to_total_qty.items()+ ):+ return warehouses_for_channel.filter(+ click_and_collect_option=warehouse_cc_option_enum.ALL_WAREHOUSES+ )+ return self.none()+ def _cc_points_for_stocks(self, stocks_qs: QuerySet["Stock"]):return (- self.for_channel(channel_id)+ self.filter(Exists(stocks_qs.filter(warehouse_id=OuterRef("id"))))+ .exclude(click_and_collect_option=WarehouseClickAndCollectOption.DISABLED).prefetch_related(Prefetch("stock_set", queryset=stocks_qs))- .filter(stock__in=stocks_qs)- .annotate(stock_num=Count("stock__id", distinct=True))- .filter(- Q(stock_num=number_of_variants)- & Q(click_and_collect_option=warehouse_cc_option_enum.LOCAL_STOCK)- | Q(click_and_collect_option=warehouse_cc_option_enum.ALL_WAREHOUSES)- ))def _for_channel_click_and_collect(self, channel_id: int) -> QuerySet["Warehouse"]:@@ -215,6 +285,13 @@ class Warehouse(ModelWithMetadata, ModelWithExternalReference):class Meta(ModelWithMetadata.Meta):ordering = ("-slug",)+ indexes = [+ *ModelWithMetadata.Meta.indexes,+ BTreeIndex( # type: ignore+ name="click_and_collect_option_idx",+ fields=["click_and_collect_option"],+ ),+ ]def __str__(self):return self.name@@ -232,15 +309,18 @@ class Warehouse(ModelWithMetadata, ModelWithExternalReference):class StockQuerySet(models.QuerySet["Stock"]):def annotate_available_quantity(self) -> QuerySet[StockWithAvailableQuantity]:+ allocation_quantity = (+ Allocation.objects.filter(stock_id=OuterRef("id"))+ .values("stock_id")+ .annotate(total_allocated_quantity=Sum("quantity_allocated"))+ .values("total_allocated_quantity")+ )return cast(QuerySet[StockWithAvailableQuantity],self.annotate(available_quantity=F("quantity")- Coalesce(- Sum(- "allocations__quantity_allocated",- filter=Q(allocations__quantity_allocated__gt=0),- ),+ Subquery(allocation_quantity),0,)),diff --git a/saleor/warehouse/tests/test_warehouse.py b/saleor/warehouse/tests/test_warehouse.pyindex f98d15c5bb..081c4ceb53 100644--- a/saleor/warehouse/tests/test_warehouse.py+++ b/saleor/warehouse/tests/test_warehouse.py@@ -1,47 +1,118 @@import pytest-from django.db.models import Sum+from django.db.models import Q, Sum+from ...order.models import OrderLinefrom .. import WarehouseClickAndCollectOptionfrom ..models import Stock, Warehousedef test_applicable_for_click_and_collect_finds_warehouse_with_all_and_local(- stocks_for_cc, checkout_with_items_for_cc, channel_USD+ stocks_for_cc, warehouses_for_cc, checkout_with_items_for_cc, channel_USD):- expected_number_of_warehouses = 2+ # given++ # all lines in local warehouse are available only in last CC+ local_warehouse_id = warehouses_for_cc[3].id++ # as there is a local warehouse from which the products can be shipped,+ # all warehouses with `ALL_WAREHOUSES` option should be returned as well+ expected_warehouses = Warehouse.objects.filter(+ Q(click_and_collect_option=WarehouseClickAndCollectOption.ALL_WAREHOUSES)+ | Q(id=local_warehouse_id)+ )lines = checkout_with_items_for_cc.lines.all()++ # whenresult = Warehouse.objects.applicable_for_click_and_collect(lines, channel_USD.id)- result.get(click_and_collect_option=WarehouseClickAndCollectOption.ALL_WAREHOUSES)- warehouse2 = result.get(- click_and_collect_option=WarehouseClickAndCollectOption.LOCAL_STOCK++ # then+ assert set(result.values_list("id", flat=True)) == set(+ expected_warehouses.values_list("id", flat=True))- assert result.count() == expected_number_of_warehouses- assert warehouse2.stock_set.count() == lines.count()++def test_applicable_for_click_and_collect_warehouse_with_all_not_available_in_channel(+ stocks_for_cc, warehouses_for_cc, checkout_with_items_for_cc, channel_USD+):+ # given+ # all lines in local warehouse are available only in last CC+ local_warehouse_id = warehouses_for_cc[3].id++ # remove the channel from the warehouse with `ALL_WAREHOUSES` option+ all_warehouse = warehouses_for_cc[1]+ all_warehouse.channels.remove(channel_USD)++ lines = checkout_with_items_for_cc.lines.all()++ # when+ result = Warehouse.objects.applicable_for_click_and_collect(lines, channel_USD.id)++ # then+ assert len(result) == 1+ assert result.first().id == local_warehouse_id+++def test_applicable_for_click_and_collect_quantity_exceeded(+ stocks_for_cc, checkout_with_items_for_cc, channel_USD+):+ # given+ lines = checkout_with_items_for_cc.lines.all()+ line = lines[2]+ # line quantity is above the available stock in all warehouses+ quantity_above_available_in_stock = (+ Stock.objects.filter(product_variant=line.variant)+ .aggregate(total_quantity=Sum("quantity"))+ .get("total_quantity")+ + 1+ )++ line.quantity = quantity_above_available_in_stock+ line.save(update_fields=["quantity"])+ checkout_with_items_for_cc.refresh_from_db()++ # when+ result = Warehouse.objects.applicable_for_click_and_collect(lines, channel_USD.id)++ # then+ assert result.count() == 0def test_applicable_for_click_and_collect_quantity_exceeded_for_local(stocks_for_cc, checkout_with_items_for_cc, channel_USD):+ # givenexpected_number_of_warehouses = Warehouse.objects.filter(click_and_collect_option=WarehouseClickAndCollectOption.ALL_WAREHOUSES).count()lines = checkout_with_items_for_cc.lines.all()line = lines[2]- quantity_above_available_in_stock = (+ # line quantity is above the available stock in local warehouse+ quantity_above_local_available_in_stock = (Stock.objects.filter(product_variant=line.variant)- .aggregate(total_quantity=Sum("quantity"))- .get("total_quantity")+ .order_by("-quantity")+ .first()+ .quantity+ 1)- line.quantity = quantity_above_available_in_stock+ line.quantity = quantity_above_local_available_in_stockline.save(update_fields=["quantity"])++ # ensure that the line quantity can be collected from different warehouses+ assert (+ Stock.objects.filter(product_variant=line.variant)+ .aggregate(total_quantity=Sum("quantity"))+ .get("total_quantity")+ ) > quantity_above_local_available_in_stock+checkout_with_items_for_cc.refresh_from_db()+ # whenresult = Warehouse.objects.applicable_for_click_and_collect(lines, channel_USD.id)++ # thenassert result.count() == expected_number_of_warehouseswith pytest.raises(Warehouse.DoesNotExist):result.get(click_and_collect_option=WarehouseClickAndCollectOption.LOCAL_STOCK)@@ -50,53 +121,59 @@ def test_applicable_for_click_and_collect_quantity_exceeded_for_local(def test_applicable_for_click_and_collect_for_one_line_two_local_warehouses(stocks_for_cc, checkout_with_item_for_cc, channel_USD):- expected_total_number_of_warehouses = Warehouse.objects.exclude(- click_and_collect_option=WarehouseClickAndCollectOption.DISABLED- ).count()- expected_total_number_of_local_warehouses = Warehouse.objects.filter(- click_and_collect_option=WarehouseClickAndCollectOption.LOCAL_STOCK- ).count()- expected_total_number_of_all_warehouses = (- expected_total_number_of_warehouses - expected_total_number_of_local_warehouses+ # given++ # line is available in two local warehouses,+ # so also in warehouse with `ALL_WAREHOUSES` option, as the product can be shipped+ # from one of the locals+ warehouse_ids = set(+ Stock.objects.filter(+ Q(product_variant=checkout_with_item_for_cc.lines.first().variant)+ & Q(+ warehouse__click_and_collect_option=WarehouseClickAndCollectOption.LOCAL_STOCK+ )+ | Q(+ warehouse__click_and_collect_option=WarehouseClickAndCollectOption.ALL_WAREHOUSES+ )+ ).values_list("warehouse_id", flat=True))lines = checkout_with_item_for_cc.lines.all()++ # whenresult = Warehouse.objects.applicable_for_click_and_collect(lines, channel_USD.id)- assert result.count() == expected_total_number_of_warehouses- assert (- result.filter(- click_and_collect_option=WarehouseClickAndCollectOption.LOCAL_STOCK- ).count()- == expected_total_number_of_local_warehouses- )- assert (- result.filter(- click_and_collect_option=WarehouseClickAndCollectOption.ALL_WAREHOUSES- ).count()- == expected_total_number_of_all_warehouses- )++ # then+ assert result.count() == len(warehouse_ids)+ assert set(result.values_list("id", flat=True)) == warehouse_idsdef test_applicable_for_click_and_collect_does_not_show_warehouses_with_empty_stocks(stocks_for_cc, checkout_with_items_for_cc, channel_USD):- expected_total_number_of_warehouses = 1- reduced_stock_quantity = 0+ # given+ line_with_empty_stock = checkout_with_items_for_cc.lines.last()- lines = checkout_with_items_for_cc.lines.all()- stock = Stock.objects.filter(+ stocks = Stock.objects.filter(product_variant=line_with_empty_stock.variant)+ empty_stock = stocks.filter(warehouse__click_and_collect_option=WarehouseClickAndCollectOption.LOCAL_STOCK- ).last()- stock.quantity = reduced_stock_quantity- stock.save(update_fields=["quantity"])+ ).first()+ empty_stock.quantity = 0+ empty_stock.save(update_fields=["quantity"])- result = Warehouse.objects.applicable_for_click_and_collect(lines, channel_USD.id)- assert result.count() == expected_total_number_of_warehouses- assert (- result.first().click_and_collect_option- == WarehouseClickAndCollectOption.ALL_WAREHOUSES+ warehouse_ids = set(+ stocks.exclude(id=empty_stock.id).values_list("warehouse_id", flat=True))+ lines = checkout_with_items_for_cc.lines.all()++ # when+ result = Warehouse.objects.applicable_for_click_and_collect(lines, channel_USD.id)++ # then+ assert result.count() == len(warehouse_ids)+ assert set(result.values_list("id", flat=True)) == warehouse_ids+def test_applicable_for_click_and_collect_additional_stock_does_not_change_availbility(stocks_for_cc,@@ -105,6 +182,7 @@ def test_applicable_for_click_and_collect_additional_stock_does_not_change_availproduct_variant_list,channel_USD,):+ # givenexpected_total_number_of_stocks = 5expected_total_number_of_warehouses = 2expected_number_of_checkout_lines = 3@@ -114,8 +192,10 @@ def test_applicable_for_click_and_collect_additional_stock_does_not_change_avail)lines = checkout_with_items_for_cc.lines.all()+ # whenresult = Warehouse.objects.applicable_for_click_and_collect(lines, channel_USD.id)+ # thenassert result.count() == expected_total_number_of_warehousesresult.get(click_and_collect_option=WarehouseClickAndCollectOption.ALL_WAREHOUSES)warehouse = result.get(@@ -143,9 +223,587 @@ def test_applicable_for_click_and_collect_returns_empty_collection_if_no_channeldef test_applicable_for_click_and_collect_returns_empty_collection_if_different_channel(warehouse_for_cc, checkout_with_items_for_cc, channel_PLN):+ # givenlines = checkout_with_items_for_cc.lines.all()warehouse_for_cc.shipping_zones.filter(name="Poland").delete()+ # whenresult = Warehouse.objects.applicable_for_click_and_collect(lines, channel_PLN.id)+ # thenassert not result+++def test_applicable_for_click_and_collect_stock_only_in_local_all_and_local_returned(+ warehouses_for_cc, checkout_with_item_for_cc, channel_USD+):+ """Esnure the `ALL` warehouse is returned when the stock is availble in local one.++ When the stock is available only in local warehouse, but not+ available in the warehouse with `ALL_WAREHOUSES` option, both warehouses+ are returned.+ """+ # given+ line = checkout_with_item_for_cc.lines.first()++ all_warehouse = warehouses_for_cc[1]+ local_warehouse = warehouses_for_cc[2]++ Stock.objects.bulk_create(+ [+ Stock(warehouse=all_warehouse, product_variant=line.variant, quantity=0),+ Stock(warehouse=local_warehouse, product_variant=line.variant, quantity=10),+ ]+ )++ lines = checkout_with_item_for_cc.lines.all()++ # when+ result = Warehouse.objects.applicable_for_click_and_collect(lines, channel_USD.id)++ # then+ assert len(result) == 2+ assert set(result.values_list("id", flat=True)) == {+ all_warehouse.id,+ local_warehouse.id,+ }+++def test_applicable_for_click_and_collect_stock_only_in_warehouse_with_all_option(+ warehouses_for_cc, checkout_with_item_for_cc, channel_USD+):+ """Ensure that only `ALL` warehouse is returned when stock is available only there.++ When the stock is available only in warehouse with `ALL_WAREHOUSES`+ click and collect option, only this one is returned.+ """+ # given+ line = checkout_with_item_for_cc.lines.first()++ all_warehouse = warehouses_for_cc[1]+ local_warehouse = warehouses_for_cc[2]++ Stock.objects.bulk_create(+ [+ Stock(warehouse=all_warehouse, product_variant=line.variant, quantity=10),+ Stock(warehouse=local_warehouse, product_variant=line.variant, quantity=0),+ ]+ )++ lines = checkout_with_item_for_cc.lines.all()++ # when+ result = Warehouse.objects.applicable_for_click_and_collect(lines, channel_USD.id)++ # then+ assert len(result) == 1+ assert result.first().id == all_warehouse.id+++def test_applicable_for_click_and_collect_all_returned_stock_collected_from_local(+ warehouses_for_cc, checkout_with_item_for_cc, channel_USD+):+ """Ensure that stocks can be collected from local warehouse to `ALL` warehouse.++ When the stock is not available in warehouse with `ALL_WAREHOUSES`+ click and collect option, but can be collected from the different warehouses,+ the warehouse with `ALL_WAREHOUSES` click and collect option is returned.+ """+ # given+ line = checkout_with_item_for_cc.lines.first()+ line.quantity = 5+ line.save(update_fields=["quantity"])++ all_warehouse = warehouses_for_cc[1]+ local_warehouse_1 = warehouses_for_cc[2]+ local_warehouse_2 = warehouses_for_cc[3]++ Stock.objects.bulk_create(+ [+ Stock(warehouse=all_warehouse, product_variant=line.variant, quantity=0),+ Stock(+ warehouse=local_warehouse_1, product_variant=line.variant, quantity=2+ ),+ Stock(+ warehouse=local_warehouse_2, product_variant=line.variant, quantity=4+ ),+ ]+ )++ lines = checkout_with_item_for_cc.lines.all()++ # when+ result = Warehouse.objects.applicable_for_click_and_collect(lines, channel_USD.id)++ # then+ assert len(result) == 1+ assert result.first().id == all_warehouse.id+++def test_applicable_for_click_and_collect_stock_from_local_but_not_all_in_channel(+ warehouses_for_cc, checkout_with_item_for_cc, channel_USD+):+ """Ensure the warehouse isn't returned when it's not available in the given channel.++ When the stock is not available in warehouse with `ALL_WAREHOUSES`+ click and collect option, but can be collected from the different warehouses,+ and the all warehouse is not available in given channel, the warehouse+ is not returned.+ """+ # given+ line = checkout_with_item_for_cc.lines.first()+ line.quantity = 5+ line.save(update_fields=["quantity"])++ all_warehouse = warehouses_for_cc[1]+ local_warehouse_1 = warehouses_for_cc[2]+ local_warehouse_2 = warehouses_for_cc[3]++ Stock.objects.bulk_create(+ [+ Stock(warehouse=all_warehouse, product_variant=line.variant, quantity=0),+ Stock(+ warehouse=local_warehouse_1, product_variant=line.variant, quantity=2+ ),+ Stock(+ warehouse=local_warehouse_2, product_variant=line.variant, quantity=4+ ),+ ]+ )++ all_warehouse.channels.remove(channel_USD)+ lines = checkout_with_item_for_cc.lines.all()++ # when+ result = Warehouse.objects.applicable_for_click_and_collect(lines, channel_USD.id)++ # then+ assert len(result) == 0+++def test_applicable_for_click_and_collect_all_returned_stock_from_disabled_warehouse(+ warehouses_for_cc, checkout_with_item_for_cc, channel_USD+):+ """Ensure that stocks can be collected from disabled warehouse to `ALL` warehouse.++ When the stock is not available in warehouse with `ALL_WAREHOUSES`+ click and collect option, but can be collected from the different warehouse+ with `DISABLED` click and collect option, the warehouse with `ALL_WAREHOUSES`+ option is returned.+ """+ # given+ line = checkout_with_item_for_cc.lines.first()++ all_warehouse = warehouses_for_cc[1]+ disabled_warehouse = warehouses_for_cc[0]++ Stock.objects.bulk_create(+ [+ Stock(warehouse=all_warehouse, product_variant=line.variant, quantity=0),+ Stock(+ warehouse=disabled_warehouse, product_variant=line.variant, quantity=10+ ),+ ]+ )++ lines = checkout_with_item_for_cc.lines.all()++ # when+ result = Warehouse.objects.applicable_for_click_and_collect(lines, channel_USD.id)++ # then+ assert len(result) == 1+ assert result.first().id == all_warehouse.id+++def test_applicable_for_click_and_collect_stock_collected_from_different_warehouses(+ warehouses_for_cc, checkout_with_items_for_cc, channel_USD+):+ """Ensure that stock can be collected from mutliple different warehouses.++ When the all stock is not available in warehouse with+ `ALL_WAREHOUSES` click and collect option, but can be collected from the+ different warehouses, the warehouse with `ALL_WAREHOUSES` click and collect+ option is returned, only when the stock for all products can be collected.+ """+ # given+ line_1, line_2, line_3 = checkout_with_items_for_cc.lines.all()+ line_1.quantity = 5+ line_2.quantity = 3+ line_3.quantity = 7+ OrderLine.objects.bulk_update([line_1, line_2, line_3], ["quantity"])++ all_warehouse = warehouses_for_cc[1]+ local_warehouse_1 = warehouses_for_cc[2]+ local_warehouse_2 = warehouses_for_cc[3]+ disabled_warehouse = warehouses_for_cc[0]++ Stock.objects.bulk_create(+ [+ Stock(warehouse=all_warehouse, product_variant=line_1.variant, quantity=0),+ Stock(warehouse=all_warehouse, product_variant=line_2.variant, quantity=3),+ Stock(warehouse=all_warehouse, product_variant=line_3.variant, quantity=0),+ Stock(+ warehouse=local_warehouse_1, product_variant=line_1.variant, quantity=3+ ),+ Stock(+ warehouse=local_warehouse_2, product_variant=line_1.variant, quantity=4+ ),+ Stock(+ warehouse=disabled_warehouse, product_variant=line_3.variant, quantity=5+ ),+ Stock(+ warehouse=local_warehouse_2, product_variant=line_3.variant, quantity=3+ ),+ ]+ )++ lines = checkout_with_items_for_cc.lines.all()++ # when+ result = Warehouse.objects.applicable_for_click_and_collect(lines, channel_USD.id)++ # then+ assert len(result) == 1+ assert result.first().id == all_warehouse.id+++def test_applicable_for_click_and_collect_empty_result_when_not_all_products_available(+ warehouses_for_cc, checkout_with_items_for_cc, channel_USD+):+ """Ensure that stocks for all lines must be covered to return the warehouse.++ When there is no enough stock for at least one product, no warehouse+ is returned.+ """+ # given+ line_1, line_2, line_3 = checkout_with_items_for_cc.lines.all()+ line_1.quantity = 5+ line_2.quantity = 3+ line_3.quantity = 7+ OrderLine.objects.bulk_update([line_1, line_2, line_3], ["quantity"])++ all_warehouse = warehouses_for_cc[1]+ local_warehouse_1 = warehouses_for_cc[2]+ local_warehouse_2 = warehouses_for_cc[3]+ disabled_warehouse = warehouses_for_cc[0]++ Stock.objects.bulk_create(+ [+ Stock(warehouse=all_warehouse, product_variant=line_1.variant, quantity=0),+ Stock(warehouse=all_warehouse, product_variant=line_2.variant, quantity=0),+ Stock(warehouse=all_warehouse, product_variant=line_3.variant, quantity=0),+ Stock(+ warehouse=local_warehouse_1, product_variant=line_1.variant, quantity=3+ ),+ Stock(+ warehouse=local_warehouse_2, product_variant=line_1.variant, quantity=4+ ),+ Stock(+ warehouse=disabled_warehouse, product_variant=line_3.variant, quantity=5+ ),+ Stock(+ warehouse=local_warehouse_2, product_variant=line_3.variant, quantity=3+ ),+ ]+ )++ lines = checkout_with_items_for_cc.lines.all()++ # when+ result = Warehouse.objects.applicable_for_click_and_collect(lines, channel_USD.id)++ # then+ assert len(result) == 0+++def test_applicable_for_click_and_collect_additional_stocks(+ warehouses_for_cc, checkout_with_items_for_cc, channel_USD, variant+):+ """Ensure that stock of another variant will be not taken into account.++ When the warehouse has additional stock for another variant, and the warehouse stock+ number is equal to the number of variants, the warehouse is not returned.+ """+ # given+ line_1, line_2, line_3 = checkout_with_items_for_cc.lines.all()+ line_1.quantity = 5+ line_2.quantity = 3+ line_3.quantity = 7+ OrderLine.objects.bulk_update([line_1, line_2, line_3], ["quantity"])++ all_warehouse = warehouses_for_cc[1]+ local_warehouse_1 = warehouses_for_cc[2]+ local_warehouse_2 = warehouses_for_cc[3]+ disabled_warehouse = warehouses_for_cc[0]++ Stock.objects.bulk_create(+ [+ Stock(warehouse=all_warehouse, product_variant=line_1.variant, quantity=0),+ Stock(warehouse=all_warehouse, product_variant=line_2.variant, quantity=3),+ Stock(warehouse=all_warehouse, product_variant=line_3.variant, quantity=0),+ Stock(+ warehouse=local_warehouse_1, product_variant=line_1.variant, quantity=3+ ),+ Stock(+ warehouse=local_warehouse_2, product_variant=line_1.variant, quantity=4+ ),+ Stock(+ warehouse=disabled_warehouse, product_variant=line_3.variant, quantity=5+ ),+ Stock(+ warehouse=local_warehouse_2, product_variant=line_3.variant, quantity=3+ ),+ # stocks for different variant, causes that the number of stocks for+ # local_warehouse_2 is equal to the number of variants;+ # should not be taken into consideration, and local_warehouse_2 should+ # not be returned+ Stock(warehouse=local_warehouse_2, product_variant=variant, quantity=3),+ ]+ )++ lines = checkout_with_items_for_cc.lines.all()++ # when+ result = Warehouse.objects.applicable_for_click_and_collect(lines, channel_USD.id)++ # then+ assert len(result) == 1+ assert result.first().id == all_warehouse.id+++def test_applicable_for_click_and_collect_no_quantity_check_stock_available(+ warehouses_for_cc, checkout_with_item_for_cc, channel_USD+):+ """Ensure that when the stock exists in the warehouse, the warehouse is returned."""+ # given+ line = checkout_with_item_for_cc.lines.first()+ line.quantity = 10+ line.save(update_fields=["quantity"])++ all_warehouse = warehouses_for_cc[1]+ local_warehouse = warehouses_for_cc[2]++ Stock.objects.bulk_create(+ [+ Stock(warehouse=all_warehouse, product_variant=line.variant, quantity=0),+ Stock(warehouse=local_warehouse, product_variant=line.variant, quantity=1),+ ]+ )++ lines = checkout_with_item_for_cc.lines.all()++ # when+ result = Warehouse.objects.applicable_for_click_and_collect_no_quantity_check(+ lines, channel_USD.id+ )++ # then+ assert len(result) == 2+ assert set(result.values_list("id", flat=True)) == {+ all_warehouse.id,+ local_warehouse.id,+ }+++def test_applicable_for_click_and_collect_no_quantity_check_stock_available_in_local(+ warehouses_for_cc, checkout_with_item_for_cc, channel_USD+):+ """Ensure that the stock for `ALL` warehouse can be collected from local one.++ When the stock is available in the local warehouse, also+ the warehouse with `ALL_WAREHOUSES` option is returned.+ """+ # given+ line = checkout_with_item_for_cc.lines.first()+ line.quantity = 10+ line.save(update_fields=["quantity"])++ all_warehouse = warehouses_for_cc[1]+ local_warehouse = warehouses_for_cc[2]++ Stock.objects.bulk_create(+ [+ Stock(warehouse=local_warehouse, product_variant=line.variant, quantity=1),+ ]+ )++ lines = checkout_with_item_for_cc.lines.all()++ # when+ result = Warehouse.objects.applicable_for_click_and_collect_no_quantity_check(+ lines, channel_USD.id+ )++ # then+ assert len(result) == 2+ assert set(result.values_list("id", flat=True)) == {+ all_warehouse.id,+ local_warehouse.id,+ }+++def test_applicable_for_click_and_collect_no_quantity_check_stock_available_in_disabled(+ warehouses_for_cc, checkout_with_item_for_cc, channel_USD+):+ """Ensure that the stock for `ALL` warehouse can be collected from disabled one.++ When the stock is available in the warehouse with `DISABLED`+ click and collect option, also the warehouse with `ALL_WAREHOUSES`+ option is returned.+ """+ # given+ line = checkout_with_item_for_cc.lines.first()+ line.quantity = 10+ line.save(update_fields=["quantity"])++ all_warehouse = warehouses_for_cc[1]+ disabled_warehouse = warehouses_for_cc[0]++ Stock.objects.bulk_create(+ [+ Stock(+ warehouse=disabled_warehouse, product_variant=line.variant, quantity=1+ ),+ ]+ )++ lines = checkout_with_item_for_cc.lines.all()++ # when+ result = Warehouse.objects.applicable_for_click_and_collect_no_quantity_check(+ lines, channel_USD.id+ )++ # then+ assert len(result) == 1+ assert result.first().id == all_warehouse.id+++def test_applicable_for_click_and_collect_no_quantity_check_no_stocks(+ warehouses_for_cc, checkout_with_item_for_cc, channel_USD+):+ """Ensure that when there are no stocks, no warehouse is returned."""+ # given+ line = checkout_with_item_for_cc.lines.first()+ line.quantity = 10+ line.save(update_fields=["quantity"])++ lines = checkout_with_item_for_cc.lines.all()++ # when+ result = Warehouse.objects.applicable_for_click_and_collect_no_quantity_check(+ lines, channel_USD.id+ )++ # then+ assert len(result) == 0+++def test_applicable_for_click_and_collect_no_quantity_check_one_line_without_stock(+ warehouses_for_cc, checkout_with_items_for_cc, channel_USD+):+ """Ensure that when there are no stocks for all lines, no warehouse is returned."""+ # given+ line_1, line_2, line_3 = checkout_with_items_for_cc.lines.all()++ all_warehouse = warehouses_for_cc[1]+ local_warehouse = warehouses_for_cc[2]++ Stock.objects.bulk_create(+ [+ Stock(+ warehouse=local_warehouse,+ product_variant=line_1.variant,+ quantity=0,+ ),+ Stock(warehouse=all_warehouse, product_variant=line_2.variant, quantity=0),+ ]+ )+ lines = checkout_with_items_for_cc.lines.all()++ # when+ result = Warehouse.objects.applicable_for_click_and_collect_no_quantity_check(+ lines, channel_USD.id+ )++ # then+ assert len(result) == 0+++def test_applicable_for_click_and_collect_no_quantity_check_no_channels(+ warehouses_for_cc, checkout_with_item_for_cc, channel_USD+):+ """Ensure the warehouse isn't returned when it's not available in the given channel."""+ # given+ line = checkout_with_item_for_cc.lines.first()+ line.quantity = 10+ line.save(update_fields=["quantity"])++ all_warehouse = warehouses_for_cc[1]+ local_warehouse = warehouses_for_cc[2]++ Stock.objects.bulk_create(+ [+ Stock(warehouse=local_warehouse, product_variant=line.variant, quantity=1),+ ]+ )++ all_warehouse.channels.remove(channel_USD)+ lines = checkout_with_item_for_cc.lines.all()++ # when+ result = Warehouse.objects.applicable_for_click_and_collect_no_quantity_check(+ lines, channel_USD.id+ )++ # then+ assert len(result) == 1+ assert result.first().id == local_warehouse.id+++def test_applicable_for_click_and_collect_no_quantity_check_additional_stock(+ warehouses_for_cc, checkout_with_items_for_cc, channel_USD, variant+):+ """Ensure that stock of another variant will be not taken into account.++ When the warehouse has additional stock for another variant, and the warehouse stock+ number is equal to the number of variants, the warehouse is not returned.+ """+ # given+ line_1, line_2, line_3 = checkout_with_items_for_cc.lines.all()++ all_warehouse = warehouses_for_cc[1]+ local_warehouse_1 = warehouses_for_cc[2]+ local_warehouse_2 = warehouses_for_cc[3]++ Stock.objects.bulk_create(+ [+ Stock(warehouse=all_warehouse, product_variant=line_1.variant, quantity=1),+ Stock(+ warehouse=local_warehouse_1, product_variant=line_1.variant, quantity=1+ ),+ Stock(+ warehouse=local_warehouse_1, product_variant=line_2.variant, quantity=1+ ),+ Stock(+ warehouse=local_warehouse_2, product_variant=line_3.variant, quantity=1+ ),+ # stock for different variant, causes that the number of stocks for+ # local_warehouse_1 is equal to the number of variants;+ # should not be taken into consideration, and local_warehouse_2 should+ # not be returned+ Stock(warehouse=local_warehouse_1, product_variant=variant, quantity=1),+ ]+ )++ lines = checkout_with_items_for_cc.lines.all()++ # when+ result = Warehouse.objects.applicable_for_click_and_collect_no_quantity_check(+ lines, channel_USD.id+ )++ # then+ assert len(result) == 1+ assert result.first().id == all_warehouse.id