Skip to content

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

Improve click & collect and stock allocation (#10043)

Iga Karbowiak133b176a7983
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e902c2387d..fb5fd5587f 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -12,6 +12,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Added `OrderFilter.numbers` filter - #9967 by @SzymJ
- Added `metadata` fields to `OrderLine` and `CheckoutLine` models - #10040 by @SzymJ
- Improve checkout total base calculations - #10048 by @IKarbowiak
+- Improve click & collect and stock allocation - #10043 by @IKarbowiak
#### Saleor Apps
- Add webhooks `PAGE_TYPE_CREATED`, `PAGE_TYPE_UPDATED` and `PAGE_TYPE_DELETED` - #9859 by @SzymJ
diff --git a/conftest.py b/conftest.py
index 56b6a8add6..c06c726f48 100644
--- a/conftest.py
+++ b/conftest.py
@@ -13,6 +13,7 @@ pytest_plugins = [
"saleor.plugins.tests.fixtures",
"saleor.graphql.tests.fixtures",
"saleor.graphql.channel.tests.fixtures",
+ "saleor.graphql.channel.tests.benchmark.fixtures",
"saleor.graphql.account.tests.benchmark.fixtures",
"saleor.graphql.order.tests.benchmark.fixtures",
"saleor.graphql.giftcard.tests.benchmark.fixtures",
diff --git a/saleor/checkout/fetch.py b/saleor/checkout/fetch.py
index ada060af21..0dfccdfbf5 100644
--- a/saleor/checkout/fetch.py
+++ b/saleor/checkout/fetch.py
@@ -576,11 +576,7 @@ def update_delivery_method_lists_for_checkout_info(
_resolve_all_shipping_methods
) # type: ignore
checkout_info.valid_pick_up_points = SimpleLazyObject(
- lambda: (
- get_valid_collection_points_for_checkout_info(
- shipping_address, lines, checkout_info
- )
- )
+ lambda: (get_valid_collection_points_for_checkout_info(lines, checkout_info))
) # type: ignore
update_checkout_info_delivery_method_info(
checkout_info,
@@ -591,19 +587,13 @@ def update_delivery_method_lists_for_checkout_info(
def get_valid_collection_points_for_checkout_info(
- shipping_address: Optional["Address"],
lines: Iterable[CheckoutLineInfo],
checkout_info: CheckoutInfo,
):
from .utils import get_valid_collection_points_for_checkout
- if shipping_address:
- country_code = shipping_address.country.code
- else:
- country_code = checkout_info.channel.default_country.code
-
valid_collection_points = get_valid_collection_points_for_checkout(
- lines, country_code=country_code, quantity_check=False
+ lines, checkout_info.channel.id, quantity_check=False
)
return SimpleLazyObject(lambda: list(valid_collection_points))
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index a88ec7c436..eff24d0b30 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -51,6 +51,7 @@ if TYPE_CHECKING:
from prices import TaxedMoney
from ..account.models import Address
+ from ..channel.models import Channel
from ..order.models import Order
from .fetch import CheckoutInfo, CheckoutLineInfo
@@ -724,7 +725,7 @@ def get_valid_internal_shipping_methods_for_checkout(
def get_valid_collection_points_for_checkout(
lines: Iterable["CheckoutLineInfo"],
- country_code: Optional[str] = None,
+ channel_id: int,
quantity_check: bool = True,
):
"""Return a collection of `Warehouse`s that can be used as a collection point.
@@ -733,19 +734,17 @@ def get_valid_collection_points_for_checkout(
be validated in further steps (checkout completion) in order to raise
'InsufficientProductStock' error instead of 'InvalidShippingError'.
"""
-
if not is_shipping_required(lines):
return []
- if not country_code:
- return []
+
line_ids = [line_info.line.id for line_info in lines]
lines = CheckoutLine.objects.filter(id__in=line_ids)
return (
- Warehouse.objects.applicable_for_click_and_collect(lines, country_code)
+ Warehouse.objects.applicable_for_click_and_collect(lines, channel_id)
if quantity_check
else Warehouse.objects.applicable_for_click_and_collect_no_quantity_check(
- lines, country_code
+ lines, channel_id
)
)
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.py
index 27316855b0..dca0f9a2aa 100644
--- a/saleor/core/utils/random_data.py
+++ b/saleor/core/utils/random_data.py
@@ -1339,6 +1339,7 @@ def create_shipping_zones():
def create_additional_cc_warehouse():
+ channel = Channel.objects.first()
shipping_zone = ShippingZone.objects.first()
warehouse_name = f"{shipping_zone.name} for click and collect"
warehouse, _ = Warehouse.objects.update_or_create(
@@ -1351,9 +1352,11 @@ def create_additional_cc_warehouse():
},
)
warehouse.shipping_zones.add(shipping_zone)
+ warehouse.channels.add(channel)
def create_warehouses():
+ channels = Channel.objects.all()
for shipping_zone in ShippingZone.objects.all():
shipping_zone_name = shipping_zone.name
is_private = random.choice([True, False])
@@ -1376,6 +1379,7 @@ def create_warehouses():
},
)
warehouse.shipping_zones.add(shipping_zone)
+ warehouse.channels.add(*channels)
create_additional_cc_warehouse()
diff --git a/saleor/giftcard/utils.py b/saleor/giftcard/utils.py
index 31ff2654b2..d73267a5b0 100644
--- a/saleor/giftcard/utils.py
+++ b/saleor/giftcard/utils.py
@@ -130,7 +130,7 @@ def fulfill_gift_card_lines(
{"order_line": line, "quantity": quantity}
)
else:
- stock = line.variant.stocks.for_channel(channel_slug).first()
+ stock = line.variant.stocks.for_channel_and_country(channel_slug).first()
if not stock:
raise GiftCardNotApplicable(
message="Lack of gift card stock for checkout channel.",
diff --git a/saleor/graphql/channel/dataloaders.py b/saleor/graphql/channel/dataloaders.py
index 4e63bf0aff..4fe22a5ad4 100644
--- a/saleor/graphql/channel/dataloaders.py
+++ b/saleor/graphql/channel/dataloaders.py
@@ -1,14 +1,10 @@
-from collections import defaultdict
-
from django.db.models import Exists, OuterRef
from ...channel.models import Channel
from ...order.models import Order
-from ...shipping.models import ShippingZone
from ..checkout.dataloaders import CheckoutByTokenLoader, CheckoutLineByIdLoader
from ..core.dataloaders import DataLoader
from ..order.dataloaders import OrderByIdLoader, OrderLineByIdLoader
-from ..shipping.dataloaders import ShippingZoneByIdLoader
class ChannelByIdLoader(DataLoader):
@@ -86,30 +82,3 @@ class ChannelWithHasOrdersByIdLoader(DataLoader):
.in_bulk(keys)
)
return [channels.get(channel_id) for channel_id in keys]
-
-
-class ShippingZonesByChannelIdLoader(DataLoader):
- context_key = "shippingzone_by_channel"
-
- def batch_load(self, keys):
- zone_and_channel_is_pairs = (
- ShippingZone.objects.using(self.database_connection_name)
- .filter(channels__id__in=keys)
- .values_list("pk", "channels__id")
- )
- channel_shipping_zone_map = defaultdict(list)
- for zone_id, channel_id in zone_and_channel_is_pairs:
- channel_shipping_zone_map[channel_id].append(zone_id)
-
- def map_shipping_zones(shipping_zones):
- zone_map = {zone.pk: zone for zone in shipping_zones}
- return [
- [zone_map[zone_id] for zone_id in channel_shipping_zone_map[channel_id]]
- for channel_id in keys
- ]
-
- return (
- ShippingZoneByIdLoader(self.context)
- .load_many({pk for pk, _ in zone_and_channel_is_pairs})
- .then(map_shipping_zones)
- )
diff --git a/saleor/graphql/channel/mutations.py b/saleor/graphql/channel/mutations.py
index c78f798258..2145e50cee 100644
--- a/saleor/graphql/channel/mutations.py
+++ b/saleor/graphql/channel/mutations.py
@@ -14,16 +14,29 @@ from ...core.utils.date_time import convert_to_utc_date_time
from ...order.models import Order
from ...shipping.tasks import drop_invalid_shipping_methods_relations_for_given_channels
from ..account.enums import CountryCodeEnum
-from ..core.descriptions import ADDED_IN_31
+from ..core.descriptions import ADDED_IN_31, ADDED_IN_35, PREVIEW_FEATURE
from ..core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation
from ..core.types import ChannelError, ChannelErrorCode, NonNullList
from ..core.utils import get_duplicated_values, get_duplicates_items
from ..utils.validators import check_for_duplicates
from .types import Channel
+from .utils import delete_invalid_warehouse_to_shipping_zone_relations
class ChannelInput(graphene.InputObjectType):
is_active = graphene.Boolean(description="isActive flag.")
+ add_shipping_zones = NonNullList(
+ graphene.ID,
+ description="List of shipping zones to assign to the channel.",
+ required=False,
+ )
+ add_warehouses = NonNullList(
+ graphene.ID,
+ description="List of warehouses to assign to the channel."
+ + ADDED_IN_35
+ + PREVIEW_FEATURE,
+ required=False,
+ )
class ChannelCreateInput(ChannelInput):
@@ -36,15 +49,12 @@ class ChannelCreateInput(ChannelInput):
description=(
"Default country for the channel. Default country can be "
"used in checkout to determine the stock quantities or calculate taxes "
- "when the country was not explicitly provided." + ADDED_IN_31
+ "when the country was not explicitly provided."
+ + ADDED_IN_31
+ + PREVIEW_FEATURE
),
required=True,
)
- add_shipping_zones = NonNullList(
- graphene.ID,
- description="List of shipping zones to assign to the channel.",
- required=False,
- )
class ChannelCreate(ModelMutation):
@@ -81,6 +91,9 @@ class ChannelCreate(ModelMutation):
shipping_zones = cleaned_data.get("add_shipping_zones")
if shipping_zones:
instance.shipping_zones.add(*shipping_zones)
+ warehouses = cleaned_data.get("add_warehouses")
+ if warehouses:
+ instance.warehouses.add(*warehouses)
@classmethod
def post_save_action(cls, info, instance, cleaned_input):
@@ -97,14 +110,16 @@ class ChannelUpdateInput(ChannelInput):
"when the country was not explicitly provided." + ADDED_IN_31
)
)
- add_shipping_zones = NonNullList(
+ remove_shipping_zones = NonNullList(
graphene.ID,
- description="List of shipping zones to assign to the channel.",
+ description="List of shipping zones to unassign from the channel.",
required=False,
)
- remove_shipping_zones = NonNullList(
+ remove_warehouses = NonNullList(
graphene.ID,
- description="List of shipping zones to unassign from the channel.",
+ description="List of warehouses to unassign from the channel."
+ + ADDED_IN_35
+ + PREVIEW_FEATURE,
required=False,
)
@@ -126,12 +141,21 @@ class ChannelUpdate(ModelMutation):
@classmethod
def clean_input(cls, info, instance, data, input_cls=None):
- error = check_for_duplicates(
+ errors = {}
+ if error := check_for_duplicates(
data, "add_shipping_zones", "remove_shipping_zones", "shipping_zones"
- )
- if error:
+ ):
error.code = ChannelErrorCode.DUPLICATED_INPUT_ITEM.value
- raise ValidationError({"shipping_zones": error})
+ errors["shipping_zones"] = error
+
+ if error := check_for_duplicates(
+ data, "add_warehouses", "remove_warehouses", "warehouses"
+ ):
+ error.code = ChannelErrorCode.DUPLICATED_INPUT_ITEM.value
+ errors["warehouses"] = error
+
+ if errors:
+ raise ValidationError(errors)
cleaned_input = super().clean_input(info, instance, data)
slug = cleaned_input.get("slug")
@@ -144,6 +168,25 @@ class ChannelUpdate(ModelMutation):
@traced_atomic_transaction()
def _save_m2m(cls, info, instance, cleaned_data):
super()._save_m2m(info, instance, cleaned_data)
+ cls._update_shipping_zones(instance, cleaned_data)
+ cls._update_warehouses(instance, cleaned_data)
+ if (
+ "remove_shipping_zones" in cleaned_data
+ or "remove_warehouses" in cleaned_data
+ ):
+ warehouse_ids = [
+ warehouse.id for warehouse in cleaned_data.get("remove_warehouses", [])
+ ]
+ shipping_zone_ids = [
+ warehouse.id
+ for warehouse in cleaned_data.get("remove_shipping_zones", [])
+ ]
+ delete_invalid_warehouse_to_shipping_zone_relations(
+ instance, warehouse_ids, shipping_zone_ids
+ )
+
+ @classmethod
+ def _update_shipping_zones(cls, instance, cleaned_data):
add_shipping_zones = cleaned_data.get("add_shipping_zones")
if add_shipping_zones:
instance.shipping_zones.add(*add_shipping_zones)
@@ -161,6 +204,15 @@ class ChannelUpdate(ModelMutation):
shipping_method_ids, [instance.id]
)
+ @classmethod
+ def _update_warehouses(cls, instance, cleaned_data):
+ add_warehouses = cleaned_data.get("add_warehouses")
+ if add_warehouses:
+ instance.warehouses.add(*add_warehouses)
+ remove_warehouses = cleaned_data.get("remove_warehouses")
+ if remove_warehouses:
+ instance.warehouses.remove(*remove_warehouses)
+
@classmethod
def post_save_action(cls, info, instance, cleaned_input):
info.context.plugins.channel_updated(instance)
@@ -255,6 +307,7 @@ class ChannelDelete(ModelDeleteMutation):
info.context.plugins.channel_deleted(instance)
@classmethod
+ @traced_atomic_transaction()
def perform_mutation(cls, _root, info, **data):
origin_channel = cls.get_node_or_error(info, data["id"], only_type=Channel)
target_channel_global_id = data.get("input", {}).get("channel_id")
@@ -265,7 +318,11 @@ class ChannelDelete(ModelDeleteMutation):
cls.perform_delete_with_order_migration(origin_channel, target_channel)
else:
cls.perform_delete_channel_without_order(origin_channel)
-
+ delete_invalid_warehouse_to_shipping_zone_relations(
+ origin_channel,
+ origin_channel.warehouses.values("id"),
+ channel_deletion=True,
+ )
return super().perform_mutation(_root, info, **data)
diff --git a/saleor/graphql/channel/tests/benchmark/__init__.py b/saleor/graphql/channel/tests/benchmark/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/graphql/channel/tests/benchmark/fixtures.py b/saleor/graphql/channel/tests/benchmark/fixtures.py
new file mode 100644
index 0000000000..fd96738aa9
--- /dev/null
+++ b/saleor/graphql/channel/tests/benchmark/fixtures.py
@@ -0,0 +1,34 @@
+import pytest
+
+from .....channel.models import Channel
+from .....warehouse.models import Warehouse
+
+CHANNEL_COUNT_IN_BENCHMARKS = 10
+
+
+def channels_for_benchmark(address):
+ warehouses = [
+ Warehouse(
+ address=address,
+ name=f"Example Warehouse {i}",
+ slug=f"example-warehouse-{i}",
+ )
+ for i in range(CHANNEL_COUNT_IN_BENCHMARKS)
+ ]
+ created_warehouses = Warehouse.objects.bulk_create(warehouses)
+
+ channels = [
+ Channel(
+ name=f"channel {i}",
+ slug=f"channel-{i}",
+ )
+ for i in range(CHANNEL_COUNT_IN_BENCHMARKS)
+ ]
+ created_channels = Channel.objects.bulk_create(channels)
+
+ for channel, warehouse in zip(created_channels, created_warehouses):
+ channel.warehouses.add(warehouse)
+
+ return created_channels
diff --git a/saleor/graphql/channel/tests/benchmark/test_channel.py b/saleor/graphql/channel/tests/benchmark/test_channel.py
new file mode 100644
index 0000000000..5806623aaa
--- /dev/null
+++ b/saleor/graphql/channel/tests/benchmark/test_channel.py
@@ -0,0 +1,36 @@
+import pytest
+
+from ....tests.utils import get_graphql_content
+
+CHANNELS_QUERY = """
+ query {
+ channels {
+ name
+ slug
+ currencyCode
+ warehouses {
+ id
+ }
+ defaultCountry {
+ code
+ country
+ }
+ }
+ }
+"""
+
+
[email protected]_queries(autouse=False)
+def test_channels_query(
+ staff_api_client, permission_manage_channels, channels_for_benchmark, count_queries
+):
+ content = get_graphql_content(
+ staff_api_client.post_graphql(
+ CHANNELS_QUERY,
+ permissions=[permission_manage_channels],
+ check_no_permissions=False,
+ )
+ )
+
+ assert content["data"]["channels"]
diff --git a/saleor/graphql/channel/tests/test_channel_create_mutations.py b/saleor/graphql/channel/tests/test_channel_create_mutations.py
index 349078293b..446f892b3b 100644
--- a/saleor/graphql/channel/tests/test_channel_create_mutations.py
+++ b/saleor/graphql/channel/tests/test_channel_create_mutations.py
@@ -23,6 +23,9 @@ CHANNEL_CREATE_MUTATION = """
code
country
}
+ warehouses {
+ slug
+ }
}
errors{
field
@@ -275,6 +278,53 @@ def test_channel_create_mutation_with_shipping_zones(
shipping_zone.channels.get(slug=slug)
+def test_channel_create_mutation_with_warehouses(
+ permission_manage_channels,
+ staff_api_client,
+ warehouses,
+):
+ # given
+ name = "testName"
+ slug = "test_slug"
+ currency_code = "USD"
+ default_country = "US"
+ warehouses_ids = [
+ graphene.Node.to_global_id("Warehouse", warehouse.pk)
+ for warehouse in warehouses
+ ]
+ variables = {
+ "input": {
+ "name": name,
+ "slug": slug,
+ "currencyCode": currency_code,
+ "addWarehouses": warehouses_ids,
+ "defaultCountry": default_country,
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ CHANNEL_CREATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_channels,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["channelCreate"]
+ assert not data["errors"]
+ channel_data = data["channel"]
+ channel = Channel.objects.get(
+ id=graphene.Node.from_global_id(channel_data["id"])[1]
+ )
+ assert channel_data["name"] == channel.name == name
+ assert channel_data["slug"] == channel.slug == slug
+ assert channel_data["currencyCode"] == channel.currency_code == currency_code
+ assert {
+ warehouse_data["slug"] for warehouse_data in channel_data["warehouses"]
+ } == {warehouse.slug for warehouse in warehouses}
+
+
@freeze_time("2022-05-12 12:00:00")
@mock.patch("saleor.plugins.webhook.plugin.get_webhooks_for_event")
@mock.patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")
diff --git a/saleor/graphql/channel/tests/test_channel_delete_mutations.py b/saleor/graphql/channel/tests/test_channel_delete_mutations.py
index f4d74cfaf8..b45ab1c1aa 100644
--- a/saleor/graphql/channel/tests/test_channel_delete_mutations.py
+++ b/saleor/graphql/channel/tests/test_channel_delete_mutations.py
@@ -282,3 +282,70 @@ def test_channel_delete_mutation_trigger_webhook(
channel_USD,
SimpleLazyObject(lambda: staff_api_client.user),
)
+
+
+def test_channel_delete_mutation_deletes_invalid_warehouse_to_zone_relations(
+ order_list,
+ checkout,
+ permission_manage_channels,
+ staff_api_client,
+ channel_USD,
+ channel_PLN,
+ channel_JPY,
+ warehouses,
+ warehouse_JPY,
+ shipping_zones,
+ other_channel_USD,
+):
+ """Ensure deleting channel deletes no longer valid warehouse to zone relations."""
+ # given
+ order = order_list[0]
+ order.channel = channel_USD
+ order.save()
+
+ # prepare warehouse to shipping zone relations:
+ # warehouse[0] - with channel USD, PLN assigned to both shipping zones
+ # warehouse[1] - with channel USD, JPY assigned to both shipping zones
+ # shipping_zones[0] - assigned to channel USD and PLN
+ # shipping_zones[0] - assigned to channel USD, PLN, JPY
+ channel_USD.warehouses.add(*warehouses)
+ channel_PLN.warehouses.add(warehouses[0])
+ channel_JPY.warehouses.add(warehouses[1])
+ for shipping_zone in shipping_zones:
+ shipping_zone.warehouses.add(*warehouses)
+
+ # add additional common channel for warehouse[1]
+ shipping_zones[0].channels.add(channel_JPY)
+
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ channel_target_id = graphene.Node.to_global_id("Channel", other_channel_USD.id)
+ variables = {"id": channel_id, "input": {"channelId": channel_target_id}}
+ assert Checkout.objects.first() is not None
+
+ # when
+ response = staff_api_client.post_graphql(
+ CHANNEL_DELETE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_channels,),
+ )
+
+ # then
+ get_graphql_content(response)
+ order.refresh_from_db()
+
+ assert order.channel == other_channel_USD
+ assert Checkout.objects.first() is None
+ assert not Channel.objects.filter(slug=channel_USD.slug).exists()
+
+ # ensure warehouse from index 1 has not been deleted from any shipping zone
+ # common PLN channel
+ for zone in shipping_zones:
+ zone.refresh_from_db()
+ assert warehouses[0] in zone.warehouses.all()
+
+ # ensure warehouse from index 1 has not been deleted from shipping zone
+ # with JPY channel
+ assert warehouses[1] in shipping_zones[0].warehouses.all()
+ # ensure warehouse from index 1 has been deleted from shipping zone
+ # without JPY channel
+ assert warehouses[1] not in shipping_zones[1].warehouses.all()
diff --git a/saleor/graphql/channel/tests/test_channel_update_mutations.py b/saleor/graphql/channel/tests/test_channel_update_mutations.py
index 9a1dfcd261..0661421e51 100644
--- a/saleor/graphql/channel/tests/test_channel_update_mutations.py
+++ b/saleor/graphql/channel/tests/test_channel_update_mutations.py
@@ -1,6 +1,7 @@
from unittest.mock import patch
import graphene
+import pytest
from django.utils.functional import SimpleLazyObject
from django.utils.text import slugify
from freezegun import freeze_time
@@ -22,12 +23,16 @@ CHANNEL_UPDATE_MUTATION = """
code
country
}
+ warehouses {
+ slug
+ }
}
errors{
field
code
message
shippingZones
+ warehouses
}
}
}
@@ -276,9 +281,18 @@ def test_channel_update_mutation_remove_shipping_zone(
staff_api_client,
channel_USD,
shipping_zones,
+ warehouses,
+ channel_PLN,
):
# given
channel_USD.shipping_zones.add(*shipping_zones)
+ channel_PLN.shipping_zones.add(*shipping_zones)
+
+ for warehouse in warehouses:
+ warehouse.shipping_zones.add(*shipping_zones)
+
+ # add another common channel with zone to warehouses on index 1
+ channel_PLN.warehouses.add(warehouses[0])
channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
name = "newName"
@@ -320,6 +334,13 @@ def test_channel_update_mutation_remove_shipping_zone(
mocked_drop_invalid_shipping_methods_relations.assert_called_once_with(
list(shipping_method_ids), [channel_USD.id]
)
+ # ensure one warehouse was removed from shipping zone as they do not have
+ # common channel anymore
+ assert warehouses[0].id not in shipping_zones[0].warehouses.values("id")
+
+ # ensure another shipping zone has all warehouses assigned
+ for zone in shipping_zones[1:]:
+ assert zone.warehouses.count() == len(warehouses)
def test_channel_update_mutation_add_and_remove_shipping_zone(
@@ -465,3 +486,202 @@ def test_channel_update_mutation_trigger_webhook(
channel_USD,
SimpleLazyObject(lambda: staff_api_client.user),
)
+
+
+def test_channel_update_mutation_add_warehouse(
+ permission_manage_channels, staff_api_client, channel_USD, warehouse
+):
+ # given
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ name = "newName"
+ slug = "new_slug"
+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)
+ variables = {
+ "id": channel_id,
+ "input": {"name": name, "slug": slug, "addWarehouses": [warehouse_id]},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ CHANNEL_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_channels,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["channelUpdate"]
+ assert not data["errors"]
+ channel_data = data["channel"]
+ channel_USD.refresh_from_db()
+ warehouse.refresh_from_db()
+ assert channel_data["name"] == channel_USD.name == name
+ assert channel_data["slug"] == channel_USD.slug == slug
+ assert channel_data["currencyCode"] == channel_USD.currency_code == "USD"
+ assert len(channel_data["warehouses"]) == 1
+ assert channel_data["warehouses"][0]["slug"] == warehouse.slug
+
+
[email protected]_queries(autouse=False)
+def test_channel_update_mutation_remove_warehouse(
+ permission_manage_channels,
+ staff_api_client,
+ channel_USD,
+ channel_PLN,
+ channel_JPY,
+ warehouses,
+ warehouse_JPY,
+ shipping_zones,
+ count_queries,
+):
+ """Ensure that removing warehouses from channel works properly.
+
+ Also, ensure that when the warehouse is removed from the channel it's also removed
+ from shipping zones with which the warehouse do not have a common channel anymore.
+ """
+ # given
+ channel_USD.warehouses.add(*(warehouses + [warehouse_JPY]))
+ channel_PLN.warehouses.add(*[warehouses[0], warehouse_JPY])
+ channel_JPY.warehouses.add(warehouses[1])
+ for shipping_zone in shipping_zones:
+ shipping_zone.warehouses.add(*warehouses)
+
+ # add additional common channel for warehouse[1]
+ shipping_zones[0].channels.add(channel_JPY)
+
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ name = "newName"
+ slug = "new_slug"
+ remove_warehouses = [
+ graphene.Node.to_global_id("Warehouse", warehouse.pk)
+ for warehouse in warehouses
+ ]
+ warehouses_count = channel_USD.warehouses.count()
+
+ variables = {
+ "id": channel_id,
+ "input": {
+ "name": name,
+ "slug": slug,
+ "removeWarehouses": remove_warehouses,
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ CHANNEL_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_channels,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["channelUpdate"]
+ assert not data["errors"]
+ channel_data = data["channel"]
+ channel_USD.refresh_from_db()
+ assert channel_data["name"] == channel_USD.name == name
+ assert channel_data["slug"] == channel_USD.slug == slug
+ assert channel_data["currencyCode"] == channel_USD.currency_code == "USD"
+ assert len(channel_data["warehouses"]) == warehouses_count - 2
+ assert {
+ warehouse_data["slug"] for warehouse_data in channel_data["warehouses"]
+ } == {warehouse_JPY.slug}
+ # ensure warehouse from index 1 has not been deleted from any shipping zone
+ for zone in shipping_zones:
+ zone.refresh_from_db()
+ assert warehouses[0] in zone.warehouses.all()
+ # ensure warehouse from index 1 has not been deleted from shipping zone
+ # with JPY channel
+ assert warehouses[1] in shipping_zones[0].warehouses.all()
+ # ensure warehouse from index 1 has been deleted from shipping zone
+ # without JPY channel
+ assert warehouses[1] not in shipping_zones[1].warehouses.all()
+
+
+def test_channel_update_mutation_add_and_remove_warehouse(
+ permission_manage_channels,
+ staff_api_client,
+ channel_USD,
+ warehouses,
+ warehouse,
+):
+ # given
+ channel_USD.warehouses.add(*warehouses)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ name = "newName"
+ slug = "new_slug"
+ remove_warehouse = graphene.Node.to_global_id("Warehouse", warehouses[0].pk)
+ add_warehouse = graphene.Node.to_global_id("Warehouse", warehouse.pk)
+ variables = {
+ "id": channel_id,
+ "input": {
+ "name": name,
+ "slug": slug,
+ "addWarehouses": [add_warehouse],
+ "removeWarehouses": [remove_warehouse],
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ CHANNEL_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_channels,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["channelUpdate"]
+ assert not data["errors"]
+ channel_data = data["channel"]
+ channel_USD.refresh_from_db()
+ assert channel_data["name"] == channel_USD.name == name
+ assert channel_data["slug"] == channel_USD.slug == slug
+ assert channel_data["currencyCode"] == channel_USD.currency_code == "USD"
+ assert {
+ warehouse_data["slug"] for warehouse_data in channel_data["warehouses"]
+ } == {warehouse.slug for warehouse in warehouses[1:] + [warehouse]}
+
+
+def test_channel_update_mutation_duplicated_warehouses(
+ permission_manage_channels,
+ staff_api_client,
+ channel_USD,
+ warehouses,
+ warehouse,
+):
+ # given
+ channel_USD.warehouses.add(*warehouses)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.id)
+ name = "newName"
+ slug = "new_slug"
+ remove_warehouse = graphene.Node.to_global_id("Warehouse", warehouses[0].pk)
+ add_warehouse = graphene.Node.to_global_id("Warehouse", warehouse.pk)
+ variables = {
+ "id": channel_id,
+ "input": {
+ "name": name,
+ "slug": slug,
+ "addWarehouses": [add_warehouse],
+ "removeWarehouses": [remove_warehouse, add_warehouse],
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ CHANNEL_UPDATE_MUTATION,
+ variables=variables,
+ permissions=(permission_manage_channels,),
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["channelUpdate"]
+ assert not data["channel"]
+ errors = data["errors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "warehouses"
+ assert errors[0]["code"] == ChannelErrorCode.DUPLICATED_INPUT_ITEM.name
+ assert errors[0]["warehouses"] == [add_warehouse]
diff --git a/saleor/graphql/channel/types.py b/saleor/graphql/channel/types.py
index a90a828da3..96f95de0f3 100644
--- a/saleor/graphql/channel/types.py
+++ b/saleor/graphql/channel/types.py
@@ -6,11 +6,13 @@ from graphene.types.resolver import get_default_resolver
from ...channel import models
from ...core.permissions import ChannelPermissions
-from ..core.descriptions import ADDED_IN_31
+from ..core.descriptions import ADDED_IN_31, ADDED_IN_35, PREVIEW_FEATURE
from ..core.fields import PermissionsField
-from ..core.types import CountryDisplay, ModelObjectType
+from ..core.types import CountryDisplay, ModelObjectType, NonNullList
from ..meta.types import ObjectWithMetadata
from ..translations.resolvers import resolve_translation
+from ..warehouse.dataloaders import WarehousesByChannelIdLoader
+from ..warehouse.types import Warehouse
from . import ChannelContext
from .dataloaders import ChannelWithHasOrdersByIdLoader
@@ -139,6 +141,13 @@ class Channel(ModelObjectType):
),
required=True,
)
+ warehouses = NonNullList(
+ Warehouse,
+ description="List of warehouses assigned to this channel."
+ + ADDED_IN_35
+ + PREVIEW_FEATURE,
+ required=True,
+ )
class Meta:
description = "Represents channel."
@@ -158,3 +167,7 @@ class Channel(ModelObjectType):
return CountryDisplay(
code=root.default_country.code, country=root.default_country.name
)
+
+ @staticmethod
+ def resolve_warehouses(root: models.Channel, info):
+ return WarehousesByChannelIdLoader(info.context).load(root.id)
diff --git a/saleor/graphql/channel/utils.py b/saleor/graphql/channel/utils.py
index cf8ca11dc8..df8317eebc 100644
--- a/saleor/graphql/channel/utils.py
+++ b/saleor/graphql/channel/utils.py
@@ -1,10 +1,14 @@
+from collections import defaultdict
+
from django.core.exceptions import ValidationError
+from django.db.models import Exists, OuterRef, Q
from django.utils.functional import SimpleLazyObject
from graphql.error import GraphQLError
from ...channel.exceptions import ChannelNotDefined, NoDefaultChannel
from ...channel.models import Channel
from ...channel.utils import get_default_channel
+from ...shipping.models import ShippingZone
def get_default_channel_slug_or_graphql_error() -> SimpleLazyObject:
@@ -71,3 +75,81 @@ def clean_channel(
}
)
return channel
+
+
+def delete_invalid_warehouse_to_shipping_zone_relations(
+ channel, warehouse_ids, shipping_zone_ids=None, channel_deletion=False
+):
+ """Delete not valid warehouse-zone relations after channel updates.
+
+ Look up for warehouse to shipping zone relations that will not have common channels
+ after unlinking the given channel from warehouses or shipping zones.
+ The warehouse can be linked with shipping zone only if common channel exists.
+ """
+ shipping_zone_ids = shipping_zone_ids or []
+
+ ChannelWarehouse = Channel.warehouses.through
+ ShippingZoneWarehouse = ShippingZone.warehouses.through
+ ShippingZoneChannel = ShippingZone.channels.through
+
+ shipping_zone_warehouses = ShippingZoneWarehouse.objects.filter(
+ Q(warehouse_id__in=warehouse_ids) | Q(shippingzone_id__in=shipping_zone_ids)
+ )
+ channel_warehouses = ChannelWarehouse.objects.filter(
+ Exists(shipping_zone_warehouses.filter(warehouse_id=OuterRef("warehouse_id")))
+ )
+ shipping_zone_channels = ShippingZoneChannel.objects.filter(
+ Exists(
+ shipping_zone_warehouses.filter(shippingzone_id=OuterRef("shippingzone_id"))
+ )
+ )
+
+ warehouse_to_channel_ids = _get_warehouse_to_channels_mapping(
+ channel, channel_warehouses, channel_deletion
+ )
+ zone_to_channel_ids = _get_shipping_zone_to_channels_mapping(shipping_zone_channels)
+ shipping_zone_warehouses_to_delete = _get_invalid_shipping_zone_warehouses_ids(
+ shipping_zone_warehouses, warehouse_to_channel_ids, zone_to_channel_ids
+ )
+
+ # delete invalid shipping zone - warehouse relations
+ ShippingZoneWarehouse.objects.filter(
+ id__in=shipping_zone_warehouses_to_delete
+ ).delete()
+
+
+def _get_warehouse_to_channels_mapping(channel, channel_warehouses, channel_deletion):
+ warehouse_to_channel_ids = defaultdict(set)
+ for warehouse_id, channel_id in channel_warehouses.values_list(
+ "warehouse_id", "channel_id"
+ ):
+ # when the channel will be deleted so we do not want this channel in warehouse
+ # channels set
+ if not channel_deletion or channel_id != channel.id:
+ warehouse_to_channel_ids[warehouse_id].add(channel_id)
+ return warehouse_to_channel_ids
+
+
+def _get_shipping_zone_to_channels_mapping(shipping_zone_channels):
+ zone_to_channel_ids = defaultdict(set)
+ for zone_id, channel_id in shipping_zone_channels.values_list(
+ "shippingzone_id", "channel_id"
+ ):
+ zone_to_channel_ids[zone_id].add(channel_id)
+ return zone_to_channel_ids
+
+
+def _get_invalid_shipping_zone_warehouses_ids(
+ shipping_zone_warehouses, warehouse_to_channel_ids, zone_to_channel_ids
+):
+ shipping_zone_warehouses_to_delete = []
+ for id, zone_id, warehouse_id in shipping_zone_warehouses.values_list(
+ "id", "shippingzone_id", "warehouse_id"
+ ):
+ warehouse_channels = warehouse_to_channel_ids.get(warehouse_id, set())
+ zone_channels = zone_to_channel_ids.get(zone_id, set())
+ # if there is no common channels between shipping zone and warehouse
+ # the relation should be deleted
+ if not warehouse_channels.intersection(zone_channels):
+ shipping_zone_warehouses_to_delete.append(id)
+ return shipping_zone_warehouses_to_delete
diff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.py
index 5ea28746c0..9643529402 100644
--- a/saleor/graphql/checkout/tests/test_checkout.py
+++ b/saleor/graphql/checkout/tests/test_checkout.py
@@ -728,19 +728,24 @@ query AvailableCollectionPoints($id: ID) {
def test_available_collection_points_for_preorders_variants_in_checkout(
- api_client, staff_api_client, checkout_with_preorders_only
+ api_client, staff_api_client, checkout_with_preorders_only, channel_USD
):
+ # given
expected_collection_points = list(
- Warehouse.objects.for_country("US")
+ Warehouse.objects.for_channel(channel_USD.id)
.exclude(
click_and_collect_option=WarehouseClickAndCollectOption.DISABLED,
)
.values("name")
)
+
+ # when
response = staff_api_client.post_graphql(
QUERY_GET_ALL_COLLECTION_POINTS_FROM_CHECKOUT,
variables={"id": to_global_id_or_none(checkout_with_preorders_only)},
)
+
+ # then
response_content = get_graphql_content(response)
assert (
expected_collection_points
@@ -833,11 +838,11 @@ def test_checkout_avail_collect_points_exceeded_quantity_shows_only_all_warehous
]
-def test_checkout_avail_collect_points_returns_empty_list_when_not_in_shipping_zone(
+def test_checkout_avail_collect_points_returns_empty_list_when_no_channels(
api_client, warehouse_for_cc, checkout_with_items_for_cc
):
query = GET_CHECKOUT_AVAILABLE_COLLECTION_POINTS
- warehouse_for_cc.shipping_zones.filter(name="Poland").delete()
+ checkout_with_items_for_cc.channel.warehouses.remove(warehouse_for_cc)
variables = {"id": to_global_id_or_none(checkout_with_items_for_cc)}
response = api_client.post_graphql(query, variables)
diff --git a/saleor/graphql/checkout/types.py b/saleor/graphql/checkout/types.py
index 79a40e52a4..0d14b83448 100644
--- a/saleor/graphql/checkout/types.py
+++ b/saleor/graphql/checkout/types.py
@@ -16,7 +16,7 @@ from ...warehouse.reservations import is_reservation_enabled
from ..account.dataloaders import AddressByIdLoader
from ..account.utils import check_is_owner_or_has_one_of_perms
from ..channel import ChannelContext
-from ..channel.dataloaders import ChannelByCheckoutLineIDLoader, ChannelByIdLoader
+from ..channel.dataloaders import ChannelByCheckoutLineIDLoader
from ..channel.types import Channel
from ..core.connection import CountableConnection
from ..core.descriptions import (
@@ -678,28 +678,13 @@ class Checkout(ModelObjectType):
@staticmethod
@traced_resolver
def resolve_available_collection_points(root: models.Checkout, info):
- def get_available_collection_points(data):
- address, lines, channel = data
+ def get_available_collection_points(lines):
+ return get_valid_collection_points_for_checkout(lines, root.channel_id)
- if address:
- country_code = address.country.code
- else:
- country_code = channel.default_country.code
-
- return get_valid_collection_points_for_checkout(
- lines, country_code=country_code
- )
-
- lines = CheckoutLinesInfoByCheckoutTokenLoader(info.context).load(root.token)
- channel = ChannelByIdLoader(info.context).load(root.channel_id)
- address = (
- AddressByIdLoader(info.context).load(root.shipping_address_id)
- if root.shipping_address_id
- else None
- )
-
- return Promise.all([address, lines, channel]).then(
- get_available_collection_points
+ return (
+ CheckoutLinesInfoByCheckoutTokenLoader(info.context)
+ .load(root.token)
+ .then(get_available_collection_points)
)
@staticmethod
diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.py
index fe231ba213..508a199d9c 100644
--- a/saleor/graphql/core/types/common.py
+++ b/saleor/graphql/core/types/common.py
@@ -142,6 +142,11 @@ class ChannelError(Error):
description="List of shipping zone IDs which causes the error.",
required=False,
)
+ warehouses = NonNullList(
+ graphene.ID,
+ description="List of warehouses IDs which causes the error.",
+ required=False,
+ )
class CheckoutError(Error):
diff --git a/saleor/graphql/order/tests/test_order.py b/saleor/graphql/order/tests/test_order.py
index 35a82b5a04..92d4110f9c 100644
--- a/saleor/graphql/order/tests/test_order.py
+++ b/saleor/graphql/order/tests/test_order.py
@@ -576,7 +576,7 @@ def test_order_query(
channel_id=order.channel_id,
)
expected_collection_points = Warehouse.objects.applicable_for_click_and_collect(
- lines_qs=order.lines, country=order.shipping_address.country.code
+ lines_qs=order.lines, channel_id=order.channel.id
)
assert len(order_data["availableShippingMethods"]) == (expected_methods.count())
diff --git a/saleor/graphql/order/types.py b/saleor/graphql/order/types.py
index c21dc85269..e250de59ba 100644
--- a/saleor/graphql/order/types.py
+++ b/saleor/graphql/order/types.py
@@ -1428,14 +1428,10 @@ class Order(ModelObjectType):
@classmethod
@traced_resolver
def resolve_available_collection_points(cls, root: models.Order, info):
- def get_available_collection_points(data):
- lines, address = data
+ def get_available_collection_points(lines):
+ return get_valid_collection_points_for_order(lines, root.channel_id)
- return get_valid_collection_points_for_order(lines, address)
-
- lines = cls.resolve_lines(root, info)
- address = cls.resolve_shipping_address(root, info)
- return Promise.all([lines, address]).then(get_available_collection_points)
+ return cls.resolve_lines(root, info).then(get_available_collection_points)
@staticmethod
def resolve_invoices(root: models.Order, info):
diff --git a/saleor/graphql/product/filters.py b/saleor/graphql/product/filters.py
index 6ace66da83..e3dabd4f19 100644
--- a/saleor/graphql/product/filters.py
+++ b/saleor/graphql/product/filters.py
@@ -321,7 +321,7 @@ def filter_products_by_stock_availability(qs, stock_availability, channel_slug):
allocated_subquery = Subquery(queryset=allocations, output_field=IntegerField())
stocks = (
- Stock.objects.for_channel(channel_slug)
+ Stock.objects.for_channel_and_country(channel_slug)
.filter(quantity__gt=Coalesce(allocated_subquery, 0))
.values("product_variant_id")
)
diff --git a/saleor/graphql/product/tests/test_variant.py b/saleor/graphql/product/tests/test_variant.py
index 8e0f7eb76a..953c9d2266 100644
--- a/saleor/graphql/product/tests/test_variant.py
+++ b/saleor/graphql/product/tests/test_variant.py
@@ -30,16 +30,7 @@ from ...tests.utils import (
get_graphql_content_from_response,
)
-
-def test_fetch_variant(
- staff_api_client,
- product,
- permission_manage_products,
- site_settings,
- channel_USD,
-):
- query = """
- query ProductVariantDetails(
+QUERY_VARIANT = """query ProductVariantDetails(
$id: ID!, $address: AddressInput, $countryCode: CountryCode, $channel: String
) {
productVariant(id: $id, channel: $channel) {
@@ -98,8 +89,18 @@ def test_fetch_variant(
created
}
}
- """
+"""
+
+
+def test_fetch_variant(
+ staff_api_client,
+ product,
+ permission_manage_products,
+ site_settings,
+ channel_USD,
+):
# given
+ query = QUERY_VARIANT
variant = product.variants.first()
variant.weight = Weight(kg=10)
variant.save(update_fields=["weight"])
@@ -137,6 +138,56 @@ def test_fetch_variant(
)
+def test_fetch_variant_no_stocks(
+ staff_api_client,
+ product,
+ permission_manage_products,
+ site_settings,
+ channel_USD,
+):
+ # given
+ query = QUERY_VARIANT
+ variant = product.variants.first()
+ variant.weight = Weight(kg=10)
+ variant.save(update_fields=["weight"])
+
+ site_settings.default_weight_unit = WeightUnits.G
+ site_settings.save(update_fields=["default_weight_unit"])
+
+ warehouse = variant.stocks.first().warehouse
+ # remove the warehouse channels
+ # the stocks for this warehouse shouldn't be returned
+ warehouse.channels.clear()
+
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ variables = {"id": variant_id, "countryCode": "EU", "channel": channel_USD.slug}
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ # when
+ response = staff_api_client.post_graphql(query, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["productVariant"]
+ assert data["name"] == variant.name
+ assert data["created"] == variant.created_at.isoformat()
+
+ assert not data["deprecatedStocksByCountry"]
+ assert not data["stocksByAddress"]
+
+ assert data["weight"]["value"] == 10000
+ assert data["weight"]["unit"] == WeightUnitsEnum.G.name
+ channel_listing_data = data["channelListings"][0]
+ channel_listing = variant.channel_listings.get()
+ assert channel_listing_data["channel"]["slug"] == channel_listing.channel.slug
+ assert channel_listing_data["price"]["currency"] == channel_listing.currency
+ assert channel_listing_data["price"]["amount"] == channel_listing.price_amount
+ assert channel_listing_data["costPrice"]["currency"] == channel_listing.currency
+ assert (
+ channel_listing_data["costPrice"]["amount"] == channel_listing.cost_price_amount
+ )
+
+
QUERY_PRODUCT_VARIANT_CHANNEL_LISTING = """
query ProductVariantDetails($id: ID!, $channel: String) {
productVariant(id: $id, channel: $channel) {
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 96e46bf7a5..2c0503aadf 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -3653,6 +3653,15 @@ type Channel implements Node {
Added in Saleor 3.1.
"""
defaultCountry: CountryDisplay!
+
+ """
+ List of warehouses assigned to this channel.
+
+ Added in Saleor 3.5.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ warehouses: [Warehouse!]!
}
"""Represents shipping method postal code rule."""
@@ -5811,6 +5820,7 @@ input WarehouseFilterInput {
search: String
ids: [ID!]
isPrivate: Boolean
+ channels: [ID!]
}
input WarehouseSortingInput {
@@ -19389,6 +19399,9 @@ type ChannelError {
"""List of shipping zone IDs which causes the error."""
shippingZones: [ID!]
+
+ """List of warehouses IDs which causes the error."""
+ warehouses: [ID!]
}
"""An enumeration."""
@@ -19408,6 +19421,18 @@ input ChannelCreateInput {
"""isActive flag."""
isActive: Boolean
+ """List of shipping zones to assign to the channel."""
+ addShippingZones: [ID!]
+
+ """
+ List of warehouses to assign to the channel.
+
+ Added in Saleor 3.5.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ addWarehouses: [ID!]
+
"""Name of the channel."""
name: String!
@@ -19421,11 +19446,10 @@ input ChannelCreateInput {
Default country for the channel. Default country can be used in checkout to determine the stock quantities or calculate taxes when the country was not explicitly provided.
Added in Saleor 3.1.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
"""
defaultCountry: CountryCode!
-
- """List of shipping zones to assign to the channel."""
- addShippingZones: [ID!]
}
"""
@@ -19443,6 +19467,18 @@ input ChannelUpdateInput {
"""isActive flag."""
isActive: Boolean
+ """List of shipping zones to assign to the channel."""
+ addShippingZones: [ID!]
+
+ """
+ List of warehouses to assign to the channel.
+
+ Added in Saleor 3.5.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ addWarehouses: [ID!]
+
"""Name of the channel."""
name: String
@@ -19456,11 +19492,17 @@ input ChannelUpdateInput {
"""
defaultCountry: CountryCode
- """List of shipping zones to assign to the channel."""
- addShippingZones: [ID!]
-
"""List of shipping zones to unassign from the channel."""
removeShippingZones: [ID!]
+
+ """
+ List of warehouses to unassign from the channel.
+
+ Added in Saleor 3.5.
+
+ Note: this API is currently in Feature Preview and can be subject to changes at later point.
+ """
+ removeWarehouses: [ID!]
}
"""
diff --git a/saleor/graphql/shipping/mutations/shippings.py b/saleor/graphql/shipping/mutations/shippings.py
index fbdc67ec7b..1564c73032 100644
--- a/saleor/graphql/shipping/mutations/shippings.py
+++ b/saleor/graphql/shipping/mutations/shippings.py
@@ -2,8 +2,10 @@ from collections import defaultdict
import graphene
from django.core.exceptions import ValidationError
+from django.db.models import Exists, OuterRef
from django.db.utils import IntegrityError
+from ....channel import models as channel_models
from ....core.permissions import ShippingPermissions
from ....core.tracing import traced_atomic_transaction
from ....product import models as product_models
@@ -118,6 +120,8 @@ class ShippingZoneMixin:
raise ValidationError(errors)
cleaned_input = super().clean_input(info, instance, data)
+ if add_warehouses := cleaned_input.get("add_warehouses"):
+ cls.clean_add_warehouses(instance, add_warehouses, cleaned_input)
cleaned_input = cls.clean_default(instance, cleaned_input)
return cleaned_input
@@ -141,6 +145,101 @@ class ShippingZoneMixin:
error.code = ShippingErrorCode.DUPLICATED_INPUT_ITEM.value
errors[error_class_field].append(error)
+ @classmethod
+ def clean_add_warehouses(cls, shipping_zone, warehouses, cleaned_input):
+ """Check if all warehouses to add has common channel with shipping zone.
+
+ Raise and error when the condition is not fulfilled.
+ """
+ warehouse_ids = [warehouse.id for warehouse in warehouses]
+
+ remove_channel_ids = set()
+ if remove_channels := cleaned_input.get("remove_channels"):
+ remove_channel_ids = {channel.id for channel in remove_channels}
+
+ add_channel_ids = set()
+ if add_channels := cleaned_input.get("add_channels"):
+ add_channel_ids = {channel.id for channel in add_channels}
+
+ ChannelWarehouse = channel_models.Channel.warehouses.through
+ channel_warehouses = ChannelWarehouse.objects.filter(
+ warehouse_id__in=warehouse_ids
+ )
+
+ # any warehouse from the list cannot be assigned when:
+ # 1) where there are no channels assigned to any warehouse
+ # 2) any channel is will be not assigned to the shipping zone
+ if not channel_warehouses or (not shipping_zone.id and not add_channel_ids):
+ invalid_warehouse_ids = warehouse_ids
+
+ warehouse_to_channel_mapping = defaultdict(set)
+ for warehouse_id, channel_id in channel_warehouses.values_list(
+ "warehouse_id", "channel_id"
+ ):
+ warehouse_to_channel_mapping[warehouse_id].add(channel_id)
+
+ # if the shipping zone does not exist yet, all zone channels will be channels
+ # provided in `add_channels` field
+ shipping_zone_channel_ids = (
+ add_channel_ids
+ if not shipping_zone.id
+ else cls._get_shipping_zone_channel_ids(
+ shipping_zone, remove_channel_ids, add_channel_ids
+ )
+ )
+
+ invalid_warehouse_ids = cls._find_invalid_warehouses(
+ warehouse_to_channel_mapping, warehouse_ids, shipping_zone_channel_ids
+ )
+
+ if invalid_warehouse_ids:
+ invalid_warehouses = {
+ graphene.Node.to_global_id("Warehouse", pk)
+ for pk in invalid_warehouse_ids
+ }
+ raise ValidationError(
+ {
+ "add_warehouses": ValidationError(
+ "Only warehouses that have common channel with shipping zone "
+ "can be assigned.",
+ code=ShippingErrorCode.INVALID,
+ params={
+ "warehouses": invalid_warehouses,
+ },
+ )
+ }
+ )
+
+ @staticmethod
+ def _get_shipping_zone_channel_ids(
+ shipping_zone, remove_channel_ids, add_channel_ids
+ ):
+ # get shipping zone channels
+ ShippingZoneChannel = models.ShippingZone.channels.through
+ shipping_zone_channel_ids = set(
+ ShippingZoneChannel.objects.filter(shippingzone_id=shipping_zone.id)
+ .exclude(channel_id__in=remove_channel_ids)
+ .values_list("channel_id", flat=True)
+ )
+ # shipping zone channels set need to be updated with channels
+ # that will be removed and added to shipping zone
+ return shipping_zone_channel_ids | add_channel_ids
+
+ @staticmethod
+ def _find_invalid_warehouses(
+ warehouse_to_channel_mapping, warehouse_ids, zone_channel_ids
+ ):
+ invalid_warehouse_ids = []
+ for warehouse_id in warehouse_ids:
+ warehouse_channels = warehouse_to_channel_mapping.get(warehouse_id)
+ # warehouse cannot be added if it hasn't got any channel assigned
+ # or if it does not have common channel with shipping zone
+ if not warehouse_channels or not warehouse_channels.intersection(
+ zone_channel_ids
+ ):
+ invalid_warehouse_ids.append(warehouse_id)
+ return invalid_warehouse_ids
+
@classmethod
def clean_default(cls, instance, data):
default = data.get("default")
@@ -191,10 +290,60 @@ class ShippingZoneMixin:
)
shipping_channel_listings.delete()
channel_ids = [channel.id for channel in remove_channels]
+ cls.delete_invalid_shipping_zone_to_warehouse_relation(instance)
drop_invalid_shipping_methods_relations_for_given_channels.delay(
shipping_method_ids, channel_ids
)
+ @classmethod
+ def delete_invalid_shipping_zone_to_warehouse_relation(cls, shipping_zone):
+ """Drop zone-warehouse relations that becomes invalid after channels deletion.
+
+ Remove all shipping zone to warehouse relations that will not have common
+ channel after removing given channels from the shipping zone.
+ """
+ WarehouseShippingZone = models.ShippingZone.warehouses.through
+ ChannelWarehouse = channel_models.Channel.warehouses.through
+ ShippingZoneChannel = models.ShippingZone.channels.through
+
+ warehouse_shipping_zones = WarehouseShippingZone.objects.filter(
+ shippingzone_id=shipping_zone.id
+ )
+
+ channel_warehouses = ChannelWarehouse.objects.filter(
+ Exists(
+ warehouse_shipping_zones.filter(warehouse_id=OuterRef("warehouse_id"))
+ )
+ )
+
+ warehouse_to_channel_mapping = defaultdict(set)
+ for warehouse_id, channel_id in channel_warehouses.values_list(
+ "warehouse_id", "channel_id"
+ ):
+ warehouse_to_channel_mapping[warehouse_id].add(channel_id)
+
+ shipping_zone_channel_ids = set(
+ ShippingZoneChannel.objects.filter(
+ shippingzone_id=shipping_zone.id
+ ).values_list("channel_id", flat=True)
+ )
+
+ shipping_zone_warehouses_to_delete = []
+ for id, warehouse_id in warehouse_shipping_zones.values_list(
+ "id", "warehouse_id"
+ ):
+ warehouse_channels = warehouse_to_channel_mapping.get(warehouse_id, set())
+ # if there is no common channels between shipping zone and warehouse
+ # the relation should be deleted
+ if not warehouse_channels or not warehouse_channels.intersection(
+ shipping_zone_channel_ids
+ ):
+ shipping_zone_warehouses_to_delete.append(id)
+
+ WarehouseShippingZone.objects.filter(
+ id__in=shipping_zone_warehouses_to_delete
+ ).delete()
+
class ShippingZoneCreate(ShippingZoneMixin, ModelMutation):
class Arguments:
diff --git a/saleor/graphql/shipping/tests/mutations/test_shipping_zone_create.py b/saleor/graphql/shipping/tests/mutations/test_shipping_zone_create.py
index 8a59b75f12..30e2da0dee 100644
--- a/saleor/graphql/shipping/tests/mutations/test_shipping_zone_create.py
+++ b/saleor/graphql/shipping/tests/mutations/test_shipping_zone_create.py
@@ -34,6 +34,7 @@ CREATE_SHIPPING_ZONE_MUTATION = """
code
message
channels
+ warehouses
}
shippingZone {
id
@@ -58,6 +59,8 @@ CREATE_SHIPPING_ZONE_MUTATION = """
def test_create_shipping_zone(
staff_api_client, warehouse, permission_manage_shipping, channel_PLN
):
+ # given
+ warehouse.channels.add(channel_PLN)
warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)
channel_id = graphene.Node.to_global_id("Channel", channel_PLN.pk)
variables = {
@@ -67,11 +70,15 @@ def test_create_shipping_zone(
"addWarehouses": [warehouse_id],
"addChannels": [channel_id],
}
+
+ # when
response = staff_api_client.post_graphql(
CREATE_SHIPPING_ZONE_MUTATION,
variables,
permissions=[permission_manage_shipping],
)
+
+ # then
content = get_graphql_content(response)
data = content["data"]["shippingZoneCreate"]
zone = data["shippingZone"]
@@ -197,14 +204,17 @@ TEST_COUNTRIES_LIST = ["DZ", "AX", "BY"]
return_value=TEST_COUNTRIES_LIST,
)
def test_create_default_shipping_zone(
- _, staff_api_client, warehouse, permission_manage_shipping
+ _, staff_api_client, warehouse, permission_manage_shipping, channel_PLN
):
unassigned_countries = TEST_COUNTRIES_LIST
+ warehouse.channels.add(channel_PLN)
warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.pk)
variables = {
"default": True,
"name": "test shipping",
"countries": ["PL"],
+ "addChannels": [channel_id],
"addWarehouses": [warehouse_id],
}
response = staff_api_client.post_graphql(
@@ -246,3 +256,73 @@ def test_create_duplicated_default_shipping_zone(
assert data["errors"]
assert data["errors"][0]["field"] == "default"
assert data["errors"][0]["code"] == ShippingErrorCode.ALREADY_EXISTS.name
+
+
+def test_create_shipping_zone_invalid_warehouses_no_channels_assigned(
+ staff_api_client, warehouse, permission_manage_shipping, channel_PLN
+):
+ """Ensure an error is raised when warehouses without any channels are added."""
+ # given
+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.pk)
+ variables = {
+ "name": "test shipping",
+ "description": "test description",
+ "countries": ["PL"],
+ "addWarehouses": [warehouse_id],
+ "addChannels": [channel_id],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ CREATE_SHIPPING_ZONE_MUTATION,
+ variables,
+ permissions=[permission_manage_shipping],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["shippingZoneCreate"]
+ assert len(data["errors"]) == 1
+ assert data["errors"][0]["field"] == "addWarehouses"
+ assert data["errors"][0]["code"] == ShippingErrorCode.INVALID.name
+ assert data["errors"][0]["warehouses"] == [warehouse_id]
+
+
+def test_create_shipping_zone_invalid_warehouses(
+ staff_api_client, warehouses, permission_manage_shipping, channel_PLN, channel_USD
+):
+ """Ensure an error is raised when warehouses without common channel
+ with the shipping zone are added."""
+ # given
+ warehouse_ids = [
+ graphene.Node.to_global_id("Warehouse", warehouse.pk)
+ for warehouse in warehouses
+ ]
+ # add to warehouse on index 0 common channel with created shipping zone
+ warehouses[0].channels.add(channel_PLN)
+ # add to warehouse on index 1 another channel not common with shipping zone
+ warehouses[1].channels.add(channel_USD)
+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.pk)
+ variables = {
+ "name": "test shipping",
+ "description": "test description",
+ "countries": ["PL"],
+ "addWarehouses": warehouse_ids,
+ "addChannels": [channel_id],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ CREATE_SHIPPING_ZONE_MUTATION,
+ variables,
+ permissions=[permission_manage_shipping],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["shippingZoneCreate"]
+ assert len(data["errors"]) == 1
+ assert data["errors"][0]["field"] == "addWarehouses"
+ assert data["errors"][0]["code"] == ShippingErrorCode.INVALID.name
+ assert data["errors"][0]["warehouses"] == warehouse_ids[1:]
diff --git a/saleor/graphql/shipping/tests/mutations/test_shipping_zone_update.py b/saleor/graphql/shipping/tests/mutations/test_shipping_zone_update.py
index d175c55c85..0259f3ffd5 100644
--- a/saleor/graphql/shipping/tests/mutations/test_shipping_zone_update.py
+++ b/saleor/graphql/shipping/tests/mutations/test_shipping_zone_update.py
@@ -471,3 +471,168 @@ def test_update_shipping_zone_same_channel_id_in_add_and_remove_list(
data = content["data"]["shippingZoneUpdate"]["shippingZone"]
assert len(data["channels"]) == 1
assert data["channels"][0]["id"] == add_channel_id
+
+
+def test_update_shipping_zone_add_invalid_warehouses(
+ staff_api_client,
+ shipping_zone,
+ warehouses,
+ warehouse_JPY,
+ permission_manage_shipping,
+ channel_USD,
+ channel_PLN,
+ channel_JPY,
+):
+ """Ensure an error is raised when the warehouse that has not a common
+ channel with shipping zone is added."""
+ shipping_id = graphene.Node.to_global_id("ShippingZone", shipping_zone.pk)
+ # warehouse with common USD channel
+ warehouse_usd_id = graphene.Node.to_global_id("Warehouse", warehouses[0].pk)
+
+ # warehouse with common PLN channel
+ warehouse_pln_id = graphene.Node.to_global_id("Warehouse", warehouses[1].pk)
+ warehouses[1].channels.set([channel_PLN])
+
+ # assign only USD channel to shipping zone
+ # the channel PLN will be added in mutation
+ shipping_zone.channels.set([channel_USD])
+
+ # warehouse without common channel
+ warehouse_jpy_id = graphene.Node.to_global_id("Warehouse", warehouse_JPY.pk)
+ warehouse_JPY.channels.set([channel_JPY])
+
+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.pk)
+ variables = {
+ "id": shipping_id,
+ "name": shipping_zone.name,
+ "addWarehouses": [warehouse_usd_id, warehouse_jpy_id, warehouse_pln_id],
+ "addChannels": [channel_id],
+ }
+ response = staff_api_client.post_graphql(
+ UPDATE_SHIPPING_ZONE_MUTATION,
+ variables,
+ permissions=[permission_manage_shipping],
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["shippingZoneUpdate"]
+ assert len(data["errors"]) == 1
+ assert data["errors"][0]["field"] == "addWarehouses"
+ assert data["errors"][0]["code"] == ShippingErrorCode.INVALID.name
+ assert data["errors"][0]["warehouses"] == [warehouse_jpy_id]
+
+
+def test_update_shipping_zone_add_warehouse_without_any_channel(
+ staff_api_client,
+ shipping_zone,
+ warehouse,
+ permission_manage_shipping,
+ channel_PLN,
+):
+ """Ensure an error is raised when the warehouse that has not a common
+ channel with shipping zone is added."""
+ shipping_id = graphene.Node.to_global_id("ShippingZone", shipping_zone.pk)
+
+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)
+ warehouse.channels.clear()
+
+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.pk)
+ variables = {
+ "id": shipping_id,
+ "name": shipping_zone.name,
+ "addWarehouses": [warehouse_id],
+ "addChannels": [channel_id],
+ }
+ response = staff_api_client.post_graphql(
+ UPDATE_SHIPPING_ZONE_MUTATION,
+ variables,
+ permissions=[permission_manage_shipping],
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["shippingZoneUpdate"]
+ assert len(data["errors"]) == 1
+ assert data["errors"][0]["field"] == "addWarehouses"
+ assert data["errors"][0]["code"] == ShippingErrorCode.INVALID.name
+ assert data["errors"][0]["warehouses"] == [warehouse_id]
+
+
+def test_update_shipping_zone_add_warehouses_and_remove_common_channel(
+ staff_api_client,
+ shipping_zone,
+ warehouse,
+ channel_USD,
+ permission_manage_shipping,
+):
+ """Ensure an error is raised when the warehouse is added and common channel
+ with the shipping zone is removed."""
+ # given
+ shipping_id = graphene.Node.to_global_id("ShippingZone", shipping_zone.pk)
+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.pk)
+ variables = {
+ "id": shipping_id,
+ "name": shipping_zone.name,
+ "addWarehouses": [warehouse_id],
+ "removeChannels": [channel_id],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ UPDATE_SHIPPING_ZONE_MUTATION,
+ variables,
+ permissions=[permission_manage_shipping],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["shippingZoneUpdate"]
+ assert len(data["errors"]) == 1
+ assert data["errors"][0]["field"] == "addWarehouses"
+ assert data["errors"][0]["code"] == ShippingErrorCode.INVALID.name
+ assert data["errors"][0]["warehouses"] == [warehouse_id]
+
+
+def test_update_shipping_zone_remove_channels_remove_common_warehouse_channel(
+ staff_api_client,
+ shipping_zone,
+ warehouses,
+ channel_USD,
+ channel_PLN,
+ permission_manage_shipping,
+):
+ """Ensure the shipping zone to channel relation is deleted when common channel
+ is removed from shipping zone."""
+ # given
+ shipping_id = graphene.Node.to_global_id("ShippingZone", shipping_zone.pk)
+ channel_id = graphene.Node.to_global_id("Channel", channel_USD.pk)
+
+ shipping_zone.warehouses.add(*warehouses)
+ shipping_zone.channels.add(channel_PLN)
+
+ assert shipping_zone.channels.count() == 2
+
+ warehouses[1].channels.add(channel_PLN)
+
+ variables = {
+ "id": shipping_id,
+ "name": shipping_zone.name,
+ "removeChannels": [channel_id],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ UPDATE_SHIPPING_ZONE_MUTATION,
+ variables,
+ permissions=[permission_manage_shipping],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["shippingZoneUpdate"]
+ assert not data["errors"]
+ shipping_zone_data = content["data"]["shippingZoneUpdate"]["shippingZone"]
+ assert len(shipping_zone_data["channels"]) == 1
+ assert shipping_zone_data["channels"][0]["id"] == graphene.Node.to_global_id(
+ "Channel", channel_PLN.pk
+ )
+ assert len(shipping_zone_data["warehouses"]) == 1
+ assert shipping_zone_data["warehouses"][0]["slug"] == warehouses[1].slug
diff --git a/saleor/graphql/warehouse/dataloaders.py b/saleor/graphql/warehouse/dataloaders.py
index 2a03d0baaf..ab224f7c91 100644
--- a/saleor/graphql/warehouse/dataloaders.py
+++ b/saleor/graphql/warehouse/dataloaders.py
@@ -232,7 +232,8 @@ class StocksWithAvailableQuantityByProductVariantIdCountryCodeAndChannelLoader(
)
if channel_slug:
stocks = stocks.filter(
- warehouse__shipping_zones__channels__slug=channel_slug
+ warehouse__shipping_zones__channels__slug=channel_slug,
+ warehouse__channels__slug=channel_slug,
)
stocks = stocks.annotate_available_quantity()
@@ -347,3 +348,34 @@ class StockByIdLoader(DataLoader):
def batch_load(self, keys):
return Stock.objects.using(self.database_connection_name).in_bulk(keys).values()
+
+
+class WarehousesByChannelIdLoader(DataLoader):
+ context_key = "warehouse_by_channel"
+
+ def batch_load(self, keys):
+ WarehouseChannel = Warehouse.channels.through
+ warehouse_and_channel_in_pairs = (
+ WarehouseChannel.objects.using(self.database_connection_name)
+ .filter(channel_id__in=keys)
+ .values_list("warehouse_id", "channel_id")
+ )
+ channel_warehouse_map = defaultdict(list)
+ for warehouse_id, channel_id in warehouse_and_channel_in_pairs:
+ channel_warehouse_map[channel_id].append(warehouse_id)
+
+ def map_warehouses(warehouses):
+ warehouse_map = {warehouse.pk: warehouse for warehouse in warehouses}
+ return [
+ [
+ warehouse_map[warehouse_id]
+ for warehouse_id in channel_warehouse_map[channel_id]
+ ]
+ for channel_id in keys
+ ]
+
+ return (
+ WarehouseByIdLoader(self.context)
+ .load_many({pk for pk, _ in warehouse_and_channel_in_pairs})
+ .then(map_warehouses)
+ )
diff --git a/saleor/graphql/warehouse/filters.py b/saleor/graphql/warehouse/filters.py
index 501118ce83..23909d0485 100644
--- a/saleor/graphql/warehouse/filters.py
+++ b/saleor/graphql/warehouse/filters.py
@@ -5,8 +5,10 @@ from ...account.models import Address
from ...product.models import Product, ProductVariant
from ...warehouse import WarehouseClickAndCollectOption
from ...warehouse.models import Stock, Warehouse
+from ..channel.types import Channel
from ..core.filters import EnumFilter, GlobalIDMultipleChoiceFilter
from ..core.types import FilterInputObjectType
+from ..utils import resolve_global_ids_to_primary_keys
from ..warehouse.enums import WarehouseClickAndCollectOptionEnum
@@ -46,6 +48,17 @@ def filter_click_and_collect_option(qs, _, value):
return qs
+def filter_channels(qs, _, values):
+ if values:
+ _, channels_ids = resolve_global_ids_to_primary_keys(values, Channel)
+ WarehouseChannel = Warehouse.channels.through
+ warehouse_channels = WarehouseChannel.objects.filter(
+ channel_id__in=channels_ids
+ )
+ qs = qs.filter(Exists(warehouse_channels.filter(warehouse_id=OuterRef("id"))))
+ return qs
+
+
def filter_search_stock(qs, _, value):
if value:
products = Product.objects.filter(name__ilike=value).values("pk")
@@ -72,6 +85,7 @@ class WarehouseFilter(django_filters.FilterSet):
input_class=WarehouseClickAndCollectOptionEnum,
method=filter_click_and_collect_option,
)
+ channels = GlobalIDMultipleChoiceFilter(method=filter_channels)
class Meta:
model = Warehouse
diff --git a/saleor/graphql/warehouse/tests/test_stock.py b/saleor/graphql/warehouse/tests/test_stock.py
index 8b4b382f65..5ef26ded95 100644
--- a/saleor/graphql/warehouse/tests/test_stock.py
+++ b/saleor/graphql/warehouse/tests/test_stock.py
@@ -333,7 +333,7 @@ def test_stock_quantity_is_sum_of_quantities_from_warehouses_that_support_countr
# Create another warehouse with a different shipping zone that supports PL. As
# a result there should be two shipping zones and two warehouses that support PL.
- stocks = variant.stocks.for_country_and_channel("PL", channel_USD.slug)
+ stocks = variant.stocks.for_channel_and_country(channel_USD.slug, "PL")
warehouse = Warehouse.objects.create(
address=address.get_copy(),
name="WarehousePL",
@@ -341,9 +341,10 @@ def test_stock_quantity_is_sum_of_quantities_from_warehouses_that_support_countr
)
warehouse.shipping_zones.add(shipping_zone)
+ warehouse.channels.add(channel_USD)
Stock.objects.create(warehouse=warehouse, product_variant=variant, quantity=10)
- stocks = variant.stocks.for_country_and_channel("PL", channel_USD.slug)
+ stocks = variant.stocks.for_channel_and_country(channel_USD.slug, "PL")
sum_quantities = sum([stock.quantity for stock in stocks])
variables = {
diff --git a/saleor/graphql/warehouse/tests/test_warehouse.py b/saleor/graphql/warehouse/tests/test_warehouse.py
index 9f2cd3d63f..7bd012aea5 100644
--- a/saleor/graphql/warehouse/tests/test_warehouse.py
+++ b/saleor/graphql/warehouse/tests/test_warehouse.py
@@ -558,6 +558,62 @@ def test_query_warehouses_with_filters_and_no_id(
assert total_count == 0
+def test_query_warehouses_with_filters_by_channels(
+ staff_api_client,
+ permission_manage_products,
+ warehouses,
+ warehouse_JPY,
+ channel_PLN,
+ channel_JPY,
+):
+ # given
+ warehouses[1].channels.add(channel_PLN)
+
+ channel_ids = [
+ graphene.Node.to_global_id("Channel", channel.id)
+ for channel in [channel_PLN, channel_JPY]
+ ]
+
+ variables_exists = {"filters": {"channels": channel_ids}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_WAREHOUSES_WITH_FILTERS,
+ variables=variables_exists,
+ permissions=[permission_manage_products],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ warehouses_data = content["data"]["warehouses"]["edges"]
+ assert len(warehouses_data) == 2
+ assert {warehouse_data["node"]["name"] for warehouse_data in warehouses_data} == {
+ warehouses[1].name,
+ warehouse_JPY.name,
+ }
+
+
+def test_query_warehouses_with_filters_by_channels_no_warehouse_returned(
+ staff_api_client, permission_manage_products, warehouses, channel_PLN
+):
+ # given
+ channel_id = graphene.Node.to_global_id("Channel", channel_PLN.id)
+
+ variables_exists = {"filters": {"channels": [channel_id]}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_WAREHOUSES_WITH_FILTERS,
+ variables=variables_exists,
+ permissions=[permission_manage_products],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ warehouses_data = content["data"]["warehouses"]["edges"]
+ assert not warehouses_data
+
+
def test_mutation_create_warehouse(
staff_api_client, permission_manage_products, shipping_zone
):
diff --git a/saleor/order/actions.py b/saleor/order/actions.py
index 42ff72c510..6368a53abe 100644
--- a/saleor/order/actions.py
+++ b/saleor/order/actions.py
@@ -656,7 +656,7 @@ def _create_fulfillment_lines(
lines = [line_data["order_line"] for line_data in lines_data]
variants = [line.variant for line in lines]
stocks = (
- Stock.objects.for_channel(channel_slug)
+ Stock.objects.for_channel_and_country(channel_slug)
.filter(warehouse_id=warehouse_pk, product_variant__in=variants)
.select_related("product_variant")
)
diff --git a/saleor/order/tests/test_order.py b/saleor/order/tests/test_order.py
index b7a8d58a87..d191da34ca 100644
--- a/saleor/order/tests/test_order.py
+++ b/saleor/order/tests/test_order.py
@@ -1285,7 +1285,7 @@ def test_available_collection_points_for_preorders_variants_in_order(
api_client, staff_api_client, order_with_preorder_lines
):
expected_collection_points = list(
- Warehouse.objects.for_country("US")
+ Warehouse.objects.for_channel(order_with_preorder_lines.channel_id)
.exclude(
click_and_collect_option=WarehouseClickAndCollectOption.DISABLED,
)
@@ -1310,7 +1310,7 @@ def test_available_collection_points_for_preorders_and_regular_variants_in_order
order_with_preorder_lines,
):
expected_collection_points = list(
- Warehouse.objects.for_country("US")
+ Warehouse.objects.for_channel(order_with_preorder_lines.channel_id)
.exclude(
click_and_collect_option=WarehouseClickAndCollectOption.DISABLED,
)
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index 07c8b91528..1b2e69e2de 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -714,18 +714,16 @@ def is_shipping_required(lines: Iterable["OrderLine"]):
return any(line.is_shipping_required for line in lines)
-def get_valid_collection_points_for_order(lines: Iterable["OrderLine"], address):
+def get_valid_collection_points_for_order(
+ lines: Iterable["OrderLine"], channel_id: int
+):
if not is_shipping_required(lines):
return []
- if not address:
- return []
line_ids = [line.id for line in lines]
lines = OrderLine.objects.filter(id__in=line_ids)
- return Warehouse.objects.applicable_for_click_and_collect(
- lines, address.country.code
- )
+ return Warehouse.objects.applicable_for_click_and_collect(lines, channel_id)
def get_discounted_lines(lines, voucher):
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 40da382a59..e9afe1e827 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -5373,7 +5373,7 @@ def staff_notification_recipient(db, staff_user):
@pytest.fixture
-def warehouse(address, shipping_zone):
+def warehouse(address, shipping_zone, channel_USD):
warehouse = Warehouse.objects.create(
address=address,
name="Example Warehouse",
@@ -5381,12 +5381,13 @@ def warehouse(address, shipping_zone):
)
warehouse.shipping_zones.add(shipping_zone)
+ warehouse.channels.add(channel_USD)
warehouse.save()
return warehouse
@pytest.fixture
-def warehouse_JPY(address, shipping_zone_JPY):
+def warehouse_JPY(address, shipping_zone_JPY, channel_JPY):
warehouse = Warehouse.objects.create(
address=address,
name="Example Warehouse JPY",
@@ -5394,13 +5395,14 @@ def warehouse_JPY(address, shipping_zone_JPY):
)
warehouse.shipping_zones.add(shipping_zone_JPY)
+ warehouse.channels.add(channel_JPY)
warehouse.save()
return warehouse
@pytest.fixture
-def warehouses(address, address_usa):
- return Warehouse.objects.bulk_create(
+def warehouses(address, address_usa, channel_USD):
+ warehouses = Warehouse.objects.bulk_create(
[
Warehouse(
address=address.get_copy(),
@@ -5416,10 +5418,13 @@ def warehouses(address, address_usa):
),
]
)
+ for warehouse in warehouses:
+ warehouse.channels.add(channel_USD)
+ return warehouses
@pytest.fixture()
-def warehouses_for_cc(address, shipping_zones):
+def warehouses_for_cc(address, shipping_zones, channel_USD):
warehouses = Warehouse.objects.bulk_create(
[
Warehouse(
@@ -5453,15 +5458,14 @@ def warehouses_for_cc(address, shipping_zones):
),
]
)
- for warehouse in warehouses:
- warehouse.shipping_zones.add(shipping_zones[0])
- warehouse.shipping_zones.add(shipping_zones[1])
- warehouse.save()
+ for shipping_zone in shipping_zones:
+ shipping_zone.warehouses.add(*warehouses)
+ channel_USD.warehouses.add(*warehouses)
return warehouses
@pytest.fixture
-def warehouse_for_cc(address, product_variant_list, shipping_zones):
+def warehouse_for_cc(address, product_variant_list, shipping_zones, channel_USD):
warehouse = Warehouse.objects.create(
address=address.get_copy(),
name="Local Warehouse",
@@ -5470,8 +5474,8 @@ def warehouse_for_cc(address, product_variant_list, shipping_zones):
is_private=False,
click_and_collect_option=WarehouseClickAndCollectOption.LOCAL_STOCK,
)
- warehouse.shipping_zones.add(shipping_zones[0])
- warehouse.shipping_zones.add(shipping_zones[1])
+ warehouse.shipping_zones.add(shipping_zones[0], shipping_zones[1])
+ warehouse.channels.add(channel_USD)
Stock.objects.bulk_create(
[
@@ -5605,13 +5609,14 @@ def warehouses_with_different_shipping_zone(warehouses, shipping_zones):
@pytest.fixture
-def warehouse_no_shipping_zone(address):
+def warehouse_no_shipping_zone(address, channel_USD):
warehouse = Warehouse.objects.create(
address=address,
name="Warehouse without shipping zone",
slug="warehouse-no-shipping-zone",
)
+ warehouse.channels.add(channel_USD)
return warehouse
diff --git a/saleor/warehouse/availability.py b/saleor/warehouse/availability.py
index f47168f28e..7bf9bf0152 100644
--- a/saleor/warehouse/availability.py
+++ b/saleor/warehouse/availability.py
@@ -225,7 +225,7 @@ def check_stock_quantity_bulk(
filter_lookup.update(additional_filter_lookup)
all_variants_stocks = (
- Stock.objects.for_country_and_channel(country_code, channel_slug)
+ Stock.objects.for_channel_and_country(channel_slug, country_code)
.filter(**filter_lookup)
.annotate_available_quantity()
)
diff --git a/saleor/warehouse/management.py b/saleor/warehouse/management.py
index 94f8741513..f92c9ac44f 100644
--- a/saleor/warehouse/management.py
+++ b/saleor/warehouse/management.py
@@ -67,7 +67,7 @@ def allocate_stocks(
stocks = list(
Stock.objects.select_for_update(of=("self",))
- .for_country_and_channel(country_code, channel_slug)
+ .for_channel_and_country(channel_slug, country_code)
.filter(**filter_lookup)
.order_by("pk")
.values("id", "product_variant", "pk", "quantity")
@@ -107,6 +107,14 @@ def allocate_stocks(
"quantity_allocated_sum"
]
+ def sort_stocks(stock_data):
+ return stock_data["quantity"] - quantity_allocation_for_stocks.get(
+ stock_data["pk"], 0
+ )
+
+ # prioritize stocks with the highest quantity available
+ stocks.sort(key=sort_stocks, reverse=True)
+
variant_to_stocks: Dict[str, List[StockData]] = defaultdict(list)
for stock_data in stocks:
variant = stock_data.pop("product_variant")
diff --git a/saleor/warehouse/migrations/0029_warehouse_channels.py b/saleor/warehouse/migrations/0029_warehouse_channels.py
new file mode 100644
index 0000000000..8465ea7b85
--- /dev/null
+++ b/saleor/warehouse/migrations/0029_warehouse_channels.py
@@ -0,0 +1,21 @@
+# Generated by Django 3.2.13 on 2022-06-14 08:36
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("channel", "0003_alter_channel_default_country"),
+ ("warehouse", "0028_rewrite_checkouline_relations"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="warehouse",
+ name="channels",
+ field=models.ManyToManyField(
+ related_name="warehouses", to="channel.Channel"
+ ),
+ ),
+ ]
diff --git a/saleor/warehouse/migrations/0030_add_channels_to_warehouses.py b/saleor/warehouse/migrations/0030_add_channels_to_warehouses.py
new file mode 100644
index 0000000000..349d6ad736
--- /dev/null
+++ b/saleor/warehouse/migrations/0030_add_channels_to_warehouses.py
@@ -0,0 +1,25 @@
+# Generated by Django 3.2.13 on 2022-06-14 08:42
+
+from django.db import migrations
+
+
+def add_relations_between_existing_channels_and_warehouses(apps, schema_editor):
+ Channel = apps.get_model("channel", "Channel")
+ Warehouse = apps.get_model("warehouse", "Warehouse")
+ warehouse_ids = Warehouse.objects.values_list("id", flat=True)
+ for channel in Channel.objects.iterator():
+ channel.warehouses.set(warehouse_ids)
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("warehouse", "0029_warehouse_channels"),
+ ]
+
+ operations = [
+ migrations.RunPython(
+ add_relations_between_existing_channels_and_warehouses,
+ migrations.RunPython.noop,
+ ),
+ ]
diff --git a/saleor/warehouse/models.py b/saleor/warehouse/models.py
index fb0ace74b6..54826e94b8 100644
--- a/saleor/warehouse/models.py
+++ b/saleor/warehouse/models.py
@@ -20,18 +20,47 @@ from . import WarehouseClickAndCollectOption
class WarehouseQueryset(models.QuerySet):
- def prefetch_data(self):
- return self.select_related("address").prefetch_related("shipping_zones")
+ def for_channel(self, channel_id: int):
+ WarehouseChannel = Channel.warehouses.through # type: ignore
+ return self.filter(
+ Exists(
+ WarehouseChannel.objects.filter(
+ channel_id=channel_id, warehouse_id=OuterRef("id")
+ )
+ )
+ ).order_by("pk")
- def for_country(self, country: str):
- return (
- self.prefetch_data()
- .filter(shipping_zones__countries__contains=country)
- .order_by("pk")
+ def for_country_and_channel(self, country: str, channel_id: int):
+ ShippingZoneChannel = Channel.shipping_zones.through # type: ignore
+ WarehouseShippingZone = ShippingZone.warehouses.through # type: ignore
+ WarehouseChannel = Channel.warehouses.through # type: ignore
+
+ shipping_zones = ShippingZone.objects.filter(
+ countries__contains=country
+ ).values("pk")
+ shipping_zone_channels = ShippingZoneChannel.objects.filter(
+ Exists(shipping_zones.filter(pk=OuterRef("shippingzone_id"))),
+ channel_id=channel_id,
)
+ warehouse_shipping_zones = WarehouseShippingZone.objects.filter(
+ Exists(
+ shipping_zone_channels.filter(
+ shippingzone_id=OuterRef("shippingzone_id")
+ )
+ ),
+ Exists(
+ WarehouseChannel.objects.filter(
+ channel_id=channel_id, warehouse_id=OuterRef("warehouse_id")
+ )
+ ),
+ ).values("warehouse_id")
+ return self.filter(
+ Exists(warehouse_shipping_zones.filter(warehouse_id=OuterRef("pk")))
+ ).order_by("pk")
+
def applicable_for_click_and_collect_no_quantity_check(
- self, lines_qs: QuerySet[CheckoutLine], country: str
+ self, lines_qs: QuerySet[CheckoutLine], channel_id: int
):
"""Return the queryset of a `Warehouse` which are applicable for click and collect.
@@ -43,16 +72,16 @@ class WarehouseQueryset(models.QuerySet):
line.variant.is_preorder_active()
for line in lines_qs.select_related("variant").only("variant_id")
):
- return self._for_country_click_and_collect(country)
+ return self._for_channel_click_and_collect(channel_id)
stocks_qs = Stock.objects.filter(
product_variant__id__in=lines_qs.values("variant_id"),
).select_related("product_variant")
- return self._for_country_lines_and_stocks(lines_qs, stocks_qs, country)
+ return self._for_channel_lines_and_stocks(lines_qs, stocks_qs, channel_id)
def applicable_for_click_and_collect(
- self, lines_qs: QuerySet[CheckoutLine], country: str
+ self, lines_qs: QuerySet[CheckoutLine], channel_id: int
) -> QuerySet["Warehouse"]:
"""Return the queryset of a `Warehouse` which are applicable for click and collect.
@@ -65,7 +94,7 @@ class WarehouseQueryset(models.QuerySet):
line.variant.is_preorder_active()
for line in lines_qs.select_related("variant").only("variant_id")
):
- return self._for_country_click_and_collect(country)
+ return self._for_channel_click_and_collect(channel_id)
lines_quantity = (
lines_qs.filter(variant_id=OuterRef("product_variant_id"))
@@ -84,18 +113,18 @@ class WarehouseQueryset(models.QuerySet):
.select_related("product_variant")
)
- return self._for_country_lines_and_stocks(lines_qs, stocks_qs, country)
+ return self._for_channel_lines_and_stocks(lines_qs, stocks_qs, channel_id)
- def _for_country_lines_and_stocks(
+ def _for_channel_lines_and_stocks(
self,
lines_qs: QuerySet[CheckoutLine],
stocks_qs: QuerySet["Stock"],
- country: str,
+ channel_id: int,
) -> QuerySet["Warehouse"]:
warehouse_cc_option_enum = WarehouseClickAndCollectOption
return (
- self.for_country(country)
+ self.for_channel(channel_id)
.prefetch_related(Prefetch("stock_set", queryset=stocks_qs))
.filter(stock__in=stocks_qs)
.annotate(stock_num=Count("stock__id", distinct=True))
@@ -106,8 +135,8 @@ class WarehouseQueryset(models.QuerySet):
)
)
- def _for_country_click_and_collect(self, country: str) -> QuerySet["Warehouse"]:
- return self.for_country(country).filter(
+ def _for_channel_click_and_collect(self, channel_id: int) -> QuerySet["Warehouse"]:
+ return self.for_channel(channel_id).filter(
click_and_collect_option__in=[
WarehouseClickAndCollectOption.LOCAL_STOCK,
WarehouseClickAndCollectOption.ALL_WAREHOUSES,
@@ -116,10 +145,10 @@ class WarehouseQueryset(models.QuerySet):
class Warehouse(ModelWithMetadata):
-
id = models.UUIDField(default=uuid.uuid4, primary_key=True)
name = models.CharField(max_length=250)
slug = models.SlugField(max_length=255, unique=True, allow_unicode=True)
+ channels = models.ManyToManyField(Channel, related_name="warehouses")
shipping_zones = models.ManyToManyField(
ShippingZone, blank=True, related_name="warehouses"
)
@@ -175,19 +204,40 @@ class StockQuerySet(models.QuerySet):
)
)
- def for_channel(self, channel_slug: str):
+ def for_channel_and_country(
+ self, channel_slug: str, country_code: Optional[str] = None
+ ):
ShippingZoneChannel = Channel.shipping_zones.through # type: ignore
WarehouseShippingZone = ShippingZone.warehouses.through # type: ignore
+ WarehouseChannel = Channel.warehouses.through # type: ignore
+
channels = Channel.objects.filter(slug=channel_slug).values("pk")
+
shipping_zone_channels = ShippingZoneChannel.objects.filter(
Exists(channels.filter(pk=OuterRef("channel_id")))
- ).values("shippingzone_id")
+ )
+
+ if country_code:
+ shipping_zones = ShippingZone.objects.filter(
+ countries__contains=country_code
+ ).values("pk")
+ shipping_zone_channels = shipping_zone_channels.filter(
+ Exists(shipping_zones.filter(pk=OuterRef("shippingzone_id")))
+ )
+
+ shipping_zone_channels.values("shippingzone_id")
+
+ warehouse_channels = WarehouseChannel.objects.filter(
+ Exists(channels.filter(pk=OuterRef("channel_id")))
+ ).values("warehouse_id")
+
warehouse_shipping_zones = WarehouseShippingZone.objects.filter(
Exists(
shipping_zone_channels.filter(
shippingzone_id=OuterRef("shippingzone_id")
)
- )
+ ),
+ Exists(warehouse_channels.filter(warehouse_id=OuterRef("warehouse_id"))),
).values("warehouse_id")
return self.select_related("product_variant").filter(
Exists(
@@ -195,17 +245,6 @@ class StockQuerySet(models.QuerySet):
)
)
- def for_country_and_channel(self, country_code: str, channel_slug):
- filter_lookup = {"shipping_zones__countries__contains": country_code}
- if channel_slug is not None:
- filter_lookup["shipping_zones__channels__slug"] = channel_slug
- query_warehouse = models.Subquery(
- Warehouse.objects.filter(**filter_lookup).values("pk")
- )
- return self.select_related("product_variant", "warehouse").filter(
- warehouse__in=query_warehouse
- )
-
def get_variant_stocks_for_country(
self, country_code: str, channel_slug: str, product_variant: ProductVariant
):
@@ -213,7 +252,7 @@ class StockQuerySet(models.QuerySet):
Note it will raise a 'Stock.DoesNotExist' exception if no such stock is found.
"""
- return self.for_country_and_channel(country_code, channel_slug).filter(
+ return self.for_channel_and_country(channel_slug, country_code).filter(
product_variant=product_variant
)
@@ -227,14 +266,14 @@ class StockQuerySet(models.QuerySet):
Note it will raise a 'Stock.DoesNotExist' exception if no such stock is found.
"""
- return self.for_country_and_channel(country_code, channel_slug).filter(
+ return self.for_channel_and_country(channel_slug, country_code).filter(
product_variant__in=products_variants
)
def get_product_stocks_for_country_and_channel(
self, country_code: str, channel_slug: str, product: Product
):
- return self.for_country_and_channel(country_code, channel_slug).filter(
+ return self.for_channel_and_country(channel_slug, country_code).filter(
product_variant__product_id=product.pk
)
diff --git a/saleor/warehouse/tests/test_stock.py b/saleor/warehouse/tests/test_stock.py
index 5552ab6102..c1007e0751 100644
--- a/saleor/warehouse/tests/test_stock.py
+++ b/saleor/warehouse/tests/test_stock.py
@@ -6,7 +6,7 @@ COUNTRY_CODE = "US"
def test_stocks_for_country(variant_with_many_stocks, channel_USD):
[stock1, stock2] = (
Stock.objects.filter(product_variant=variant_with_many_stocks)
- .for_country_and_channel(COUNTRY_CODE, channel_USD.slug)
+ .for_channel_and_country(channel_USD.slug, COUNTRY_CODE)
.order_by("pk")
.all()
)
@@ -25,7 +25,21 @@ def test_stock_for_country_does_not_exists(product, warehouse, channel_PLN):
warehouse.refresh_from_db()
fake_country_code = "PL"
assert fake_country_code not in warehouse.countries
- stock_qs = Stock.objects.for_country_and_channel(
- fake_country_code, channel_PLN.slug
+ stock_qs = Stock.objects.for_channel_and_country(
+ channel_PLN.slug,
+ fake_country_code,
)
assert not stock_qs.exists()
+
+
+def test_stocks_for_country_warehouse_with_given_channel_do_not_exist(
+ variant_with_many_stocks, channel_PLN
+):
+ stock_qs = (
+ Stock.objects.filter(product_variant=variant_with_many_stocks)
+ .for_channel_and_country(channel_PLN.slug, COUNTRY_CODE)
+ .order_by("pk")
+ .all()
+ )
+
+ assert not stock_qs.exists()
diff --git a/saleor/warehouse/tests/test_stock_management.py b/saleor/warehouse/tests/test_stock_management.py
index 09cf9410f0..8a650594f6 100644
--- a/saleor/warehouse/tests/test_stock_management.py
+++ b/saleor/warehouse/tests/test_stock_management.py
@@ -148,18 +148,33 @@ def test_allocate_stock_many_stocks_partially_allocated(
order_line_with_one_allocation,
channel_USD,
):
+ # given
allocated_line = order_line_with_allocation_in_many_stocks
variant = allocated_line.variant
- stocks = variant.stocks.all()
+ stock_ids = list(
+ variant.stocks.annotate_available_quantity()
+ .order_by("-available_quantity")
+ .values_list("id", flat=True)
+ )
line_data = OrderLineInfo(line=order_line, variant=order_line.variant, quantity=3)
+
+ # when
allocate_stocks(
[line_data], COUNTRY_CODE, channel_USD.slug, manager=get_plugins_manager()
)
- allocations = Allocation.objects.filter(order_line=order_line, stock__in=stocks)
- assert allocations[0].quantity_allocated == 1
- assert allocations[1].quantity_allocated == 2
+ # then
+ # ensure that we firstly allocate stocks with the highest quantity available
+ allocations = Allocation.objects.filter(
+ order_line=order_line, stock_id__in=stock_ids
+ ).values("stock_id", "quantity_allocated")
+ stock_to_quantity_allocated = {
+ allocation["stock_id"]: allocation["quantity_allocated"]
+ for allocation in allocations
+ }
+ assert stock_to_quantity_allocated[stock_ids[0]] == 2
+ assert stock_to_quantity_allocated[stock_ids[1]] == 1
def test_allocate_stock_partially_allocated_insufficient_stocks(
diff --git a/saleor/warehouse/tests/test_stock_reservations_management.py b/saleor/warehouse/tests/test_stock_reservations_management.py
index 614968e87b..7b4fe196f0 100644
--- a/saleor/warehouse/tests/test_stock_reservations_management.py
+++ b/saleor/warehouse/tests/test_stock_reservations_management.py
@@ -75,6 +75,7 @@ def test_multiple_stocks_are_reserved_if_single_stock_is_not_enough(
email=warehouse.email,
)
secondary_warehouse.shipping_zones.add(shipping_zone)
+ secondary_warehouse.channels.add(channel_USD)
secondary_warehouse.save()
secondary_stock = Stock.objects.create(
diff --git a/saleor/warehouse/tests/test_warehouse.py b/saleor/warehouse/tests/test_warehouse.py
index 881aafafcd..f98d15c5bb 100644
--- a/saleor/warehouse/tests/test_warehouse.py
+++ b/saleor/warehouse/tests/test_warehouse.py
@@ -1,20 +1,17 @@
import pytest
from django.db.models import Sum
-from ...shipping.models import ShippingZone
from .. import WarehouseClickAndCollectOption
from ..models import Stock, Warehouse
def test_applicable_for_click_and_collect_finds_warehouse_with_all_and_local(
- stocks_for_cc, checkout_with_items_for_cc
+ stocks_for_cc, checkout_with_items_for_cc, channel_USD
):
expected_number_of_warehouses = 2
lines = checkout_with_items_for_cc.lines.all()
- result = Warehouse.objects.applicable_for_click_and_collect(
- lines, checkout_with_items_for_cc.shipping_address.country.code
- )
+ result = 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
@@ -25,7 +22,7 @@ def test_applicable_for_click_and_collect_finds_warehouse_with_all_and_local(
def test_applicable_for_click_and_collect_quantity_exceeded_for_local(
- stocks_for_cc, checkout_with_items_for_cc
+ stocks_for_cc, checkout_with_items_for_cc, channel_USD
):
expected_number_of_warehouses = Warehouse.objects.filter(
click_and_collect_option=WarehouseClickAndCollectOption.ALL_WAREHOUSES
@@ -44,16 +41,14 @@ def test_applicable_for_click_and_collect_quantity_exceeded_for_local(
line.save(update_fields=["quantity"])
checkout_with_items_for_cc.refresh_from_db()
- result = Warehouse.objects.applicable_for_click_and_collect(
- lines, checkout_with_items_for_cc.shipping_address.country.code
- )
+ result = Warehouse.objects.applicable_for_click_and_collect(lines, channel_USD.id)
assert result.count() == expected_number_of_warehouses
with pytest.raises(Warehouse.DoesNotExist):
result.get(click_and_collect_option=WarehouseClickAndCollectOption.LOCAL_STOCK)
def test_applicable_for_click_and_collect_for_one_line_two_local_warehouses(
- stocks_for_cc, checkout_with_item_for_cc
+ stocks_for_cc, checkout_with_item_for_cc, channel_USD
):
expected_total_number_of_warehouses = Warehouse.objects.exclude(
click_and_collect_option=WarehouseClickAndCollectOption.DISABLED
@@ -66,9 +61,7 @@ def test_applicable_for_click_and_collect_for_one_line_two_local_warehouses(
)
lines = checkout_with_item_for_cc.lines.all()
- result = Warehouse.objects.applicable_for_click_and_collect(
- lines, checkout_with_item_for_cc.shipping_address.country.code
- )
+ result = Warehouse.objects.applicable_for_click_and_collect(lines, channel_USD.id)
assert result.count() == expected_total_number_of_warehouses
assert (
result.filter(
@@ -85,7 +78,7 @@ def test_applicable_for_click_and_collect_for_one_line_two_local_warehouses(
def test_applicable_for_click_and_collect_does_not_show_warehouses_with_empty_stocks(
- stocks_for_cc, checkout_with_items_for_cc
+ stocks_for_cc, checkout_with_items_for_cc, channel_USD
):
expected_total_number_of_warehouses = 1
reduced_stock_quantity = 0
@@ -97,9 +90,7 @@ def test_applicable_for_click_and_collect_does_not_show_warehouses_with_empty_st
stock.quantity = reduced_stock_quantity
stock.save(update_fields=["quantity"])
- result = Warehouse.objects.applicable_for_click_and_collect(
- lines, checkout_with_items_for_cc.shipping_address.country.code
- )
+ 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
@@ -108,7 +99,11 @@ def test_applicable_for_click_and_collect_does_not_show_warehouses_with_empty_st
def test_applicable_for_click_and_collect_additional_stock_does_not_change_availbility(
- stocks_for_cc, checkout_with_items_for_cc, warehouses_for_cc, product_variant_list
+ stocks_for_cc,
+ checkout_with_items_for_cc,
+ warehouses_for_cc,
+ product_variant_list,
+ channel_USD,
):
expected_total_number_of_stocks = 5
expected_total_number_of_warehouses = 2
@@ -119,9 +114,7 @@ def test_applicable_for_click_and_collect_additional_stock_does_not_change_avail
)
lines = checkout_with_items_for_cc.lines.all()
- result = Warehouse.objects.applicable_for_click_and_collect(
- lines, checkout_with_items_for_cc.shipping_address.country.code
- )
+ result = Warehouse.objects.applicable_for_click_and_collect(lines, channel_USD.id)
assert result.count() == expected_total_number_of_warehouses
result.get(click_and_collect_option=WarehouseClickAndCollectOption.ALL_WAREHOUSES)
@@ -134,46 +127,25 @@ def test_applicable_for_click_and_collect_additional_stock_does_not_change_avail
assert lines.count() == expected_number_of_checkout_lines
-def test_applicable_for_click_and_collect_returns_empty_collection_if_no_shipping_zone(
- warehouse_for_cc, checkout_with_items_for_cc
+def test_applicable_for_click_and_collect_returns_empty_collection_if_no_channels(
+ warehouse_for_cc, checkout_with_items_for_cc, channel_USD
):
lines = checkout_with_items_for_cc.lines.all()
- result = Warehouse.objects.applicable_for_click_and_collect(
- lines, checkout_with_items_for_cc.shipping_address.country.code
- )
+ result = Warehouse.objects.applicable_for_click_and_collect(lines, channel_USD.id)
assert result.count() == 1
- warehouse_for_cc.shipping_zones.clear()
- result = Warehouse.objects.applicable_for_click_and_collect(
- lines, checkout_with_items_for_cc.shipping_address.country.code
- )
+ warehouse_for_cc.channels.clear()
+ result = Warehouse.objects.applicable_for_click_and_collect(lines, channel_USD.id)
assert not result
-def test_applicable_for_click_and_collect_returns_empty_collection_if_different_zone(
- warehouse_for_cc, checkout_with_items_for_cc
+def test_applicable_for_click_and_collect_returns_empty_collection_if_different_channel(
+ warehouse_for_cc, checkout_with_items_for_cc, channel_PLN
):
lines = checkout_with_items_for_cc.lines.all()
warehouse_for_cc.shipping_zones.filter(name="Poland").delete()
- result = Warehouse.objects.applicable_for_click_and_collect(
- lines, checkout_with_items_for_cc.shipping_address.country.code
- )
+ result = Warehouse.objects.applicable_for_click_and_collect(lines, channel_PLN.id)
assert not result
-
-
-def test_applicable_for_click_and_collect_when_country_is_duplicated_within_zones(
- warehouse_for_cc, checkout_with_items_for_cc
-):
- shipping_zone = ShippingZone.objects.create(name="Poland", countries=["PL"])
- warehouse_for_cc.shipping_zones.add(shipping_zone)
-
- lines = checkout_with_items_for_cc.lines.all()
-
- result = Warehouse.objects.applicable_for_click_and_collect(
- lines, checkout_with_items_for_cc.shipping_address.country.code
- )
-
- assert result.count() == 1
diff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.py
index 8c4153b778..1b36bea3e4 100644
--- a/saleor/webhook/payloads.py
+++ b/saleor/webhook/payloads.py
@@ -491,8 +491,8 @@ def generate_checkout_payload(
# todo use the most appropriate warehouse
warehouse = None
if checkout.shipping_address:
- warehouse = Warehouse.objects.for_country(
- checkout.shipping_address.country.code
+ warehouse = Warehouse.objects.for_country_and_channel(
+ checkout.shipping_address.country.code, checkout.channel_id
).first()
checkout_data = serializer.serialize(
@@ -879,7 +879,9 @@ def generate_fulfillment_payload(
if fulfillment_line and fulfillment_line.stock:
warehouse = fulfillment_line.stock.warehouse
else:
- warehouse = Warehouse.objects.for_country(order_country).first()
+ warehouse = Warehouse.objects.for_country_and_channel(
+ order_country, order.channel_id
+ ).first()
fulfillment_data = serializer.serialize(
[fulfillment],
fields=fulfillment_fields,