Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Refactor warehouse mutations (#10239)
Iga Karbowiakc36e03482aa9
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 80ef3aac84..03c6f0c2bb 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,10 +5,18 @@ All notable, unreleased changes to this project will be documented in this file.# 3.7.0 [Unreleased]### GraphQL API+- Sorting warehouses within channel - #10416 by @IKarbowiak- Add `channelReorderWarehouses` mutation- Extend the `Channel` type with `stockSettings` field- Extend `ChannelCreateInput` and `ChannelUpdateInput` with `stockSettings`+ - Add `name` parameter to `ProductVariantInput` - #10456 by @SzymJ++### Breaking changes++- Refactor warehouse mutations - #10239 by @IKarbowiak+ - Providing the value in `shippingZone` filed in `WarehouseCreate` mutation will raise a ValidationError.+ Use `WarehouseShippingZoneAssign` to assign shipping zones to warehouse .### Other changes@@ -17,8 +25,6 @@ All notable, unreleased changes to this project will be documented in this file.- Add support for bcrypt password hashes - #10346 by @pkucmus- Add ability to set taxes configuration per channel in the Avatax plugin - #10445 by @mociepka-### GraphQL API- - Add `name` parameter to `ProductVariantInput` - #10456 by @SzymJ# 3.6.0diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.pyindex 457665a04d..eb2f8c8962 100644--- a/saleor/graphql/core/types/common.py+++ b/saleor/graphql/core/types/common.py@@ -339,7 +339,7 @@ class PaymentError(Error):code = PaymentErrorCode(description="The error code.", required=True)variants = NonNullList(graphene.ID,- description="List of varint IDs which causes the error.",+ description="List of variant IDs which causes the error.",required=False,)@@ -387,6 +387,11 @@ class UploadError(Error):class WarehouseError(Error):code = WarehouseErrorCode(description="The error code.", required=True)+ shipping_zones = NonNullList(+ graphene.ID,+ description="List of shipping zones IDs which causes the error.",+ required=False,+ )class WebhookError(Error):diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 265435db2a..a88195423f 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -14574,6 +14574,9 @@ type WarehouseError {"""The error code."""code: WarehouseErrorCode!++ """List of shipping zones IDs which causes the error."""+ shippingZones: [ID!]}"""An enumeration."""@@ -14599,7 +14602,11 @@ input WarehouseCreateInput {"""Address of the warehouse."""address: AddressInput!- """Shipping zones supported by the warehouse."""+ """+ Shipping zones supported by the warehouse.++ DEPRECATED: this field will be removed in Saleor 4.0. Providing the zone ids will raise a ValidationError.+ """shippingZones: [ID!]}@@ -16816,7 +16823,7 @@ type PaymentError {"""The error code."""code: PaymentErrorCode!- """List of varint IDs which causes the error."""+ """List of variant IDs which causes the error."""variants: [ID!]}diff --git a/saleor/graphql/warehouse/mutations.py b/saleor/graphql/warehouse/mutations.pyindex 15d4811937..85270a5a82 100644--- a/saleor/graphql/warehouse/mutations.py+++ b/saleor/graphql/warehouse/mutations.py@@ -1,7 +1,10 @@+from collections import defaultdict+import graphenefrom django.core.exceptions import ValidationErrorfrom django.db import transaction+from ...channel import models as channel_modelsfrom ...core.permissions import ProductPermissionsfrom ...core.tracing import traced_atomic_transactionfrom ...warehouse import WarehouseClickAndCollectOption, models@@ -48,11 +51,16 @@ class WarehouseMixin:error.code = WarehouseErrorCode.REQUIRED.valueraise ValidationError({"name": error})- shipping_zones = cleaned_input.get("shipping_zones", [])- if not validate_warehouse_count(shipping_zones, instance):- msg = "Shipping zone can be assigned only to one warehouse."+ # assigning shipping zones in the WarehouseCreate mutation is deprecated+ if cleaned_input.get("shipping_zones"):raise ValidationError(- {"shipping_zones": msg}, code=WarehouseErrorCode.INVALID+ {+ "shipping_zones": ValidationError(+ "The shippingZone input field is deprecated. "+ "Use WarehouseShippingZoneAssign mutation",+ code=WarehouseErrorCode.INVALID.value,+ )+ })click_and_collect_option = cleaned_input.get(@@ -103,7 +111,7 @@ class WarehouseCreate(WarehouseMixin, ModelMutation, I18nMixin):info.context.plugins.warehouse_created(instance)-class WarehouseShippingZoneAssign(WarehouseMixin, ModelMutation, I18nMixin):+class WarehouseShippingZoneAssign(ModelMutation, I18nMixin):class Meta:model = models.Warehouseobject_type = Warehouse@@ -126,11 +134,88 @@ class WarehouseShippingZoneAssign(WarehouseMixin, ModelMutation, I18nMixin):shipping_zones = cls.get_nodes_or_error(data.get("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+ )++ 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+ 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,+ },+ )+ }+ )-class WarehouseShippingZoneUnassign(WarehouseMixin, ModelMutation, I18nMixin):+ @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.Warehouseobject_type = Warehousediff --git a/saleor/graphql/warehouse/tests/test_warehouse.py b/saleor/graphql/warehouse/tests/test_warehouse.pyindex 76102a2be9..61da0b9ac8 100644--- a/saleor/graphql/warehouse/tests/test_warehouse.py+++ b/saleor/graphql/warehouse/tests/test_warehouse.py@@ -123,6 +123,13 @@ mutation createWarehouse($input: WarehouseCreateInput!) {address {id}+ shippingZones(first: 5) {+ edges {+ node {+ id+ }+ }+ }}errors {message@@ -179,6 +186,7 @@ mutation assignWarehouseShippingZone($id: ID!, $shippingZoneIds: [ID!]!) {fieldmessagecode+ shippingZones}}}@@ -631,9 +639,6 @@ def test_mutation_create_warehouse("postalCode": "53-601","companyName": "Amazing Company Inc",},- "shippingZones": [- graphene.Node.to_global_id("ShippingZone", shipping_zone.id)- ],}}@@ -654,6 +659,41 @@ def test_mutation_create_warehouse(assert created_warehouse["companyName"] == warehouse.address.company_name+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(@@ -681,9 +721,6 @@ def test_mutation_create_warehouse_trigger_webhook("postalCode": "53-601","companyName": "Amazing Company Inc",},- "shippingZones": [- graphene.Node.to_global_id("ShippingZone", shipping_zone.id)- ],}}@@ -762,9 +799,6 @@ def test_create_warehouse_creates_address("companyName": "Amazing Company Inc","postalCode": "53-601",},- "shippingZones": [- graphene.Node.to_global_id("ShippingZone", shipping_zone.id)- ],}}assert not Address.objects.exists()@@ -1254,41 +1288,35 @@ def test_delete_warehouse_deletes_associated_address(def test_shipping_zone_can_be_assigned_only_to_one_warehouse(- staff_api_client, warehouse, permission_manage_products+ staff_api_client, warehouse, warehouse_JPY, permission_manage_products):+ # givenused_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 = {- "input": {- "name": "Warehouse #q",- "email": "[email protected]",- "address": {- "streetAddress1": "Teczowa 8",- "city": "Wroclaw",- "country": "PL",- "companyName": "Big Company",- "postalCode": "53-601",- },- "shippingZones": [used_shipping_zone_id],- }+ "id": graphene.Node.to_global_id("Warehouse", warehouse_JPY.pk),+ "shippingZoneIds": [used_shipping_zone_id],}+ # whenresponse = staff_api_client.post_graphql(- MUTATION_CREATE_WAREHOUSE,+ MUTATION_ASSIGN_SHIPPING_ZONE_WAREHOUSE,variables=variables,permissions=[permission_manage_products],)++ # thencontent = get_graphql_content(response)- errors = content["data"]["createWarehouse"]["errors"]+ errors = content["data"]["assignWarehouseShippingZone"]["errors"]assert len(errors) == 1- assert (- errors[0]["message"] == "Shipping zone can be assigned only to one warehouse."- )+ assert errors[0]["code"] == WarehouseErrorCode.INVALID.name+ assert errors[0]["field"] == "shippingZones"used_shipping_zone.refresh_from_db()- assert used_shipping_zone.warehouses.count() == 1+ assert used_shipping_zone.warehouses.count() == zone_warehouses_countdef test_shipping_zone_assign_to_warehouse(@@ -1314,6 +1342,82 @@ def test_shipping_zone_assign_to_warehouse(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,diff --git a/saleor/graphql/warehouse/types.py b/saleor/graphql/warehouse/types.pyindex bb8a1e7e75..42e7b1bc64 100644--- a/saleor/graphql/warehouse/types.py+++ b/saleor/graphql/warehouse/types.py@@ -9,7 +9,12 @@ from ...warehouse.reservations import is_reservation_enabledfrom ..account.dataloaders import AddressByIdLoaderfrom ..channel import ChannelContextfrom ..core.connection import CountableConnection, create_connection_slice-from ..core.descriptions import ADDED_IN_31, DEPRECATED_IN_3X_FIELD, PREVIEW_FEATURE+from ..core.descriptions import (+ ADDED_IN_31,+ DEPRECATED_IN_3X_FIELD,+ DEPRECATED_IN_3X_INPUT,+ PREVIEW_FEATURE,+)from ..core.fields import ConnectionField, PermissionsFieldfrom ..core.types import ModelObjectType, NonNullListfrom ..meta.types import ObjectWithMetadata@@ -31,7 +36,10 @@ class WarehouseCreateInput(WarehouseInput):required=True,)shipping_zones = NonNullList(- graphene.ID, description="Shipping zones supported by the warehouse."+ graphene.ID,+ description="Shipping zones supported by the warehouse."+ + DEPRECATED_IN_3X_INPUT+ + " Providing the zone ids will raise a ValidationError.",)