Skip to content

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

Split warehouse module (#13147)

Iga Karbowiakca30c6fe975e
diff --git a/saleor/graphql/product/tests/queries/test_variant_query.py b/saleor/graphql/product/tests/queries/test_variant_query.py
index 62d6d75e86..eaab3ea022 100644
--- a/saleor/graphql/product/tests/queries/test_variant_query.py
+++ b/saleor/graphql/product/tests/queries/test_variant_query.py
@@ -6,6 +6,7 @@ from .....attribute.utils import (
_associate_attribute_to_instance,
associate_attribute_values_to_instance,
)
+from .....warehouse.models import Stock, Warehouse
from ....tests.utils import (
assert_graphql_error_with_message,
get_graphql_content,
@@ -923,3 +924,116 @@ def test_variant_query_with_invalid_object_type(user_api_client, variant, channe
response = user_api_client.post_graphql(QUERY_PRODUCT_VARIANT_BY_ID, variables)
content = get_graphql_content(response)
assert content["data"]["productVariant"] is None
+
+
+def test_stock_quantities_in_different_warehouses(
+ api_client, channel_USD, variant_with_many_stocks_different_shipping_zones
+):
+ query = """
+ query ProductVariant(
+ $id: ID!, $channel: String!, $country1: CountryCode, $country2: CountryCode
+ ) {
+ productVariant(id: $id, channel: $channel) {
+ quantityPL: quantityAvailable(address: { country: $country1 })
+ quantityUS: quantityAvailable(address: { country: $country2 })
+ quantityNoAddress: quantityAvailable
+ }
+ }
+ """
+
+ variant = variant_with_many_stocks_different_shipping_zones
+ stock_map = {}
+ for stock in variant.stocks.all():
+ country = stock.warehouse.shipping_zones.get().countries[0]
+ stock_map[country.code] = stock.quantity
+
+ variables = {
+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),
+ "channel": channel_USD.slug,
+ "country1": "PL",
+ "country2": "US",
+ }
+ response = api_client.post_graphql(
+ query,
+ variables,
+ )
+ content = get_graphql_content(response)
+
+ assert content["data"]["productVariant"]["quantityPL"] == stock_map["PL"]
+ assert content["data"]["productVariant"]["quantityUS"] == stock_map["US"]
+
+ # when country is not provided, should return max value of all available stock
+ # quantities
+ assert content["data"]["productVariant"]["quantityNoAddress"] == max(
+ stock_map.values()
+ )
+
+
+def test_stock_quantity_is_max_from_all_warehouses_without_provided_country(
+ api_client, channel_USD, variant_with_many_stocks_different_shipping_zones
+):
+ query = """
+ query ProductVariant($id: ID!, $channel: String!) {
+ productVariant(id: $id, channel: $channel) {
+ quantityAvailable
+ }
+ }
+ """
+
+ variant = variant_with_many_stocks_different_shipping_zones
+ max_warehouse_quantity = max([stock.quantity for stock in variant.stocks.all()])
+
+ variables = {
+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),
+ "channel": channel_USD.slug,
+ }
+ response = api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+
+ assert (
+ content["data"]["productVariant"]["quantityAvailable"] == max_warehouse_quantity
+ )
+
+
+def test_stock_quantity_is_sum_of_quantities_from_warehouses_that_support_country(
+ api_client,
+ address,
+ channel_USD,
+ shipping_zone,
+ variant_with_many_stocks_different_shipping_zones,
+):
+ query = """
+ query ProductVariant($id: ID!, $channel: String!, $country: CountryCode) {
+ productVariant(id: $id, channel: $channel) {
+ quantityAvailable(address: { country: $country })
+ }
+ }
+ """
+
+ variant = variant_with_many_stocks_different_shipping_zones
+
+ # 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_channel_and_country(channel_USD.slug, "PL")
+ warehouse = Warehouse.objects.create(
+ address=address.get_copy(),
+ name="WarehousePL",
+ slug="warehousePL",
+ )
+ 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_channel_and_country(channel_USD.slug, "PL")
+ sum_quantities = sum([stock.quantity for stock in stocks])
+
+ variables = {
+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),
+ "channel": channel_USD.slug,
+ "country": "PL",
+ }
+ response = api_client.post_graphql(query, variables)
+ content = get_graphql_content(response)
+
+ assert content["data"]["productVariant"]["quantityAvailable"] == sum_quantities
diff --git a/saleor/graphql/warehouse/mutations.py b/saleor/graphql/warehouse/mutations.py
deleted file mode 100644
index 4871e085cc..0000000000
--- a/saleor/graphql/warehouse/mutations.py
+++ /dev/null
@@ -1,335 +0,0 @@
-from collections import defaultdict
-from typing import List
-
-import graphene
-from django.core.exceptions import ValidationError
-
-from ...channel import models as channel_models
-from ...core.tracing import traced_atomic_transaction
-from ...permission.enums import ProductPermissions
-from ...warehouse import WarehouseClickAndCollectOption, models
-from ...warehouse.error_codes import WarehouseErrorCode
-from ...warehouse.validation import validate_warehouse_count
-from ..account.i18n import I18nMixin
-from ..core import ResolveInfo
-from ..core.mutations import ModelDeleteMutation, ModelMutation
-from ..core.types import NonNullList, WarehouseError
-from ..core.validators import (
- validate_required_string_field,
- validate_slug_and_generate_if_needed,
-)
-from ..plugins.dataloaders import get_plugin_manager_promise
-from ..shipping.types import ShippingZone
-from .types import Warehouse, WarehouseCreateInput, WarehouseUpdateInput
-
-ADDRESS_FIELDS = [
- "street_address_1",
- "street_address_2",
- "city",
- "city_area",
- "postal_code",
- "country",
- "country_area",
- "phone",
-]
-
-
-class WarehouseMixin:
- @classmethod
- def clean_input(cls, info: ResolveInfo, instance, data, **kwargs):
- cleaned_input = super().clean_input( # type: ignore[misc] # mixin
- info, instance, data, **kwargs
- )
- try:
- cleaned_input = validate_slug_and_generate_if_needed(
- instance, "name", cleaned_input
- )
- except ValidationError as error:
- error.code = WarehouseErrorCode.REQUIRED.value
- raise ValidationError({"slug": error})
-
- if "name" in cleaned_input:
- try:
- cleaned_input = validate_required_string_field(cleaned_input, "name")
- except ValidationError as error:
- error.code = WarehouseErrorCode.REQUIRED.value
- raise ValidationError({"name": error})
-
- # assigning shipping zones in the WarehouseCreate mutation is deprecated
- if cleaned_input.get("shipping_zones"):
- raise ValidationError(
- {
- "shipping_zones": ValidationError(
- "The shippingZone input field is deprecated. "
- "Use WarehouseShippingZoneAssign mutation",
- code=WarehouseErrorCode.INVALID.value,
- )
- }
- )
-
- click_and_collect_option = cleaned_input.get(
- "click_and_collect_option", instance.click_and_collect_option
- )
- is_private = cleaned_input.get("is_private", instance.is_private)
- if (
- click_and_collect_option == WarehouseClickAndCollectOption.LOCAL_STOCK
- and is_private
- ):
- msg = "Local warehouse can be toggled only for non-private warehouse stocks"
- raise ValidationError(
- {
- "click_and_collect_option": ValidationError(
- msg, code=WarehouseErrorCode.INVALID.value
- )
- },
- )
- return cleaned_input
-
- @classmethod
- def construct_instance(cls, instance, cleaned_data):
- cleaned_data["address"] = cls.prepare_address(cleaned_data, instance) # type: ignore[attr-defined] # mixing # noqa: E501
- return super().construct_instance(instance, cleaned_data) # type: ignore[misc] # mixing # noqa: E501
-
-
-class WarehouseCreate(WarehouseMixin, ModelMutation, I18nMixin):
- class Arguments:
- input = WarehouseCreateInput(
- required=True, description="Fields required to create warehouse."
- )
-
- class Meta:
- description = "Creates new warehouse."
- model = models.Warehouse
- object_type = Warehouse
- permissions = (ProductPermissions.MANAGE_PRODUCTS,)
- error_type_class = WarehouseError
- error_type_field = "warehouse_errors"
-
- @classmethod
- def prepare_address(cls, cleaned_data, *args):
- address_form = cls.validate_address_form(cleaned_data["address"])
- return address_form.save()
-
- @classmethod
- def post_save_action(cls, info: ResolveInfo, instance, cleaned_input):
- manager = get_plugin_manager_promise(info.context).get()
- cls.call_event(manager.warehouse_created, instance)
-
-
-class WarehouseShippingZoneAssign(ModelMutation, I18nMixin):
- class Meta:
- model = models.Warehouse
- object_type = Warehouse
- permissions = (ProductPermissions.MANAGE_PRODUCTS,)
- description = "Add shipping zone to given warehouse."
- error_type_class = WarehouseError
- error_type_field = "warehouse_errors"
-
- class Arguments:
- id = graphene.ID(description="ID of a warehouse to update.", required=True)
- shipping_zone_ids = NonNullList(
- graphene.ID,
- required=True,
- description="List of shipping zone IDs.",
- )
-
- @classmethod
- def perform_mutation( # type: ignore[override]
- cls, _root, info: ResolveInfo, /, *, id: str, shipping_zone_ids: List[str]
- ):
- warehouse = cls.get_node_or_error(info, id, only_type=Warehouse)
- shipping_zones = cls.get_nodes_or_error(
- shipping_zone_ids, "shipping_zone_id", only_type=ShippingZone
- )
- cls.clean_shipping_zones(warehouse, shipping_zones)
- warehouse.shipping_zones.add(*shipping_zones)
- return WarehouseShippingZoneAssign(warehouse=warehouse)
-
- @classmethod
- def clean_shipping_zones(cls, instance, shipping_zones):
- if not validate_warehouse_count(shipping_zones, instance):
- msg = "Shipping zone can be assigned only to one warehouse."
- raise ValidationError(
- {"shipping_zones": msg}, code=WarehouseErrorCode.INVALID.value
- )
-
- cls.check_if_zones_can_be_assigned(instance, shipping_zones)
-
- @classmethod
- def check_if_zones_can_be_assigned(cls, instance, shipping_zones):
- """Check if all shipping zones to add has common channel with warehouse.
-
- Raise and error when the condition is not fulfilled.
- """
- shipping_zone_ids = [zone.id for zone in shipping_zones]
- ChannelShippingZone = channel_models.Channel.shipping_zones.through # type: ignore[attr-defined] # raw access to the through model # noqa: E501
- channel_shipping_zones = ChannelShippingZone.objects.filter(
- shippingzone_id__in=shipping_zone_ids
- )
-
- # shipping zone cannot be assigned when any channel is assigned to the zone
- if not channel_shipping_zones:
- invalid_shipping_zone_ids = shipping_zone_ids
-
- zone_to_channel_mapping = defaultdict(set)
- for shipping_zone_id, channel_id in channel_shipping_zones.values_list(
- "shippingzone_id", "channel_id"
- ):
- zone_to_channel_mapping[shipping_zone_id].add(channel_id)
-
- WarehouseChannel = models.Warehouse.channels.through
- zone_channel_ids = set(
- WarehouseChannel.objects.filter(warehouse_id=instance.id).values_list(
- "channel_id", flat=True
- )
- )
-
- invalid_shipping_zone_ids = cls._find_invalid_shipping_zones(
- zone_to_channel_mapping, shipping_zone_ids, zone_channel_ids
- )
-
- if invalid_shipping_zone_ids:
- invalid_zones = {
- graphene.Node.to_global_id("ShippingZone", pk)
- for pk in invalid_shipping_zone_ids
- }
- raise ValidationError(
- {
- "shipping_zones": ValidationError(
- "Only warehouses that have common channel with shipping zone "
- "can be assigned.",
- code=WarehouseErrorCode.INVALID,
- params={
- "shipping_zones": invalid_zones,
- },
- )
- }
- )
-
- @staticmethod
- def _find_invalid_shipping_zones(
- zone_to_channel_mapping, shipping_zone_ids, warehouse_channel_ids
- ):
- invalid_warehouse_ids = []
- for zone_id in shipping_zone_ids:
- zone_channels = zone_to_channel_mapping.get(zone_id)
- # shipping zone cannot be added if it hasn't got any channel assigned
- # or if it does not have common channel with the warehouse
- if not zone_channels or not zone_channels.intersection(
- warehouse_channel_ids
- ):
- invalid_warehouse_ids.append(zone_id)
- return invalid_warehouse_ids
-
-
-class WarehouseShippingZoneUnassign(ModelMutation, I18nMixin):
- class Meta:
- model = models.Warehouse
- object_type = Warehouse
- permissions = (ProductPermissions.MANAGE_PRODUCTS,)
- description = "Remove shipping zone from given warehouse."
- error_type_class = WarehouseError
- error_type_field = "warehouse_errors"
-
- class Arguments:
- id = graphene.ID(description="ID of a warehouse to update.", required=True)
- shipping_zone_ids = NonNullList(
- graphene.ID,
- required=True,
- description="List of shipping zone IDs.",
- )
-
- @classmethod
- def perform_mutation( # type: ignore[override]
- cls, _root, info: ResolveInfo, /, *, id: str, shipping_zone_ids: List[str]
- ):
- warehouse = cls.get_node_or_error(info, id, only_type=Warehouse)
- shipping_zones = cls.get_nodes_or_error(
- shipping_zone_ids, "shipping_zone_id", only_type=ShippingZone
- )
- warehouse.shipping_zones.remove(*shipping_zones)
- return WarehouseShippingZoneAssign(warehouse=warehouse)
-
-
-class WarehouseUpdate(WarehouseMixin, ModelMutation, I18nMixin):
- class Meta:
- model = models.Warehouse
- object_type = Warehouse
- permissions = (ProductPermissions.MANAGE_PRODUCTS,)
- description = "Updates given warehouse."
- error_type_class = WarehouseError
- error_type_field = "warehouse_errors"
-
- class Arguments:
- id = graphene.ID(description="ID of a warehouse to update.", required=True)
- input = WarehouseUpdateInput(
- required=True, description="Fields required to update warehouse."
- )
-
- @classmethod
- def prepare_address(cls, cleaned_data, instance):
- address_data = cleaned_data.get("address")
- address = instance.address
- if address_data is None:
- return address
- address_form = cls.validate_address_form(address_data, instance=address)
- return address_form.save()
-
- @classmethod
- def post_save_action(cls, info: ResolveInfo, instance, cleaned_input):
- manager = get_plugin_manager_promise(info.context).get()
- cls.call_event(manager.warehouse_updated, instance)
-
-
-class WarehouseDelete(ModelDeleteMutation):
- class Meta:
- model = models.Warehouse
- object_type = Warehouse
- permissions = (ProductPermissions.MANAGE_PRODUCTS,)
- description = "Deletes selected warehouse."
- error_type_class = WarehouseError
- error_type_field = "warehouse_errors"
-
- class Arguments:
- id = graphene.ID(description="ID of a warehouse to delete.", required=True)
-
- @classmethod
- def perform_mutation(cls, _root, info: ResolveInfo, /, **data):
- manager = get_plugin_manager_promise(info.context).get()
- node_id = data.get("id")
- model_type = cls.get_type_for_model()
- instance = cls.get_node_or_error(info, node_id, only_type=model_type)
-
- if instance:
- cls.clean_instance(info, instance)
-
- stocks = (stock for stock in instance.stock_set.only("product_variant"))
- address_id = instance.address_id
- address = instance.address
-
- db_id = instance.id
- with traced_atomic_transaction():
- instance.delete()
-
- # After the instance is deleted, set its ID to the original database's
- # ID so that the success response contains ID of the deleted object.
- # Additionally, assign copy of deleted Address object to allow fetching
- # address data on success response or in subscription webhook query.
- instance.id = db_id
- address.id = address_id
- instance.address = address
-
- # Set `is_object_deleted` attribute to use it in Warehouse object type
- # resolvers and for example decide if we should use Dataloader to resolve
- # address or return object directly.
- instance.is_object_deleted = True
-
- cls.post_save_action(info, instance, None)
- for stock in stocks:
- cls.call_event(manager.product_variant_out_of_stock, stock)
- return cls.success_response(instance)
-
- @classmethod
- def post_save_action(cls, info: ResolveInfo, instance, cleaned_input):
- manager = get_plugin_manager_promise(info.context).get()
- cls.call_event(manager.warehouse_deleted, instance)
diff --git a/saleor/graphql/warehouse/mutations/__init__.py b/saleor/graphql/warehouse/mutations/__init__.py
new file mode 100644
index 0000000000..ee7191444e
--- /dev/null
+++ b/saleor/graphql/warehouse/mutations/__init__.py
@@ -0,0 +1,13 @@
+from .warehouse_create import WarehouseCreate
+from .warehouse_delete import WarehouseDelete
+from .warehouse_shipping_zone_assign import WarehouseShippingZoneAssign
+from .warehouse_shipping_zone_unassign import WarehouseShippingZoneUnassign
+from .warehouse_update import WarehouseUpdate
+
+__all__ = [
+ "WarehouseCreate",
+ "WarehouseDelete",
+ "WarehouseShippingZoneAssign",
+ "WarehouseShippingZoneUnassign",
+ "WarehouseUpdate",
+]
diff --git a/saleor/graphql/warehouse/mutations/base.py b/saleor/graphql/warehouse/mutations/base.py
new file mode 100644
index 0000000000..b41498668c
--- /dev/null
+++ b/saleor/graphql/warehouse/mutations/base.py
@@ -0,0 +1,66 @@
+from django.core.exceptions import ValidationError
+
+from ....warehouse import WarehouseClickAndCollectOption
+from ....warehouse.error_codes import WarehouseErrorCode
+from ...core import ResolveInfo
+from ...core.validators import (
+ validate_required_string_field,
+ validate_slug_and_generate_if_needed,
+)
+
+
+class WarehouseMixin:
+ @classmethod
+ def clean_input(cls, info: ResolveInfo, instance, data, **kwargs):
+ cleaned_input = super().clean_input( # type: ignore[misc] # mixin
+ info, instance, data, **kwargs
+ )
+ try:
+ cleaned_input = validate_slug_and_generate_if_needed(
+ instance, "name", cleaned_input
+ )
+ except ValidationError as error:
+ error.code = WarehouseErrorCode.REQUIRED.value
+ raise ValidationError({"slug": error})
+
+ if "name" in cleaned_input:
+ try:
+ cleaned_input = validate_required_string_field(cleaned_input, "name")
+ except ValidationError as error:
+ error.code = WarehouseErrorCode.REQUIRED.value
+ raise ValidationError({"name": error})
+
+ # assigning shipping zones in the WarehouseCreate mutation is deprecated
+ if cleaned_input.get("shipping_zones"):
+ raise ValidationError(
+ {
+ "shipping_zones": ValidationError(
+ "The shippingZone input field is deprecated. "
+ "Use WarehouseShippingZoneAssign mutation",
+ code=WarehouseErrorCode.INVALID.value,
+ )
+ }
+ )
+
+ click_and_collect_option = cleaned_input.get(
+ "click_and_collect_option", instance.click_and_collect_option
+ )
+ is_private = cleaned_input.get("is_private", instance.is_private)
+ if (
+ click_and_collect_option == WarehouseClickAndCollectOption.LOCAL_STOCK
+ and is_private
+ ):
+ msg = "Local warehouse can be toggled only for non-private warehouse stocks"
+ raise ValidationError(
+ {
+ "click_and_collect_option": ValidationError(
+ msg, code=WarehouseErrorCode.INVALID.value
+ )
+ },
+ )
+ return cleaned_input
+
+ @classmethod
+ def construct_instance(cls, instance, cleaned_data):
+ cleaned_data["address"] = cls.prepare_address(cleaned_data, instance) # type: ignore[attr-defined] # mixing # noqa: E501
+ return super().construct_instance(instance, cleaned_data) # type: ignore[misc] # mixing # noqa: E501
diff --git a/saleor/graphql/warehouse/mutations/warehouse_create.py b/saleor/graphql/warehouse/mutations/warehouse_create.py
new file mode 100644
index 0000000000..9418417c08
--- /dev/null
+++ b/saleor/graphql/warehouse/mutations/warehouse_create.py
@@ -0,0 +1,34 @@
+from ....permission.enums import ProductPermissions
+from ....warehouse import models
+from ...account.i18n import I18nMixin
+from ...core import ResolveInfo
+from ...core.mutations import ModelMutation
+from ...core.types import WarehouseError
+from ...plugins.dataloaders import get_plugin_manager_promise
+from ..types import Warehouse, WarehouseCreateInput
+from .base import WarehouseMixin
+
+
+class WarehouseCreate(WarehouseMixin, ModelMutation, I18nMixin):
+ class Arguments:
+ input = WarehouseCreateInput(
+ required=True, description="Fields required to create warehouse."
+ )
+
+ class Meta:
+ description = "Creates new warehouse."
+ model = models.Warehouse
+ object_type = Warehouse
+ permissions = (ProductPermissions.MANAGE_PRODUCTS,)
+ error_type_class = WarehouseError
+ error_type_field = "warehouse_errors"
+
+ @classmethod
+ def prepare_address(cls, cleaned_data, *args):
+ address_form = cls.validate_address_form(cleaned_data["address"])
+ return address_form.save()
+
+ @classmethod
+ def post_save_action(cls, info: ResolveInfo, instance, cleaned_input):
+ manager = get_plugin_manager_promise(info.context).get()
+ cls.call_event(manager.warehouse_created, instance)
diff --git a/saleor/graphql/warehouse/mutations/warehouse_delete.py b/saleor/graphql/warehouse/mutations/warehouse_delete.py
new file mode 100644
index 0000000000..a4ea3b3093
--- /dev/null
+++ b/saleor/graphql/warehouse/mutations/warehouse_delete.py
@@ -0,0 +1,64 @@
+import graphene
+
+from ....core.tracing import traced_atomic_transaction
+from ....permission.enums import ProductPermissions
+from ....warehouse import models
+from ...core import ResolveInfo
+from ...core.mutations import ModelDeleteMutation
+from ...core.types import WarehouseError
+from ...plugins.dataloaders import get_plugin_manager_promise
+from ..types import Warehouse
+
+
+class WarehouseDelete(ModelDeleteMutation):
+ class Meta:
+ model = models.Warehouse
+ object_type = Warehouse
+ permissions = (ProductPermissions.MANAGE_PRODUCTS,)
+ description = "Deletes selected warehouse."
+ error_type_class = WarehouseError
+ error_type_field = "warehouse_errors"
+
+ class Arguments:
+ id = graphene.ID(description="ID of a warehouse to delete.", required=True)
+
+ @classmethod
+ def perform_mutation(cls, _root, info: ResolveInfo, /, **data):
+ manager = get_plugin_manager_promise(info.context).get()
+ node_id = data.get("id")
+ model_type = cls.get_type_for_model()
+ instance = cls.get_node_or_error(info, node_id, only_type=model_type)
+
+ if instance:
+ cls.clean_instance(info, instance)
+
+ stocks = (stock for stock in instance.stock_set.only("product_variant"))
+ address_id = instance.address_id
+ address = instance.address
+
+ db_id = instance.id
+ with traced_atomic_transaction():
+ instance.delete()
+
+ # After the instance is deleted, set its ID to the original database's
+ # ID so that the success response contains ID of the deleted object.
+ # Additionally, assign copy of deleted Address object to allow fetching
+ # address data on success response or in subscription webhook query.
+ instance.id = db_id
+ address.id = address_id
+ instance.address = address
+
+ # Set `is_object_deleted` attribute to use it in Warehouse object type
+ # resolvers and for example decide if we should use Dataloader to resolve
+ # address or return object directly.
+ instance.is_object_deleted = True
+
+ cls.post_save_action(info, instance, None)
+ for stock in stocks:
+ cls.call_event(manager.product_variant_out_of_stock, stock)
+ return cls.success_response(instance)
+
+ @classmethod
+ def post_save_action(cls, info: ResolveInfo, instance, cleaned_input):
+ manager = get_plugin_manager_promise(info.context).get()
+ cls.call_event(manager.warehouse_deleted, instance)
diff --git a/saleor/graphql/warehouse/mutations/warehouse_shipping_zone_assign.py b/saleor/graphql/warehouse/mutations/warehouse_shipping_zone_assign.py
new file mode 100644
index 0000000000..d9628f02a6
--- /dev/null
+++ b/saleor/graphql/warehouse/mutations/warehouse_shipping_zone_assign.py
@@ -0,0 +1,123 @@
+from collections import defaultdict
+from typing import List
+
+import graphene
+from django.core.exceptions import ValidationError
+
+from ....channel import models as channel_models
+from ....permission.enums import ProductPermissions
+from ....warehouse import models
+from ....warehouse.error_codes import WarehouseErrorCode
+from ....warehouse.validation import validate_warehouse_count
+from ...account.i18n import I18nMixin
+from ...core import ResolveInfo
+from ...core.mutations import ModelMutation
+from ...core.types import NonNullList, WarehouseError
+from ...shipping.types import ShippingZone
+from ..types import Warehouse
+
+
+class WarehouseShippingZoneAssign(ModelMutation, I18nMixin):
+ class Meta:
+ model = models.Warehouse
+ object_type = Warehouse
+ permissions = (ProductPermissions.MANAGE_PRODUCTS,)
+ description = "Add shipping zone to given warehouse."
+ error_type_class = WarehouseError
+ error_type_field = "warehouse_errors"
+
+ class Arguments:
+ id = graphene.ID(description="ID of a warehouse to update.", required=True)
+ shipping_zone_ids = NonNullList(
+ graphene.ID,
+ required=True,
+ description="List of shipping zone IDs.",
+ )
+
+ @classmethod
+ def perform_mutation( # type: ignore[override]
+ cls, _root, info: ResolveInfo, /, *, id: str, shipping_zone_ids: List[str]
+ ):
+ warehouse = cls.get_node_or_error(info, id, only_type=Warehouse)
+ shipping_zones = cls.get_nodes_or_error(
+ shipping_zone_ids, "shipping_zone_id", only_type=ShippingZone
+ )
+ cls.clean_shipping_zones(warehouse, shipping_zones)
+ warehouse.shipping_zones.add(*shipping_zones)
+ return WarehouseShippingZoneAssign(warehouse=warehouse)
+
+ @classmethod
+ def clean_shipping_zones(cls, instance, shipping_zones):
+ if not validate_warehouse_count(shipping_zones, instance):
+ msg = "Shipping zone can be assigned only to one warehouse."
+ raise ValidationError(
+ {"shipping_zones": msg}, code=WarehouseErrorCode.INVALID.value
+ )
+
+ cls.check_if_zones_can_be_assigned(instance, shipping_zones)
+
+ @classmethod
+ def check_if_zones_can_be_assigned(cls, instance, shipping_zones):
+ """Check if all shipping zones to add has common channel with warehouse.
+
+ Raise and error when the condition is not fulfilled.
+ """
+ shipping_zone_ids = [zone.id for zone in shipping_zones]
+ ChannelShippingZone = channel_models.Channel.shipping_zones.through # type: ignore[attr-defined] # raw access to the through model # noqa: E501
+ channel_shipping_zones = ChannelShippingZone.objects.filter(
+ shippingzone_id__in=shipping_zone_ids
+ )
+
+ # shipping zone cannot be assigned when any channel is assigned to the zone
+ if not channel_shipping_zones:
+ invalid_shipping_zone_ids = shipping_zone_ids
+
+ zone_to_channel_mapping = defaultdict(set)
+ for shipping_zone_id, channel_id in channel_shipping_zones.values_list(
+ "shippingzone_id", "channel_id"
+ ):
+ zone_to_channel_mapping[shipping_zone_id].add(channel_id)
+
+ WarehouseChannel = models.Warehouse.channels.through
+ zone_channel_ids = set(
+ WarehouseChannel.objects.filter(warehouse_id=instance.id).values_list(
+ "channel_id", flat=True
+ )
+ )
+
+ invalid_shipping_zone_ids = cls._find_invalid_shipping_zones(
+ zone_to_channel_mapping, shipping_zone_ids, zone_channel_ids
+ )
+
+ if invalid_shipping_zone_ids:
+ invalid_zones = {
+ graphene.Node.to_global_id("ShippingZone", pk)
+ for pk in invalid_shipping_zone_ids
+ }
+ raise ValidationError(
+ {
+ "shipping_zones": ValidationError(
+ "Only warehouses that have common channel with shipping zone "
+ "can be assigned.",
+ code=WarehouseErrorCode.INVALID,
+ params={
+ "shipping_zones": invalid_zones,
+ },
+ )
+ }
+ )
+
+ @staticmethod
+ def _find_invalid_shipping_zones(
+ zone_to_channel_mapping, shipping_zone_ids, warehouse_channel_ids
+ ):
+ invalid_warehouse_ids = []
+ for zone_id in shipping_zone_ids:
+ zone_channels = zone_to_channel_mapping.get(zone_id)
+ # shipping zone cannot be added if it hasn't got any channel assigned
+ # or if it does not have common channel with the warehouse
+ if not zone_channels or not zone_channels.intersection(
+ warehouse_channel_ids
+ ):
+ invalid_warehouse_ids.append(zone_id)
+ return invalid_warehouse_ids
diff --git a/saleor/graphql/warehouse/mutations/warehouse_shipping_zone_unassign.py b/saleor/graphql/warehouse/mutations/warehouse_shipping_zone_unassign.py
new file mode 100644
index 0000000000..1ff53922f7
--- /dev/null
+++ b/saleor/graphql/warehouse/mutations/warehouse_shipping_zone_unassign.py
@@ -0,0 +1,42 @@
+from typing import List
+
+import graphene
+
+from ....permission.enums import ProductPermissions
+from ....warehouse import models
+from ...account.i18n import I18nMixin
+from ...core import ResolveInfo
+from ...core.mutations import ModelMutation
+from ...core.types import NonNullList, WarehouseError
+from ...shipping.types import ShippingZone
+from ..types import Warehouse
+from .warehouse_shipping_zone_assign import WarehouseShippingZoneAssign
+
+
+class WarehouseShippingZoneUnassign(ModelMutation, I18nMixin):
+ class Meta:
+ model = models.Warehouse
+ object_type = Warehouse
+ permissions = (ProductPermissions.MANAGE_PRODUCTS,)
+ description = "Remove shipping zone from given warehouse."
+ error_type_class = WarehouseError
+ error_type_field = "warehouse_errors"
+
+ class Arguments:
+ id = graphene.ID(description="ID of a warehouse to update.", required=True)
+ shipping_zone_ids = NonNullList(
+ graphene.ID,
+ required=True,
+ description="List of shipping zone IDs.",
+ )
+
+ @classmethod
+ def perform_mutation( # type: ignore[override]
+ cls, _root, info: ResolveInfo, /, *, id: str, shipping_zone_ids: List[str]
+ ):
+ warehouse = cls.get_node_or_error(info, id, only_type=Warehouse)
+ shipping_zones = cls.get_nodes_or_error(
+ shipping_zone_ids, "shipping_zone_id", only_type=ShippingZone
+ )
+ warehouse.shipping_zones.remove(*shipping_zones)
+ return WarehouseShippingZoneAssign(warehouse=warehouse)
diff --git a/saleor/graphql/warehouse/mutations/warehouse_update.py b/saleor/graphql/warehouse/mutations/warehouse_update.py
new file mode 100644
index 0000000000..711dfbea67
--- /dev/null
+++ b/saleor/graphql/warehouse/mutations/warehouse_update.py
@@ -0,0 +1,41 @@
+import graphene
+
+from ....permission.enums import ProductPermissions
+from ....warehouse import models
+from ...account.i18n import I18nMixin
+from ...core import ResolveInfo
+from ...core.mutations import ModelMutation
+from ...core.types import WarehouseError
+from ...plugins.dataloaders import get_plugin_manager_promise
+from ..types import Warehouse, WarehouseUpdateInput
+from .base import WarehouseMixin
+
+
+class WarehouseUpdate(WarehouseMixin, ModelMutation, I18nMixin):
+ class Meta:
+ model = models.Warehouse
+ object_type = Warehouse
+ permissions = (ProductPermissions.MANAGE_PRODUCTS,)
+ description = "Updates given warehouse."
+ error_type_class = WarehouseError
+ error_type_field = "warehouse_errors"
+
+ class Arguments:
+ id = graphene.ID(description="ID of a warehouse to update.", required=True)
+ input = WarehouseUpdateInput(
+ required=True, description="Fields required to update warehouse."
+ )
+
+ @classmethod
+ def prepare_address(cls, cleaned_data, instance):
+ address_data = cleaned_data.get("address")
+ address = instance.address
+ if address_data is None:
+ return address
+ address_form = cls.validate_address_form(address_data, instance=address)
+ return address_form.save()
+
+ @classmethod
+ def post_save_action(cls, info: ResolveInfo, instance, cleaned_input):
+ manager = get_plugin_manager_promise(info.context).get()
+ cls.call_event(manager.warehouse_updated, instance)
diff --git a/saleor/graphql/warehouse/tests/bulk_mutations/__init__.py b/saleor/graphql/warehouse/tests/bulk_mutations/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/graphql/warehouse/tests/test_stock_bulk_update.py b/saleor/graphql/warehouse/tests/bulk_mutations/test_stock_bulk_update.py
similarity index 99%
rename from saleor/graphql/warehouse/tests/test_stock_bulk_update.py
rename to saleor/graphql/warehouse/tests/bulk_mutations/test_stock_bulk_update.py
index c2616c0044..bfe63a6344 100644
--- a/saleor/graphql/warehouse/tests/test_stock_bulk_update.py
+++ b/saleor/graphql/warehouse/tests/bulk_mutations/test_stock_bulk_update.py
@@ -2,8 +2,8 @@ from unittest.mock import patch
import graphene
-from ....warehouse.error_codes import StockBulkUpdateErrorCode
-from ...tests.utils import get_graphql_content
+from .....warehouse.error_codes import StockBulkUpdateErrorCode
+from ....tests.utils import get_graphql_content
STOCKS_BULK_UPDATE_MUTATION = """
mutation StockBulkUpdate($stocks: [StockBulkUpdateInput!]!){
diff --git a/saleor/graphql/warehouse/tests/mutations/__init__.py b/saleor/graphql/warehouse/tests/mutations/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/graphql/warehouse/tests/mutations/test_warehouse_create.py b/saleor/graphql/warehouse/tests/mutations/test_warehouse_create.py
new file mode 100644
index 0000000000..e02e8b0e6b
--- /dev/null
+++ b/saleor/graphql/warehouse/tests/mutations/test_warehouse_create.py
@@ -0,0 +1,333 @@
+import json
+from unittest.mock import patch
+
+import graphene
+import pytest
+from django.utils.functional import SimpleLazyObject
+
+from .....account.models import Address
+from .....core.utils.json_serializer import CustomJsonEncoder
+from .....warehouse.error_codes import WarehouseErrorCode
+from .....warehouse.models import Warehouse
+from .....webhook.event_types import WebhookEventAsyncType
+from ....tests.utils import get_graphql_content
+
+MUTATION_CREATE_WAREHOUSE = """
+mutation createWarehouse($input: WarehouseCreateInput!) {
+ createWarehouse(input: $input){
+ warehouse {
+ id
+ name
+ slug
+ companyName
+ externalReference
+ address {
+ id
+ }
+ shippingZones(first: 5) {
+ edges {
+ node {
+ id
+ }
+ }
+ }
+ }
+ errors {
+ message
+ field
+ code
+ }
+ }
+}
+"""
+
+
+def test_mutation_create_warehouse(
+ staff_api_client, permission_manage_products, shipping_zone
+):
+ # given
+ variables = {
+ "input": {
+ "name": "Test warehouse",
+ "slug": "test-warhouse",
+ "email": "[email protected]",
+ "externalReference": "test-ext-ref",
+ "address": {
+ "streetAddress1": "Teczowa 8",
+ "city": "Wroclaw",
+ "country": "PL",
+ "postalCode": "53-601",
+ "companyName": "Amazing Company Inc",
+ },
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_CREATE_WAREHOUSE,
+ variables=variables,
+ permissions=[permission_manage_products],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert Warehouse.objects.count() == 1
+ warehouse = Warehouse.objects.first()
+ created_warehouse = content["data"]["createWarehouse"]["warehouse"]
+ assert created_warehouse["id"] == graphene.Node.to_global_id(
+ "Warehouse", warehouse.id
+ )
+ assert created_warehouse["name"] == warehouse.name
+ assert created_warehouse["slug"] == warehouse.slug
+ assert created_warehouse["companyName"] == warehouse.address.company_name
+ assert created_warehouse["externalReference"] == warehouse.external_reference
+
+
+def test_mutation_create_warehouse_shipping_zone_provided(
+ staff_api_client, permission_manage_products, shipping_zone
+):
+ # given
+ variables = {
+ "input": {
+ "name": "Test warehouse",
+ "slug": "test-warhouse",
+ "email": "[email protected]",
+ "address": {
+ "streetAddress1": "Teczowa 8",
+ "city": "Wroclaw",
+ "country": "PL",
+ "postalCode": "53-601",
+ "companyName": "Amazing Company Inc",
+ },
+ # DEPRECATED
+ "shippingZones": [
+ graphene.Node.to_global_id("ShippingZone", shipping_zone.id)
+ ],
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_CREATE_WAREHOUSE,
+ variables=variables,
+ permissions=[permission_manage_products],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["createWarehouse"]
+ errors = data["errors"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == WarehouseErrorCode.INVALID.name
+ assert errors[0]["field"] == "shippingZones"
+
+
+@patch("saleor.plugins.webhook.plugin.get_webhooks_for_event")
+@patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")
+def test_mutation_create_warehouse_trigger_webhook(
+ mocked_webhook_trigger,
+ mocked_get_webhooks_for_event,
+ any_webhook,
+ staff_api_client,
+ permission_manage_products,
+ shipping_zone,
+ settings,
+):
+ # given
+ mocked_get_webhooks_for_event.return_value = [any_webhook]
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+
+ variables = {
+ "input": {
+ "name": "Test warehouse",
+ "slug": "test-warhouse",
+ "email": "[email protected]",
+ "address": {
+ "streetAddress1": "Teczowa 8",
+ "city": "Wroclaw",
+ "country": "PL",
+ "postalCode": "53-601",
+ "companyName": "Amazing Company Inc",
+ },
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_CREATE_WAREHOUSE,
+ variables=variables,
+ permissions=[permission_manage_products],
+ )
+ content = get_graphql_content(response)
+ warehouse = Warehouse.objects.last()
+
+ # then
+ assert content["data"]["createWarehouse"]["warehouse"]
+ mocked_webhook_trigger.assert_called_once_with(
+ json.dumps(
+ {
+ "id": graphene.Node.to_global_id("Warehouse", warehouse.id),
+ "name": warehouse.name,
+ },
+ cls=CustomJsonEncoder,
+ ),
+ WebhookEventAsyncType.WAREHOUSE_CREATED,
+ [any_webhook],
+ warehouse,
+ SimpleLazyObject(lambda: staff_api_client.user),
+ )
+
+
+def test_mutation_create_warehouse_does_not_create_when_name_is_empty_string(
+ staff_api_client, permission_manage_products, shipping_zone
+):
+ # given
+ variables = {
+ "input": {
+ "name": " ",
+ "slug": "test-warhouse",
+ "email": "[email protected]",
+ "address": {
+ "streetAddress1": "Teczowa 8",
+ "city": "Wroclaw",
+ "country": "PL",
+ "postalCode": "53-601",
+ "companyName": "Amazing Company Inc",
+ },
+ "shippingZones": [
+ graphene.Node.to_global_id("ShippingZone", shipping_zone.id)
+ ],
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_CREATE_WAREHOUSE,
+ variables=variables,
+ permissions=[permission_manage_products],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["createWarehouse"]
+ errors = data["errors"]
+ assert Warehouse.objects.count() == 0
+ assert len(errors) == 1
+ assert errors[0]["field"] == "name"
+ assert errors[0]["code"] == WarehouseErrorCode.REQUIRED.name
+
+
+def test_create_warehouse_creates_address(
+ staff_api_client, permission_manage_products, shipping_zone
+):
+ # given
+ variables = {
+ "input": {
+ "name": "Test warehouse",
+ "email": "[email protected]",
+ "address": {
+ "streetAddress1": "Teczowa 8",
+ "city": "Wroclaw",
+ "country": "PL",
+ "companyName": "Amazing Company Inc",
+ "postalCode": "53-601",
+ },
+ }
+ }
+ assert not Address.objects.exists()
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_CREATE_WAREHOUSE,
+ variables=variables,
+ permissions=[permission_manage_products],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ errors = content["data"]["createWarehouse"]["errors"]
+ assert len(errors) == 0
+ assert Address.objects.count() == 1
+ address = Address.objects.get(street_address_1="Teczowa 8", city="WROCLAW")
+ address_id = graphene.Node.to_global_id("Address", address.id)
+ warehouse_data = content["data"]["createWarehouse"]["warehouse"]
+ assert warehouse_data["address"]["id"] == address_id
+ assert address.street_address_1 == "Teczowa 8"
+ assert address.company_name == "Amazing Company Inc"
+ assert address.city == "WROCLAW"
+
+
+ "input_slug, expected_slug",
+ (
+ ("test-slug", "test-slug"),
+ (None, "test-warehouse"),
+ ("", "test-warehouse"),
+ ),
+)
+def test_create_warehouse_with_given_slug(
+ staff_api_client, permission_manage_products, input_slug, expected_slug
+):
+ # given
+ query = MUTATION_CREATE_WAREHOUSE
+ name = "Test warehouse"
+ variables = {"name": name, "slug": input_slug}
+ variables = {
+ "input": {
+ "name": name,
+ "slug": input_slug,
+ "address": {
+ "streetAddress1": "Teczowa 8",
+ "city": "Wroclaw",
+ "country": "PL",
+ "postalCode": "53-601",
+ },
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["createWarehouse"]
+ assert not data["errors"]
+ assert data["warehouse"]["slug"] == expected_slug
+
+
+def test_create_warehouse_with_non_unique_external_reference(
+ staff_api_client, permission_manage_products, shipping_zone, warehouse
+):
+ # given
+ ext_ref = "test-ext-ref"
+ warehouse.external_reference = ext_ref
+ warehouse.save(update_fields=["external_reference"])
+
+ variables = {
+ "input": {
+ "name": "Test warehouse",
+ "externalReference": ext_ref,
+ "address": {
+ "streetAddress1": "Teczowa 8",
+ "city": "Wroclaw",
+ "country": "PL",
+ "postalCode": "53-601",
+ },
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_CREATE_WAREHOUSE,
+ variables=variables,
+ permissions=[permission_manage_products],
+ )
+ content = get_graphql_content(response)
+
+ # then
+ error = content["data"]["createWarehouse"]["errors"][0]
+ assert error["field"] == "externalReference"
+ assert error["code"] == WarehouseErrorCode.UNIQUE.name
+ assert error["message"] == "Warehouse with this External reference already exists."
diff --git a/saleor/graphql/warehouse/tests/mutations/test_warehouse_delete.py b/saleor/graphql/warehouse/tests/mutations/test_warehouse_delete.py
new file mode 100644
index 0000000000..e745960592
--- /dev/null
+++ b/saleor/graphql/warehouse/tests/mutations/test_warehouse_delete.py
@@ -0,0 +1,166 @@
+import json
+from unittest.mock import patch
+
+import graphene
+from django.utils.functional import SimpleLazyObject
+
+from .....account.models import Address
+from .....core.utils.json_serializer import CustomJsonEncoder
+from .....warehouse.models import Stock, Warehouse
+from .....webhook.event_types import WebhookEventAsyncType
+from ....tests.utils import get_graphql_content
+
+MUTATION_DELETE_WAREHOUSE = """
+mutation deleteWarehouse($id: ID!) {
+ deleteWarehouse(id: $id) {
+ errors {
+ message
+ field
+ code
+ }
+ }
+}
+"""
+
+
+def test_delete_warehouse_mutation(
+ staff_api_client, warehouse, permission_manage_products
+):
+ # given
+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)
+ assert Warehouse.objects.count() == 1
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_DELETE_WAREHOUSE,
+ variables={"id": warehouse_id},
+ permissions=[permission_manage_products],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ errors = content["data"]["deleteWarehouse"]["errors"]
+ assert len(errors) == 0
+ assert not Warehouse.objects.exists()
+
+
+@patch("saleor.plugins.webhook.plugin.get_webhooks_for_event")
+@patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")
+def test_delete_warehouse_mutation_trigger_webhook(
+ mocked_webhook_trigger,
+ mocked_get_webhooks_for_event,
+ any_webhook,
+ staff_api_client,
+ warehouse,
+ permission_manage_products,
+ settings,
+):
+ # given
+ mocked_get_webhooks_for_event.return_value = [any_webhook]
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+
+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_DELETE_WAREHOUSE,
+ variables={"id": warehouse_id},
+ permissions=[permission_manage_products],
+ )
+ content = get_graphql_content(response)
+
+ # then
+ assert len(content["data"]["deleteWarehouse"]["errors"]) == 0
+ mocked_webhook_trigger.assert_called_once_with(
+ json.dumps(
+ {
+ "id": warehouse_id,
+ "name": warehouse.name,
+ },
+ cls=CustomJsonEncoder,
+ ),
+ WebhookEventAsyncType.WAREHOUSE_DELETED,
+ [any_webhook],
+ warehouse,
+ SimpleLazyObject(lambda: staff_api_client.user),
+ )
+
+
+@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")
+def test_delete_warehouse_mutation_with_webhooks(
+ product_variant_out_of_stock_webhook,
+ staff_api_client,
+ warehouse,
+ permission_manage_products,
+ variant_with_many_stocks,
+):
+ # given
+ old_first_stock = Stock.objects.first()
+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)
+ assert Warehouse.objects.count() == 3
+ assert Stock.objects.count() == 3
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_DELETE_WAREHOUSE,
+ variables={"id": warehouse_id},
+ permissions=[permission_manage_products],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ errors = content["data"]["deleteWarehouse"]["errors"]
+ assert len(errors) == 0
+ assert Warehouse.objects.count() == 2
+ assert Stock.objects.count() == 2
+ product_variant_out_of_stock_webhook.assert_called_once_with(old_first_stock)
+
+
+@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")
+def test_delete_warehouse_mutation_with_webhooks_for_many_product_variants(
+ product_variant_out_of_stock_webhook,
+ staff_api_client,
+ warehouse,
+ permission_manage_products,
+ product_with_two_variants,
+):
+ # given
+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)
+ assert Warehouse.objects.count() == 1
+ assert Stock.objects.count() == 2
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_DELETE_WAREHOUSE,
+ variables={"id": warehouse_id},
+ permissions=[permission_manage_products],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ errors = content["data"]["deleteWarehouse"]["errors"]
+ assert len(errors) == 0
+ assert Warehouse.objects.count() == 0
+ assert Stock.objects.count() == 0
+ assert product_variant_out_of_stock_webhook.call_count == 2
+
+
+def test_delete_warehouse_deletes_associated_address(
+ staff_api_client, warehouse, permission_manage_products
+):
+ # given
+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)
+ assert Address.objects.count() == 1
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_DELETE_WAREHOUSE,
+ variables={"id": warehouse_id},
+ permissions=[permission_manage_products],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ errors = content["data"]["deleteWarehouse"]["errors"]
+ assert len(errors) == 0
+ assert not Address.objects.exists()
diff --git a/saleor/graphql/warehouse/tests/mutations/test_warehouse_shipping_zone_assign.py b/saleor/graphql/warehouse/tests/mutations/test_warehouse_shipping_zone_assign.py
new file mode 100644
index 0000000000..fba2a8e142
--- /dev/null
+++ b/saleor/graphql/warehouse/tests/mutations/test_warehouse_shipping_zone_assign.py
@@ -0,0 +1,183 @@
+import graphene
+
+from .....warehouse.error_codes import WarehouseErrorCode
+from ....tests.utils import get_graphql_content
+
+MUTATION_ASSIGN_SHIPPING_ZONE_WAREHOUSE = """
+mutation assignWarehouseShippingZone($id: ID!, $shippingZoneIds: [ID!]!) {
+ assignWarehouseShippingZone(id: $id, shippingZoneIds: $shippingZoneIds) {
+ errors {
+ field
+ message
+ code
+ shippingZones
+ }
+ }
+}
+
+"""
+
+
+def test_shipping_zone_can_be_assigned_only_to_one_warehouse(
+ staff_api_client, warehouse, warehouse_JPY, permission_manage_products
+):
+ # given
+ used_shipping_zone = warehouse.shipping_zones.first()
+ used_shipping_zone_id = graphene.Node.to_global_id(
+ "ShippingZone", used_shipping_zone.pk
+ )
+ zone_warehouses_count = used_shipping_zone.warehouses.count()
+
+ variables = {
+ "id": graphene.Node.to_global_id("Warehouse", warehouse_JPY.pk),
+ "shippingZoneIds": [used_shipping_zone_id],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_ASSIGN_SHIPPING_ZONE_WAREHOUSE,
+ variables=variables,
+ permissions=[permission_manage_products],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ errors = content["data"]["assignWarehouseShippingZone"]["errors"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == WarehouseErrorCode.INVALID.name
+ assert errors[0]["field"] == "shippingZones"
+ used_shipping_zone.refresh_from_db()
+ assert used_shipping_zone.warehouses.count() == zone_warehouses_count
+
+
+def test_shipping_zone_assign_to_warehouse(
+ staff_api_client,
+ warehouse_no_shipping_zone,
+ shipping_zone,
+ permission_manage_products,
+):
+ # given
+ assert not warehouse_no_shipping_zone.shipping_zones.all()
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ variables = {
+ "id": graphene.Node.to_global_id("Warehouse", warehouse_no_shipping_zone.pk),
+ "shippingZoneIds": [
+ graphene.Node.to_global_id("ShippingZone", shipping_zone.pk)
+ ],
+ }
+
+ # when
+ staff_api_client.post_graphql(
+ MUTATION_ASSIGN_SHIPPING_ZONE_WAREHOUSE, variables=variables
+ )
+
+ # then
+ warehouse_no_shipping_zone.refresh_from_db()
+ shipping_zone.refresh_from_db()
+ assert warehouse_no_shipping_zone.shipping_zones.first().pk == shipping_zone.pk
+
+
+def test_shipping_zone_assign_to_warehouse_no_common_channel(
+ staff_api_client,
+ warehouse_no_shipping_zone,
+ shipping_zone,
+ permission_manage_products,
+ channel_PLN,
+):
+ # given
+ assert not warehouse_no_shipping_zone.shipping_zones.all()
+
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ # remove channel_USD from shipping zone channels, assign channel_PLN
+ shipping_zone.channels.set([channel_PLN])
+
+ zone_id = graphene.Node.to_global_id("ShippingZone", shipping_zone.pk)
+
+ variables = {
+ "id": graphene.Node.to_global_id("Warehouse", warehouse_no_shipping_zone.pk),
+ "shippingZoneIds": [zone_id],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_ASSIGN_SHIPPING_ZONE_WAREHOUSE, variables=variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ errors = content["data"]["assignWarehouseShippingZone"]["errors"]
+
+ assert len(errors) == 1
+ assert errors[0]["code"] == WarehouseErrorCode.INVALID.name
+ assert errors[0]["field"] == "shippingZones"
+ assert errors[0]["shippingZones"] == [zone_id]
+
+
+def test_shipping_zone_assign_to_warehouse_no_zone_channels(
+ staff_api_client,
+ warehouse_no_shipping_zone,
+ shipping_zone,
+ permission_manage_products,
+ channel_PLN,
+):
+ # given
+ assert not warehouse_no_shipping_zone.shipping_zones.all()
+
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ # remove all channels from the shipping zone
+ shipping_zone.channels.clear()
+
+ zone_id = graphene.Node.to_global_id("ShippingZone", shipping_zone.pk)
+
+ variables = {
+ "id": graphene.Node.to_global_id("Warehouse", warehouse_no_shipping_zone.pk),
+ "shippingZoneIds": [
+ graphene.Node.to_global_id("ShippingZone", shipping_zone.pk)
+ ],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_ASSIGN_SHIPPING_ZONE_WAREHOUSE, variables=variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ errors = content["data"]["assignWarehouseShippingZone"]["errors"]
+
+ assert len(errors) == 1
+ assert errors[0]["code"] == WarehouseErrorCode.INVALID.name
+ assert errors[0]["field"] == "shippingZones"
+ assert errors[0]["shippingZones"] == [zone_id]
+
+
+def test_empty_shipping_zone_assign_to_warehouse(
+ staff_api_client,
+ warehouse_no_shipping_zone,
+ shipping_zone,
+ permission_manage_products,
+):
+ # given
+ assert not warehouse_no_shipping_zone.shipping_zones.all()
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ variables = {
+ "id": graphene.Node.to_global_id("Warehouse", warehouse_no_shipping_zone.pk),
+ "shippingZoneIds": [],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_ASSIGN_SHIPPING_ZONE_WAREHOUSE, variables=variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ errors = content["data"]["assignWarehouseShippingZone"]["errors"]
+ warehouse_no_shipping_zone.refresh_from_db()
+ shipping_zone.refresh_from_db()
+
+ assert not warehouse_no_shipping_zone.shipping_zones.all()
+ assert errors[0]["field"] == "shippingZoneId"
+ assert errors[0]["code"] == "GRAPHQL_ERROR"
diff --git a/saleor/graphql/warehouse/tests/mutations/test_warehouse_shipping_zone_unassign.py b/saleor/graphql/warehouse/tests/mutations/test_warehouse_shipping_zone_unassign.py
new file mode 100644
index 0000000000..5584afb8cd
--- /dev/null
+++ b/saleor/graphql/warehouse/tests/mutations/test_warehouse_shipping_zone_unassign.py
@@ -0,0 +1,38 @@
+import graphene
+
+MUTATION_UNASSIGN_SHIPPING_ZONE_WAREHOUSE = """
+mutation unassignWarehouseShippingZone($id: ID!, $shippingZoneIds: [ID!]!) {
+ unassignWarehouseShippingZone(id: $id, shippingZoneIds: $shippingZoneIds) {
+ errors {
+ field
+ message
+ code
+ }
+ }
+}
+
+"""
+
+
+def test_shipping_zone_unassign_from_warehouse(
+ staff_api_client, warehouse, shipping_zone, permission_manage_products
+):
+ # given
+ assert warehouse.shipping_zones.first().pk == shipping_zone.pk
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ variables = {
+ "id": graphene.Node.to_global_id("Warehouse", warehouse.pk),
+ "shippingZoneIds": [
+ graphene.Node.to_global_id("ShippingZone", shipping_zone.pk)
+ ],
+ }
+
+ # when
+ staff_api_client.post_graphql(
+ MUTATION_UNASSIGN_SHIPPING_ZONE_WAREHOUSE, variables=variables
+ )
+
+ # then
+ warehouse.refresh_from_db()
+ shipping_zone.refresh_from_db()
+ assert not warehouse.shipping_zones.all()
diff --git a/saleor/graphql/warehouse/tests/mutations/test_warehouse_update.py b/saleor/graphql/warehouse/tests/mutations/test_warehouse_update.py
new file mode 100644
index 0000000000..672f917af6
--- /dev/null
+++ b/saleor/graphql/warehouse/tests/mutations/test_warehouse_update.py
@@ -0,0 +1,451 @@
+import json
+from unittest.mock import patch
+
+import graphene
+import pytest
+from django.utils.functional import SimpleLazyObject
+
+from .....core.utils.json_serializer import CustomJsonEncoder
+from .....warehouse import WarehouseClickAndCollectOption
+from .....warehouse.error_codes import WarehouseErrorCode
+from .....warehouse.models import Warehouse
+from .....webhook.event_types import WebhookEventAsyncType
+from ....tests.utils import get_graphql_content
+from ...enums import WarehouseClickAndCollectOptionEnum
+
+MUTATION_UPDATE_WAREHOUSE = """
+mutation updateWarehouse($input: WarehouseUpdateInput!, $id: ID!) {
+ updateWarehouse(id: $id, input: $input) {
+ errors {
+ message
+ field
+ code
+ }
+ warehouse {
+ name
+ slug
+ companyName
+ isPrivate
+ clickAndCollectOption
+ externalReference
+ address {
+ id
+ streetAddress1
+ streetAddress2
+ }
+ }
+ }
+}
+"""
+
+
+def test_mutation_update_warehouse(
+ staff_api_client, warehouse, permission_manage_products
+):
+ # given
+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.id)
+ warehouse_old_name = warehouse.name
+ warehouse_slug = warehouse.slug
+ external_reference = "test-ext-ref"
+ variables = {
+ "id": warehouse_id,
+ "input": {"name": "New name", "externalReference": external_reference},
+ }
+
+ # when
+ staff_api_client.post_graphql(
+ MUTATION_UPDATE_WAREHOUSE,
+ variables=variables,
+ permissions=[permission_manage_products],
+ )
+
+ # then
+ warehouse.refresh_from_db()
+ assert not (warehouse.name == warehouse_old_name)
+ assert warehouse.name == "New name"
+ assert warehouse.slug == warehouse_slug
+ assert warehouse.external_reference == external_reference
+
+
+def test_mutation_update_warehouse_with_non_unique_external_reference(
+ staff_api_client, warehouse, permission_manage_products, warehouse_JPY
+):
+ # given
+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.id)
+ ext_ref = "test-ext-ref"
+ warehouse_JPY.external_reference = ext_ref
+ warehouse_JPY.save(update_fields=["external_reference"])
+
+ variables = {
+ "id": warehouse_id,
+ "input": {"externalReference": ext_ref},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_UPDATE_WAREHOUSE,
+ variables=variables,
+ permissions=[permission_manage_products],
+ )
+ content = get_graphql_content(response)
+
+ # then
+ error = content["data"]["updateWarehouse"]["errors"][0]
+ assert error["field"] == "externalReference"
+ assert error["code"] == WarehouseErrorCode.UNIQUE.name
+ assert error["message"] == "Warehouse with this External reference already exists."
+
+
+@patch("saleor.plugins.webhook.plugin.get_webhooks_for_event")
+@patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")
+def test_mutation_update_warehouse_trigger_webhook(
+ mocked_webhook_trigger,
+ mocked_get_webhooks_for_event,
+ any_webhook,
+ staff_api_client,
+ warehouse,
+ permission_manage_products,
+ settings,
+):
+ # given
+ mocked_get_webhooks_for_event.return_value = [any_webhook]
+ settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
+
+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.id)
+ variables = {
+ "id": warehouse_id,
+ "input": {"name": "New name"},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_UPDATE_WAREHOUSE,
+ variables=variables,
+ permissions=[permission_manage_products],
+ )
+ content = get_graphql_content(response)
+ warehouse.refresh_from_db()
+
+ # then
+ assert content["data"]["updateWarehouse"]["warehouse"]
+ mocked_webhook_trigger.assert_called_once_with(
+ json.dumps(
+ {
+ "id": variables["id"],
+ "name": warehouse.name,
+ },
+ cls=CustomJsonEncoder,
+ ),
+ WebhookEventAsyncType.WAREHOUSE_UPDATED,
+ [any_webhook],
+ warehouse,
+ SimpleLazyObject(lambda: staff_api_client.user),
+ )
+
+
+def test_mutation_update_warehouse_can_update_address(
+ staff_api_client, warehouse, permission_manage_products
+):
+ # given
+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)
+ address_id = graphene.Node.to_global_id("Address", warehouse.address.pk)
+ address = warehouse.address
+ variables = {
+ "id": warehouse_id,
+ "input": {
+ "name": warehouse.name,
+ "address": {
+ "streetAddress1": "Teczowa 8",
+ "streetAddress2": "Ground floor",
+ "companyName": "",
+ "city": address.city,
+ "country": address.country.code,
+ "postalCode": "53-601",
+ },
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_UPDATE_WAREHOUSE,
+ variables=variables,
+ permissions=[permission_manage_products],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ content_address = content["data"]["updateWarehouse"]["warehouse"]["address"]
+ assert content_address["id"] == address_id
+ address.refresh_from_db()
+ assert address.street_address_1 == "Teczowa 8"
+ assert address.street_address_2 == "Ground floor"
+
+
+def test_mutation_update_warehouse_to_country_with_different_validation_rules(
+ staff_api_client, warehouse, permission_manage_products, address_usa
+):
+ # given
+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)
+ warehouse.address = address_usa
+ warehouse.save(update_fields=["address"])
+ address_id = graphene.Node.to_global_id("Address", warehouse.address.pk)
+ variables = {
+ "id": warehouse_id,
+ "input": {
+ "name": warehouse.name,
+ "address": {
+ "streetAddress1": "Fake street",
+ "city": "London",
+ "country": "GB",
+ "postalCode": "B52 1AA",
+ },
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ MUTATION_UPDATE_WAREHOUSE,
+ variables=variables,
+ permissions=[permission_manage_products],
+ )
+ content = get_graphql_content(response)
+ content_address = content["data"]["updateWarehouse"]["warehouse"]["address"]
+
+ # then
+ assert len(content["data"]["updateWarehouse"]["errors"]) == 0
+ assert content_address["streetAddress1"] == "Fake street"
+ assert content_address["id"] == address_id
+
+
+ "input_slug, expected_slug, error_message",
+ [
+ ("test-slug", "test-slug", None),
+ ("", "", "Slug value cannot be blank."),
+ (None, "", "Slug value cannot be blank."),
+ ],
+)
+def test_update_warehouse_slug(
+ staff_api_client,
+ warehouse,
+ permission_manage_products,
+ input_slug,
+ expected_slug,
+ error_message,
+):
+ # given
+ query = MUTATION_UPDATE_WAREHOUSE
+ old_slug = warehouse.slug
+
+ assert old_slug != input_slug
+
+ node_id = graphene.Node.to_global_id("Warehouse", warehouse.id)
+ variables = {"id": node_id, "input": {"slug": input_slug}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["updateWarehouse"]
+ errors = data["errors"]
+ if not error_message:
+ assert not errors
+ assert data["warehouse"]["slug"] == expected_slug
+ else:
+ assert errors
+ assert errors[0]["field"] == "slug"
+ assert errors[0]["code"] == WarehouseErrorCode.REQUIRED.name
+
+
+def test_update_warehouse_slug_exists(
+ staff_api_client, warehouse, permission_manage_products
+):
+ # given
+ query = MUTATION_UPDATE_WAREHOUSE
+ input_slug = "test-slug"
+
+ second_warehouse = Warehouse.objects.get(pk=warehouse.pk)
+ second_warehouse.pk = None
+ second_warehouse.slug = input_slug
+ second_warehouse.save()
+
+ assert input_slug != warehouse.slug
+
+ node_id = graphene.Node.to_global_id("Warehouse", warehouse.id)
+ variables = {"id": node_id, "input": {"slug": input_slug}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["updateWarehouse"]
+ errors = data["errors"]
+ assert errors
+ assert errors[0]["field"] == "slug"
+ assert errors[0]["code"] == WarehouseErrorCode.UNIQUE.name
+
+
+ "input_slug, expected_slug, input_name, expected_name, error_message, error_field",
+ [
+ ("test-slug", "test-slug", "New name", "New name", None, None),
+ (
+ "test-slug",
+ "test-slug",
+ " stripped ",
+ "stripped",
+ None,
+ None,
+ ),
+ ("", "", "New name", "New name", "Slug value cannot be blank.", "slug"),
+ (None, "", "New name", "New name", "Slug value cannot be blank.", "slug"),
+ ("test-slug", "", None, None, "This field cannot be blank.", "name"),
+ ("test-slug", "", "", None, "This field cannot be blank.", "name"),
+ (None, None, None, None, "Slug value cannot be blank.", "slug"),
+ ("test-slug", "test-slug", " ", None, "Name value cannot be blank", "name"),
+ ],
+)
+def test_update_warehouse_slug_and_name(
+ staff_api_client,
+ warehouse,
+ permission_manage_products,
+ input_slug,
+ expected_slug,
+ input_name,
+ expected_name,
+ error_message,
+ error_field,
+):
+ # given
+ query = MUTATION_UPDATE_WAREHOUSE
+
+ old_name = warehouse.name
+ old_slug = warehouse.slug
+
+ assert input_slug != old_slug
+ assert input_name != old_name
+
+ node_id = graphene.Node.to_global_id("Warehouse", warehouse.id)
+ variables = {"input": {"slug": input_slug, "name": input_name}, "id": node_id}
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ warehouse.refresh_from_db()
+ data = content["data"]["updateWarehouse"]
+ errors = data["errors"]
+ if not error_message:
+ assert data["warehouse"]["name"] == expected_name == warehouse.name
+ assert (
+ data["warehouse"]["slug"] == input_slug == warehouse.slug == expected_slug
+ )
+ else:
+ assert errors
+ assert errors[0]["field"] == error_field
+ assert errors[0]["code"] == WarehouseErrorCode.REQUIRED.name
+
+
+ "expected_private, expected_cc_option",
+ [
+ (private, option)
+ for private in (True, False)
+ for option in [
+ WarehouseClickAndCollectOptionEnum.ALL.name,
+ WarehouseClickAndCollectOptionEnum.DISABLED.name,
+ ]
+ ]
+ + [(False, WarehouseClickAndCollectOptionEnum.LOCAL.name)],
+)
+def test_update_click_and_collect_option(
+ staff_api_client,
+ warehouse,
+ permission_manage_products,
+ expected_private,
+ expected_cc_option,
+):
+ # given
+ query = MUTATION_UPDATE_WAREHOUSE
+
+ assert warehouse.is_private
+ assert warehouse.click_and_collect_option == WarehouseClickAndCollectOption.DISABLED
+
+ node_id = graphene.Node.to_global_id("Warehouse", warehouse.id)
+ variables = {
+ "input": {
+ "isPrivate": expected_private,
+ "clickAndCollectOption": expected_cc_option,
+ },
+ "id": node_id,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ warehouse.refresh_from_db()
+ data = content["data"]["updateWarehouse"]
+ errors = data["errors"]
+
+ assert not errors
+ assert data["warehouse"]["isPrivate"] == expected_private == warehouse.is_private
+ assert (
+ data["warehouse"]["clickAndCollectOption"]
+ == expected_cc_option
+ == warehouse.click_and_collect_option.upper()
+ )
+
+
+def test_update_click_and_collect_option_invalid_input(
+ staff_api_client, warehouse, permission_manage_products
+):
+ # given
+ query = MUTATION_UPDATE_WAREHOUSE
+
+ warehouse_is_private = warehouse.is_private
+ warehouse_click_and_collect = warehouse.click_and_collect_option
+ assert warehouse_is_private
+ assert warehouse_click_and_collect == WarehouseClickAndCollectOption.DISABLED
+
+ node_id = graphene.Node.to_global_id("Warehouse", warehouse.id)
+ variables = {
+ "input": {
+ "isPrivate": True,
+ "clickAndCollectOption": WarehouseClickAndCollectOptionEnum.LOCAL.name,
+ },
+ "id": node_id,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ warehouse.refresh_from_db()
+ data = content["data"]["updateWarehouse"]
+ errors = data["errors"]
+
+ assert len(errors) == 1
+ assert (
+ errors[0]["message"]
+ == "Local warehouse can be toggled only for non-private warehouse stocks"
+ )
+ assert errors[0]["field"] == "clickAndCollectOption"
+
+ assert warehouse.is_private == warehouse_is_private
+ assert warehouse.click_and_collect_option == warehouse_click_and_collect
diff --git a/saleor/graphql/warehouse/tests/queries/__init__.py b/saleor/graphql/warehouse/tests/queries/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/graphql/warehouse/tests/queries/test_stock.py b/saleor/graphql/warehouse/tests/queries/test_stock.py
new file mode 100644
index 0000000000..b0c4d52ef6
--- /dev/null
+++ b/saleor/graphql/warehouse/tests/queries/test_stock.py
@@ -0,0 +1,154 @@
+from datetime import timedelta
+
+import graphene
+from django.utils import timezone
+
+from .....permission.enums import ProductPermissions
+from .....warehouse.models import Reservation
+from .....warehouse.tests.utils import get_quantity_allocated_for_stock
+from ....tests.utils import (
+ assert_no_permission,
+ get_graphql_content,
+ get_graphql_content_from_response,
+)
+
+QUERY_STOCK = """
+query stock($id: ID!) {
+ stock(id: $id) {
+ warehouse {
+ name
+ }
+ productVariant {
+ product {
+ name
+ }
+ }
+ quantity
+ quantityAllocated
+ quantityReserved
+ }
+}
+"""
+
+
+def test_query_stock_requires_permission(staff_api_client, stock):
+ # given
+ assert not staff_api_client.user.has_perm(ProductPermissions.MANAGE_PRODUCTS)
+ stock_id = graphene.Node.to_global_id("Stock", stock.pk)
+
+ # when
+ response = staff_api_client.post_graphql(QUERY_STOCK, variables={"id": stock_id})
+
+ # then
+ assert_no_permission(response)
+
+
+def test_query_stock(staff_api_client, stock, permission_manage_products):
+ # given
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ stock_id = graphene.Node.to_global_id("Stock", stock.pk)
+
+ # when
+ response = staff_api_client.post_graphql(QUERY_STOCK, variables={"id": stock_id})
+
+ # then
+ content = get_graphql_content(response)
+ content_stock = content["data"]["stock"]
+ assert (
+ content_stock["productVariant"]["product"]["name"]
+ == stock.product_variant.product.name
+ )
+ assert content_stock["warehouse"]["name"] == stock.warehouse.name
+ assert content_stock["quantity"] == stock.quantity
+ assert content_stock["quantityAllocated"] == get_quantity_allocated_for_stock(stock)
+ assert content_stock["quantityReserved"] == 0
+
+
+def test_query_stock_with_reservations(
+ site_settings_with_reservations,
+ staff_api_client,
+ stock,
+ checkout_line_with_reservation_in_many_stocks,
+ permission_manage_products,
+):
+ # given
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ stock_id = graphene.Node.to_global_id("Stock", stock.pk)
+
+ # when
+ response = staff_api_client.post_graphql(QUERY_STOCK, variables={"id": stock_id})
+
+ # then
+ content = get_graphql_content(response)
+ content_stock = content["data"]["stock"]
+ assert (
+ content_stock["productVariant"]["product"]["name"]
+ == stock.product_variant.product.name
+ )
+ assert content_stock["warehouse"]["name"] == stock.warehouse.name
+ assert content_stock["quantity"] == stock.quantity
+ assert content_stock["quantityAllocated"] == get_quantity_allocated_for_stock(stock)
+ assert content_stock["quantityReserved"] == 2
+
+
+def test_query_stock_with_expired_reservations(
+ site_settings_with_reservations,
+ staff_api_client,
+ stock,
+ checkout_line_with_reservation_in_many_stocks,
+ permission_manage_products,
+):
+ # given
+ Reservation.objects.update(reserved_until=timezone.now() - timedelta(minutes=2))
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ stock_id = graphene.Node.to_global_id("Stock", stock.pk)
+
+ # when
+ response = staff_api_client.post_graphql(QUERY_STOCK, variables={"id": stock_id})
+
+ # then
+ content = get_graphql_content(response)
+ content_stock = content["data"]["stock"]
+ assert (
+ content_stock["productVariant"]["product"]["name"]
+ == stock.product_variant.product.name
+ )
+ assert content_stock["warehouse"]["name"] == stock.warehouse.name
+ assert content_stock["quantity"] == stock.quantity
+ assert content_stock["quantityAllocated"] == get_quantity_allocated_for_stock(stock)
+ assert content_stock["quantityReserved"] == 0
+
+
+def test_staff_query_stock_by_invalid_id(
+ staff_api_client, stock, permission_manage_products
+):
+ # given
+ id = "bh/"
+ variables = {"id": id}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_STOCK, variables, permissions=[permission_manage_products]
+ )
+
+ # then
+ content = get_graphql_content_from_response(response)
+ assert len(content["errors"]) == 1
+ assert content["errors"][0]["message"] == f"Couldn't resolve id: {id}."
+ assert content["data"]["stock"] is None
+
+
+def test_staff_query_stock_with_invalid_object_type(
+ staff_api_client, stock, permission_manage_products
+):
+ # given
+ variables = {"id": graphene.Node.to_global_id("Order", stock.pk)}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_STOCK, variables, permissions=[permission_manage_products]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["stock"] is None
diff --git a/saleor/graphql/warehouse/tests/queries/test_stocks.py b/saleor/graphql/warehouse/tests/queries/test_stocks.py
new file mode 100644
index 0000000000..140818eb60
--- /dev/null
+++ b/saleor/graphql/warehouse/tests/queries/test_stocks.py
@@ -0,0 +1,51 @@
+from .....permission.enums import ProductPermissions
+from .....warehouse.models import Stock
+from ....tests.utils import assert_no_permission, get_graphql_content
+
+QUERY_STOCKS = """
+ query {
+ stocks(first:100) {
+ totalCount
+ edges {
+ node {
+ id
+ warehouse {
+ name
+ id
+ }
+ productVariant {
+ name
+ id
+ }
+ quantity
+ quantityAllocated
+ quantityReserved
+ }
+ }
+ }
+ }
+"""
+
+
+def test_query_stocks_requires_permissions(staff_api_client):
+ # given
+ assert not staff_api_client.user.has_perm(ProductPermissions.MANAGE_PRODUCTS)
+
+ # when
+ response = staff_api_client.post_graphql(QUERY_STOCKS)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_query_stocks(staff_api_client, stock, permission_manage_products):
+ # given
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ # when
+ response = staff_api_client.post_graphql(QUERY_STOCKS)
+
+ # then
+ content = get_graphql_content(response)
+ total_count = content["data"]["stocks"]["totalCount"]
+ assert total_count == Stock.objects.count()
diff --git a/saleor/graphql/warehouse/tests/queries/test_stocks_filtering.py b/saleor/graphql/warehouse/tests/queries/test_stocks_filtering.py
new file mode 100644
index 0000000000..687a45e311
--- /dev/null
+++ b/saleor/graphql/warehouse/tests/queries/test_stocks_filtering.py
@@ -0,0 +1,104 @@
+from .....warehouse.models import Stock
+from ....tests.utils import get_graphql_content
+
+QUERY_STOCKS_WITH_FILTERS = """
+ query stocks($filter: StockFilterInput!) {
+ stocks(first: 100, filter: $filter) {
+ totalCount
+ edges {
+ node {
+ id
+ }
+ }
+ }
+ }
+"""
+
+
+def test_query_stocks_with_filters_quantity(
+ staff_api_client, stock, permission_manage_products
+):
+ # given
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ quantities = Stock.objects.all().values_list("quantity", flat=True)
+ sum_quantities = sum(quantities)
+ variables = {"filter": {"quantity": sum_quantities}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_STOCKS_WITH_FILTERS, variables=variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ total_count = content["data"]["stocks"]["totalCount"]
+ assert total_count == 0
+
+ variables = {"filter": {"quantity": max(quantities)}}
+ response = staff_api_client.post_graphql(
+ QUERY_STOCKS_WITH_FILTERS, variables=variables
+ )
+ content = get_graphql_content(response)
+ total_count = content["data"]["stocks"]["totalCount"]
+ assert total_count == Stock.objects.filter(quantity=max(quantities)).count()
+
+
+def test_query_stocks_with_filters_warehouse(
+ staff_api_client, stock, permission_manage_products
+):
+ # given
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ warehouse = stock.warehouse
+
+ # when
+ response_name = staff_api_client.post_graphql(
+ QUERY_STOCKS_WITH_FILTERS, variables={"filter": {"search": warehouse.name}}
+ )
+
+ # then
+ content = get_graphql_content(response_name)
+ total_count = content["data"]["stocks"]["totalCount"]
+ assert total_count == Stock.objects.filter(warehouse=warehouse).count()
+
+
+def test_query_stocks_with_filters_product_variant(
+ staff_api_client, stock, permission_manage_products
+):
+ # given
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ product_variant = stock.product_variant
+
+ # when
+ response_name = staff_api_client.post_graphql(
+ QUERY_STOCKS_WITH_FILTERS,
+ variables={"filter": {"search": product_variant.name}},
+ )
+
+ # then
+ content = get_graphql_content(response_name)
+ total_count = content["data"]["stocks"]["totalCount"]
+ assert (
+ total_count
+ == Stock.objects.filter(product_variant__name=product_variant.name).count()
+ )
+
+
+def test_query_stocks_with_filters_product_variant__product(
+ staff_api_client, stock, permission_manage_products
+):
+ # given
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ product = stock.product_variant.product
+
+ # when
+ response_name = staff_api_client.post_graphql(
+ QUERY_STOCKS_WITH_FILTERS, variables={"filter": {"search": product.name}}
+ )
+
+ # then
+ content = get_graphql_content(response_name)
+ total_count = content["data"]["stocks"]["totalCount"]
+ assert (
+ total_count
+ == Stock.objects.filter(product_variant__product__name=product.name).count()
+ )
diff --git a/saleor/graphql/warehouse/tests/queries/test_warehouse.py b/saleor/graphql/warehouse/tests/queries/test_warehouse.py
new file mode 100644
index 0000000000..8b6a5b0f01
--- /dev/null
+++ b/saleor/graphql/warehouse/tests/queries/test_warehouse.py
@@ -0,0 +1,229 @@
+import graphene
+
+from ....tests.utils import (
+ assert_no_permission,
+ get_graphql_content,
+ get_graphql_content_from_response,
+)
+
+QUERY_WAREHOUSE = """
+query warehouse($id: ID!){
+ warehouse(id: $id) {
+ id
+ name
+ companyName
+ email
+ shippingZones(first: 100) {
+ edges {
+ node {
+ name
+ countries {
+ country
+ }
+ }
+ }
+ }
+ address {
+ streetAddress1
+ streetAddress2
+ postalCode
+ city
+ phone
+ }
+ }
+}
+"""
+
+
+def test_warehouse_query(staff_api_client, warehouse, permission_manage_products):
+ # given
+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_WAREHOUSE,
+ variables={"id": warehouse_id},
+ permissions=[permission_manage_products],
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ queried_warehouse = content["data"]["warehouse"]
+ assert queried_warehouse["name"] == warehouse.name
+ assert queried_warehouse["email"] == warehouse.email
+
+ shipping_zones = queried_warehouse["shippingZones"]["edges"]
+ assert len(shipping_zones) == warehouse.shipping_zones.count()
+ queried_shipping_zone = shipping_zones[0]["node"]
+ shipipng_zone = warehouse.shipping_zones.first()
+ assert queried_shipping_zone["name"] == shipipng_zone.name
+ assert len(queried_shipping_zone["countries"]) == len(shipipng_zone.countries)
+
+ address = warehouse.address
+ queried_address = queried_warehouse["address"]
+ assert queried_address["streetAddress1"] == address.street_address_1
+ assert queried_address["postalCode"] == address.postal_code
+
+
+def test_warehouse_query_as_staff_with_manage_orders(
+ staff_api_client, warehouse, permission_manage_orders
+):
+ # given
+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_WAREHOUSE,
+ variables={"id": warehouse_id},
+ permissions=[permission_manage_orders],
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ queried_warehouse = content["data"]["warehouse"]
+ assert queried_warehouse["name"] == warehouse.name
+ assert queried_warehouse["email"] == warehouse.email
+
+ shipping_zones = queried_warehouse["shippingZones"]["edges"]
+ assert len(shipping_zones) == warehouse.shipping_zones.count()
+ queried_shipping_zone = shipping_zones[0]["node"]
+ shipipng_zone = warehouse.shipping_zones.first()
+ assert queried_shipping_zone["name"] == shipipng_zone.name
+ assert len(queried_shipping_zone["countries"]) == len(shipipng_zone.countries)
+
+ address = warehouse.address
+ queried_address = queried_warehouse["address"]
+ assert queried_address["streetAddress1"] == address.street_address_1
+ assert queried_address["postalCode"] == address.postal_code
+
+
+def test_warehouse_query_as_staff_with_manage_shipping(
+ staff_api_client, warehouse, permission_manage_shipping
+):
+ # given
+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_WAREHOUSE,
+ variables={"id": warehouse_id},
+ permissions=[permission_manage_shipping],
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ queried_warehouse = content["data"]["warehouse"]
+ assert queried_warehouse["name"] == warehouse.name
+ assert queried_warehouse["email"] == warehouse.email
+
+ shipping_zones = queried_warehouse["shippingZones"]["edges"]
+ assert len(shipping_zones) == warehouse.shipping_zones.count()
+ queried_shipping_zone = shipping_zones[0]["node"]
+ shipipng_zone = warehouse.shipping_zones.first()
+ assert queried_shipping_zone["name"] == shipipng_zone.name
+ assert len(queried_shipping_zone["countries"]) == len(shipipng_zone.countries)
+
+ address = warehouse.address
+ queried_address = queried_warehouse["address"]
+ assert queried_address["streetAddress1"] == address.street_address_1
+ assert queried_address["postalCode"] == address.postal_code
+
+
+def test_warehouse_query_as_staff_with_manage_apps(
+ staff_api_client, warehouse, permission_manage_apps
+):
+ # given
+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_WAREHOUSE,
+ variables={"id": warehouse_id},
+ permissions=[permission_manage_apps],
+ )
+
+ # then
+ assert_no_permission(response)
+
+
+def test_warehouse_query_as_customer(user_api_client, warehouse):
+ # given
+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)
+
+ # when
+ response = user_api_client.post_graphql(
+ QUERY_WAREHOUSE,
+ variables={"id": warehouse_id},
+ )
+
+ # then
+ assert_no_permission(response)
+
+
+def test_staff_query_warehouse_by_invalid_id(
+ staff_api_client, warehouse, permission_manage_shipping
+):
+ # given
+ id = "bh/"
+ variables = {"id": id}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_WAREHOUSE, variables, permissions=[permission_manage_shipping]
+ )
+
+ # then
+ content = get_graphql_content_from_response(response)
+ assert len(content["errors"]) == 1
+ assert content["errors"][0]["message"] == f"Couldn't resolve id: {id}."
+ assert content["data"]["warehouse"] is None
+
+
+def test_staff_query_warehouse_with_invalid_object_type(
+ staff_api_client, permission_manage_shipping, warehouse
+):
+ # given
+ variables = {"id": graphene.Node.to_global_id("Order", warehouse.pk)}
+ response = staff_api_client.post_graphql(
+ QUERY_WAREHOUSE, variables, permissions=[permission_manage_shipping]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert content["data"]["warehouse"] is None
+
+
+QUERY_WAREHOUSE_BY_EXTERNAL_REFERENCE = """
+query warehouse($id: ID, $externalReference: String){
+ warehouse(id: $id, externalReference: $externalReference) {
+ id
+ externalReference
+ }
+}
+"""
+
+
+def test_warehouse_query_by_external_reference(
+ staff_api_client, warehouse, permission_manage_products
+):
+ # given
+ ext_ref = "test-ext-ref"
+ warehouse.external_reference = ext_ref
+ warehouse.save(update_fields=["external_reference"])
+ variables = {"externalReference": ext_ref}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_WAREHOUSE_BY_EXTERNAL_REFERENCE,
+ variables=variables,
+ permissions=[permission_manage_products],
+ )
+ content = get_graphql_content(response)
+
+ # then
+ data = content["data"]["warehouse"]
+ assert data["externalReference"] == ext_ref
+ assert data["id"] == graphene.Node.to_global_id("Warehouse", warehouse.id)
diff --git a/saleor/graphql/warehouse/tests/queries/test_warehouses.py b/saleor/graphql/warehouse/tests/queries/test_warehouses.py
new file mode 100644
index 0000000000..37d82e7593
--- /dev/null
+++ b/saleor/graphql/warehouse/tests/queries/test_warehouses.py
@@ -0,0 +1,124 @@
+import graphene
+
+from .....warehouse.models import Warehouse
+from ....tests.utils import assert_no_permission, get_graphql_content
+
+QUERY_WAREHOUSES = """
+query {
+ warehouses(first:100) {
+ totalCount
+ edges {
+ node {
+ id
+ name
+ companyName
+ email
+ shippingZones(first:100) {
+ edges {
+ node {
+ name
+ countries {
+ country
+ }
+ }
+ }
+ }
+ address {
+ city
+ postalCode
+ country {
+ country
+ }
+ phone
+ }
+ }
+ }
+ }
+}
+"""
+
+
+def test_query_warehouses_as_staff_with_manage_orders(
+ staff_api_client, warehouse, permission_manage_orders
+):
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_WAREHOUSES, permissions=[permission_manage_orders]
+ )
+
+ # then
+ content = get_graphql_content(response)["data"]
+ assert content["warehouses"]["totalCount"] == Warehouse.objects.count()
+ warehouses = content["warehouses"]["edges"]
+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)
+ warehouse_first = warehouses[0]["node"]
+ assert warehouse_first["id"] == warehouse_id
+ assert warehouse_first["name"] == warehouse.name
+ assert (
+ len(warehouse_first["shippingZones"]["edges"])
+ == warehouse.shipping_zones.count()
+ )
+
+
+def test_query_warehouses_as_staff_with_manage_shipping(
+ staff_api_client, warehouse, permission_manage_shipping
+):
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_WAREHOUSES, permissions=[permission_manage_shipping]
+ )
+
+ # then
+ content = get_graphql_content(response)["data"]
+ assert content["warehouses"]["totalCount"] == Warehouse.objects.count()
+ warehouses = content["warehouses"]["edges"]
+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)
+ warehouse_first = warehouses[0]["node"]
+ assert warehouse_first["id"] == warehouse_id
+ assert warehouse_first["name"] == warehouse.name
+ assert (
+ len(warehouse_first["shippingZones"]["edges"])
+ == warehouse.shipping_zones.count()
+ )
+
+
+def test_query_warehouses_as_staff_with_manage_apps(
+ staff_api_client, warehouse, permission_manage_apps
+):
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_WAREHOUSES, permissions=[permission_manage_apps]
+ )
+
+ # then
+ assert_no_permission(response)
+
+
+def test_query_warehouses_as_customer(
+ user_api_client, warehouse, permission_manage_apps
+):
+ # when
+ response = user_api_client.post_graphql(QUERY_WAREHOUSES)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_query_warehouses(staff_api_client, warehouse, permission_manage_products):
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_WAREHOUSES, permissions=[permission_manage_products]
+ )
+
+ # then
+ content = get_graphql_content(response)["data"]
+ assert content["warehouses"]["totalCount"] == Warehouse.objects.count()
+ warehouses = content["warehouses"]["edges"]
+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)
+ warehouse_first = warehouses[0]["node"]
+ assert warehouse_first["id"] == warehouse_id
+ assert warehouse_first["name"] == warehouse.name
+ assert (
+ len(warehouse_first["shippingZones"]["edges"])
+ == warehouse.shipping_zones.count()
+ )
diff --git a/saleor/graphql/warehouse/tests/queries/test_warehouses_filtering.py b/saleor/graphql/warehouse/tests/queries/test_warehouses_filtering.py
new file mode 100644
index 0000000000..d9206b9deb
--- /dev/null
+++ b/saleor/graphql/warehouse/tests/queries/test_warehouses_filtering.py
@@ -0,0 +1,308 @@
+import graphene
+import pytest
+
+from .....warehouse import WarehouseClickAndCollectOption
+from .....warehouse.models import Warehouse
+from ....tests.utils import get_graphql_content
+
+QUERY_WAREHOUSES_WITH_FILTERS = """
+query Warehouses($filters: WarehouseFilterInput) {
+ warehouses(first:100, filter: $filters) {
+ totalCount
+ edges {
+ node {
+ id
+ name
+ companyName
+ email
+ }
+ }
+ }
+}
+"""
+
+QUERY_WERHOUSES_WITH_FILTERS_NO_IDS = """
+query Warehouses($filters: WarehouseFilterInput) {
+ warehouses(first:100, filter: $filters) {
+ totalCount
+ edges {
+ node {
+ name
+ companyName
+ email
+ }
+ }
+ }
+}
+"""
+
+
+def test_query_warehouses_with_filters_name(
+ staff_api_client, permission_manage_products, warehouse
+):
+ # given
+ variables_exists = {"filters": {"search": "warehouse"}}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_WAREHOUSES_WITH_FILTERS,
+ variables=variables_exists,
+ permissions=[permission_manage_products],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.id)
+ content_warehouse = content["data"]["warehouses"]["edges"][0]["node"]
+ assert content_warehouse["id"] == warehouse_id
+ variables_does_not_exists = {"filters": {"search": "Absolutelywrong name"}}
+ response1 = staff_api_client.post_graphql(
+ QUERY_WAREHOUSES_WITH_FILTERS, variables=variables_does_not_exists
+ )
+ content1 = get_graphql_content(response1)
+ total_count = content1["data"]["warehouses"]["totalCount"]
+ assert total_count == 0
+
+
+def test_query_warehouse_with_filters_email(
+ staff_api_client, permission_manage_products, warehouse
+):
+ # given
+ variables_exists = {"filters": {"search": "test"}}
+
+ # when
+ response_exists = staff_api_client.post_graphql(
+ QUERY_WAREHOUSES_WITH_FILTERS,
+ variables=variables_exists,
+ permissions=[permission_manage_products],
+ )
+
+ # then
+ content_exists = get_graphql_content(response_exists)
+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.id)
+ content_warehouse = content_exists["data"]["warehouses"]["edges"][0]["node"]
+ assert content_warehouse["id"] == warehouse_id
+
+ variable_does_not_exists = {"filters": {"search": "[email protected]"}}
+ response_not_exists = staff_api_client.post_graphql(
+ QUERY_WAREHOUSES_WITH_FILTERS, variables=variable_does_not_exists
+ )
+ content_not_exists = get_graphql_content(response_not_exists)
+ total_count = content_not_exists["data"]["warehouses"]["totalCount"]
+ assert total_count == 0
+
+
+def test_query_warehouse_with_filters_by_ids(
+ staff_api_client, permission_manage_products, warehouse, warehouse_no_shipping_zone
+):
+ # given
+ warehouse_ids = [
+ graphene.Node.to_global_id("Warehouse", warehouse.id),
+ graphene.Node.to_global_id("Warehouse", warehouse_no_shipping_zone.id),
+ ]
+ variables_exists = {"filters": {"ids": warehouse_ids}}
+
+ # when
+ response_exists = staff_api_client.post_graphql(
+ QUERY_WAREHOUSES_WITH_FILTERS,
+ variables=variables_exists,
+ permissions=[permission_manage_products],
+ )
+
+ # then
+ content_exists = get_graphql_content(response_exists)
+
+ content_warehouses = content_exists["data"]["warehouses"]["edges"]
+ for content_warehouse in content_warehouses:
+ assert content_warehouse["node"]["id"] in warehouse_ids
+ assert content_exists["data"]["warehouses"]["totalCount"] == 2
+
+
+def test_query_warehouse_with_filters_by_id(
+ staff_api_client, permission_manage_products, warehouse, warehouse_no_shipping_zone
+):
+ # given
+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.id)
+ variables_exists = {"filters": {"ids": [warehouse_id]}}
+
+ # when
+ response_exists = staff_api_client.post_graphql(
+ QUERY_WAREHOUSES_WITH_FILTERS,
+ variables=variables_exists,
+ permissions=[permission_manage_products],
+ )
+
+ # then
+ content_exists = get_graphql_content(response_exists)
+
+ content_warehouses = content_exists["data"]["warehouses"]["edges"]
+ assert content_warehouses[0]["node"]["id"] == warehouse_id
+ assert content_exists["data"]["warehouses"]["totalCount"] == 1
+
+
+ "graphql_filter, db_filter", [("true", True), ("false", False)]
+)
+def test_query_warehouse_with_filters_by_is_private(
+ staff_api_client,
+ permission_manage_products,
+ warehouses_for_cc,
+ graphql_filter,
+ db_filter,
+):
+ # given
+ db_count = Warehouse.objects.filter(is_private=db_filter).count()
+ variables_exists = {"filters": {"isPrivate": graphql_filter}}
+
+ # when
+ response_exists = staff_api_client.post_graphql(
+ QUERY_WAREHOUSES_WITH_FILTERS,
+ variables=variables_exists,
+ permissions=[permission_manage_products],
+ )
+
+ # then
+ content_exists = get_graphql_content(response_exists)
+
+ assert content_exists["data"]["warehouses"]["totalCount"] == db_count
+
+
+ "db_option, graphql_option",
+ [
+ (WarehouseClickAndCollectOption.DISABLED, "DISABLED"),
+ (WarehouseClickAndCollectOption.ALL_WAREHOUSES, "ALL"),
+ (WarehouseClickAndCollectOption.LOCAL_STOCK, "LOCAL"),
+ ],
+)
+def test_query_warehouse_with_filters_by_click_and_collect_option(
+ staff_api_client,
+ permission_manage_products,
+ warehouses_for_cc,
+ db_option,
+ graphql_option,
+):
+ # given
+ db_count = Warehouse.objects.filter(click_and_collect_option=db_option).count()
+ variables_exists = {"filters": {"clickAndCollectOption": graphql_option}}
+
+ # when
+ response_exists = staff_api_client.post_graphql(
+ QUERY_WAREHOUSES_WITH_FILTERS,
+ variables=variables_exists,
+ permissions=[permission_manage_products],
+ )
+
+ # then
+ content_exists = get_graphql_content(response_exists)
+ assert content_exists["data"]["warehouses"]["totalCount"] == db_count
+
+
+def test_query_warehouses_with_filters_and_no_id(
+ staff_api_client, permission_manage_products, warehouse
+):
+ # given
+ variables_exists = {"filters": {"search": "test"}}
+
+ # when
+ response_exists = staff_api_client.post_graphql(
+ QUERY_WAREHOUSES_WITH_FILTERS,
+ variables=variables_exists,
+ permissions=[permission_manage_products],
+ )
+
+ # then
+ content_exists = get_graphql_content(response_exists)
+ warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.id)
+ content_warehouse = content_exists["data"]["warehouses"]["edges"][0]["node"]
+ assert content_warehouse["id"] == warehouse_id
+
+ variable_does_not_exists = {"filters": {"search": "[email protected]"}}
+ response_not_exists = staff_api_client.post_graphql(
+ QUERY_WAREHOUSES_WITH_FILTERS, variables=variable_does_not_exists
+ )
+ content_not_exists = get_graphql_content(response_not_exists)
+ total_count = content_not_exists["data"]["warehouses"]["totalCount"]
+ 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
+
+
+ "filter_by, pages_count",
+ [
+ ({"slugs": ["warehouse1", "warehouse2"]}, 2),
+ ({"slugs": []}, 2),
+ ],
+)
+def test_query_warehouses_with_filtering(
+ filter_by, pages_count, staff_api_client, permission_manage_products, warehouses
+):
+ # given
+ variables = {"filter": filter_by}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_WAREHOUSES_WITH_FILTERS,
+ variables,
+ permissions=[permission_manage_products],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ pages_nodes = content["data"]["warehouses"]["edges"]
+ assert len(pages_nodes) == pages_count
diff --git a/saleor/graphql/warehouse/tests/test_pagination.py b/saleor/graphql/warehouse/tests/queries/test_warehouses_pagination.py
similarity index 95%
rename from saleor/graphql/warehouse/tests/test_pagination.py
rename to saleor/graphql/warehouse/tests/queries/test_warehouses_pagination.py
index f2e99b62be..dbc9f51a1e 100644
--- a/saleor/graphql/warehouse/tests/test_pagination.py
+++ b/saleor/graphql/warehouse/tests/queries/test_warehouses_pagination.py
@@ -1,8 +1,8 @@
import graphene
import pytest
-from ....warehouse.models import Warehouse
-from ...tests.utils import get_graphql_content
+from .....warehouse.models import Warehouse
+from ....tests.utils import get_graphql_content
@pytest.fixture
@@ -83,12 +83,17 @@ def test_warehouses_pagination_with_sorting(
permission_manage_products,
warehouses_for_pagination,
):
+ # given
page_size = 3
variables = {"first": page_size, "after": None, "sortBy": sort_by}
+
+ # when
response = staff_api_client.post_graphql(
QUERY_WAREHOUSES_PAGINATION, variables, permissions=[permission_manage_products]
)
+
+ # then
content = get_graphql_content(response)
warehouses_nodes = content["data"]["warehouses"]["edges"]
assert warehouses_order[0] == warehouses_nodes[0]["node"]["name"]
@@ -114,12 +119,17 @@ def test_warehouses_pagination_with_filtering(
permission_manage_products,
warehouses_for_pagination,
):
+ # given
page_size = 2
variables = {"first": page_size, "after": None, "filter": filter_by}
+
+ # when
response = staff_api_client.post_graphql(
QUERY_WAREHOUSES_PAGINATION, variables, permissions=[permission_manage_products]
)
+
+ # then
content = get_graphql_content(response)
warehouses_nodes = content["data"]["warehouses"]["edges"]
assert warehouses_order[0] == warehouses_nodes[0]["node"]["name"]
@@ -132,6 +142,7 @@ def test_warehouses_pagination_with_filtering_by_id(
permission_manage_products,
warehouses_for_pagination,
):
+ # given
page_size = 2
warehouses_order = ["WarehouseWarehouse2", "WarehouseWarehouse1"]
warehouses_ids = [
@@ -141,9 +152,13 @@ def test_warehouses_pagination_with_filtering_by_id(
filter_by = {"ids": warehouses_ids}
variables = {"first": page_size, "after": None, "filter": filter_by}
+
+ # when
response = staff_api_client.post_graphql(
QUERY_WAREHOUSES_PAGINATION, variables, permissions=[permission_manage_products]
)
+
+ # then
content = get_graphql_content(response)
warehouses_nodes = content["data"]["warehouses"]["edges"]
assert warehouses_order[0] == warehouses_nodes[0]["node"]["name"]
diff --git a/saleor/graphql/warehouse/tests/test_stock.py b/saleor/graphql/warehouse/tests/test_stock.py
deleted file mode 100644
index 831162de75..0000000000
--- a/saleor/graphql/warehouse/tests/test_stock.py
+++ /dev/null
@@ -1,358 +0,0 @@
-from datetime import timedelta
-
-import graphene
-from django.utils import timezone
-
-from ....permission.enums import ProductPermissions
-from ....warehouse.models import Reservation, Stock, Warehouse
-from ....warehouse.tests.utils import get_quantity_allocated_for_stock
-from ...tests.utils import (
- assert_no_permission,
- get_graphql_content,
- get_graphql_content_from_response,
-)
-
-QUERY_STOCK = """
-query stock($id: ID!) {
- stock(id: $id) {
- warehouse {
- name
- }
- productVariant {
- product {
- name
- }
- }
- quantity
- quantityAllocated
- quantityReserved
- }
-}
-"""
-
-
-QUERY_STOCKS = """
- query {
- stocks(first:100) {
- totalCount
- edges {
- node {
- id
- warehouse {
- name
- id
- }
- productVariant {
- name
- id
- }
- quantity
- quantityAllocated
- quantityReserved
- }
- }
- }
- }
-"""
-
-QUERY_STOCKS_WITH_FILTERS = """
- query stocks($filter: StockFilterInput!) {
- stocks(first: 100, filter: $filter) {
- totalCount
- edges {
- node {
- id
- }
- }
- }
- }
-"""
-
-
-def test_query_stock_requires_permission(staff_api_client, stock):
- assert not staff_api_client.user.has_perm(ProductPermissions.MANAGE_PRODUCTS)
- stock_id = graphene.Node.to_global_id("Stock", stock.pk)
- response = staff_api_client.post_graphql(QUERY_STOCK, variables={"id": stock_id})
- assert_no_permission(response)
-
-
-def test_query_stock(staff_api_client, stock, permission_manage_products):
- staff_api_client.user.user_permissions.add(permission_manage_products)
- stock_id = graphene.Node.to_global_id("Stock", stock.pk)
- response = staff_api_client.post_graphql(QUERY_STOCK, variables={"id": stock_id})
- content = get_graphql_content(response)
- content_stock = content["data"]["stock"]
- assert (
- content_stock["productVariant"]["product"]["name"]
- == stock.product_variant.product.name
- )
- assert content_stock["warehouse"]["name"] == stock.warehouse.name
- assert content_stock["quantity"] == stock.quantity
- assert content_stock["quantityAllocated"] == get_quantity_allocated_for_stock(stock)
- assert content_stock["quantityReserved"] == 0
-
-
-def test_query_stock_with_reservations(
- site_settings_with_reservations,
- staff_api_client,
- stock,
- checkout_line_with_reservation_in_many_stocks,
- permission_manage_products,
-):
- staff_api_client.user.user_permissions.add(permission_manage_products)
- stock_id = graphene.Node.to_global_id("Stock", stock.pk)
- response = staff_api_client.post_graphql(QUERY_STOCK, variables={"id": stock_id})
- content = get_graphql_content(response)
- content_stock = content["data"]["stock"]
- assert (
- content_stock["productVariant"]["product"]["name"]
- == stock.product_variant.product.name
- )
- assert content_stock["warehouse"]["name"] == stock.warehouse.name
- assert content_stock["quantity"] == stock.quantity
- assert content_stock["quantityAllocated"] == get_quantity_allocated_for_stock(stock)
- assert content_stock["quantityReserved"] == 2
-
-
-def test_query_stock_with_expired_reservations(
- site_settings_with_reservations,
- staff_api_client,
- stock,
- checkout_line_with_reservation_in_many_stocks,
- permission_manage_products,
-):
- Reservation.objects.update(reserved_until=timezone.now() - timedelta(minutes=2))
- staff_api_client.user.user_permissions.add(permission_manage_products)
- stock_id = graphene.Node.to_global_id("Stock", stock.pk)
- response = staff_api_client.post_graphql(QUERY_STOCK, variables={"id": stock_id})
- content = get_graphql_content(response)
- content_stock = content["data"]["stock"]
- assert (
- content_stock["productVariant"]["product"]["name"]
- == stock.product_variant.product.name
- )
- assert content_stock["warehouse"]["name"] == stock.warehouse.name
- assert content_stock["quantity"] == stock.quantity
- assert content_stock["quantityAllocated"] == get_quantity_allocated_for_stock(stock)
- assert content_stock["quantityReserved"] == 0
-
-
-def test_staff_query_stock_by_invalid_id(
- staff_api_client, stock, permission_manage_products
-):
- id = "bh/"
- variables = {"id": id}
- response = staff_api_client.post_graphql(
- QUERY_STOCK, variables, permissions=[permission_manage_products]
- )
- content = get_graphql_content_from_response(response)
- assert len(content["errors"]) == 1
- assert content["errors"][0]["message"] == f"Couldn't resolve id: {id}."
- assert content["data"]["stock"] is None
-
-
-def test_staff_query_stock_with_invalid_object_type(
- staff_api_client, stock, permission_manage_products
-):
- variables = {"id": graphene.Node.to_global_id("Order", stock.pk)}
- response = staff_api_client.post_graphql(
- QUERY_STOCK, variables, permissions=[permission_manage_products]
- )
- content = get_graphql_content(response)
- assert content["data"]["stock"] is None
-
-
-def test_query_stocks_requires_permissions(staff_api_client):
- assert not staff_api_client.user.has_perm(ProductPermissions.MANAGE_PRODUCTS)
- response = staff_api_client.post_graphql(QUERY_STOCKS)
- assert_no_permission(response)
-
-
-def test_query_stocks(staff_api_client, stock, permission_manage_products):
- staff_api_client.user.user_permissions.add(permission_manage_products)
- response = staff_api_client.post_graphql(QUERY_STOCKS)
- content = get_graphql_content(response)
- total_count = content["data"]["stocks"]["totalCount"]
- assert total_count == Stock.objects.count()
-
-
-def test_query_stocks_with_filters_quantity(
- staff_api_client, stock, permission_manage_products
-):
- staff_api_client.user.user_permissions.add(permission_manage_products)
- quantities = Stock.objects.all().values_list("quantity", flat=True)
- sum_quantities = sum(quantities)
- variables = {"filter": {"quantity": sum_quantities}}
- response = staff_api_client.post_graphql(
- QUERY_STOCKS_WITH_FILTERS, variables=variables
- )
- content = get_graphql_content(response)
- total_count = content["data"]["stocks"]["totalCount"]
- assert total_count == 0
-
- variables = {"filter": {"quantity": max(quantities)}}
- response = staff_api_client.post_graphql(
- QUERY_STOCKS_WITH_FILTERS, variables=variables
- )
- content = get_graphql_content(response)
- total_count = content["data"]["stocks"]["totalCount"]
- assert total_count == Stock.objects.filter(quantity=max(quantities)).count()
-
-
-def test_query_stocks_with_filters_warehouse(
- staff_api_client, stock, permission_manage_products
-):
- staff_api_client.user.user_permissions.add(permission_manage_products)
- warehouse = stock.warehouse
- response_name = staff_api_client.post_graphql(
- QUERY_STOCKS_WITH_FILTERS, variables={"filter": {"search": warehouse.name}}
- )
- content = get_graphql_content(response_name)
- total_count = content["data"]["stocks"]["totalCount"]
- assert total_count == Stock.objects.filter(warehouse=warehouse).count()
-
-
-def test_query_stocks_with_filters_product_variant(
- staff_api_client, stock, permission_manage_products
-):
- staff_api_client.user.user_permissions.add(permission_manage_products)
- product_variant = stock.product_variant
- response_name = staff_api_client.post_graphql(
- QUERY_STOCKS_WITH_FILTERS,
- variables={"filter": {"search": product_variant.name}},
- )
- content = get_graphql_content(response_name)
- total_count = content["data"]["stocks"]["totalCount"]
- assert (
- total_count
- == Stock.objects.filter(product_variant__name=product_variant.name).count()
- )
-
-
-def test_query_stocks_with_filters_product_variant__product(
- staff_api_client, stock, permission_manage_products
-):
- staff_api_client.user.user_permissions.add(permission_manage_products)
- product = stock.product_variant.product
- response_name = staff_api_client.post_graphql(
- QUERY_STOCKS_WITH_FILTERS, variables={"filter": {"search": product.name}}
- )
- content = get_graphql_content(response_name)
- total_count = content["data"]["stocks"]["totalCount"]
- assert (
- total_count
- == Stock.objects.filter(product_variant__product__name=product.name).count()
- )
-
-
-def test_stock_quantities_in_different_warehouses(
- api_client, channel_USD, variant_with_many_stocks_different_shipping_zones
-):
- query = """
- query ProductVariant(
- $id: ID!, $channel: String!, $country1: CountryCode, $country2: CountryCode
- ) {
- productVariant(id: $id, channel: $channel) {
- quantityPL: quantityAvailable(address: { country: $country1 })
- quantityUS: quantityAvailable(address: { country: $country2 })
- quantityNoAddress: quantityAvailable
- }
- }
- """
-
- variant = variant_with_many_stocks_different_shipping_zones
- stock_map = {}
- for stock in variant.stocks.all():
- country = stock.warehouse.shipping_zones.get().countries[0]
- stock_map[country.code] = stock.quantity
-
- variables = {
- "id": graphene.Node.to_global_id("ProductVariant", variant.pk),
- "channel": channel_USD.slug,
- "country1": "PL",
- "country2": "US",
- }
- response = api_client.post_graphql(
- query,
- variables,
- )
- content = get_graphql_content(response)
-
- assert content["data"]["productVariant"]["quantityPL"] == stock_map["PL"]
- assert content["data"]["productVariant"]["quantityUS"] == stock_map["US"]
-
- # when country is not provided, should return max value of all available stock
- # quantities
- assert content["data"]["productVariant"]["quantityNoAddress"] == max(
- stock_map.values()
- )
-
-
-def test_stock_quantity_is_max_from_all_warehouses_without_provided_country(
- api_client, channel_USD, variant_with_many_stocks_different_shipping_zones
-):
- query = """
- query ProductVariant($id: ID!, $channel: String!) {
- productVariant(id: $id, channel: $channel) {
- quantityAvailable
- }
- }
- """
-
- variant = variant_with_many_stocks_different_shipping_zones
- max_warehouse_quantity = max([stock.quantity for stock in variant.stocks.all()])
-
- variables = {
- "id": graphene.Node.to_global_id("ProductVariant", variant.pk),
- "channel": channel_USD.slug,
- }
- response = api_client.post_graphql(query, variables)
- content = get_graphql_content(response)
-
- assert (
- content["data"]["productVariant"]["quantityAvailable"] == max_warehouse_quantity
- )
-
-
-def test_stock_quantity_is_sum_of_quantities_from_warehouses_that_support_country(
- api_client,
- address,
- channel_USD,
- shipping_zone,
- variant_with_many_stocks_different_shipping_zones,
-):
- query = """
- query ProductVariant($id: ID!, $channel: String!, $country: CountryCode) {
- productVariant(id: $id, channel: $channel) {
- quantityAvailable(address: { country: $country })
- }
- }
- """
-
- variant = variant_with_many_stocks_different_shipping_zones
-
- # 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_channel_and_country(channel_USD.slug, "PL")
- warehouse = Warehouse.objects.create(
- address=address.get_copy(),
- name="WarehousePL",
- slug="warehousePL",
- )
- 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_channel_and_country(channel_USD.slug, "PL")
- sum_quantities = sum([stock.quantity for stock in stocks])
-
- variables = {
- "id": graphene.Node.to_global_id("ProductVariant", variant.pk),
- "channel": channel_USD.slug,
- "country": "PL",
- }
- response = api_client.post_graphql(query, variables)
- content = get_graphql_content(response)
-
- assert content["data"]["productVariant"]["quantityAvailable"] == sum_quantities
diff --git a/saleor/graphql/warehouse/tests/test_warehouse.py b/saleor/graphql/warehouse/tests/test_warehouse.py
deleted file mode 100644
index 85b9649131..0000000000
--- a/saleor/graphql/warehouse/tests/test_warehouse.py
+++ /dev/null
@@ -1,1629 +0,0 @@
-import json
-from unittest.mock import patch
-
-import graphene
-import pytest
-from django.utils.functional import SimpleLazyObject
-
-from ....account.models import Address
-from ....core.utils.json_serializer import CustomJsonEncoder
-from ....warehouse import WarehouseClickAndCollectOption
-from ....warehouse.error_codes import WarehouseErrorCode
-from ....warehouse.models import Stock, Warehouse
-from ....webhook.event_types import WebhookEventAsyncType
-from ...tests.utils import (
- assert_no_permission,
- get_graphql_content,
- get_graphql_content_from_response,
-)
-from ..enums import WarehouseClickAndCollectOptionEnum
-
-QUERY_WAREHOUSES = """
-query {
- warehouses(first:100) {
- totalCount
- edges {
- node {
- id
- name
- companyName
- email
- shippingZones(first:100) {
- edges {
- node {
- name
- countries {
- country
- }
- }
- }
- }
- address {
- city
- postalCode
- country {
- country
- }
- phone
- }
- }
- }
- }
-}
-"""
-
-QUERY_WAREHOUSES_WITH_FILTERS = """
-query Warehouses($filters: WarehouseFilterInput) {
- warehouses(first:100, filter: $filters) {
- totalCount
- edges {
- node {
- id
- name
- companyName
- email
- }
- }
- }
-}
-"""
-
-QUERY_WERHOUSES_WITH_FILTERS_NO_IDS = """
-query Warehouses($filters: WarehouseFilterInput) {
- warehouses(first:100, filter: $filters) {
- totalCount
- edges {
- node {
- name
- companyName
- email
- }
- }
- }
-}
-"""
-
-QUERY_WAREHOUSE = """
-query warehouse($id: ID!){
- warehouse(id: $id) {
- id
- name
- companyName
- email
- shippingZones(first: 100) {
- edges {
- node {
- name
- countries {
- country
- }
- }
- }
- }
- address {
- streetAddress1
- streetAddress2
- postalCode
- city
- phone
- }
- }
-}
-"""
-
-
-QUERY_WAREHOUSE_BY_EXTERNAL_REFERENCE = """
-query warehouse($id: ID, $externalReference: String){
- warehouse(id: $id, externalReference: $externalReference) {
- id
- externalReference
- }
-}
-"""
-
-
-MUTATION_CREATE_WAREHOUSE = """
-mutation createWarehouse($input: WarehouseCreateInput!) {
- createWarehouse(input: $input){
- warehouse {
- id
- name
- slug
- companyName
- externalReference
- address {
- id
- }
- shippingZones(first: 5) {
- edges {
- node {
- id
- }
- }
- }
- }
- errors {
- message
- field
- code
- }
- }
-}
-"""
-
-
-MUTATION_UPDATE_WAREHOUSE = """
-mutation updateWarehouse($input: WarehouseUpdateInput!, $id: ID!) {
- updateWarehouse(id: $id, input: $input) {
- errors {
- message
- field
- code
- }
- warehouse {
- name
- slug
- companyName
- isPrivate
- clickAndCollectOption
- externalReference
- address {
- id
- streetAddress1
- streetAddress2
- }
- }
- }
-}
-"""
-
-
-MUTATION_DELETE_WAREHOUSE = """
-mutation deleteWarehouse($id: ID!) {
- deleteWarehouse(id: $id) {
- errors {
- message
- field
- code
- }
- }
-}
-"""
-
-
-MUTATION_ASSIGN_SHIPPING_ZONE_WAREHOUSE = """
-mutation assignWarehouseShippingZone($id: ID!, $shippingZoneIds: [ID!]!) {
- assignWarehouseShippingZone(id: $id, shippingZoneIds: $shippingZoneIds) {
- errors {
- field
- message
- code
- shippingZones
- }
- }
-}
-
-"""
-
-
-MUTATION_UNASSIGN_SHIPPING_ZONE_WAREHOUSE = """
-mutation unassignWarehouseShippingZone($id: ID!, $shippingZoneIds: [ID!]!) {
- unassignWarehouseShippingZone(id: $id, shippingZoneIds: $shippingZoneIds) {
- errors {
- field
- message
- code
- }
- }
-}
-
-"""
-
-
-def test_warehouse_query(staff_api_client, warehouse, permission_manage_products):
- warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)
-
- response = staff_api_client.post_graphql(
- QUERY_WAREHOUSE,
- variables={"id": warehouse_id},
- permissions=[permission_manage_products],
- )
- content = get_graphql_content(response)
-
- queried_warehouse = content["data"]["warehouse"]
- assert queried_warehouse["name"] == warehouse.name
- assert queried_warehouse["email"] == warehouse.email
-
- shipping_zones = queried_warehouse["shippingZones"]["edges"]
- assert len(shipping_zones) == warehouse.shipping_zones.count()
- queried_shipping_zone = shipping_zones[0]["node"]
- shipipng_zone = warehouse.shipping_zones.first()
- assert queried_shipping_zone["name"] == shipipng_zone.name
- assert len(queried_shipping_zone["countries"]) == len(shipipng_zone.countries)
-
- address = warehouse.address
- queried_address = queried_warehouse["address"]
- assert queried_address["streetAddress1"] == address.street_address_1
- assert queried_address["postalCode"] == address.postal_code
-
-
-def test_warehouse_query_as_staff_with_manage_orders(
- staff_api_client, warehouse, permission_manage_orders
-):
- warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)
-
- response = staff_api_client.post_graphql(
- QUERY_WAREHOUSE,
- variables={"id": warehouse_id},
- permissions=[permission_manage_orders],
- )
- content = get_graphql_content(response)
-
- queried_warehouse = content["data"]["warehouse"]
- assert queried_warehouse["name"] == warehouse.name
- assert queried_warehouse["email"] == warehouse.email
-
- shipping_zones = queried_warehouse["shippingZones"]["edges"]
- assert len(shipping_zones) == warehouse.shipping_zones.count()
- queried_shipping_zone = shipping_zones[0]["node"]
- shipipng_zone = warehouse.shipping_zones.first()
- assert queried_shipping_zone["name"] == shipipng_zone.name
- assert len(queried_shipping_zone["countries"]) == len(shipipng_zone.countries)
-
- address = warehouse.address
- queried_address = queried_warehouse["address"]
- assert queried_address["streetAddress1"] == address.street_address_1
- assert queried_address["postalCode"] == address.postal_code
-
-
-def test_warehouse_query_as_staff_with_manage_shipping(
- staff_api_client, warehouse, permission_manage_shipping
-):
- warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)
-
- response = staff_api_client.post_graphql(
- QUERY_WAREHOUSE,
- variables={"id": warehouse_id},
- permissions=[permission_manage_shipping],
- )
- content = get_graphql_content(response)
-
- queried_warehouse = content["data"]["warehouse"]
- assert queried_warehouse["name"] == warehouse.name
- assert queried_warehouse["email"] == warehouse.email
-
- shipping_zones = queried_warehouse["shippingZones"]["edges"]
- assert len(shipping_zones) == warehouse.shipping_zones.count()
- queried_shipping_zone = shipping_zones[0]["node"]
- shipipng_zone = warehouse.shipping_zones.first()
- assert queried_shipping_zone["name"] == shipipng_zone.name
- assert len(queried_shipping_zone["countries"]) == len(shipipng_zone.countries)
-
- address = warehouse.address
- queried_address = queried_warehouse["address"]
- assert queried_address["streetAddress1"] == address.street_address_1
- assert queried_address["postalCode"] == address.postal_code
-
-
-def test_warehouse_query_as_staff_with_manage_apps(
- staff_api_client, warehouse, permission_manage_apps
-):
- warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)
-
- response = staff_api_client.post_graphql(
- QUERY_WAREHOUSE,
- variables={"id": warehouse_id},
- permissions=[permission_manage_apps],
- )
-
- assert_no_permission(response)
-
-
-def test_warehouse_query_as_customer(user_api_client, warehouse):
- warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)
-
- response = user_api_client.post_graphql(
- QUERY_WAREHOUSE,
- variables={"id": warehouse_id},
- )
-
- assert_no_permission(response)
-
-
-def test_staff_query_warehouse_by_invalid_id(
- staff_api_client, warehouse, permission_manage_shipping
-):
- id = "bh/"
- variables = {"id": id}
- response = staff_api_client.post_graphql(
- QUERY_WAREHOUSE, variables, permissions=[permission_manage_shipping]
- )
- content = get_graphql_content_from_response(response)
- assert len(content["errors"]) == 1
- assert content["errors"][0]["message"] == f"Couldn't resolve id: {id}."
- assert content["data"]["warehouse"] is None
-
-
-def test_staff_query_warehouse_with_invalid_object_type(
- staff_api_client, permission_manage_shipping, warehouse
-):
- variables = {"id": graphene.Node.to_global_id("Order", warehouse.pk)}
- response = staff_api_client.post_graphql(
- QUERY_WAREHOUSE, variables, permissions=[permission_manage_shipping]
- )
- content = get_graphql_content(response)
- assert content["data"]["warehouse"] is None
-
-
-def test_query_warehouses_as_staff_with_manage_orders(
- staff_api_client, warehouse, permission_manage_orders
-):
- response = staff_api_client.post_graphql(
- QUERY_WAREHOUSES, permissions=[permission_manage_orders]
- )
- content = get_graphql_content(response)["data"]
- assert content["warehouses"]["totalCount"] == Warehouse.objects.count()
- warehouses = content["warehouses"]["edges"]
- warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)
- warehouse_first = warehouses[0]["node"]
- assert warehouse_first["id"] == warehouse_id
- assert warehouse_first["name"] == warehouse.name
- assert (
- len(warehouse_first["shippingZones"]["edges"])
- == warehouse.shipping_zones.count()
- )
-
-
-def test_query_warehouses_as_staff_with_manage_shipping(
- staff_api_client, warehouse, permission_manage_shipping
-):
- response = staff_api_client.post_graphql(
- QUERY_WAREHOUSES, permissions=[permission_manage_shipping]
- )
- content = get_graphql_content(response)["data"]
- assert content["warehouses"]["totalCount"] == Warehouse.objects.count()
- warehouses = content["warehouses"]["edges"]
- warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)
- warehouse_first = warehouses[0]["node"]
- assert warehouse_first["id"] == warehouse_id
- assert warehouse_first["name"] == warehouse.name
- assert (
- len(warehouse_first["shippingZones"]["edges"])
- == warehouse.shipping_zones.count()
- )
-
-
-def test_query_warehouses_as_staff_with_manage_apps(
- staff_api_client, warehouse, permission_manage_apps
-):
- response = staff_api_client.post_graphql(
- QUERY_WAREHOUSES, permissions=[permission_manage_apps]
- )
- assert_no_permission(response)
-
-
-def test_query_warehouses_as_customer(
- user_api_client, warehouse, permission_manage_apps
-):
- response = user_api_client.post_graphql(QUERY_WAREHOUSES)
- assert_no_permission(response)
-
-
-def test_query_warehouses(staff_api_client, warehouse, permission_manage_products):
- response = staff_api_client.post_graphql(
- QUERY_WAREHOUSES, permissions=[permission_manage_products]
- )
- content = get_graphql_content(response)["data"]
- assert content["warehouses"]["totalCount"] == Warehouse.objects.count()
- warehouses = content["warehouses"]["edges"]
- warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)
- warehouse_first = warehouses[0]["node"]
- assert warehouse_first["id"] == warehouse_id
- assert warehouse_first["name"] == warehouse.name
- assert (
- len(warehouse_first["shippingZones"]["edges"])
- == warehouse.shipping_zones.count()
- )
-
-
-def test_query_warehouses_with_filters_name(
- staff_api_client, permission_manage_products, warehouse
-):
- variables_exists = {"filters": {"search": "warehouse"}}
- response = staff_api_client.post_graphql(
- QUERY_WAREHOUSES_WITH_FILTERS,
- variables=variables_exists,
- permissions=[permission_manage_products],
- )
- content = get_graphql_content(response)
- warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.id)
- content_warehouse = content["data"]["warehouses"]["edges"][0]["node"]
- assert content_warehouse["id"] == warehouse_id
- variables_does_not_exists = {"filters": {"search": "Absolutelywrong name"}}
- response1 = staff_api_client.post_graphql(
- QUERY_WAREHOUSES_WITH_FILTERS, variables=variables_does_not_exists
- )
- content1 = get_graphql_content(response1)
- total_count = content1["data"]["warehouses"]["totalCount"]
- assert total_count == 0
-
-
-def test_query_warehouse_with_filters_email(
- staff_api_client, permission_manage_products, warehouse
-):
- variables_exists = {"filters": {"search": "test"}}
- response_exists = staff_api_client.post_graphql(
- QUERY_WAREHOUSES_WITH_FILTERS,
- variables=variables_exists,
- permissions=[permission_manage_products],
- )
- content_exists = get_graphql_content(response_exists)
- warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.id)
- content_warehouse = content_exists["data"]["warehouses"]["edges"][0]["node"]
- assert content_warehouse["id"] == warehouse_id
-
- variable_does_not_exists = {"filters": {"search": "[email protected]"}}
- response_not_exists = staff_api_client.post_graphql(
- QUERY_WAREHOUSES_WITH_FILTERS, variables=variable_does_not_exists
- )
- content_not_exists = get_graphql_content(response_not_exists)
- total_count = content_not_exists["data"]["warehouses"]["totalCount"]
- assert total_count == 0
-
-
-def test_query_warehouse_with_filters_by_ids(
- staff_api_client, permission_manage_products, warehouse, warehouse_no_shipping_zone
-):
- warehouse_ids = [
- graphene.Node.to_global_id("Warehouse", warehouse.id),
- graphene.Node.to_global_id("Warehouse", warehouse_no_shipping_zone.id),
- ]
- variables_exists = {"filters": {"ids": warehouse_ids}}
- response_exists = staff_api_client.post_graphql(
- QUERY_WAREHOUSES_WITH_FILTERS,
- variables=variables_exists,
- permissions=[permission_manage_products],
- )
- content_exists = get_graphql_content(response_exists)
-
- content_warehouses = content_exists["data"]["warehouses"]["edges"]
- for content_warehouse in content_warehouses:
- assert content_warehouse["node"]["id"] in warehouse_ids
- assert content_exists["data"]["warehouses"]["totalCount"] == 2
-
-
-def test_query_warehouse_with_filters_by_id(
- staff_api_client, permission_manage_products, warehouse, warehouse_no_shipping_zone
-):
- warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.id)
- variables_exists = {"filters": {"ids": [warehouse_id]}}
- response_exists = staff_api_client.post_graphql(
- QUERY_WAREHOUSES_WITH_FILTERS,
- variables=variables_exists,
- permissions=[permission_manage_products],
- )
- content_exists = get_graphql_content(response_exists)
-
- content_warehouses = content_exists["data"]["warehouses"]["edges"]
- assert content_warehouses[0]["node"]["id"] == warehouse_id
- assert content_exists["data"]["warehouses"]["totalCount"] == 1
-
-
- "graphql_filter, db_filter", [("true", True), ("false", False)]
-)
-def test_query_warehouse_with_filters_by_is_private(
- staff_api_client,
- permission_manage_products,
- warehouses_for_cc,
- graphql_filter,
- db_filter,
-):
- db_count = Warehouse.objects.filter(is_private=db_filter).count()
- variables_exists = {"filters": {"isPrivate": graphql_filter}}
- response_exists = staff_api_client.post_graphql(
- QUERY_WAREHOUSES_WITH_FILTERS,
- variables=variables_exists,
- permissions=[permission_manage_products],
- )
- content_exists = get_graphql_content(response_exists)
-
- assert content_exists["data"]["warehouses"]["totalCount"] == db_count
-
-
- "db_option, graphql_option",
- [
- (WarehouseClickAndCollectOption.DISABLED, "DISABLED"),
- (WarehouseClickAndCollectOption.ALL_WAREHOUSES, "ALL"),
- (WarehouseClickAndCollectOption.LOCAL_STOCK, "LOCAL"),
- ],
-)
-def test_query_warehouse_with_filters_by_click_and_collect_option(
- staff_api_client,
- permission_manage_products,
- warehouses_for_cc,
- db_option,
- graphql_option,
-):
- db_count = Warehouse.objects.filter(click_and_collect_option=db_option).count()
- variables_exists = {"filters": {"clickAndCollectOption": graphql_option}}
- response_exists = staff_api_client.post_graphql(
- QUERY_WAREHOUSES_WITH_FILTERS,
- variables=variables_exists,
- permissions=[permission_manage_products],
- )
- content_exists = get_graphql_content(response_exists)
- assert content_exists["data"]["warehouses"]["totalCount"] == db_count
-
-
-def test_query_warehouses_with_filters_and_no_id(
- staff_api_client, permission_manage_products, warehouse
-):
- variables_exists = {"filters": {"search": "test"}}
- response_exists = staff_api_client.post_graphql(
- QUERY_WAREHOUSES_WITH_FILTERS,
- variables=variables_exists,
- permissions=[permission_manage_products],
- )
- content_exists = get_graphql_content(response_exists)
- warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.id)
- content_warehouse = content_exists["data"]["warehouses"]["edges"][0]["node"]
- assert content_warehouse["id"] == warehouse_id
-
- variable_does_not_exists = {"filters": {"search": "[email protected]"}}
- response_not_exists = staff_api_client.post_graphql(
- QUERY_WAREHOUSES_WITH_FILTERS, variables=variable_does_not_exists
- )
- content_not_exists = get_graphql_content(response_not_exists)
- total_count = content_not_exists["data"]["warehouses"]["totalCount"]
- 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
-
-
- "filter_by, pages_count",
- [
- ({"slugs": ["warehouse1", "warehouse2"]}, 2),
- ({"slugs": []}, 2),
- ],
-)
-def test_query_warehouses_with_filtering(
- filter_by, pages_count, staff_api_client, permission_manage_products, warehouses
-):
- # given
- variables = {"filter": filter_by}
-
- # when
- response = staff_api_client.post_graphql(
- QUERY_WAREHOUSES_WITH_FILTERS,
- variables,
- permissions=[permission_manage_products],
- )
-
- # then
- content = get_graphql_content(response)
- pages_nodes = content["data"]["warehouses"]["edges"]
- assert len(pages_nodes) == pages_count
-
-
-def test_mutation_create_warehouse(
- staff_api_client, permission_manage_products, shipping_zone
-):
- variables = {
- "input": {
- "name": "Test warehouse",
- "slug": "test-warhouse",
- "email": "[email protected]",
- "externalReference": "test-ext-ref",
- "address": {
- "streetAddress1": "Teczowa 8",
- "city": "Wroclaw",
- "country": "PL",
- "postalCode": "53-601",
- "companyName": "Amazing Company Inc",
- },
- }
- }
-
- response = staff_api_client.post_graphql(
- MUTATION_CREATE_WAREHOUSE,
- variables=variables,
- permissions=[permission_manage_products],
- )
- content = get_graphql_content(response)
- assert Warehouse.objects.count() == 1
- warehouse = Warehouse.objects.first()
- created_warehouse = content["data"]["createWarehouse"]["warehouse"]
- assert created_warehouse["id"] == graphene.Node.to_global_id(
- "Warehouse", warehouse.id
- )
- assert created_warehouse["name"] == warehouse.name
- assert created_warehouse["slug"] == warehouse.slug
- assert created_warehouse["companyName"] == warehouse.address.company_name
- assert created_warehouse["externalReference"] == warehouse.external_reference
-
-
-def test_mutation_create_warehouse_shipping_zone_provided(
- staff_api_client, permission_manage_products, shipping_zone
-):
- variables = {
- "input": {
- "name": "Test warehouse",
- "slug": "test-warhouse",
- "email": "[email protected]",
- "address": {
- "streetAddress1": "Teczowa 8",
- "city": "Wroclaw",
- "country": "PL",
- "postalCode": "53-601",
- "companyName": "Amazing Company Inc",
- },
- # DEPRECATED
- "shippingZones": [
- graphene.Node.to_global_id("ShippingZone", shipping_zone.id)
- ],
- }
- }
-
- response = staff_api_client.post_graphql(
- MUTATION_CREATE_WAREHOUSE,
- variables=variables,
- permissions=[permission_manage_products],
- )
- content = get_graphql_content(response)
- data = content["data"]["createWarehouse"]
- errors = data["errors"]
- assert len(errors) == 1
- assert errors[0]["code"] == WarehouseErrorCode.INVALID.name
- assert errors[0]["field"] == "shippingZones"
-
-
-@patch("saleor.plugins.webhook.plugin.get_webhooks_for_event")
-@patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")
-def test_mutation_create_warehouse_trigger_webhook(
- mocked_webhook_trigger,
- mocked_get_webhooks_for_event,
- any_webhook,
- staff_api_client,
- permission_manage_products,
- shipping_zone,
- settings,
-):
- # given
- mocked_get_webhooks_for_event.return_value = [any_webhook]
- settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
-
- variables = {
- "input": {
- "name": "Test warehouse",
- "slug": "test-warhouse",
- "email": "[email protected]",
- "address": {
- "streetAddress1": "Teczowa 8",
- "city": "Wroclaw",
- "country": "PL",
- "postalCode": "53-601",
- "companyName": "Amazing Company Inc",
- },
- }
- }
-
- # when
- response = staff_api_client.post_graphql(
- MUTATION_CREATE_WAREHOUSE,
- variables=variables,
- permissions=[permission_manage_products],
- )
- content = get_graphql_content(response)
- warehouse = Warehouse.objects.last()
-
- # then
- assert content["data"]["createWarehouse"]["warehouse"]
- mocked_webhook_trigger.assert_called_once_with(
- json.dumps(
- {
- "id": graphene.Node.to_global_id("Warehouse", warehouse.id),
- "name": warehouse.name,
- },
- cls=CustomJsonEncoder,
- ),
- WebhookEventAsyncType.WAREHOUSE_CREATED,
- [any_webhook],
- warehouse,
- SimpleLazyObject(lambda: staff_api_client.user),
- )
-
-
-def test_mutation_create_warehouse_does_not_create_when_name_is_empty_string(
- staff_api_client, permission_manage_products, shipping_zone
-):
- variables = {
- "input": {
- "name": " ",
- "slug": "test-warhouse",
- "email": "[email protected]",
- "address": {
- "streetAddress1": "Teczowa 8",
- "city": "Wroclaw",
- "country": "PL",
- "postalCode": "53-601",
- "companyName": "Amazing Company Inc",
- },
- "shippingZones": [
- graphene.Node.to_global_id("ShippingZone", shipping_zone.id)
- ],
- }
- }
-
- response = staff_api_client.post_graphql(
- MUTATION_CREATE_WAREHOUSE,
- variables=variables,
- permissions=[permission_manage_products],
- )
- content = get_graphql_content(response)
- data = content["data"]["createWarehouse"]
- errors = data["errors"]
- assert Warehouse.objects.count() == 0
- assert len(errors) == 1
- assert errors[0]["field"] == "name"
- assert errors[0]["code"] == WarehouseErrorCode.REQUIRED.name
-
-
-def test_create_warehouse_creates_address(
- staff_api_client, permission_manage_products, shipping_zone
-):
- variables = {
- "input": {
- "name": "Test warehouse",
- "email": "[email protected]",
- "address": {
- "streetAddress1": "Teczowa 8",
- "city": "Wroclaw",
- "country": "PL",
- "companyName": "Amazing Company Inc",
- "postalCode": "53-601",
- },
- }
- }
- assert not Address.objects.exists()
- response = staff_api_client.post_graphql(
- MUTATION_CREATE_WAREHOUSE,
- variables=variables,
- permissions=[permission_manage_products],
- )
- content = get_graphql_content(response)
- errors = content["data"]["createWarehouse"]["errors"]
- assert len(errors) == 0
- assert Address.objects.count() == 1
- address = Address.objects.get(street_address_1="Teczowa 8", city="WROCLAW")
- address_id = graphene.Node.to_global_id("Address", address.id)
- warehouse_data = content["data"]["createWarehouse"]["warehouse"]
- assert warehouse_data["address"]["id"] == address_id
- assert address.street_address_1 == "Teczowa 8"
- assert address.company_name == "Amazing Company Inc"
- assert address.city == "WROCLAW"
-
-
- "input_slug, expected_slug",
- (
- ("test-slug", "test-slug"),
- (None, "test-warehouse"),
- ("", "test-warehouse"),
- ),
-)
-def test_create_warehouse_with_given_slug(
- staff_api_client, permission_manage_products, input_slug, expected_slug
-):
- query = MUTATION_CREATE_WAREHOUSE
- name = "Test warehouse"
- variables = {"name": name, "slug": input_slug}
- variables = {
- "input": {
- "name": name,
- "slug": input_slug,
- "address": {
- "streetAddress1": "Teczowa 8",
- "city": "Wroclaw",
- "country": "PL",
- "postalCode": "53-601",
- },
- }
- }
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_products]
- )
- content = get_graphql_content(response)
- data = content["data"]["createWarehouse"]
- assert not data["errors"]
- assert data["warehouse"]["slug"] == expected_slug
-
-
-def test_create_warehouse_with_non_unique_external_reference(
- staff_api_client, permission_manage_products, shipping_zone, warehouse
-):
- # given
- ext_ref = "test-ext-ref"
- warehouse.external_reference = ext_ref
- warehouse.save(update_fields=["external_reference"])
-
- variables = {
- "input": {
- "name": "Test warehouse",
- "externalReference": ext_ref,
- "address": {
- "streetAddress1": "Teczowa 8",
- "city": "Wroclaw",
- "country": "PL",
- "postalCode": "53-601",
- },
- }
- }
-
- # when
- response = staff_api_client.post_graphql(
- MUTATION_CREATE_WAREHOUSE,
- variables=variables,
- permissions=[permission_manage_products],
- )
- content = get_graphql_content(response)
-
- # then
- error = content["data"]["createWarehouse"]["errors"][0]
- assert error["field"] == "externalReference"
- assert error["code"] == WarehouseErrorCode.UNIQUE.name
- assert error["message"] == "Warehouse with this External reference already exists."
-
-
-def test_mutation_update_warehouse(
- staff_api_client, warehouse, permission_manage_products
-):
- warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.id)
- warehouse_old_name = warehouse.name
- warehouse_slug = warehouse.slug
- external_reference = "test-ext-ref"
- variables = {
- "id": warehouse_id,
- "input": {"name": "New name", "externalReference": external_reference},
- }
- staff_api_client.post_graphql(
- MUTATION_UPDATE_WAREHOUSE,
- variables=variables,
- permissions=[permission_manage_products],
- )
- warehouse.refresh_from_db()
- assert not (warehouse.name == warehouse_old_name)
- assert warehouse.name == "New name"
- assert warehouse.slug == warehouse_slug
- assert warehouse.external_reference == external_reference
-
-
-def test_mutation_update_warehouse_with_non_unique_external_reference(
- staff_api_client, warehouse, permission_manage_products, warehouse_JPY
-):
- # given
- warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.id)
- ext_ref = "test-ext-ref"
- warehouse_JPY.external_reference = ext_ref
- warehouse_JPY.save(update_fields=["external_reference"])
-
- variables = {
- "id": warehouse_id,
- "input": {"externalReference": ext_ref},
- }
-
- # when
- response = staff_api_client.post_graphql(
- MUTATION_UPDATE_WAREHOUSE,
- variables=variables,
- permissions=[permission_manage_products],
- )
- content = get_graphql_content(response)
-
- # then
- error = content["data"]["updateWarehouse"]["errors"][0]
- assert error["field"] == "externalReference"
- assert error["code"] == WarehouseErrorCode.UNIQUE.name
- assert error["message"] == "Warehouse with this External reference already exists."
-
-
-@patch("saleor.plugins.webhook.plugin.get_webhooks_for_event")
-@patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")
-def test_mutation_update_warehouse_trigger_webhook(
- mocked_webhook_trigger,
- mocked_get_webhooks_for_event,
- any_webhook,
- staff_api_client,
- warehouse,
- permission_manage_products,
- settings,
-):
- # given
- mocked_get_webhooks_for_event.return_value = [any_webhook]
- settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
-
- warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.id)
- variables = {
- "id": warehouse_id,
- "input": {"name": "New name"},
- }
-
- # when
- response = staff_api_client.post_graphql(
- MUTATION_UPDATE_WAREHOUSE,
- variables=variables,
- permissions=[permission_manage_products],
- )
- content = get_graphql_content(response)
- warehouse.refresh_from_db()
-
- # then
- assert content["data"]["updateWarehouse"]["warehouse"]
- mocked_webhook_trigger.assert_called_once_with(
- json.dumps(
- {
- "id": variables["id"],
- "name": warehouse.name,
- },
- cls=CustomJsonEncoder,
- ),
- WebhookEventAsyncType.WAREHOUSE_UPDATED,
- [any_webhook],
- warehouse,
- SimpleLazyObject(lambda: staff_api_client.user),
- )
-
-
-def test_mutation_update_warehouse_can_update_address(
- staff_api_client, warehouse, permission_manage_products
-):
- warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)
- address_id = graphene.Node.to_global_id("Address", warehouse.address.pk)
- address = warehouse.address
- variables = {
- "id": warehouse_id,
- "input": {
- "name": warehouse.name,
- "address": {
- "streetAddress1": "Teczowa 8",
- "streetAddress2": "Ground floor",
- "companyName": "",
- "city": address.city,
- "country": address.country.code,
- "postalCode": "53-601",
- },
- },
- }
- response = staff_api_client.post_graphql(
- MUTATION_UPDATE_WAREHOUSE,
- variables=variables,
- permissions=[permission_manage_products],
- )
- content = get_graphql_content(response)
- content_address = content["data"]["updateWarehouse"]["warehouse"]["address"]
- assert content_address["id"] == address_id
- address.refresh_from_db()
- assert address.street_address_1 == "Teczowa 8"
- assert address.street_address_2 == "Ground floor"
-
-
-def test_mutation_update_warehouse_to_country_with_different_validation_rules(
- staff_api_client, warehouse, permission_manage_products, address_usa
-):
- # given
- warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)
- warehouse.address = address_usa
- warehouse.save(update_fields=["address"])
- address_id = graphene.Node.to_global_id("Address", warehouse.address.pk)
- variables = {
- "id": warehouse_id,
- "input": {
- "name": warehouse.name,
- "address": {
- "streetAddress1": "Fake street",
- "city": "London",
- "country": "GB",
- "postalCode": "B52 1AA",
- },
- },
- }
-
- # when
- response = staff_api_client.post_graphql(
- MUTATION_UPDATE_WAREHOUSE,
- variables=variables,
- permissions=[permission_manage_products],
- )
- content = get_graphql_content(response)
- content_address = content["data"]["updateWarehouse"]["warehouse"]["address"]
-
- # then
- assert len(content["data"]["updateWarehouse"]["errors"]) == 0
- assert content_address["streetAddress1"] == "Fake street"
- assert content_address["id"] == address_id
-
-
- "input_slug, expected_slug, error_message",
- [
- ("test-slug", "test-slug", None),
- ("", "", "Slug value cannot be blank."),
- (None, "", "Slug value cannot be blank."),
- ],
-)
-def test_update_warehouse_slug(
- staff_api_client,
- warehouse,
- permission_manage_products,
- input_slug,
- expected_slug,
- error_message,
-):
- query = MUTATION_UPDATE_WAREHOUSE
- old_slug = warehouse.slug
-
- assert old_slug != input_slug
-
- node_id = graphene.Node.to_global_id("Warehouse", warehouse.id)
- variables = {"id": node_id, "input": {"slug": input_slug}}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_products]
- )
- content = get_graphql_content(response)
- data = content["data"]["updateWarehouse"]
- errors = data["errors"]
- if not error_message:
- assert not errors
- assert data["warehouse"]["slug"] == expected_slug
- else:
- assert errors
- assert errors[0]["field"] == "slug"
- assert errors[0]["code"] == WarehouseErrorCode.REQUIRED.name
-
-
-def test_update_warehouse_slug_exists(
- staff_api_client, warehouse, permission_manage_products
-):
- query = MUTATION_UPDATE_WAREHOUSE
- input_slug = "test-slug"
-
- second_warehouse = Warehouse.objects.get(pk=warehouse.pk)
- second_warehouse.pk = None
- second_warehouse.slug = input_slug
- second_warehouse.save()
-
- assert input_slug != warehouse.slug
-
- node_id = graphene.Node.to_global_id("Warehouse", warehouse.id)
- variables = {"id": node_id, "input": {"slug": input_slug}}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_products]
- )
- content = get_graphql_content(response)
- data = content["data"]["updateWarehouse"]
- errors = data["errors"]
- assert errors
- assert errors[0]["field"] == "slug"
- assert errors[0]["code"] == WarehouseErrorCode.UNIQUE.name
-
-
- "input_slug, expected_slug, input_name, expected_name, error_message, error_field",
- [
- ("test-slug", "test-slug", "New name", "New name", None, None),
- (
- "test-slug",
- "test-slug",
- " stripped ",
- "stripped",
- None,
- None,
- ),
- ("", "", "New name", "New name", "Slug value cannot be blank.", "slug"),
- (None, "", "New name", "New name", "Slug value cannot be blank.", "slug"),
- ("test-slug", "", None, None, "This field cannot be blank.", "name"),
- ("test-slug", "", "", None, "This field cannot be blank.", "name"),
- (None, None, None, None, "Slug value cannot be blank.", "slug"),
- ("test-slug", "test-slug", " ", None, "Name value cannot be blank", "name"),
- ],
-)
-def test_update_warehouse_slug_and_name(
- staff_api_client,
- warehouse,
- permission_manage_products,
- input_slug,
- expected_slug,
- input_name,
- expected_name,
- error_message,
- error_field,
-):
- query = MUTATION_UPDATE_WAREHOUSE
-
- old_name = warehouse.name
- old_slug = warehouse.slug
-
- assert input_slug != old_slug
- assert input_name != old_name
-
- node_id = graphene.Node.to_global_id("Warehouse", warehouse.id)
- variables = {"input": {"slug": input_slug, "name": input_name}, "id": node_id}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_products]
- )
- content = get_graphql_content(response)
- warehouse.refresh_from_db()
- data = content["data"]["updateWarehouse"]
- errors = data["errors"]
- if not error_message:
- assert data["warehouse"]["name"] == expected_name == warehouse.name
- assert (
- data["warehouse"]["slug"] == input_slug == warehouse.slug == expected_slug
- )
- else:
- assert errors
- assert errors[0]["field"] == error_field
- assert errors[0]["code"] == WarehouseErrorCode.REQUIRED.name
-
-
- "expected_private, expected_cc_option",
- [
- (private, option)
- for private in (True, False)
- for option in [
- WarehouseClickAndCollectOptionEnum.ALL.name,
- WarehouseClickAndCollectOptionEnum.DISABLED.name,
- ]
- ]
- + [(False, WarehouseClickAndCollectOptionEnum.LOCAL.name)],
-)
-def test_update_click_and_collect_option(
- staff_api_client,
- warehouse,
- permission_manage_products,
- expected_private,
- expected_cc_option,
-):
- query = MUTATION_UPDATE_WAREHOUSE
-
- assert warehouse.is_private
- assert warehouse.click_and_collect_option == WarehouseClickAndCollectOption.DISABLED
-
- node_id = graphene.Node.to_global_id("Warehouse", warehouse.id)
- variables = {
- "input": {
- "isPrivate": expected_private,
- "clickAndCollectOption": expected_cc_option,
- },
- "id": node_id,
- }
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_products]
- )
- content = get_graphql_content(response)
- warehouse.refresh_from_db()
- data = content["data"]["updateWarehouse"]
- errors = data["errors"]
-
- assert not errors
- assert data["warehouse"]["isPrivate"] == expected_private == warehouse.is_private
- assert (
- data["warehouse"]["clickAndCollectOption"]
- == expected_cc_option
- == warehouse.click_and_collect_option.upper()
- )
-
-
-def test_update_click_and_collect_option_invalid_input(
- staff_api_client, warehouse, permission_manage_products
-):
- query = MUTATION_UPDATE_WAREHOUSE
-
- warehouse_is_private = warehouse.is_private
- warehouse_click_and_collect = warehouse.click_and_collect_option
- assert warehouse_is_private
- assert warehouse_click_and_collect == WarehouseClickAndCollectOption.DISABLED
-
- node_id = graphene.Node.to_global_id("Warehouse", warehouse.id)
- variables = {
- "input": {
- "isPrivate": True,
- "clickAndCollectOption": WarehouseClickAndCollectOptionEnum.LOCAL.name,
- },
- "id": node_id,
- }
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_products]
- )
- content = get_graphql_content(response)
- warehouse.refresh_from_db()
- data = content["data"]["updateWarehouse"]
- errors = data["errors"]
-
- assert len(errors) == 1
- assert (
- errors[0]["message"]
- == "Local warehouse can be toggled only for non-private warehouse stocks"
- )
- assert errors[0]["field"] == "clickAndCollectOption"
-
- assert warehouse.is_private == warehouse_is_private
- assert warehouse.click_and_collect_option == warehouse_click_and_collect
-
-
-def test_delete_warehouse_mutation(
- staff_api_client, warehouse, permission_manage_products
-):
- warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)
- assert Warehouse.objects.count() == 1
- response = staff_api_client.post_graphql(
- MUTATION_DELETE_WAREHOUSE,
- variables={"id": warehouse_id},
- permissions=[permission_manage_products],
- )
- content = get_graphql_content(response)
- errors = content["data"]["deleteWarehouse"]["errors"]
- assert len(errors) == 0
- assert not Warehouse.objects.exists()
-
-
-@patch("saleor.plugins.webhook.plugin.get_webhooks_for_event")
-@patch("saleor.plugins.webhook.plugin.trigger_webhooks_async")
-def test_delete_warehouse_mutation_trigger_webhook(
- mocked_webhook_trigger,
- mocked_get_webhooks_for_event,
- any_webhook,
- staff_api_client,
- warehouse,
- permission_manage_products,
- settings,
-):
- # given
- mocked_get_webhooks_for_event.return_value = [any_webhook]
- settings.PLUGINS = ["saleor.plugins.webhook.plugin.WebhookPlugin"]
-
- warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)
- response = staff_api_client.post_graphql(
- MUTATION_DELETE_WAREHOUSE,
- variables={"id": warehouse_id},
- permissions=[permission_manage_products],
- )
- content = get_graphql_content(response)
-
- # then
- assert len(content["data"]["deleteWarehouse"]["errors"]) == 0
- mocked_webhook_trigger.assert_called_once_with(
- json.dumps(
- {
- "id": warehouse_id,
- "name": warehouse.name,
- },
- cls=CustomJsonEncoder,
- ),
- WebhookEventAsyncType.WAREHOUSE_DELETED,
- [any_webhook],
- warehouse,
- SimpleLazyObject(lambda: staff_api_client.user),
- )
-
-
-@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")
-def test_delete_warehouse_mutation_with_webhooks(
- product_variant_out_of_stock_webhook,
- staff_api_client,
- warehouse,
- permission_manage_products,
- variant_with_many_stocks,
-):
- old_first_stock = Stock.objects.first()
- warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)
- assert Warehouse.objects.count() == 3
- assert Stock.objects.count() == 3
- response = staff_api_client.post_graphql(
- MUTATION_DELETE_WAREHOUSE,
- variables={"id": warehouse_id},
- permissions=[permission_manage_products],
- )
- content = get_graphql_content(response)
- errors = content["data"]["deleteWarehouse"]["errors"]
- assert len(errors) == 0
- assert Warehouse.objects.count() == 2
- assert Stock.objects.count() == 2
- product_variant_out_of_stock_webhook.assert_called_once_with(old_first_stock)
-
-
-@patch("saleor.plugins.manager.PluginsManager.product_variant_out_of_stock")
-def test_delete_warehouse_mutation_with_webhooks_for_many_product_variants(
- product_variant_out_of_stock_webhook,
- staff_api_client,
- warehouse,
- permission_manage_products,
- product_with_two_variants,
-):
- warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)
- assert Warehouse.objects.count() == 1
- assert Stock.objects.count() == 2
- response = staff_api_client.post_graphql(
- MUTATION_DELETE_WAREHOUSE,
- variables={"id": warehouse_id},
- permissions=[permission_manage_products],
- )
- content = get_graphql_content(response)
- errors = content["data"]["deleteWarehouse"]["errors"]
- assert len(errors) == 0
- assert Warehouse.objects.count() == 0
- assert Stock.objects.count() == 0
- assert product_variant_out_of_stock_webhook.call_count == 2
-
-
-def test_delete_warehouse_deletes_associated_address(
- staff_api_client, warehouse, permission_manage_products
-):
- warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)
- assert Address.objects.count() == 1
- response = staff_api_client.post_graphql(
- MUTATION_DELETE_WAREHOUSE,
- variables={"id": warehouse_id},
- permissions=[permission_manage_products],
- )
- content = get_graphql_content(response)
- errors = content["data"]["deleteWarehouse"]["errors"]
- assert len(errors) == 0
- assert not Address.objects.exists()
-
-
-def test_shipping_zone_can_be_assigned_only_to_one_warehouse(
- staff_api_client, warehouse, warehouse_JPY, permission_manage_products
-):
- # given
- used_shipping_zone = warehouse.shipping_zones.first()
- used_shipping_zone_id = graphene.Node.to_global_id(
- "ShippingZone", used_shipping_zone.pk
- )
- zone_warehouses_count = used_shipping_zone.warehouses.count()
-
- variables = {
- "id": graphene.Node.to_global_id("Warehouse", warehouse_JPY.pk),
- "shippingZoneIds": [used_shipping_zone_id],
- }
-
- # when
- response = staff_api_client.post_graphql(
- MUTATION_ASSIGN_SHIPPING_ZONE_WAREHOUSE,
- variables=variables,
- permissions=[permission_manage_products],
- )
-
- # then
- content = get_graphql_content(response)
- errors = content["data"]["assignWarehouseShippingZone"]["errors"]
- assert len(errors) == 1
- assert errors[0]["code"] == WarehouseErrorCode.INVALID.name
- assert errors[0]["field"] == "shippingZones"
- used_shipping_zone.refresh_from_db()
- assert used_shipping_zone.warehouses.count() == zone_warehouses_count
-
-
-def test_shipping_zone_assign_to_warehouse(
- staff_api_client,
- warehouse_no_shipping_zone,
- shipping_zone,
- permission_manage_products,
-):
- assert not warehouse_no_shipping_zone.shipping_zones.all()
- staff_api_client.user.user_permissions.add(permission_manage_products)
- variables = {
- "id": graphene.Node.to_global_id("Warehouse", warehouse_no_shipping_zone.pk),
- "shippingZoneIds": [
- graphene.Node.to_global_id("ShippingZone", shipping_zone.pk)
- ],
- }
-
- staff_api_client.post_graphql(
- MUTATION_ASSIGN_SHIPPING_ZONE_WAREHOUSE, variables=variables
- )
- warehouse_no_shipping_zone.refresh_from_db()
- shipping_zone.refresh_from_db()
- assert warehouse_no_shipping_zone.shipping_zones.first().pk == shipping_zone.pk
-
-
-def test_shipping_zone_assign_to_warehouse_no_common_channel(
- staff_api_client,
- warehouse_no_shipping_zone,
- shipping_zone,
- permission_manage_products,
- channel_PLN,
-):
- # given
- assert not warehouse_no_shipping_zone.shipping_zones.all()
-
- staff_api_client.user.user_permissions.add(permission_manage_products)
-
- # remove channel_USD from shipping zone channels, assign channel_PLN
- shipping_zone.channels.set([channel_PLN])
-
- zone_id = graphene.Node.to_global_id("ShippingZone", shipping_zone.pk)
-
- variables = {
- "id": graphene.Node.to_global_id("Warehouse", warehouse_no_shipping_zone.pk),
- "shippingZoneIds": [zone_id],
- }
-
- # when
- response = staff_api_client.post_graphql(
- MUTATION_ASSIGN_SHIPPING_ZONE_WAREHOUSE, variables=variables
- )
-
- # then
- content = get_graphql_content(response)
- errors = content["data"]["assignWarehouseShippingZone"]["errors"]
-
- assert len(errors) == 1
- assert errors[0]["code"] == WarehouseErrorCode.INVALID.name
- assert errors[0]["field"] == "shippingZones"
- assert errors[0]["shippingZones"] == [zone_id]
-
-
-def test_shipping_zone_assign_to_warehouse_no_zone_channels(
- staff_api_client,
- warehouse_no_shipping_zone,
- shipping_zone,
- permission_manage_products,
- channel_PLN,
-):
- # given
- assert not warehouse_no_shipping_zone.shipping_zones.all()
-
- staff_api_client.user.user_permissions.add(permission_manage_products)
-
- # remove all channels from the shipping zone
- shipping_zone.channels.clear()
-
- zone_id = graphene.Node.to_global_id("ShippingZone", shipping_zone.pk)
-
- variables = {
- "id": graphene.Node.to_global_id("Warehouse", warehouse_no_shipping_zone.pk),
- "shippingZoneIds": [
- graphene.Node.to_global_id("ShippingZone", shipping_zone.pk)
- ],
- }
-
- # when
- response = staff_api_client.post_graphql(
- MUTATION_ASSIGN_SHIPPING_ZONE_WAREHOUSE, variables=variables
- )
-
- # then
- content = get_graphql_content(response)
- errors = content["data"]["assignWarehouseShippingZone"]["errors"]
-
- assert len(errors) == 1
- assert errors[0]["code"] == WarehouseErrorCode.INVALID.name
- assert errors[0]["field"] == "shippingZones"
- assert errors[0]["shippingZones"] == [zone_id]
-
-
-def test_empty_shipping_zone_assign_to_warehouse(
- staff_api_client,
- warehouse_no_shipping_zone,
- shipping_zone,
- permission_manage_products,
-):
- assert not warehouse_no_shipping_zone.shipping_zones.all()
- staff_api_client.user.user_permissions.add(permission_manage_products)
- variables = {
- "id": graphene.Node.to_global_id("Warehouse", warehouse_no_shipping_zone.pk),
- "shippingZoneIds": [],
- }
-
- response = staff_api_client.post_graphql(
- MUTATION_ASSIGN_SHIPPING_ZONE_WAREHOUSE, variables=variables
- )
- content = get_graphql_content(response)
- errors = content["data"]["assignWarehouseShippingZone"]["errors"]
- warehouse_no_shipping_zone.refresh_from_db()
- shipping_zone.refresh_from_db()
-
- assert not warehouse_no_shipping_zone.shipping_zones.all()
- assert errors[0]["field"] == "shippingZoneId"
- assert errors[0]["code"] == "GRAPHQL_ERROR"
-
-
-def test_shipping_zone_unassign_from_warehouse(
- staff_api_client, warehouse, shipping_zone, permission_manage_products
-):
- assert warehouse.shipping_zones.first().pk == shipping_zone.pk
- staff_api_client.user.user_permissions.add(permission_manage_products)
- variables = {
- "id": graphene.Node.to_global_id("Warehouse", warehouse.pk),
- "shippingZoneIds": [
- graphene.Node.to_global_id("ShippingZone", shipping_zone.pk)
- ],
- }
-
- staff_api_client.post_graphql(
- MUTATION_UNASSIGN_SHIPPING_ZONE_WAREHOUSE, variables=variables
- )
- warehouse.refresh_from_db()
- shipping_zone.refresh_from_db()
- assert not warehouse.shipping_zones.all()
-
-
-def test_warehouse_query_by_external_reference(
- staff_api_client, warehouse, permission_manage_products
-):
- # given
- ext_ref = "test-ext-ref"
- warehouse.external_reference = ext_ref
- warehouse.save(update_fields=["external_reference"])
- variables = {"externalReference": ext_ref}
-
- # when
- response = staff_api_client.post_graphql(
- QUERY_WAREHOUSE_BY_EXTERNAL_REFERENCE,
- variables=variables,
- permissions=[permission_manage_products],
- )
- content = get_graphql_content(response)
-
- # then
- data = content["data"]["warehouse"]
- assert data["externalReference"] == ext_ref
- assert data["id"] == graphene.Node.to_global_id("Warehouse", warehouse.id)