Skip to content

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

Add mutations to manage variant images

Marcin Gębalaae3b23e1c338
diff --git a/saleor/graphql/api.py b/saleor/graphql/api.py
index 0268a544d7..e07fba87dc 100644
--- a/saleor/graphql/api.py
+++ b/saleor/graphql/api.py
@@ -49,7 +49,7 @@ from .product.mutations.products import (
ProductTypeDelete, ProductImageCreate, ProductImageDelete,
ProductImageReorder, ProductImageUpdate, ProductTypeUpdate,
ProductVariantCreate, ProductVariantDelete,
- ProductVariantUpdate, VariantImageAssign, VariantImageDelete)
+ ProductVariantUpdate, VariantImageAssign, VariantImageUnassign)
from .product.resolvers import (
resolve_attributes, resolve_categories, resolve_collections,
resolve_products, resolve_product_types)
@@ -337,7 +337,7 @@ class Mutations(graphene.ObjectType):
shipping_price_update = ShippingPriceUpdate.Field()
variant_image_assign = VariantImageAssign.Field()
- variant_image_delete = VariantImageDelete.Field()
+ variant_image_unassign = VariantImageUnassign.Field()
schema = graphene.Schema(Query, Mutations)
diff --git a/saleor/graphql/core/mutations.py b/saleor/graphql/core/mutations.py
index 5e6995ed4e..1b46d73dcc 100644
--- a/saleor/graphql/core/mutations.py
+++ b/saleor/graphql/core/mutations.py
@@ -49,6 +49,39 @@ class BaseMutation(graphene.Mutation):
cls._meta.arguments.update(arguments)
cls._meta.fields.update(fields)
+ @classmethod
+ def add_error(cls, errors, field, message):
+ """Add an error to the errors list.
+
+ `errors` is the list of errors that happened during execution of the
+ mutation. `field` is the name of model field the error is related
+ to. `None` is allowed and it indicates that the error is a general one
+ and not related to any of the model fields. `message` is the actual
+ error message.
+
+ As a result of this method, the `errors` argument is updated with an
+ Error object to be returned in mutation result.
+ """
+ errors.append(Error(field=field, message=message))
+
+ @classmethod
+ def get_node_or_error(cls, info, id, errors, field, only_type=None):
+ instance = None
+ try:
+ instance = get_node(info, id, only_type)
+ except GraphQLError as e:
+ cls.add_error(field=field, message=str(e), errors=errors)
+ return instance
+
+ @classmethod
+ def get_nodes_or_error(cls, ids, errors, field, only_type=None):
+ instances = None
+ try:
+ instances = get_nodes(ids, only_type)
+ except GraphQLError as e:
+ cls.add_error(field=field, message=str(e), errors=errors)
+ return instances
+
class ModelMutation(BaseMutation):
class Meta:
@@ -78,21 +111,6 @@ class ModelMutation(BaseMutation):
cls._update_mutation_arguments_and_fields(
arguments=arguments, fields=fields)
- @classmethod
- def add_error(cls, errors, field, message):
- """Add an error to the errors list.
-
- `errors` is the list of errors that happened during execution of the
- mutation. `field` is the name of model field the error is related
- to. `None` is allowed and it indicates that the error is a general one
- and not related to any of the model fields. `message` is the actual
- error message.
-
- As a result of this method, the `errors` argument is updated with an
- Error object to be returned in mutation result.
- """
- errors.append(Error(field=field, message=message))
-
@classmethod
def _check_type(cls, field, target_type):
if hasattr(field.type, 'of_type'):
@@ -213,24 +231,6 @@ class ModelMutation(BaseMutation):
def save(cls, info, instance, cleaned_input):
instance.save()
- @classmethod
- def get_node_or_error(cls, info, id, errors, field, only_type=None):
- instance = None
- try:
- instance = get_node(info, id, only_type)
- except GraphQLError as e:
- cls.add_error(field=field, message=str(e), errors=errors)
- return instance
-
- @classmethod
- def get_nodes_or_error(cls, ids, errors, field, graphene_type=None):
- instances = None
- try:
- instances = get_nodes(ids, graphene_type)
- except GraphQLError as e:
- cls.add_error(field=field, message=str(e), errors=errors)
- return instances
-
@classmethod
def mutate(cls, root, info, **data):
"""Perform model mutation.
diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.py
index 87ec31c162..fadf9afa1d 100644
--- a/saleor/graphql/product/mutations/products.py
+++ b/saleor/graphql/product/mutations/products.py
@@ -9,7 +9,7 @@ from ...core.types.common import Decimal, Error, SeoInput
from ...core.utils import clean_seo_fields
from ...file_upload.types import Upload
from ...utils import get_attributes_dict_from_list, get_node, get_nodes
-from ..types import Collection, Product, ProductImage
+from ..types import Collection, Product, ProductImage, ProductVariant
class CategoryInput(graphene.InputObjectType):
@@ -528,49 +528,70 @@ class ProductImageDelete(ModelDeleteMutation):
return user.has_perm('product.manage_products')
-class VariantImageAssignInput(graphene.InputObjectType):
- variant = graphene.ID(
- name='variant',
- description='ID of a product variant to assign the image to.')
- image = graphene.ID(
- name='image',
- description='ID of a product image to assign to the variant.')
+class VariantImageAssign(BaseMutation):
+ image = graphene.Field(
+ ProductImage, description='Product image beeing assigned.')
-
-class VariantImageAssign(ModelMutation):
class Arguments:
- input = VariantImageAssignInput(
+ image_id = graphene.ID(
+ required=True,
+ description='ID of a product image to assign to a variant.')
+ variant_id = graphene.ID(
required=True,
- description='''
- Fields required to assign an image to a product variant.''')
+ description='ID of a product variant.')
class Meta:
description = 'Assign an image to a product variant'
- model = models.VariantImage
@classmethod
- def user_is_allowed(cls, user, input):
- return user.has_perm('product.manage_products')
-
- @classmethod
- def clean_input(cls, info, instance, input, errors):
- cleaned_input = super().clean_input(info, instance, input, errors)
- image = cleaned_input.get('image')
- variant = cleaned_input.get('variant')
- if image and variant and not variant.product.images.filter(pk=image.pk).first():
- cls.add_error(errors, 'image', 'Image must be for this product')
- return cleaned_input
-
-
-class VariantImageDelete(ModelDeleteMutation):
+ @permission_required('product.manage_products')
+ def mutate(cls, root, info, image_id, variant_id):
+ errors = []
+ image = cls.get_node_or_error(
+ info, image_id, errors, 'imageId', ProductImage)
+ variant = cls.get_node_or_error(
+ info, variant_id, errors, 'variantId', ProductVariant)
+ if image and variant:
+ # check if the given image and variant can be matched together
+ image_belongs_to_product = variant.product.images.filter(
+ pk=image.pk).first()
+ if image_belongs_to_product:
+ image.variant_images.create(variant=variant)
+ else:
+ cls.add_error(
+ errors, 'imageId', 'Image must be for this product')
+ return VariantImageAssign(image=image, errors=errors)
+
+
+class VariantImageUnassign(BaseMutation):
class Arguments:
- id = graphene.ID(
- required=True, description='ID of a variant image to delete.')
+ image_id = graphene.ID(
+ required=True,
+ description='ID of a product image to unassign from a variant.')
+ variant_id = graphene.ID(
+ required=True, description='ID of a product variant.')
+
+ image = graphene.Field(
+ ProductImage, description='Product image beeing unassigned.')
class Meta:
- description = 'Unassign an image from a variant.'
- model = models.VariantImage
+ description = 'Unassign an image from a product variant'
@classmethod
- def user_is_allowed(cls, user, input):
- return user.has_perm('product.manage_products')
+ @permission_required('product.manage_products')
+ def mutate(cls, root, info, image_id, variant_id):
+ errors = []
+ image = cls.get_node_or_error(
+ info, image_id, errors, 'imageId', ProductImage)
+ variant = cls.get_node_or_error(
+ info, variant_id, errors, 'variantId', ProductVariant)
+ if image and variant:
+ try:
+ variant_image = models.VariantImage.objects.get(
+ image=image, variant=variant)
+ except models.VariantImage.DoesNotExist:
+ cls.add_error(
+ errors, 'imageId', 'Image is not assigned to this variant.')
+ else:
+ variant_image.delete()
+ return VariantImageUnassign(image=image, errors=errors)
diff --git a/saleor/graphql/product/types.py b/saleor/graphql/product/types.py
index dfe23b8328..35da9e744f 100644
--- a/saleor/graphql/product/types.py
+++ b/saleor/graphql/product/types.py
@@ -98,6 +98,7 @@ class ProductVariant(CountableDjangoObjectType):
class Meta:
description = """Represents a version of a product such as different
size or color."""
+ exclude_fields = ['variant_images']
interfaces = [relay.Node]
model = models.ProductVariant
@@ -260,12 +261,14 @@ class Category(CountableDjangoObjectType):
class ProductImage(CountableDjangoObjectType):
url = graphene.String(
required=True,
- description='',
- size=graphene.Int(description='Size of image'))
+ description='The URL of the image.',
+ size=graphene.Int(description='Size of the image'))
class Meta:
description = 'Represents a product image.'
- exclude_fields = ['product', 'productvariant_set', 'variant_images']
+ exclude_fields = [
+ 'image', 'product', 'ppoi', 'productvariant_set',
+ 'variant_images']
interfaces = [relay.Node]
model = models.ProductImage
diff --git a/tests/api/test_product.py b/tests/api/test_product.py
index 65806d9ad0..5160ca622c 100644
--- a/tests/api/test_product.py
+++ b/tests/api/test_product.py
@@ -809,7 +809,6 @@ def test_product_image_create_mutation(admin_api_client, product):
productImageCreate(input: {image: $image, product: $product}) {
productImage {
id
- image
url
sortOrder
}
@@ -825,10 +824,8 @@ def test_product_image_create_mutation(admin_api_client, product):
content = get_graphql_content(response)
assert 'errors' not in content
data = content['data']['productImageCreate']
- file_name = data['productImage']['image']
product.refresh_from_db()
assert product.images.first().image.file
- assert product.images.first().image.name == file_name
def test_invalid_product_image_create_mutation(admin_api_client, product):
@@ -837,7 +834,6 @@ def test_invalid_product_image_create_mutation(admin_api_client, product):
productImageCreate(input: {image: $image, product: $product}) {
productImage {
id
- image
url
sortOrder
}
@@ -1116,15 +1112,15 @@ def test_remove_products_to_collection(
def test_assign_variant_image(admin_api_client, user_api_client, product_with_image):
query = """
- mutation assignVariantImageMutation($variant: ID!, $image: ID!) {
- variantImageAssign(input: {
- variant: $variant
- image: $image
- }) {
+ mutation assignVariantImageMutation($variantId: ID!, $imageId: ID!) {
+ variantImageAssign(variantId: $variantId, imageId: $imageId) {
errors {
field
message
}
+ image {
+ id
+ }
}
}
"""
@@ -1132,8 +1128,8 @@ def test_assign_variant_image(admin_api_client, user_api_client, product_with_im
image = product_with_image.images.first()
variables = json.dumps({
- 'variant': to_global_id('ProductVariant', variant.pk),
- 'image': to_global_id('ProductImage', image.pk)})
+ 'variantId': to_global_id('ProductVariant', variant.pk),
+ 'imageId': to_global_id('ProductImage', image.pk)})
response = admin_api_client.post(
reverse('api'), {'query': query, 'variables': variables})
content = get_graphql_content(response)
@@ -1147,12 +1143,57 @@ def test_assign_variant_image(admin_api_client, user_api_client, product_with_im
image_2 = ProductImage.objects.create(product=product_with_image)
variables = json.dumps({
- 'variant': to_global_id('ProductVariant', variant.pk),
- 'image': to_global_id('ProductImage', image_2.pk)})
+ 'variantId': to_global_id('ProductVariant', variant.pk),
+ 'imageId': to_global_id('ProductImage', image_2.pk)})
+ response = admin_api_client.post(
+ reverse('api'), {'query': query, 'variables': variables})
+ content = get_graphql_content(response)
+ assert content['data']['variantImageAssign']['errors'][0]['field'] == 'imageId'
+
+ # check permissions
+ response = user_api_client.post(
+ reverse('api'), {'query': query, 'variables': variables})
+ assert_no_permission(response)
+
+
+def test_unassign_variant_image(admin_api_client, user_api_client, product_with_image):
+ image = product_with_image.images.first()
+ variant = product_with_image.variants.first()
+ variant.variant_images.create(image=image)
+
+ query = """
+ mutation unassignVariantImageMutation($variantId: ID!, $imageId: ID!) {
+ variantImageUnassign(variantId: $variantId, imageId: $imageId) {
+ errors {
+ field
+ message
+ }
+ image {
+ id
+ }
+ }
+ }
+ """
+
+ variables = json.dumps({
+ 'variantId': to_global_id('ProductVariant', variant.pk),
+ 'imageId': to_global_id('ProductImage', image.pk)})
+ response = admin_api_client.post(
+ reverse('api'), {'query': query, 'variables': variables})
+ content = get_graphql_content(response)
+ assert 'errors' not in content
+ variant.refresh_from_db()
+ assert variant.images.count() == 0
+
+ # check that unsassigning a not assigned image throws error
+ image_2 = ProductImage.objects.create(product=product_with_image)
+ variables = json.dumps({
+ 'variantId': to_global_id('ProductVariant', variant.pk),
+ 'imageId': to_global_id('ProductImage', image_2.pk)})
response = admin_api_client.post(
reverse('api'), {'query': query, 'variables': variables})
content = get_graphql_content(response)
- assert content['data']['variantImageAssign']['errors'][0]['field'] == 'image'
+ assert content['data']['variantImageUnassign']['errors'][0]['field'] == 'imageId'
# check permissions
response = user_api_client.post(