Skip to content

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

Page Types (#6261)

Iga Karbowiak0183cc0e8f8a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8070b84716..3944a4a81e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Add basic rating for `Products` - #6284 by @korycins
- Add metadata to shipping zones and shipping methods - #6340 by @maarcingebala
- Drop deprecated meta mutations - #6422 by @maarcingebala
+- Add Page Types - #6261 by @IKarbowiak
- Migrate draftjs content to editorjs format - #6430 by @IKarbowiak
- Drop deprecated service accounts and webhooks API - #6431 by @maarcingebala
- Add editorjs sanitizer - #6456 by @IKarbowiak
diff --git a/saleor/attribute/__init__.py b/saleor/attribute/__init__.py
new file mode 100644
index 0000000000..ee8fb37023
--- /dev/null
+++ b/saleor/attribute/__init__.py
@@ -0,0 +1,19 @@
+class AttributeInputType:
+ """The type that we expect to render the attribute's values as."""
+
+ DROPDOWN = "dropdown"
+ MULTISELECT = "multiselect"
+
+ CHOICES = [
+ (DROPDOWN, "Dropdown"),
+ (MULTISELECT, "Multi Select"),
+ ]
+ # list the input types that cannot be assigned to a variant
+ NON_ASSIGNABLE_TO_VARIANTS = [MULTISELECT]
+
+
+class AttributeType:
+ PRODUCT_TYPE = "product-type"
+ PAGE_TYPE = "page-type"
+
+ CHOICES = [(PRODUCT_TYPE, "Product type"), (PAGE_TYPE, "Page type")]
diff --git a/saleor/attribute/error_codes.py b/saleor/attribute/error_codes.py
new file mode 100644
index 0000000000..7fdda8d783
--- /dev/null
+++ b/saleor/attribute/error_codes.py
@@ -0,0 +1,10 @@
+from enum import Enum
+
+
+class AttributeErrorCode(Enum):
+ ALREADY_EXISTS = "already_exists"
+ GRAPHQL_ERROR = "graphql_error"
+ INVALID = "invalid"
+ NOT_FOUND = "not_found"
+ REQUIRED = "required"
+ UNIQUE = "unique"
diff --git a/saleor/attribute/migrations/0001_initial.py b/saleor/attribute/migrations/0001_initial.py
new file mode 100644
index 0000000000..3b8a017e03
--- /dev/null
+++ b/saleor/attribute/migrations/0001_initial.py
@@ -0,0 +1,493 @@
+# Generated by Django 3.1 on 2020-10-30 11:28
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+import saleor.core.utils.json_serializer
+
+
+class Migration(migrations.Migration):
+
+ initial = True
+
+ dependencies = [
+ ("product", "0136_add_attribute_type_and_page_to_attribute_relation"),
+ ("page", "0017_pagetype"),
+ ]
+
+ state_operations = [
+ migrations.CreateModel(
+ name="AssignedPageAttribute",
+ fields=[
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ],
+ options={"db_table": "product_assignedpageattribute"},
+ ),
+ migrations.CreateModel(
+ name="AssignedProductAttribute",
+ fields=[
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ],
+ options={"db_table": "product_assignedproductattribute"},
+ ),
+ migrations.CreateModel(
+ name="AssignedVariantAttribute",
+ fields=[
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ],
+ options={"db_table": "product_assignedvariantattribute"},
+ ),
+ migrations.CreateModel(
+ name="Attribute",
+ fields=[
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ (
+ "private_metadata",
+ models.JSONField(
+ blank=True,
+ default=dict,
+ encoder=saleor.core.utils.json_serializer.CustomJsonEncoder,
+ null=True,
+ ),
+ ),
+ (
+ "metadata",
+ models.JSONField(
+ blank=True,
+ default=dict,
+ encoder=saleor.core.utils.json_serializer.CustomJsonEncoder,
+ null=True,
+ ),
+ ),
+ (
+ "slug",
+ models.SlugField(allow_unicode=True, max_length=250, unique=True),
+ ),
+ ("name", models.CharField(max_length=255)),
+ (
+ "type",
+ models.CharField(
+ choices=[
+ ("product-type", "Product type"),
+ ("page-type", "Page type"),
+ ],
+ max_length=50,
+ ),
+ ),
+ (
+ "input_type",
+ models.CharField(
+ choices=[
+ ("dropdown", "Dropdown"),
+ ("multiselect", "Multi Select"),
+ ],
+ default="dropdown",
+ max_length=50,
+ ),
+ ),
+ ("value_required", models.BooleanField(blank=True, default=False)),
+ ("is_variant_only", models.BooleanField(blank=True, default=False)),
+ (
+ "visible_in_storefront",
+ models.BooleanField(blank=True, default=True),
+ ),
+ (
+ "filterable_in_storefront",
+ models.BooleanField(blank=True, default=True),
+ ),
+ (
+ "filterable_in_dashboard",
+ models.BooleanField(blank=True, default=True),
+ ),
+ (
+ "storefront_search_position",
+ models.IntegerField(blank=True, default=0),
+ ),
+ ("available_in_grid", models.BooleanField(blank=True, default=True)),
+ ],
+ options={
+ "db_table": "product_attribute",
+ "ordering": ("storefront_search_position", "slug"),
+ },
+ ),
+ migrations.CreateModel(
+ name="AttributeValue",
+ 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),
+ ),
+ ("name", models.CharField(max_length=250)),
+ ("value", models.CharField(blank=True, default="", max_length=100)),
+ ("slug", models.SlugField(allow_unicode=True, max_length=255)),
+ (
+ "attribute",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="values",
+ to="attribute.attribute",
+ ),
+ ),
+ ],
+ options={
+ "db_table": "product_attributevalue",
+ "ordering": ("sort_order", "pk"),
+ "unique_together": {("slug", "attribute")},
+ },
+ ),
+ migrations.CreateModel(
+ name="AttributeVariant",
+ 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),
+ ),
+ (
+ "assigned_variants",
+ models.ManyToManyField(
+ blank=True,
+ related_name="attributesrelated",
+ through="attribute.AssignedVariantAttribute",
+ to="product.ProductVariant",
+ ),
+ ),
+ (
+ "attribute",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="attributevariant",
+ to="attribute.attribute",
+ ),
+ ),
+ (
+ "product_type",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="attributevariant",
+ to="product.producttype",
+ ),
+ ),
+ ],
+ options={
+ "db_table": "product_attributevariant",
+ "ordering": ("sort_order", "pk"),
+ "unique_together": {("attribute", "product_type")},
+ },
+ ),
+ migrations.CreateModel(
+ name="AttributeProduct",
+ 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),
+ ),
+ (
+ "assigned_products",
+ models.ManyToManyField(
+ blank=True,
+ related_name="attributesrelated",
+ through="attribute.AssignedProductAttribute",
+ to="product.Product",
+ ),
+ ),
+ (
+ "attribute",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="attributeproduct",
+ to="attribute.attribute",
+ ),
+ ),
+ (
+ "product_type",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="attributeproduct",
+ to="product.producttype",
+ ),
+ ),
+ ],
+ options={
+ "db_table": "product_attributeproduct",
+ "ordering": ("sort_order", "pk"),
+ "unique_together": {("attribute", "product_type")},
+ },
+ ),
+ migrations.CreateModel(
+ name="AttributePage",
+ 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),
+ ),
+ (
+ "assigned_pages",
+ models.ManyToManyField(
+ blank=True,
+ related_name="attributesrelated",
+ through="attribute.AssignedPageAttribute",
+ to="page.Page",
+ ),
+ ),
+ (
+ "attribute",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="attributepage",
+ to="attribute.attribute",
+ ),
+ ),
+ (
+ "page_type",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="attributepage",
+ to="page.pagetype",
+ ),
+ ),
+ ],
+ options={
+ "db_table": "product_attributepage",
+ "ordering": ("sort_order", "pk"),
+ "unique_together": {("attribute", "page_type")},
+ },
+ ),
+ migrations.AddField(
+ model_name="attribute",
+ name="page_types",
+ field=models.ManyToManyField(
+ blank=True,
+ related_name="page_attributes",
+ through="attribute.AttributePage",
+ to="page.PageType",
+ ),
+ ),
+ migrations.AddField(
+ model_name="attribute",
+ name="product_types",
+ field=models.ManyToManyField(
+ blank=True,
+ related_name="product_attributes",
+ through="attribute.AttributeProduct",
+ to="product.ProductType",
+ ),
+ ),
+ migrations.AddField(
+ model_name="attribute",
+ name="product_variant_types",
+ field=models.ManyToManyField(
+ blank=True,
+ related_name="variant_attributes",
+ through="attribute.AttributeVariant",
+ to="product.ProductType",
+ ),
+ ),
+ migrations.AddField(
+ model_name="assignedvariantattribute",
+ name="assignment",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="variantassignments",
+ to="attribute.attributevariant",
+ ),
+ ),
+ migrations.AddField(
+ model_name="assignedvariantattribute",
+ name="values",
+ field=models.ManyToManyField(to="attribute.AttributeValue"),
+ ),
+ migrations.AddField(
+ model_name="assignedvariantattribute",
+ name="variant",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="attributes",
+ to="product.productvariant",
+ ),
+ ),
+ migrations.AddField(
+ model_name="assignedproductattribute",
+ name="assignment",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="productassignments",
+ to="attribute.attributeproduct",
+ ),
+ ),
+ migrations.AddField(
+ model_name="assignedproductattribute",
+ name="product",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="attributes",
+ to="product.product",
+ ),
+ ),
+ migrations.AddField(
+ model_name="assignedproductattribute",
+ name="values",
+ field=models.ManyToManyField(to="attribute.AttributeValue"),
+ ),
+ migrations.AddField(
+ model_name="assignedpageattribute",
+ name="assignment",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="pageassignments",
+ to="attribute.attributepage",
+ ),
+ ),
+ migrations.AddField(
+ model_name="assignedpageattribute",
+ name="page",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="attributes",
+ to="page.page",
+ ),
+ ),
+ migrations.AddField(
+ model_name="assignedpageattribute",
+ name="values",
+ field=models.ManyToManyField(to="attribute.AttributeValue"),
+ ),
+ migrations.CreateModel(
+ name="AttributeValueTranslation",
+ fields=[
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("language_code", models.CharField(max_length=10)),
+ ("name", models.CharField(max_length=100)),
+ (
+ "attribute_value",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="translations",
+ to="attribute.attributevalue",
+ ),
+ ),
+ ],
+ options={
+ "db_table": "product_attributevaluetranslation",
+ "unique_together": {("language_code", "attribute_value")},
+ },
+ ),
+ migrations.CreateModel(
+ name="AttributeTranslation",
+ fields=[
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ("language_code", models.CharField(max_length=10)),
+ ("name", models.CharField(max_length=100)),
+ (
+ "attribute",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="translations",
+ to="attribute.attribute",
+ ),
+ ),
+ ],
+ options={
+ "db_table": "product_attributetranslation",
+ "unique_together": {("language_code", "attribute")},
+ },
+ ),
+ migrations.AlterUniqueTogether(
+ name="assignedvariantattribute",
+ unique_together={("variant", "assignment")},
+ ),
+ migrations.AlterUniqueTogether(
+ name="assignedproductattribute",
+ unique_together={("product", "assignment")},
+ ),
+ migrations.AlterUniqueTogether(
+ name="assignedpageattribute", unique_together={("page", "assignment")},
+ ),
+ ]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(state_operations=state_operations)
+ ]
diff --git a/saleor/attribute/migrations/0002_auto_20201030_1141.py b/saleor/attribute/migrations/0002_auto_20201030_1141.py
new file mode 100644
index 0000000000..272690efda
--- /dev/null
+++ b/saleor/attribute/migrations/0002_auto_20201030_1141.py
@@ -0,0 +1,24 @@
+# Generated by Django 3.1 on 2020-10-30 11:41
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("attribute", "0001_initial"),
+ ("product", "0137_drop_attribute_models"),
+ ]
+
+ operations = [
+ migrations.AlterModelTable(name="assignedpageattribute", table=None,),
+ migrations.AlterModelTable(name="assignedproductattribute", table=None,),
+ migrations.AlterModelTable(name="assignedvariantattribute", table=None,),
+ migrations.AlterModelTable(name="attribute", table=None,),
+ migrations.AlterModelTable(name="attributepage", table=None,),
+ migrations.AlterModelTable(name="attributeproduct", table=None,),
+ migrations.AlterModelTable(name="attributetranslation", table=None,),
+ migrations.AlterModelTable(name="attributevalue", table=None,),
+ migrations.AlterModelTable(name="attributevaluetranslation", table=None,),
+ migrations.AlterModelTable(name="attributevariant", table=None,),
+ ]
diff --git a/saleor/attribute/migrations/__init__.py b/saleor/attribute/migrations/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/attribute/models.py b/saleor/attribute/models.py
new file mode 100644
index 0000000000..eaebf66dc8
--- /dev/null
+++ b/saleor/attribute/models.py
@@ -0,0 +1,343 @@
+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 AttributeInputType, AttributeType
+
+if TYPE_CHECKING:
+ 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
+
+ @property
+ def attribute(self):
+ return self.assignment.attribute
+
+ @property
+ def attribute_pk(self):
+ 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."""
+
+ page = models.ForeignKey(Page, related_name="attributes", on_delete=models.CASCADE)
+ assignment = models.ForeignKey(
+ "AttributePage", on_delete=models.CASCADE, related_name="pageassignments"
+ )
+
+ class Meta:
+ unique_together = (("page", "assignment"),)
+
+
+class AssociatedAttributeQuerySet(BaseAttributeQuerySet):
+ def get_public_attributes(self):
+ 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(
+ Q(attributeproduct__product_type_id=product_type_pk)
+ | Q(attributevariant__product_type_id=product_type_pk)
+ )
+
+ def get_unassigned_page_type_attributes(self, page_type_pk: int):
+ return self.page_type_attributes().exclude(
+ attributepage__page_type_id=page_type_pk
+ )
+
+ def get_assigned_product_type_attributes(self, product_type_pk: int):
+ return self.product_type_attributes().filter(
+ Q(attributeproduct__product_type_id=product_type_pk)
+ | Q(attributevariant__product_type_id=product_type_pk)
+ )
+
+ def get_assigned_page_type_attributes(self, product_type_pk: int):
+ return self.page_type_attributes().filter(
+ Q(attributepage__page_type_id=product_type_pk)
+ )
+
+ def get_public_attributes(self):
+ return self.filter(visible_in_storefront=True)
+
+ def _get_sorted_m2m_field(self, m2m_field_name: str, asc: bool):
+ sort_order_field = F(f"{m2m_field_name}__sort_order")
+ id_field = F(f"{m2m_field_name}__id")
+ if asc:
+ sort_method = sort_order_field.asc(nulls_last=True)
+ id_sort: Union["OrderBy", "F"] = id_field
+ else:
+ sort_method = sort_order_field.desc(nulls_first=True)
+ id_sort = id_field.desc()
+
+ return self.order_by(sort_method, id_sort)
+
+ def product_attributes_sorted(self, asc=True):
+ return self._get_sorted_m2m_field("attributeproduct", asc)
+
+ def variant_attributes_sorted(self, asc=True):
+ return self._get_sorted_m2m_field("attributevariant", asc)
+
+ def product_type_attributes(self):
+ return self.filter(type=AttributeType.PRODUCT_TYPE)
+
+ def page_type_attributes(self):
+ return self.filter(type=AttributeType.PAGE_TYPE)
+
+
+class Attribute(ModelWithMetadata):
+ slug = models.SlugField(max_length=250, unique=True, allow_unicode=True)
+ name = models.CharField(max_length=255)
+ type = models.CharField(max_length=50, choices=AttributeType.CHOICES)
+
+ input_type = models.CharField(
+ max_length=50,
+ choices=AttributeInputType.CHOICES,
+ default=AttributeInputType.DROPDOWN,
+ )
+
+ product_types = models.ManyToManyField(
+ ProductType,
+ blank=True,
+ related_name="product_attributes",
+ through=AttributeProduct,
+ through_fields=("attribute", "product_type"),
+ )
+ product_variant_types = models.ManyToManyField(
+ ProductType,
+ blank=True,
+ related_name="variant_attributes",
+ through=AttributeVariant,
+ through_fields=("attribute", "product_type"),
+ )
+ page_types = models.ManyToManyField(
+ PageType,
+ blank=True,
+ related_name="page_attributes",
+ through=AttributePage,
+ through_fields=("attribute", "page_type"),
+ )
+
+ value_required = models.BooleanField(default=False, blank=True)
+ is_variant_only = models.BooleanField(default=False, blank=True)
+ visible_in_storefront = models.BooleanField(default=True, blank=True)
+
+ filterable_in_storefront = models.BooleanField(default=True, blank=True)
+ filterable_in_dashboard = models.BooleanField(default=True, blank=True)
+
+ storefront_search_position = models.IntegerField(default=0, blank=True)
+ available_in_grid = models.BooleanField(default=True, blank=True)
+
+ objects = AttributeQuerySet.as_manager()
+ translated = TranslationProxy()
+
+ class Meta:
+ ordering = ("storefront_search_position", "slug")
+
+ def __str__(self) -> str:
+ return self.name
+
+ def has_values(self) -> bool:
+ return self.values.exists()
+
+
+class AttributeTranslation(models.Model):
+ language_code = models.CharField(max_length=10)
+ attribute = models.ForeignKey(
+ Attribute, related_name="translations", on_delete=models.CASCADE
+ )
+ name = models.CharField(max_length=100)
+
+ class Meta:
+ unique_together = (("language_code", "attribute"),)
+
+ def __repr__(self):
+ class_ = type(self)
+ return "%s(pk=%r, name=%r, attribute_pk=%r)" % (
+ class_.__name__,
+ self.pk,
+ self.name,
+ self.attribute_id,
+ )
+
+ def __str__(self) -> str:
+ return self.name
+
+
+class AttributeValue(SortableModel):
+ name = models.CharField(max_length=250)
+ value = models.CharField(max_length=100, blank=True, default="")
+ slug = models.SlugField(max_length=255, allow_unicode=True)
+ attribute = models.ForeignKey(
+ Attribute, related_name="values", on_delete=models.CASCADE
+ )
+
+ translated = TranslationProxy()
+
+ class Meta:
+ ordering = ("sort_order", "pk")
+ unique_together = ("slug", "attribute")
+
+ def __str__(self) -> str:
+ return self.name
+
+ @property
+ def input_type(self):
+ return self.attribute.input_type
+
+ def get_ordering_queryset(self):
+ return self.attribute.values.all()
+
+
+class AttributeValueTranslation(models.Model):
+ language_code = models.CharField(max_length=10)
+ attribute_value = models.ForeignKey(
+ AttributeValue, related_name="translations", on_delete=models.CASCADE
+ )
+ name = models.CharField(max_length=100)
+
+ class Meta:
+ unique_together = (("language_code", "attribute_value"),)
+
+ def __repr__(self) -> str:
+ class_ = type(self)
+ return "%s(pk=%r, name=%r, attribute_value_pk=%r)" % (
+ class_.__name__,
+ self.pk,
+ self.name,
+ self.attribute_value_id,
+ )
+
+ def __str__(self) -> str:
+ return self.name
diff --git a/saleor/attribute/tests/__init__.py b/saleor/attribute/tests/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/attribute/tests/test_utils.py b/saleor/attribute/tests/test_utils.py
new file mode 100644
index 0000000000..3d093bdde5
--- /dev/null
+++ b/saleor/attribute/tests/test_utils.py
@@ -0,0 +1,47 @@
+import pytest
+
+from ..models import ProductType
+from ..utils import associate_attribute_values_to_instance
+
+
+def test_associate_attribute_to_non_product_instance(color_attribute):
+ instance = ProductType()
+ attribute = color_attribute
+ value = color_attribute.values.first()
+
+ with pytest.raises(AssertionError) as exc:
+ associate_attribute_values_to_instance(instance, attribute, value) # noqa
+
+ assert exc.value.args == ("ProductType is unsupported",)
+
+
+def test_associate_attribute_to_product_instance_from_different_attribute(
+ product, color_attribute, size_attribute
+):
+ """Ensure an assertion error is raised when one tries to associate attribute values
+ to an object that don't belong to the supplied attribute.
+ """
+ instance = product
+ attribute = color_attribute
+ value = size_attribute.values.first()
+
+ with pytest.raises(AssertionError) as exc:
+ associate_attribute_values_to_instance(instance, attribute, value)
+
+ assert exc.value.args == ("Some values are not from the provided attribute.",)
+
+
+def test_associate_attribute_to_product_instance_without_values(product):
+ """Ensure clearing the values from a product is properly working."""
+ old_assignment = product.attributes.first()
+ assert old_assignment is not None, "The product doesn't have attribute-values"
+ assert old_assignment.values.count() == 1
+
+ attribute = old_assignment.attribute
+
+ # Clear the values
+ new_assignment = associate_attribute_values_to_instance(product, attribute)
+
+ # Ensure the values were cleared and no new assignment entry was created
+ assert new_assignment.pk == old_assignment.pk
+ assert new_assignment.values.count() == 0
diff --git a/saleor/product/utils/attributes.py b/saleor/attribute/utils.py
similarity index 68%
rename from saleor/product/utils/attributes.py
rename to saleor/attribute/utils.py
index 3b2d9f9bcb..2771028c78 100644
--- a/saleor/product/utils/attributes.py
+++ b/saleor/attribute/utils.py
@@ -1,42 +1,32 @@
-from typing import TYPE_CHECKING, Optional, Set, Union
+from typing import TYPE_CHECKING, Set, Union
-from ..models import (
+from ..page.models import Page
+from ..product.models import Product, ProductVariant
+from .models import (
+ AssignedPageAttribute,
AssignedProductAttribute,
AssignedVariantAttribute,
Attribute,
AttributeValue,
- Product,
- ProductVariant,
)
-AttributeAssignmentType = Union[AssignedProductAttribute, AssignedVariantAttribute]
+AttributeAssignmentType = Union[
+ AssignedProductAttribute, AssignedVariantAttribute, AssignedPageAttribute
+]
if TYPE_CHECKING:
- # flake8: noqa
- from ..models import AttributeProduct, AttributeVariant
-
-
-def generate_name_for_variant(variant: ProductVariant) -> str:
- """Generate ProductVariant's name based on its attributes."""
- attributes_display = []
-
- for attribute_rel in variant.attributes.all(): # type: AssignedVariantAttribute
- values_qs = attribute_rel.values.all() # FIXME: this should be sorted
- translated_values = [str(value.translated) for value in values_qs]
- attributes_display.append(", ".join(translated_values))
-
- return " / ".join(attributes_display)
+ from .models import AttributeProduct, AttributeVariant, AttributePage
def _associate_attribute_to_instance(
- instance: Union[Product, ProductVariant], attribute_pk: int
+ instance: Union[Product, ProductVariant, Page], attribute_pk: int
) -> AttributeAssignmentType:
"""Associate a given attribute to an instance."""
- assignment: Union["AssignedProductAttribute", "AssignedVariantAttribute"]
+ assignment: AttributeAssignmentType
if isinstance(instance, Product):
attribute_rel: Union[
- "AttributeProduct", "AttributeVariant"
+ "AttributeProduct", "AttributeVariant", "AttributePage"
] = instance.product_type.attributeproduct.get(attribute_id=attribute_pk)
assignment, _ = AssignedProductAttribute.objects.get_or_create(
@@ -50,6 +40,11 @@ def _associate_attribute_to_instance(
assignment, _ = AssignedVariantAttribute.objects.get_or_create(
variant=instance, assignment=attribute_rel
)
+ elif isinstance(instance, Page):
+ attribute_rel = instance.page_type.attributepage.get(attribute_id=attribute_pk)
+ assignment, _ = AssignedPageAttribute.objects.get_or_create(
+ page=instance, assignment=attribute_rel
+ )
else:
raise AssertionError(f"{instance.__class__.__name__} is unsupported")
@@ -68,7 +63,7 @@ def validate_attribute_owns_values(attribute: Attribute, value_ids: Set[int]) ->
def associate_attribute_values_to_instance(
- instance: Union[Product, ProductVariant],
+ instance: Union[Product, ProductVariant, Page],
attribute: Attribute,
*values: AttributeValue,
) -> AttributeAssignmentType:
diff --git a/saleor/core/management/commands/cleardb.py b/saleor/core/management/commands/cleardb.py
index f9d6146d5d..f9dd377d1f 100644
--- a/saleor/core/management/commands/cleardb.py
+++ b/saleor/core/management/commands/cleardb.py
@@ -10,13 +10,14 @@ from django.core.management.base import BaseCommand, CommandError
from django.db.models import Q
from ....account.models import User
+from ....attribute.models import Attribute
from ....checkout.models import Checkout
from ....discount.models import Sale, Voucher
from ....giftcard.models import GiftCard
from ....order.models import Order
from ....page.models import Page
from ....payment.models import Payment, Transaction
-from ....product.models import Attribute, Category, Collection, Product, ProductType
+from ....product.models import Category, Collection, Product, ProductType
from ....shipping.models import ShippingMethod, ShippingZone
from ....warehouse.models import Warehouse
from ....webhook.models import Webhook
diff --git a/saleor/core/management/commands/populatedb.py b/saleor/core/management/commands/populatedb.py
index d0469167d8..79a40506f8 100644
--- a/saleor/core/management/commands/populatedb.py
+++ b/saleor/core/management/commands/populatedb.py
@@ -14,6 +14,7 @@ from ...utils.random_data import (
create_menus,
create_orders,
create_page,
+ create_page_type,
create_permission_groups,
create_product_sales,
create_products_by_schema,
@@ -101,6 +102,10 @@ class Command(BaseCommand):
self.stdout.write(msg)
create_warehouses()
self.stdout.write("Created warehouses")
+ for msg in create_page_type():
+ self.stdout.write(msg)
+ for msg in create_page():
+ self.stdout.write(msg)
create_products_by_schema(self.placeholders_dir, create_images)
self.stdout.write("Created products")
for msg in create_product_sales(5):
diff --git a/saleor/core/permissions.py b/saleor/core/permissions.py
index 609526ec92..6bb8d2bb7a 100644
--- a/saleor/core/permissions.py
+++ b/saleor/core/permissions.py
@@ -51,6 +51,10 @@ class PagePermissions(BasePermissionEnum):
MANAGE_PAGES = "page.manage_pages"
+class PageTypePermissions(BasePermissionEnum):
+ MANAGE_PAGE_TYPES_AND_ATTRIBUTES = "page.manage_page_types_and_attributes"
+
+
class ProductPermissions(BasePermissionEnum):
MANAGE_PRODUCTS = "product.manage_products"
@@ -78,6 +82,7 @@ PERMISSIONS_ENUMS = [
MenuPermissions,
OrderPermissions,
PagePermissions,
+ PageTypePermissions,
ProductPermissions,
ProductTypePermissions,
ShippingPermissions,
diff --git a/saleor/core/tests/test_core.py b/saleor/core/tests/test_core.py
index 4f75b0b1d8..a0215a50be 100644
--- a/saleor/core/tests/test_core.py
+++ b/saleor/core/tests/test_core.py
@@ -162,6 +162,10 @@ def test_create_fake_order(db, monkeypatch, image, media_root, warehouse):
pass
for _ in random_data.create_users(3):
pass
+ for msg in random_data.create_page_type():
+ pass
+ for msg in random_data.create_page():
+ pass
random_data.create_products_by_schema("/", False)
how_many = 2
for _ in random_data.create_orders(how_many):
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.py
index b23eff735b..7d2480faac 100644
--- a/saleor/core/utils/random_data.py
+++ b/saleor/core/utils/random_data.py
@@ -24,6 +24,16 @@ from prices import Money, TaxedMoney
from ...account.models import Address, User
from ...account.utils import store_user_address
+from ...attribute.models import (
+ AssignedPageAttribute,
+ AssignedProductAttribute,
+ AssignedVariantAttribute,
+ Attribute,
+ AttributePage,
+ AttributeProduct,
+ AttributeValue,
+ AttributeVariant,
+)
from ...channel.models import Channel
from ...checkout import AddressType
from ...core.permissions import (
@@ -42,17 +52,11 @@ from ...giftcard.models import GiftCard
from ...menu.models import Menu
from ...order.models import Fulfillment, Order, OrderLine
from ...order.utils import update_order_status
-from ...page.models import Page
+from ...page.models import Page, PageType
from ...payment import gateway
from ...payment.utils import create_payment
from ...plugins.manager import get_plugins_manager
from ...product.models import (
- AssignedProductAttribute,
- AssignedVariantAttribute,
- Attribute,
- AttributeProduct,
- AttributeValue,
- AttributeVariant,
Category,
Collection,
CollectionChannelListing,
@@ -318,6 +322,17 @@ def assign_attributes_to_product_types(
association_model.objects.update_or_create(pk=pk, defaults=defaults)
+def assign_attributes_to_page_types(
+ association_model: AttributePage, attributes: list,
+):
+ for value in attributes:
+ pk = value["pk"]
+ defaults = value["fields"]
+ defaults["attribute_id"] = defaults.pop("attribute")
+ defaults["page_type_id"] = defaults.pop("page_type")
+ association_model.objects.update_or_create(pk=pk, defaults=defaults)
+
+
def assign_attributes_to_products(product_attributes):
for value in product_attributes:
pk = value["pk"]
@@ -346,6 +361,20 @@ def assign_attributes_to_variants(variant_attributes):
assoc.values.set(AttributeValue.objects.filter(pk__in=assigned_values))
+def assign_attributes_to_pages(page_attributes):
+ for value in page_attributes:
+ pk = value["pk"]
+ defaults = value["fields"]
+ defaults["page_id"] = defaults.pop("page")
+ defaults["assignment_id"] = defaults.pop("assignment")
+ assigned_values = defaults.pop("values")
+ assoc, created = AssignedPageAttribute.objects.update_or_create(
+ pk=pk, defaults=defaults
+ )
+ if created:
+ assoc.values.set(AttributeValue.objects.filter(pk__in=assigned_values))
+
+
def set_field_as_money(defaults, field):
amount_field = f"{field}_amount"
if amount_field in defaults and defaults[amount_field] is not None:
@@ -390,12 +419,16 @@ def create_products_by_schema(placeholder_dir, create_images):
assign_attributes_to_product_types(
AttributeVariant, attributes=types["product.attributevariant"]
)
+ assign_attributes_to_page_types(
+ AttributePage, attributes=types["product.attributepage"]
+ )
assign_attributes_to_products(
product_attributes=types["product.assignedproductattribute"]
)
assign_attributes_to_variants(
variant_attributes=types["product.assignedvariantattribute"]
)
+ assign_attributes_to_pages(page_attributes=types["product.assignedpageattribute"])
create_collections(
data=types["product.collection"], placeholder_dir=placeholder_dir
)
@@ -1185,6 +1218,35 @@ def add_address_to_admin(email):
store_user_address(user, address, AddressType.SHIPPING)
+def create_page_type():
+ data = [
+ {
+ "pk": 1,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "name": "About",
+ "slug": "about",
+ },
+ },
+ {
+ "pk": 2,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "name": "Mission",
+ "slug": "mission",
+ },
+ },
+ ]
+ for page_type_data in data:
+ pk = page_type_data.pop("pk")
+ page_type, _ = PageType.objects.update_or_create(
+ pk=pk, **page_type_data["fields"]
+ )
+ yield "Page type %s created" % page_type.slug
+
+
def create_page():
content = """
<h2>E-commerce for the PWA era</h2>
@@ -1243,8 +1305,9 @@ def create_page():
"content_json": content_json,
"title": "About",
"is_published": True,
+ "page_type_id": 1,
}
- page, dummy = Page.objects.get_or_create(slug="about", defaults=page_data)
+ page, dummy = Page.objects.get_or_create(pk=1, slug="about", defaults=page_data)
yield "Page %s created" % page.slug
diff --git a/saleor/csv/tests/export/products_data/test_get_products_data.py b/saleor/csv/tests/export/products_data/test_get_products_data.py
index 0f431d76f1..5d121ac136 100644
--- a/saleor/csv/tests/export/products_data/test_get_products_data.py
+++ b/saleor/csv/tests/export/products_data/test_get_products_data.py
@@ -1,7 +1,8 @@
from measurement.measures import Weight
+from .....attribute.models import Attribute
from .....channel.models import Channel
-from .....product.models import Attribute, Product, ProductVariant, VariantImage
+from .....product.models import Product, ProductVariant, VariantImage
from .....warehouse.models import Warehouse
from ....utils import ProductExportFields
from ....utils.products_data import get_products_data
diff --git a/saleor/csv/tests/export/products_data/test_handle_relations_data.py b/saleor/csv/tests/export/products_data/test_handle_relations_data.py
index c37f8192e5..f6fae7743a 100644
--- a/saleor/csv/tests/export/products_data/test_handle_relations_data.py
+++ b/saleor/csv/tests/export/products_data/test_handle_relations_data.py
@@ -1,6 +1,7 @@
from unittest.mock import patch
-from .....product.models import Attribute, Product, ProductImage, VariantImage
+from .....attribute.models import Attribute
+from .....product.models import Product, ProductImage, VariantImage
from .....warehouse.models import Warehouse
from ....utils import ProductExportFields
from ....utils.products_data import (
diff --git a/saleor/csv/tests/export/products_data/test_prepare_headers.py b/saleor/csv/tests/export/products_data/test_prepare_headers.py
index 3ac514a3af..f911dfdc5a 100644
--- a/saleor/csv/tests/export/products_data/test_prepare_headers.py
+++ b/saleor/csv/tests/export/products_data/test_prepare_headers.py
@@ -1,6 +1,6 @@
+from .....attribute.models import Attribute
from .....channel.models import Channel
from .....graphql.csv.enums import ProductFieldEnum
-from .....product.models import Attribute
from ....utils.product_headers import (
get_attributes_headers,
get_channels_headers,
diff --git a/saleor/csv/utils/product_headers.py b/saleor/csv/utils/product_headers.py
index cbe1886135..370fdf2365 100644
--- a/saleor/csv/utils/product_headers.py
+++ b/saleor/csv/utils/product_headers.py
@@ -4,8 +4,8 @@ from typing import Dict, List, Tuple
from django.db.models import Value as V
from django.db.models.functions import Concat
+from ...attribute.models import Attribute
from ...channel.models import Channel
-from ...product.models import Attribute
from ...warehouse.models import Warehouse
from . import ProductExportFields
diff --git a/saleor/graphql/api.py b/saleor/graphql/api.py
index a2f3a3b99f..059395a781 100644
--- a/saleor/graphql/api.py
+++ b/saleor/graphql/api.py
@@ -2,6 +2,7 @@ from graphene_federation import build_schema
from .account.schema import AccountMutations, AccountQueries
from .app.schema import AppMutations, AppQueries
+from .attribute.schema import AttributeMutations, AttributeQueries
from .channel.schema import ChannelMutations, ChannelQueries
from .checkout.schema import CheckoutMutations, CheckoutQueries
from .core.schema import CoreMutations, CoreQueries
@@ -26,6 +27,7 @@ from .webhook.schema import WebhookMutations, WebhookQueries
class Query(
AccountQueries,
AppQueries,
+ AttributeQueries,
ChannelQueries,
CheckoutQueries,
CoreQueries,
@@ -51,6 +53,7 @@ class Query(
class Mutation(
AccountMutations,
AppMutations,
+ AttributeMutations,
ChannelMutations,
CheckoutMutations,
CoreMutations,
diff --git a/saleor/graphql/attribute/__init__.py b/saleor/graphql/attribute/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/graphql/product/bulk_mutations/attributes.py b/saleor/graphql/attribute/bulk_mutations.py
similarity index 56%
rename from saleor/graphql/product/bulk_mutations/attributes.py
rename to saleor/graphql/attribute/bulk_mutations.py
index da395df895..92d39e6554 100644
--- a/saleor/graphql/product/bulk_mutations/attributes.py
+++ b/saleor/graphql/attribute/bulk_mutations.py
@@ -1,9 +1,9 @@
import graphene
-from ....core.permissions import ProductPermissions
-from ....product import models
-from ...core.mutations import ModelBulkDeleteMutation
-from ...core.types.common import ProductError
+from ...attribute import models
+from ...core.permissions import PageTypePermissions
+from ..core.mutations import ModelBulkDeleteMutation
+from ..core.types.common import AttributeError
class AttributeBulkDelete(ModelBulkDeleteMutation):
@@ -15,9 +15,9 @@ class AttributeBulkDelete(ModelBulkDeleteMutation):
class Meta:
description = "Deletes attributes."
model = models.Attribute
- permissions = (ProductPermissions.MANAGE_PRODUCTS,)
- error_type_class = ProductError
- error_type_field = "product_errors"
+ permissions = (PageTypePermissions.MANAGE_PAGE_TYPES_AND_ATTRIBUTES,)
+ error_type_class = AttributeError
+ error_type_field = "attribute_errors"
class AttributeValueBulkDelete(ModelBulkDeleteMutation):
@@ -31,6 +31,6 @@ class AttributeValueBulkDelete(ModelBulkDeleteMutation):
class Meta:
description = "Deletes values of attributes."
model = models.AttributeValue
- permissions = (ProductPermissions.MANAGE_PRODUCTS,)
- error_type_class = ProductError
- error_type_field = "product_errors"
+ permissions = (PageTypePermissions.MANAGE_PAGE_TYPES_AND_ATTRIBUTES,)
+ error_type_class = AttributeError
+ error_type_field = "attribute_errors"
diff --git a/saleor/graphql/attribute/dataloaders.py b/saleor/graphql/attribute/dataloaders.py
new file mode 100644
index 0000000000..4f34fb0563
--- /dev/null
+++ b/saleor/graphql/attribute/dataloaders.py
@@ -0,0 +1,33 @@
+from collections import defaultdict
+
+from ...attribute.models import Attribute, AttributeValue
+from ..core.dataloaders import DataLoader
+
+
+class AttributeValuesByAttributeIdLoader(DataLoader):
+ context_key = "attributevalues_by_attribute"
+
+ def batch_load(self, keys):
+ attribute_values = AttributeValue.objects.filter(attribute_id__in=keys)
+ attribute_to_attributevalues = defaultdict(list)
+ for attribute_value in attribute_values.iterator():
+ attribute_to_attributevalues[attribute_value.attribute_id].append(
+ attribute_value
+ )
+ return [attribute_to_attributevalues[attribute_id] for attribute_id in keys]
+
+
+class AttributesByAttributeId(DataLoader):
+ context_key = "attributes_by_id"
+
+ def batch_load(self, keys):
+ attributes = Attribute.objects.in_bulk(keys)
+ return [attributes.get(key) for key in keys]
+
+
+class AttributeValueByIdLoader(DataLoader):
+ context_key = "attributevalue_by_id"
+
+ def batch_load(self, keys):
+ attribute_values = AttributeValue.objects.in_bulk(keys)
+ return [attribute_values.get(attribute_value_id) for attribute_value_id in keys]
diff --git a/saleor/graphql/product/descriptions.py b/saleor/graphql/attribute/descriptions.py
similarity index 97%
rename from saleor/graphql/product/descriptions.py
rename to saleor/graphql/attribute/descriptions.py
index d079fdd0ff..e2d9139c55 100644
--- a/saleor/graphql/product/descriptions.py
+++ b/saleor/graphql/attribute/descriptions.py
@@ -2,6 +2,7 @@ class AttributeDescriptions:
INPUT_TYPE = "The input type to use for entering attribute values in the dashboard."
NAME = "Name of an attribute displayed in the interface."
SLUG = "Internal representation of an attribute name."
+ TYPE = "The attribute type."
VALUES = "List of attribute's values."
VALUE_REQUIRED = "Whether the attribute requires values to be passed or not."
IS_VARIANT_ONLY = "Whether the attribute is for variants only."
diff --git a/saleor/graphql/attribute/enums.py b/saleor/graphql/attribute/enums.py
new file mode 100644
index 0000000000..ad109a9f9d
--- /dev/null
+++ b/saleor/graphql/attribute/enums.py
@@ -0,0 +1,14 @@
+import graphene
+
+from ...attribute import AttributeInputType, AttributeType
+from ..core.enums import to_enum
+
+AttributeInputTypeEnum = to_enum(AttributeInputType)
+AttributeTypeEnum = to_enum(AttributeType)
+
+
+class AttributeValueType(graphene.Enum):
+ COLOR = "COLOR"
+ GRADIENT = "GRADIENT"
+ URL = "URL"
+ STRING = "STRING"
diff --git a/saleor/graphql/attribute/filters.py b/saleor/graphql/attribute/filters.py
new file mode 100644
index 0000000000..9cf482ea1f
--- /dev/null
+++ b/saleor/graphql/attribute/filters.py
@@ -0,0 +1,99 @@
+import django_filters
+from django.db.models import Q
+from graphene_django.filter import GlobalIDFilter, GlobalIDMultipleChoiceFilter
+
+from ...attribute.models import Attribute
+from ...product.models import Category, Product
+from ..attribute.enums import AttributeTypeEnum
+from ..channel.filters import get_channel_slug_from_filter_data
+from ..core.filters import EnumFilter
+from ..core.types import ChannelFilterInputObjectType
+from ..core.utils import from_global_id_strict_type
+from ..utils import get_user_or_app_from_context
+from ..utils.filters import filter_fields_containing_value
+
+
+def filter_attributes_by_product_types(qs, field, value, requestor, channel_slug):
+ if not value:
+ return qs
+
+ product_qs = Product.objects.visible_to_user(requestor, channel_slug)
+
+ if field == "in_category":
+ category_id = from_global_id_strict_type(
+ value, only_type="Category", field=field
+ )
+ category = Category.objects.filter(pk=category_id).first()
+
+ if category is None:
+ return qs.none()
+
+ tree = category.get_descendants(include_self=True)
+ product_qs = product_qs.filter(category__in=tree)
+
+ if not product_qs.user_has_access_to_all(requestor):
+ product_qs = product_qs.annotate_visible_in_listings(channel_slug).exclude(
+ visible_in_listings=False
+ )
+
+ elif field == "in_collection":
+ collection_id = from_global_id_strict_type(
+ value, only_type="Collection", field=field
+ )
+ product_qs = product_qs.filter(collections__id=collection_id)
+
+ else:
+ raise NotImplementedError(f"Filtering by {field} is unsupported")
+
+ product_types = set(product_qs.values_list("product_type_id", flat=True))
+ return qs.filter(
+ Q(product_types__in=product_types) | Q(product_variant_types__in=product_types)
+ )
+
+
+def filter_attribute_type(qs, _, value):
+ if not value:
+ return qs
+ return qs.filter(type=value)
+
+
+class AttributeFilter(django_filters.FilterSet):
+ # Search by attribute name and slug
+ search = django_filters.CharFilter(
+ method=filter_fields_containing_value("slug", "name")
+ )
+ ids = GlobalIDMultipleChoiceFilter(field_name="id")
+ type = EnumFilter(input_class=AttributeTypeEnum, method=filter_attribute_type)
+
+ in_collection = GlobalIDFilter(method="filter_in_collection")
+ in_category = GlobalIDFilter(method="filter_in_category")
+
+ class Meta:
+ model = Attribute
+ fields = [
+ "value_required",
+ "is_variant_only",
+ "visible_in_storefront",
+ "filterable_in_storefront",
+ "filterable_in_dashboard",
+ "available_in_grid",
+ ]
+
+ def filter_in_collection(self, queryset, name, value):
+ requestor = get_user_or_app_from_context(self.request)
+ channel_slug = get_channel_slug_from_filter_data(self.data)
+ return filter_attributes_by_product_types(
+ queryset, name, value, requestor, channel_slug
+ )
+
+ def filter_in_category(self, queryset, name, value):
+ requestor = get_user_or_app_from_context(self.request)
+ channel_slug = get_channel_slug_from_filter_data(self.data)
+ return filter_attributes_by_product_types(
+ queryset, name, value, requestor, channel_slug
+ )
+
+
+class AttributeFilterInput(ChannelFilterInputObjectType):
+ class Meta:
+ filterset_class = AttributeFilter
diff --git a/saleor/graphql/attribute/mutations.py b/saleor/graphql/attribute/mutations.py
new file mode 100644
index 0000000000..72137b2b8e
--- /dev/null
+++ b/saleor/graphql/attribute/mutations.py
@@ -0,0 +1,532 @@
+from typing import TYPE_CHECKING
+
+import graphene
+from django.core.exceptions import ObjectDoesNotExist, ValidationError
+from django.db import transaction
+from django.utils.text import slugify
+
+from ...attribute import models as models
+from ...attribute.error_codes import AttributeErrorCode
+from ...core.exceptions import PermissionDenied
+from ...core.permissions import (
+ PageTypePermissions,
+ ProductPermissions,
+ ProductTypePermissions,
+)
+from ..attribute.types import Attribute, AttributeValue
+from ..core.inputs import ReorderInput
+from ..core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation
+from ..core.types.common import AttributeError
+from ..core.utils import (
+ from_global_id_strict_type,
+ validate_slug_and_generate_if_needed,
+)
+from ..core.utils.reordering import perform_reordering
+from ..utils import resolve_global_ids_to_primary_keys
+from .descriptions import AttributeDescriptions, AttributeValueDescriptions
+from .enums import AttributeInputTypeEnum, AttributeTypeEnum
+
+if TYPE_CHECKING:
+ from django.db.models import QuerySet
+
+
+class BaseReorderAttributesMutation(BaseMutation):
+ class Meta:
+ abstract = True
+
+ @classmethod
+ def prepare_operations(cls, moves: ReorderInput, attributes: "QuerySet"):
+ """Prepare operations dict for reordering attributes.
+
+ Operation dict format:
+ key: attribute pk,
+ value: sort_order value - relative sorting position of the attribute
+ """
+ attribute_ids = []
+ sort_orders = []
+
+ # resolve attribute moves
+ for move_info in moves:
+ attribute_ids.append(move_info.id)
+ sort_orders.append(move_info.sort_order)
+
+ _, attr_pks = resolve_global_ids_to_primary_keys(attribute_ids, Attribute)
+ attr_pks = [int(pk) for pk in attr_pks]
+
+ attributes_m2m = attributes.filter(attribute_id__in=attr_pks)
+
+ if attributes_m2m.count() != len(attr_pks):
+ attribute_pks = attributes_m2m.values_list("attribute_id", flat=True)
+ invalid_attrs = set(attr_pks) - set(attribute_pks)
+ invalid_attr_ids = [
+ graphene.Node.to_global_id("Attribute", attr_pk)
+ for attr_pk in invalid_attrs
+ ]
+ raise ValidationError(
+ "Couldn't resolve to an attribute.",
+ params={"attributes": invalid_attr_ids},
+ )
+
+ attributes_m2m = list(attributes_m2m)
+ attributes_m2m.sort(
+ key=lambda e: attr_pks.index(e.attribute.pk)
+ ) # preserve order in pks
+
+ operations = {
+ attribute.pk: sort_order
+ for attribute, sort_order in zip(attributes_m2m, sort_orders)
+ }
+
+ return operations
+
+
+class AttributeValueCreateInput(graphene.InputObjectType):
+ name = graphene.String(required=True, description=AttributeValueDescriptions.NAME)
+
+
+class AttributeCreateInput(graphene.InputObjectType):
+ input_type = AttributeInputTypeEnum(description=AttributeDescriptions.INPUT_TYPE)
+ name = graphene.String(required=True, description=AttributeDescriptions.NAME)
+ slug = graphene.String(required=False, description=AttributeDescriptions.SLUG)
+ type = AttributeTypeEnum(description=AttributeDescriptions.TYPE, required=True)
+ values = graphene.List(
+ AttributeValueCreateInput, description=AttributeDescriptions.VALUES
+ )
+ value_required = graphene.Boolean(description=AttributeDescriptions.VALUE_REQUIRED)
+ is_variant_only = graphene.Boolean(
+ required=False, description=AttributeDescriptions.IS_VARIANT_ONLY
+ )
+ visible_in_storefront = graphene.Boolean(
+ description=AttributeDescriptions.VISIBLE_IN_STOREFRONT
+ )
+ filterable_in_storefront = graphene.Boolean(
+ description=AttributeDescriptions.FILTERABLE_IN_STOREFRONT
+ )
+ filterable_in_dashboard = graphene.Boolean(
+ description=AttributeDescriptions.FILTERABLE_IN_DASHBOARD
+ )
+ storefront_search_position = graphene.Int(
+ required=False, description=AttributeDescriptions.STOREFRONT_SEARCH_POSITION
+ )
+ available_in_grid = graphene.Boolean(
+ required=False, description=AttributeDescriptions.AVAILABLE_IN_GRID
+ )
+
+
+class AttributeUpdateInput(graphene.InputObjectType):
+ name = graphene.String(description=AttributeDescriptions.NAME)
+ slug = graphene.String(description=AttributeDescriptions.SLUG)
+ remove_values = graphene.List(
+ graphene.ID,
+ name="removeValues",
+ description="IDs of values to be removed from this attribute.",
+ )
+ add_values = graphene.List(
+ AttributeValueCreateInput,
+ name="addValues",
+ description="New values to be created for this attribute.",
+ )
+ value_required = graphene.Boolean(description=AttributeDescriptions.VALUE_REQUIRED)
+ is_variant_only = graphene.Boolean(
+ required=False, description=AttributeDescriptions.IS_VARIANT_ONLY
+ )
+ visible_in_storefront = graphene.Boolean(
+ description=AttributeDescriptions.VISIBLE_IN_STOREFRONT
+ )
+ filterable_in_storefront = graphene.Boolean(
+ description=AttributeDescriptions.FILTERABLE_IN_STOREFRONT
+ )
+ filterable_in_dashboard = graphene.Boolean(
+ description=AttributeDescriptions.FILTERABLE_IN_DASHBOARD
+ )
+ storefront_search_position = graphene.Int(
+ required=False, description=AttributeDescriptions.STOREFRONT_SEARCH_POSITION
+ )
+ available_in_grid = graphene.Boolean(
+ required=False, description=AttributeDescriptions.AVAILABLE_IN_GRID
+ )
+
+
+class AttributeMixin:
+ @classmethod
+ def check_values_are_unique(cls, values_input, attribute):
+ # Check values uniqueness in case of creating new attribute.
+ existing_values = attribute.values.values_list("slug", flat=True)
+ for value_data in values_input:
+ slug = slugify(value_data["name"], allow_unicode=True)
+ if slug in existing_values:
+ msg = (
+ "Value %s already exists within this attribute."
+ % value_data["name"]
+ )
+ raise ValidationError(
+ {
+ cls.ATTRIBUTE_VALUES_FIELD: ValidationError(
+ msg, code=AttributeErrorCode.ALREADY_EXISTS
+ )
+ }
+ )
+
+ new_slugs = [
+ slugify(value_data["name"], allow_unicode=True)
+ for value_data in values_input
+ ]
+ if len(set(new_slugs)) != len(new_slugs):
+ raise ValidationError(
+ {
+ cls.ATTRIBUTE_VALUES_FIELD: ValidationError(
+ "Provided values are not unique.",
+ code=AttributeErrorCode.UNIQUE,
+ )
+ }
+ )
+
+ @classmethod
+ def clean_values(cls, cleaned_input, attribute):
+ """Clean attribute values.
+
+ Transforms AttributeValueCreateInput into AttributeValue instances.
+ Slugs are created from given names and checked for uniqueness within
+ an attribute.
+ """
+ values_input = cleaned_input.get(cls.ATTRIBUTE_VALUES_FIELD)
+
+ if values_input is None:
+ return
+
+ for value_data in values_input:
+ value_data["slug"] = slugify(value_data["name"], allow_unicode=True)
+ attribute_value = models.AttributeValue(**value_data, attribute=attribute)
+ try:
+ attribute_value.full_clean()
+ except ValidationError as validation_errors:
+ for field, err in validation_errors.error_dict.items():
+ if field == "attribute":
+ continue
+ raise ValidationError({cls.ATTRIBUTE_VALUES_FIELD: err})
+ cls.check_values_are_unique(values_input, attribute)
+
+ @classmethod
+ def clean_attribute(cls, instance, cleaned_input):
+ try:
+ cleaned_input = validate_slug_and_generate_if_needed(
+ instance, "name", cleaned_input
+ )
+ except ValidationError as error:
+ error.code = AttributeErrorCode.REQUIRED.value
+ raise ValidationError({"slug": error})
+
+ return cleaned_input
+
+ @classmethod
+ def _save_m2m(cls, info, attribute, cleaned_data):
+ super()._save_m2m(info, attribute, cleaned_data)
+ values = cleaned_data.get(cls.ATTRIBUTE_VALUES_FIELD) or []
+ for value in values:
+ attribute.values.create(**value)
+
+
+class AttributeCreate(AttributeMixin, ModelMutation):
+ # Needed by AttributeMixin,
+ # represents the input name for the passed list of values
+ ATTRIBUTE_VALUES_FIELD = "values"
+
+ attribute = graphene.Field(Attribute, description="The created attribute.")
+
+ class Arguments:
+ input = AttributeCreateInput(
+ required=True, description="Fields required to create an attribute."
+ )
+
+ class Meta:
+ model = models.Attribute
+ description = "Creates an attribute."
+ error_type_class = AttributeError
+ error_type_field = "attribute_errors"
+
+ @classmethod
+ def perform_mutation(cls, _root, info, **data):
+ input = data.get("input")
+ # check permissions based on attribute type
+ if input["type"] == AttributeTypeEnum.PRODUCT_TYPE.value:
+ permissions = (ProductTypePermissions.MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES,)
+ else:
+ permissions = (PageTypePermissions.MANAGE_PAGE_TYPES_AND_ATTRIBUTES,)
+ if not cls.check_permissions(info.context, permissions):
+ raise PermissionDenied()
+
+ instance = models.Attribute()
+
+ # Do cleaning and uniqueness checks
+ cleaned_input = cls.clean_input(info, instance, input)
+ cls.clean_attribute(instance, cleaned_input)
+ cls.clean_values(cleaned_input, instance)
+
+ # Construct the attribute
+ instance = cls.construct_instance(instance, cleaned_input)
+ cls.clean_instance(info, instance)
+
+ # Commit it
+ instance.save()
+ cls._save_m2m(info, instance, cleaned_input)
+
+ # Return the attribute that was created
+ return AttributeCreate(attribute=instance)
+
+
+class AttributeUpdate(AttributeMixin, ModelMutation):
+ # Needed by AttributeMixin,
+ # represents the input name for the passed list of values
+ ATTRIBUTE_VALUES_FIELD = "add_values"
+
+ attribute = graphene.Field(Attribute, description="The updated attribute.")
+
+ class Arguments:
+ id = graphene.ID(required=True, description="ID of an attribute to update.")
+ input = AttributeUpdateInput(
+ required=True, description="Fields required to update an attribute."
+ )
+
+ class Meta:
+ model = models.Attribute
+ description = "Updates attribute."
+ permissions = (ProductTypePermissions.MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES,)
+ error_type_class = AttributeError
+ error_type_field = "attribute_errors"
+
+ @classmethod
+ def clean_remove_values(cls, cleaned_input, instance):
+ """Check if the values to be removed are assigned to the given attribute."""
+ remove_values = cleaned_input.get("remove_values", [])
+ for value in remove_values:
+ if value.attribute != instance:
+ msg = "Value %s does not belong to this attribute." % value
+ raise ValidationError(
+ {
+ "remove_values": ValidationError(
+ msg, code=AttributeErrorCode.INVALID
+ )
+ }
+ )
+ return remove_values
+
+ @classmethod
+ def _save_m2m(cls, info, instance, cleaned_data):
+ super()._save_m2m(info, instance, cleaned_data)
+ for attribute_value in cleaned_data.get("remove_values", []):
+ attribute_value.delete()
+
+ @classmethod
+ def perform_mutation(cls, _root, info, id, input):
+ instance = cls.get_node_or_error(info, id, only_type=Attribute)
+
+ # Do cleaning and uniqueness checks
+ cleaned_input = cls.clean_input(info, instance, input)
+ cls.clean_attribute(instance, cleaned_input)
+ cls.clean_values(cleaned_input, instance)
+ cls.clean_remove_values(cleaned_input, instance)
+
+ # Construct the attribute
+ instance = cls.construct_instance(instance, cleaned_input)
+ cls.clean_instance(info, instance)
+
+ # Commit it
+ instance.save()
+ cls._save_m2m(info, instance, cleaned_input)
+
+ # Return the attribute that was created
+ return AttributeUpdate(attribute=instance)
+
+
+class AttributeDelete(ModelDeleteMutation):
+ class Arguments:
+ id = graphene.ID(required=True, description="ID of an attribute to delete.")
+
+ class Meta:
+ model = models.Attribute
+ description = "Deletes an attribute."
+ permissions = (ProductTypePermissions.MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES,)
+ error_type_class = AttributeError
+ error_type_field = "attribute_errors"
+
+
+def validate_value_is_unique(attribute: models.Attribute, value: models.AttributeValue):
+ """Check if the attribute value is unique within the attribute it belongs to."""
+ duplicated_values = attribute.values.exclude(pk=value.pk).filter(slug=value.slug)
+ if duplicated_values.exists():
+ raise ValidationError(
+ {
+ "name": ValidationError(
+ f"Value with slug {value.slug} already exists.",
+ code=AttributeErrorCode.ALREADY_EXISTS.value,
+ )
+ }
+ )
+
+
+class AttributeValueCreate(ModelMutation):
+ attribute = graphene.Field(Attribute, description="The updated attribute.")
+
+ class Arguments:
+ attribute_id = graphene.ID(
+ required=True,
+ name="attribute",
+ description="Attribute to which value will be assigned.",
+ )
+ input = AttributeValueCreateInput(
+ required=True, description="Fields required to create an AttributeValue."
+ )
+
+ class Meta:
+ model = models.AttributeValue
+ description = "Creates a value for an attribute."
+ permissions = (ProductPermissions.MANAGE_PRODUCTS,)
+ error_type_class = AttributeError
+ error_type_field = "attribute_errors"
+
+ @classmethod
+ def clean_input(cls, info, instance, data):
+ cleaned_input = super().clean_input(info, instance, data)
+ cleaned_input["slug"] = slugify(cleaned_input["name"], allow_unicode=True)
+ return cleaned_input
+
+ @classmethod
+ def clean_instance(cls, info, instance):
+ validate_value_is_unique(instance.attribute, instance)
+ super().clean_instance(info, instance)
+
+ @classmethod
+ def perform_mutation(cls, _root, info, attribute_id, input):
+ attribute = cls.get_node_or_error(info, attribute_id, only_type=Attribute)
+ instance = models.AttributeValue(attribute=attribute)
+ cleaned_input = cls.clean_input(info, instance, input)
+ instance = cls.construct_instance(instance, cleaned_input)
+ cls.clean_instance(info, instance)
+
+ instance.save()
+ cls._save_m2m(info, instance, cleaned_input)
+ return AttributeValueCreate(attribute=attribute, attributeValue=instance)
+
+
+class AttributeValueUpdate(ModelMutation):
+ attribute = graphene.Field(Attribute, description="The updated attribute.")
+
+ class Arguments:
+ id = graphene.ID(
+ required=True, description="ID of an AttributeValue to update."
+ )
+ input = AttributeValueCreateInput(
+ required=True, description="Fields required to update an AttributeValue."
+ )
+
+ class Meta:
+ model = models.AttributeValue
+ description = "Updates value of an attribute."
+ permissions = (ProductTypePermissions.MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES,)
+ error_type_class = AttributeError
+ error_type_field = "attribute_errors"
+
+ @classmethod
+ def clean_input(cls, info, instance, data):
+ cleaned_input = super().clean_input(info, instance, data)
+ if "name" in cleaned_input:
+ cleaned_input["slug"] = slugify(cleaned_input["name"], allow_unicode=True)
+ return cleaned_input
+
+ @classmethod
+ def clean_instance(cls, info, instance):
+ validate_value_is_unique(instance.attribute, instance)
+ super().clean_instance(info, instance)
+
+ @classmethod
+ def success_response(cls, instance):
+ response = super().success_response(instance)
+ response.attribute = instance.attribute
+ return response
+
+
+class AttributeValueDelete(ModelDeleteMutation):
+ attribute = graphene.Field(Attribute, description="The updated attribute.")
+
+ class Arguments:
+ id = graphene.ID(required=True, description="ID of a value to delete.")
+
+ class Meta:
+ model = models.AttributeValue
+ description = "Deletes a value of an attribute."
+ permissions = (ProductTypePermissions.MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES,)
+ error_type_class = AttributeError
+ error_type_field = "attribute_errors"
+
+ @classmethod
+ def success_response(cls, instance):
+ response = super().success_response(instance)
+ response.attribute = instance.attribute
+ return response
+
+
+class AttributeReorderValues(BaseMutation):
+ attribute = graphene.Field(
+ Attribute, description="Attribute from which values are reordered."
+ )
+
+ class Meta:
+ description = "Reorder the values of an attribute."
+ permissions = (ProductTypePermissions.MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES,)
+ error_type_class = AttributeError
+ error_type_field = "attribute_errors"
+
+ class Arguments:
+ 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, attribute_id, moves):
+ pk = from_global_id_strict_type(
+ attribute_id, only_type=Attribute, field="attribute_id"
+ )
+
+ try:
+ attribute = models.Attribute.objects.prefetch_related("values").get(pk=pk)
+ except ObjectDoesNotExist:
+ raise ValidationError(
+ {
+ "attribute_id": ValidationError(
+ f"Couldn't resolve to an attribute: {attribute_id}",
+ code=AttributeErrorCode.NOT_FOUND,
+ )
+ }
+ )
+
+ values_m2m = attribute.values
+ operations = {}
+
+ # Resolve the values
+ for move_info in moves:
+ value_pk = from_global_id_strict_type(
+ move_info.id, only_type=AttributeValue, field="moves"
+ )
+
+ try:
+ m2m_info = values_m2m.get(pk=int(value_pk))
+ except ObjectDoesNotExist:
+ raise ValidationError(
+ {
+ "moves": ValidationError(
+ f"Couldn't resolve to an attribute value: {move_info.id}",
+ code=AttributeErrorCode.NOT_FOUND,
+ )
+ }
+ )
+ operations[m2m_info.pk] = move_info.sort_order
+
+ with transaction.atomic():
+ perform_reordering(values_m2m, operations)
+ attribute.refresh_from_db(fields=["values"])
+ return AttributeReorderValues(attribute=attribute)
diff --git a/saleor/graphql/attribute/resolvers.py b/saleor/graphql/attribute/resolvers.py
new file mode 100644
index 0000000000..ae6ddf3ce3
--- /dev/null
+++ b/saleor/graphql/attribute/resolvers.py
@@ -0,0 +1,8 @@
+from ...attribute import models
+from ..utils import get_user_or_app_from_context
+
+
+def resolve_attributes(info, qs=None, **_kwargs):
+ requestor = get_user_or_app_from_context(info.context)
+ qs = qs or models.Attribute.objects.get_visible_to_user(requestor)
+ return qs.distinct()
diff --git a/saleor/graphql/attribute/schema.py b/saleor/graphql/attribute/schema.py
new file mode 100644
index 0000000000..0efb99273f
--- /dev/null
+++ b/saleor/graphql/attribute/schema.py
@@ -0,0 +1,57 @@
+import graphene
+
+from ..core.fields import FilterInputConnectionField
+from ..translations.mutations import AttributeTranslate, AttributeValueTranslate
+from .bulk_mutations import AttributeBulkDelete, AttributeValueBulkDelete
+from .filters import AttributeFilterInput
+from .mutations import (
+ AttributeCreate,
+ AttributeDelete,
+ AttributeReorderValues,
+ AttributeUpdate,
+ AttributeValueCreate,
+ AttributeValueDelete,
+ AttributeValueUpdate,
+)
+from .resolvers import resolve_attributes
+from .sorters import AttributeSortingInput
+from .types import Attribute
+
+
+class AttributeQueries(graphene.ObjectType):
+ attributes = FilterInputConnectionField(
+ Attribute,
+ description="List of the shop's attributes.",
+ filter=AttributeFilterInput(description="Filtering options for attributes."),
+ sort_by=AttributeSortingInput(description="Sorting options for attributes."),
+ )
+ attribute = graphene.Field(
+ Attribute,
+ id=graphene.Argument(
+ graphene.ID, description="ID of the attribute.", required=True
+ ),
+ description="Look up an attribute by ID.",
+ )
+
+ def resolve_attributes(self, info, **kwargs):
+ return resolve_attributes(info, **kwargs)
+
+ def resolve_attribute(self, info, id):
+ return graphene.Node.get_node_from_global_id(info, id, Attribute)
+
+
+class AttributeMutations(graphene.ObjectType):
+ # attribute mutations
+ attribute_create = AttributeCreate.Field()
+ attribute_delete = AttributeDelete.Field()
+ attribute_update = AttributeUpdate.Field()
+ attribute_translate = AttributeTranslate.Field()
+ attribute_bulk_delete = AttributeBulkDelete.Field()
+ attribute_value_bulk_delete = AttributeValueBulkDelete.Field()
+
+ # attribute value mutations
+ attribute_value_create = AttributeValueCreate.Field()
+ attribute_value_delete = AttributeValueDelete.Field()
+ attribute_value_update = AttributeValueUpdate.Field()
+ attribute_value_translate = AttributeValueTranslate.Field()
+ attribute_reorder_values = AttributeReorderValues.Field()
diff --git a/saleor/graphql/attribute/sorters.py b/saleor/graphql/attribute/sorters.py
new file mode 100644
index 0000000000..85beccc181
--- /dev/null
+++ b/saleor/graphql/attribute/sorters.py
@@ -0,0 +1,54 @@
+import graphene
+
+from ..core.types import SortInputObjectType
+
+
+class AttributeSortField(graphene.Enum):
+ NAME = ["name", "slug"]
+ SLUG = ["slug"]
+ VALUE_REQUIRED = ["value_required", "name", "slug"]
+ IS_VARIANT_ONLY = ["is_variant_only", "name", "slug"]
+ VISIBLE_IN_STOREFRONT = ["visible_in_storefront", "name", "slug"]
+ FILTERABLE_IN_STOREFRONT = ["filterable_in_storefront", "name", "slug"]
+ FILTERABLE_IN_DASHBOARD = ["filterable_in_dashboard", "name", "slug"]
+ STOREFRONT_SEARCH_POSITION = ["storefront_search_position", "name", "pk"]
+ AVAILABLE_IN_GRID = ["available_in_grid", "name", "pk"]
+
+ @property
+ def description(self):
+ # pylint: disable=no-member
+ descriptions = {
+ AttributeSortField.NAME.name: "Sort attributes by name",
+ AttributeSortField.SLUG.name: "Sort attributes by slug",
+ AttributeSortField.VALUE_REQUIRED.name: (
+ "Sort attributes by the value required flag"
+ ),
+ AttributeSortField.IS_VARIANT_ONLY.name: (
+ "Sort attributes by the variant only flag"
+ ),
+ AttributeSortField.VISIBLE_IN_STOREFRONT.name: (
+ "Sort attributes by visibility in the storefront"
+ ),
+ AttributeSortField.FILTERABLE_IN_STOREFRONT.name: (
+ "Sort attributes by the filterable in storefront flag"
+ ),
+ AttributeSortField.FILTERABLE_IN_DASHBOARD.name: (
+ "Sort attributes by the filterable in dashboard flag"
+ ),
+ AttributeSortField.STOREFRONT_SEARCH_POSITION.name: (
+ "Sort attributes by their position in storefront"
+ ),
+ AttributeSortField.AVAILABLE_IN_GRID.name: (
+ "Sort attributes based on whether they can be displayed "
+ "or not in a product grid."
+ ),
+ }
+ if self.name in descriptions:
+ return descriptions[self.name]
+ raise ValueError("Unsupported enum value: %s" % self.value)
+
+
+class AttributeSortingInput(SortInputObjectType):
+ class Meta:
+ sort_enum = AttributeSortField
+ type_name = "attributes"
diff --git a/saleor/graphql/attribute/tests/__init__.py b/saleor/graphql/attribute/tests/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/graphql/attribute/tests/benchmark/__init__.py b/saleor/graphql/attribute/tests/benchmark/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/graphql/attribute/tests/benchmark/test_attribute.py b/saleor/graphql/attribute/tests/benchmark/test_attribute.py
new file mode 100644
index 0000000000..f44b76e526
--- /dev/null
+++ b/saleor/graphql/attribute/tests/benchmark/test_attribute.py
@@ -0,0 +1,83 @@
+import graphene
+import pytest
+
+from ....tests.utils import get_graphql_content
+
+
[email protected]_queries(autouse=False)
+def test_query_attribute(
+ staff_api_client, color_attribute, permission_manage_products, count_queries,
+):
+ query = """
+ query($id: ID!) {
+ attribute(id: $id) {
+ id
+ slug
+ name
+ inputType
+ type
+ values {
+ slug
+ inputType
+ }
+ valueRequired
+ visibleInStorefront
+ filterableInStorefront
+ filterableInDashboard
+ availableInGrid
+ storefrontSearchPosition
+ }
+ }
+ """
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ attribute_gql_id = graphene.Node.to_global_id("Attribute", color_attribute.id)
+ response = staff_api_client.post_graphql(query, {"id": attribute_gql_id})
+
+ content = get_graphql_content(response)
+ data = content["data"]["attribute"]
+ assert data
+
+
[email protected]_queries(autouse=False)
+def test_query_attributes(
+ staff_api_client,
+ size_attribute,
+ weight_attribute,
+ color_attribute,
+ permission_manage_products,
+ count_queries,
+):
+ query = """
+ query {
+ attributes(first: 20) {
+ edges {
+ node {
+ id
+ slug
+ name
+ inputType
+ type
+ values {
+ slug
+ inputType
+ }
+ valueRequired
+ visibleInStorefront
+ filterableInStorefront
+ filterableInDashboard
+ availableInGrid
+ storefrontSearchPosition
+ }
+ }
+ }
+ }
+ """
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ response = staff_api_client.post_graphql(query, {})
+
+ content = get_graphql_content(response)
+ data = content["data"]["attributes"]
+ assert data
diff --git a/saleor/graphql/attribute/tests/mutations/__init__.py b/saleor/graphql/attribute/tests/mutations/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_create.py b/saleor/graphql/attribute/tests/mutations/test_attribute_create.py
new file mode 100644
index 0000000000..74366f8126
--- /dev/null
+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_create.py
@@ -0,0 +1,243 @@
+import pytest
+from django.utils.text import slugify
+
+from .....attribute.error_codes import AttributeErrorCode
+from ....tests.utils import get_graphql_content
+from ...enums import AttributeTypeEnum
+
+CREATE_ATTRIBUTE_MUTATION = """
+ mutation createAttribute(
+ $name: String!, $slug: String, $type: AttributeTypeEnum!,
+ $values: [AttributeValueCreateInput]
+ ){
+ attributeCreate(input: {
+ name: $name, values: $values, slug: $slug, type: $type,
+ }) {
+ attributeErrors {
+ field
+ message
+ code
+ }
+ attribute {
+ name
+ slug
+ type
+ values {
+ name
+ slug
+ }
+ productTypes(first: 10) {
+ edges {
+ node {
+ id
+ }
+ }
+ }
+ }
+ }
+ }
+"""
+
+
+def test_create_attribute_and_attribute_values(
+ staff_api_client, permission_manage_product_types_and_attributes
+):
+ # given
+ query = CREATE_ATTRIBUTE_MUTATION
+
+ attribute_name = "Example name"
+ name = "Value name"
+ variables = {
+ "name": attribute_name,
+ "values": [{"name": name}],
+ "type": AttributeTypeEnum.PRODUCT_TYPE.name,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_product_types_and_attributes]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["attributeCreate"]["attributeErrors"]
+ data = content["data"]["attributeCreate"]
+
+ # Check if the attribute was correctly created
+ assert data["attribute"]["name"] == attribute_name
+ assert data["attribute"]["slug"] == slugify(
+ attribute_name
+ ), "The default slug should be the slugified name"
+ assert (
+ data["attribute"]["productTypes"]["edges"] == []
+ ), "The attribute should not have been assigned to a product type"
+
+ # Check if the attribute values were correctly created
+ assert len(data["attribute"]["values"]) == 1
+ assert data["attribute"]["type"] == AttributeTypeEnum.PRODUCT_TYPE.name
+ assert data["attribute"]["values"][0]["name"] == name
+ assert data["attribute"]["values"][0]["slug"] == slugify(name)
+
+
+def test_create_page_attribute_and_attribute_values(
+ staff_api_client, permission_manage_page_types_and_attributes
+):
+ # given
+ query = CREATE_ATTRIBUTE_MUTATION
+
+ attribute_name = "Example name"
+ name = "Value name"
+ variables = {
+ "name": attribute_name,
+ "values": [{"name": name}],
+ "type": AttributeTypeEnum.PAGE_TYPE.name,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_page_types_and_attributes]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["attributeCreate"]["attributeErrors"]
+ data = content["data"]["attributeCreate"]
+
+ # Check if the attribute was correctly created
+ assert data["attribute"]["name"] == attribute_name
+ assert data["attribute"]["slug"] == slugify(
+ attribute_name
+ ), "The default slug should be the slugified name"
+ assert (
+ data["attribute"]["productTypes"]["edges"] == []
+ ), "The attribute should not have been assigned to a product type"
+
+ # Check if the attribute values were correctly created
+ assert len(data["attribute"]["values"]) == 1
+ assert data["attribute"]["type"] == AttributeTypeEnum.PAGE_TYPE.name
+ assert data["attribute"]["values"][0]["name"] == name
+ assert data["attribute"]["values"][0]["slug"] == slugify(name)
+
+
+ "input_slug, expected_slug",
+ (
+ ("my-slug", "my-slug"),
+ (None, "my-name"),
+ ("", "my-name"),
+ ("わたし-わ-にっぽん-です", "わたし-わ-にっぽん-です"),
+ ),
+)
+def test_create_attribute_with_given_slug(
+ staff_api_client,
+ permission_manage_product_types_and_attributes,
+ input_slug,
+ expected_slug,
+):
+ # given
+ staff_api_client.user.user_permissions.add(
+ permission_manage_product_types_and_attributes
+ )
+ query = """
+ mutation createAttribute(
+ $name: String!, $slug: String, $type: AttributeTypeEnum!) {
+ attributeCreate(input: {name: $name, slug: $slug, type: $type}) {
+ attributeErrors {
+ field
+ message
+ code
+ }
+ attribute {
+ slug
+ }
+ }
+ }
+ """
+
+ attribute_name = "My Name"
+ variables = {
+ "name": attribute_name,
+ "slug": input_slug,
+ "type": AttributeTypeEnum.PRODUCT_TYPE.name,
+ }
+
+ # when
+ content = get_graphql_content(staff_api_client.post_graphql(query, variables))
+
+ # then
+ assert not content["data"]["attributeCreate"]["attributeErrors"]
+ assert content["data"]["attributeCreate"]["attribute"]["slug"] == expected_slug
+
+
+def test_create_attribute_value_name_and_slug_with_unicode(
+ staff_api_client, permission_manage_product_types_and_attributes
+):
+ # given
+ query = CREATE_ATTRIBUTE_MUTATION
+ name = "わたし わ にっぽん です"
+ slug = "わたし-わ-にっぽん-で"
+ variables = {
+ "name": name,
+ "slug": slug,
+ "type": AttributeTypeEnum.PRODUCT_TYPE.name,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_product_types_and_attributes]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["attributeCreate"]
+ assert not data["attributeErrors"]
+ assert data["attribute"]["name"] == name
+ assert data["attribute"]["slug"] == slug
+
+
+ "name_1, name_2, error_msg, error_code",
+ (
+ (
+ "Red color",
+ "Red color",
+ "Provided values are not unique.",
+ AttributeErrorCode.UNIQUE,
+ ),
+ (
+ "Red color",
+ "red color",
+ "Provided values are not unique.",
+ AttributeErrorCode.UNIQUE,
+ ),
+ ),
+)
+def test_create_attribute_and_attribute_values_errors(
+ staff_api_client,
+ name_1,
+ name_2,
+ error_msg,
+ error_code,
+ permission_manage_product_types_and_attributes,
+ product_type,
+):
+ # given
+ query = CREATE_ATTRIBUTE_MUTATION
+ variables = {
+ "name": "Example name",
+ "type": AttributeTypeEnum.PRODUCT_TYPE.name,
+ "values": [{"name": name_1}, {"name": name_2}],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_product_types_and_attributes]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ errors = content["data"]["attributeCreate"]["attributeErrors"]
+ assert errors
+ assert errors[0]["field"] == "values"
+ assert errors[0]["message"] == error_msg
+ assert errors[0]["code"] == error_code.name
diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_delete.py b/saleor/graphql/attribute/tests/mutations/test_attribute_delete.py
new file mode 100644
index 0000000000..983c49b8ca
--- /dev/null
+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_delete.py
@@ -0,0 +1,41 @@
+import graphene
+import pytest
+
+from ....tests.utils import get_graphql_content
+
+
+def test_delete_attribute(
+ staff_api_client,
+ color_attribute,
+ permission_manage_product_types_and_attributes,
+ product_type,
+):
+ # given
+ attribute = color_attribute
+ query = """
+ mutation deleteAttribute($id: ID!) {
+ attributeDelete(id: $id) {
+ errors {
+ field
+ message
+ }
+ attribute {
+ id
+ }
+ }
+ }
+ """
+ node_id = graphene.Node.to_global_id("Attribute", attribute.id)
+ variables = {"id": node_id}
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_product_types_and_attributes]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["attributeDelete"]
+ assert data["attribute"]["id"] == variables["id"]
+ with pytest.raises(attribute._meta.model.DoesNotExist):
+ attribute.refresh_from_db()
diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_reorder_values.py b/saleor/graphql/attribute/tests/mutations/test_attribute_reorder_values.py
new file mode 100644
index 0000000000..e06af0167e
--- /dev/null
+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_reorder_values.py
@@ -0,0 +1,137 @@
+import graphene
+
+from .....attribute.models import AttributeValue
+from ....tests.utils import get_graphql_content
+
+ATTRIBUTE_VALUES_REORDER_MUTATION = """
+ mutation attributeReorderValues($attributeId: ID!, $moves: [ReorderInput]!) {
+ attributeReorderValues(attributeId: $attributeId, moves: $moves) {
+ attribute {
+ id
+ values {
+ id
+ }
+ }
+
+ errors {
+ field
+ message
+ }
+ }
+ }
+"""
+
+
+def test_sort_values_within_attribute_invalid_product_type(
+ staff_api_client, permission_manage_product_types_and_attributes
+):
+ """Try to reorder an invalid attribute (invalid ID)."""
+
+ attribute_id = graphene.Node.to_global_id("Attribute", -1)
+ value_id = graphene.Node.to_global_id("AttributeValue", -1)
+
+ variables = {
+ "attributeId": attribute_id,
+ "moves": [{"id": value_id, "sortOrder": 1}],
+ }
+
+ content = get_graphql_content(
+ staff_api_client.post_graphql(
+ ATTRIBUTE_VALUES_REORDER_MUTATION,
+ variables,
+ permissions=[permission_manage_product_types_and_attributes],
+ )
+ )["data"]["attributeReorderValues"]
+
+ assert content["errors"] == [
+ {
+ "field": "attributeId",
+ "message": f"Couldn't resolve to an attribute: {attribute_id}",
+ }
+ ]
+
+
+def test_sort_values_within_attribute_invalid_id(
+ staff_api_client, permission_manage_product_types_and_attributes, color_attribute
+):
+ """Try to reorder a value not associated to the given attribute."""
+
+ attribute_id = graphene.Node.to_global_id("Attribute", color_attribute.id)
+ value_id = graphene.Node.to_global_id("AttributeValue", -1)
+
+ variables = {
+ "type": "VARIANT",
+ "attributeId": attribute_id,
+ "moves": [{"id": value_id, "sortOrder": 1}],
+ }
+
+ content = get_graphql_content(
+ staff_api_client.post_graphql(
+ ATTRIBUTE_VALUES_REORDER_MUTATION,
+ variables,
+ permissions=[permission_manage_product_types_and_attributes],
+ )
+ )["data"]["attributeReorderValues"]
+
+ assert content["errors"] == [
+ {
+ "field": "moves",
+ "message": f"Couldn't resolve to an attribute value: {value_id}",
+ }
+ ]
+
+
+def test_sort_values_within_attribute(
+ staff_api_client, color_attribute, permission_manage_product_types_and_attributes
+):
+ attribute = color_attribute
+ AttributeValue.objects.create(attribute=attribute, name="Green", slug="green")
+ values = list(attribute.values.all())
+ assert len(values) == 3
+
+ staff_api_client.user.user_permissions.add(
+ permission_manage_product_types_and_attributes
+ )
+
+ attribute_id = graphene.Node.to_global_id("Attribute", attribute.id)
+ m2m_values = attribute.values
+ m2m_values.set(values)
+
+ assert values == sorted(
+ values, key=lambda o: o.sort_order if o.sort_order is not None else o.pk
+ ), "The values are not properly ordered"
+
+ variables = {
+ "attributeId": attribute_id,
+ "moves": [
+ {
+ "id": graphene.Node.to_global_id("AttributeValue", values[0].pk),
+ "sortOrder": +1,
+ },
+ {
+ "id": graphene.Node.to_global_id("AttributeValue", values[2].pk),
+ "sortOrder": -1,
+ },
+ ],
+ }
+
+ expected_order = [values[1].pk, values[2].pk, values[0].pk]
+
+ content = get_graphql_content(
+ staff_api_client.post_graphql(ATTRIBUTE_VALUES_REORDER_MUTATION, variables)
+ )["data"]["attributeReorderValues"]
+ assert not content["errors"]
+
+ assert content["attribute"]["id"] == attribute_id
+
+ gql_values = content["attribute"]["values"]
+ assert len(gql_values) == len(expected_order)
+
+ actual_order = []
+
+ for attr, expected_pk in zip(gql_values, expected_order):
+ gql_type, gql_attr_id = graphene.Node.from_global_id(attr["id"])
+ assert gql_type == "AttributeValue"
+ actual_order.append(int(gql_attr_id))
+
+ assert actual_order == expected_order
diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_update.py b/saleor/graphql/attribute/tests/mutations/test_attribute_update.py
new file mode 100644
index 0000000000..9720f83b8d
--- /dev/null
+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_update.py
@@ -0,0 +1,387 @@
+import graphene
+import pytest
+
+from .....attribute.error_codes import AttributeErrorCode
+from .....attribute.models import Attribute
+from ....tests.utils import get_graphql_content
+
+UPDATE_ATTRIBUTE_MUTATION = """
+ mutation updateAttribute(
+ $id: ID!, $name: String!, $addValues: [AttributeValueCreateInput]!,
+ $removeValues: [ID]!) {
+ attributeUpdate(
+ id: $id,
+ input: {
+ name: $name, addValues: $addValues,
+ removeValues: $removeValues}) {
+ attributeErrors {
+ field
+ message
+ code
+ }
+ attribute {
+ name
+ slug
+ values {
+ name
+ slug
+ }
+ productTypes(first: 10) {
+ edges {
+ node {
+ id
+ }
+ }
+ }
+ }
+ }
+}
+"""
+
+
+def test_update_attribute_name(
+ staff_api_client, color_attribute, permission_manage_product_types_and_attributes
+):
+ # given
+ query = UPDATE_ATTRIBUTE_MUTATION
+ attribute = color_attribute
+ name = "Wings name"
+ slug = attribute.slug
+ node_id = graphene.Node.to_global_id("Attribute", attribute.id)
+ variables = {"name": name, "id": node_id, "addValues": [], "removeValues": []}
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_product_types_and_attributes]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ attribute.refresh_from_db()
+ data = content["data"]["attributeUpdate"]
+ assert data["attribute"]["name"] == name == attribute.name
+ assert data["attribute"]["slug"] == slug == attribute.slug
+ assert data["attribute"]["productTypes"]["edges"] == []
+
+
+def test_update_attribute_remove_and_add_values(
+ staff_api_client, color_attribute, permission_manage_product_types_and_attributes
+):
+ # given
+ query = UPDATE_ATTRIBUTE_MUTATION
+ attribute = color_attribute
+ name = "Wings name"
+ attribute_value_name = "Red Color"
+ node_id = graphene.Node.to_global_id("Attribute", attribute.id)
+ attribute_value_id = attribute.values.first().id
+ value_id = graphene.Node.to_global_id("AttributeValue", attribute_value_id)
+ variables = {
+ "name": name,
+ "id": node_id,
+ "addValues": [{"name": attribute_value_name}],
+ "removeValues": [value_id],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_product_types_and_attributes]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ attribute.refresh_from_db()
+ data = content["data"]["attributeUpdate"]
+ assert not data["attributeErrors"]
+ assert data["attribute"]["name"] == name == attribute.name
+ assert not attribute.values.filter(pk=attribute_value_id).exists()
+ assert attribute.values.filter(name=attribute_value_name).exists()
+
+
+def test_update_empty_attribute_and_add_values(
+ staff_api_client,
+ color_attribute_without_values,
+ permission_manage_product_types_and_attributes,
+):
+ # given
+ query = UPDATE_ATTRIBUTE_MUTATION
+ attribute = color_attribute_without_values
+ name = "Wings name"
+ attribute_value_name = "Yellow Color"
+ node_id = graphene.Node.to_global_id("Attribute", attribute.id)
+ variables = {
+ "name": name,
+ "id": node_id,
+ "addValues": [{"name": attribute_value_name}],
+ "removeValues": [],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_product_types_and_attributes]
+ )
+
+ # then
+ get_graphql_content(response)
+ attribute.refresh_from_db()
+ assert attribute.values.count() == 1
+ assert attribute.values.filter(name=attribute_value_name).exists()
+
+
+UPDATE_ATTRIBUTE_SLUG_MUTATION = """
+ mutation updateAttribute(
+ $id: ID!, $slug: String) {
+ attributeUpdate(
+ id: $id,
+ input: {
+ slug: $slug}) {
+ attributeErrors {
+ field
+ message
+ code
+ }
+ attribute {
+ name
+ slug
+ }
+ }
+}
+"""
+
+
+ "input_slug, expected_slug, error_message",
+ [
+ ("test-slug", "test-slug", None),
+ ("", "", "Slug value cannot be blank."),
+ (None, "", "Slug value cannot be blank."),
+ ],
+)
+def test_update_attribute_slug(
+ staff_api_client,
+ color_attribute,
+ permission_manage_product_types_and_attributes,
+ input_slug,
+ expected_slug,
+ error_message,
+):
+ # given
+ query = UPDATE_ATTRIBUTE_SLUG_MUTATION
+
+ attribute = color_attribute
+ name = attribute.name
+ old_slug = attribute.slug
+
+ assert input_slug != old_slug
+
+ node_id = graphene.Node.to_global_id("Attribute", attribute.id)
+ variables = {"slug": input_slug, "id": node_id}
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_product_types_and_attributes]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ attribute.refresh_from_db()
+ data = content["data"]["attributeUpdate"]
+ errors = data["attributeErrors"]
+ if not error_message:
+ assert data["attribute"]["name"] == name == attribute.name
+ assert data["attribute"]["slug"] == input_slug == attribute.slug
+ else:
+ assert errors
+ assert data["attribute"] is None
+ assert errors[0]["field"] == "slug"
+ assert errors[0]["code"] == AttributeErrorCode.REQUIRED.name
+
+
+def test_update_attribute_slug_exists(
+ staff_api_client, color_attribute, permission_manage_product_types_and_attributes,
+):
+ # given
+ query = UPDATE_ATTRIBUTE_SLUG_MUTATION
+
+ second_attribute = Attribute.objects.get(pk=color_attribute.pk)
+ second_attribute.pk = None
+ second_attribute.slug = "second-attribute"
+ second_attribute.save()
+
+ attribute = color_attribute
+ old_slug = attribute.slug
+ new_slug = second_attribute.slug
+
+ assert new_slug != old_slug
+
+ node_id = graphene.Node.to_global_id("Attribute", attribute.id)
+ variables = {"slug": new_slug, "id": node_id}
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_product_types_and_attributes]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ attribute.refresh_from_db()
+ data = content["data"]["attributeUpdate"]
+ errors = data["attributeErrors"]
+
+ assert errors
+ assert data["attribute"] is None
+ assert errors[0]["field"] == "slug"
+ assert errors[0]["code"] == AttributeErrorCode.UNIQUE.name
+
+
+ "input_slug, expected_slug, input_name, error_message, error_field",
+ [
+ ("test-slug", "test-slug", "New name", None, None),
+ ("", "", "New name", "Slug value cannot be blank.", "slug"),
+ (None, "", "New name", "Slug value cannot be blank.", "slug"),
+ ("test-slug", "", None, "This field cannot be blank.", "name"),
+ ("test-slug", "", "", "This field cannot be blank.", "name"),
+ (None, None, None, "Slug value cannot be blank.", "slug"),
+ ],
+)
+def test_update_attribute_slug_and_name(
+ staff_api_client,
+ color_attribute,
+ permission_manage_product_types_and_attributes,
+ input_slug,
+ expected_slug,
+ input_name,
+ error_message,
+ error_field,
+):
+ # given
+ query = """
+ mutation updateAttribute(
+ $id: ID!, $slug: String, $name: String) {
+ attributeUpdate(
+ id: $id,
+ input: {
+ slug: $slug, name: $name}) {
+ attributeErrors {
+ field
+ message
+ code
+ }
+ attribute {
+ name
+ slug
+ }
+ }
+ }
+ """
+
+ attribute = color_attribute
+ old_name = attribute.name
+ old_slug = attribute.slug
+
+ assert input_slug != old_slug
+ assert input_name != old_name
+
+ node_id = graphene.Node.to_global_id("Attribute", attribute.id)
+ variables = {"slug": input_slug, "name": input_name, "id": node_id}
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_product_types_and_attributes]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ attribute.refresh_from_db()
+ data = content["data"]["attributeUpdate"]
+ errors = data["attributeErrors"]
+ if not error_message:
+ assert data["attribute"]["name"] == input_name == attribute.name
+ assert data["attribute"]["slug"] == input_slug == attribute.slug
+ else:
+ assert errors
+ assert errors[0]["field"] == error_field
+ assert errors[0]["code"] == AttributeErrorCode.REQUIRED.name
+
+
+ "name_1, name_2, error_msg, error_code",
+ (
+ (
+ "Red color",
+ "Red color",
+ "Provided values are not unique.",
+ AttributeErrorCode.UNIQUE,
+ ),
+ (
+ "Red color",
+ "red color",
+ "Provided values are not unique.",
+ AttributeErrorCode.UNIQUE,
+ ),
+ ),
+)
+def test_update_attribute_and_add_attribute_values_errors(
+ staff_api_client,
+ name_1,
+ name_2,
+ error_msg,
+ error_code,
+ color_attribute,
+ permission_manage_product_types_and_attributes,
+):
+ # given
+ query = UPDATE_ATTRIBUTE_MUTATION
+ attribute = color_attribute
+ node_id = graphene.Node.to_global_id("Attribute", attribute.id)
+ variables = {
+ "name": "Example name",
+ "id": node_id,
+ "removeValues": [],
+ "addValues": [{"name": name_1}, {"name": name_2}],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_product_types_and_attributes]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ errors = content["data"]["attributeUpdate"]["attributeErrors"]
+ assert errors
+ assert errors[0]["field"] == "addValues"
+ assert errors[0]["message"] == error_msg
+ assert errors[0]["code"] == error_code.name
+
+
+def test_update_attribute_and_remove_others_attribute_value(
+ staff_api_client,
+ color_attribute,
+ size_attribute,
+ permission_manage_product_types_and_attributes,
+):
+ # given
+ query = UPDATE_ATTRIBUTE_MUTATION
+ attribute = color_attribute
+ node_id = graphene.Node.to_global_id("Attribute", attribute.id)
+ size_attribute = size_attribute.values.first()
+ attr_id = graphene.Node.to_global_id("AttributeValue", size_attribute.pk)
+ variables = {
+ "name": "Example name",
+ "id": node_id,
+ "addValues": [],
+ "removeValues": [attr_id],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_product_types_and_attributes]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ errors = content["data"]["attributeUpdate"]["attributeErrors"]
+ assert errors
+ assert errors[0]["field"] == "removeValues"
+ assert errors[0]["code"] == AttributeErrorCode.INVALID.name
diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_value_create.py b/saleor/graphql/attribute/tests/mutations/test_attribute_value_create.py
new file mode 100644
index 0000000000..5fca083e9d
--- /dev/null
+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_value_create.py
@@ -0,0 +1,123 @@
+import graphene
+import pytest
+from django.core.exceptions import ValidationError
+from django.utils.text import slugify
+
+from .....attribute.error_codes import AttributeErrorCode
+from .....attribute.models import AttributeValue
+from ....tests.utils import get_graphql_content
+from ...mutations import validate_value_is_unique
+
+
+def test_validate_value_is_unique(color_attribute):
+ value = color_attribute.values.first()
+
+ # a new value but with existing slug should raise an error
+ with pytest.raises(ValidationError):
+ validate_value_is_unique(color_attribute, AttributeValue(slug=value.slug))
+
+ # a new value with a new slug should pass
+ validate_value_is_unique(
+ color_attribute, AttributeValue(slug="spanish-inquisition")
+ )
+
+ # value that already belongs to the attribute shouldn't be taken into account
+ validate_value_is_unique(color_attribute, value)
+
+
+CREATE_ATTRIBUTE_VALUE_MUTATION = """
+ mutation createAttributeValue(
+ $attributeId: ID!, $name: String!) {
+ attributeValueCreate(
+ attribute: $attributeId, input: {name: $name}) {
+ attributeErrors {
+ field
+ message
+ code
+ }
+ attribute {
+ values {
+ name
+ }
+ }
+ attributeValue {
+ name
+ type
+ slug
+ }
+ }
+}
+"""
+
+
+def test_create_attribute_value(
+ staff_api_client, color_attribute, permission_manage_products
+):
+ # given
+ attribute = color_attribute
+ query = CREATE_ATTRIBUTE_VALUE_MUTATION
+ attribute_id = graphene.Node.to_global_id("Attribute", attribute.id)
+ name = "test name"
+ variables = {"name": name, "attributeId": attribute_id}
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["attributeValueCreate"]
+ assert not data["attributeErrors"]
+
+ attr_data = data["attributeValue"]
+ assert attr_data["name"] == name
+ assert attr_data["slug"] == slugify(name)
+ assert attr_data["type"] == "STRING"
+ assert name in [value["name"] for value in data["attribute"]["values"]]
+
+
+def test_create_attribute_value_not_unique_name(
+ staff_api_client, color_attribute, permission_manage_products
+):
+ # given
+ attribute = color_attribute
+ query = CREATE_ATTRIBUTE_VALUE_MUTATION
+ attribute_id = graphene.Node.to_global_id("Attribute", attribute.id)
+ value_name = attribute.values.first().name
+ variables = {"name": value_name, "attributeId": attribute_id}
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["attributeValueCreate"]
+ assert data["attributeErrors"]
+ assert data["attributeErrors"][0]["code"] == AttributeErrorCode.ALREADY_EXISTS.name
+ assert data["attributeErrors"][0]["field"] == "name"
+
+
+def test_create_attribute_value_capitalized_name(
+ staff_api_client, color_attribute, permission_manage_products
+):
+ # given
+ attribute = color_attribute
+ query = CREATE_ATTRIBUTE_VALUE_MUTATION
+ attribute_id = graphene.Node.to_global_id("Attribute", attribute.id)
+ value_name = attribute.values.first().name
+ variables = {"name": value_name.upper(), "attributeId": attribute_id}
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["attributeValueCreate"]
+ assert data["attributeErrors"]
+ assert data["attributeErrors"][0]["code"] == AttributeErrorCode.ALREADY_EXISTS.name
+ assert data["attributeErrors"][0]["field"] == "name"
diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_value_delete.py b/saleor/graphql/attribute/tests/mutations/test_attribute_value_delete.py
new file mode 100644
index 0000000000..2cdd7b672f
--- /dev/null
+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_value_delete.py
@@ -0,0 +1,33 @@
+import graphene
+import pytest
+
+
+def test_delete_attribute_value(
+ staff_api_client,
+ color_attribute,
+ pink_attribute_value,
+ permission_manage_product_types_and_attributes,
+):
+ # given
+ value = color_attribute.values.get(name="Red")
+ query = """
+ mutation updateChoice($id: ID!) {
+ attributeValueDelete(id: $id) {
+ attributeValue {
+ name
+ slug
+ }
+ }
+ }
+ """
+ node_id = graphene.Node.to_global_id("AttributeValue", value.id)
+ variables = {"id": node_id}
+
+ # when
+ staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_product_types_and_attributes]
+ )
+
+ # then
+ with pytest.raises(value._meta.model.DoesNotExist):
+ value.refresh_from_db()
diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_value_update.py b/saleor/graphql/attribute/tests/mutations/test_attribute_value_update.py
new file mode 100644
index 0000000000..04a32526e6
--- /dev/null
+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_value_update.py
@@ -0,0 +1,81 @@
+import graphene
+from django.utils.text import slugify
+
+from .....attribute.error_codes import AttributeErrorCode
+from ....tests.utils import get_graphql_content
+
+UPDATE_ATTRIBUTE_VALUE_MUTATION = """
+mutation AttributeValueUpdate(
+ $id: ID!, $name: String!) {
+ attributeValueUpdate(
+ id: $id, input: {name: $name}) {
+ attributeErrors {
+ field
+ message
+ code
+ }
+ attributeValue {
+ name
+ slug
+ }
+ attribute {
+ values {
+ name
+ }
+ }
+ }
+}
+"""
+
+
+def test_update_attribute_value(
+ staff_api_client,
+ pink_attribute_value,
+ permission_manage_product_types_and_attributes,
+):
+ # given
+ query = UPDATE_ATTRIBUTE_VALUE_MUTATION
+ value = pink_attribute_value
+ node_id = graphene.Node.to_global_id("AttributeValue", value.id)
+ name = "Crimson name"
+ variables = {"name": name, "id": node_id}
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_product_types_and_attributes]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["attributeValueUpdate"]
+ value.refresh_from_db()
+ assert data["attributeValue"]["name"] == name == value.name
+ assert data["attributeValue"]["slug"] == slugify(name)
+ assert name in [value["name"] for value in data["attribute"]["values"]]
+
+
+def test_update_attribute_value_name_not_unique(
+ staff_api_client,
+ pink_attribute_value,
+ permission_manage_product_types_and_attributes,
+):
+ # given
+ query = UPDATE_ATTRIBUTE_VALUE_MUTATION
+ value = pink_attribute_value.attribute.values.create(
+ name="Example Name", slug="example-name", value="#RED"
+ )
+ node_id = graphene.Node.to_global_id("AttributeValue", value.id)
+ variables = {"name": pink_attribute_value.name, "id": node_id}
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_product_types_and_attributes]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["attributeValueUpdate"]
+ assert data["attributeErrors"]
+ assert data["attributeErrors"][0]["message"]
+ assert data["attributeErrors"][0]["field"] == "name"
+ assert data["attributeErrors"][0]["code"] == AttributeErrorCode.ALREADY_EXISTS.name
diff --git a/saleor/graphql/attribute/tests/mutations/test_bulk_delete.py b/saleor/graphql/attribute/tests/mutations/test_bulk_delete.py
new file mode 100644
index 0000000000..0064f1e344
--- /dev/null
+++ b/saleor/graphql/attribute/tests/mutations/test_bulk_delete.py
@@ -0,0 +1,77 @@
+import graphene
+import pytest
+
+from .....attribute.models import Attribute, AttributeValue
+from ....tests.utils import get_graphql_content
+
+
+def attribute_value_list(color_attribute):
+ value_1 = AttributeValue.objects.create(
+ slug="pink", name="Pink", attribute=color_attribute, value="#FF69B4"
+ )
+ value_2 = AttributeValue.objects.create(
+ slug="white", name="White", attribute=color_attribute, value="#FFFFFF"
+ )
+ value_3 = AttributeValue.objects.create(
+ slug="black", name="Black", attribute=color_attribute, value="#000000"
+ )
+ return value_1, value_2, value_3
+
+
+def test_delete_attributes(
+ staff_api_client,
+ product_type_attribute_list,
+ permission_manage_page_types_and_attributes,
+):
+ query = """
+ mutation attributeBulkDelete($ids: [ID]!) {
+ attributeBulkDelete(ids: $ids) {
+ count
+ }
+ }
+ """
+
+ variables = {
+ "ids": [
+ graphene.Node.to_global_id("Attribute", attr.id)
+ for attr in product_type_attribute_list
+ ]
+ }
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_page_types_and_attributes]
+ )
+ content = get_graphql_content(response)
+
+ assert content["data"]["attributeBulkDelete"]["count"] == 3
+ assert not Attribute.objects.filter(
+ id__in=[attr.id for attr in product_type_attribute_list]
+ ).exists()
+
+
+def test_delete_attribute_values(
+ staff_api_client, attribute_value_list, permission_manage_page_types_and_attributes
+):
+ query = """
+ mutation attributeValueBulkDelete($ids: [ID]!) {
+ attributeValueBulkDelete(ids: $ids) {
+ count
+ }
+ }
+ """
+
+ variables = {
+ "ids": [
+ graphene.Node.to_global_id("AttributeValue", val.id)
+ for val in attribute_value_list
+ ]
+ }
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_page_types_and_attributes]
+ )
+ content = get_graphql_content(response)
+
+ assert content["data"]["attributeValueBulkDelete"]["count"] == 3
+ assert not AttributeValue.objects.filter(
+ id__in=[val.id for val in attribute_value_list]
+ ).exists()
diff --git a/saleor/graphql/attribute/tests/queries/__init__.py b/saleor/graphql/attribute/tests/queries/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/graphql/attribute/tests/queries/test_attribute_filter.py b/saleor/graphql/attribute/tests/queries/test_attribute_filter.py
new file mode 100644
index 0000000000..44d6ed32d6
--- /dev/null
+++ b/saleor/graphql/attribute/tests/queries/test_attribute_filter.py
@@ -0,0 +1,915 @@
+from unittest import mock
+
+import graphene
+import pytest
+
+from .....attribute.models import Attribute
+from .....attribute.utils import associate_attribute_values_to_instance
+from .....product.models import ProductType
+from ....tests.utils import get_graphql_content
+from ...filters import filter_attributes_by_product_types
+
+ATTRIBUTES_FILTER_QUERY = """
+ query($filters: AttributeFilterInput!) {
+ attributes(first: 10, filter: $filters) {
+ edges {
+ node {
+ name
+ slug
+ }
+ }
+ }
+ }
+"""
+
+
+def test_search_attributes(api_client, color_attribute, size_attribute):
+ variables = {"filters": {"search": "color"}}
+
+ attributes = get_graphql_content(
+ api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables)
+ )["data"]["attributes"]["edges"]
+
+ assert len(attributes) == 1
+ assert attributes[0]["node"]["slug"] == "color"
+
+
+def test_filter_attributes_if_filterable_in_dashboard(
+ api_client, color_attribute, size_attribute
+):
+ color_attribute.filterable_in_dashboard = False
+ color_attribute.save(update_fields=["filterable_in_dashboard"])
+
+ variables = {"filters": {"filterableInDashboard": True}}
+
+ attributes = get_graphql_content(
+ api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables)
+ )["data"]["attributes"]["edges"]
+
+ assert len(attributes) == 1
+ assert attributes[0]["node"]["slug"] == "size"
+
+
+def test_filter_attributes_if_available_in_grid(
+ api_client, color_attribute, size_attribute
+):
+ color_attribute.available_in_grid = False
+ color_attribute.save(update_fields=["available_in_grid"])
+
+ variables = {"filters": {"availableInGrid": True}}
+
+ attributes = get_graphql_content(
+ api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables)
+ )["data"]["attributes"]["edges"]
+
+ assert len(attributes) == 1
+ assert attributes[0]["node"]["slug"] == "size"
+
+
+def test_filter_attributes_by_global_id_list(api_client, product_type_attribute_list):
+ global_ids = [
+ graphene.Node.to_global_id("Attribute", attribute.pk)
+ for attribute in product_type_attribute_list[:2]
+ ]
+ variables = {"filters": {"ids": global_ids}}
+
+ expected_slugs = sorted(
+ [product_type_attribute_list[0].slug, product_type_attribute_list[1].slug]
+ )
+
+ attributes = get_graphql_content(
+ api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables)
+ )["data"]["attributes"]["edges"]
+
+ assert len(attributes) == 2
+ received_slugs = sorted(
+ [attributes[0]["node"]["slug"], attributes[1]["node"]["slug"]]
+ )
+
+ assert received_slugs == expected_slugs
+
+
+def test_filter_attributes_in_category_not_visible_in_listings_by_customer(
+ user_api_client, product_list, weight_attribute, channel_USD
+):
+ # given
+ product_type = ProductType.objects.create(
+ name="Default Type 2",
+ slug="default-type-2",
+ has_variants=True,
+ is_shipping_required=True,
+ )
+ product_type.product_attributes.add(weight_attribute)
+
+ last_product = product_list[-1]
+ last_product.product_type = product_type
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(visible_in_listings=False)
+
+ associate_attribute_values_to_instance(
+ product_list[-1], weight_attribute, weight_attribute.values.first()
+ )
+
+ attribute_count = Attribute.objects.count()
+
+ category = last_product.category
+ variables = {
+ "filters": {
+ "inCategory": graphene.Node.to_global_id("Category", category.pk),
+ "channel": channel_USD.slug,
+ }
+ }
+
+ # when
+ attributes = get_graphql_content(
+ user_api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables)
+ )["data"]["attributes"]["edges"]
+
+ # then
+ assert len(attributes) == attribute_count - 1
+ assert weight_attribute.slug not in {
+ attribute["node"]["slug"] for attribute in attributes
+ }
+
+
+def test_filter_attributes_in_category_not_visible_in_listings_by_staff_with_perm(
+ staff_api_client,
+ product_list,
+ weight_attribute,
+ permission_manage_products,
+ channel_USD,
+):
+ # given
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ product_type = ProductType.objects.create(
+ name="Default Type 2",
+ slug="default-type-2",
+ has_variants=True,
+ is_shipping_required=True,
+ )
+ product_type.product_attributes.add(weight_attribute)
+
+ last_product = product_list[-1]
+ last_product.product_type = product_type
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(visible_in_listings=False)
+
+ associate_attribute_values_to_instance(
+ product_list[-1], weight_attribute, weight_attribute.values.first()
+ )
+
+ attribute_count = Attribute.objects.count()
+
+ category = last_product.category
+ variables = {
+ "filters": {
+ "inCategory": graphene.Node.to_global_id("Category", category.pk),
+ "channel": channel_USD.slug,
+ }
+ }
+
+ # when
+ attributes = get_graphql_content(
+ staff_api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables)
+ )["data"]["attributes"]["edges"]
+
+ # then
+ assert len(attributes) == attribute_count
+
+
+def test_filter_attributes_in_category_not_visible_in_listings_by_staff_without_perm(
+ staff_api_client,
+ product_list,
+ weight_attribute,
+ permission_manage_products,
+ channel_USD,
+):
+ # given
+ product_type = ProductType.objects.create(
+ name="Default Type 2",
+ slug="default-type-2",
+ has_variants=True,
+ is_shipping_required=True,
+ )
+ product_type.product_attributes.add(weight_attribute)
+
+ last_product = product_list[-1]
+ last_product.product_type = product_type
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(visible_in_listings=False)
+
+ associate_attribute_values_to_instance(
+ product_list[-1], weight_attribute, weight_attribute.values.first()
+ )
+
+ attribute_count = Attribute.objects.count()
+
+ category = last_product.category
+ variables = {
+ "filters": {
+ "inCategory": graphene.Node.to_global_id("Category", category.pk),
+ "channel": channel_USD.slug,
+ }
+ }
+
+ # when
+ attributes = get_graphql_content(
+ staff_api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables)
+ )["data"]["attributes"]["edges"]
+
+ # then
+ assert len(attributes) == attribute_count - 1
+ assert weight_attribute.slug not in {
+ attribute["node"]["slug"] for attribute in attributes
+ }
+
+
+def test_filter_attributes_in_category_not_visible_in_listings_by_app_with_perm(
+ app_api_client,
+ product_list,
+ weight_attribute,
+ permission_manage_products,
+ channel_USD,
+):
+ # given
+ app_api_client.app.permissions.add(permission_manage_products)
+
+ product_type = ProductType.objects.create(
+ name="Default Type 2",
+ slug="default-type-2",
+ has_variants=True,
+ is_shipping_required=True,
+ )
+ product_type.product_attributes.add(weight_attribute)
+
+ last_product = product_list[-1]
+ last_product.product_type = product_type
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(visible_in_listings=False)
+
+ associate_attribute_values_to_instance(
+ product_list[-1], weight_attribute, weight_attribute.values.first()
+ )
+
+ attribute_count = Attribute.objects.count()
+
+ category = last_product.category
+ variables = {
+ "filters": {
+ "inCategory": graphene.Node.to_global_id("Category", category.pk),
+ "channel": channel_USD.slug,
+ }
+ }
+
+ # when
+ attributes = get_graphql_content(
+ app_api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables)
+ )["data"]["attributes"]["edges"]
+
+ # then
+ assert len(attributes) == attribute_count
+
+
+def test_filter_attributes_in_category_not_visible_in_listings_by_app_without_perm(
+ app_api_client,
+ product_list,
+ weight_attribute,
+ permission_manage_products,
+ channel_USD,
+):
+ # given
+ product_type = ProductType.objects.create(
+ name="Default Type 2",
+ slug="default-type-2",
+ has_variants=True,
+ is_shipping_required=True,
+ )
+ product_type.product_attributes.add(weight_attribute)
+
+ last_product = product_list[-1]
+ last_product.product_type = product_type
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(visible_in_listings=False)
+
+ associate_attribute_values_to_instance(
+ product_list[-1], weight_attribute, weight_attribute.values.first()
+ )
+
+ attribute_count = Attribute.objects.count()
+
+ category = last_product.category
+ variables = {
+ "filters": {
+ "inCategory": graphene.Node.to_global_id("Category", category.pk),
+ "channel": channel_USD.slug,
+ }
+ }
+
+ # when
+ attributes = get_graphql_content(
+ app_api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables)
+ )["data"]["attributes"]["edges"]
+
+ # then
+ assert len(attributes) == attribute_count - 1
+ assert weight_attribute.slug not in {
+ attribute["node"]["slug"] for attribute in attributes
+ }
+
+
+def test_filter_attributes_in_category_not_published_by_customer(
+ user_api_client, product_list, weight_attribute, channel_USD
+):
+ # given
+ product_type = ProductType.objects.create(
+ name="Default Type 2",
+ slug="default-type-2",
+ has_variants=True,
+ is_shipping_required=True,
+ )
+ product_type.product_attributes.add(weight_attribute)
+
+ last_product = product_list[-1]
+ last_product.product_type = product_type
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(is_published=False)
+
+ associate_attribute_values_to_instance(
+ product_list[-1], weight_attribute, weight_attribute.values.first()
+ )
+
+ attribute_count = Attribute.objects.count()
+
+ category = last_product.category
+ variables = {
+ "filters": {
+ "inCategory": graphene.Node.to_global_id("Category", category.pk),
+ "channel": channel_USD.slug,
+ },
+ }
+
+ # when
+ attributes = get_graphql_content(
+ user_api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables)
+ )["data"]["attributes"]["edges"]
+
+ # then
+ assert len(attributes) == attribute_count - 1
+ assert weight_attribute.slug not in {
+ attribute["node"]["slug"] for attribute in attributes
+ }
+
+
+def test_filter_attributes_in_category_not_published_by_staff_with_perm(
+ staff_api_client,
+ product_list,
+ weight_attribute,
+ permission_manage_products,
+ channel_USD,
+):
+ # given
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ product_type = ProductType.objects.create(
+ name="Default Type 2",
+ slug="default-type-2",
+ has_variants=True,
+ is_shipping_required=True,
+ )
+ product_type.product_attributes.add(weight_attribute)
+
+ last_product = product_list[-1]
+ last_product.product_type = product_type
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(is_published=False)
+
+ associate_attribute_values_to_instance(
+ product_list[-1], weight_attribute, weight_attribute.values.first()
+ )
+
+ attribute_count = Attribute.objects.count()
+
+ category = last_product.category
+ variables = {
+ "filters": {
+ "inCategory": graphene.Node.to_global_id("Category", category.pk),
+ "channel": channel_USD.slug,
+ }
+ }
+
+ # when
+ attributes = get_graphql_content(
+ staff_api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables)
+ )["data"]["attributes"]["edges"]
+
+ # then
+ assert len(attributes) == attribute_count
+
+
+def test_filter_attributes_in_category_not_published_by_staff_without_perm(
+ staff_api_client,
+ product_list,
+ weight_attribute,
+ permission_manage_products,
+ channel_USD,
+):
+ # given
+ product_type = ProductType.objects.create(
+ name="Default Type 2",
+ slug="default-type-2",
+ has_variants=True,
+ is_shipping_required=True,
+ )
+ product_type.product_attributes.add(weight_attribute)
+
+ last_product = product_list[-1]
+ last_product.product_type = product_type
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(is_published=False)
+
+ associate_attribute_values_to_instance(
+ product_list[-1], weight_attribute, weight_attribute.values.first()
+ )
+
+ attribute_count = Attribute.objects.count()
+
+ category = last_product.category
+ variables = {
+ "filters": {
+ "inCategory": graphene.Node.to_global_id("Category", category.pk),
+ "channel": channel_USD.slug,
+ }
+ }
+
+ # when
+ attributes = get_graphql_content(
+ staff_api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables)
+ )["data"]["attributes"]["edges"]
+
+ # then
+ assert len(attributes) == attribute_count - 1
+ assert weight_attribute.slug not in {
+ attribute["node"]["slug"] for attribute in attributes
+ }
+
+
+def test_filter_attributes_in_category_not_published_by_app_with_perm(
+ app_api_client,
+ product_list,
+ weight_attribute,
+ permission_manage_products,
+ channel_USD,
+):
+ # given
+ app_api_client.app.permissions.add(permission_manage_products)
+
+ product_type = ProductType.objects.create(
+ name="Default Type 2",
+ slug="default-type-2",
+ has_variants=True,
+ is_shipping_required=True,
+ )
+ product_type.product_attributes.add(weight_attribute)
+
+ last_product = product_list[-1]
+ last_product.product_type = product_type
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(is_published=False)
+
+ associate_attribute_values_to_instance(
+ product_list[-1], weight_attribute, weight_attribute.values.first()
+ )
+
+ attribute_count = Attribute.objects.count()
+
+ category = last_product.category
+ variables = {
+ "filters": {
+ "inCategory": graphene.Node.to_global_id("Category", category.pk),
+ "channel": channel_USD.slug,
+ }
+ }
+
+ # when
+ attributes = get_graphql_content(
+ app_api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables)
+ )["data"]["attributes"]["edges"]
+
+ # then
+ assert len(attributes) == attribute_count
+
+
+def test_filter_attributes_in_category_not_published_by_app_without_perm(
+ app_api_client,
+ product_list,
+ weight_attribute,
+ permission_manage_products,
+ channel_USD,
+):
+ # given
+ product_type = ProductType.objects.create(
+ name="Default Type 2",
+ slug="default-type-2",
+ has_variants=True,
+ is_shipping_required=True,
+ )
+ product_type.product_attributes.add(weight_attribute)
+
+ last_product = product_list[-1]
+ last_product.product_type = product_type
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(is_published=False)
+
+ associate_attribute_values_to_instance(
+ product_list[-1], weight_attribute, weight_attribute.values.first()
+ )
+
+ attribute_count = Attribute.objects.count()
+
+ category = last_product.category
+ variables = {
+ "filters": {
+ "inCategory": graphene.Node.to_global_id("Category", category.pk),
+ "channel": channel_USD.slug,
+ }
+ }
+
+ # when
+ attributes = get_graphql_content(
+ app_api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables)
+ )["data"]["attributes"]["edges"]
+
+ # then
+ assert len(attributes) == attribute_count - 1
+ assert weight_attribute.slug not in {
+ attribute["node"]["slug"] for attribute in attributes
+ }
+
+
+def test_filter_attributes_in_collection_not_visible_in_listings_by_customer(
+ user_api_client, product_list, weight_attribute, collection, channel_USD
+):
+ # given
+ product_type = ProductType.objects.create(
+ name="Default Type 2",
+ slug="default-type-2",
+ has_variants=True,
+ is_shipping_required=True,
+ )
+ product_type.product_attributes.add(weight_attribute)
+
+ last_product = product_list[-1]
+ last_product.product_type = product_type
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(visible_in_listings=False)
+
+ for product in product_list:
+ collection.products.add(product)
+
+ associate_attribute_values_to_instance(
+ product_list[-1], weight_attribute, weight_attribute.values.first()
+ )
+
+ attribute_count = Attribute.objects.count()
+
+ variables = {
+ "filters": {
+ "inCollection": graphene.Node.to_global_id("Collection", collection.pk),
+ "channel": channel_USD.slug,
+ }
+ }
+
+ # when
+ attributes = get_graphql_content(
+ user_api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables)
+ )["data"]["attributes"]["edges"]
+
+ # then
+ assert len(attributes) == attribute_count
+
+
+def test_filter_in_collection_not_published_by_customer(
+ user_api_client, product_list, weight_attribute, collection, channel_USD
+):
+ # given
+ product_type = ProductType.objects.create(
+ name="Default Type 2",
+ slug="default-type-2",
+ has_variants=True,
+ is_shipping_required=True,
+ )
+ product_type.product_attributes.add(weight_attribute)
+
+ last_product = product_list[-1]
+ last_product.product_type = product_type
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(is_published=False)
+
+ for product in product_list:
+ collection.products.add(product)
+
+ associate_attribute_values_to_instance(
+ product_list[-1], weight_attribute, weight_attribute.values.first()
+ )
+
+ attribute_count = Attribute.objects.count()
+
+ variables = {
+ "filters": {
+ "inCollection": graphene.Node.to_global_id("Collection", collection.pk),
+ "channel": channel_USD.slug,
+ }
+ }
+
+ # when
+ attributes = get_graphql_content(
+ user_api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables)
+ )["data"]["attributes"]["edges"]
+
+ # then
+ assert len(attributes) == attribute_count - 1
+ assert weight_attribute.slug not in {
+ attribute["node"]["slug"] for attribute in attributes
+ }
+
+
+def test_filter_in_collection_not_published_by_staff_with_perm(
+ staff_api_client,
+ product_list,
+ weight_attribute,
+ permission_manage_products,
+ collection,
+ channel_USD,
+):
+ # given
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ product_type = ProductType.objects.create(
+ name="Default Type 2",
+ slug="default-type-2",
+ has_variants=True,
+ is_shipping_required=True,
+ )
+ product_type.product_attributes.add(weight_attribute)
+
+ last_product = product_list[-1]
+ last_product.product_type = product_type
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(is_published=False)
+
+ for product in product_list:
+ collection.products.add(product)
+
+ associate_attribute_values_to_instance(
+ product_list[-1], weight_attribute, weight_attribute.values.first()
+ )
+
+ attribute_count = Attribute.objects.count()
+
+ variables = {
+ "filters": {
+ "inCollection": graphene.Node.to_global_id("Collection", collection.pk),
+ "channel": channel_USD.slug,
+ }
+ }
+
+ # when
+ attributes = get_graphql_content(
+ staff_api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables)
+ )["data"]["attributes"]["edges"]
+
+ # then
+ assert len(attributes) == attribute_count
+
+
+def test_filter_in_collection_not_published_by_staff_without_perm(
+ staff_api_client,
+ product_list,
+ weight_attribute,
+ permission_manage_products,
+ collection,
+ channel_USD,
+):
+ # given
+ product_type = ProductType.objects.create(
+ name="Default Type 2",
+ slug="default-type-2",
+ has_variants=True,
+ is_shipping_required=True,
+ )
+ product_type.product_attributes.add(weight_attribute)
+
+ last_product = product_list[-1]
+ last_product.product_type = product_type
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(is_published=False)
+
+ for product in product_list:
+ collection.products.add(product)
+
+ associate_attribute_values_to_instance(
+ product_list[-1], weight_attribute, weight_attribute.values.first()
+ )
+
+ attribute_count = Attribute.objects.count()
+
+ variables = {
+ "filters": {
+ "inCollection": graphene.Node.to_global_id("Collection", collection.pk),
+ "channel": channel_USD.slug,
+ }
+ }
+
+ # when
+ attributes = get_graphql_content(
+ staff_api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables)
+ )["data"]["attributes"]["edges"]
+
+ # then
+ assert len(attributes) == attribute_count - 1
+ assert weight_attribute.slug not in {
+ attribute["node"]["slug"] for attribute in attributes
+ }
+
+
+def test_filter_in_collection_not_published_by_app_with_perm(
+ app_api_client,
+ product_list,
+ weight_attribute,
+ permission_manage_products,
+ collection,
+ channel_USD,
+):
+ # given
+ app_api_client.app.permissions.add(permission_manage_products)
+
+ product_type = ProductType.objects.create(
+ name="Default Type 2",
+ slug="default-type-2",
+ has_variants=True,
+ is_shipping_required=True,
+ )
+ product_type.product_attributes.add(weight_attribute)
+
+ last_product = product_list[-1]
+ last_product.product_type = product_type
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(is_published=False)
+
+ for product in product_list:
+ collection.products.add(product)
+
+ associate_attribute_values_to_instance(
+ product_list[-1], weight_attribute, weight_attribute.values.first()
+ )
+
+ attribute_count = Attribute.objects.count()
+
+ variables = {
+ "filters": {
+ "inCollection": graphene.Node.to_global_id("Collection", collection.pk),
+ "channel": channel_USD.slug,
+ }
+ }
+
+ # when
+ attributes = get_graphql_content(
+ app_api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables)
+ )["data"]["attributes"]["edges"]
+
+ # then
+ assert len(attributes) == attribute_count
+
+
+def test_filter_in_collection_not_published_by_app_without_perm(
+ app_api_client,
+ product_list,
+ weight_attribute,
+ permission_manage_products,
+ collection,
+ channel_USD,
+):
+ # given
+ product_type = ProductType.objects.create(
+ name="Default Type 2",
+ slug="default-type-2",
+ has_variants=True,
+ is_shipping_required=True,
+ )
+ product_type.product_attributes.add(weight_attribute)
+
+ last_product = product_list[-1]
+ last_product.product_type = product_type
+ last_product.save(update_fields=["product_type"])
+ last_product.channel_listings.all().update(is_published=False)
+
+ for product in product_list:
+ collection.products.add(product)
+
+ associate_attribute_values_to_instance(
+ product_list[-1], weight_attribute, weight_attribute.values.first()
+ )
+
+ attribute_count = Attribute.objects.count()
+
+ variables = {
+ "filters": {
+ "inCollection": graphene.Node.to_global_id("Collection", collection.pk),
+ "channel": channel_USD.slug,
+ }
+ }
+
+ # when
+ attributes = get_graphql_content(
+ app_api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables)
+ )["data"]["attributes"]["edges"]
+
+ # then
+ assert len(attributes) == attribute_count - 1
+ assert weight_attribute.slug not in {
+ attribute["node"]["slug"] for attribute in attributes
+ }
+
+
+def test_filter_attributes_by_page_type(
+ staff_api_client,
+ size_page_attribute,
+ product_type_attribute_list,
+ permission_manage_products,
+):
+ # given
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ variables = {"filters": {"type": "PAGE_TYPE"}}
+
+ # when
+ attributes = get_graphql_content(
+ staff_api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables)
+ )["data"]["attributes"]["edges"]
+
+ # then
+ assert len(attributes) == 1
+ assert attributes[0]["node"]["slug"] == size_page_attribute.slug
+
+
+def test_filter_attributes_by_product_type(
+ staff_api_client,
+ size_page_attribute,
+ product_type_attribute_list,
+ permission_manage_products,
+):
+ # given
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ variables = {"filters": {"type": "PRODUCT_TYPE"}}
+
+ # when
+ attributes = get_graphql_content(
+ staff_api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables)
+ )["data"]["attributes"]["edges"]
+
+ # then
+ assert len(attributes) == len(product_type_attribute_list)
+ assert size_page_attribute.slug not in {
+ attribute["node"]["slug"] for attribute in attributes
+ }
+
+
+def test_attributes_filter_by_product_type_with_empty_value():
+ """Ensure passing an empty or null value is ignored and the queryset is simply
+ returned without any modification.
+ """
+
+ qs = Attribute.objects.all()
+
+ assert filter_attributes_by_product_types(qs, "...", "", None, None) is qs
+ assert filter_attributes_by_product_types(qs, "...", None, None, None) is qs
+
+
+def test_attributes_filter_by_product_type_with_unsupported_field(
+ customer_user, channel_USD
+):
+ """Ensure using an unknown field to filter attributes by raises a NotImplemented
+ exception.
+ """
+
+ qs = Attribute.objects.all()
+
+ with pytest.raises(NotImplementedError) as exc:
+ filter_attributes_by_product_types(
+ qs, "in_space", "a-value", customer_user, channel_USD.slug
+ )
+
+ assert exc.value.args == ("Filtering by in_space is unsupported",)
+
+
+def test_attributes_filter_by_non_existing_category_id(customer_user, channel_USD):
+ """Ensure using a non-existing category ID returns an empty query set."""
+
+ category_id = graphene.Node.to_global_id("Category", -1)
+ mocked_qs = mock.MagicMock()
+ qs = filter_attributes_by_product_types(
+ mocked_qs, "in_category", category_id, customer_user, channel_USD.slug
+ )
+ assert qs == mocked_qs.none.return_value
diff --git a/saleor/graphql/product/tests/test_attribute_filtering_with_channels.py b/saleor/graphql/attribute/tests/queries/test_attribute_filtering_with_channels.py
similarity index 97%
rename from saleor/graphql/product/tests/test_attribute_filtering_with_channels.py
rename to saleor/graphql/attribute/tests/queries/test_attribute_filtering_with_channels.py
index 5327b66ef8..52247471e3 100644
--- a/saleor/graphql/product/tests/test_attribute_filtering_with_channels.py
+++ b/saleor/graphql/attribute/tests/queries/test_attribute_filtering_with_channels.py
@@ -3,18 +3,16 @@ from decimal import Decimal
import graphene
import pytest
-from ....product.models import (
- Attribute,
- AttributeProduct,
- AttributeVariant,
+from .....attribute.models import Attribute, AttributeProduct, AttributeVariant
+from .....product.models import (
Product,
ProductChannelListing,
ProductType,
ProductVariant,
ProductVariantChannelListing,
)
-from ...channel.filters import LACK_OF_CHANNEL_IN_FILTERING_MSG
-from ...tests.utils import assert_graphql_error_with_message, get_graphql_content
+from ....channel.filters import LACK_OF_CHANNEL_IN_FILTERING_MSG
+from ....tests.utils import assert_graphql_error_with_message, get_graphql_content
@pytest.fixture
diff --git a/saleor/graphql/product/tests/test_attribute_pagination.py b/saleor/graphql/attribute/tests/queries/test_attribute_pagination.py
similarity index 94%
rename from saleor/graphql/product/tests/test_attribute_pagination.py
rename to saleor/graphql/attribute/tests/queries/test_attribute_pagination.py
index 4cafaadbb3..38f68e2d7b 100644
--- a/saleor/graphql/product/tests/test_attribute_pagination.py
+++ b/saleor/graphql/attribute/tests/queries/test_attribute_pagination.py
@@ -3,17 +3,16 @@ from decimal import Decimal
import graphene
import pytest
-from ....product.models import (
- Attribute,
- AttributeProduct,
- AttributeVariant,
+from .....attribute import AttributeType
+from .....attribute.models import Attribute, AttributeProduct, AttributeVariant
+from .....product.models import (
Product,
ProductChannelListing,
ProductType,
ProductVariant,
ProductVariantChannelListing,
)
-from ...tests.utils import get_graphql_content
+from ....tests.utils import get_graphql_content
@pytest.fixture
@@ -25,30 +24,35 @@ def attributes_for_pagination(collection, category, channel_USD):
slug="attr1",
value_required=True,
storefront_search_position=4,
+ type=AttributeType.PRODUCT_TYPE,
),
Attribute(
name="AttrAttr1",
slug="attr_attr1",
value_required=True,
storefront_search_position=3,
+ type=AttributeType.PRODUCT_TYPE,
),
Attribute(
name="AttrAttr2",
slug="attr_attr2",
value_required=True,
storefront_search_position=2,
+ type=AttributeType.PRODUCT_TYPE,
),
Attribute(
name="Attr2",
slug="attr2",
value_required=False,
storefront_search_position=5,
+ type=AttributeType.PRODUCT_TYPE,
),
Attribute(
name="Attr3",
slug="attr3",
value_required=False,
storefront_search_position=1,
+ type=AttributeType.PRODUCT_TYPE,
),
]
)
diff --git a/saleor/graphql/attribute/tests/queries/test_attribute_query.py b/saleor/graphql/attribute/tests/queries/test_attribute_query.py
new file mode 100644
index 0000000000..a0d6a2bbfa
--- /dev/null
+++ b/saleor/graphql/attribute/tests/queries/test_attribute_query.py
@@ -0,0 +1,412 @@
+import graphene
+import pytest
+from django.db.models import Q
+from graphene.utils.str_converters import to_camel_case
+
+from .....attribute.models import Attribute
+from .....product.models import Category, Collection, Product, ProductType
+from ....tests.utils import assert_no_permission, get_graphql_content
+from ...enums import AttributeValueType
+from ...types import resolve_attribute_value_type
+
+
+def test_get_single_attribute_by_id_as_customer(
+ user_api_client, color_attribute_without_values
+):
+ attribute_gql_id = graphene.Node.to_global_id(
+ "Attribute", color_attribute_without_values.id
+ )
+ query = """
+ query($id: ID!) {
+ attribute(id: $id) {
+ id
+ name
+ slug
+ }
+ }
+ """
+ content = get_graphql_content(
+ user_api_client.post_graphql(query, {"id": attribute_gql_id})
+ )
+
+ assert content["data"]["attribute"], "Should have found an attribute"
+ assert content["data"]["attribute"]["id"] == attribute_gql_id
+ assert content["data"]["attribute"]["slug"] == color_attribute_without_values.slug
+
+
+QUERY_ATTRIBUTE = """
+query($id: ID!) {
+ attribute(id: $id) {
+ id
+ slug
+ name
+ inputType
+ type
+ values {
+ slug
+ inputType
+ }
+ valueRequired
+ visibleInStorefront
+ filterableInStorefront
+ filterableInDashboard
+ availableInGrid
+ storefrontSearchPosition
+ }
+}
+"""
+
+
+def test_get_single_product_attribute_by_staff(
+ staff_api_client, color_attribute_without_values, permission_manage_products
+):
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ attribute_gql_id = graphene.Node.to_global_id(
+ "Attribute", color_attribute_without_values.id
+ )
+ query = QUERY_ATTRIBUTE
+ content = get_graphql_content(
+ staff_api_client.post_graphql(query, {"id": attribute_gql_id})
+ )
+
+ assert content["data"]["attribute"], "Should have found an attribute"
+ assert content["data"]["attribute"]["id"] == attribute_gql_id
+ assert content["data"]["attribute"]["slug"] == color_attribute_without_values.slug
+ assert (
+ content["data"]["attribute"]["valueRequired"]
+ == color_attribute_without_values.value_required
+ )
+ assert (
+ content["data"]["attribute"]["visibleInStorefront"]
+ == color_attribute_without_values.visible_in_storefront
+ )
+ assert (
+ content["data"]["attribute"]["filterableInStorefront"]
+ == color_attribute_without_values.filterable_in_storefront
+ )
+ assert (
+ content["data"]["attribute"]["filterableInDashboard"]
+ == color_attribute_without_values.filterable_in_dashboard
+ )
+ assert (
+ content["data"]["attribute"]["availableInGrid"]
+ == color_attribute_without_values.available_in_grid
+ )
+ assert (
+ content["data"]["attribute"]["storefrontSearchPosition"]
+ == color_attribute_without_values.storefront_search_position
+ )
+
+
+def test_get_single_product_attribute_by_app(
+ staff_api_client, color_attribute_without_values, permission_manage_products
+):
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ attribute_gql_id = graphene.Node.to_global_id(
+ "Attribute", color_attribute_without_values.id
+ )
+ query = QUERY_ATTRIBUTE
+ content = get_graphql_content(
+ staff_api_client.post_graphql(query, {"id": attribute_gql_id})
+ )
+
+ assert content["data"]["attribute"], "Should have found an attribute"
+ assert content["data"]["attribute"]["id"] == attribute_gql_id
+ assert content["data"]["attribute"]["slug"] == color_attribute_without_values.slug
+ assert (
+ content["data"]["attribute"]["valueRequired"]
+ == color_attribute_without_values.value_required
+ )
+ assert (
+ content["data"]["attribute"]["visibleInStorefront"]
+ == color_attribute_without_values.visible_in_storefront
+ )
+ assert (
+ content["data"]["attribute"]["filterableInStorefront"]
+ == color_attribute_without_values.filterable_in_storefront
+ )
+ assert (
+ content["data"]["attribute"]["filterableInDashboard"]
+ == color_attribute_without_values.filterable_in_dashboard
+ )
+ assert (
+ content["data"]["attribute"]["availableInGrid"]
+ == color_attribute_without_values.available_in_grid
+ )
+ assert (
+ content["data"]["attribute"]["storefrontSearchPosition"]
+ == color_attribute_without_values.storefront_search_position
+ )
+
+
+def test_get_single_product_attribute_by_staff_no_perm(
+ staff_api_client, color_attribute_without_values, permission_manage_pages
+):
+ staff_api_client.user.user_permissions.add(permission_manage_pages)
+ attribute_gql_id = graphene.Node.to_global_id(
+ "Attribute", color_attribute_without_values.id
+ )
+ query = QUERY_ATTRIBUTE
+ response = staff_api_client.post_graphql(query, {"id": attribute_gql_id})
+
+ assert_no_permission(response)
+
+
+def test_get_single_page_attribute_by_staff(
+ staff_api_client, size_page_attribute, permission_manage_pages
+):
+ staff_api_client.user.user_permissions.add(permission_manage_pages)
+ attribute_gql_id = graphene.Node.to_global_id("Attribute", size_page_attribute.id)
+ query = QUERY_ATTRIBUTE
+ content = get_graphql_content(
+ staff_api_client.post_graphql(query, {"id": attribute_gql_id})
+ )
+
+ assert content["data"]["attribute"], "Should have found an attribute"
+ assert content["data"]["attribute"]["id"] == attribute_gql_id
+ assert content["data"]["attribute"]["slug"] == size_page_attribute.slug
+
+
+def test_get_single_page_attribute_by_staff_no_perm(
+ staff_api_client, size_page_attribute, permission_manage_products
+):
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ attribute_gql_id = graphene.Node.to_global_id("Attribute", size_page_attribute.id)
+ query = QUERY_ATTRIBUTE
+ response = staff_api_client.post_graphql(query, {"id": attribute_gql_id})
+
+ assert_no_permission(response)
+
+
+QUERY_ATTRIBUTES = """
+ query {
+ attributes(first: 20) {
+ edges {
+ node {
+ id
+ name
+ slug
+ values {
+ id
+ name
+ slug
+ }
+ }
+ }
+ }
+ }
+"""
+
+
+def test_attributes_query(user_api_client, product):
+ attributes = Attribute.objects
+ query = QUERY_ATTRIBUTES
+ response = user_api_client.post_graphql(query)
+ content = get_graphql_content(response)
+ attributes_data = content["data"]["attributes"]["edges"]
+ assert attributes_data
+ assert len(attributes_data) == attributes.count()
+
+
+def test_attributes_query_hidden_attribute(user_api_client, product, color_attribute):
+ query = QUERY_ATTRIBUTES
+
+ # hide the attribute
+ color_attribute.visible_in_storefront = False
+ color_attribute.save(update_fields=["visible_in_storefront"])
+
+ attribute_count = Attribute.objects.get_visible_to_user(
+ user_api_client.user
+ ).count()
+ assert attribute_count == 1
+
+ response = user_api_client.post_graphql(query)
+ content = get_graphql_content(response)
+ attributes_data = content["data"]["attributes"]["edges"]
+ assert len(attributes_data) == attribute_count
+
+
+def test_attributes_query_hidden_attribute_as_staff_user(
+ staff_api_client, product, color_attribute, permission_manage_products
+):
+ query = QUERY_ATTRIBUTES
+
+ # hide the attribute
+ color_attribute.visible_in_storefront = False
+ color_attribute.save(update_fields=["visible_in_storefront"])
+
+ attribute_count = Attribute.objects.all().count()
+
+ # The user doesn't have the permission yet to manage products,
+ # the user shouldn't be able to see the hidden attributes
+ assert Attribute.objects.get_visible_to_user(staff_api_client.user).count() == 1
+
+ # The user should now be able to see the attributes
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ response = staff_api_client.post_graphql(query)
+ content = get_graphql_content(response)
+ attributes_data = content["data"]["attributes"]["edges"]
+ assert len(attributes_data) == attribute_count
+
+
+NOT_EXISTS_IDS_ATTRIBUTES_QUERY = """
+ query ($filter: AttributeFilterInput!) {
+ attributes(first: 5, filter: $filter) {
+ edges {
+ node {
+ id
+ name
+ }
+ }
+ }
+ }
+"""
+
+
+def test_attributes_query_ids_not_exists(user_api_client, category):
+ query = NOT_EXISTS_IDS_ATTRIBUTES_QUERY
+ variables = {"filter": {"ids": ["ygRqjpmXYqaTD9r=", "PBa4ZLBhnXHSz6v="]}}
+ response = user_api_client.post_graphql(query, variables)
+ content = get_graphql_content(response, ignore_errors=True)
+ message_error = '{"ids": [{"message": "Invalid ID specified.", "code": ""}]}'
+
+ assert len(content["errors"]) == 1
+ assert content["errors"][0]["message"] == message_error
+ assert content["data"]["attributes"] is None
+
+
+ "attribute, expected_value",
+ (
+ ("filterable_in_storefront", True),
+ ("filterable_in_dashboard", True),
+ ("visible_in_storefront", True),
+ ("available_in_grid", True),
+ ("value_required", False),
+ ("storefront_search_position", 0),
+ ),
+)
+def test_retrieving_the_restricted_attributes_restricted(
+ staff_api_client,
+ color_attribute,
+ permission_manage_products,
+ attribute,
+ expected_value,
+):
+ """Checks if the attributes are restricted and if their default value
+ is the expected one."""
+
+ attribute = to_camel_case(attribute)
+ query = (
+ """
+ {
+ attributes(first: 10) {
+ edges {
+ node {
+ %s
+ }
+ }
+ }
+ }
+ """
+ % attribute
+ )
+
+ found_attributes = get_graphql_content(
+ staff_api_client.post_graphql(query, permissions=[permission_manage_products])
+ )["data"]["attributes"]["edges"]
+
+ assert len(found_attributes) == 1
+ assert found_attributes[0]["node"][attribute] == expected_value
+
+
+ "raw_value, expected_type",
+ [
+ ("#0000", AttributeValueType.COLOR),
+ ("#FF69B4", AttributeValueType.COLOR),
+ ("rgb(255, 0, 0)", AttributeValueType.COLOR),
+ ("hsl(0, 100%, 50%)", AttributeValueType.COLOR),
+ ("hsla(120, 60%, 70%, 0.3)", AttributeValueType.COLOR),
+ ("rgba(100%, 255, 0, 0)", AttributeValueType.COLOR),
+ ("http://example.com", AttributeValueType.URL),
+ ("https://example.com", AttributeValueType.URL),
+ ("ftp://example.com", AttributeValueType.URL),
+ ("example.com", AttributeValueType.STRING),
+ ("Foo", AttributeValueType.STRING),
+ ("linear-gradient(red, yellow)", AttributeValueType.GRADIENT),
+ ("radial-gradient(#0000, yellow)", AttributeValueType.GRADIENT),
+ ],
+)
+def test_resolve_attribute_value_type(raw_value, expected_type):
+ assert resolve_attribute_value_type(raw_value) == expected_type
+
+
[email protected]("tested_field", ["inCategory", "inCollection"])
+def test_attributes_in_collection_query(
+ user_api_client,
+ product_type,
+ category,
+ published_collection,
+ collection_with_products,
+ tested_field,
+ channel_USD,
+):
+ if "Collection" in tested_field:
+ filtered_by_node_id = graphene.Node.to_global_id(
+ "Collection", published_collection.pk
+ )
+ elif "Category" in tested_field:
+ filtered_by_node_id = graphene.Node.to_global_id("Category", category.pk)
+ else:
+ raise AssertionError(tested_field)
+ expected_qs = Attribute.objects.filter(
+ Q(attributeproduct__product_type_id=product_type.pk)
+ | Q(attributevariant__product_type_id=product_type.pk)
+ )
+
+ # Create another product type and attribute that shouldn't get matched
+ other_category = Category.objects.create(name="Other Category", slug="other-cat")
+ other_attribute = Attribute.objects.create(name="Other", slug="other")
+ other_product_type = ProductType.objects.create(
+ name="Other type", has_variants=True, is_shipping_required=True
+ )
+ other_product_type.product_attributes.add(other_attribute)
+ other_product = Product.objects.create(
+ name="Another Product", product_type=other_product_type, category=other_category
+ )
+
+ # Create another collection with products but shouldn't get matched
+ # as we don't look for this other collection
+ other_collection = Collection.objects.create(
+ name="Other Collection", slug="other-collection", description="Description",
+ )
+ other_collection.products.add(other_product)
+
+ query = """
+ query($nodeID: ID!, $channel: String) {
+ attributes(first: 20, %(filter_input)s) {
+ edges {
+ node {
+ id
+ name
+ slug
+ }
+ }
+ }
+ }
+ """
+
+ query = query % {
+ "filter_input": "filter: { %s: $nodeID, channel: $channel }" % tested_field
+ }
+
+ variables = {"nodeID": filtered_by_node_id, "channel": channel_USD.slug}
+ content = get_graphql_content(user_api_client.post_graphql(query, variables))
+ attributes_data = content["data"]["attributes"]["edges"]
+
+ flat_attributes_data = [attr["node"]["slug"] for attr in attributes_data]
+ expected_flat_attributes_data = list(expected_qs.values_list("slug", flat=True))
+
+ assert flat_attributes_data == expected_flat_attributes_data
diff --git a/saleor/graphql/attribute/tests/queries/test_attributes_sort.py b/saleor/graphql/attribute/tests/queries/test_attributes_sort.py
new file mode 100644
index 0000000000..0327c832bd
--- /dev/null
+++ b/saleor/graphql/attribute/tests/queries/test_attributes_sort.py
@@ -0,0 +1,148 @@
+from typing import TYPE_CHECKING, Union
+
+import graphene
+import pytest
+
+from .....attribute import AttributeType
+from .....attribute.models import Attribute
+from .....attribute.utils import associate_attribute_values_to_instance
+from ....tests.utils import get_graphql_content
+
+if TYPE_CHECKING:
+ from .....product.models import Product, ProductVariant
+
+
+ATTRIBUTES_SORT_QUERY = """
+ query($sortBy: AttributeSortingInput) {
+ attributes(first: 10, sortBy: $sortBy) {
+ edges {
+ node {
+ slug
+ }
+ }
+ }
+ }
+"""
+
+
+def test_sort_attributes_by_slug(api_client):
+ Attribute.objects.bulk_create(
+ [
+ Attribute(name="MyAttribute", slug="b", type=AttributeType.PRODUCT_TYPE),
+ Attribute(name="MyAttribute", slug="a", type=AttributeType.PRODUCT_TYPE),
+ ]
+ )
+
+ variables = {"sortBy": {"field": "SLUG", "direction": "ASC"}}
+
+ attributes = get_graphql_content(
+ api_client.post_graphql(ATTRIBUTES_SORT_QUERY, variables)
+ )["data"]["attributes"]["edges"]
+
+ assert len(attributes) == 2
+ assert attributes[0]["node"]["slug"] == "a"
+ assert attributes[1]["node"]["slug"] == "b"
+
+
+def test_sort_attributes_by_default_sorting(api_client):
+ """Don't provide any sorting, this should sort by slug by default."""
+ Attribute.objects.bulk_create(
+ [
+ Attribute(name="A", slug="b", type=AttributeType.PRODUCT_TYPE),
+ Attribute(name="B", slug="a", type=AttributeType.PRODUCT_TYPE),
+ ]
+ )
+
+ attributes = get_graphql_content(
+ api_client.post_graphql(ATTRIBUTES_SORT_QUERY, {})
+ )["data"]["attributes"]["edges"]
+
+ assert len(attributes) == 2
+ assert attributes[0]["node"]["slug"] == "a"
+ assert attributes[1]["node"]["slug"] == "b"
+
+
[email protected]("is_variant", (True, False))
+def test_attributes_of_products_are_sorted(
+ user_api_client, product, color_attribute, is_variant, channel_USD
+):
+ """Ensures the attributes of products and variants are sorted."""
+
+ variant = product.variants.first()
+
+ if is_variant:
+ query = """
+ query($id: ID!, $channel: String) {
+ productVariant(id: $id, channel: $channel) {
+ attributes {
+ attribute {
+ id
+ }
+ }
+ }
+ }
+ """
+ else:
+ query = """
+ query($id: ID!, $channel: String) {
+ product(id: $id, channel: $channel) {
+ attributes {
+ attribute {
+ id
+ }
+ }
+ }
+ }
+ """
+
+ # Create a dummy attribute with a higher ID
+ # This will allow us to make sure it is always the last attribute
+ # when sorted by ID. Thus, we are sure the query is actually passing the test.
+ other_attribute = Attribute.objects.create(name="Other", slug="other")
+
+ # Add the attribute to the product type
+ if is_variant:
+ product.product_type.variant_attributes.set([color_attribute, other_attribute])
+ else:
+ product.product_type.product_attributes.set([color_attribute, other_attribute])
+
+ # Retrieve the M2M object for the attribute vs the product type
+ if is_variant:
+ m2m_rel_other_attr = other_attribute.attributevariant.last()
+ else:
+ m2m_rel_other_attr = other_attribute.attributeproduct.last()
+
+ # Push the last attribute to the top and let the others to None
+ m2m_rel_other_attr.sort_order = 0
+ m2m_rel_other_attr.save(update_fields=["sort_order"])
+
+ # Assign attributes to the product
+ node = variant if is_variant else product # type: Union[Product, ProductVariant]
+ node.attributesrelated.clear()
+ associate_attribute_values_to_instance(
+ node, color_attribute, color_attribute.values.first()
+ )
+
+ # Sort the database attributes by their sort order and ID (when None)
+ expected_order = [other_attribute.pk, color_attribute.pk]
+
+ # Make the node ID
+ if is_variant:
+ node_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ else:
+ node_id = graphene.Node.to_global_id("Product", product.pk)
+
+ # Retrieve the attributes
+ data = get_graphql_content(
+ user_api_client.post_graphql(
+ query, {"id": node_id, "channel": channel_USD.slug}
+ )
+ )["data"]
+ attributes = data["productVariant" if is_variant else "product"]["attributes"]
+ actual_order = [
+ int(graphene.Node.from_global_id(attr["attribute"]["id"])[1])
+ for attr in attributes
+ ]
+
+ # Compare the received data against our expectations
+ assert actual_order == expected_order
diff --git a/saleor/graphql/product/types/attributes.py b/saleor/graphql/attribute/types.py
similarity index 81%
rename from saleor/graphql/product/types/attributes.py
rename to saleor/graphql/attribute/types.py
index 5b9975e11a..dfd19355f4 100644
--- a/saleor/graphql/product/types/attributes.py
+++ b/saleor/graphql/attribute/types.py
@@ -1,18 +1,19 @@
import re
import graphene
-from graphene import relay
-
-from ....core.permissions import ProductPermissions
-from ....product import models
-from ...core.connection import CountableDjangoObjectType
-from ...decorators import permission_required
-from ...meta.types import ObjectWithMetadata
-from ...translations.fields import TranslationField
-from ...translations.types import AttributeTranslation, AttributeValueTranslation
-from ..dataloaders import AttributeValuesByAttributeIdLoader
-from ..descriptions import AttributeDescriptions, AttributeValueDescriptions
-from ..enums import AttributeInputTypeEnum, AttributeValueType
+
+from ...attribute import models
+from ..core.connection import CountableDjangoObjectType
+from ..decorators import (
+ check_attribute_required_permissions,
+ check_attribute_value_required_permissions,
+)
+from ..meta.types import ObjectWithMetadata
+from ..translations.fields import TranslationField
+from ..translations.types import AttributeTranslation, AttributeValueTranslation
+from .dataloaders import AttributeValuesByAttributeIdLoader
+from .descriptions import AttributeDescriptions, AttributeValueDescriptions
+from .enums import AttributeInputTypeEnum, AttributeTypeEnum, AttributeValueType
COLOR_PATTERN = r"^(#[0-9a-fA-F]{3}|#(?:[0-9a-fA-F]{2}){2,4}|(rgb|hsl)a?\((-?\d+%?[,\s]+){2,3}\s*[\d\.]+%?\))$" # noqa
color_pattern = re.compile(COLOR_PATTERN)
@@ -46,7 +47,7 @@ class AttributeValue(CountableDjangoObjectType):
class Meta:
description = "Represents a value of an attribute."
only_fields = ["id"]
- interfaces = [relay.Node]
+ interfaces = [graphene.relay.Node]
model = models.AttributeValue
@staticmethod
@@ -54,7 +55,7 @@ class AttributeValue(CountableDjangoObjectType):
return resolve_attribute_value_type(root.value)
@staticmethod
- @permission_required(ProductPermissions.MANAGE_PRODUCTS)
+ @check_attribute_value_required_permissions()
def resolve_input_type(root: models.AttributeValue, *_args):
return root.input_type
@@ -64,6 +65,7 @@ class Attribute(CountableDjangoObjectType):
name = graphene.String(description=AttributeDescriptions.NAME)
slug = graphene.String(description=AttributeDescriptions.SLUG)
+ type = AttributeTypeEnum(description=AttributeDescriptions.TYPE)
values = graphene.List(AttributeValue, description=AttributeDescriptions.VALUES)
@@ -95,7 +97,7 @@ class Attribute(CountableDjangoObjectType):
"variants at the product type level."
)
only_fields = ["id", "product_types", "product_variant_types"]
- interfaces = [relay.Node, ObjectWithMetadata]
+ interfaces = [graphene.relay.Node, ObjectWithMetadata]
model = models.Attribute
@staticmethod
@@ -103,32 +105,32 @@ class Attribute(CountableDjangoObjectType):
return AttributeValuesByAttributeIdLoader(info.context).load(root.id)
@staticmethod
- @permission_required(ProductPermissions.MANAGE_PRODUCTS)
+ @check_attribute_required_permissions()
def resolve_value_required(root: models.Attribute, *_args):
return root.value_required
@staticmethod
- @permission_required(ProductPermissions.MANAGE_PRODUCTS)
+ @check_attribute_required_permissions()
def resolve_visible_in_storefront(root: models.Attribute, *_args):
return root.visible_in_storefront
@staticmethod
- @permission_required(ProductPermissions.MANAGE_PRODUCTS)
+ @check_attribute_required_permissions()
def resolve_filterable_in_storefront(root: models.Attribute, *_args):
return root.filterable_in_storefront
@staticmethod
- @permission_required(ProductPermissions.MANAGE_PRODUCTS)
+ @check_attribute_required_permissions()
def resolve_filterable_in_dashboard(root: models.Attribute, *_args):
return root.filterable_in_dashboard
@staticmethod
- @permission_required(ProductPermissions.MANAGE_PRODUCTS)
+ @check_attribute_required_permissions()
def resolve_storefront_search_position(root: models.Attribute, *_args):
return root.storefront_search_position
@staticmethod
- @permission_required(ProductPermissions.MANAGE_PRODUCTS)
+ @check_attribute_required_permissions()
def resolve_available_in_grid(root: models.Attribute, *_args):
return root.available_in_grid
diff --git a/saleor/graphql/core/enums.py b/saleor/graphql/core/enums.py
index 358810ce79..6301505d34 100644
--- a/saleor/graphql/core/enums.py
+++ b/saleor/graphql/core/enums.py
@@ -2,6 +2,7 @@ import graphene
from ...account import error_codes as account_error_codes
from ...app import error_codes as app_error_codes
+from ...attribute import error_codes as attribute_error_codes
from ...channel import error_codes as channel_error_codes
from ...checkout import error_codes as checkout_error_codes
from ...core import JobStatus, error_codes as core_error_codes
@@ -88,6 +89,7 @@ WeightUnitsEnum = graphene.Enum(
AccountErrorCode = graphene.Enum.from_enum(account_error_codes.AccountErrorCode)
AppErrorCode = graphene.Enum.from_enum(app_error_codes.AppErrorCode)
+AttributeErrorCode = graphene.Enum.from_enum(attribute_error_codes.AttributeErrorCode)
ChannelErrorCode = graphene.Enum.from_enum(channel_error_codes.ChannelErrorCode)
CheckoutErrorCode = graphene.Enum.from_enum(checkout_error_codes.CheckoutErrorCode)
ExportErrorCode = graphene.Enum.from_enum(csv_error_codes.ExportErrorCode)
diff --git a/saleor/graphql/product/mutations/common.py b/saleor/graphql/core/inputs.py
similarity index 100%
rename from saleor/graphql/product/mutations/common.py
rename to saleor/graphql/core/inputs.py
diff --git a/saleor/graphql/core/tests/test_core_reordering.py b/saleor/graphql/core/tests/test_core_reordering.py
index d73d4ec5fe..ed1c98c2b5 100644
--- a/saleor/graphql/core/tests/test_core_reordering.py
+++ b/saleor/graphql/core/tests/test_core_reordering.py
@@ -1,9 +1,9 @@
import pytest
-from ....product import models
+from ....attribute import models as attribute_models
from ..utils.reordering import perform_reordering
-SortedModel = models.AttributeValue
+SortedModel = attribute_models.AttributeValue
def _sorted_by_order(items):
@@ -18,7 +18,7 @@ def _get_sorted_map():
@pytest.fixture
def dummy_attribute():
- return models.Attribute.objects.create(name="Dummy")
+ return attribute_models.Attribute.objects.create(name="Dummy")
@pytest.fixture
@@ -266,18 +266,19 @@ def test_reordering_concurrently(dummy_attribute, assert_num_queries):
perform_reordering(qs, operations)
assert ctx[0]["sql"] == (
- 'SELECT "product_attributevalue"."id", "product_attributevalue"."sort_order" '
- 'FROM "product_attributevalue" '
+ 'SELECT "attribute_attributevalue"."id", '
+ '"attribute_attributevalue"."sort_order" '
+ 'FROM "attribute_attributevalue" '
"ORDER BY "
- '"product_attributevalue"."sort_order" ASC NULLS LAST, '
- '"product_attributevalue"."id" ASC FOR UPDATE'
+ '"attribute_attributevalue"."sort_order" ASC NULLS LAST, '
+ '"attribute_attributevalue"."id" ASC FOR UPDATE'
)
assert ctx[1]["sql"] == (
- 'UPDATE "product_attributevalue" '
- 'SET "sort_order" = (CASE WHEN ("product_attributevalue"."id" = 1) '
- 'THEN 1 WHEN ("product_attributevalue"."id" = 2) '
+ 'UPDATE "attribute_attributevalue" '
+ 'SET "sort_order" = (CASE WHEN ("attribute_attributevalue"."id" = 1) '
+ 'THEN 1 WHEN ("attribute_attributevalue"."id" = 2) '
"THEN 0 ELSE NULL END)::integer "
- 'WHERE "product_attributevalue"."id" IN (1, 2)'
+ 'WHERE "attribute_attributevalue"."id" IN (1, 2)'
)
@@ -309,9 +310,9 @@ def test_reordering_deleted_node_from_concurrent(dummy_attribute, assert_num_que
perform_reordering(qs, operations)
assert ctx[1]["sql"] == (
- 'UPDATE "product_attributevalue" '
- 'SET "sort_order" = (CASE WHEN ("product_attributevalue"."id" = 1) '
- 'THEN 1 WHEN ("product_attributevalue"."id" = 2) '
+ 'UPDATE "attribute_attributevalue" '
+ 'SET "sort_order" = (CASE WHEN ("attribute_attributevalue"."id" = 1) '
+ 'THEN 1 WHEN ("attribute_attributevalue"."id" = 2) '
"THEN 0 ELSE NULL END)::integer "
- 'WHERE "product_attributevalue"."id" IN (1, 2)'
+ 'WHERE "attribute_attributevalue"."id" IN (1, 2)'
)
diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.py
index e19bf39d06..ee7c70ff85 100644
--- a/saleor/graphql/core/types/common.py
+++ b/saleor/graphql/core/types/common.py
@@ -5,6 +5,7 @@ from ...translations.enums import LanguageCodeEnum
from ..enums import (
AccountErrorCode,
AppErrorCode,
+ AttributeErrorCode,
ChannelErrorCode,
CheckoutErrorCode,
CollectionErrorCode,
@@ -85,6 +86,10 @@ class AppError(Error):
)
+class AttributeError(Error):
+ code = AttributeErrorCode(description="The error code.", required=True)
+
+
class StaffError(AccountError):
permissions = graphene.List(
graphene.NonNull(PermissionEnum),
@@ -242,6 +247,11 @@ class ShippingError(Error):
class PageError(Error):
code = PageErrorCode(description="The error code.", required=True)
+ attributes = graphene.List(
+ graphene.NonNull(graphene.ID),
+ description="List of attributes IDs which causes the error.",
+ required=False,
+ )
class PaymentError(Error):
diff --git a/saleor/graphql/core/utils/error_codes.py b/saleor/graphql/core/utils/error_codes.py
index 1e4405e816..0eb7382063 100644
--- a/saleor/graphql/core/utils/error_codes.py
+++ b/saleor/graphql/core/utils/error_codes.py
@@ -2,6 +2,7 @@ from enum import Enum
from ....account.error_codes import AccountErrorCode, PermissionGroupErrorCode
from ....app.error_codes import AppErrorCode
+from ....attribute.error_codes import AttributeErrorCode
from ....channel.error_codes import ChannelErrorCode
from ....checkout.error_codes import CheckoutErrorCode
from ....core.error_codes import (
@@ -16,6 +17,7 @@ from ....giftcard.error_codes import GiftCardErrorCode
from ....invoice.error_codes import InvoiceErrorCode
from ....menu.error_codes import MenuErrorCode
from ....order.error_codes import OrderErrorCode
+from ....page.error_codes import PageErrorCode
from ....payment.error_codes import PaymentErrorCode
from ....plugins.error_codes import PluginErrorCode
from ....product.error_codes import ProductErrorCode
@@ -52,6 +54,7 @@ DJANGO_FORM_FIELDS_ERROR_CODES = [
SALEOR_ERROR_CODE_ENUMS = [
AccountErrorCode,
AppErrorCode,
+ AttributeErrorCode,
ChannelErrorCode,
CheckoutErrorCode,
ExportErrorCode,
@@ -62,6 +65,7 @@ SALEOR_ERROR_CODE_ENUMS = [
MenuErrorCode,
MetadataErrorCode,
OrderErrorCode,
+ PageErrorCode,
PaymentErrorCode,
PermissionGroupErrorCode,
ProductErrorCode,
diff --git a/saleor/graphql/csv/mutations.py b/saleor/graphql/csv/mutations.py
index abd60c978a..010e8ef4cd 100644
--- a/saleor/graphql/csv/mutations.py
+++ b/saleor/graphql/csv/mutations.py
@@ -7,12 +7,13 @@ from ...core.permissions import ProductPermissions
from ...csv import models as csv_models
from ...csv.events import export_started_event
from ...csv.tasks import export_products_task
+from ..attribute.types import Attribute
from ..channel.types import Channel
from ..core.enums import ExportErrorCode
from ..core.mutations import BaseMutation
from ..core.types.common import ExportError
from ..product.filters import ProductFilterInput
-from ..product.types import Attribute, Product
+from ..product.types import Product
from ..utils import resolve_global_ids_to_primary_keys
from ..warehouse.types import Warehouse
from .enums import ExportScope, FileTypeEnum, ProductFieldEnum
diff --git a/saleor/graphql/csv/tests/mutations/test_export_products.py b/saleor/graphql/csv/tests/mutations/test_export_products.py
index 322c5c696a..dd34727f70 100644
--- a/saleor/graphql/csv/tests/mutations/test_export_products.py
+++ b/saleor/graphql/csv/tests/mutations/test_export_products.py
@@ -3,10 +3,10 @@ from unittest.mock import ANY, patch
import graphene
import pytest
+from .....attribute.models import Attribute
from .....channel.models import Channel
from .....csv import ExportEvents
from .....csv.models import ExportEvent
-from .....product.models import Attribute
from .....warehouse.models import Warehouse
from ....tests.utils import get_graphql_content
from ...enums import ExportScope, FileTypeEnum, ProductFieldEnum
diff --git a/saleor/graphql/decorators.py b/saleor/graphql/decorators.py
index ef4bedf70e..e0764921a1 100644
--- a/saleor/graphql/decorators.py
+++ b/saleor/graphql/decorators.py
@@ -4,8 +4,9 @@ from typing import Iterable, Union
from graphql.execution.base import ResolveInfo
+from ..attribute import AttributeType
from ..core.exceptions import PermissionDenied
-from ..core.permissions import AccountPermissions
+from ..core.permissions import AccountPermissions, PagePermissions, ProductPermissions
def context(f):
@@ -35,6 +36,23 @@ def account_passes_test(test_func):
return decorator
+def account_passes_test_for_attribute(test_func):
+ """Determine if user/app has permission to access to content."""
+
+ def decorator(f):
+ @wraps(f)
+ @context(f)
+ def wrapper(context, *args, **kwargs):
+ root = args[0]
+ if test_func(context, root):
+ return f(*args, **kwargs)
+ raise PermissionDenied()
+
+ return wrapper
+
+ return decorator
+
+
def _permission_required(perms: Iterable[Enum], context):
if context.user.has_perms(perms):
return True
@@ -77,3 +95,33 @@ staff_member_required = account_passes_test(
staff_member_or_app_required = account_passes_test(
lambda context: context.app or (context.user.is_active and context.user.is_staff)
)
+
+
+def check_attribute_required_permissions():
+ """Check attribute permissions that depend on attribute type.
+
+ As an attribute can belong to the product or to the page,
+ different permissions need to be checked.
+ """
+
+ def check_perms(context, attribute):
+ if attribute.type == AttributeType.PAGE_TYPE:
+ return _permission_required((PagePermissions.MANAGE_PAGES,), context)
+ return _permission_required((ProductPermissions.MANAGE_PRODUCTS,), context)
+
+ return account_passes_test_for_attribute(check_perms)
+
+
+def check_attribute_value_required_permissions():
+ """Check attribute value permissions depending on the corresponding attribute type.
+
+ As an value's attribute can belong to the product or to the page,
+ different permissions need to be checked.
+ """
+
+ def check_perms(context, attribute_value):
+ if attribute_value.attribute.type == AttributeType.PAGE_TYPE:
+ return _permission_required((PagePermissions.MANAGE_PAGES,), context)
+ return _permission_required((ProductPermissions.MANAGE_PRODUCTS,), context)
+
+ return account_passes_test_for_attribute(check_perms)
diff --git a/saleor/graphql/menu/tests/test_menu.py b/saleor/graphql/menu/tests/test_menu.py
index fc351c71ff..57f5fb67fd 100644
--- a/saleor/graphql/menu/tests/test_menu.py
+++ b/saleor/graphql/menu/tests/test_menu.py
@@ -426,21 +426,24 @@ def test_query_menu_items_with_sort(
assert menu_items[order]["node"]["name"] == menu_item_name
-def test_menu_item_query_static_url(user_api_client, menu_item):
- query = """
- query menuitem($id: ID!) {
- menuItem(id: $id) {
- name
- url
- category {
- id
- }
- page {
- id
- }
+QUERY_MENU_ITEM = """
+query menuitem($id: ID!) {
+ menuItem(id: $id) {
+ name
+ url
+ category {
+ id
+ }
+ page {
+ id
}
}
- """
+}
+"""
+
+
+def test_menu_item_query_static_url(user_api_client, menu_item):
+ query = QUERY_MENU_ITEM
menu_item.url = "http://example.com"
menu_item.save()
variables = {"id": graphene.Node.to_global_id("MenuItem", menu_item.pk)}
@@ -453,6 +456,55 @@ def test_menu_item_query_static_url(user_api_client, menu_item):
assert not data["page"]
+def test_menu_item_query_staff_with_permission_gets_all_pages(
+ staff_api_client, permission_manage_pages, menu_item, page
+):
+ # given
+ staff_api_client.user.user_permissions.add(permission_manage_pages)
+ variables = {"id": graphene.Node.to_global_id("MenuItem", menu_item.pk)}
+
+ page.is_published = False
+ page.save(update_fields=["is_published"])
+
+ menu_item.page = page
+ menu_item.save(update_fields=["page"])
+
+ # when
+ response = staff_api_client.post_graphql(QUERY_MENU_ITEM, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["menuItem"]
+
+ assert data["name"] == menu_item.name
+ assert data["url"] == menu_item.url
+ assert data["page"]["id"] == graphene.Node.to_global_id("Page", page.id)
+
+
+def test_menu_item_query_staff_without_permission_gets_only_published_pages(
+ staff_api_client, permission_manage_pages, menu_item, page
+):
+ # given
+ variables = {"id": graphene.Node.to_global_id("MenuItem", menu_item.pk)}
+
+ page.is_published = False
+ page.save(update_fields=["is_published"])
+
+ menu_item.page = page
+ menu_item.save(update_fields=["page"])
+
+ # when
+ response = staff_api_client.post_graphql(QUERY_MENU_ITEM, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["menuItem"]
+
+ assert data["name"] == menu_item.name
+ assert data["url"] == menu_item.url
+ assert data["page"] is None
+
+
def test_create_menu(
staff_api_client, published_collection, category, page, permission_manage_menus
):
diff --git a/saleor/graphql/menu/types.py b/saleor/graphql/menu/types.py
index 2e35e040db..28d355f913 100644
--- a/saleor/graphql/menu/types.py
+++ b/saleor/graphql/menu/types.py
@@ -1,6 +1,7 @@
import graphene
from graphene import relay
+from ...core.permissions import PagePermissions
from ...menu import models
from ...product.models import Collection
from ..channel.dataloaders import ChannelBySlugLoader
@@ -165,7 +166,19 @@ class MenuItem(ChannelContextType, CountableDjangoObjectType):
@staticmethod
def resolve_page(root: ChannelContext[models.MenuItem], info, **kwargs):
if root.node.page_id:
- return PageByIdLoader(info.context).load(root.node.page_id)
+ requestor = get_user_or_app_from_context(info.context)
+ requestor_has_access_to_all = requestor.is_active and requestor.has_perm(
+ PagePermissions.MANAGE_PAGES
+ )
+ return (
+ PageByIdLoader(info.context)
+ .load(root.node.page_id)
+ .then(
+ lambda page: page
+ if requestor_has_access_to_all or page.is_visible
+ else None
+ )
+ )
return None
diff --git a/saleor/graphql/meta/permissions.py b/saleor/graphql/meta/permissions.py
index bbc25ae88f..9faa3d074d 100644
--- a/saleor/graphql/meta/permissions.py
+++ b/saleor/graphql/meta/permissions.py
@@ -1,6 +1,7 @@
from typing import Any, List
from ...account import models as account_models
+from ...attribute import AttributeType, models as attribute_models
from ...core.exceptions import PermissionDenied
from ...core.permissions import (
AccountPermissions,
@@ -9,6 +10,7 @@ from ...core.permissions import (
CheckoutPermissions,
OrderPermissions,
PagePermissions,
+ PageTypePermissions,
ProductPermissions,
ProductTypePermissions,
ShippingPermissions,
@@ -73,12 +75,24 @@ def page_permissions(_info, _object_pk: Any) -> List[BasePermissionEnum]:
return [PagePermissions.MANAGE_PAGES]
+def page_type_permissions(_info, _object_pk: Any) -> List[BasePermissionEnum]:
+ return [PageTypePermissions.MANAGE_PAGE_TYPES_AND_ATTRIBUTES]
+
+
+def attribute_permissions(_info, attribute_pk: int):
+ attribute = attribute_models.Attribute.objects.get(pk=attribute_pk)
+ if attribute.type == AttributeType.PAGE_TYPE:
+ return page_type_permissions(_info, attribute_pk)
+ else:
+ return product_type_permissions(_info, attribute_pk)
+
+
def shipping_permissions(_info, _object_pk: Any) -> List[BasePermissionEnum]:
return [ShippingPermissions.MANAGE_SHIPPING]
PUBLIC_META_PERMISSION_MAP = {
- "Attribute": product_type_permissions,
+ "Attribute": attribute_permissions,
"Category": product_permissions,
"Checkout": no_permissions,
"Collection": product_permissions,
@@ -87,6 +101,7 @@ PUBLIC_META_PERMISSION_MAP = {
"Order": no_permissions,
"Invoice": invoice_permissions,
"Page": page_permissions,
+ "PageType": page_type_permissions,
"Product": product_permissions,
"ProductType": product_type_permissions,
"ProductVariant": product_permissions,
@@ -98,7 +113,7 @@ PUBLIC_META_PERMISSION_MAP = {
PRIVATE_META_PERMISSION_MAP = {
- "Attribute": product_type_permissions,
+ "Attribute": attribute_permissions,
"Category": product_permissions,
"Checkout": checkout_permissions,
"Collection": product_permissions,
@@ -107,6 +122,7 @@ PRIVATE_META_PERMISSION_MAP = {
"Order": order_permissions,
"Invoice": invoice_permissions,
"Page": page_permissions,
+ "PageType": page_type_permissions,
"Product": product_permissions,
"ProductType": product_type_permissions,
"ProductVariant": product_permissions,
diff --git a/saleor/graphql/meta/resolvers.py b/saleor/graphql/meta/resolvers.py
index 9a02802347..b846fae3f1 100644
--- a/saleor/graphql/meta/resolvers.py
+++ b/saleor/graphql/meta/resolvers.py
@@ -2,6 +2,7 @@ from operator import itemgetter
from ...account import models as account_models
from ...app import models as app_models
+from ...attribute import models as attribute_models
from ...checkout import models as checkout_models
from ...core.exceptions import PermissionDenied
from ...core.models import ModelWithMetadata
@@ -17,6 +18,7 @@ def resolve_object_with_metadata_type(instance: ModelWithMetadata):
# Imports inside resolvers to avoid circular imports.
from ...invoice import models as invoice_models
from ..account import types as account_types
+ from ..attribute import types as attribute_types
from ..app import types as app_types
from ..checkout import types as checkout_types
from ..invoice import types as invoice_types
@@ -26,7 +28,7 @@ def resolve_object_with_metadata_type(instance: ModelWithMetadata):
from ..shipping import types as shipping_types
MODEL_TO_TYPE_MAP = {
- product_models.Attribute: product_types.Attribute,
+ attribute_models.Attribute: attribute_types.Attribute,
product_models.Category: product_types.Category,
checkout_models.Checkout: checkout_types.Checkout,
product_models.Collection: product_types.Collection,
@@ -35,6 +37,7 @@ def resolve_object_with_metadata_type(instance: ModelWithMetadata):
order_models.Order: order_types.Order,
invoice_models.Invoice: invoice_types.Invoice,
page_models.Page: page_types.Page,
+ page_models.PageType: page_types.PageType,
product_models.Product: product_types.Product,
product_models.ProductType: product_types.ProductType,
product_models.ProductVariant: product_types.ProductVariant,
diff --git a/saleor/graphql/meta/tests/test_meta_mutations.py b/saleor/graphql/meta/tests/test_meta_mutations.py
index 730fa92880..7d1402f024 100644
--- a/saleor/graphql/meta/tests/test_meta_mutations.py
+++ b/saleor/graphql/meta/tests/test_meta_mutations.py
@@ -343,7 +343,7 @@ def test_add_public_metadata_for_draft_order(api_client, draft_order):
)
-def test_add_public_metadata_for_attribute(
+def test_add_public_metadata_for_product_attribute(
staff_api_client, permission_manage_product_types_and_attributes, color_attribute
):
# given
@@ -363,6 +363,26 @@ def test_add_public_metadata_for_attribute(
)
+def test_add_public_metadata_for_page_attribute(
+ staff_api_client, permission_manage_page_types_and_attributes, size_page_attribute
+):
+ # given
+ attribute_id = graphene.Node.to_global_id("Attribute", size_page_attribute.pk)
+
+ # when
+ response = execute_update_public_metadata_for_item(
+ staff_api_client,
+ permission_manage_page_types_and_attributes,
+ attribute_id,
+ "Attribute",
+ )
+
+ # then
+ assert item_contains_proper_public_metadata(
+ response["data"]["updateMetadata"]["item"], size_page_attribute, attribute_id
+ )
+
+
def test_add_public_metadata_for_category(
staff_api_client, permission_manage_products, category
):
@@ -891,7 +911,7 @@ def test_delete_public_metadata_for_draft_order(api_client, draft_order):
)
-def test_delete_public_metadata_for_attribute(
+def test_delete_public_metadata_for_product_attribute(
staff_api_client, permission_manage_product_types_and_attributes, color_attribute
):
# given
@@ -913,6 +933,28 @@ def test_delete_public_metadata_for_attribute(
)
+def test_delete_public_metadata_for_page_attribute(
+ staff_api_client, permission_manage_page_types_and_attributes, size_page_attribute
+):
+ # given
+ size_page_attribute.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
+ size_page_attribute.save(update_fields=["metadata"])
+ attribute_id = graphene.Node.to_global_id("Attribute", size_page_attribute.pk)
+
+ # when
+ response = execute_clear_public_metadata_for_item(
+ staff_api_client,
+ permission_manage_page_types_and_attributes,
+ attribute_id,
+ "Attribute",
+ )
+
+ # then
+ assert item_without_public_metadata(
+ response["data"]["deleteMetadata"]["item"], size_page_attribute, attribute_id
+ )
+
+
def test_delete_public_metadata_for_category(
staff_api_client, permission_manage_products, category
):
@@ -1510,7 +1552,7 @@ def test_add_private_metadata_for_draft_order(
)
-def test_add_private_metadata_for_attribute(
+def test_add_private_metadata_for_product_attribute(
staff_api_client, permission_manage_product_types_and_attributes, color_attribute
):
# given
@@ -1530,6 +1572,28 @@ def test_add_private_metadata_for_attribute(
)
+def test_add_private_metadata_for_page_attribute(
+ staff_api_client, permission_manage_page_types_and_attributes, size_page_attribute
+):
+ # given
+ attribute_id = graphene.Node.to_global_id("Attribute", size_page_attribute.pk)
+
+ # when
+ response = execute_update_private_metadata_for_item(
+ staff_api_client,
+ permission_manage_page_types_and_attributes,
+ attribute_id,
+ "Attribute",
+ )
+
+ # then
+ assert item_contains_proper_private_metadata(
+ response["data"]["updatePrivateMetadata"]["item"],
+ size_page_attribute,
+ attribute_id,
+ )
+
+
def test_add_private_metadata_for_category(
staff_api_client, permission_manage_products, category
):
@@ -2085,7 +2149,7 @@ def test_delete_private_metadata_for_draft_order(
)
-def test_delete_private_metadata_for_attribute(
+def test_delete_private_metadata_for_product_attribute(
staff_api_client, permission_manage_product_types_and_attributes, color_attribute
):
# given
@@ -2107,6 +2171,30 @@ def test_delete_private_metadata_for_attribute(
)
+def test_delete_private_metadata_for_page_attribute(
+ staff_api_client, permission_manage_page_types_and_attributes, size_page_attribute
+):
+ # given
+ size_page_attribute.store_value_in_private_metadata({PRIVATE_KEY: PRIVATE_VALUE})
+ size_page_attribute.save(update_fields=["private_metadata"])
+ attribute_id = graphene.Node.to_global_id("Attribute", size_page_attribute.pk)
+
+ # when
+ response = execute_clear_private_metadata_for_item(
+ staff_api_client,
+ permission_manage_page_types_and_attributes,
+ attribute_id,
+ "Attribute",
+ )
+
+ # then
+ assert item_without_private_metadata(
+ response["data"]["deletePrivateMetadata"]["item"],
+ size_page_attribute,
+ attribute_id,
+ )
+
+
def test_delete_private_metadata_for_category(
staff_api_client, permission_manage_products, category
):
diff --git a/saleor/graphql/meta/tests/test_meta_queries.py b/saleor/graphql/meta/tests/test_meta_queries.py
index 4e9d7f960e..3e3abf3d8c 100644
--- a/saleor/graphql/meta/tests/test_meta_queries.py
+++ b/saleor/graphql/meta/tests/test_meta_queries.py
@@ -1369,6 +1369,96 @@ def test_query_public_meta_for_app_as_app(app_api_client, app, permission_manage
assert metadata["value"] == PUBLIC_VALUE
+QUERY_PAGE_TYPE_PUBLIC_META = """
+ query pageTypeMeta($id: ID!){
+ pageType(id: $id){
+ metadata{
+ key
+ value
+ }
+ }
+ }
+"""
+
+
+def test_query_public_meta_for_page_type_as_anonymous_user(api_client, page_type):
+ # given
+ page_type.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
+ page_type.save(update_fields=["metadata"])
+ variables = {"id": graphene.Node.to_global_id("PageType", page_type.pk)}
+
+ # when
+ response = api_client.post_graphql(QUERY_PAGE_TYPE_PUBLIC_META, variables)
+ content = get_graphql_content(response)
+
+ # then
+ metadata = content["data"]["pageType"]["metadata"][0]
+ assert metadata["key"] == PUBLIC_KEY
+ assert metadata["value"] == PUBLIC_VALUE
+
+
+def test_query_public_meta_for_page_type_as_customer(user_api_client, page_type):
+ # given
+ page_type.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
+ page_type.save(update_fields=["metadata"])
+ variables = {"id": graphene.Node.to_global_id("PageType", page_type.pk)}
+
+ # when
+ response = user_api_client.post_graphql(QUERY_PAGE_TYPE_PUBLIC_META, variables)
+ content = get_graphql_content(response)
+
+ # then
+ metadata = content["data"]["pageType"]["metadata"][0]
+ assert metadata["key"] == PUBLIC_KEY
+ assert metadata["value"] == PUBLIC_VALUE
+
+
+def test_query_public_meta_for_page_type_as_staff(
+ staff_api_client, page_type, permission_manage_products
+):
+ # given
+ page_type.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
+ page_type.save(update_fields=["metadata"])
+ variables = {"id": graphene.Node.to_global_id("PageType", page_type.pk)}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_PAGE_TYPE_PUBLIC_META,
+ variables,
+ [permission_manage_products],
+ check_no_permissions=False,
+ )
+ content = get_graphql_content(response)
+
+ # then
+ metadata = content["data"]["pageType"]["metadata"][0]
+ assert metadata["key"] == PUBLIC_KEY
+ assert metadata["value"] == PUBLIC_VALUE
+
+
+def test_query_public_meta_for_page_type_as_app(
+ app_api_client, page_type, permission_manage_products
+):
+ # given
+ page_type.store_value_in_metadata({PUBLIC_KEY: PUBLIC_VALUE})
+ page_type.save(update_fields=["metadata"])
+ variables = {"id": graphene.Node.to_global_id("PageType", page_type.pk)}
+
+ # when
+ response = app_api_client.post_graphql(
+ QUERY_PAGE_TYPE_PUBLIC_META,
+ variables,
+ [permission_manage_products],
+ check_no_permissions=False,
+ )
+ content = get_graphql_content(response)
+
+ # then
+ metadata = content["data"]["pageType"]["metadata"][0]
+ assert metadata["key"] == PUBLIC_KEY
+ assert metadata["value"] == PUBLIC_VALUE
+
+
QUERY_SELF_PRIVATE_META = """
{
me{
@@ -2659,3 +2749,83 @@ def test_query_private_meta_for_app_as_app(app_api_client, app, permission_manag
metadata = content["data"]["app"]["privateMetadata"][0]
assert metadata["key"] == PRIVATE_KEY
assert metadata["value"] == PRIVATE_VALUE
+
+
+QUERY_PAGE_TYPE_PRIVATE_META = """
+ query pageTypeMeta($id: ID!){
+ pageType(id: $id){
+ privateMetadata{
+ key
+ value
+ }
+ }
+ }
+"""
+
+
+def test_query_private_meta_for_page_type_as_anonymous_user(api_client, page_type):
+ # given
+ variables = {"id": graphene.Node.to_global_id("PageType", page_type.pk)}
+
+ # when
+ response = api_client.post_graphql(QUERY_PAGE_TYPE_PRIVATE_META, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_query_private_meta_for_page_type_as_customer(user_api_client, page_type):
+ # given
+ variables = {"id": graphene.Node.to_global_id("PageType", page_type.pk)}
+
+ # when
+ response = user_api_client.post_graphql(QUERY_PAGE_TYPE_PRIVATE_META, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_query_private_meta_for_page_type_as_staff(
+ staff_api_client, page_type, permission_manage_page_types_and_attributes
+):
+ # given
+ page_type.store_value_in_private_metadata({PRIVATE_KEY: PRIVATE_VALUE})
+ page_type.save(update_fields=["private_metadata"])
+ variables = {"id": graphene.Node.to_global_id("PageType", page_type.pk)}
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_PAGE_TYPE_PRIVATE_META,
+ variables,
+ [permission_manage_page_types_and_attributes],
+ check_no_permissions=False,
+ )
+ content = get_graphql_content(response)
+
+ # then
+ metadata = content["data"]["pageType"]["privateMetadata"][0]
+ assert metadata["key"] == PRIVATE_KEY
+ assert metadata["value"] == PRIVATE_VALUE
+
+
+def test_query_private_meta_for_page_type_as_app(
+ app_api_client, page_type, permission_manage_page_types_and_attributes
+):
+ # given
+ page_type.store_value_in_private_metadata({PRIVATE_KEY: PRIVATE_VALUE})
+ page_type.save(update_fields=["private_metadata"])
+ variables = {"id": graphene.Node.to_global_id("PageType", page_type.pk)}
+
+ # when
+ response = app_api_client.post_graphql(
+ QUERY_PAGE_TYPE_PRIVATE_META,
+ variables,
+ [permission_manage_page_types_and_attributes],
+ check_no_permissions=False,
+ )
+ content = get_graphql_content(response)
+
+ # then
+ metadata = content["data"]["pageType"]["privateMetadata"][0]
+ assert metadata["key"] == PRIVATE_KEY
+ assert metadata["value"] == PRIVATE_VALUE
diff --git a/saleor/graphql/page/bulk_mutations.py b/saleor/graphql/page/bulk_mutations.py
index 9024d54600..7604a87bd0 100644
--- a/saleor/graphql/page/bulk_mutations.py
+++ b/saleor/graphql/page/bulk_mutations.py
@@ -1,6 +1,6 @@
import graphene
-from ...core.permissions import PagePermissions
+from ...core.permissions import PagePermissions, PageTypePermissions
from ...page import models
from ..core.mutations import BaseBulkMutation, ModelBulkDeleteMutation
from ..core.types.common import PageError
@@ -39,3 +39,19 @@ class PageBulkPublish(BaseBulkMutation):
@classmethod
def bulk_action(cls, queryset, is_published):
queryset.update(is_published=is_published)
+
+
+class PageTypeBulkDelete(ModelBulkDeleteMutation):
+ class Arguments:
+ ids = graphene.List(
+ graphene.NonNull(graphene.ID),
+ description="List of page type IDs to delete",
+ required=True,
+ )
+
+ class Meta:
+ description = "Delete page types."
+ model = models.PageType
+ permissions = (PageTypePermissions.MANAGE_PAGE_TYPES_AND_ATTRIBUTES,)
+ error_type_class = PageError
+ error_type_field = "page_errors"
diff --git a/saleor/graphql/page/dataloaders.py b/saleor/graphql/page/dataloaders.py
index 78827e177f..071261cdff 100644
--- a/saleor/graphql/page/dataloaders.py
+++ b/saleor/graphql/page/dataloaders.py
@@ -1,10 +1,225 @@
-from ...page.models import Page
+from collections import defaultdict
+
+from promise import Promise
+
+from ...attribute.models import AssignedPageAttribute, AttributePage, AttributeValue
+from ...core.permissions import PagePermissions
+from ...page.models import Page, PageType
+from ..attribute.dataloaders import AttributesByAttributeId, AttributeValueByIdLoader
from ..core.dataloaders import DataLoader
+from ..utils import get_user_or_app_from_context
class PageByIdLoader(DataLoader):
context_key = "page_by_id"
def batch_load(self, keys):
- pages = Page.objects.visible_to_user(self.user).in_bulk(keys)
+ pages = Page.objects.in_bulk(keys)
return [pages.get(page_id) for page_id in keys]
+
+
+class PageTypeByIdLoader(DataLoader):
+ context_key = "page_type_by_id"
+
+ def batch_load(self, keys):
+ page_types = PageType.objects.in_bulk(keys)
+ return [page_types.get(page_type_id) for page_type_id in keys]
+
+
+class PagesByPageTypeIdLoader(DataLoader):
+ """Loads pages by pages type ID."""
+
+ context_key = "pages_by_pagetype"
+
+ def batch_load(self, keys):
+ pages = Page.objects.filter(page_type_id__in=keys)
+
+ pagetype_to_pages = defaultdict(list)
+ for page in pages:
+ pagetype_to_pages[page.page_type_id].append(page)
+
+ return [pagetype_to_pages[key] for key in keys]
+
+
+class PageAttributesByPageTypeIdLoader(DataLoader):
+ """Loads page attributes by page type ID."""
+
+ context_key = "page_attributes_by_pagetype"
+
+ def batch_load(self, keys):
+ requestor = get_user_or_app_from_context(self.context)
+ if requestor.is_active and requestor.has_perm(PagePermissions.MANAGE_PAGES):
+ qs = AttributePage.objects.all()
+ else:
+ qs = AttributePage.objects.filter(attribute__visible_in_storefront=True)
+
+ page_type_attribute_pairs = qs.filter(page_type_id__in=keys).values_list(
+ "page_type_id", "attribute_id"
+ )
+
+ page_type_to_attributes_map = defaultdict(list)
+ for page_type_id, attr_id in page_type_attribute_pairs:
+ page_type_to_attributes_map[page_type_id].append(attr_id)
+
+ def map_attributes(attributes):
+ attributes_map = {attr.id: attr for attr in attributes}
+ return [
+ [
+ attributes_map[attr_id]
+ for attr_id in page_type_to_attributes_map[page_type_id]
+ ]
+ for page_type_id in keys
+ ]
+
+ return (
+ AttributesByAttributeId(self.context)
+ .load_many(set(attr_id for _, attr_id in page_type_attribute_pairs))
+ .then(map_attributes)
+ )
+
+
+class AttributePagesByPageTypeIdLoader(DataLoader):
+ """Loads AttributePage objects by page type ID."""
+
+ context_key = "attributepages_by_pagetype"
+
+ def batch_load(self, keys):
+ requestor = get_user_or_app_from_context(self.context)
+ if requestor.is_active and requestor.has_perm(PagePermissions.MANAGE_PAGES):
+ qs = AttributePage.objects.all()
+ else:
+ qs = AttributePage.objects.filter(attribute__visible_in_storefront=True)
+ attribute_pages = qs.filter(page_type_id__in=keys)
+ pagetype_to_attributepages = defaultdict(list)
+ for attribute_page in attribute_pages:
+ pagetype_to_attributepages[attribute_page.page_type_id].append(
+ attribute_page
+ )
+ return [pagetype_to_attributepages[key] for key in keys]
+
+
+class AssignedPageAttributesByPageIdLoader(DataLoader):
+ context_key = "assignedpageattributes_by_page"
+
+ def batch_load(self, keys):
+ requestor = get_user_or_app_from_context(self.context)
+ if requestor.is_active and requestor.has_perm(PagePermissions.MANAGE_PAGES):
+ qs = AssignedPageAttribute.objects.all()
+ else:
+ qs = AssignedPageAttribute.objects.filter(
+ assignment__attribute__visible_in_storefront=True
+ )
+ assigned_page_attributes = qs.filter(page_id__in=keys)
+ page_to_assignedattributes = defaultdict(list)
+ for assigned_page_attribute in assigned_page_attributes:
+ page_to_assignedattributes[assigned_page_attribute.page_id].append(
+ assigned_page_attribute
+ )
+ return [page_to_assignedattributes[page_id] for page_id in keys]
+
+
+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
+ )
+ value_ids = [a.attributevalue_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)
+ )
+ return [
+ sorted(assigned_page_map[key], key=lambda v: (v.sort_order, v.id))
+ for key in keys
+ ]
+
+ return (
+ AttributeValueByIdLoader(self.context)
+ .load_many(value_ids)
+ .then(map_assignment_to_values)
+ )
+
+
+class SelectedAttributesByPageIdLoader(DataLoader):
+ context_key = "selectedattributes_by_page"
+
+ def batch_load(self, keys):
+ def with_pages_and_assigned_attributes(result):
+ pages, page_attributes = result
+ assigned_page_attributes_ids = list(
+ {attr.id for attrs in page_attributes for attr in attrs}
+ )
+ page_type_ids = [page.page_type_id for page in pages]
+ page_attributes = dict(zip(keys, page_attributes))
+
+ def with_attribute_pages_and_values(result):
+ attribute_pages, attribute_values = result
+ attribute_ids = list(
+ {ap.attribute_id for aps in attribute_pages for ap in aps}
+ )
+ attribute_pages = dict(zip(page_type_ids, attribute_pages))
+ attribute_values = dict(
+ zip(assigned_page_attributes_ids, attribute_values)
+ )
+
+ def with_attributes(attributes):
+ id_to_attribute = dict(zip(attribute_ids, attributes))
+ selected_attributes_map = defaultdict(list)
+ for key, page in zip(keys, pages):
+ assigned_pagetype_attributes = attribute_pages[
+ page.page_type_id
+ ]
+ assigned_page_attributes = page_attributes[key]
+ for assigned_pagetype_attribute in assigned_pagetype_attributes:
+ page_assignment = next(
+ (
+ apa
+ for apa in assigned_page_attributes
+ if apa.assignment_id
+ == assigned_pagetype_attribute.id
+ ),
+ None,
+ )
+ attribute = id_to_attribute[
+ assigned_pagetype_attribute.attribute_id
+ ]
+ if page_assignment:
+ values = attribute_values[page_assignment.id]
+ else:
+ values = []
+ selected_attributes_map[key].append(
+ {"values": values, "attribute": attribute}
+ )
+ return [selected_attributes_map[key] for key in keys]
+
+ return (
+ AttributesByAttributeId(self.context)
+ .load_many(attribute_ids)
+ .then(with_attributes)
+ )
+
+ attribute_pages = AttributePagesByPageTypeIdLoader(self.context).load_many(
+ page_type_ids
+ )
+ attribute_values = AttributeValuesByAssignedPageAttributeIdLoader(
+ self.context
+ ).load_many(assigned_page_attributes_ids)
+ return Promise.all([attribute_pages, attribute_values]).then(
+ with_attribute_pages_and_values
+ )
+
+ pages = PageByIdLoader(self.context).load_many(keys)
+ assigned_attributes = AssignedPageAttributesByPageIdLoader(
+ self.context
+ ).load_many(keys)
+
+ return Promise.all([pages, assigned_attributes]).then(
+ with_pages_and_assigned_attributes
+ )
diff --git a/saleor/graphql/page/filters.py b/saleor/graphql/page/filters.py
index 023f637e80..daa1354c41 100644
--- a/saleor/graphql/page/filters.py
+++ b/saleor/graphql/page/filters.py
@@ -11,6 +11,13 @@ def filter_page_search(qs, _, value):
return qs
+def filter_page_type_search(qs, _, value):
+ fields = ["name", "slug"]
+ if value:
+ qs = filter_by_query_param(qs, value, fields)
+ return qs
+
+
class PageFilter(django_filters.FilterSet):
search = django_filters.CharFilter(method=filter_page_search)
@@ -22,3 +29,12 @@ class PageFilter(django_filters.FilterSet):
class PageFilterInput(FilterInputObjectType):
class Meta:
filterset_class = PageFilter
+
+
+class PageTypeFilter(django_filters.FilterSet):
+ search = django_filters.CharFilter(method=filter_page_type_search)
+
+
+class PageTypeFilterInput(FilterInputObjectType):
+ class Meta:
+ filterset_class = PageTypeFilter
diff --git a/saleor/graphql/page/mutations.py b/saleor/graphql/page/mutations.py
deleted file mode 100644
index 0bf7dd8769..0000000000
--- a/saleor/graphql/page/mutations.py
+++ /dev/null
@@ -1,85 +0,0 @@
-from datetime import date
-
-import graphene
-from django.core.exceptions import ValidationError
-
-from ...core.permissions import PagePermissions
-from ...page import models
-from ...page.error_codes import PageErrorCode
-from ..core.mutations import ModelDeleteMutation, ModelMutation
-from ..core.types.common import PageError, SeoInput
-from ..core.utils import clean_seo_fields, validate_slug_and_generate_if_needed
-
-
-class PageInput(graphene.InputObjectType):
- slug = graphene.String(description="Page internal name.")
- title = graphene.String(description="Page title.")
- content = graphene.String(
- description=("Page content. May consist of ordinary text, HTML and images.")
- )
- content_json = graphene.JSONString(description="Page content in JSON format.")
- is_published = graphene.Boolean(
- description="Determines if page is visible in the storefront."
- )
- publication_date = graphene.String(
- description="Publication date. ISO 8601 standard."
- )
- seo = SeoInput(description="Search engine optimization fields.")
-
-
-class PageCreate(ModelMutation):
- class Arguments:
- input = PageInput(
- required=True, description="Fields required to create a page."
- )
-
- class Meta:
- description = "Creates a new page."
- model = models.Page
- permissions = (PagePermissions.MANAGE_PAGES,)
- error_type_class = PageError
- error_type_field = "page_errors"
-
- @classmethod
- def clean_input(cls, info, instance, data):
- cleaned_input = super().clean_input(info, instance, data)
- try:
- cleaned_input = validate_slug_and_generate_if_needed(
- instance, "title", cleaned_input
- )
- except ValidationError as error:
- error.code = PageErrorCode.REQUIRED
- raise ValidationError({"slug": error})
- is_published = cleaned_input.get("is_published")
- publication_date = cleaned_input.get("publication_date")
- if is_published and not publication_date:
- cleaned_input["publication_date"] = date.today()
- clean_seo_fields(cleaned_input)
- return cleaned_input
-
-
-class PageUpdate(PageCreate):
- class Arguments:
- id = graphene.ID(required=True, description="ID of a page to update.")
- input = PageInput(
- required=True, description="Fields required to update a page."
- )
-
- class Meta:
- description = "Updates an existing page."
- model = models.Page
- permissions = (PagePermissions.MANAGE_PAGES,)
- error_type_class = PageError
- error_type_field = "page_errors"
-
-
-class PageDelete(ModelDeleteMutation):
- class Arguments:
- id = graphene.ID(required=True, description="ID of a page to delete.")
-
- class Meta:
- description = "Deletes a page."
- model = models.Page
- permissions = (PagePermissions.MANAGE_PAGES,)
- error_type_class = PageError
- error_type_field = "page_errors"
diff --git a/saleor/graphql/page/mutations/__init__.py b/saleor/graphql/page/mutations/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/graphql/page/mutations/attributes.py b/saleor/graphql/page/mutations/attributes.py
new file mode 100644
index 0000000000..12bfb82a8f
--- /dev/null
+++ b/saleor/graphql/page/mutations/attributes.py
@@ -0,0 +1,199 @@
+from collections import defaultdict
+from typing import Dict, List
+
+import graphene
+from django.core.exceptions import ObjectDoesNotExist, ValidationError
+from django.db import transaction
+
+from ....attribute import AttributeType, models
+from ....core.permissions import PageTypePermissions
+from ....page import models as page_models
+from ....page.error_codes import PageErrorCode
+from ...attribute.mutations import BaseReorderAttributesMutation
+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 ...utils import resolve_global_ids_to_primary_keys
+
+
+class PageAttributeAssign(BaseMutation):
+ page_type = graphene.Field(PageType, description="The updated page type.")
+
+ class Arguments:
+ page_type_id = graphene.ID(
+ required=True,
+ description="ID of the page type to assign the attributes into.",
+ )
+ attribute_ids = graphene.List(
+ graphene.NonNull(graphene.ID),
+ required=True,
+ description="The IDs of the attributes to assign.",
+ )
+
+ class Meta:
+ description = "Assign attributes to a given page type."
+ error_type_class = PageError
+ error_type_field = "page_errors"
+ permissions = (PageTypePermissions.MANAGE_PAGE_TYPES_AND_ATTRIBUTES,)
+
+ @classmethod
+ def clean_attributes(
+ cls,
+ errors: Dict["str", List[ValidationError]],
+ page_type: "page_models.PageType",
+ attr_pks: List[int],
+ ):
+ """Ensure the attributes are page attributes and are not already assigned."""
+
+ # check if any attribute is not a page type
+ invalid_attributes = models.Attribute.objects.filter(pk__in=attr_pks).exclude(
+ type=AttributeType.PAGE_TYPE
+ )
+
+ if invalid_attributes:
+ invalid_attributes_ids = [
+ graphene.Node.to_global_id("Attribute", attr.pk)
+ for attr in invalid_attributes
+ ]
+ error = ValidationError(
+ "Only page attributes can be assigned.",
+ code=PageErrorCode.INVALID.value,
+ params={"attributes": invalid_attributes_ids},
+ )
+ errors["attribute_ids"].append(error)
+
+ # check if any attribute is already assigned to this page type
+ assigned_attrs = models.Attribute.objects.get_assigned_page_type_attributes(
+ page_type.pk
+ ).filter(pk__in=attr_pks)
+
+ if assigned_attrs:
+ assigned_attributes_ids = [
+ graphene.Node.to_global_id("Attribute", attr.pk)
+ for attr in assigned_attrs
+ ]
+ error = ValidationError(
+ "Some of the attributes have been already assigned to this page type.",
+ code=PageErrorCode.ATTRIBUTE_ALREADY_ASSIGNED.value,
+ params={"attributes": assigned_attributes_ids},
+ )
+ errors["attribute_ids"].append(error)
+
+ @classmethod
+ def perform_mutation(cls, _root, info, **data):
+ errors = defaultdict(list)
+ page_type_id: str = data["page_type_id"]
+ attribute_ids = data["attribute_ids"]
+
+ # retrieve the requested page type
+ page_type = cls.get_node_or_error(info, page_type_id, only_type=PageType)
+
+ # resolve all passed attributes IDs to attributes pks
+ _, attr_pks = resolve_global_ids_to_primary_keys(attribute_ids, Attribute)
+
+ # ensure the attributes are assignable
+ cls.clean_attributes(errors, page_type, attr_pks)
+
+ if errors:
+ raise ValidationError(errors)
+
+ page_type.page_attributes.add(*attr_pks)
+
+ return cls(page_type=page_type)
+
+
+class PageAttributeUnassign(BaseMutation):
+ page_type = graphene.Field(PageType, description="The updated page type.")
+
+ class Arguments:
+ page_type_id = graphene.ID(
+ required=True,
+ description=(
+ "ID of the page type from which the attributes should be unassign."
+ ),
+ )
+ attribute_ids = graphene.List(
+ graphene.NonNull(graphene.ID),
+ required=True,
+ description="The IDs of the attributes to unassign.",
+ )
+
+ class Meta:
+ description = "Unassign attributes from a given page type."
+ permissions = (PageTypePermissions.MANAGE_PAGE_TYPES_AND_ATTRIBUTES,)
+ error_type_class = PageError
+ error_type_field = "page_errors"
+
+ @classmethod
+ def perform_mutation(cls, _root, info, **data):
+ page_type_id = data["page_type_id"]
+ attribute_ids = data["attribute_ids"]
+
+ # retrieve the requested page type
+ page_type = cls.get_node_or_error(info, page_type_id, only_type=PageType)
+
+ # resolve all passed attributes IDs to attributes pks
+ _, attr_pks = resolve_global_ids_to_primary_keys(attribute_ids, Attribute)
+
+ page_type.page_attributes.remove(*attr_pks)
+
+ return cls(page_type=page_type)
+
+
+class PageTypeReorderAttributes(BaseReorderAttributesMutation):
+ page_type = graphene.Field(
+ PageType, description="Page type from which attributes are reordered."
+ )
+
+ class Arguments:
+ page_type_id = graphene.Argument(
+ graphene.ID, required=True, description="ID of a page type."
+ )
+ moves = graphene.List(
+ graphene.NonNull(ReorderInput),
+ required=True,
+ description="The list of attribute reordering operations.",
+ )
+
+ class Meta:
+ description = "Reorder the attributes of a page type."
+ permissions = (PageTypePermissions.MANAGE_PAGE_TYPES_AND_ATTRIBUTES,)
+ error_type_class = PageError
+ error_type_field = "page_errors"
+
+ @classmethod
+ def perform_mutation(cls, _root, info, **data):
+ page_type_id = data["page_type_id"]
+ pk = from_global_id_strict_type(page_type_id, only_type=PageType, field="pk")
+
+ try:
+ page_type = page_models.PageType.objects.prefetch_related(
+ "attributepage"
+ ).get(pk=pk)
+ except ObjectDoesNotExist:
+ raise ValidationError(
+ {
+ "page_type_id": ValidationError(
+ f"Couldn't resolve to a page type: {page_type_id}",
+ code=PageErrorCode.NOT_FOUND.value,
+ )
+ }
+ )
+
+ page_attributes = page_type.attributepage.all()
+ moves = data["moves"]
+
+ try:
+ operations = cls.prepare_operations(moves, page_attributes)
+ except ValidationError as error:
+ error.code = PageErrorCode.NOT_FOUND.value
+ raise ValidationError({"moves": error})
+
+ with transaction.atomic():
+ perform_reordering(page_attributes, operations)
+
+ return PageTypeReorderAttributes(page_type=page_type)
diff --git a/saleor/graphql/page/mutations/pages.py b/saleor/graphql/page/mutations/pages.py
new file mode 100644
index 0000000000..0383ae2a2b
--- /dev/null
+++ b/saleor/graphql/page/mutations/pages.py
@@ -0,0 +1,307 @@
+from collections import defaultdict
+from datetime import date
+from typing import TYPE_CHECKING, Dict, List
+
+import graphene
+from django.core.exceptions import ValidationError
+from django.db import transaction
+
+from ....attribute import AttributeType
+from ....core.permissions import PagePermissions, PageTypePermissions
+from ....page import models
+from ....page.error_codes import PageErrorCode
+from ...core.mutations import ModelDeleteMutation, ModelMutation
+from ...core.types.common import PageError, SeoInput
+from ...core.utils import (
+ clean_seo_fields,
+ get_duplicates_ids,
+ validate_slug_and_generate_if_needed,
+)
+from ...product.mutations.products import AttributeAssignmentMixin, AttributeValueInput
+
+if TYPE_CHECKING:
+ from ....attribute.models import Attribute
+
+
+class PageInput(graphene.InputObjectType):
+ slug = graphene.String(description="Page internal name.")
+ title = graphene.String(description="Page title.")
+ content = graphene.String(
+ description=("Page content. May consist of ordinary text, HTML and images.")
+ )
+ content_json = graphene.JSONString(description="Page content in JSON format.")
+ attributes = graphene.List(
+ graphene.NonNull(AttributeValueInput), description="List of attributes."
+ )
+ is_published = graphene.Boolean(
+ description="Determines if page is visible in the storefront."
+ )
+ publication_date = graphene.String(
+ description="Publication date. ISO 8601 standard."
+ )
+ seo = SeoInput(description="Search engine optimization fields.")
+
+
+class PageCreateInput(PageInput):
+ page_type = graphene.ID(
+ description="ID of the page type that page belongs to.", required=True
+ )
+
+
+class PageCreate(ModelMutation):
+ class Arguments:
+ input = PageCreateInput(
+ required=True, description="Fields required to create a page."
+ )
+
+ class Meta:
+ description = "Creates a new page."
+ model = models.Page
+ permissions = (PagePermissions.MANAGE_PAGES,)
+ error_type_class = PageError
+ error_type_field = "page_errors"
+
+ @classmethod
+ def clean_attributes(cls, attributes: dict, page_type: models.PageType):
+ attributes_qs = page_type.page_attributes
+ attributes = AttributeAssignmentMixin.clean_input(
+ attributes, attributes_qs, is_page_attributes=True
+ )
+ return attributes
+
+ @classmethod
+ def clean_input(cls, info, instance, data):
+ cleaned_input = super().clean_input(info, instance, data)
+ try:
+ cleaned_input = validate_slug_and_generate_if_needed(
+ instance, "title", cleaned_input
+ )
+ except ValidationError as error:
+ error.code = PageErrorCode.REQUIRED
+ raise ValidationError({"slug": error})
+
+ is_published = cleaned_input.get("is_published")
+ publication_date = cleaned_input.get("publication_date")
+ if is_published and not publication_date:
+ cleaned_input["publication_date"] = date.today()
+
+ attributes = cleaned_input.get("attributes")
+ page_type = (
+ instance.page_type if instance.pk else cleaned_input.get("page_type")
+ )
+ if attributes and page_type:
+ try:
+ cleaned_input["attributes"] = cls.clean_attributes(
+ attributes, page_type
+ )
+ except ValidationError as exc:
+ raise ValidationError({"attributes": exc})
+
+ clean_seo_fields(cleaned_input)
+
+ return cleaned_input
+
+ @classmethod
+ @transaction.atomic
+ def _save_m2m(cls, info, instance, cleaned_data):
+ super()._save_m2m(info, instance, cleaned_data)
+
+ attributes = cleaned_data.get("attributes")
+ if attributes:
+ AttributeAssignmentMixin.save(instance, attributes)
+
+
+class PageUpdate(PageCreate):
+ class Arguments:
+ id = graphene.ID(required=True, description="ID of a page to update.")
+ input = PageInput(
+ required=True, description="Fields required to update a page."
+ )
+
+ class Meta:
+ description = "Updates an existing page."
+ model = models.Page
+ permissions = (PagePermissions.MANAGE_PAGES,)
+ error_type_class = PageError
+ error_type_field = "page_errors"
+
+
+class PageDelete(ModelDeleteMutation):
+ class Arguments:
+ id = graphene.ID(required=True, description="ID of a page to delete.")
+
+ class Meta:
+ description = "Deletes a page."
+ model = models.Page
+ permissions = (PagePermissions.MANAGE_PAGES,)
+ error_type_class = PageError
+ error_type_field = "page_errors"
+
+
+class PageTypeCreateInput(graphene.InputObjectType):
+ name = graphene.String(description="Name of the page type.")
+ slug = graphene.String(description="Page type slug.")
+ add_attributes = graphene.List(
+ graphene.NonNull(graphene.ID),
+ description="List of attribute IDs to be assigned to the page type.",
+ )
+
+
+class PageTypeUpdateInput(PageTypeCreateInput):
+ remove_attributes = graphene.List(
+ graphene.NonNull(graphene.ID),
+ description="List of attribute IDs to be assigned to the page type.",
+ )
+
+
+class PageTypeMixin:
+ @classmethod
+ def validate_attributes(
+ cls,
+ errors: Dict[str, List[ValidationError]],
+ attributes: List["Attribute"],
+ field: str,
+ ):
+ """All attributes must be page type attribute.
+
+ Raise an error if any of the attributes are not page attribute.
+ """
+ if attributes:
+ not_valid_attributes = [
+ graphene.Node.to_global_id("Attribute", attr.pk)
+ for attr in attributes
+ if attr.type != AttributeType.PAGE_TYPE
+ ]
+ if not_valid_attributes:
+ error = ValidationError(
+ "Only page type attributes allowed.",
+ code=PageErrorCode.INVALID.value,
+ params={"attributes": not_valid_attributes},
+ )
+ errors[field].append(error)
+
+
+class PageTypeCreate(PageTypeMixin, ModelMutation):
+ class Arguments:
+ input = PageTypeCreateInput(
+ description="Fields required to create page type.", required=True
+ )
+
+ class Meta:
+ description = "Create a new page type."
+ model = models.PageType
+ permissions = (PageTypePermissions.MANAGE_PAGE_TYPES_AND_ATTRIBUTES,)
+ error_type_class = PageError
+ error_type_field = "page_errors"
+
+ @classmethod
+ def clean_input(cls, info, instance, data):
+ cleaned_input = super().clean_input(info, instance, data)
+ errors = defaultdict(list)
+ try:
+ cleaned_input = validate_slug_and_generate_if_needed(
+ instance, "name", cleaned_input
+ )
+ except ValidationError as error:
+ error.code = PageErrorCode.REQUIRED.value
+ errors["slug"].append(error)
+
+ cls.validate_attributes(
+ errors, cleaned_input.get("add_attributes"), "add_attributes"
+ )
+
+ if errors:
+ raise ValidationError(errors)
+
+ return cleaned_input
+
+ @classmethod
+ def _save_m2m(cls, info, instance, cleaned_data):
+ super()._save_m2m(info, instance, cleaned_data)
+ attributes = cleaned_data.get("add_attributes")
+ if attributes is not None:
+ instance.page_attributes.add(*attributes)
+
+
+class PageTypeUpdate(PageTypeMixin, ModelMutation):
+ class Arguments:
+ id = graphene.ID(description="ID of the page type to update.")
+ input = PageTypeUpdateInput(
+ description="Fields required to update page type.", required=True
+ )
+
+ class Meta:
+ description = "Update page type."
+ model = models.PageType
+ permissions = (PageTypePermissions.MANAGE_PAGE_TYPES_AND_ATTRIBUTES,)
+ error_type_class = PageError
+ error_type_field = "page_errors"
+
+ @classmethod
+ def check_for_duplicates(cls, errors: Dict[str, List[ValidationError]], data: dict):
+ """Check if any items are on both list for adding and removing.
+
+ Raise error if some of items are duplicated.
+ """
+ add_attributes = data.get("add_attributes")
+ remove_attributes = data.get("remove_attributes")
+
+ duplicated_ids = get_duplicates_ids(add_attributes, remove_attributes)
+ if duplicated_ids:
+ error_msg = (
+ "The same object cannot be in both list"
+ "for adding and removing items."
+ )
+ error = ValidationError(
+ error_msg,
+ code=PageErrorCode.DUPLICATED_INPUT_ITEM.value,
+ params={"attributes": duplicated_ids},
+ )
+ errors["attributes"].append(error)
+
+ @classmethod
+ def clean_input(cls, info, instance, data):
+ errors = defaultdict(list)
+ cls.check_for_duplicates(errors, data)
+
+ cleaned_input = super().clean_input(info, instance, data)
+ try:
+ cleaned_input = validate_slug_and_generate_if_needed(
+ instance, "name", cleaned_input
+ )
+ except ValidationError as error:
+ error.code = PageErrorCode.REQUIRED
+ errors["slug"].append(error)
+
+ add_attributes = cleaned_input.get("add_attributes")
+ cls.validate_attributes(errors, add_attributes, "add_attributes")
+
+ remove_attributes = cleaned_input.get("remove_attributes")
+ cls.validate_attributes(errors, remove_attributes, "remove_attributes")
+
+ if errors:
+ raise ValidationError(errors)
+
+ return cleaned_input
+
+ @classmethod
+ def _save_m2m(cls, info, instance, cleaned_data):
+ super()._save_m2m(info, instance, cleaned_data)
+ remove_attributes = cleaned_data.get("remove_attributes")
+ add_attributes = cleaned_data.get("add_attributes")
+ if remove_attributes is not None:
+ instance.page_attributes.remove(*remove_attributes)
+ if add_attributes is not None:
+ instance.page_attributes.add(*add_attributes)
+
+
+class PageTypeDelete(ModelDeleteMutation):
+ class Arguments:
+ id = graphene.ID(required=True, description="ID of the page type to delete.")
+
+ class Meta:
+ description = "Delete a page type."
+ model = models.PageType
+ permissions = (PageTypePermissions.MANAGE_PAGE_TYPES_AND_ATTRIBUTES,)
+ error_type_class = PageError
+ error_type_field = "page_errors"
diff --git a/saleor/graphql/page/resolvers.py b/saleor/graphql/page/resolvers.py
index c44da7c2a8..83d7fbf5a6 100644
--- a/saleor/graphql/page/resolvers.py
+++ b/saleor/graphql/page/resolvers.py
@@ -1,6 +1,7 @@
import graphene
from ...page import models
+from .types import PageType
def resolve_page(info, global_page_id=None, slug=None):
@@ -18,3 +19,11 @@ def resolve_page(info, global_page_id=None, slug=None):
def resolve_pages(info, **_kwargs):
user = info.context.user
return models.Page.objects.visible_to_user(user)
+
+
+def resolve_page_type(info, global_page_type_id):
+ return graphene.Node.get_node_from_global_id(info, global_page_type_id, PageType)
+
+
+def resolve_page_types(info, **_kwargs):
+ return models.PageType.objects.all()
diff --git a/saleor/graphql/page/schema.py b/saleor/graphql/page/schema.py
index 679c674e8e..0a819ddead 100644
--- a/saleor/graphql/page/schema.py
+++ b/saleor/graphql/page/schema.py
@@ -2,12 +2,29 @@ import graphene
from ..core.fields import FilterInputConnectionField
from ..translations.mutations import PageTranslate
-from .bulk_mutations import PageBulkDelete, PageBulkPublish
-from .filters import PageFilterInput
-from .mutations import PageCreate, PageDelete, PageUpdate
-from .resolvers import resolve_page, resolve_pages
-from .sorters import PageSortingInput
-from .types import Page
+from .bulk_mutations import PageBulkDelete, PageBulkPublish, PageTypeBulkDelete
+from .filters import PageFilterInput, PageTypeFilterInput
+from .mutations.attributes import (
+ PageAttributeAssign,
+ PageAttributeUnassign,
+ PageTypeReorderAttributes,
+)
+from .mutations.pages import (
+ PageCreate,
+ PageDelete,
+ PageTypeCreate,
+ PageTypeDelete,
+ PageTypeUpdate,
+ PageUpdate,
+)
+from .resolvers import (
+ resolve_page,
+ resolve_page_type,
+ resolve_page_types,
+ resolve_pages,
+)
+from .sorters import PageSortingInput, PageTypeSortingInput
+from .types import Page, PageType
class PageQueries(graphene.ObjectType):
@@ -23,6 +40,19 @@ class PageQueries(graphene.ObjectType):
filter=PageFilterInput(description="Filtering options for pages."),
description="List of the shop's pages.",
)
+ page_type = graphene.Field(
+ PageType,
+ id=graphene.Argument(
+ graphene.ID, description="ID of the page type.", required=True
+ ),
+ description="Look up a page type by ID.",
+ )
+ page_types = FilterInputConnectionField(
+ PageType,
+ sort_by=PageTypeSortingInput(description="Sort page types."),
+ filter=PageTypeFilterInput(description="Filtering options for page types."),
+ description="List of the page types.",
+ )
def resolve_page(self, info, id=None, slug=None):
return resolve_page(info, id, slug)
@@ -30,11 +60,29 @@ class PageQueries(graphene.ObjectType):
def resolve_pages(self, info, **kwargs):
return resolve_pages(info, **kwargs)
+ def resolve_page_type(self, info, id):
+ return resolve_page_type(info, id)
+
+ def resolve_page_types(self, info, **kwargs):
+ return resolve_page_types(info, **kwargs)
+
class PageMutations(graphene.ObjectType):
+ # page mutations
page_create = PageCreate.Field()
page_delete = PageDelete.Field()
page_bulk_delete = PageBulkDelete.Field()
page_bulk_publish = PageBulkPublish.Field()
page_update = PageUpdate.Field()
page_translate = PageTranslate.Field()
+
+ # page type mutations
+ page_type_create = PageTypeCreate.Field()
+ page_type_update = PageTypeUpdate.Field()
+ page_type_delete = PageTypeDelete.Field()
+ page_type_bulk_delete = PageTypeBulkDelete.Field()
+
+ # attributes mutations
+ page_attribute_assign = PageAttributeAssign.Field()
+ page_attribute_unassign = PageAttributeUnassign.Field()
+ page_type_reorder_attributes = PageTypeReorderAttributes.Field()
diff --git a/saleor/graphql/page/sorters.py b/saleor/graphql/page/sorters.py
index 8bd4b5e011..bd5ad529e9 100644
--- a/saleor/graphql/page/sorters.py
+++ b/saleor/graphql/page/sorters.py
@@ -22,3 +22,21 @@ class PageSortingInput(SortInputObjectType):
class Meta:
sort_enum = PageSortField
type_name = "pages"
+
+
+class PageTypeSortField(graphene.Enum):
+ NAME = ["name", "slug"]
+ SLUG = ["slug"]
+
+ @property
+ def description(self):
+ if self.name in PageTypeSortField.__enum__._member_names_:
+ sport_name = self.name.lower().replace("_", " ")
+ return f"Sort page types by {sport_name}."
+ raise ValueError(f"Unsupported enum value: {self.value}")
+
+
+class PageTypeSortingInput(SortInputObjectType):
+ class Meta:
+ sort_enum = PageTypeSortField
+ type_name = "page types"
diff --git a/saleor/graphql/page/tests/benchmark/__init__.py b/saleor/graphql/page/tests/benchmark/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/graphql/page/tests/benchmark/test_page_type.py b/saleor/graphql/page/tests/benchmark/test_page_type.py
new file mode 100644
index 0000000000..f28ed9f12a
--- /dev/null
+++ b/saleor/graphql/page/tests/benchmark/test_page_type.py
@@ -0,0 +1,131 @@
+import graphene
+import pytest
+
+from ....tests.utils import get_graphql_content
+
+
[email protected]_queries(autouse=False)
+def test_query_page_type(
+ page_type,
+ staff_api_client,
+ author_page_attribute,
+ permission_manage_pages,
+ permission_manage_products,
+ count_queries,
+):
+ query = """
+ query PageType($id: ID!, $filters: AttributeFilterInput) {
+ pageType(id: $id) {
+ id
+ name
+ slug
+ hasPages
+ attributes {
+ slug
+ name
+ type
+ inputType
+ values {
+ name
+ slug
+ type
+ }
+ valueRequired
+ visibleInStorefront
+ filterableInStorefront
+ }
+ availableAttributes(first: 10, filter: $filters) {
+ edges {
+ node {
+ slug
+ name
+ type
+ inputType
+ values {
+ name
+ slug
+ type
+ }
+ valueRequired
+ visibleInStorefront
+ filterableInStorefront
+ }
+ }
+ }
+ }
+ }
+ """
+ variables = {"id": graphene.Node.to_global_id("PageType", page_type.pk)}
+ response = staff_api_client.post_graphql(
+ query,
+ variables,
+ permissions=[permission_manage_products, permission_manage_pages],
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["pageType"]
+ assert data
+
+
[email protected]_queries(autouse=False)
+def test_query_page_types(
+ page_type_list,
+ staff_api_client,
+ author_page_attribute,
+ permission_manage_pages,
+ permission_manage_products,
+ count_queries,
+):
+ query = """
+ query {
+ pageTypes(first: 10) {
+ edges {
+ node {
+ id
+ name
+ slug
+ hasPages
+ attributes {
+ slug
+ name
+ type
+ inputType
+ values {
+ name
+ slug
+ type
+ }
+ valueRequired
+ visibleInStorefront
+ filterableInStorefront
+ }
+ availableAttributes(first: 10) {
+ edges {
+ node {
+ slug
+ name
+ type
+ inputType
+ values {
+ name
+ slug
+ type
+ }
+ valueRequired
+ visibleInStorefront
+ filterableInStorefront
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ """
+ response = staff_api_client.post_graphql(
+ query, {}, permissions=[permission_manage_products, permission_manage_pages],
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["pageTypes"]
+ assert data
diff --git a/saleor/graphql/page/tests/test_attributes.py b/saleor/graphql/page/tests/test_attributes.py
new file mode 100644
index 0000000000..16472c6030
--- /dev/null
+++ b/saleor/graphql/page/tests/test_attributes.py
@@ -0,0 +1,404 @@
+from unittest.mock import ANY
+
+import graphene
+
+from ....page.error_codes import PageErrorCode
+from ...tests.utils import assert_no_permission, get_graphql_content
+
+PAGE_ASSIGN_ATTR_QUERY = """
+ mutation assign($pageTypeId: ID!, $attributeIds: [ID!]!) {
+ pageAttributeAssign(pageTypeId: $pageTypeId, attributeIds: $attributeIds) {
+ pageErrors {
+ field
+ code
+ message
+ attributes
+ }
+ pageType {
+ id
+ attributes {
+ id
+ }
+ }
+ }
+ }
+"""
+
+
+def test_assign_attributes_to_page_type_by_staff(
+ staff_api_client,
+ permission_manage_page_types_and_attributes,
+ page_type,
+ author_page_attribute,
+):
+ # given
+ staff_user = staff_api_client.user
+ staff_user.user_permissions.add(permission_manage_page_types_and_attributes)
+
+ page_type_attr_count = page_type.page_attributes.count()
+
+ author_page_attr_id = graphene.Node.to_global_id(
+ "Attribute", author_page_attribute.pk
+ )
+
+ variables = {
+ "pageTypeId": graphene.Node.to_global_id("PageType", page_type.pk),
+ "attributeIds": [author_page_attr_id],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(PAGE_ASSIGN_ATTR_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["pageAttributeAssign"]
+ errors = data["pageErrors"]
+
+ assert not errors
+ assert len(data["pageType"]["attributes"]) == page_type_attr_count + 1
+ assert author_page_attr_id in {
+ attr["id"] for attr in data["pageType"]["attributes"]
+ }
+
+
+def test_assign_attributes_to_page_type_by_app(
+ app_api_client,
+ permission_manage_page_types_and_attributes,
+ page_type,
+ author_page_attribute,
+):
+ # given
+ app = app_api_client.app
+ app.permissions.add(permission_manage_page_types_and_attributes)
+
+ page_type_attr_count = page_type.page_attributes.count()
+
+ author_page_attr_id = graphene.Node.to_global_id(
+ "Attribute", author_page_attribute.pk
+ )
+
+ variables = {
+ "pageTypeId": graphene.Node.to_global_id("PageType", page_type.pk),
+ "attributeIds": [author_page_attr_id],
+ }
+
+ # when
+ response = app_api_client.post_graphql(PAGE_ASSIGN_ATTR_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["pageAttributeAssign"]
+ errors = data["pageErrors"]
+
+ assert not errors
+ assert len(data["pageType"]["attributes"]) == page_type_attr_count + 1
+ assert author_page_attr_id in {
+ attr["id"] for attr in data["pageType"]["attributes"]
+ }
+
+
+def test_assign_attributes_to_page_type_by_staff_no_perm(
+ staff_api_client,
+ permission_manage_page_types_and_attributes,
+ page_type,
+ author_page_attribute,
+):
+ # given
+ author_page_attr_id = graphene.Node.to_global_id(
+ "Attribute", author_page_attribute.pk
+ )
+
+ variables = {
+ "pageTypeId": graphene.Node.to_global_id("PageType", page_type.pk),
+ "attributeIds": [author_page_attr_id],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(PAGE_ASSIGN_ATTR_QUERY, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_assign_attributes_to_page_type_by_app_no_perm(
+ app_api_client,
+ permission_manage_page_types_and_attributes,
+ page_type,
+ author_page_attribute,
+):
+ # given
+ author_page_attr_id = graphene.Node.to_global_id(
+ "Attribute", author_page_attribute.pk
+ )
+
+ variables = {
+ "pageTypeId": graphene.Node.to_global_id("PageType", page_type.pk),
+ "attributeIds": [author_page_attr_id],
+ }
+
+ # when
+ response = app_api_client.post_graphql(PAGE_ASSIGN_ATTR_QUERY, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_assign_attributes_to_page_type_not_page_attribute(
+ staff_api_client,
+ permission_manage_page_types_and_attributes,
+ page_type,
+ author_page_attribute,
+ color_attribute,
+):
+ # given
+ staff_user = staff_api_client.user
+ staff_user.user_permissions.add(permission_manage_page_types_and_attributes)
+
+ page_type_attr_count = page_type.page_attributes.count()
+
+ author_page_attr_id = graphene.Node.to_global_id(
+ "Attribute", author_page_attribute.pk
+ )
+ color_attribute_id = graphene.Node.to_global_id("Attribute", color_attribute.pk)
+
+ variables = {
+ "pageTypeId": graphene.Node.to_global_id("PageType", page_type.pk),
+ "attributeIds": [author_page_attr_id, color_attribute_id],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(PAGE_ASSIGN_ATTR_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["pageAttributeAssign"]
+ errors = data["pageErrors"]
+
+ assert not data["pageType"]
+ page_type.refresh_from_db()
+ assert page_type.page_attributes.count() == page_type_attr_count
+ assert len(errors) == 1
+ assert errors[0]["field"] == "attributeIds"
+ assert errors[0]["code"] == PageErrorCode.INVALID.name
+ assert len(errors[0]["attributes"]) == 1
+ assert errors[0]["attributes"] == [color_attribute_id]
+
+
+def test_assign_attributes_to_page_type_attribute_already_assigned(
+ staff_api_client,
+ permission_manage_page_types_and_attributes,
+ page_type,
+ author_page_attribute,
+):
+ # given
+ staff_user = staff_api_client.user
+ staff_user.user_permissions.add(permission_manage_page_types_and_attributes)
+
+ page_type_attr_count = page_type.page_attributes.count()
+
+ assigned_attr = page_type.page_attributes.first()
+ assigned_attr_id = graphene.Node.to_global_id("Attribute", assigned_attr.pk)
+ author_page_attr_id = graphene.Node.to_global_id(
+ "Attribute", author_page_attribute.pk
+ )
+
+ variables = {
+ "pageTypeId": graphene.Node.to_global_id("PageType", page_type.pk),
+ "attributeIds": [author_page_attr_id, assigned_attr_id],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(PAGE_ASSIGN_ATTR_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["pageAttributeAssign"]
+ errors = data["pageErrors"]
+
+ assert not data["pageType"]
+ page_type.refresh_from_db()
+ assert page_type.page_attributes.count() == page_type_attr_count
+ assert len(errors) == 1
+ assert errors[0]["field"] == "attributeIds"
+ assert errors[0]["code"] == PageErrorCode.ATTRIBUTE_ALREADY_ASSIGNED.name
+ assert len(errors[0]["attributes"]) == 1
+ assert errors[0]["attributes"] == [assigned_attr_id]
+
+
+def test_assign_attributes_to_page_type_multiple_error_returned(
+ staff_api_client,
+ permission_manage_page_types_and_attributes,
+ page_type,
+ author_page_attribute,
+ color_attribute,
+):
+ """Ensure that when multiple errors ocurred all will br returned. """
+ # given
+ staff_user = staff_api_client.user
+ staff_user.user_permissions.add(permission_manage_page_types_and_attributes)
+
+ page_type_attr_count = page_type.page_attributes.count()
+
+ assigned_attr = page_type.page_attributes.first()
+ assigned_attr_id = graphene.Node.to_global_id("Attribute", assigned_attr.pk)
+ author_page_attr_id = graphene.Node.to_global_id(
+ "Attribute", author_page_attribute.pk
+ )
+ color_attribute_id = graphene.Node.to_global_id("Attribute", color_attribute.pk)
+
+ variables = {
+ "pageTypeId": graphene.Node.to_global_id("PageType", page_type.pk),
+ "attributeIds": [author_page_attr_id, assigned_attr_id, color_attribute_id],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(PAGE_ASSIGN_ATTR_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["pageAttributeAssign"]
+ errors = data["pageErrors"]
+
+ assert not data["pageType"]
+ page_type.refresh_from_db()
+ assert page_type.page_attributes.count() == page_type_attr_count
+ assert len(errors) == 2
+ expected_errors = [
+ {
+ "field": "attributeIds",
+ "code": PageErrorCode.ATTRIBUTE_ALREADY_ASSIGNED.name,
+ "attributes": [assigned_attr_id],
+ "message": ANY,
+ },
+ {
+ "field": "attributeIds",
+ "code": PageErrorCode.INVALID.name,
+ "attributes": [color_attribute_id],
+ "message": ANY,
+ },
+ ]
+ assert len(errors) == len(expected_errors)
+ for error in errors:
+ assert error in expected_errors
+
+
+PAGE_UNASSIGN_ATTR_QUERY = """
+ mutation PageAttributeUnassign(
+ $pageTypeId: ID!, $attributeIds: [ID!]!
+ ) {
+ pageAttributeUnassign(
+ pageTypeId: $pageTypeId, attributeIds: $attributeIds
+ ) {
+ pageType {
+ id
+ attributes {
+ id
+ }
+ }
+ pageErrors {
+ field
+ code
+ message
+ attributes
+ }
+ }
+ }
+"""
+
+
+def test_unassign_attributes_from_page_type_by_staff(
+ staff_api_client, page_type, permission_manage_page_types_and_attributes
+):
+ # given
+ staff_user = staff_api_client.user
+ staff_user.user_permissions.add(permission_manage_page_types_and_attributes)
+
+ attr_count = page_type.page_attributes.count()
+ attr_to_unassign = page_type.page_attributes.first()
+ attr_to_unassign_id = graphene.Node.to_global_id("Attribute", attr_to_unassign.pk)
+
+ variables = {
+ "pageTypeId": graphene.Node.to_global_id("PageType", page_type.pk),
+ "attributeIds": [attr_to_unassign_id],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(PAGE_UNASSIGN_ATTR_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["pageAttributeUnassign"]
+ errors = data["pageErrors"]
+
+ assert not errors
+ assert len(data["pageType"]["attributes"]) == attr_count - 1
+ assert attr_to_unassign_id not in {
+ attr["id"] for attr in data["pageType"]["attributes"]
+ }
+
+
+def test_unassign_attributes_from_page_type_by_staff_no_perm(
+ staff_api_client, page_type
+):
+ # given
+ attr_to_unassign = page_type.page_attributes.first()
+ attr_to_unassign_id = graphene.Node.to_global_id("Attribute", attr_to_unassign.pk)
+
+ variables = {
+ "pageTypeId": graphene.Node.to_global_id("PageType", page_type.pk),
+ "attributeIds": [attr_to_unassign_id],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(PAGE_UNASSIGN_ATTR_QUERY, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_unassign_attributes_from_page_type_by_app(
+ app_api_client, page_type, permission_manage_page_types_and_attributes
+):
+ # given
+ app = app_api_client.app
+ app.permissions.add(permission_manage_page_types_and_attributes)
+
+ attr_count = page_type.page_attributes.count()
+ attr_to_unassign = page_type.page_attributes.first()
+ attr_to_unassign_id = graphene.Node.to_global_id("Attribute", attr_to_unassign.pk)
+
+ variables = {
+ "pageTypeId": graphene.Node.to_global_id("PageType", page_type.pk),
+ "attributeIds": [attr_to_unassign_id],
+ }
+
+ # when
+ response = app_api_client.post_graphql(PAGE_UNASSIGN_ATTR_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["pageAttributeUnassign"]
+ errors = data["pageErrors"]
+
+ assert not errors
+ assert len(data["pageType"]["attributes"]) == attr_count - 1
+ assert attr_to_unassign_id not in {
+ attr["id"] for attr in data["pageType"]["attributes"]
+ }
+
+
+def test_unassign_attributes_from_page_type_by_app_no_perm(app_api_client, page_type):
+ # given
+ attr_to_unassign = page_type.page_attributes.first()
+ attr_to_unassign_id = graphene.Node.to_global_id("Attribute", attr_to_unassign.pk)
+
+ variables = {
+ "pageTypeId": graphene.Node.to_global_id("PageType", page_type.pk),
+ "attributeIds": [attr_to_unassign_id],
+ }
+
+ # when
+ response = app_api_client.post_graphql(PAGE_UNASSIGN_ATTR_QUERY, variables)
+
+ # then
+ assert_no_permission(response)
diff --git a/saleor/graphql/page/tests/test_page.py b/saleor/graphql/page/tests/test_page.py
index 9853b0a347..36748c4810 100644
--- a/saleor/graphql/page/tests/test_page.py
+++ b/saleor/graphql/page/tests/test_page.py
@@ -15,6 +15,17 @@ PAGE_QUERY = """
page(id: $id, slug: $slug) {
title
slug
+ pageType {
+ id
+ }
+ attributes {
+ attribute {
+ slug
+ }
+ values {
+ slug
+ }
+ }
}
}
"""
@@ -24,6 +35,15 @@ def test_query_published_page(user_api_client, page):
page.is_published = True
page.save()
+ page_type = page.page_type
+
+ assert page.attributes.count() == 1
+ page_attr_assigned = page.attributes.first()
+ page_attr = page_attr_assigned.attribute
+
+ assert page_attr_assigned.values.count() == 1
+ page_attr_value = page_attr_assigned.values.first()
+
# query by ID
variables = {"id": graphene.Node.to_global_id("Page", page.id)}
response = user_api_client.post_graphql(PAGE_QUERY, variables)
@@ -31,6 +51,17 @@ def test_query_published_page(user_api_client, page):
page_data = content["data"]["page"]
assert page_data["title"] == page.title
assert page_data["slug"] == page.slug
+ assert page_data["pageType"]["id"] == graphene.Node.to_global_id(
+ "PageType", page.page_type.pk
+ )
+
+ expected_attributes = []
+ for attr in page_type.page_attributes.all():
+ values = [{"slug": page_attr_value.slug}] if attr.slug == page_attr.slug else []
+ expected_attributes.append({"attribute": {"slug": attr.slug}, "values": values})
+
+ for attr_data in page_data["attributes"]:
+ assert attr_data in expected_attributes
# query by slug
variables = {"slug": page.slug}
@@ -95,13 +126,14 @@ def test_staff_query_unpublished_page(staff_api_client, page, permission_manage_
CREATE_PAGE_MUTATION = """
mutation CreatePage(
- $slug: String, $title: String, $content: String,
- $contentJson: JSONString, $isPublished: Boolean) {
+ $slug: String, $title: String, $content: String, $pageType: ID!
+ $contentJson: JSONString, $isPublished: Boolean,
+ $attributes: [AttributeValueInput!]) {
pageCreate(
input: {
- slug: $slug, title: $title,
+ slug: $slug, title: $title, pageType: $pageType
content: $content, contentJson: $contentJson
- isPublished: $isPublished}) {
+ isPublished: $isPublished, attributes: $attributes}) {
page {
id
title
@@ -110,11 +142,23 @@ CREATE_PAGE_MUTATION = """
slug
isPublished
publicationDate
+ pageType {
+ id
+ }
+ attributes {
+ attribute {
+ slug
+ }
+ values {
+ slug
+ }
+ }
}
pageErrors {
field
code
message
+ attributes
}
}
}
@@ -122,12 +166,23 @@ CREATE_PAGE_MUTATION = """
@freeze_time("2020-03-18 12:00:00")
-def test_page_create_mutation(staff_api_client, permission_manage_pages):
+def test_page_create_mutation(staff_api_client, permission_manage_pages, page_type):
page_slug = "test-slug"
page_content = "test content"
page_content_json = json.dumps({"content": "test content"})
page_title = "test title"
page_is_published = True
+ page_type_id = graphene.Node.to_global_id("PageType", page_type.pk)
+
+ # Default attributes defined in product_type fixture
+ tag_attr = page_type.page_attributes.get(name="tag")
+ tag_value_slug = tag_attr.values.first().slug
+ tag_attr_id = graphene.Node.to_global_id("Attribute", tag_attr.id)
+
+ # Add second attribute
+ size_attr = page_type.page_attributes.get(name="Page size")
+ size_attr_id = graphene.Node.to_global_id("Attribute", size_attr.id)
+ non_existent_attr_value = "New value"
# test creating root page
variables = {
@@ -136,7 +191,13 @@ def test_page_create_mutation(staff_api_client, permission_manage_pages):
"contentJson": page_content_json,
"isPublished": page_is_published,
"slug": page_slug,
+ "pageType": page_type_id,
+ "attributes": [
+ {"id": tag_attr_id, "values": [tag_value_slug]},
+ {"id": size_attr_id, "values": [non_existent_attr_value]},
+ ],
}
+
response = staff_api_client.post_graphql(
CREATE_PAGE_MUTATION, variables, permissions=[permission_manage_pages]
)
@@ -149,11 +210,21 @@ def test_page_create_mutation(staff_api_client, permission_manage_pages):
assert data["page"]["slug"] == page_slug
assert data["page"]["isPublished"] == page_is_published
assert data["page"]["publicationDate"] == "2020-03-18"
+ assert data["page"]["pageType"]["id"] == page_type_id
+ values = (
+ data["page"]["attributes"][0]["values"][0]["slug"],
+ data["page"]["attributes"][1]["values"][0]["slug"],
+ )
+ assert slugify(non_existent_attr_value) in values
+ assert tag_value_slug in values
-def test_page_create_required_fields(staff_api_client, permission_manage_pages):
+def test_page_create_required_fields(
+ staff_api_client, permission_manage_pages, page_type
+):
+ variables = {"pageType": graphene.Node.to_global_id("PageType", page_type.pk)}
response = staff_api_client.post_graphql(
- CREATE_PAGE_MUTATION, {}, permissions=[permission_manage_pages]
+ CREATE_PAGE_MUTATION, variables, permissions=[permission_manage_pages]
)
content = get_graphql_content(response)
errors = content["data"]["pageCreate"]["pageErrors"]
@@ -163,11 +234,15 @@ def test_page_create_required_fields(staff_api_client, permission_manage_pages):
assert errors[0]["code"] == PageErrorCode.REQUIRED.name
-def test_create_default_slug(staff_api_client, permission_manage_pages):
+def test_create_default_slug(staff_api_client, permission_manage_pages, page_type):
# test creating root page
title = "Spanish inquisition"
+ variables = {
+ "title": title,
+ "pageType": graphene.Node.to_global_id("PageType", page_type.pk),
+ }
response = staff_api_client.post_graphql(
- CREATE_PAGE_MUTATION, {"title": title}, permissions=[permission_manage_pages]
+ CREATE_PAGE_MUTATION, variables, permissions=[permission_manage_pages]
)
content = get_graphql_content(response)
data = content["data"]["pageCreate"]
@@ -176,6 +251,102 @@ def test_create_default_slug(staff_api_client, permission_manage_pages):
assert data["page"]["slug"] == slugify(title)
+def test_page_create_mutation_missing_required_attributes(
+ staff_api_client, permission_manage_pages, page_type
+):
+ # given
+ page_slug = "test-slug"
+ page_content = "test content"
+ page_content_json = json.dumps({"content": "test content"})
+ page_title = "test title"
+ page_is_published = True
+ page_type_id = graphene.Node.to_global_id("PageType", page_type.pk)
+
+ # Default attributes defined in product_type fixture
+ tag_attr = page_type.page_attributes.get(name="tag")
+ tag_value_slug = tag_attr.values.first().slug
+ tag_attr_id = graphene.Node.to_global_id("Attribute", tag_attr.id)
+
+ # Add second attribute
+ size_attr = page_type.page_attributes.get(name="Page size")
+ size_attr.value_required = True
+ size_attr.save(update_fields=["value_required"])
+
+ # test creating root page
+ variables = {
+ "title": page_title,
+ "content": page_content,
+ "contentJson": page_content_json,
+ "isPublished": page_is_published,
+ "slug": page_slug,
+ "pageType": page_type_id,
+ "attributes": [{"id": tag_attr_id, "values": [tag_value_slug]}],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ CREATE_PAGE_MUTATION, variables, permissions=[permission_manage_pages]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["pageCreate"]
+ errors = data["pageErrors"]
+
+ assert not data["page"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "attributes"
+ assert errors[0]["code"] == PageErrorCode.REQUIRED.name
+ assert errors[0]["attributes"] == [
+ graphene.Node.to_global_id("Attribute", size_attr.pk)
+ ]
+
+
+def test_page_create_mutation_empty_attribute_value(
+ staff_api_client, permission_manage_pages, page_type
+):
+ # given
+ page_slug = "test-slug"
+ page_content = "test content"
+ page_content_json = json.dumps({"content": "test content"})
+ page_title = "test title"
+ page_is_published = True
+ page_type_id = graphene.Node.to_global_id("PageType", page_type.pk)
+
+ # Default attributes defined in product_type fixture
+ tag_attr = page_type.page_attributes.get(name="tag")
+ tag_attr_id = graphene.Node.to_global_id("Attribute", tag_attr.id)
+
+ # test creating root page
+ variables = {
+ "title": page_title,
+ "content": page_content,
+ "contentJson": page_content_json,
+ "isPublished": page_is_published,
+ "slug": page_slug,
+ "pageType": page_type_id,
+ "attributes": [{"id": tag_attr_id, "values": [" "]}],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ CREATE_PAGE_MUTATION, variables, permissions=[permission_manage_pages]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["pageCreate"]
+ errors = data["pageErrors"]
+
+ assert not data["page"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "attributes"
+ assert errors[0]["code"] == PageErrorCode.REQUIRED.name
+ assert errors[0]["attributes"] == [
+ graphene.Node.to_global_id("Attribute", tag_attr.pk)
+ ]
+
+
def test_page_delete_mutation(staff_api_client, page, permission_manage_pages):
query = """
mutation DeletePage($id: ID!) {
@@ -204,14 +375,31 @@ def test_page_delete_mutation(staff_api_client, page, permission_manage_pages):
UPDATE_PAGE_MUTATION = """
- mutation updatePage($id: ID!, $slug: String, $is_published: Boolean!) {
- pageUpdate(id: $id, input: {slug: $slug, isPublished: $is_published}) {
+ mutation updatePage(
+ $id: ID!,
+ $slug: String,
+ $is_published: Boolean!,
+ $attributes: [AttributeValueInput!]
+ ) {
+ pageUpdate(
+ id: $id, input: {
+ slug: $slug, isPublished: $is_published, attributes: $attributes
+ }
+ ) {
page {
id
title
slug
isPublished
publicationDate
+ attributes {
+ attribute {
+ slug
+ }
+ values {
+ slug
+ }
+ }
}
pageErrors {
field
@@ -224,16 +412,33 @@ UPDATE_PAGE_MUTATION = """
def test_update_page(staff_api_client, permission_manage_pages, page):
+ # given
query = UPDATE_PAGE_MUTATION
+
+ page_type = page.page_type
+ tag_attr = page_type.page_attributes.get(name="tag")
+ tag_attr_id = graphene.Node.to_global_id("Attribute", tag_attr.id)
+ new_value = "Rainbow"
+
page_title = page.title
new_slug = "new-slug"
assert new_slug != page.slug
page_id = graphene.Node.to_global_id("Page", page.id)
- variables = {"id": page_id, "slug": new_slug, "is_published": True}
+
+ variables = {
+ "id": page_id,
+ "slug": new_slug,
+ "is_published": True,
+ "attributes": [{"id": tag_attr_id, "values": [new_value]}],
+ }
+
+ # when
response = staff_api_client.post_graphql(
query, variables, permissions=[permission_manage_pages]
)
+
+ # then
content = get_graphql_content(response)
data = content["data"]["pageUpdate"]
@@ -241,14 +446,40 @@ def test_update_page(staff_api_client, permission_manage_pages, page):
assert data["page"]["title"] == page_title
assert data["page"]["slug"] == new_slug
+ expected_attributes = []
+ page_attr = page.attributes.all()
+ for attr in page_type.page_attributes.all():
+ if attr.slug != tag_attr.slug:
+ values = [
+ {"slug": slug}
+ for slug in page_attr.filter(assignment__attribute=attr).values_list(
+ "values__slug", flat=True
+ )
+ ]
+ else:
+ values = [{"slug": slugify(new_value)}]
+ attr_data = {
+ "attribute": {"slug": attr.slug},
+ "values": values,
+ }
+ expected_attributes.append(attr_data)
+
+ attributes = data["page"]["attributes"]
+ assert len(attributes) == len(expected_attributes)
+ for attr_data in attributes:
+ assert attr_data in expected_attributes
+
@freeze_time("2020-03-18 12:00:00")
-def test_public_page_sets_publication_date(staff_api_client, permission_manage_pages):
+def test_public_page_sets_publication_date(
+ staff_api_client, permission_manage_pages, page_type
+):
data = {
"slug": "test-url",
"title": "Test page",
"content": "test content",
"is_published": False,
+ "page_type": page_type,
}
page = Page.objects.create(**data)
page_id = graphene.Node.to_global_id("Page", page.id)
@@ -317,19 +548,21 @@ def test_update_page_with_title_value_and_without_slug_value(
assert errors[0]["code"] == PageErrorCode.REQUIRED.name
-def test_paginate_pages(user_api_client, page):
+def test_paginate_pages(user_api_client, page, page_type):
page.is_published = True
data_02 = {
"slug": "test02-url",
"title": "Test page",
"content": "test content",
"is_published": True,
+ "page_type": page_type,
}
data_03 = {
"slug": "test03-url",
"title": "Test page",
"content": "test content",
"is_published": True,
+ "page_type": page_type,
}
Page.objects.create(**data_02)
@@ -406,7 +639,7 @@ def test_bulk_unpublish(staff_api_client, page_list, permission_manage_pages):
],
)
def test_pages_query_with_filter(
- page_filter, count, staff_api_client, permission_manage_pages
+ page_filter, count, staff_api_client, permission_manage_pages, page_type
):
query = """
query ($filter: PageFilterInput) {
@@ -420,9 +653,24 @@ def test_pages_query_with_filter(
}
}
"""
- Page.objects.create(title="Page1", slug="slug_page_1", content="Content for page 1")
- Page.objects.create(title="Page2", slug="slug_page_2", content="Content for page 2")
- Page.objects.create(title="About", slug="slug_about", content="About test content")
+ Page.objects.create(
+ title="Page1",
+ slug="slug_page_1",
+ content="Content for page 1",
+ page_type=page_type,
+ )
+ Page.objects.create(
+ title="Page2",
+ slug="slug_page_2",
+ content="Content for page 2",
+ page_type=page_type,
+ )
+ Page.objects.create(
+ title="About",
+ slug="slug_about",
+ content="About test content",
+ page_type=page_type,
+ )
variables = {"filter": page_filter}
staff_api_client.user.user_permissions.add(permission_manage_pages)
response = staff_api_client.post_graphql(query, variables)
@@ -465,7 +713,7 @@ QUERY_PAGE_WITH_SORT = """
],
)
def test_query_pages_with_sort(
- page_sort, result_order, staff_api_client, permission_manage_pages
+ page_sort, result_order, staff_api_client, permission_manage_pages, page_type
):
with freeze_time("2017-05-31 12:00:01"):
Page.objects.create(
@@ -474,6 +722,7 @@ def test_query_pages_with_sort(
content="p1",
is_published=True,
publication_date=timezone.now().replace(year=2018, month=12, day=5),
+ page_type=page_type,
)
with freeze_time("2019-05-31 12:00:01"):
Page.objects.create(
@@ -482,10 +731,15 @@ def test_query_pages_with_sort(
content="p2",
is_published=False,
publication_date=timezone.now().replace(year=2019, month=12, day=5),
+ page_type=page_type,
)
with freeze_time("2018-05-31 12:00:01"):
Page.objects.create(
- title="About", slug="about", content="Ab", is_published=True
+ title="About",
+ slug="about",
+ content="Ab",
+ is_published=True,
+ page_type=page_type,
)
variables = {"sort_by": page_sort}
staff_api_client.user.user_permissions.add(permission_manage_pages)
diff --git a/saleor/graphql/page/tests/test_bulk_delete.py b/saleor/graphql/page/tests/test_page_bulk_delete.py
similarity index 100%
rename from saleor/graphql/page/tests/test_bulk_delete.py
rename to saleor/graphql/page/tests/test_page_bulk_delete.py
diff --git a/saleor/graphql/page/tests/test_page_type_create.py b/saleor/graphql/page/tests/test_page_type_create.py
new file mode 100644
index 0000000000..b26d23634d
--- /dev/null
+++ b/saleor/graphql/page/tests/test_page_type_create.py
@@ -0,0 +1,280 @@
+import graphene
+
+from ....page.error_codes import PageErrorCode
+from ....page.models import PageType
+from ...tests.utils import assert_no_permission, get_graphql_content
+
+PAGE_TYPE_CREATE_MUTATION = """
+ mutation PageTypeCreate($name: String, $slug: String, $addAttributes: [ID!]) {
+ pageTypeCreate(input: {
+ name: $name, slug: $slug, addAttributes: $addAttributes
+ }) {
+ pageType {
+ id
+ name
+ slug
+ attributes {
+ slug
+ }
+ }
+ pageErrors {
+ code
+ field
+ message
+ attributes
+ }
+ }
+ }
+"""
+
+
+def test_page_type_create_as_staff(
+ staff_api_client,
+ tag_page_attribute,
+ author_page_attribute,
+ permission_manage_page_types_and_attributes,
+):
+ # given
+ staff_user = staff_api_client.user
+ staff_user.user_permissions.add(permission_manage_page_types_and_attributes)
+
+ name = "Test page type"
+ slug = "test-page-type"
+
+ attributes = [author_page_attribute, tag_page_attribute]
+
+ variables = {
+ "name": name,
+ "slug": slug,
+ "addAttributes": [
+ graphene.Node.to_global_id("Attribute", attr.pk) for attr in attributes
+ ],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(PAGE_TYPE_CREATE_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["pageTypeCreate"]
+ page_type_data = data["pageType"]
+ errors = data["pageErrors"]
+
+ assert not errors
+ assert page_type_data["name"] == name
+ assert page_type_data["slug"] == slug
+ assert len(page_type_data["attributes"]) == 2
+ assert {attr_data["slug"] for attr_data in page_type_data["attributes"]} == {
+ attr.slug for attr in attributes
+ }
+
+
+def test_page_type_create_as_staff_no_perm(
+ staff_api_client, tag_page_attribute, author_page_attribute
+):
+ # given
+ name = "Test page type"
+ slug = "test-page-type"
+
+ attributes = [author_page_attribute, tag_page_attribute]
+
+ variables = {
+ "name": name,
+ "slug": slug,
+ "addAttributes": [
+ graphene.Node.to_global_id("Attribute", attr.pk) for attr in attributes
+ ],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(PAGE_TYPE_CREATE_MUTATION, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_page_type_create_as_app(
+ app_api_client, tag_page_attribute, permission_manage_page_types_and_attributes
+):
+ # given
+ app = app_api_client.app
+ app.permissions.add(permission_manage_page_types_and_attributes)
+
+ name = "Test page type"
+ slug = "test-page-type"
+
+ variables = {
+ "name": name,
+ "slug": slug,
+ "addAttributes": [
+ graphene.Node.to_global_id("Attribute", tag_page_attribute.pk)
+ ],
+ }
+
+ # when
+ response = app_api_client.post_graphql(PAGE_TYPE_CREATE_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["pageTypeCreate"]
+ page_type_data = data["pageType"]
+ errors = data["pageErrors"]
+
+ assert not errors
+ assert page_type_data["name"] == name
+ assert page_type_data["slug"] == slug
+ assert len(page_type_data["attributes"]) == 1
+ assert page_type_data["attributes"][0]["slug"] == tag_page_attribute.slug
+
+
+def test_page_type_create_as_app_no_perm(app_api_client, tag_page_attribute):
+ # given
+ name = "Test page type"
+ slug = "test-page-type"
+
+ variables = {
+ "name": name,
+ "slug": slug,
+ "addAttributes": [
+ graphene.Node.to_global_id("Attribute", tag_page_attribute.pk)
+ ],
+ }
+
+ # when
+ response = app_api_client.post_graphql(PAGE_TYPE_CREATE_MUTATION, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_page_type_create_unique_slug_generated(
+ staff_api_client,
+ tag_page_attribute,
+ author_page_attribute,
+ permission_manage_page_types_and_attributes,
+):
+ """Ensure that unique slug is generated when slug is not given."""
+
+ # given
+ staff_user = staff_api_client.user
+ staff_user.user_permissions.add(permission_manage_page_types_and_attributes)
+
+ name_1 = "Test page type"
+ name_2 = "test page type"
+ slug = "test-page-type"
+
+ page_type = PageType.objects.create(name=name_1, slug=slug)
+
+ attributes = [author_page_attribute, tag_page_attribute]
+
+ variables = {
+ "name": name_2,
+ "addAttributes": [
+ graphene.Node.to_global_id("Attribute", attr.pk) for attr in attributes
+ ],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(PAGE_TYPE_CREATE_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["pageTypeCreate"]
+ page_type_data = data["pageType"]
+ errors = data["pageErrors"]
+
+ assert not errors
+ assert PageType.objects.count() == 2
+ assert page_type_data["id"] != graphene.Node.to_global_id("PageType", page_type.pk)
+ assert page_type_data["name"] == name_2
+ assert page_type_data["slug"] == "test-page-type-2"
+ assert len(page_type_data["attributes"]) == 2
+ assert {attr_data["slug"] for attr_data in page_type_data["attributes"]} == {
+ attr.slug for attr in attributes
+ }
+
+
+def test_page_type_create_duplicated_slug(
+ staff_api_client,
+ tag_page_attribute,
+ author_page_attribute,
+ permission_manage_page_types_and_attributes,
+):
+ """Ensure that unique errors is raised when page type with given slug exists."""
+
+ # given
+ staff_user = staff_api_client.user
+ staff_user.user_permissions.add(permission_manage_page_types_and_attributes)
+
+ name_1 = "Test page type"
+ name_2 = "test page type"
+ slug = "test-page-type"
+
+ PageType.objects.create(name=name_1, slug=slug)
+
+ attributes = [author_page_attribute, tag_page_attribute]
+
+ variables = {
+ "name": name_2,
+ "slug": slug,
+ "addAttributes": [
+ graphene.Node.to_global_id("Attribute", attr.pk) for attr in attributes
+ ],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(PAGE_TYPE_CREATE_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["pageTypeCreate"]
+ page_type_data = data["pageType"]
+ errors = data["pageErrors"]
+
+ assert not page_type_data
+ assert len(errors) == 1
+ assert errors[0]["code"] == PageErrorCode.UNIQUE.name
+ assert errors[0]["field"] == "slug"
+
+
+def test_page_type_create_not_valid_attributes(
+ staff_api_client,
+ tag_page_attribute,
+ color_attribute,
+ size_attribute,
+ permission_manage_page_types_and_attributes,
+):
+ # given
+ staff_user = staff_api_client.user
+ staff_user.user_permissions.add(permission_manage_page_types_and_attributes)
+
+ name = "Test page type"
+ slug = "test-page-type"
+
+ attributes = [color_attribute, tag_page_attribute, size_attribute]
+
+ variables = {
+ "name": name,
+ "slug": slug,
+ "addAttributes": [
+ graphene.Node.to_global_id("Attribute", attr.pk) for attr in attributes
+ ],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(PAGE_TYPE_CREATE_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["pageTypeCreate"]
+ page_type_data = data["pageType"]
+ errors = data["pageErrors"]
+
+ assert not page_type_data
+ assert len(errors) == 1
+ assert errors[0]["code"] == PageErrorCode.INVALID.name
+ assert errors[0]["field"] == "addAttributes"
+ assert set(errors[0]["attributes"]) == {
+ graphene.Node.to_global_id("Attribute", attr.pk)
+ for attr in [color_attribute, size_attribute]
+ }
diff --git a/saleor/graphql/page/tests/test_page_type_delete.py b/saleor/graphql/page/tests/test_page_type_delete.py
new file mode 100644
index 0000000000..ee592458a0
--- /dev/null
+++ b/saleor/graphql/page/tests/test_page_type_delete.py
@@ -0,0 +1,116 @@
+import graphene
+import pytest
+
+from ....page.models import Page
+from ...tests.utils import assert_no_permission, get_graphql_content
+
+DELETE_PAGE_TYPE_MUTATION = """
+ mutation DeletePageType($id: ID!) {
+ pageTypeDelete(id: $id) {
+ pageType {
+ id
+ name
+ slug
+ }
+ pageErrors {
+ field
+ code
+ message
+ }
+ }
+ }
+"""
+
+
+def test_page_type_delete_by_staff(
+ staff_api_client, page_type, page, permission_manage_page_types_and_attributes
+):
+ # given
+ staff_api_client.user.user_permissions.add(
+ permission_manage_page_types_and_attributes
+ )
+
+ pages_pks = list(page_type.pages.values_list("pk", flat=True))
+
+ assert pages_pks
+
+ page_type_id = graphene.Node.to_global_id("PageType", page_type.pk)
+
+ variables = {"id": page_type_id}
+
+ # when
+ response = staff_api_client.post_graphql(DELETE_PAGE_TYPE_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["pageTypeDelete"]
+
+ assert not data["pageErrors"]
+ assert data["pageType"]["id"] == page_type_id
+
+ with pytest.raises(page_type._meta.model.DoesNotExist):
+ page_type.refresh_from_db()
+
+ # ensure that corresponding pages has been removed
+ assert not Page.objects.filter(pk__in=pages_pks)
+
+
+def test_page_type_delete_by_staff_no_perm(
+ staff_api_client, page_type, page, permission_manage_page_types_and_attributes
+):
+ # given
+ page_type_id = graphene.Node.to_global_id("PageType", page_type.pk)
+
+ variables = {"id": page_type_id}
+
+ # when
+ response = staff_api_client.post_graphql(DELETE_PAGE_TYPE_MUTATION, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_page_type_delete_by_app(
+ app_api_client, page_type, page, permission_manage_page_types_and_attributes
+):
+ # given
+ app_api_client.app.permissions.add(permission_manage_page_types_and_attributes)
+
+ page_type_id = graphene.Node.to_global_id("PageType", page_type.pk)
+
+ pages_pks = list(page_type.pages.values_list("pk", flat=True))
+
+ assert pages_pks
+
+ variables = {"id": page_type_id}
+
+ # when
+ response = app_api_client.post_graphql(DELETE_PAGE_TYPE_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["pageTypeDelete"]
+
+ assert not data["pageErrors"]
+ assert data["pageType"]["id"] == page_type_id
+
+ with pytest.raises(page_type._meta.model.DoesNotExist):
+ page_type.refresh_from_db()
+
+ # ensure that corresponding pages has been removed
+ assert not Page.objects.filter(pk__in=pages_pks)
+
+
+def test_page_type_delete_by_app_no_perm(
+ app_api_client, page_type, page, permission_manage_page_types_and_attributes
+):
+ # given
+ page_type_id = graphene.Node.to_global_id("PageType", page_type.pk)
+
+ variables = {"id": page_type_id}
+
+ # when
+ response = app_api_client.post_graphql(DELETE_PAGE_TYPE_MUTATION, variables)
+
+ # then
+ assert_no_permission(response)
diff --git a/saleor/graphql/page/tests/test_page_type_query.py b/saleor/graphql/page/tests/test_page_type_query.py
new file mode 100644
index 0000000000..8bf286dd34
--- /dev/null
+++ b/saleor/graphql/page/tests/test_page_type_query.py
@@ -0,0 +1,180 @@
+import graphene
+
+from ...tests.utils import assert_no_permission, get_graphql_content
+
+PAGE_TYPE_QUERY = """
+ query PageType($id: ID!, $filters: AttributeFilterInput) {
+ pageType(id: $id) {
+ id
+ name
+ slug
+ hasPages
+ attributes {
+ slug
+ }
+ availableAttributes(first: 10, filter: $filters) {
+ edges {
+ node {
+ slug
+ }
+ }
+ }
+ }
+ }
+"""
+
+
+def test_page_type_query_by_staff(
+ staff_api_client,
+ page_type,
+ author_page_attribute,
+ permission_manage_pages,
+ color_attribute,
+ page,
+):
+ # given
+ staff_user = staff_api_client.user
+ staff_user.user_permissions.add(permission_manage_pages)
+
+ variables = {"id": graphene.Node.to_global_id("PageType", page_type.pk)}
+
+ # when
+ response = staff_api_client.post_graphql(PAGE_TYPE_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ page_type_data = content["data"]["pageType"]
+
+ assert page_type_data["slug"] == page_type.slug
+ assert page_type_data["name"] == page_type.name
+ assert {attr["slug"] for attr in page_type_data["attributes"]} == {
+ attr.slug for attr in page_type.page_attributes.all()
+ }
+ assert page_type_data["hasPages"] is True
+ available_attributes = page_type_data["availableAttributes"]["edges"]
+ assert len(available_attributes) == 1
+ assert available_attributes[0]["node"]["slug"] == author_page_attribute.slug
+
+
+def test_page_type_query_by_staff_no_perm(
+ staff_api_client, page_type, author_page_attribute
+):
+ # given
+ variables = {"id": graphene.Node.to_global_id("PageType", page_type.pk)}
+
+ # when
+ response = staff_api_client.post_graphql(PAGE_TYPE_QUERY, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_page_type_query_by_app(
+ app_api_client,
+ page_type,
+ author_page_attribute,
+ permission_manage_pages,
+ color_attribute,
+):
+ # given
+ staff_user = app_api_client.app
+ staff_user.permissions.add(permission_manage_pages)
+
+ variables = {"id": graphene.Node.to_global_id("PageType", page_type.pk)}
+
+ # when
+ response = app_api_client.post_graphql(PAGE_TYPE_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ page_type_data = content["data"]["pageType"]
+
+ assert page_type_data["slug"] == page_type.slug
+ assert page_type_data["name"] == page_type.name
+ assert {attr["slug"] for attr in page_type_data["attributes"]} == {
+ attr.slug for attr in page_type.page_attributes.all()
+ }
+ available_attributes = page_type_data["availableAttributes"]["edges"]
+ assert len(available_attributes) == 1
+ assert available_attributes[0]["node"]["slug"] == author_page_attribute.slug
+
+
+def test_page_type_query_by_app_no_perm(
+ app_api_client,
+ page_type,
+ author_page_attribute,
+ permission_manage_page_types_and_attributes,
+):
+ # given
+ variables = {"id": graphene.Node.to_global_id("PageType", page_type.pk)}
+
+ # when
+ response = app_api_client.post_graphql(PAGE_TYPE_QUERY, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_page_type_query_filter_unassigned_attributes(
+ staff_api_client,
+ page_type,
+ permission_manage_pages,
+ page_type_attribute_list,
+ color_attribute,
+):
+ # given
+ staff_user = staff_api_client.user
+ staff_user.user_permissions.add(permission_manage_pages)
+
+ expected_attribute = page_type_attribute_list[0]
+
+ variables = {
+ "id": graphene.Node.to_global_id("PageType", page_type.pk),
+ "filters": {"search": expected_attribute.name},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(PAGE_TYPE_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ page_type_data = content["data"]["pageType"]
+
+ assert page_type_data["slug"] == page_type.slug
+ assert {attr["slug"] for attr in page_type_data["attributes"]} == {
+ attr.slug for attr in page_type.page_attributes.all()
+ }
+ available_attributes = page_type_data["availableAttributes"]["edges"]
+ assert len(available_attributes) == 1
+ assert available_attributes[0]["node"]["slug"] == expected_attribute.slug
+
+
+def test_page_type_query_no_pages(
+ staff_api_client,
+ page_type,
+ author_page_attribute,
+ permission_manage_pages,
+ color_attribute,
+):
+ # given
+ staff_user = staff_api_client.user
+ staff_user.user_permissions.add(permission_manage_pages)
+
+ variables = {"id": graphene.Node.to_global_id("PageType", page_type.pk)}
+
+ # when
+ response = staff_api_client.post_graphql(PAGE_TYPE_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ page_type_data = content["data"]["pageType"]
+
+ assert page_type_data["slug"] == page_type.slug
+ assert page_type_data["name"] == page_type.name
+ assert {attr["slug"] for attr in page_type_data["attributes"]} == {
+ attr.slug for attr in page_type.page_attributes.all()
+ }
+ assert page_type_data["hasPages"] is False
+ available_attributes = page_type_data["availableAttributes"]["edges"]
+ assert len(available_attributes) == 1
+ assert available_attributes[0]["node"]["slug"] == author_page_attribute.slug
diff --git a/saleor/graphql/page/tests/test_page_type_reorder_attributes.py b/saleor/graphql/page/tests/test_page_type_reorder_attributes.py
new file mode 100644
index 0000000000..f335e67ebe
--- /dev/null
+++ b/saleor/graphql/page/tests/test_page_type_reorder_attributes.py
@@ -0,0 +1,306 @@
+import graphene
+
+from ....page.error_codes import PageErrorCode
+from ....page.models import PageType
+from ...tests.utils import assert_no_permission, get_graphql_content
+
+PAGE_TYPE_REORDER_ATTRIBUTES_MUTATION = """
+ mutation PageTypeReorderAttributes(
+ $pageTypeId: ID!
+ $moves: [ReorderInput!]!
+ ) {
+ pageTypeReorderAttributes(
+ pageTypeId: $pageTypeId
+ moves: $moves
+ ) {
+ pageType {
+ id
+ attributes {
+ id
+ slug
+ }
+ }
+ pageErrors {
+ code
+ field
+ message
+ attributes
+ }
+ }
+ }
+"""
+
+
+def test_reorder_page_type_attributes_by_staff(
+ staff_api_client,
+ permission_manage_page_types_and_attributes,
+ page_type_attribute_list,
+):
+ # given
+ staff_api_client.user.user_permissions.add(
+ permission_manage_page_types_and_attributes
+ )
+
+ attributes = page_type_attribute_list
+ assert len(attributes) == 3
+
+ page_type = PageType.objects.create(name="Test page type", slug="test-page-type")
+ page_type.page_attributes.set(attributes)
+
+ sorted_attributes = list(page_type.page_attributes.order_by())
+
+ assert len(sorted_attributes) == 3
+
+ variables = {
+ "pageTypeId": graphene.Node.to_global_id("PageType", page_type.pk),
+ "moves": [
+ {
+ "id": graphene.Node.to_global_id("Attribute", sorted_attributes[2].pk),
+ "sortOrder": -2,
+ },
+ {
+ "id": graphene.Node.to_global_id("Attribute", sorted_attributes[0].pk),
+ "sortOrder": 1,
+ },
+ ],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PAGE_TYPE_REORDER_ATTRIBUTES_MUTATION, variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["pageTypeReorderAttributes"]
+ errors = data["pageErrors"]
+ page_type_data = data["pageType"]
+
+ assert not errors
+ assert len(page_type_data["attributes"]) == len(sorted_attributes)
+
+ expected_order = [
+ sorted_attributes[2].pk,
+ sorted_attributes[1].pk,
+ sorted_attributes[0].pk,
+ ]
+
+ for attr, expected_pk in zip(page_type_data["attributes"], expected_order):
+ gql_type, gql_attr_id = graphene.Node.from_global_id(attr["id"])
+ assert gql_type == "Attribute"
+ assert int(gql_attr_id) == expected_pk
+
+
+def test_reorder_page_type_attributes_by_staff_no_perm(
+ staff_api_client, page_type_attribute_list
+):
+ # given
+ attributes = page_type_attribute_list
+ assert len(attributes) == 3
+
+ page_type = PageType.objects.create(name="Test page type", slug="test-page-type")
+ page_type.page_attributes.set(attributes)
+
+ sorted_attributes = list(page_type.page_attributes.order_by())
+
+ assert len(sorted_attributes) == 3
+
+ variables = {
+ "pageTypeId": graphene.Node.to_global_id("PageType", page_type.pk),
+ "moves": [
+ {
+ "id": graphene.Node.to_global_id("Attribute", attributes[0].pk),
+ "sortOrder": 1,
+ },
+ {
+ "id": graphene.Node.to_global_id("Attribute", attributes[2].pk),
+ "sortOrder": -1,
+ },
+ ],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PAGE_TYPE_REORDER_ATTRIBUTES_MUTATION, variables
+ )
+
+ # then
+ assert_no_permission(response)
+
+
+def test_reorder_page_type_attributes_by_app(
+ app_api_client,
+ permission_manage_page_types_and_attributes,
+ page_type_attribute_list,
+):
+ # given
+ app_api_client.app.permissions.add(permission_manage_page_types_and_attributes)
+
+ attributes = page_type_attribute_list
+ assert len(attributes) == 3
+
+ page_type = PageType.objects.create(name="Test page type", slug="test-page-type")
+ page_type.page_attributes.set(attributes)
+
+ sorted_attributes = list(page_type.page_attributes.order_by())
+
+ assert len(sorted_attributes) == 3
+
+ variables = {
+ "pageTypeId": graphene.Node.to_global_id("PageType", page_type.pk),
+ "moves": [
+ {
+ "id": graphene.Node.to_global_id("Attribute", sorted_attributes[2].pk),
+ "sortOrder": -2,
+ },
+ {
+ "id": graphene.Node.to_global_id("Attribute", sorted_attributes[0].pk),
+ "sortOrder": 1,
+ },
+ ],
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ PAGE_TYPE_REORDER_ATTRIBUTES_MUTATION, variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["pageTypeReorderAttributes"]
+ errors = data["pageErrors"]
+ page_type_data = data["pageType"]
+
+ assert not errors
+ assert len(page_type_data["attributes"]) == len(sorted_attributes)
+
+ expected_order = [
+ sorted_attributes[2].pk,
+ sorted_attributes[1].pk,
+ sorted_attributes[0].pk,
+ ]
+
+ for attr, expected_pk in zip(page_type_data["attributes"], expected_order):
+ gql_type, gql_attr_id = graphene.Node.from_global_id(attr["id"])
+ assert gql_type == "Attribute"
+ assert int(gql_attr_id) == expected_pk
+
+
+def test_reorder_page_type_attributes_by_app_no_perm(
+ app_api_client, page_type_attribute_list
+):
+ # given
+ attributes = page_type_attribute_list
+ assert len(attributes) == 3
+
+ page_type = PageType.objects.create(name="Test page type", slug="test-page-type")
+ page_type.page_attributes.set(attributes)
+
+ sorted_attributes = list(page_type.page_attributes.order_by())
+
+ assert len(sorted_attributes) == 3
+
+ variables = {
+ "pageTypeId": graphene.Node.to_global_id("PageType", page_type.pk),
+ "moves": [
+ {
+ "id": graphene.Node.to_global_id("Attribute", attributes[2].pk),
+ "sortOrder": -2,
+ },
+ {
+ "id": graphene.Node.to_global_id("Attribute", attributes[0].pk),
+ "sortOrder": 1,
+ },
+ ],
+ }
+
+ # when
+ response = app_api_client.post_graphql(
+ PAGE_TYPE_REORDER_ATTRIBUTES_MUTATION, variables
+ )
+
+ # then
+ assert_no_permission(response)
+
+
+def test_reorder_page_type_attributes_invalid_page_type(
+ staff_api_client, permission_manage_page_types_and_attributes, page_type
+):
+ # given
+ staff_api_client.user.user_permissions.add(
+ permission_manage_page_types_and_attributes
+ )
+
+ attribute = page_type.page_attributes.first()
+
+ variables = {
+ "pageTypeId": graphene.Node.to_global_id("PageType", -1),
+ "moves": [
+ {
+ "id": graphene.Node.to_global_id("Attribute", attribute.pk),
+ "sortOrder": 1,
+ },
+ ],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PAGE_TYPE_REORDER_ATTRIBUTES_MUTATION, variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["pageTypeReorderAttributes"]
+ errors = data["pageErrors"]
+ page_type_data = data["pageType"]
+
+ assert not page_type_data
+ assert len(errors) == 1
+ assert errors[0]["field"] == "pageTypeId"
+ assert errors[0]["code"] == PageErrorCode.NOT_FOUND.name
+
+
+def test_reorder_page_type_attributes_invalid_attribute_id(
+ staff_api_client,
+ permission_manage_page_types_and_attributes,
+ page_type,
+ color_attribute,
+ size_attribute,
+):
+ # given
+ staff_api_client.user.user_permissions.add(
+ permission_manage_page_types_and_attributes
+ )
+
+ page_type_attribute = page_type.page_attributes.first()
+ color_attribute_id = graphene.Node.to_global_id("Attribute", color_attribute.pk)
+ size_attribute_id = graphene.Node.to_global_id("Attribute", size_attribute.pk)
+
+ variables = {
+ "pageTypeId": graphene.Node.to_global_id("PageType", page_type.pk),
+ "moves": [
+ {"id": color_attribute_id, "sortOrder": 1},
+ {
+ "id": graphene.Node.to_global_id("Attribute", page_type_attribute.pk),
+ "sortOrder": 1,
+ },
+ {"id": size_attribute_id, "sortOrder": 1},
+ ],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ PAGE_TYPE_REORDER_ATTRIBUTES_MUTATION, variables
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["pageTypeReorderAttributes"]
+ errors = data["pageErrors"]
+ page_type_data = data["pageType"]
+
+ assert not page_type_data
+ assert len(errors) == 1
+ assert errors[0]["field"] == "moves"
+ assert errors[0]["code"] == PageErrorCode.NOT_FOUND.name
+ assert set(errors[0]["attributes"]) == {color_attribute_id, size_attribute_id}
diff --git a/saleor/graphql/page/tests/test_page_type_update.py b/saleor/graphql/page/tests/test_page_type_update.py
new file mode 100644
index 0000000000..c51578e261
--- /dev/null
+++ b/saleor/graphql/page/tests/test_page_type_update.py
@@ -0,0 +1,356 @@
+from unittest.mock import ANY
+
+import graphene
+
+from ....page.error_codes import PageErrorCode
+from ....page.models import PageType
+from ...tests.utils import assert_no_permission, get_graphql_content
+
+PAGE_TYPE_UPDATE_MUTATION = """
+ mutation PageTypeUpdate(
+ $id: ID!, $input: PageTypeUpdateInput!
+ ) {
+ pageTypeUpdate(id: $id, input: $input) {
+ pageType {
+ id
+ name
+ slug
+ attributes {
+ slug
+ }
+ }
+ pageErrors {
+ code
+ field
+ message
+ attributes
+ }
+ }
+ }
+"""
+
+
+def test_page_type_update_as_staff(
+ staff_api_client,
+ page_type,
+ permission_manage_page_types_and_attributes,
+ author_page_attribute,
+ size_page_attribute,
+ tag_page_attribute,
+):
+ # given
+ staff_user = staff_api_client.user
+ staff_user.user_permissions.add(permission_manage_page_types_and_attributes)
+
+ slug = "new-slug"
+ name = "new-name"
+
+ variables = {
+ "id": graphene.Node.to_global_id("PageType", page_type.pk),
+ "input": {
+ "slug": slug,
+ "name": name,
+ "addAttributes": [
+ graphene.Node.to_global_id("Attribute", author_page_attribute.pk)
+ ],
+ "removeAttributes": [
+ graphene.Node.to_global_id("Attribute", size_page_attribute.pk)
+ ],
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(PAGE_TYPE_UPDATE_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["pageTypeUpdate"]
+ errors = data["pageErrors"]
+ page_type_data = data["pageType"]
+
+ page_type.refresh_from_db()
+ assert not errors
+ assert page_type_data["name"] == name
+ assert page_type_data["slug"] == slug
+ assert {attr["slug"] for attr in page_type_data["attributes"]} == {
+ tag_page_attribute.slug,
+ author_page_attribute.slug,
+ }
+
+
+def test_page_type_update_as_staff_no_perm(staff_api_client, page_type):
+ # given
+ variables = {
+ "id": graphene.Node.to_global_id("PageType", page_type.pk),
+ "input": {"name": "New page type name"},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(PAGE_TYPE_UPDATE_MUTATION, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_page_type_update_as_app(
+ staff_api_client,
+ page_type,
+ permission_manage_page_types_and_attributes,
+ author_page_attribute,
+ size_page_attribute,
+ tag_page_attribute,
+):
+ # given
+ staff_user = staff_api_client.user
+ staff_user.user_permissions.add(permission_manage_page_types_and_attributes)
+
+ slug = "new-slug"
+ name = "new-name"
+
+ variables = {
+ "id": graphene.Node.to_global_id("PageType", page_type.pk),
+ "input": {
+ "slug": slug,
+ "name": name,
+ "addAttributes": [
+ graphene.Node.to_global_id("Attribute", author_page_attribute.pk)
+ ],
+ "removeAttributes": [
+ graphene.Node.to_global_id("Attribute", size_page_attribute.pk)
+ ],
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(PAGE_TYPE_UPDATE_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["pageTypeUpdate"]
+ errors = data["pageErrors"]
+ page_type_data = data["pageType"]
+
+ page_type.refresh_from_db()
+ assert not errors
+ assert page_type_data["name"] == name
+ assert page_type_data["slug"] == slug
+ assert {attr["slug"] for attr in page_type_data["attributes"]} == {
+ tag_page_attribute.slug,
+ author_page_attribute.slug,
+ }
+
+
+def test_page_type_update_as_app_no_perm(app_api_client, page_type):
+ # given
+ variables = {
+ "id": graphene.Node.to_global_id("PageType", page_type.pk),
+ "input": {"name": "New page type name"},
+ }
+
+ # when
+ response = app_api_client.post_graphql(PAGE_TYPE_UPDATE_MUTATION, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_page_type_update_duplicated_attributes(
+ staff_api_client,
+ page_type,
+ permission_manage_page_types_and_attributes,
+ author_page_attribute,
+ size_page_attribute,
+):
+ # given
+ staff_user = staff_api_client.user
+ staff_user.user_permissions.add(permission_manage_page_types_and_attributes)
+
+ author_page_attr_id = graphene.Node.to_global_id(
+ "Attribute", author_page_attribute.pk
+ )
+ size_page_att_id = graphene.Node.to_global_id("Attribute", size_page_attribute.pk)
+
+ variables = {
+ "id": graphene.Node.to_global_id("PageType", page_type.pk),
+ "input": {
+ "addAttributes": [author_page_attr_id],
+ "removeAttributes": [author_page_attr_id, size_page_att_id],
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(PAGE_TYPE_UPDATE_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["pageTypeUpdate"]
+ errors = data["pageErrors"]
+ page_type_data = data["pageType"]
+
+ assert not page_type_data
+ assert len(errors) == 1
+ assert errors[0]["code"] == PageErrorCode.DUPLICATED_INPUT_ITEM.name
+ assert errors[0]["field"] == "attributes"
+ assert errors[0]["attributes"] == [author_page_attr_id]
+
+
+def test_page_type_update_not_valid_attributes(
+ staff_api_client,
+ page_type,
+ permission_manage_page_types_and_attributes,
+ author_page_attribute,
+ size_page_attribute,
+ color_attribute,
+ weight_attribute,
+ size_attribute,
+):
+ # given
+ staff_user = staff_api_client.user
+ staff_user.user_permissions.add(permission_manage_page_types_and_attributes)
+
+ variables = {
+ "id": graphene.Node.to_global_id("PageType", page_type.pk),
+ "input": {
+ "addAttributes": [
+ graphene.Node.to_global_id("Attribute", attr.pk)
+ for attr in [author_page_attribute, color_attribute]
+ ],
+ "removeAttributes": [
+ graphene.Node.to_global_id("Attribute", attr.pk)
+ for attr in [size_page_attribute, weight_attribute, size_attribute]
+ ],
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(PAGE_TYPE_UPDATE_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["pageTypeUpdate"]
+ errors = data["pageErrors"]
+ page_type_data = data["pageType"]
+
+ assert not page_type_data
+ assert len(errors) == 2
+ expected_errors = [
+ {
+ "code": PageErrorCode.INVALID.name,
+ "field": "addAttributes",
+ "message": ANY,
+ "attributes": [graphene.Node.to_global_id("Attribute", color_attribute.pk)],
+ },
+ {
+ "code": PageErrorCode.INVALID.name,
+ "field": "removeAttributes",
+ "message": ANY,
+ "attributes": [
+ graphene.Node.to_global_id("Attribute", attr.pk)
+ for attr in [weight_attribute, size_attribute]
+ ],
+ },
+ ]
+ for error in errors:
+ assert error in expected_errors
+
+
+def test_page_type_update_empty_slug(
+ staff_api_client, page_type, permission_manage_page_types_and_attributes
+):
+ # given
+ staff_user = staff_api_client.user
+ staff_user.user_permissions.add(permission_manage_page_types_and_attributes)
+
+ variables = {
+ "id": graphene.Node.to_global_id("PageType", page_type.pk),
+ "input": {"name": "New page type name", "slug": ""},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(PAGE_TYPE_UPDATE_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["pageTypeUpdate"]
+ errors = data["pageErrors"]
+ page_type_data = data["pageType"]
+
+ assert not page_type_data
+ assert len(errors) == 1
+ assert errors[0]["code"] == PageErrorCode.REQUIRED.name
+ assert errors[0]["field"] == "slug"
+
+
+def test_page_type_update_duplicated_slug(
+ staff_api_client, page_type, permission_manage_page_types_and_attributes
+):
+ # given
+ staff_user = staff_api_client.user
+ staff_user.user_permissions.add(permission_manage_page_types_and_attributes)
+
+ slug = "duplicated-tag"
+ PageType.objects.create(name="Test page type 2", slug=slug)
+
+ variables = {
+ "id": graphene.Node.to_global_id("PageType", page_type.pk),
+ "input": {"name": "New page type name", "slug": slug},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(PAGE_TYPE_UPDATE_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["pageTypeUpdate"]
+ errors = data["pageErrors"]
+ page_type_data = data["pageType"]
+
+ assert not page_type_data
+ assert len(errors) == 1
+ assert errors[0]["code"] == PageErrorCode.UNIQUE.name
+ assert errors[0]["field"] == "slug"
+
+
+def test_page_type_update_multiply_errors(
+ staff_api_client,
+ page_type,
+ permission_manage_page_types_and_attributes,
+ author_page_attribute,
+ size_page_attribute,
+ color_attribute,
+):
+ """Ensure that if multiply errors occurred all will raised."""
+
+ # given
+ staff_user = staff_api_client.user
+ staff_user.user_permissions.add(permission_manage_page_types_and_attributes)
+
+ color_attribute_id = graphene.Node.to_global_id("Attribute", color_attribute.pk)
+ author_page_attr_id = graphene.Node.to_global_id(
+ "Attribute", author_page_attribute.pk
+ )
+ size_page_att_id = graphene.Node.to_global_id("Attribute", size_page_attribute.pk)
+
+ variables = {
+ "id": graphene.Node.to_global_id("PageType", page_type.pk),
+ "input": {
+ "slug": "",
+ "addAttributes": [author_page_attr_id, color_attribute_id],
+ "removeAttributes": [author_page_attr_id, size_page_att_id],
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(PAGE_TYPE_UPDATE_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["pageTypeUpdate"]
+ errors = data["pageErrors"]
+ page_type_data = data["pageType"]
+
+ assert not page_type_data
+ assert len(errors) == 3
+ assert errors[0]["code"] == PageErrorCode.DUPLICATED_INPUT_ITEM.name
+ assert errors[0]["field"] == "attributes"
+ assert errors[0]["attributes"] == [author_page_attr_id]
diff --git a/saleor/graphql/page/tests/test_page_types_bulk_delete.py b/saleor/graphql/page/tests/test_page_types_bulk_delete.py
new file mode 100644
index 0000000000..678473628c
--- /dev/null
+++ b/saleor/graphql/page/tests/test_page_types_bulk_delete.py
@@ -0,0 +1,119 @@
+import graphene
+
+from ....page.models import Page
+from ...tests.utils import assert_no_permission, get_graphql_content
+
+PAGE_TYPE_BULK_DELETE_MUTATION = """
+ mutation PageTypeBulkDelete($ids: [ID!]!) {
+ pageTypeBulkDelete(ids: $ids) {
+ count
+ pageErrors {
+ code
+ field
+ message
+ }
+ }
+ }
+"""
+
+
+def test_page_type_bulk_delete_by_staff(
+ staff_api_client, page_type_list, permission_manage_page_types_and_attributes
+):
+ # given
+ staff_api_client.user.user_permissions.add(
+ permission_manage_page_types_and_attributes
+ )
+
+ page_type_count = len(page_type_list)
+
+ pages_pks = list(
+ Page.objects.filter(page_type__in=page_type_list).values_list("pk", flat=True)
+ )
+
+ variables = {
+ "ids": [
+ graphene.Node.to_global_id("PageType", page_type.pk)
+ for page_type in page_type_list
+ ]
+ }
+
+ # when
+ response = staff_api_client.post_graphql(PAGE_TYPE_BULK_DELETE_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["pageTypeBulkDelete"]
+
+ assert not data["pageErrors"]
+ assert data["count"] == page_type_count
+
+ assert not Page.objects.filter(pk__in=pages_pks)
+
+
+def test_page_type_bulk_delete_by_staff_no_perm(
+ staff_api_client, page_type_list, permission_manage_page_types_and_attributes
+):
+ # given
+ variables = {
+ "ids": [
+ graphene.Node.to_global_id("PageType", page_type.pk)
+ for page_type in page_type_list
+ ]
+ }
+
+ # when
+ response = staff_api_client.post_graphql(PAGE_TYPE_BULK_DELETE_MUTATION, variables)
+
+ # then
+ assert_no_permission(response)
+
+
+def test_page_type_bulk_delete_by_app(
+ app_api_client, page_type_list, permission_manage_page_types_and_attributes
+):
+ # given
+ app_api_client.app.permissions.add(permission_manage_page_types_and_attributes)
+
+ page_type_count = len(page_type_list)
+
+ pages_pks = list(
+ Page.objects.filter(page_type__in=page_type_list).values_list("pk", flat=True)
+ )
+
+ variables = {
+ "ids": [
+ graphene.Node.to_global_id("PageType", page_type.pk)
+ for page_type in page_type_list
+ ]
+ }
+
+ # when
+ response = app_api_client.post_graphql(PAGE_TYPE_BULK_DELETE_MUTATION, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["pageTypeBulkDelete"]
+
+ assert not data["pageErrors"]
+ assert data["count"] == page_type_count
+
+ assert not Page.objects.filter(pk__in=pages_pks)
+
+
+def test_page_type_bulk_delete_by_app_no_perm(
+ app_api_client, page_type_list, permission_manage_page_types_and_attributes
+):
+ # given
+ variables = {
+ "ids": [
+ graphene.Node.to_global_id("PageType", page_type.pk)
+ for page_type in page_type_list
+ ]
+ }
+
+ # when
+ response = app_api_client.post_graphql(PAGE_TYPE_BULK_DELETE_MUTATION, variables)
+
+ # then
+ assert_no_permission(response)
diff --git a/saleor/graphql/page/tests/test_page_types_sorting_and_filtering.py b/saleor/graphql/page/tests/test_page_types_sorting_and_filtering.py
new file mode 100644
index 0000000000..86df77b045
--- /dev/null
+++ b/saleor/graphql/page/tests/test_page_types_sorting_and_filtering.py
@@ -0,0 +1,109 @@
+import graphene
+import pytest
+
+from ....page.models import PageType
+from ...tests.utils import get_graphql_content
+
+PAGE_TYPES_QUERY = """
+ query PageTypes($filter: PageTypeFilterInput, $sortBy: PageTypeSortingInput) {
+ pageTypes(first: 10, filter: $filter, sortBy: $sortBy) {
+ edges {
+ node {
+ id
+ }
+ }
+ }
+ }
+"""
+
+
+ "search_value, result_items",
+ [("test", [0]), ("page", [0, 1, 2]), ("Example page", [1, 2])],
+)
+def test_filter_page_types(
+ search_value, result_items, staff_api_client, page_type_list
+):
+ # given
+ variables = {"filter": {"search": search_value}}
+
+ # when
+ response = staff_api_client.post_graphql(PAGE_TYPES_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["pageTypes"]["edges"]
+
+ assert {node["node"]["id"] for node in data} == {
+ graphene.Node.to_global_id("PageType", page_type_list[i].pk)
+ for i in result_items
+ }
+
+
+ "direction, order_direction", (("ASC", "name"), ("DESC", "-name")),
+)
+def test_sort_page_types_by_name(
+ direction, order_direction, staff_api_client, page_type_list
+):
+ # given
+ variables = {"sortBy": {"field": "NAME", "direction": direction}}
+
+ # when
+ response = staff_api_client.post_graphql(PAGE_TYPES_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["pageTypes"]["edges"]
+
+ assert [node["node"]["id"] for node in data] == [
+ graphene.Node.to_global_id("PageType", page_type.pk)
+ for page_type in PageType.objects.order_by(order_direction)
+ ]
+
+
+ "direction, order_direction", (("ASC", "slug"), ("DESC", "-slug")),
+)
+def test_sort_page_types_by_slug(
+ direction, order_direction, staff_api_client, page_type_list
+):
+ # given
+ variables = {"sortBy": {"field": "SLUG", "direction": direction}}
+
+ # when
+ response = staff_api_client.post_graphql(PAGE_TYPES_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["pageTypes"]["edges"]
+
+ assert [node["node"]["id"] for node in data] == [
+ graphene.Node.to_global_id("PageType", page_type.pk)
+ for page_type in PageType.objects.order_by(order_direction)
+ ]
+
+
+ "direction, result_items", (("ASC", [1, 2]), ("DESC", [2, 1])),
+)
+def test_filter_and_sort_by_slug_page_types(
+ direction, result_items, staff_api_client, page_type_list
+):
+ # given
+ variables = {
+ "filter": {"search": "Example"},
+ "sortBy": {"field": "SLUG", "direction": direction},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(PAGE_TYPES_QUERY, variables)
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["pageTypes"]["edges"]
+
+ assert [node["node"]["id"] for node in data] == [
+ graphene.Node.to_global_id("PageType", page_type_list[i].pk)
+ for i in result_items
+ ]
diff --git a/saleor/graphql/page/types.py b/saleor/graphql/page/types.py
index 5a655d7c22..872215d592 100644
--- a/saleor/graphql/page/types.py
+++ b/saleor/graphql/page/types.py
@@ -1,14 +1,32 @@
-from graphene import relay
+import graphene
+from graphene_federation import key
+from ...attribute import models as attribute_models
+from ...core.permissions import PagePermissions
from ...page import models
+from ..attribute.filters import AttributeFilterInput
+from ..attribute.types import Attribute, SelectedAttribute
from ..core.connection import CountableDjangoObjectType
+from ..core.fields import FilterInputConnectionField
+from ..decorators import permission_required
from ..meta.types import ObjectWithMetadata
from ..translations.fields import TranslationField
from ..translations.types import PageTranslation
+from .dataloaders import (
+ PageAttributesByPageTypeIdLoader,
+ PagesByPageTypeIdLoader,
+ PageTypeByIdLoader,
+ SelectedAttributesByPageIdLoader,
+)
class Page(CountableDjangoObjectType):
translation = TranslationField(PageTranslation, type_name="page")
+ attributes = graphene.List(
+ graphene.NonNull(SelectedAttribute),
+ required=True,
+ description="List of attributes assigned to this product.",
+ )
class Meta:
description = (
@@ -21,11 +39,62 @@ class Page(CountableDjangoObjectType):
"created",
"id",
"is_published",
+ "page_type",
"publication_date",
"seo_description",
"seo_title",
"slug",
"title",
]
- interfaces = [relay.Node, ObjectWithMetadata]
+ interfaces = [graphene.relay.Node, ObjectWithMetadata]
model = models.Page
+
+ @staticmethod
+ def resolve_page_type(root: models.Page, info):
+ return PageTypeByIdLoader(info.context).load(root.page_type_id)
+
+ @staticmethod
+ def resolve_attributes(root: models.Page, info):
+ return SelectedAttributesByPageIdLoader(info.context).load(root.id)
+
+
+@key(fields="id")
+class PageType(CountableDjangoObjectType):
+ attributes = graphene.List(
+ Attribute, description="Page attributes of that page type."
+ )
+ available_attributes = FilterInputConnectionField(
+ Attribute,
+ filter=AttributeFilterInput(),
+ description="Attributes that can be assigned to the page type.",
+ )
+ has_pages = graphene.Boolean(description="Whether page type has pages assigned.")
+
+ class Meta:
+ description = (
+ "Represents a type of page. It defines what attributes are available to "
+ "pages of this type."
+ )
+ interfaces = [graphene.relay.Node, ObjectWithMetadata]
+ model = models.PageType
+ only_fields = ["id", "name", "slug"]
+
+ @staticmethod
+ def resolve_attributes(root: models.PageType, info):
+ return PageAttributesByPageTypeIdLoader(info.context).load(root.pk)
+
+ @staticmethod
+ @permission_required(PagePermissions.MANAGE_PAGES)
+ def resolve_available_attributes(root: models.PageType, info, **kwargs):
+ return attribute_models.Attribute.objects.get_unassigned_page_type_attributes(
+ root.pk
+ )
+
+ @staticmethod
+ @permission_required(PagePermissions.MANAGE_PAGES)
+ def resolve_has_pages(root: models.PageType, info, **kwargs):
+ return (
+ PagesByPageTypeIdLoader(info.context)
+ .load(root.pk)
+ .then(lambda pages: bool(pages))
+ )
diff --git a/saleor/graphql/product/bulk_mutations/products.py b/saleor/graphql/product/bulk_mutations/products.py
index d4acbc7321..acc5425298 100644
--- a/saleor/graphql/product/bulk_mutations/products.py
+++ b/saleor/graphql/product/bulk_mutations/products.py
@@ -10,7 +10,7 @@ from ....product import models
from ....product.error_codes import ProductErrorCode
from ....product.tasks import update_product_discounted_price_task
from ....product.utils import delete_categories
-from ....product.utils.attributes import generate_name_for_variant
+from ....product.utils.variants import generate_name_for_variant
from ....warehouse import models as warehouse_models
from ....warehouse.error_codes import StockErrorCode
from ...channel import ChannelContext
diff --git a/saleor/graphql/product/dataloaders/__init__.py b/saleor/graphql/product/dataloaders/__init__.py
index b2c3b86c10..99f09d6019 100644
--- a/saleor/graphql/product/dataloaders/__init__.py
+++ b/saleor/graphql/product/dataloaders/__init__.py
@@ -1,5 +1,4 @@
from .attributes import (
- AttributeValuesByAttributeIdLoader,
ProductAttributesByProductTypeIdLoader,
SelectedAttributesByProductIdLoader,
SelectedAttributesByProductVariantIdLoader,
@@ -28,7 +27,6 @@ from .products import (
)
__all__ = [
- "AttributeValuesByAttributeIdLoader",
"CategoryByIdLoader",
"CollectionByIdLoader",
"CollectionChannelListingByCollectionIdAndChannelSlugLoader",
diff --git a/saleor/graphql/product/dataloaders/attributes.py b/saleor/graphql/product/dataloaders/attributes.py
index 4b2e5b6277..1907f28532 100644
--- a/saleor/graphql/product/dataloaders/attributes.py
+++ b/saleor/graphql/product/dataloaders/attributes.py
@@ -2,41 +2,20 @@ from collections import defaultdict
from promise import Promise
-from ....core.permissions import ProductPermissions
-from ....product.models import (
+from ....attribute.models import (
AssignedProductAttribute,
AssignedVariantAttribute,
- Attribute,
AttributeProduct,
AttributeValue,
AttributeVariant,
)
+from ....core.permissions import ProductPermissions
+from ...attribute.dataloaders import AttributesByAttributeId, AttributeValueByIdLoader
from ...core.dataloaders import DataLoader
from ...utils import get_user_or_app_from_context
from .products import ProductByIdLoader, ProductVariantByIdLoader
-class AttributeValuesByAttributeIdLoader(DataLoader):
- context_key = "attributevalues_by_attribute"
-
- def batch_load(self, keys):
- attribute_values = AttributeValue.objects.filter(attribute_id__in=keys)
- attribute_to_attributevalues = defaultdict(list)
- for attribute_value in attribute_values.iterator():
- attribute_to_attributevalues[attribute_value.attribute_id].append(
- attribute_value
- )
- return [attribute_to_attributevalues[attribute_id] for attribute_id in keys]
-
-
-class AttributesByAttributeId(DataLoader):
- context_key = "attributes_by_id"
-
- def batch_load(self, keys):
- attributes = Attribute.objects.in_bulk(keys)
- return [attributes.get(key) for key in keys]
-
-
class BaseProductAttributesByProductTypeIdLoader(DataLoader):
"""Loads product attributes by product type ID."""
@@ -185,14 +164,6 @@ class AssignedVariantAttributesByProductVariantId(DataLoader):
return [variant_attributes[variant_id] for variant_id in keys]
-class AttributeValueByIdLoader(DataLoader):
- context_key = "attributevalue_by_id"
-
- def batch_load(self, keys):
- attribute_values = AttributeValue.objects.in_bulk(keys)
- return [attribute_values.get(attribute_value_id) for attribute_value_id in keys]
-
-
class AttributeValuesByAssignedProductAttributeIdLoader(DataLoader):
context_key = "attributevalues_by_assignedproductattribute"
diff --git a/saleor/graphql/product/enums.py b/saleor/graphql/product/enums.py
index 706657f41b..a994a4a43d 100644
--- a/saleor/graphql/product/enums.py
+++ b/saleor/graphql/product/enums.py
@@ -1,23 +1,11 @@
import graphene
-from ...product import AttributeInputType
-from ..core.enums import to_enum
-AttributeInputTypeEnum = to_enum(AttributeInputType)
-
-
-class AttributeTypeEnum(graphene.Enum):
+class ProductAttributeType(graphene.Enum):
PRODUCT = "PRODUCT"
VARIANT = "VARIANT"
-class AttributeValueType(graphene.Enum):
- COLOR = "COLOR"
- GRADIENT = "GRADIENT"
- URL = "URL"
- STRING = "STRING"
-
-
class StockAvailability(graphene.Enum):
IN_STOCK = "AVAILABLE"
OUT_OF_STOCK = "OUT_OF_STOCK"
diff --git a/saleor/graphql/product/filters.py b/saleor/graphql/product/filters.py
index 72d80626e1..32f0634c8a 100644
--- a/saleor/graphql/product/filters.py
+++ b/saleor/graphql/product/filters.py
@@ -7,29 +7,20 @@ from django.db.models import Exists, F, OuterRef, Q, Subquery, Sum
from django.db.models.functions import Coalesce
from graphene_django.filter import GlobalIDFilter, GlobalIDMultipleChoiceFilter
-from ...product.models import (
+from ...attribute.models import (
AssignedProductAttribute,
AssignedVariantAttribute,
Attribute,
- Category,
- Collection,
- Product,
- ProductType,
- ProductVariant,
)
+from ...product.models import Category, Collection, Product, ProductType, ProductVariant
from ...search.backends import picker
from ...warehouse.models import Stock
from ..channel.filters import get_channel_slug_from_filter_data
from ..core.filters import EnumFilter, ListObjectTypeFilter, ObjectTypeFilter
from ..core.types import ChannelFilterInputObjectType, FilterInputObjectType
from ..core.types.common import IntRangeInput, PriceRangeInput
-from ..core.utils import from_global_id_strict_type
-from ..utils import (
- get_nodes,
- get_user_or_app_from_context,
- resolve_global_ids_to_primary_keys,
-)
-from ..utils.filters import filter_by_query_param, filter_range_field
+from ..utils import get_nodes, resolve_global_ids_to_primary_keys
+from ..utils.filters import filter_fields_containing_value, filter_range_field
from ..warehouse import types as warehouse_types
from .enums import (
CollectionPublished,
@@ -39,17 +30,6 @@ from .enums import (
)
-def filter_fields_containing_value(*search_fields: str):
- """Create a icontains filters through given fields on a given query set object."""
-
- def _filter_qs(qs, _, value):
- if value:
- qs = filter_by_query_param(qs, value, search_fields)
- return qs
-
- return _filter_qs
-
-
def _clean_product_attributes_filter_input(
filter_value,
) -> Dict[int, List[Optional[int]]]:
@@ -251,44 +231,6 @@ def filter_product_type(qs, _, value):
return qs
-def filter_attributes_by_product_types(qs, field, value, requestor, channel_slug):
- if not value:
- return qs
-
- product_qs = Product.objects.visible_to_user(requestor, channel_slug)
-
- if field == "in_category":
- category_id = from_global_id_strict_type(
- value, only_type="Category", field=field
- )
- category = Category.objects.filter(pk=category_id).first()
-
- if category is None:
- return qs.none()
-
- tree = category.get_descendants(include_self=True)
- product_qs = product_qs.filter(category__in=tree)
-
- if not product_qs.user_has_access_to_all(requestor):
- product_qs = product_qs.annotate_visible_in_listings(channel_slug).exclude(
- visible_in_listings=False
- )
-
- elif field == "in_collection":
- collection_id = from_global_id_strict_type(
- value, only_type="Collection", field=field
- )
- product_qs = product_qs.filter(collections__id=collection_id)
-
- else:
- raise NotImplementedError(f"Filtering by {field} is unsupported")
-
- product_types = set(product_qs.values_list("product_type_id", flat=True))
- return qs.filter(
- Q(product_types__in=product_types) | Q(product_variant_types__in=product_types)
- )
-
-
def filter_stocks(qs, _, value):
warehouse_ids = value.get("warehouse_ids")
quantity = value.get("quantity")
@@ -359,7 +301,7 @@ class ProductFilter(django_filters.FilterSet):
field_name="minimal_price_amount",
)
attributes = ListObjectTypeFilter(
- input_class="saleor.graphql.product.types.attributes.AttributeInput",
+ input_class="saleor.graphql.attribute.types.AttributeInput",
method=filter_attributes,
)
stock_availability = EnumFilter(
@@ -459,42 +401,6 @@ class ProductTypeFilter(django_filters.FilterSet):
fields = ["search", "configurable", "product_type"]
-class AttributeFilter(django_filters.FilterSet):
- # Search by attribute name and slug
- search = django_filters.CharFilter(
- method=filter_fields_containing_value("slug", "name")
- )
- ids = GlobalIDMultipleChoiceFilter(field_name="id")
-
- in_collection = GlobalIDFilter(method="filter_in_collection")
- in_category = GlobalIDFilter(method="filter_in_category")
-
- class Meta:
- model = Attribute
- fields = [
- "value_required",
- "is_variant_only",
- "visible_in_storefront",
- "filterable_in_storefront",
- "filterable_in_dashboard",
- "available_in_grid",
- ]
-
- def filter_in_collection(self, queryset, name, value):
- requestor = get_user_or_app_from_context(self.request)
- channel_slug = get_channel_slug_from_filter_data(self.data)
- return filter_attributes_by_product_types(
- queryset, name, value, requestor, channel_slug
- )
-
- def filter_in_category(self, queryset, name, value):
- requestor = get_user_or_app_from_context(self.request)
- channel_slug = get_channel_slug_from_filter_data(self.data)
- return filter_attributes_by_product_types(
- queryset, name, value, requestor, channel_slug
- )
-
-
class ProductFilterInput(ChannelFilterInputObjectType):
class Meta:
filterset_class = ProductFilter
@@ -518,8 +424,3 @@ class CategoryFilterInput(FilterInputObjectType):
class ProductTypeFilterInput(FilterInputObjectType):
class Meta:
filterset_class = ProductTypeFilter
-
-
-class AttributeFilterInput(ChannelFilterInputObjectType):
- class Meta:
- filterset_class = AttributeFilter
diff --git a/saleor/graphql/product/mutations/attributes.py b/saleor/graphql/product/mutations/attributes.py
index 84e0509f3b..fd3c179ead 100644
--- a/saleor/graphql/product/mutations/attributes.py
+++ b/saleor/graphql/product/mutations/attributes.py
@@ -1,284 +1,34 @@
+from collections import defaultdict
from typing import List
import graphene
from django.core.exceptions import ObjectDoesNotExist, ValidationError
from django.db import transaction
from django.db.models import Q
-from django.utils.text import slugify
-from ....core.permissions import ProductPermissions, ProductTypePermissions
-from ....product import AttributeInputType, models
+from ....attribute import AttributeInputType, AttributeType, models as attribute_models
+from ....core.permissions import ProductTypePermissions
+from ....product import models
from ....product.error_codes import ProductErrorCode
-from ...core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation
+from ...attribute.mutations import BaseReorderAttributesMutation
+from ...attribute.types import Attribute
+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,
- validate_slug_and_generate_if_needed,
-)
+from ...core.utils import from_global_id_strict_type
from ...core.utils.reordering import perform_reordering
from ...product.types import ProductType
-from ..descriptions import AttributeDescriptions, AttributeValueDescriptions
-from ..enums import AttributeInputTypeEnum, AttributeTypeEnum
-from ..types import Attribute, AttributeValue
-from .common import ReorderInput
+from ..enums import ProductAttributeType
-class AttributeValueCreateInput(graphene.InputObjectType):
- name = graphene.String(required=True, description=AttributeValueDescriptions.NAME)
-
-
-class AttributeCreateInput(graphene.InputObjectType):
- input_type = AttributeInputTypeEnum(description=AttributeDescriptions.INPUT_TYPE)
- name = graphene.String(required=True, description=AttributeDescriptions.NAME)
- slug = graphene.String(required=False, description=AttributeDescriptions.SLUG)
- values = graphene.List(
- AttributeValueCreateInput, description=AttributeDescriptions.VALUES
- )
- value_required = graphene.Boolean(description=AttributeDescriptions.VALUE_REQUIRED)
- is_variant_only = graphene.Boolean(
- required=False, description=AttributeDescriptions.IS_VARIANT_ONLY
- )
- visible_in_storefront = graphene.Boolean(
- description=AttributeDescriptions.VISIBLE_IN_STOREFRONT
- )
- filterable_in_storefront = graphene.Boolean(
- description=AttributeDescriptions.FILTERABLE_IN_STOREFRONT
- )
- filterable_in_dashboard = graphene.Boolean(
- description=AttributeDescriptions.FILTERABLE_IN_DASHBOARD
- )
- storefront_search_position = graphene.Int(
- required=False, description=AttributeDescriptions.STOREFRONT_SEARCH_POSITION
- )
- available_in_grid = graphene.Boolean(
- required=False, description=AttributeDescriptions.AVAILABLE_IN_GRID
- )
-
-
-class AttributeUpdateInput(graphene.InputObjectType):
- name = graphene.String(description=AttributeDescriptions.NAME)
- slug = graphene.String(description=AttributeDescriptions.SLUG)
- remove_values = graphene.List(
- graphene.ID,
- name="removeValues",
- description="IDs of values to be removed from this attribute.",
- )
- add_values = graphene.List(
- AttributeValueCreateInput,
- name="addValues",
- description="New values to be created for this attribute.",
- )
- value_required = graphene.Boolean(description=AttributeDescriptions.VALUE_REQUIRED)
- is_variant_only = graphene.Boolean(
- required=False, description=AttributeDescriptions.IS_VARIANT_ONLY
- )
- visible_in_storefront = graphene.Boolean(
- description=AttributeDescriptions.VISIBLE_IN_STOREFRONT
- )
- filterable_in_storefront = graphene.Boolean(
- description=AttributeDescriptions.FILTERABLE_IN_STOREFRONT
- )
- filterable_in_dashboard = graphene.Boolean(
- description=AttributeDescriptions.FILTERABLE_IN_DASHBOARD
- )
- storefront_search_position = graphene.Int(
- required=False, description=AttributeDescriptions.STOREFRONT_SEARCH_POSITION
- )
- available_in_grid = graphene.Boolean(
- required=False, description=AttributeDescriptions.AVAILABLE_IN_GRID
- )
-
-
-class AttributeAssignInput(graphene.InputObjectType):
+class ProductAttributeAssignInput(graphene.InputObjectType):
id = graphene.ID(required=True, description="The ID of the attribute to assign.")
- type = AttributeTypeEnum(
+ type = ProductAttributeType(
required=True, description="The attribute type to be assigned as."
)
-class AttributeMixin:
- @classmethod
- def check_values_are_unique(cls, values_input, attribute):
- # Check values uniqueness in case of creating new attribute.
- existing_values = attribute.values.values_list("slug", flat=True)
- for value_data in values_input:
- slug = slugify(value_data["name"], allow_unicode=True)
- if slug in existing_values:
- msg = (
- "Value %s already exists within this attribute."
- % value_data["name"]
- )
- raise ValidationError(
- {
- cls.ATTRIBUTE_VALUES_FIELD: ValidationError(
- msg, code=ProductErrorCode.ALREADY_EXISTS
- )
- }
- )
-
- new_slugs = [
- slugify(value_data["name"], allow_unicode=True)
- for value_data in values_input
- ]
- if len(set(new_slugs)) != len(new_slugs):
- raise ValidationError(
- {
- cls.ATTRIBUTE_VALUES_FIELD: ValidationError(
- "Provided values are not unique.", code=ProductErrorCode.UNIQUE
- )
- }
- )
-
- @classmethod
- def clean_values(cls, cleaned_input, attribute):
- """Clean attribute values.
-
- Transforms AttributeValueCreateInput into AttributeValue instances.
- Slugs are created from given names and checked for uniqueness within
- an attribute.
- """
- values_input = cleaned_input.get(cls.ATTRIBUTE_VALUES_FIELD)
-
- if values_input is None:
- return
-
- for value_data in values_input:
- value_data["slug"] = slugify(value_data["name"], allow_unicode=True)
- attribute_value = models.AttributeValue(**value_data, attribute=attribute)
- try:
- attribute_value.full_clean()
- except ValidationError as validation_errors:
- for field, err in validation_errors.error_dict.items():
- if field == "attribute":
- continue
- raise ValidationError({cls.ATTRIBUTE_VALUES_FIELD: err})
- cls.check_values_are_unique(values_input, attribute)
-
- @classmethod
- def clean_attribute(cls, instance, cleaned_input):
- try:
- cleaned_input = validate_slug_and_generate_if_needed(
- instance, "name", cleaned_input
- )
- except ValidationError as error:
- error.code = ProductErrorCode.REQUIRED.value
- raise ValidationError({"slug": error})
-
- return cleaned_input
-
- @classmethod
- def _save_m2m(cls, info, attribute, cleaned_data):
- super()._save_m2m(info, attribute, cleaned_data)
- values = cleaned_data.get(cls.ATTRIBUTE_VALUES_FIELD) or []
- for value in values:
- attribute.values.create(**value)
-
-
-class AttributeCreate(AttributeMixin, ModelMutation):
- # Needed by AttributeMixin,
- # represents the input name for the passed list of values
- ATTRIBUTE_VALUES_FIELD = "values"
-
- attribute = graphene.Field(Attribute, description="The created attribute.")
-
- class Arguments:
- input = AttributeCreateInput(
- required=True, description="Fields required to create an attribute."
- )
-
- class Meta:
- model = models.Attribute
- description = "Creates an attribute."
- permissions = (ProductTypePermissions.MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES,)
- error_type_class = ProductError
- error_type_field = "product_errors"
-
- @classmethod
- def perform_mutation(cls, _root, info, **data):
- instance = models.Attribute()
-
- # Do cleaning and uniqueness checks
- cleaned_input = cls.clean_input(info, instance, data.get("input"))
- cls.clean_attribute(instance, cleaned_input)
- cls.clean_values(cleaned_input, instance)
-
- # Construct the attribute
- instance = cls.construct_instance(instance, cleaned_input)
- cls.clean_instance(info, instance)
-
- # Commit it
- instance.save()
- cls._save_m2m(info, instance, cleaned_input)
-
- # Return the attribute that was created
- return AttributeCreate(attribute=instance)
-
-
-class AttributeUpdate(AttributeMixin, ModelMutation):
- # Needed by AttributeMixin,
- # represents the input name for the passed list of values
- ATTRIBUTE_VALUES_FIELD = "add_values"
-
- attribute = graphene.Field(Attribute, description="The updated attribute.")
-
- class Arguments:
- id = graphene.ID(required=True, description="ID of an attribute to update.")
- input = AttributeUpdateInput(
- required=True, description="Fields required to update an attribute."
- )
-
- class Meta:
- model = models.Attribute
- description = "Updates attribute."
- permissions = (ProductTypePermissions.MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES,)
- error_type_class = ProductError
- error_type_field = "product_errors"
-
- @classmethod
- def clean_remove_values(cls, cleaned_input, instance):
- """Check if the values to be removed are assigned to the given attribute."""
- remove_values = cleaned_input.get("remove_values", [])
- for value in remove_values:
- if value.attribute != instance:
- msg = "Value %s does not belong to this attribute." % value
- raise ValidationError(
- {
- "remove_values": ValidationError(
- msg, code=ProductErrorCode.INVALID
- )
- }
- )
- return remove_values
-
- @classmethod
- def _save_m2m(cls, info, instance, cleaned_data):
- super()._save_m2m(info, instance, cleaned_data)
- for attribute_value in cleaned_data.get("remove_values", []):
- attribute_value.delete()
-
- @classmethod
- def perform_mutation(cls, _root, info, id, input):
- instance = cls.get_node_or_error(info, id, only_type=Attribute)
-
- # Do cleaning and uniqueness checks
- cleaned_input = cls.clean_input(info, instance, input)
- cls.clean_attribute(instance, cleaned_input)
- cls.clean_values(cleaned_input, instance)
- cls.clean_remove_values(cleaned_input, instance)
-
- # Construct the attribute
- instance = cls.construct_instance(instance, cleaned_input)
- cls.clean_instance(info, instance)
-
- # Commit it
- instance.save()
- cls._save_m2m(info, instance, cleaned_input)
-
- # Return the attribute that was created
- return AttributeUpdate(attribute=instance)
-
-
-class AttributeAssign(BaseMutation):
+class ProductAttributeAssign(BaseMutation):
product_type = graphene.Field(ProductType, description="The updated product type.")
class Arguments:
@@ -287,7 +37,7 @@ class AttributeAssign(BaseMutation):
description="ID of the product type to assign the attributes into.",
)
operations = graphene.List(
- AttributeAssignInput,
+ ProductAttributeAssignInput,
required=True,
description="The operations to perform.",
)
@@ -304,7 +54,7 @@ class AttributeAssign(BaseMutation):
)
@classmethod
- def get_operations(cls, info, operations: List[AttributeAssignInput]):
+ def get_operations(cls, info, operations: List[ProductAttributeAssignInput]):
"""Resolve all passed global ids into integer PKs of the Attribute type."""
product_attrs_pks = []
variant_attrs_pks = []
@@ -313,101 +63,135 @@ class AttributeAssign(BaseMutation):
pk = from_global_id_strict_type(
operation.id, only_type=Attribute, field="operations"
)
- if operation.type == AttributeTypeEnum.PRODUCT:
+ if operation.type == ProductAttributeType.PRODUCT:
product_attrs_pks.append(pk)
else:
variant_attrs_pks.append(pk)
return product_attrs_pks, variant_attrs_pks
+ @classmethod
+ def check_attributes_types(cls, errors, product_attrs_pks, variant_attrs_pks):
+ """Ensure the attributes are product attributes."""
+
+ not_valid_attributes = attribute_models.Attribute.objects.filter(
+ Q(pk__in=product_attrs_pks) | Q(pk__in=variant_attrs_pks)
+ ).exclude(type=AttributeType.PRODUCT_TYPE)
+
+ if not_valid_attributes:
+ not_valid_attr_ids = [
+ graphene.Node.to_global_id("Attribute", attr.pk)
+ for attr in not_valid_attributes
+ ]
+ error = ValidationError(
+ "Only product attributes can be assigned.",
+ code=ProductErrorCode.INVALID.value,
+ params={"attributes": not_valid_attr_ids},
+ )
+ errors["operations"].append(error)
+
@classmethod
def check_operations_not_assigned_already(
- cls, product_type, product_attrs_pks, variant_attrs_pks
+ cls, errors, product_type, product_attrs_pks, variant_attrs_pks
):
qs = (
- models.Attribute.objects.get_assigned_attributes(product_type.pk)
- .values_list("name", "slug")
+ attribute_models.Attribute.objects.get_assigned_product_type_attributes(
+ product_type.pk
+ )
+ .values_list("pk", "name", "slug")
.filter(Q(pk__in=product_attrs_pks) | Q(pk__in=variant_attrs_pks))
)
invalid_attributes = list(qs)
if invalid_attributes:
- msg = ", ".join([f"{name} ({slug})" for name, slug in invalid_attributes])
- raise ValidationError(
- {
- "operations": ValidationError(
- (f"{msg} have already been assigned to this product type."),
- code=ProductErrorCode.ATTRIBUTE_ALREADY_ASSIGNED,
- )
- }
+ msg = ", ".join(
+ [f"{name} ({slug})" for _, name, slug in invalid_attributes]
)
+ invalid_attr_ids = [
+ graphene.Node.to_global_id("Attribute", attr[0])
+ for attr in invalid_attributes
+ ]
+ error = ValidationError(
+ (f"{msg} have already been assigned to this product type."),
+ code=ProductErrorCode.ATTRIBUTE_ALREADY_ASSIGNED,
+ params={"attributes": invalid_attr_ids},
+ )
+ errors["operations"].append(error)
# check if attributes' input type is assignable to variants
- is_not_assignable_to_variant = models.Attribute.objects.filter(
+ not_assignable_to_variant = attribute_models.Attribute.objects.filter(
Q(pk__in=variant_attrs_pks)
& Q(input_type__in=AttributeInputType.NON_ASSIGNABLE_TO_VARIANTS)
- ).exists()
+ )
- if is_not_assignable_to_variant:
- raise ValidationError(
- {
- "operations": ValidationError(
- (
- f"Attributes having for input types "
- f"{AttributeInputType.NON_ASSIGNABLE_TO_VARIANTS} "
- f"cannot be assigned as variant attributes"
- ),
- code=ProductErrorCode.ATTRIBUTE_CANNOT_BE_ASSIGNED,
- )
- }
+ if not_assignable_to_variant:
+ not_assignable_attr_ids = [
+ graphene.Node.to_global_id("Attribute", attr.pk)
+ for attr in not_assignable_to_variant
+ ]
+ error = ValidationError(
+ (
+ f"Attributes having for input types "
+ f"{AttributeInputType.NON_ASSIGNABLE_TO_VARIANTS} "
+ f"cannot be assigned as variant attributes"
+ ),
+ code=ProductErrorCode.ATTRIBUTE_CANNOT_BE_ASSIGNED,
+ params={"attributes": not_assignable_attr_ids},
)
+ errors["operations"].append(error)
@classmethod
- def check_product_operations_are_assignable(cls, product_attrs_pks):
- contains_restricted_attributes = models.Attribute.objects.filter(
+ def check_product_operations_are_assignable(cls, errors, product_attrs_pks):
+ restricted_attributes = attribute_models.Attribute.objects.filter(
pk__in=product_attrs_pks, is_variant_only=True
- ).exists()
+ )
- if contains_restricted_attributes:
- raise ValidationError(
- {
- "operations": ValidationError(
- "Cannot assign variant only attributes.",
- code=ProductErrorCode.ATTRIBUTE_CANNOT_BE_ASSIGNED,
- )
- }
+ if restricted_attributes:
+ restricted_attr_ids = [
+ graphene.Node.to_global_id("Attribute", attr.pk)
+ for attr in restricted_attributes
+ ]
+ error = ValidationError(
+ "Cannot assign variant only attributes.",
+ code=ProductErrorCode.ATTRIBUTE_CANNOT_BE_ASSIGNED,
+ params={"attributes": restricted_attr_ids},
)
+ errors["operations"].append(error)
@classmethod
def clean_operations(cls, product_type, product_attrs_pks, variant_attrs_pks):
"""Ensure the attributes are not already assigned to the product type."""
+ errors = defaultdict(list)
+
attrs_pk = product_attrs_pks + variant_attrs_pks
- attributes = models.Attribute.objects.filter(id__in=attrs_pk).values_list(
- "pk", flat=True
- )
+ attributes = attribute_models.Attribute.objects.filter(
+ id__in=attrs_pk
+ ).values_list("pk", flat=True)
if len(attrs_pk) != len(attributes):
invalid_attrs = set(attrs_pk) - set(attributes)
invalid_attrs = [
graphene.Node.to_global_id("Attribute", pk) for pk in invalid_attrs
]
- raise ValidationError(
- {
- "operations": ValidationError(
- "Attribute doesn't exist.",
- code=ProductErrorCode.NOT_FOUND,
- params={"attributes": list(invalid_attrs)},
- )
- }
+ error = ValidationError(
+ "Attribute doesn't exist.",
+ code=ProductErrorCode.NOT_FOUND,
+ params={"attributes": list(invalid_attrs)},
)
- cls.check_product_operations_are_assignable(product_attrs_pks)
+ errors["operations"].append(error)
+
+ cls.check_attributes_types(errors, product_attrs_pks, variant_attrs_pks)
+ cls.check_product_operations_are_assignable(errors, product_attrs_pks)
cls.check_operations_not_assigned_already(
- product_type, product_attrs_pks, variant_attrs_pks
+ errors, product_type, product_attrs_pks, variant_attrs_pks
)
+ if errors:
+ raise ValidationError(errors)
+
@classmethod
def save_field_values(cls, product_type, model_name, pks):
"""Add in bulk the PKs to assign to a given product type."""
- model = getattr(models, model_name)
+ model = getattr(attribute_models, model_name)
for pk in pks:
model.objects.create(product_type=product_type, attribute_id=pk)
@@ -415,7 +199,7 @@ class AttributeAssign(BaseMutation):
@transaction.atomic()
def perform_mutation(cls, _root, info, **data):
product_type_id: str = data["product_type_id"]
- operations: List[AttributeAssignInput] = data["operations"]
+ operations: List[ProductAttributeAssignInput] = data["operations"]
# Retrieve the requested product type
product_type: models.ProductType = graphene.Node.get_node_from_global_id(
info, product_type_id, only_type=ProductType
@@ -444,18 +228,20 @@ class AttributeAssign(BaseMutation):
return cls(product_type=product_type)
-class AttributeUnassign(BaseMutation):
+class ProductAttributeUnassign(BaseMutation):
product_type = graphene.Field(ProductType, description="The updated product type.")
class Arguments:
product_type_id = graphene.ID(
required=True,
- description="ID of the product type to assign the attributes into.",
+ description=(
+ "ID of the product type from which the attributes should be unassigned."
+ ),
)
attribute_ids = graphene.List(
graphene.ID,
required=True,
- description="The IDs of the attributes to assign.",
+ description="The IDs of the attributes to unassign.",
)
class Meta:
@@ -498,134 +284,7 @@ class AttributeUnassign(BaseMutation):
return cls(product_type=product_type)
-class AttributeDelete(ModelDeleteMutation):
- class Arguments:
- id = graphene.ID(required=True, description="ID of an attribute to delete.")
-
- class Meta:
- model = models.Attribute
- description = "Deletes an attribute."
- permissions = (ProductTypePermissions.MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES,)
- error_type_class = ProductError
- error_type_field = "product_errors"
-
-
-def validate_value_is_unique(attribute: models.Attribute, value: models.AttributeValue):
- """Check if the attribute value is unique within the attribute it belongs to."""
- duplicated_values = attribute.values.exclude(pk=value.pk).filter(slug=value.slug)
- if duplicated_values.exists():
- raise ValidationError(
- {
- "name": ValidationError(
- f"Value with slug {value.slug} already exists.",
- code=ProductErrorCode.ALREADY_EXISTS.value,
- )
- }
- )
-
-
-class AttributeValueCreate(ModelMutation):
- attribute = graphene.Field(Attribute, description="The updated attribute.")
-
- class Arguments:
- attribute_id = graphene.ID(
- required=True,
- name="attribute",
- description="Attribute to which value will be assigned.",
- )
- input = AttributeValueCreateInput(
- required=True, description="Fields required to create an AttributeValue."
- )
-
- class Meta:
- model = models.AttributeValue
- description = "Creates a value for an attribute."
- permissions = (ProductPermissions.MANAGE_PRODUCTS,)
- error_type_class = ProductError
- error_type_field = "product_errors"
-
- @classmethod
- def clean_input(cls, info, instance, data):
- cleaned_input = super().clean_input(info, instance, data)
- cleaned_input["slug"] = slugify(cleaned_input["name"], allow_unicode=True)
- return cleaned_input
-
- @classmethod
- def clean_instance(cls, info, instance):
- validate_value_is_unique(instance.attribute, instance)
- super().clean_instance(info, instance)
-
- @classmethod
- def perform_mutation(cls, _root, info, attribute_id, input):
- attribute = cls.get_node_or_error(info, attribute_id, only_type=Attribute)
- instance = models.AttributeValue(attribute=attribute)
- cleaned_input = cls.clean_input(info, instance, input)
- instance = cls.construct_instance(instance, cleaned_input)
- cls.clean_instance(info, instance)
-
- instance.save()
- cls._save_m2m(info, instance, cleaned_input)
- return AttributeValueCreate(attribute=attribute, attributeValue=instance)
-
-
-class AttributeValueUpdate(ModelMutation):
- attribute = graphene.Field(Attribute, description="The updated attribute.")
-
- class Arguments:
- id = graphene.ID(
- required=True, description="ID of an AttributeValue to update."
- )
- input = AttributeValueCreateInput(
- required=True, description="Fields required to update an AttributeValue."
- )
-
- class Meta:
- model = models.AttributeValue
- description = "Updates value of an attribute."
- permissions = (ProductTypePermissions.MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES,)
- error_type_class = ProductError
- error_type_field = "product_errors"
-
- @classmethod
- def clean_input(cls, info, instance, data):
- cleaned_input = super().clean_input(info, instance, data)
- if "name" in cleaned_input:
- cleaned_input["slug"] = slugify(cleaned_input["name"], allow_unicode=True)
- return cleaned_input
-
- @classmethod
- def clean_instance(cls, info, instance):
- validate_value_is_unique(instance.attribute, instance)
- super().clean_instance(info, instance)
-
- @classmethod
- def success_response(cls, instance):
- response = super().success_response(instance)
- response.attribute = instance.attribute
- return response
-
-
-class AttributeValueDelete(ModelDeleteMutation):
- attribute = graphene.Field(Attribute, description="The updated attribute.")
-
- class Arguments:
- id = graphene.ID(required=True, description="ID of a value to delete.")
-
- class Meta:
- model = models.AttributeValue
- description = "Deletes a value of an attribute."
- permissions = (ProductTypePermissions.MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES,)
- error_type_class = ProductError
- error_type_field = "product_errors"
-
- @classmethod
- def success_response(cls, instance):
- response = super().success_response(instance)
- response.attribute = instance.attribute
- return response
-
-
-class ProductTypeReorderAttributes(BaseMutation):
+class ProductTypeReorderAttributes(BaseReorderAttributesMutation):
product_type = graphene.Field(
ProductType, description="Product type from which attributes are reordered."
)
@@ -640,7 +299,7 @@ class ProductTypeReorderAttributes(BaseMutation):
product_type_id = graphene.Argument(
graphene.ID, required=True, description="ID of a product type."
)
- type = AttributeTypeEnum(
+ type = ProductAttributeType(
required=True, description="The attribute type to reorder."
)
moves = graphene.List(
@@ -655,7 +314,7 @@ class ProductTypeReorderAttributes(BaseMutation):
product_type_id, only_type=ProductType, field="product_type_id"
)
- if type == AttributeTypeEnum.PRODUCT:
+ if type == ProductAttributeType.PRODUCT:
m2m_field = "attributeproduct"
else:
m2m_field = "attributevariant"
@@ -675,94 +334,14 @@ class ProductTypeReorderAttributes(BaseMutation):
)
attributes_m2m = getattr(product_type, m2m_field)
- operations = {}
- # Resolve the attributes
- for move_info in moves:
- attribute_pk = from_global_id_strict_type(
- move_info.id, only_type=Attribute, field="moves"
- )
-
- try:
- m2m_info = attributes_m2m.get(attribute_id=int(attribute_pk))
- except ObjectDoesNotExist:
- raise ValidationError(
- {
- "moves": ValidationError(
- f"Couldn't resolve to an attribute: {move_info.id}",
- code=ProductErrorCode.NOT_FOUND,
- )
- }
- )
- operations[m2m_info.pk] = move_info.sort_order
+ try:
+ operations = cls.prepare_operations(moves, attributes_m2m)
+ except ValidationError as error:
+ error.code = ProductErrorCode.NOT_FOUND.value
+ raise ValidationError({"moves": error})
with transaction.atomic():
perform_reordering(attributes_m2m, operations)
- return ProductTypeReorderAttributes(product_type=product_type)
-
-
-class AttributeReorderValues(BaseMutation):
- attribute = graphene.Field(
- Attribute, description="Attribute from which values are reordered."
- )
-
- class Meta:
- description = "Reorder the values of an attribute."
- permissions = (ProductTypePermissions.MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES,)
- error_type_class = ProductError
- error_type_field = "product_errors"
- class Arguments:
- 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, attribute_id, moves):
- pk = from_global_id_strict_type(
- attribute_id, only_type=Attribute, field="attribute_id"
- )
-
- try:
- attribute = models.Attribute.objects.prefetch_related("values").get(pk=pk)
- except ObjectDoesNotExist:
- raise ValidationError(
- {
- "attribute_id": ValidationError(
- f"Couldn't resolve to an attribute: {attribute_id}",
- code=ProductErrorCode.NOT_FOUND,
- )
- }
- )
-
- values_m2m = attribute.values
- operations = {}
-
- # Resolve the values
- for move_info in moves:
- value_pk = from_global_id_strict_type(
- move_info.id, only_type=AttributeValue, field="moves"
- )
-
- try:
- m2m_info = values_m2m.get(pk=int(value_pk))
- except ObjectDoesNotExist:
- raise ValidationError(
- {
- "moves": ValidationError(
- f"Couldn't resolve to an attribute value: {move_info.id}",
- code=ProductErrorCode.NOT_FOUND,
- )
- }
- )
- operations[m2m_info.pk] = move_info.sort_order
-
- with transaction.atomic():
- perform_reordering(values_m2m, operations)
- attribute.refresh_from_db(fields=["values"])
- return AttributeReorderValues(attribute=attribute)
+ return ProductTypeReorderAttributes(product_type=product_type)
diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.py
index 07e97997f9..7b6d3945ef 100644
--- a/saleor/graphql/product/mutations/products.py
+++ b/saleor/graphql/product/mutations/products.py
@@ -1,6 +1,6 @@
import datetime
from collections import defaultdict
-from typing import Iterable, List, Tuple, Union
+from typing import TYPE_CHECKING, Iterable, List, Tuple, Union
import graphene
from django.core.exceptions import ObjectDoesNotExist, ValidationError
@@ -10,9 +10,13 @@ from django.utils.text import slugify
from graphene.types import InputObjectType
from graphql_relay import from_global_id
+from ....attribute import AttributeType
+from ....attribute.utils import associate_attribute_values_to_instance
from ....core.exceptions import PermissionDenied
from ....core.permissions import ProductPermissions, ProductTypePermissions
from ....order import OrderStatus, models as order_models
+from ....page import models as page_models
+from ....page.error_codes import PageErrorCode
from ....product import models
from ....product.error_codes import CollectionErrorCode, ProductErrorCode
from ....product.tasks import (
@@ -26,11 +30,9 @@ from ....product.thumbnails import (
create_product_thumbnails,
)
from ....product.utils import delete_categories, get_products_ids_without_variants
-from ....product.utils.attributes import (
- associate_attribute_values_to_instance,
- generate_name_for_variant,
-)
+from ....product.utils.variants import generate_name_for_variant
from ...channel import ChannelContext
+from ...core.inputs import ReorderInput
from ...core.mutations import BaseMutation, ModelDeleteMutation, ModelMutation
from ...core.scalars import WeightScalar
from ...core.types import SeoInput, Upload
@@ -56,10 +58,12 @@ from ..utils import (
create_stocks,
get_used_attribute_values_for_variant,
get_used_variants_attribute_values,
- validate_attributes_input_for_product,
+ validate_attributes_input_for_product_and_page,
validate_attributes_input_for_variant,
)
-from .common import ReorderInput
+
+if TYPE_CHECKING:
+ from ....attribute import models as attribute_models
class CategoryInput(graphene.InputObjectType):
@@ -502,8 +506,8 @@ class ProductCreateInput(ProductInput):
)
-T_INPUT_MAP = List[Tuple[models.Attribute, List[str]]]
-T_INSTANCE = Union[models.Product, models.ProductVariant]
+T_INPUT_MAP = List[Tuple["attribute_models.Attribute", List[str]]]
+T_INSTANCE = Union[models.Product, models.ProductVariant, page_models.Page]
class AttributeAssignmentMixin:
@@ -533,7 +537,7 @@ class AttributeAssignmentMixin:
):
"""Retrieve attributes nodes from given global IDs and/or slugs."""
qs = qs.filter(Q(pk__in=pks) | Q(slug__in=slugs))
- nodes = list(qs) # type: List[models.Attribute]
+ nodes: List["attribute_models.Attribute"] = list(qs)
if not nodes:
raise ValidationError(
@@ -583,7 +587,9 @@ class AttributeAssignmentMixin:
return int(internal_id)
@classmethod
- def _pre_save_values(cls, attribute: models.Attribute, values: List[str]):
+ def _pre_save_values(
+ cls, attribute: "attribute_models.Attribute", values: List[str]
+ ):
"""Lazy-retrieve or create the database objects from the supplied raw values."""
get_or_create = attribute.values.get_or_create
return tuple(
@@ -596,37 +602,19 @@ class AttributeAssignmentMixin:
)
@classmethod
- def _check_input_for_product(cls, cleaned_input: T_INPUT_MAP, qs: QuerySet):
- """Check the cleaned attribute input for a product.
-
- An Attribute queryset is supplied.
+ def _validate_product_attributes_input(
+ cls, cleaned_input: T_INPUT_MAP, attribute_qs: QuerySet, is_variant: bool
+ ):
+ """Check if no invalid operations were supplied.
- - ensure all required attributes are passed
- - ensure the values are correct for a product
+ :raises ValidationError: when an invalid operation was found.
"""
- errors = validate_attributes_input_for_product(cleaned_input)
-
- supplied_attribute_pk = [attribute.pk for attribute, _ in cleaned_input]
-
- # Asserts all required attributes are supplied
- missing_required_attributes = qs.filter(
- Q(value_required=True) & ~Q(pk__in=supplied_attribute_pk)
- )
-
- if missing_required_attributes:
- ids = [
- graphene.Node.to_global_id("Attribute", attr.pk)
- for attr in missing_required_attributes
- ]
- error = ValidationError(
- "All attributes flagged as having a value required must be supplied.",
- code=ProductErrorCode.REQUIRED.value,
- params={"attributes": ids},
+ if is_variant:
+ return cls._check_input_for_variant(cleaned_input, attribute_qs)
+ else:
+ return cls._check_input_for_page_and_product(
+ cleaned_input, attribute_qs, False
)
- errors.append(error)
-
- if errors:
- raise ValidationError(errors)
@classmethod
def _check_input_for_variant(cls, cleaned_input: T_INPUT_MAP, qs: QuerySet):
@@ -647,21 +635,31 @@ class AttributeAssignmentMixin:
raise ValidationError(errors)
@classmethod
- def _validate_input(
- cls, cleaned_input: T_INPUT_MAP, attribute_qs, is_variant: bool
+ def _check_input_for_page_and_product(
+ cls, cleaned_input: T_INPUT_MAP, qs: QuerySet, is_page_attributes: bool
):
- """Check if no invalid operations were supplied.
+ """Check the cleaned attribute input for a product.
- :raises ValidationError: when an invalid operation was found.
+ An Attribute queryset is supplied.
+
+ - ensure all required attributes are passed
+ - ensure the values are correct for a product
"""
- if is_variant:
- return cls._check_input_for_variant(cleaned_input, attribute_qs)
- else:
- return cls._check_input_for_product(cleaned_input, attribute_qs)
+ error_codes_enum = PageErrorCode if is_page_attributes else ProductErrorCode
+ errors = validate_attributes_input_for_product_and_page(
+ cleaned_input, qs, error_codes_enum
+ )
+
+ if errors:
+ raise ValidationError(errors)
@classmethod
def clean_input(
- cls, raw_input: dict, attributes_qs: QuerySet, is_variant: bool
+ cls,
+ raw_input: dict,
+ attributes_qs: QuerySet,
+ is_variant: bool = False,
+ is_page_attributes: bool = False,
) -> T_INPUT_MAP:
"""Resolve and prepare the input for further checks.
@@ -669,6 +667,7 @@ class AttributeAssignmentMixin:
:param attributes_qs:
A queryset of attributes, the attribute values must be prefetched.
Prefetch is needed by ``_pre_save_values`` during save.
+ :param page_attributes: Whether the input is for page type or not.
:param is_variant: Whether the input is for a variant or a product.
:raises ValidationError: contain the message.
@@ -712,7 +711,13 @@ class AttributeAssignmentMixin:
key = slugs[attribute.slug]
cleaned_input.append((attribute, key))
- cls._validate_input(cleaned_input, attributes_qs, is_variant)
+
+ if is_page_attributes:
+ cls._check_input_for_page_and_product(cleaned_input, attributes_qs, True)
+ else:
+ cls._validate_product_attributes_input(
+ cleaned_input, attributes_qs, is_variant
+ )
return cleaned_input
@classmethod
@@ -1279,8 +1284,31 @@ class ProductTypeCreate(ModelMutation):
if tax_code:
info.context.plugins.assign_tax_code_to_object_meta(instance, tax_code)
+ cls.validate_attributes(cleaned_input)
+
return cleaned_input
+ @classmethod
+ def validate_attributes(cls, cleaned_data):
+ errors = {}
+ for field in ["product_attributes", "variant_attributes"]:
+ attributes = cleaned_data.get(field)
+ if not attributes:
+ continue
+ not_valid_attributes = [
+ graphene.Node.to_global_id("Attribute", attr.pk)
+ for attr in attributes
+ if attr.type != AttributeType.PRODUCT_TYPE
+ ]
+ if not_valid_attributes:
+ errors[field] = ValidationError(
+ "Only Product type attributes are allowed.",
+ code=ProductErrorCode.INVALID.value,
+ params={"attributes": not_valid_attributes},
+ )
+ if errors:
+ raise ValidationError(errors)
+
@classmethod
def _save_m2m(cls, info, instance, cleaned_data):
super()._save_m2m(info, instance, cleaned_data)
diff --git a/saleor/graphql/product/resolvers.py b/saleor/graphql/product/resolvers.py
index c918b8982f..5ec7678b8c 100644
--- a/saleor/graphql/product/resolvers.py
+++ b/saleor/graphql/product/resolvers.py
@@ -21,12 +21,6 @@ from ..utils.filters import filter_by_period
from .filters import filter_products_by_stock_availability
-def resolve_attributes(info, qs=None, **_kwargs):
- requestor = get_user_or_app_from_context(info.context)
- qs = qs or models.Attribute.objects.get_visible_to_user(requestor)
- return qs.distinct()
-
-
def resolve_category_by_slug(slug):
return models.Category.objects.filter(slug=slug).first()
diff --git a/saleor/graphql/product/schema.py b/saleor/graphql/product/schema.py
index b6a7d7c4cb..469cb517ae 100644
--- a/saleor/graphql/product/schema.py
+++ b/saleor/graphql/product/schema.py
@@ -13,15 +13,12 @@ from ..core.fields import (
from ..core.validators import validate_one_of_args_is_in_query
from ..decorators import permission_required
from ..translations.mutations import (
- AttributeTranslate,
- AttributeValueTranslate,
CategoryTranslate,
CollectionTranslate,
ProductTranslate,
ProductVariantTranslate,
)
from ..utils import get_user_or_app_from_context
-from .bulk_mutations.attributes import AttributeBulkDelete, AttributeValueBulkDelete
from .bulk_mutations.products import (
CategoryBulkDelete,
CollectionBulkDelete,
@@ -36,7 +33,6 @@ from .bulk_mutations.products import (
)
from .enums import StockAvailability
from .filters import (
- AttributeFilterInput,
CategoryFilterInput,
CollectionFilterInput,
ProductFilterInput,
@@ -44,15 +40,8 @@ from .filters import (
ProductVariantFilterInput,
)
from .mutations.attributes import (
- AttributeAssign,
- AttributeCreate,
- AttributeDelete,
- AttributeReorderValues,
- AttributeUnassign,
- AttributeUpdate,
- AttributeValueCreate,
- AttributeValueDelete,
- AttributeValueUpdate,
+ ProductAttributeAssign,
+ ProductAttributeUnassign,
ProductTypeReorderAttributes,
)
from .mutations.channels import (
@@ -95,7 +84,6 @@ from .mutations.products import (
VariantImageUnassign,
)
from .resolvers import (
- resolve_attributes,
resolve_categories,
resolve_category_by_slug,
resolve_collection_by_id,
@@ -112,14 +100,12 @@ from .resolvers import (
resolve_variant_by_id,
)
from .sorters import (
- AttributeSortingInput,
CategorySortingInput,
CollectionSortingInput,
ProductOrder,
ProductTypeSortingInput,
)
from .types import (
- Attribute,
Category,
Collection,
DigitalContent,
@@ -140,19 +126,6 @@ class ProductQueries(graphene.ObjectType):
digital_contents = PrefetchingConnectionField(
DigitalContent, description="List of digital content."
)
- attributes = FilterInputConnectionField(
- Attribute,
- description="List of the shop's attributes.",
- filter=AttributeFilterInput(description="Filtering options for attributes."),
- sort_by=AttributeSortingInput(description="Sorting options for attributes."),
- )
- attribute = graphene.Field(
- Attribute,
- id=graphene.Argument(
- graphene.ID, description="ID of the attribute.", required=True
- ),
- description="Look up an attribute by ID.",
- )
categories = FilterInputConnectionField(
Category,
filter=CategoryFilterInput(description="Filtering options for categories."),
@@ -263,12 +236,6 @@ class ProductQueries(graphene.ObjectType):
description="List of top selling products.",
)
- def resolve_attributes(self, info, **kwargs):
- return resolve_attributes(info, **kwargs)
-
- def resolve_attribute(self, info, id):
- return graphene.Node.get_node_from_global_id(info, id, Attribute)
-
def resolve_categories(self, info, level=None, **kwargs):
return resolve_categories(info, level=level, **kwargs)
@@ -399,20 +366,8 @@ class ProductQueries(graphene.ObjectType):
class ProductMutations(graphene.ObjectType):
- attribute_create = AttributeCreate.Field()
- attribute_delete = AttributeDelete.Field()
- attribute_bulk_delete = AttributeBulkDelete.Field()
- attribute_assign = AttributeAssign.Field()
- attribute_unassign = AttributeUnassign.Field()
- attribute_update = AttributeUpdate.Field()
- attribute_translate = AttributeTranslate.Field()
-
- attribute_value_create = AttributeValueCreate.Field()
- attribute_value_delete = AttributeValueDelete.Field()
- attribute_value_bulk_delete = AttributeValueBulkDelete.Field()
- attribute_value_update = AttributeValueUpdate.Field()
- attribute_value_translate = AttributeValueTranslate.Field()
- attribute_reorder_values = AttributeReorderValues.Field()
+ product_attribute_assign = ProductAttributeAssign.Field()
+ product_attribute_unassign = ProductAttributeUnassign.Field()
category_create = CategoryCreate.Field()
category_delete = CategoryDelete.Field()
diff --git a/saleor/graphql/product/sorters.py b/saleor/graphql/product/sorters.py
index 7c1099127b..8e39ebc9d4 100644
--- a/saleor/graphql/product/sorters.py
+++ b/saleor/graphql/product/sorters.py
@@ -25,57 +25,6 @@ from ..channel.sorters import validate_channel_slug
from ..core.types import ChannelSortInputObjectType, SortInputObjectType
-class AttributeSortField(graphene.Enum):
- NAME = ["name", "slug"]
- SLUG = ["slug"]
- VALUE_REQUIRED = ["value_required", "name", "slug"]
- IS_VARIANT_ONLY = ["is_variant_only", "name", "slug"]
- VISIBLE_IN_STOREFRONT = ["visible_in_storefront", "name", "slug"]
- FILTERABLE_IN_STOREFRONT = ["filterable_in_storefront", "name", "slug"]
- FILTERABLE_IN_DASHBOARD = ["filterable_in_dashboard", "name", "slug"]
- STOREFRONT_SEARCH_POSITION = ["storefront_search_position", "name", "pk"]
- AVAILABLE_IN_GRID = ["available_in_grid", "name", "pk"]
-
- @property
- def description(self):
- # pylint: disable=no-member
- descriptions = {
- AttributeSortField.NAME.name: "Sort attributes by name",
- AttributeSortField.SLUG.name: "Sort attributes by slug",
- AttributeSortField.VALUE_REQUIRED.name: (
- "Sort attributes by the value required flag"
- ),
- AttributeSortField.IS_VARIANT_ONLY.name: (
- "Sort attributes by the variant only flag"
- ),
- AttributeSortField.VISIBLE_IN_STOREFRONT.name: (
- "Sort attributes by visibility in the storefront"
- ),
- AttributeSortField.FILTERABLE_IN_STOREFRONT.name: (
- "Sort attributes by the filterable in storefront flag"
- ),
- AttributeSortField.FILTERABLE_IN_DASHBOARD.name: (
- "Sort attributes by the filterable in dashboard flag"
- ),
- AttributeSortField.STOREFRONT_SEARCH_POSITION.name: (
- "Sort attributes by their position in storefront"
- ),
- AttributeSortField.AVAILABLE_IN_GRID.name: (
- "Sort attributes based on whether they can be displayed "
- "or not in a product grid."
- ),
- }
- if self.name in descriptions:
- return descriptions[self.name]
- raise ValueError("Unsupported enum value: %s" % self.value)
-
-
-class AttributeSortingInput(SortInputObjectType):
- class Meta:
- sort_enum = AttributeSortField
- type_name = "attributes"
-
-
class CategorySortField(graphene.Enum):
NAME = ["name", "slug"]
PRODUCT_COUNT = ["product_count", "name", "slug"]
diff --git a/saleor/graphql/product/tests/test_attributes.py b/saleor/graphql/product/tests/test_attributes.py
index 7be4131af8..4e312335c5 100644
--- a/saleor/graphql/product/tests/test_attributes.py
+++ b/saleor/graphql/product/tests/test_attributes.py
@@ -1,169 +1,21 @@
-from typing import Union
from unittest import mock
import graphene
import pytest
-from django.core.exceptions import ValidationError
-from django.db.models import Q
-from django.utils.text import slugify
-from graphene.utils.str_converters import to_camel_case
-from ....product import AttributeInputType
-from ....product.error_codes import ProductErrorCode
-from ....product.models import (
+from ....attribute import AttributeInputType, AttributeType
+from ....attribute.models import (
Attribute,
AttributeProduct,
AttributeValue,
AttributeVariant,
- Category,
- Collection,
- Product,
- ProductType,
- ProductVariant,
)
-from ....product.utils.attributes import associate_attribute_values_to_instance
+from ....product.error_codes import ProductErrorCode
+from ....product.models import ProductType
+from ...attribute.enums import AttributeTypeEnum
from ...core.utils import snake_to_camel_case
from ...tests.utils import get_graphql_content
-from ..enums import AttributeTypeEnum, AttributeValueType
-from ..filters import filter_attributes_by_product_types
-from ..mutations.attributes import validate_value_is_unique
-from ..types.attributes import resolve_attribute_value_type
-
-
-def test_validate_value_is_unique(color_attribute):
- value = color_attribute.values.first()
-
- # a new value but with existing slug should raise an error
- with pytest.raises(ValidationError):
- validate_value_is_unique(color_attribute, AttributeValue(slug=value.slug))
-
- # a new value with a new slug should pass
- validate_value_is_unique(
- color_attribute, AttributeValue(slug="spanish-inquisition")
- )
-
- # value that already belongs to the attribute shouldn't be taken into account
- validate_value_is_unique(color_attribute, value)
-
-
-def test_get_single_attribute_by_pk(user_api_client, color_attribute_without_values):
- attribute_gql_id = graphene.Node.to_global_id(
- "Attribute", color_attribute_without_values.id
- )
- query = """
- query($id: ID!) {
- attribute(id: $id) {
- id
- slug
- }
- }
- """
- content = get_graphql_content(
- user_api_client.post_graphql(query, {"id": attribute_gql_id})
- )
-
- assert content["data"]["attribute"], "Should have found an attribute"
- assert content["data"]["attribute"]["id"] == attribute_gql_id
- assert content["data"]["attribute"]["slug"] == color_attribute_without_values.slug
-
-
-QUERY_ATTRIBUTES = """
- query {
- attributes(first: 20) {
- edges {
- node {
- id
- name
- slug
- values {
- id
- name
- slug
- }
- }
- }
- }
- }
-"""
-
-
-def test_attributes_query(user_api_client, product):
- attributes = Attribute.objects
- query = QUERY_ATTRIBUTES
- response = user_api_client.post_graphql(query)
- content = get_graphql_content(response)
- attributes_data = content["data"]["attributes"]["edges"]
- assert attributes_data
- assert len(attributes_data) == attributes.count()
-
-
-NOT_EXISTS_IDS_ATTRIBUTES_QUERY = """
- query ($filter: AttributeFilterInput!) {
- attributes(first: 5, filter: $filter) {
- edges {
- node {
- id
- name
- }
- }
- }
- }
-"""
-
-
-def test_attributes_query_ids_not_exists(user_api_client, category):
- query = NOT_EXISTS_IDS_ATTRIBUTES_QUERY
- variables = {"filter": {"ids": ["ygRqjpmXYqaTD9r=", "PBa4ZLBhnXHSz6v="]}}
- response = user_api_client.post_graphql(query, variables)
- content = get_graphql_content(response, ignore_errors=True)
- message_error = '{"ids": [{"message": "Invalid ID specified.", "code": ""}]}'
-
- assert len(content["errors"]) == 1
- assert content["errors"][0]["message"] == message_error
- assert content["data"]["attributes"] is None
-
-
-def test_attributes_query_hidden_attribute(user_api_client, product, color_attribute):
- query = QUERY_ATTRIBUTES
-
- # hide the attribute
- color_attribute.visible_in_storefront = False
- color_attribute.save(update_fields=["visible_in_storefront"])
-
- attribute_count = Attribute.objects.get_visible_to_user(
- user_api_client.user
- ).count()
- assert attribute_count == 1
-
- response = user_api_client.post_graphql(query)
- content = get_graphql_content(response)
- attributes_data = content["data"]["attributes"]["edges"]
- assert len(attributes_data) == attribute_count
-
-
-def test_attributes_query_hidden_attribute_as_staff_user(
- staff_api_client, product, color_attribute, permission_manage_products
-):
- query = QUERY_ATTRIBUTES
-
- # hide the attribute
- color_attribute.visible_in_storefront = False
- color_attribute.save(update_fields=["visible_in_storefront"])
-
- attribute_count = Attribute.objects.all().count()
-
- # The user doesn't have the permission yet to manage products,
- # the user shouldn't be able to see the hidden attributes
- assert Attribute.objects.get_visible_to_user(staff_api_client.user).count() == 1
-
- # The user should now be able to see the attributes
- staff_api_client.user.user_permissions.add(permission_manage_products)
-
- response = staff_api_client.post_graphql(query)
- content = get_graphql_content(response)
- attributes_data = content["data"]["attributes"]["edges"]
- assert len(attributes_data) == attribute_count
-
+from ..enums import ProductAttributeType
QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES = """
query ($channel: String){
@@ -173,6 +25,7 @@ QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES = """
attributes {
attribute {
slug
+ type
}
values {
slug
@@ -182,6 +35,7 @@ QUERY_PRODUCT_AND_VARIANTS_ATTRIBUTES = """
attributes {
attribute {
slug
+ type
}
values {
slug
@@ -272,10 +126,17 @@ def test_resolve_attribute_values(user_api_client, product, staff_user, channel_
assert len(variant_attributes) == len(variant_attribute_values)
assert product_attributes[0]["attribute"]["slug"] == "color"
+ assert (
+ product_attributes[0]["attribute"]["type"]
+ == AttributeTypeEnum.PRODUCT_TYPE.name
+ )
assert product_attributes[0]["values"][0]["slug"] == product_attribute_values[0]
assert variant_attributes[0]["attribute"]["slug"] == "size"
- assert variant_attributes[0]["values"][0]["slug"] == variant_attribute_values[0]
+ assert (
+ variant_attributes[0]["attribute"]["type"]
+ == AttributeTypeEnum.PRODUCT_TYPE.name
+ )
def test_resolve_attribute_values_non_assigned_to_node(
@@ -293,8 +154,12 @@ def test_resolve_attribute_values_non_assigned_to_node(
product_type = product.product_type
# Create dummy attributes
- unassigned_product_attribute = Attribute.objects.create(name="P", slug="product")
- unassigned_variant_attribute = Attribute.objects.create(name="V", slug="variant")
+ unassigned_product_attribute = Attribute.objects.create(
+ name="P", slug="product", type=AttributeType.PRODUCT_TYPE
+ )
+ unassigned_variant_attribute = Attribute.objects.create(
+ name="V", slug="variant", type=AttributeType.PRODUCT_TYPE
+ )
# Create a value for each dummy attribute to ensure they are not returned
# by the product or variant as they are not associated to them
@@ -334,2585 +199,712 @@ def test_resolve_attribute_values_non_assigned_to_node(
assert variant_attributes[0]["values"] == []
-def test_attributes_filter_by_product_type_with_empty_value():
- """Ensure passing an empty or null value is ignored and the queryset is simply
- returned without any modification.
- """
-
- qs = Attribute.objects.all()
-
- assert filter_attributes_by_product_types(qs, "...", "", None, None) is qs
- assert filter_attributes_by_product_types(qs, "...", None, None, None) is qs
-
-
-def test_attributes_filter_by_product_type_with_unsupported_field(
- customer_user, channel_USD
+def test_resolve_assigned_attribute_without_values(
+ api_client, product_type, product, channel_USD
):
- """Ensure using an unknown field to filter attributes by raises a NotImplemented
- exception.
+ """Ensure the attributes assigned to a product type are resolved even if
+ the product doesn't provide any value for it or is not directly associated to it.
"""
+ # Retrieve the product's variant
+ variant = product.variants.get()
- qs = Attribute.objects.all()
+ # Remove all attributes and values from the product and its variant
+ product.attributesrelated.clear()
+ variant.attributesrelated.clear()
- with pytest.raises(NotImplementedError) as exc:
- filter_attributes_by_product_types(
- qs, "in_space", "a-value", customer_user, channel_USD.slug
+ # Retrieve the product and variant's attributes
+ products = get_graphql_content(
+ api_client.post_graphql(
+ """
+ query ($channel: String) {
+ products(first: 10, channel: $channel) {
+ edges {
+ node {
+ attributes {
+ attribute {
+ slug
+ }
+ values {
+ name
+ }
+ }
+ variants {
+ attributes {
+ attribute {
+ slug
+ }
+ values {
+ name
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ """,
+ {"channel": channel_USD.slug},
)
+ )["data"]["products"]["edges"]
- assert exc.value.args == ("Filtering by in_space is unsupported",)
+ # Ensure we are only working on one product and variant, the ones we are testing
+ assert len(products) == 1
+ assert len(products[0]["node"]["variants"]) == 1
+ # Retrieve the nodes data
+ product = products[0]["node"]
+ variant = product["variants"][0]
-def test_attributes_filter_by_non_existing_category_id(customer_user, channel_USD):
- """Ensure using a non-existing category ID returns an empty query set."""
+ # Ensure the product attributes values are all None
+ assert len(product["attributes"]) == 1
+ assert product["attributes"][0]["attribute"]["slug"] == "color"
+ assert product["attributes"][0]["values"] == []
- category_id = graphene.Node.to_global_id("Category", -1)
- mocked_qs = mock.MagicMock()
- qs = filter_attributes_by_product_types(
- mocked_qs, "in_category", category_id, customer_user, channel_USD.slug
- )
- assert qs == mocked_qs.none.return_value
+ # Ensure the variant attributes values are all None
+ assert variant["attributes"][0]["attribute"]["slug"] == "size"
+ assert variant["attributes"][0]["values"] == []
[email protected]("tested_field", ["inCategory", "inCollection"])
-def test_attributes_in_collection_query(
- user_api_client,
- product_type,
- category,
- published_collection,
- collection_with_products,
- tested_field,
- channel_USD,
-):
- if "Collection" in tested_field:
- filtered_by_node_id = graphene.Node.to_global_id(
- "Collection", published_collection.pk
- )
- elif "Category" in tested_field:
- filtered_by_node_id = graphene.Node.to_global_id("Category", category.pk)
- else:
- raise AssertionError(tested_field)
- expected_qs = Attribute.objects.filter(
- Q(attributeproduct__product_type_id=product_type.pk)
- | Q(attributevariant__product_type_id=product_type.pk)
- )
+PRODUCT_ASSIGN_ATTR_QUERY = """
+ mutation assign($productTypeId: ID!, $operations: [ProductAttributeAssignInput]!) {
+ productAttributeAssign(productTypeId: $productTypeId, operations: $operations) {
+ productErrors {
+ field
+ code
+ message
+ attributes
+ }
+ productType {
+ id
+ productAttributes {
+ id
+ }
+ variantAttributes {
+ id
+ }
+ }
+ }
+ }
+"""
- # Create another product type and attribute that shouldn't get matched
- other_category = Category.objects.create(name="Other Category", slug="other-cat")
- other_attribute = Attribute.objects.create(name="Other", slug="other")
- other_product_type = ProductType.objects.create(
- name="Other type", has_variants=True, is_shipping_required=True
- )
- other_product_type.product_attributes.add(other_attribute)
- other_product = Product.objects.create(
- name="Another Product", product_type=other_product_type, category=other_category
- )
- # Create another collection with products but shouldn't get matched
- # as we don't look for this other collection
- other_collection = Collection.objects.create(
- name="Other Collection", slug="other-collection", description="Description",
- )
- other_collection.products.add(other_product)
+def test_assign_attributes_to_product_type(
+ staff_api_client,
+ permission_manage_product_types_and_attributes,
+ product_type_attribute_list,
+):
+ product_type = ProductType.objects.create(name="Default Type", has_variants=True)
+ product_type_global_id = graphene.Node.to_global_id("ProductType", product_type.pk)
- query = """
- query($nodeID: ID!, $channel: String) {
- attributes(first: 20, %(filter_input)s) {
- edges {
- node {
- id
- name
- slug
- }
- }
- }
- }
- """
+ query = PRODUCT_ASSIGN_ATTR_QUERY
+ operations = []
+ variables = {"productTypeId": product_type_global_id, "operations": operations}
- query = query % {
- "filter_input": "filter: { %s: $nodeID, channel: $channel }" % tested_field
- }
+ product_attributes_ids = {attr.pk for attr in product_type_attribute_list[:2]}
+ variant_attributes_ids = {attr.pk for attr in product_type_attribute_list[2:]}
- variables = {"nodeID": filtered_by_node_id, "channel": channel_USD.slug}
- content = get_graphql_content(user_api_client.post_graphql(query, variables))
- attributes_data = content["data"]["attributes"]["edges"]
+ for attr_id in product_attributes_ids:
+ operations.append(
+ {"type": "PRODUCT", "id": graphene.Node.to_global_id("Attribute", attr_id)}
+ )
- flat_attributes_data = [attr["node"]["slug"] for attr in attributes_data]
- expected_flat_attributes_data = list(expected_qs.values_list("slug", flat=True))
+ for attr_id in variant_attributes_ids:
+ operations.append(
+ {"type": "VARIANT", "id": graphene.Node.to_global_id("Attribute", attr_id)}
+ )
- assert flat_attributes_data == expected_flat_attributes_data
+ content = get_graphql_content(
+ staff_api_client.post_graphql(
+ query,
+ variables,
+ permissions=[permission_manage_product_types_and_attributes],
+ )
+ )["data"]["productAttributeAssign"]
+ assert not content["productErrors"], "Should have succeeded"
+ assert content["productType"]["id"] == product_type_global_id
+ assert len(content["productType"]["productAttributes"]) == len(
+ product_attributes_ids
+ )
+ assert len(content["productType"]["variantAttributes"]) == len(
+ variant_attributes_ids
+ )
-CREATE_ATTRIBUTES_QUERY = """
- mutation createAttribute(
- $name: String!, $slug: String, $values: [AttributeValueCreateInput]
- ){
- attributeCreate(input: {name: $name, values: $values, slug: $slug}) {
- errors {
- field
- message
- }
- productErrors {
- field
- message
- code
- }
- attribute {
- name
- slug
- values {
- name
- slug
- }
- productTypes(first: 10) {
- edges {
- node {
- id
- }
- }
- }
- }
- }
+ found_product_attrs_ids = {
+ int(graphene.Node.from_global_id(attr["id"])[1])
+ for attr in content["productType"]["productAttributes"]
+ }
+ found_variant_attrs_ids = {
+ int(graphene.Node.from_global_id(attr["id"])[1])
+ for attr in content["productType"]["variantAttributes"]
}
-"""
+ assert found_product_attrs_ids == product_attributes_ids
+ assert found_variant_attrs_ids == variant_attributes_ids
-def test_create_attribute_and_attribute_values(
- staff_api_client, permission_manage_product_types_and_attributes
+
+def test_assign_non_existing_attributes_to_product_type(
+ staff_api_client,
+ permission_manage_product_types_and_attributes,
+ product_type_attribute_list,
):
- query = CREATE_ATTRIBUTES_QUERY
+ product_type = ProductType.objects.create(name="Default Type", has_variants=True)
+ product_type_global_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+
+ query = PRODUCT_ASSIGN_ATTR_QUERY
+ attribute_id = graphene.Node.to_global_id("Attribute", "55511155593")
+ operations = [{"type": "PRODUCT", "id": attribute_id}]
+ variables = {"productTypeId": product_type_global_id, "operations": operations}
- attribute_name = "Example name"
- name = "Value name"
- variables = {"name": attribute_name, "values": [{"name": name}]}
response = staff_api_client.post_graphql(
query, variables, permissions=[permission_manage_product_types_and_attributes]
)
content = get_graphql_content(response)
- assert not content["data"]["attributeCreate"]["errors"]
- data = content["data"]["attributeCreate"]
-
- # Check if the attribute was correctly created
- assert data["attribute"]["name"] == attribute_name
- assert data["attribute"]["slug"] == slugify(
- attribute_name
- ), "The default slug should be the slugified name"
- assert (
- data["attribute"]["productTypes"]["edges"] == []
- ), "The attribute should not have been assigned to a product type"
-
- # Check if the attribute values were correctly created
- assert len(data["attribute"]["values"]) == 1
- assert data["attribute"]["values"][0]["name"] == name
- assert data["attribute"]["values"][0]["slug"] == slugify(name)
+ content = content["data"]["productAttributeAssign"]
+ assert content["productErrors"][0]["code"] == ProductErrorCode.NOT_FOUND.name
+ assert content["productErrors"][0]["field"] == "operations"
+ assert content["productErrors"][0]["attributes"] == [attribute_id]
- "input_slug, expected_slug",
- (
- ("my-slug", "my-slug"),
- (None, "my-name"),
- ("", "my-name"),
- ("わたし-わ-にっぽん-です", "わたし-わ-にっぽん-です"),
- ),
-)
-def test_create_attribute_with_given_slug(
+def test_assign_variant_attribute_to_product_type_with_disabled_variants(
staff_api_client,
permission_manage_product_types_and_attributes,
- input_slug,
- expected_slug,
+ product_type_without_variant,
+ color_attribute_without_values,
):
+ """The assignAttribute mutation should raise an error when trying
+ to add an attribute as a variant attribute when
+ the product type doesn't support variants"""
+
+ product_type = product_type_without_variant
+ attribute = color_attribute_without_values
staff_api_client.user.user_permissions.add(
permission_manage_product_types_and_attributes
)
- query = """
- mutation createAttribute(
- $name: String!, $slug: String) {
- attributeCreate(input: {name: $name, slug: $slug}) {
- productErrors {
- field
- message
- code
- }
- attribute {
- slug
- }
- }
- }
- """
- attribute_name = "My Name"
- variables = {"name": attribute_name, "slug": input_slug}
- content = get_graphql_content(staff_api_client.post_graphql(query, variables))
-
- assert not content["data"]["attributeCreate"]["productErrors"]
- assert content["data"]["attributeCreate"]["attribute"]["slug"] == expected_slug
+ product_type_global_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+ query = PRODUCT_ASSIGN_ATTR_QUERY
+ operations = [
+ {"type": "VARIANT", "id": graphene.Node.to_global_id("Attribute", attribute.pk)}
+ ]
+ variables = {"productTypeId": product_type_global_id, "operations": operations}
-def test_create_attribute_value_name_and_slug_with_unicode(
- staff_api_client, permission_manage_product_types_and_attributes
-):
- query = CREATE_ATTRIBUTES_QUERY
- name = "わたし わ にっぽん です"
- slug = "わたし-わ-にっぽん-で"
- variables = {"name": name, "slug": slug}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_product_types_and_attributes]
+ content = get_graphql_content(staff_api_client.post_graphql(query, variables))[
+ "data"
+ ]["productAttributeAssign"]
+ assert content["productErrors"][0]["field"] == "operations"
+ assert (
+ content["productErrors"][0]["message"]
+ == "Variants are disabled in this product type."
+ )
+ assert (
+ content["productErrors"][0]["code"]
+ == ProductErrorCode.ATTRIBUTE_VARIANTS_DISABLED.name
)
- content = get_graphql_content(response)
- data = content["data"]["attributeCreate"]
- assert not data["productErrors"]
- assert data["attribute"]["name"] == name
- assert data["attribute"]["slug"] == slug
- "name_1, name_2, error_msg, error_code",
- (
- (
- "Red color",
- "Red color",
- "Provided values are not unique.",
- ProductErrorCode.UNIQUE,
- ),
- (
- "Red color",
- "red color",
- "Provided values are not unique.",
- ProductErrorCode.UNIQUE,
- ),
- ),
-)
-def test_create_attribute_and_attribute_values_errors(
+def test_assign_variant_attribute_having_unsupported_input_type(
staff_api_client,
- name_1,
- name_2,
- error_msg,
- error_code,
permission_manage_product_types_and_attributes,
product_type,
+ size_attribute,
):
- query = CREATE_ATTRIBUTES_QUERY
- variables = {"name": "Example name", "values": [{"name": name_1}, {"name": name_2}]}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_product_types_and_attributes]
- )
- content = get_graphql_content(response)
- errors = content["data"]["attributeCreate"]["errors"]
- assert errors
- assert errors[0]["field"] == "values"
- assert errors[0]["message"] == error_msg
-
- product_errors = content["data"]["attributeCreate"]["productErrors"]
- assert product_errors[0]["code"] == error_code.name
-
-
-UPDATE_ATTRIBUTE_MUTATION = """
- mutation updateAttribute(
- $id: ID!, $name: String!, $addValues: [AttributeValueCreateInput]!,
- $removeValues: [ID]!) {
- attributeUpdate(
- id: $id,
- input: {
- name: $name, addValues: $addValues,
- removeValues: $removeValues}) {
- errors {
- field
- message
- }
- productErrors {
- field
- message
- code
- }
- attribute {
- name
- slug
- values {
- name
- slug
- }
- productTypes(first: 10) {
- edges {
- node {
- id
- }
- }
- }
- }
- }
-}
-"""
+ """The assignAttribute mutation should raise an error when trying
+ to use an attribute as a variant attribute when
+ the attribute's input type doesn't support variants"""
+ attribute = size_attribute
+ attribute.input_type = AttributeInputType.MULTISELECT
+ attribute.save(update_fields=["input_type"])
+ product_type.variant_attributes.clear()
-def test_update_attribute_name(
- staff_api_client, color_attribute, permission_manage_product_types_and_attributes
-):
- query = UPDATE_ATTRIBUTE_MUTATION
- attribute = color_attribute
- name = "Wings name"
- slug = attribute.slug
- node_id = graphene.Node.to_global_id("Attribute", attribute.id)
- variables = {"name": name, "id": node_id, "addValues": [], "removeValues": []}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_product_types_and_attributes]
+ staff_api_client.user.user_permissions.add(
+ permission_manage_product_types_and_attributes
)
- content = get_graphql_content(response)
- attribute.refresh_from_db()
- data = content["data"]["attributeUpdate"]
- assert data["attribute"]["name"] == name == attribute.name
- assert data["attribute"]["slug"] == slug == attribute.slug
- assert data["attribute"]["productTypes"]["edges"] == []
-
-def test_update_attribute_remove_and_add_values(
- staff_api_client, color_attribute, permission_manage_product_types_and_attributes
-):
- query = UPDATE_ATTRIBUTE_MUTATION
- attribute = color_attribute
- name = "Wings name"
- attribute_value_name = "Red Color"
- node_id = graphene.Node.to_global_id("Attribute", attribute.id)
- attribute_value_id = attribute.values.first().id
- value_id = graphene.Node.to_global_id("AttributeValue", attribute_value_id)
- variables = {
- "name": name,
- "id": node_id,
- "addValues": [{"name": attribute_value_name}],
- "removeValues": [value_id],
- }
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_product_types_and_attributes]
- )
- content = get_graphql_content(response)
- attribute.refresh_from_db()
- data = content["data"]["attributeUpdate"]
- assert not data["errors"]
- assert data["attribute"]["name"] == name == attribute.name
- assert not attribute.values.filter(pk=attribute_value_id).exists()
- assert attribute.values.filter(name=attribute_value_name).exists()
+ product_type_global_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+ query = PRODUCT_ASSIGN_ATTR_QUERY
+ operations = [
+ {"type": "VARIANT", "id": graphene.Node.to_global_id("Attribute", attribute.pk)}
+ ]
+ variables = {"productTypeId": product_type_global_id, "operations": operations}
-def test_update_empty_attribute_and_add_values(
- staff_api_client,
- color_attribute_without_values,
- permission_manage_product_types_and_attributes,
-):
- query = UPDATE_ATTRIBUTE_MUTATION
- attribute = color_attribute_without_values
- name = "Wings name"
- attribute_value_name = "Yellow Color"
- node_id = graphene.Node.to_global_id("Attribute", attribute.id)
- variables = {
- "name": name,
- "id": node_id,
- "addValues": [{"name": attribute_value_name}],
- "removeValues": [],
- }
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_product_types_and_attributes]
+ content = get_graphql_content(staff_api_client.post_graphql(query, variables))[
+ "data"
+ ]["productAttributeAssign"]
+ assert content["productErrors"][0]["field"] == "operations"
+ assert (
+ content["productErrors"][0]["message"]
+ == "Attributes having for input types ['multiselect'] "
+ "cannot be assigned as variant attributes"
+ )
+ assert (
+ content["productErrors"][0]["code"]
+ == ProductErrorCode.ATTRIBUTE_CANNOT_BE_ASSIGNED.name
)
- get_graphql_content(response)
- attribute.refresh_from_db()
- assert attribute.values.count() == 1
- assert attribute.values.filter(name=attribute_value_name).exists()
-
-
-UPDATE_ATTRIBUTE_SLUG_MUTATION = """
- mutation updateAttribute(
- $id: ID!, $slug: String) {
- attributeUpdate(
- id: $id,
- input: {
- slug: $slug}) {
- errors {
- field
- message
- }
- productErrors {
- field
- message
- code
- }
- attribute {
- name
- slug
- }
- }
-}
-"""
@pytest.mark.parametrize(
- "input_slug, expected_slug, error_message",
- [
- ("test-slug", "test-slug", None),
- ("", "", "Slug value cannot be blank."),
- (None, "", "Slug value cannot be blank."),
- ],
+ "product_type_attribute_type, gql_attribute_type",
+ (
+ (ProductAttributeType.PRODUCT, ProductAttributeType.VARIANT),
+ (ProductAttributeType.VARIANT, ProductAttributeType.PRODUCT),
+ (ProductAttributeType.PRODUCT, ProductAttributeType.PRODUCT),
+ (ProductAttributeType.VARIANT, ProductAttributeType.VARIANT),
+ ),
)
-def test_update_attribute_slug(
+def test_assign_attribute_to_product_type_having_already_that_attribute(
staff_api_client,
- color_attribute,
permission_manage_product_types_and_attributes,
- input_slug,
- expected_slug,
- error_message,
+ color_attribute_without_values,
+ product_type_attribute_type,
+ gql_attribute_type,
):
- query = UPDATE_ATTRIBUTE_SLUG_MUTATION
-
- attribute = color_attribute
- name = attribute.name
- old_slug = attribute.slug
-
- assert input_slug != old_slug
+ """The assignAttribute mutation should raise an error when trying
+ to add an attribute already contained in the product type."""
- node_id = graphene.Node.to_global_id("Attribute", attribute.id)
- variables = {"slug": input_slug, "id": node_id}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_product_types_and_attributes]
+ product_type = ProductType.objects.create(name="Type")
+ attribute = color_attribute_without_values
+ staff_api_client.user.user_permissions.add(
+ permission_manage_product_types_and_attributes
)
- content = get_graphql_content(response)
- attribute.refresh_from_db()
- data = content["data"]["attributeUpdate"]
- errors = data["productErrors"]
- if not error_message:
- assert data["attribute"]["name"] == name == attribute.name
- assert data["attribute"]["slug"] == input_slug == attribute.slug
- else:
- assert errors
- assert data["attribute"] is None
- assert errors[0]["field"] == "slug"
- assert errors[0]["code"] == ProductErrorCode.REQUIRED.name
+ product_type_global_id = graphene.Node.to_global_id("ProductType", product_type.pk)
-def test_update_attribute_slug_exists(
- staff_api_client, color_attribute, permission_manage_product_types_and_attributes,
-):
- query = UPDATE_ATTRIBUTE_SLUG_MUTATION
-
- second_attribute = Attribute.objects.get(pk=color_attribute.pk)
- second_attribute.pk = None
- second_attribute.slug = "second-attribute"
- second_attribute.save()
-
- attribute = color_attribute
- old_slug = attribute.slug
- new_slug = second_attribute.slug
+ if product_type_attribute_type == ProductAttributeType.PRODUCT:
+ product_type.product_attributes.add(attribute)
+ elif product_type_attribute_type == ProductAttributeType.VARIANT:
+ product_type.variant_attributes.add(attribute)
+ else:
+ raise ValueError(f"Unknown: {product_type}")
- assert new_slug != old_slug
+ query = PRODUCT_ASSIGN_ATTR_QUERY
+ operations = [
+ {
+ "type": gql_attribute_type.value,
+ "id": graphene.Node.to_global_id("Attribute", attribute.pk),
+ }
+ ]
+ variables = {"productTypeId": product_type_global_id, "operations": operations}
- node_id = graphene.Node.to_global_id("Attribute", attribute.id)
- variables = {"slug": new_slug, "id": node_id}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_product_types_and_attributes]
+ content = get_graphql_content(staff_api_client.post_graphql(query, variables))[
+ "data"
+ ]["productAttributeAssign"]
+ assert content["productErrors"][0]["field"] == "operations"
+ assert (
+ content["productErrors"][0]["message"]
+ == "Color (color) have already been assigned to this product type."
+ )
+ assert (
+ content["productErrors"][0]["code"]
+ == ProductErrorCode.ATTRIBUTE_ALREADY_ASSIGNED.name
)
- content = get_graphql_content(response)
- attribute.refresh_from_db()
- data = content["data"]["attributeUpdate"]
- errors = data["productErrors"]
-
- assert errors
- assert data["attribute"] is None
- assert errors[0]["field"] == "slug"
- assert errors[0]["code"] == ProductErrorCode.UNIQUE.name
- "input_slug, expected_slug, input_name, error_message, error_field",
- [
- ("test-slug", "test-slug", "New name", None, None),
- ("", "", "New name", "Slug value cannot be blank.", "slug"),
- (None, "", "New name", "Slug value cannot be blank.", "slug"),
- ("test-slug", "", None, "This field cannot be blank.", "name"),
- ("test-slug", "", "", "This field cannot be blank.", "name"),
- (None, None, None, "Slug value cannot be blank.", "slug"),
- ],
-)
-def test_update_attribute_slug_and_name(
+def test_assign_page_attribute_to_product_type(
staff_api_client,
- color_attribute,
permission_manage_product_types_and_attributes,
- input_slug,
- expected_slug,
- input_name,
- error_message,
- error_field,
+ tag_page_attribute,
+ product_type,
):
- query = """
- mutation updateAttribute(
- $id: ID!, $slug: String, $name: String) {
- attributeUpdate(
- id: $id,
- input: {
- slug: $slug, name: $name}) {
- errors {
- field
- message
- }
- productErrors {
- field
- message
- code
- }
- attribute {
- name
- slug
- }
- }
- }
- """
-
- attribute = color_attribute
- old_name = attribute.name
- old_slug = attribute.slug
-
- assert input_slug != old_slug
- assert input_name != old_name
-
- node_id = graphene.Node.to_global_id("Attribute", attribute.id)
- variables = {"slug": input_slug, "name": input_name, "id": node_id}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_product_types_and_attributes]
+ # given
+ staff_api_client.user.user_permissions.add(
+ permission_manage_product_types_and_attributes
)
- content = get_graphql_content(response)
- attribute.refresh_from_db()
- data = content["data"]["attributeUpdate"]
- errors = data["productErrors"]
- if not error_message:
- assert data["attribute"]["name"] == input_name == attribute.name
- assert data["attribute"]["slug"] == input_slug == attribute.slug
- else:
- assert errors
- assert errors[0]["field"] == error_field
- assert errors[0]["code"] == ProductErrorCode.REQUIRED.name
+ tag_page_attr_id = graphene.Node.to_global_id("Attribute", tag_page_attribute.pk)
- "name_1, name_2, error_msg, error_code",
- (
- (
- "Red color",
- "Red color",
- "Provided values are not unique.",
- ProductErrorCode.UNIQUE,
- ),
- (
- "Red color",
- "red color",
- "Provided values are not unique.",
- ProductErrorCode.UNIQUE,
- ),
- ),
-)
-def test_update_attribute_and_add_attribute_values_errors(
- staff_api_client,
- name_1,
- name_2,
- error_msg,
- error_code,
- color_attribute,
- permission_manage_product_types_and_attributes,
-):
- query = UPDATE_ATTRIBUTE_MUTATION
- attribute = color_attribute
- node_id = graphene.Node.to_global_id("Attribute", attribute.id)
variables = {
- "name": "Example name",
- "id": node_id,
- "removeValues": [],
- "addValues": [{"name": name_1}, {"name": name_2}],
+ "productTypeId": graphene.Node.to_global_id("ProductType", product_type.pk),
+ "operations": [
+ {"type": ProductAttributeType.PRODUCT.value, "id": tag_page_attr_id},
+ ],
}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_product_types_and_attributes]
- )
+
+ # when
+ response = staff_api_client.post_graphql(PRODUCT_ASSIGN_ATTR_QUERY, variables)
+
+ # then
content = get_graphql_content(response)
- errors = content["data"]["attributeUpdate"]["errors"]
- assert errors
- assert errors[0]["field"] == "addValues"
- assert errors[0]["message"] == error_msg
+ data = content["data"]["productAttributeAssign"]
+ errors = data["productErrors"]
- product_errors = content["data"]["attributeUpdate"]["productErrors"]
- assert product_errors[0]["code"] == error_code.name
+ assert not data["productType"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "operations"
+ assert errors[0]["code"] == ProductErrorCode.INVALID.name
+ assert errors[0]["attributes"] == [tag_page_attr_id]
-def test_update_attribute_and_remove_others_attribute_value(
+def test_assign_attribute_to_product_type_multiply_errors_returned(
staff_api_client,
+ permission_manage_product_types_and_attributes,
color_attribute,
size_attribute,
- permission_manage_product_types_and_attributes,
+ tag_page_attribute,
):
- query = UPDATE_ATTRIBUTE_MUTATION
- attribute = color_attribute
- node_id = graphene.Node.to_global_id("Attribute", attribute.id)
- size_attribute = size_attribute.values.first()
- attr_id = graphene.Node.to_global_id("AttributeValue", size_attribute.pk)
- variables = {
- "name": "Example name",
- "id": node_id,
- "addValues": [],
- "removeValues": [attr_id],
- }
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_product_types_and_attributes]
+ # given
+ product_type = ProductType.objects.create(name="Type")
+ staff_api_client.user.user_permissions.add(
+ permission_manage_product_types_and_attributes
)
- content = get_graphql_content(response)
- errors = content["data"]["attributeUpdate"]["errors"]
- assert errors
- assert errors[0]["field"] == "removeValues"
- err_msg = "Value %s does not belong to this attribute." % str(size_attribute)
- assert errors[0]["message"] == err_msg
- product_errors = content["data"]["attributeUpdate"]["productErrors"]
- assert product_errors[0]["code"] == ProductErrorCode.INVALID.name
+ product_type.product_attributes.add(color_attribute)
+ unsupported_type_attr = size_attribute
+ unsupported_type_attr.input_type = AttributeInputType.MULTISELECT
+ unsupported_type_attr.save(update_fields=["input_type"])
-def test_delete_attribute(
- staff_api_client,
- color_attribute,
- permission_manage_product_types_and_attributes,
- product_type,
-):
- attribute = color_attribute
- query = """
- mutation deleteAttribute($id: ID!) {
- attributeDelete(id: $id) {
- errors {
- field
- message
- }
- attribute {
- id
- }
- }
- }
- """
- node_id = graphene.Node.to_global_id("Attribute", attribute.id)
- variables = {"id": node_id}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_product_types_and_attributes]
+ color_attr_id = graphene.Node.to_global_id("Attribute", color_attribute.pk)
+ unsupported_type_attr_id = graphene.Node.to_global_id(
+ "Attribute", unsupported_type_attr.pk
)
+ tag_page_attr_id = graphene.Node.to_global_id("Attribute", tag_page_attribute.pk)
+
+ variables = {
+ "productTypeId": graphene.Node.to_global_id("ProductType", product_type.pk),
+ "operations": [
+ {"type": ProductAttributeType.PRODUCT.value, "id": color_attr_id},
+ {
+ "type": ProductAttributeType.VARIANT.value,
+ "id": unsupported_type_attr_id,
+ },
+ {"type": ProductAttributeType.PRODUCT.value, "id": tag_page_attr_id},
+ ],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(PRODUCT_ASSIGN_ATTR_QUERY, variables)
+
+ # then
content = get_graphql_content(response)
- data = content["data"]["attributeDelete"]
- assert data["attribute"]["id"] == variables["id"]
- with pytest.raises(attribute._meta.model.DoesNotExist):
- attribute.refresh_from_db()
+ data = content["data"]["productAttributeAssign"]
+ errors = data["productErrors"]
+
+ assert not data["productType"]
+ assert len(errors) == 3
+ expected_errors = [
+ {
+ "code": ProductErrorCode.ATTRIBUTE_ALREADY_ASSIGNED.name,
+ "field": "operations",
+ "message": mock.ANY,
+ "attributes": [color_attr_id],
+ },
+ {
+ "code": ProductErrorCode.ATTRIBUTE_CANNOT_BE_ASSIGNED.name,
+ "field": "operations",
+ "message": mock.ANY,
+ "attributes": [unsupported_type_attr_id],
+ },
+ {
+ "code": ProductErrorCode.INVALID.name,
+ "field": "operations",
+ "message": mock.ANY,
+ "attributes": [tag_page_attr_id],
+ },
+ ]
+ for error in expected_errors:
+ assert error in errors
-CREATE_ATTRIBUTE_VALUE_QUERY = """
- mutation createAttributeValue(
- $attributeId: ID!, $name: String!) {
- attributeValueCreate(
- attribute: $attributeId, input: {name: $name}) {
+PRODUCT_UNASSIGN_ATTR_QUERY = """
+ mutation ProductUnassignAttribute(
+ $productTypeId: ID!, $attributeIds: [ID]!
+ ) {
+ productAttributeUnassign(
+ productTypeId: $productTypeId, attributeIds: $attributeIds
+ ) {
productErrors {
- field
- message
- code
- }
- attribute {
- values {
- name
- }
+ field
+ message
}
- attributeValue {
- name
- type
- slug
+ productType {
+ id
+ variantAttributes {
+ id
+ }
+ productAttributes {
+ id
+ }
}
+ }
}
-}
"""
-def test_create_attribute_value(
- staff_api_client, color_attribute, permission_manage_products
+def test_unassign_attributes_from_product_type(
+ staff_api_client,
+ permission_manage_product_types_and_attributes,
+ product_type_attribute_list,
):
- attribute = color_attribute
- query = CREATE_ATTRIBUTE_VALUE_QUERY
- attribute_id = graphene.Node.to_global_id("Attribute", attribute.id)
- name = "test name"
- variables = {"name": name, "attributeId": attribute_id}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_products]
- )
- content = get_graphql_content(response)
- data = content["data"]["attributeValueCreate"]
- assert not data["productErrors"]
+ product_type = ProductType.objects.create(name="Type")
+ product_type_global_id = graphene.Node.to_global_id("ProductType", product_type.pk)
- attr_data = data["attributeValue"]
- assert attr_data["name"] == name
- assert attr_data["slug"] == slugify(name)
- assert attr_data["type"] == "STRING"
- assert name in [value["name"] for value in data["attribute"]["values"]]
+ variant_attribute, *product_attributes = product_type_attribute_list
+ product_type.product_attributes.add(*product_attributes)
+ product_type.variant_attributes.add(variant_attribute)
-
-def test_create_attribute_value_not_unique_name(
- staff_api_client, color_attribute, permission_manage_products
-):
- attribute = color_attribute
- query = CREATE_ATTRIBUTE_VALUE_QUERY
- attribute_id = graphene.Node.to_global_id("Attribute", attribute.id)
- value_name = attribute.values.first().name
- variables = {"name": value_name, "attributeId": attribute_id}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_products]
+ remaining_attribute_global_id = graphene.Node.to_global_id(
+ "Attribute", product_attributes[1].pk
)
- content = get_graphql_content(response)
- data = content["data"]["attributeValueCreate"]
- assert data["productErrors"]
- assert data["productErrors"][0]["code"] == ProductErrorCode.ALREADY_EXISTS.name
- assert data["productErrors"][0]["field"] == "name"
-
-def test_create_attribute_value_capitalized_name(
- staff_api_client, color_attribute, permission_manage_products
-):
- attribute = color_attribute
- query = CREATE_ATTRIBUTE_VALUE_QUERY
- attribute_id = graphene.Node.to_global_id("Attribute", attribute.id)
- value_name = attribute.values.first().name
- variables = {"name": value_name.upper(), "attributeId": attribute_id}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_products]
- )
- content = get_graphql_content(response)
- data = content["data"]["attributeValueCreate"]
- assert data["productErrors"]
- assert data["productErrors"][0]["code"] == ProductErrorCode.ALREADY_EXISTS.name
- assert data["productErrors"][0]["field"] == "name"
-
-
-UPDATE_ATTRIBUTE_VALUE_QUERY = """
-mutation updateChoice(
- $id: ID!, $name: String!) {
- attributeValueUpdate(
- id: $id, input: {name: $name}) {
- errors {
- field
- message
- }
- attributeValue {
- name
- slug
- }
- attribute {
- values {
- name
- }
- }
+ query = PRODUCT_UNASSIGN_ATTR_QUERY
+ variables = {
+ "productTypeId": product_type_global_id,
+ "attributeIds": [
+ graphene.Node.to_global_id("Attribute", product_attributes[0].pk)
+ ],
}
-}
-"""
+ content = get_graphql_content(
+ staff_api_client.post_graphql(
+ query,
+ variables,
+ permissions=[permission_manage_product_types_and_attributes],
+ )
+ )["data"]["productAttributeUnassign"]
+ assert not content["productErrors"]
-def test_update_attribute_value(
- staff_api_client,
- pink_attribute_value,
- permission_manage_product_types_and_attributes,
-):
- query = UPDATE_ATTRIBUTE_VALUE_QUERY
- value = pink_attribute_value
- node_id = graphene.Node.to_global_id("AttributeValue", value.id)
- name = "Crimson name"
- variables = {"name": name, "id": node_id}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_product_types_and_attributes]
+ assert content["productType"]["id"] == product_type_global_id
+ assert len(content["productType"]["productAttributes"]) == 1
+ assert len(content["productType"]["variantAttributes"]) == 1
+
+ assert (
+ content["productType"]["productAttributes"][0]["id"]
+ == remaining_attribute_global_id
)
- content = get_graphql_content(response)
- data = content["data"]["attributeValueUpdate"]
- value.refresh_from_db()
- assert data["attributeValue"]["name"] == name == value.name
- assert data["attributeValue"]["slug"] == slugify(name)
- assert name in [value["name"] for value in data["attribute"]["values"]]
-def test_update_attribute_value_name_not_unique(
+def test_unassign_attributes_not_in_product_type(
staff_api_client,
- pink_attribute_value,
permission_manage_product_types_and_attributes,
+ color_attribute_without_values,
):
- query = UPDATE_ATTRIBUTE_VALUE_QUERY
- value = pink_attribute_value.attribute.values.create(
- name="Example Name", slug="example-name", value="#RED"
- )
- node_id = graphene.Node.to_global_id("AttributeValue", value.id)
- variables = {"name": pink_attribute_value.name, "id": node_id}
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_product_types_and_attributes]
+ """The unAssignAttribute mutation should not raise any error when trying
+ to remove an attribute that is not/no longer in the product type."""
+
+ staff_api_client.user.user_permissions.add(
+ permission_manage_product_types_and_attributes
)
- content = get_graphql_content(response)
- data = content["data"]["attributeValueUpdate"]
- assert data["errors"]
- assert data["errors"][0]["message"]
- assert data["errors"][0]["field"] == "name"
+ product_type = ProductType.objects.create(name="Type")
+ product_type_global_id = graphene.Node.to_global_id("ProductType", product_type.pk)
-def test_delete_attribute_value(
- staff_api_client,
- color_attribute,
- pink_attribute_value,
- permission_manage_product_types_and_attributes,
-):
- value = color_attribute.values.get(name="Red")
- query = """
- mutation updateChoice($id: ID!) {
- attributeValueDelete(id: $id) {
- attributeValue {
- name
- slug
- }
- }
+ query = PRODUCT_UNASSIGN_ATTR_QUERY
+ variables = {
+ "productTypeId": product_type_global_id,
+ "attributeIds": [
+ graphene.Node.to_global_id("Attribute", color_attribute_without_values.pk)
+ ],
}
- """
- node_id = graphene.Node.to_global_id("AttributeValue", value.id)
- variables = {"id": node_id}
- staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_product_types_and_attributes]
- )
- with pytest.raises(value._meta.model.DoesNotExist):
- value.refresh_from_db()
+ content = get_graphql_content(staff_api_client.post_graphql(query, variables))[
+ "data"
+ ]["productAttributeUnassign"]
+ assert not content["productErrors"]
- "raw_value, expected_type",
- [
- ("#0000", AttributeValueType.COLOR),
- ("#FF69B4", AttributeValueType.COLOR),
- ("rgb(255, 0, 0)", AttributeValueType.COLOR),
- ("hsl(0, 100%, 50%)", AttributeValueType.COLOR),
- ("hsla(120, 60%, 70%, 0.3)", AttributeValueType.COLOR),
- ("rgba(100%, 255, 0, 0)", AttributeValueType.COLOR),
- ("http://example.com", AttributeValueType.URL),
- ("https://example.com", AttributeValueType.URL),
- ("ftp://example.com", AttributeValueType.URL),
- ("example.com", AttributeValueType.STRING),
- ("Foo", AttributeValueType.STRING),
- ("linear-gradient(red, yellow)", AttributeValueType.GRADIENT),
- ("radial-gradient(#0000, yellow)", AttributeValueType.GRADIENT),
- ],
-)
-def test_resolve_attribute_value_type(raw_value, expected_type):
- assert resolve_attribute_value_type(raw_value) == expected_type
+ assert content["productType"]["id"] == product_type_global_id
+ assert len(content["productType"]["productAttributes"]) == 0
+ assert len(content["productType"]["variantAttributes"]) == 0
-def test_resolve_assigned_attribute_without_values(
- api_client, product_type, product, channel_USD
+def test_retrieve_product_attributes_input_type(
+ staff_api_client, product, permission_manage_products, channel_USD
):
- """Ensure the attributes assigned to a product type are resolved even if
- the product doesn't provide any value for it or is not directly associated to it.
- """
- # Retrieve the product's variant
- variant = product.variants.get()
-
- # Remove all attributes and values from the product and its variant
- product.attributesrelated.clear()
- variant.attributesrelated.clear()
-
- # Retrieve the product and variant's attributes
- products = get_graphql_content(
- api_client.post_graphql(
- """
- query ($channel: String) {
+ query = """
+ query ($channel: String){
products(first: 10, channel: $channel) {
edges {
node {
attributes {
- attribute {
- slug
- }
values {
- name
- }
- }
- variants {
- attributes {
- attribute {
- slug
- }
- values {
- name
- }
+ type
+ inputType
}
}
}
}
}
}
- """,
- {"channel": channel_USD.slug},
+ """
+
+ variables = {"channel": channel_USD.slug}
+ found_products = get_graphql_content(
+ staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
)
)["data"]["products"]["edges"]
+ assert len(found_products) == 1
- # Ensure we are only working on one product and variant, the ones we are testing
- assert len(products) == 1
- assert len(products[0]["node"]["variants"]) == 1
-
- # Retrieve the nodes data
- product = products[0]["node"]
- variant = product["variants"][0]
-
- # Ensure the product attributes values are all None
- assert len(product["attributes"]) == 1
- assert product["attributes"][0]["attribute"]["slug"] == "color"
- assert product["attributes"][0]["values"] == []
-
- # Ensure the variant attributes values are all None
- assert variant["attributes"][0]["attribute"]["slug"] == "size"
- assert variant["attributes"][0]["values"] == []
+ for gql_attr in found_products[0]["node"]["attributes"]:
+ assert len(gql_attr["values"]) == 1
+ assert gql_attr["values"][0]["type"] == "STRING"
+ assert gql_attr["values"][0]["inputType"] == "DROPDOWN"
-ASSIGN_ATTR_QUERY = """
- mutation assign($productTypeId: ID!, $operations: [AttributeAssignInput]!) {
- attributeAssign(productTypeId: $productTypeId, operations: $operations) {
- productErrors {
- field
- code
- message
- attributes
- }
+ATTRIBUTES_RESORT_QUERY = """
+ mutation ProductTypeReorderAttributes(
+ $productTypeId: ID!
+ $moves: [ReorderInput]!
+ $type: ProductAttributeType!
+ ) {
+ productTypeReorderAttributes(
+ productTypeId: $productTypeId
+ moves: $moves
+ type: $type
+ ) {
productType {
id
- productAttributes {
+ variantAttributes {
id
+ slug
}
- variantAttributes {
+ productAttributes {
id
}
}
+
+ productErrors {
+ field
+ message
+ code
+ attributes
+ }
}
}
"""
-def test_assign_attributes_to_product_type(
- staff_api_client, permission_manage_product_types_and_attributes, attribute_list
+def test_sort_attributes_within_product_type_invalid_product_type(
+ staff_api_client, permission_manage_product_types_and_attributes
):
- product_type = ProductType.objects.create(name="Default Type", has_variants=True)
- product_type_global_id = graphene.Node.to_global_id("ProductType", product_type.pk)
-
- query = ASSIGN_ATTR_QUERY
- operations = []
- variables = {"productTypeId": product_type_global_id, "operations": operations}
-
- product_attributes_ids = {attr.pk for attr in attribute_list[:2]}
- variant_attributes_ids = {attr.pk for attr in attribute_list[2:]}
+ """Try to reorder an invalid product type (invalid ID)."""
- for attr_id in product_attributes_ids:
- operations.append(
- {"type": "PRODUCT", "id": graphene.Node.to_global_id("Attribute", attr_id)}
- )
+ product_type_id = graphene.Node.to_global_id("ProductType", -1)
+ attribute_id = graphene.Node.to_global_id("Attribute", -1)
- for attr_id in variant_attributes_ids:
- operations.append(
- {"type": "VARIANT", "id": graphene.Node.to_global_id("Attribute", attr_id)}
- )
+ variables = {
+ "type": "VARIANT",
+ "productTypeId": product_type_id,
+ "moves": [{"id": attribute_id, "sortOrder": 1}],
+ }
content = get_graphql_content(
staff_api_client.post_graphql(
- query,
+ ATTRIBUTES_RESORT_QUERY,
variables,
permissions=[permission_manage_product_types_and_attributes],
)
- )["data"]["attributeAssign"]
- assert not content["productErrors"], "Should have succeeded"
-
- assert content["productType"]["id"] == product_type_global_id
- assert len(content["productType"]["productAttributes"]) == len(
- product_attributes_ids
- )
- assert len(content["productType"]["variantAttributes"]) == len(
- variant_attributes_ids
- )
-
- found_product_attrs_ids = {
- int(graphene.Node.from_global_id(attr["id"])[1])
- for attr in content["productType"]["productAttributes"]
- }
- found_variant_attrs_ids = {
- int(graphene.Node.from_global_id(attr["id"])[1])
- for attr in content["productType"]["variantAttributes"]
- }
+ )["data"]["productTypeReorderAttributes"]
- assert found_product_attrs_ids == product_attributes_ids
- assert found_variant_attrs_ids == variant_attributes_ids
+ assert content["productErrors"] == [
+ {
+ "field": "productTypeId",
+ "code": ProductErrorCode.NOT_FOUND.name,
+ "message": f"Couldn't resolve to a product type: {product_type_id}",
+ "attributes": None,
+ }
+ ]
-def test_assign_non_existing_attributes_to_product_type(
- staff_api_client, permission_manage_product_types_and_attributes, attribute_list
+def test_sort_attributes_within_product_type_invalid_id(
+ staff_api_client, permission_manage_product_types_and_attributes, color_attribute
):
- product_type = ProductType.objects.create(name="Default Type", has_variants=True)
- product_type_global_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+ """Try to reorder an attribute not associated to the given product type."""
- query = ASSIGN_ATTR_QUERY
- attribute_id = graphene.Node.to_global_id("Attribute", "55511155593")
- operations = [{"type": "PRODUCT", "id": attribute_id}]
- variables = {"productTypeId": product_type_global_id, "operations": operations}
+ product_type = ProductType.objects.create(name="Dummy Type")
+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.id)
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_product_types_and_attributes]
- )
- content = get_graphql_content(response)
- content = content["data"]["attributeAssign"]
- assert content["productErrors"][0]["code"] == ProductErrorCode.NOT_FOUND.name
- assert content["productErrors"][0]["field"] == "operations"
- assert content["productErrors"][0]["attributes"] == [attribute_id]
+ attribute_id = graphene.Node.to_global_id("Attribute", color_attribute.id)
+ variables = {
+ "type": "VARIANT",
+ "productTypeId": product_type_id,
+ "moves": [{"id": attribute_id, "sortOrder": 1}],
+ }
-def test_assign_variant_attribute_to_product_type_with_disabled_variants(
- staff_api_client,
- permission_manage_product_types_and_attributes,
- product_type_without_variant,
- color_attribute_without_values,
-):
- """The assignAttribute mutation should raise an error when trying
- to add an attribute as a variant attribute when
- the product type doesn't support variants"""
-
- product_type = product_type_without_variant
- attribute = color_attribute_without_values
- staff_api_client.user.user_permissions.add(
- permission_manage_product_types_and_attributes
- )
-
- product_type_global_id = graphene.Node.to_global_id("ProductType", product_type.pk)
-
- query = ASSIGN_ATTR_QUERY
- operations = [
- {"type": "VARIANT", "id": graphene.Node.to_global_id("Attribute", attribute.pk)}
- ]
- variables = {"productTypeId": product_type_global_id, "operations": operations}
-
- content = get_graphql_content(staff_api_client.post_graphql(query, variables))[
- "data"
- ]["attributeAssign"]
- assert content["productErrors"][0]["field"] == "operations"
- assert (
- content["productErrors"][0]["message"]
- == "Variants are disabled in this product type."
- )
- assert (
- content["productErrors"][0]["code"]
- == ProductErrorCode.ATTRIBUTE_VARIANTS_DISABLED.name
- )
-
-
-def test_assign_variant_attribute_having_unsupported_input_type(
- staff_api_client,
- permission_manage_product_types_and_attributes,
- product_type,
- size_attribute,
-):
- """The assignAttribute mutation should raise an error when trying
- to use an attribute as a variant attribute when
- the attribute's input type doesn't support variants"""
-
- attribute = size_attribute
- attribute.input_type = AttributeInputType.MULTISELECT
- attribute.save(update_fields=["input_type"])
- product_type.variant_attributes.clear()
-
- staff_api_client.user.user_permissions.add(
- permission_manage_product_types_and_attributes
- )
-
- product_type_global_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+ content = get_graphql_content(
+ staff_api_client.post_graphql(
+ ATTRIBUTES_RESORT_QUERY,
+ variables,
+ permissions=[permission_manage_product_types_and_attributes],
+ )
+ )["data"]["productTypeReorderAttributes"]
- query = ASSIGN_ATTR_QUERY
- operations = [
- {"type": "VARIANT", "id": graphene.Node.to_global_id("Attribute", attribute.pk)}
+ assert content["productErrors"] == [
+ {
+ "field": "moves",
+ "message": "Couldn't resolve to an attribute.",
+ "attributes": [attribute_id],
+ "code": ProductErrorCode.NOT_FOUND.name,
+ }
]
- variables = {"productTypeId": product_type_global_id, "operations": operations}
-
- content = get_graphql_content(staff_api_client.post_graphql(query, variables))[
- "data"
- ]["attributeAssign"]
- assert content["productErrors"][0]["field"] == "operations"
- assert (
- content["productErrors"][0]["message"]
- == "Attributes having for input types ['multiselect'] "
- "cannot be assigned as variant attributes"
- )
- assert (
- content["productErrors"][0]["code"]
- == ProductErrorCode.ATTRIBUTE_CANNOT_BE_ASSIGNED.name
- )
@pytest.mark.parametrize(
- "product_type_attribute_type, gql_attribute_type",
+ "attribute_type, relation_field, backref_field",
(
- (AttributeTypeEnum.PRODUCT, AttributeTypeEnum.VARIANT),
- (AttributeTypeEnum.VARIANT, AttributeTypeEnum.PRODUCT),
- (AttributeTypeEnum.PRODUCT, AttributeTypeEnum.PRODUCT),
- (AttributeTypeEnum.VARIANT, AttributeTypeEnum.VARIANT),
+ ("VARIANT", "variant_attributes", "attributevariant"),
+ ("PRODUCT", "product_attributes", "attributeproduct"),
),
)
-def test_assign_attribute_to_product_type_having_already_that_attribute(
+def test_sort_attributes_within_product_type(
staff_api_client,
+ product_type_attribute_list,
permission_manage_product_types_and_attributes,
- color_attribute_without_values,
- product_type_attribute_type,
- gql_attribute_type,
+ attribute_type,
+ relation_field,
+ backref_field,
):
- """The assignAttribute mutation should raise an error when trying
- to add an attribute already contained in the product type."""
+ attributes = product_type_attribute_list
+ assert len(attributes) == 3
- product_type = ProductType.objects.create(name="Type")
- attribute = color_attribute_without_values
staff_api_client.user.user_permissions.add(
permission_manage_product_types_and_attributes
)
- product_type_global_id = graphene.Node.to_global_id("ProductType", product_type.pk)
-
- if product_type_attribute_type == AttributeTypeEnum.PRODUCT:
- product_type.product_attributes.add(attribute)
- elif product_type_attribute_type == AttributeTypeEnum.VARIANT:
- product_type.variant_attributes.add(attribute)
- else:
- raise ValueError(f"Unknown: {product_type}")
-
- query = ASSIGN_ATTR_QUERY
- operations = [
- {
- "type": gql_attribute_type.value,
- "id": graphene.Node.to_global_id("Attribute", attribute.pk),
- }
- ]
- variables = {"productTypeId": product_type_global_id, "operations": operations}
-
- content = get_graphql_content(staff_api_client.post_graphql(query, variables))[
- "data"
- ]["attributeAssign"]
- assert content["productErrors"][0]["field"] == "operations"
- assert (
- content["productErrors"][0]["message"]
- == "Color (color) have already been assigned to this product type."
- )
- assert (
- content["productErrors"][0]["code"]
- == ProductErrorCode.ATTRIBUTE_ALREADY_ASSIGNED.name
- )
-
-
-UNASSIGN_ATTR_QUERY = """
- mutation unAssignAttribute(
- $productTypeId: ID!, $attributeIds: [ID]!
- ) {
- attributeUnassign(productTypeId: $productTypeId, attributeIds: $attributeIds) {
- errors {
- field
- message
- }
- productType {
- id
- variantAttributes {
- id
- }
- productAttributes {
- id
- }
- }
- }
- }
-"""
-
-
-def test_unassign_attributes_from_product_type(
- staff_api_client, permission_manage_product_types_and_attributes, attribute_list
-):
- product_type = ProductType.objects.create(name="Type")
- product_type_global_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+ product_type = ProductType.objects.create(name="Dummy Type")
+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.id)
+ m2m_attributes = getattr(product_type, relation_field)
+ m2m_attributes.set(attributes)
- variant_attribute, *product_attributes = attribute_list
- product_type.product_attributes.add(*product_attributes)
- product_type.variant_attributes.add(variant_attribute)
+ sort_method = getattr(m2m_attributes, f"{relation_field}_sorted")
+ attributes = list(sort_method())
- remaining_attribute_global_id = graphene.Node.to_global_id(
- "Attribute", product_attributes[1].pk
- )
+ assert len(attributes) == 3
- query = UNASSIGN_ATTR_QUERY
variables = {
- "productTypeId": product_type_global_id,
- "attributeIds": [
- graphene.Node.to_global_id("Attribute", product_attributes[0].pk)
+ "type": attribute_type,
+ "productTypeId": product_type_id,
+ "moves": [
+ {
+ "id": graphene.Node.to_global_id("Attribute", attributes[0].pk),
+ "sortOrder": +1,
+ },
+ {
+ "id": graphene.Node.to_global_id("Attribute", attributes[2].pk),
+ "sortOrder": -1,
+ },
],
}
- content = get_graphql_content(
- staff_api_client.post_graphql(
- query,
- variables,
- permissions=[permission_manage_product_types_and_attributes],
- )
- )["data"]["attributeUnassign"]
- assert not content["errors"]
+ expected_order = [attributes[1].pk, attributes[2].pk, attributes[0].pk]
- assert content["productType"]["id"] == product_type_global_id
- assert len(content["productType"]["productAttributes"]) == 1
- assert len(content["productType"]["variantAttributes"]) == 1
+ content = get_graphql_content(
+ staff_api_client.post_graphql(ATTRIBUTES_RESORT_QUERY, variables)
+ )["data"]["productTypeReorderAttributes"]
+ assert not content["productErrors"]
assert (
- content["productType"]["productAttributes"][0]["id"]
- == remaining_attribute_global_id
- )
-
-
-def test_unassign_attributes_not_in_product_type(
- staff_api_client,
- permission_manage_product_types_and_attributes,
- color_attribute_without_values,
-):
- """The unAssignAttribute mutation should not raise any error when trying
- to remove an attribute that is not/no longer in the product type."""
-
- staff_api_client.user.user_permissions.add(
- permission_manage_product_types_and_attributes
- )
-
- product_type = ProductType.objects.create(name="Type")
- product_type_global_id = graphene.Node.to_global_id("ProductType", product_type.pk)
-
- query = UNASSIGN_ATTR_QUERY
- variables = {
- "productTypeId": product_type_global_id,
- "attributeIds": [
- graphene.Node.to_global_id("Attribute", color_attribute_without_values.pk)
- ],
- }
-
- content = get_graphql_content(staff_api_client.post_graphql(query, variables))[
- "data"
- ]["attributeUnassign"]
- assert not content["errors"]
-
- assert content["productType"]["id"] == product_type_global_id
- assert len(content["productType"]["productAttributes"]) == 0
- assert len(content["productType"]["variantAttributes"]) == 0
-
-
-def test_retrieve_product_attributes_input_type(
- staff_api_client, product, permission_manage_products, channel_USD
-):
- query = """
- query ($channel: String){
- products(first: 10, channel: $channel) {
- edges {
- node {
- attributes {
- values {
- type
- inputType
- }
- }
- }
- }
- }
- }
- """
-
- variables = {"channel": channel_USD.slug}
- found_products = get_graphql_content(
- staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_products]
- )
- )["data"]["products"]["edges"]
- assert len(found_products) == 1
-
- for gql_attr in found_products[0]["node"]["attributes"]:
- assert len(gql_attr["values"]) == 1
- assert gql_attr["values"][0]["type"] == "STRING"
- assert gql_attr["values"][0]["inputType"] == "DROPDOWN"
+ content["productType"]["id"] == product_type_id
+ ), "Did not return the correct product type"
-
- "attribute, expected_value",
- (
- ("filterable_in_storefront", True),
- ("filterable_in_dashboard", True),
- ("visible_in_storefront", True),
- ("available_in_grid", True),
- ("value_required", False),
- ("storefront_search_position", 0),
- ),
-)
-def test_retrieving_the_restricted_attributes_restricted(
- staff_api_client,
- color_attribute,
- permission_manage_products,
- attribute,
- expected_value,
-):
- """Checks if the attributes are restricted and if their default value
- is the expected one."""
-
- attribute = to_camel_case(attribute)
- query = (
- """
- {
- attributes(first: 10) {
- edges {
- node {
- %s
- }
- }
- }
- }
- """
- % attribute
- )
-
- found_attributes = get_graphql_content(
- staff_api_client.post_graphql(query, permissions=[permission_manage_products])
- )["data"]["attributes"]["edges"]
-
- assert len(found_attributes) == 1
- assert found_attributes[0]["node"][attribute] == expected_value
-
-
-ATTRIBUTES_RESORT_QUERY = """
- mutation ProductTypeReorderAttributes(
- $productTypeId: ID!
- $moves: [ReorderInput]!
- $type: AttributeTypeEnum!
- ) {
- productTypeReorderAttributes(
- productTypeId: $productTypeId
- moves: $moves
- type: $type
- ) {
- productType {
- id
- variantAttributes {
- id
- slug
- }
- productAttributes {
- id
- }
- }
-
- errors {
- field
- message
- }
- }
- }
-"""
-
-
-def test_sort_attributes_within_product_type_invalid_product_type(
- staff_api_client, permission_manage_product_types_and_attributes
-):
- """Try to reorder an invalid product type (invalid ID)."""
-
- product_type_id = graphene.Node.to_global_id("ProductType", -1)
- attribute_id = graphene.Node.to_global_id("Attribute", -1)
-
- variables = {
- "type": "VARIANT",
- "productTypeId": product_type_id,
- "moves": [{"id": attribute_id, "sortOrder": 1}],
- }
-
- content = get_graphql_content(
- staff_api_client.post_graphql(
- ATTRIBUTES_RESORT_QUERY,
- variables,
- permissions=[permission_manage_product_types_and_attributes],
- )
- )["data"]["productTypeReorderAttributes"]
-
- assert content["errors"] == [
- {
- "field": "productTypeId",
- "message": f"Couldn't resolve to a product type: {product_type_id}",
- }
- ]
-
-
-def test_sort_attributes_within_product_type_invalid_id(
- staff_api_client, permission_manage_product_types_and_attributes, color_attribute
-):
- """Try to reorder an attribute not associated to the given product type."""
-
- product_type = ProductType.objects.create(name="Dummy Type")
- product_type_id = graphene.Node.to_global_id("ProductType", product_type.id)
-
- attribute_id = graphene.Node.to_global_id("Attribute", color_attribute.id)
-
- variables = {
- "type": "VARIANT",
- "productTypeId": product_type_id,
- "moves": [{"id": attribute_id, "sortOrder": 1}],
- }
-
- content = get_graphql_content(
- staff_api_client.post_graphql(
- ATTRIBUTES_RESORT_QUERY,
- variables,
- permissions=[permission_manage_product_types_and_attributes],
- )
- )["data"]["productTypeReorderAttributes"]
-
- assert content["errors"] == [
- {
- "field": "moves",
- "message": f"Couldn't resolve to an attribute: {attribute_id}",
- }
- ]
-
-
- "attribute_type, relation_field, backref_field",
- (
- ("VARIANT", "variant_attributes", "attributevariant"),
- ("PRODUCT", "product_attributes", "attributeproduct"),
- ),
-)
-def test_sort_attributes_within_product_type(
- staff_api_client,
- attribute_list,
- permission_manage_product_types_and_attributes,
- attribute_type,
- relation_field,
- backref_field,
-):
- attributes = attribute_list
- assert len(attributes) == 3
-
- staff_api_client.user.user_permissions.add(
- permission_manage_product_types_and_attributes
- )
-
- product_type = ProductType.objects.create(name="Dummy Type")
- product_type_id = graphene.Node.to_global_id("ProductType", product_type.id)
- m2m_attributes = getattr(product_type, relation_field)
- m2m_attributes.set(attributes)
-
- sort_method = getattr(m2m_attributes, f"{relation_field}_sorted")
- attributes = list(sort_method())
-
- assert len(attributes) == 3
-
- variables = {
- "type": attribute_type,
- "productTypeId": product_type_id,
- "moves": [
- {
- "id": graphene.Node.to_global_id("Attribute", attributes[0].pk),
- "sortOrder": +1,
- },
- {
- "id": graphene.Node.to_global_id("Attribute", attributes[2].pk),
- "sortOrder": -1,
- },
- ],
- }
-
- expected_order = [attributes[1].pk, attributes[2].pk, attributes[0].pk]
-
- content = get_graphql_content(
- staff_api_client.post_graphql(ATTRIBUTES_RESORT_QUERY, variables)
- )["data"]["productTypeReorderAttributes"]
- assert not content["errors"]
-
- assert (
- content["productType"]["id"] == product_type_id
- ), "Did not return the correct product type"
-
- gql_attributes = content["productType"][snake_to_camel_case(relation_field)]
- assert len(gql_attributes) == len(expected_order)
+ gql_attributes = content["productType"][snake_to_camel_case(relation_field)]
+ assert len(gql_attributes) == len(expected_order)
for attr, expected_pk in zip(gql_attributes, expected_order):
gql_type, gql_attr_id = graphene.Node.from_global_id(attr["id"])
assert gql_type == "Attribute"
assert int(gql_attr_id) == expected_pk
-
-
-ATTRIBUTE_VALUES_RESORT_QUERY = """
- mutation attributeReorderValues($attributeId: ID!, $moves: [ReorderInput]!) {
- attributeReorderValues(attributeId: $attributeId, moves: $moves) {
- attribute {
- id
- values {
- id
- }
- }
-
- errors {
- field
- message
- }
- }
- }
-"""
-
-
-def test_sort_values_within_attribute_invalid_product_type(
- staff_api_client, permission_manage_product_types_and_attributes
-):
- """Try to reorder an invalid attribute (invalid ID)."""
-
- attribute_id = graphene.Node.to_global_id("Attribute", -1)
- value_id = graphene.Node.to_global_id("AttributeValue", -1)
-
- variables = {
- "attributeId": attribute_id,
- "moves": [{"id": value_id, "sortOrder": 1}],
- }
-
- content = get_graphql_content(
- staff_api_client.post_graphql(
- ATTRIBUTE_VALUES_RESORT_QUERY,
- variables,
- permissions=[permission_manage_product_types_and_attributes],
- )
- )["data"]["attributeReorderValues"]
-
- assert content["errors"] == [
- {
- "field": "attributeId",
- "message": f"Couldn't resolve to an attribute: {attribute_id}",
- }
- ]
-
-
-def test_sort_values_within_attribute_invalid_id(
- staff_api_client, permission_manage_product_types_and_attributes, color_attribute
-):
- """Try to reorder a value not associated to the given attribute."""
-
- attribute_id = graphene.Node.to_global_id("Attribute", color_attribute.id)
- value_id = graphene.Node.to_global_id("AttributeValue", -1)
-
- variables = {
- "type": "VARIANT",
- "attributeId": attribute_id,
- "moves": [{"id": value_id, "sortOrder": 1}],
- }
-
- content = get_graphql_content(
- staff_api_client.post_graphql(
- ATTRIBUTE_VALUES_RESORT_QUERY,
- variables,
- permissions=[permission_manage_product_types_and_attributes],
- )
- )["data"]["attributeReorderValues"]
-
- assert content["errors"] == [
- {
- "field": "moves",
- "message": f"Couldn't resolve to an attribute value: {value_id}",
- }
- ]
-
-
-def test_sort_values_within_attribute(
- staff_api_client, color_attribute, permission_manage_product_types_and_attributes
-):
- attribute = color_attribute
- AttributeValue.objects.create(attribute=attribute, name="Green", slug="green")
- values = list(attribute.values.all())
- assert len(values) == 3
-
- staff_api_client.user.user_permissions.add(
- permission_manage_product_types_and_attributes
- )
-
- attribute_id = graphene.Node.to_global_id("Attribute", attribute.id)
- m2m_values = attribute.values
- m2m_values.set(values)
-
- assert values == sorted(
- values, key=lambda o: o.sort_order if o.sort_order is not None else o.pk
- ), "The values are not properly ordered"
-
- variables = {
- "attributeId": attribute_id,
- "moves": [
- {
- "id": graphene.Node.to_global_id("AttributeValue", values[0].pk),
- "sortOrder": +1,
- },
- {
- "id": graphene.Node.to_global_id("AttributeValue", values[2].pk),
- "sortOrder": -1,
- },
- ],
- }
-
- expected_order = [values[1].pk, values[2].pk, values[0].pk]
-
- content = get_graphql_content(
- staff_api_client.post_graphql(ATTRIBUTE_VALUES_RESORT_QUERY, variables)
- )["data"]["attributeReorderValues"]
- assert not content["errors"]
-
- assert content["attribute"]["id"] == attribute_id
-
- gql_values = content["attribute"]["values"]
- assert len(gql_values) == len(expected_order)
-
- actual_order = []
-
- for attr, expected_pk in zip(gql_values, expected_order):
- gql_type, gql_attr_id = graphene.Node.from_global_id(attr["id"])
- assert gql_type == "AttributeValue"
- actual_order.append(int(gql_attr_id))
-
- assert actual_order == expected_order
-
-
-ATTRIBUTES_FILTER_QUERY = """
- query($filters: AttributeFilterInput!) {
- attributes(first: 10, filter: $filters) {
- edges {
- node {
- name
- slug
- }
- }
- }
- }
-"""
-
-
-def test_search_attributes(api_client, color_attribute, size_attribute):
- variables = {"filters": {"search": "color"}}
-
- attributes = get_graphql_content(
- api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables)
- )["data"]["attributes"]["edges"]
-
- assert len(attributes) == 1
- assert attributes[0]["node"]["slug"] == "color"
-
-
-def test_filter_attributes_if_filterable_in_dashboard(
- api_client, color_attribute, size_attribute
-):
- color_attribute.filterable_in_dashboard = False
- color_attribute.save(update_fields=["filterable_in_dashboard"])
-
- variables = {"filters": {"filterableInDashboard": True}}
-
- attributes = get_graphql_content(
- api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables)
- )["data"]["attributes"]["edges"]
-
- assert len(attributes) == 1
- assert attributes[0]["node"]["slug"] == "size"
-
-
-def test_filter_attributes_if_available_in_grid(
- api_client, color_attribute, size_attribute
-):
- color_attribute.available_in_grid = False
- color_attribute.save(update_fields=["available_in_grid"])
-
- variables = {"filters": {"availableInGrid": True}}
-
- attributes = get_graphql_content(
- api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables)
- )["data"]["attributes"]["edges"]
-
- assert len(attributes) == 1
- assert attributes[0]["node"]["slug"] == "size"
-
-
-def test_filter_attributes_by_global_id_list(api_client, attribute_list):
- global_ids = [
- graphene.Node.to_global_id("Attribute", attribute.pk)
- for attribute in attribute_list[:2]
- ]
- variables = {"filters": {"ids": global_ids}}
-
- expected_slugs = sorted([attribute_list[0].slug, attribute_list[1].slug])
-
- attributes = get_graphql_content(
- api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables)
- )["data"]["attributes"]["edges"]
-
- assert len(attributes) == 2
- received_slugs = sorted(
- [attributes[0]["node"]["slug"], attributes[1]["node"]["slug"]]
- )
-
- assert received_slugs == expected_slugs
-
-
-def test_filter_attributes_in_category_not_visible_in_listings_by_customer(
- user_api_client, product_list, weight_attribute, channel_USD
-):
- # given
- product_type = ProductType.objects.create(
- name="Default Type 2",
- slug="default-type-2",
- has_variants=True,
- is_shipping_required=True,
- )
- product_type.product_attributes.add(weight_attribute)
-
- last_product = product_list[-1]
- last_product.product_type = product_type
- last_product.save(update_fields=["product_type"])
- last_product.channel_listings.all().update(visible_in_listings=False)
-
- associate_attribute_values_to_instance(
- product_list[-1], weight_attribute, weight_attribute.values.first()
- )
-
- attribute_count = Attribute.objects.count()
-
- category = last_product.category
- variables = {
- "filters": {
- "inCategory": graphene.Node.to_global_id("Category", category.pk),
- "channel": channel_USD.slug,
- }
- }
-
- # when
- attributes = get_graphql_content(
- user_api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables)
- )["data"]["attributes"]["edges"]
-
- # then
- assert len(attributes) == attribute_count - 1
- assert weight_attribute.slug not in {
- attribute["node"]["slug"] for attribute in attributes
- }
-
-
-def test_filter_attributes_in_category_not_visible_in_listings_by_staff_with_perm(
- staff_api_client,
- product_list,
- weight_attribute,
- permission_manage_products,
- channel_USD,
-):
- # given
- staff_api_client.user.user_permissions.add(permission_manage_products)
-
- product_type = ProductType.objects.create(
- name="Default Type 2",
- slug="default-type-2",
- has_variants=True,
- is_shipping_required=True,
- )
- product_type.product_attributes.add(weight_attribute)
-
- last_product = product_list[-1]
- last_product.product_type = product_type
- last_product.save(update_fields=["product_type"])
- last_product.channel_listings.all().update(visible_in_listings=False)
-
- associate_attribute_values_to_instance(
- product_list[-1], weight_attribute, weight_attribute.values.first()
- )
-
- attribute_count = Attribute.objects.count()
-
- category = last_product.category
- variables = {
- "filters": {
- "inCategory": graphene.Node.to_global_id("Category", category.pk),
- "channel": channel_USD.slug,
- }
- }
-
- # when
- attributes = get_graphql_content(
- staff_api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables)
- )["data"]["attributes"]["edges"]
-
- # then
- assert len(attributes) == attribute_count
-
-
-def test_filter_attributes_in_category_not_visible_in_listings_by_staff_without_perm(
- staff_api_client,
- product_list,
- weight_attribute,
- permission_manage_products,
- channel_USD,
-):
- # given
- product_type = ProductType.objects.create(
- name="Default Type 2",
- slug="default-type-2",
- has_variants=True,
- is_shipping_required=True,
- )
- product_type.product_attributes.add(weight_attribute)
-
- last_product = product_list[-1]
- last_product.product_type = product_type
- last_product.save(update_fields=["product_type"])
- last_product.channel_listings.all().update(visible_in_listings=False)
-
- associate_attribute_values_to_instance(
- product_list[-1], weight_attribute, weight_attribute.values.first()
- )
-
- attribute_count = Attribute.objects.count()
-
- category = last_product.category
- variables = {
- "filters": {
- "inCategory": graphene.Node.to_global_id("Category", category.pk),
- "channel": channel_USD.slug,
- }
- }
-
- # when
- attributes = get_graphql_content(
- staff_api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables)
- )["data"]["attributes"]["edges"]
-
- # then
- assert len(attributes) == attribute_count - 1
- assert weight_attribute.slug not in {
- attribute["node"]["slug"] for attribute in attributes
- }
-
-
-def test_filter_attributes_in_category_not_visible_in_listings_by_app_with_perm(
- app_api_client,
- product_list,
- weight_attribute,
- permission_manage_products,
- channel_USD,
-):
- # given
- app_api_client.app.permissions.add(permission_manage_products)
-
- product_type = ProductType.objects.create(
- name="Default Type 2",
- slug="default-type-2",
- has_variants=True,
- is_shipping_required=True,
- )
- product_type.product_attributes.add(weight_attribute)
-
- last_product = product_list[-1]
- last_product.product_type = product_type
- last_product.save(update_fields=["product_type"])
- last_product.channel_listings.all().update(visible_in_listings=False)
-
- associate_attribute_values_to_instance(
- product_list[-1], weight_attribute, weight_attribute.values.first()
- )
-
- attribute_count = Attribute.objects.count()
-
- category = last_product.category
- variables = {
- "filters": {
- "inCategory": graphene.Node.to_global_id("Category", category.pk),
- "channel": channel_USD.slug,
- }
- }
-
- # when
- attributes = get_graphql_content(
- app_api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables)
- )["data"]["attributes"]["edges"]
-
- # then
- assert len(attributes) == attribute_count
-
-
-def test_filter_attributes_in_category_not_visible_in_listings_by_app_without_perm(
- app_api_client,
- product_list,
- weight_attribute,
- permission_manage_products,
- channel_USD,
-):
- # given
- product_type = ProductType.objects.create(
- name="Default Type 2",
- slug="default-type-2",
- has_variants=True,
- is_shipping_required=True,
- )
- product_type.product_attributes.add(weight_attribute)
-
- last_product = product_list[-1]
- last_product.product_type = product_type
- last_product.save(update_fields=["product_type"])
- last_product.channel_listings.all().update(visible_in_listings=False)
-
- associate_attribute_values_to_instance(
- product_list[-1], weight_attribute, weight_attribute.values.first()
- )
-
- attribute_count = Attribute.objects.count()
-
- category = last_product.category
- variables = {
- "filters": {
- "inCategory": graphene.Node.to_global_id("Category", category.pk),
- "channel": channel_USD.slug,
- }
- }
-
- # when
- attributes = get_graphql_content(
- app_api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables)
- )["data"]["attributes"]["edges"]
-
- # then
- assert len(attributes) == attribute_count - 1
- assert weight_attribute.slug not in {
- attribute["node"]["slug"] for attribute in attributes
- }
-
-
-def test_filter_attributes_in_category_not_published_by_customer(
- user_api_client, product_list, weight_attribute, channel_USD
-):
- # given
- product_type = ProductType.objects.create(
- name="Default Type 2",
- slug="default-type-2",
- has_variants=True,
- is_shipping_required=True,
- )
- product_type.product_attributes.add(weight_attribute)
-
- last_product = product_list[-1]
- last_product.product_type = product_type
- last_product.save(update_fields=["product_type"])
- last_product.channel_listings.all().update(is_published=False)
-
- associate_attribute_values_to_instance(
- product_list[-1], weight_attribute, weight_attribute.values.first()
- )
-
- attribute_count = Attribute.objects.count()
-
- category = last_product.category
- variables = {
- "filters": {
- "inCategory": graphene.Node.to_global_id("Category", category.pk),
- "channel": channel_USD.slug,
- },
- }
-
- # when
- attributes = get_graphql_content(
- user_api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables)
- )["data"]["attributes"]["edges"]
-
- # then
- assert len(attributes) == attribute_count - 1
- assert weight_attribute.slug not in {
- attribute["node"]["slug"] for attribute in attributes
- }
-
-
-def test_filter_attributes_in_category_not_published_by_staff_with_perm(
- staff_api_client,
- product_list,
- weight_attribute,
- permission_manage_products,
- channel_USD,
-):
- # given
- staff_api_client.user.user_permissions.add(permission_manage_products)
-
- product_type = ProductType.objects.create(
- name="Default Type 2",
- slug="default-type-2",
- has_variants=True,
- is_shipping_required=True,
- )
- product_type.product_attributes.add(weight_attribute)
-
- last_product = product_list[-1]
- last_product.product_type = product_type
- last_product.save(update_fields=["product_type"])
- last_product.channel_listings.all().update(is_published=False)
-
- associate_attribute_values_to_instance(
- product_list[-1], weight_attribute, weight_attribute.values.first()
- )
-
- attribute_count = Attribute.objects.count()
-
- category = last_product.category
- variables = {
- "filters": {
- "inCategory": graphene.Node.to_global_id("Category", category.pk),
- "channel": channel_USD.slug,
- }
- }
-
- # when
- attributes = get_graphql_content(
- staff_api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables)
- )["data"]["attributes"]["edges"]
-
- # then
- assert len(attributes) == attribute_count
-
-
-def test_filter_attributes_in_category_not_published_by_staff_without_perm(
- staff_api_client,
- product_list,
- weight_attribute,
- permission_manage_products,
- channel_USD,
-):
- # given
- product_type = ProductType.objects.create(
- name="Default Type 2",
- slug="default-type-2",
- has_variants=True,
- is_shipping_required=True,
- )
- product_type.product_attributes.add(weight_attribute)
-
- last_product = product_list[-1]
- last_product.product_type = product_type
- last_product.save(update_fields=["product_type"])
- last_product.channel_listings.all().update(is_published=False)
-
- associate_attribute_values_to_instance(
- product_list[-1], weight_attribute, weight_attribute.values.first()
- )
-
- attribute_count = Attribute.objects.count()
-
- category = last_product.category
- variables = {
- "filters": {
- "inCategory": graphene.Node.to_global_id("Category", category.pk),
- "channel": channel_USD.slug,
- }
- }
-
- # when
- attributes = get_graphql_content(
- staff_api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables)
- )["data"]["attributes"]["edges"]
-
- # then
- assert len(attributes) == attribute_count - 1
- assert weight_attribute.slug not in {
- attribute["node"]["slug"] for attribute in attributes
- }
-
-
-def test_filter_attributes_in_category_not_published_by_app_with_perm(
- app_api_client,
- product_list,
- weight_attribute,
- permission_manage_products,
- channel_USD,
-):
- # given
- app_api_client.app.permissions.add(permission_manage_products)
-
- product_type = ProductType.objects.create(
- name="Default Type 2",
- slug="default-type-2",
- has_variants=True,
- is_shipping_required=True,
- )
- product_type.product_attributes.add(weight_attribute)
-
- last_product = product_list[-1]
- last_product.product_type = product_type
- last_product.save(update_fields=["product_type"])
- last_product.channel_listings.all().update(is_published=False)
-
- associate_attribute_values_to_instance(
- product_list[-1], weight_attribute, weight_attribute.values.first()
- )
-
- attribute_count = Attribute.objects.count()
-
- category = last_product.category
- variables = {
- "filters": {
- "inCategory": graphene.Node.to_global_id("Category", category.pk),
- "channel": channel_USD.slug,
- }
- }
-
- # when
- attributes = get_graphql_content(
- app_api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables)
- )["data"]["attributes"]["edges"]
-
- # then
- assert len(attributes) == attribute_count
-
-
-def test_filter_attributes_in_category_not_published_by_app_without_perm(
- app_api_client,
- product_list,
- weight_attribute,
- permission_manage_products,
- channel_USD,
-):
- # given
- product_type = ProductType.objects.create(
- name="Default Type 2",
- slug="default-type-2",
- has_variants=True,
- is_shipping_required=True,
- )
- product_type.product_attributes.add(weight_attribute)
-
- last_product = product_list[-1]
- last_product.product_type = product_type
- last_product.save(update_fields=["product_type"])
- last_product.channel_listings.all().update(is_published=False)
-
- associate_attribute_values_to_instance(
- product_list[-1], weight_attribute, weight_attribute.values.first()
- )
-
- attribute_count = Attribute.objects.count()
-
- category = last_product.category
- variables = {
- "filters": {
- "inCategory": graphene.Node.to_global_id("Category", category.pk),
- "channel": channel_USD.slug,
- }
- }
-
- # when
- attributes = get_graphql_content(
- app_api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables)
- )["data"]["attributes"]["edges"]
-
- # then
- assert len(attributes) == attribute_count - 1
- assert weight_attribute.slug not in {
- attribute["node"]["slug"] for attribute in attributes
- }
-
-
-def test_filter_attributes_in_collection_not_visible_in_listings_by_customer(
- user_api_client, product_list, weight_attribute, collection, channel_USD
-):
- # given
- product_type = ProductType.objects.create(
- name="Default Type 2",
- slug="default-type-2",
- has_variants=True,
- is_shipping_required=True,
- )
- product_type.product_attributes.add(weight_attribute)
-
- last_product = product_list[-1]
- last_product.product_type = product_type
- last_product.save(update_fields=["product_type"])
- last_product.channel_listings.all().update(visible_in_listings=False)
-
- for product in product_list:
- collection.products.add(product)
-
- associate_attribute_values_to_instance(
- product_list[-1], weight_attribute, weight_attribute.values.first()
- )
-
- attribute_count = Attribute.objects.count()
-
- variables = {
- "filters": {
- "inCollection": graphene.Node.to_global_id("Collection", collection.pk),
- "channel": channel_USD.slug,
- }
- }
-
- # when
- attributes = get_graphql_content(
- user_api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables)
- )["data"]["attributes"]["edges"]
-
- # then
- assert len(attributes) == attribute_count
-
-
-def test_filter_in_collection_not_published_by_customer(
- user_api_client, product_list, weight_attribute, collection, channel_USD
-):
- # given
- product_type = ProductType.objects.create(
- name="Default Type 2",
- slug="default-type-2",
- has_variants=True,
- is_shipping_required=True,
- )
- product_type.product_attributes.add(weight_attribute)
-
- last_product = product_list[-1]
- last_product.product_type = product_type
- last_product.save(update_fields=["product_type"])
- last_product.channel_listings.all().update(is_published=False)
-
- for product in product_list:
- collection.products.add(product)
-
- associate_attribute_values_to_instance(
- product_list[-1], weight_attribute, weight_attribute.values.first()
- )
-
- attribute_count = Attribute.objects.count()
-
- variables = {
- "filters": {
- "inCollection": graphene.Node.to_global_id("Collection", collection.pk),
- "channel": channel_USD.slug,
- }
- }
-
- # when
- attributes = get_graphql_content(
- user_api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables)
- )["data"]["attributes"]["edges"]
-
- # then
- assert len(attributes) == attribute_count - 1
- assert weight_attribute.slug not in {
- attribute["node"]["slug"] for attribute in attributes
- }
-
-
-def test_filter_in_collection_not_published_by_staff_with_perm(
- staff_api_client,
- product_list,
- weight_attribute,
- permission_manage_products,
- collection,
- channel_USD,
-):
- # given
- staff_api_client.user.user_permissions.add(permission_manage_products)
-
- product_type = ProductType.objects.create(
- name="Default Type 2",
- slug="default-type-2",
- has_variants=True,
- is_shipping_required=True,
- )
- product_type.product_attributes.add(weight_attribute)
-
- last_product = product_list[-1]
- last_product.product_type = product_type
- last_product.save(update_fields=["product_type"])
- last_product.channel_listings.all().update(is_published=False)
-
- for product in product_list:
- collection.products.add(product)
-
- associate_attribute_values_to_instance(
- product_list[-1], weight_attribute, weight_attribute.values.first()
- )
-
- attribute_count = Attribute.objects.count()
-
- variables = {
- "filters": {
- "inCollection": graphene.Node.to_global_id("Collection", collection.pk),
- "channel": channel_USD.slug,
- }
- }
-
- # when
- attributes = get_graphql_content(
- staff_api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables)
- )["data"]["attributes"]["edges"]
-
- # then
- assert len(attributes) == attribute_count
-
-
-def test_filter_in_collection_not_published_by_staff_without_perm(
- staff_api_client,
- product_list,
- weight_attribute,
- permission_manage_products,
- collection,
- channel_USD,
-):
- # given
- product_type = ProductType.objects.create(
- name="Default Type 2",
- slug="default-type-2",
- has_variants=True,
- is_shipping_required=True,
- )
- product_type.product_attributes.add(weight_attribute)
-
- last_product = product_list[-1]
- last_product.product_type = product_type
- last_product.save(update_fields=["product_type"])
- last_product.channel_listings.all().update(is_published=False)
-
- for product in product_list:
- collection.products.add(product)
-
- associate_attribute_values_to_instance(
- product_list[-1], weight_attribute, weight_attribute.values.first()
- )
-
- attribute_count = Attribute.objects.count()
-
- variables = {
- "filters": {
- "inCollection": graphene.Node.to_global_id("Collection", collection.pk),
- "channel": channel_USD.slug,
- }
- }
-
- # when
- attributes = get_graphql_content(
- staff_api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables)
- )["data"]["attributes"]["edges"]
-
- # then
- assert len(attributes) == attribute_count - 1
- assert weight_attribute.slug not in {
- attribute["node"]["slug"] for attribute in attributes
- }
-
-
-def test_filter_in_collection_not_published_by_app_with_perm(
- app_api_client,
- product_list,
- weight_attribute,
- permission_manage_products,
- collection,
- channel_USD,
-):
- # given
- app_api_client.app.permissions.add(permission_manage_products)
-
- product_type = ProductType.objects.create(
- name="Default Type 2",
- slug="default-type-2",
- has_variants=True,
- is_shipping_required=True,
- )
- product_type.product_attributes.add(weight_attribute)
-
- last_product = product_list[-1]
- last_product.product_type = product_type
- last_product.save(update_fields=["product_type"])
- last_product.channel_listings.all().update(is_published=False)
-
- for product in product_list:
- collection.products.add(product)
-
- associate_attribute_values_to_instance(
- product_list[-1], weight_attribute, weight_attribute.values.first()
- )
-
- attribute_count = Attribute.objects.count()
-
- variables = {
- "filters": {
- "inCollection": graphene.Node.to_global_id("Collection", collection.pk),
- "channel": channel_USD.slug,
- }
- }
-
- # when
- attributes = get_graphql_content(
- app_api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables)
- )["data"]["attributes"]["edges"]
-
- # then
- assert len(attributes) == attribute_count
-
-
-def test_filter_in_collection_not_published_by_app_without_perm(
- app_api_client,
- product_list,
- weight_attribute,
- permission_manage_products,
- collection,
- channel_USD,
-):
- # given
- product_type = ProductType.objects.create(
- name="Default Type 2",
- slug="default-type-2",
- has_variants=True,
- is_shipping_required=True,
- )
- product_type.product_attributes.add(weight_attribute)
-
- last_product = product_list[-1]
- last_product.product_type = product_type
- last_product.save(update_fields=["product_type"])
- last_product.channel_listings.all().update(is_published=False)
-
- for product in product_list:
- collection.products.add(product)
-
- associate_attribute_values_to_instance(
- product_list[-1], weight_attribute, weight_attribute.values.first()
- )
-
- attribute_count = Attribute.objects.count()
-
- variables = {
- "filters": {
- "inCollection": graphene.Node.to_global_id("Collection", collection.pk),
- "channel": channel_USD.slug,
- }
- }
-
- # when
- attributes = get_graphql_content(
- app_api_client.post_graphql(ATTRIBUTES_FILTER_QUERY, variables)
- )["data"]["attributes"]["edges"]
-
- # then
- assert len(attributes) == attribute_count - 1
- assert weight_attribute.slug not in {
- attribute["node"]["slug"] for attribute in attributes
- }
-
-
-ATTRIBUTES_SORT_QUERY = """
- query($sortBy: AttributeSortingInput) {
- attributes(first: 10, sortBy: $sortBy) {
- edges {
- node {
- slug
- }
- }
- }
- }
-"""
-
-
-def test_sort_attributes_by_slug(api_client):
- Attribute.objects.bulk_create(
- [
- Attribute(name="MyAttribute", slug="b"),
- Attribute(name="MyAttribute", slug="a"),
- ]
- )
-
- variables = {"sortBy": {"field": "SLUG", "direction": "ASC"}}
-
- attributes = get_graphql_content(
- api_client.post_graphql(ATTRIBUTES_SORT_QUERY, variables)
- )["data"]["attributes"]["edges"]
-
- assert len(attributes) == 2
- assert attributes[0]["node"]["slug"] == "a"
- assert attributes[1]["node"]["slug"] == "b"
-
-
-def test_sort_attributes_by_default_sorting(api_client):
- """Don't provide any sorting, this should sort by slug by default."""
- Attribute.objects.bulk_create(
- [Attribute(name="A", slug="b"), Attribute(name="B", slug="a")]
- )
-
- attributes = get_graphql_content(
- api_client.post_graphql(ATTRIBUTES_SORT_QUERY, {})
- )["data"]["attributes"]["edges"]
-
- assert len(attributes) == 2
- assert attributes[0]["node"]["slug"] == "a"
- assert attributes[1]["node"]["slug"] == "b"
-
-
[email protected]("is_variant", (True, False))
-def test_attributes_of_products_are_sorted(
- user_api_client, product, color_attribute, is_variant, channel_USD
-):
- """Ensures the attributes of products and variants are sorted."""
-
- variant = product.variants.first()
-
- if is_variant:
- query = """
- query($id: ID!, $channel: String) {
- productVariant(id: $id, channel: $channel) {
- attributes {
- attribute {
- id
- }
- }
- }
- }
- """
- else:
- query = """
- query($id: ID!, $channel: String) {
- product(id: $id, channel: $channel) {
- attributes {
- attribute {
- id
- }
- }
- }
- }
- """
-
- # Create a dummy attribute with a higher ID
- # This will allow us to make sure it is always the last attribute
- # when sorted by ID. Thus, we are sure the query is actually passing the test.
- other_attribute = Attribute.objects.create(name="Other", slug="other")
-
- # Add the attribute to the product type
- if is_variant:
- product.product_type.variant_attributes.set([color_attribute, other_attribute])
- else:
- product.product_type.product_attributes.set([color_attribute, other_attribute])
-
- # Retrieve the M2M object for the attribute vs the product type
- if is_variant:
- m2m_rel_other_attr = other_attribute.attributevariant.last()
- else:
- m2m_rel_other_attr = other_attribute.attributeproduct.last()
-
- # Push the last attribute to the top and let the others to None
- m2m_rel_other_attr.sort_order = 0
- m2m_rel_other_attr.save(update_fields=["sort_order"])
-
- # Assign attributes to the product
- node = variant if is_variant else product # type: Union[Product, ProductVariant]
- node.attributesrelated.clear()
- associate_attribute_values_to_instance(
- node, color_attribute, color_attribute.values.first()
- )
-
- # Sort the database attributes by their sort order and ID (when None)
- expected_order = [other_attribute.pk, color_attribute.pk]
-
- # Make the node ID
- if is_variant:
- node_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
- else:
- node_id = graphene.Node.to_global_id("Product", product.pk)
-
- # Retrieve the attributes
- data = get_graphql_content(
- user_api_client.post_graphql(
- query, {"id": node_id, "channel": channel_USD.slug}
- )
- )["data"]
- attributes = data["productVariant" if is_variant else "product"]["attributes"]
- actual_order = [
- int(graphene.Node.from_global_id(attr["attribute"]["id"])[1])
- for attr in attributes
- ]
-
- # Compare the received data against our expectations
- assert actual_order == expected_order
diff --git a/saleor/graphql/product/tests/test_bulk_delete.py b/saleor/graphql/product/tests/test_bulk_delete.py
index 763e3bc9aa..a00929aa23 100644
--- a/saleor/graphql/product/tests/test_bulk_delete.py
+++ b/saleor/graphql/product/tests/test_bulk_delete.py
@@ -8,8 +8,6 @@ from prices import Money, TaxedMoney
from ....order import OrderStatus
from ....order.models import OrderLine
from ....product.models import (
- Attribute,
- AttributeValue,
Category,
Collection,
Product,
@@ -38,75 +36,6 @@ def product_type_list():
return product_type_1, product_type_2, product_type_3
-def attribute_value_list(color_attribute):
- value_1 = AttributeValue.objects.create(
- slug="pink", name="Pink", attribute=color_attribute, value="#FF69B4"
- )
- value_2 = AttributeValue.objects.create(
- slug="white", name="White", attribute=color_attribute, value="#FFFFFF"
- )
- value_3 = AttributeValue.objects.create(
- slug="black", name="Black", attribute=color_attribute, value="#000000"
- )
- return value_1, value_2, value_3
-
-
-def test_delete_attributes(
- staff_api_client, attribute_list, permission_manage_products
-):
- query = """
- mutation attributeBulkDelete($ids: [ID]!) {
- attributeBulkDelete(ids: $ids) {
- count
- }
- }
- """
-
- variables = {
- "ids": [
- graphene.Node.to_global_id("Attribute", attr.id) for attr in attribute_list
- ]
- }
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_products]
- )
- content = get_graphql_content(response)
-
- assert content["data"]["attributeBulkDelete"]["count"] == 3
- assert not Attribute.objects.filter(
- id__in=[attr.id for attr in attribute_list]
- ).exists()
-
-
-def test_delete_attribute_values(
- staff_api_client, attribute_value_list, permission_manage_products
-):
- query = """
- mutation attributeValueBulkDelete($ids: [ID]!) {
- attributeValueBulkDelete(ids: $ids) {
- count
- }
- }
- """
-
- variables = {
- "ids": [
- graphene.Node.to_global_id("AttributeValue", val.id)
- for val in attribute_value_list
- ]
- }
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_products]
- )
- content = get_graphql_content(response)
-
- assert content["data"]["attributeValueBulkDelete"]["count"] == 3
- assert not AttributeValue.objects.filter(
- id__in=[val.id for val in attribute_value_list]
- ).exists()
-
-
MUTATION_CATEGORY_BULK_DELETE = """
mutation categoryBulkDelete($ids: [ID]!) {
categoryBulkDelete(ids: $ids) {
diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.py
index 771e0c7035..3e76352e06 100644
--- a/saleor/graphql/product/tests/test_product.py
+++ b/saleor/graphql/product/tests/test_product.py
@@ -13,16 +13,16 @@ from graphql_relay import to_global_id
from measurement.measures import Weight
from prices import Money, TaxedMoney
+from ....attribute import AttributeInputType, AttributeType
+from ....attribute.models import Attribute, AttributeValue
+from ....attribute.utils import associate_attribute_values_to_instance
from ....core.taxes import TaxType
from ....core.weight import WeightUnits
from ....order import OrderStatus
from ....order.models import OrderLine
from ....plugins.manager import PluginsManager
-from ....product import AttributeInputType
from ....product.error_codes import ProductErrorCode
from ....product.models import (
- Attribute,
- AttributeValue,
Category,
Collection,
CollectionChannelListing,
@@ -35,7 +35,6 @@ from ....product.models import (
)
from ....product.tasks import update_variants_names
from ....product.tests.utils import create_image, create_pdf_file_with_image_ext
-from ....product.utils.attributes import associate_attribute_values_to_instance
from ....product.utils.costs import get_product_costs_data
from ....warehouse.models import Allocation, Stock, Warehouse
from ...core.enums import ReportingPeriod
@@ -3550,6 +3549,7 @@ PRODUCT_TYPE_CREATE_MUTATION = """
field
message
code
+ attributes
}
}
@@ -3679,40 +3679,125 @@ def test_create_product_type_create_with_negative_weight(
assert error["code"] == ProductErrorCode.INVALID.name
-def test_product_type_update_mutation(
- staff_api_client, product_type, permission_manage_product_types_and_attributes
+def test_product_type_create_mutation_not_valid_attributes(
+ staff_api_client,
+ product_type,
+ permission_manage_product_types_and_attributes,
+ monkeypatch,
+ setup_vatlayer,
):
- query = """
- mutation updateProductType(
- $id: ID!,
- $name: String!,
- $hasVariants: Boolean!,
- $isShippingRequired: Boolean!,
- $productAttributes: [ID],
- ) {
- productTypeUpdate(
- id: $id,
- input: {
- name: $name,
- hasVariants: $hasVariants,
- isShippingRequired: $isShippingRequired,
- productAttributes: $productAttributes
- }) {
- productType {
- name
- slug
- isShippingRequired
- hasVariants
- variantAttributes {
- id
- }
- productAttributes {
- id
- }
+ # given
+ query = PRODUCT_TYPE_CREATE_MUTATION
+ product_type_name = "test type"
+ slug = "test-type"
+ has_variants = True
+ require_shipping = True
+
+ product_attributes = product_type.product_attributes.all()
+ product_page_attribute = product_attributes.last()
+ product_page_attribute.type = AttributeType.PAGE_TYPE
+ product_page_attribute.save(update_fields=["type"])
+
+ variant_attributes = product_type.variant_attributes.all()
+ variant_page_attribute = variant_attributes.last()
+ variant_page_attribute.type = AttributeType.PAGE_TYPE
+ variant_page_attribute.save(update_fields=["type"])
+
+ product_attributes_ids = [
+ graphene.Node.to_global_id("Attribute", att.id) for att in product_attributes
+ ]
+ variant_attributes_ids = [
+ graphene.Node.to_global_id("Attribute", att.id) for att in variant_attributes
+ ]
+
+ variables = {
+ "name": product_type_name,
+ "slug": slug,
+ "hasVariants": has_variants,
+ "taxCode": "wine",
+ "isShippingRequired": require_shipping,
+ "productAttributes": product_attributes_ids,
+ "variantAttributes": variant_attributes_ids,
+ }
+ initial_count = ProductType.objects.count()
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_product_types_and_attributes]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["productTypeCreate"]
+ errors = data["productErrors"]
+
+ assert len(errors) == 2
+ expected_errors = [
+ {
+ "code": ProductErrorCode.INVALID.name,
+ "field": "productAttributes",
+ "message": ANY,
+ "attributes": [
+ graphene.Node.to_global_id("Attribute", product_page_attribute.pk)
+ ],
+ },
+ {
+ "code": ProductErrorCode.INVALID.name,
+ "field": "variantAttributes",
+ "message": ANY,
+ "attributes": [
+ graphene.Node.to_global_id("Attribute", variant_page_attribute.pk)
+ ],
+ },
+ ]
+ for error in errors:
+ assert error in expected_errors
+
+ assert initial_count == ProductType.objects.count()
+
+
+PRODUCT_TYPE_UPDATE_MUTATION = """
+mutation updateProductType(
+ $id: ID!,
+ $name: String!,
+ $hasVariants: Boolean!,
+ $isShippingRequired: Boolean!,
+ $productAttributes: [ID],
+ ) {
+ productTypeUpdate(
+ id: $id,
+ input: {
+ name: $name,
+ hasVariants: $hasVariants,
+ isShippingRequired: $isShippingRequired,
+ productAttributes: $productAttributes
+ }) {
+ productType {
+ name
+ slug
+ isShippingRequired
+ hasVariants
+ variantAttributes {
+ id
+ }
+ productAttributes {
+ id
}
- }
}
- """
+ productErrors {
+ code
+ field
+ attributes
+ }
+ }
+ }
+"""
+
+
+def test_product_type_update_mutation(
+ staff_api_client, product_type, permission_manage_product_types_and_attributes
+):
+ query = PRODUCT_TYPE_UPDATE_MUTATION
product_type_name = "test type updated"
slug = product_type.slug
has_variants = True
@@ -3747,6 +3832,53 @@ def test_product_type_update_mutation(
assert len(data["variantAttributes"]) == (variant_attributes.count())
+def test_product_type_update_mutation_not_valid_attributes(
+ staff_api_client,
+ product_type,
+ permission_manage_product_types_and_attributes,
+ size_page_attribute,
+):
+ # given
+ query = PRODUCT_TYPE_UPDATE_MUTATION
+ product_type_name = "test type updated"
+ has_variants = True
+ require_shipping = False
+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.id)
+
+ # Test scenario: adding page attribute raise error
+
+ page_attribute_id = graphene.Node.to_global_id("Attribute", size_page_attribute.id)
+ product_attributes_ids = [
+ page_attribute_id,
+ graphene.Node.to_global_id(
+ "Attribute", product_type.product_attributes.first().pk
+ ),
+ ]
+
+ variables = {
+ "id": product_type_id,
+ "name": product_type_name,
+ "hasVariants": has_variants,
+ "isShippingRequired": require_shipping,
+ "productAttributes": product_attributes_ids,
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_product_types_and_attributes]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["productTypeUpdate"]
+ errors = data["productErrors"]
+
+ assert len(errors) == 1
+ assert errors[0]["field"] == "productAttributes"
+ assert errors[0]["code"] == ProductErrorCode.INVALID.name
+ assert errors[0]["attributes"] == [page_attribute_id]
+
+
UPDATE_PRODUCT_TYPE_SLUG_MUTATION = """
mutation($id: ID!, $slug: String) {
productTypeUpdate(
@@ -5107,7 +5239,7 @@ QUERY_AVAILABLE_ATTRIBUTES = """
"""
-def test_product_type_get_unassigned_attributes(
+def test_product_type_get_unassigned_product_type_attributes(
staff_api_client, permission_manage_products
):
query = QUERY_AVAILABLE_ATTRIBUTES
@@ -5121,22 +5253,39 @@ def test_product_type_get_unassigned_attributes(
unassigned_attributes = list(
Attribute.objects.bulk_create(
[
- Attribute(slug="size", name="Size"),
- Attribute(slug="weight", name="Weight"),
- Attribute(slug="thickness", name="Thickness"),
+ Attribute(slug="size", name="Size", type=AttributeType.PRODUCT_TYPE),
+ Attribute(
+ slug="weight", name="Weight", type=AttributeType.PRODUCT_TYPE
+ ),
+ Attribute(
+ slug="thickness", name="Thickness", type=AttributeType.PRODUCT_TYPE
+ ),
+ ]
+ )
+ )
+
+ unassigned_page_attributes = list(
+ Attribute.objects.bulk_create(
+ [
+ Attribute(slug="length", name="Length", type=AttributeType.PAGE_TYPE),
+ Attribute(slug="width", name="Width", type=AttributeType.PAGE_TYPE),
]
)
)
assigned_attributes = list(
Attribute.objects.bulk_create(
- [Attribute(slug="color", name="Color"), Attribute(slug="type", name="Type")]
+ [
+ Attribute(slug="color", name="Color", type=AttributeType.PRODUCT_TYPE),
+ Attribute(slug="type", name="Type", type=AttributeType.PRODUCT_TYPE),
+ ]
)
)
# Ensure that assigning them to another product type
# doesn't return an invalid response
ignored_product_type.product_attributes.add(*unassigned_attributes)
+ ignored_product_type.product_attributes.add(*unassigned_page_attributes)
# Assign the other attributes to the target product type
target_product_type.product_attributes.add(*assigned_attributes)
@@ -5169,9 +5318,9 @@ def test_product_type_get_unassigned_attributes(
def test_product_type_filter_unassigned_attributes(
- staff_api_client, permission_manage_products, attribute_list
+ staff_api_client, permission_manage_products, product_type_attribute_list
):
- expected_attribute = attribute_list[0]
+ expected_attribute = product_type_attribute_list[0]
query = QUERY_AVAILABLE_ATTRIBUTES
product_type = ProductType.objects.create(name="Empty Type")
product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
diff --git a/saleor/graphql/product/tests/test_product_pagination.py b/saleor/graphql/product/tests/test_product_pagination.py
index 8b7e0bf678..07e6cc397d 100644
--- a/saleor/graphql/product/tests/test_product_pagination.py
+++ b/saleor/graphql/product/tests/test_product_pagination.py
@@ -4,6 +4,7 @@ from decimal import Decimal
import graphene
import pytest
+from ....attribute.utils import associate_attribute_values_to_instance
from ....product.models import (
Category,
Collection,
@@ -14,7 +15,6 @@ from ....product.models import (
ProductVariant,
ProductVariantChannelListing,
)
-from ....product.utils.attributes import associate_attribute_values_to_instance
from ....warehouse.models import Stock
from ...tests.utils import get_graphql_content
diff --git a/saleor/graphql/product/tests/test_product_sorting_attributes.py b/saleor/graphql/product/tests/test_product_sorting_attributes.py
index 507b6f8315..a0c34205b7 100644
--- a/saleor/graphql/product/tests/test_product_sorting_attributes.py
+++ b/saleor/graphql/product/tests/test_product_sorting_attributes.py
@@ -4,8 +4,9 @@ from decimal import Decimal
import graphene
import pytest
+from ....attribute import AttributeType, models as attribute_models
+from ....attribute.utils import associate_attribute_values_to_instance
from ....product import models as product_models
-from ....product.utils.attributes import associate_attribute_values_to_instance
from ...tests.utils import get_graphql_content
HERE = os.path.realpath(os.path.dirname(__file__))
@@ -51,7 +52,7 @@ def products_structures(category, channel_USD):
assert product_models.Product.objects.count() == 0
- in_multivals = product_models.AttributeInputType.MULTISELECT
+ in_multivals = attribute_models.AttributeInputType.MULTISELECT
pt_apples, pt_oranges, pt_other = list(
product_models.ProductType.objects.bulk_create(
@@ -70,13 +71,20 @@ def products_structures(category, channel_USD):
)
colors_attr, trademark_attr, dummy_attr = list(
- product_models.Attribute.objects.bulk_create(
+ attribute_models.Attribute.objects.bulk_create(
[
- product_models.Attribute(
- name="Colors", slug="colors", input_type=in_multivals
+ attribute_models.Attribute(
+ name="Colors",
+ slug="colors",
+ input_type=in_multivals,
+ type=AttributeType.PRODUCT_TYPE,
+ ),
+ attribute_models.Attribute(
+ name="Trademark", slug="trademark", type=AttributeType.PRODUCT_TYPE
+ ),
+ attribute_models.Attribute(
+ name="Dummy", slug="dummy", type=AttributeType.PRODUCT_TYPE
),
- product_models.Attribute(name="Trademark", slug="trademark"),
- product_models.Attribute(name="Dummy", slug="dummy"),
]
)
)
@@ -552,8 +560,10 @@ def test_sort_product_not_having_attribute_data(api_client, category, count_quer
)
# Assign an attribute to the product type
- attribute = product_models.Attribute.objects.create(name="Kind", slug="kind")
- value = product_models.AttributeValue.objects.create(
+ attribute = attribute_models.Attribute.objects.create(
+ name="Kind", slug="kind", type=AttributeType.PRODUCT_TYPE
+ )
+ value = attribute_models.AttributeValue.objects.create(
name="Value", slug="value", attribute=attribute
)
product_type.product_attributes.add(attribute)
@@ -621,8 +631,8 @@ def test_sort_product_by_attribute_using_attribute_having_no_products(
"""Ensure passing an empty attribute ID as sorting field does nothing."""
query = QUERY_SORT_PRODUCTS_BY_ATTRIBUTE
- attribute_without_products = product_models.Attribute.objects.create(
- name="Colors 2", slug="colors-2"
+ attribute_without_products = attribute_models.Attribute.objects.create(
+ name="Colors 2", slug="colors-2", type=AttributeType.PRODUCT_TYPE
)
attribute_id: str = graphene.Node.to_global_id(
diff --git a/saleor/graphql/product/tests/test_utils.py b/saleor/graphql/product/tests/test_utils.py
index f8ed3220c9..5f6cfd1b7e 100644
--- a/saleor/graphql/product/tests/test_utils.py
+++ b/saleor/graphql/product/tests/test_utils.py
@@ -1,14 +1,17 @@
import graphene
-from ....product import AttributeInputType
+from ....attribute import AttributeInputType
+from ....page.error_codes import PageErrorCode
from ....product.error_codes import ProductErrorCode
from ..utils import (
- validate_attributes_input_for_product,
+ validate_attributes_input_for_product_and_page,
validate_attributes_input_for_variant,
)
-def test_validate_attributes_input_for_product(weight_attribute, color_attribute):
+def test_validate_attributes_input_for_product(
+ weight_attribute, color_attribute, product_type
+):
# given
color_attribute.value_required = True
color_attribute.save(update_fields=["value_required"])
@@ -19,14 +22,16 @@ def test_validate_attributes_input_for_product(weight_attribute, color_attribute
input_data = [(weight_attribute, ["a"]), (color_attribute, ["b"])]
# when
- errors = validate_attributes_input_for_product(input_data)
+ errors = validate_attributes_input_for_product_and_page(
+ input_data, product_type.product_attributes.all(), ProductErrorCode
+ )
# then
assert not errors
def test_validate_attributes_input_for_product_no_values_given(
- weight_attribute, color_attribute
+ weight_attribute, color_attribute, product_type
):
# given
color_attribute.value_required = True
@@ -38,7 +43,9 @@ def test_validate_attributes_input_for_product_no_values_given(
input_data = [(weight_attribute, []), (color_attribute, [])]
# when
- errors = validate_attributes_input_for_product(input_data)
+ errors = validate_attributes_input_for_product_and_page(
+ input_data, product_type.product_attributes.all(), ProductErrorCode
+ )
# then
assert len(errors) == 1
@@ -51,7 +58,7 @@ def test_validate_attributes_input_for_product_no_values_given(
def test_validate_attributes_input_for_product_too_many_values_given(
- weight_attribute, color_attribute
+ weight_attribute, color_attribute, product_type
):
# given
color_attribute.input_type = AttributeInputType.DROPDOWN
@@ -65,7 +72,9 @@ def test_validate_attributes_input_for_product_too_many_values_given(
input_data = [(weight_attribute, ["abc", "efg"]), (color_attribute, ["a", "b"])]
# when
- errors = validate_attributes_input_for_product(input_data)
+ errors = validate_attributes_input_for_product_and_page(
+ input_data, product_type.product_attributes.all(), ProductErrorCode
+ )
# then
assert len(errors) == 1
@@ -77,7 +86,7 @@ def test_validate_attributes_input_for_product_too_many_values_given(
def test_validate_attributes_input_for_product_empty_values_given(
- weight_attribute, color_attribute
+ weight_attribute, color_attribute, product_type
):
# given
color_attribute.input_type = AttributeInputType.DROPDOWN
@@ -91,7 +100,9 @@ def test_validate_attributes_input_for_product_empty_values_given(
input_data = [(weight_attribute, ["a", None]), (color_attribute, [" "])]
# when
- errors = validate_attributes_input_for_product(input_data)
+ errors = validate_attributes_input_for_product_and_page(
+ input_data, product_type.product_attributes.all(), ProductErrorCode
+ )
# then
assert len(errors) == 1
@@ -103,8 +114,36 @@ def test_validate_attributes_input_for_product_empty_values_given(
}
+def test_validate_attributes_input_for_product_lack_of_required_attribute(
+ weight_attribute, color_attribute, product_type
+):
+ # given
+ product_attributes = product_type.product_attributes.all()
+ attr = product_attributes.first()
+ attr.value_required = True
+ attr.save(update_fields=["value_required"])
+
+ weight_attribute.value_required = True
+ weight_attribute.save(update_fields=["value_required"])
+
+ input_data = [(weight_attribute, ["a"])]
+
+ # when
+ errors = validate_attributes_input_for_product_and_page(
+ input_data, product_attributes, ProductErrorCode
+ )
+
+ # then
+ assert len(errors) == 1
+ error = errors[0]
+ assert error.code == ProductErrorCode.REQUIRED.value
+ assert set(error.params["attributes"]) == {
+ graphene.Node.to_global_id("Attribute", attr.pk)
+ }
+
+
def test_validate_attributes_input_for_product_multiply_errors(
- weight_attribute, color_attribute
+ weight_attribute, color_attribute, product_type
):
# given
color_attribute.input_type = AttributeInputType.DROPDOWN
@@ -118,7 +157,9 @@ def test_validate_attributes_input_for_product_multiply_errors(
input_data = [(weight_attribute, [None]), (color_attribute, ["a", "b"])]
# when
- errors = validate_attributes_input_for_product(input_data)
+ errors = validate_attributes_input_for_product_and_page(
+ input_data, product_type.product_attributes.all(), ProductErrorCode
+ )
# then
assert len(errors) == 2
@@ -132,6 +173,170 @@ def test_validate_attributes_input_for_product_multiply_errors(
}
+def test_validate_attributes_input_for_page(
+ weight_attribute, color_attribute, page_type
+):
+ # given
+ color_attribute.value_required = True
+ color_attribute.save(update_fields=["value_required"])
+
+ weight_attribute.value_required = True
+ weight_attribute.save(update_fields=["value_required"])
+
+ input_data = [(weight_attribute, ["a"]), (color_attribute, ["b"])]
+
+ # when
+ errors = validate_attributes_input_for_product_and_page(
+ input_data, page_type.page_attributes.all(), PageErrorCode
+ )
+
+ # then
+ assert not errors
+
+
+def test_validate_attributes_input_for_page_no_values_given(
+ weight_attribute, color_attribute, page_type
+):
+ # given
+ color_attribute.value_required = True
+ color_attribute.save(update_fields=["value_required"])
+
+ weight_attribute.value_required = True
+ weight_attribute.save(update_fields=["value_required"])
+
+ input_data = [(weight_attribute, []), (color_attribute, [])]
+
+ # when
+ errors = validate_attributes_input_for_product_and_page(
+ input_data, page_type.page_attributes.all(), PageErrorCode
+ )
+
+ # then
+ assert len(errors) == 1
+ error = errors[0]
+ assert error.code == PageErrorCode.REQUIRED.value
+ assert set(error.params["attributes"]) == {
+ graphene.Node.to_global_id("Attribute", attr.pk)
+ for attr in [weight_attribute, color_attribute]
+ }
+
+
+def test_validate_attributes_input_for_page_too_many_values_given(
+ weight_attribute, color_attribute, page_type
+):
+ # given
+ color_attribute.input_type = AttributeInputType.DROPDOWN
+ color_attribute.value_required = True
+ color_attribute.save(update_fields=["value_required", "input_type"])
+
+ weight_attribute.value_required = True
+ weight_attribute.input_type = AttributeInputType.MULTISELECT
+ weight_attribute.save(update_fields=["value_required", "input_type"])
+
+ input_data = [(weight_attribute, ["abc", "efg"]), (color_attribute, ["a", "b"])]
+
+ # when
+ errors = validate_attributes_input_for_product_and_page(
+ input_data, page_type.page_attributes.all(), PageErrorCode
+ )
+
+ # then
+ assert len(errors) == 1
+ error = errors[0]
+ assert error.code == PageErrorCode.INVALID.value
+ assert error.params["attributes"] == [
+ graphene.Node.to_global_id("Attribute", color_attribute.pk)
+ ]
+
+
+def test_validate_attributes_input_for_page_empty_values_given(
+ weight_attribute, color_attribute, page_type
+):
+ # given
+ color_attribute.input_type = AttributeInputType.DROPDOWN
+ color_attribute.value_required = True
+ color_attribute.save(update_fields=["value_required", "input_type"])
+
+ weight_attribute.value_required = True
+ weight_attribute.input_type = AttributeInputType.MULTISELECT
+ weight_attribute.save(update_fields=["value_required", "input_type"])
+
+ input_data = [(weight_attribute, ["a", None]), (color_attribute, [" "])]
+
+ # when
+ errors = validate_attributes_input_for_product_and_page(
+ input_data, page_type.page_attributes.all(), PageErrorCode
+ )
+
+ # then
+ assert len(errors) == 1
+ error = errors[0]
+ assert error.code == PageErrorCode.REQUIRED.value
+ assert set(error.params["attributes"]) == {
+ graphene.Node.to_global_id("Attribute", attr.pk)
+ for attr in [weight_attribute, color_attribute]
+ }
+
+
+def test_validate_attributes_input_for_page_lack_of_required_attribute(
+ weight_attribute, color_attribute, page_type
+):
+ # given
+ page_attributes = page_type.page_attributes.all()
+ attr = page_attributes.first()
+ attr.value_required = True
+ attr.save(update_fields=["value_required"])
+
+ weight_attribute.value_required = True
+ weight_attribute.save(update_fields=["value_required"])
+
+ input_data = [(weight_attribute, ["a"])]
+
+ # when
+ errors = validate_attributes_input_for_product_and_page(
+ input_data, page_attributes, PageErrorCode
+ )
+
+ # then
+ assert len(errors) == 1
+ error = errors[0]
+ assert error.code == PageErrorCode.REQUIRED.value
+ assert set(error.params["attributes"]) == {
+ graphene.Node.to_global_id("Attribute", attr.pk)
+ }
+
+
+def test_validate_attributes_input_for_page_multiply_errors(
+ weight_attribute, color_attribute, page_type
+):
+ # given
+ color_attribute.input_type = AttributeInputType.DROPDOWN
+ color_attribute.value_required = True
+ color_attribute.save(update_fields=["value_required", "input_type"])
+
+ weight_attribute.value_required = True
+ weight_attribute.input_type = AttributeInputType.MULTISELECT
+ weight_attribute.save(update_fields=["value_required", "input_type"])
+
+ input_data = [(weight_attribute, [None]), (color_attribute, ["a", "b"])]
+
+ # when
+ errors = validate_attributes_input_for_product_and_page(
+ input_data, page_type.page_attributes.all(), PageErrorCode
+ )
+
+ # then
+ assert len(errors) == 2
+ assert {error.code for error in errors} == {
+ PageErrorCode.INVALID.value,
+ PageErrorCode.REQUIRED.value,
+ }
+ assert {attr for error in errors for attr in error.params["attributes"]} == {
+ graphene.Node.to_global_id("Attribute", attr.pk)
+ for attr in [weight_attribute, color_attribute]
+ }
+
+
def test_validate_attributes_input_for_variant(weight_attribute, color_attribute):
# given
color_attribute.value_required = True
diff --git a/saleor/graphql/product/tests/test_variant.py b/saleor/graphql/product/tests/test_variant.py
index 3010799f8c..1689b7141f 100644
--- a/saleor/graphql/product/tests/test_variant.py
+++ b/saleor/graphql/product/tests/test_variant.py
@@ -6,12 +6,12 @@ import pytest
from measurement.measures import Weight
from prices import Money, TaxedMoney
+from ....attribute.utils import associate_attribute_values_to_instance
from ....core.weight import WeightUnits
from ....order import OrderStatus
from ....order.models import OrderLine
from ....product.error_codes import ProductErrorCode
from ....product.models import Product, ProductChannelListing, ProductVariant
-from ....product.utils.attributes import associate_attribute_values_to_instance
from ....warehouse.error_codes import StockErrorCode
from ....warehouse.models import Stock, Warehouse
from ...core.enums import WeightUnitsEnum
diff --git a/saleor/graphql/product/types/__init__.py b/saleor/graphql/product/types/__init__.py
index b74a702812..59e102e126 100644
--- a/saleor/graphql/product/types/__init__.py
+++ b/saleor/graphql/product/types/__init__.py
@@ -1,5 +1,4 @@
# flake8: noqa
-from .attributes import Attribute, AttributeValue, SelectedAttribute
from .digital_contents import DigitalContent, DigitalContentUrl
from .products import (
Category,
diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.py
index d6a1afde88..7d3c3cbf9e 100644
--- a/saleor/graphql/product/types/products.py
+++ b/saleor/graphql/product/types/products.py
@@ -6,6 +6,7 @@ from graphene import relay
from graphene_federation import key
from graphql.error import GraphQLError
+from ....attribute import models as attribute_models
from ....core.permissions import OrderPermissions, ProductPermissions
from ....core.weight import convert_weight_to_default_weight_unit
from ....product import models
@@ -24,6 +25,9 @@ from ....warehouse.availability import (
is_product_in_stock,
)
from ...account.enums import CountryCodeEnum
+from ...attribute.filters import AttributeFilterInput
+from ...attribute.resolvers import resolve_attributes
+from ...attribute.types import Attribute, SelectedAttribute
from ...channel import ChannelContext, ChannelQsContext
from ...channel.dataloaders import ChannelBySlugLoader
from ...channel.types import ChannelContextType, ChannelContextTypeWithMetadata
@@ -76,10 +80,8 @@ from ..dataloaders import (
VariantChannelListingByVariantIdLoader,
VariantsChannelListingByProductIdAndChanneSlugLoader,
)
-from ..filters import AttributeFilterInput, ProductFilterInput
-from ..resolvers import resolve_attributes
+from ..filters import ProductFilterInput
from ..sorters import ProductOrder
-from .attributes import Attribute, SelectedAttribute
from .channels import (
CollectionChannelListing,
ProductChannelListing,
@@ -825,7 +827,9 @@ class ProductType(CountableDjangoObjectType):
@staticmethod
@permission_required(ProductPermissions.MANAGE_PRODUCTS)
def resolve_available_attributes(root: models.ProductType, info, **kwargs):
- qs = models.Attribute.objects.get_unassigned_attributes(root.pk)
+ qs = attribute_models.Attribute.objects.get_unassigned_product_type_attributes(
+ root.pk
+ )
return resolve_attributes(info, qs=qs, **kwargs)
@staticmethod
diff --git a/saleor/graphql/product/utils.py b/saleor/graphql/product/utils.py
index 7411f382bb..e2f2f70fbc 100644
--- a/saleor/graphql/product/utils.py
+++ b/saleor/graphql/product/utils.py
@@ -4,31 +4,40 @@ from typing import TYPE_CHECKING, Dict, List, Tuple
import graphene
from django.core.exceptions import ValidationError
from django.db import transaction
+from django.db.models import Q
from django.db.utils import IntegrityError
-from ...product import AttributeInputType
+from ...attribute import AttributeInputType
from ...product.error_codes import ProductErrorCode
from ...warehouse.models import Stock
if TYPE_CHECKING:
from django.db.models import QuerySet
+ from ...attribute.models import Attribute
+ from ...product.models import ProductVariant
- from ...product.models import Attribute, ProductVariant
-
-def validate_attributes_input_for_product(
+def validate_attributes_input_for_product_and_page(
input_data: List[Tuple["Attribute", List[str]]],
+ attribute_qs: "QuerySet",
+ error_code_enum,
):
+ """Validate attribute input.
+
+ - ensure all required attributes are passed
+ - ensure the values are correct for a products or a page
+ """
+
error_no_value_given = ValidationError(
"Attribute expects a value but none were given",
- code=ProductErrorCode.REQUIRED.value,
+ code=error_code_enum.REQUIRED.value,
)
error_dropdown_get_more_than_one_value = ValidationError(
"Attribute attribute must take only one value",
- code=ProductErrorCode.INVALID.value,
+ code=error_code_enum.INVALID.value,
)
error_blank_value = ValidationError(
- "Attribute values cannot be blank", code=ProductErrorCode.REQUIRED.value,
+ "Attribute values cannot be blank", code=error_code_enum.REQUIRED.value,
)
attribute_errors: Dict[ValidationError, List[str]] = defaultdict(list)
@@ -50,7 +59,41 @@ def validate_attributes_input_for_product(
attribute_errors[error_blank_value].append(attribute_id)
continue
- return prepare_error_list_from_error_attribute_mapping(attribute_errors)
+ errors = prepare_error_list_from_error_attribute_mapping(attribute_errors)
+ errors = validate_required_attributes(
+ input_data, attribute_qs, errors, error_code_enum
+ )
+
+ return errors
+
+
+def validate_required_attributes(
+ input_data: List[Tuple["Attribute", List[str]]],
+ attribute_qs: "QuerySet",
+ errors: List[ValidationError],
+ error_code_enum,
+):
+ """Ensure all required attributes are supplied."""
+
+ supplied_attribute_pk = [attribute.pk for attribute, _ in input_data]
+
+ missing_required_attributes = attribute_qs.filter(
+ Q(value_required=True) & ~Q(pk__in=supplied_attribute_pk)
+ )
+
+ if missing_required_attributes:
+ ids = [
+ graphene.Node.to_global_id("Attribute", attr.pk)
+ for attr in missing_required_attributes
+ ]
+ error = ValidationError(
+ "All attributes flagged as having a value required must be supplied.",
+ code=error_code_enum.REQUIRED.value,
+ params={"attributes": ids},
+ )
+ errors.append(error)
+
+ return errors
def validate_attributes_input_for_variant(
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 7c3254ee98..659616c045 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -394,6 +394,7 @@ type Attribute implements Node & ObjectWithMetadata {
inputType: AttributeInputTypeEnum
name: String
slug: String
+ type: AttributeTypeEnum
values: [AttributeValue]
valueRequired: Boolean!
visibleInStorefront: Boolean!
@@ -404,21 +405,10 @@ type Attribute implements Node & ObjectWithMetadata {
storefrontSearchPosition: Int!
}
-type AttributeAssign {
- errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
- productType: ProductType
- productErrors: [ProductError!]!
-}
-
-input AttributeAssignInput {
- id: ID!
- type: AttributeTypeEnum!
-}
-
type AttributeBulkDelete {
errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
count: Int!
- productErrors: [ProductError!]!
+ attributeErrors: [AttributeError!]!
}
type AttributeCountableConnection {
@@ -435,13 +425,14 @@ type AttributeCountableEdge {
type AttributeCreate {
errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
attribute: Attribute
- productErrors: [ProductError!]!
+ attributeErrors: [AttributeError!]!
}
input AttributeCreateInput {
inputType: AttributeInputTypeEnum
name: String!
slug: String
+ type: AttributeTypeEnum!
values: [AttributeValueCreateInput]
valueRequired: Boolean
isVariantOnly: Boolean
@@ -454,10 +445,25 @@ input AttributeCreateInput {
type AttributeDelete {
errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
- productErrors: [ProductError!]!
+ attributeErrors: [AttributeError!]!
attribute: Attribute
}
+type AttributeError {
+ field: String
+ message: String
+ code: AttributeErrorCode!
+}
+
+enum AttributeErrorCode {
+ ALREADY_EXISTS
+ GRAPHQL_ERROR
+ INVALID
+ NOT_FOUND
+ REQUIRED
+ UNIQUE
+}
+
input AttributeFilterInput {
valueRequired: Boolean
isVariantOnly: Boolean
@@ -467,6 +473,7 @@ input AttributeFilterInput {
availableInGrid: Boolean
search: String
ids: [ID]
+ type: AttributeTypeEnum
inCollection: ID
inCategory: ID
channel: String
@@ -486,7 +493,7 @@ enum AttributeInputTypeEnum {
type AttributeReorderValues {
errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
attribute: Attribute
- productErrors: [ProductError!]!
+ attributeErrors: [AttributeError!]!
}
enum AttributeSortField {
@@ -526,20 +533,14 @@ type AttributeTranslation implements Node {
}
enum AttributeTypeEnum {
- PRODUCT
- VARIANT
-}
-
-type AttributeUnassign {
- errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
- productType: ProductType
- productErrors: [ProductError!]!
+ PRODUCT_TYPE
+ PAGE_TYPE
}
type AttributeUpdate {
errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
attribute: Attribute
- productErrors: [ProductError!]!
+ attributeErrors: [AttributeError!]!
}
input AttributeUpdateInput {
@@ -568,13 +569,13 @@ type AttributeValue implements Node {
type AttributeValueBulkDelete {
errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
count: Int!
- productErrors: [ProductError!]!
+ attributeErrors: [AttributeError!]!
}
type AttributeValueCreate {
errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
attribute: Attribute
- productErrors: [ProductError!]!
+ attributeErrors: [AttributeError!]!
attributeValue: AttributeValue
}
@@ -585,7 +586,7 @@ input AttributeValueCreateInput {
type AttributeValueDelete {
errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
attribute: Attribute
- productErrors: [ProductError!]!
+ attributeErrors: [AttributeError!]!
attributeValue: AttributeValue
}
@@ -623,7 +624,7 @@ enum AttributeValueType {
type AttributeValueUpdate {
errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
attribute: Attribute
- productErrors: [ProductError!]!
+ attributeErrors: [AttributeError!]!
attributeValue: AttributeValue
}
@@ -2561,19 +2562,8 @@ type Mutation {
shippingZoneDelete(id: ID!): ShippingZoneDelete
shippingZoneBulkDelete(ids: [ID]!): ShippingZoneBulkDelete
shippingZoneUpdate(id: ID!, input: ShippingZoneUpdateInput!): ShippingZoneUpdate
- attributeCreate(input: AttributeCreateInput!): AttributeCreate
- attributeDelete(id: ID!): AttributeDelete
- attributeBulkDelete(ids: [ID]!): AttributeBulkDelete
- attributeAssign(operations: [AttributeAssignInput]!, productTypeId: ID!): AttributeAssign
- attributeUnassign(attributeIds: [ID]!, productTypeId: ID!): AttributeUnassign
- attributeUpdate(id: ID!, input: AttributeUpdateInput!): AttributeUpdate
- attributeTranslate(id: ID!, input: NameTranslationInput!, languageCode: LanguageCodeEnum!): AttributeTranslate
- attributeValueCreate(attribute: ID!, input: AttributeValueCreateInput!): AttributeValueCreate
- attributeValueDelete(id: ID!): AttributeValueDelete
- attributeValueBulkDelete(ids: [ID]!): AttributeValueBulkDelete
- attributeValueUpdate(id: ID!, input: AttributeValueCreateInput!): AttributeValueUpdate
- attributeValueTranslate(id: ID!, input: NameTranslationInput!, languageCode: LanguageCodeEnum!): AttributeValueTranslate
- attributeReorderValues(attributeId: ID!, moves: [ReorderInput]!): AttributeReorderValues
+ productAttributeAssign(operations: [ProductAttributeAssignInput]!, productTypeId: ID!): ProductAttributeAssign
+ productAttributeUnassign(attributeIds: [ID]!, productTypeId: ID!): ProductAttributeUnassign
categoryCreate(input: CategoryInput!, parent: ID): CategoryCreate
categoryDelete(id: ID!): CategoryDelete
categoryBulkDelete(ids: [ID]!): CategoryBulkDelete
@@ -2604,7 +2594,7 @@ type Mutation {
productTypeDelete(id: ID!): ProductTypeDelete
productTypeBulkDelete(ids: [ID]!): ProductTypeBulkDelete
productTypeUpdate(id: ID!, input: ProductTypeInput!): ProductTypeUpdate
- productTypeReorderAttributes(moves: [ReorderInput]!, productTypeId: ID!, type: AttributeTypeEnum!): ProductTypeReorderAttributes
+ productTypeReorderAttributes(moves: [ReorderInput]!, productTypeId: ID!, type: ProductAttributeType!): ProductTypeReorderAttributes
digitalContentCreate(input: DigitalContentUploadInput!, variantId: ID!): DigitalContentCreate
digitalContentDelete(variantId: ID!): DigitalContentDelete
digitalContentUpdate(input: DigitalContentInput!, variantId: ID!): DigitalContentUpdate
@@ -2626,12 +2616,19 @@ type Mutation {
paymentRefund(amount: PositiveDecimal, paymentId: ID!): PaymentRefund
paymentVoid(paymentId: ID!): PaymentVoid
paymentInitialize(gateway: String!, paymentData: JSONString): PaymentInitialize
- pageCreate(input: PageInput!): PageCreate
+ pageCreate(input: PageCreateInput!): PageCreate
pageDelete(id: ID!): PageDelete
pageBulkDelete(ids: [ID]!): PageBulkDelete
pageBulkPublish(ids: [ID]!, isPublished: Boolean!): PageBulkPublish
pageUpdate(id: ID!, input: PageInput!): PageUpdate
pageTranslate(id: ID!, input: PageTranslationInput!, languageCode: LanguageCodeEnum!): PageTranslate
+ pageTypeCreate(input: PageTypeCreateInput!): PageTypeCreate
+ pageTypeUpdate(id: ID, input: PageTypeUpdateInput!): PageTypeUpdate
+ pageTypeDelete(id: ID!): PageTypeDelete
+ pageTypeBulkDelete(ids: [ID!]!): PageTypeBulkDelete
+ pageAttributeAssign(attributeIds: [ID!]!, pageTypeId: ID!): PageAttributeAssign
+ pageAttributeUnassign(attributeIds: [ID!]!, pageTypeId: ID!): PageAttributeUnassign
+ pageTypeReorderAttributes(moves: [ReorderInput!]!, pageTypeId: ID!): PageTypeReorderAttributes
draftOrderComplete(id: ID!): DraftOrderComplete
draftOrderCreate(input: DraftOrderCreateInput!): DraftOrderCreate
draftOrderDelete(id: ID!): DraftOrderDelete
@@ -2716,6 +2713,17 @@ type Mutation {
channelDelete(id: ID!, input: ChannelDeleteInput!): ChannelDelete
channelActivate(id: ID!): ChannelActivate
channelDeactivate(id: ID!): ChannelDeactivate
+ attributeCreate(input: AttributeCreateInput!): AttributeCreate
+ attributeDelete(id: ID!): AttributeDelete
+ attributeUpdate(id: ID!, input: AttributeUpdateInput!): AttributeUpdate
+ attributeTranslate(id: ID!, input: NameTranslationInput!, languageCode: LanguageCodeEnum!): AttributeTranslate
+ attributeBulkDelete(ids: [ID]!): AttributeBulkDelete
+ attributeValueBulkDelete(ids: [ID]!): AttributeValueBulkDelete
+ attributeValueCreate(attribute: ID!, input: AttributeValueCreateInput!): AttributeValueCreate
+ attributeValueDelete(id: ID!): AttributeValueDelete
+ attributeValueUpdate(id: ID!, input: AttributeValueCreateInput!): AttributeValueUpdate
+ attributeValueTranslate(id: ID!, input: NameTranslationInput!, languageCode: LanguageCodeEnum!): AttributeValueTranslate
+ attributeReorderValues(attributeId: ID!, moves: [ReorderInput]!): AttributeReorderValues
appCreate(input: AppInput!): AppCreate
appUpdate(id: ID!, input: AppInput!): AppUpdate
appDelete(id: ID!): AppDelete
@@ -3149,10 +3157,24 @@ type Page implements Node & ObjectWithMetadata {
publicationDate: Date
isPublished: Boolean!
slug: String!
+ pageType: PageType!
created: DateTime!
privateMetadata: [MetadataItem]!
metadata: [MetadataItem]!
translation(languageCode: LanguageCodeEnum!): PageTranslation
+ attributes: [SelectedAttribute!]!
+}
+
+type PageAttributeAssign {
+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
+ pageType: PageType
+ pageErrors: [PageError!]!
+}
+
+type PageAttributeUnassign {
+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
+ pageType: PageType
+ pageErrors: [PageError!]!
}
type PageBulkDelete {
@@ -3184,6 +3206,18 @@ type PageCreate {
page: Page
}
+input PageCreateInput {
+ slug: String
+ title: String
+ content: String
+ contentJson: JSONString
+ attributes: [AttributeValueInput!]
+ isPublished: Boolean
+ publicationDate: String
+ seo: SeoInput
+ pageType: ID!
+}
+
type PageDelete {
errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
pageErrors: [PageError!]!
@@ -3194,6 +3228,7 @@ type PageError {
field: String
message: String
code: PageErrorCode!
+ attributes: [ID!]
}
enum PageErrorCode {
@@ -3202,6 +3237,8 @@ enum PageErrorCode {
NOT_FOUND
REQUIRED
UNIQUE
+ DUPLICATED_INPUT_ITEM
+ ATTRIBUTE_ALREADY_ASSIGNED
}
input PageFilterInput {
@@ -3220,6 +3257,7 @@ input PageInput {
title: String
content: String
contentJson: JSONString
+ attributes: [AttributeValueInput!]
isPublished: Boolean
publicationDate: String
seo: SeoInput
@@ -3273,6 +3311,85 @@ input PageTranslationInput {
contentJson: JSONString
}
+type PageType implements Node & ObjectWithMetadata {
+ id: ID!
+ name: String!
+ slug: String!
+ privateMetadata: [MetadataItem]!
+ metadata: [MetadataItem]!
+ attributes: [Attribute]
+ availableAttributes(filter: AttributeFilterInput, before: String, after: String, first: Int, last: Int): AttributeCountableConnection
+ hasPages: Boolean
+}
+
+type PageTypeBulkDelete {
+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
+ count: Int!
+ pageErrors: [PageError!]!
+}
+
+type PageTypeCountableConnection {
+ pageInfo: PageInfo!
+ edges: [PageTypeCountableEdge!]!
+ totalCount: Int
+}
+
+type PageTypeCountableEdge {
+ node: PageType!
+ cursor: String!
+}
+
+type PageTypeCreate {
+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
+ pageErrors: [PageError!]!
+ pageType: PageType
+}
+
+input PageTypeCreateInput {
+ name: String
+ slug: String
+ addAttributes: [ID!]
+}
+
+type PageTypeDelete {
+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
+ pageErrors: [PageError!]!
+ pageType: PageType
+}
+
+input PageTypeFilterInput {
+ search: String
+}
+
+type PageTypeReorderAttributes {
+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
+ pageType: PageType
+ pageErrors: [PageError!]!
+}
+
+enum PageTypeSortField {
+ NAME
+ SLUG
+}
+
+input PageTypeSortingInput {
+ direction: OrderDirection!
+ field: PageTypeSortField!
+}
+
+type PageTypeUpdate {
+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
+ pageErrors: [PageError!]!
+ pageType: PageType
+}
+
+input PageTypeUpdateInput {
+ name: String
+ slug: String
+ addAttributes: [ID!]
+ removeAttributes: [ID!]
+}
+
type PageUpdate {
errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
pageErrors: [PageError!]!
@@ -3414,6 +3531,7 @@ enum PermissionEnum {
MANAGE_MENUS
MANAGE_ORDERS
MANAGE_PAGES
+ MANAGE_PAGE_TYPES_AND_ATTRIBUTES
MANAGE_PRODUCTS
MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES
MANAGE_SHIPPING
@@ -3586,6 +3704,28 @@ type Product implements Node & ObjectWithMetadata {
isAvailableForPurchase: Boolean
}
+type ProductAttributeAssign {
+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
+ productType: ProductType
+ productErrors: [ProductError!]!
+}
+
+input ProductAttributeAssignInput {
+ id: ID!
+ type: ProductAttributeType!
+}
+
+enum ProductAttributeType {
+ PRODUCT
+ VARIANT
+}
+
+type ProductAttributeUnassign {
+ errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
+ productType: ProductType
+ productErrors: [ProductError!]!
+}
+
type ProductBulkDelete {
errors: [Error!]! @deprecated(reason: "Use typed errors with error codes. This field will be removed after 2020-07-31.")
count: Int!
@@ -4151,8 +4291,6 @@ type Query {
shippingZones(channel: String, before: String, after: String, first: Int, last: Int): ShippingZoneCountableConnection
digitalContent(id: ID!): DigitalContent
digitalContents(before: String, after: String, first: Int, last: Int): DigitalContentCountableConnection
- attributes(filter: AttributeFilterInput, sortBy: AttributeSortingInput, before: String, after: String, first: Int, last: Int): AttributeCountableConnection
- attribute(id: ID!): Attribute
categories(filter: CategoryFilterInput, sortBy: CategorySortingInput, level: Int, before: String, after: String, first: Int, last: Int): CategoryCountableConnection
category(id: ID, slug: String): Category
collection(id: ID, slug: String, channel: String): Collection
@@ -4168,6 +4306,8 @@ type Query {
payments(before: String, after: String, first: Int, last: Int): PaymentCountableConnection
page(id: ID, slug: String): Page
pages(sortBy: PageSortingInput, filter: PageFilterInput, before: String, after: String, first: Int, last: Int): PageCountableConnection
+ pageType(id: ID!): PageType
+ pageTypes(sortBy: PageTypeSortingInput, filter: PageTypeFilterInput, before: String, after: String, first: Int, last: Int): PageTypeCountableConnection
homepageEvents(before: String, after: String, first: Int, last: Int): OrderEventCountableConnection
order(id: ID!): Order
orders(sortBy: OrderSortingInput, filter: OrderFilterInput, created: ReportingPeriod, status: OrderStatusFilter, channel: String, before: String, after: String, first: Int, last: Int): OrderCountableConnection
@@ -4195,6 +4335,8 @@ type Query {
checkoutLines(before: String, after: String, first: Int, last: Int): CheckoutLineCountableConnection
channel(id: ID): Channel
channels: [Channel!]
+ attributes(filter: AttributeFilterInput, sortBy: AttributeSortingInput, before: String, after: String, first: Int, last: Int): AttributeCountableConnection
+ attribute(id: ID!): Attribute
appsInstallations: [AppInstallation!]!
apps(filter: AppFilterInput, sortBy: AppSortingInput, before: String, after: String, first: Int, last: Int): AppCountableConnection
app(id: ID!): App
@@ -5519,7 +5661,7 @@ enum WeightUnitsEnum {
scalar _Any
-union _Entity = Address | User | Group | App | ProductVariant | Product | ProductType | Collection | Category | ProductImage
+union _Entity = Address | User | Group | App | ProductVariant | Product | ProductType | Collection | Category | ProductImage | PageType
type _Service {
sdl: String
diff --git a/saleor/graphql/translations/mutations.py b/saleor/graphql/translations/mutations.py
index 2724b30ef2..85f29b076f 100644
--- a/saleor/graphql/translations/mutations.py
+++ b/saleor/graphql/translations/mutations.py
@@ -1,6 +1,7 @@
import graphene
from django.core.exceptions import ValidationError
+from ...attribute import models as attribute_models
from ...core.permissions import SitePermissions
from ...discount import models as discount_models
from ...menu import models as menu_models
@@ -162,7 +163,7 @@ class AttributeTranslate(BaseTranslateMutation):
class Meta:
description = "Creates/Updates translations for attribute."
- model = product_models.Attribute
+ model = attribute_models.Attribute
error_type_class = TranslationError
error_type_field = "translation_errors"
@@ -177,7 +178,7 @@ class AttributeValueTranslate(BaseTranslateMutation):
class Meta:
description = "Creates/Updates translations for attribute value."
- model = product_models.AttributeValue
+ model = attribute_models.AttributeValue
error_type_class = TranslationError
error_type_field = "translation_errors"
diff --git a/saleor/graphql/translations/resolvers.py b/saleor/graphql/translations/resolvers.py
index ace7c4e0d6..8487ffd8d1 100644
--- a/saleor/graphql/translations/resolvers.py
+++ b/saleor/graphql/translations/resolvers.py
@@ -1,3 +1,4 @@
+from ...attribute import models as attribute_models
from ...discount import models as discount_models
from ...product import models as product_models
from ...shipping import models as shipping_models
@@ -13,7 +14,7 @@ def resolve_shipping_methods(info):
def resolve_attribute_values(info):
- return product_models.AttributeValue.objects.all()
+ return attribute_models.AttributeValue.objects.all()
def resolve_products(_info):
diff --git a/saleor/graphql/translations/schema.py b/saleor/graphql/translations/schema.py
index aef7d20ff3..013ae0f3c7 100644
--- a/saleor/graphql/translations/schema.py
+++ b/saleor/graphql/translations/schema.py
@@ -1,24 +1,19 @@
import graphene
+from ...attribute.models import Attribute, AttributeValue
from ...core.permissions import SitePermissions
from ...discount.models import Sale, Voucher
from ...menu.models import MenuItem
from ...page.models import Page
-from ...product.models import (
- Attribute,
- AttributeValue,
- Category,
- Collection,
- Product,
- ProductVariant,
-)
+from ...product.models import Category, Collection, Product, ProductVariant
from ...shipping.models import ShippingMethod
+from ..attribute.resolvers import resolve_attributes
from ..core.connection import CountableConnection
from ..core.fields import BaseConnectionField
from ..decorators import permission_required
from ..menu.resolvers import resolve_menu_items
from ..page.resolvers import resolve_pages
-from ..product.resolvers import resolve_attributes, resolve_categories
+from ..product.resolvers import resolve_categories
from ..translations import types as translation_types
from .resolvers import (
resolve_attribute_values,
diff --git a/saleor/graphql/translations/types.py b/saleor/graphql/translations/types.py
index 423fbc472a..038dcc73c8 100644
--- a/saleor/graphql/translations/types.py
+++ b/saleor/graphql/translations/types.py
@@ -1,6 +1,7 @@
import graphene
from django.conf import settings
+from ...attribute import models as attribute_models
from ...core.permissions import DiscountPermissions, ShippingPermissions
from ...discount import models as discount_models
from ...menu import models as menu_models
@@ -52,7 +53,7 @@ class BaseTranslationType(CountableDjangoObjectType):
class AttributeValueTranslation(BaseTranslationType):
class Meta:
- model = product_models.AttributeValueTranslation
+ model = attribute_models.AttributeValueTranslation
interfaces = [graphene.relay.Node]
only_fields = BASIC_TRANSLATABLE_FIELDS
@@ -62,23 +63,23 @@ class AttributeValueTranslatableContent(CountableDjangoObjectType):
AttributeValueTranslation, type_name="attribute value"
)
attribute_value = graphene.Field(
- "saleor.graphql.product.types.attributes.AttributeValue",
+ "saleor.graphql.attribute.types.AttributeValue",
description="Represents a value of an attribute.",
)
class Meta:
- model = product_models.AttributeValue
+ model = attribute_models.AttributeValue
interfaces = [graphene.relay.Node]
only_fields = BASIC_TRANSLATABLE_FIELDS
@staticmethod
- def resolve_attribute_value(root: product_models.AttributeValue, _info):
+ def resolve_attribute_value(root: attribute_models.AttributeValue, _info):
return root
class AttributeTranslation(BaseTranslationType):
class Meta:
- model = product_models.AttributeTranslation
+ model = attribute_models.AttributeTranslation
interfaces = [graphene.relay.Node]
only_fields = BASIC_TRANSLATABLE_FIELDS
@@ -86,17 +87,17 @@ class AttributeTranslation(BaseTranslationType):
class AttributeTranslatableContent(CountableDjangoObjectType):
translation = TranslationField(AttributeTranslation, type_name="attribute")
attribute = graphene.Field(
- "saleor.graphql.product.types.attributes.Attribute",
+ "saleor.graphql.attribute.types.Attribute",
description="Custom attribute of a product.",
)
class Meta:
- model = product_models.Attribute
+ model = attribute_models.Attribute
interfaces = [graphene.relay.Node]
only_fields = BASIC_TRANSLATABLE_FIELDS
@staticmethod
- def resolve_attribute(root: product_models.Attribute, _info):
+ def resolve_attribute(root: attribute_models.Attribute, _info):
return root
diff --git a/saleor/graphql/utils/filters.py b/saleor/graphql/utils/filters.py
index 2e0d21b06a..1e824510af 100644
--- a/saleor/graphql/utils/filters.py
+++ b/saleor/graphql/utils/filters.py
@@ -4,6 +4,17 @@ from django.utils import timezone
from ..core.enums import ReportingPeriod
+def filter_fields_containing_value(*search_fields: str):
+ """Create a icontains filters through given fields on a given query set object."""
+
+ def _filter_qs(qs, _, value):
+ if value:
+ qs = filter_by_query_param(qs, value, search_fields)
+ return qs
+
+ return _filter_qs
+
+
def filter_by_query_param(queryset, query, search_fields):
"""Filter queryset according to given parameters.
diff --git a/saleor/page/error_codes.py b/saleor/page/error_codes.py
index 7336febc15..06eac6a485 100644
--- a/saleor/page/error_codes.py
+++ b/saleor/page/error_codes.py
@@ -7,3 +7,5 @@ class PageErrorCode(Enum):
NOT_FOUND = "not_found"
REQUIRED = "required"
UNIQUE = "unique"
+ DUPLICATED_INPUT_ITEM = "duplicated_input_item"
+ ATTRIBUTE_ALREADY_ASSIGNED = "attribute_already_assigned"
diff --git a/saleor/page/migrations/0017_pagetype.py b/saleor/page/migrations/0017_pagetype.py
new file mode 100644
index 0000000000..42e727a3f1
--- /dev/null
+++ b/saleor/page/migrations/0017_pagetype.py
@@ -0,0 +1,119 @@
+import django.db.models.deletion
+from django.core.management.sql import emit_post_migrate_signal
+from django.db import migrations, models
+
+import saleor.core.utils.json_serializer
+
+
+def update_groups_with_manage_pages_with_new_permission(apps, schema_editor):
+ # force post signal as permissions are created in post migrate signals
+ # related Django issue https://code.djangoproject.com/ticket/23422
+ emit_post_migrate_signal(2, False, "default")
+
+ Group = apps.get_model("auth", "Group")
+ Permission = apps.get_model("auth", "Permission")
+
+ manage_page_types_and_attributes_perm = Permission.objects.filter(
+ codename="manage_page_types_and_attributes", content_type__app_label="page",
+ ).first()
+
+ groups = Group.objects.filter(
+ permissions__content_type__app_label="page",
+ permissions__codename="manage_pages",
+ )
+ for group in groups:
+ group.permissions.add(manage_page_types_and_attributes_perm)
+
+
+def add_page_types_to_existing_pages(apps, schema_editor):
+ Page = apps.get_model("page", "Page")
+ PageType = apps.get_model("page", "PageType")
+
+ pages = Page.objects.all()
+
+ if pages:
+ page_type = PageType.objects.create(name="Default", slug="default")
+
+ page_type.pages.add(*pages)
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("page", "0016_auto_20201112_0904"),
+ ]
+
+ operations = [
+ migrations.CreateModel(
+ name="PageType",
+ fields=[
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ (
+ "private_metadata",
+ models.JSONField(
+ blank=True,
+ default=dict,
+ encoder=saleor.core.utils.json_serializer.CustomJsonEncoder,
+ null=True,
+ ),
+ ),
+ (
+ "metadata",
+ models.JSONField(
+ blank=True,
+ default=dict,
+ encoder=saleor.core.utils.json_serializer.CustomJsonEncoder,
+ null=True,
+ ),
+ ),
+ ("name", models.CharField(max_length=250)),
+ (
+ "slug",
+ models.SlugField(allow_unicode=True, max_length=255, unique=True),
+ ),
+ ],
+ options={
+ "ordering": ("slug",),
+ "permissions": (
+ (
+ "manage_page_types_and_attributes",
+ "Manage page types and attributes.",
+ ),
+ ),
+ },
+ ),
+ migrations.RunPython(
+ update_groups_with_manage_pages_with_new_permission,
+ migrations.RunPython.noop,
+ ),
+ migrations.AddField(
+ model_name="page",
+ name="page_type",
+ field=models.ForeignKey(
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="pages",
+ to="page.pagetype",
+ ),
+ ),
+ migrations.RunPython(
+ add_page_types_to_existing_pages, migrations.RunPython.noop
+ ),
+ migrations.AlterField(
+ model_name="page",
+ name="page_type",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="pages",
+ to="page.pagetype",
+ ),
+ ),
+ ]
diff --git a/saleor/page/models.py b/saleor/page/models.py
index 7019b09110..81a7fd435e 100644
--- a/saleor/page/models.py
+++ b/saleor/page/models.py
@@ -2,7 +2,7 @@ from django.db import models
from ..core.db.fields import SanitizedJSONField
from ..core.models import ModelWithMetadata, PublishableModel, PublishedQuerySet
-from ..core.permissions import PagePermissions
+from ..core.permissions import PagePermissions, PageTypePermissions
from ..core.sanitizers.editorjs_sanitizer import clean_editor_js
from ..core.utils.translations import TranslationProxy
from ..seo.models import SeoModel, SeoModelTranslation
@@ -17,6 +17,9 @@ class PagePublishedQuerySet(PublishedQuerySet):
class Page(ModelWithMetadata, SeoModel, PublishableModel):
slug = models.SlugField(unique=True, max_length=255)
title = models.CharField(max_length=250)
+ page_type = models.ForeignKey(
+ "PageType", related_name="pages", on_delete=models.CASCADE
+ )
content = models.TextField(blank=True)
content_json = SanitizedJSONField(
blank=True, default=dict, sanitizer=clean_editor_js
@@ -60,3 +63,17 @@ class PageTranslation(SeoModelTranslation):
def __str__(self):
return self.title
+
+
+class PageType(ModelWithMetadata):
+ name = models.CharField(max_length=250)
+ slug = models.SlugField(max_length=255, unique=True, allow_unicode=True)
+
+ class Meta:
+ ordering = ("slug",)
+ permissions = (
+ (
+ PageTypePermissions.MANAGE_PAGE_TYPES_AND_ATTRIBUTES.codename,
+ "Manage page types and attributes.",
+ ),
+ )
diff --git a/saleor/product/__init__.py b/saleor/product/__init__.py
index f3236ce684..e69de29bb2 100644
--- a/saleor/product/__init__.py
+++ b/saleor/product/__init__.py
@@ -1,12 +0,0 @@
-class AttributeInputType:
- """The type that we expect to render the attribute's values as."""
-
- DROPDOWN = "dropdown"
- MULTISELECT = "multiselect"
-
- CHOICES = [
- (DROPDOWN, "Dropdown"),
- (MULTISELECT, "Multi Select"),
- ]
- # list the input types that cannot be assigned to a variant
- NON_ASSIGNABLE_TO_VARIANTS = [MULTISELECT]
diff --git a/saleor/product/migrations/0136_add_attribute_type_and_page_to_attribute_relation.py b/saleor/product/migrations/0136_add_attribute_type_and_page_to_attribute_relation.py
new file mode 100644
index 0000000000..dc7edd333e
--- /dev/null
+++ b/saleor/product/migrations/0136_add_attribute_type_and_page_to_attribute_relation.py
@@ -0,0 +1,135 @@
+# Generated by Django 3.1 on 2020-10-09 10:17
+
+import django.db.models.deletion
+from django.db import migrations, models
+
+
+def set_product_type_to_all_existing_attributes(apps, schema_editor):
+ Attribute = apps.get_model("product", "Attribute")
+ Attribute.objects.all().update(type="product-type")
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("page", "0017_pagetype"),
+ ("product", "0135_collection_channel_listing"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="attribute",
+ name="type",
+ field=models.CharField(
+ choices=[("product-type", "Product type"), ("page-type", "Page type")],
+ max_length=50,
+ null=True,
+ ),
+ ),
+ migrations.RunPython(
+ set_product_type_to_all_existing_attributes, migrations.RunPython.noop,
+ ),
+ migrations.AlterField(
+ model_name="attribute",
+ name="type",
+ field=models.CharField(
+ choices=[("product-type", "Product type"), ("page-type", "Page type")],
+ max_length=50,
+ ),
+ ),
+ migrations.CreateModel(
+ name="AssignedPageAttribute",
+ fields=[
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ ],
+ options={"abstract": False},
+ ),
+ migrations.CreateModel(
+ name="AttributePage",
+ 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),
+ ),
+ (
+ "assigned_pages",
+ models.ManyToManyField(
+ blank=True,
+ related_name="attributesrelated",
+ through="product.AssignedPageAttribute",
+ to="page.Page",
+ ),
+ ),
+ (
+ "attribute",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="attributepage",
+ to="product.attribute",
+ ),
+ ),
+ (
+ "page_type",
+ models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="attributepage",
+ to="page.pagetype",
+ ),
+ ),
+ ],
+ options={
+ "ordering": ("sort_order", "pk"),
+ "unique_together": {("attribute", "page_type")},
+ },
+ ),
+ migrations.AddField(
+ model_name="assignedpageattribute",
+ name="assignment",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="pageassignments",
+ to="product.attributepage",
+ ),
+ ),
+ migrations.AddField(
+ model_name="assignedpageattribute",
+ name="page",
+ field=models.ForeignKey(
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="attributes",
+ to="page.page",
+ ),
+ ),
+ migrations.AddField(
+ model_name="assignedpageattribute",
+ name="values",
+ field=models.ManyToManyField(to="product.AttributeValue"),
+ ),
+ migrations.AddField(
+ model_name="attribute",
+ name="page_types",
+ field=models.ManyToManyField(
+ blank=True,
+ related_name="page_attributes",
+ through="product.AttributePage",
+ to="page.PageType",
+ ),
+ ),
+ ]
diff --git a/saleor/product/migrations/0137_drop_attribute_models.py b/saleor/product/migrations/0137_drop_attribute_models.py
new file mode 100644
index 0000000000..ae1b6b793d
--- /dev/null
+++ b/saleor/product/migrations/0137_drop_attribute_models.py
@@ -0,0 +1,75 @@
+# Generated by Django 3.1 on 2020-10-30 11:37
+
+from django.db import migrations
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("product", "0136_add_attribute_type_and_page_to_attribute_relation"),
+ ("attribute", "0001_initial"),
+ ]
+
+ state_operations = [
+ migrations.AlterUniqueTogether(
+ name="assignedproductattribute", unique_together=None,
+ ),
+ migrations.RemoveField(
+ model_name="assignedproductattribute", name="assignment",
+ ),
+ migrations.RemoveField(model_name="assignedproductattribute", name="product",),
+ migrations.RemoveField(model_name="assignedproductattribute", name="values",),
+ migrations.AlterUniqueTogether(
+ name="assignedvariantattribute", unique_together=None,
+ ),
+ migrations.RemoveField(
+ model_name="assignedvariantattribute", name="assignment",
+ ),
+ migrations.RemoveField(model_name="assignedvariantattribute", name="values",),
+ migrations.RemoveField(model_name="assignedvariantattribute", name="variant",),
+ migrations.RemoveField(model_name="attribute", name="page_types",),
+ migrations.RemoveField(model_name="attribute", name="product_types",),
+ migrations.RemoveField(model_name="attribute", name="product_variant_types",),
+ migrations.AlterUniqueTogether(name="attributepage", unique_together=None,),
+ migrations.RemoveField(model_name="attributepage", name="assigned_pages",),
+ migrations.RemoveField(model_name="attributepage", name="attribute",),
+ migrations.RemoveField(model_name="attributepage", name="page_type",),
+ migrations.AlterUniqueTogether(name="attributeproduct", unique_together=None,),
+ migrations.RemoveField(
+ model_name="attributeproduct", name="assigned_products",
+ ),
+ migrations.RemoveField(model_name="attributeproduct", name="attribute",),
+ migrations.RemoveField(model_name="attributeproduct", name="product_type",),
+ migrations.AlterUniqueTogether(
+ name="attributetranslation", unique_together=None,
+ ),
+ migrations.RemoveField(model_name="attributetranslation", name="attribute",),
+ migrations.AlterUniqueTogether(name="attributevalue", unique_together=None,),
+ migrations.RemoveField(model_name="attributevalue", name="attribute",),
+ migrations.AlterUniqueTogether(
+ name="attributevaluetranslation", unique_together=None,
+ ),
+ migrations.RemoveField(
+ model_name="attributevaluetranslation", name="attribute_value",
+ ),
+ migrations.AlterUniqueTogether(name="attributevariant", unique_together=None,),
+ migrations.RemoveField(
+ model_name="attributevariant", name="assigned_variants",
+ ),
+ migrations.RemoveField(model_name="attributevariant", name="attribute",),
+ migrations.RemoveField(model_name="attributevariant", name="product_type",),
+ migrations.DeleteModel(name="AssignedPageAttribute",),
+ migrations.DeleteModel(name="AssignedProductAttribute",),
+ migrations.DeleteModel(name="AssignedVariantAttribute",),
+ migrations.DeleteModel(name="Attribute",),
+ migrations.DeleteModel(name="AttributePage",),
+ migrations.DeleteModel(name="AttributeProduct",),
+ migrations.DeleteModel(name="AttributeTranslation",),
+ migrations.DeleteModel(name="AttributeValue",),
+ migrations.DeleteModel(name="AttributeValueTranslation",),
+ migrations.DeleteModel(name="AttributeVariant",),
+ ]
+
+ operations = [
+ migrations.SeparateDatabaseAndState(state_operations=state_operations)
+ ]
diff --git a/saleor/product/models.py b/saleor/product/models.py
index 411e13ad08..77d838ba20 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -43,7 +43,6 @@ from ..core.weight import WeightUnits, zero_weight
from ..discount import DiscountInfo
from ..discount.utils import calculate_discounted_price
from ..seo.models import SeoModel, SeoModelTranslation
-from . import AttributeInputType
if TYPE_CHECKING:
# flake8: noqa
@@ -217,6 +216,8 @@ class ProductsQueryset(models.QuerySet):
to sort by.
:param descending: The sorting direction.
"""
+ from ..attribute.models import AttributeProduct, AttributeValue
+
qs: models.QuerySet = self
# If the passed attribute ID is valid, execute the sorting
if not (isinstance(attribute_pk, int) or attribute_pk.isnumeric()):
@@ -619,273 +620,6 @@ class DigitalContentUrl(models.Model):
return build_absolute_uri(url)
-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
-
- @property
- def attribute(self):
- return self.assignment.attribute
-
- @property
- def attribute_pk(self):
- 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 AssociatedAttributeQuerySet(BaseAttributeQuerySet):
- def get_public_attributes(self):
- 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 AttributeQuerySet(BaseAttributeQuerySet):
- def get_unassigned_attributes(self, product_type_pk: int):
- return self.exclude(
- Q(attributeproduct__product_type_id=product_type_pk)
- | Q(attributevariant__product_type_id=product_type_pk)
- )
-
- def get_assigned_attributes(self, product_type_pk: int):
- return self.filter(
- Q(attributeproduct__product_type_id=product_type_pk)
- | Q(attributevariant__product_type_id=product_type_pk)
- )
-
- def get_public_attributes(self):
- return self.filter(visible_in_storefront=True)
-
- def _get_sorted_m2m_field(self, m2m_field_name: str, asc: bool):
- sort_order_field = F(f"{m2m_field_name}__sort_order")
- id_field = F(f"{m2m_field_name}__id")
- if asc:
- sort_method = sort_order_field.asc(nulls_last=True)
- id_sort: Union["OrderBy", "F"] = id_field
- else:
- sort_method = sort_order_field.desc(nulls_first=True)
- id_sort = id_field.desc()
-
- return self.order_by(sort_method, id_sort)
-
- def product_attributes_sorted(self, asc=True):
- return self._get_sorted_m2m_field("attributeproduct", asc)
-
- def variant_attributes_sorted(self, asc=True):
- return self._get_sorted_m2m_field("attributevariant", asc)
-
-
-class Attribute(ModelWithMetadata):
- slug = models.SlugField(max_length=250, unique=True, allow_unicode=True)
- name = models.CharField(max_length=255)
-
- input_type = models.CharField(
- max_length=50,
- choices=AttributeInputType.CHOICES,
- default=AttributeInputType.DROPDOWN,
- )
-
- product_types = models.ManyToManyField(
- ProductType,
- blank=True,
- related_name="product_attributes",
- through=AttributeProduct,
- through_fields=("attribute", "product_type"),
- )
- product_variant_types = models.ManyToManyField(
- ProductType,
- blank=True,
- related_name="variant_attributes",
- through=AttributeVariant,
- through_fields=("attribute", "product_type"),
- )
-
- value_required = models.BooleanField(default=False, blank=True)
- is_variant_only = models.BooleanField(default=False, blank=True)
- visible_in_storefront = models.BooleanField(default=True, blank=True)
-
- filterable_in_storefront = models.BooleanField(default=True, blank=True)
- filterable_in_dashboard = models.BooleanField(default=True, blank=True)
-
- storefront_search_position = models.IntegerField(default=0, blank=True)
- available_in_grid = models.BooleanField(default=True, blank=True)
-
- objects = AttributeQuerySet.as_manager()
- translated = TranslationProxy()
-
- class Meta:
- ordering = ("storefront_search_position", "slug")
-
- def __str__(self) -> str:
- return self.name
-
- def has_values(self) -> bool:
- return self.values.exists()
-
-
-class AttributeTranslation(models.Model):
- language_code = models.CharField(max_length=10)
- attribute = models.ForeignKey(
- Attribute, related_name="translations", on_delete=models.CASCADE
- )
- name = models.CharField(max_length=100)
-
- class Meta:
- unique_together = (("language_code", "attribute"),)
-
- def __repr__(self):
- class_ = type(self)
- return "%s(pk=%r, name=%r, attribute_pk=%r)" % (
- class_.__name__,
- self.pk,
- self.name,
- self.attribute_id,
- )
-
- def __str__(self) -> str:
- return self.name
-
-
-class AttributeValue(SortableModel):
- name = models.CharField(max_length=250)
- value = models.CharField(max_length=100, blank=True, default="")
- slug = models.SlugField(max_length=255, allow_unicode=True)
- attribute = models.ForeignKey(
- Attribute, related_name="values", on_delete=models.CASCADE
- )
-
- translated = TranslationProxy()
-
- class Meta:
- ordering = ("sort_order", "pk")
- unique_together = ("slug", "attribute")
-
- def __str__(self) -> str:
- return self.name
-
- @property
- def input_type(self):
- return self.attribute.input_type
-
- def get_ordering_queryset(self):
- return self.attribute.values.all()
-
-
-class AttributeValueTranslation(models.Model):
- language_code = models.CharField(max_length=10)
- attribute_value = models.ForeignKey(
- AttributeValue, related_name="translations", on_delete=models.CASCADE
- )
- name = models.CharField(max_length=100)
-
- class Meta:
- unique_together = (("language_code", "attribute_value"),)
-
- def __repr__(self) -> str:
- class_ = type(self)
- return "%s(pk=%r, name=%r, attribute_value_pk=%r)" % (
- class_.__name__,
- self.pk,
- self.name,
- self.attribute_value_id,
- )
-
- def __str__(self) -> str:
- return self.name
-
-
class ProductImage(SortableModel):
product = models.ForeignKey(
Product, related_name="images", on_delete=models.CASCADE
diff --git a/saleor/product/tasks.py b/saleor/product/tasks.py
index 275f164ef6..8f8ce41d02 100644
--- a/saleor/product/tasks.py
+++ b/saleor/product/tasks.py
@@ -1,15 +1,16 @@
from typing import Iterable, List, Optional
+from ..attribute.models import Attribute
from ..celeryconf import app
from ..discount.models import Sale
-from .models import Attribute, Product, ProductType, ProductVariant
-from .utils.attributes import generate_name_for_variant
+from .models import Product, ProductType, ProductVariant
from .utils.variant_prices import (
update_product_discounted_price,
update_products_discounted_prices,
update_products_discounted_prices_of_catalogues,
update_products_discounted_prices_of_discount,
)
+from .utils.variants import generate_name_for_variant
def _update_variants_names(instance: ProductType, saved_attributes: Iterable):
diff --git a/saleor/product/tests/test_product_attributes.py b/saleor/product/tests/test_generate_name_for_variant.py
similarity index 64%
rename from saleor/product/tests/test_product_attributes.py
rename to saleor/product/tests/test_generate_name_for_variant.py
index c74bf4490e..5fa9a774cc 100644
--- a/saleor/product/tests/test_product_attributes.py
+++ b/saleor/product/tests/test_generate_name_for_variant.py
@@ -3,19 +3,13 @@ from unittest.mock import MagicMock, Mock
import pytest
-from .. import AttributeInputType
-from ..models import (
- AttributeValue,
- Product,
- ProductType,
- ProductVariant,
- ProductVariantChannelListing,
-)
+from ...attribute import AttributeInputType
+from ...attribute.models import AttributeValue
+from ...attribute.utils import associate_attribute_values_to_instance
+from ...product.models import ProductVariantChannelListing
+from ..models import Product, ProductType, ProductVariant
from ..tasks import _update_variants_names
-from ..utils.attributes import (
- associate_attribute_values_to_instance,
- generate_name_for_variant,
-)
+from ..utils.variants import generate_name_for_variant
@pytest.fixture()
@@ -104,46 +98,3 @@ def test_update_variants_changed_does_nothing_with_no_attributes():
saved_attributes = []
# FIXME: This method no longer returns any value
assert _update_variants_names(product_type, saved_attributes) is None
-
-
-def test_associate_attribute_to_non_product_instance(color_attribute):
- instance = ProductType()
- attribute = color_attribute
- value = color_attribute.values.first()
-
- with pytest.raises(AssertionError) as exc:
- associate_attribute_values_to_instance(instance, attribute, value) # noqa
-
- assert exc.value.args == ("ProductType is unsupported",)
-
-
-def test_associate_attribute_to_product_instance_from_different_attribute(
- product, color_attribute, size_attribute
-):
- """Ensure an assertion error is raised when one tries to associate attribute values
- to an object that don't belong to the supplied attribute.
- """
- instance = product
- attribute = color_attribute
- value = size_attribute.values.first()
-
- with pytest.raises(AssertionError) as exc:
- associate_attribute_values_to_instance(instance, attribute, value)
-
- assert exc.value.args == ("Some values are not from the provided attribute.",)
-
-
-def test_associate_attribute_to_product_instance_without_values(product):
- """Ensure clearing the values from a product is properly working."""
- old_assignment = product.attributes.first()
- assert old_assignment is not None, "The product doesn't have attribute-values"
- assert old_assignment.values.count() == 1
-
- attribute = old_assignment.attribute
-
- # Clear the values
- new_assignment = associate_attribute_values_to_instance(product, attribute)
-
- # Ensure the values were cleared and no new assignment entry was created
- assert new_assignment.pk == old_assignment.pk
- assert new_assignment.values.count() == 0
diff --git a/saleor/product/tests/test_product.py b/saleor/product/tests/test_product.py
index 2c52ce22f7..e21e2e83d9 100644
--- a/saleor/product/tests/test_product.py
+++ b/saleor/product/tests/test_product.py
@@ -7,11 +7,11 @@ from freezegun import freeze_time
from prices import Money
from ...account import events as account_events
+from ...attribute.utils import associate_attribute_values_to_instance
from ...graphql.product.filters import filter_products_by_attributes_values
from .. import models
from ..models import DigitalContentUrl
from ..thumbnails import create_product_thumbnails
-from ..utils.attributes import associate_attribute_values_to_instance
from ..utils.costs import get_margin_for_variant_channel_listing
from ..utils.digital_products import increment_download_count
diff --git a/saleor/product/tests/test_translation.py b/saleor/product/tests/test_translation.py
index 0522b6490b..4d3304132a 100644
--- a/saleor/product/tests/test_translation.py
+++ b/saleor/product/tests/test_translation.py
@@ -1,8 +1,7 @@
import pytest
+from ...attribute.models import AttributeTranslation, AttributeValueTranslation
from ..models import (
- AttributeTranslation,
- AttributeValueTranslation,
CategoryTranslation,
CollectionTranslation,
ProductTranslation,
diff --git a/saleor/product/utils/variants.py b/saleor/product/utils/variants.py
new file mode 100644
index 0000000000..7852b986bf
--- /dev/null
+++ b/saleor/product/utils/variants.py
@@ -0,0 +1,17 @@
+from typing import TYPE_CHECKING
+
+if TYPE_CHECKING:
+ from ...attribute.models import AssignedVariantAttribute
+ from ..models import ProductVariant
+
+
+def generate_name_for_variant(variant: "ProductVariant") -> str:
+ """Generate ProductVariant's name based on its attributes."""
+ attributes_display = []
+
+ for attribute_rel in variant.attributes.all(): # type: AssignedVariantAttribute
+ values_qs = attribute_rel.values.all() # FIXME: this should be sorted
+ translated_values = [str(value.translated) for value in values_qs]
+ attributes_display.append(", ".join(translated_values))
+
+ return " / ".join(attributes_display)
diff --git a/saleor/settings.py b/saleor/settings.py
index f46a391f16..d6277948dd 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -234,6 +234,7 @@ INSTALLED_APPS = [
"saleor.discount",
"saleor.giftcard",
"saleor.product",
+ "saleor.attribute",
"saleor.channel",
"saleor.checkout",
"saleor.core",
diff --git a/saleor/static/populatedb_data.json b/saleor/static/populatedb_data.json
index 05fff34777..63d11d9241 100644
--- a/saleor/static/populatedb_data.json
+++ b/saleor/static/populatedb_data.json
@@ -8426,6 +8426,28 @@
]
}
},
+ {
+ "model": "product.assignedpageattribute",
+ "pk": 1,
+ "fields": {
+ "page": 1,
+ "assignment": 3,
+ "values": [
+ 87
+ ]
+ }
+ },
+ {
+ "model": "product.assignedpageattribute",
+ "pk": 2,
+ "fields": {
+ "page": 1,
+ "assignment": 2,
+ "values": [
+ 93
+ ]
+ }
+ },
{
"model": "product.attributeproduct",
"pk": 1,
@@ -8543,6 +8565,33 @@
"product_type": 15
}
},
+ {
+ "model": "product.attributepage",
+ "pk": 2,
+ "fields": {
+ "sort_order": null,
+ "attribute": 29,
+ "page_type": 1
+ }
+},
+{
+ "model": "product.attributepage",
+ "pk": 3,
+ "fields": {
+ "sort_order": null,
+ "attribute": 27,
+ "page_type": 1
+ }
+},
+{
+ "model": "product.attributepage",
+ "pk": 4,
+ "fields": {
+ "sort_order": null,
+ "attribute": 29,
+ "page_type": 2
+ }
+},
{
"model": "product.attribute",
"pk": 13,
@@ -8551,6 +8600,7 @@
"metadata": {},
"slug": "size",
"name": "Size",
+ "type": "product-type",
"input_type": "dropdown",
"value_required": false,
"is_variant_only": false,
@@ -8569,6 +8619,7 @@
"metadata": {},
"slug": "color",
"name": "Color",
+ "type": "product-type",
"input_type": "dropdown",
"value_required": false,
"is_variant_only": false,
@@ -8587,6 +8638,7 @@
"metadata": {},
"slug": "bottle-size",
"name": "Bottle Size",
+ "type": "product-type",
"input_type": "dropdown",
"value_required": false,
"is_variant_only": false,
@@ -8605,6 +8657,7 @@
"metadata": {},
"slug": "flavor",
"name": "Flavor",
+ "type": "product-type",
"input_type": "dropdown",
"value_required": false,
"is_variant_only": false,
@@ -8623,6 +8676,7 @@
"metadata": {},
"slug": "bucket-size",
"name": "Bucket Size",
+ "type": "product-type",
"input_type": "dropdown",
"value_required": false,
"is_variant_only": false,
@@ -8641,6 +8695,7 @@
"metadata": {},
"slug": "medium",
"name": "Medium",
+ "type": "product-type",
"input_type": "dropdown",
"value_required": false,
"is_variant_only": false,
@@ -8659,6 +8714,7 @@
"metadata": {},
"slug": "volume",
"name": "Volume",
+ "type": "product-type",
"input_type": "dropdown",
"value_required": false,
"is_variant_only": false,
@@ -8677,6 +8733,7 @@
"metadata": {},
"slug": "abv",
"name": "ABV",
+ "type": "product-type",
"input_type": "dropdown",
"value_required": false,
"is_variant_only": false,
@@ -8695,6 +8752,7 @@
"metadata": {},
"slug": "cushion-size",
"name": "Cushion Size",
+ "type": "product-type",
"input_type": "dropdown",
"value_required": false,
"is_variant_only": false,
@@ -8713,6 +8771,7 @@
"metadata": {},
"slug": "material",
"name": "Material",
+ "type": "product-type",
"input_type": "dropdown",
"value_required": false,
"is_variant_only": false,
@@ -8731,6 +8790,7 @@
"metadata": {},
"slug": "shoe-size",
"name": "Shoe size",
+ "type": "product-type",
"input_type": "dropdown",
"value_required": false,
"is_variant_only": false,
@@ -8749,6 +8809,7 @@
"metadata": {},
"slug": "ebook-format",
"name": "Format",
+ "type": "product-type",
"input_type": "dropdown",
"value_required": true,
"is_variant_only": false,
@@ -8767,6 +8828,7 @@
"metadata": {},
"slug": "publisher",
"name": "Publisher",
+ "type": "product-type",
"input_type": "dropdown",
"value_required": false,
"is_variant_only": false,
@@ -8777,6 +8839,44 @@
"available_in_grid": true
}
},
+ {
+ "model": "product.attribute",
+ "pk": 27,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "slug": "author",
+ "name": "Author",
+ "type": "page-type",
+ "input_type": "dropdown",
+ "value_required": false,
+ "is_variant_only": false,
+ "visible_in_storefront": true,
+ "filterable_in_storefront": true,
+ "filterable_in_dashboard": true,
+ "storefront_search_position": 0,
+ "available_in_grid": true
+ }
+ },
+ {
+ "model": "product.attribute",
+ "pk": 29,
+ "fields": {
+ "private_metadata": {},
+ "metadata": {},
+ "slug": "tag",
+ "name": "Tag",
+ "type": "page-type",
+ "input_type": "multiselect",
+ "value_required": false,
+ "is_variant_only": false,
+ "visible_in_storefront": true,
+ "filterable_in_storefront": true,
+ "filterable_in_dashboard": true,
+ "storefront_search_position": 0,
+ "available_in_grid": true
+ }
+ },
{
"model": "product.attributevalue",
"pk": 1,
@@ -9316,6 +9416,83 @@
"attribute": 26
}
},
+ {
+ "model": "product.attributevalue",
+ "pk": 87,
+ "fields": {
+ "sort_order": 0,
+ "name": "Suzanne Ellison",
+ "value": "",
+ "slug": "suzanne-ellison",
+ "attribute": 27
+ }
+ },
+ {
+ "model": "product.attributevalue",
+ "pk": 88,
+ "fields": {
+ "sort_order": 1,
+ "name": "Dennis Perkins",
+ "value": "",
+ "slug": "dennis-perkins",
+ "attribute": 27
+ }
+ },
+ {
+ "model": "product.attributevalue",
+ "pk": 89,
+ "fields": {
+ "sort_order": 2,
+ "name": "Dylan Lamb",
+ "value": "",
+ "slug": "dylan-lamb",
+ "attribute": 27
+ }
+ },
+ {
+ "model": "product.attributevalue",
+ "pk": 90,
+ "fields": {
+ "sort_order": 0,
+ "name": "Security",
+ "value": "",
+ "slug": "security",
+ "attribute": 29
+ }
+ },
+ {
+ "model": "product.attributevalue",
+ "pk": 91,
+ "fields": {
+ "sort_order": 1,
+ "name": "Support",
+ "value": "",
+ "slug": "support",
+ "attribute": 29
+ }
+ },
+ {
+ "model": "product.attributevalue",
+ "pk": 92,
+ "fields": {
+ "sort_order": 2,
+ "name": "Medical",
+ "value": "",
+ "slug": "medical",
+ "attribute": 29
+ }
+ },
+ {
+ "model": "product.attributevalue",
+ "pk": 93,
+ "fields": {
+ "sort_order": 3,
+ "name": "General",
+ "value": "",
+ "slug": "general",
+ "attribute": 29
+ }
+ },
{
"model": "product.productimage",
"pk": 1,
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index a23e2a4417..332572b97f 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -26,6 +26,14 @@ from prices import Money, TaxedMoney
from ..account.models import Address, StaffNotificationRecipient, User
from ..app.models import App, AppInstallation
from ..app.types import AppType
+from ..attribute import AttributeInputType, AttributeType
+from ..attribute.models import (
+ Attribute,
+ AttributeTranslation,
+ AttributeValue,
+ AttributeValueTranslation,
+)
+from ..attribute.utils import associate_attribute_values_to_instance
from ..checkout import utils
from ..checkout.models import Checkout
from ..checkout.utils import add_variant_to_checkout
@@ -51,19 +59,14 @@ from ..order.actions import cancel_fulfillment, fulfill_order_line
from ..order.events import OrderEvents
from ..order.models import FulfillmentStatus, Order, OrderEvent, OrderLine
from ..order.utils import recalculate_order
-from ..page.models import Page, PageTranslation
+from ..page.models import Page, PageTranslation, PageType
from ..payment import ChargeStatus, TransactionKind
from ..payment.interface import GatewayConfig, PaymentData
from ..payment.models import Payment
from ..plugins.invoicing.plugin import InvoicingPlugin
from ..plugins.models import PluginConfiguration
from ..plugins.vatlayer.plugin import VatlayerPlugin
-from ..product import AttributeInputType
from ..product.models import (
- Attribute,
- AttributeTranslation,
- AttributeValue,
- AttributeValueTranslation,
Category,
CategoryTranslation,
Collection,
@@ -81,7 +84,6 @@ from ..product.models import (
ProductVariantTranslation,
)
from ..product.tests.utils import create_image
-from ..product.utils.attributes import associate_attribute_values_to_instance
from ..shipping.models import (
ShippingMethod,
ShippingMethodChannelListing,
@@ -705,7 +707,9 @@ def shipping_method_channel_PLN(shipping_zone, channel_PLN):
@pytest.fixture
def color_attribute(db): # pylint: disable=W0613
- attribute = Attribute.objects.create(slug="color", name="Color")
+ attribute = Attribute.objects.create(
+ slug="color", name="Color", type=AttributeType.PRODUCT_TYPE
+ )
AttributeValue.objects.create(attribute=attribute, name="Red", slug="red")
AttributeValue.objects.create(attribute=attribute, name="Blue", slug="blue")
return attribute
@@ -713,7 +717,9 @@ def color_attribute(db): # pylint: disable=W0613
@pytest.fixture
def color_attribute_without_values(db): # pylint: disable=W0613
- return Attribute.objects.create(slug="color", name="Color")
+ return Attribute.objects.create(
+ slug="color", name="Color", type=AttributeType.PRODUCT_TYPE
+ )
@pytest.fixture
@@ -726,7 +732,9 @@ def pink_attribute_value(color_attribute): # pylint: disable=W0613
@pytest.fixture
def size_attribute(db): # pylint: disable=W0613
- attribute = Attribute.objects.create(slug="size", name="Size")
+ attribute = Attribute.objects.create(
+ slug="size", name="Size", type=AttributeType.PRODUCT_TYPE
+ )
AttributeValue.objects.create(attribute=attribute, name="Small", slug="small")
AttributeValue.objects.create(attribute=attribute, name="Big", slug="big")
return attribute
@@ -734,7 +742,9 @@ def size_attribute(db): # pylint: disable=W0613
@pytest.fixture
def weight_attribute(db):
- attribute = Attribute.objects.create(slug="material", name="Material")
+ attribute = Attribute.objects.create(
+ slug="material", name="Material", type=AttributeType.PRODUCT_TYPE
+ )
AttributeValue.objects.create(attribute=attribute, name="Cotton", slug="cotton")
AttributeValue.objects.create(
attribute=attribute, name="Poliester", slug="poliester"
@@ -743,13 +753,66 @@ def weight_attribute(db):
@pytest.fixture
-def attribute_list() -> List[Attribute]:
+def size_page_attribute(db):
+ attribute = Attribute.objects.create(
+ slug="page-size", name="Page size", type=AttributeType.PAGE_TYPE
+ )
+ AttributeValue.objects.create(attribute=attribute, name="10", slug="10")
+ AttributeValue.objects.create(attribute=attribute, name="15", slug="15")
+ return attribute
+
+
+def tag_page_attribute(db):
+ attribute = Attribute.objects.create(
+ slug="tag", name="tag", type=AttributeType.PAGE_TYPE
+ )
+ AttributeValue.objects.create(attribute=attribute, name="About", slug="about")
+ AttributeValue.objects.create(attribute=attribute, name="Help", slug="help")
+ return attribute
+
+
+def author_page_attribute(db):
+ attribute = Attribute.objects.create(
+ slug="author", name="author", type=AttributeType.PAGE_TYPE
+ )
+ AttributeValue.objects.create(
+ attribute=attribute, name="Test author 1", slug="test-author-1"
+ )
+ AttributeValue.objects.create(
+ attribute=attribute, name="Test author 2", slug="test-author-2"
+ )
+ return attribute
+
+
+def product_type_attribute_list() -> List[Attribute]:
+ return list(
+ Attribute.objects.bulk_create(
+ [
+ Attribute(slug="size", name="Size", type=AttributeType.PRODUCT_TYPE),
+ Attribute(
+ slug="weight", name="Weight", type=AttributeType.PRODUCT_TYPE
+ ),
+ Attribute(
+ slug="thickness", name="Thickness", type=AttributeType.PRODUCT_TYPE
+ ),
+ ]
+ )
+ )
+
+
+def page_type_attribute_list() -> List[Attribute]:
return list(
Attribute.objects.bulk_create(
[
- Attribute(slug="size", name="Size"),
- Attribute(slug="weight", name="Weight"),
- Attribute(slug="thickness", name="Thickness"),
+ Attribute(slug="size", name="Size", type=AttributeType.PAGE_TYPE),
+ Attribute(slug="font", name="Weight", type=AttributeType.PAGE_TYPE),
+ Attribute(
+ slug="margin", name="Thickness", type=AttributeType.PAGE_TYPE
+ ),
]
)
)
@@ -1071,7 +1134,10 @@ def product_with_variant_with_two_attributes(
def product_with_multiple_values_attributes(product, product_type, category) -> Product:
attribute = Attribute.objects.create(
- slug="modes", name="Available Modes", input_type=AttributeInputType.MULTISELECT
+ slug="modes",
+ name="Available Modes",
+ input_type=AttributeInputType.MULTISELECT,
+ type=AttributeType.PRODUCT_TYPE,
)
attr_val_1 = AttributeValue.objects.create(
@@ -2383,6 +2449,11 @@ def permission_manage_pages():
return Permission.objects.get(codename="manage_pages")
+def permission_manage_page_types_and_attributes():
+ return Permission.objects.get(codename="manage_page_types_and_attributes")
+
+
@pytest.fixture
def permission_manage_translations():
return Permission.objects.get(codename="manage_translations")
@@ -2508,47 +2579,96 @@ def collection_list(db, channel_USD):
@pytest.fixture
-def page(db):
+def page(db, page_type):
data = {
"slug": "test-url",
"title": "Test page",
"content": "test content",
"is_published": True,
+ "page_type": page_type,
}
page = Page.objects.create(**data)
+
+ # associate attribute value
+ page_attr = page_type.page_attributes.first()
+ page_attr_value = page_attr.values.first()
+
+ associate_attribute_values_to_instance(page, page_attr, page_attr_value)
+
return page
@pytest.fixture
-def page_list(db):
+def page_list(db, page_type):
data_1 = {
"slug": "test-url",
"title": "Test page",
"content": "test content",
"is_published": True,
+ "page_type": page_type,
}
data_2 = {
"slug": "test-url-2",
"title": "Test page",
"content": "test content",
"is_published": True,
+ "page_type": page_type,
}
pages = Page.objects.bulk_create([Page(**data_1), Page(**data_2)])
return pages
@pytest.fixture
-def page_list_unpublished(db):
+def page_list_unpublished(db, page_type):
pages = Page.objects.bulk_create(
[
- Page(slug="page-1", title="Page 1", is_published=False),
- Page(slug="page-2", title="Page 2", is_published=False),
- Page(slug="page-3", title="Page 3", is_published=False),
+ Page(
+ slug="page-1", title="Page 1", is_published=False, page_type=page_type
+ ),
+ Page(
+ slug="page-2", title="Page 2", is_published=False, page_type=page_type
+ ),
+ Page(
+ slug="page-3", title="Page 3", is_published=False, page_type=page_type
+ ),
]
)
return pages
+def page_type(db, size_page_attribute, tag_page_attribute):
+ page_type = PageType.objects.create(name="Test page type", slug="test-page-type")
+ page_type.page_attributes.add(size_page_attribute)
+ page_type.page_attributes.add(tag_page_attribute)
+
+ return page_type
+
+
+def page_type_list(db, tag_page_attribute):
+ page_types = list(
+ PageType.objects.bulk_create(
+ [
+ PageType(name="Test page type 1", slug="test-page-type-1"),
+ PageType(name="Example page type 2", slug="page-type-2"),
+ PageType(name="Example page type 3", slug="page-type-3"),
+ ]
+ )
+ )
+
+ for i, page_type in enumerate(page_types):
+ page_type.page_attributes.add(tag_page_attribute)
+ Page.objects.create(
+ title=f"Test page {i}",
+ slug=f"test-url-{i}",
+ is_published=True,
+ page_type=page_type,
+ )
+
+ return page_types
+
+
@pytest.fixture
def model_form_class():
mocked_form_class = MagicMock(name="test", spec=ModelForm)