Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Mutation and model changes to allow product variant sorting
Tomasz Szymanskieac861bf8ae9
diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.pyindex ce3f1d2044..57383543e4 100644--- a/saleor/graphql/product/mutations/products.py+++ b/saleor/graphql/product/mutations/products.py@@ -1784,6 +1784,67 @@ class ProductImageReorder(BaseMutation):return ProductImageReorder(product=product, images=images)+class ProductVariantReorder(BaseMutation):+ product = graphene.Field(Product)+ variants = graphene.List(ProductVariant)++ class Arguments:+ product_id = graphene.ID(+ required=True,+ description="Id of product that variants order will be altered.",+ )+ variants = graphene.List(+ graphene.ID,+ required=True,+ description="IDs of a product variants in the desired order.",+ )++ class Meta:+ description = "Changes ordering of the product variants."+ permissions = (ProductPermissions.MANAGE_PRODUCTS,)+ error_type_class = ProductError+ error_type_field = "product_errors"++ @classmethod+ def perform_mutation(cls, _root, info, product_id, variants):+ product = cls.get_node_or_error(+ info, product_id, field="product_id", only_type=Product+ )++ if len(variants) != product.variants.count():+ raise ValidationError(+ {+ "order": ValidationError(+ "Incorrect number of variant IDs provided.",+ code=ProductErrorCode.INVALID,+ )+ }+ )++ ordered_variants = []+ for variant_id in variants:+ variant = cls.get_node_or_error(+ info, variant_id, field="order", only_type=ProductVariant+ )+ if variant and variant.product != product:+ raise ValidationError(+ {+ "order": ValidationError(+ "Variant %(variant_id) does not belong to this product.",+ code=ProductErrorCode.NOT_PRODUCTS_VARIANT,+ params={"variant_id": variant.id},+ )+ }+ )+ ordered_variants.append(variant)++ for _order, variant in enumerate(ordered_variants):+ variant.sort_order = _order+ variant.save(update_fields=["sort_order"])++ return ProductVariantReorder(product=product, variants=ordered_variants)++class ProductImageDelete(BaseMutation):product = graphene.Field(Product)image = graphene.Field(ProductImage)diff --git a/saleor/graphql/product/schema.py b/saleor/graphql/product/schema.pyindex 0f9e5ce76b..088cb2f074 100644--- a/saleor/graphql/product/schema.py+++ b/saleor/graphql/product/schema.py@@ -99,6 +99,7 @@ from .mutations.products import (ProductVariantClearPrivateMeta,ProductVariantCreate,ProductVariantDelete,+ ProductVariantReorder,ProductVariantUpdate,ProductVariantUpdateMeta,ProductVariantUpdatePrivateMeta,@@ -443,6 +444,7 @@ class ProductMutations(graphene.ObjectType):product_set_availability_for_purchase = ProductSetAvailabilityForPurchase.Field()product_image_create = ProductImageCreate.Field()+ product_variant_reorder = ProductVariantReorder.Field()product_image_delete = ProductImageDelete.Field()product_image_bulk_delete = ProductImageBulkDelete.Field()product_image_reorder = ProductImageReorder.Field()diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.pyindex 7412f085b9..b2e7bb9b12 100644--- a/saleor/graphql/product/tests/test_product.py+++ b/saleor/graphql/product/tests/test_product.py@@ -1402,6 +1402,88 @@ def test_create_product(assert color_value_slug in values+REORDER_PRODUCT_VARIANTS_MUTATION = """+ mutation ProductVariantReorder($product:ID!, $variants: [ID]!) {+ productVariantReorder(productId: $product, variants:$variants) {+ productErrors {+ code+ }+ }+ }+"""+++def test_reorder_variants(+ staff_api_client, product_with_two_variants, permission_manage_products,+):+ default_variants = product_with_two_variants.variants.all()+ new_variants = [default_variants[1], default_variants[0]]++ variables = {+ "product": graphene.Node.to_global_id("Product", product_with_two_variants.pk),+ "variants": [+ graphene.Node.to_global_id("ProductVariant", variant.pk)+ for variant in new_variants+ ],+ }++ response = staff_api_client.post_graphql(+ REORDER_PRODUCT_VARIANTS_MUTATION,+ variables,+ permissions=[permission_manage_products],+ )+ content = get_graphql_content(response)+ data = content["data"]["productVariantReorder"]+ assert not data["productErrors"]+ assert list(product_with_two_variants.variants.all()) == new_variants+++def test_reorder_variants_not_enough_variants(+ staff_api_client, product_with_two_variants, permission_manage_products,+):+ first_variant = product_with_two_variants.variants.first()++ variables = {+ "product": graphene.Node.to_global_id("Product", product_with_two_variants.pk),+ "variants": [graphene.Node.to_global_id("ProductVariant", first_variant.pk)],+ }++ response = staff_api_client.post_graphql(+ REORDER_PRODUCT_VARIANTS_MUTATION,+ variables,+ permissions=[permission_manage_products],+ )+ content = get_graphql_content(response)+ data = content["data"]["productVariantReorder"]+ assert data["productErrors"][0]["code"] == ProductErrorCode.INVALID.name+++def test_reorder_variants_invalid_variants(+ staff_api_client, product, product_with_two_variants, permission_manage_products,+):+ default_variants = product_with_two_variants.variants.all()+ new_variants = [product.variants.first(), default_variants[1]]++ variables = {+ "product": graphene.Node.to_global_id("Product", product_with_two_variants.pk),+ "variants": [+ graphene.Node.to_global_id("ProductVariant", variant.pk)+ for variant in new_variants+ ],+ }++ response = staff_api_client.post_graphql(+ REORDER_PRODUCT_VARIANTS_MUTATION,+ variables,+ permissions=[permission_manage_products],+ )+ content = get_graphql_content(response)+ data = content["data"]["productVariantReorder"]+ assert (+ data["productErrors"][0]["code"] == ProductErrorCode.NOT_PRODUCTS_VARIANT.name+ )++@pytest.mark.parametrize("input_slug", ["", None])def test_create_product_no_slug_in_input(staff_api_client,diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex a221f65d5d..635705472a 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -2640,6 +2640,7 @@ type Mutation {productClearPrivateMetadata(id: ID!, input: MetaPath!): ProductClearPrivateMeta @deprecated(reason: "Use the `deletePrivateMetadata` mutation instead. This field will be removed after 2020-07-31.")productSetAvailabilityForPurchase(isAvailable: Boolean!, productId: ID!, startDate: Date): ProductSetAvailabilityForPurchaseproductImageCreate(input: ProductImageCreateInput!): ProductImageCreate+ productVariantReorder(productId: ID!, variants: [ID]!): ProductVariantReorderproductImageDelete(id: ID!): ProductImageDeleteproductImageBulkDelete(ids: [ID]!): ProductImageBulkDeleteproductImageReorder(imagesIds: [ID]!, productId: ID!): ProductImageReorder@@ -3752,6 +3753,7 @@ enum ProductErrorCode {GRAPHQL_ERRORINVALIDNOT_PRODUCTS_IMAGE+ NOT_PRODUCTS_VARIANTNOT_FOUNDREQUIREDUNIQUE@@ -4175,6 +4177,13 @@ input ProductVariantInput {weight: WeightScalar}+type ProductVariantReorder {+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")+ product: Product+ variants: [ProductVariant]+ productErrors: [ProductError!]!+}+type ProductVariantStocksCreate {errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")productVariant: ProductVariantdiff --git a/saleor/product/error_codes.py b/saleor/product/error_codes.pyindex 32fe5e7b03..534c2b0356 100644--- a/saleor/product/error_codes.py+++ b/saleor/product/error_codes.py@@ -10,6 +10,7 @@ class ProductErrorCode(Enum):GRAPHQL_ERROR = "graphql_error"INVALID = "invalid"NOT_PRODUCTS_IMAGE = "not_products_image"+ NOT_PRODUCTS_VARIANT = "not_products_variant"NOT_FOUND = "not_found"REQUIRED = "required"UNIQUE = "unique"diff --git a/saleor/product/migrations/0125_auto_20200916_1511.py b/saleor/product/migrations/0125_auto_20200916_1511.pynew file mode 100644index 0000000000..57007eb5f3--- /dev/null+++ b/saleor/product/migrations/0125_auto_20200916_1511.py@@ -0,0 +1,21 @@+# Generated by Django 3.1.1 on 2020-09-16 15:11++from django.db import migrations, models+++class Migration(migrations.Migration):++ dependencies = [+ ("product", "0124_auto_20200909_0904"),+ ]++ operations = [+ migrations.AlterModelOptions(+ name="productvariant", options={"ordering": ("sort_order", "sku")},+ ),+ migrations.AddField(+ model_name="productvariant",+ name="sort_order",+ field=models.IntegerField(db_index=True, editable=False, null=True),+ ),+ ]diff --git a/saleor/product/models.py b/saleor/product/models.pyindex 95048858dd..5312113cad 100644--- a/saleor/product/models.py+++ b/saleor/product/models.py@@ -374,7 +374,7 @@ class ProductVariantQueryset(models.QuerySet):return variants-class ProductVariant(ModelWithMetadata):+class ProductVariant(SortableModel, ModelWithMetadata):sku = models.CharField(max_length=255, unique=True)name = models.CharField(max_length=255, blank=True)currency = models.CharField(@@ -409,7 +409,7 @@ class ProductVariant(ModelWithMetadata):translated = TranslationProxy()class Meta:- ordering = ("sku",)+ ordering = ("sort_order", "sku")app_label = "product"def __str__(self) -> str:@@ -453,6 +453,9 @@ class ProductVariant(ModelWithMetadata):images = list(self.images.all())return images[0] if images else self.product.get_first_image()+ def get_ordering_queryset(self):+ return self.product.variants.all()+class ProductVariantTranslation(models.Model):language_code = models.CharField(max_length=10)