Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add related name to shipping-zone from warehouses
Krzysztof Świątek410aaaea7c0d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e72fa531e9..c54ed6c8c3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -60,6 +60,7 @@ All notable, unreleased changes to this project will be documented in this file.- Unify permission for service account api client in test - #5197 by @fowczarek- Allow sorting warehouses by name - #5211 by @dominik-zeglen- Add anonymization to GraphQL's `webhookSamplePayload` endpoint - #5161 @derenio+- Add mutation for assigning, unassigning shipping zones to warehouse - #5217 by @kswiatek92## 2.9.0diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.pyindex f6c0f543f3..65f3277ade 100644--- a/saleor/graphql/product/types/products.py+++ b/saleor/graphql/product/types/products.py@@ -523,8 +523,8 @@ class Product(CountableDjangoObjectType, MetadataObjectType):@staticmethod@gql_optimizer.resolver_hints(prefetch_related=("variants"))- def resolve_is_available(root: models.Product, _info):- country = _info.context.country+ def resolve_is_available(root: models.Product, info):+ country = info.context.countryin_stock = is_product_in_stock(root, country)return root.is_visible and in_stock@@ -663,7 +663,7 @@ class ProductType(CountableDjangoObjectType, MetadataObjectType):return TaxType(tax_code=tax_data.code, description=tax_data.description)@staticmethod- def resolve_tax_rate(root: models.ProductType, info, **_kwargs):+ def resolve_tax_rate(root: models.ProductType, _info, **_kwargs):# FIXME this resolver should be dropped after we drop tax_rate from APIif not hasattr(root, "meta"):return Nonediff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 9b5a2d250a..44df9ec530 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -2109,6 +2109,8 @@ type Mutation {createWarehouse(input: WarehouseCreateInput!): WarehouseCreateupdateWarehouse(id: ID!, input: WarehouseUpdateInput!): WarehouseUpdatedeleteWarehouse(id: ID!): WarehouseDelete+ assignWarehouseShippingZone(id: ID!, shippingZoneIds: [ID!]!): WarehouseShippingZoneAssign+ unassignWarehouseShippingZone(id: ID!, shippingZoneIds: [ID!]!): WarehouseShippingZoneUnassigncreateStock(input: StockInput!): StockCreateupdateStock(id: ID!, input: StockInput!): StockUpdatedeleteStock(id: ID!): StockDelete@@ -3997,6 +3999,7 @@ type ShippingZone implements Node {priceRange: MoneyRangecountries: [CountryDisplay]shippingMethods: [ShippingMethod]+ warehouses: [Warehouse]}type ShippingZoneBulkDelete {@@ -4740,9 +4743,9 @@ type WarehouseCreate {input WarehouseCreateInput {name: String!companyName: String- shippingZones: [ID]email: Stringaddress: WarehouseAddressInput!+ shippingZones: [ID]}type WarehouseDelete {@@ -4770,6 +4773,18 @@ input WarehouseFilterInput {search: String}+type WarehouseShippingZoneAssign {+ errors: [Error!]+ warehouse: Warehouse+ warehouseErrors: [WarehouseError!]+}++type WarehouseShippingZoneUnassign {+ errors: [Error!]+ warehouse: Warehouse+ warehouseErrors: [WarehouseError!]+}+enum WarehouseSortField {NAME}@@ -4788,7 +4803,6 @@ type WarehouseUpdate {input WarehouseUpdateInput {name: String!companyName: String- shippingZones: [ID]email: Stringaddress: WarehouseAddressInput}diff --git a/saleor/graphql/shipping/types.py b/saleor/graphql/shipping/types.pyindex a472bdfb8e..4011c958f3 100644--- a/saleor/graphql/shipping/types.py+++ b/saleor/graphql/shipping/types.py@@ -2,12 +2,15 @@ import grapheneimport graphene_django_optimizer as gql_optimizerfrom graphene import relay+from ...core.permissions import ProductPermissionsfrom ...shipping import modelsfrom ..core.connection import CountableDjangoObjectTypefrom ..core.types import CountryDisplay, MoneyRange+from ..decorators import permission_requiredfrom ..translations.fields import TranslationFieldfrom ..translations.types import ShippingMethodTranslationfrom .enums import ShippingMethodTypeEnum+from ..warehouse.types import Warehouseclass ShippingMethod(CountableDjangoObjectType):@@ -51,6 +54,9 @@ class ShippingZone(CountableDjangoObjectType):),model_field="shipping_methods",)+ warehouses = graphene.List(+ Warehouse, description="List of warehouses for shipping zone."+ )class Meta:description = (@@ -76,3 +82,8 @@ class ShippingZone(CountableDjangoObjectType):@staticmethoddef resolve_shipping_methods(root: models.ShippingZone, *_args):return root.shipping_methods.all()++ @staticmethod+ @permission_required(ProductPermissions.MANAGE_PRODUCTS)+ def resolve_warehouses(root: models.ShippingZone, *_args):+ return root.warehouses.all()diff --git a/saleor/graphql/warehouse/mutations.py b/saleor/graphql/warehouse/mutations.pyindex b6e65f0c5f..7c2e32dfde 100644--- a/saleor/graphql/warehouse/mutations.py+++ b/saleor/graphql/warehouse/mutations.py@@ -8,7 +8,9 @@ from ...warehouse.validation import validate_warehouse_count # type: ignorefrom ..account.i18n import I18nMixinfrom ..core.mutations import ModelBulkDeleteMutation, ModelDeleteMutation, ModelMutationfrom ..core.types.common import StockError, WarehouseError-from .types import StockInput, WarehouseCreateInput, WarehouseUpdateInput+from ..shipping.types import ShippingZone+from .types import StockInput, Warehouse, WarehouseCreateInput, WarehouseUpdateInput+ADDRESS_FIELDS = ["street_address_1",@@ -59,6 +61,66 @@ class WarehouseCreate(WarehouseMixin, ModelMutation, I18nMixin):return address_form.save()+class WarehouseShippingZoneAssign(WarehouseMixin, ModelMutation, I18nMixin):+ warehouse = graphene.Field(+ Warehouse, description="A warehouse to add shipping zone."+ )++ class Meta:+ model = models.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 = graphene.List(+ graphene.NonNull(graphene.ID),+ required=True,+ description="List of shipping zone IDs.",+ )++ @classmethod+ def perform_mutation(cls, _root, info, **data):+ warehouse = cls.get_node_or_error(info, data.get("id"), only_type=Warehouse)+ shipping_zones = cls.get_nodes_or_error(+ data.get("shipping_zone_ids"), "shipping_zone_id", only_type=ShippingZone+ )+ warehouse.shipping_zones.add(*shipping_zones)+ return WarehouseShippingZoneAssign(warehouse=warehouse)+++class WarehouseShippingZoneUnassign(WarehouseMixin, ModelMutation, I18nMixin):+ warehouse = graphene.Field(+ Warehouse, description="A warehouse to add shipping zone."+ )++ class Meta:+ model = models.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 = graphene.List(+ graphene.NonNull(graphene.ID),+ required=True,+ description="List of shipping zone IDs.",+ )++ @classmethod+ def perform_mutation(cls, _root, info, **data):+ warehouse = cls.get_node_or_error(info, data.get("id"), only_type=Warehouse)+ shipping_zones = cls.get_nodes_or_error(+ data.get("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.Warehousediff --git a/saleor/graphql/warehouse/schema.py b/saleor/graphql/warehouse/schema.pyindex f7a5490a8c..542acf2ebd 100644--- a/saleor/graphql/warehouse/schema.py+++ b/saleor/graphql/warehouse/schema.py@@ -15,12 +15,11 @@ from .mutations import (WarehouseCreate,WarehouseDelete,WarehouseUpdate,+ WarehouseShippingZoneAssign,+ WarehouseShippingZoneUnassign,)from ..utils import sort_queryset-from .sorters import (- WarehouseSortField,- WarehouseSortingInput,-)+from .sorters import WarehouseSortField, WarehouseSortingInputfrom .types import Stock, Warehouse@@ -62,6 +61,8 @@ class WarehouseMutations(graphene.ObjectType):create_warehouse = WarehouseCreate.Field()update_warehouse = WarehouseUpdate.Field()delete_warehouse = WarehouseDelete.Field()+ assign_warehouse_shipping_zone = WarehouseShippingZoneAssign.Field()+ unassign_warehouse_shipping_zone = WarehouseShippingZoneUnassign.Field()class StockQueries(graphene.ObjectType):@@ -71,7 +72,7 @@ class StockQueries(graphene.ObjectType):id=graphene.ID(required=True, description="ID of an warehouse"),)stocks = FilterInputConnectionField(- Stock, description="List of stocks.", filter=StockFilterInput(),+ Stock, description="List of stocks.", filter=StockFilterInput())@permission_required(ProductPermissions.MANAGE_PRODUCTS)diff --git a/saleor/graphql/warehouse/types.py b/saleor/graphql/warehouse/types.pyindex 78933f7b03..6acc62f150 100644--- a/saleor/graphql/warehouse/types.py+++ b/saleor/graphql/warehouse/types.py@@ -22,9 +22,6 @@ class WarehouseAddressInput(graphene.InputObjectType):class WarehouseInput(graphene.InputObjectType):name = graphene.String(description="Warehouse name.", required=True)company_name = graphene.String(description="Company name.")- shipping_zones = graphene.List(- graphene.ID, description="Shipping zones supported by the warehouse."- )email = graphene.String(description="The email address of the warehouse.")@@ -32,6 +29,9 @@ class WarehouseCreateInput(WarehouseInput):address = WarehouseAddressInput(description="Address of the warehouse.", required=True)+ shipping_zones = graphene.List(+ graphene.ID, description="Shipping zones supported by the warehouse."+ )class WarehouseUpdateInput(WarehouseInput):diff --git a/saleor/warehouse/migrations/0003_auto_20200131_0703.py b/saleor/warehouse/migrations/0003_auto_20200131_0703.pynew file mode 100644index 0000000000..ed47c8811f--- /dev/null+++ b/saleor/warehouse/migrations/0003_auto_20200131_0703.py@@ -0,0 +1,18 @@+# Generated by Django 2.2.9 on 2020-01-31 13:03++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [("warehouse", "0002_auto_20200123_0036")]++ operations = [+ migrations.AlterField(+ model_name="warehouse",+ name="shipping_zones",+ field=models.ManyToManyField(+ blank=True, related_name="warehouses", to="shipping.ShippingZone"+ ),+ )+ ]diff --git a/saleor/warehouse/models.py b/saleor/warehouse/models.pyindex 0b8ce8a8b7..60a4520ef1 100644--- a/saleor/warehouse/models.py+++ b/saleor/warehouse/models.py@@ -24,7 +24,9 @@ class Warehouse(models.Model):name = models.CharField(max_length=255)company_name = models.CharField(blank=True, max_length=255)- shipping_zones = models.ManyToManyField(ShippingZone, blank=True)+ shipping_zones = models.ManyToManyField(+ ShippingZone, blank=True, related_name="warehouses"+ )address = models.ForeignKey(Address, on_delete=models.PROTECT)email = models.EmailField(blank=True, default="")diff --git a/saleor/warehouse/validation.py b/saleor/warehouse/validation.pyindex 8c61a75420..6c34c04b92 100644--- a/saleor/warehouse/validation.py+++ b/saleor/warehouse/validation.py@@ -14,8 +14,8 @@ def validate_warehouse_count(shipping_zones, instance: Warehouse) -> bool:ShippingZone.objects.filter(id__in=[shipping_zone.id for shipping_zone in shipping_zones])- .filter(warehouse__isnull=False)- .values_list("warehouse", flat=True)+ .filter(warehouses__isnull=False)+ .values_list("warehouses", flat=True))if not bool(warehouses):return Truediff --git a/tests/api/test_shipping_method.py b/tests/api/test_shipping_method.pyindex f2fd4e7f3b..7a0aca19ba 100644--- a/tests/api/test_shipping_method.py+++ b/tests/api/test_shipping_method.py@@ -47,18 +47,31 @@ def test_shipping_zone_query(def test_shipping_zones_query(- staff_api_client, shipping_zone, permission_manage_shipping+ staff_api_client,+ shipping_zone,+ permission_manage_shipping,+ permission_manage_products,):query = """query MultipleShippings {- shippingZones {+ shippingZones(first: 100) {+ edges {+ node {+ id+ name+ warehouses {+ id+ name+ }+ }+ }totalCount}}"""num_of_shippings = shipping_zone._meta.model.objects.count()response = staff_api_client.post_graphql(- query, permissions=[permission_manage_shipping]+ query, permissions=[permission_manage_shipping, permission_manage_products])content = get_graphql_content(response)assert content["data"]["shippingZones"]["totalCount"] == num_of_shippingsdiff --git a/tests/api/test_warehouse.py b/tests/api/test_warehouse.pyindex 74d6fa9b72..8dda19424e 100644--- a/tests/api/test_warehouse.py+++ b/tests/api/test_warehouse.py@@ -137,6 +137,34 @@ mutation deleteWarehouse($id: ID!) {"""+MUTATION_ASSIGN_SHIPPING_ZONE_WAREHOUSE = """+mutation assignWarehouseShippingZone($id: ID!, $shippingZoneIds: [ID!]!) {+ assignWarehouseShippingZone(id: $id, shippingZoneIds: $shippingZoneIds) {+ warehouseErrors {+ field+ message+ code+ }+ }+}++"""+++MUTATION_UNASSIGN_SHIPPING_ZONE_WAREHOUSE = """+mutation unassignWarehouseShippingZone($id: ID!, $shippingZoneIds: [ID!]!) {+ unassignWarehouseShippingZone(id: $id, shippingZoneIds: $shippingZoneIds) {+ warehouseErrors {+ field+ message+ code+ }+ }+}++"""++def test_warehouse_cannot_query_without_permissions(user_api_client, warehouse):assert not user_api_client.user.has_perm(ProductPermissions.MANAGE_PRODUCTS)warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)@@ -364,11 +392,7 @@ def test_mutation_update_warehouse(warehouse_old_company_name = warehouse.company_namevariables = {"id": warehouse_id,- "input": {- "name": "New name",- "companyName": "New name for company",- "shippingZones": [],- },+ "input": {"name": "New name", "companyName": "New name for company"},}staff_api_client.post_graphql(MUTATION_UPDATE_WAREHOUSE, variables=variables)warehouse.refresh_from_db()@@ -376,7 +400,6 @@ def test_mutation_update_warehouse(assert not (warehouse.company_name == warehouse_old_company_name)assert warehouse.name == "New name"assert warehouse.company_name == "New name for company"- assert warehouse.shipping_zones.count() == 0def test_mutation_update_warehouse_can_update_address(@@ -411,51 +434,6 @@ def test_mutation_update_warehouse_can_update_address(assert address.street_address_2 == "Ground floor"-def test_mutation_update_warehouse_removing_shipping_zones(- staff_api_client, warehouse, permission_manage_products-):- staff_api_client.user.user_permissions.add(permission_manage_products)- warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.id)- assert warehouse.shipping_zones.count() == 1- variables = {- "id": warehouse_id,- "input": {- "name": warehouse.name,- "companyName": warehouse.company_name,- "shippingZones": [],- },- }- staff_api_client.post_graphql(MUTATION_UPDATE_WAREHOUSE, variables=variables)- warehouse.refresh_from_db()- assert not warehouse.shipping_zones.exists()---def test_mutation_update_warehouse_adding_shipping_zones(- staff_api_client,- warehouse,- permission_manage_products,- shipping_zone_without_countries,-):- staff_api_client.user.user_permissions.add(permission_manage_products)- warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.id)- assert warehouse.shipping_zones.count() == 1- current_zone = warehouse.shipping_zones.first()- current_zone_id = graphene.Node.to_global_id("ShippingZone", current_zone.id)- new_zone = shipping_zone_without_countries- new_zone_id = graphene.Node.to_global_id("ShippingZone", new_zone.pk)- variables = {- "id": warehouse_id,- "input": {- "name": warehouse.name,- "companyName": warehouse.company_name,- "shippingZones": [current_zone_id, new_zone_id],- },- }- staff_api_client.post_graphql(MUTATION_UPDATE_WAREHOUSE, variables=variables)- warehouse.refresh_from_db()- assert warehouse.shipping_zones.count() == 2--def test_delete_warehouse_requires_permission(staff_api_client, warehouse):assert not staff_api_client.user.has_perm(ProductPermissions.MANAGE_PRODUCTS)warehouse_id = graphene.Node.to_global_id("Warehouse", warehouse.pk)@@ -532,4 +510,73 @@ def test_shipping_zone_can_be_assigned_only_to_one_warehouse(errors[0]["message"] == "Shipping zone can be assigned only to one warehouse.")used_shipping_zone.refresh_from_db()- assert used_shipping_zone.warehouse_set.count() == 1+ assert used_shipping_zone.warehouses.count() == 1+++def test_shipping_zone_assign_to_warehouse(+ staff_api_client,+ warehouse_wo_shipping_zone,+ shipping_zone,+ permission_manage_products,+):+ assert not warehouse_wo_shipping_zone.shipping_zones.all()+ staff_api_client.user.user_permissions.add(permission_manage_products)+ variables = {+ "id": graphene.Node.to_global_id("Warehouse", warehouse_wo_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_wo_shipping_zone.refresh_from_db()+ shipping_zone.refresh_from_db()+ assert warehouse_wo_shipping_zone.shipping_zones.first().pk == shipping_zone.pk+++def test_empty_shipping_zone_assign_to_warehouse(+ staff_api_client,+ warehouse_wo_shipping_zone,+ shipping_zone,+ permission_manage_products,+):+ assert not warehouse_wo_shipping_zone.shipping_zones.all()+ staff_api_client.user.user_permissions.add(permission_manage_products)+ variables = {+ "id": graphene.Node.to_global_id("Warehouse", warehouse_wo_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"]["warehouseErrors"]+ warehouse_wo_shipping_zone.refresh_from_db()+ shipping_zone.refresh_from_db()++ assert not warehouse_wo_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()diff --git a/tests/conftest.py b/tests/conftest.pyindex 8b7cc0e1eb..ab54619493 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -644,7 +644,7 @@ def product_with_single_variant(product_type, category, warehouse):is_published=True,)variant = ProductVariant.objects.create(- product=product, sku="SKU_SINGLE_VARIANT", cost_price=Money("1.00", "USD"),+ product=product, sku="SKU_SINGLE_VARIANT", cost_price=Money("1.00", "USD"))Stock.objects.create(product_variant=variant, warehouse=warehouse, quantity=101, quantity_allocated=1@@ -983,7 +983,7 @@ def voucher_specific_product_type(voucher_percentage):@pytest.fixturedef voucher_with_high_min_spent_amount():return Voucher.objects.create(- code="mirumee", discount_value=10, min_spent=Money(1000000, "USD")+ code="mirumee", discount_value=10, min_spent=Money(1_000_000, "USD"))@@ -1849,6 +1849,14 @@ def warehouse(address, shipping_zone):return warehouse+def warehouse_wo_shipping_zone(address, shipping_zone):+ warehouse = Warehouse.objects.create(+ address=address, name="Example Warehouse", email="[email protected]"+ )+ return warehouse++@pytest.fixturedef stock(variant, warehouse):return Stock.objects.get_or_create(