Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Change reorder variants mutation to use newer reordering method
Tomasz Szymanskibe7dbf47011c
diff --git a/saleor/graphql/product/mutations/attributes.py b/saleor/graphql/product/mutations/attributes.pyindex 27f05f5ea5..b4f04ee050 100644--- a/saleor/graphql/product/mutations/attributes.py+++ b/saleor/graphql/product/mutations/attributes.py@@ -21,6 +21,7 @@ from ...product.types import ProductTypefrom ..descriptions import AttributeDescriptions, AttributeValueDescriptionsfrom ..enums import AttributeInputTypeEnum, AttributeTypeEnumfrom ..types import Attribute, AttributeValue+from .common import ReorderInputclass AttributeValueCreateInput(graphene.InputObjectType):@@ -96,17 +97,6 @@ class AttributeAssignInput(graphene.InputObjectType):)-class ReorderInput(graphene.InputObjectType):- id = graphene.ID(required=True, description="The ID of the item to move.")- sort_order = graphene.Int(- description=(- "The new relative sorting position of the item (from -inf to +inf). "- "1 moves the item one position forward, -1 moves the item one position "- "backward, 0 leaves the item unchanged."- )- )--class AttributeMixin:@classmethoddef check_values_are_unique(cls, values_input, attribute):diff --git a/saleor/graphql/product/mutations/common.py b/saleor/graphql/product/mutations/common.pynew file mode 100644index 0000000000..d39be7a233--- /dev/null+++ b/saleor/graphql/product/mutations/common.py@@ -0,0 +1,12 @@+import graphene+++class ReorderInput(graphene.InputObjectType):+ id = graphene.ID(required=True, description="The ID of the item to move.")+ sort_order = graphene.Int(+ description=(+ "The new relative sorting position of the item (from -inf to +inf). "+ "1 moves the item one position forward, -1 moves the item one position "+ "backward, 0 leaves the item unchanged."+ )+ )diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.pyindex 57383543e4..02e71a905e 100644--- a/saleor/graphql/product/mutations/products.py+++ b/saleor/graphql/product/mutations/products.py@@ -60,6 +60,7 @@ from ..utils import (validate_attribute_input_for_product,validate_attribute_input_for_variant,)+from .common import ReorderInputclass CategoryInput(graphene.InputObjectType):@@ -1786,63 +1787,64 @@ class ProductImageReorder(BaseMutation):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,+ moves = graphene.List(+ ReorderInput,required=True,- description="IDs of a product variants in the desired order.",+ description="The list of variant reordering operations.",)class Meta:- description = "Changes ordering of the product variants."+ description = "Reorder the variants of a product."permissions = (ProductPermissions.MANAGE_PRODUCTS,)error_type_class = ProductErrorerror_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- )+ def perform_mutation(cls, _root, info, product_id, moves):+ pk = from_global_id_strict_type(product_id, only_type=Product, field="id")- if len(variants) != product.variants.count():+ try:+ product = models.Product.objects.prefetch_related("variants").get(pk=pk)+ except ObjectDoesNotExist:raise ValidationError({- "order": ValidationError(- "Incorrect number of variant IDs provided.",- code=ProductErrorCode.INVALID,+ "product_id": ValidationError(+ (f"Couldn't resolve to a product type: {product_id}"),+ code=ProductErrorCode.NOT_FOUND,)})- ordered_variants = []- for variant_id in variants:- variant = cls.get_node_or_error(- info, variant_id, field="order", only_type=ProductVariant+ variants_m2m = product.variants+ operations = {}++ for move_info in moves:+ variant_pk = from_global_id_strict_type(+ move_info.id, only_type=ProductVariant, field="moves")- if variant and variant.product != product:++ try:+ m2m_info = variants_m2m.get(id=int(variant_pk))+ except ObjectDoesNotExist:raise ValidationError({- "order": ValidationError(- "Variant %(variant_id) does not belong to this product.",- code=ProductErrorCode.NOT_PRODUCTS_VARIANT,- params={"variant_id": variant.id},+ "moves": ValidationError(+ f"Couldn't resolve to a variant: {move_info.id}",+ code=ProductErrorCode.NOT_FOUND,)})- ordered_variants.append(variant)-- for _order, variant in enumerate(ordered_variants):- variant.sort_order = _order- variant.save(update_fields=["sort_order"])+ operations[m2m_info.pk] = move_info.sort_order- return ProductVariantReorder(product=product, variants=ordered_variants)+ with transaction.atomic():+ perform_reordering(variants_m2m, operations)+ return ProductVariantReorder(product=product)class ProductImageDelete(BaseMutation):diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.pyindex b2e7bb9b12..3deb02e366 100644--- a/saleor/graphql/product/tests/test_product.py+++ b/saleor/graphql/product/tests/test_product.py@@ -1403,10 +1403,11 @@ def test_create_product(REORDER_PRODUCT_VARIANTS_MUTATION = """- mutation ProductVariantReorder($product:ID!, $variants: [ID]!) {- productVariantReorder(productId: $product, variants:$variants) {+ mutation ProductVariantReorder($product: ID!, $moves: [ReorderInput]!) {+ productVariantReorder(productId: $product, moves: $moves) {productErrors {code+ field}}}@@ -1421,9 +1422,12 @@ def test_reorder_variants(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+ "moves": [+ {+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),+ "sortOrder": _order + 1,+ }+ for _order, variant in enumerate(new_variants)],}@@ -1438,26 +1442,6 @@ def test_reorder_variants(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,):@@ -1466,9 +1450,12 @@ def test_reorder_variants_invalid_variants(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+ "moves": [+ {+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),+ "sortOrder": _order + 1,+ }+ for _order, variant in enumerate(new_variants)],}@@ -1479,9 +1466,8 @@ def test_reorder_variants_invalid_variants()content = get_graphql_content(response)data = content["data"]["productVariantReorder"]- assert (- data["productErrors"][0]["code"] == ProductErrorCode.NOT_PRODUCTS_VARIANT.name- )+ assert data["productErrors"][0]["field"] == "moves"+ assert data["productErrors"][0]["code"] == ProductErrorCode.NOT_FOUND.name@pytest.mark.parametrize("input_slug", ["", None])diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 635705472a..abe05671b3 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -2640,7 +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]!): ProductVariantReorder+ productVariantReorder(moves: [ReorderInput]!, productId: ID!): ProductVariantReorderproductImageDelete(id: ID!): ProductImageDeleteproductImageBulkDelete(ids: [ID]!): ProductImageBulkDeleteproductImageReorder(imagesIds: [ID]!, productId: ID!): ProductImageReorder@@ -3753,7 +3753,6 @@ enum ProductErrorCode {GRAPHQL_ERRORINVALIDNOT_PRODUCTS_IMAGE- NOT_PRODUCTS_VARIANTNOT_FOUNDREQUIREDUNIQUE@@ -4180,7 +4179,6 @@ input ProductVariantInput {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!]!}diff --git a/saleor/product/error_codes.py b/saleor/product/error_codes.pyindex 534c2b0356..32fe5e7b03 100644--- a/saleor/product/error_codes.py+++ b/saleor/product/error_codes.py@@ -10,7 +10,6 @@ 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"