Skip to content

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

Allow sorting assigned references (#6603)

Iga Karbowiak96e4a8d16f29
diff --git a/saleor/attribute/migrations/0005_add_assignedattributevalues.py b/saleor/attribute/migrations/0005_add_assignedattributevalues.py
new file mode 100644
index 0000000000..7df71da317
--- /dev/null
+++ b/saleor/attribute/migrations/0005_add_assignedattributevalues.py
@@ -0,0 +1,216 @@
+# Generated by Django 3.1.3 on 2020-12-09 10:30
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+
+def create_through_product_relations(apps, schema_editor):
+ AssignedProductAttribute = apps.get_model("attribute", "AssignedProductAttribute")
+ AssignedProductAttributeValue = apps.get_model(
+ "attribute", "AssignedProductAttributeValue"
+ )
+ for assignment in AssignedProductAttribute.objects.iterator():
+ instances = []
+ for value in assignment.values.all():
+ instances.append(
+ AssignedProductAttributeValue(value=value, assignment=assignment)
+ )
+ AssignedProductAttributeValue.objects.bulk_create(instances)
+
+
+def create_through_variant_relations(apps, schema_editor):
+ AssignedVariantAttribute = apps.get_model("attribute", "AssignedVariantAttribute")
+ AssignedVariantAttributeValue = apps.get_model(
+ "attribute", "AssignedVariantAttributeValue"
+ )
+ for assignment in AssignedVariantAttribute.objects.iterator():
+ instances = []
+ for value in assignment.values.all():
+ instances.append(
+ AssignedVariantAttributeValue(value=value, assignment=assignment)
+ )
+ AssignedVariantAttributeValue.objects.bulk_create(instances)
+
+
+def create_through_page_relations(apps, schema_editor):
+ AssignedPageAttribute = apps.get_model("attribute", "AssignedPageAttribute")
+ AssignedPageAttributeValue = apps.get_model(
+ "attribute", "AssignedPageAttributeValue"
+ )
+ for assignment in AssignedPageAttribute.objects.iterator():
+ instances = []
+ for value in assignment.values.all():
+ instances.append(
+ AssignedPageAttributeValue(value=value, assignment=assignment)
+ )
+ AssignedPageAttributeValue.objects.bulk_create(instances)
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("attribute", "0004_auto_20201204_1325"),
+ ]
+
+ operations = [
+ # create new through models
+ migrations.CreateModel(
+ name="AssignedProductAttributeValue",
+ fields=[
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ (
+ "sort_order",
+ models.IntegerField(db_index=True, editable=False, null=True),
+ ),
+ (
+ "assignment",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="productvalueassignment",
+ to="attribute.assignedproductattribute",
+ ),
+ ),
+ (
+ "value",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="productvalueassignment",
+ to="attribute.attributevalue",
+ ),
+ ),
+ ],
+ options={
+ "ordering": ("sort_order", "pk"),
+ "unique_together": {("value", "assignment")},
+ },
+ ),
+ migrations.CreateModel(
+ name="AssignedVariantAttributeValue",
+ fields=[
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ (
+ "sort_order",
+ models.IntegerField(db_index=True, editable=False, null=True),
+ ),
+ (
+ "assignment",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="variantvalueassignment",
+ to="attribute.assignedvariantattribute",
+ ),
+ ),
+ (
+ "value",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="variantvalueassignment",
+ to="attribute.attributevalue",
+ ),
+ ),
+ ],
+ options={
+ "ordering": ("sort_order", "pk"),
+ "unique_together": {("value", "assignment")},
+ },
+ ),
+ migrations.CreateModel(
+ name="AssignedPageAttributeValue",
+ fields=[
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ (
+ "sort_order",
+ models.IntegerField(db_index=True, editable=False, null=True),
+ ),
+ (
+ "assignment",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="pagevalueassignment",
+ to="attribute.assignedpageattribute",
+ ),
+ ),
+ (
+ "value",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="pagevalueassignment",
+ to="attribute.attributevalue",
+ ),
+ ),
+ ],
+ options={
+ "ordering": ("sort_order", "pk"),
+ "unique_together": {("value", "assignment")},
+ },
+ ),
+ # migrate existing data to through model
+ migrations.RunPython(
+ create_through_product_relations, reverse_code=migrations.RunPython.noop
+ ),
+ migrations.RunPython(
+ create_through_variant_relations, reverse_code=migrations.RunPython.noop
+ ),
+ migrations.RunPython(
+ create_through_page_relations, reverse_code=migrations.RunPython.noop
+ ),
+ # remove current `values` relations
+ migrations.RemoveField(model_name="assignedproductattribute", name="values",),
+ migrations.RemoveField(model_name="assignedvariantattribute", name="values",),
+ migrations.RemoveField(model_name="assignedpageattribute", name="values",),
+ # create new values relations with use of through models
+ migrations.AddField(
+ model_name="assignedproductattribute",
+ name="values",
+ field=models.ManyToManyField(
+ blank=True,
+ related_name="productassignments",
+ through="attribute.AssignedProductAttributeValue",
+ to="attribute.AttributeValue",
+ ),
+ ),
+ migrations.AddField(
+ model_name="assignedvariantattribute",
+ name="values",
+ field=models.ManyToManyField(
+ blank=True,
+ related_name="variantassignments",
+ through="attribute.AssignedVariantAttributeValue",
+ to="attribute.AttributeValue",
+ ),
+ ),
+ migrations.AddField(
+ model_name="assignedpageattribute",
+ name="values",
+ field=models.ManyToManyField(
+ blank=True,
+ related_name="pageassignments",
+ through="attribute.AssignedPageAttributeValue",
+ to="attribute.AttributeValue",
+ ),
+ ),
+ ]
diff --git a/saleor/attribute/models/__init__.py b/saleor/attribute/models/__init__.py
new file mode 100644
index 0000000000..d7b1f64844
--- /dev/null
+++ b/saleor/attribute/models/__init__.py
@@ -0,0 +1,33 @@
+from .base import (
+ Attribute,
+ AttributeTranslation,
+ AttributeValue,
+ AttributeValueTranslation,
+)
+from .page import AssignedPageAttribute, AssignedPageAttributeValue, AttributePage
+from .product import (
+ AssignedProductAttribute,
+ AssignedProductAttributeValue,
+ AttributeProduct,
+)
+from .product_variant import (
+ AssignedVariantAttribute,
+ AssignedVariantAttributeValue,
+ AttributeVariant,
+)
+
+__all__ = [
+ "Attribute",
+ "AttributeTranslation",
+ "AttributeValue",
+ "AttributeValueTranslation",
+ "AssignedPageAttribute",
+ "AssignedPageAttributeValue",
+ "AttributePage",
+ "AssignedProductAttribute",
+ "AssignedProductAttributeValue",
+ "AttributeProduct",
+ "AssignedVariantAttribute",
+ "AssignedVariantAttributeValue",
+ "AttributeVariant",
+]
diff --git a/saleor/attribute/models.py b/saleor/attribute/models/base.py
similarity index 62%
rename from saleor/attribute/models.py
rename to saleor/attribute/models/base.py
index 3db58606ca..016468f6b2 100644
--- a/saleor/attribute/models.py
+++ b/saleor/attribute/models/base.py
@@ -3,35 +3,20 @@ from typing import TYPE_CHECKING, Union
from django.db import models
from django.db.models import F, Q
-from ..core.models import ModelWithMetadata, SortableModel
-from ..core.permissions import ProductPermissions
-from ..core.utils.translations import TranslationProxy
-from ..page.models import Page, PageType
-from ..product.models import Product, ProductType, ProductVariant
-from . import AttributeEntityType, AttributeInputType, AttributeType
+from ...core.models import ModelWithMetadata, SortableModel
+from ...core.permissions import ProductPermissions
+from ...core.utils.translations import TranslationProxy
+from ...page.models import PageType
+from ...product.models import ProductType
+from .. import AttributeEntityType, AttributeInputType, AttributeType
if TYPE_CHECKING:
- from ..account.models import User
+ from ...account.models import User
from django.db.models import OrderBy
-class BaseAttributeQuerySet(models.QuerySet):
- @staticmethod
- def user_has_access_to_all(user: "User") -> bool:
- return user.is_active and user.has_perm(ProductPermissions.MANAGE_PRODUCTS)
-
- def get_public_attributes(self):
- raise NotImplementedError
-
- def get_visible_to_user(self, user: "User"):
- if self.user_has_access_to_all(user):
- return self.all()
- return self.get_public_attributes()
-
-
class BaseAssignedAttribute(models.Model):
assignment = None
- values = models.ManyToManyField("AttributeValue")
class Meta:
abstract = True
@@ -45,44 +30,18 @@ class BaseAssignedAttribute(models.Model):
return self.assignment.attribute_id
-class AssignedProductAttribute(BaseAssignedAttribute):
- """Associate a product type attribute and selected values to a given product."""
-
- product = models.ForeignKey(
- Product, related_name="attributes", on_delete=models.CASCADE
- )
- assignment = models.ForeignKey(
- "AttributeProduct", on_delete=models.CASCADE, related_name="productassignments"
- )
-
- class Meta:
- unique_together = (("product", "assignment"),)
-
-
-class AssignedVariantAttribute(BaseAssignedAttribute):
- """Associate a product type attribute and selected values to a given variant."""
-
- variant = models.ForeignKey(
- ProductVariant, related_name="attributes", on_delete=models.CASCADE
- )
- assignment = models.ForeignKey(
- "AttributeVariant", on_delete=models.CASCADE, related_name="variantassignments"
- )
-
- class Meta:
- unique_together = (("variant", "assignment"),)
-
-
-class AssignedPageAttribute(BaseAssignedAttribute):
- """Associate a page type attribute and selected values to a given page."""
+class BaseAttributeQuerySet(models.QuerySet):
+ @staticmethod
+ def user_has_access_to_all(user: "User") -> bool:
+ return user.is_active and user.has_perm(ProductPermissions.MANAGE_PRODUCTS)
- page = models.ForeignKey(Page, related_name="attributes", on_delete=models.CASCADE)
- assignment = models.ForeignKey(
- "AttributePage", on_delete=models.CASCADE, related_name="pageassignments"
- )
+ def get_public_attributes(self):
+ raise NotImplementedError
- class Meta:
- unique_together = (("page", "assignment"),)
+ def get_visible_to_user(self, user: "User"):
+ if self.user_has_access_to_all(user):
+ return self.all()
+ return self.get_public_attributes()
class AssociatedAttributeQuerySet(BaseAttributeQuerySet):
@@ -90,81 +49,6 @@ class AssociatedAttributeQuerySet(BaseAttributeQuerySet):
return self.filter(attribute__visible_in_storefront=True)
-class AttributeProduct(SortableModel):
- attribute = models.ForeignKey(
- "Attribute", related_name="attributeproduct", on_delete=models.CASCADE
- )
- product_type = models.ForeignKey(
- ProductType, related_name="attributeproduct", on_delete=models.CASCADE
- )
- assigned_products = models.ManyToManyField(
- Product,
- blank=True,
- through=AssignedProductAttribute,
- through_fields=("assignment", "product"),
- related_name="attributesrelated",
- )
-
- objects = AssociatedAttributeQuerySet.as_manager()
-
- class Meta:
- unique_together = (("attribute", "product_type"),)
- ordering = ("sort_order", "pk")
-
- def get_ordering_queryset(self):
- return self.product_type.attributeproduct.all()
-
-
-class AttributeVariant(SortableModel):
- attribute = models.ForeignKey(
- "Attribute", related_name="attributevariant", on_delete=models.CASCADE
- )
- product_type = models.ForeignKey(
- ProductType, related_name="attributevariant", on_delete=models.CASCADE
- )
- assigned_variants = models.ManyToManyField(
- ProductVariant,
- blank=True,
- through=AssignedVariantAttribute,
- through_fields=("assignment", "variant"),
- related_name="attributesrelated",
- )
-
- objects = AssociatedAttributeQuerySet.as_manager()
-
- class Meta:
- unique_together = (("attribute", "product_type"),)
- ordering = ("sort_order", "pk")
-
- def get_ordering_queryset(self):
- return self.product_type.attributevariant.all()
-
-
-class AttributePage(SortableModel):
- attribute = models.ForeignKey(
- "Attribute", related_name="attributepage", on_delete=models.CASCADE
- )
- page_type = models.ForeignKey(
- PageType, related_name="attributepage", on_delete=models.CASCADE
- )
- assigned_pages = models.ManyToManyField(
- Page,
- blank=True,
- through=AssignedPageAttribute,
- through_fields=("assignment", "page"),
- related_name="attributesrelated",
- )
-
- objects = AssociatedAttributeQuerySet.as_manager()
-
- class Meta:
- unique_together = (("attribute", "page_type"),)
- ordering = ("sort_order", "pk")
-
- def get_ordering_queryset(self):
- return self.page_type.attributepage.all()
-
-
class AttributeQuerySet(BaseAttributeQuerySet):
def get_unassigned_product_type_attributes(self, product_type_pk: int):
return self.product_type_attributes().exclude(
@@ -234,21 +118,21 @@ class Attribute(ModelWithMetadata):
ProductType,
blank=True,
related_name="product_attributes",
- through=AttributeProduct,
+ through="AttributeProduct",
through_fields=("attribute", "product_type"),
)
product_variant_types = models.ManyToManyField(
ProductType,
blank=True,
related_name="variant_attributes",
- through=AttributeVariant,
+ through="AttributeVariant",
through_fields=("attribute", "product_type"),
)
page_types = models.ManyToManyField(
PageType,
blank=True,
related_name="page_attributes",
- through=AttributePage,
+ through="AttributePage",
through_fields=("attribute", "page_type"),
)
diff --git a/saleor/attribute/models/page.py b/saleor/attribute/models/page.py
new file mode 100644
index 0000000000..87bdedb6b9
--- /dev/null
+++ b/saleor/attribute/models/page.py
@@ -0,0 +1,66 @@
+from django.db import models
+
+from ...core.models import SortableModel
+from ...page.models import Page, PageType
+from .base import AssociatedAttributeQuerySet, BaseAssignedAttribute
+
+
+class AssignedPageAttributeValue(SortableModel):
+ value = models.ForeignKey(
+ "AttributeValue", on_delete=models.CASCADE, related_name="pagevalueassignment",
+ )
+ assignment = models.ForeignKey(
+ "AssignedPageAttribute",
+ on_delete=models.CASCADE,
+ related_name="pagevalueassignment",
+ )
+
+ class Meta:
+ unique_together = (("value", "assignment"),)
+ ordering = ("sort_order", "pk")
+
+ def get_ordering_queryset(self):
+ return self.assignment.pagevalueassignment.all()
+
+
+class AssignedPageAttribute(BaseAssignedAttribute):
+ """Associate a page type attribute and selected values to a given page."""
+
+ page = models.ForeignKey(Page, related_name="attributes", on_delete=models.CASCADE)
+ assignment = models.ForeignKey(
+ "AttributePage", on_delete=models.CASCADE, related_name="pageassignments"
+ )
+ values = models.ManyToManyField(
+ "AttributeValue",
+ blank=True,
+ related_name="pageassignments",
+ through=AssignedPageAttributeValue,
+ )
+
+ class Meta:
+ unique_together = (("page", "assignment"),)
+
+
+class AttributePage(SortableModel):
+ attribute = models.ForeignKey(
+ "Attribute", related_name="attributepage", on_delete=models.CASCADE
+ )
+ page_type = models.ForeignKey(
+ PageType, related_name="attributepage", on_delete=models.CASCADE
+ )
+ assigned_pages = models.ManyToManyField(
+ Page,
+ blank=True,
+ through=AssignedPageAttribute,
+ through_fields=("assignment", "page"),
+ related_name="attributesrelated",
+ )
+
+ objects = AssociatedAttributeQuerySet.as_manager()
+
+ class Meta:
+ unique_together = (("attribute", "page_type"),)
+ ordering = ("sort_order", "pk")
+
+ def get_ordering_queryset(self):
+ return self.page_type.attributepage.all()
diff --git a/saleor/attribute/models/product.py b/saleor/attribute/models/product.py
new file mode 100644
index 0000000000..d85302c2cf
--- /dev/null
+++ b/saleor/attribute/models/product.py
@@ -0,0 +1,70 @@
+from django.db import models
+
+from ...core.models import SortableModel
+from ...product.models import Product, ProductType
+from .base import AssociatedAttributeQuerySet, BaseAssignedAttribute
+
+
+class AssignedProductAttributeValue(SortableModel):
+ value = models.ForeignKey(
+ "AttributeValue",
+ on_delete=models.CASCADE,
+ related_name="productvalueassignment",
+ )
+ assignment = models.ForeignKey(
+ "AssignedProductAttribute",
+ on_delete=models.CASCADE,
+ related_name="productvalueassignment",
+ )
+
+ class Meta:
+ unique_together = (("value", "assignment"),)
+ ordering = ("sort_order", "pk")
+
+ def get_ordering_queryset(self):
+ return self.assignment.productvalueassignment.all()
+
+
+class AssignedProductAttribute(BaseAssignedAttribute):
+ """Associate a product type attribute and selected values to a given product."""
+
+ product = models.ForeignKey(
+ Product, related_name="attributes", on_delete=models.CASCADE
+ )
+ assignment = models.ForeignKey(
+ "AttributeProduct", on_delete=models.CASCADE, related_name="productassignments"
+ )
+ values = models.ManyToManyField(
+ "AttributeValue",
+ blank=True,
+ related_name="productassignments",
+ through=AssignedProductAttributeValue,
+ )
+
+ class Meta:
+ unique_together = (("product", "assignment"),)
+
+
+class AttributeProduct(SortableModel):
+ attribute = models.ForeignKey(
+ "Attribute", related_name="attributeproduct", on_delete=models.CASCADE
+ )
+ product_type = models.ForeignKey(
+ ProductType, related_name="attributeproduct", on_delete=models.CASCADE
+ )
+ assigned_products = models.ManyToManyField(
+ Product,
+ blank=True,
+ through=AssignedProductAttribute,
+ through_fields=("assignment", "product"),
+ related_name="attributesrelated",
+ )
+
+ objects = AssociatedAttributeQuerySet.as_manager()
+
+ class Meta:
+ unique_together = (("attribute", "product_type"),)
+ ordering = ("sort_order", "pk")
+
+ def get_ordering_queryset(self):
+ return self.product_type.attributeproduct.all()
diff --git a/saleor/attribute/models/product_variant.py b/saleor/attribute/models/product_variant.py
new file mode 100644
index 0000000000..37437c2b14
--- /dev/null
+++ b/saleor/attribute/models/product_variant.py
@@ -0,0 +1,70 @@
+from django.db import models
+
+from ...core.models import SortableModel
+from ...product.models import ProductType, ProductVariant
+from .base import AssociatedAttributeQuerySet, BaseAssignedAttribute
+
+
+class AssignedVariantAttributeValue(SortableModel):
+ value = models.ForeignKey(
+ "AttributeValue",
+ on_delete=models.CASCADE,
+ related_name="variantvalueassignment",
+ )
+ assignment = models.ForeignKey(
+ "AssignedVariantAttribute",
+ on_delete=models.CASCADE,
+ related_name="variantvalueassignment",
+ )
+
+ class Meta:
+ unique_together = (("value", "assignment"),)
+ ordering = ("sort_order", "pk")
+
+ def get_ordering_queryset(self):
+ return self.assignment.variantvalueassignment.all()
+
+
+class AssignedVariantAttribute(BaseAssignedAttribute):
+ """Associate a product type attribute and selected values to a given variant."""
+
+ variant = models.ForeignKey(
+ ProductVariant, related_name="attributes", on_delete=models.CASCADE
+ )
+ assignment = models.ForeignKey(
+ "AttributeVariant", on_delete=models.CASCADE, related_name="variantassignments"
+ )
+ values = models.ManyToManyField(
+ "AttributeValue",
+ blank=True,
+ related_name="variantassignments",
+ through=AssignedVariantAttributeValue,
+ )
+
+ class Meta:
+ unique_together = (("variant", "assignment"),)
+
+
+class AttributeVariant(SortableModel):
+ attribute = models.ForeignKey(
+ "Attribute", related_name="attributevariant", on_delete=models.CASCADE
+ )
+ product_type = models.ForeignKey(
+ ProductType, related_name="attributevariant", on_delete=models.CASCADE
+ )
+ assigned_variants = models.ManyToManyField(
+ ProductVariant,
+ blank=True,
+ through=AssignedVariantAttribute,
+ through_fields=("assignment", "variant"),
+ related_name="attributesrelated",
+ )
+
+ objects = AssociatedAttributeQuerySet.as_manager()
+
+ class Meta:
+ unique_together = (("attribute", "product_type"),)
+ ordering = ("sort_order", "pk")
+
+ def get_ordering_queryset(self):
+ return self.product_type.attributevariant.all()
diff --git a/saleor/attribute/tests/test_utils.py b/saleor/attribute/tests/test_utils.py
index 3d093bdde5..37a06a7c60 100644
--- a/saleor/attribute/tests/test_utils.py
+++ b/saleor/attribute/tests/test_utils.py
@@ -1,6 +1,6 @@
import pytest
-from ..models import ProductType
+from ...product.models import ProductType
from ..utils import associate_attribute_values_to_instance
diff --git a/saleor/graphql/attribute/mutations.py b/saleor/graphql/attribute/mutations.py
index 59a1cff6b0..e99d9f11dc 100644
--- a/saleor/graphql/attribute/mutations.py
+++ b/saleor/graphql/attribute/mutations.py
@@ -80,6 +80,104 @@ class BaseReorderAttributesMutation(BaseMutation):
return operations
+class BaseReorderAttributeValuesMutation(BaseMutation):
+ class Meta:
+ abstract = True
+
+ @classmethod
+ def perform(cls, instance_id: str, instance_type: str, data: dict, error_code_enum):
+ attribute_id = data["attribute_id"]
+ moves = data["moves"]
+
+ instance = cls.get_instance(instance_id)
+ attribute_assignment = cls.get_attribute_assignment(
+ instance, instance_type, attribute_id, error_code_enum
+ )
+ values_m2m = getattr(attribute_assignment, "values")
+
+ try:
+ operations = cls.prepare_operations(moves, values_m2m)
+ except ValidationError as error:
+ error.code = error_code_enum.NOT_FOUND.value
+ raise ValidationError({"moves": error})
+
+ with transaction.atomic():
+ perform_reordering(values_m2m, operations)
+
+ return instance
+
+ @staticmethod
+ def get_instance(instance_id: str):
+ pass
+
+ @staticmethod
+ def get_attribute_assignment(
+ instance, instance_type, attribute_id: str, error_code_enum
+ ):
+ attribute_pk = from_global_id_strict_type(
+ attribute_id, only_type=Attribute, field="attribute_id"
+ )
+
+ try:
+ attribute_assignment = instance.attributes.prefetch_related("values").get(
+ assignment__attribute_id=attribute_pk # type: ignore
+ )
+ except ObjectDoesNotExist:
+ raise ValidationError(
+ {
+ "attribute_id": ValidationError(
+ f"Couldn't resolve to a {instance_type} "
+ f"attribute: {attribute_id}.",
+ code=error_code_enum.NOT_FOUND.value,
+ )
+ }
+ )
+ return attribute_assignment
+
+ @classmethod
+ def prepare_operations(cls, moves: ReorderInput, values: "QuerySet"):
+ """Prepare operations dict for reordering attribute values.
+
+ Operation dict format:
+ key: attribute value pk,
+ value: sort_order value - relative sorting position of the attribute
+ """
+ value_ids = []
+ sort_orders = []
+
+ # resolve attribute moves
+ for move_info in moves:
+ value_ids.append(move_info.id)
+ sort_orders.append(move_info.sort_order)
+
+ _, values_pks = resolve_global_ids_to_primary_keys(value_ids, AttributeValue)
+ values_pks = [int(pk) for pk in values_pks]
+
+ values_m2m = values.filter(id__in=values_pks)
+
+ if values_m2m.count() != len(values_pks):
+ pks = values_m2m.values_list("pk", flat=True)
+ invalid_values = set(values_pks) - set(pks)
+ invalid_ids = [
+ graphene.Node.to_global_id("AttributeValue", val_pk)
+ for val_pk in invalid_values
+ ]
+ raise ValidationError(
+ "Couldn't resolve to an attribute value.",
+ params={"values": invalid_ids},
+ )
+
+ values_m2m = list(values_m2m)
+ values_m2m.sort(key=lambda e: values_pks.index(e.pk)) # preserve order in pks
+
+ operations = {
+ attribute.pk: sort_order
+ for attribute, sort_order in zip(values_m2m, sort_orders)
+ }
+
+ return operations
+
+
class AttributeValueCreateInput(graphene.InputObjectType):
name = graphene.String(required=True, description=AttributeValueDescriptions.NAME)
diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.py
index 365ee5ddb6..6ade594e45 100644
--- a/saleor/graphql/core/types/common.py
+++ b/saleor/graphql/core/types/common.py
@@ -197,6 +197,11 @@ class ProductError(Error):
description="List of attributes IDs which causes the error.",
required=False,
)
+ values = graphene.List(
+ graphene.NonNull(graphene.ID),
+ description="List of attribute values IDs which causes the error.",
+ required=False,
+ )
class CollectionError(ProductWithoutVariantError):
@@ -260,6 +265,11 @@ class PageError(Error):
description="List of attributes IDs which causes the error.",
required=False,
)
+ values = graphene.List(
+ graphene.NonNull(graphene.ID),
+ description="List of attribute values IDs which causes the error.",
+ required=False,
+ )
class PaymentError(Error):
diff --git a/saleor/graphql/page/dataloaders.py b/saleor/graphql/page/dataloaders.py
index 071261cdff..23f7baab0e 100644
--- a/saleor/graphql/page/dataloaders.py
+++ b/saleor/graphql/page/dataloaders.py
@@ -2,7 +2,11 @@ from collections import defaultdict
from promise import Promise
-from ...attribute.models import AssignedPageAttribute, AttributePage, AttributeValue
+from ...attribute.models import (
+ AssignedPageAttribute,
+ AssignedPageAttributeValue,
+ AttributePage,
+)
from ...core.permissions import PagePermissions
from ...page.models import Page, PageType
from ..attribute.dataloaders import AttributesByAttributeId, AttributeValueByIdLoader
@@ -122,18 +126,17 @@ class AttributeValuesByAssignedPageAttributeIdLoader(DataLoader):
context_key = "attributevalues_by_assigned_pageattribute"
def batch_load(self, keys):
- AttributeAssignment = AttributeValue.assignedpageattribute_set.through
- attribute_values = AttributeAssignment.objects.filter(
- assignedpageattribute_id__in=keys
+ attribute_values = AssignedPageAttributeValue.objects.filter(
+ assignment_id__in=keys
)
- value_ids = [a.attributevalue_id for a in attribute_values]
+ value_ids = [a.value_id for a in attribute_values]
def map_assignment_to_values(values):
value_map = dict(zip(value_ids, values))
assigned_page_map = defaultdict(list)
for attribute_value in attribute_values:
- assigned_page_map[attribute_value.assignedpageattribute_id].append(
- value_map.get(attribute_value.attributevalue_id)
+ assigned_page_map[attribute_value.assignment_id].append(
+ value_map.get(attribute_value.value_id)
)
return [
sorted(assigned_page_map[key], key=lambda v: (v.sort_order, v.id))
diff --git a/saleor/graphql/page/mutations/attributes.py b/saleor/graphql/page/mutations/attributes.py
index 12bfb82a8f..a536b175d6 100644
--- a/saleor/graphql/page/mutations/attributes.py
+++ b/saleor/graphql/page/mutations/attributes.py
@@ -6,17 +6,20 @@ from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.db import transaction
from ....attribute import AttributeType, models
-from ....core.permissions import PageTypePermissions
+from ....core.permissions import PagePermissions, PageTypePermissions
from ....page import models as page_models
from ....page.error_codes import PageErrorCode
-from ...attribute.mutations import BaseReorderAttributesMutation
+from ...attribute.mutations import (
+ BaseReorderAttributesMutation,
+ BaseReorderAttributeValuesMutation,
+)
from ...attribute.types import Attribute
from ...core.inputs import ReorderInput
from ...core.mutations import BaseMutation
from ...core.types.common import PageError
from ...core.utils import from_global_id_strict_type
from ...core.utils.reordering import perform_reordering
-from ...page.types import PageType
+from ...page.types import Page, PageType
from ...utils import resolve_global_ids_to_primary_keys
@@ -197,3 +200,51 @@ class PageTypeReorderAttributes(BaseReorderAttributesMutation):
perform_reordering(page_attributes, operations)
return PageTypeReorderAttributes(page_type=page_type)
+
+
+class PageReorderAttributeValues(BaseReorderAttributeValuesMutation):
+ page = graphene.Field(
+ Page, description="Page from which attribute values are reordered."
+ )
+
+ class Meta:
+ description = "Reorder page attribute values."
+ permissions = (PagePermissions.MANAGE_PAGES,)
+ error_type_class = PageError
+ error_type_field = "page_errors"
+
+ class Arguments:
+ page_id = graphene.Argument(
+ graphene.ID, required=True, description="ID of a page."
+ )
+ attribute_id = graphene.Argument(
+ graphene.ID, required=True, description="ID of an attribute."
+ )
+ moves = graphene.List(
+ ReorderInput,
+ required=True,
+ description="The list of reordering operations for given attribute values.",
+ )
+
+ @classmethod
+ def perform_mutation(cls, _root, _info, **data):
+ page_id = data["page_id"]
+ page = cls.perform(page_id, "page", data, PageErrorCode)
+ return PageReorderAttributeValues(page=page)
+
+ @staticmethod
+ def get_instance(instance_id: str):
+ pk = from_global_id_strict_type(instance_id, only_type=Page, field="page_id")
+
+ try:
+ page = page_models.Page.objects.prefetch_related("attributes").get(pk=pk)
+ except ObjectDoesNotExist:
+ raise ValidationError(
+ {
+ "page_id": ValidationError(
+ (f"Couldn't resolve to a page: {instance_id}"),
+ code=PageErrorCode.NOT_FOUND.value,
+ )
+ }
+ )
+ return page
diff --git a/saleor/graphql/page/schema.py b/saleor/graphql/page/schema.py
index 0a819ddead..f382c81cae 100644
--- a/saleor/graphql/page/schema.py
+++ b/saleor/graphql/page/schema.py
@@ -7,6 +7,7 @@ from .filters import PageFilterInput, PageTypeFilterInput
from .mutations.attributes import (
PageAttributeAssign,
PageAttributeUnassign,
+ PageReorderAttributeValues,
PageTypeReorderAttributes,
)
from .mutations.pages import (
@@ -86,3 +87,4 @@ class PageMutations(graphene.ObjectType):
page_attribute_assign = PageAttributeAssign.Field()
page_attribute_unassign = PageAttributeUnassign.Field()
page_type_reorder_attributes = PageTypeReorderAttributes.Field()
+ page_reorder_attribute_values = PageReorderAttributeValues.Field()
diff --git a/saleor/graphql/page/tests/test_page_reorder_attribute_values.py b/saleor/graphql/page/tests/test_page_reorder_attribute_values.py
new file mode 100644
index 0000000000..f0f0985e9c
--- /dev/null
+++ b/saleor/graphql/page/tests/test_page_reorder_attribute_values.py
@@ -0,0 +1,220 @@
+import graphene
+
+from ....attribute.models import AttributeValue
+from ....attribute.utils import associate_attribute_values_to_instance
+from ....page.error_codes import PageErrorCode
+from ...tests.utils import get_graphql_content
+
+PAGE_REORDER_ATTRIBUTE_VALUES_MUTATION = """
+ mutation PageReorderAttributeValues(
+ $pageId: ID!
+ $attributeId: ID!
+ $moves: [ReorderInput]!
+ ) {
+ pageReorderAttributeValues(
+ pageId: $pageId
+ attributeId: $attributeId
+ moves: $moves
+ ) {
+ page {
+ id
+ attributes {
+ attribute {
+ id
+ slug
+ }
+ values {
+ id
+ }
+ }
+ }
+
+ pageErrors {
+ field
+ message
+ code
+ attributes
+ values
+ }
+ }
+ }
+"""
+
+
+def test_sort_page_attribute_values(
+ staff_api_client, permission_manage_pages, page, page_reference_attribute,
+):
+ staff_api_client.user.user_permissions.add(permission_manage_pages)
+
+ page_type = page.page_type
+ page_type.page_attributes.clear()
+ page_type.page_attributes.add(page_reference_attribute)
+
+ page_id = graphene.Node.to_global_id("Page", page.id)
+ attribute_id = graphene.Node.to_global_id("Attribute", page_reference_attribute.id)
+ attr_values = AttributeValue.objects.bulk_create(
+ [
+ AttributeValue(
+ attribute=page_reference_attribute,
+ slug=f"{page.pk}_1",
+ name="test name 1",
+ ),
+ AttributeValue(
+ attribute=page_reference_attribute,
+ slug=f"{page.pk}_2",
+ name="test name 2",
+ ),
+ AttributeValue(
+ attribute=page_reference_attribute,
+ slug=f"{page.pk}_3",
+ name="test name 3",
+ ),
+ ]
+ )
+ associate_attribute_values_to_instance(page, page_reference_attribute, *attr_values)
+
+ variables = {
+ "pageId": page_id,
+ "attributeId": attribute_id,
+ "moves": [
+ {
+ "id": graphene.Node.to_global_id("AttributeValue", attr_values[0].pk),
+ "sortOrder": +1,
+ },
+ {
+ "id": graphene.Node.to_global_id("AttributeValue", attr_values[2].pk),
+ "sortOrder": -2,
+ },
+ ],
+ }
+
+ expected_order = [attr_values[2].pk, attr_values[1].pk, attr_values[0].pk]
+
+ content = get_graphql_content(
+ staff_api_client.post_graphql(PAGE_REORDER_ATTRIBUTE_VALUES_MUTATION, variables)
+ )["data"]["pageReorderAttributeValues"]
+ assert not content["pageErrors"]
+
+ assert content["page"]["id"] == page_id, "Did not return the correct page"
+
+ gql_attribute_values = content["page"]["attributes"][0]["values"]
+ assert len(gql_attribute_values) == 3
+
+ for attr, expected_pk in zip(gql_attribute_values, expected_order):
+ db_type, value_pk = graphene.Node.from_global_id(attr["id"])
+ assert db_type == "AttributeValue"
+ assert int(value_pk) == expected_pk
+
+
+def test_sort_page_attribute_values_invalid_attribute_id(
+ staff_api_client,
+ permission_manage_pages,
+ page,
+ page_reference_attribute,
+ color_attribute,
+):
+ staff_api_client.user.user_permissions.add(permission_manage_pages)
+
+ page_type = page.page_type
+ page_type.page_attributes.clear()
+ page_type.page_attributes.add(page_reference_attribute)
+
+ page_id = graphene.Node.to_global_id("Page", page.id)
+ attr_values = AttributeValue.objects.bulk_create(
+ [
+ AttributeValue(
+ attribute=page_reference_attribute,
+ slug=f"{page.pk}_1",
+ name="test name 1",
+ ),
+ AttributeValue(
+ attribute=page_reference_attribute,
+ slug=f"{page.pk}_2",
+ name="test name 2",
+ ),
+ ]
+ )
+ associate_attribute_values_to_instance(page, page_reference_attribute, *attr_values)
+
+ variables = {
+ "pageId": page_id,
+ "attributeId": graphene.Node.to_global_id("Attribute", color_attribute.pk),
+ "moves": [
+ {
+ "id": graphene.Node.to_global_id("AttributeValue", attr_values[0].pk),
+ "sortOrder": +1,
+ },
+ ],
+ }
+
+ content = get_graphql_content(
+ staff_api_client.post_graphql(PAGE_REORDER_ATTRIBUTE_VALUES_MUTATION, variables)
+ )["data"]["pageReorderAttributeValues"]
+ errors = content["pageErrors"]
+ assert not content["page"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == PageErrorCode.NOT_FOUND.name
+ assert errors[0]["field"] == "attributeId"
+
+
+def test_sort_page_attribute_values_invalid_value_id(
+ staff_api_client,
+ permission_manage_pages,
+ page,
+ page_reference_attribute,
+ size_page_attribute,
+):
+ staff_api_client.user.user_permissions.add(permission_manage_pages)
+
+ page_type = page.page_type
+ page_type.page_attributes.clear()
+ page_type.page_attributes.add(page_reference_attribute)
+
+ page_id = graphene.Node.to_global_id("Page", page.id)
+ attribute_id = graphene.Node.to_global_id("Attribute", page_reference_attribute.id)
+ attr_values = AttributeValue.objects.bulk_create(
+ [
+ AttributeValue(
+ attribute=page_reference_attribute,
+ slug=f"{page.pk}_1",
+ name="test name 1",
+ ),
+ AttributeValue(
+ attribute=page_reference_attribute,
+ slug=f"{page.pk}_2",
+ name="test name 2",
+ ),
+ AttributeValue(
+ attribute=page_reference_attribute,
+ slug=f"{page.pk}_3",
+ name="test name 3",
+ ),
+ ]
+ )
+ associate_attribute_values_to_instance(page, page_reference_attribute, *attr_values)
+
+ invalid_value_id = graphene.Node.to_global_id(
+ "AttributeValue", size_page_attribute.values.first().pk
+ )
+
+ variables = {
+ "pageId": page_id,
+ "attributeId": attribute_id,
+ "moves": [
+ {"id": invalid_value_id, "sortOrder": +1},
+ {
+ "id": graphene.Node.to_global_id("AttributeValue", attr_values[2].pk),
+ "sortOrder": -1,
+ },
+ ],
+ }
+
+ content = get_graphql_content(
+ staff_api_client.post_graphql(PAGE_REORDER_ATTRIBUTE_VALUES_MUTATION, variables)
+ )["data"]["pageReorderAttributeValues"]
+ errors = content["pageErrors"]
+ assert not content["page"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == PageErrorCode.NOT_FOUND.name
+ assert errors[0]["field"] == "moves"
+ assert errors[0]["values"] == [invalid_value_id]
diff --git a/saleor/graphql/product/dataloaders/attributes.py b/saleor/graphql/product/dataloaders/attributes.py
index 1907f28532..62aaab4c77 100644
--- a/saleor/graphql/product/dataloaders/attributes.py
+++ b/saleor/graphql/product/dataloaders/attributes.py
@@ -4,9 +4,10 @@ from promise import Promise
from ....attribute.models import (
AssignedProductAttribute,
+ AssignedProductAttributeValue,
AssignedVariantAttribute,
+ AssignedVariantAttributeValue,
AttributeProduct,
- AttributeValue,
AttributeVariant,
)
from ....core.permissions import ProductPermissions
@@ -168,19 +169,18 @@ class AttributeValuesByAssignedProductAttributeIdLoader(DataLoader):
context_key = "attributevalues_by_assignedproductattribute"
def batch_load(self, keys):
- AttributeAssignment = AttributeValue.assignedproductattribute_set.through
- attribute_values = AttributeAssignment.objects.filter(
- assignedproductattribute_id__in=keys
+ attribute_values = AssignedProductAttributeValue.objects.filter(
+ assignment_id__in=keys
)
- value_ids = [a.attributevalue_id for a in attribute_values]
+ value_ids = [a.value_id for a in attribute_values]
def map_assignment_to_values(values):
value_map = dict(zip(value_ids, values))
assigned_product_map = defaultdict(list)
for attribute_value in attribute_values:
- assigned_product_map[
- attribute_value.assignedproductattribute_id
- ].append(value_map.get(attribute_value.attributevalue_id))
+ assigned_product_map[attribute_value.assignment_id].append(
+ value_map.get(attribute_value.value_id)
+ )
return [
sorted(assigned_product_map[key], key=lambda v: (v.sort_order, v.id))
for key in keys
@@ -197,19 +197,18 @@ class AttributeValuesByAssignedVariantAttributeIdLoader(DataLoader):
context_key = "attributevalues_by_assignedvariantattribute"
def batch_load(self, keys):
- AttributeAssignment = AttributeValue.assignedvariantattribute_set.through
- attribute_values = AttributeAssignment.objects.filter(
- assignedvariantattribute_id__in=keys
+ attribute_values = AssignedVariantAttributeValue.objects.filter(
+ assignment_id__in=keys
)
- value_ids = [a.attributevalue_id for a in attribute_values]
+ value_ids = [a.value_id for a in attribute_values]
def map_assignment_to_values(values):
value_map = dict(zip(value_ids, values))
assigned_variant_map = defaultdict(list)
for attribute_value in attribute_values:
- assigned_variant_map[
- attribute_value.assignedvariantattribute_id
- ].append(value_map.get(attribute_value.attributevalue_id))
+ assigned_variant_map[attribute_value.assignment_id].append(
+ value_map.get(attribute_value.value_id)
+ )
return [
sorted(assigned_variant_map[key], key=lambda v: (v.sort_order, v.id))
for key in keys
diff --git a/saleor/graphql/product/mutations/attributes.py b/saleor/graphql/product/mutations/attributes.py
index c21162e7c6..584214266f 100644
--- a/saleor/graphql/product/mutations/attributes.py
+++ b/saleor/graphql/product/mutations/attributes.py
@@ -7,17 +7,21 @@ from django.db import transaction
from django.db.models import Q
from ....attribute import AttributeType, models as attribute_models
-from ....core.permissions import ProductTypePermissions
+from ....core.permissions import ProductPermissions, ProductTypePermissions
from ....product import models
from ....product.error_codes import ProductErrorCode
-from ...attribute.mutations import BaseReorderAttributesMutation
+from ...attribute.mutations import (
+ BaseReorderAttributesMutation,
+ BaseReorderAttributeValuesMutation,
+)
from ...attribute.types import Attribute
+from ...channel import ChannelContext
from ...core.inputs import ReorderInput
from ...core.mutations import BaseMutation
from ...core.types.common import ProductError
from ...core.utils import from_global_id_strict_type
from ...core.utils.reordering import perform_reordering
-from ...product.types import ProductType
+from ...product.types import Product, ProductType, ProductVariant
from ..enums import ProductAttributeType
@@ -323,3 +327,112 @@ class ProductTypeReorderAttributes(BaseReorderAttributesMutation):
perform_reordering(attributes_m2m, operations)
return ProductTypeReorderAttributes(product_type=product_type)
+
+
+class ProductReorderAttributeValues(BaseReorderAttributeValuesMutation):
+ product = graphene.Field(
+ Product, description="Product from which attribute values are reordered."
+ )
+
+ class Meta:
+ description = "Reorder product attribute values."
+ permissions = (ProductPermissions.MANAGE_PRODUCTS,)
+ error_type_class = ProductError
+ error_type_field = "product_errors"
+
+ class Arguments:
+ product_id = graphene.Argument(
+ graphene.ID, required=True, description="ID of a product."
+ )
+ attribute_id = graphene.Argument(
+ graphene.ID, required=True, description="ID of an attribute."
+ )
+ moves = graphene.List(
+ ReorderInput,
+ required=True,
+ description="The list of reordering operations for given attribute values.",
+ )
+
+ @classmethod
+ def perform_mutation(cls, _root, info, **data):
+ product_id = data["product_id"]
+ product = cls.perform(product_id, "product", data, ProductErrorCode)
+
+ return ProductReorderAttributeValues(
+ product=ChannelContext(node=product, channel_slug=None)
+ )
+
+ @staticmethod
+ def get_instance(instance_id: str):
+ pk = from_global_id_strict_type(
+ instance_id, only_type=Product, field="product_id"
+ )
+
+ try:
+ product = models.Product.objects.prefetch_related("attributes").get(pk=pk)
+ except ObjectDoesNotExist:
+ raise ValidationError(
+ {
+ "product_id": ValidationError(
+ (f"Couldn't resolve to a product: {instance_id}"),
+ code=ProductErrorCode.NOT_FOUND.value,
+ )
+ }
+ )
+ return product
+
+
+class ProductVariantReorderAttributeValues(BaseReorderAttributeValuesMutation):
+ product_variant = graphene.Field(
+ ProductVariant,
+ description="Product variant from which attribute values are reordered.",
+ )
+
+ class Meta:
+ description = "Reorder product variant attribute values."
+ permissions = (ProductPermissions.MANAGE_PRODUCTS,)
+ error_type_class = ProductError
+ error_type_field = "product_errors"
+
+ class Arguments:
+ variant_id = graphene.Argument(
+ graphene.ID, required=True, description="ID of a product variant."
+ )
+ attribute_id = graphene.Argument(
+ graphene.ID, required=True, description="ID of an attribute."
+ )
+ moves = graphene.List(
+ ReorderInput,
+ required=True,
+ description="The list of reordering operations for given attribute values.",
+ )
+
+ @classmethod
+ def perform_mutation(cls, _root, info, **data):
+ variant_id = data["variant_id"]
+ variant = cls.perform(variant_id, "variant", data, ProductErrorCode)
+
+ return ProductVariantReorderAttributeValues(
+ product_variant=ChannelContext(node=variant, channel_slug=None)
+ )
+
+ @staticmethod
+ def get_instance(instance_id: str):
+ pk = from_global_id_strict_type(
+ instance_id, only_type=ProductVariant, field="variant_id"
+ )
+
+ try:
+ variant = models.ProductVariant.objects.prefetch_related("attributes").get(
+ pk=pk
+ )
+ except ObjectDoesNotExist:
+ raise ValidationError(
+ {
+ "variant_id": ValidationError(
+ (f"Couldn't resolve to a product variant: {instance_id}"),
+ code=ProductErrorCode.NOT_FOUND.value,
+ )
+ }
+ )
+ return variant
diff --git a/saleor/graphql/product/schema.py b/saleor/graphql/product/schema.py
index 469cb517ae..3220190e37 100644
--- a/saleor/graphql/product/schema.py
+++ b/saleor/graphql/product/schema.py
@@ -42,7 +42,9 @@ from .filters import (
from .mutations.attributes import (
ProductAttributeAssign,
ProductAttributeUnassign,
+ ProductReorderAttributeValues,
ProductTypeReorderAttributes,
+ ProductVariantReorderAttributeValues,
)
from .mutations.channels import (
CollectionChannelListingUpdate,
@@ -405,6 +407,7 @@ class ProductMutations(graphene.ObjectType):
product_type_bulk_delete = ProductTypeBulkDelete.Field()
product_type_update = ProductTypeUpdate.Field()
product_type_reorder_attributes = ProductTypeReorderAttributes.Field()
+ product_reorder_attribute_values = ProductReorderAttributeValues.Field()
digital_content_create = DigitalContentCreate.Field()
digital_content_delete = DigitalContentDelete.Field()
@@ -423,6 +426,9 @@ class ProductMutations(graphene.ObjectType):
product_variant_set_default = ProductVariantSetDefault.Field()
product_variant_translate = ProductVariantTranslate.Field()
product_variant_channel_listing_update = ProductVariantChannelListingUpdate.Field()
+ product_variant_reorder_attribute_values = (
+ ProductVariantReorderAttributeValues.Field()
+ )
variant_image_assign = VariantImageAssign.Field()
variant_image_unassign = VariantImageUnassign.Field()
diff --git a/saleor/graphql/product/tests/test_attributes.py b/saleor/graphql/product/tests/test_attributes.py
index ba839c68ea..5b817f3e63 100644
--- a/saleor/graphql/product/tests/test_attributes.py
+++ b/saleor/graphql/product/tests/test_attributes.py
@@ -10,6 +10,7 @@ from ....attribute.models import (
AttributeValue,
AttributeVariant,
)
+from ....attribute.utils import associate_attribute_values_to_instance
from ....product.error_codes import ProductErrorCode
from ....product.models import ProductType
from ...attribute.enums import AttributeTypeEnum
@@ -895,3 +896,462 @@ def test_sort_attributes_within_product_type(
gql_type, gql_attr_id = graphene.Node.from_global_id(attr["id"])
assert gql_type == "Attribute"
assert int(gql_attr_id) == expected_pk
+
+
+PRODUCT_REORDER_ATTRIBUTE_VALUES_MUTATION = """
+ mutation ProductReorderAttributeValues(
+ $productId: ID!
+ $attributeId: ID!
+ $moves: [ReorderInput]!
+ ) {
+ productReorderAttributeValues(
+ productId: $productId
+ attributeId: $attributeId
+ moves: $moves
+ ) {
+ product {
+ id
+ attributes {
+ attribute {
+ id
+ slug
+ }
+ values {
+ id
+ }
+ }
+ }
+
+ productErrors {
+ field
+ message
+ code
+ attributes
+ values
+ }
+ }
+ }
+"""
+
+
+def test_sort_product_attribute_values(
+ staff_api_client, permission_manage_products, product, page_reference_attribute,
+):
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ product_type = product.product_type
+ product_type.product_attributes.clear()
+ product_type.product_attributes.add(page_reference_attribute)
+
+ product_id = graphene.Node.to_global_id("Product", product.id)
+ attribute_id = graphene.Node.to_global_id("Attribute", page_reference_attribute.id)
+ attr_values = AttributeValue.objects.bulk_create(
+ [
+ AttributeValue(
+ attribute=page_reference_attribute,
+ slug=f"{product.pk}_1",
+ name="test name 1",
+ ),
+ AttributeValue(
+ attribute=page_reference_attribute,
+ slug=f"{product.pk}_2",
+ name="test name 2",
+ ),
+ AttributeValue(
+ attribute=page_reference_attribute,
+ slug=f"{product.pk}_3",
+ name="test name 3",
+ ),
+ ]
+ )
+ associate_attribute_values_to_instance(
+ product, page_reference_attribute, *attr_values
+ )
+
+ variables = {
+ "productId": product_id,
+ "attributeId": attribute_id,
+ "moves": [
+ {
+ "id": graphene.Node.to_global_id("AttributeValue", attr_values[0].pk),
+ "sortOrder": +1,
+ },
+ {
+ "id": graphene.Node.to_global_id("AttributeValue", attr_values[2].pk),
+ "sortOrder": -1,
+ },
+ ],
+ }
+
+ expected_order = [attr_values[1].pk, attr_values[2].pk, attr_values[0].pk]
+
+ content = get_graphql_content(
+ staff_api_client.post_graphql(
+ PRODUCT_REORDER_ATTRIBUTE_VALUES_MUTATION, variables
+ )
+ )["data"]["productReorderAttributeValues"]
+ assert not content["productErrors"]
+
+ assert content["product"]["id"] == product_id, "Did not return the correct product"
+
+ gql_attribute_values = content["product"]["attributes"][0]["values"]
+ assert len(gql_attribute_values) == 3
+
+ for attr, expected_pk in zip(gql_attribute_values, expected_order):
+ db_type, value_pk = graphene.Node.from_global_id(attr["id"])
+ assert db_type == "AttributeValue"
+ assert int(value_pk) == expected_pk
+
+
+def test_sort_product_attribute_values_invalid_attribute_id(
+ staff_api_client,
+ permission_manage_products,
+ product,
+ page_reference_attribute,
+ color_attribute,
+):
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ product_type = product.product_type
+ product_type.product_attributes.clear()
+ product_type.product_attributes.add(page_reference_attribute)
+
+ product_id = graphene.Node.to_global_id("Product", product.id)
+ attr_values = AttributeValue.objects.bulk_create(
+ [
+ AttributeValue(
+ attribute=page_reference_attribute,
+ slug=f"{product.pk}_1",
+ name="test name 1",
+ ),
+ AttributeValue(
+ attribute=page_reference_attribute,
+ slug=f"{product.pk}_2",
+ name="test name 2",
+ ),
+ ]
+ )
+ associate_attribute_values_to_instance(
+ product, page_reference_attribute, *attr_values
+ )
+
+ variables = {
+ "productId": product_id,
+ "attributeId": graphene.Node.to_global_id("Attribute", color_attribute.pk),
+ "moves": [
+ {
+ "id": graphene.Node.to_global_id("AttributeValue", attr_values[0].pk),
+ "sortOrder": +1,
+ },
+ ],
+ }
+
+ content = get_graphql_content(
+ staff_api_client.post_graphql(
+ PRODUCT_REORDER_ATTRIBUTE_VALUES_MUTATION, variables
+ )
+ )["data"]["productReorderAttributeValues"]
+ errors = content["productErrors"]
+ assert not content["product"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == ProductErrorCode.NOT_FOUND.name
+ assert errors[0]["field"] == "attributeId"
+
+
+def test_sort_product_attribute_values_invalid_value_id(
+ staff_api_client,
+ permission_manage_products,
+ product,
+ page_reference_attribute,
+ size_page_attribute,
+):
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ product_type = product.product_type
+ product_type.product_attributes.clear()
+ product_type.product_attributes.add(page_reference_attribute)
+
+ product_id = graphene.Node.to_global_id("Product", product.id)
+ attribute_id = graphene.Node.to_global_id("Attribute", page_reference_attribute.id)
+ attr_values = AttributeValue.objects.bulk_create(
+ [
+ AttributeValue(
+ attribute=page_reference_attribute,
+ slug=f"{product.pk}_1",
+ name="test name 1",
+ ),
+ AttributeValue(
+ attribute=page_reference_attribute,
+ slug=f"{product.pk}_2",
+ name="test name 2",
+ ),
+ AttributeValue(
+ attribute=page_reference_attribute,
+ slug=f"{product.pk}_3",
+ name="test name 3",
+ ),
+ ]
+ )
+ associate_attribute_values_to_instance(
+ product, page_reference_attribute, *attr_values
+ )
+
+ invalid_value_id = graphene.Node.to_global_id(
+ "AttributeValue", size_page_attribute.values.first().pk
+ )
+
+ variables = {
+ "productId": product_id,
+ "attributeId": attribute_id,
+ "moves": [
+ {"id": invalid_value_id, "sortOrder": +1},
+ {
+ "id": graphene.Node.to_global_id("AttributeValue", attr_values[2].pk),
+ "sortOrder": -1,
+ },
+ ],
+ }
+
+ content = get_graphql_content(
+ staff_api_client.post_graphql(
+ PRODUCT_REORDER_ATTRIBUTE_VALUES_MUTATION, variables
+ )
+ )["data"]["productReorderAttributeValues"]
+ errors = content["productErrors"]
+ assert not content["product"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == ProductErrorCode.NOT_FOUND.name
+ assert errors[0]["field"] == "moves"
+ assert errors[0]["values"] == [invalid_value_id]
+
+
+PRODUCT_VARIANT_REORDER_ATTRIBUTE_VALUES_MUTATION = """
+ mutation ProductVariantReorderAttributeValues(
+ $variantId: ID!
+ $attributeId: ID!
+ $moves: [ReorderInput]!
+ ) {
+ productVariantReorderAttributeValues(
+ variantId: $variantId
+ attributeId: $attributeId
+ moves: $moves
+ ) {
+ productVariant {
+ id
+ attributes {
+ attribute {
+ id
+ slug
+ }
+ values {
+ id
+ }
+ }
+ }
+
+ productErrors {
+ field
+ message
+ code
+ attributes
+ values
+ }
+ }
+ }
+"""
+
+
+def test_sort_product_variant_attribute_values(
+ staff_api_client, permission_manage_products, product, page_reference_attribute,
+):
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ variant = product.variants.first()
+ product_type = product.product_type
+ product_type.variant_attributes.clear()
+ product_type.variant_attributes.add(page_reference_attribute)
+
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ attribute_id = graphene.Node.to_global_id("Attribute", page_reference_attribute.id)
+ attr_values = AttributeValue.objects.bulk_create(
+ [
+ AttributeValue(
+ attribute=page_reference_attribute,
+ slug=f"{variant.pk}_1",
+ name="test name 1",
+ ),
+ AttributeValue(
+ attribute=page_reference_attribute,
+ slug=f"{variant.pk}_2",
+ name="test name 2",
+ ),
+ AttributeValue(
+ attribute=page_reference_attribute,
+ slug=f"{variant.pk}_3",
+ name="test name 3",
+ ),
+ ]
+ )
+ associate_attribute_values_to_instance(
+ variant, page_reference_attribute, *attr_values
+ )
+
+ variables = {
+ "variantId": variant_id,
+ "attributeId": attribute_id,
+ "moves": [
+ {
+ "id": graphene.Node.to_global_id("AttributeValue", attr_values[0].pk),
+ "sortOrder": +1,
+ },
+ {
+ "id": graphene.Node.to_global_id("AttributeValue", attr_values[2].pk),
+ "sortOrder": -1,
+ },
+ ],
+ }
+
+ expected_order = [attr_values[1].pk, attr_values[2].pk, attr_values[0].pk]
+
+ content = get_graphql_content(
+ staff_api_client.post_graphql(
+ PRODUCT_VARIANT_REORDER_ATTRIBUTE_VALUES_MUTATION, variables
+ )
+ )["data"]["productVariantReorderAttributeValues"]
+ assert not content["productErrors"]
+
+ assert (
+ content["productVariant"]["id"] == variant_id
+ ), "Did not return the correct product variant"
+
+ gql_attribute_values = content["productVariant"]["attributes"][0]["values"]
+ assert len(gql_attribute_values) == 3
+
+ for attr, expected_pk in zip(gql_attribute_values, expected_order):
+ db_type, value_pk = graphene.Node.from_global_id(attr["id"])
+ assert db_type == "AttributeValue"
+ assert int(value_pk) == expected_pk
+
+
+def test_sort_product_variant_attribute_values_invalid_attribute_id(
+ staff_api_client,
+ permission_manage_products,
+ product,
+ page_reference_attribute,
+ color_attribute,
+):
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ variant = product.variants.first()
+ product_type = product.product_type
+ product_type.variant_attributes.clear()
+ product_type.variant_attributes.add(page_reference_attribute)
+
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ attr_values = AttributeValue.objects.bulk_create(
+ [
+ AttributeValue(
+ attribute=page_reference_attribute,
+ slug=f"{variant.pk}_1",
+ name="test name 1",
+ ),
+ AttributeValue(
+ attribute=page_reference_attribute,
+ slug=f"{variant.pk}_2",
+ name="test name 2",
+ ),
+ ]
+ )
+ associate_attribute_values_to_instance(
+ variant, page_reference_attribute, *attr_values
+ )
+
+ variables = {
+ "variantId": variant_id,
+ "attributeId": graphene.Node.to_global_id("Attribute", color_attribute.pk),
+ "moves": [
+ {
+ "id": graphene.Node.to_global_id("AttributeValue", attr_values[0].pk),
+ "sortOrder": +1,
+ },
+ ],
+ }
+
+ content = get_graphql_content(
+ staff_api_client.post_graphql(
+ PRODUCT_VARIANT_REORDER_ATTRIBUTE_VALUES_MUTATION, variables
+ )
+ )["data"]["productVariantReorderAttributeValues"]
+ errors = content["productErrors"]
+ assert not content["productVariant"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == ProductErrorCode.NOT_FOUND.name
+ assert errors[0]["field"] == "attributeId"
+
+
+def test_sort_product_variant_attribute_values_invalid_value_id(
+ staff_api_client,
+ permission_manage_products,
+ product,
+ page_reference_attribute,
+ size_page_attribute,
+):
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ variant = product.variants.first()
+ product_type = product.product_type
+ product_type.variant_attributes.clear()
+ product_type.variant_attributes.add(page_reference_attribute)
+
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ attribute_id = graphene.Node.to_global_id("Attribute", page_reference_attribute.id)
+ attr_values = AttributeValue.objects.bulk_create(
+ [
+ AttributeValue(
+ attribute=page_reference_attribute,
+ slug=f"{variant.pk}_1",
+ name="test name 1",
+ ),
+ AttributeValue(
+ attribute=page_reference_attribute,
+ slug=f"{variant.pk}_2",
+ name="test name 2",
+ ),
+ AttributeValue(
+ attribute=page_reference_attribute,
+ slug=f"{variant.pk}_3",
+ name="test name 3",
+ ),
+ ]
+ )
+ associate_attribute_values_to_instance(
+ variant, page_reference_attribute, *attr_values
+ )
+
+ invalid_value_id = graphene.Node.to_global_id(
+ "AttributeValue", size_page_attribute.values.first().pk
+ )
+
+ variables = {
+ "variantId": variant_id,
+ "attributeId": attribute_id,
+ "moves": [
+ {"id": invalid_value_id, "sortOrder": +1},
+ {
+ "id": graphene.Node.to_global_id("AttributeValue", attr_values[2].pk),
+ "sortOrder": -1,
+ },
+ ],
+ }
+
+ content = get_graphql_content(
+ staff_api_client.post_graphql(
+ PRODUCT_VARIANT_REORDER_ATTRIBUTE_VALUES_MUTATION, variables
+ )
+ )["data"]["productVariantReorderAttributeValues"]
+ errors = content["productErrors"]
+ assert not content["productVariant"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == ProductErrorCode.NOT_FOUND.name
+ assert errors[0]["field"] == "moves"
+ assert errors[0]["values"] == [invalid_value_id]
diff --git a/saleor/graphql/product/tests/test_product_sorting_attributes.py b/saleor/graphql/product/tests/test_product_sorting_attributes.py
index a0c34205b7..373d3cb15f 100644
--- a/saleor/graphql/product/tests/test_product_sorting_attributes.py
+++ b/saleor/graphql/product/tests/test_product_sorting_attributes.py
@@ -4,7 +4,7 @@ from decimal import Decimal
import graphene
import pytest
-from ....attribute import AttributeType, models as attribute_models
+from ....attribute import AttributeInputType, AttributeType, models as attribute_models
from ....attribute.utils import associate_attribute_values_to_instance
from ....product import models as product_models
from ...tests.utils import get_graphql_content
@@ -52,7 +52,7 @@ def products_structures(category, channel_USD):
assert product_models.Product.objects.count() == 0
- in_multivals = attribute_models.AttributeInputType.MULTISELECT
+ in_multivals = AttributeInputType.MULTISELECT
pt_apples, pt_oranges, pt_other = list(
product_models.ProductType.objects.bulk_create(
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 99aac99730..5332afeb3a 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -681,6 +681,7 @@ type BulkProductError {
message: String
code: ProductErrorCode!
attributes: [ID!]
+ values: [ID!]
index: Int
warehouses: [ID!]
channels: [ID!]
@@ -691,6 +692,7 @@ type BulkStockError {
message: String
code: ProductErrorCode!
attributes: [ID!]
+ values: [ID!]
index: Int
}
@@ -1120,6 +1122,7 @@ type CollectionChannelListingError {
message: String
code: ProductErrorCode!
attributes: [ID!]
+ values: [ID!]
channels: [ID!]
}
@@ -2636,6 +2639,7 @@ type Mutation {
productTypeBulkDelete(ids: [ID]!): ProductTypeBulkDelete
productTypeUpdate(id: ID!, input: ProductTypeInput!): ProductTypeUpdate
productTypeReorderAttributes(moves: [ReorderInput]!, productTypeId: ID!, type: ProductAttributeType!): ProductTypeReorderAttributes
+ productReorderAttributeValues(attributeId: ID!, moves: [ReorderInput]!, productId: ID!): ProductReorderAttributeValues
digitalContentCreate(input: DigitalContentUploadInput!, variantId: ID!): DigitalContentCreate
digitalContentDelete(variantId: ID!): DigitalContentDelete
digitalContentUpdate(input: DigitalContentInput!, variantId: ID!): DigitalContentUpdate
@@ -2651,6 +2655,7 @@ type Mutation {
productVariantSetDefault(productId: ID!, variantId: ID!): ProductVariantSetDefault
productVariantTranslate(id: ID!, input: NameTranslationInput!, languageCode: LanguageCodeEnum!): ProductVariantTranslate
productVariantChannelListingUpdate(id: ID!, input: [ProductVariantChannelListingAddInput!]!): ProductVariantChannelListingUpdate
+ productVariantReorderAttributeValues(attributeId: ID!, moves: [ReorderInput]!, variantId: ID!): ProductVariantReorderAttributeValues
variantImageAssign(imageId: ID!, variantId: ID!): VariantImageAssign
variantImageUnassign(imageId: ID!, variantId: ID!): VariantImageUnassign
paymentCapture(amount: PositiveDecimal, paymentId: ID!): PaymentCapture
@@ -2670,6 +2675,7 @@ type Mutation {
pageAttributeAssign(attributeIds: [ID!]!, pageTypeId: ID!): PageAttributeAssign
pageAttributeUnassign(attributeIds: [ID!]!, pageTypeId: ID!): PageAttributeUnassign
pageTypeReorderAttributes(moves: [ReorderInput!]!, pageTypeId: ID!): PageTypeReorderAttributes
+ pageReorderAttributeValues(attributeId: ID!, moves: [ReorderInput]!, pageId: ID!): PageReorderAttributeValues
draftOrderComplete(id: ID!): DraftOrderComplete
draftOrderCreate(input: DraftOrderCreateInput!): DraftOrderCreate
draftOrderDelete(id: ID!): DraftOrderDelete
@@ -3329,6 +3335,7 @@ type PageError {
message: String
code: PageErrorCode!
attributes: [ID!]
+ values: [ID!]
}
enum PageErrorCode {
@@ -3363,6 +3370,12 @@ input PageInput {
seo: SeoInput
}
+type PageReorderAttributeValues {
+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
+ page: Page
+ pageErrors: [PageError!]!
+}
+
enum PageSortField {
TITLE
SLUG
@@ -3860,6 +3873,7 @@ type ProductChannelListingError {
message: String
code: ProductErrorCode!
attributes: [ID!]
+ values: [ID!]
channels: [ID!]
}
@@ -3918,6 +3932,7 @@ type ProductError {
message: String
code: ProductErrorCode!
attributes: [ID!]
+ values: [ID!]
}
enum ProductErrorCode {
@@ -4065,6 +4080,12 @@ type ProductPricingInfo {
priceRangeLocalCurrency: TaxedMoneyRange
}
+type ProductReorderAttributeValues {
+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
+ product: Product
+ productErrors: [ProductError!]!
+}
+
input ProductStockFilterInput {
warehouseIds: [ID!]
quantity: IntRangeInput
@@ -4321,6 +4342,12 @@ type ProductVariantReorder {
productErrors: [ProductError!]!
}
+type ProductVariantReorderAttributeValues {
+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
+ productVariant: ProductVariant
+ productErrors: [ProductError!]!
+}
+
type ProductVariantSetDefault {
errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
product: Product