Skip to content

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

Narrow down reference attributes (#18084)

Iga Karbowiak96a737de3321
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ea15b5df28..c65bde40b6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -97,8 +97,8 @@ Like `reference`, the `single-reference` type can target entities defined in the
- Refunds are now more powerful. You can configure new `RefundSettings` to accept a `reasonReferenceType`. Once assigned, creating refunds (both manual and with grant refunds) will require a reason type to be specified. `refundReasonReferenceTypeClear` clears the settings.
- You can now use the `AssignedAttribute` interface and the `assignedAttribute`, `assignedAttributes` fields on `Page`, `Product`, and `ProductVariant` to fetch assigned attributes and their values in a cleaner, more focused shape.
- `attribute` and `attributes` fields on Page, Product, and ProductVariant are deprecated.
-
-
+- Added support for restricting available references for `REFERENCE` and `SINGLE_REFERENCE` attributes by specifying reference product or page types.
+ - You can now define `referenceTypes` on an `Attribute` to limit reference choices. Use `productType` for product and product variant references, and page types for page references.
### Webhooks
- Transaction webhooks responsible for processing payments can now return payment method details`, which will be associated with the corresponding transaction. See [docs](https://docs.saleor.io/developer/extending/webhooks/synchronous-events/transaction#response-4) to learn more.
diff --git a/saleor/attribute/lock_objects.py b/saleor/attribute/lock_objects.py
index bf5cd4aa6e..0361872920 100644
--- a/saleor/attribute/lock_objects.py
+++ b/saleor/attribute/lock_objects.py
@@ -1,9 +1,21 @@
from django.db.models import QuerySet
-from .models.base import AttributeValue
+from .models.base import Attribute, AttributeValue
def attribute_value_qs_select_for_update() -> QuerySet[AttributeValue]:
return AttributeValue.objects.order_by("sort_order", "pk").select_for_update(
of=(["self"])
)
+
+
+def attribute_reference_product_types_qs_select_for_update() -> QuerySet:
+ return Attribute.reference_product_types.through.objects.order_by(
+ "pk"
+ ).select_for_update(of=["self"])
+
+
+def attribute_reference_page_types_qs_select_for_update() -> QuerySet:
+ return Attribute.reference_page_types.through.objects.order_by(
+ "pk"
+ ).select_for_update(of=["self"])
diff --git a/saleor/attribute/migrations/0054_attribute_reference_page_and_product_types.py b/saleor/attribute/migrations/0054_attribute_reference_page_and_product_types.py
new file mode 100644
index 0000000000..48570c0e90
--- /dev/null
+++ b/saleor/attribute/migrations/0054_attribute_reference_page_and_product_types.py
@@ -0,0 +1,28 @@
+# Generated by Django 5.2.1 on 2025-08-07 12:51
+
+from django.db import migrations, models
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("attribute", "0053_fulfill_numeric_attribute_value"),
+ ("page", "0031_alter_page_metadata_alter_page_private_metadata_and_more"),
+ ("product", "0201_productvariant_variant_gin"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="attribute",
+ name="reference_page_types",
+ field=models.ManyToManyField(
+ blank=True, related_name="+", to="page.pagetype"
+ ),
+ ),
+ migrations.AddField(
+ model_name="attribute",
+ name="reference_product_types",
+ field=models.ManyToManyField(
+ blank=True, related_name="+", to="product.producttype"
+ ),
+ ),
+ ]
diff --git a/saleor/attribute/models/base.py b/saleor/attribute/models/base.py
index 892f07af71..692694421d 100644
--- a/saleor/attribute/models/base.py
+++ b/saleor/attribute/models/base.py
@@ -126,6 +126,22 @@ class Attribute(ModelWithMetadata, ModelWithExternalReference):
entity_type = models.CharField(
max_length=50, choices=AttributeEntityType.CHOICES, blank=True, null=True
)
+ # The product types that are used to narrow down the choices of products
+ # or variants for a reference attribute.
+ # Applicable only for attributes with the `PRODUCT` and `VARIANT` entity types.
+ reference_product_types = models.ManyToManyField(
+ ProductType,
+ blank=True,
+ related_name="+",
+ )
+ # The page types that are used to narrow down the choices of pages
+ # for a reference attribute.
+ # Applicable only for attributes with the `PAGE` entity type.
+ reference_page_types = models.ManyToManyField(
+ PageType,
+ blank=True,
+ related_name="+",
+ )
product_types = models.ManyToManyField(
ProductType,
diff --git a/saleor/attribute/tests/fixtures/attribute.py b/saleor/attribute/tests/fixtures/attribute.py
index 50589ddc03..e6e8ca7fa1 100644
--- a/saleor/attribute/tests/fixtures/attribute.py
+++ b/saleor/attribute/tests/fixtures/attribute.py
@@ -577,8 +577,8 @@ def swatch_attribute(db):
@pytest.fixture
def product_type_page_reference_attribute(db):
return Attribute.objects.create(
- slug="page-reference",
- name="Page reference",
+ slug="product-page-reference",
+ name="Product page reference",
type=AttributeType.PRODUCT_TYPE,
input_type=AttributeInputType.REFERENCE,
entity_type=AttributeEntityType.PAGE,
diff --git a/saleor/graphql/attribute/dataloaders/__init__.py b/saleor/graphql/attribute/dataloaders/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/graphql/attribute/dataloaders.py b/saleor/graphql/attribute/dataloaders/attributes.py
similarity index 94%
rename from saleor/graphql/attribute/dataloaders.py
rename to saleor/graphql/attribute/dataloaders/attributes.py
index ebef161583..afddf60316 100644
--- a/saleor/graphql/attribute/dataloaders.py
+++ b/saleor/graphql/attribute/dataloaders/attributes.py
@@ -1,7 +1,7 @@
from collections import defaultdict
-from ...attribute.models import Attribute, AttributeValue
-from ..core.dataloaders import DataLoader
+from ....attribute.models import Attribute, AttributeValue
+from ...core.dataloaders import DataLoader
class AttributeValuesByAttributeIdLoader(DataLoader[int, list[AttributeValue]]):
diff --git a/saleor/graphql/attribute/dataloaders/reference_types.py b/saleor/graphql/attribute/dataloaders/reference_types.py
new file mode 100644
index 0000000000..605e61d9e6
--- /dev/null
+++ b/saleor/graphql/attribute/dataloaders/reference_types.py
@@ -0,0 +1,105 @@
+from collections import defaultdict
+from collections.abc import Iterable
+
+from ....attribute.models import Attribute
+from ....page.models import PageType
+from ....product.models import ProductType
+from ...core.dataloaders import DataLoader
+from ...page.dataloaders import PageTypeByIdLoader
+from ...product.dataloaders import ProductTypeByIdLoader
+
+type LIMIT = int | None
+type PAGE_TYPE_ID = int
+type ATTRIBUTE_ID = int
+
+
+class AttributeReferenceProductTypesByAttributeIdAndLimitLoader(
+ DataLoader[tuple[ATTRIBUTE_ID, LIMIT], list[ProductType]]
+):
+ context_key = "attributereferenceproducttypes_by_attributeid_and_limit"
+
+ def batch_load(self, keys: Iterable[tuple[ATTRIBUTE_ID, LIMIT]]):
+ ReferenceTypeModel = Attribute.reference_product_types.through
+ attribute_ids = [attribute_id for attribute_id, _ in keys]
+ reference_types = (
+ ReferenceTypeModel.objects.using(self.database_connection_name).filter(
+ attribute_id__in=attribute_ids
+ )
+ ).values_list("attribute_id", "producttype_id")
+
+ attribute_id_to_product_type_ids = defaultdict(list)
+ for attribute_id, producttype_id in reference_types:
+ attribute_id_to_product_type_ids[attribute_id].append(producttype_id)
+
+ product_type_ids = set()
+ for attribute_id, limit in keys:
+ product_type_ids.update(
+ attribute_id_to_product_type_ids.get(attribute_id, [])[:limit]
+ )
+
+ def get_reference_types(product_types):
+ response = []
+ product_type_map = {
+ product_type.id: product_type for product_type in product_types
+ }
+ for attribute_id, limit in keys:
+ product_type_ids = attribute_id_to_product_type_ids.get(
+ attribute_id, []
+ )[:limit]
+ single_response_entry: list[ProductType] = []
+ for product_type_id in product_type_ids:
+ if product_type := product_type_map.get(product_type_id):
+ single_response_entry.append(product_type)
+ response.append(single_response_entry)
+ return response
+
+ return (
+ ProductTypeByIdLoader(self.context)
+ .load_many(list(product_type_ids))
+ .then(get_reference_types)
+ )
+
+
+class AttributeReferencePageTypesByAttributeIdAndLimitLoader(
+ DataLoader[tuple[ATTRIBUTE_ID, LIMIT], list[PageType]]
+):
+ context_key = "attributereferencepagetypes_by_attributeid_and_limit"
+
+ def batch_load(self, keys: Iterable[tuple[ATTRIBUTE_ID, LIMIT]]):
+ ReferenceTypeModel = Attribute.reference_page_types.through
+ attribute_ids = [attribute_id for attribute_id, _ in keys]
+ reference_types = (
+ ReferenceTypeModel.objects.using(self.database_connection_name).filter(
+ attribute_id__in=attribute_ids
+ )
+ ).values_list("attribute_id", "pagetype_id")
+
+ attribute_id_to_page_type_ids = defaultdict(list)
+ for attribute_id, pagetype_id in reference_types:
+ attribute_id_to_page_type_ids[attribute_id].append(pagetype_id)
+
+ page_type_ids = set()
+ for attribute_id, limit in keys:
+ page_type_ids.update(
+ attribute_id_to_page_type_ids.get(attribute_id, [])[:limit]
+ )
+
+ def get_reference_types(page_types):
+ response = []
+ page_type_map = {page_type.id: page_type for page_type in page_types}
+ for attribute_id, limit in keys:
+ page_type_ids = attribute_id_to_page_type_ids.get(attribute_id, [])[
+ :limit
+ ]
+ single_response_entry: list[PageType] = []
+ for page_type_id in page_type_ids:
+ if page_type := page_type_map.get(page_type_id):
+ single_response_entry.append(page_type)
+ response.append(single_response_entry)
+ return response
+
+ return (
+ PageTypeByIdLoader(self.context)
+ .load_many(list(page_type_ids))
+ .then(get_reference_types)
+ )
diff --git a/saleor/graphql/attribute/mutations/attribute_bulk_create.py b/saleor/graphql/attribute/mutations/attribute_bulk_create.py
index aa8d8ddf79..41ab8e6ea9 100644
--- a/saleor/graphql/attribute/mutations/attribute_bulk_create.py
+++ b/saleor/graphql/attribute/mutations/attribute_bulk_create.py
@@ -1,4 +1,5 @@
from collections import defaultdict
+from typing import cast
import graphene
from django.core.exceptions import ValidationError
@@ -6,7 +7,12 @@ from django.utils.text import slugify
from graphene.utils.str_converters import to_camel_case
from text_unidecode import unidecode
-from ....attribute import ATTRIBUTE_PROPERTIES_CONFIGURATION, AttributeInputType, models
+from ....attribute import (
+ ATTRIBUTE_PROPERTIES_CONFIGURATION,
+ AttributeEntityType,
+ AttributeInputType,
+ models,
+)
from ....attribute.error_codes import AttributeBulkCreateErrorCode
from ....core.tracing import traced_atomic_transaction
from ....core.utils import prepare_unique_slug
@@ -24,6 +30,7 @@ from ...plugins.dataloaders import get_plugin_manager_promise
from ..enums import AttributeTypeEnum
from ..mutations.attribute_create import AttributeCreateInput, AttributeValueCreateInput
from ..types import Attribute
+from .mixins import AttributeMixin
ONLY_SWATCH_FIELDS = ["file_url", "content_type", "value"]
DEPRECATED_ATTR_FIELDS = [
@@ -335,6 +342,19 @@ class AttributeBulkCreate(BaseMutation):
cleaned_inputs_map[attribute_index] = None
continue
+ try:
+ AttributeMixin.validate_reference_types_limit(attribute_data)
+ except ValidationError as e:
+ index_error_map[attribute_index].append(
+ AttributeBulkCreateError(
+ path="referenceTypes",
+ message=e.messages[0],
+ code=AttributeBulkCreateErrorCode.INVALID.value,
+ )
+ )
+ cleaned_inputs_map[attribute_index] = None
+ continue
+
cleaned_input = cls.clean_attribute_input(
info,
attribute_data,
@@ -382,8 +402,9 @@ class AttributeBulkCreate(BaseMutation):
)
return None
- input_type = cleaned_input.get("input_type")
entity_type = cleaned_input.get("entity_type")
+ # set the db default input type if not provided
+ input_type = cleaned_input.get("input_type", AttributeInputType.DROPDOWN)
if input_type == AttributeInputType.REFERENCE and not entity_type:
index_error_map[attribute_index].append(
AttributeBulkCreateError(
@@ -414,6 +435,19 @@ class AttributeBulkCreate(BaseMutation):
)
return None
+ entity_type = cast(str, entity_type)
+ try:
+ AttributeMixin.clean_reference_types(cleaned_input, entity_type, input_type)
+ except ValidationError as e:
+ index_error_map[attribute_index].append(
+ AttributeBulkCreateError(
+ path="referenceTypes",
+ message=e.messages[0],
+ code=AttributeBulkCreateErrorCode.INVALID.value,
+ )
+ )
+ return None
+
# generate slug
cleaned_input["slug"] = cls._generate_slug(cleaned_input, existing_slugs)
@@ -458,6 +492,8 @@ class AttributeBulkCreate(BaseMutation):
continue
values: list = []
+ product_reference_types: list = []
+ page_reference_types: list = []
values_data = cleaned_input.pop("values", None)
instance = models.Attribute()
@@ -470,6 +506,8 @@ class AttributeBulkCreate(BaseMutation):
"instance": instance,
"errors": index_error_map[index],
"values": values,
+ "product_reference_types": product_reference_types,
+ "page_reference_types": page_reference_types,
}
)
except ValidationError as exc:
@@ -487,6 +525,10 @@ class AttributeBulkCreate(BaseMutation):
)
continue
+ cls.create_reference_types(
+ cleaned_input, instance, product_reference_types, page_reference_types
+ )
+
if values_data:
cls.create_values(instance, values_data, values, index, index_error_map)
@@ -525,12 +567,40 @@ class AttributeBulkCreate(BaseMutation):
)
)
+ @classmethod
+ def create_reference_types(
+ cls,
+ cleaned_input: dict,
+ attribute: models.Attribute,
+ product_reference_types: list,
+ page_reference_types: list,
+ ):
+ if reference_types_objects := cleaned_input.get("reference_types"):
+ if attribute.entity_type == AttributeEntityType.PAGE:
+ PageReferenceTypeModel = models.Attribute.reference_page_types.through
+ page_reference_types.extend(
+ PageReferenceTypeModel(attribute=attribute, pagetype=reference_type)
+ for reference_type in reference_types_objects
+ )
+ else:
+ ProductReferenceTypeModel = (
+ models.Attribute.reference_product_types.through
+ )
+ product_reference_types.extend(
+ ProductReferenceTypeModel(
+ attribute=attribute, producttype=reference_type
+ )
+ for reference_type in reference_types_objects
+ )
+
@classmethod
def save(
cls, instances_data_with_errors_list: list[dict]
) -> list[models.Attribute]:
attributes_to_create: list = []
values_to_create: list = []
+ product_reference_types_to_create: list = []
+ page_reference_types_to_create: list = []
for attribute_data in instances_data_with_errors_list:
attribute = attribute_data["instance"]
@@ -542,8 +612,20 @@ class AttributeBulkCreate(BaseMutation):
if attribute_data["values"]:
values_to_create.extend(attribute_data["values"])
+ if ref_types := attribute_data["product_reference_types"]:
+ product_reference_types_to_create.extend(ref_types)
+
+ if ref_types := attribute_data["page_reference_types"]:
+ page_reference_types_to_create.extend(ref_types)
+
models.Attribute.objects.bulk_create(attributes_to_create)
models.AttributeValue.objects.bulk_create(values_to_create)
+ if product_reference_types_to_create:
+ ReferenceTypeModel = product_reference_types_to_create[0]._meta.model
+ ReferenceTypeModel.objects.bulk_create(product_reference_types_to_create)
+ if page_reference_types_to_create:
+ ReferenceTypeModel = page_reference_types_to_create[0]._meta.model
+ ReferenceTypeModel.objects.bulk_create(page_reference_types_to_create)
return attributes_to_create
diff --git a/saleor/graphql/attribute/mutations/attribute_bulk_update.py b/saleor/graphql/attribute/mutations/attribute_bulk_update.py
index e5f5b7c84c..7731547ed0 100644
--- a/saleor/graphql/attribute/mutations/attribute_bulk_update.py
+++ b/saleor/graphql/attribute/mutations/attribute_bulk_update.py
@@ -1,4 +1,5 @@
from collections import defaultdict
+from dataclasses import dataclass, field
import graphene
from django.core.exceptions import ValidationError
@@ -9,9 +10,13 @@ from graphene.utils.str_converters import to_camel_case
from graphql.error import GraphQLError
from text_unidecode import unidecode
-from ....attribute import models
+from ....attribute import AttributeEntityType, models
from ....attribute.error_codes import AttributeBulkUpdateErrorCode
-from ....attribute.lock_objects import attribute_value_qs_select_for_update
+from ....attribute.lock_objects import (
+ attribute_reference_page_types_qs_select_for_update,
+ attribute_reference_product_types_qs_select_for_update,
+ attribute_value_qs_select_for_update,
+)
from ....core.tracing import traced_atomic_transaction
from ....permission.enums import PageTypePermissions, ProductTypePermissions
from ....webhook.utils import get_webhooks_for_event
@@ -38,6 +43,15 @@ from ..enums import AttributeTypeEnum
from ..types import Attribute
from .attribute_bulk_create import DEPRECATED_ATTR_FIELDS, clean_values
from .attribute_update import AttributeUpdateInput
+from .mixins import AttributeMixin
+
+
+@dataclass
+class ReferenceTypeUpdateData:
+ create_product_reference_types: list[tuple[int, int]] = field(default_factory=list)
+ create_page_reference_types: list[tuple[int, int]] = field(default_factory=list)
+ delete_product_reference_types: list[tuple[int, int]] = field(default_factory=list)
+ delete_page_reference_types: list[tuple[int, int]] = field(default_factory=list)
class AttributeBulkUpdateResult(BaseObjectType):
@@ -229,6 +243,19 @@ class AttributeBulkUpdate(BaseMutation):
cleaned_inputs_map[attribute_index] = None
continue
+ try:
+ AttributeMixin.validate_reference_types_limit(attribute_data.fields)
+ except ValidationError as e:
+ index_error_map[attribute_index].append(
+ AttributeBulkUpdateError(
+ path="referenceTypes",
+ message=e.messages[0],
+ code=AttributeBulkUpdateErrorCode.INVALID.value,
+ )
+ )
+ cleaned_inputs_map[attribute_index] = None
+ continue
+
cleaned_input = cls.clean_attribute_input(
info,
attribute_data,
@@ -294,6 +321,26 @@ class AttributeBulkUpdate(BaseMutation):
return values_existing_external_refs, duplicated_values_external_ref
+ @classmethod
+ def get_existing_reference_types(cls, cleaned_inputs_map: dict) -> dict[int, set]:
+ existing_reference_types = defaultdict(set)
+ ReferenceProductType = models.Attribute.reference_product_types.through
+ ReferencePageType = models.Attribute.reference_page_types.through
+ attr_ids = [
+ cleaned_input["instance"].pk
+ for cleaned_input in cleaned_inputs_map.values()
+ if cleaned_input and "instance" in cleaned_input
+ ]
+ for attr_id, product_type_id in ReferenceProductType.objects.filter(
+ attribute_id__in=attr_ids
+ ).values_list("attribute_id", "producttype_id"):
+ existing_reference_types[attr_id].add(product_type_id)
+ for attr_id, page_type_id in ReferencePageType.objects.filter(
+ attribute_id__in=attr_ids
+ ).values_list("attribute_id", "pagetype_id"):
+ existing_reference_types[attr_id].add(page_type_id)
+ return existing_reference_types
+
@classmethod
def clean_attribute_input(
cls,
@@ -345,6 +392,20 @@ class AttributeBulkUpdate(BaseMutation):
info, None, attribute_data.fields, input_cls=AttributeUpdateInput
)
+ try:
+ AttributeMixin.clean_reference_types(
+ attribute_data["fields"], attr.entity_type, attr.input_type
+ )
+ except ValidationError as e:
+ index_error_map[attribute_index].append(
+ AttributeBulkUpdateError(
+ path="referenceTypes",
+ message=e.messages[0],
+ code=AttributeBulkUpdateErrorCode.INVALID.value,
+ )
+ )
+ return None
+
if remove_values:
cleaned_remove_values = cls.clean_remove_values(
remove_values, attr, attribute_index, index_error_map
@@ -412,6 +473,7 @@ class AttributeBulkUpdate(BaseMutation):
cleaned_inputs_map: dict[int, dict],
error_policy: str,
index_error_map: dict[int, list[AttributeBulkUpdateError]],
+ existing_reference_types_map: dict[int, set],
) -> list[dict]:
instances_data_and_errors_list: list[dict] = []
@@ -446,12 +508,18 @@ class AttributeBulkUpdate(BaseMutation):
)
continue
+ reference_types_update_data = cls.create_reference_types(
+ attr,
+ existing_reference_types_map.get(attr.pk, set()),
+ fields,
+ )
data = {
"instance": attr,
"errors": index_error_map[index],
"remove_values": remove_values,
"add_values": [],
"attribute_updated": True if fields else False,
+ "reference_types_updated": reference_types_update_data,
}
if add_values:
@@ -496,6 +564,38 @@ class AttributeBulkUpdate(BaseMutation):
)
return values
+ @classmethod
+ def create_reference_types(
+ cls,
+ attribute: models.Attribute,
+ existing_reference_types: set[int],
+ cleaned_input: dict,
+ ) -> ReferenceTypeUpdateData:
+ if "reference_types" not in cleaned_input:
+ return ReferenceTypeUpdateData()
+ reference_type_ids = [
+ ref_type.id for ref_type in cleaned_input["reference_types"]
+ ]
+ to_create = set(reference_type_ids) - existing_reference_types
+ to_delete = existing_reference_types - set(reference_type_ids)
+ if attribute.entity_type == AttributeEntityType.PAGE:
+ return ReferenceTypeUpdateData(
+ create_page_reference_types=[
+ (attribute.pk, reference_type) for reference_type in to_create
+ ],
+ delete_page_reference_types=[
+ (attribute.pk, reference_type) for reference_type in to_delete
+ ],
+ )
+ return ReferenceTypeUpdateData(
+ create_product_reference_types=[
+ (attribute.pk, reference_type) for reference_type in to_create
+ ],
+ delete_product_reference_types=[
+ (attribute.pk, reference_type) for reference_type in to_delete
+ ],
+ )
+
@classmethod
def get_attributes(
cls, attributes_data: list[AttributeBulkUpdateInput]
@@ -559,6 +659,10 @@ class AttributeBulkUpdate(BaseMutation):
values_to_create: list = []
values_to_remove: list = []
updated_attributes: list = []
+ create_product_reference_types: list = []
+ create_page_reference_types: list = []
+ delete_product_reference_types_lookup: Q = Q()
+ delete_page_reference_types_lookup: Q = Q()
for attribute_data in instances_data_with_errors_list:
attribute = attribute_data["instance"]
@@ -574,6 +678,16 @@ class AttributeBulkUpdate(BaseMutation):
values_to_remove.extend(attribute_data["remove_values"])
values_to_create.extend(attribute_data["add_values"])
+ delete_product_ref, delete_page_ref = (
+ cls._prepare_reference_types_for_saving(
+ attribute_data["reference_types_updated"],
+ create_product_reference_types,
+ create_page_reference_types,
+ )
+ )
+ delete_product_reference_types_lookup |= delete_product_ref
+ delete_page_reference_types_lookup |= delete_page_ref
+
with transaction.atomic():
models.Attribute.objects.bulk_update(
attributes_to_update,
@@ -597,9 +711,94 @@ class AttributeBulkUpdate(BaseMutation):
models.AttributeValue.objects.bulk_create(values_to_create)
+ cls._save_reference_types(
+ create_product_reference_types,
+ create_page_reference_types,
+ delete_product_reference_types_lookup,
+ delete_page_reference_types_lookup,
+ )
+
updated_attributes.extend(attributes_to_update)
return updated_attributes, values_to_remove, values_to_create
+ @classmethod
+ def _prepare_reference_types_for_saving(
+ cls,
+ reference_update_data: ReferenceTypeUpdateData,
+ create_product_reference_types: list,
+ create_page_reference_types: list,
+ ) -> tuple[Q, Q]:
+ ModelProductReferenceType = models.Attribute.reference_product_types.through
+ ModelPageReferenceType = models.Attribute.reference_page_types.through
+ create_product_reference_types.extend(
+ ModelProductReferenceType(
+ attribute_id=attr_id,
+ producttype_id=product_type_id,
+ )
+ for attr_id, product_type_id in reference_update_data.create_product_reference_types
+ )
+ create_page_reference_types.extend(
+ ModelPageReferenceType(
+ attribute_id=attr_id,
+ pagetype_id=page_type_id,
+ )
+ for attr_id, page_type_id in reference_update_data.create_page_reference_types
+ )
+
+ delete_product_reference_types_lookup = Q()
+ delete_page_reference_types_lookup = Q()
+ for (
+ attr_id,
+ product_type_id,
+ ) in reference_update_data.delete_product_reference_types:
+ delete_product_reference_types_lookup |= Q(
+ attribute_id=attr_id,
+ producttype_id=product_type_id,
+ )
+ for attr_id, page_type_id in reference_update_data.delete_page_reference_types:
+ delete_page_reference_types_lookup |= Q(
+ attribute_id=attr_id,
+ pagetype_id=page_type_id,
+ )
+ return delete_product_reference_types_lookup, delete_page_reference_types_lookup
+
+ @classmethod
+ def _save_reference_types(
+ cls,
+ create_product_reference_types: list,
+ create_page_reference_types: list,
+ delete_product_reference_types_lookup: Q,
+ delete_page_reference_types_lookup: Q,
+ ):
+ ModelProductReferenceType = models.Attribute.reference_product_types.through
+ ModelPageReferenceType = models.Attribute.reference_page_types.through
+
+ if create_product_reference_types:
+ ModelProductReferenceType.objects.bulk_create(
+ create_product_reference_types
+ )
+ if create_page_reference_types:
+ ModelPageReferenceType.objects.bulk_create(create_page_reference_types)
+
+ if delete_product_reference_types_lookup:
+ _locked_ref_product_types = list(
+ attribute_reference_product_types_qs_select_for_update().filter(
+ delete_product_reference_types_lookup
+ )
+ )
+ ModelProductReferenceType.objects.filter(
+ delete_product_reference_types_lookup
+ ).delete()
+ if delete_page_reference_types_lookup:
+ _locked_ref_page_types = list(
+ attribute_reference_page_types_qs_select_for_update().filter(
+ delete_page_reference_types_lookup
+ )
+ )
+ ModelPageReferenceType.objects.filter(
+ delete_page_reference_types_lookup
+ ).delete()
+
@classmethod
def post_save_actions(
cls,
@@ -629,8 +828,15 @@ class AttributeBulkUpdate(BaseMutation):
cleaned_inputs_map = cls.clean_attributes(
info, data["attributes"], index_error_map
)
+ existing_reference_types_map = cls.get_existing_reference_types(
+ cleaned_inputs_map
+ )
instances_data_with_errors_list = cls.update_attributes(
- info, cleaned_inputs_map, error_policy, index_error_map
+ info,
+ cleaned_inputs_map,
+ error_policy,
+ index_error_map,
+ existing_reference_types_map,
)
# check if errors occurred
diff --git a/saleor/graphql/attribute/mutations/attribute_create.py b/saleor/graphql/attribute/mutations/attribute_create.py
index c694319755..9694abe22d 100644
--- a/saleor/graphql/attribute/mutations/attribute_create.py
+++ b/saleor/graphql/attribute/mutations/attribute_create.py
@@ -9,7 +9,7 @@ from ....permission.enums import PageTypePermissions, ProductTypePermissions
from ....webhook.event_types import WebhookEventAsyncType
from ...core import ResolveInfo
from ...core.context import ChannelContext
-from ...core.descriptions import DEPRECATED_IN_3X_INPUT
+from ...core.descriptions import ADDED_IN_322, DEPRECATED_IN_3X_INPUT
from ...core.doc_category import DOC_CATEGORY_ATTRIBUTES
from ...core.enums import MeasurementUnitsEnum
from ...core.fields import JSONString
@@ -20,7 +20,7 @@ from ...plugins.dataloaders import get_plugin_manager_promise
from ..descriptions import AttributeDescriptions, AttributeValueDescriptions
from ..enums import AttributeEntityTypeEnum, AttributeInputTypeEnum, AttributeTypeEnum
from ..types import Attribute
-from .mixins import AttributeMixin
+from .mixins import REFERENCE_TYPES_LIMIT, AttributeMixin
class AttributeValueInput(BaseInputObjectType):
@@ -94,6 +94,21 @@ class AttributeCreateInput(BaseInputObjectType):
external_reference = graphene.String(
description="External ID of this attribute.", required=False
)
+ reference_types = NonNullList(
+ graphene.ID,
+ required=False,
+ description=(
+ "Specifies reference types to narrow down the choices of reference "
+ "objects. Applicable only for `REFERENCE` and `SINGLE_REFERENCE` "
+ "attributes with `PRODUCT`, `PRODUCT_VARIANT` and `PAGE` entity types. "
+ "Accepts `ProductType` IDs for `PRODUCT` and `PRODUCT_VARIANT` "
+ "entity types, and `PageType` IDs for `PAGE` entity type. "
+ "If omitted, all objects of the selected entity type are available "
+ "as attribute values.\n\n"
+ f"A maximum of {REFERENCE_TYPES_LIMIT} reference types can be specified."
+ + ADDED_IN_322
+ ),
+ )
class Meta:
doc_category = DOC_CATEGORY_ATTRIBUTES
@@ -161,6 +176,7 @@ class AttributeCreate(AttributeMixin, DeprecatedModelMutation):
if not cls.check_permissions(info.context, permissions):
raise PermissionDenied(permissions=permissions)
+ cls.validate_reference_types_limit(input)
instance = models.Attribute()
# Do cleaning and uniqueness checks
diff --git a/saleor/graphql/attribute/mutations/attribute_update.py b/saleor/graphql/attribute/mutations/attribute_update.py
index 2232b9dd72..646f7675f2 100644
--- a/saleor/graphql/attribute/mutations/attribute_update.py
+++ b/saleor/graphql/attribute/mutations/attribute_update.py
@@ -7,7 +7,7 @@ from ....permission.enums import ProductTypePermissions
from ....webhook.event_types import WebhookEventAsyncType
from ...core import ResolveInfo
from ...core.context import ChannelContext
-from ...core.descriptions import DEPRECATED_IN_3X_INPUT
+from ...core.descriptions import ADDED_IN_322, DEPRECATED_IN_3X_INPUT
from ...core.doc_category import DOC_CATEGORY_ATTRIBUTES
from ...core.enums import MeasurementUnitsEnum
from ...core.mutations import ModelWithExtRefMutation
@@ -17,7 +17,7 @@ from ...plugins.dataloaders import get_plugin_manager_promise
from ..descriptions import AttributeDescriptions, AttributeValueDescriptions
from ..types import Attribute
from .attribute_create import AttributeValueInput
-from .mixins import AttributeMixin
+from .mixins import REFERENCE_TYPES_LIMIT, AttributeMixin
class AttributeValueUpdateInput(AttributeValueInput):
@@ -67,6 +67,21 @@ class AttributeUpdateInput(BaseInputObjectType):
external_reference = graphene.String(
description="External ID of this product.", required=False
)
+ reference_types = NonNullList(
+ graphene.ID,
+ required=False,
+ description=(
+ "Specifies reference types to narrow down the choices of reference "
+ "objects. Applicable only for `REFERENCE` and `SINGLE_REFERENCE` "
+ "attributes with `PRODUCT`, `PRODUCT_VARIANT` and `PAGE` entity types. "
+ "Accepts `ProductType` IDs for `PRODUCT` and `PRODUCT_VARIANT` "
+ "entity types, and `PageType` IDs for `PAGE` entity type. "
+ "If omitted, all objects of the selected entity type are available "
+ "as attribute values.\n\n"
+ f"A maximum of {REFERENCE_TYPES_LIMIT} reference types can be specified."
+ + ADDED_IN_322
+ ),
+ )
class Meta:
doc_category = DOC_CATEGORY_ATTRIBUTES
@@ -137,6 +152,7 @@ class AttributeUpdate(AttributeMixin, ModelWithExtRefMutation):
):
instance = cls.get_instance(info, external_reference=external_reference, id=id)
+ cls.validate_reference_types_limit(input)
# Do cleaning and uniqueness checks
cleaned_input = cls.clean_input(info, instance, input)
cls.clean_attribute(instance, cleaned_input)
diff --git a/saleor/graphql/attribute/mutations/mixins.py b/saleor/graphql/attribute/mutations/mixins.py
index d263c39f1e..5fd3151f75 100644
--- a/saleor/graphql/attribute/mutations/mixins.py
+++ b/saleor/graphql/attribute/mutations/mixins.py
@@ -1,13 +1,28 @@
+from typing import cast
+
from django.core.exceptions import ValidationError
from django.utils.text import slugify
from text_unidecode import unidecode
-from ....attribute import ATTRIBUTE_PROPERTIES_CONFIGURATION, AttributeInputType
+from ....attribute import (
+ ATTRIBUTE_PROPERTIES_CONFIGURATION,
+ AttributeEntityType,
+ AttributeInputType,
+)
from ....attribute import models as models
from ....attribute.error_codes import AttributeErrorCode
from ....core.utils import prepare_unique_slug
+from ....page import models as page_models
+from ....product import models as product_models
from ...core import ResolveInfo
-from ...core.validators import validate_slug_and_generate_if_needed
+from ...core.validators import (
+ validate_limit_of_list_input,
+ validate_slug_and_generate_if_needed,
+)
+
+REFERENCE_TYPES_LIMIT = 100
+
+T_REFERENCE_TYPES = list[product_models.ProductType] | list[page_models.PageType]
class AttributeMixin:
@@ -153,6 +168,22 @@ class AttributeMixin:
}
)
+ @classmethod
+ def validate_reference_types_limit(cls, input: dict):
+ """Validate the number of reference types."""
+ reference_types = input.get("reference_types")
+ if not reference_types:
+ return
+
+ try:
+ validate_limit_of_list_input(
+ reference_types, REFERENCE_TYPES_LIMIT, "reference_types"
+ )
+ except ValidationError as error:
+ # If the validation fails, we raise a ValidationError with a custom message.
+ error.code = AttributeErrorCode.INVALID.value
+ raise ValidationError({"reference_types": error}) from error
+
@classmethod
def clean_attribute(cls, instance, cleaned_input):
try:
@@ -163,6 +194,10 @@ class AttributeMixin:
e.code = AttributeErrorCode.REQUIRED.value
raise ValidationError({"slug": e}) from e
cls._clean_attribute_settings(instance, cleaned_input)
+ entity_type = cleaned_input.get("entity_type") or instance.entity_type
+ input_type = cleaned_input.get("input_type") or instance.input_type
+ entity_type = cast(str, entity_type)
+ cls.clean_reference_types(cleaned_input, entity_type, input_type)
return cleaned_input
@@ -186,9 +221,93 @@ class AttributeMixin:
if errors:
raise ValidationError(errors)
+ @classmethod
+ def clean_reference_types(
+ cls, cleaned_input: dict, entity_type: str, input_type: str
+ ):
+ """Validate reference types for reference attributes."""
+ reference_types = cleaned_input.get("reference_types")
+
+ if not reference_types:
+ return
+
+ cls._validate_reference_input_type(input_type)
+ cls._validate_reference_entity_type(entity_type)
+ cls._validate_reference_types(reference_types, entity_type)
+
+ @staticmethod
+ def _validate_reference_input_type(attribute_input_type: str):
+ if attribute_input_type not in [
+ AttributeInputType.REFERENCE,
+ AttributeInputType.SINGLE_REFERENCE,
+ ]:
+ raise ValidationError(
+ {
+ "reference_types": ValidationError(
+ "Reference types can only be specified for `REFERENCE` "
+ "and `SINGLE_REFERENCE` attributes.",
+ code=AttributeErrorCode.INVALID.value,
+ )
+ }
+ )
+
+ @staticmethod
+ def _validate_reference_entity_type(entity_type: str):
+ if entity_type not in [
+ AttributeEntityType.PRODUCT,
+ AttributeEntityType.PRODUCT_VARIANT,
+ AttributeEntityType.PAGE,
+ ]:
+ raise ValidationError(
+ {
+ "reference_types": ValidationError(
+ "Reference types can only be specified for attributes with "
+ f"{AttributeEntityType.PRODUCT}, "
+ f"{AttributeEntityType.PRODUCT_VARIANT}, or "
+ f"{AttributeEntityType.PAGE} entity types.",
+ code=AttributeErrorCode.INVALID.value,
+ )
+ }
+ )
+
+ @staticmethod
+ def _validate_reference_types(reference_types: T_REFERENCE_TYPES, entity_type: str):
+ error_msg = None
+ if entity_type in [
+ AttributeEntityType.PRODUCT,
+ AttributeEntityType.PRODUCT_VARIANT,
+ ]:
+ if not all(
+ isinstance(ref_type, product_models.ProductType)
+ for ref_type in reference_types
+ ):
+ error_msg = "Expecting a list of ProductType IDs."
+
+ elif not all(
+ isinstance(ref_type, page_models.PageType) for ref_type in reference_types
+ ):
+ error_msg = "Expecting a list of PageType IDs."
+
+ if error_msg:
+ raise ValidationError(
+ {
+ "reference_types": ValidationError(
+ error_msg,
+ code=AttributeErrorCode.INVALID.value,
+ )
+ }
+ )
+
@classmethod
def _save_m2m(cls, info: ResolveInfo, attribute, cleaned_data):
super()._save_m2m(info, attribute, cleaned_data) # type: ignore[misc] # mixin
+
+ if "reference_types" in cleaned_data:
+ if attribute.entity_type == AttributeEntityType.PAGE:
+ attribute.reference_page_types.set(cleaned_data["reference_types"])
+ else:
+ attribute.reference_product_types.set(cleaned_data["reference_types"])
+
values = cleaned_data.get(cls.ATTRIBUTE_VALUES_FIELD) or []
for value in values:
attribute.values.create(**value)
diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_bulk_create.py b/saleor/graphql/attribute/tests/mutations/test_attribute_bulk_create.py
index 41e43e8ca4..1dc09a8932 100644
--- a/saleor/graphql/attribute/tests/mutations/test_attribute_bulk_create.py
+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_bulk_create.py
@@ -1,10 +1,12 @@
from unittest.mock import patch
+import graphene
+
from .....attribute.error_codes import AttributeBulkCreateErrorCode
from .....attribute.models import Attribute, AttributeValue
from ....core.enums import ErrorPolicyEnum
from ....tests.utils import get_graphql_content
-from ...enums import AttributeInputTypeEnum, AttributeTypeEnum
+from ...enums import AttributeEntityTypeEnum, AttributeInputTypeEnum, AttributeTypeEnum
ATTRIBUTE_BULK_CREATE_MUTATION = """
mutation AttributeBulkCreate(
@@ -22,6 +24,17 @@ ATTRIBUTE_BULK_CREATE_MUTATION = """
id
name
slug
+ entityType
+ referenceTypes {
+ ... on ProductType {
+ id
+ slug
+ }
+ ... on PageType {
+ id
+ slug
+ }
+ }
choices(first: 10) {
edges {
node {
@@ -646,3 +659,153 @@ def test_attribute_bulk_create_dropdown_with_invalid_row_and_reject_failed_rows(
choices = data["results"][0]["attribute"]["choices"]["edges"]
assert choices[0]["node"]["name"] == value_1
assert choices[0]["node"]["value"] == ""
+
+
+def test_attribute_bulk_create_with_reference_types(
+ staff_api_client,
+ permission_manage_product_types_and_attributes,
+ product_type,
+ page_type,
+):
+ # given
+ attribute_1_name = "Example name 1"
+ attribute_2_name = "Example name 2"
+ ref_product_type_id = graphene.Node.to_global_id("ProductType", product_type.id)
+ ref_page_type_id = graphene.Node.to_global_id("PageType", page_type.id)
+ entity_type_1 = AttributeEntityTypeEnum.PRODUCT.name
+ entity_type_2 = AttributeEntityTypeEnum.PAGE.name
+
+ attributes = [
+ {
+ "name": attribute_1_name,
+ "type": AttributeTypeEnum.PRODUCT_TYPE.name,
+ "inputType": AttributeInputTypeEnum.REFERENCE.name,
+ "entityType": entity_type_1,
+ "referenceTypes": [ref_product_type_id],
+ },
+ {
+ "name": attribute_2_name,
+ "type": AttributeTypeEnum.PRODUCT_TYPE.name,
+ "inputType": AttributeInputTypeEnum.SINGLE_REFERENCE.name,
+ "entityType": entity_type_2,
+ "referenceTypes": [ref_page_type_id],
+ },
+ ]
+
+ # when
+ staff_api_client.user.user_permissions.add(
+ permission_manage_product_types_and_attributes
+ )
+ response = staff_api_client.post_graphql(
+ ATTRIBUTE_BULK_CREATE_MUTATION,
+ {"attributes": attributes},
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["attributeBulkCreate"]
+
+ # then
+ attributes = Attribute.objects.all()
+
+ assert not data["results"][0]["errors"]
+ assert not data["results"][1]["errors"]
+ assert data["count"] == 2
+ assert data["results"][0]["attribute"]["name"] == attribute_1_name
+ assert data["results"][1]["attribute"]["name"] == attribute_2_name
+ assert data["results"][0]["attribute"]["entityType"] == entity_type_1
+ assert data["results"][1]["attribute"]["entityType"] == entity_type_2
+ assert len(data["results"][0]["attribute"]["referenceTypes"]) == 1
+ assert len(data["results"][1]["attribute"]["referenceTypes"]) == 1
+
+ assert (
+ data["results"][0]["attribute"]["referenceTypes"][0]["id"]
+ == ref_product_type_id
+ )
+ assert (
+ data["results"][1]["attribute"]["referenceTypes"][0]["id"] == ref_page_type_id
+ )
+
+
+@patch("saleor.graphql.attribute.mutations.mixins.REFERENCE_TYPES_LIMIT", 1)
+def test_attribute_bulk_create_with_invalid_reference_types(
+ staff_api_client,
+ permission_manage_product_types_and_attributes,
+ product_type,
+ page_type,
+ page_type_list,
+):
+ # given
+ attribute_1_name = "Example name 1"
+ attribute_2_name = "Example name 2"
+ ref_product_type_id = graphene.Node.to_global_id("ProductType", product_type.id)
+ ref_page_type_id = graphene.Node.to_global_id("PageType", page_type.id)
+
+ attributes = [
+ {
+ "name": attribute_1_name,
+ "type": AttributeTypeEnum.PRODUCT_TYPE.name,
+ "inputType": AttributeInputTypeEnum.REFERENCE.name,
+ "entityType": AttributeEntityTypeEnum.PRODUCT.name,
+ # should be a list of product types
+ "referenceTypes": [ref_page_type_id],
+ },
+ {
+ "name": attribute_2_name,
+ "type": AttributeTypeEnum.PRODUCT_TYPE.name,
+ "inputType": AttributeInputTypeEnum.SINGLE_REFERENCE.name,
+ "entityType": AttributeEntityTypeEnum.PAGE.name,
+ # should be a list of page types
+ "referenceTypes": [ref_product_type_id],
+ },
+ {
+ "name": attribute_2_name,
+ "type": AttributeTypeEnum.PRODUCT_TYPE.name,
+ "inputType": AttributeInputTypeEnum.SINGLE_REFERENCE.name,
+ "entityType": AttributeEntityTypeEnum.PAGE.name,
+ # limit exceeded
+ "referenceTypes": [
+ graphene.Node.to_global_id("PageType", p_type.id)
+ for p_type in page_type_list
+ ],
+ },
+ {
+ "name": attribute_2_name,
+ "type": AttributeTypeEnum.PRODUCT_TYPE.name,
+ "inputType": AttributeInputTypeEnum.SINGLE_REFERENCE.name,
+ # invalid entity type
+ "entityType": AttributeEntityTypeEnum.COLLECTION.name,
+ "referenceTypes": [ref_product_type_id],
+ },
+ {
+ "name": attribute_2_name,
+ "type": AttributeTypeEnum.PRODUCT_TYPE.name,
+ # invalid input type
+ "inputType": AttributeInputTypeEnum.DROPDOWN.name,
+ "referenceTypes": [ref_product_type_id],
+ },
+ ]
+
+ # when
+ staff_api_client.user.user_permissions.add(
+ permission_manage_product_types_and_attributes
+ )
+ response = staff_api_client.post_graphql(
+ ATTRIBUTE_BULK_CREATE_MUTATION,
+ {"attributes": attributes},
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["attributeBulkCreate"]
+
+ # then
+ attributes = Attribute.objects.all()
+
+ assert data["count"] == 0
+ assert data["results"][0]["errors"]
+ assert data["results"][1]["errors"]
+ assert data["results"][2]["errors"]
+ assert data["results"][3]["errors"]
+ assert data["results"][4]["errors"]
+
+ for result in data["results"]:
+ assert len(result["errors"]) == 1
+ assert result["errors"][0]["code"] == AttributeBulkCreateErrorCode.INVALID.name
+ assert result["errors"][0]["path"] == "referenceTypes"
diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_bulk_update.py b/saleor/graphql/attribute/tests/mutations/test_attribute_bulk_update.py
index a1c8fedd51..a33be9ba81 100644
--- a/saleor/graphql/attribute/tests/mutations/test_attribute_bulk_update.py
+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_bulk_update.py
@@ -23,6 +23,17 @@ ATTRIBUTE_BULK_UPDATE_MUTATION = """
id
name
slug
+ entityType
+ referenceTypes {
+ ... on ProductType {
+ id
+ slug
+ }
+ ... on PageType {
+ id
+ slug
+ }
+ }
choices(first: 10) {
edges {
node {
@@ -880,3 +891,193 @@ def test_attribute_bulk_update_add_value_missing_name(
assert errors[0]["code"] == AttributeBulkUpdateErrorCode.REQUIRED.name
assert errors[1]["path"] == "addValues.1.name"
assert errors[1]["code"] == AttributeBulkUpdateErrorCode.REQUIRED.name
+
+
+def test_attribute_bulk_update_reference_types(
+ staff_api_client,
+ permission_manage_product_types_and_attributes,
+ permission_manage_page_types_and_attributes,
+ product_type_product_single_reference_attribute,
+ product_type_variant_single_reference_attribute,
+ product_type_page_reference_attribute,
+ page_type_page_reference_attribute,
+ page_type_list,
+ product_type,
+):
+ # given
+ product_type_variant_single_reference_attribute.reference_product_types.add(
+ product_type
+ )
+ product_type_page_reference_attribute.reference_page_types.add(page_type_list[0])
+ page_type_page_reference_attribute.reference_page_types.add(page_type_list[1])
+
+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.id)
+ page_type_ids = [
+ graphene.Node.to_global_id("PageType", page_type.id)
+ for page_type in page_type_list
+ ]
+ attributes = [
+ # set reference types
+ {
+ "id": graphene.Node.to_global_id(
+ "Attribute", product_type_product_single_reference_attribute.id
+ ),
+ "fields": {"referenceTypes": [product_type_id]},
+ },
+ # clear product reference types
+ {
+ "id": graphene.Node.to_global_id(
+ "Attribute", product_type_variant_single_reference_attribute.id
+ ),
+ "fields": {"referenceTypes": []},
+ },
+ # change reference types
+ {
+ "id": graphene.Node.to_global_id(
+ "Attribute", product_type_page_reference_attribute.id
+ ),
+ "fields": {"referenceTypes": page_type_ids[1:]},
+ },
+ # clear page reference types
+ {
+ "id": graphene.Node.to_global_id(
+ "Attribute", page_type_page_reference_attribute.id
+ ),
+ "fields": {"referenceTypes": []},
+ },
+ ]
+
+ # when
+ staff_api_client.user.user_permissions.add(
+ permission_manage_product_types_and_attributes,
+ permission_manage_page_types_and_attributes,
+ )
+ response = staff_api_client.post_graphql(
+ ATTRIBUTE_BULK_UPDATE_MUTATION,
+ {"attributes": attributes},
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["attributeBulkUpdate"]
+
+ # then
+ assert len(attributes) == 4
+ assert not data["results"][0]["errors"]
+ assert not data["results"][1]["errors"]
+ assert not data["results"][2]["errors"]
+ assert not data["results"][3]["errors"]
+ assert data["count"] == 4
+ assert len(data["results"][0]["attribute"]["referenceTypes"]) == 1
+ assert len(data["results"][1]["attribute"]["referenceTypes"]) == 0
+ assert (
+ len(data["results"][2]["attribute"]["referenceTypes"])
+ == len(page_type_list) - 1
+ )
+ assert len(data["results"][3]["attribute"]["referenceTypes"]) == 0
+
+ assert data["results"][0]["attribute"]["referenceTypes"][0]["id"] == product_type_id
+ assert {
+ ref_type["id"] for ref_type in data["results"][2]["attribute"]["referenceTypes"]
+ } == set(page_type_ids[1:])
+
+ product_type_product_single_reference_attribute.refresh_from_db()
+ assert (
+ product_type_product_single_reference_attribute.reference_product_types.count()
+ == 1
+ )
+ product_type_variant_single_reference_attribute.refresh_from_db()
+ assert (
+ product_type_variant_single_reference_attribute.reference_product_types.count()
+ == 0
+ )
+ product_type_page_reference_attribute.refresh_from_db()
+ assert product_type_page_reference_attribute.reference_page_types.count() == len(
+ page_type_ids[1:]
+ )
+ page_type_page_reference_attribute.refresh_from_db()
+ assert page_type_page_reference_attribute.reference_page_types.count() == 0
+
+
+@patch("saleor.graphql.attribute.mutations.mixins.REFERENCE_TYPES_LIMIT", 1)
+def test_attribute_bulk_update_invalid_reference_types(
+ staff_api_client,
+ permission_manage_product_types_and_attributes,
+ permission_manage_page_types_and_attributes,
+ product_type_variant_single_reference_attribute,
+ product_type_collection_single_reference_attribute,
+ product_type_page_reference_attribute,
+ color_attribute,
+ page_type_page_reference_attribute,
+ page_type_list,
+ product_type,
+):
+ # given
+ product_type_variant_single_reference_attribute.reference_product_types.add(
+ product_type
+ )
+ product_type_page_reference_attribute.reference_page_types.add(page_type_list[0])
+ page_type_page_reference_attribute.reference_page_types.add(page_type_list[1])
+
+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.id)
+ page_type_ids = [
+ graphene.Node.to_global_id("PageType", page_type.id)
+ for page_type in page_type_list
+ ]
+ input_attributes = [
+ {
+ "id": graphene.Node.to_global_id("Attribute", color_attribute.id),
+ # invalid input type
+ "fields": {"referenceTypes": [product_type_id]},
+ },
+ {
+ "id": graphene.Node.to_global_id(
+ "Attribute", product_type_collection_single_reference_attribute.id
+ ),
+ # invalid entity type of attribute
+ "fields": {"referenceTypes": [product_type_id]},
+ },
+ {
+ "id": graphene.Node.to_global_id(
+ "Attribute", product_type_variant_single_reference_attribute.id
+ ),
+ # should be a list of product types
+ "fields": {"referenceTypes": [page_type_ids[1]]},
+ },
+ {
+ "id": graphene.Node.to_global_id(
+ "Attribute", product_type_page_reference_attribute.id
+ ),
+ # # limit exceeded
+ "fields": {"referenceTypes": page_type_ids[1:]},
+ },
+ {
+ "id": graphene.Node.to_global_id(
+ "Attribute", page_type_page_reference_attribute.id
+ ),
+ # should be a list of page types
+ "fields": {"referenceTypes": [product_type_id]},
+ },
+ ]
+
+ # when
+ staff_api_client.user.user_permissions.add(
+ permission_manage_product_types_and_attributes,
+ permission_manage_page_types_and_attributes,
+ )
+ response = staff_api_client.post_graphql(
+ ATTRIBUTE_BULK_UPDATE_MUTATION,
+ {"attributes": input_attributes},
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["attributeBulkUpdate"]
+
+ # then
+ assert data["results"][0]["errors"]
+ assert data["results"][1]["errors"]
+ assert data["results"][2]["errors"]
+ assert data["results"][3]["errors"]
+ assert data["results"][4]["errors"]
+ assert data["count"] == 0
+ for result in data["results"]:
+ assert len(result["errors"]) == 1
+ assert result["errors"][0]["code"] == AttributeBulkUpdateErrorCode.INVALID.name
+ assert result["errors"][0]["path"] == "referenceTypes"
diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_create.py b/saleor/graphql/attribute/tests/mutations/test_attribute_create.py
index 0a057dfcc0..212791733e 100644
--- a/saleor/graphql/attribute/tests/mutations/test_attribute_create.py
+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_create.py
@@ -33,6 +33,16 @@ CREATE_ATTRIBUTE_MUTATION = """
unit
inputType
entityType
+ referenceTypes {
+ ... on ProductType {
+ id
+ slug
+ }
+ ... on PageType {
+ id
+ slug
+ }
+ }
filterableInStorefront
filterableInDashboard
availableInGrid
@@ -1444,3 +1454,413 @@ def test_create_attribute_similar_names(
assert len(values_edges) == 2
slugs = [node["node"]["slug"] for node in values_edges]
assert set(slugs) == {"15", "15-2"}
+
+
+ "input_type",
+ [
+ AttributeInputTypeEnum.SINGLE_REFERENCE.name,
+ AttributeInputTypeEnum.REFERENCE.name,
+ ],
+)
+def test_create_product_reference_attribute_with_reference_types(
+ input_type,
+ staff_api_client,
+ permission_manage_product_types_and_attributes,
+ permission_manage_products,
+ product_type,
+):
+ # given
+ query = CREATE_ATTRIBUTE_MUTATION
+
+ attribute_name = "Reference attribute"
+ product_reference_type_id = graphene.Node.to_global_id(
+ "ProductType", product_type.id
+ )
+ type = AttributeTypeEnum.PRODUCT_TYPE.name
+ entity_type = AttributeEntityTypeEnum.PRODUCT.name
+ variables = {
+ "input": {
+ "name": attribute_name,
+ "type": type,
+ "inputType": input_type,
+ "entityType": entity_type,
+ "referenceTypes": [product_reference_type_id],
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query,
+ variables,
+ permissions=[
+ permission_manage_product_types_and_attributes,
+ permission_manage_products,
+ ],
+ )
+
+ # then
+ 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)
+ assert data["attribute"]["productTypes"]["edges"] == []
+ assert data["attribute"]["type"] == type
+ assert data["attribute"]["inputType"] == input_type
+ assert data["attribute"]["entityType"] == entity_type
+ assert len(data["attribute"]["referenceTypes"]) == 1
+ assert data["attribute"]["referenceTypes"][0]["id"] == product_reference_type_id
+ assert data["attribute"]["referenceTypes"][0]["slug"] == product_type.slug
+
+
+ "input_type",
+ [
+ AttributeInputTypeEnum.SINGLE_REFERENCE.name,
+ AttributeInputTypeEnum.REFERENCE.name,
+ ],
+)
+def test_create_variant_reference_attribute_with_reference_types(
+ input_type,
+ staff_api_client,
+ permission_manage_page_types_and_attributes,
+ permission_manage_products,
+ product_type,
+ product_type_with_product_attributes,
+):
+ # given
+ query = CREATE_ATTRIBUTE_MUTATION
+
+ attribute_name = "Reference attribute"
+ type = AttributeTypeEnum.PAGE_TYPE.name
+ entity_type = AttributeEntityTypeEnum.PRODUCT_VARIANT.name
+ product_type_ids = [
+ graphene.Node.to_global_id("ProductType", ref_type.id)
+ for ref_type in [product_type_with_product_attributes, product_type]
+ ]
+ variables = {
+ "input": {
+ "name": attribute_name,
+ "type": type,
+ "inputType": input_type,
+ "entityType": entity_type,
+ "referenceTypes": product_type_ids,
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query,
+ variables,
+ permissions=[
+ permission_manage_page_types_and_attributes,
+ permission_manage_products,
+ ],
+ )
+
+ # then
+ 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)
+ assert data["attribute"]["productTypes"]["edges"] == []
+ assert data["attribute"]["type"] == type
+ assert data["attribute"]["inputType"] == input_type
+ assert data["attribute"]["entityType"] == entity_type
+ assert len(data["attribute"]["referenceTypes"]) == len(product_type_ids)
+ assert {ref_type["id"] for ref_type in data["attribute"]["referenceTypes"]} == set(
+ product_type_ids
+ )
+
+
+ "input_type",
+ [
+ AttributeInputTypeEnum.SINGLE_REFERENCE.name,
+ AttributeInputTypeEnum.REFERENCE.name,
+ ],
+)
+def test_create_page_reference_attribute_with_reference_types(
+ input_type,
+ staff_api_client,
+ permission_manage_product_types_and_attributes,
+ permission_manage_products,
+ page_type_list,
+):
+ # given
+ query = CREATE_ATTRIBUTE_MUTATION
+
+ attribute_name = "Reference attribute"
+ type = AttributeTypeEnum.PRODUCT_TYPE.name
+ entity_type = AttributeEntityTypeEnum.PAGE.name
+ page_type_ids = [
+ graphene.Node.to_global_id("PageType", ref_type.id)
+ for ref_type in page_type_list
+ ]
+ variables = {
+ "input": {
+ "name": attribute_name,
+ "type": type,
+ "inputType": input_type,
+ "entityType": entity_type,
+ "referenceTypes": page_type_ids,
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query,
+ variables,
+ permissions=[
+ permission_manage_product_types_and_attributes,
+ permission_manage_products,
+ ],
+ )
+
+ # then
+ 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)
+ assert data["attribute"]["productTypes"]["edges"] == []
+ assert data["attribute"]["type"] == type
+ assert data["attribute"]["inputType"] == input_type
+ assert data["attribute"]["entityType"] == entity_type
+ assert len(data["attribute"]["referenceTypes"]) == len(page_type_ids)
+ assert {ref_type["id"] for ref_type in data["attribute"]["referenceTypes"]} == set(
+ page_type_ids
+ )
+
+
+ "entity_type",
+ [
+ AttributeEntityTypeEnum.COLLECTION.name,
+ AttributeEntityTypeEnum.CATEGORY.name,
+ ],
+)
+def test_create_reference_attribute_with_reference_types_not_valid_entity_type(
+ entity_type,
+ staff_api_client,
+ permission_manage_product_types_and_attributes,
+ permission_manage_products,
+ product_type,
+):
+ # given
+ query = CREATE_ATTRIBUTE_MUTATION
+
+ attribute_name = "Reference attribute"
+ type = AttributeTypeEnum.PRODUCT_TYPE.name
+ input_type = AttributeInputTypeEnum.REFERENCE.name
+ product_reference_type_id = graphene.Node.to_global_id(
+ "ProductType", product_type.id
+ )
+ variables = {
+ "input": {
+ "name": attribute_name,
+ "type": type,
+ "inputType": input_type,
+ "entityType": entity_type,
+ "referenceTypes": [product_reference_type_id],
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query,
+ variables,
+ permissions=[
+ permission_manage_product_types_and_attributes,
+ permission_manage_products,
+ ],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["attributeCreate"]["attribute"]
+ errors = content["data"]["attributeCreate"]["errors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "referenceTypes"
+ assert errors[0]["code"] == AttributeErrorCode.INVALID.name
+
+
+def test_create_attribute_with_reference_types_invalid_input_type(
+ staff_api_client,
+ permission_manage_product_types_and_attributes,
+ permission_manage_products,
+ product_type,
+):
+ # given
+ query = CREATE_ATTRIBUTE_MUTATION
+
+ attribute_name = "Reference attribute"
+ input_type = AttributeInputTypeEnum.DROPDOWN.name
+ product_reference_type_id = graphene.Node.to_global_id(
+ "ProductType", product_type.id
+ )
+ variables = {
+ "input": {
+ "name": attribute_name,
+ "type": AttributeTypeEnum.PRODUCT_TYPE.name,
+ "inputType": input_type,
+ "referenceTypes": [product_reference_type_id],
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query,
+ variables,
+ permissions=[
+ permission_manage_product_types_and_attributes,
+ permission_manage_products,
+ ],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["attributeCreate"]["attribute"]
+ errors = content["data"]["attributeCreate"]["errors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "referenceTypes"
+ assert errors[0]["code"] == AttributeErrorCode.INVALID.name
+
+
[email protected]("saleor.graphql.attribute.mutations.mixins.REFERENCE_TYPES_LIMIT", 1)
+def test_create_attribute_with_reference_types_limit_exceeded(
+ staff_api_client,
+ permission_manage_product_types_and_attributes,
+ permission_manage_products,
+ product_type,
+ product_type_with_product_attributes,
+):
+ # given
+ query = CREATE_ATTRIBUTE_MUTATION
+
+ attribute_name = "Single variant reference attribute"
+ input_type = AttributeInputTypeEnum.REFERENCE.name
+ product_type_ids = [
+ graphene.Node.to_global_id("ProductType", ref_type.id)
+ for ref_type in [product_type_with_product_attributes, product_type]
+ ]
+ variables = {
+ "input": {
+ "name": attribute_name,
+ "type": AttributeTypeEnum.PRODUCT_TYPE.name,
+ "entityType": AttributeEntityTypeEnum.PRODUCT_VARIANT.name,
+ "inputType": input_type,
+ "referenceTypes": product_type_ids,
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query,
+ variables,
+ permissions=[
+ permission_manage_product_types_and_attributes,
+ permission_manage_products,
+ ],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["attributeCreate"]["attribute"]
+ errors = content["data"]["attributeCreate"]["errors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "referenceTypes"
+ assert errors[0]["code"] == AttributeErrorCode.INVALID.name
+
+
+def test_create_attribute_with_reference_types_page_types_provided_for_variant_ref(
+ staff_api_client,
+ permission_manage_product_types_and_attributes,
+ permission_manage_products,
+ page_type_list,
+):
+ # given
+ query = CREATE_ATTRIBUTE_MUTATION
+
+ attribute_name = "Single variant reference attribute"
+ input_type = AttributeInputTypeEnum.REFERENCE.name
+ page_type_ids = [
+ graphene.Node.to_global_id("PageType", ref_type.id)
+ for ref_type in page_type_list
+ ]
+ variables = {
+ "input": {
+ "name": attribute_name,
+ "type": AttributeTypeEnum.PRODUCT_TYPE.name,
+ "entityType": AttributeEntityTypeEnum.PRODUCT_VARIANT.name,
+ "inputType": input_type,
+ "referenceTypes": page_type_ids,
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query,
+ variables,
+ permissions=[
+ permission_manage_product_types_and_attributes,
+ permission_manage_products,
+ ],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["attributeCreate"]["attribute"]
+ errors = content["data"]["attributeCreate"]["errors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "referenceTypes"
+ assert errors[0]["code"] == AttributeErrorCode.INVALID.name
+
+
+def test_create_attribute_with_reference_types_product_types_provided_for_page_ref(
+ staff_api_client,
+ permission_manage_product_types_and_attributes,
+ permission_manage_products,
+ product_type,
+):
+ # given
+ query = CREATE_ATTRIBUTE_MUTATION
+
+ attribute_name = "Single variant reference attribute"
+ input_type = AttributeInputTypeEnum.REFERENCE.name
+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.id)
+ variables = {
+ "input": {
+ "name": attribute_name,
+ "type": AttributeTypeEnum.PRODUCT_TYPE.name,
+ "entityType": AttributeEntityTypeEnum.PAGE.name,
+ "inputType": input_type,
+ "referenceTypes": [product_type_id],
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query,
+ variables,
+ permissions=[
+ permission_manage_product_types_and_attributes,
+ permission_manage_products,
+ ],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ assert not content["data"]["attributeCreate"]["attribute"]
+ errors = content["data"]["attributeCreate"]["errors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "referenceTypes"
+ assert errors[0]["code"] == AttributeErrorCode.INVALID.name
diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_update.py b/saleor/graphql/attribute/tests/mutations/test_attribute_update.py
index 653528be1e..3c32f7388a 100644
--- a/saleor/graphql/attribute/tests/mutations/test_attribute_update.py
+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_update.py
@@ -6,6 +6,7 @@ import pytest
from django.utils.functional import SimpleLazyObject
from freezegun import freeze_time
+from .....attribute import AttributeEntityType, AttributeInputType
from .....attribute.error_codes import AttributeErrorCode
from .....attribute.models import Attribute, AttributeValue
from .....core.utils.json_serializer import CustomJsonEncoder
@@ -30,6 +31,17 @@ UPDATE_ATTRIBUTE_MUTATION = """
name
slug
unit
+ entityType
+ referenceTypes {
+ ... on ProductType {
+ id
+ slug
+ }
+ ... on PageType {
+ id
+ slug
+ }
+ }
externalReference
choices(first: 10) {
edges {
@@ -851,3 +863,282 @@ def test_update_attribute_name_similar_value(
assert len(values_edges) == 2
slugs = [node["node"]["slug"] for node in values_edges]
assert set(slugs) == {"15", "15-2"}
+
+
+ "input_type",
+ [
+ AttributeInputType.SINGLE_REFERENCE,
+ AttributeInputType.REFERENCE,
+ ],
+)
+def test_update_attribute_reference_types(
+ input_type,
+ staff_api_client,
+ product_type_product_single_reference_attribute,
+ permission_manage_product_types_and_attributes,
+ product_type,
+ product_type_with_product_attributes,
+):
+ # given
+ query = UPDATE_ATTRIBUTE_MUTATION
+ attribute = product_type_product_single_reference_attribute
+ attribute.input_type = input_type
+ attribute.reference_product_types.add(product_type_with_product_attributes)
+ attribute.save()
+
+ new_ref_product_type_id = graphene.Node.to_global_id("ProductType", product_type.id)
+ node_id = graphene.Node.to_global_id("Attribute", attribute.id)
+ variables = {
+ "input": {"referenceTypes": [new_ref_product_type_id]},
+ "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"]
+ assert not data["errors"]
+ assert data["attribute"]
+ assert len(data["attribute"]["referenceTypes"]) == 1
+ assert data["attribute"]["referenceTypes"][0]["id"] == new_ref_product_type_id
+
+
+def test_update_attribute_clear_reference_types(
+ staff_api_client,
+ product_type_product_single_reference_attribute,
+ permission_manage_product_types_and_attributes,
+ product_type,
+):
+ # given
+ query = UPDATE_ATTRIBUTE_MUTATION
+ attribute = product_type_product_single_reference_attribute
+ attribute.reference_product_types.add(product_type)
+ attribute.save()
+
+ assert attribute.reference_product_types.count() == 1
+
+ node_id = graphene.Node.to_global_id("Attribute", attribute.id)
+ variables = {
+ "input": {"referenceTypes": []},
+ "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"]
+ assert not data["errors"]
+ assert data["attribute"]
+ assert len(data["attribute"]["referenceTypes"]) == 0
+
+
+ "entity_type",
+ [
+ AttributeEntityType.COLLECTION,
+ AttributeEntityType.CATEGORY,
+ ],
+)
+def test_update_reference_attribute_with_reference_types_not_valid_entity_type(
+ entity_type,
+ staff_api_client,
+ permission_manage_product_types_and_attributes,
+ product_type_product_single_reference_attribute,
+ product_type,
+):
+ # given
+ query = UPDATE_ATTRIBUTE_MUTATION
+
+ attribute = product_type_product_single_reference_attribute
+ attribute.entity_type = entity_type
+ attribute.save()
+
+ product_reference_type_id = graphene.Node.to_global_id(
+ "ProductType", product_type.id
+ )
+ node_id = graphene.Node.to_global_id("Attribute", attribute.id)
+ variables = {
+ "id": node_id,
+ "input": {
+ "referenceTypes": [product_reference_type_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"]["errors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "referenceTypes"
+ assert errors[0]["code"] == AttributeErrorCode.INVALID.name
+
+
+def test_update_attribute_with_reference_types_invalid_input_type(
+ staff_api_client,
+ permission_manage_product_types_and_attributes,
+ product_type_product_single_reference_attribute,
+ product_type,
+):
+ # given
+ query = UPDATE_ATTRIBUTE_MUTATION
+
+ attribute = product_type_product_single_reference_attribute
+ attribute.input_type = AttributeInputType.DROPDOWN
+ attribute.save()
+
+ product_reference_type_id = graphene.Node.to_global_id(
+ "ProductType", product_type.id
+ )
+ node_id = graphene.Node.to_global_id("Attribute", attribute.id)
+ variables = {
+ "id": node_id,
+ "input": {
+ "referenceTypes": [product_reference_type_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"]["errors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "referenceTypes"
+ assert errors[0]["code"] == AttributeErrorCode.INVALID.name
+
+
[email protected]("saleor.graphql.attribute.mutations.mixins.REFERENCE_TYPES_LIMIT", 1)
+def test_update_attribute_with_reference_types_limit_exceeded(
+ staff_api_client,
+ permission_manage_product_types_and_attributes,
+ product_type_product_single_reference_attribute,
+ product_type,
+ product_type_with_product_attributes,
+):
+ # given
+ query = UPDATE_ATTRIBUTE_MUTATION
+
+ attribute = product_type_product_single_reference_attribute
+ attribute.input_type = AttributeInputType.REFERENCE
+ attribute.save()
+
+ product_type_ids = [
+ graphene.Node.to_global_id("ProductType", ref_type.id)
+ for ref_type in [product_type_with_product_attributes, product_type]
+ ]
+ node_id = graphene.Node.to_global_id("Attribute", attribute.id)
+ variables = {
+ "id": node_id,
+ "input": {
+ "referenceTypes": product_type_ids,
+ },
+ }
+
+ # 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"]["errors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "referenceTypes"
+ assert errors[0]["code"] == AttributeErrorCode.INVALID.name
+
+
+def test_update_attribute_with_reference_types_page_types_provided_for_variant_ref(
+ staff_api_client,
+ permission_manage_product_types_and_attributes,
+ product_type_product_single_reference_attribute,
+ page_type_list,
+):
+ # given
+ query = UPDATE_ATTRIBUTE_MUTATION
+
+ attribute = product_type_product_single_reference_attribute
+
+ page_type_ids = [
+ graphene.Node.to_global_id("PageType", ref_type.id)
+ for ref_type in page_type_list
+ ]
+ node_id = graphene.Node.to_global_id("Attribute", attribute.id)
+ variables = {
+ "id": node_id,
+ "input": {
+ "referenceTypes": page_type_ids,
+ },
+ }
+
+ # 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"]["errors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "referenceTypes"
+ assert errors[0]["code"] == AttributeErrorCode.INVALID.name
+
+
+def test_update_attribute_with_reference_types_product_types_provided_for_page_ref(
+ staff_api_client,
+ permission_manage_product_types_and_attributes,
+ product_type_page_single_reference_attribute,
+ product_type,
+):
+ # given
+ query = UPDATE_ATTRIBUTE_MUTATION
+
+ attribute = product_type_page_single_reference_attribute
+
+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.id)
+ node_id = graphene.Node.to_global_id("Attribute", attribute.id)
+ variables = {
+ "id": node_id,
+ "input": {
+ "referenceTypes": [product_type_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"]["errors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "referenceTypes"
+ assert errors[0]["code"] == AttributeErrorCode.INVALID.name
diff --git a/saleor/graphql/attribute/tests/queries/test_attribute_query.py b/saleor/graphql/attribute/tests/queries/test_attribute_query.py
index a4ae695c10..839d6655c7 100644
--- a/saleor/graphql/attribute/tests/queries/test_attribute_query.py
+++ b/saleor/graphql/attribute/tests/queries/test_attribute_query.py
@@ -71,6 +71,17 @@ query ($id: ID!, $query: String) {
name
inputType
entityType
+ referenceTypes {
+ __typename
+ ... on ProductType {
+ id
+ slug
+ }
+ ... on PageType {
+ id
+ slug
+ }
+ }
type
unit
choices(first: 10, filter: {search: $query}) {
@@ -450,6 +461,427 @@ def test_get_single_swatch_attribute_by_staff(
assert data in content["data"]["attribute"]["choices"]["edges"]
+def test_get_single_reference_product_attribute_with_reference_types(
+ staff_api_client,
+ product_type_product_single_reference_attribute,
+ product_type,
+ product_type_with_product_attributes,
+ product_type_with_variant_attributes,
+ permission_manage_products,
+):
+ # given
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ attribute = product_type_product_single_reference_attribute
+ reference_product_types = [product_type, product_type_with_product_attributes]
+ attribute.reference_product_types.add(*reference_product_types)
+
+ query = QUERY_ATTRIBUTE
+ attribute_id = graphene.Node.to_global_id("Attribute", attribute.id)
+ variables = {"id": attribute_id}
+
+ # when
+ content = get_graphql_content(staff_api_client.post_graphql(query, variables))
+
+ # then
+ attribute_data = content["data"]["attribute"]
+
+ assert attribute_data["id"] == attribute_id
+ assert attribute_data["slug"] == attribute.slug
+
+ reference_types = attribute_data["referenceTypes"]
+ assert len(reference_types) == len(reference_product_types)
+ assert {type["slug"] for type in reference_types} == {
+ product_type.slug for product_type in reference_product_types
+ }
+
+
+def test_get_single_reference_variant_attribute_with_reference_types(
+ staff_api_client,
+ product_type_variant_single_reference_attribute,
+ product_type,
+ product_type_with_product_attributes,
+ product_type_with_variant_attributes,
+ permission_manage_products,
+):
+ # given
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ attribute = product_type_variant_single_reference_attribute
+ reference_product_types = [product_type, product_type_with_product_attributes]
+ attribute.reference_product_types.add(*reference_product_types)
+
+ query = QUERY_ATTRIBUTE
+ attribute_id = graphene.Node.to_global_id("Attribute", attribute.id)
+ variables = {"id": attribute_id}
+
+ # when
+ content = get_graphql_content(staff_api_client.post_graphql(query, variables))
+
+ # then
+ attribute_data = content["data"]["attribute"]
+
+ assert attribute_data["id"] == attribute_id
+ assert attribute_data["slug"] == attribute.slug
+
+ reference_types = attribute_data["referenceTypes"]
+ assert len(reference_types) == len(reference_product_types)
+ assert {ref_type["slug"] for ref_type in reference_types} == {
+ product_type.slug for product_type in reference_product_types
+ }
+
+
+def test_get_single_reference_page_attribute_with_reference_types(
+ staff_api_client,
+ product_type_page_single_reference_attribute,
+ page_type_list,
+ permission_manage_products,
+):
+ # given
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ attribute = product_type_page_single_reference_attribute
+ reference_page_types = page_type_list[:2]
+ attribute.reference_page_types.add(*reference_page_types)
+
+ query = QUERY_ATTRIBUTE
+ attribute_id = graphene.Node.to_global_id("Attribute", attribute.id)
+ variables = {"id": attribute_id}
+
+ # when
+ content = get_graphql_content(staff_api_client.post_graphql(query, variables))
+
+ # then
+ attribute_data = content["data"]["attribute"]
+
+ assert attribute_data["id"] == attribute_id
+ assert attribute_data["slug"] == attribute.slug
+
+ reference_types = attribute_data["referenceTypes"]
+ assert len(reference_types) == len(reference_page_types)
+ assert {type["slug"] for type in reference_types} == {
+ product_type.slug for product_type in reference_page_types
+ }
+
+
+def test_get_reference_product_attribute_with_reference_types(
+ staff_api_client,
+ product_type_product_reference_attribute,
+ product_type,
+ product_type_with_product_attributes,
+ product_type_with_variant_attributes,
+ permission_manage_products,
+):
+ # given
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ attribute = product_type_product_reference_attribute
+ reference_product_types = [product_type, product_type_with_product_attributes]
+ attribute.reference_product_types.add(*reference_product_types)
+
+ query = QUERY_ATTRIBUTE
+ attribute_id = graphene.Node.to_global_id("Attribute", attribute.id)
+ variables = {"id": attribute_id}
+
+ # when
+ content = get_graphql_content(staff_api_client.post_graphql(query, variables))
+
+ # then
+ attribute_data = content["data"]["attribute"]
+
+ assert attribute_data["id"] == attribute_id
+ assert attribute_data["slug"] == attribute.slug
+
+ reference_types = attribute_data["referenceTypes"]
+ assert len(reference_types) == len(reference_product_types)
+ assert {type["slug"] for type in reference_types} == {
+ product_type.slug for product_type in reference_product_types
+ }
+
+
+def test_get_reference_variant_attribute_with_reference_types(
+ staff_api_client,
+ product_type_variant_reference_attribute,
+ product_type,
+ product_type_with_product_attributes,
+ product_type_with_variant_attributes,
+ permission_manage_products,
+):
+ # given
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ attribute = product_type_variant_reference_attribute
+ reference_product_types = [product_type, product_type_with_product_attributes]
+ attribute.reference_product_types.add(*reference_product_types)
+
+ query = QUERY_ATTRIBUTE
+ attribute_id = graphene.Node.to_global_id("Attribute", attribute.id)
+ variables = {"id": attribute_id}
+
+ # when
+ content = get_graphql_content(staff_api_client.post_graphql(query, variables))
+
+ # then
+ attribute_data = content["data"]["attribute"]
+
+ assert attribute_data["id"] == attribute_id
+ assert attribute_data["slug"] == attribute.slug
+
+ reference_types = attribute_data["referenceTypes"]
+ assert len(reference_types) == len(reference_product_types)
+ assert {type["slug"] for type in reference_types} == {
+ product_type.slug for product_type in reference_product_types
+ }
+
+
+def test_get_reference_page_attribute_with_reference_types(
+ staff_api_client,
+ product_type_page_reference_attribute,
+ page_type_list,
+ permission_manage_products,
+):
+ # given
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ attribute = product_type_page_reference_attribute
+ reference_page_types = page_type_list[:2]
+ attribute.reference_page_types.add(*reference_page_types)
+
+ query = QUERY_ATTRIBUTE
+ attribute_id = graphene.Node.to_global_id("Attribute", attribute.id)
+ variables = {"id": attribute_id}
+
+ # when
+ content = get_graphql_content(staff_api_client.post_graphql(query, variables))
+
+ # then
+ attribute_data = content["data"]["attribute"]
+
+ assert attribute_data["id"] == attribute_id
+ assert attribute_data["slug"] == attribute.slug
+
+ reference_types = attribute_data["referenceTypes"]
+ assert len(reference_types) == len(reference_page_types)
+ assert {type["slug"] for type in reference_types} == {
+ product_type.slug for product_type in reference_page_types
+ }
+
+
+def test_get_reference_collection_attribute(
+ staff_api_client,
+ product_type_collection_reference_attribute,
+ product_type,
+ product_type_with_product_attributes,
+ permission_manage_products,
+):
+ # given
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ attribute = product_type_collection_reference_attribute
+ reference_product_types = [product_type, product_type_with_product_attributes]
+ attribute.reference_product_types.add(*reference_product_types)
+
+ query = QUERY_ATTRIBUTE
+ attribute_id = graphene.Node.to_global_id("Attribute", attribute.id)
+ variables = {"id": attribute_id}
+
+ # when
+ content = get_graphql_content(staff_api_client.post_graphql(query, variables))
+
+ # then
+ attribute_data = content["data"]["attribute"]
+ assert attribute_data["id"] == attribute_id
+ assert attribute_data["slug"] == attribute.slug
+
+ assert not attribute_data["referenceTypes"]
+
+
+def test_get_reference_category_attribute(
+ staff_api_client,
+ product_type_category_reference_attribute,
+ product_type,
+ product_type_with_product_attributes,
+ permission_manage_products,
+):
+ # given
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ attribute = product_type_category_reference_attribute
+ reference_product_types = [product_type, product_type_with_product_attributes]
+ attribute.reference_product_types.add(*reference_product_types)
+
+ query = QUERY_ATTRIBUTE
+ attribute_id = graphene.Node.to_global_id("Attribute", attribute.id)
+ variables = {"id": attribute_id}
+
+ # when
+ content = get_graphql_content(staff_api_client.post_graphql(query, variables))
+
+ # then
+ attribute_data = content["data"]["attribute"]
+ assert attribute_data["id"] == attribute_id
+ assert attribute_data["slug"] == attribute.slug
+
+ assert not attribute_data["referenceTypes"]
+
+
+QUERY_ATTRIBUTE_REFERENCE_TYPES = """
+ query ($id: ID!, $limit: PositiveInt) {
+ attribute(id: $id) {
+ id
+ name
+ slug
+ referenceTypes(limit: $limit) {
+ ... on ProductType {
+ id
+ name
+ slug
+ }
+ ... on PageType {
+ id
+ name
+ slug
+ }
+ }
+ }
+ }
+"""
+
+
+def test_get_attribute_reference_product_types_with_limit(
+ staff_api_client,
+ product_type_product_reference_attribute,
+ product_type,
+ product_type_with_product_attributes,
+ product_type_with_variant_attributes,
+ permission_manage_products,
+):
+ # given
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ attribute = product_type_product_reference_attribute
+ reference_product_types = [
+ product_type,
+ product_type_with_product_attributes,
+ product_type_with_variant_attributes,
+ ]
+ attribute.reference_product_types.add(*reference_product_types)
+
+ query = QUERY_ATTRIBUTE_REFERENCE_TYPES
+ attribute_id = graphene.Node.to_global_id("Attribute", attribute.id)
+ # limit smaller than the number of reference types
+ limit = 2
+ variables = {"id": attribute_id, "limit": limit}
+
+ # when
+ content = get_graphql_content(staff_api_client.post_graphql(query, variables))
+
+ # then
+ attribute_data = content["data"]["attribute"]
+ assert attribute_data["id"] == attribute_id
+ assert attribute_data["slug"] == attribute.slug
+
+ reference_types = attribute_data["referenceTypes"]
+ assert len(reference_types) == limit
+
+
+def test_get_attribute_reference_product_types_limit_exceeded(
+ staff_api_client,
+ product_type_product_reference_attribute,
+ product_type,
+ product_type_with_product_attributes,
+ product_type_with_variant_attributes,
+ permission_manage_products,
+):
+ # given
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ attribute = product_type_product_reference_attribute
+ reference_product_types = [
+ product_type,
+ product_type_with_product_attributes,
+ product_type_with_variant_attributes,
+ ]
+ attribute.reference_product_types.add(*reference_product_types)
+
+ query = QUERY_ATTRIBUTE_REFERENCE_TYPES
+ attribute_id = graphene.Node.to_global_id("Attribute", attribute.id)
+ limit = 0
+ variables = {"id": attribute_id, "limit": limit}
+
+ # when
+ content = get_graphql_content_from_response(
+ staff_api_client.post_graphql(query, variables)
+ )
+
+ # then
+ assert len(content["errors"]) == 1
+ assert (
+ f'Variable "$limit" got invalid value {limit}'
+ in content["errors"][0]["message"]
+ )
+
+
+def test_get_attribute_reference_page_types_with_limit(
+ staff_api_client,
+ product_type_page_reference_attribute,
+ page_type_list,
+ permission_manage_products,
+):
+ # given
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ attribute = product_type_page_reference_attribute
+ attribute.reference_page_types.add(*page_type_list)
+
+ query = QUERY_ATTRIBUTE_REFERENCE_TYPES
+ attribute_id = graphene.Node.to_global_id("Attribute", attribute.id)
+ # limit smaller than the number of reference types
+ limit = 2
+ variables = {"id": attribute_id, "limit": limit}
+
+ # when
+ content = get_graphql_content(staff_api_client.post_graphql(query, variables))
+
+ # then
+ attribute_data = content["data"]["attribute"]
+ assert attribute_data["id"] == attribute_id
+ assert attribute_data["slug"] == attribute.slug
+
+ reference_types = attribute_data["referenceTypes"]
+ assert len(reference_types) == limit
+
+
+def test_get_attribute_reference_page_types_invalid_limit(
+ staff_api_client,
+ product_type_page_reference_attribute,
+ page_type_list,
+ permission_manage_products,
+):
+ # given
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ attribute = product_type_page_reference_attribute
+ attribute.reference_page_types.add(*page_type_list)
+
+ query = QUERY_ATTRIBUTE_REFERENCE_TYPES
+ attribute_id = graphene.Node.to_global_id("Attribute", attribute.id)
+ limit = 0
+ variables = {"id": attribute_id, "limit": limit}
+
+ # when
+ content = get_graphql_content_from_response(
+ staff_api_client.post_graphql(query, variables)
+ )
+
+ # then
+ assert len(content["errors"]) == 1
+ assert (
+ f'Variable "$limit" got invalid value {limit}'
+ in content["errors"][0]["message"]
+ )
+
+
QUERY_ATTRIBUTES = """
query {
attributes(first: 20) {
@@ -783,3 +1215,81 @@ def test_get_attribute_by_external_reference(
data = content["data"]["attribute"]
assert data["externalReference"] == ext_ref
assert data["id"] == graphene.Node.to_global_id("Attribute", attribute.id)
+
+
+QUERY_ATTRIBUTE_TWO_LIMITS = """
+ query($id: ID, $limit1: PositiveInt, $limit2: PositiveInt) {
+ limit1: attribute(id: $id) {
+ id
+ name
+ slug
+ referenceTypes(limit: $limit1) {
+ ... on ProductType {
+ id
+ name
+ }
+ ... on PageType {
+ id
+ name
+ }
+ }
+ }
+ limit2: attribute(id: $id) {
+ id
+ name
+ slug
+ referenceTypes(limit: $limit2) {
+ ... on ProductType {
+ id
+ name
+ }
+ ... on PageType {
+ id
+ name
+ }
+ }
+ }
+ }
+"""
+
+
+def test_get_reference_product_attribute_with_reference_types_and_different_limits(
+ staff_api_client,
+ product_type_product_reference_attribute,
+ product_type,
+ product_type_with_product_attributes,
+ product_type_with_variant_attributes,
+ permission_manage_products,
+):
+ # given
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ attribute = product_type_product_reference_attribute
+ reference_product_types = [product_type, product_type_with_product_attributes]
+ attribute.reference_product_types.add(*reference_product_types)
+
+ query = QUERY_ATTRIBUTE_TWO_LIMITS
+ attribute_id = graphene.Node.to_global_id("Attribute", attribute.id)
+ limit1 = 1
+ limit2 = 2
+ variables = {"id": attribute_id, "limit1": limit1, "limit2": limit2}
+
+ # when
+ content = get_graphql_content(staff_api_client.post_graphql(query, variables))
+
+ # then
+ attribute_data = content["data"]
+ limit1_data = attribute_data["limit1"]
+ limit2_data = attribute_data["limit2"]
+
+ assert limit1_data["id"] == attribute_id
+ assert limit1_data["slug"] == attribute.slug
+
+ reference_types = limit1_data["referenceTypes"]
+ assert len(reference_types) == limit1
+
+ assert limit2_data["id"] == attribute_id
+ assert limit2_data["slug"] == attribute.slug
+
+ reference_types = limit2_data["referenceTypes"]
+ assert len(reference_types) == limit2
diff --git a/saleor/graphql/attribute/tests/type_handlers/test_reference_handler.py b/saleor/graphql/attribute/tests/type_handlers/test_reference_handler.py
index 2b9ebdb6e9..74aaf7549a 100644
--- a/saleor/graphql/attribute/tests/type_handlers/test_reference_handler.py
+++ b/saleor/graphql/attribute/tests/type_handlers/test_reference_handler.py
@@ -74,6 +74,74 @@ def test_reference_handler_clean_and_validate_variant_reference(
assert set(handler.values_input.reference_objects) == set(product_variant_list)
+def test_reference_handler_clean_and_validate_product_reference_with_reference_types(
+ product_type_product_reference_attribute, product_list, product_type
+):
+ # given
+ product_type_product_reference_attribute.reference_product_types.add(product_type)
+ product_ids = [graphene.Node.to_global_id("Product", p.id) for p in product_list]
+ attribute = product_type_product_reference_attribute
+ attribute_id = graphene.Node.to_global_id("Attribute", attribute.id)
+ values_input = AttrValuesInput(global_id=attribute_id, references=product_ids)
+ handler = ReferenceAttributeHandler(attribute, values_input)
+ attribute_errors = defaultdict(list)
+
+ # when
+ handler.clean_and_validate(attribute_errors)
+
+ # then
+ assert not attribute_errors
+ assert handler.values_input.references
+ assert handler.values_input.reference_objects
+ assert set(handler.values_input.reference_objects) == set(product_list)
+
+
+def test_reference_handler_clean_and_validate_page_reference_with_reference_types(
+ product_type_page_reference_attribute, page_list, page_type
+):
+ # given
+ product_type_page_reference_attribute.reference_page_types.add(page_type)
+ page_ids = [graphene.Node.to_global_id("Page", p.id) for p in page_list]
+ attribute = product_type_page_reference_attribute
+ attribute_id = graphene.Node.to_global_id("Attribute", attribute.id)
+ values_input = AttrValuesInput(global_id=attribute_id, references=page_ids)
+ handler = ReferenceAttributeHandler(attribute, values_input)
+ attribute_errors = defaultdict(list)
+
+ # when
+ handler.clean_and_validate(attribute_errors)
+
+ # then
+ assert not attribute_errors
+ assert handler.values_input.references
+ assert handler.values_input.reference_objects
+ assert set(handler.values_input.reference_objects) == set(page_list)
+
+
+def test_reference_handler_clean_and_validate_variant_reference_with_reference_types(
+ page_type_variant_reference_attribute, product_variant_list, product_type
+):
+ # given
+ page_type_variant_reference_attribute.reference_product_types.add(product_type)
+ variant_ids = [
+ graphene.Node.to_global_id("ProductVariant", v.id) for v in product_variant_list
+ ]
+ attribute = page_type_variant_reference_attribute
+ attribute_id = graphene.Node.to_global_id("Attribute", attribute.id)
+ values_input = AttrValuesInput(global_id=attribute_id, references=variant_ids)
+ handler = ReferenceAttributeHandler(attribute, values_input)
+ attribute_errors = defaultdict(list)
+
+ # when
+ handler.clean_and_validate(attribute_errors)
+
+ # then
+ assert not attribute_errors
+ assert handler.values_input.references
+ assert handler.values_input.reference_objects
+ assert set(handler.values_input.reference_objects) == set(product_variant_list)
+
+
def test_reference_handler_clean_and_validate_category_reference(
product_type_category_reference_attribute, category_list
):
@@ -118,6 +186,74 @@ def test_reference_handler_clean_and_validate_collection_reference(
assert set(handler.values_input.reference_objects) == set(collection_list)
+def test_reference_handler_clean_and_validate_invalid_product_reference_type(
+ product_type_product_reference_attribute,
+ product,
+ product_type_with_variant_attributes,
+):
+ # given
+ attribute = product_type_product_reference_attribute
+ product_type_product_reference_attribute.reference_product_types.add(
+ product_type_with_variant_attributes
+ )
+ values_input = AttrValuesInput(
+ global_id=graphene.Node.to_global_id("Attribute", attribute.id),
+ references=[graphene.Node.to_global_id("Product", product.id)],
+ )
+ handler = ReferenceAttributeHandler(attribute, values_input)
+ attribute_errors = defaultdict(list)
+
+ # when
+ handler.clean_and_validate(attribute_errors)
+
+ # then
+ assert attribute_errors[AttributeInputErrors.INVALID_REFERENCE_TYPE]
+
+
+def test_reference_handler_clean_and_validate_invalid_product_variant_ref_type(
+ product_type_variant_reference_attribute,
+ variant,
+ product_type_with_variant_attributes,
+):
+ # given
+ attribute = product_type_variant_reference_attribute
+ product_type_variant_reference_attribute.reference_product_types.add(
+ product_type_with_variant_attributes
+ )
+ values_input = AttrValuesInput(
+ global_id=graphene.Node.to_global_id("Attribute", attribute.id),
+ references=[graphene.Node.to_global_id("ProductVariant", variant.id)],
+ )
+ handler = ReferenceAttributeHandler(attribute, values_input)
+ attribute_errors = defaultdict(list)
+
+ # when
+ handler.clean_and_validate(attribute_errors)
+
+ # then
+ assert attribute_errors[AttributeInputErrors.INVALID_REFERENCE_TYPE]
+
+
+def test_reference_handler_clean_and_validate_invalid_page_reference_type(
+ product_type_page_reference_attribute, page, page_type_list
+):
+ # given
+ attribute = product_type_page_reference_attribute
+ product_type_page_reference_attribute.reference_page_types.add(page_type_list[1])
+ values_input = AttrValuesInput(
+ global_id=graphene.Node.to_global_id("Attribute", attribute.id),
+ references=[graphene.Node.to_global_id("Page", page.id)],
+ )
+ handler = ReferenceAttributeHandler(attribute, values_input)
+ attribute_errors = defaultdict(list)
+
+ # when
+ handler.clean_and_validate(attribute_errors)
+
+ # then
+ assert attribute_errors[AttributeInputErrors.INVALID_REFERENCE_TYPE]
+
+
def test_single_reference_handler_clean_and_validate_page_reference(
product_type_page_single_reference_attribute, page
):
@@ -194,6 +330,73 @@ def test_single_reference_handler_clean_and_validate_collection_reference(
assert handler.values_input.reference_objects == [collection]
+def test_single_reference_handler_clean_and_validate_product_ref_with_reference_types(
+ product_type_product_single_reference_attribute, product, product_type
+):
+ # given
+ product_type_product_single_reference_attribute.reference_product_types.add(
+ product_type
+ )
+ product_id = graphene.Node.to_global_id("Product", product.id)
+ attribute = product_type_product_single_reference_attribute
+ attribute_id = graphene.Node.to_global_id("Attribute", attribute.id)
+ values_input = AttrValuesInput(global_id=attribute_id, reference=product_id)
+ handler = ReferenceAttributeHandler(attribute, values_input)
+ attribute_errors = defaultdict(list)
+
+ # when
+ handler.clean_and_validate(attribute_errors)
+
+ # then
+ assert not attribute_errors
+ assert handler.values_input.reference
+ assert handler.values_input.reference_objects == [product]
+
+
+def test_single_reference_handler_clean_and_validate_page_ref_with_reference_types(
+ product_type_page_single_reference_attribute, page, page_type
+):
+ # given
+ product_type_page_single_reference_attribute.reference_page_types.add(page_type)
+ page_id = graphene.Node.to_global_id("Page", page.id)
+ attribute = product_type_page_single_reference_attribute
+ attribute_id = graphene.Node.to_global_id("Attribute", attribute.id)
+ values_input = AttrValuesInput(global_id=attribute_id, reference=page_id)
+ handler = ReferenceAttributeHandler(attribute, values_input)
+ attribute_errors = defaultdict(list)
+
+ # when
+ handler.clean_and_validate(attribute_errors)
+
+ # then
+ assert not attribute_errors
+ assert handler.values_input.reference
+ assert handler.values_input.reference_objects == [page]
+
+
+def test_single_reference_handler_clean_and_validate_variant_ref_with_reference_types(
+ page_type_variant_single_reference_attribute, variant, product_type
+):
+ # given
+ page_type_variant_single_reference_attribute.reference_product_types.add(
+ product_type
+ )
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.id)
+ attribute = page_type_variant_single_reference_attribute
+ attribute_id = graphene.Node.to_global_id("Attribute", attribute.id)
+ values_input = AttrValuesInput(global_id=attribute_id, reference=variant_id)
+ handler = ReferenceAttributeHandler(attribute, values_input)
+ attribute_errors = defaultdict(list)
+
+ # when
+ handler.clean_and_validate(attribute_errors)
+
+ # then
+ assert not attribute_errors
+ assert handler.values_input.reference
+ assert handler.values_input.reference_objects == [variant]
+
+
def test_single_reference_handler_clean_and_validate_success(
product_type_product_single_reference_attribute, product
):
@@ -295,6 +498,76 @@ def test_single_reference_handler_clean_and_validate_invalid_reference(
assert attribute_errors[AttributeInputErrors.INVALID_REFERENCE]
+def test_single_reference_handler_clean_and_validate_invalid_product_reference_type(
+ product_type_product_single_reference_attribute,
+ product,
+ product_type_with_variant_attributes,
+):
+ # given
+ attribute = product_type_product_single_reference_attribute
+ product_type_product_single_reference_attribute.reference_product_types.add(
+ product_type_with_variant_attributes
+ )
+ values_input = AttrValuesInput(
+ global_id=graphene.Node.to_global_id("Attribute", attribute.id),
+ reference=graphene.Node.to_global_id("Product", product.id),
+ )
+ handler = ReferenceAttributeHandler(attribute, values_input)
+ attribute_errors = defaultdict(list)
+
+ # when
+ handler.clean_and_validate(attribute_errors)
+
+ # then
+ assert attribute_errors[AttributeInputErrors.INVALID_REFERENCE_TYPE]
+
+
+def test_single_reference_handler_clean_and_validate_invalid_product_variant_ref_type(
+ product_type_variant_single_reference_attribute,
+ variant,
+ product_type_with_variant_attributes,
+):
+ # given
+ attribute = product_type_variant_single_reference_attribute
+ product_type_variant_single_reference_attribute.reference_product_types.add(
+ product_type_with_variant_attributes
+ )
+ values_input = AttrValuesInput(
+ global_id=graphene.Node.to_global_id("Attribute", attribute.id),
+ reference=graphene.Node.to_global_id("ProductVariant", variant.id),
+ )
+ handler = ReferenceAttributeHandler(attribute, values_input)
+ attribute_errors = defaultdict(list)
+
+ # when
+ handler.clean_and_validate(attribute_errors)
+
+ # then
+ assert attribute_errors[AttributeInputErrors.INVALID_REFERENCE_TYPE]
+
+
+def test_single_reference_handler_clean_and_validate_invalid_page_reference_type(
+ product_type_page_single_reference_attribute, page, page_type_list
+):
+ # given
+ attribute = product_type_page_single_reference_attribute
+ product_type_page_single_reference_attribute.reference_page_types.add(
+ page_type_list[1]
+ )
+ values_input = AttrValuesInput(
+ global_id=graphene.Node.to_global_id("Attribute", attribute.id),
+ reference=graphene.Node.to_global_id("Page", page.id),
+ )
+ handler = ReferenceAttributeHandler(attribute, values_input)
+ attribute_errors = defaultdict(list)
+
+ # when
+ handler.clean_and_validate(attribute_errors)
+
+ # then
+ assert attribute_errors[AttributeInputErrors.INVALID_REFERENCE_TYPE]
+
+
def test_reference_handler_pre_save_value(
product_type_product_reference_attribute, product_list, product
):
diff --git a/saleor/graphql/attribute/types.py b/saleor/graphql/attribute/types.py
index 3991042a42..d4067eab36 100644
--- a/saleor/graphql/attribute/types.py
+++ b/saleor/graphql/attribute/types.py
@@ -29,6 +29,7 @@ from ..core.descriptions import (
ADDED_IN_322,
DEFAULT_DEPRECATION_REASON,
DEPRECATED_IN_3X_INPUT,
+ NESTED_QUERY_LIMIT_DESCRIPTION,
)
from ..core.doc_category import DOC_CATEGORY_ATTRIBUTES
from ..core.enums import LanguageCodeEnum, MeasurementUnitsEnum
@@ -59,7 +60,13 @@ from ..translations.dataloaders import (
)
from ..translations.fields import TranslationField
from ..translations.types import AttributeTranslation, AttributeValueTranslation
-from .dataloaders import AttributesByAttributeId
+from .dataloaders.attributes import (
+ AttributesByAttributeId,
+)
+from .dataloaders.reference_types import (
+ AttributeReferencePageTypesByAttributeIdAndLimitLoader,
+ AttributeReferenceProductTypesByAttributeIdAndLimitLoader,
+)
from .descriptions import AttributeDescriptions, AttributeValueDescriptions
from .enums import AttributeEntityTypeEnum, AttributeInputTypeEnum, AttributeTypeEnum
from .filters import (
@@ -268,6 +275,18 @@ class Attribute(ChannelContextType[models.Attribute]):
entity_type = AttributeEntityTypeEnum(
description=AttributeDescriptions.ENTITY_TYPE, required=False
)
+ reference_types = NonNullList(
+ "saleor.graphql.attribute.unions.ReferenceType",
+ description=(
+ "The reference types (product or page type) that are used to narrow down "
+ "the choices of reference objects." + ADDED_IN_322
+ ),
+ required=False,
+ limit=PositiveInt(
+ description=NESTED_QUERY_LIMIT_DESCRIPTION,
+ default_value=DEFAULT_NESTED_LIST_LIMIT,
+ ),
+ )
name = graphene.String(description=AttributeDescriptions.NAME)
slug = graphene.String(description=AttributeDescriptions.SLUG)
@@ -392,6 +411,24 @@ class Attribute(ChannelContextType[models.Attribute]):
interfaces = [graphene.relay.Node, ObjectWithMetadata]
model = models.Attribute
+ @staticmethod
+ def resolve_reference_types(
+ root: ChannelContext[models.Attribute], info: ResolveInfo, limit: int, **kwargs
+ ):
+ attr = root.node
+ if attr.entity_type in [
+ AttributeEntityTypeEnum.PRODUCT.value,
+ AttributeEntityTypeEnum.PRODUCT_VARIANT.value,
+ ]:
+ return AttributeReferenceProductTypesByAttributeIdAndLimitLoader(
+ info.context
+ ).load((attr.id, limit))
+ if attr.entity_type == AttributeEntityTypeEnum.PAGE.value:
+ return AttributeReferencePageTypesByAttributeIdAndLimitLoader(
+ info.context
+ ).load((attr.id, limit))
+ return []
+
@staticmethod
def resolve_choices(
root: ChannelContext[models.Attribute], info: ResolveInfo, **kwargs
diff --git a/saleor/graphql/attribute/unions.py b/saleor/graphql/attribute/unions.py
new file mode 100644
index 0000000000..d0d746c392
--- /dev/null
+++ b/saleor/graphql/attribute/unions.py
@@ -0,0 +1,28 @@
+import graphene
+
+from ...page import models as page_models
+from ...product import models as product_models
+from ..core import ResolveInfo
+from ..page.types import PageType
+from ..product.types import ProductType
+
+
+class ReferenceType(graphene.Union):
+ class Meta:
+ description = (
+ "The reference types (product or page type) that are used to narrow down "
+ "the choices of reference objects.\n"
+ "ProductType applicable for reference attribute with `PRODUCT` or "
+ "`PRODUCT_VARIANT` entity type.\n"
+ "PageType applicable for reference attribute with `PAGE` entity type."
+ )
+ types = (ProductType, PageType)
+
+ @classmethod
+ def resolve_type(cls, instance, info: ResolveInfo):
+ if isinstance(instance, product_models.ProductType):
+ return ProductType
+ if isinstance(instance, page_models.PageType):
+ return PageType
+
+ return super().resolve_type(instance, info)
diff --git a/saleor/graphql/attribute/utils/attribute_assignment.py b/saleor/graphql/attribute/utils/attribute_assignment.py
index 3ca82e45db..7d022d4dad 100644
--- a/saleor/graphql/attribute/utils/attribute_assignment.py
+++ b/saleor/graphql/attribute/utils/attribute_assignment.py
@@ -72,8 +72,11 @@ class AttributeAssignmentMixin:
ext_ref_set: set[str],
):
"""Retrieve attributes nodes from given identifiers."""
+ nodes = qs.filter(
+ Q(pk__in=id_map.keys()) | Q(external_reference__in=ext_ref_set)
+ )
nodes = list(
- qs.filter(Q(pk__in=id_map.keys()) | Q(external_reference__in=ext_ref_set))
+ nodes.prefetch_related("reference_product_types", "reference_page_types")
)
resolved_pks = {node.pk for node in nodes}
diff --git a/saleor/graphql/attribute/utils/type_handlers.py b/saleor/graphql/attribute/utils/type_handlers.py
index 39c4abb3f3..ccc8f2e0c6 100644
--- a/saleor/graphql/attribute/utils/type_handlers.py
+++ b/saleor/graphql/attribute/utils/type_handlers.py
@@ -73,6 +73,11 @@ class AttributeInputErrors:
# Reference Errors
REFERENCE_REQUIRED = ("A reference is required for this attribute.", "REQUIRED")
INVALID_REFERENCE = ("Invalid reference type.", "INVALID")
+ INVALID_REFERENCE_TYPE = (
+ "Invalid reference, must be an object from available choices defined by "
+ "reference types on attribute.",
+ "INVALID",
+ )
# Numeric Errors
ERROR_NUMERIC_VALUE_REQUIRED = ("Numeric value is required.", "INVALID")
@@ -451,17 +456,68 @@ class ReferenceAttributeHandler(AttributeTypeHandler):
return
entity_data = ENTITY_TYPE_MAPPING[self.attribute.entity_type]
+ prefetch_related = (
+ ["product"]
+ if self.attribute.entity_type == AttributeEntityType.PRODUCT_VARIANT
+ else []
+ )
try:
ref_instances = get_nodes(
- references, self.attribute.entity_type, model=entity_data.model
+ references,
+ self.attribute.entity_type,
+ model=entity_data.model,
+ prefetch_related=prefetch_related,
)
except GraphQLError:
attribute_errors[AttributeInputErrors.INVALID_REFERENCE].append(
self.attribute_identifier
)
return
+
+ invalid_refs = self.get_references_with_invalid_reference_types(
+ ref_instances, attribute_errors
+ )
+ if invalid_refs:
+ attribute_errors[AttributeInputErrors.INVALID_REFERENCE_TYPE].append(
+ self.attribute_identifier
+ )
+ return
+
self.values_input.reference_objects = ref_instances
+ def get_references_with_invalid_reference_types(
+ self, ref_instances: list, attribute_errors: T_ERROR_DICT
+ ):
+ """Validate that all references are of the correct type.
+
+ For `PRODUCT` and `PRODUCT_VARIANT` entity types, check if the
+ references belong to the reference product types defined in the attribute.
+
+ For `PAGE` entity type, check if the references belong to the reference page
+ types defined in the attribute.
+ """
+ # `reference_product_types` and `reference_page_types` are pre-fetched
+ # in `AttributeAssignmentMixin._resolve_attribute_nodes`
+ if reference_product_types := self.attribute.reference_product_types.all():
+ ref_product_type_ids = set()
+ if self.attribute.entity_type == AttributeEntityType.PRODUCT:
+ ref_product_type_ids = {ref.product_type_id for ref in ref_instances}
+ elif self.attribute.entity_type == AttributeEntityType.PRODUCT_VARIANT:
+ # product is pre-fetched in `get_nodes`
+ ref_product_type_ids = {
+ ref.product.product_type_id for ref in ref_instances
+ }
+ attribute_product_type_ids = {pt.id for pt in reference_product_types}
+ invalid_refs = ref_product_type_ids - attribute_product_type_ids
+ return invalid_refs
+ if reference_page_types := self.attribute.reference_page_types.all():
+ ref_page_type_ids = {ref.page_type_id for ref in ref_instances}
+ # `reference_page_types` are pre-fetched in `AttributeAssignmentMixin._resolve_attribute_nodes`
+ attribute_page_type_ids = {pt.id for pt in reference_page_types}
+ invalid_refs = ref_page_type_ids - attribute_page_type_ids
+ return invalid_refs
+ return {}
+
def pre_save_value(self, instance: T_INSTANCE) -> list[tuple]:
references = self.values_input.reference_objects
entity_type = self.attribute.entity_type
diff --git a/saleor/graphql/core/descriptions.py b/saleor/graphql/core/descriptions.py
index 307b51cfbb..52a25243e5 100644
--- a/saleor/graphql/core/descriptions.py
+++ b/saleor/graphql/core/descriptions.py
@@ -1,5 +1,7 @@
from graphql import DEFAULT_DEPRECATION_REASON as DEFAULT_DEPRECATION_REASON
+from .const import DEFAULT_NESTED_LIST_LIMIT
+
# Deprecation message for input fields and query arguments. Use it, when
# deprecation message needs to be included in the field description.
DEPRECATED_IN_3X_INPUT = "\n\nDEPRECATED: this field will be removed."
@@ -26,3 +28,8 @@ CHANNEL_REQUIRED = (
)
RICH_CONTENT = "\n\nRich text format. For reference see https://editorjs.io/"
+
+NESTED_QUERY_LIMIT_DESCRIPTION = (
+ "Maximum number of objects to return. "
+ f"Value must be greater than 0. Default is {DEFAULT_NESTED_LIST_LIMIT}."
+)
diff --git a/saleor/graphql/core/tests/test_query_cost_validation.py b/saleor/graphql/core/tests/test_query_cost_validation.py
index cc998e807a..3d39e97912 100644
--- a/saleor/graphql/core/tests/test_query_cost_validation.py
+++ b/saleor/graphql/core/tests/test_query_cost_validation.py
@@ -3,6 +3,7 @@ import pytest
from django.test import override_settings
from ...query_cost_map import COST_MAP
+from ..const import DEFAULT_NESTED_LIST_LIMIT
@override_settings(GRAPHQL_QUERY_MAX_COMPLEXITY=1)
@@ -468,3 +469,82 @@ def test_query_cost_for_spread_and_inline_fragments_on_interface(api_client):
+ assigned_attributes_limit * assigned_multi_category_limit
)
assert query_cost == expected_cost
+
+
+ATTRIBUTE_QUERY_WITH_LIMIT = """
+query($limit: PositiveInt) {
+ attributes(first:100) {
+ edges {
+ node {
+ id
+ name
+ referenceTypes(limit: $limit) {
+ ... on ProductType{
+ id
+ slug
+ }
+ }
+ }
+ }
+ }
+}
+"""
+
+
+def test_query_with_empty_not_required_limit_argument(
+ api_client,
+ product_type_product_single_reference_attribute,
+ product_type,
+ product_type_with_product_attributes,
+ product_type_variant_single_reference_attribute,
+):
+ # given
+ product_type_product_single_reference_attribute.reference_product_types.add(
+ product_type, product_type_with_product_attributes
+ )
+ product_type_variant_single_reference_attribute.reference_product_types.add(
+ product_type
+ )
+
+ variables = {"limit": None}
+
+ # when
+ response = api_client.post_graphql(ATTRIBUTE_QUERY_WITH_LIMIT, variables)
+ json_response = response.json()
+
+ # then
+ assert "errors" not in json_response
+ assert json_response["data"]["attributes"]["edges"]
+ query_cost = json_response["extensions"]["cost"]["requestedQueryCost"]
+ assert (
+ query_cost == 100 * 1 + 100 * DEFAULT_NESTED_LIST_LIMIT
+ ) # 100 attributes + 100 product types (limit value) per attribute
+
+
+def test_query_with_not_required_limit_argument_not_provided(
+ api_client,
+ product_type_product_single_reference_attribute,
+ product_type,
+ product_type_with_product_attributes,
+ product_type_variant_single_reference_attribute,
+):
+ # given
+ product_type_product_single_reference_attribute.reference_product_types.add(
+ product_type, product_type_with_product_attributes
+ )
+ product_type_variant_single_reference_attribute.reference_product_types.add(
+ product_type
+ )
+ variables = {}
+
+ # when
+ response = api_client.post_graphql(ATTRIBUTE_QUERY_WITH_LIMIT, variables)
+ json_response = response.json()
+
+ # then
+ assert "errors" not in json_response
+ assert json_response["data"]["attributes"]["edges"]
+ query_cost = json_response["extensions"]["cost"]["requestedQueryCost"]
+ assert (
+ query_cost == 100 * 1 + 100 * DEFAULT_NESTED_LIST_LIMIT
+ ) # 100 attributes + 100 product types (limit value) per attribute
diff --git a/saleor/graphql/core/validators/__init__.py b/saleor/graphql/core/validators/__init__.py
index 4d4bafd502..6d752ca563 100644
--- a/saleor/graphql/core/validators/__init__.py
+++ b/saleor/graphql/core/validators/__init__.py
@@ -215,3 +215,15 @@ def validate_if_int_or_uuid(id):
UUID(id)
except (AttributeError, ValueError) as e:
raise ValidationError("Must receive an int or UUID.") from e
+
+
+def validate_limit_of_list_input(
+ input_list: list,
+ limit: int,
+ field_name: str,
+):
+ """Validate if the length of the input list does not exceed the limit."""
+ if len(input_list) > limit:
+ raise ValidationError(
+ f"The maximum number of items in {field_name} is {limit}."
+ )
diff --git a/saleor/graphql/core/validators/query_cost.py b/saleor/graphql/core/validators/query_cost.py
index 3f616635ff..75a49cca05 100644
--- a/saleor/graphql/core/validators/query_cost.py
+++ b/saleor/graphql/core/validators/query_cost.py
@@ -4,6 +4,7 @@ from operator import add, mul
from typing import Any, cast
from graphql import (
+ GraphQLArgument,
GraphQLError,
GraphQLInterfaceType,
GraphQLObjectType,
@@ -88,6 +89,8 @@ class CostValidator(ValidationRule):
report_error(self.context, e)
field_args = {}
+ field_args = self.update_empty_args_with_default(field_args, field.args)
+
if not self.cost_map:
return 0
@@ -155,6 +158,17 @@ class CostValidator(ValidationRule):
total += max(fragment_map_cost.values(), default=0)
return total
+ def update_empty_args_with_default(
+ self, field_args: dict[str, Any], args_defs: dict[str, GraphQLArgument]
+ ) -> dict[str, Any]:
+ """Update empty args with default values from argument definition."""
+ for arg_name, value in field_args.items():
+ if value is None and arg_name in args_defs:
+ arg_def = args_defs[arg_name]
+ if arg_def.default_value is not None:
+ field_args[arg_name] = arg_def.default_value
+ return field_args
+
def enter_operation_definition(self, node, key, parent, path, ancestors): # pylint: disable=unused-argument
if self.cost_map:
try:
diff --git a/saleor/graphql/page/dataloaders.py b/saleor/graphql/page/dataloaders.py
index 230e79b5ca..3027ffa7da 100644
--- a/saleor/graphql/page/dataloaders.py
+++ b/saleor/graphql/page/dataloaders.py
@@ -5,7 +5,7 @@ from promise import Promise
from ...attribute.models import AssignedPageAttributeValue, Attribute, AttributePage
from ...page.models import Page, PageType
-from ..attribute.dataloaders import (
+from ..attribute.dataloaders.attributes import (
AttributesByAttributeId,
AttributesBySlugLoader,
AttributeValueByIdLoader,
diff --git a/saleor/graphql/page/tests/mutations/test_page_create.py b/saleor/graphql/page/tests/mutations/test_page_create.py
index c09dbae650..037a0b92d2 100644
--- a/saleor/graphql/page/tests/mutations/test_page_create.py
+++ b/saleor/graphql/page/tests/mutations/test_page_create.py
@@ -861,6 +861,143 @@ def test_create_page_with_page_reference_attribute(
assert page_type_page_reference_attribute.values.count() == values_count + 1
+def test_create_page_with_reference_attributes_and_reference_types_defined(
+ staff_api_client,
+ page_type,
+ page_type_page_reference_attribute,
+ page_type_product_reference_attribute,
+ page_type_variant_reference_attribute,
+ page,
+ product,
+ variant,
+ permission_manage_pages,
+):
+ # given
+ page_type.page_attributes.clear()
+ page_type.page_attributes.add(
+ page_type_page_reference_attribute,
+ page_type_product_reference_attribute,
+ page_type_variant_reference_attribute,
+ )
+
+ page_type_page_reference_attribute.reference_page_types.add(page.page_type)
+ page_type_product_reference_attribute.reference_product_types.add(
+ product.product_type
+ )
+ page_type_variant_reference_attribute.reference_product_types.add(
+ variant.product.product_type
+ )
+
+ page_ref_attr_id = graphene.Node.to_global_id(
+ "Attribute", page_type_page_reference_attribute.id
+ )
+ product_ref_attr_id = graphene.Node.to_global_id(
+ "Attribute", page_type_product_reference_attribute.id
+ )
+ variant_ref_attr_id = graphene.Node.to_global_id(
+ "Attribute", page_type_variant_reference_attribute.id
+ )
+ page_ref = graphene.Node.to_global_id("Page", page.pk)
+ product_ref = graphene.Node.to_global_id("Product", product.pk)
+ variant_ref = graphene.Node.to_global_id("ProductVariant", variant.pk)
+
+ page_title = "test title"
+ page_slug = "test-slug"
+ page_type_id = graphene.Node.to_global_id("PageType", page_type.pk)
+
+ variables = {
+ "input": {
+ "title": page_title,
+ "slug": page_slug,
+ "pageType": page_type_id,
+ "attributes": [
+ {"id": page_ref_attr_id, "references": [page_ref]},
+ {"id": product_ref_attr_id, "references": [product_ref]},
+ {"id": variant_ref_attr_id, "references": [variant_ref]},
+ ],
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ CREATE_PAGE_MUTATION, variables, permissions=[permission_manage_pages]
+ )
+
+ # then
+ content = get_graphql_content(response)["data"]["pageCreate"]
+
+ assert not content["errors"]
+ data = content["page"]
+ assert data["title"] == page_title
+ assert data["slug"] == page_slug
+ page_id = data["id"]
+ _, page_pk = graphene.Node.from_global_id(page_id)
+ assert len(data["attributes"]) == len(variables["input"]["attributes"])
+ expected_attributes_data = [
+ {
+ "attribute": {"slug": page_type_page_reference_attribute.slug},
+ "values": [
+ {
+ "slug": f"{page_pk}_{page.id}",
+ "file": None,
+ "plainText": None,
+ "reference": page_ref,
+ "name": page.title,
+ "date": None,
+ "dateTime": None,
+ }
+ ],
+ },
+ {
+ "attribute": {"slug": page_type_product_reference_attribute.slug},
+ "values": [
+ {
+ "slug": f"{page_pk}_{product.id}",
+ "file": None,
+ "plainText": None,
+ "reference": product_ref,
+ "name": product.name,
+ "date": None,
+ "dateTime": None,
+ }
+ ],
+ },
+ {
+ "attribute": {"slug": page_type_variant_reference_attribute.slug},
+ "values": [
+ {
+ "slug": f"{page_pk}_{variant.id}",
+ "file": None,
+ "plainText": None,
+ "reference": variant_ref,
+ "name": f"{variant.product.name}: {variant.name}",
+ "date": None,
+ "dateTime": None,
+ }
+ ],
+ },
+ ]
+ for attr_data in data["attributes"]:
+ assert attr_data in expected_attributes_data
+
+ assigned_attributes = data["assignedAttributes"]
+ expected_page_ref_assigned_attribute = {
+ "attribute": {"slug": page_type_page_reference_attribute.slug},
+ "pages": [{"slug": page.slug}],
+ }
+ assert expected_page_ref_assigned_attribute in assigned_attributes
+ expected_product_ref_assigned_attribute = {
+ "attribute": {"slug": page_type_product_reference_attribute.slug},
+ "products": [{"slug": product.slug}],
+ }
+ assert expected_product_ref_assigned_attribute in assigned_attributes
+ expected_variant_ref_assigned_attribute = {
+ "attribute": {"slug": page_type_variant_reference_attribute.slug},
+ "variants": [{"sku": variant.sku}],
+ }
+ assert expected_variant_ref_assigned_attribute in assigned_attributes
+
+
@freeze_time(datetime.datetime(2020, 5, 5, 5, 5, 5, tzinfo=datetime.UTC))
def test_create_page_with_date_attribute(
staff_api_client,
@@ -1175,6 +1312,87 @@ def test_create_page_with_page_reference_attribute_required_no_references_given(
assert errors[0]["attributes"] == [reference_attribute_id]
+def test_create_page_with_reference_attributes_ref_not_in_available_choices(
+ staff_api_client,
+ page_type,
+ page_type_page_reference_attribute,
+ page_type_product_reference_attribute,
+ page_type_variant_reference_attribute,
+ page,
+ product,
+ variant,
+ page_type_list,
+ permission_manage_pages,
+ product_type_with_variant_attributes,
+):
+ # given
+ page_type.page_attributes.clear()
+ page_type.page_attributes.add(
+ page_type_page_reference_attribute,
+ page_type_product_reference_attribute,
+ page_type_variant_reference_attribute,
+ )
+
+ # assigned reference types that do not match product/page types of references
+ # that are provided in the input
+ page_type_page_reference_attribute.reference_page_types.add(page_type_list[1])
+ page_type_product_reference_attribute.reference_product_types.add(
+ product_type_with_variant_attributes
+ )
+ page_type_variant_reference_attribute.reference_product_types.add(
+ product_type_with_variant_attributes
+ )
+
+ page_ref_attr_id = graphene.Node.to_global_id(
+ "Attribute", page_type_page_reference_attribute.id
+ )
+ product_ref_attr_id = graphene.Node.to_global_id(
+ "Attribute", page_type_product_reference_attribute.id
+ )
+ variant_ref_attr_id = graphene.Node.to_global_id(
+ "Attribute", page_type_variant_reference_attribute.id
+ )
+ page_ref = graphene.Node.to_global_id("Page", page.pk)
+ product_ref = graphene.Node.to_global_id("Product", product.pk)
+ variant_ref = graphene.Node.to_global_id("ProductVariant", variant.pk)
+
+ page_title = "test title"
+ page_slug = "test-slug"
+ page_type_id = graphene.Node.to_global_id("PageType", page_type.pk)
+
+ variables = {
+ "input": {
+ "title": page_title,
+ "slug": page_slug,
+ "pageType": page_type_id,
+ "attributes": [
+ {"id": page_ref_attr_id, "references": [page_ref]},
+ {"id": product_ref_attr_id, "references": [product_ref]},
+ {"id": variant_ref_attr_id, "references": [variant_ref]},
+ ],
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ CREATE_PAGE_MUTATION, variables, permissions=[permission_manage_pages]
+ )
+
+ # then
+ content = get_graphql_content(response)["data"]["pageCreate"]
+
+ errors = content["errors"]
+ assert not content["page"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == PageErrorCode.INVALID.name
+ assert errors[0]["field"] == "attributes"
+ assert set(errors[0]["attributes"]) == {
+ page_ref_attr_id,
+ product_ref_attr_id,
+ variant_ref_attr_id,
+ }
+
+
def test_create_page_with_product_reference_attribute(
staff_api_client,
permission_manage_pages,
diff --git a/saleor/graphql/page/tests/mutations/test_page_update.py b/saleor/graphql/page/tests/mutations/test_page_update.py
index 560398c7aa..e53b33b7e5 100644
--- a/saleor/graphql/page/tests/mutations/test_page_update.py
+++ b/saleor/graphql/page/tests/mutations/test_page_update.py
@@ -741,6 +741,144 @@ def test_update_page_with_plain_text_attribute_new_value(
assert plain_text_attribute_page_type.values.count() == values_count + 1
+def test_update_page_with_reference_attributes_and_reference_types_defined(
+ staff_api_client,
+ page_list,
+ page,
+ product,
+ variant,
+ page_type_page_reference_attribute,
+ page_type_product_reference_attribute,
+ page_type_variant_reference_attribute,
+ permission_manage_pages,
+ permission_manage_products,
+):
+ # given
+ page.page_type.page_attributes.clear()
+ page.page_type.page_attributes.add(
+ page_type_page_reference_attribute,
+ page_type_product_reference_attribute,
+ page_type_variant_reference_attribute,
+ )
+
+ reference_page = page_list[1]
+
+ page_type_page_reference_attribute.reference_page_types.add(
+ reference_page.page_type
+ )
+ page_type_product_reference_attribute.reference_product_types.add(
+ product.product_type
+ )
+ page_type_variant_reference_attribute.reference_product_types.add(
+ variant.product.product_type
+ )
+
+ page_ref_attr_id = graphene.Node.to_global_id(
+ "Attribute", page_type_page_reference_attribute.id
+ )
+ product_ref_attr_id = graphene.Node.to_global_id(
+ "Attribute", page_type_product_reference_attribute.id
+ )
+ variant_ref_attr_id = graphene.Node.to_global_id(
+ "Attribute", page_type_variant_reference_attribute.id
+ )
+ page_ref = graphene.Node.to_global_id("Page", reference_page.pk)
+ product_ref = graphene.Node.to_global_id("Product", product.pk)
+ variant_ref = graphene.Node.to_global_id("ProductVariant", variant.pk)
+
+ page_id = graphene.Node.to_global_id("Page", page.pk)
+ variables = {
+ "id": page_id,
+ "input": {
+ "attributes": [
+ {"id": page_ref_attr_id, "references": [page_ref]},
+ {"id": product_ref_attr_id, "references": [product_ref]},
+ {"id": variant_ref_attr_id, "references": [variant_ref]},
+ ]
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ UPDATE_PAGE_ATTRIBUTES_MUTATION,
+ variables,
+ permissions=[permission_manage_pages, permission_manage_products],
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["pageUpdate"]
+ assert not data["errors"]
+ attributes_data = data["page"]["attributes"]
+ assert len(attributes_data) == len(variables["input"]["attributes"])
+ expected_attributes_data = [
+ {
+ "attribute": {"slug": page_type_page_reference_attribute.slug},
+ "values": [
+ {
+ "id": ANY,
+ "slug": f"{page.pk}_{reference_page.pk}",
+ "file": None,
+ "plainText": None,
+ "reference": page_ref,
+ "name": reference_page.title,
+ "date": None,
+ "dateTime": None,
+ }
+ ],
+ },
+ {
+ "attribute": {"slug": page_type_product_reference_attribute.slug},
+ "values": [
+ {
+ "id": ANY,
+ "slug": f"{page.pk}_{product.pk}",
+ "file": None,
+ "plainText": None,
+ "reference": product_ref,
+ "name": product.name,
+ "date": None,
+ "dateTime": None,
+ }
+ ],
+ },
+ {
+ "attribute": {"slug": page_type_variant_reference_attribute.slug},
+ "values": [
+ {
+ "id": ANY,
+ "slug": f"{page.pk}_{variant.pk}",
+ "file": None,
+ "plainText": None,
+ "reference": variant_ref,
+ "name": f"{variant.product.name}: {variant.name}",
+ "date": None,
+ "dateTime": None,
+ }
+ ],
+ },
+ ]
+ for attr_data in attributes_data:
+ assert attr_data in expected_attributes_data
+
+ assigned_attributes = data["page"]["assignedAttributes"]
+ expected_page_ref_assigned_attribute = {
+ "attribute": {"slug": page_type_page_reference_attribute.slug},
+ "pages": [{"slug": reference_page.slug}],
+ }
+ assert expected_page_ref_assigned_attribute in assigned_attributes
+ expected_product_ref_assigned_attribute = {
+ "attribute": {"slug": page_type_product_reference_attribute.slug},
+ "products": [{"slug": product.slug}],
+ }
+ assert expected_product_ref_assigned_attribute in assigned_attributes
+ expected_variant_ref_assigned_attribute = {
+ "attribute": {"slug": page_type_variant_reference_attribute.slug},
+ "variants": [{"sku": variant.sku}],
+ }
+ assert expected_variant_ref_assigned_attribute in assigned_attributes
+
+
def test_update_page_with_plain_text_attribute_existing_value(
staff_api_client,
permission_manage_pages,
@@ -1245,6 +1383,88 @@ def test_update_page_with_collection_reference_attribute_new_value(
assert page_type_collection_reference_attribute.values.count() == values_count + 1
+def test_update_page_with_reference_attributes_ref_not_in_available_choices(
+ staff_api_client,
+ page_list,
+ product,
+ variant,
+ page_type_page_reference_attribute,
+ page_type_product_reference_attribute,
+ page_type_variant_reference_attribute,
+ permission_manage_pages,
+ product_type_with_variant_attributes,
+ page_type_with_rich_text_attribute,
+):
+ # given
+ page = page_list[0]
+ page.page_type.page_attributes.clear()
+ page.page_type.page_attributes.add(
+ page_type_page_reference_attribute,
+ page_type_product_reference_attribute,
+ page_type_variant_reference_attribute,
+ )
+
+ reference_page = page_list[1]
+ # assigned reference types that do not match product/page types of references
+ # that are provided in the input
+ page_type_page_reference_attribute.reference_page_types.add(
+ page_type_with_rich_text_attribute
+ )
+ page_type_product_reference_attribute.reference_product_types.add(
+ product_type_with_variant_attributes
+ )
+ page_type_variant_reference_attribute.reference_product_types.add(
+ product_type_with_variant_attributes
+ )
+
+ page_ref_attr_id = graphene.Node.to_global_id(
+ "Attribute", page_type_page_reference_attribute.id
+ )
+ product_ref_attr_id = graphene.Node.to_global_id(
+ "Attribute", page_type_product_reference_attribute.id
+ )
+ variant_ref_attr_id = graphene.Node.to_global_id(
+ "Attribute", page_type_variant_reference_attribute.id
+ )
+ variant_ref = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ page_ref = graphene.Node.to_global_id("Page", reference_page.pk)
+ product_ref = graphene.Node.to_global_id("Product", product.pk)
+
+ page_id = graphene.Node.to_global_id("Page", page.pk)
+ variables = {
+ "id": page_id,
+ "input": {
+ "attributes": [
+ {"id": page_ref_attr_id, "references": [page_ref]},
+ {"id": product_ref_attr_id, "references": [product_ref]},
+ {"id": variant_ref_attr_id, "references": [variant_ref]},
+ ]
+ },
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ UPDATE_PAGE_ATTRIBUTES_MUTATION,
+ variables,
+ permissions=[permission_manage_pages],
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ data = content["data"]["pageUpdate"]
+ errors = data["errors"]
+ assert not data["page"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == PageErrorCode.INVALID.name
+ assert errors[0]["field"] == "attributes"
+ assert set(errors[0]["attributes"]) == {
+ page_ref_attr_id,
+ product_ref_attr_id,
+ variant_ref_attr_id,
+ }
+
+
@freeze_time("2020-03-18 12:00:00")
def test_public_page_sets_publication_date(
staff_api_client, permission_manage_pages, page_type
@@ -1374,6 +1594,26 @@ UPDATE_PAGE_ATTRIBUTES_MUTATION = """
slug
}
}
+ ... on AssignedMultiProductVariantReferenceAttribute {
+ variants: value {
+ sku
+ }
+ }
+ ... on AssignedMultiCategoryReferenceAttribute {
+ categories: value {
+ slug
+ }
+ }
+ ... on AssignedMultiCollectionReferenceAttribute {
+ collections: value {
+ slug
+ }
+ }
+ ... on AssignedMultiPageReferenceAttribute {
+ pages: value {
+ slug
+ }
+ }
... on AssignedSingleCategoryReferenceAttribute {
category: value {
slug
@@ -1423,6 +1663,7 @@ UPDATE_PAGE_ATTRIBUTES_MUTATION = """
field
code
message
+ attributes
}
}
}
diff --git a/saleor/graphql/product/dataloaders/attributes.py b/saleor/graphql/product/dataloaders/attributes.py
index 632d81d782..7098e8fffc 100644
--- a/saleor/graphql/product/dataloaders/attributes.py
+++ b/saleor/graphql/product/dataloaders/attributes.py
@@ -11,7 +11,10 @@ from ....attribute.models import (
AttributeVariant,
)
from ....permission.enums import ProductPermissions
-from ...attribute.dataloaders import AttributesByAttributeId, AttributeValueByIdLoader
+from ...attribute.dataloaders.attributes import (
+ AttributesByAttributeId,
+ AttributeValueByIdLoader,
+)
from ...core.dataloaders import DataLoader
from ...utils import get_user_or_app_from_context
from .products import ProductByIdLoader, ProductVariantByIdLoader
diff --git a/saleor/graphql/product/tests/mutations/test_product_bulk_create.py b/saleor/graphql/product/tests/mutations/test_product_bulk_create.py
index f851b96bdf..a351f1d2e6 100644
--- a/saleor/graphql/product/tests/mutations/test_product_bulk_create.py
+++ b/saleor/graphql/product/tests/mutations/test_product_bulk_create.py
@@ -60,6 +60,7 @@ mutation ProductBulkCreate($products: [ProductBulkCreateInput!]!, $errorPolicy:
}
values {
value
+ reference
}
}
assignedAttributes(limit:10) {
@@ -1334,6 +1335,224 @@ def test_product_bulk_create_with_single_reference_attributes(
assert expected_assigned_page_attribute in second_p_assigned_attributes
+def test_product_bulk_create_with_reference_attributes_and_reference_types_defined(
+ staff_api_client,
+ product_type,
+ product_type_page_single_reference_attribute,
+ product_type_product_reference_attribute,
+ product_type_variant_reference_attribute,
+ page,
+ product,
+ variant,
+ category,
+ permission_manage_products,
+):
+ # given
+ product_type.product_attributes.clear()
+ product_type.product_attributes.add(
+ product_type_page_single_reference_attribute,
+ product_type_product_reference_attribute,
+ product_type_variant_reference_attribute,
+ )
+
+ product_type_page_single_reference_attribute.reference_page_types.add(
+ page.page_type
+ )
+ product_type_product_reference_attribute.reference_product_types.add(
+ product.product_type
+ )
+ product_type_variant_reference_attribute.reference_product_types.add(
+ variant.product.product_type
+ )
+
+ page_ref_attr_id = graphene.Node.to_global_id(
+ "Attribute", product_type_page_single_reference_attribute.id
+ )
+ product_ref_attr_id = graphene.Node.to_global_id(
+ "Attribute", product_type_product_reference_attribute.id
+ )
+ variant_ref_attr_id = graphene.Node.to_global_id(
+ "Attribute", product_type_variant_reference_attribute.id
+ )
+ page_ref = graphene.Node.to_global_id("Page", page.pk)
+ product_ref = graphene.Node.to_global_id("Product", product.pk)
+ variant_ref = graphene.Node.to_global_id("ProductVariant", variant.pk)
+
+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+ category_id = graphene.Node.to_global_id("Category", category.pk)
+
+ product_name_1 = "test name 1"
+ product_name_2 = "test name 2"
+ base_product_slug = "product-test-slug"
+
+ products = [
+ {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name_1,
+ "slug": f"{base_product_slug}-1",
+ "attributes": [{"id": page_ref_attr_id, "reference": page_ref}],
+ },
+ {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name_2,
+ "slug": f"{base_product_slug}-2",
+ "attributes": [{"id": product_ref_attr_id, "references": [product_ref]}],
+ },
+ {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": "test name 3",
+ "slug": f"{base_product_slug}-3",
+ "attributes": [{"id": variant_ref_attr_id, "references": [variant_ref]}],
+ },
+ ]
+
+ # when
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_graphql(
+ PRODUCT_BULK_CREATE_MUTATION, {"products": products}
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productBulkCreate"]
+
+ # then
+ assert not data["results"][0]["errors"]
+ assert not data["results"][1]["errors"]
+ assert not data["results"][2]["errors"]
+ assert data["count"] == 3
+
+ expected_attributes = [
+ {
+ "attribute": {"slug": product_type_page_single_reference_attribute.slug},
+ "values": [{"reference": page_ref, "value": ""}],
+ },
+ {
+ "attribute": {"slug": product_type_product_reference_attribute.slug},
+ "values": [{"reference": product_ref, "value": ""}],
+ },
+ {
+ "attribute": {"slug": product_type_variant_reference_attribute.slug},
+ "values": [{"reference": variant_ref, "value": ""}],
+ },
+ ]
+ expected_assigned_attributes = [
+ {
+ "attribute": {"slug": product_type_page_single_reference_attribute.slug},
+ "page": {"slug": page.slug},
+ },
+ {
+ "attribute": {"slug": product_type_product_reference_attribute.slug},
+ "products": [{"slug": product.slug}],
+ },
+ {
+ "attribute": {"slug": product_type_variant_reference_attribute.slug},
+ "variants": [{"sku": variant.sku}],
+ },
+ ]
+
+ for i, result in enumerate(data["results"]):
+ assert expected_attributes[i] in result["product"]["attributes"]
+ assert (
+ expected_assigned_attributes[i] in result["product"]["assignedAttributes"]
+ )
+
+
+def test_product_bulk_create_with_reference_attributes_refs_not_in_available_choices(
+ staff_api_client,
+ product_type,
+ product_type_page_reference_attribute,
+ product_type_product_single_reference_attribute,
+ product_type_variant_reference_attribute,
+ page,
+ product,
+ variant,
+ category,
+ permission_manage_products,
+ product_type_with_variant_attributes,
+ page_type_list,
+):
+ # given
+ product_type.product_attributes.clear()
+ product_type.product_attributes.add(
+ product_type_page_reference_attribute,
+ product_type_product_single_reference_attribute,
+ product_type_variant_reference_attribute,
+ )
+
+ product_type_page_reference_attribute.reference_page_types.add(page_type_list[1])
+ product_type_product_single_reference_attribute.reference_product_types.add(
+ product_type_with_variant_attributes
+ )
+ product_type_variant_reference_attribute.reference_product_types.add(
+ product_type_with_variant_attributes
+ )
+
+ page_ref_attr_id = graphene.Node.to_global_id(
+ "Attribute", product_type_page_reference_attribute.id
+ )
+ product_ref_attr_id = graphene.Node.to_global_id(
+ "Attribute", product_type_product_single_reference_attribute.id
+ )
+ variant_ref_attr_id = graphene.Node.to_global_id(
+ "Attribute", product_type_variant_reference_attribute.id
+ )
+ page_ref = graphene.Node.to_global_id("Page", page.pk)
+ product_ref = graphene.Node.to_global_id("Product", product.pk)
+ variant_ref = graphene.Node.to_global_id("ProductVariant", variant.pk)
+
+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+ category_id = graphene.Node.to_global_id("Category", category.pk)
+
+ product_name_1 = "test name 1"
+ product_name_2 = "test name 2"
+ base_product_slug = "product-test-slug"
+
+ products = [
+ {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name_1,
+ "slug": f"{base_product_slug}-1",
+ "attributes": [{"id": page_ref_attr_id, "references": [page_ref]}],
+ },
+ {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name_2,
+ "slug": f"{base_product_slug}-2",
+ "attributes": [{"id": product_ref_attr_id, "reference": product_ref}],
+ },
+ {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": "test name 3",
+ "slug": f"{base_product_slug}-3",
+ "attributes": [{"id": variant_ref_attr_id, "references": [variant_ref]}],
+ },
+ ]
+
+ # when
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_graphql(
+ PRODUCT_BULK_CREATE_MUTATION, {"products": products}
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productBulkCreate"]
+
+ # then
+ assert len(data["results"][0]["errors"]) == 1
+ assert len(data["results"][1]["errors"]) == 1
+ assert len(data["results"][2]["errors"]) == 1
+ assert data["count"] == 0
+
+ for result in data["results"]:
+ assert len(result["errors"]) == 1
+ assert result["errors"][0]["code"] == ProductBulkCreateErrorCode.INVALID.name
+ assert result["errors"][0]["path"] == "attributes"
+
+
def test_product_bulk_create_with_attributes_using_external_refs(
staff_api_client,
product_type,
diff --git a/saleor/graphql/product/tests/mutations/test_product_create.py b/saleor/graphql/product/tests/mutations/test_product_create.py
index e2fbf78cb6..15fed93e93 100644
--- a/saleor/graphql/product/tests/mutations/test_product_create.py
+++ b/saleor/graphql/product/tests/mutations/test_product_create.py
@@ -1813,6 +1813,87 @@ def test_create_product_with_page_reference_attribute(
assert expected_assigned_attribute in assigned_attributes
+def test_create_product_with_page_reference_attribute_and_reference_types(
+ staff_api_client,
+ product_type,
+ category,
+ color_attribute,
+ product_type_page_reference_attribute,
+ permission_manage_products,
+ page,
+):
+ query = CREATE_PRODUCT_MUTATION
+
+ values_count = product_type_page_reference_attribute.values.count()
+ product_type_page_reference_attribute.reference_page_types.add(page.page_type)
+
+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+ category_id = graphene.Node.to_global_id("Category", category.pk)
+ product_name = "test name"
+ product_slug = "product-test-slug"
+
+ # Add second attribute
+ product_type.product_attributes.add(product_type_page_reference_attribute)
+ reference_attr_id = graphene.Node.to_global_id(
+ "Attribute", product_type_page_reference_attribute.id
+ )
+ reference = graphene.Node.to_global_id("Page", page.pk)
+
+ # test creating root product
+ variables = {
+ "input": {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name,
+ "slug": product_slug,
+ "attributes": [{"id": reference_attr_id, "references": [reference]}],
+ }
+ }
+
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productCreate"]
+ assert data["errors"] == []
+ assert data["product"]["name"] == product_name
+ assert data["product"]["slug"] == product_slug
+ assert data["product"]["productType"]["name"] == product_type.name
+ assert data["product"]["category"]["name"] == category.name
+ _, product_id = graphene.Node.from_global_id(data["product"]["id"])
+ expected_attributes_data = [
+ {"attribute": {"slug": color_attribute.slug}, "values": []},
+ {
+ "attribute": {"slug": product_type_page_reference_attribute.slug},
+ "values": [
+ {
+ "slug": f"{product_id}_{page.id}",
+ "name": page.title,
+ "file": None,
+ "richText": None,
+ "plainText": None,
+ "boolean": None,
+ "date": None,
+ "dateTime": None,
+ "reference": reference,
+ }
+ ],
+ },
+ ]
+ for attr_data in data["product"]["attributes"]:
+ assert attr_data in expected_attributes_data
+
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_page_ref_assigned_attribute = {
+ "attribute": {"slug": product_type_page_reference_attribute.slug},
+ "pages": [{"slug": page.slug}],
+ }
+ assert expected_page_ref_assigned_attribute in assigned_attributes
+
+ product_type_page_reference_attribute.refresh_from_db()
+ assert product_type_page_reference_attribute.values.count() == values_count + 1
+
+
def test_create_product_with_product_reference_attribute(
staff_api_client,
product_type,
@@ -1893,6 +1974,89 @@ def test_create_product_with_product_reference_attribute(
assert expected_assigned_attribute in assigned_attributes
+def test_create_product_with_product_reference_attribute_and_reference_types(
+ staff_api_client,
+ product_type,
+ category,
+ color_attribute,
+ product_type_product_reference_attribute,
+ permission_manage_products,
+ product,
+):
+ query = CREATE_PRODUCT_MUTATION
+
+ values_count = product_type_product_reference_attribute.values.count()
+ product_type_product_reference_attribute.reference_product_types.add(
+ product.product_type
+ )
+
+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+ category_id = graphene.Node.to_global_id("Category", category.pk)
+ product_name = "test name"
+ product_slug = "product-test-slug"
+
+ # Add second attribute
+ product_type.product_attributes.add(product_type_product_reference_attribute)
+ reference_attr_id = graphene.Node.to_global_id(
+ "Attribute", product_type_product_reference_attribute.id
+ )
+ reference = graphene.Node.to_global_id("Product", product.pk)
+
+ # test creating root product
+ variables = {
+ "input": {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name,
+ "slug": product_slug,
+ "attributes": [{"id": reference_attr_id, "references": [reference]}],
+ }
+ }
+
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productCreate"]
+ assert data["errors"] == []
+ assert data["product"]["name"] == product_name
+ assert data["product"]["slug"] == product_slug
+ assert data["product"]["productType"]["name"] == product_type.name
+ assert data["product"]["category"]["name"] == category.name
+ _, product_id = graphene.Node.from_global_id(data["product"]["id"])
+ expected_attributes_data = [
+ {"attribute": {"slug": color_attribute.slug}, "values": []},
+ {
+ "attribute": {"slug": product_type_product_reference_attribute.slug},
+ "values": [
+ {
+ "slug": f"{product_id}_{product.id}",
+ "name": product.name,
+ "file": None,
+ "richText": None,
+ "plainText": None,
+ "boolean": None,
+ "date": None,
+ "dateTime": None,
+ "reference": reference,
+ }
+ ],
+ },
+ ]
+ for attr_data in data["product"]["attributes"]:
+ assert attr_data in expected_attributes_data
+
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_page_ref_assigned_attribute = {
+ "attribute": {"slug": product_type_product_reference_attribute.slug},
+ "products": [{"slug": product.slug}],
+ }
+ assert expected_page_ref_assigned_attribute in assigned_attributes
+
+ product_type_product_reference_attribute.refresh_from_db()
+ assert product_type_product_reference_attribute.values.count() == values_count + 1
+
+
def test_create_product_with_variant_reference_attribute(
staff_api_client,
product_type,
@@ -1977,6 +2141,93 @@ def test_create_product_with_variant_reference_attribute(
assert expected_assigned_attribute in assigned_attributes
+def test_create_product_with_variant_reference_attribute_and_reference_types(
+ staff_api_client,
+ product_type,
+ category,
+ color_attribute,
+ product_type_variant_reference_attribute,
+ permission_manage_products,
+ variant,
+):
+ # given
+ query = CREATE_PRODUCT_MUTATION
+
+ values_count = product_type_variant_reference_attribute.values.count()
+ product_type_variant_reference_attribute.reference_product_types.add(
+ variant.product.product_type
+ )
+
+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+ category_id = graphene.Node.to_global_id("Category", category.pk)
+ product_name = "test name"
+ product_slug = "product-test-slug"
+
+ # Add second attribute
+ product_type.product_attributes.add(product_type_variant_reference_attribute)
+ reference_attr_id = graphene.Node.to_global_id(
+ "Attribute", product_type_variant_reference_attribute.id
+ )
+ reference = graphene.Node.to_global_id("ProductVariant", variant.pk)
+
+ # test creating root product
+ variables = {
+ "input": {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name,
+ "slug": product_slug,
+ "attributes": [{"id": reference_attr_id, "references": [reference]}],
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["productCreate"]
+ assert data["errors"] == []
+ assert data["product"]["name"] == product_name
+ assert data["product"]["slug"] == product_slug
+ assert data["product"]["productType"]["name"] == product_type.name
+ assert data["product"]["category"]["name"] == category.name
+ _, product_id = graphene.Node.from_global_id(data["product"]["id"])
+ expected_attributes_data = [
+ {"attribute": {"slug": color_attribute.slug}, "values": []},
+ {
+ "attribute": {"slug": product_type_variant_reference_attribute.slug},
+ "values": [
+ {
+ "slug": f"{product_id}_{variant.id}",
+ "name": f"{variant.product.name}: {variant.name}",
+ "file": None,
+ "richText": None,
+ "plainText": None,
+ "boolean": None,
+ "date": None,
+ "dateTime": None,
+ "reference": reference,
+ }
+ ],
+ },
+ ]
+ for attr_data in data["product"]["attributes"]:
+ assert attr_data in expected_attributes_data
+
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_page_ref_assigned_attribute = {
+ "attribute": {"slug": product_type_variant_reference_attribute.slug},
+ "variants": [{"sku": variant.sku}],
+ }
+ assert expected_page_ref_assigned_attribute in assigned_attributes
+
+ product_type_variant_reference_attribute.refresh_from_db()
+ assert product_type_variant_reference_attribute.values.count() == values_count + 1
+
+
def test_create_product_with_category_reference_attribute(
staff_api_client,
product_type,
@@ -2730,6 +2981,169 @@ def test_create_product_with_product_reference_attribute_required_no_references(
]
+def test_create_product_with_page_reference_attribute_ref_not_in_available_choices(
+ staff_api_client,
+ product_type,
+ category,
+ product_type_page_reference_attribute,
+ permission_manage_products,
+ page,
+ page_type_list,
+):
+ query = CREATE_PRODUCT_MUTATION
+
+ product_type_page_reference_attribute.reference_page_types.add(page_type_list[1])
+
+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+ category_id = graphene.Node.to_global_id("Category", category.pk)
+ product_name = "test name"
+ product_slug = "product-test-slug"
+ reference = graphene.Node.to_global_id("Page", page.pk)
+
+ # Add second attribute
+ product_type.product_attributes.add(product_type_page_reference_attribute)
+ reference_attr_id = graphene.Node.to_global_id(
+ "Attribute", product_type_page_reference_attribute.id
+ )
+
+ # test creating root product
+ variables = {
+ "input": {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name,
+ "slug": product_slug,
+ "attributes": [{"id": reference_attr_id, "references": [reference]}],
+ }
+ }
+
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productCreate"]
+ errors = data["errors"]
+ assert not data["product"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == ProductErrorCode.INVALID.name
+ assert errors[0]["field"] == "attributes"
+ assert errors[0]["attributes"] == [
+ graphene.Node.to_global_id(
+ "Attribute", product_type_page_reference_attribute.pk
+ )
+ ]
+
+
+def test_create_product_with_product_reference_attribute_ref_not_in_available_choices(
+ staff_api_client,
+ product_type,
+ category,
+ product_type_product_reference_attribute,
+ permission_manage_products,
+ product,
+ product_type_with_variant_attributes,
+):
+ query = CREATE_PRODUCT_MUTATION
+
+ product_type_product_reference_attribute.reference_product_types.add(
+ product_type_with_variant_attributes
+ )
+
+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+ category_id = graphene.Node.to_global_id("Category", category.pk)
+ product_name = "test name"
+ product_slug = "product-test-slug"
+ reference = graphene.Node.to_global_id("Product", product.pk)
+
+ # Add second attribute
+ product_type.product_attributes.add(product_type_product_reference_attribute)
+ reference_attr_id = graphene.Node.to_global_id(
+ "Attribute", product_type_product_reference_attribute.id
+ )
+
+ # test creating root product
+ variables = {
+ "input": {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name,
+ "slug": product_slug,
+ "attributes": [{"id": reference_attr_id, "references": [reference]}],
+ }
+ }
+
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productCreate"]
+ errors = data["errors"]
+ assert not data["product"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == ProductErrorCode.INVALID.name
+ assert errors[0]["field"] == "attributes"
+ assert errors[0]["attributes"] == [
+ graphene.Node.to_global_id(
+ "Attribute", product_type_product_reference_attribute.pk
+ )
+ ]
+
+
+def test_create_product_with_variant_reference_attribute_ref_not_in_available_choices(
+ staff_api_client,
+ product_type,
+ category,
+ product_type_variant_reference_attribute,
+ permission_manage_products,
+ variant,
+ product_type_with_variant_attributes,
+):
+ query = CREATE_PRODUCT_MUTATION
+
+ product_type_variant_reference_attribute.reference_product_types.add(
+ product_type_with_variant_attributes
+ )
+
+ product_type_id = graphene.Node.to_global_id("ProductType", product_type.pk)
+ category_id = graphene.Node.to_global_id("Category", category.pk)
+ product_name = "test name"
+ product_slug = "product-test-slug"
+ reference = graphene.Node.to_global_id("ProductVariant", variant.pk)
+
+ # Add second attribute
+ product_type.product_attributes.add(product_type_variant_reference_attribute)
+ reference_attr_id = graphene.Node.to_global_id(
+ "Attribute", product_type_variant_reference_attribute.id
+ )
+
+ # test creating root product
+ variables = {
+ "input": {
+ "productType": product_type_id,
+ "category": category_id,
+ "name": product_name,
+ "slug": product_slug,
+ "attributes": [{"id": reference_attr_id, "references": [reference]}],
+ }
+ }
+
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productCreate"]
+ errors = data["errors"]
+ assert not data["product"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == ProductErrorCode.INVALID.name
+ assert errors[0]["field"] == "attributes"
+ assert errors[0]["attributes"] == [
+ graphene.Node.to_global_id(
+ "Attribute", product_type_variant_reference_attribute.pk
+ )
+ ]
+
+
def test_create_product_no_values_given(
staff_api_client,
product_type,
diff --git a/saleor/graphql/product/tests/mutations/test_product_update.py b/saleor/graphql/product/tests/mutations/test_product_update.py
index 60e13da333..f3a075d9a4 100644
--- a/saleor/graphql/product/tests/mutations/test_product_update.py
+++ b/saleor/graphql/product/tests/mutations/test_product_update.py
@@ -1507,6 +1507,161 @@ def test_update_product_with_single_reference_attribute_value(
assert expected_assigned_collection_attribute in assigned_attributes
+@patch("saleor.plugins.manager.PluginsManager.product_updated")
+def test_update_product_with_page_reference_attribute_value_and_reference_types(
+ updated_webhook_mock,
+ staff_api_client,
+ product_type_page_reference_attribute,
+ product,
+ product_type,
+ page,
+ permission_manage_products,
+):
+ # given
+ query = MUTATION_UPDATE_PRODUCT
+
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+
+ attribute_id = graphene.Node.to_global_id(
+ "Attribute", product_type_page_reference_attribute.pk
+ )
+ product_type.product_attributes.add(product_type_page_reference_attribute)
+ product_type_page_reference_attribute.reference_page_types.add(page.page_type)
+
+ values_count = product_type_page_reference_attribute.values.count()
+
+ reference = graphene.Node.to_global_id("Page", page.pk)
+
+ variables = {
+ "productId": product_id,
+ "input": {"attributes": [{"id": attribute_id, "references": [reference]}]},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["productUpdate"]
+ assert data["errors"] == []
+
+ attributes = data["product"]["attributes"]
+
+ assert len(attributes) == 2
+ expected_file_att_data = {
+ "attribute": {
+ "id": attribute_id,
+ "name": product_type_page_reference_attribute.name,
+ },
+ "values": [
+ {
+ "id": ANY,
+ "name": page.title,
+ "slug": f"{product.id}_{page.id}",
+ "file": None,
+ "reference": reference,
+ "boolean": None,
+ "plainText": None,
+ }
+ ],
+ }
+ assert expected_file_att_data in attributes
+
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_page_ref_assigned_attribute = {
+ "attribute": {"slug": product_type_page_reference_attribute.slug},
+ "pages": [{"slug": page.slug}],
+ }
+ assert expected_page_ref_assigned_attribute in assigned_attributes
+
+ updated_webhook_mock.assert_called_once_with(product)
+
+ product_type_page_reference_attribute.refresh_from_db()
+ assert product_type_page_reference_attribute.values.count() == values_count + 1
+
+
+@patch("saleor.plugins.manager.PluginsManager.product_updated")
+def test_update_product_with_variant_single_ref_attribute_value_and_reference_types(
+ updated_webhook_mock,
+ staff_api_client,
+ product_type_variant_single_reference_attribute,
+ product,
+ product_type,
+ variant,
+ permission_manage_products,
+):
+ # given
+ query = MUTATION_UPDATE_PRODUCT
+
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+
+ attribute_id = graphene.Node.to_global_id(
+ "Attribute", product_type_variant_single_reference_attribute.pk
+ )
+ product_type.product_attributes.add(product_type_variant_single_reference_attribute)
+ product_type_variant_single_reference_attribute.reference_product_types.add(
+ product_type
+ )
+
+ values_count = product_type_variant_single_reference_attribute.values.count()
+
+ reference = graphene.Node.to_global_id("ProductVariant", variant.pk)
+
+ variables = {
+ "productId": product_id,
+ "input": {"attributes": [{"id": attribute_id, "reference": reference}]},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["productUpdate"]
+ assert data["errors"] == []
+
+ attributes = data["product"]["attributes"]
+
+ assert len(attributes) == 2
+ expected_file_att_data = {
+ "attribute": {
+ "id": attribute_id,
+ "name": product_type_variant_single_reference_attribute.name,
+ },
+ "values": [
+ {
+ "id": ANY,
+ "name": f"{variant.product.name}: {variant.name}",
+ "slug": f"{product.id}_{variant.id}",
+ "file": None,
+ "reference": reference,
+ "boolean": None,
+ "plainText": None,
+ }
+ ],
+ }
+ assert expected_file_att_data in attributes
+
+ assigned_attributes = data["product"]["assignedAttributes"]
+ expected_page_ref_assigned_attribute = {
+ "attribute": {"slug": product_type_variant_single_reference_attribute.slug},
+ "variant": {"sku": variant.sku},
+ }
+ assert expected_page_ref_assigned_attribute in assigned_attributes
+
+ updated_webhook_mock.assert_called_once_with(product)
+
+ product_type_variant_single_reference_attribute.refresh_from_db()
+ assert (
+ product_type_variant_single_reference_attribute.values.count()
+ == values_count + 1
+ )
+
+
def test_update_product_without_supplying_required_product_attribute(
staff_api_client, product, permission_manage_products, color_attribute
):
@@ -2023,6 +2178,53 @@ def test_update_product_with_collection_reference_attribute_value(
updated_webhook_mock.assert_called_once_with(product)
+@patch("saleor.plugins.manager.PluginsManager.product_updated")
+def test_update_product_with_page_reference_attribute_value_not_in_available_choices(
+ updated_webhook_mock,
+ staff_api_client,
+ product_type_page_reference_attribute,
+ product,
+ product_type,
+ page,
+ page_type_list,
+ permission_manage_products,
+):
+ # given
+ query = MUTATION_UPDATE_PRODUCT
+
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+
+ attribute_id = graphene.Node.to_global_id(
+ "Attribute", product_type_page_reference_attribute.pk
+ )
+ product_type.product_attributes.add(product_type_page_reference_attribute)
+ product_type_page_reference_attribute.reference_page_types.add(page_type_list[0])
+
+ values_count = product_type_page_reference_attribute.values.count()
+
+ reference = graphene.Node.to_global_id("Page", page.pk)
+
+ variables = {
+ "productId": product_id,
+ "input": {"attributes": [{"id": attribute_id, "references": [reference]}]},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["productUpdate"]
+ assert not data["product"]
+ assert data["errors"]
+ assert len(data["errors"]) == 1
+ assert data["errors"][0]["field"] == "attributes"
+ assert data["errors"][0]["code"] == ProductErrorCode.INVALID.name
+ assert product_type_page_reference_attribute.values.count() == values_count
+
+
def test_update_product_with_attribute_without_id_or_external_ref(
staff_api_client, product, permission_manage_products, color_attribute
):
diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.py b/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.py
index 6df2b6c768..0bb9518023 100644
--- a/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.py
+++ b/saleor/graphql/product/tests/mutations/test_product_variant_bulk_create.py
@@ -964,6 +964,216 @@ def test_product_variant_bulk_create_with_single_reference_attribute(
assert product_variant_count + 1 == ProductVariant.objects.count()
+def test_product_variant_bulk_create_with_ref_attributes_and_reference_types_defined(
+ staff_api_client,
+ product,
+ product_type,
+ product_type_page_single_reference_attribute,
+ product_type_product_reference_attribute,
+ product_type_variant_reference_attribute,
+ page,
+ variant,
+ permission_manage_products,
+):
+ # given
+ product_type.variant_attributes.clear()
+ product_type.variant_attributes.add(
+ product_type_page_single_reference_attribute,
+ product_type_product_reference_attribute,
+ product_type_variant_reference_attribute,
+ )
+
+ product_type_page_single_reference_attribute.reference_page_types.add(
+ page.page_type
+ )
+ product_type_product_reference_attribute.reference_product_types.add(
+ product.product_type
+ )
+ product_type_variant_reference_attribute.reference_product_types.add(
+ variant.product.product_type
+ )
+
+ page_ref_attr_id = graphene.Node.to_global_id(
+ "Attribute", product_type_page_single_reference_attribute.id
+ )
+ product_ref_attr_id = graphene.Node.to_global_id(
+ "Attribute", product_type_product_reference_attribute.id
+ )
+ variant_ref_attr_id = graphene.Node.to_global_id(
+ "Attribute", product_type_variant_reference_attribute.id
+ )
+ page_ref = graphene.Node.to_global_id("Page", page.pk)
+ product_ref = graphene.Node.to_global_id("Product", product.pk)
+ variant_ref = graphene.Node.to_global_id("ProductVariant", variant.pk)
+
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+
+ sku1 = str(uuid4())[:12]
+ sku2 = str(uuid4())[:12]
+ sku3 = str(uuid4())[:12]
+
+ variants = [
+ {
+ "sku": sku1,
+ "attributes": [{"id": page_ref_attr_id, "reference": page_ref}],
+ },
+ {
+ "sku": sku2,
+ "attributes": [{"id": product_ref_attr_id, "references": [product_ref]}],
+ },
+ {
+ "sku": sku3,
+ "attributes": [{"id": variant_ref_attr_id, "references": [variant_ref]}],
+ },
+ ]
+
+ # when
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_BULK_CREATE_MUTATION,
+ {"productId": product_id, "variants": variants},
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productVariantBulkCreate"]
+
+ # then
+ assert not data["results"][0]["errors"]
+ assert not data["results"][1]["errors"]
+ assert not data["results"][2]["errors"]
+ assert data["count"] == 3
+
+ expected_attributes = [
+ {
+ "slug": product_type_page_single_reference_attribute.slug,
+ "reference": page_ref,
+ },
+ {
+ "slug": product_type_product_reference_attribute.slug,
+ "reference": product_ref,
+ },
+ {
+ "slug": product_type_variant_reference_attribute.slug,
+ "reference": variant_ref,
+ },
+ ]
+ expected_assigned_attributes = [
+ {
+ "attribute": {"slug": product_type_page_single_reference_attribute.slug},
+ "page": {"slug": page.slug},
+ },
+ {
+ "attribute": {"slug": product_type_product_reference_attribute.slug},
+ "products": [{"slug": product.slug}],
+ },
+ {
+ "attribute": {"slug": product_type_variant_reference_attribute.slug},
+ "variants": [{"sku": variant.sku}],
+ },
+ ]
+
+ for i, result in enumerate(data["results"]):
+ matching_attribute = next(
+ attr
+ for attr in result["productVariant"]["attributes"]
+ if attr["attribute"]["slug"] == expected_attributes[i]["slug"]
+ )
+ assert len(matching_attribute["values"]) == 1
+ assert (
+ matching_attribute["values"][0]["reference"]
+ == expected_attributes[i]["reference"]
+ )
+ assert (
+ expected_assigned_attributes[i]
+ in result["productVariant"]["assignedAttributes"]
+ )
+
+
+def test_product_variant_bulk_create_with_ref_attributes_refs_not_in_available_choices(
+ staff_api_client,
+ product,
+ product_type,
+ product_type_page_single_reference_attribute,
+ product_type_product_reference_attribute,
+ product_type_variant_reference_attribute,
+ page,
+ variant,
+ permission_manage_products,
+ product_type_with_variant_attributes,
+ page_type_list,
+):
+ # given
+ product_type.variant_attributes.clear()
+ product_type.variant_attributes.add(
+ product_type_page_single_reference_attribute,
+ product_type_product_reference_attribute,
+ product_type_variant_reference_attribute,
+ )
+
+ product_type_page_single_reference_attribute.reference_page_types.add(
+ page_type_list[1]
+ )
+ product_type_product_reference_attribute.reference_product_types.add(
+ product_type_with_variant_attributes
+ )
+ product_type_variant_reference_attribute.reference_product_types.add(
+ product_type_with_variant_attributes
+ )
+
+ page_ref_attr_id = graphene.Node.to_global_id(
+ "Attribute", product_type_page_single_reference_attribute.id
+ )
+ product_ref_attr_id = graphene.Node.to_global_id(
+ "Attribute", product_type_product_reference_attribute.id
+ )
+ variant_ref_attr_id = graphene.Node.to_global_id(
+ "Attribute", product_type_variant_reference_attribute.id
+ )
+ page_ref = graphene.Node.to_global_id("Page", page.pk)
+ product_ref = graphene.Node.to_global_id("Product", product.pk)
+ variant_ref = graphene.Node.to_global_id("ProductVariant", variant.pk)
+
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+
+ sku1 = str(uuid4())[:12]
+ sku2 = str(uuid4())[:12]
+ sku3 = str(uuid4())[:12]
+
+ variants = [
+ {
+ "sku": sku1,
+ "attributes": [{"id": page_ref_attr_id, "reference": page_ref}],
+ },
+ {
+ "sku": sku2,
+ "attributes": [{"id": product_ref_attr_id, "references": [product_ref]}],
+ },
+ {
+ "sku": sku3,
+ "attributes": [{"id": variant_ref_attr_id, "references": [variant_ref]}],
+ },
+ ]
+
+ # when
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_BULK_CREATE_MUTATION,
+ {"productId": product_id, "variants": variants},
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productVariantBulkCreate"]
+
+ # then
+ assert len(data["results"][0]["errors"]) == 1
+ assert len(data["results"][1]["errors"]) == 1
+ assert len(data["results"][2]["errors"]) == 1
+ assert data["count"] == 0
+
+ for result in data["results"]:
+ assert len(result["errors"]) == 1
+ assert result["errors"][0]["code"] == ProductVariantBulkErrorCode.INVALID.name
+ assert result["errors"][0]["path"] == "attributes"
+
+
def test_product_variant_bulk_create_with_dropdown_attribute(
staff_api_client,
product,
diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_bulk_update.py b/saleor/graphql/product/tests/mutations/test_product_variant_bulk_update.py
index c5f177200e..63090ccc2c 100644
--- a/saleor/graphql/product/tests/mutations/test_product_variant_bulk_update.py
+++ b/saleor/graphql/product/tests/mutations/test_product_variant_bulk_update.py
@@ -26,63 +26,176 @@ PRODUCT_VARIANT_BULK_UPDATE_MUTATION = """
$errorPolicy: ErrorPolicyEnum
) {
productVariantBulkUpdate(
- variants: $variants, product: $productId, errorPolicy: $errorPolicy
- ) {
- results{
- errors {
- field
- path
- message
- code
- warehouses
- channels
+ variants: $variants,
+ product: $productId,
+ errorPolicy: $errorPolicy
+ ) {
+ results {
+ errors {
+ field
+ path
+ message
+ code
+ warehouses
+ channels
+ }
+ productVariant {
+ metadata {
+ key
+ value
+ }
+ id
+ name
+ sku
+ stocks {
+ warehouse {
+ slug
+ }
+ quantity
+ }
+ channelListings {
+ channel {
+ slug
+ }
+ price {
+ currency
+ amount
+ }
+ costPrice {
+ currency
+ amount
+ }
+ priorPrice {
+ currency
+ amount
+ }
+ preorderThreshold {
+ quantity
+ }
}
- productVariant{
- metadata {
- key
+ attributes {
+ attribute {
+ slug
+ }
+ values {
value
+ reference
}
- id
- name
- sku
- stocks {
- warehouse {
+ }
+ assignedAttributes(limit: 10) {
+ attribute {
+ slug
+ }
+ ... on AssignedNumericAttribute {
+ value
+ }
+ ... on AssignedTextAttribute {
+ text: value
+ }
+ ... on AssignedPlainTextAttribute {
+ plain_text: value
+ }
+ ... on AssignedFileAttribute {
+ file: value {
+ contentType
+ url
+ }
+ }
+ ... on AssignedMultiPageReferenceAttribute {
+ pages: value {
slug
}
- quantity
}
- channelListings {
- channel {
+ ... on AssignedMultiProductReferenceAttribute {
+ products: value {
+ slug
+ }
+ }
+ ... on AssignedMultiCategoryReferenceAttribute {
+ categories: value {
+ slug
+ }
+ }
+ ... on AssignedMultiCollectionReferenceAttribute {
+ collections: value {
+ slug
+ }
+ }
+ ... on AssignedSinglePageReferenceAttribute {
+ page: value {
+ slug
+ }
+ }
+ ... on AssignedSingleProductReferenceAttribute {
+ product: value {
+ slug
+ }
+ }
+ ... on AssignedSingleProductVariantReferenceAttribute {
+ variant: value {
+ sku
+ }
+ }
+ ... on AssignedSingleCategoryReferenceAttribute {
+ category: value {
slug
}
- price {
- currency
- amount
+ }
+ ... on AssignedSingleCollectionReferenceAttribute {
+ collection: value {
+ slug
+ }
+ }
+ ... on AssignedMultiProductVariantReferenceAttribute {
+ variants: value {
+ sku
}
- costPrice {
- currency
- amount
+ }
+ ... on AssignedSingleChoiceAttribute {
+ choice: value {
+ name
+ slug
}
- priorPrice {
- currency
- amount
+ }
+ ... on AssignedMultiChoiceAttribute {
+ multi: value {
+ name
+ slug
}
- preorderThreshold {
- quantity
+ }
+ ... on AssignedSwatchAttribute {
+ swatch: value {
+ name
+ slug
+ hexColor
+ file {
+ url
+ contentType
+ }
}
}
- preorder {
- globalThreshold
- endDate
+ ... on AssignedBooleanAttribute {
+ bool: value
+ }
+ ... on AssignedDateAttribute {
+ date: value
+ }
+ ... on AssignedDateTimeAttribute {
+ datetime: value
}
}
+ preorder {
+ globalThreshold
+ endDate
+ }
}
- count
- errors{
- field
- message
- code
- }
+ }
+ count
+ errors {
+ field
+ message
+ code
+ }
}
}
"""
@@ -804,6 +917,201 @@ def test_product_variant_bulk_update_attributes(
assert rule.variants_dirty
+def test_product_variant_bulk_update_with_ref_attributes_and_reference_types_defined(
+ staff_api_client,
+ product,
+ product_type,
+ product_type_page_single_reference_attribute,
+ product_type_product_reference_attribute,
+ product_type_variant_reference_attribute,
+ page,
+ variant,
+ permission_manage_products,
+):
+ # given
+ product_type.variant_attributes.clear()
+ product_type.variant_attributes.add(
+ product_type_page_single_reference_attribute,
+ product_type_product_reference_attribute,
+ product_type_variant_reference_attribute,
+ )
+
+ product_type_page_single_reference_attribute.reference_page_types.add(
+ page.page_type
+ )
+ product_type_product_reference_attribute.reference_product_types.add(
+ product.product_type
+ )
+ product_type_variant_reference_attribute.reference_product_types.add(
+ variant.product.product_type
+ )
+
+ page_ref_attr_id = graphene.Node.to_global_id(
+ "Attribute", product_type_page_single_reference_attribute.id
+ )
+ product_ref_attr_id = graphene.Node.to_global_id(
+ "Attribute", product_type_product_reference_attribute.id
+ )
+ variant_ref_attr_id = graphene.Node.to_global_id(
+ "Attribute", product_type_variant_reference_attribute.id
+ )
+ page_ref = graphene.Node.to_global_id("Page", page.pk)
+ product_ref = graphene.Node.to_global_id("Product", product.pk)
+ variant_ref = graphene.Node.to_global_id("ProductVariant", variant.pk)
+
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+
+ variants = [
+ {
+ "id": variant_id,
+ "attributes": [{"id": page_ref_attr_id, "reference": page_ref}],
+ },
+ {
+ "id": variant_id,
+ "attributes": [{"id": product_ref_attr_id, "references": [product_ref]}],
+ },
+ {
+ "id": variant_id,
+ "attributes": [{"id": variant_ref_attr_id, "references": [variant_ref]}],
+ },
+ ]
+
+ # when
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_BULK_UPDATE_MUTATION,
+ {"productId": product_id, "variants": variants},
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productVariantBulkUpdate"]
+
+ # then
+ assert not data["results"][0]["errors"]
+ assert not data["results"][1]["errors"]
+ assert not data["results"][2]["errors"]
+ assert data["count"] == 3
+
+ expected_attributes = [
+ {
+ "attribute": {"slug": product_type_page_single_reference_attribute.slug},
+ "values": [{"reference": page_ref, "value": ""}],
+ },
+ {
+ "attribute": {"slug": product_type_product_reference_attribute.slug},
+ "values": [{"reference": product_ref, "value": ""}],
+ },
+ {
+ "attribute": {"slug": product_type_variant_reference_attribute.slug},
+ "values": [{"reference": variant_ref, "value": ""}],
+ },
+ ]
+ expected_assigned_attributes = [
+ {
+ "attribute": {"slug": product_type_page_single_reference_attribute.slug},
+ "page": {"slug": page.slug},
+ },
+ {
+ "attribute": {"slug": product_type_product_reference_attribute.slug},
+ "products": [{"slug": product.slug}],
+ },
+ {
+ "attribute": {"slug": product_type_variant_reference_attribute.slug},
+ "variants": [{"sku": variant.sku}],
+ },
+ ]
+
+ for i, result in enumerate(data["results"]):
+ assert expected_attributes[i] in result["productVariant"]["attributes"]
+ assert (
+ expected_assigned_attributes[i]
+ in result["productVariant"]["assignedAttributes"]
+ )
+
+
+def test_product_variant_bulk_update_with_ref_attributes__refs_not_in_available_choices(
+ staff_api_client,
+ product,
+ product_type,
+ product_type_page_single_reference_attribute,
+ product_type_product_reference_attribute,
+ product_type_variant_reference_attribute,
+ page,
+ variant,
+ permission_manage_products,
+ product_type_with_variant_attributes,
+ page_type_list,
+):
+ # given
+ product_type.variant_attributes.clear()
+ product_type.variant_attributes.add(
+ product_type_page_single_reference_attribute,
+ product_type_product_reference_attribute,
+ product_type_variant_reference_attribute,
+ )
+
+ product_type_page_single_reference_attribute.reference_page_types.add(
+ page_type_list[1]
+ )
+ product_type_product_reference_attribute.reference_product_types.add(
+ product_type_with_variant_attributes
+ )
+ product_type_variant_reference_attribute.reference_product_types.add(
+ product_type_with_variant_attributes
+ )
+
+ page_ref_attr_id = graphene.Node.to_global_id(
+ "Attribute", product_type_page_single_reference_attribute.id
+ )
+ product_ref_attr_id = graphene.Node.to_global_id(
+ "Attribute", product_type_product_reference_attribute.id
+ )
+ variant_ref_attr_id = graphene.Node.to_global_id(
+ "Attribute", product_type_variant_reference_attribute.id
+ )
+ page_ref = graphene.Node.to_global_id("Page", page.pk)
+ product_ref = graphene.Node.to_global_id("Product", product.pk)
+ variant_ref = graphene.Node.to_global_id("ProductVariant", variant.pk)
+
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+
+ variants = [
+ {
+ "id": variant_id,
+ "attributes": [{"id": page_ref_attr_id, "reference": page_ref}],
+ },
+ {
+ "id": variant_id,
+ "attributes": [{"id": product_ref_attr_id, "references": [product_ref]}],
+ },
+ {
+ "id": variant_id,
+ "attributes": [{"id": variant_ref_attr_id, "references": [variant_ref]}],
+ },
+ ]
+
+ # when
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ response = staff_api_client.post_graphql(
+ PRODUCT_VARIANT_BULK_UPDATE_MUTATION,
+ {"productId": product_id, "variants": variants},
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productVariantBulkUpdate"]
+
+ # then
+ assert len(data["results"][0]["errors"]) == 1
+ assert len(data["results"][1]["errors"]) == 1
+ assert len(data["results"][2]["errors"]) == 1
+ assert data["count"] == 0
+
+ for result in data["results"]:
+ assert len(result["errors"]) == 1
+ assert result["errors"][0]["code"] == ProductVariantBulkErrorCode.INVALID.name
+ assert result["errors"][0]["path"] == "attributes"
+
+
@override_settings(ENABLE_LIMITING_WEBHOOKS_FOR_IDENTICAL_PAYLOADS=True)
@mock.patch(
"saleor.graphql.product.bulk_mutations.product_variant_bulk_update.ProductVariantBulkUpdate.call_event"
diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_create.py b/saleor/graphql/product/tests/mutations/test_product_variant_create.py
index 3f186c816d..1c6ac5779e 100644
--- a/saleor/graphql/product/tests/mutations/test_product_variant_create.py
+++ b/saleor/graphql/product/tests/mutations/test_product_variant_create.py
@@ -1520,6 +1520,156 @@ def test_create_variant_with_collection_reference_attribute(
created_webhook_mock.assert_called_once_with(product.variants.last())
+def test_create_variant_with_reference_attributes_and_reference_types_defined(
+ staff_api_client,
+ product,
+ product_type,
+ product_type_page_reference_attribute,
+ product_type_product_reference_attribute,
+ product_type_variant_reference_attribute,
+ page,
+ permission_manage_products,
+ warehouse,
+ variant,
+):
+ # given
+ query = CREATE_VARIANT_MUTATION
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ sku = "1"
+
+ product_type.variant_attributes.clear()
+ product_type.variant_attributes.add(
+ product_type_page_reference_attribute,
+ product_type_product_reference_attribute,
+ product_type_variant_reference_attribute,
+ )
+
+ product_type_page_reference_attribute.reference_page_types.add(page.page_type)
+ product_type_product_reference_attribute.reference_product_types.add(
+ product.product_type
+ )
+ product_type_variant_reference_attribute.reference_product_types.add(
+ variant.product.product_type
+ )
+
+ page_ref_attr_id = graphene.Node.to_global_id(
+ "Attribute", product_type_page_reference_attribute.id
+ )
+ product_ref_attr_id = graphene.Node.to_global_id(
+ "Attribute", product_type_product_reference_attribute.id
+ )
+ variant_ref_attr_id = graphene.Node.to_global_id(
+ "Attribute", product_type_variant_reference_attribute.id
+ )
+ variant_ref = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ page_ref = graphene.Node.to_global_id("Page", page.pk)
+ product_ref = graphene.Node.to_global_id("Product", product.pk)
+
+ stocks = [
+ {
+ "warehouse": graphene.Node.to_global_id("Warehouse", warehouse.pk),
+ "quantity": 20,
+ }
+ ]
+
+ variables = {
+ "input": {
+ "product": product_id,
+ "sku": sku,
+ "stocks": stocks,
+ "attributes": [
+ {"id": page_ref_attr_id, "references": [page_ref]},
+ {"id": product_ref_attr_id, "references": [product_ref]},
+ {"id": variant_ref_attr_id, "references": [variant_ref]},
+ ],
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+
+ # then
+ content = get_graphql_content(response)["data"]["productVariantCreate"]
+
+ assert not content["errors"]
+ data = content["productVariant"]
+ assert data["sku"] == sku
+ variant_id = data["id"]
+ _, variant_pk = graphene.Node.from_global_id(variant_id)
+ assert len(data["attributes"]) == len(variables["input"]["attributes"])
+ expected_attributes_data = [
+ {
+ "attribute": {"slug": product_type_page_reference_attribute.slug},
+ "values": [
+ {
+ "slug": f"{variant_pk}_{page.id}",
+ "file": None,
+ "richText": None,
+ "plainText": None,
+ "reference": page_ref,
+ "name": page.title,
+ "boolean": None,
+ "date": None,
+ "dateTime": None,
+ }
+ ],
+ },
+ {
+ "attribute": {"slug": product_type_product_reference_attribute.slug},
+ "values": [
+ {
+ "slug": f"{variant_pk}_{product.id}",
+ "file": None,
+ "richText": None,
+ "plainText": None,
+ "reference": product_ref,
+ "name": product.name,
+ "boolean": None,
+ "date": None,
+ "dateTime": None,
+ }
+ ],
+ },
+ {
+ "attribute": {"slug": product_type_variant_reference_attribute.slug},
+ "values": [
+ {
+ "slug": f"{variant_pk}_{variant.id}",
+ "file": None,
+ "richText": None,
+ "plainText": None,
+ "reference": variant_ref,
+ "name": f"{variant.product.name}: {variant.name}",
+ "boolean": None,
+ "date": None,
+ "dateTime": None,
+ }
+ ],
+ },
+ ]
+ for attr_data in data["attributes"]:
+ assert attr_data in expected_attributes_data
+
+ assigned_attributes = data["assignedAttributes"]
+ expected_page_ref_assigned_attribute = {
+ "attribute": {"slug": product_type_page_reference_attribute.slug},
+ "pages": [{"slug": page.slug}],
+ }
+ assert expected_page_ref_assigned_attribute in assigned_attributes
+ expected_product_ref_assigned_attribute = {
+ "attribute": {"slug": product_type_product_reference_attribute.slug},
+ "products": [{"slug": product.slug}],
+ }
+ assert expected_product_ref_assigned_attribute in assigned_attributes
+ expected_variant_ref_assigned_attribute = {
+ "attribute": {"slug": product_type_variant_reference_attribute.slug},
+ "variants": [{"sku": variant.sku}],
+ }
+ assert expected_variant_ref_assigned_attribute in assigned_attributes
+
+
@patch("saleor.plugins.manager.PluginsManager.product_variant_created")
def test_create_variant_with_single_reference_attributes(
created_webhook_mock,
@@ -2017,6 +2167,95 @@ def test_create_variant_invalid_variant_attributes(
assert error in errors
+def test_create_variant_with_reference_attributes_ref_not_in_available_choices(
+ staff_api_client,
+ product,
+ product_type,
+ product_type_with_variant_attributes,
+ product_type_page_reference_attribute,
+ product_type_product_reference_attribute,
+ product_type_variant_reference_attribute,
+ page,
+ page_type_list,
+ permission_manage_products,
+ warehouse,
+ variant,
+):
+ # given
+ query = CREATE_VARIANT_MUTATION
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ sku = "1"
+
+ product_type.variant_attributes.clear()
+ product_type.variant_attributes.add(
+ product_type_page_reference_attribute,
+ product_type_product_reference_attribute,
+ product_type_variant_reference_attribute,
+ )
+
+ # assigned reference types that do not match product/page types of references
+ # that are provided in the input
+ product_type_page_reference_attribute.reference_page_types.add(page_type_list[1])
+ product_type_product_reference_attribute.reference_product_types.add(
+ product_type_with_variant_attributes
+ )
+ product_type_variant_reference_attribute.reference_product_types.add(
+ product_type_with_variant_attributes
+ )
+
+ page_ref_attr_id = graphene.Node.to_global_id(
+ "Attribute", product_type_page_reference_attribute.id
+ )
+ product_ref_attr_id = graphene.Node.to_global_id(
+ "Attribute", product_type_product_reference_attribute.id
+ )
+ variant_ref_attr_id = graphene.Node.to_global_id(
+ "Attribute", product_type_variant_reference_attribute.id
+ )
+ variant_ref = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ page_ref = graphene.Node.to_global_id("Page", page.pk)
+ product_ref = graphene.Node.to_global_id("Product", product.pk)
+
+ stocks = [
+ {
+ "warehouse": graphene.Node.to_global_id("Warehouse", warehouse.pk),
+ "quantity": 20,
+ }
+ ]
+
+ variables = {
+ "input": {
+ "product": product_id,
+ "sku": sku,
+ "stocks": stocks,
+ "attributes": [
+ {"id": page_ref_attr_id, "references": [page_ref]},
+ {"id": product_ref_attr_id, "references": [product_ref]},
+ {"id": variant_ref_attr_id, "references": [variant_ref]},
+ ],
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+
+ # then
+ data = get_graphql_content(response)["data"]["productVariantCreate"]
+
+ errors = data["errors"]
+ assert not data["productVariant"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == ProductErrorCode.INVALID.name
+ assert errors[0]["field"] == "attributes"
+ assert set(errors[0]["attributes"]) == {
+ page_ref_attr_id,
+ product_ref_attr_id,
+ variant_ref_attr_id,
+ }
+
+
@patch("saleor.plugins.manager.PluginsManager.product_variant_created")
def test_create_variant_with_rich_text_attribute(
created_webhook_mock,
diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_update.py b/saleor/graphql/product/tests/mutations/test_product_variant_update.py
index 497cb43597..d185f30218 100644
--- a/saleor/graphql/product/tests/mutations/test_product_variant_update.py
+++ b/saleor/graphql/product/tests/mutations/test_product_variant_update.py
@@ -792,6 +792,7 @@ mutation updateVariant($id: ID!, $sku: String, $attributes: [AttributeValueInput
field
code
message
+ attributes
}
}
}
@@ -1973,11 +1974,11 @@ def test_update_product_variant_with_duplicated_attribute(
content = get_graphql_content(response)
data = content["data"]["productVariantUpdate"]
- assert data["errors"][0] == {
- "field": "attributes",
- "code": ProductErrorCode.DUPLICATED_INPUT_ITEM.name,
- "message": ANY,
- }
+ errors = data["errors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "attributes"
+ assert errors[0]["code"] == ProductErrorCode.DUPLICATED_INPUT_ITEM.name
+ assert set(errors[0]["attributes"]) == {color_attribute_id, size_attribute_id}
def test_update_product_variant_with_current_file_attribute(
@@ -2084,11 +2085,11 @@ def test_update_product_variant_with_duplicated_file_attribute(
content = get_graphql_content(response)
data = content["data"]["productVariantUpdate"]
- assert data["errors"][0] == {
- "field": "attributes",
- "code": ProductErrorCode.DUPLICATED_INPUT_ITEM.name,
- "message": ANY,
- }
+ errors = data["errors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "attributes"
+ assert errors[0]["code"] == ProductErrorCode.DUPLICATED_INPUT_ITEM.name
+ assert set(errors[0]["attributes"]) == {file_attribute_id}
def test_update_product_variant_with_file_attribute_new_value_is_not_created(
@@ -2400,6 +2401,151 @@ def test_update_product_variant_with_category_reference_attribute(
assert expected_assigned_attribute in assigned_attributes
+def test_update_product_variant_with_reference_attributes_and_reference_types_defined(
+ staff_api_client,
+ product_list,
+ page,
+ product_type_page_reference_attribute,
+ product_type_product_reference_attribute,
+ product_type_variant_reference_attribute,
+ permission_manage_products,
+):
+ # given
+ variant = product_list[0].variants.first()
+ sku = str(uuid4())[:12]
+ assert not variant.sku == sku
+
+ product_type = variant.product.product_type
+ product_type.variant_attributes.clear()
+ product_type.variant_attributes.add(
+ product_type_page_reference_attribute,
+ product_type_product_reference_attribute,
+ product_type_variant_reference_attribute,
+ )
+
+ reference_product = product_list[1]
+ reference_variant = product_list[2].variants.first()
+ product_type_page_reference_attribute.reference_page_types.add(page.page_type)
+ product_type_product_reference_attribute.reference_product_types.add(
+ reference_product.product_type
+ )
+ product_type_variant_reference_attribute.reference_product_types.add(
+ variant.product.product_type
+ )
+
+ page_ref_attr_id = graphene.Node.to_global_id(
+ "Attribute", product_type_page_reference_attribute.id
+ )
+ product_ref_attr_id = graphene.Node.to_global_id(
+ "Attribute", product_type_product_reference_attribute.id
+ )
+ variant_ref_attr_id = graphene.Node.to_global_id(
+ "Attribute", product_type_variant_reference_attribute.id
+ )
+ variant_ref = graphene.Node.to_global_id("ProductVariant", reference_variant.pk)
+ page_ref = graphene.Node.to_global_id("Page", page.pk)
+ product_ref = graphene.Node.to_global_id("Product", reference_product.pk)
+
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ variables = {
+ "id": variant_id,
+ "sku": sku,
+ "attributes": [
+ {"id": page_ref_attr_id, "references": [page_ref]},
+ {"id": product_ref_attr_id, "references": [product_ref]},
+ {"id": variant_ref_attr_id, "references": [variant_ref]},
+ ],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_UPDATE_VARIANT_ATTRIBUTES,
+ variables,
+ permissions=[permission_manage_products],
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ data = content["data"]["productVariantUpdate"]
+ assert not data["errors"]
+ variant_data = data["productVariant"]
+ assert variant_data["sku"] == sku
+ assert len(variant_data["attributes"]) == len(variables["attributes"])
+ expected_attributes_data = [
+ {
+ "attribute": {"slug": product_type_page_reference_attribute.slug},
+ "values": [
+ {
+ "id": ANY,
+ "slug": f"{variant.pk}_{page.id}",
+ "file": None,
+ "richText": None,
+ "plainText": None,
+ "reference": page_ref,
+ "name": page.title,
+ "boolean": None,
+ "date": None,
+ "dateTime": None,
+ }
+ ],
+ },
+ {
+ "attribute": {"slug": product_type_product_reference_attribute.slug},
+ "values": [
+ {
+ "id": ANY,
+ "slug": f"{variant.pk}_{reference_product.id}",
+ "file": None,
+ "richText": None,
+ "plainText": None,
+ "reference": product_ref,
+ "name": reference_product.name,
+ "boolean": None,
+ "date": None,
+ "dateTime": None,
+ }
+ ],
+ },
+ {
+ "attribute": {"slug": product_type_variant_reference_attribute.slug},
+ "values": [
+ {
+ "id": ANY,
+ "slug": f"{variant.pk}_{reference_variant.id}",
+ "file": None,
+ "richText": None,
+ "plainText": None,
+ "reference": variant_ref,
+ "name": f"{reference_variant.product.name}: {reference_variant.name}",
+ "boolean": None,
+ "date": None,
+ "dateTime": None,
+ }
+ ],
+ },
+ ]
+ for attr_data in variant_data["attributes"]:
+ assert attr_data in expected_attributes_data
+
+ assigned_attributes = variant_data["assignedAttributes"]
+ expected_page_ref_assigned_attribute = {
+ "attribute": {"slug": product_type_page_reference_attribute.slug},
+ "pages": [{"slug": page.slug}],
+ }
+ assert expected_page_ref_assigned_attribute in assigned_attributes
+ expected_product_ref_assigned_attribute = {
+ "attribute": {"slug": product_type_product_reference_attribute.slug},
+ "products": [{"slug": reference_product.slug}],
+ }
+ assert expected_product_ref_assigned_attribute in assigned_attributes
+ expected_variant_ref_assigned_attribute = {
+ "attribute": {"slug": product_type_variant_reference_attribute.slug},
+ "variants": [{"sku": reference_variant.sku}],
+ }
+ assert expected_variant_ref_assigned_attribute in assigned_attributes
+
+
def test_update_product_variant_with_single_reference_attributes(
staff_api_client,
product,
@@ -2694,11 +2840,12 @@ def test_update_product_variant_requires_values(
assert len(content["data"]["productVariantUpdate"]["errors"]) == 1, (
f"expected: {message}"
)
- assert content["data"]["productVariantUpdate"]["errors"][0] == {
- "field": "attributes",
- "message": message,
- "code": code,
- }
+ errors = content["data"]["productVariantUpdate"]["errors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "attributes"
+ assert errors[0]["code"] == code
+ assert errors[0]["message"] == message
+ assert set(errors[0]["attributes"]) == {attr_id}
assert not variant.product.variants.filter(sku=sku).exists()
@@ -2731,15 +2878,98 @@ def test_update_product_variant_requires_attr_value_when_is_required(
)
variant.refresh_from_db()
content = get_graphql_content(response)
- assert len(content["data"]["productVariantUpdate"]["errors"]) == 1
- assert content["data"]["productVariantUpdate"]["errors"][0] == {
- "field": "attributes",
- "message": "Attribute expects a value but none were given.",
- "code": "REQUIRED",
- }
+ errors = content["data"]["productVariantUpdate"]["errors"]
+ assert len(errors) == 1
+ assert errors[0]["field"] == "attributes"
+ assert errors[0]["code"] == ProductErrorCode.REQUIRED.name
+ assert errors[0]["message"] == "Attribute expects a value but none were given."
+ assert set(errors[0]["attributes"]) == {attr_id}
assert not variant.product.variants.filter(sku=sku).exists()
+def test_update_product_variant_with_reference_attributes_ref_not_in_available_choices(
+ staff_api_client,
+ product_list,
+ page,
+ product_type_page_reference_attribute,
+ product_type_product_reference_attribute,
+ product_type_variant_reference_attribute,
+ permission_manage_products,
+ page_type_list,
+ product_type_with_variant_attributes,
+):
+ # given
+ variant = product_list[0].variants.first()
+ sku = str(uuid4())[:12]
+ assert not variant.sku == sku
+
+ product_type = variant.product.product_type
+ product_type.variant_attributes.clear()
+ product_type.variant_attributes.add(
+ product_type_page_reference_attribute,
+ product_type_product_reference_attribute,
+ product_type_variant_reference_attribute,
+ )
+
+ reference_product = product_list[1]
+ reference_variant = product_list[2].variants.first()
+ # assigned reference types that do not match product/page types of references
+ # that are provided in the input
+ product_type_page_reference_attribute.reference_page_types.add(page_type_list[1])
+ product_type_product_reference_attribute.reference_product_types.add(
+ product_type_with_variant_attributes
+ )
+ product_type_variant_reference_attribute.reference_product_types.add(
+ product_type_with_variant_attributes
+ )
+
+ page_ref_attr_id = graphene.Node.to_global_id(
+ "Attribute", product_type_page_reference_attribute.id
+ )
+ product_ref_attr_id = graphene.Node.to_global_id(
+ "Attribute", product_type_product_reference_attribute.id
+ )
+ variant_ref_attr_id = graphene.Node.to_global_id(
+ "Attribute", product_type_variant_reference_attribute.id
+ )
+ variant_ref = graphene.Node.to_global_id("ProductVariant", reference_variant.pk)
+ page_ref = graphene.Node.to_global_id("Page", page.pk)
+ product_ref = graphene.Node.to_global_id("Product", reference_product.pk)
+
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ variables = {
+ "id": variant_id,
+ "sku": sku,
+ "attributes": [
+ {"id": page_ref_attr_id, "references": [page_ref]},
+ {"id": product_ref_attr_id, "references": [product_ref]},
+ {"id": variant_ref_attr_id, "references": [variant_ref]},
+ ],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_UPDATE_VARIANT_ATTRIBUTES,
+ variables,
+ permissions=[permission_manage_products],
+ )
+
+ # then
+ content = get_graphql_content(response)
+
+ data = content["data"]["productVariantUpdate"]
+ errors = data["errors"]
+ assert not data["productVariant"]
+ assert len(errors) == 1
+ assert errors[0]["code"] == ProductErrorCode.INVALID.name
+ assert errors[0]["field"] == "attributes"
+ assert set(errors[0]["attributes"]) == {
+ page_ref_attr_id,
+ product_ref_attr_id,
+ variant_ref_attr_id,
+ }
+
+
def test_update_product_variant_with_price_does_not_raise_price_validation_error(
staff_api_client, variant, size_attribute, permission_manage_products
):
diff --git a/saleor/graphql/product/tests/queries/products_filtrations/test_over_references_pages.py b/saleor/graphql/product/tests/queries/products_filtrations/test_over_references_pages.py
index d3b6053078..5dc23e789d 100644
--- a/saleor/graphql/product/tests/queries/products_filtrations/test_over_references_pages.py
+++ b/saleor/graphql/product/tests/queries/products_filtrations/test_over_references_pages.py
@@ -83,7 +83,7 @@ def test_products_query_with_attr_slug_and_attribute_value_reference_to_pages(
"where": {
"attributes": [
{
- "slug": "page-reference",
+ "slug": "product-page-reference",
"value": {
"reference": {
"pageSlugs": {
diff --git a/saleor/graphql/product/tests/queries/variants_where/test_over_references_pages.py b/saleor/graphql/product/tests/queries/variants_where/test_over_references_pages.py
index 238cb0dddd..306efb1cf9 100644
--- a/saleor/graphql/product/tests/queries/variants_where/test_over_references_pages.py
+++ b/saleor/graphql/product/tests/queries/variants_where/test_over_references_pages.py
@@ -81,7 +81,7 @@ def test_product_variants_query_with_attr_slug_and_attribute_value_reference_to_
"where": {
"attributes": [
{
- "slug": "page-reference",
+ "slug": "product-page-reference",
"value": {
"reference": {
"pageSlugs": {
diff --git a/saleor/graphql/query_cost_map.py b/saleor/graphql/query_cost_map.py
index 47aed5f90a..64b578e5a3 100644
--- a/saleor/graphql/query_cost_map.py
+++ b/saleor/graphql/query_cost_map.py
@@ -230,6 +230,7 @@ COST_MAP = {
"choices": {"complexity": 1, "multipliers": ["first", "last"]},
"productTypes": {"complexity": 1, "multipliers": ["first", "last"]},
"productVariantTypes": {"complexity": 1, "multipliers": ["first", "last"]},
+ "referenceTypes": {"complexity": 1, "multipliers": ["limit"]},
},
"Category": {
"ancestors": {"complexity": 1, "multipliers": ["first", "last"]},
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 242b355d09..209459cbbe 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -5947,6 +5947,18 @@ type Attribute implements Node & ObjectWithMetadata @doc(category: "Attributes")
"""The entity type which can be used as a reference."""
entityType: AttributeEntityTypeEnum
+ """
+ The reference types (product or page type) that are used to narrow down the choices of reference objects.
+
+ Added in Saleor 3.22.
+ """
+ referenceTypes(
+ """
+ Maximum number of objects to return. Value must be greater than 0. Default is 100.
+ """
+ limit: PositiveInt = 100
+ ): [ReferenceType!]
+
"""Name of an attribute displayed in the interface."""
name: String
@@ -6108,268 +6120,315 @@ enum AttributeEntityTypeEnum @doc(category: "Attributes") {
COLLECTION
}
-enum AttributeTypeEnum @doc(category: "Attributes") {
- PRODUCT_TYPE
- PAGE_TYPE
-}
-
-enum MeasurementUnitsEnum {
- MM
- CM
- DM
- M
- KM
- FT
- YD
- INCH
- SQ_MM
- SQ_CM
- SQ_DM
- SQ_M
- SQ_KM
- SQ_FT
- SQ_YD
- SQ_INCH
- CUBIC_MILLIMETER
- CUBIC_CENTIMETER
- CUBIC_DECIMETER
- CUBIC_METER
- LITER
- CUBIC_FOOT
- CUBIC_INCH
- CUBIC_YARD
- QT
- PINT
- FL_OZ
- ACRE_IN
- ACRE_FT
- G
- LB
- OZ
- KG
- TONNE
-}
-
-type AttributeValueCountableConnection @doc(category: "Attributes") {
- """Pagination data for this connection."""
- pageInfo: PageInfo!
- edges: [AttributeValueCountableEdge!]!
-
- """A total count of items in the collection."""
- totalCount: Int
-}
-
-type AttributeValueCountableEdge @doc(category: "Attributes") {
- """The item at the end of the edge."""
- node: AttributeValue!
-
- """A cursor for use in pagination."""
- cursor: String!
-}
+"""
+The reference types (product or page type) that are used to narrow down the choices of reference objects.
+ProductType applicable for reference attribute with `PRODUCT` or `PRODUCT_VARIANT` entity type.
+PageType applicable for reference attribute with `PAGE` entity type.
+"""
+union ReferenceType = ProductType | PageType
-"""Represents a value of an attribute."""
-type AttributeValue implements Node @doc(category: "Attributes") {
- """The ID of the attribute value."""
+"""
+Represents a type of product. It defines what attributes are available to products of this type.
+"""
+type ProductType implements Node & ObjectWithMetadata @doc(category: "Products") {
+ """The ID of the product type."""
id: ID!
- """Name of a value displayed in the interface."""
- name: String
-
- """Internal representation of a value (unique per attribute)."""
- slug: String
+ """List of private metadata items. Requires staff permissions to access."""
+ privateMetadata: [MetadataItem!]!
"""
- Represent value of the attribute value (e.g. color values for swatch attributes).
+ A single key from private metadata. Requires staff permissions to access.
+
+ Tip: Use GraphQL aliases to fetch multiple keys.
"""
- value: String
-
- """Returns translated attribute value fields for the given language code."""
- translation(
- """A language code to return the translation for attribute value."""
- languageCode: LanguageCodeEnum!
- ): AttributeValueTranslation
-
- """The input type to use for entering attribute values in the dashboard."""
- inputType: AttributeInputTypeEnum
+ privateMetafield(key: String!): String
- """The ID of the referenced object."""
- reference: ID
+ """
+ Private metadata. Requires staff permissions to access. Use `keys` to control which fields you want to include. The default is to include everything.
+ """
+ privateMetafields(keys: [String!]): Metadata
- """Represents file URL and content type (if attribute value is a file)."""
- file: File
+ """List of public metadata items. Can be accessed without permissions."""
+ metadata: [MetadataItem!]!
"""
- Represents the text of the attribute value, includes formatting.
+ A single key from public metadata.
- Rich text format. For reference see https://editorjs.io/
+ Tip: Use GraphQL aliases to fetch multiple keys.
"""
- richText: JSONString
+ metafield(key: String!): String
"""
- Represents the text of the attribute value, plain text without formatting.
+ Public metadata. Use `keys` to control which fields you want to include. The default is to include everything.
"""
- plainText: String
+ metafields(keys: [String!]): Metadata
- """Represents the boolean value of the attribute value."""
- boolean: Boolean
+ """Name of the product type."""
+ name: String!
- """Represents the date value of the attribute value."""
- date: Date
+ """Slug of the product type."""
+ slug: String!
- """Represents the date/time value of the attribute value."""
- dateTime: DateTime
+ """Whether the product type has variants."""
+ hasVariants: Boolean!
- """External ID of this attribute value."""
- externalReference: String
-}
+ """Whether shipping is required for this product type."""
+ isShippingRequired: Boolean!
-"""Represents attribute value translations."""
-type AttributeValueTranslation implements Node @doc(category: "Attributes") {
- """The ID of the attribute value translation."""
- id: ID!
+ """Whether the product type is digital."""
+ isDigital: Boolean!
- """Translation language."""
- language: LanguageDisplay!
+ """Weight of the product type."""
+ weight: Weight
- """Translated attribute value name."""
- name: String!
+ """The product type kind."""
+ kind: ProductTypeKindEnum!
- """
- Translated rich-text attribute value.
-
- Rich text format. For reference see https://editorjs.io/
- """
- richText: JSONString
+ """List of products of this type."""
+ products(
+ """Slug of a channel for which the data should be returned."""
+ channel: String
- """Translated plain text attribute value ."""
- plainText: String
+ """Return the elements in the list that come before the specified cursor."""
+ before: String
- """Represents the attribute value fields to translate."""
- translatableContent: AttributeValueTranslatableContent
-}
+ """Return the elements in the list that come after the specified cursor."""
+ after: String
-"""
-Represents attribute value's original translatable fields and related translations.
-"""
-type AttributeValueTranslatableContent implements Node @doc(category: "Attributes") {
- """The ID of the attribute value translatable content."""
- id: ID!
+ """
+ Retrieve the first n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.
+ """
+ first: Int
- """The ID of the attribute value to translate."""
- attributeValueId: ID!
+ """
+ Retrieve the last n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.
+ """
+ last: Int
+ ): ProductCountableConnection @deprecated(reason: "Use the top-level `products` query with the `productTypes` filter.")
- """Name of the attribute value to translate."""
- name: String!
+ """A type of tax. Assigned by enabled tax gateway"""
+ taxType: TaxType @deprecated(reason: "Use `taxClass` field instead.")
"""
- Attribute value.
+ Tax class assigned to this product type. All products of this product type use this tax class, unless it's overridden in the `Product` type.
- Rich text format. For reference see https://editorjs.io/
+ Requires one of the following permissions: AUTHENTICATED_STAFF_USER, AUTHENTICATED_APP.
"""
- richText: JSONString
-
- """Attribute plain text value."""
- plainText: String
+ taxClass: TaxClass
- """Returns translated attribute value fields for the given language code."""
- translation(
- """A language code to return the translation for attribute value."""
- languageCode: LanguageCodeEnum!
- ): AttributeValueTranslation
+ """Variant attributes of that product type."""
+ variantAttributes(
+ """Define scope of returned attributes."""
+ variantSelection: VariantAttributeScope
+ ): [Attribute!] @deprecated(reason: "Use `assignedVariantAttributes` instead.")
- """Represents a value of an attribute."""
- attributeValue: AttributeValue @deprecated(reason: "Get model fields from the root level queries.")
+ """
+ Variant attributes of that product type with attached variant selection.
+ """
+ assignedVariantAttributes(
+ """Define scope of returned attributes."""
+ variantSelection: VariantAttributeScope
+ ): [AssignedVariantAttribute!]
- """Associated attribute that can be translated."""
- attribute: AttributeTranslatableContent
-}
+ """Product attributes of that product type."""
+ productAttributes: [Attribute!]
-"""
-Represents attribute's original translatable fields and related translations.
-"""
-type AttributeTranslatableContent implements Node @doc(category: "Attributes") {
- """The ID of the attribute translatable content."""
- id: ID!
+ """
+ List of attributes which can be assigned to this product type.
+
+ Requires one of the following permissions: MANAGE_PRODUCTS.
+ """
+ availableAttributes(
+ """Filtering options for attributes of this product type."""
+ filter: AttributeFilterInput @deprecated(reason: "Use `where` filter instead.")
- """The ID of the attribute to translate."""
- attributeId: ID!
+ """Where filtering options for attributes of this product type."""
+ where: AttributeWhereInput
- """Name of the attribute to translate."""
- name: String!
+ """Search attributes."""
+ search: String
- """Returns translated attribute fields for the given language code."""
- translation(
- """A language code to return the translation for attribute."""
- languageCode: LanguageCodeEnum!
- ): AttributeTranslation
+ """Return the elements in the list that come before the specified cursor."""
+ before: String
- """Custom attribute of a product."""
- attribute: Attribute @deprecated(reason: "Get model fields from the root level queries.")
-}
+ """Return the elements in the list that come after the specified cursor."""
+ after: String
-"""Represents attribute translations."""
-type AttributeTranslation implements Node @doc(category: "Attributes") {
- """The ID of the attribute translation."""
+ """
+ Retrieve the first n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.
+ """
+ first: Int
+
+ """
+ Retrieve the last n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.
+ """
+ last: Int
+ ): AttributeCountableConnection
+}
+
+enum ProductTypeKindEnum @doc(category: "Products") {
+ NORMAL
+ GIFT_CARD
+}
+
+"""Representation of tax types fetched from tax gateway."""
+type TaxType @doc(category: "Taxes") {
+ """Description of the tax type."""
+ description: String
+
+ """External tax code used to identify given tax group."""
+ taxCode: String
+}
+
+"""
+Tax class is a named object used to define tax rates per country. Tax class can be assigned to product types, products and shipping methods to define their tax rates.
+"""
+type TaxClass implements Node & ObjectWithMetadata @doc(category: "Taxes") {
+ """The ID of the object."""
id: ID!
- """Translation language."""
- language: LanguageDisplay!
+ """List of private metadata items. Requires staff permissions to access."""
+ privateMetadata: [MetadataItem!]!
- """Translated attribute name."""
+ """
+ A single key from private metadata. Requires staff permissions to access.
+
+ Tip: Use GraphQL aliases to fetch multiple keys.
+ """
+ privateMetafield(key: String!): String
+
+ """
+ Private metadata. Requires staff permissions to access. Use `keys` to control which fields you want to include. The default is to include everything.
+ """
+ privateMetafields(keys: [String!]): Metadata
+
+ """List of public metadata items. Can be accessed without permissions."""
+ metadata: [MetadataItem!]!
+
+ """
+ A single key from public metadata.
+
+ Tip: Use GraphQL aliases to fetch multiple keys.
+ """
+ metafield(key: String!): String
+
+ """
+ Public metadata. Use `keys` to control which fields you want to include. The default is to include everything.
+ """
+ metafields(keys: [String!]): Metadata
+
+ """Name of the tax class."""
name: String!
- """Represents the attribute fields to translate."""
- translatableContent: AttributeTranslatableContent
+ """Country-specific tax rates for this tax class."""
+ countries: [TaxClassCountryRate!]!
}
-type File {
- """The URL of the file."""
- url: String!
+"""
+Tax rate for a country. When tax class is null, it represents the default tax rate for that country; otherwise it's a country tax rate specific to the given tax class.
+"""
+type TaxClassCountryRate @doc(category: "Taxes") {
+ """Country in which this tax rate applies."""
+ country: CountryDisplay!
- """Content type of the file."""
- contentType: String
+ """Tax rate value."""
+ rate: Float!
+
+ """Related tax class."""
+ taxClass: TaxClass
+}
+
+enum VariantAttributeScope @doc(category: "Products") {
+ ALL
+ VARIANT_SELECTION
+ NOT_VARIANT_SELECTION
}
"""
-The `Date` scalar type represents a Date
-value as specified by
-[iso8601](https://en.wikipedia.org/wiki/ISO_8601).
+Represents assigned attribute to variant with variant selection attached.
"""
-scalar Date
+type AssignedVariantAttribute @doc(category: "Attributes") {
+ """Attribute assigned to variant."""
+ attribute: Attribute!
-input AttributeChoicesSortingInput @doc(category: "Attributes") {
- """Specifies the direction in which to sort attribute choices."""
- direction: OrderDirection!
+ """
+ Determines, whether assigned attribute is allowed for variant selection. Supported variant types for variant selection are: ['dropdown', 'boolean', 'swatch', 'numeric']
+ """
+ variantSelection: Boolean!
+}
- """Sort attribute choices by the selected field."""
- field: AttributeChoicesSortField!
+type AttributeCountableConnection @doc(category: "Attributes") {
+ """Pagination data for this connection."""
+ pageInfo: PageInfo!
+ edges: [AttributeCountableEdge!]!
+
+ """A total count of items in the collection."""
+ totalCount: Int
}
-enum AttributeChoicesSortField @doc(category: "Attributes") {
- """Sort attribute choice by name."""
- NAME
+type AttributeCountableEdge @doc(category: "Attributes") {
+ """The item at the end of the edge."""
+ node: Attribute!
- """Sort attribute choice by slug."""
- SLUG
+ """A cursor for use in pagination."""
+ cursor: String!
}
-input AttributeValueFilterInput @doc(category: "Attributes") {
+input AttributeFilterInput @doc(category: "Attributes") {
+ valueRequired: Boolean
+ isVariantOnly: Boolean
+ visibleInStorefront: Boolean
+ filterableInStorefront: Boolean
+ filterableInDashboard: Boolean
+ availableInGrid: Boolean
+ metadata: [MetadataFilter!]
search: String
ids: [ID!]
+ type: AttributeTypeEnum
+ inCollection: ID
+ inCategory: ID
slugs: [String!]
+
+ """Specifies the channel by which the data should be filtered."""
+ channel: String @deprecated(reason: "Use root-level channel argument instead.")
}
-"""Where filtering options for attribute values."""
-input AttributeValueWhereInput @doc(category: "Attributes") {
+input MetadataFilter {
+ """Key of a metadata item."""
+ key: String!
+
+ """Value of a metadata item."""
+ value: String
+}
+
+enum AttributeTypeEnum @doc(category: "Attributes") {
+ PRODUCT_TYPE
+ PAGE_TYPE
+}
+
+"""Where filtering options."""
+input AttributeWhereInput @doc(category: "Attributes") {
+ metadata: [MetadataFilter!]
ids: [ID!]
name: StringFilterInput
slug: StringFilterInput
+ withChoices: Boolean
+ inputType: AttributeInputTypeEnumFilterInput
+ entityType: AttributeEntityTypeEnumFilterInput
+ type: AttributeTypeEnumFilterInput
+ unit: MeasurementUnitsEnumFilterInput
+ inCollection: ID
+ inCategory: ID
+ valueRequired: Boolean
+ visibleInStorefront: Boolean
+ filterableInDashboard: Boolean
"""List of conditions that must be met."""
- AND: [AttributeValueWhereInput!]
+ AND: [AttributeWhereInput!]
"""A list of conditions of which at least one must be met."""
- OR: [AttributeValueWhereInput!]
+ OR: [AttributeWhereInput!]
}
"""Define the filtering options for string fields."""
@@ -6381,28 +6440,80 @@ input StringFilterInput {
oneOf: [String!]
}
-type ProductTypeCountableConnection @doc(category: "Products") {
- """Pagination data for this connection."""
- pageInfo: PageInfo!
- edges: [ProductTypeCountableEdge!]!
+input AttributeInputTypeEnumFilterInput @doc(category: "Attributes") {
+ """The value equal to."""
+ eq: AttributeInputTypeEnum
- """A total count of items in the collection."""
- totalCount: Int
+ """The value included in."""
+ oneOf: [AttributeInputTypeEnum!]
}
-type ProductTypeCountableEdge @doc(category: "Products") {
- """The item at the end of the edge."""
- node: ProductType!
+input AttributeEntityTypeEnumFilterInput @doc(category: "Attributes") {
+ """The value equal to."""
+ eq: AttributeEntityTypeEnum
- """A cursor for use in pagination."""
- cursor: String!
+ """The value included in."""
+ oneOf: [AttributeEntityTypeEnum!]
+}
+
+input AttributeTypeEnumFilterInput @doc(category: "Attributes") {
+ """The value equal to."""
+ eq: AttributeTypeEnum
+
+ """The value included in."""
+ oneOf: [AttributeTypeEnum!]
+}
+
+input MeasurementUnitsEnumFilterInput @doc(category: "Attributes") {
+ """The value equal to."""
+ eq: MeasurementUnitsEnum
+
+ """The value included in."""
+ oneOf: [MeasurementUnitsEnum!]
+}
+
+enum MeasurementUnitsEnum {
+ MM
+ CM
+ DM
+ M
+ KM
+ FT
+ YD
+ INCH
+ SQ_MM
+ SQ_CM
+ SQ_DM
+ SQ_M
+ SQ_KM
+ SQ_FT
+ SQ_YD
+ SQ_INCH
+ CUBIC_MILLIMETER
+ CUBIC_CENTIMETER
+ CUBIC_DECIMETER
+ CUBIC_METER
+ LITER
+ CUBIC_FOOT
+ CUBIC_INCH
+ CUBIC_YARD
+ QT
+ PINT
+ FL_OZ
+ ACRE_IN
+ ACRE_FT
+ G
+ LB
+ OZ
+ KG
+ TONNE
}
"""
-Represents a type of product. It defines what attributes are available to products of this type.
+Represents a type of page. It defines what attributes are available to pages of this type.
"""
-type ProductType implements Node & ObjectWithMetadata @doc(category: "Products") {
- """The ID of the product type."""
+type PageType implements Node & ObjectWithMetadata @doc(category: "Pages") {
+ """ID of the page type."""
id: ID!
"""List of private metadata items. Requires staff permissions to access."""
@@ -6435,31 +6546,29 @@ type ProductType implements Node & ObjectWithMetadata @doc(category: "Products")
"""
metafields(keys: [String!]): Metadata
- """Name of the product type."""
+ """Name of the page type."""
name: String!
- """Slug of the product type."""
+ """Slug of the page type."""
slug: String!
- """Whether the product type has variants."""
- hasVariants: Boolean!
-
- """Whether shipping is required for this product type."""
- isShippingRequired: Boolean!
-
- """Whether the product type is digital."""
- isDigital: Boolean!
+ """Page attributes of that page type."""
+ attributes: [Attribute!]
- """Weight of the product type."""
- weight: Weight
+ """
+ Attributes that can be assigned to the page type.
+
+ Requires one of the following permissions: MANAGE_PAGES, MANAGE_PAGE_TYPES_AND_ATTRIBUTES.
+ """
+ availableAttributes(
+ """Filtering options for attributes."""
+ filter: AttributeFilterInput @deprecated(reason: "Use `where` filter instead.")
- """The product type kind."""
- kind: ProductTypeKindEnum!
+ """Where filtering options for attributes."""
+ where: AttributeWhereInput
- """List of products of this type."""
- products(
- """Slug of a channel for which the data should be returned."""
- channel: String
+ """Search attributes."""
+ search: String
"""Return the elements in the list that come before the specified cursor."""
before: String
@@ -6476,266 +6585,262 @@ type ProductType implements Node & ObjectWithMetadata @doc(category: "Products")
Retrieve the last n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.
"""
last: Int
- ): ProductCountableConnection @deprecated(reason: "Use the top-level `products` query with the `productTypes` filter.")
-
- """A type of tax. Assigned by enabled tax gateway"""
- taxType: TaxType @deprecated(reason: "Use `taxClass` field instead.")
+ ): AttributeCountableConnection
"""
- Tax class assigned to this product type. All products of this product type use this tax class, unless it's overridden in the `Product` type.
+ Whether page type has pages assigned.
- Requires one of the following permissions: AUTHENTICATED_STAFF_USER, AUTHENTICATED_APP.
+ Requires one of the following permissions: MANAGE_PAGES, MANAGE_PAGE_TYPES_AND_ATTRIBUTES.
"""
- taxClass: TaxClass
+ hasPages: Boolean
+}
- """Variant attributes of that product type."""
- variantAttributes(
- """Define scope of returned attributes."""
- variantSelection: VariantAttributeScope
- ): [Attribute!] @deprecated(reason: "Use `assignedVariantAttributes` instead.")
+"""
+Positive Integer scalar implementation.
+
+Should be used in places where value must be positive (greater than 0).
+"""
+scalar PositiveInt
+
+type AttributeValueCountableConnection @doc(category: "Attributes") {
+ """Pagination data for this connection."""
+ pageInfo: PageInfo!
+ edges: [AttributeValueCountableEdge!]!
+
+ """A total count of items in the collection."""
+ totalCount: Int
+}
+
+type AttributeValueCountableEdge @doc(category: "Attributes") {
+ """The item at the end of the edge."""
+ node: AttributeValue!
+
+ """A cursor for use in pagination."""
+ cursor: String!
+}
+
+"""Represents a value of an attribute."""
+type AttributeValue implements Node @doc(category: "Attributes") {
+ """The ID of the attribute value."""
+ id: ID!
+
+ """Name of a value displayed in the interface."""
+ name: String
+
+ """Internal representation of a value (unique per attribute)."""
+ slug: String
"""
- Variant attributes of that product type with attached variant selection.
+ Represent value of the attribute value (e.g. color values for swatch attributes).
"""
- assignedVariantAttributes(
- """Define scope of returned attributes."""
- variantSelection: VariantAttributeScope
- ): [AssignedVariantAttribute!]
+ value: String
- """Product attributes of that product type."""
- productAttributes: [Attribute!]
+ """Returns translated attribute value fields for the given language code."""
+ translation(
+ """A language code to return the translation for attribute value."""
+ languageCode: LanguageCodeEnum!
+ ): AttributeValueTranslation
+
+ """The input type to use for entering attribute values in the dashboard."""
+ inputType: AttributeInputTypeEnum
+
+ """The ID of the referenced object."""
+ reference: ID
+
+ """Represents file URL and content type (if attribute value is a file)."""
+ file: File
"""
- List of attributes which can be assigned to this product type.
+ Represents the text of the attribute value, includes formatting.
- Requires one of the following permissions: MANAGE_PRODUCTS.
+ Rich text format. For reference see https://editorjs.io/
"""
- availableAttributes(
- """Filtering options for attributes of this product type."""
- filter: AttributeFilterInput @deprecated(reason: "Use `where` filter instead.")
-
- """Where filtering options for attributes of this product type."""
- where: AttributeWhereInput
+ richText: JSONString
- """Search attributes."""
- search: String
+ """
+ Represents the text of the attribute value, plain text without formatting.
+ """
+ plainText: String
- """Return the elements in the list that come before the specified cursor."""
- before: String
+ """Represents the boolean value of the attribute value."""
+ boolean: Boolean
- """Return the elements in the list that come after the specified cursor."""
- after: String
+ """Represents the date value of the attribute value."""
+ date: Date
- """
- Retrieve the first n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.
- """
- first: Int
+ """Represents the date/time value of the attribute value."""
+ dateTime: DateTime
- """
- Retrieve the last n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.
- """
- last: Int
- ): AttributeCountableConnection
+ """External ID of this attribute value."""
+ externalReference: String
}
-enum ProductTypeKindEnum @doc(category: "Products") {
- NORMAL
- GIFT_CARD
-}
+"""Represents attribute value translations."""
+type AttributeValueTranslation implements Node @doc(category: "Attributes") {
+ """The ID of the attribute value translation."""
+ id: ID!
-"""Representation of tax types fetched from tax gateway."""
-type TaxType @doc(category: "Taxes") {
- """Description of the tax type."""
- description: String
+ """Translation language."""
+ language: LanguageDisplay!
- """External tax code used to identify given tax group."""
- taxCode: String
+ """Translated attribute value name."""
+ name: String!
+
+ """
+ Translated rich-text attribute value.
+
+ Rich text format. For reference see https://editorjs.io/
+ """
+ richText: JSONString
+
+ """Translated plain text attribute value ."""
+ plainText: String
+
+ """Represents the attribute value fields to translate."""
+ translatableContent: AttributeValueTranslatableContent
}
"""
-Tax class is a named object used to define tax rates per country. Tax class can be assigned to product types, products and shipping methods to define their tax rates.
+Represents attribute value's original translatable fields and related translations.
"""
-type TaxClass implements Node & ObjectWithMetadata @doc(category: "Taxes") {
- """The ID of the object."""
+type AttributeValueTranslatableContent implements Node @doc(category: "Attributes") {
+ """The ID of the attribute value translatable content."""
id: ID!
- """List of private metadata items. Requires staff permissions to access."""
- privateMetadata: [MetadataItem!]!
+ """The ID of the attribute value to translate."""
+ attributeValueId: ID!
+
+ """Name of the attribute value to translate."""
+ name: String!
"""
- A single key from private metadata. Requires staff permissions to access.
+ Attribute value.
- Tip: Use GraphQL aliases to fetch multiple keys.
+ Rich text format. For reference see https://editorjs.io/
"""
- privateMetafield(key: String!): String
+ richText: JSONString
- """
- Private metadata. Requires staff permissions to access. Use `keys` to control which fields you want to include. The default is to include everything.
- """
- privateMetafields(keys: [String!]): Metadata
+ """Attribute plain text value."""
+ plainText: String
- """List of public metadata items. Can be accessed without permissions."""
- metadata: [MetadataItem!]!
+ """Returns translated attribute value fields for the given language code."""
+ translation(
+ """A language code to return the translation for attribute value."""
+ languageCode: LanguageCodeEnum!
+ ): AttributeValueTranslation
- """
- A single key from public metadata.
-
- Tip: Use GraphQL aliases to fetch multiple keys.
- """
- metafield(key: String!): String
+ """Represents a value of an attribute."""
+ attributeValue: AttributeValue @deprecated(reason: "Get model fields from the root level queries.")
- """
- Public metadata. Use `keys` to control which fields you want to include. The default is to include everything.
- """
- metafields(keys: [String!]): Metadata
+ """Associated attribute that can be translated."""
+ attribute: AttributeTranslatableContent
+}
- """Name of the tax class."""
+"""
+Represents attribute's original translatable fields and related translations.
+"""
+type AttributeTranslatableContent implements Node @doc(category: "Attributes") {
+ """The ID of the attribute translatable content."""
+ id: ID!
+
+ """The ID of the attribute to translate."""
+ attributeId: ID!
+
+ """Name of the attribute to translate."""
name: String!
- """Country-specific tax rates for this tax class."""
- countries: [TaxClassCountryRate!]!
+ """Returns translated attribute fields for the given language code."""
+ translation(
+ """A language code to return the translation for attribute."""
+ languageCode: LanguageCodeEnum!
+ ): AttributeTranslation
+
+ """Custom attribute of a product."""
+ attribute: Attribute @deprecated(reason: "Get model fields from the root level queries.")
}
-"""
-Tax rate for a country. When tax class is null, it represents the default tax rate for that country; otherwise it's a country tax rate specific to the given tax class.
-"""
-type TaxClassCountryRate @doc(category: "Taxes") {
- """Country in which this tax rate applies."""
- country: CountryDisplay!
+"""Represents attribute translations."""
+type AttributeTranslation implements Node @doc(category: "Attributes") {
+ """The ID of the attribute translation."""
+ id: ID!
- """Tax rate value."""
- rate: Float!
+ """Translation language."""
+ language: LanguageDisplay!
- """Related tax class."""
- taxClass: TaxClass
+ """Translated attribute name."""
+ name: String!
+
+ """Represents the attribute fields to translate."""
+ translatableContent: AttributeTranslatableContent
}
-enum VariantAttributeScope @doc(category: "Products") {
- ALL
- VARIANT_SELECTION
- NOT_VARIANT_SELECTION
+type File {
+ """The URL of the file."""
+ url: String!
+
+ """Content type of the file."""
+ contentType: String
}
"""
-Represents assigned attribute to variant with variant selection attached.
+The `Date` scalar type represents a Date
+value as specified by
+[iso8601](https://en.wikipedia.org/wiki/ISO_8601).
"""
-type AssignedVariantAttribute @doc(category: "Attributes") {
- """Attribute assigned to variant."""
- attribute: Attribute!
-
- """
- Determines, whether assigned attribute is allowed for variant selection. Supported variant types for variant selection are: ['dropdown', 'boolean', 'swatch', 'numeric']
- """
- variantSelection: Boolean!
-}
+scalar Date
-type AttributeCountableConnection @doc(category: "Attributes") {
- """Pagination data for this connection."""
- pageInfo: PageInfo!
- edges: [AttributeCountableEdge!]!
+input AttributeChoicesSortingInput @doc(category: "Attributes") {
+ """Specifies the direction in which to sort attribute choices."""
+ direction: OrderDirection!
- """A total count of items in the collection."""
- totalCount: Int
+ """Sort attribute choices by the selected field."""
+ field: AttributeChoicesSortField!
}
-type AttributeCountableEdge @doc(category: "Attributes") {
- """The item at the end of the edge."""
- node: Attribute!
+enum AttributeChoicesSortField @doc(category: "Attributes") {
+ """Sort attribute choice by name."""
+ NAME
- """A cursor for use in pagination."""
- cursor: String!
+ """Sort attribute choice by slug."""
+ SLUG
}
-input AttributeFilterInput @doc(category: "Attributes") {
- valueRequired: Boolean
- isVariantOnly: Boolean
- visibleInStorefront: Boolean
- filterableInStorefront: Boolean
- filterableInDashboard: Boolean
- availableInGrid: Boolean
- metadata: [MetadataFilter!]
+input AttributeValueFilterInput @doc(category: "Attributes") {
search: String
ids: [ID!]
- type: AttributeTypeEnum
- inCollection: ID
- inCategory: ID
slugs: [String!]
-
- """Specifies the channel by which the data should be filtered."""
- channel: String @deprecated(reason: "Use root-level channel argument instead.")
-}
-
-input MetadataFilter {
- """Key of a metadata item."""
- key: String!
-
- """Value of a metadata item."""
- value: String
}
-"""Where filtering options."""
-input AttributeWhereInput @doc(category: "Attributes") {
- metadata: [MetadataFilter!]
+"""Where filtering options for attribute values."""
+input AttributeValueWhereInput @doc(category: "Attributes") {
ids: [ID!]
name: StringFilterInput
slug: StringFilterInput
- withChoices: Boolean
- inputType: AttributeInputTypeEnumFilterInput
- entityType: AttributeEntityTypeEnumFilterInput
- type: AttributeTypeEnumFilterInput
- unit: MeasurementUnitsEnumFilterInput
- inCollection: ID
- inCategory: ID
- valueRequired: Boolean
- visibleInStorefront: Boolean
- filterableInDashboard: Boolean
"""List of conditions that must be met."""
- AND: [AttributeWhereInput!]
+ AND: [AttributeValueWhereInput!]
"""A list of conditions of which at least one must be met."""
- OR: [AttributeWhereInput!]
-}
-
-input AttributeInputTypeEnumFilterInput @doc(category: "Attributes") {
- """The value equal to."""
- eq: AttributeInputTypeEnum
-
- """The value included in."""
- oneOf: [AttributeInputTypeEnum!]
-}
-
-input AttributeEntityTypeEnumFilterInput @doc(category: "Attributes") {
- """The value equal to."""
- eq: AttributeEntityTypeEnum
-
- """The value included in."""
- oneOf: [AttributeEntityTypeEnum!]
+ OR: [AttributeValueWhereInput!]
}
-input AttributeTypeEnumFilterInput @doc(category: "Attributes") {
- """The value equal to."""
- eq: AttributeTypeEnum
+type ProductTypeCountableConnection @doc(category: "Products") {
+ """Pagination data for this connection."""
+ pageInfo: PageInfo!
+ edges: [ProductTypeCountableEdge!]!
- """The value included in."""
- oneOf: [AttributeTypeEnum!]
+ """A total count of items in the collection."""
+ totalCount: Int
}
-input MeasurementUnitsEnumFilterInput @doc(category: "Attributes") {
- """The value equal to."""
- eq: MeasurementUnitsEnum
+type ProductTypeCountableEdge @doc(category: "Products") {
+ """The item at the end of the edge."""
+ node: ProductType!
- """The value included in."""
- oneOf: [MeasurementUnitsEnum!]
+ """A cursor for use in pagination."""
+ cursor: String!
}
-"""
-Positive Integer scalar implementation.
-
-Should be used in places where value must be positive (greater than 0).
-"""
-scalar PositiveInt
-
"""
Represents a single category of products. Categories allow to organize products in a tree-hierarchies which can be used for navigation in the storefront.
"""
@@ -8836,92 +8941,6 @@ type Page implements Node & ObjectWithMetadata & ObjectWithAttributes @doc(categ
attributes: [SelectedAttribute!]! @deprecated(reason: "Use `assignedAttributes` field instead.")
}
-"""
-Represents a type of page. It defines what attributes are available to pages of this type.
-"""
-type PageType implements Node & ObjectWithMetadata @doc(category: "Pages") {
- """ID of the page type."""
- id: ID!
-
- """List of private metadata items. Requires staff permissions to access."""
- privateMetadata: [MetadataItem!]!
-
- """
- A single key from private metadata. Requires staff permissions to access.
-
- Tip: Use GraphQL aliases to fetch multiple keys.
- """
- privateMetafield(key: String!): String
-
- """
- Private metadata. Requires staff permissions to access. Use `keys` to control which fields you want to include. The default is to include everything.
- """
- privateMetafields(keys: [String!]): Metadata
-
- """List of public metadata items. Can be accessed without permissions."""
- metadata: [MetadataItem!]!
-
- """
- A single key from public metadata.
-
- Tip: Use GraphQL aliases to fetch multiple keys.
- """
- metafield(key: String!): String
-
- """
- Public metadata. Use `keys` to control which fields you want to include. The default is to include everything.
- """
- metafields(keys: [String!]): Metadata
-
- """Name of the page type."""
- name: String!
-
- """Slug of the page type."""
- slug: String!
-
- """Page attributes of that page type."""
- attributes: [Attribute!]
-
- """
- Attributes that can be assigned to the page type.
-
- Requires one of the following permissions: MANAGE_PAGES, MANAGE_PAGE_TYPES_AND_ATTRIBUTES.
- """
- availableAttributes(
- """Filtering options for attributes."""
- filter: AttributeFilterInput @deprecated(reason: "Use `where` filter instead.")
-
- """Where filtering options for attributes."""
- where: AttributeWhereInput
-
- """Search attributes."""
- search: String
-
- """Return the elements in the list that come before the specified cursor."""
- before: String
-
- """Return the elements in the list that come after the specified cursor."""
- after: String
-
- """
- Retrieve the first n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.
- """
- first: Int
-
- """
- Retrieve the last n elements from the list. Note that the system only allows fetching a maximum of 100 objects in a single query.
- """
- last: Int
- ): AttributeCountableConnection
-
- """
- Whether page type has pages assigned.
-
- Requires one of the following permissions: MANAGE_PAGES, MANAGE_PAGE_TYPES_AND_ATTRIBUTES.
- """
- hasPages: Boolean
-}
-
"""
Represents voucher's original translatable fields and related translations.
"""
@@ -29037,6 +29056,15 @@ input AttributeCreateInput @doc(category: "Attributes") {
"""External ID of this attribute."""
externalReference: String
+
+ """
+ Specifies reference types to narrow down the choices of reference objects. Applicable only for `REFERENCE` and `SINGLE_REFERENCE` attributes with `PRODUCT`, `PRODUCT_VARIANT` and `PAGE` entity types. Accepts `ProductType` IDs for `PRODUCT` and `PRODUCT_VARIANT` entity types, and `PageType` IDs for `PAGE` entity type. If omitted, all objects of the selected entity type are available as attribute values.
+
+ A maximum of 100 reference types can be specified.
+
+ Added in Saleor 3.22.
+ """
+ referenceTypes: [ID!]
}
input AttributeValueCreateInput @doc(category: "Attributes") {
@@ -29145,6 +29173,15 @@ input AttributeUpdateInput @doc(category: "Attributes") {
"""External ID of this product."""
externalReference: String
+
+ """
+ Specifies reference types to narrow down the choices of reference objects. Applicable only for `REFERENCE` and `SINGLE_REFERENCE` attributes with `PRODUCT`, `PRODUCT_VARIANT` and `PAGE` entity types. Accepts `ProductType` IDs for `PRODUCT` and `PRODUCT_VARIANT` entity types, and `PageType` IDs for `PAGE` entity type. If omitted, all objects of the selected entity type are available as attribute values.
+
+ A maximum of 100 reference types can be specified.
+
+ Added in Saleor 3.22.
+ """
+ referenceTypes: [ID!]
}
input AttributeValueUpdateInput @doc(category: "Attributes") {
diff --git a/saleor/graphql/translations/types.py b/saleor/graphql/translations/types.py
index 8c01000491..c01babd6f8 100644
--- a/saleor/graphql/translations/types.py
+++ b/saleor/graphql/translations/types.py
@@ -19,7 +19,10 @@ from ...permission.enums import (
from ...product import models as product_models
from ...shipping import models as shipping_models
from ...site import models as site_models
-from ..attribute.dataloaders import AttributesByAttributeId, AttributeValueByIdLoader
+from ..attribute.dataloaders.attributes import (
+ AttributesByAttributeId,
+ AttributeValueByIdLoader,
+)
from ..core.context import ChannelContext, get_database_connection_name
from ..core.descriptions import ADDED_IN_321, DEPRECATED_IN_3X_TYPE, RICH_CONTENT
from ..core.enums import LanguageCodeEnum
diff --git a/saleor/graphql/utils/__init__.py b/saleor/graphql/utils/__init__.py
index f0d8932c70..69d97ed93f 100644
--- a/saleor/graphql/utils/__init__.py
+++ b/saleor/graphql/utils/__init__.py
@@ -104,6 +104,7 @@ def get_nodes(
qs=None,
schema=None,
database_connection_name: str = settings.DATABASE_CONNECTION_DEFAULT_NAME,
+ prefetch_related: Iterable[str] | None = None,
):
"""Return a list of nodes.
@@ -131,11 +132,15 @@ def get_nodes(
elif model is not None:
qs = model.objects.using(database_connection_name)
+ if prefetch_related is None:
+ prefetch_related = []
is_object_type_with_double_id = str(graphene_type) in TYPES_WITH_DOUBLE_ID_AVAILABLE
if is_object_type_with_double_id:
- nodes = _get_node_for_types_with_double_id(qs, pks, graphene_type)
+ nodes = _get_node_for_types_with_double_id(
+ qs, pks, graphene_type, prefetch_related
+ )
else:
- nodes = list(qs.filter(pk__in=pks))
+ nodes = list(qs.filter(pk__in=pks).prefetch_related(*prefetch_related))
nodes.sort(key=lambda e: pks.index(str(e.pk))) # preserve order in pks
if not nodes:
@@ -152,7 +157,7 @@ def get_nodes(
return nodes
-def _get_node_for_types_with_double_id(qs, pks, graphene_type):
+def _get_node_for_types_with_double_id(qs, pks, graphene_type, prefetch_related):
uuid_pks = []
old_pks = []
is_order_type = str(graphene_type) == "Order"
@@ -166,7 +171,7 @@ def _get_node_for_types_with_double_id(qs, pks, graphene_type):
lookup = Q(id__in=uuid_pks) | (Q(use_old_id=True) & Q(number__in=old_pks))
else:
lookup = Q(id__in=uuid_pks) | (Q(old_id__isnull=False) & Q(old_id__in=old_pks))
- nodes = list(qs.filter(lookup))
+ nodes = list(qs.filter(lookup).prefetch_related(*prefetch_related))
old_id_field = "number" if is_order_type else "old_id"
return sorted(
nodes,
diff --git a/saleor/page/tests/fixtures/page_type.py b/saleor/page/tests/fixtures/page_type.py
index 337c04d6be..2a316f5aa9 100644
--- a/saleor/page/tests/fixtures/page_type.py
+++ b/saleor/page/tests/fixtures/page_type.py
@@ -14,7 +14,9 @@ def page_type(db, size_page_attribute, tag_page_attribute):
@pytest.fixture
def page_type_with_rich_text_attribute(db, rich_text_attribute_page_type):
- page_type = PageType.objects.create(name="Test page type", slug="test-page-type")
+ page_type = PageType.objects.create(
+ name="Test page type", slug="test-page-type-rich"
+ )
page_type.page_attributes.add(rich_text_attribute_page_type)
return page_type
diff --git a/saleor/settings.py b/saleor/settings.py
index ef1f6061a3..fdd54c9c2b 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -452,6 +452,7 @@ LOGGING = {
},
}
+
AUTH_USER_MODEL = "account.User"
AUTH_PASSWORD_VALIDATORS = [
diff --git a/saleor/tests/e2e/attributes/utils/__init__.py b/saleor/tests/e2e/attributes/utils/__init__.py
index 7d6d2fd28b..45fbab399b 100644
--- a/saleor/tests/e2e/attributes/utils/__init__.py
+++ b/saleor/tests/e2e/attributes/utils/__init__.py
@@ -1,10 +1,17 @@
from .attribute_bulk_create import bulk_create_attributes
from .create_attribute import attribute_create
-from .prepare_attributes import prepare_all_attributes, prepare_all_attributes_in_bulk
+from .prepare_attributes import (
+ prepare_all_attributes,
+ prepare_all_attributes_in_bulk,
+ prepare_attributes_in_bulk,
+)
+from .update_attribute import attribute_update
__all__ = [
"attribute_create",
+ "attribute_update",
"prepare_all_attributes",
"bulk_create_attributes",
"prepare_all_attributes_in_bulk",
+ "prepare_attributes_in_bulk",
]
diff --git a/saleor/tests/e2e/attributes/utils/create_attribute.py b/saleor/tests/e2e/attributes/utils/create_attribute.py
index b8681f0bb6..835d4e3431 100644
--- a/saleor/tests/e2e/attributes/utils/create_attribute.py
+++ b/saleor/tests/e2e/attributes/utils/create_attribute.py
@@ -5,6 +5,30 @@ mutation AttributeCreate($input: AttributeCreateInput!) {
attributeCreate(input: $input) {
attribute {
id
+ name
+ slug
+ unit
+ entityType
+ referenceTypes {
+ ... on ProductType {
+ __typename
+ id
+ slug
+ }
+ ... on PageType {
+ __typename
+ id
+ slug
+ }
+ }
+ externalReference
+ productTypes(first: 10) {
+ edges {
+ node {
+ id
+ }
+ }
+ }
}
errors {
code
@@ -26,8 +50,11 @@ def attribute_create(
is_variant_only=False,
values=None,
unit=None,
- entityType=None,
+ entity_type=None,
+ reference_types=None,
):
+ if reference_types is None:
+ reference_types = []
variables = {
"input": {
"inputType": input_type,
@@ -38,7 +65,8 @@ def attribute_create(
"isVariantOnly": is_variant_only,
"values": values,
"unit": unit,
- "entityType": entityType,
+ "entityType": entity_type,
+ "referenceTypes": reference_types,
}
}
diff --git a/saleor/tests/e2e/attributes/utils/prepare_attributes.py b/saleor/tests/e2e/attributes/utils/prepare_attributes.py
index 06ea59e32f..2a9ff492e9 100644
--- a/saleor/tests/e2e/attributes/utils/prepare_attributes.py
+++ b/saleor/tests/e2e/attributes/utils/prepare_attributes.py
@@ -140,7 +140,7 @@ def prepare_all_attributes(e2e_staff_api_client, attribute_type, entity_type):
slug="reference-test",
type=attribute_type,
value_required=True,
- entityType=entity_type,
+ entity_type=entity_type,
)
attr_reference_id = attr_reference["id"]
@@ -172,8 +172,12 @@ def prepare_all_attributes(e2e_staff_api_client, attribute_type, entity_type):
)
-def prepare_all_attributes_in_bulk(e2e_staff_api_client, attribute_type, entity_type):
- attributes = [
+def prepare_all_attributes_in_bulk(
+ e2e_staff_api_client,
+ attribute_type,
+ entity_type,
+):
+ attributes_input = [
{
"name": "Dropdown",
"slug": "dropdown",
@@ -260,6 +264,14 @@ def prepare_all_attributes_in_bulk(e2e_staff_api_client, attribute_type, entity_
"valueRequired": False,
"entityType": entity_type,
},
+ {
+ "name": "Single Reference",
+ "slug": "single-reference",
+ "inputType": "SINGLE_REFERENCE",
+ "type": attribute_type,
+ "valueRequired": False,
+ "entityType": entity_type,
+ },
{
"name": "File",
"slug": "file",
@@ -268,30 +280,14 @@ def prepare_all_attributes_in_bulk(e2e_staff_api_client, attribute_type, entity_
"valueRequired": False,
},
]
- attributes_data = bulk_create_attributes(e2e_staff_api_client, attributes)
+ return prepare_attributes_in_bulk(e2e_staff_api_client, attributes_input)
- attr_dropdown_id = attributes_data["results"][0]["attribute"]["id"]
- attr_multiselect_id = attributes_data["results"][1]["attribute"]["id"]
- attr_date_id = attributes_data["results"][2]["attribute"]["id"]
- attr_date_time_id = attributes_data["results"][3]["attribute"]["id"]
- attr_plain_text_id = attributes_data["results"][4]["attribute"]["id"]
- attr_rich_text_id = attributes_data["results"][5]["attribute"]["id"]
- attr_numeric_id = attributes_data["results"][6]["attribute"]["id"]
- attr_bool_id = attributes_data["results"][7]["attribute"]["id"]
- attr_swatch_id = attributes_data["results"][8]["attribute"]["id"]
- attr_reference_id = attributes_data["results"][9]["attribute"]["id"]
- attr_file_id = attributes_data["results"][10]["attribute"]["id"]
- return (
- attr_dropdown_id,
- attr_multiselect_id,
- attr_date_id,
- attr_date_time_id,
- attr_plain_text_id,
- attr_rich_text_id,
- attr_numeric_id,
- attr_bool_id,
- attr_swatch_id,
- attr_reference_id,
- attr_file_id,
- )
+def prepare_attributes_in_bulk(e2e_staff_api_client, attributes_input):
+ attributes_data = bulk_create_attributes(e2e_staff_api_client, attributes_input)
+
+ attribute_ids = [
+ attribute_data["attribute"]["id"]
+ for attribute_data in attributes_data["results"]
+ ]
+ return attribute_ids
diff --git a/saleor/tests/e2e/attributes/utils/update_attribute.py b/saleor/tests/e2e/attributes/utils/update_attribute.py
new file mode 100644
index 0000000000..17e8e2753b
--- /dev/null
+++ b/saleor/tests/e2e/attributes/utils/update_attribute.py
@@ -0,0 +1,58 @@
+from ...utils import get_graphql_content
+
+ATTRIBUTE_UPDATE_MUTATION = """
+ mutation updateAttribute(
+ $id: ID!, $input: AttributeUpdateInput!
+ ) {
+ attributeUpdate(
+ id: $id,
+ input: $input) {
+ errors {
+ field
+ message
+ code
+ }
+ attribute {
+ id
+ name
+ slug
+ unit
+ entityType
+ referenceTypes {
+ ... on ProductType {
+ id
+ slug
+ }
+ ... on PageType {
+ id
+ slug
+ }
+ }
+ externalReference
+ productTypes(first: 10) {
+ edges {
+ node {
+ id
+ }
+ }
+ }
+ }
+ }
+}
+"""
+
+
+def attribute_update(client, attribute_id, input_data):
+ """Send a GraphQL mutation to update an attribute."""
+ variables = {"id": attribute_id, "input": input_data}
+
+ response = client.post_graphql(
+ ATTRIBUTE_UPDATE_MUTATION,
+ variables,
+ )
+ content = get_graphql_content(response)
+
+ assert content["data"]["attributeUpdate"]["errors"] == []
+ data = content["data"]["attributeUpdate"]["attribute"]
+ assert data["id"] == attribute_id
+ return data
diff --git a/saleor/tests/e2e/product/test_create_product_with_all_attributes_types.py b/saleor/tests/e2e/product/test_create_product_with_all_attributes_types.py
index b17579a914..ae8c744876 100644
--- a/saleor/tests/e2e/product/test_create_product_with_all_attributes_types.py
+++ b/saleor/tests/e2e/product/test_create_product_with_all_attributes_types.py
@@ -51,6 +51,7 @@ def test_create_product_with_attributes_created_in_bulk_core_0704(
attr_bool_id,
attr_swatch_id,
attr_reference_id,
+ attr_single_reference_id,
attr_file_id,
) = prepare_all_attributes_in_bulk(
e2e_staff_api_client, attribute_type="PRODUCT_TYPE", entity_type="PAGE"
@@ -68,6 +69,7 @@ def test_create_product_with_attributes_created_in_bulk_core_0704(
attr_bool_id,
attr_swatch_id,
attr_reference_id,
+ attr_single_reference_id,
attr_file_id,
]
product_type_data = create_product_type(
@@ -76,7 +78,7 @@ def test_create_product_with_attributes_created_in_bulk_core_0704(
product_attributes=add_attributes,
)
product_type_id = product_type_data["id"]
- assert len(product_type_data["productAttributes"]) == 11
+ assert len(product_type_data["productAttributes"]) == len(add_attributes)
# Step 3 - Create product with all attributes
expected_base_text = "Test rich attribute text"
@@ -99,6 +101,7 @@ def test_create_product_with_attributes_created_in_bulk_core_0704(
{"id": attr_bool_id, "boolean": True},
{"id": attr_swatch_id, "values": ["blue"]},
{"id": attr_reference_id, "references": [page_id]},
+ {"id": attr_single_reference_id, "reference": page_id},
{"id": attr_file_id, "file": file_url, "contentType": file_content_type},
]
product_data = create_product(
@@ -107,5 +110,4 @@ def test_create_product_with_attributes_created_in_bulk_core_0704(
category_id,
attributes=attributes,
)
- attributes = product_data["attributes"]
- assert len(product_data["attributes"]) == 11
+ assert len(product_data["attributes"]) == len(attributes)
diff --git a/saleor/tests/e2e/product/test_create_product_with_restricted_reference_attributes.py b/saleor/tests/e2e/product/test_create_product_with_restricted_reference_attributes.py
new file mode 100644
index 0000000000..8360fefc4e
--- /dev/null
+++ b/saleor/tests/e2e/product/test_create_product_with_restricted_reference_attributes.py
@@ -0,0 +1,208 @@
+import pytest
+
+from ..attributes.utils import attribute_create, attribute_update
+from ..pages.utils import create_page, create_page_type
+from ..utils import assign_permissions
+from .utils import (
+ create_category,
+ create_product,
+ create_product_type,
+ create_product_variant,
+ raw_create_product,
+ update_product,
+)
+
+
+def test_product_with_restricted_reference_attribute(
+ e2e_staff_api_client,
+ permission_manage_page_types_and_attributes,
+ permission_manage_pages,
+ permission_manage_products,
+ permission_manage_product_types_and_attributes,
+):
+ # Before
+ permissions = [
+ permission_manage_page_types_and_attributes,
+ permission_manage_pages,
+ permission_manage_products,
+ permission_manage_product_types_and_attributes,
+ ]
+ assign_permissions(e2e_staff_api_client, permissions)
+
+ category_data = create_category(e2e_staff_api_client)
+ category_id = category_data["id"]
+
+ page_type_data = create_page_type(e2e_staff_api_client)
+ page_type_id = page_type_data["id"]
+
+ product_type_data = create_product_type(
+ e2e_staff_api_client,
+ slug="product-type",
+ )
+ product_type_id = product_type_data["id"]
+
+ # Step 1 - Create reference attributes with reference types
+ page_reference_attribute_data = attribute_create(
+ e2e_staff_api_client,
+ input_type="REFERENCE",
+ entity_type="PAGE",
+ name="page ref",
+ slug="page-ref",
+ reference_types=[page_type_id],
+ )
+ page_ref_attribute_id = page_reference_attribute_data["id"]
+ assert page_reference_attribute_data["entityType"] == "PAGE"
+ assert len(page_reference_attribute_data["referenceTypes"]) == 1
+ assert page_reference_attribute_data["referenceTypes"][0]["id"] == page_type_id
+ assert (
+ page_reference_attribute_data["referenceTypes"][0]["__typename"] == "PageType"
+ )
+
+ product_reference_attribute_data = attribute_create(
+ e2e_staff_api_client,
+ input_type="REFERENCE",
+ entity_type="PRODUCT",
+ name="product ref",
+ slug="product-ref",
+ reference_types=[product_type_id],
+ )
+ product_ref_attribute_id = product_reference_attribute_data["id"]
+ assert product_reference_attribute_data["entityType"] == "PRODUCT"
+ assert len(product_reference_attribute_data["referenceTypes"]) == 1
+ assert (
+ product_reference_attribute_data["referenceTypes"][0]["id"] == product_type_id
+ )
+ assert (
+ product_reference_attribute_data["referenceTypes"][0]["__typename"]
+ == "ProductType"
+ )
+
+ variant_reference_attribute_data = attribute_create(
+ e2e_staff_api_client,
+ input_type="SINGLE_REFERENCE",
+ entity_type="PRODUCT_VARIANT",
+ name="variant ref",
+ slug="variant-ref",
+ reference_types=[product_type_id],
+ )
+ variant_ref_attribute_id = variant_reference_attribute_data["id"]
+ assert variant_reference_attribute_data["entityType"] == "PRODUCT_VARIANT"
+ assert len(product_reference_attribute_data["referenceTypes"]) == 1
+ assert (
+ variant_reference_attribute_data["referenceTypes"][0]["id"] == product_type_id
+ )
+ assert (
+ variant_reference_attribute_data["referenceTypes"][0]["__typename"]
+ == "ProductType"
+ )
+
+ # Step 2 - Create product type with the attributes
+ product_type_with_references = create_product_type(
+ e2e_staff_api_client,
+ "referenced-product-type",
+ product_attributes=[
+ page_ref_attribute_id,
+ product_ref_attribute_id,
+ variant_ref_attribute_id,
+ ],
+ )
+ product_type_with_references_id = product_type_with_references["id"]
+ assert len(product_type_with_references["productAttributes"]) == 3
+
+ # Step 3 - Prepare references not valid for specified attributes
+ page_type_data = create_page_type(e2e_staff_api_client, name="another page type")
+ page_type_id_not_in_choices = page_type_data["id"]
+ page_not_in_choices = create_page(
+ e2e_staff_api_client, page_type_id_not_in_choices, title="invalid page"
+ )
+ page_not_in_choices_id = page_not_in_choices["id"]
+
+ product_type_data = create_product_type(
+ e2e_staff_api_client, slug="another-product-type"
+ )
+ product_type_id_not_in_choices = product_type_data["id"]
+ product_not_in_choices = create_product(
+ e2e_staff_api_client,
+ product_type_id_not_in_choices,
+ category_id,
+ product_name="invalid product",
+ )
+ product_not_in_choices_id = product_not_in_choices["id"]
+ variant_not_in_choices = create_product_variant(
+ e2e_staff_api_client, product_not_in_choices_id
+ )
+ variant_id_not_in_choices = variant_not_in_choices["id"]
+
+ # Step 4 - Create product with a wrong attribute value and check for error
+ invalid_attribute_data = [
+ {"id": page_ref_attribute_id, "references": [page_not_in_choices_id]},
+ {"id": product_ref_attribute_id, "references": [product_not_in_choices_id]},
+ {"id": variant_ref_attribute_id, "reference": variant_id_not_in_choices},
+ ]
+ product_content = raw_create_product(
+ e2e_staff_api_client,
+ product_type_with_references_id,
+ category_id,
+ attributes=invalid_attribute_data,
+ )
+ product_data = product_content["data"]["productCreate"]
+ errors = product_data["errors"]
+ assert errors[0]["field"] == "attributes"
+ assert errors[0]["code"] == "INVALID"
+ assert len(errors[0]["attributes"]) == len(invalid_attribute_data)
+
+ # Step 5 - Create product with a correct attribute values
+ correct_page = create_page(e2e_staff_api_client, page_type_id)
+ correct_page_id = correct_page["id"]
+
+ correct_product_ref = create_product(
+ e2e_staff_api_client,
+ product_type_id,
+ category_id,
+ product_name="valid product",
+ )
+ correct_product_ref_id = correct_product_ref["id"]
+ correct_variant_ref = create_product_variant(
+ e2e_staff_api_client, correct_product_ref_id
+ )
+ correct_variant_ref_id = correct_variant_ref["id"]
+
+ attributes = [
+ {"id": page_ref_attribute_id, "references": [correct_page_id]},
+ {"id": product_ref_attribute_id, "references": [correct_product_ref_id]},
+ {"id": variant_ref_attribute_id, "reference": correct_variant_ref_id},
+ ]
+ product_data = create_product(
+ e2e_staff_api_client,
+ product_type_with_references_id,
+ category_id,
+ attributes=attributes,
+ product_name="Tested product",
+ )
+ product_id = product_data["id"]
+ assert len(product_data["attributes"]) == 3
+
+ # Step 6 - Update attributes and clear reference types
+ attribute_data = attribute_update(
+ e2e_staff_api_client, page_ref_attribute_id, {"referenceTypes": []}
+ )
+ assert attribute_data["referenceTypes"] == []
+
+ attribute_data = attribute_update(
+ e2e_staff_api_client, product_ref_attribute_id, {"referenceTypes": []}
+ )
+ assert attribute_data["referenceTypes"] == []
+
+ attribute_data = attribute_update(
+ e2e_staff_api_client, variant_ref_attribute_id, {"referenceTypes": []}
+ )
+ assert attribute_data["referenceTypes"] == []
+
+ # Step 7 - Update product with a previously wrong attribute value
+ product_data = update_product(
+ e2e_staff_api_client,
+ product_id,
+ {"attributes": invalid_attribute_data},
+ )
+ assert len(product_data["attributes"]) == len(invalid_attribute_data)
diff --git a/saleor/tests/e2e/product/utils/__init__.py b/saleor/tests/e2e/product/utils/__init__.py
index fc4d61ac99..5d414759e9 100644
--- a/saleor/tests/e2e/product/utils/__init__.py
+++ b/saleor/tests/e2e/product/utils/__init__.py
@@ -3,7 +3,7 @@ from .collection import create_collection
from .collection_add_products import add_product_to_collection
from .collection_listing_update import create_collection_channel_listing
from .digital_content import create_digital_content
-from .product import create_product
+from .product import create_product, raw_create_product
from .product_attribute_assignment_update import (
update_product_type_assignment_attribute,
)
@@ -33,6 +33,7 @@ __all__ = [
"create_product_variant",
"raw_create_product_variant",
"create_product",
+ "raw_create_product",
"raw_create_product_channel_listing",
"create_variants_in_bulk",
"update_product_type_assignment_attribute",
diff --git a/saleor/tests/e2e/product/utils/product.py b/saleor/tests/e2e/product/utils/product.py
index e28a54c2ba..750ced1250 100644
--- a/saleor/tests/e2e/product/utils/product.py
+++ b/saleor/tests/e2e/product/utils/product.py
@@ -7,6 +7,7 @@ mutation createProduct($input: ProductCreateInput!) {
field
code
message
+ attributes
}
product {
id
@@ -41,6 +42,34 @@ def create_product(
product_name="Test product",
attributes=None,
collection_ids=None,
+):
+ content = raw_create_product(
+ staff_api_client,
+ product_type_id,
+ category_id,
+ product_name=product_name,
+ attributes=attributes,
+ collection_ids=collection_ids,
+ )
+
+ assert content["data"]["productCreate"]["errors"] == []
+
+ data = content["data"]["productCreate"]["product"]
+ assert data["id"] is not None
+ assert data["name"] == product_name
+ assert data["productType"]["id"] == product_type_id
+ assert data["category"]["id"] == category_id
+
+ return data
+
+
+def raw_create_product(
+ staff_api_client,
+ product_type_id,
+ category_id,
+ product_name="Test product",
+ attributes=None,
+ collection_ids=None,
):
if not attributes:
attributes = []
@@ -65,12 +94,4 @@ def create_product(
)
content = get_graphql_content(response)
- assert content["data"]["productCreate"]["errors"] == []
-
- data = content["data"]["productCreate"]["product"]
- assert data["id"] is not None
- assert data["name"] == product_name
- assert data["productType"]["id"] == product_type_id
- assert data["category"]["id"] == category_id
-
- return data
+ return content