Skip to content

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

[RFC] Reference attribute linking to product variants (#10468)

Iga Karbowiak917cb9b7adbc
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2b16670c5a..3aa0f7175e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -4,6 +4,10 @@ All notable, unreleased changes to this project will be documented in this file.
# 3.8.0 [Unreleased]
+### Other changes
+
+- Reference attribute linking to product variants - #10468 by @IKarbowiak
+
# 3.7.0
### Highlights
diff --git a/saleor/attribute/__init__.py b/saleor/attribute/__init__.py
index 556b6d9ed7..4dca2edc1b 100644
--- a/saleor/attribute/__init__.py
+++ b/saleor/attribute/__init__.py
@@ -102,12 +102,16 @@ class AttributeType:
class AttributeEntityType:
"""Type of a reference entity type. Must match the name of the graphql type.
- After adding new value, `REFERENCE_VALUE_NAME_MAPPING`
- and `ENTITY_TYPE_TO_MODEL_MAPPING` in saleor/graphql/attribute/utils.py
- must be updated.
+ After adding a new value the `ENTITY_TYPE_MAPPING` in
+ saleor/graphql/attribute/utils.py must be updated.
"""
PAGE = "Page"
PRODUCT = "Product"
+ PRODUCT_VARIANT = "ProductVariant"
- CHOICES = [(PAGE, "Page"), (PRODUCT, "Product")]
+ CHOICES = [
+ (PAGE, "Page"),
+ (PRODUCT, "Product"),
+ (PRODUCT_VARIANT, "Product Variant"),
+ ]
diff --git a/saleor/attribute/migrations/0023_extend_reference_attr_with_variant.py b/saleor/attribute/migrations/0023_extend_reference_attr_with_variant.py
new file mode 100644
index 0000000000..4df069a8d4
--- /dev/null
+++ b/saleor/attribute/migrations/0023_extend_reference_attr_with_variant.py
@@ -0,0 +1,40 @@
+# Generated by Django 3.2.14 on 2022-08-24 11:00
+
+from django.db import migrations, models
+import django.db.models.deletion
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ("product", "0175_alter_productmedia_product"),
+ ("attribute", "0022_plain_text_attribute"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="attributevalue",
+ name="reference_variant",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="references",
+ to="product.productvariant",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="attribute",
+ name="entity_type",
+ field=models.CharField(
+ blank=True,
+ choices=[
+ ("Page", "Page"),
+ ("Product", "Product"),
+ ("ProductVariant", "Product Variant"),
+ ],
+ max_length=50,
+ null=True,
+ ),
+ ),
+ ]
diff --git a/saleor/attribute/models/base.py b/saleor/attribute/models/base.py
index 1480cfb599..1462a03e19 100644
--- a/saleor/attribute/models/base.py
+++ b/saleor/attribute/models/base.py
@@ -15,7 +15,7 @@ from ...core.units import MeasurementUnits
from ...core.utils.editorjs import clean_editor_js
from ...core.utils.translations import Translation, TranslationProxy
from ...page.models import Page, PageType
-from ...product.models import Product, ProductType
+from ...product.models import Product, ProductType, ProductVariant
from .. import AttributeEntityType, AttributeInputType, AttributeType
if TYPE_CHECKING:
@@ -231,6 +231,14 @@ class AttributeValue(SortableModel):
blank=True,
)
+ reference_variant = models.ForeignKey(
+ ProductVariant,
+ related_name="references",
+ on_delete=models.CASCADE,
+ null=True,
+ blank=True,
+ )
+
reference_page = models.ForeignKey(
Page, related_name="references", on_delete=models.CASCADE, null=True, blank=True
)
diff --git a/saleor/csv/tests/export/products_data/test_get_products_data.py b/saleor/csv/tests/export/products_data/test_get_products_data.py
index 5afef02752..eb15614777 100644
--- a/saleor/csv/tests/export/products_data/test_get_products_data.py
+++ b/saleor/csv/tests/export/products_data/test_get_products_data.py
@@ -245,8 +245,10 @@ def test_get_products_data_for_specified_warehouses_channels_and_attributes(
file_attribute,
page_list,
product,
+ variant,
product_type_page_reference_attribute,
product_type_product_reference_attribute,
+ product_type_variant_reference_attribute,
numeric_attribute,
product_with_image,
product_with_variant_with_two_attributes,
@@ -264,6 +266,7 @@ def test_get_products_data_for_specified_warehouses_channels_and_attributes(
file_attribute,
product_type_page_reference_attribute,
product_type_product_reference_attribute,
+ product_type_variant_reference_attribute,
numeric_attribute,
rich_text_attribute,
swatch_attribute,
@@ -275,6 +278,7 @@ def test_get_products_data_for_specified_warehouses_channels_and_attributes(
file_attribute,
product_type_page_reference_attribute,
product_type_product_reference_attribute,
+ product_type_variant_reference_attribute,
numeric_attribute,
rich_text_attribute,
swatch_attribute,
@@ -374,6 +378,28 @@ def test_get_products_data_for_specified_warehouses_channels_and_attributes(
product, product_type_product_reference_attribute, product_product_ref_value
)
+ # add variant reference attribute
+ variant_variant_ref_value = AttributeValue.objects.create(
+ attribute=product_type_variant_reference_attribute,
+ reference_variant=variant,
+ slug=(f"{variant_with_many_stocks.pk}" f"_{variant.pk}"),
+ name=variant.name,
+ )
+ product_variant_ref_value = AttributeValue.objects.create(
+ attribute=product_type_variant_reference_attribute,
+ reference_variant=variant,
+ slug=f"{product.pk}_{variant.pk}",
+ name=variant.name,
+ )
+ associate_attribute_values_to_instance(
+ variant_with_many_stocks,
+ product_type_variant_reference_attribute,
+ variant_variant_ref_value,
+ )
+ associate_attribute_values_to_instance(
+ product, product_type_variant_reference_attribute, product_variant_ref_value
+ )
+
# add numeric attribute
numeric_value_1 = numeric_attribute.values.first()
numeric_value_2 = numeric_attribute.values.last()
diff --git a/saleor/csv/utils/__init__.py b/saleor/csv/utils/__init__.py
index b081b10b65..99f1da4fed 100644
--- a/saleor/csv/utils/__init__.py
+++ b/saleor/csv/utils/__init__.py
@@ -37,8 +37,9 @@ class ProductExportFields:
"entity_type": "attributes__assignment__attribute__entity_type",
"unit": "attributes__assignment__attribute__unit",
"attribute_pk": "attributes__assignment__attribute__pk",
- "value_reference_page": "attributes__values__reference_page",
- "value_reference_product": "attributes__values__reference_product",
+ "reference_page": "attributes__values__reference_page",
+ "reference_product": "attributes__values__reference_product",
+ "reference_variant": "attributes__values__reference_variant",
}
PRODUCT_CHANNEL_LISTING_FIELDS = {
@@ -71,8 +72,9 @@ class ProductExportFields:
"entity_type": "variants__attributes__assignment__attribute__entity_type",
"unit": "variants__attributes__assignment__attribute__unit",
"attribute_pk": "variants__attributes__assignment__attribute__pk",
- "value_reference_page": "variants__attributes__values__reference_page",
- "value_reference_product": "variants__attributes__values__reference_product",
+ "reference_page": "variants__attributes__values__reference_page",
+ "reference_product": "variants__attributes__values__reference_product",
+ "reference_variant": "variants__attributes__values__reference_variant",
}
VARIANT_CHANNEL_LISTING_FIELDS = {
diff --git a/saleor/csv/utils/products_data.py b/saleor/csv/utils/products_data.py
index c72910bcb4..c7243d7893 100644
--- a/saleor/csv/utils/products_data.py
+++ b/saleor/csv/utils/products_data.py
@@ -1,4 +1,5 @@
-from collections import defaultdict, namedtuple
+from collections import defaultdict
+from dataclasses import dataclass
from typing import TYPE_CHECKING, Dict, List, Optional, Set, Union
from urllib.parse import urljoin
@@ -301,24 +302,22 @@ def add_image_uris_to_data(
return result_data
-AttributeData = namedtuple(
- "AttributeData",
- [
- "slug",
- "input_type",
- "entity_type",
- "unit",
- "value_slug",
- "value_name",
- "value",
- "file_url",
- "rich_text",
- "boolean",
- "date_time",
- "reference_page",
- "reference_product",
- ],
-)
+@dataclass
+class AttributeData:
+ slug: str
+ input_type: str
+ entity_type: Optional[str] = None
+ unit: Optional[str] = None
+ value_slug: Optional[str] = None
+ value_name: Optional[str] = None
+ value: Optional[str] = None
+ file_url: Optional[str] = None
+ rich_text: Optional[str] = None
+ boolean: Optional[str] = None
+ date_time: Optional[str] = None
+ reference_page: Optional[str] = None
+ reference_product: Optional[str] = None
+ reference_variant: Optional[str] = None
def handle_attribute_data(
@@ -331,19 +330,11 @@ def handle_attribute_data(
):
attribute_pk = str(data.pop(attribute_fields["attribute_pk"], ""))
attribute_data = AttributeData(
- slug=data.pop(attribute_fields["slug"], None),
- input_type=data.pop(attribute_fields["input_type"], None),
- file_url=data.pop(attribute_fields["file_url"], None),
- value_slug=data.pop(attribute_fields["value_slug"], None),
- value_name=data.pop(attribute_fields["value_name"], None),
- value=data.pop(attribute_fields["value"], None),
- entity_type=data.pop(attribute_fields["entity_type"], None),
- unit=data.pop(attribute_fields["unit"], None),
- rich_text=data.pop(attribute_fields["rich_text"], None),
- boolean=data.pop(attribute_fields["boolean"], None),
- date_time=data.pop(attribute_fields["date_time"], None),
- reference_page=data.pop(attribute_fields["value_reference_page"], None),
- reference_product=data.pop(attribute_fields["value_reference_product"], None),
+ **{
+ field: data.pop(lookup, None)
+ for field, lookup in attribute_fields.items()
+ if field != "attribute_pk"
+ }
)
if attribute_ids and attribute_pk in attribute_ids:
@@ -434,48 +425,61 @@ def add_attribute_info_to_data(
def prepare_attribute_value(attribute_data: AttributeData):
"""Prepare value of attribute value depending on the attribute input type."""
input_type = attribute_data.input_type
- if input_type == AttributeInputType.FILE:
- file_url = attribute_data.file_url
- value = (
- build_absolute_uri(urljoin(settings.MEDIA_URL, file_url))
- if file_url
- else ""
- )
- elif input_type == AttributeInputType.REFERENCE and (
- attribute_data.reference_page or attribute_data.reference_product
- ):
- if attribute_data.reference_page:
- reference_id = attribute_data.reference_page
- else:
- reference_id = attribute_data.reference_product
- value = f"{attribute_data.entity_type}_{reference_id}"
- elif input_type == AttributeInputType.NUMERIC:
- value = f"{attribute_data.value_name}"
- if attribute_data.unit:
- value += f" {attribute_data.unit}"
- elif input_type == AttributeInputType.RICH_TEXT:
- value = clean_editor_js(attribute_data.rich_text, to_string=True)
- elif (
- input_type == AttributeInputType.BOOLEAN and attribute_data.boolean is not None
- ):
- value = str(attribute_data.boolean)
- elif input_type == AttributeInputType.DATE:
- value = str(attribute_data.date_time.date())
- elif input_type == AttributeInputType.DATE_TIME:
- value = str(attribute_data.date_time)
- elif input_type == AttributeInputType.SWATCH:
- if attribute_data.file_url:
- value = build_absolute_uri(
- urljoin(settings.MEDIA_URL, attribute_data.file_url)
- )
- else:
- value = attribute_data.value
- else:
+ input_type_to_get_value_func = {
+ AttributeInputType.FILE: _get_file_value,
+ AttributeInputType.REFERENCE: _get_reference_value,
+ AttributeInputType.NUMERIC: (
+ lambda data: data.value_name
+ if not attribute_data.unit
+ else f"{data.value_name} {data.unit}"
+ ),
+ AttributeInputType.RICH_TEXT: (
+ lambda data: clean_editor_js(data.rich_text, to_string=True)
+ ),
+ AttributeInputType.BOOLEAN: (
+ lambda data: str(data.boolean) if data.boolean is not None else None
+ ),
+ AttributeInputType.DATE: lambda data: str(data.date_time.date()),
+ AttributeInputType.DATE_TIME: lambda data: str(data.date_time),
+ AttributeInputType.SWATCH: (
+ lambda data: _get_file_value(data) if data.file_url else data.value
+ ),
+ }
+
+ value = None
+ if value_func := input_type_to_get_value_func.get(input_type):
+ value = value_func(attribute_data)
+ if value is None:
value = attribute_data.value_name or attribute_data.value_slug or ""
+ return value
+
+def _get_file_value(attribute_data):
+ file_url = attribute_data.file_url
+ value = (
+ build_absolute_uri(urljoin(settings.MEDIA_URL, file_url)) if file_url else ""
+ )
return value
+def _get_reference_value(attribute_data):
+ if not any(
+ [
+ attribute_data.reference_page,
+ attribute_data.reference_product,
+ attribute_data.reference_variant,
+ ]
+ ):
+ return None
+ if attribute_data.reference_page:
+ reference_id = attribute_data.reference_page
+ elif attribute_data.reference_product:
+ reference_id = attribute_data.reference_product
+ else:
+ reference_id = attribute_data.reference_variant
+ return f"{attribute_data.entity_type}_{reference_id}"
+
+
def add_warehouse_info_to_data(
pk: int,
warehouse_data: Dict[str, Union[Optional[str]]],
diff --git a/saleor/graphql/attribute/enums.py b/saleor/graphql/attribute/enums.py
index f55571f4fe..d239adbb00 100644
--- a/saleor/graphql/attribute/enums.py
+++ b/saleor/graphql/attribute/enums.py
@@ -1,6 +1,14 @@
+import graphene
+
from ...attribute import AttributeEntityType, AttributeInputType, AttributeType
from ..core.enums import to_enum
+from ..core.utils import str_to_enum
AttributeInputTypeEnum = to_enum(AttributeInputType)
AttributeTypeEnum = to_enum(AttributeType)
AttributeEntityTypeEnum = to_enum(AttributeEntityType)
+
+AttributeEntityTypeEnum = graphene.Enum(
+ "AttributeEntityTypeEnum",
+ [(str_to_enum(name.upper()), code) for code, name in AttributeEntityType.CHOICES],
+)
diff --git a/saleor/graphql/attribute/tests/test_utils.py b/saleor/graphql/attribute/tests/test_utils.py
index 4a09f72c2f..af942897b9 100644
--- a/saleor/graphql/attribute/tests/test_utils.py
+++ b/saleor/graphql/attribute/tests/test_utils.py
@@ -1220,6 +1220,44 @@ def test_validate_numeric_attributes_input_for_product_blank_value(
}
[email protected]("creation", [True, False])
+def test_validate_numeric_attributes_input_none_as_values(
+ creation, numeric_attribute, product_type
+):
+ # given
+ numeric_attribute.value_required = True
+ numeric_attribute.save(update_fields=["value_required"])
+
+ input_data = [
+ (
+ numeric_attribute,
+ AttrValuesInput(
+ global_id=graphene.Node.to_global_id("Attribute", numeric_attribute.pk),
+ values=None,
+ file_url=None,
+ content_type=None,
+ references=[],
+ ),
+ ),
+ ]
+
+ # when
+ errors = validate_attributes_input(
+ input_data,
+ product_type.product_attributes.all(),
+ is_page_attributes=False,
+ creation=creation,
+ )
+
+ # then
+ assert len(errors) == 1
+ error = errors[0]
+ assert error.code == ProductErrorCode.REQUIRED.value
+ assert set(error.params["attributes"]) == {
+ graphene.Node.to_global_id("Attribute", numeric_attribute.pk)
+ }
+
+
@pytest.mark.parametrize("creation", [True, False])
def test_validate_numeric_attributes_input_for_product_more_than_one_value_given(
creation, numeric_attribute, product_type
diff --git a/saleor/graphql/attribute/types.py b/saleor/graphql/attribute/types.py
index 57bff72ae4..b5de8b0b26 100644
--- a/saleor/graphql/attribute/types.py
+++ b/saleor/graphql/attribute/types.py
@@ -3,7 +3,7 @@ from typing import cast
import graphene
from django.db.models import QuerySet
-from ...attribute import AttributeEntityType, AttributeInputType, models
+from ...attribute import AttributeInputType, models
from ...core.permissions import (
PagePermissions,
PageTypePermissions,
@@ -36,6 +36,7 @@ from .descriptions import AttributeDescriptions, AttributeValueDescriptions
from .enums import AttributeEntityTypeEnum, AttributeInputTypeEnum, AttributeTypeEnum
from .filters import AttributeValueFilterInput
from .sorters import AttributeChoicesSortingInput
+from .utils import AttributeAssignmentMixin
class AttributeValue(ModelObjectType):
@@ -90,11 +91,11 @@ class AttributeValue(ModelObjectType):
def prepare_reference(attribute):
if attribute.input_type != AttributeInputType.REFERENCE:
return
- if attribute.entity_type == AttributeEntityType.PAGE:
- reference_pk = root.reference_page_id
- elif attribute.entity_type == AttributeEntityType.PRODUCT:
- reference_pk = root.reference_product_id
- else:
+ reference_field = AttributeAssignmentMixin.ENTITY_TYPE_MAPPING[
+ attribute.entity_type
+ ].value_field
+ reference_pk = getattr(root, f"{reference_field}_id", None)
+ if reference_pk is None:
return
reference_id = graphene.Node.to_global_id(
attribute.entity_type, reference_pk
diff --git a/saleor/graphql/attribute/utils.py b/saleor/graphql/attribute/utils.py
index 1289b6437f..ac0413ad98 100644
--- a/saleor/graphql/attribute/utils.py
+++ b/saleor/graphql/attribute/utils.py
@@ -1,5 +1,5 @@
import re
-from collections import defaultdict
+from collections import defaultdict, namedtuple
from dataclasses import dataclass
from datetime import datetime
from typing import TYPE_CHECKING, Dict, Iterable, List, Optional, Tuple, Union
@@ -36,7 +36,7 @@ if TYPE_CHECKING:
class AttrValuesInput:
global_id: str
values: List[str]
- references: Union[List[str], List[page_models.Page]]
+ references: Union[List[str], List[page_models.Page], None] = None
file_url: Optional[str] = None
content_type: Optional[str] = None
rich_text: Optional[dict] = None
@@ -52,6 +52,8 @@ T_INSTANCE = Union[
T_INPUT_MAP = List[Tuple[attribute_models.Attribute, AttrValuesInput]]
T_ERROR_DICT = Dict[Tuple[str, str], List[str]]
+EntityTypeData = namedtuple("EntityTypeData", ["model", "name_field", "value_field"])
+
class AttributeAssignmentMixin:
"""Handles cleaning of the attribute input and creating the proper relations.
@@ -69,14 +71,19 @@ class AttributeAssignmentMixin:
be unable to build or might only be partially built.
"""
- REFERENCE_VALUE_NAME_MAPPING = {
- AttributeEntityType.PAGE: "title",
- AttributeEntityType.PRODUCT: "name",
- }
-
- ENTITY_TYPE_TO_MODEL_MAPPING = {
- AttributeEntityType.PAGE: page_models.Page,
- AttributeEntityType.PRODUCT: product_models.Product,
+ # Defines the entity type corresponding model, the model field that should be used
+ # to create the value name, and relation field responsible for reference.
+ # Should be updated every time, the new `AttributeEntityType` value is added.
+ ENTITY_TYPE_MAPPING = {
+ AttributeEntityType.PAGE: EntityTypeData(
+ page_models.Page, "title", "reference_page"
+ ),
+ AttributeEntityType.PRODUCT: EntityTypeData(
+ product_models.Product, "name", "reference_product"
+ ),
+ AttributeEntityType.PRODUCT_VARIANT: EntityTypeData(
+ product_models.ProductVariant, "name", "reference_variant"
+ ),
}
@classmethod
@@ -87,26 +94,20 @@ class AttributeAssignmentMixin:
*,
global_ids: List[str],
pks: Iterable[int],
- slugs: Iterable[str],
):
- """Retrieve attributes nodes from given global IDs and/or slugs."""
- qs = qs.filter(Q(pk__in=pks) | Q(slug__in=slugs))
+ """Retrieve attributes nodes from given global IDs."""
+ qs = qs.filter(pk__in=pks)
nodes: List[attribute_models.Attribute] = list(qs)
if not nodes:
raise ValidationError(
- (
- f"Could not resolve to a node: ids={global_ids}"
- f" and slugs={list(slugs)}"
- ),
+ (f"Could not resolve to a node: ids={global_ids}."),
code=error_class.NOT_FOUND.value,
)
nodes_pk_list = set()
- nodes_slug_list = set()
for node in nodes:
nodes_pk_list.add(node.pk)
- nodes_slug_list.add(node.slug)
for pk, global_id in zip(pks, global_ids):
if pk not in nodes_pk_list:
@@ -115,13 +116,6 @@ class AttributeAssignmentMixin:
code=error_class.NOT_FOUND.value,
)
- for slug in slugs:
- if slug not in nodes_slug_list:
- raise ValidationError(
- f"Could not resolve slug {slug!r} to Attribute",
- code=error_class.NOT_FOUND.value,
- )
-
return nodes
@classmethod
@@ -181,56 +175,38 @@ class AttributeAssignmentMixin:
# Mapping to associate the input values back to the resolved attribute nodes
pks = {}
- slugs = {}
# Temporary storage of the passed ID for error reporting
global_ids = []
for attribute_input in raw_input:
- global_id = attribute_input.get("id")
- slug = attribute_input.get("slug")
+ global_id = attribute_input.pop("id", None)
+ if global_id is None:
+ raise ValidationError(
+ "The attribute ID is required.",
+ code=error_class.REQUIRED.value, # type: ignore
+ )
values = AttrValuesInput(
global_id=global_id,
- values=attribute_input.get("values", []),
- file_url=cls._clean_file_url(attribute_input.get("file")),
- content_type=attribute_input.get("content_type"),
- references=attribute_input.get("references", []),
- rich_text=attribute_input.get("rich_text"),
- plain_text=attribute_input.get("plain_text"),
- boolean=attribute_input.get("boolean"),
- date=attribute_input.get("date"),
- date_time=attribute_input.get("date_time"),
+ values=attribute_input.pop("values", []),
+ file_url=cls._clean_file_url(attribute_input.pop("file", None)),
+ **attribute_input,
)
- if global_id:
- internal_id = cls._resolve_attribute_global_id(error_class, global_id)
- global_ids.append(global_id)
- pks[internal_id] = values
- elif slug:
- slugs[slug] = values
- else:
- raise ValidationError(
- "You must whether supply an ID or a slug",
- code=error_class.REQUIRED.value, # type: ignore
- )
+ internal_id = cls._resolve_attribute_global_id(error_class, global_id)
+ global_ids.append(global_id)
+ pks[internal_id] = values
attributes = cls._resolve_attribute_nodes(
attributes_qs,
error_class,
global_ids=global_ids,
pks=pks.keys(),
- slugs=slugs.keys(),
)
attr_with_invalid_references = []
cleaned_input = []
for attribute in attributes:
- key = pks.get(attribute.pk, None)
-
- # Retrieve the primary key by slug if it
- # was not resolved through a global ID but a slug
- if key is None:
- key = slugs[attribute.slug]
-
+ key = pks[attribute.pk]
if attribute.input_type == AttributeInputType.REFERENCE:
try:
key = cls._validate_references(error_class, attribute, key)
@@ -273,9 +249,9 @@ class AttributeAssignmentMixin:
if not references:
return values
- entity_model = cls.ENTITY_TYPE_TO_MODEL_MAPPING[
+ entity_model = cls.ENTITY_TYPE_MAPPING[
attribute.entity_type # type: ignore
- ]
+ ].model
try:
ref_instances = get_nodes(
references, attribute.entity_type, model=entity_model
@@ -489,34 +465,28 @@ class AttributeAssignmentMixin:
Slug value is generated based on instance and reference entity id.
"""
- if not attr_values.references:
+ if not attr_values.references or not attribute.entity_type:
return tuple()
- field_name = cls.REFERENCE_VALUE_NAME_MAPPING[
- attribute.entity_type # type: ignore
- ]
+ entity_data = cls.ENTITY_TYPE_MAPPING[attribute.entity_type] # type: ignore
+ field_name = entity_data.name_field
get_or_create = attribute.values.get_or_create
reference_list = []
+ attr_value_field = entity_data.value_field
for ref in attr_values.references:
- reference_page = None
- reference_product = None
-
- if attribute.entity_type == AttributeEntityType.PAGE:
- reference_page = ref
- else:
- reference_product = ref
-
+ name = getattr(ref, field_name)
+ if attribute.entity_type == AttributeEntityType.PRODUCT_VARIANT:
+ name = f"{ref.product.name}: {name}" # type: ignore
reference_list.append(
get_or_create(
attribute=attribute,
- reference_product=reference_product,
- reference_page=reference_page,
slug=slugify(
f"{instance.id}_{ref.id}", # type: ignore
allow_unicode=True,
),
- defaults={"name": getattr(ref, field_name)},
+ defaults={"name": name},
+ **{attr_value_field: ref},
)[0]
)
return tuple(reference_list)
@@ -747,12 +717,13 @@ def validate_standard_attributes_input(
attribute_id
)
- validate_values(
- attribute_id,
- attribute,
- attr_values.values,
- attribute_errors,
- )
+ if attr_values.values is not None:
+ validate_values(
+ attribute_id,
+ attribute,
+ attr_values.values,
+ attribute_errors,
+ )
def validate_date_time_input(
diff --git a/saleor/graphql/page/tests/mutations/test_page_create.py b/saleor/graphql/page/tests/mutations/test_page_create.py
index 08402253f2..fba032838f 100644
--- a/saleor/graphql/page/tests/mutations/test_page_create.py
+++ b/saleor/graphql/page/tests/mutations/test_page_create.py
@@ -1136,3 +1136,79 @@ def test_create_page_with_product_reference_attribute_required_no_references_giv
assert errors[0]["code"] == PageErrorCode.REQUIRED.name
assert errors[0]["field"] == "attributes"
assert errors[0]["attributes"] == [file_attribute_id]
+
+
+def test_create_page_with_variant_reference_attribute(
+ staff_api_client,
+ permission_manage_pages,
+ page_type,
+ page_type_variant_reference_attribute,
+ variant,
+):
+ # given
+ page_slug = "test-slug"
+ page_content = dummy_editorjs("test content", True)
+ page_title = "test title"
+ page_is_published = True
+ page_type = PageType.objects.create(
+ name="Test page type 2", slug="test-page-type-2"
+ )
+ page_type_id = graphene.Node.to_global_id("PageType", page_type.pk)
+
+ ref_attribute_id = graphene.Node.to_global_id(
+ "Attribute", page_type_variant_reference_attribute.pk
+ )
+ page_type.page_attributes.add(page_type_variant_reference_attribute)
+ reference = graphene.Node.to_global_id("ProductVariant", variant.pk)
+
+ values_count = page_type_variant_reference_attribute.values.count()
+
+ # test creating root page
+ variables = {
+ "input": {
+ "title": page_title,
+ "content": page_content,
+ "isPublished": page_is_published,
+ "slug": page_slug,
+ "pageType": page_type_id,
+ "attributes": [{"id": ref_attribute_id, "references": [reference]}],
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ CREATE_PAGE_MUTATION, variables, permissions=[permission_manage_pages]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["pageCreate"]
+ errors = data["errors"]
+
+ assert not errors
+ assert data["page"]["title"] == page_title
+ assert data["page"]["content"] == page_content
+ assert data["page"]["slug"] == page_slug
+ assert data["page"]["isPublished"] == page_is_published
+ assert data["page"]["pageType"]["id"] == page_type_id
+ assert len(data["page"]["attributes"]) == 1
+ page_id = data["page"]["id"]
+ _, new_page_pk = graphene.Node.from_global_id(page_id)
+ expected_attr_data = {
+ "attribute": {"slug": page_type_variant_reference_attribute.slug},
+ "values": [
+ {
+ "slug": f"{new_page_pk}_{variant.pk}",
+ "file": None,
+ "name": f"{variant.product.name}: {variant.name}",
+ "reference": reference,
+ "plainText": None,
+ "dateTime": None,
+ "date": None,
+ }
+ ],
+ }
+ assert data["page"]["attributes"][0] == expected_attr_data
+
+ page_type_variant_reference_attribute.refresh_from_db()
+ assert page_type_variant_reference_attribute.values.count() == values_count + 1
diff --git a/saleor/graphql/page/tests/mutations/test_page_update.py b/saleor/graphql/page/tests/mutations/test_page_update.py
index f8c103599b..abb645d538 100644
--- a/saleor/graphql/page/tests/mutations/test_page_update.py
+++ b/saleor/graphql/page/tests/mutations/test_page_update.py
@@ -791,6 +791,126 @@ def test_update_page_with_product_reference_attribute_existing_value(
assert page_type_product_reference_attribute.values.count() == values_count
+def test_update_page_with_variant_reference_attribute_new_value(
+ staff_api_client,
+ permission_manage_pages,
+ page,
+ page_type_variant_reference_attribute,
+ variant,
+):
+ # given
+ query = UPDATE_PAGE_MUTATION
+
+ page_type = page.page_type
+ page_type.page_attributes.add(page_type_variant_reference_attribute)
+
+ values_count = page_type_variant_reference_attribute.values.count()
+ ref_attribute_id = graphene.Node.to_global_id(
+ "Attribute", page_type_variant_reference_attribute.pk
+ )
+ reference = graphene.Node.to_global_id("ProductVariant", variant.pk)
+
+ page_id = graphene.Node.to_global_id("Page", page.id)
+
+ variables = {
+ "id": page_id,
+ "input": {"attributes": [{"id": ref_attribute_id, "references": [reference]}]},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_pages]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["pageUpdate"]
+
+ assert not data["errors"]
+ assert data["page"]
+ updated_attribute = {
+ "attribute": {"slug": page_type_variant_reference_attribute.slug},
+ "values": [
+ {
+ "slug": f"{page.pk}_{variant.pk}",
+ "name": f"{variant.product.name}: {variant.name}",
+ "file": None,
+ "plainText": None,
+ "reference": reference,
+ }
+ ],
+ }
+ assert updated_attribute in data["page"]["attributes"]
+
+ page_type_variant_reference_attribute.refresh_from_db()
+ assert page_type_variant_reference_attribute.values.count() == values_count + 1
+
+
+def test_update_page_with_variant_reference_attribute_existing_value(
+ staff_api_client,
+ permission_manage_pages,
+ page,
+ page_type_variant_reference_attribute,
+ variant,
+):
+ # given
+ query = UPDATE_PAGE_MUTATION
+
+ page_type = page.page_type
+ page_type.page_attributes.add(page_type_variant_reference_attribute)
+
+ attr_value = AttributeValue.objects.create(
+ attribute=page_type_variant_reference_attribute,
+ name=page.title,
+ slug=f"{page.pk}_{variant.pk}",
+ reference_variant=variant,
+ )
+ associate_attribute_values_to_instance(
+ page, page_type_variant_reference_attribute, attr_value
+ )
+
+ values_count = page_type_variant_reference_attribute.values.count()
+ ref_attribute_id = graphene.Node.to_global_id(
+ "Attribute", page_type_variant_reference_attribute.pk
+ )
+ reference = graphene.Node.to_global_id("ProductVariant", variant.pk)
+
+ page_id = graphene.Node.to_global_id("Page", page.id)
+
+ variables = {
+ "id": page_id,
+ "input": {"attributes": [{"id": ref_attribute_id, "references": [reference]}]},
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_pages]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["pageUpdate"]
+
+ assert not data["errors"]
+ assert data["page"]
+ updated_attribute = {
+ "attribute": {"slug": page_type_variant_reference_attribute.slug},
+ "values": [
+ {
+ "slug": attr_value.slug,
+ "file": None,
+ "name": page.title,
+ "reference": reference,
+ "plainText": None,
+ }
+ ],
+ }
+ assert updated_attribute in data["page"]["attributes"]
+
+ page_type_variant_reference_attribute.refresh_from_db()
+ assert page_type_variant_reference_attribute.values.count() == values_count
+
+
@freeze_time("2020-03-18 12:00:00")
def test_public_page_sets_publication_date(
staff_api_client, permission_manage_pages, page_type
diff --git a/saleor/graphql/product/tests/test_bulk_delete.py b/saleor/graphql/product/tests/test_bulk_delete.py
index 4824feed9a..4b011c68d8 100644
--- a/saleor/graphql/product/tests/test_bulk_delete.py
+++ b/saleor/graphql/product/tests/test_bulk_delete.py
@@ -1091,7 +1091,7 @@ def test_product_delete_removes_reference_to_product(
assert not data["errors"]
-def test_product_delete_removes_reference_to_product_variant(
+def test_product_delete_removes_variant_reference_to_product(
staff_api_client,
variant,
product_type_product_reference_attribute,
@@ -1132,6 +1132,51 @@ def test_product_delete_removes_reference_to_product_variant(
assert not data["errors"]
+def test_product_delete_removes_reference_to_variant(
+ staff_api_client,
+ product_type_variant_reference_attribute,
+ product_list,
+ product_type,
+ permission_manage_products,
+):
+ # given
+ query = DELETE_PRODUCTS_MUTATION
+
+ product = product_list[0]
+ variant_ref = product_list[1].variants.first()
+
+ product_type.product_attributes.add(product_type_variant_reference_attribute)
+ attr_value = AttributeValue.objects.create(
+ attribute=product_type_variant_reference_attribute,
+ name=variant_ref.name,
+ slug=f"{product.pk}_{variant_ref.pk}",
+ reference_variant=variant_ref,
+ )
+ associate_attribute_values_to_instance(
+ product, product_type_variant_reference_attribute, attr_value
+ )
+
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+
+ variables = {"ids": [product_id]}
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+
+ # then
+ content = get_graphql_content(response)
+ data = content["data"]["productBulkDelete"]
+
+ with pytest.raises(attr_value._meta.model.DoesNotExist):
+ attr_value.refresh_from_db()
+ with pytest.raises(product._meta.model.DoesNotExist):
+ product.refresh_from_db()
+
+ assert not data["errors"]
+
+
def test_product_delete_removes_reference_to_page(
staff_api_client,
permission_manage_products,
diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.py
index 77b8870f3e..c7e0bbbe28 100644
--- a/saleor/graphql/product/tests/test_product.py
+++ b/saleor/graphql/product/tests/test_product.py
@@ -5698,6 +5698,83 @@ def test_create_product_with_product_reference_attribute(
assert product_type_product_reference_attribute.values.count() == values_count + 1
+def test_create_product_with_variant_reference_attribute(
+ 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_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
+
+ product_type_variant_reference_attribute.refresh_from_db()
+ assert product_type_variant_reference_attribute.values.count() == values_count + 1
+
+
def test_create_product_with_product_reference_attribute_values_saved_in_order(
staff_api_client,
product_type,
@@ -7678,6 +7755,51 @@ def test_update_product_clean_file_attribute_value(
assert product_attr.values.count() == 0
+@patch("saleor.plugins.manager.PluginsManager.product_updated")
+def test_update_product_none_as_attribute_values(
+ updated_webhook_mock,
+ staff_api_client,
+ product,
+ product_type,
+ permission_manage_products,
+):
+ # given
+ query = MUTATION_UPDATE_PRODUCT
+
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+
+ product_attr = product.attributes.first()
+ attribute = product_attr.assignment.attribute
+ attribute.value_required = False
+ attribute.save(update_fields=["value_required"])
+
+ attribute_id = graphene.Node.to_global_id("Attribute", attribute.pk)
+
+ variables = {
+ "productId": product_id,
+ "input": {"attributes": [{"id": attribute_id, "values": None}]},
+ }
+
+ # 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) == 1
+ assert not attributes[0]["values"]
+ with pytest.raises(product_attr._meta.model.DoesNotExist):
+ product_attr.refresh_from_db()
+
+ updated_webhook_mock.assert_called_once_with(product)
+
+
@patch("saleor.plugins.manager.PluginsManager.product_updated")
def test_update_product_with_plain_text_attribute_value(
updated_webhook_mock,
@@ -8206,6 +8328,103 @@ def test_update_product_with_product_reference_attribute_value(
assert product_type_product_reference_attribute.values.count() == values_count + 1
+@patch("saleor.plugins.manager.PluginsManager.product_updated")
+def test_update_product_with_variant_reference_attribute_value(
+ updated_webhook_mock,
+ staff_api_client,
+ product_type_variant_reference_attribute,
+ product_list,
+ product_type,
+ permission_manage_products,
+):
+ # given
+ query = MUTATION_UPDATE_PRODUCT
+
+ product = product_list[0]
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ variant_ref = product_list[1].variants.first()
+
+ attribute_id = graphene.Node.to_global_id(
+ "Attribute", product_type_variant_reference_attribute.pk
+ )
+ product_type.product_attributes.add(product_type_variant_reference_attribute)
+
+ values_count = product_type_variant_reference_attribute.values.count()
+
+ reference = graphene.Node.to_global_id("ProductVariant", variant_ref.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_variant_reference_attribute.name,
+ },
+ "values": [
+ {
+ "id": ANY,
+ "name": f"{variant_ref.product.name}: {variant_ref.name}",
+ "slug": f"{product.id}_{variant_ref.id}",
+ "file": None,
+ "reference": reference,
+ "boolean": None,
+ "plainText": None,
+ }
+ ],
+ }
+ assert expected_file_att_data in attributes
+
+ updated_webhook_mock.assert_called_once_with(product)
+
+ product_type_variant_reference_attribute.refresh_from_db()
+ assert product_type_variant_reference_attribute.values.count() == values_count + 1
+
+
+def test_update_product_with_no_id(
+ staff_api_client, product, permission_manage_products, color_attribute
+):
+ """Ensure only supplying values triggers a validation error."""
+ # given
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+
+ # Try to assign multiple values from an attribute that does not support such things
+ variables = {
+ "productId": graphene.Node.to_global_id("Product", product.pk),
+ "attributes": [{"values": ["Oopsie!"]}],
+ }
+
+ # when
+ data = get_graphql_content(
+ staff_api_client.post_graphql(SET_ATTRIBUTES_TO_PRODUCT_QUERY, variables)
+ )["data"]["productUpdate"]
+
+ # then
+ assert data["errors"] == [
+ {
+ "field": "attributes",
+ "code": ProductErrorCode.REQUIRED.name,
+ "message": ANY,
+ "attributes": None,
+ }
+ ]
+
+
@patch("saleor.plugins.manager.PluginsManager.product_updated")
def test_update_product_with_product_reference_attribute_existing_value(
updated_webhook_mock,
@@ -8684,32 +8903,6 @@ def test_update_product_with_non_existing_attribute(
]
-def test_update_product_with_no_attribute_slug_or_id(
- staff_api_client, product, permission_manage_products, color_attribute
-):
- """Ensure only supplying values triggers a validation error."""
-
- staff_api_client.user.user_permissions.add(permission_manage_products)
-
- # Try to assign multiple values from an attribute that does not support such things
- variables = {
- "productId": graphene.Node.to_global_id("Product", product.pk),
- "attributes": [{"values": ["Oopsie!"]}],
- }
-
- data = get_graphql_content(
- staff_api_client.post_graphql(SET_ATTRIBUTES_TO_PRODUCT_QUERY, variables)
- )["data"]["productUpdate"]
- assert data["errors"] == [
- {
- "field": "attributes",
- "code": ProductErrorCode.REQUIRED.name,
- "message": ANY,
- "attributes": None,
- }
- ]
-
-
def test_update_product_with_negative_weight(
staff_api_client, product_with_default_variant, permission_manage_products, product
):
diff --git a/saleor/graphql/product/tests/test_variant.py b/saleor/graphql/product/tests/test_variant.py
index e8519f1910..fa59a31c7e 100644
--- a/saleor/graphql/product/tests/test_variant.py
+++ b/saleor/graphql/product/tests/test_variant.py
@@ -1402,6 +1402,180 @@ def test_create_variant_with_product_reference_attribute_no_references_given(
updated_webhook_mock.assert_not_called()
+@patch("saleor.plugins.manager.PluginsManager.product_variant_created")
+def test_create_variant_with_variant_reference_attribute(
+ created_webhook_mock,
+ staff_api_client,
+ product,
+ product_type,
+ product_type_variant_reference_attribute,
+ product_list,
+ permission_manage_products,
+ warehouse,
+):
+ # given
+ query = CREATE_VARIANT_MUTATION
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ sku = "1"
+
+ product_type_variant_reference_attribute.value_required = True
+ product_type_variant_reference_attribute.save(update_fields=["value_required"])
+
+ product_type.variant_attributes.clear()
+ product_type.variant_attributes.add(product_type_variant_reference_attribute)
+ ref_attr_id = graphene.Node.to_global_id(
+ "Attribute", product_type_variant_reference_attribute.id
+ )
+
+ variant_1 = product_list[0].variants.first()
+ variant_2 = product_list[1].variants.first()
+ variant_ref_1 = graphene.Node.to_global_id("ProductVariant", variant_1.pk)
+ variant_ref_2 = graphene.Node.to_global_id("ProductVariant", variant_2.pk)
+
+ values_count = product_type_variant_reference_attribute.values.count()
+
+ stocks = [
+ {
+ "warehouse": graphene.Node.to_global_id("Warehouse", warehouse.pk),
+ "quantity": 20,
+ }
+ ]
+
+ variables = {
+ "input": {
+ "product": product_id,
+ "sku": sku,
+ "stocks": stocks,
+ "attributes": [
+ {"id": ref_attr_id, "references": [variant_ref_1, variant_ref_2]}
+ ],
+ "trackInventory": True,
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+
+ # then
+ content = get_graphql_content(response)["data"]["productVariantCreate"]
+ flush_post_commit_hooks()
+
+ 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 (
+ data["attributes"][0]["attribute"]["slug"]
+ == product_type_variant_reference_attribute.slug
+ )
+ expected_values = [
+ {
+ "slug": f"{variant_pk}_{variant_1.pk}",
+ "file": None,
+ "richText": None,
+ "plainText": None,
+ "reference": variant_ref_1,
+ "name": f"{variant_1.product.name}: {variant_1.name}",
+ "boolean": None,
+ "date": None,
+ "dateTime": None,
+ },
+ {
+ "slug": f"{variant_pk}_{variant_2.pk}",
+ "file": None,
+ "richText": None,
+ "plainText": None,
+ "reference": variant_ref_2,
+ "name": f"{variant_2.product.name}: {variant_2.name}",
+ "boolean": None,
+ "date": None,
+ "dateTime": None,
+ },
+ ]
+ for value in expected_values:
+ assert value in data["attributes"][0]["values"]
+ assert len(data["stocks"]) == 1
+ assert data["stocks"][0]["quantity"] == stocks[0]["quantity"]
+ assert data["stocks"][0]["warehouse"]["slug"] == warehouse.slug
+
+ product_type_variant_reference_attribute.refresh_from_db()
+ assert product_type_variant_reference_attribute.values.count() == values_count + 2
+
+ created_webhook_mock.assert_called_once_with(product.variants.last())
+
+
+@patch("saleor.plugins.manager.PluginsManager.product_variant_updated")
+@patch("saleor.plugins.manager.PluginsManager.product_variant_created")
+def test_create_variant_with_variant_reference_attribute_no_references_given(
+ created_webhook_mock,
+ updated_webhook_mock,
+ staff_api_client,
+ product,
+ product_type,
+ product_type_variant_reference_attribute,
+ permission_manage_products,
+ warehouse,
+):
+ # given
+ query = CREATE_VARIANT_MUTATION
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ sku = "1"
+
+ product_type_variant_reference_attribute.value_required = True
+ product_type_variant_reference_attribute.save(update_fields=["value_required"])
+
+ product_type.variant_attributes.clear()
+ product_type.variant_attributes.add(product_type_variant_reference_attribute)
+ ref_attr_id = graphene.Node.to_global_id(
+ "Attribute", product_type_variant_reference_attribute.id
+ )
+
+ values_count = product_type_variant_reference_attribute.values.count()
+
+ stocks = [
+ {
+ "warehouse": graphene.Node.to_global_id("Warehouse", warehouse.pk),
+ "quantity": 20,
+ }
+ ]
+
+ variables = {
+ "input": {
+ "product": product_id,
+ "sku": sku,
+ "stocks": stocks,
+ "attributes": [{"id": ref_attr_id, "file": "test.jpg"}],
+ "trackInventory": True,
+ }
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ query, variables, permissions=[permission_manage_products]
+ )
+
+ # then
+ content = get_graphql_content(response)["data"]["productVariantCreate"]
+ flush_post_commit_hooks()
+ errors = content["errors"]
+ data = content["productVariant"]
+
+ assert not data
+ assert len(errors) == 1
+ assert errors[0]["code"] == ProductErrorCode.REQUIRED.name
+ assert errors[0]["field"] == "attributes"
+ assert errors[0]["attributes"] == [ref_attr_id]
+
+ product_type_variant_reference_attribute.refresh_from_db()
+ assert product_type_variant_reference_attribute.values.count() == values_count
+
+ created_webhook_mock.assert_not_called()
+ updated_webhook_mock.assert_not_called()
+
+
@patch("saleor.plugins.manager.PluginsManager.product_variant_created")
def test_create_variant_with_numeric_attribute(
created_webhook_mock,
@@ -3322,6 +3496,64 @@ def test_update_product_variant_with_product_reference_attribute(
assert variant_data["attributes"][0]["values"][0]["reference"] == reference
+def test_update_product_variant_with_variant_reference_attribute(
+ staff_api_client,
+ product_list,
+ product_type_variant_reference_attribute,
+ permission_manage_products,
+):
+ # given
+ product = product_list[0]
+ variant_ref = product_list[1].variants.first()
+
+ variant = product.variants.first()
+ sku = str(uuid4())[:12]
+ assert not variant.sku == sku
+
+ product_type = product.product_type
+ product_type.variant_attributes.clear()
+ product_type.variant_attributes.add(product_type_variant_reference_attribute)
+
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ ref_attribute_id = graphene.Node.to_global_id(
+ "Attribute", product_type_variant_reference_attribute.pk
+ )
+ reference = graphene.Node.to_global_id("ProductVariant", variant_ref.pk)
+
+ variables = {
+ "id": variant_id,
+ "sku": sku,
+ "attributes": [{"id": ref_attribute_id, "references": [reference]}],
+ }
+
+ # 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
+ assert variant_data["sku"] == sku
+ assert len(variant_data["attributes"]) == 1
+ assert (
+ variant_data["attributes"][0]["attribute"]["slug"]
+ == product_type_variant_reference_attribute.slug
+ )
+ assert len(variant_data["attributes"][0]["values"]) == 1
+ assert (
+ variant_data["attributes"][0]["values"][0]["slug"]
+ == f"{variant.pk}_{variant_ref.pk}"
+ )
+ assert variant_data["attributes"][0]["values"][0]["reference"] == reference
+
+
def test_update_product_variant_change_attribute_values_ordering(
staff_api_client,
variant,
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 972543f0f8..0584be8a02 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -4828,6 +4828,7 @@ enum AttributeInputTypeEnum {
enum AttributeEntityTypeEnum {
PAGE
PRODUCT
+ PRODUCT_VARIANT
}
"""An enumeration."""
diff --git a/saleor/product/tests/test_get_variant_selection_attributes.py b/saleor/product/tests/test_get_variant_selection_attributes.py
index 6787aeb341..0eff81bad3 100644
--- a/saleor/product/tests/test_get_variant_selection_attributes.py
+++ b/saleor/product/tests/test_get_variant_selection_attributes.py
@@ -9,6 +9,7 @@ def test_get_variant_selection_attributes(
file_attribute_with_file_input_type_without_values,
product_type_page_reference_attribute,
product_type_product_reference_attribute,
+ page_type_variant_reference_attribute,
):
# given
multiselect_attr = product_type_attribute_list[0]
@@ -21,6 +22,7 @@ def test_get_variant_selection_attributes(
file_attribute_with_file_input_type_without_values,
product_type_page_reference_attribute,
product_type_product_reference_attribute,
+ page_type_variant_reference_attribute,
]
# for now, instead of skipping test
diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.py
index 24c6213019..3862342263 100644
--- a/saleor/tests/fixtures.py
+++ b/saleor/tests/fixtures.py
@@ -1687,6 +1687,28 @@ def page_type_product_reference_attribute(db):
)
+def product_type_variant_reference_attribute(db):
+ return Attribute.objects.create(
+ slug="variant-reference",
+ name="Variant reference",
+ type=AttributeType.PRODUCT_TYPE,
+ input_type=AttributeInputType.REFERENCE,
+ entity_type=AttributeEntityType.PRODUCT_VARIANT,
+ )
+
+
+def page_type_variant_reference_attribute(db):
+ return Attribute.objects.create(
+ slug="variant-reference",
+ name="Variant reference",
+ type=AttributeType.PAGE_TYPE,
+ input_type=AttributeInputType.REFERENCE,
+ entity_type=AttributeEntityType.PRODUCT_VARIANT,
+ )
+
+
@pytest.fixture
def size_page_attribute(db):
attribute = Attribute.objects.create(